branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>// Question: https://www.hackerrank.com/challenges/bitwise-operators-in-c/problem
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
void calculate_the_maximum(int n, int k) {
int i, j, x, y, z, max1 = 0, max2 = 0, max3 = 0;
for(i = 1; i <= n; i++)
{
for(j = i+1; j <= n; j++)
{
x = i&j;
y = i|j;
z = i^j;
if((x > max1)&&(x < k))
max1 = x;
if((y > max2)&&(y < k))
max2 = y;
if((z > max3)&&(z < k))
max3 = z;
}
}
printf("%d\n%d\n%d",max1, max2, max3);
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
calculate_the_maximum(n, k);
return 0;
}
<file_sep>// Question: https://www.hackerrank.com/challenges/pointer-in-c/problem
#include <stdio.h>
#include <math.h>
void update(int *a,int *b) {
// Complete this function
}
int main() {
int a, b;
scanf("%d",&a);
scanf("%d",&b);
printf("%d\n%d",(a+b), abs(a-b));
}
<file_sep>// Question: https://www.hackerrank.com/challenges/students-marks-sum/problem
int marks_summation(int *marks, int n, char g){
int i, sum = 0;
if(g == 'b'){
for(i = 0; i < n; i+=2){
sum = sum + marks[i];
}
}
else if(g == 'g'){
for(i = 1; i < n; i+=2){
sum = sum + marks[i];
}
}
return sum;
}
<file_sep>// Question: https://www.hackerrank.com/challenges/sum-of-digits-of-a-five-digit-number/problem
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n, i, sum = 0;
scanf("%d", &n);
for(i = n; i != 0; i=i/10)
{
sum = sum + i%10;
}
printf("%d",sum);
}
<file_sep>// Question: https://www.hackerrank.com/challenges/printing-tokens-/problem
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char s[10000];
int i;
scanf("%[^\n]", s);
for(i = 0; i < strlen(s); i++)
{
if(s[i] == 32)
printf("\n");
else
printf("%c",s[i]);
}
}
<file_sep>// Question: https://www.hackerrank.com/challenges/reverse-array-c/problem
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, a[1000], i;
scanf("%d",&n);
for(i = 0; i < n; i++)
{
scanf("%d",&a[i]);
}
for(i = n-1; i >= 0; i--)
{
printf("%d ",a[i]);
}
}
<file_sep>// Question: https://www.hackerrank.com/challenges/small-triangles-large-triangles/problem
void sort_by_area(triangle* tr, int n) {
double area[n], temp;
int i, j, tempa, tempb, tempc;
for(i = 0; i < n; i++){
double p = (double) (tr[i].a + tr[i].b + tr[i].c)/2;
area[i] = sqrt(p*(p-tr[i].a)*(p-tr[i].b)*(p-tr[i].c));
}
for(i = 0; i < n-1; i++){
for(j = i+1; j < n; j++){
if(area[i] > area[j]){
temp = area[i];
area[i] = area[j];
area[j] = temp;
tempa = tr[i].a;
tr[i].a = tr[j].a;
tr[j].a = tempa;
tempb = tr[i].b;
tr[i].b = tr[j].b;
tr[j].b = tempb;
tempc = tr[i].c;
tr[i].c = tr[j].c;
tr[j].c = tempc;
}
}
}
}
<file_sep>// Question: https://www.hackerrank.com/challenges/sorting-array-of-strings/problem
int lexicographic_sort(const char* a, const char* b);
int lexicographic_sort_reverse(const char* a, const char* b);
int sort_by_number_of_distinct_characters(const char* a, const char* b);
int sort_by_length(const char* a, const char* b);
void string_sort(char** arr,const int len,int (*cmp_func)(const char* a, const char* b));
int lexicographic_sort(const char* a, const char* b) {
if(strcmp(a, b) > 0){
return 1;
}
else{
return -1;
}
}
int lexicographic_sort_reverse(const char* a, const char* b) {
if(strcmp(a, b) > 0){
return -1;
}
else{
return 1;
}
}
int sort_by_number_of_distinct_characters(const char* a, const char* b) {
int i, j, count1 = 0, count2 = 0, sum1 = 1, sum2 = 1;
for(i = 0; i < strlen(a)-1; i++){
for(j = i+1; j < strlen(a); j++){
if(a[i] == a[j]){
count1 = 1;
}
}
if(count1 == 0){
sum1 = sum1 + 1;
}
count1 = 0;
}
for(i = 0; i < strlen(b)-1; i++){
for(j = i+1; j < strlen(b); j++){
if(b[i] == b[j]){
count2 = 1;
}
}
if(count2 == 0){
sum2 = sum2 + 1;
}
count2 = 0;
}
if(sum1 < sum2){
return -1;
}
else if(sum1 > sum2){
return 1;
}
else{
return lexicographic_sort(a, b);
}
}
int sort_by_length(const char* a, const char* b) {
if(strlen(a) < strlen(b)){
return -1;
}
else if(strlen(a) > strlen(b)){
return 1;
}
else{
return lexicographic_sort(a, b);
}
}
void string_sort(char** arr,const int len,int (*cmp_func)(const char* a, const char* b)){
int i, j, res;
char *temp;
for(i = 0; i < len-1; i++){
for(j = i+1; j < len; j++){
res = (*cmp_func)(arr[i], arr[j]);
if(res == 1){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
<file_sep>// Question: https://www.hackerrank.com/challenges/playing-with-characters/problem
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main()
{
char a, b[20], s[20];
scanf("%c",&a);
scanf("%s",&b);
scanf("\n");
scanf("%[^\n]", s);
printf("%c\n",a);
printf("%s\n",b);
printf("%s",s);
}
<file_sep>// Question: https://www.hackerrank.com/challenges/frequency-of-digits-1/problem
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
char s[1000];
int i, a[10];
scanf("%s",&s);
for(i = 0; i < 10; i++)
{
a[i] = 0;
}
for(i = 0; i < strlen(s); i++)
{
if((s[i] > 47)&&(s[i] < 58))
{
a[s[i]-48]++;
}
}
for(i = 0; i < 10; i++)
{
printf("%d ",a[i]);
}
}
|
179367a1e6d4a84dfee96fb7e43075cb3af5ae5d
|
[
"C"
] | 10 |
C
|
Mohamed-Razan/Hackerrank-C
|
aae8287eb281213d2711c9a3c44fabb87b853416
|
5756eb18d07d36b7c3ea7a3ee35955ae805f917f
|
refs/heads/main
|
<repo_name>kopn9k/trucking-mc<file_sep>/user/src/main/java/com/po/trucking/user/model/Carrier.java
package com.po.trucking.user.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
@Getter
@Setter
@NoArgsConstructor
public class Carrier {
private Long carrierId;
}
<file_sep>/consignment-unit/src/main/java/com/po/trucking/consignmentunit/model/ConsignmentUnit.java
package com.po.trucking.consignmentunit.model;
import javax.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "consignment_units")
public class ConsignmentUnit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "consignment_id")
private Long consignmentId;
private int amount;
@Column(name = "product_id")
private Long productId;
}
<file_sep>/driver/src/main/java/com/po/trucking/driver/dto/DriverIdAndNameDto.java
package com.po.trucking.driver.dto;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class DriverIdAndNameDto {
private long id;
private String firstName;
}
<file_sep>/consignment/src/main/resources/application.properties
server.port=${PORT:0}
spring.application.name=consignments-ws
spring.devtools.restart.enabled=true
eureka.instance.instance-id=${spring.application.name}:${spring.application.instance-id:${random.value}}
spring.config.import=optional:configserver:http://localhost:8888
authorization.token.header.prefix=Bearer
<file_sep>/carrier/src/test/java/com/po/trucking/carrier/CarrierApplicationTests.java
package com.po.trucking.carrier;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class CarrierApplicationTests {
@Test
void contextLoads() {
}
}
<file_sep>/user/src/main/java/com/po/trucking/user/repository/UserRepository.java
package com.po.trucking.user.repository;
import com.po.trucking.user.model.Role;
import com.po.trucking.user.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QuerydslPredicateExecutor;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface UserRepository extends PagingAndSortingRepository<User, Long> {
List<User> findAllByRole(Role role);
User findByEmail(String email);
Page<User> findAllByCarrierId(Pageable pageable, Long carrierId);
Optional<User> findByIdAndCarrierId(long id, Long carrierId);
void deleteByIdAndCarrierId (long id, Long carrierId);
}
<file_sep>/carrier/src/main/java/com/po/trucking/carrier/service/CarrierService.java
package com.po.trucking.carrier.service;
import com.po.trucking.carrier.dto.CarrierDto;
import com.po.trucking.carrier.dto.UserDtoWithPassword;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
public interface CarrierService {
Optional<CarrierDto> getById(long id);
CarrierDto add(String authorizationHeader ,UserDtoWithPassword userDto);
void update(CarrierDto carrierDto, long id);
void delete(long id);
Page<CarrierDto> getAll(Pageable pageable);
}
<file_sep>/user/src/main/java/com/po/trucking/user/converter/EnumUserType.java
package com.po.trucking.user.converter;
import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Optional;
import java.util.Properties;
import java.util.stream.Stream;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.usertype.DynamicParameterizedType;
import org.hibernate.usertype.EnhancedUserType;
import org.hibernate.usertype.LoggableUserType;
/**
* Value type modelMapper for enumerations
*/
public class EnumUserType implements EnhancedUserType, DynamicParameterizedType, LoggableUserType, Serializable {
private Class<? extends Enum> enumClass;
private EnumValueMapper enumValueMapper;
@Override
public int[] sqlTypes() {
int sqlType;
if (enumValueMapper != null) {
sqlType = enumValueMapper.getSqlType();
} else {
sqlType = Types.VARCHAR;
}
return new int[]{sqlType};
}
@Override
public Class<? extends Enum> returnedClass() {
return enumClass;
}
@Override
public boolean equals(Object o1, Object o2) {
return o1 == o2;
}
@Override
public int hashCode(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, Object owner) throws SQLException {
return enumValueMapper.getValue(rs, names);
}
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SharedSessionContractImplementor session) throws SQLException {
enumValueMapper.setValue(st, (Enum) value, index);
}
@Override
public Object deepCopy(Object value) {
return value;
}
@Override
public boolean isMutable() {
return false;
}
@Override
public Serializable disassemble(Object value) {
return (Serializable) value;
}
@Override
public Object assemble(Serializable cached, Object owner) {
return cached;
}
@Override
public Object replace(Object original, Object target, Object owner) {
return original;
}
@Override
@SuppressWarnings("unchecked")
public void setParameterValues(Properties parameters) {
ParameterType reader = (ParameterType) parameters.get(PARAMETER_TYPE);
if (reader != null) {
enumClass = reader.getReturnedClass().asSubclass(Enum.class);
Annotation[] annotations = reader.getAnnotationsMethod();
Optional<Annotation> enumAnnotation = Stream.of(annotations)
.filter(Enumerated.class::isInstance).findFirst();
if (!enumAnnotation.isPresent()) {
throw new IllegalStateException("Enumerated persistent property in class "
+ parameters.get(ENTITY) + " must be annotated with " + Enumerated.class);
}
EnumType enumType = ((Enumerated) enumAnnotation.get()).value();
enumValueMapper = createEnumValueMapper(enumType);
} else {
throw new IllegalStateException("Unable to determine Enum class");
}
}
private EnumValueMapper createEnumValueMapper(EnumType enumType) {
switch (enumType) {
case ORDINAL:
return new OrdinalEnumValueMapper();
case STRING:
return new NamedEnumValueMapper();
case POSTGRES:
return new PGEnumValueMapper();
}
throw new IllegalArgumentException("Unsupported value for enum type: " + enumType);
}
@Override
public String objectToSQLString(Object value) {
return enumValueMapper.objectToSQLString((Enum) value);
}
@Override
public String toXMLString(Object value) {
return enumValueMapper.toXMLString((Enum) value);
}
@Override
public Object fromXMLString(String xmlValue) {
return enumValueMapper.fromXMLString(xmlValue);
}
@Override
public String toLoggableString(Object value, SessionFactoryImplementor factory) {
if (enumValueMapper != null) {
return enumValueMapper.toXMLString((Enum) value);
}
return value.toString();
}
private interface EnumValueMapper extends Serializable {
int getSqlType();
Enum getValue(ResultSet rs, String[] names) throws SQLException;
void setValue(PreparedStatement st, Enum value, int index) throws SQLException;
String objectToSQLString(Enum value);
String toXMLString(Enum value);
Enum fromXMLString(String xml);
}
public abstract class AbstractEnumValueMapper implements EnumValueMapper {
protected abstract Object getJdbcValue(Enum value);
@Override
public void setValue(PreparedStatement st, Enum enumValue, int index) throws SQLException {
if (enumValue != null) {
st.setObject(index, getJdbcValue(enumValue), getSqlType());
} else {
st.setNull(index, getSqlType());
}
}
}
private class OrdinalEnumValueMapper extends AbstractEnumValueMapper {
private transient Enum[] enumValues;
@Override
public int getSqlType() {
return Types.INTEGER;
}
@Override
public Enum getValue(ResultSet rs, String[] names) throws SQLException {
int ordinal = rs.getInt(names[0]);
if (rs.wasNull()) {
return null;
}
return fromOrdinal(ordinal);
}
private Enum fromOrdinal(int ordinal) {
Enum[] currentEnumValues = getEnumValues();
if (ordinal < 0 || ordinal >= currentEnumValues.length) {
throw new IllegalArgumentException(String.format("Unknown ordinal value [%s] for enum class [%s]",
ordinal, enumClass.getName()));
}
return currentEnumValues[ordinal];
}
private Enum[] getEnumValues() {
if (enumValues == null) {
enumValues = enumClass.getEnumConstants();
if (enumValues == null) {
throw new HibernateException("Failed to init enum values");
}
}
return enumValues;
}
@Override
public String objectToSQLString(Enum value) {
return toXMLString(value);
}
@Override
public String toXMLString(Enum value) {
return Integer.toString(value.ordinal());
}
@Override
public Enum fromXMLString(String xml) {
return fromOrdinal(Integer.parseInt(xml));
}
@Override
protected Object getJdbcValue(Enum value) {
return value.ordinal();
}
}
private class NamedEnumValueMapper extends AbstractEnumValueMapper {
@Override
public int getSqlType() {
return Types.VARCHAR;
}
@Override
public Enum getValue(ResultSet rs, String[] names) throws SQLException {
String value = rs.getString(names[0]);
if (value == null) {
return null;
}
return fromName(value);
}
private Enum fromName(String name) {
try {
return Enum.valueOf(enumClass, name.trim());
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException(String.format("Unknown name value [%s] for enum class [%s]",
name, enumClass.getName()));
}
}
@Override
public String objectToSQLString(Enum value) {
return '\'' + value.name() + '\'';
}
@Override
public String toXMLString(Enum value) {
return value.name();
}
@Override
public Enum fromXMLString(String xml) {
return fromName(xml);
}
@Override
protected Object getJdbcValue(Enum value) {
return value.name();
}
}
private class PGEnumValueMapper extends NamedEnumValueMapper {
@Override
public int getSqlType() {
return Types.OTHER;
}
}
}
<file_sep>/car/src/main/java/com/po/trucking/car/service/CarService.java
package com.po.trucking.car.service;
import com.po.trucking.car.dto.CarDto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public interface CarService {
Optional<CarDto> getById(long id);
CarDto create(CarDto carDto);
void update(long id, CarDto carDto);
void delete(long id);
Page<CarDto> getAll(Pageable pageable);
List<CarDto> getAll();
List<CarDto> getAllFreeCarsByTransportationType(String transportationType);
}
<file_sep>/client/src/main/java/com/po/trucking/client/data/CarriersServiceClient.java
package com.po.trucking.client.data;
import com.po.trucking.client.dto.CarrierDto;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
@FeignClient(name = "carriers-ws", fallbackFactory = CarriersFallbackFactory.class)
public interface CarriersServiceClient {
@GetMapping(path = "/api/v1/carriers/{id}")
public ResponseEntity<CarrierDto> getCarrier(@PathVariable(name = "id") Long id);
}
@Component
class CarriersFallbackFactory implements FallbackFactory<CarriersServiceClient> {
@Override
public CarriersServiceClient create(Throwable cause) {
return new CarriersServiceClientFallback(cause);
}
}
@Slf4j
class CarriersServiceClientFallback implements CarriersServiceClient {
private final Throwable cause;
public CarriersServiceClientFallback(Throwable cause) {
this.cause = cause;
}
@Override
public ResponseEntity<CarrierDto> getCarrier(Long id) {
log.info("In CarriersServiceClient" + cause.getLocalizedMessage());
CarrierDto carrierDto = new CarrierDto();
carrierDto.setId(id);
return ResponseEntity.ok(carrierDto);
}
}<file_sep>/user/src/main/java/com/po/trucking/user/security/JwtUser.java
package com.po.trucking.user.security;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
public class JwtUser implements UserDetails {
private final long id;
private final String username;
private final String firstName;
private final String lastName;
private final String password;
private final Long carrierId;
private final Collection<? extends GrantedAuthority> authorities;
public JwtUser(long id, String email, String firstName, String lastName, String password, Long carrierId, Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = email;
this.firstName = firstName;
this.lastName = lastName;
this.password = <PASSWORD>;
this.authorities = authorities;
this.carrierId = carrierId;
}
@JsonIgnore
public long getId() {
return id;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@JsonIgnore
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@JsonIgnore
@Override
public boolean isAccountNonExpired() {
return true;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
@JsonIgnore
public Long getCarrierId() {
return carrierId;
}
@JsonIgnore
@Override
public boolean isAccountNonLocked() {
return true;
}
@JsonIgnore
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
<file_sep>/consignment-unit/src/main/java/com/po/trucking/consignmentunit/service/ConsignmentUnitService.java
package com.po.trucking.consignmentunit.service;
import com.po.trucking.consignmentunit.dto.ConsignmentUnitDto;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public interface ConsignmentUnitService {
Optional<ConsignmentUnitDto> getById(long id);
ConsignmentUnitDto create(ConsignmentUnitDto consignmentUnitDto);
void update(long id, ConsignmentUnitDto consignmentUnitDto);
void delete(long id);
List<ConsignmentUnitDto> getAll();
}
<file_sep>/carrier/src/main/java/com/po/trucking/carrier/data/UsersServiceClient.java
package com.po.trucking.carrier.data;
import com.po.trucking.carrier.dto.UserDtoWithPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
@FeignClient(name = "users-ws", fallbackFactory = UsersServiceClientFactory.class)
public interface UsersServiceClient {
@PostMapping(value = "")
public ResponseEntity<UserDtoWithPassword> saveUser(@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = true) String authorizationHeader, @RequestBody UserDtoWithPassword userDtoWithPassword);
}
@Component
class UsersServiceClientFactory implements FallbackFactory<UsersServiceClient> {
@Override
public UsersServiceClient create(Throwable cause) {
return new UsersServiceClientFallback(cause);
}
}
@Slf4j
class UsersServiceClientFallback implements UsersServiceClient {
private final Throwable cause;
public UsersServiceClientFallback(Throwable cause) {
this.cause = cause;
}
@Override
public ResponseEntity<UserDtoWithPassword> saveUser(String authorizationHeader, UserDtoWithPassword userDtoWithPassword) {
log.info("In UsersServiceClient" + cause.getLocalizedMessage());
return ResponseEntity.ok(userDtoWithPassword);
}
}
<file_sep>/consignment/src/main/java/com/po/trucking/consignment/converter/package-info.java
@org.hibernate.annotations.TypeDef(
name = "org.hibernate.type.EnumType",
typeClass = EnumUserType.class
)
package com.po.trucking.consignment.converter;
<file_sep>/consignment/src/main/java/com/po/trucking/consignment/model/ConsignmentStatus.java
package com.po.trucking.consignment.model;
public enum ConsignmentStatus {
ACCEPTED,
TESTED,
DELIVERED,
LOST
}
<file_sep>/driver/src/main/java/com/po/trucking/driver/data/UsersServiceClient.java
package com.po.trucking.driver.data;
import com.po.trucking.driver.dto.UserEmailAndIdDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
@FeignClient(name = "users-ws", fallbackFactory = UsersFallbackFactory.class)
public interface UsersServiceClient {
@GetMapping(path = "/api/v1/users/{id}")
public ResponseEntity<UserEmailAndIdDto> getUserEmailById(@PathVariable(name = "id") Long id);
}
@Component
class UsersFallbackFactory implements FallbackFactory<UsersServiceClient> {
@Override
public UsersServiceClient create(Throwable cause) {
return new UsersServiceClientFallback(cause);
}
}
@Slf4j
class UsersServiceClientFallback implements UsersServiceClient {
private final Throwable cause;
public UsersServiceClientFallback(Throwable cause) {
this.cause = cause;
}
@Override
public ResponseEntity<UserEmailAndIdDto> getUserEmailById(Long id) {
log.info("In UsersServiceClient" + cause.getLocalizedMessage());
UserEmailAndIdDto userEmailAndIdDto = new UserEmailAndIdDto();
userEmailAndIdDto.setId(id);
return ResponseEntity.ok(userEmailAndIdDto);
}
}
<file_sep>/client/src/main/java/com/po/trucking/client/service/ClientService.java
package com.po.trucking.client.service;
import com.po.trucking.client.dto.ClientDto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public interface ClientService {
Optional<ClientDto> getById(long id);
ClientDto create(ClientDto clientDto);
void update(long id, ClientDto clientDto);
void delete(long id);
Page<ClientDto> getAll(Pageable pageable);
List<ClientDto> getAll();
}
<file_sep>/product/src/main/java/com/po/trucking/product/security/WebSecurity.java
package com.po.trucking.product.security;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurity extends WebSecurityConfigurerAdapter {
Environment environment;
public WebSecurity(Environment environment) {
this.environment = environment;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable();
http.authorizeRequests()
.antMatchers("/api/v1/products/**").access("hasIpAddress(\"192.168.0.0/16\") or hasIpAddress(\"127.0.0.0/16\")")
.anyRequest().authenticated()
.and()
.addFilter(new AuthorizationFilter(authenticationManager(), environment));
http.headers().frameOptions().disable();
}
}
<file_sep>/driver/src/main/java/com/po/trucking/driver/dto/DriverDto.java
package com.po.trucking.driver.dto;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class DriverDto {
private long id;
private String firstName;
private String lastName;
private String passportNumber;
private UserEmailAndIdDto user;
}
<file_sep>/README.md
# trucking-mc
<file_sep>/product/src/main/java/com/po/trucking/product/service/ProductService.java
package com.po.trucking.product.service;
import com.po.trucking.product.dto.ProductDto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public interface ProductService {
Optional<ProductDto> getById(long id);
ProductDto create(ProductDto productDto);
void update(long id, ProductDto productDto);
void delete(long id);
Page<ProductDto> getAll(Pageable pageable);
List<ProductDto> getAll();
}<file_sep>/car/src/main/java/com/po/trucking/car/data/DriversServiceClient.java
package com.po.trucking.car.data;
import com.po.trucking.car.dto.DriverIdAndNameDto;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
@FeignClient(name = "drivers-ws", fallbackFactory = DriverFallbackFactory.class)
public interface DriversServiceClient {
@GetMapping(path = "/api/v1/drivers/{id}")
public ResponseEntity<DriverIdAndNameDto> getDriverIdAndNameDto(@PathVariable(name = "id") Long id);
}
@Component
class DriverFallbackFactory implements FallbackFactory<DriversServiceClient> {
@Override
public DriversServiceClient create(Throwable cause) {
return new DriversServiceClientFallback(cause);
}
}
@Slf4j
class DriversServiceClientFallback implements DriversServiceClient {
private final Throwable cause;
public DriversServiceClientFallback(Throwable cause) {
this.cause = cause;
}
@Override
public ResponseEntity<DriverIdAndNameDto> getDriverIdAndNameDto(Long id) {
log.info("In CarriersServiceClient" + cause.getLocalizedMessage());
DriverIdAndNameDto driverIdAndNameDto = new DriverIdAndNameDto();
driverIdAndNameDto.setId(id);
return ResponseEntity.ok(driverIdAndNameDto);
}
}
<file_sep>/carrier/src/main/java/com/po/trucking/carrier/repository/CarrierRepository.java
package com.po.trucking.carrier.repository;
import com.po.trucking.carrier.model.Carrier;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CarrierRepository extends PagingAndSortingRepository<Carrier, Long> {
}
<file_sep>/consignment/src/main/java/com/po/trucking/consignment/converter/EnumType.java
package com.po.trucking.consignment.converter;
/**
* Defines mapping for enumerated types
*
*/
public enum EnumType {
ORDINAL, STRING, POSTGRES
}
<file_sep>/user/src/main/java/com/po/trucking/user/service/UserService.java
package com.po.trucking.user.service;
import com.po.trucking.user.dto.UserDto;
import com.po.trucking.user.dto.UserDtoWithPassword;
import com.po.trucking.user.dto.UserEmailAndIdDto;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
public interface UserService extends UserDetailsService {
Optional<UserDtoWithPassword> getById(long id, String authorizationHeader);
UserDtoWithPassword save(UserDtoWithPassword userDto);
void update(UserDtoWithPassword userDto, long id);
void delete(long id);
Page<UserDto> getAll(Pageable pageable, String authorizationHeader);
List<UserEmailAndIdDto> getAllByRole(String role);
UserDtoWithPassword getUserByEmail(String email, String authorizationHeader);
UserEmailAndIdDto getUserEmailById(Long id);
}
<file_sep>/driver/src/main/java/com/po/trucking/driver/service/DriverServiceImpl.java
package com.po.trucking.driver.service;
import com.po.trucking.driver.data.UsersServiceClient;
import com.po.trucking.driver.dto.DriverDto;
import com.po.trucking.driver.dto.DriverDtoWithUserId;
import com.po.trucking.driver.dto.DriverIdAndNameDto;
import com.po.trucking.driver.dto.UserEmailAndIdDto;
import com.po.trucking.driver.model.Driver;
import com.po.trucking.driver.repository.DriverRepository;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Slf4j
@Service
public class DriverServiceImpl implements DriverService {
private final ModelMapper modelMapper;
private final DriverRepository driverRepository;
private final UsersServiceClient usersServiceClient;
@Autowired
public DriverServiceImpl(DriverRepository driverRepository, ModelMapper modelMapper, UsersServiceClient usersServiceClient) {
this.modelMapper = modelMapper;
this.driverRepository = driverRepository;
this.usersServiceClient = usersServiceClient;
}
@Override
@Transactional
public Optional<DriverDto> getById(long id) {
log.info("In DriverServiceImpl getById {}", id);
Optional<Driver> optionalDriver = driverRepository.findById(id);
Driver driver = optionalDriver.orElseGet(Driver::new);
DriverDto driverDto = modelMapper.map(driver, DriverDto.class);
UserEmailAndIdDto userEmailAndIdDto = getUserEmailAndIdDto(driver.getUserId());
driverDto.setUser(userEmailAndIdDto);
return Optional.of(driverDto);
}
@Override
@Transactional
public DriverDto save(DriverDto driverDto) {
log.info("In DriverServiceImpl save {}", driverDto);
Driver driver = modelMapper.map(driverDto, Driver.class);
driver.setUserId(driverDto.getUser().getId());
Driver savedDriver = driverRepository.save(driver);
return modelMapper.map(savedDriver, DriverDto.class);
}
@Override
@Transactional
public void update(DriverDto driverDto, long id) {
log.info("In DriverServiceImpl update {}", driverDto);
driverDto.setId(id);
Driver driver = modelMapper.map(driverDto, Driver.class);
driver.setUserId(driverDto.getUser().getId());
driverRepository.save(driver);
}
@Override
@Transactional
public void delete(long id) {
log.info("In DriverServiceImpl delete {}", id);
driverRepository.deleteById(id);
}
@Override
@Transactional
public Page<DriverDto> getAll(Pageable pageable) {
log.info("In DriverServiceImpl getAll");
Page<Driver> drivers = driverRepository.findAll(pageable);
Page<DriverDtoWithUserId> driverDtoWithUserIds = drivers.map(driver -> modelMapper.map(driver, DriverDtoWithUserId.class));
driverDtoWithUserIds.forEach(driverDto -> {
UserEmailAndIdDto userEmailAndIdDto = getUserEmailAndIdDto(driverDto.getUserId());
driverDto.setUser(userEmailAndIdDto);
});
return driverDtoWithUserIds.map(driverDtoWithUserId -> modelMapper.map(driverDtoWithUserId, DriverDto.class));
}
@Override
@Transactional
public List<DriverIdAndNameDto> getAllDrivers() {
log.info("In DriverServiceImpl getAllDrivers");
List<Driver> drivers = driverRepository.findAll();
return drivers.stream().map(driver -> modelMapper.map(driver, DriverIdAndNameDto.class)).collect(Collectors.toList());
}
@Override
@Transactional
public DriverIdAndNameDto getDriverIdAndNameDto(Long id) {
log.info("In DriverServiceImpl getDriverIdAndNameDto {}", id);
Optional<Driver> optionalDriver = driverRepository.findById(id);
Driver driver = optionalDriver.orElseGet(Driver::new);
return modelMapper.map(driver, DriverIdAndNameDto.class);
}
private UserEmailAndIdDto getUserEmailAndIdDto(Long id) {
ResponseEntity<UserEmailAndIdDto> userEmailAndIdDtoResponseEntity = usersServiceClient.getUserEmailById(id);
return userEmailAndIdDtoResponseEntity.getBody();
}
}
<file_sep>/consignment-unit/src/main/java/com/po/trucking/consignmentunit/dto/ConsignmentUnitWithNameDto.java
package com.po.trucking.consignmentunit.dto;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class ConsignmentUnitWithNameDto {
private long id;
private int amount;
private String productName;
}<file_sep>/consignment/src/main/java/com/po/trucking/consignment/converter/Enumerated.java
package com.po.trucking.consignment.converter;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Specifies how a persistent property or field should be persisted
* as a enumerated type
*/
@Target({METHOD, FIELD})
@Retention(RUNTIME)
public @interface Enumerated {
EnumType value() default EnumType.POSTGRES;
}
<file_sep>/carrier/src/main/java/com/po/trucking/carrier/controller/CarrierRestControllerV1.java
package com.po.trucking.carrier.controller;
import com.po.trucking.carrier.dto.CarrierDto;
import com.po.trucking.carrier.dto.UserDtoWithPassword;
import com.po.trucking.carrier.service.CarrierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import java.net.URI;
import java.util.Optional;
@RestController
@RequestMapping("/api/v1/carriers/")
@CrossOrigin
public class CarrierRestControllerV1 {
private final CarrierService carrierService;
@Autowired
public CarrierRestControllerV1(CarrierService carrierService) {
this.carrierService = carrierService;
}
@GetMapping(value = "{id}")
public ResponseEntity<CarrierDto> getCarrier(@PathVariable("id") long carrierId) {
Optional<CarrierDto> optionalCarrierDto = this.carrierService.getById(carrierId);
return optionalCarrierDto
.map(carrierDto -> new ResponseEntity<>(carrierDto, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PostMapping(value = "")
public ResponseEntity<CarrierDto> saveCarrier(@RequestHeader(value = HttpHeaders.AUTHORIZATION) String authorizationHeader,
@RequestBody @Valid UserDtoWithPassword userDtoWithPassword) {
CarrierDto savedCarrierDto = this.carrierService.add(authorizationHeader, userDtoWithPassword);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(savedCarrierDto.getId()).toUri();
return ResponseEntity.created(location).build();
}
@PutMapping(value = "{id}")
public CarrierDto updateCarrier(@PathVariable("id") long id, @RequestBody @Valid CarrierDto carrierDto) {
this.carrierService.update(carrierDto, id);
return carrierDto;
}
@DeleteMapping(value = "{id}")
public ResponseEntity<CarrierDto> deleteCarrier(@PathVariable("id") long id) {
this.carrierService.delete(id);
return new ResponseEntity<>(HttpStatus.OK);
}
@GetMapping(value = "")
public Page<CarrierDto> getAllCarriers(Pageable pageable) {
return this.carrierService.getAll(pageable);
}
}
<file_sep>/user/src/main/resources/application.properties
server.port=${PORT:0}
spring.application.name=users-ws
spring.devtools.restart.enabled=true
eureka.instance.instance-id=${spring.application.name}:${spring.application.instance-id:${random.value}}
spring.config.import=optional:configserver:http://localhost:8888
feign.client.config.default.loggerLevel = full
authorization.token.header.prefix=Bearer
<file_sep>/stock/src/main/java/com/po/trucking/dto/StockDto.java
package com.po.trucking.dto;
import lombok.*;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class StockDto {
private long id;
private String name;
private CarrierDto ownerOfStock;
private String telephone;
private double longitude;
private double latitude;
}
|
f977b661e9851ef4e9102684b01b93cad09fb49a
|
[
"Markdown",
"Java",
"INI"
] | 31 |
Java
|
kopn9k/trucking-mc
|
f227880d6f97cf61fd5d2814ff6197184a3c97ec
|
6df93840db2ccca5aa14a049fb259b5942b57da5
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Fri Jan 16 10:34:51 2015
@author: efourrier
Purpose: This module provide some examples of beautiful python code and
some recipes.
"""
#########################################################
# Zen of Python
#########################################################
# type in the interactive console
import this
#########################################################
# import packages
#########################################################
from itertools import izip
from collections import defaultdict
from functools import partial
def unzip(tuples):
return zip(*tuples)
# one line if else condition
r =None
n =1
r = n if r is None else r
def make_complex(x, y):
return {'x': x, 'y': y}
#########################################################
# List,tuples, and loops
#########################################################
# Variables
colors = ['red', 'green', 'blue', 'yellow']
names = ['raymond', 'rachel', 'matthew']
# Creating four None
four_nones = [None] * 4
# Creating four lists
four_lists = [[] for _ in xrange(4)]
# Unpacking
for i, color in enumerate(colors):
print i, '--->',color
# More advanced unpacking
# swap
a,b = 1,2
a,b = b,a
lup = [1234,10000,'vacation']
loan_id,amount,purpose = lup
amount
for (loan_id,amount,purpose) in [lup,[1235,5000,'home_improvment']]:
print amount,purpose
# instead of zip use izip
for name, color in izip(names, colors):
print name, '--->', color
# Instead of using break use iter
blocks = []
for block in iter(partial(f.read, 32), ''):
blocks.append(block)
#########################################################
# Dictionnaries
#########################################################
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
for k in d :
print k
# if you are mutating the dictionary use d.keys() that is creating a copy
for k in d.keys():
del d[k]
d.items() # is a list of tuples
d.iteritems() # is a generator
# more computer efficient than d.items()
for k, v in d.iteritems():
print k, '--->', v
# Constructing a dictionnary from 2 lists
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue']
d = dict(izip(names, colors))
def beautiful_histo(l):
d = {}
for e in l:
d[e] = d.get(e,0) +1
return d
beautiful_histo(['red', 'green', 'red', 'blue', 'green', 'red'])
# Dictionnary grouping
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
# i want name group by len
# Same as setdefault
dd = defaultdict(list)
for name in names :
key = len(name)
dd[key].append(name)
print dd
# updating multiple state values
x,y = 1,1
def fibonacci(n):
x, y = 0, 1
for i in xrange(n):
print x
x, y = y, x + y
# open files
with open('data.txt') as f:
data = f.read()
# do something with data
# with automaticely close the file
# quick benchmark ipython execute one by one
%timeit sum([i*i for i in range(100000)])
%timeit sum(i*i for i in range(100000))
%timeit sum(i*i for i in xrange(100000))
#########################################################
# Some tricks to know
#########################################################
import sys
sys.path
# if you want to add a path
#sys.path.append
# testing a module
#if __name__ == "__main__" :
# String formatting
pwd = '<PASSWORD>'
uid = 'odbc'
print "%s is not a good password for %s" % (pwd, uid)
dir(list) # compute all the methods of a object
# list comprehension
# [mapping−expression for element in source−list if filter−expression]
|
8a1b8440b519e5af4f85b971b8236882860e8579
|
[
"Python"
] | 1 |
Python
|
ericfourrier/beautiful-python
|
922cb7ddb8c6ac5442388d6c8f4659fa69e47ad0
|
73e57b32c704b4b53491a98acb9478c20872c103
|
refs/heads/master
|
<repo_name>4ndreas/HyperLightControl<file_sep>/test2.py
# msg = "new test"
# print(msg)
# msg += " bla"
# print(msg)
import pybullet_utils.bullet_client as bc
import pybullet as p
import pybullet
import pybullet_data
# #can also connect using different modes, GUI, SHARED_MEMORY, TCP, UDP, SHARED_MEMORY_SERVER, GUI_SERVER
# pgui = bc.BulletClient(connection_mode=pybullet.GUI)
# p0 = bc.BulletClient(connection_mode=pybullet.SHARED_MEMORY_SERVER)
# p0.setAdditionalSearchPath(pybullet_data.getDataPath())
# pgui = p.connect(p.GUI)#or p.DIRECT for non-graphical version
p.connect(p.GUI_SERVER )#or p.DIRECT for non-graphical version
# p0 = p.connect(p.SHARED_MEMORY_SERVER )#or p.DIRECT for non-graphical version
p.setAdditionalSearchPath(pybullet_data.getDataPath())
p0 = bc.BulletClient(connection_mode=pybullet.SHARED_MEMORY)
# p0.setAdditionalSearchPath(pybullet_data.getDataPath())
# p1 = bc.BulletClient(connection_mode=pybullet.SHARED_MEMORY)
# p1.setAdditionalSearchPath(pybullet_data.getDataPath())
# p1 = p.connect(p.SHARED_MEMORY )#or p.DIRECT for non-graphical version
# p1.setAdditionalSearchPath(pybullet_data.getDataPath())
p0.loadURDF("r2d2.urdf", [0,0,1])
# p1.loadSDF("stadium.sdf")
print(p0._client)
# print(p1._client)
print("p.getNumBodies()=",p.getNumBodies())
print("p0.getNumBodies()=",p0.getNumBodies())
# print("p1.getNumBodies()=",p1.getNumBodies())
while (1):
# p0.stepSimulation()
# p1.stepSimulation()
# pgui.stepSimulation()
p.stepSimulation()<file_sep>/collisionFilter.py
import pybullet as p
import time
p.connect(p.GUI)
planeId = p.loadURDF("plane.urdf", useMaximalCoordinates=False)
cubeId = p.loadURDF("maiskolben.urdf", [-3, 0, 3], useMaximalCoordinates=False)
cubeId2 = p.loadURDF("maiskolben.urdf", [3, 0, 3], useMaximalCoordinates=False)
cubeId3 = p.loadURDF("maiskolben.urdf", [3, 3, 3], useMaximalCoordinates=False)
col = p.loadURDF("cube_collisionfilter.urdf", [0, 3, 3], useMaximalCoordinates=False)
collisionFilterGroup = 0
collisionFilterMask = 0
p.setCollisionFilterGroupMask(cubeId, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(cubeId2, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(cubeId3, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(col, -1, collisionFilterGroup, collisionFilterMask)
enableCollision = 1
p.setCollisionFilterPair(planeId, cubeId, -1, -1, enableCollision)
p.setCollisionFilterPair(planeId, cubeId2, -1, -1, enableCollision)
p.setCollisionFilterPair(planeId, cubeId3, -1, -1, enableCollision)
p.setCollisionFilterPair(planeId, col, -1, -1, enableCollision)
p.setRealTimeSimulation(1)
p.setGravity(0, 0, -10)
while (p.isConnected()):
time.sleep(1. / 240.)
# res = p.getOverlappingObjects(cubeId2, cubeId2)
aabb = p.getAABB(col)
res = p.getOverlappingObjects(aabb[0],aabb[1])
print(res)
p.stepSimulation()
p.setGravity(0, 0, -10)
<file_sep>/gui_only.py
import pybullet as p
import pybullet_utils.bullet_client as bc
import pybullet
import pybullet_data
import time
import math
import os
import atexit
import threading
# import concurrent.futures
# from concurrent.futures import ThreadPoolExecutor
# from concurrent.futures import ProcessPoolExecutor
# from multiprocessing import Pool
import numpy as np
import socket
import copy
# this is the main file
p.connect(p.GUI,"localhost", 7234)
p.configureDebugVisualizer(p.COV_ENABLE_GUI,0)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
def main():
while (p.isConnected()):
time.sleep(1. / 40.) # set to 40 fps
p.stepSimulation()
if __name__ == "__main__":
main()<file_sep>/hyperlights/collider.py
import pybullet
import math
import os
# this script contains the colliders
class Collider :
def __init__(self):
self.enabled = True
self.dirpath = os.getcwd() + "\\data\\"
# Positon
self.x = 0
self.y = 0
self.z = 0
# rotation (euler)
self.r = 0
self.p = 0
self.w = 0
# movement
self.a = 0
self.b = 0
self.c = 0
self.orn = [0,0,0,0]
self.pivot = [0, 0, 10]
self.a_step = 0.0
self.a_min = -80
self.a_max = 80
self.b_step = 0.0
self.b_min = -80
self.b_max = 80
self.c_step = 0.0
self.c_min = -80
self.c_max = 80
self.max_force = 500
self.a_step_ = 0.0
self.b_step_ = 0.0
self.c_step_ = 0.0
# pybullet object id
self.col = -1
# pybullet constrain id
self.cid = -1
self.collisionFilterGroup = 0
self.collisionFilterMask = 0
#
# def scale(self, s_x, s_y, s_z):
# not supported by pybullet
def setSpeed(self, s_x, s_y, s_z):
self.a_step = self.a_step_ * s_x
self.b_step = self.b_step_ * s_y
self.c_step = self.c_step_ * s_z
def simulate(self, p):
# if enabled:
reset = False
self.a = self.a + self.a_step
self.b = self.b + self.b_step
self.c = self.c + self.c_step
self.pivot = [self.x + self.a, self.y + self.b, self.z + self.c]
if (self.a > self.a_max):
self.a = self.a_min
reset = True
if (self.b > self.b_max):
self.b = self.b_min
reset = True
if (self.c > self.c_max):
self.c = self.c_min
reset = True
if reset:
p.resetBasePositionAndOrientation(self.col, [self.x + self.a, self.y + self.b, self.z + self.c], self.orn)
p.changeConstraint(self.cid, self.pivot, jointChildFrameOrientation=self.orn, maxForce=self.max_force)
def create(self, p , model):
self.a_step_ = self.a_step
self.b_step_ = self.b_step
self.c_step_ = self.c_step
self.pivot = [self.x, self.y, self.z]
self.orn = p.getQuaternionFromEuler([self.r, self.p, self.w])
self.col = p.loadURDF(model, [self.x, self.y, self.z], useMaximalCoordinates=False)
p.setCollisionFilterGroupMask(self.col, -1, self.collisionFilterGroup, self.collisionFilterMask)
# p.changeVisualShape(self.col, -1, rgbaColor=[100, 100, 100, 100])
self.cid = p.createConstraint(self.col, -1, -1, -1, p.JOINT_FIXED, [0, 0, 0], [0, 0, 0], [0, 0, 1])
p.changeConstraint(self.cid, self.pivot, jointChildFrameOrientation=self.orn, maxForce=self.max_force)
<file_sep>/maiskolben_array.py
import pybullet as p
import time
p.connect(p.GUI)
planeId = p.loadURDF("plane.urdf", useMaximalCoordinates=False)
col = p.loadURDF("cube_collisionfilter.urdf", [0, 3, 3], useMaximalCoordinates=False)
col2 = p.loadURDF("colCube.urdf", [0, 3, 15], useMaximalCoordinates=False)
def createMaiskolben( x, y, z, m_list, m_hit):
for i in range(10):
h = i * 0.4 + z
pixel_1 = p.loadURDF("pixel.urdf", [0.52263+x, 0+y, 3+h], useMaximalCoordinates=False)
pixel_2 = p.loadURDF("pixel.urdf", [-0.52263+x, 0+y, 3+h], useMaximalCoordinates=False)
pixel_3 = p.loadURDF("pixel.urdf", [0+x, 0.52263+y, 3+h], useMaximalCoordinates=False)
pixel_4 = p.loadURDF("pixel.urdf", [0+x, -0.52263+y, 3+h], useMaximalCoordinates=False)
pixel_5 = p.loadURDF("pixel.urdf", [0.36995+x, 0.36995+y, 3+h], useMaximalCoordinates=False)
pixel_6 = p.loadURDF("pixel.urdf", [-0.36995+x, -0.36995+y, 3+h], useMaximalCoordinates=False)
pixel_7 = p.loadURDF("pixel.urdf", [0.36995+x, -0.36995+y, 3+h], useMaximalCoordinates=False)
pixel_8 = p.loadURDF("pixel.urdf", [-0.36995+x, 0.36995+y, 3+h], useMaximalCoordinates=False)
m_list.append(pixel_1)
m_list.append(pixel_2)
m_list.append(pixel_3)
m_list.append(pixel_4)
m_list.append(pixel_5)
m_list.append(pixel_6)
m_list.append(pixel_7)
m_list.append(pixel_8)
j = 0
for pixel in m_list:
body = p.getBodyUniqueId(pixel)
while len(m_hit) < body:
m_hit.append(j)
m_hit.append(j)
maiskolben_1 =[]
maiskolben_1_hit = []
maiskolben_2 =[]
maiskolben_2_hit = []
maiskolben_3 =[]
maiskolben_3_hit = []
createMaiskolben( 0,0,0, maiskolben_1 , maiskolben_1_hit)
createMaiskolben( 5,0,0, maiskolben_2 , maiskolben_2_hit)
createMaiskolben( -5,0,0, maiskolben_3 , maiskolben_3_hit)
collisionFilterGroup = 0
collisionFilterMask = 0
p.setCollisionFilterGroupMask(col, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(col2, -1, collisionFilterGroup, collisionFilterMask)
collisionFilterGroup = 0
collisionFilterMask = 0
enableCollision = 1
p.setCollisionFilterPair(planeId, col, -1, -1, enableCollision)
p.setRealTimeSimulation(1)
# p.setGravity(0, 0, -10)
cid = p.createConstraint(col, -1, -1, -1, p.JOINT_FIXED, [0, 0, 0], [0, 0, 0], [0, 0, 1])
cid2 = p.createConstraint(col2, -1, -1, -1, p.JOINT_FIXED, [0, 0, 0], [0, 0, 0], [0, 0, 0])
a = 0
b = 0
while (p.isConnected()):
time.sleep(1. / 240.)
for pixel in maiskolben_1:
res = p.getClosestPoints(col2,pixel,0.1 )
body = p.getBodyUniqueId(pixel)
if res:
maiskolben_1_hit[body] = 1
else:
maiskolben_1_hit[body] = 0
# print(maiskolben_1_hit)
a = a + 0.02
pivot = [0, 0, a]
orn = p.getQuaternionFromEuler([0, 0, 1])
if (a > 10):
a = -1
# cid.btTransform([0, 0, -1])
p.changeConstraint(cid, pivot, jointChildFrameOrientation=orn, maxForce=5000)
p.changeConstraint(cid, pivot, jointChildFrameOrientation=orn, maxForce=50)
b = b + 0.02
pivot = [0, 0, 5.5]
orn2 = p.getQuaternionFromEuler([0, 0, b])
p.changeConstraint(cid2, pivot, jointChildFrameOrientation=orn2, maxForce=50)
p.stepSimulation()
# p.setGravity(0, 0, -10)
<file_sep>/maiskolben.py
import pybullet as p
import time
p.connect(p.GUI)
from hyperlights.hyperlights import Hyperlights
from hyperlights.hyperlights import HlMaiskoblen
planeId = p.loadURDF("plane.urdf", useMaximalCoordinates=False)
col = p.loadURDF("cube_collisionfilter.urdf", [0, 3, 3], useMaximalCoordinates=False)
col2 = p.loadURDF("colCube.urdf", [0, 3, 3], useMaximalCoordinates=False)
test = HlMaiskoblen()
# test = Maiskolben()
test.x = 5
test.z = 5
test.create(p)
maiskolben_1 =[]
maiskolben_1_hit = []
# def createMaiskolben( x, y, z):
# for i in (0,80):
# pixel
# maiskolben_id =
for i in range(10):
h = i * 0.4
pixel_1 = p.loadURDF("pixel.urdf", [0.52263, 0, 3+h], useMaximalCoordinates=False)
pixel_2 = p.loadURDF("pixel.urdf", [-0.52263, 0, 3+h], useMaximalCoordinates=False)
pixel_3 = p.loadURDF("pixel.urdf", [0, 0.52263, 3+h], useMaximalCoordinates=False)
pixel_4 = p.loadURDF("pixel.urdf", [0, -0.52263, 3+h], useMaximalCoordinates=False)
pixel_5 = p.loadURDF("pixel.urdf", [0.36995, 0.36995, 3+h], useMaximalCoordinates=False)
pixel_6 = p.loadURDF("pixel.urdf", [-0.36995, -0.36995, 3+h], useMaximalCoordinates=False)
pixel_7 = p.loadURDF("pixel.urdf", [0.36995, -0.36995, 3+h], useMaximalCoordinates=False)
pixel_8 = p.loadURDF("pixel.urdf", [-0.36995, 0.36995, 3+h], useMaximalCoordinates=False)
maiskolben_1.append(pixel_1)
maiskolben_1.append(pixel_2)
maiskolben_1.append(pixel_3)
maiskolben_1.append(pixel_4)
maiskolben_1.append(pixel_5)
maiskolben_1.append(pixel_6)
maiskolben_1.append(pixel_7)
maiskolben_1.append(pixel_8)
j = 0
for pixel in maiskolben_1:
body = p.getBodyUniqueId(pixel)
while len(maiskolben_1_hit) < body:
maiskolben_1_hit.append(j)
maiskolben_1_hit.append(j)
collisionFilterGroup = 0
collisionFilterMask = 0
p.setCollisionFilterGroupMask(col, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(col2, -1, collisionFilterGroup, collisionFilterMask)
collisionFilterGroup = 0
collisionFilterMask = 0
p.setCollisionFilterGroupMask(pixel_1, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(pixel_2, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(pixel_3, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(pixel_4, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(pixel_5, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(pixel_6, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(pixel_7, -1, collisionFilterGroup, collisionFilterMask)
p.setCollisionFilterGroupMask(pixel_8, -1, collisionFilterGroup, collisionFilterMask)
enableCollision = 1
p.setCollisionFilterPair(planeId, col, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, col2, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, pixel_1, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, pixel_2, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, pixel_3, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, pixel_4, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, pixel_5, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, pixel_6, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, pixel_7, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, pixel_8, -1, -1, enableCollision)
p.setRealTimeSimulation(1)
# p.setGravity(0, 0, -10)
cid = p.createConstraint(col, -1, -1, -1, p.JOINT_FIXED, [0, 0, 0], [0, 0, 0], [0, 0, 1])
cid2 = p.createConstraint(col2, -1, -1, -1, p.JOINT_FIXED, [0, 0, 0], [0, 0, 0], [0, 0, 0])
a = 0
b = 0
while (p.isConnected()):
time.sleep(1. / 240.)
# res = p.getOverlappingObjects(cubeId2, cubeId2)
# aabb = p.getAABB(pixel_1)
# res = p.getOverlappingObjects(aabb[0],aabb[1])
# print(res)
# for test in res:
# p.getContactPoints()
# res = p.getContactPoints(col2)
# res = p.getClosestPoints(col,pixel_1,0.1 )
# print(res)
for pixel in maiskolben_1:
res = p.getClosestPoints(col2,pixel,0.1 )
body = p.getBodyUniqueId(pixel)
if res:
maiskolben_1_hit[body] = 1
# p.changeVisualShape(body, -1, rgbaColor=[1, 0, 0, 1])
# print(body)
else:
maiskolben_1_hit[body] = 0
# p.changeVisualShape(body, -1, rgbaColor=[1, 1, 1, 1])
# p.changeVisualShape(objectUid, -1, rgbaColor=colors[currentColor])
# print(maiskolben_1_hit)
a = a + 0.02
pivot = [0, 0, a]
orn = p.getQuaternionFromEuler([0, 0, 1])
if (a > 10):
a = -1
# cid.btTransform([0, 0, -1])
p.changeConstraint(cid, pivot, jointChildFrameOrientation=orn, maxForce=5000)
p.changeConstraint(cid, pivot, jointChildFrameOrientation=orn, maxForce=50)
b = b + 0.02
pivot = [0, 0, 5.5]
orn2 = p.getQuaternionFromEuler([0, 0, b])
p.changeConstraint(cid2, pivot, jointChildFrameOrientation=orn2, maxForce=50)
p.stepSimulation()
# p.setGravity(0, 0, -10)
<file_sep>/hy_test2.py
import pybullet as p
import pybullet_utils.bullet_client as bc
import pybullet
import pybullet_data
import time
import math
import os
import atexit
import threading
# import concurrent.futures
# from concurrent.futures import ThreadPoolExecutor
# from concurrent.futures import ProcessPoolExecutor
# from multiprocessing import Pool
# import urllib.request
import numpy as np
import socket
import copy
p.connect(p.GUI_SERVER)
p.configureDebugVisualizer(p.COV_ENABLE_GUI,0)
p.setAdditionalSearchPath(pybullet_data.getDataPath())
# p1 = bc.BulletClient(connection_mode=pybullet.SHARED_MEMORY)
# p.resetDebugVisualizerCamera( cameraDistance=10, cameraYaw=90, cameraPitch=-80, cameraTargetPosition=[0,20,25]) # look on a1
# p.resetDebugVisualizerCamera( cameraDistance=50, cameraYaw=45, cameraPitch=-60, cameraTargetPosition=[0,-20,25])
# p.resetDebugVisualizerCamera( cameraDistance=50, cameraYaw=45, cameraPitch=-60, cameraTargetPosition=[0,-20,25])
p.resetDebugVisualizerCamera( cameraDistance=1, cameraYaw=270, cameraPitch=-10, cameraTargetPosition=[-50,0,15]) # look on wheel
from hyperlights.hyperlights import *
from hyperlights.collider import Collider
from hyperlights.artnetOut import artnetOut
from hyperlights.inputMidi import inputMidi
from hyperlights.wheelinput import wheelInput
from hyperlights.comm import inputData
aOutput = artnetOut()
mInput = inputMidi()
wInput = wheelInput()
# create room
planeId = p.loadURDF("plane.urdf", useMaximalCoordinates=False)
lights = []
colliders =[]
#create colliders
collider1 = Collider()
collider1.enabled = False
collider1.z = 15
collider1.b_step = 0.20
collider1.b_max = 65
collider1.b_min = -65
collider1.create(p,collider1.dirpath + "coll_full.urdf")
colliders.append(collider1)
collider2 = Collider()
collider2.z = 0
collider2.c_step = 0.05
collider2.c_max = 35
collider2.c_min = -5
collider2.create(p,collider2.dirpath + "coll_full_2.urdf")
colliders.append(collider2)
#create Lights
# einheit dm = 0.1m??
hlWheel = HlWheel()
hlWheel.x = -40
hlWheel.y = 0
hlWheel.z = 10
hlWheel.universe = 0
hlWheel.ip = "192.168.2.82"
hlWheel.onColor_r = 0
hlWheel.onColor_g = 255
hlWheel.onColor_b = 0
hlWheel.create(p)
lights.append(hlWheel)
# maiskolben_1 = HlMaiskoblen()
# maiskolben_1.x = 15
# maiskolben_1.y = -51.5
# maiskolben_1.z = 25
# maiskolben_1.create(p)
# maiskolben_1.universe = 7
# maiskolben_1.onColor_r = 0
# maiskolben_1.onColor_g = 255
# maiskolben_1.onColor_b = 0
# lights.append(maiskolben_1)
# maiskolben_2 = HlMaiskoblen()
# maiskolben_2.x = 15
# maiskolben_2.y = -38.5
# maiskolben_2.z = 25
# maiskolben_2.universe = 0
# maiskolben_2.create(p)
# maiskolben_2.onColor_r = 0
# maiskolben_2.onColor_g = 255
# maiskolben_2.onColor_b = 0
# lights.append(maiskolben_2)
# maiskolben_3 = HlMaiskoblen()
# maiskolben_3.x = 15
# maiskolben_3.y = -25.5
# maiskolben_3.z = 25
# maiskolben_3.universe = 2
# maiskolben_3.onColor_r = 0
# maiskolben_3.onColor_g = 255
# maiskolben_3.onColor_b = 0
# maiskolben_3.create(p)
# lights.append(maiskolben_3)
# maiskolben_4 = HlMaiskoblen()
# maiskolben_4.x = 15
# maiskolben_4.y = -12.5
# maiskolben_4.z = 25
# maiskolben_4.universe = 3
# maiskolben_4.onColor_r = 0
# maiskolben_4.onColor_g = 255
# maiskolben_4.onColor_b = 0
# maiskolben_4.create(p)
# lights.append(maiskolben_4)
# maiskolben_5 = HlMaiskoblen()
# maiskolben_5.x = 15
# maiskolben_5.y = 0.5
# maiskolben_5.z = 25
# maiskolben_5.universe = 1
# maiskolben_5.onColor_r = 0
# maiskolben_5.onColor_g = 255
# maiskolben_5.onColor_b = 0
# maiskolben_5.create(p)
# lights.append(maiskolben_5)
# PPPanel_1 = HlPPPanel()
# PPPanel_1.x = 10
# PPPanel_1.y = -55
# PPPanel_1.z = 25
# PPPanel_1.universe = 8
# PPPanel_1.onColor_r = 0
# PPPanel_1.onColor_g = 255
# PPPanel_1.onColor_b = 0
# PPPanel_1.create(p)
# lights.append(PPPanel_1)
# PPPanel_2 = HlPPPanel()
# PPPanel_2.x = -10
# PPPanel_2.y = -55
# PPPanel_2.z = 25
# PPPanel_2.universe = 10
# PPPanel_2.onColor_r = 0
# PPPanel_2.onColor_g = 255
# PPPanel_2.onColor_b = 0
# PPPanel_2.create(p)
# lights.append(PPPanel_2)
# Grid = HlGrid()
# Grid.x = -20
# Grid.y = -19.5
# Grid.z = 25
# Grid.universe = 0
# Grid.ip = "192.168.2.81"
# Grid.onColor_r = 255
# Grid.onColor_g = 128
# Grid.onColor_b = 0
# Grid.create(p)
# lights.append(Grid)
ledGrid = []
newMod = HlGridR()
newMod.x = -20
newMod.y = -19.5
newMod.z = 25
newMod.universe = 0
newMod.ip = "192.168.2.81"
newMod.onColor_r = 255
newMod.onColor_g = 128
newMod.onColor_b = 0
ledGrid.append(newMod)
for j in range(1,7):
# newMod = copy.copy(Grid)
newMod2 = HlGrid()
newMod2.x = -20
newMod2.y = -19.5
newMod2.z = 25
newMod2.universe = 0
newMod2.ip = "192.168.2.81"
newMod2.onColor_r = 255
newMod2.onColor_g = 128
newMod2.onColor_b = 0
newMod2.y += j * 6.5
newMod2.universe = j
ledGrid.append(newMod2)
newMod3 = HlGridR()
newMod3.x = -20
newMod3.y = 26
newMod3.z = 25
newMod3.universe = 7
newMod3.ip = "192.168.2.81"
newMod3.onColor_r = 255
newMod3.onColor_g = 128
newMod3.onColor_b = 0
ledGrid.append(newMod3)
for ledMod in ledGrid :
ledMod.create(p)
lights.append(ledMod)
# print(ledMod.y)
# print(ledMod.universe)
# A1struct = Hl_A1()
# A1struct.x = 0
# A1struct.y = 20
# A1struct.z = 25
# A1struct.create(p)
# A1struct.universe = 1
# A1struct.onColor_r = 0
# A1struct.onColor_g = 255
# A1struct.onColor_b = 0
# lights.append(A1struct)
# starCoreLight = HlStarLight()
# starCoreLight.x = 0
# starCoreLight.y = -45
# starCoreLight.z = 25
# starCoreLight.ip= "192.168.2.60"
# starCoreLight.universe = 3
# starCoreLight.create(p)
# starCoreLight.onColor_r = 0
# starCoreLight.onColor_g = 255
# starCoreLight.onColor_b = 0
# lights.append(starCoreLight)
# starCoreRed = HlStarCore()
# starCoreRed.x = 15
# starCoreRed.y = 45
# starCoreRed.z = 25
# starCoreRed.ip= "192.168.2.62"
# starCoreRed.universe = 2
# starCoreRed.onColor_r = 0
# starCoreRed.onColor_g = 255
# starCoreRed.onColor_b = 0
# starCoreRed.create(p)
# lights.append(starCoreRed)
# starCoreBlue = HlStarCore()
# starCoreBlue.x = -15
# starCoreBlue.y = 45
# starCoreBlue.z = 25
# starCoreBlue.ip= "192.168.2.63"
# starCoreBlue.universe = 2
# starCoreBlue.onColor_r = 0
# starCoreBlue.onColor_g = 255
# starCoreBlue.onColor_b = 0
# starCoreBlue.create(p)
# lights.append(starCoreBlue)
def getRayFromTo(mouseX, mouseY):
width, height, viewMat, projMat, cameraUp, camForward, horizon, vertical, _, _, dist, camTarget = p.getDebugVisualizerCamera(
)
camPos = [
camTarget[0] - dist * camForward[0], camTarget[1] - dist * camForward[1],
camTarget[2] - dist * camForward[2]
]
farPlane = 10000
rayForward = [(camTarget[0] - camPos[0]), (camTarget[1] - camPos[1]), (camTarget[2] - camPos[2])]
invLen = farPlane * 1. / (math.sqrt(rayForward[0] * rayForward[0] + rayForward[1] *
rayForward[1] + rayForward[2] * rayForward[2]))
rayForward = [invLen * rayForward[0], invLen * rayForward[1], invLen * rayForward[2]]
rayFrom = camPos
oneOverWidth = float(1) / float(width)
oneOverHeight = float(1) / float(height)
dHor = [horizon[0] * oneOverWidth, horizon[1] * oneOverWidth, horizon[2] * oneOverWidth]
dVer = [vertical[0] * oneOverHeight, vertical[1] * oneOverHeight, vertical[2] * oneOverHeight]
rayToCenter = [
rayFrom[0] + rayForward[0], rayFrom[1] + rayForward[1], rayFrom[2] + rayForward[2]
]
rayTo = [
rayToCenter[0] - 0.5 * horizon[0] + 0.5 * vertical[0] + float(mouseX) * dHor[0] -
float(mouseY) * dVer[0], rayToCenter[1] - 0.5 * horizon[1] + 0.5 * vertical[1] +
float(mouseX) * dHor[1] - float(mouseY) * dVer[1], rayToCenter[2] - 0.5 * horizon[2] +
0.5 * vertical[2] + float(mouseX) * dHor[2] - float(mouseY) * dVer[2]
]
return rayFrom, rayTo
# artnetSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
p.setRealTimeSimulation(1)
# p.setGravity(0, 0, -10)
def endThreads():
aOutput.endOut()
mInput.endInput()
wInput.endInput()
# executor = ThreadPoolExecutor(max_workers=2)
# executor = ProcessPoolExecutor(max_workers=4)
def main():
atexit.register(endThreads)
for light in lights:
print("universe %d" % light.universe)
# light.create(p)
# executor.submit(light.create, p)
# light.doCollisionFilter(p,collider1.col)
# light.sendData(artnetSocket)
# light.createArtnet()
aOutput.startOut(p, lights)
mInput.startInput(lights, colliders)
wInput.startInput()
wheelAngle = 0
# for ji in range(0,hlWheel.numJoints):
# print("led %d" % ji)
# hlWheel.hit[ji] = 1
# hlWheel.update = True
# time.sleep(0.10)
# hlWheel.hit[ji] = 0
# hlWheel.update = True
colors = [[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [1, 1, 1, 1]]
currentColor = 0
try:
while (p.isConnected()):
time.sleep(1. / 40.)
aOutput.alive = 0 # reset output timeout, hack for threads...
mInput.alive = 0
wInput.alive = 0
wheelAngle = wInput.angle
hlWheel.setRotation(p,wheelAngle )
for col in colliders:
col.simulate(p)
if col.enabled :
for light in lights:
light.doCollisionFilter(p,col)
# executor.submit(light.doCollisionFilter, p,col)
p.stepSimulation()
mouseEvents = p.getMouseEvents()
for e in mouseEvents:
if ((e[0] == 2) and (e[3] == 0) and (e[4] & p.KEY_WAS_TRIGGERED)):
mouseX = e[1]
mouseY = e[2]
rayFrom, rayTo = getRayFromTo(mouseX, mouseY)
rayInfo = p.rayTest(rayFrom, rayTo)
for l in range(len(rayInfo)):
hit = rayInfo[l]
objectUid = hit[0]
jointUid = hit[1]
if (objectUid >= 1):
print("obj %i joint %i" % (objectUid , jointUid))
p.changeVisualShape(objectUid, jointUid, rgbaColor=colors[currentColor])
currentColor += 1
if (currentColor >= len(colors)):
currentColor = 0
except KeyboardInterrupt:
print("KeyboardInterrupt has been caught.")
finally:
endThreads()
if __name__ == "__main__":
main()<file_sep>/hyperlights/wheelinput.py
import pybullet
import math
import socket
import os
import threading
import numpy as np
import socket , pickle
import json
import time
# this is the wheel feedback thread
# position feedback is send via udp on a special port
class wheelInput:
def __init__(self):
self.wheel_ip = "192.168.2.82"
self.wheel_port = 50582
self.wheel_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.angle = 0.0
self.alive = 0
self.running = True
def inputDataLoop(self):
self.wheel_sock.settimeout(5.0)
while (self.running == True):
try:
(data, addr) = self.wheel_sock.recvfrom(10240)
# print(data)
strData = data.decode("utf-8")
a = strData.split()
ai = int(a[1]) + 25
# offset = math.pi/2 * 3
# self.angle = -(float(a[1]) / 4096.0) * (math.pi *2) + offset
offset = math.pi
self.angle = -(float(ai) / 4096.0) * (math.pi *2) + offset
# strData = str(data.decode("utf-8"))
# print("wheel data")
# print("angle: %i - %f" % (ai ,self.angle))
except Exception as e:
# print.error(traceback.format_exc())
if str(e) != "timed out":
print(e)
self.alive += 1
if self.alive > 5:
self.running = False
print("end wheel input thread")
def startInput(self):
self.wheel_sock.bind(('',self.wheel_port))
x = threading.Thread(target=self.inputDataLoop )
x.start()
print("starting wheel input Thread")
def endInput(self):
if self.running:
self.running = False
packet = "close"
self.wheel_sock.sendto(bytes(packet, 'utf-8'), ("127.0.0.1", self.wheel_port))
<file_sep>/hyperlights/comm.py
class inputData:
devID = 0
inpID = 0
inpVal = 0<file_sep>/hyperlights/gui.py
import pybullet
import pybullet_data
import pybullet as p
import pybullet_utils.bullet_client as bc
import time
import math
import os
import threading
import numpy as np
import socket
import copy
# p.connect(p.SHARED_MEMORY)
# # p.connect(p.GUI)
# p.configureDebugVisualizer(p.COV_ENABLE_GUI,0)
# p.resetDebugVisualizerCamera( cameraDistance=50, cameraYaw=45, cameraPitch=-60, cameraTargetPosition=[0,-20,25])
#can also connect using different modes, GUI, SHARED_MEMORY, TCP, UDP, SHARED_MEMORY_SERVER, GUI_SERVER
pgui = bc.BulletClient(connection_mode=pybullet.UDP)
while (pgui.isConnected()):
time.sleep(1. / 240.)
# import pybullet_utils.bullet_client as bc
# import pybullet
# import pybullet_data
# p0 = bc.BulletClient(connection_mode=pybullet.DIRECT)
# p0.setAdditionalSearchPath(pybullet_data.getDataPath())
# p1 = bc.BulletClient(connection_mode=pybullet.DIRECT)
# p1.setAdditionalSearchPath(pybullet_data.getDataPath())
# #can also connect using different modes, GUI, SHARED_MEMORY, TCP, UDP, SHARED_MEMORY_SERVER, GUI_SERVER
# pgui = bc.BulletClient(connection_mode=pybullet.GUI)
# p0.loadURDF("r2d2.urdf")
# p1.loadSDF("stadium.sdf")
# print(p0._client)
# print(p1._client)
# print("p0.getNumBodies()=",p0.getNumBodies())
# print("p1.getNumBodies()=",p1.getNumBodies())
# while (1):
# p0.stepSimulation()
# p1.stepSimulation()
# pgui.stepSimulation()<file_sep>/pyGUI.py
import pygame
import time
import random
import os
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0,0) #-3584
pygame.init()
display_width = 1027
display_height = 768
text_color = (187,131,7)
button_color = (187,131,7)
button_highlight_color = (255,208,99)
button_back_color = (15,15,15)
button_highlight_back_color = (50,50,50)
black = (20,20,20)
white = (255,255,255)
red = (192,0,0)
bright_red = (255,0,0)
green = (0,128,0)
bright_green = (0,255,0)
# gameDisplay = pygame.display.set_mode((display_width,display_height), pygame.FULLSCREEN |pygame.HWSURFACE )
gameDisplay = pygame.display.set_mode((display_width,display_height), pygame.NOFRAME)
pygame.display.set_caption('HyperLight GUI')
clock = pygame.time.Clock()
# carImg = pygame.image.load('racecar.png')
#######
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
#######
def text_objects(text, font):
textSurface = font.render(text, True, text_color)
return textSurface, textSurface.get_rect()
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
# print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, button_highlight_back_color,(x,y,w,h))
pygame.draw.rect(gameDisplay, ac,(x,y,w,h), 2)
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(gameDisplay, button_back_color,(x,y,w,h))
pygame.draw.rect(gameDisplay, ic,(x,y,w,h),3)
smallText = pygame.font.SysFont("swiss721",14)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def button_round(msg,x,y,w,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
# print(click)
if x+2*w > mouse[0] > x and y+2*w > mouse[1] > y:
pygame.draw.circle(gameDisplay, button_highlight_back_color,(x+w,y+w),w)
pygame.draw.circle(gameDisplay, ac,(x+w,y+w),w, 2)
if click[0] == 1 and action != None:
action()
else:
pygame.draw.circle(gameDisplay, button_back_color,(x+w,y+w),w)
pygame.draw.circle(gameDisplay, ic,(x+w,y+w),w,3)
smallText = pygame.font.SysFont("swiss721",14)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w)), (y+(w)) )
gameDisplay.blit(textSurf, textRect)
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed')
gameExit = False
def quitgame():
gameExit = True
pygame.quit()
quit()
def button_pressed():
print('click')
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_offset = 0
y_offset = 180
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.draw.rect(gameDisplay, button_color,(0,0,1024,768), 4)
button("EXIT",16*60+x_offset,10,50,50,red,bright_red,quitgame)
for x in range(1, 9):
for y in range(1, 9):
button("%d%d" %(x,y),x*60 + x_offset,y*60 + y_offset,50,50,button_color,button_highlight_color,button_pressed)
y = y_offset
for x in range(1, 9):
button_round("%d%d" %(x,y),x*60 + x_offset,y,25,button_color,button_highlight_color,button_pressed)
x = 9*60 + x_offset
for y in range(1, 9):
button_round("%d%d" %(x,y),x,y*60 + y_offset,25,button_color,button_highlight_color,button_pressed)
pygame.display.update()
clock.tick(15)
game_loop()
pygame.quit()
quit()<file_sep>/pybullettut.py
import pybullet as p
import time
import pybullet_data
physicsClient = p.connect(p.GUI)#or p.DIRECT for non-graphical version
p.setAdditionalSearchPath(pybullet_data.getDataPath()) #optionally
p.setGravity(0,0,0)
planeId = p.loadURDF("plane.urdf")
cubeStartPos = [0,0,1]
cubeStartOrientation = p.getQuaternionFromEuler([0,0,0])
boxId = p.loadURDF("r2d2.urdf",cubeStartPos, cubeStartOrientation)
# trigger1 = p.loadURDF("cube.urdf", [2, 2, 5])
shift = [0, -0.02, 0]
meshScale = [0.1, 0.1, 0.1]
triggerCube = p.createVisualShape(shapeType=p.GEOM_MESH,
fileName="cube.urdf",
rgbaColor=[1, 1, 1, 1],
specularColor=[0.4, .4, 0],
visualFramePosition=shift,
meshScale=meshScale)
visualShapeId = p.createVisualShape(shapeType=p.GEOM_SPHERE,
radius=5,
rgbaColor=[1, 1, 1, 1],
specularColor=[0.4, .4, 0]
)
for i in range (10000):
p.stepSimulation()
res = p.getOverlappingObjects(triggerCube, triggerCube)
print(res)
time.sleep(1./240.)
cubePos, cubeOrn = p.getBasePositionAndOrientation(boxId)
print(cubePos,cubeOrn)
p.disconnect()
<file_sep>/hyperlights/urdf_generator.py
# import xml.etree.cElementTree as ET
# root = ET.Element("root")
# doc = ET.SubElement(root, "doc")
# ET.SubElement(doc, "field1", name="blah").text = "some value1"
# ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"
# tree = ET.ElementTree(root)
# tree.write("filename.xml")
# If you have OCD and need a clean namespace, change to standard import
from odio_urdf import *
# https://github.com/hauptmech/odio_urdf
# my_robot = Robot(
# Link(name="link1"),
# Link(name="link2"),
# Link("link3"), #String arguments without keys are assumed to be 'name'
# Link(name="link4"),
# Joint("joint1", Parent("link1"), Child("link2"), type="continuous"),
# Joint("joint2",
# Parent("link1"),
# Child("link2"),
# type="continuous" #KeyValue arguments go at the end of a call
# ),
# Joint("joint3", Parent("link3"), Child("link4"), type="continuous")
# )
filepath = ""
robot_name = "LED"
def link(N,robot_name,origin,mass,I,material,geom_origin):
"""
Most of the links are the same except for the passed in info.
This function just allows grouping the important numbers better.
"""
N = str(N)
ret = Link(
Inertial(
Origin(origin),
Mass(value=mass),
Inertia(I)),
Visual(
Origin(geom_origin),
Geometry(Mesh(filename = filepath+"visual/link_"+N+".stl")),
Material(material)),
Collision(
Origin(geom_origin),
Geometry(Mesh(filename = filepath+"collision/link_"+N+".stl")),
Material(material, Color(rgba="1,1,1,1"))),
name = robot_name+"_link_"+N)
return ret
def LED(link_name,origin,material,geom_origin):
"""
Most of the links are the same except for the passed in info.
This function just allows grouping the important numbers better.
"""
mass = 1.0
# <inertia ixx="100" ixy="0" ixz="0" iyy="100" iyz="0" izz="100"/>
I = [1.0,0,0,1.0,0,1.0]
ret = Link(
Inertial(
Origin(origin),
Mass(value=mass),
Inertia(I)),
Visual(
Origin(geom_origin),
Geometry(Box(size = "0.5 0.5 0.16")),
Material(material, Color(rgba="1 1 1 1"))),
Collision(
Origin(geom_origin),
Geometry(Box(size = "0.5 0.5 0.16")),
Material(material, Color(rgba="1 1 1 1"))),
name = link_name)
return ret
# print(my_robot) #Dump urdf to stdout
my_robot = Robot("Tristar48")
# link1 = Link() #name 'link1' will be used unless link1.name is set
# link1 = link(1,"hl","0,0,0",1,1,"White","0,0,0")
# link1 = LED("hl","0,0,0","White","0,0,0")
# link2 = Link()
# link3 = Link("special_name") #This link has the name 'special_name'
mass = 1.0
origin = [0,0,0 ,0,0,0]
geom_origin = "0,0,0"
I = [1.0,0,0,1.0,0,1.0]
material = "white"
link_name= "baseLink"
baseLink = Link(
Inertial(
Origin(origin),
Mass(value=mass),
Inertia(I)),
Visual(
Origin(geom_origin),
Geometry(Box(size = "0.5 0.5 8.6")),
Material(material, Color(rgba="1 1 1 0.5"))),
Collision(
Origin(geom_origin),
Geometry(Box(size = "0.5 0.5 8.6")),
Material(material, Color(rgba="1 1 1 0.5"))),
name = link_name)
my_robot(baseLink)
base = Parent("baseLink")
N = 48
for i in range(1,N):
d = -0.17
link_name = robot_name+"_link_"+ str(i)
joint_name = robot_name+"_joint_"+ str(i)
geom_origin = [0 , 0 , i*d + 4.3]
origin = [0,0,0 ,0,0,0]
led_link = LED(link_name,origin,"White",geom_origin)
joint1 = Joint(joint_name, base, Child(link_name), type="fixed")
my_robot(led_link)
my_robot(joint1)
#Add first elements to robot
# my_robot(link1,link2,link3)
# my_robot(link1)
# base = Parent("link1")
# joint1 = Joint(base, Child("link2"), type="fixed")
# joint2 = Joint(base, Child("link3"), type="continuous")
# joint3 = Joint(Parent("link3"), Child("special_name"), type="continuous")
# my_robot(joint1,joint2,joint3)
# my_robot.write("filename.xml")
f= open("tristar_48g.urdf","w+")
print(my_robot, file=f)
# f.write(my_robot)
f.close()
print(my_robot)
<file_sep>/launchcontrol_.py
#!/usr/bin/env python
# needs my patched version of launchpad.py
# download and install from
# https://github.com/4ndreas/launchpad.py
import sys
import socket , pickle
import json
import pygame
import random
from pygame import time
import os
import ctypes
ctypes.windll.user32.SetProcessDPIAware()
from hyperlights.comm import inputData
try:
import launchpad_py as launchpad
except ImportError:
try:
import launchpad
except ImportError:
sys.exit("error loading launchpad.py")
# create an instance
lp = lambda: None
lp2 = lambda: None
but = lambda: None
but2 = lambda: None
lp_but = []
lp_knob = []
lp2_but = []
lp2_knob = []
pygame.init()
text_color = (187,131,7)
button_color = (187,131,7)
button_highlight_color = (255,208,99)
button_back_color = (15,15,15)
button_highlight_back_color = (50,50,50)
black = (20,20,20)
white = (255,255,255)
red = (192,0,0)
bright_red = (255,0,0)
green = (0,128,0)
bright_green = (0,255,0)
frame_border = 5
infoObject = pygame.display.Info()
# pygame.display.set_mode((infoObject.current_w, infoObject.current_h))
display_width = infoObject.current_w
display_height = 300
display_x_offset = 0
taskleiste_h = 50
display_y_offset = infoObject.current_h - display_height - taskleiste_h
print("init screen w:%d h:%d, x:%d y:%d" % (display_width, display_height, display_x_offset, display_y_offset ))
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (display_x_offset,display_y_offset) #-3584,00
gameDisplay = pygame.display.set_mode((display_width,display_height), pygame.NOFRAME)
pygame.display.set_caption('HyperLight GUI')
clock = pygame.time.Clock()
gameExit = False
exitFlag = [False, False]
def quitgame():
gameExit = True
# lp.Reset()
# lp2.Reset()
# lp.Close()
# lp2.Close()
pygame.quit()
quit()
transfer_port = 50505
transfer_ip = "127.0.0.1"
transfer_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# class inputData:
# devID = 0.0
# inpID = 0.0
# inpVal = 0.0
# def openSocket():
# transfer_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Controlsock.setblocking(0)
# transfer_socket.bind(('',transfer_socket))
# transfer_socket.sendto(bytes(info, "utf-8"), (UDP_IP, UDP_InfoPort))
def sendData(pad, id, val):
data_variable = inputData()
data_variable.devID = pad
data_variable.inpID = id
data_variable.inpVal = val
data_string = pickle.dumps(data_variable)
# transfer_socket.send(data_string)
# print(data_string)
# transfer_socket.sendto(data_string, (transfer_ip, transfer_port))
# transfer_socket.sendto(bytes(data_string, "utf-8"), (transfer_ip, transfer_port))
# data_string = json.dumps(data_variable)
# rx_data_variable = pickle.loads(data_string)
# print(str(rx_data_variable.inpID))
# transfer_socket.sendto(bytes(str(data_string), "utf-8"), (transfer_ip, transfer_port))
transfer_socket.sendto(data_string, (transfer_ip, transfer_port))
def mapInput(pad, input, but, knob):
if input[0] == 9:
but[0] = input[1]
drawButton(pad, 0, but[0] )
elif input[0] == 10:
but[1] = input[1]
drawButton(pad, 1, but[1] )
elif input[0] == 11:
but[2] = input[1]
drawButton(pad, 2, but[2] )
elif input[0] == 12:
but[3] = input[1]
drawButton(pad, 3, but[3] )
elif input[0] == 13:
but[4] = input[1]
drawButton(pad, 4, but[4] )
elif input[0] == 14:
but[5] = input[1]
drawButton(pad, 5, but[5] )
elif input[0] == 15:
but[6] = input[1]
drawButton(pad, 6, but[6] )
elif input[0] == 16:
but[7] = input[1]
drawButton(pad, 7, but[7] )
elif input[0] == 114:
but[8] = input[1]
elif input[0] == 115:
but[9] = input[1]
exitFlag[pad] = input[1]
if exitFlag[0] > 0 and exitFlag[1] > 0 :
print("exit")
quitgame()
elif input[0] == 116:
but[10] = input[1]
elif input[0] == 117:
but[11] = input[1]
if input[0] == 21:
knob[0] = input[1]
drawKnob(pad, 0, knob[0] )
elif input[0] == 22:
knob[1] = input[1]
drawKnob(pad, 1, knob[1] )
elif input[0] == 23:
knob[2] = input[1]
drawKnob(pad, 2, knob[2] )
elif input[0] == 24:
knob[3] = input[1]
drawKnob(pad, 3, knob[3] )
elif input[0] == 25:
knob[4] = input[1]
drawKnob(pad, 4, knob[4] )
elif input[0] == 26:
knob[5] = input[1]
drawKnob(pad, 5, knob[5] )
elif input[0] == 27:
knob[6] = input[1]
drawKnob(pad, 6, knob[6] )
elif input[0] == 28:
knob[7] = input[1]
drawKnob(pad, 7, knob[7] )
elif input[0] == 41:
knob[8] = input[1]
drawKnob(pad, 8, knob[8] )
elif input[0] == 42:
knob[9] = input[1]
drawKnob(pad, 9, knob[9] )
elif input[0] == 43:
knob[10] = input[1]
drawKnob(pad, 10, knob[10] )
elif input[0] == 44:
knob[11] = input[1]
drawKnob(pad, 11, knob[11] )
elif input[0] == 45:
knob[12] = input[1]
drawKnob(pad, 12, knob[12] )
elif input[0] == 46:
knob[13] = input[1]
drawKnob(pad, 13, knob[13] )
elif input[0] == 47:
knob[14] = input[1]
drawKnob(pad, 14, knob[14] )
elif input[0] == 48:
knob[15] = input[1]
drawKnob(pad, 15, knob[15] )
def text_objects(text, font):
textSurface = font.render(text, True, text_color)
return textSurface, textSurface.get_rect()
def drawKnob(pad, knob, val):
w = 40
y = 20
if knob > 7:
y = 110
knob -= 8
x = int((w*2.5) * knob + pad * (display_width / 2)) + w
pygame.draw.circle(gameDisplay, button_highlight_back_color,(x+w,y+w),w)
pygame.draw.circle(gameDisplay, button_highlight_color,(x+w,y+w),w,2)
smallText = pygame.font.SysFont("swiss721",20)
textSurf, textRect = text_objects(str(val), smallText)
textRect.center = ( (x+(w)), (y+(w)) )
gameDisplay.blit(textSurf, textRect)
sendData(pad, knob+12, val)
def drawButton(pad, button, val):
w = 80
h = 80
y = 200
x = int( ((w/2*2.5)) * button + pad * (display_width / 2) + w/2 )
pygame.draw.rect(gameDisplay, button_highlight_back_color,(x,y,w,h))
pygame.draw.rect(gameDisplay, button_highlight_color,(x,y,w,h),2)
if val > 0:
pygame.draw.rect(gameDisplay, button_highlight_color,(x+8,y+8,w-16,h-16))
# else:
# pygame.draw.rect(gameDisplay, button_highlight_color,(x,y,w,h),2)
sendData(pad, button, val)
def drawLaunchControl( pad ):
x_size = (display_width / 2)
x_offset = (pad) * x_size
s_x = x_offset + frame_border
s_y = frame_border
e_x = x_size - 2*frame_border
e_y = display_height - 2* frame_border
pygame.draw.rect(gameDisplay, button_color,(s_x,s_y,e_x, e_y), 2)
for i in range( 0,16):
if pad == 0:
drawKnob(pad, i, lp_knob[i])
else:
drawKnob(pad, i, lp2_knob[i])
for i in range( 0,8):
if pad == 0:
drawButton(pad, i, lp_but[i])
else:
drawButton(pad, i, lp2_but[i])
def main():
mode = None
# create an instance
lp = launchpad.Launchpad()
lp2 = launchpad.Launchpad()
# check what we have here and override lp if necessary
# if lp.Check( 0, "mk2" ):
# lp = launchpad.LaunchpadMk2()
# if lp.Open( 0, "mk2" ):
# print("Launchpad Mk2")
# mode = "Mk2"
if lp.Check( 1, "control" ):
lp = launchpad.LaunchControl()
if lp.Open( 1, "control" ):
# lp.TemplateSet(1)
print("First Launch Control")
mode = "S"
if lp2.Check( 0, "control" ):
lp2 = launchpad.LaunchControl()
if lp2.Open( 0, "control" ):
# lp2.TemplateSet(1)
print("Second Launch Control")
mode = "S"
if mode is None:
print("Did not find any Launchpads, meh...")
return
print("---\nDual LaunchControl GUI")
print("events before you press one of the (top) automap buttons")
# Clear the buffer because the Launchpad remembers everything :-)
lp.ButtonFlush()
lp2.ButtonFlush()
# lp.Reset() # turn all LEDs off
# lp2.Reset() # turn all LEDs off
for i in range( 0,16):
lp_knob.append(0)
lp2_knob.append(0)
for i in range( 0,12):
lp_but.append(0)
lp2_but.append(0)
drawLaunchControl(0)
drawLaunchControl(1)
pygame.display.update()
# openSocket()
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
but = lp.InputStateRaw()
if but != []:
mapInput(0,but, lp_but, lp_knob)
if but[1] > 0:
# print("set button %d to On" % but[0])
lp.LedCtrl(but[0],128,0)
else:
lp.LedCtrl(but[0],0,0)
data = 'event LC1: %d - %d' % (but[0] , but[1])
# print(data)
but2 = lp2.InputStateRaw()
if but2 != []:
mapInput(1,but2, lp2_but, lp2_knob)
if but2[1] > 0:
# print("set button %d to On" % but2[0])
lp2.LedCtrl(but2[0],128,0)
else:
lp2.LedCtrl(but2[0],0,0)
data = 'event LC2: %d - %d' % (but2[0] , but2[1])
# print(data)
# Create an instance of ProcessData() to send to server.
# variable = ProcessData()
# # Pickle the object and send it to the server
# data_string = pickle.dumps(variable)
# s.send(data_string)
pygame.display.update()
# now quit...
print("Quitting might raise a 'Bad Pointer' error (~almost~ nothing to worry about...:).\n\n")
lp.Reset() # turn all LEDs off
lp2.Reset() # turn all LEDs off
lp.Close() # close the Launchpad (will quit with an error due to a PyGame bug)
lp2.Close() # close the Launchpad (will quit with an error due to a PyGame bug)
if __name__ == '__main__':
main()
<file_sep>/README.md
# HyperLightControl
```
pip install pybullet
```
run
```
hyperlight_main.py
```
optionl run launchcontrol_.py for midi control
<file_sep>/hyperlights/artnetOut.py
import pybullet
import math
import os
import threading
import numpy as np
import socket
import time
# this script contains the artnet output thread
class artnetOut:
def __init__(self):
# self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._lights = []
self.running = False
self.alive = 0
self.t = threading.Timer(1, self.sendData)
def sendDataLoop(self):
while (self.running == True):
for light in self._lights:
# print(light.universe)
# light.doCollisionFilter(p,collider1.col)
light.sendData()
# light.sendData(self._sock)
# if light.enable:
# light.createArtnet()
# light.make_header()
# light.createArtnet()
# if light.universe == 0:
# self._sock.sendto(bytes(light.packet), (light.ip, light.artnetPort))
self.alive += 1
if self.alive > 100:
self.running = False
time.sleep(1./ 40.0) # 40 fps
print("end artnet thread")
def sendData(self):
# if(self.running == False):
print("output data")
# self.running = True
for light in self._lights:
light.createArtnet()
light.sendData(self._sock)
# self.running = False
# self.t.start()
def startOut(self,p, lights):
self._lights = lights
self.running = True
# start_new_thread(self.sendData, ())
x = threading.Thread(target=self.sendDataLoop )
x.start()
print("starting artnet Output Thread")
# self.t.start()
# self.t.join()
def endOut(self):
if self.running:
self.running = False
<file_sep>/hyperlights/hlWheel.py
import math
from odio_urdf import *
# https://github.com/hauptmech/odio_urdf
# this script generates the urdf file for the rotating wheel
filepath = ""
robot_name = "LED"
def LED(link_name,origin,material,geom_origin, color="1 1 1 1"):
"""
Most of the links are the same except for the passed in info.
This function just allows grouping the important numbers better.
"""
mass = 1.0
# <inertia ixx="100" ixy="0" ixz="0" iyy="100" iyz="0" izz="100"/>
# I = [1.0,0,0,1.0,0,1.0]
I = [0,0,0,0,0,0]
ret = Link(
Inertial(
Origin(origin),
Mass(value=mass),
Inertia(I)),
Visual(
Origin(geom_origin),
Geometry(Box(size = "0.5 0.5 0.16")),
Material(material, Color(rgba=color))),
Collision(
Origin(geom_origin),
Geometry(Box(size = "0.5 0.5 0.16")),
Material(material, Color(rgba=color))),
name = link_name)
return ret
#math.pi/2
mass = 1.0
origin = [0,0,0 ,0,0,0,]
geom_origin = [0,0,0 ,math.pi/2,0,0,]
I = [1.0,0,0,1.0,0,1.0]
material = "white"
link_name= "baseLink"
baseLink = Link(
Inertial(
Origin(origin),
Mass(value=mass),
Inertia(I)),
Visual(
Origin(geom_origin),
# Geometry(Cylinder(size = "20.0 2.0 20.0")),
Geometry(Cylinder(radius = "10.0", length="2.0")),
Material(material, Color(rgba="1 1 1 0.5"))),
Collision(
Origin(geom_origin),
Geometry(Cylinder(radius = "10.0", length="2.0")),
Material(material, Color(rgba="1 1 1 0.5"))),
name = link_name)
my_robot = Robot("hlWheel")
my_robot(baseLink)
base = Parent("baseLink")
N = 49
i = 0
for j in range(0,6):
for k in range(1,N):
d = 0.17
d2 = 1.0
link_name = robot_name+"_link_"+ str(i)
joint_name = robot_name+"_joint_"+ str(i)
rot = j * ((math.pi * 2 )/ 6)
# origin = [0 , 0 , 0 ,rot,0,0]
# geom_origin = [0,0,k*d + 9 ,0,0,0]
origin = [0,0,0 ,0,0,0]
geom_origin = [0 , 0 , 0 ,0,0,0]
f = 48 / (k) - 1
color = "%f %f %f 1" % (f,1,1)
# led_link = LED(link_name,origin,"White",geom_origin, color)
led_link = LED(link_name,origin,"White",geom_origin)
dy = math.sin(rot) * (k*d + d2 )
dz = math.cos(rot) * (k*d + d2 )
jorigin = [dy,0,dz ,0,rot,0]
joint1 = Joint(joint_name, base, Child(link_name), Origin(jorigin), type="fixed")
# joint1 = Joint(joint_name, base, Child(link_name), type="fixed")
my_robot(led_link)
my_robot(joint1)
i+= 1
f= open("data\\hlWheel.urdf","w+")
print(my_robot, file=f)
f.close()
print(my_robot)
<file_sep>/artnet_Viewer.py
import pygame
import time
import random
import os
import socket
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0,0) #-3584
pygame.init()
UDP_IP = "127.0.0.1"
artnetPort = 6454
display_width = 1027
display_height = 768
text_color = (187,131,7)
button_color = (187,131,7)
button_highlight_color = (255,208,99)
button_back_color = (15,15,15)
button_highlight_back_color = (50,50,50)
black = (20,20,20)
white = (255,255,255)
red = (192,0,0)
bright_red = (255,0,0)
green = (0,128,0)
bright_green = (0,255,0)
# gameDisplay = pygame.display.set_mode((display_width,display_height), pygame.FULLSCREEN |pygame.HWSURFACE )
# gameDisplay = pygame.display.set_mode((display_width,display_height), pygame.NOFRAME)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Artnet viwer')
clock = pygame.time.Clock()
#######
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
#######
def text_objects(text, font):
textSurface = font.render(text, True, text_color)
return textSurface, textSurface.get_rect()
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
# print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, button_highlight_back_color,(x,y,w,h))
pygame.draw.rect(gameDisplay, ac,(x,y,w,h), 2)
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(gameDisplay, button_back_color,(x,y,w,h))
pygame.draw.rect(gameDisplay, ic,(x,y,w,h),3)
smallText = pygame.font.SysFont("swiss721",14)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def button_round(msg,x,y,w,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
# print(click)
if x+2*w > mouse[0] > x and y+2*w > mouse[1] > y:
pygame.draw.circle(gameDisplay, button_highlight_back_color,(x+w,y+w),w)
pygame.draw.circle(gameDisplay, ac,(x+w,y+w),w, 2)
if click[0] == 1 and action != None:
action()
else:
pygame.draw.circle(gameDisplay, button_back_color,(x+w,y+w),w)
pygame.draw.circle(gameDisplay, ic,(x+w,y+w),w,3)
smallText = pygame.font.SysFont("swiss721",14)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w)), (y+(w)) )
gameDisplay.blit(textSurf, textRect)
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed')
gameExit = False
def quitgame():
gameExit = True
pygame.quit()
quit()
def button_pressed():
print('click')
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_offset = 0
y_offset = 180
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('',artnetPort))
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.draw.rect(gameDisplay, button_color,(0,0,1024,768), 4)
button("EXIT",16*60+x_offset,10,50,50,red,bright_red,quitgame)
# (data, addr) = sock.recvfrom(10240)
# if len(data) < 20:
# sdata = data.decode("utf-8")
# if sdata == "quit":
# print("exit program")
# break
# print (data)
# continue
# universe = int(data[9])
# protverhi = int(data[10])
# protverlo = int(data[11])
# sequence = int(data[12])
# physical = int(data[13])
# subuni = int(data[14])
# net = int(data[15])
# lengthhi = int(data[16])
# length = int(data[17])
# #dmx = data[18:]
# offset = subuni * 170
# col = pygame.Color(0,0,0)
# w = 5
# if( net == 0):
# for i in range(0,170):
# x = int((i + offset) % 240)
# y = int((i + offset) / 240)
# col.r = data[i*3 +18]
# col.g = data[i*3 +19]
# col.b = data[i*3 +20]
# # pygame.gfxdraw.pixel(screen, x, y,col )
# pygame.draw.circle(gameDisplay, col,(x+w,y+w),w)
pygame.display.update()
clock.tick(15)
game_loop()
pygame.quit()
quit()<file_sep>/hy_test.py
import pybullet as p
import time
import math
p.connect(p.GUI)
# p.resetDebugVisualizerCamera( cameraDistance=10, cameraYaw=90, cameraPitch=-80, cameraTargetPosition=[0,20,25]) # look on a1
# p.resetDebugVisualizerCamera( cameraDistance=50, cameraYaw=45, cameraPitch=-60, cameraTargetPosition=[0,-20,25])
p.resetDebugVisualizerCamera( cameraDistance=50, cameraYaw=45, cameraPitch=-60, cameraTargetPosition=[0,-45,25])
from hyperlights.hyperlights import Hyperlights
from hyperlights.hyperlights import HlMaiskoblen
from hyperlights.hyperlights import HlStarCore
from hyperlights.hyperlights import HlStarLight
from hyperlights.hyperlights import Hl_A1
from hyperlights.hyperlights import HlGrid
from hyperlights.hyperlights import HlPPPanel
from hyperlights.collider import Collider
planeId = p.loadURDF("plane.urdf", useMaximalCoordinates=False)
# col = p.loadURDF("cube_collisionfilter.urdf", [0, 3, 3], useMaximalCoordinates=False)
# col = p.loadURDF("coll_full.urdf", [0, 0, 15], useMaximalCoordinates=False)
collider1 = Collider()
collider1.z = 15
collider1.create(p,"coll_full.urdf")
# col2 = p.loadURDF("colCube.urdf", [0, 3, 3], useMaximalCoordinates=False)
# einheit dm = 0.1m??
# maiskolben_1 = HlMaiskoblen()
# maiskolben_1.x = 15
# maiskolben_1.y = -51.5
# maiskolben_1.z = 25
# maiskolben_1.create(p)
# maiskolben_2 = HlMaiskoblen()
# maiskolben_2.x = 15
# maiskolben_2.y = -38.5
# maiskolben_2.z = 25
# maiskolben_2.create(p)
# maiskolben_3 = HlMaiskoblen()
# maiskolben_3.x = 15
# maiskolben_3.y = -25.5
# maiskolben_3.z = 25
# maiskolben_3.create(p)
# maiskolben_4 = HlMaiskoblen()
# maiskolben_4.x = 15
# maiskolben_4.y = -12.5
# maiskolben_4.z = 25
# maiskolben_4.create(p)
# maiskolben_5 = HlMaiskoblen()
# maiskolben_5.x = 15
# maiskolben_5.y = 0.5
# maiskolben_5.z = 25
# maiskolben_5.create(p)
# PPPanel_1 = HlPPPanel()
# PPPanel_1.x = -10
# PPPanel_1.y = -60
# PPPanel_1.z = 25
# PPPanel_1.create(p)
# PPPanel_2 = HlPPPanel()
# PPPanel_2.x = 10
# PPPanel_2.y = -60
# PPPanel_2.z = 25
# PPPanel_2.create(p)
Grid = HlGrid()
Grid.x = -20
Grid.y = 0
Grid.z = 25
Grid.create(p)
A1struct = Hl_A1()
A1struct.x = 0
A1struct.y = 20
A1struct.z = 25
A1struct.create(p)
starCoreLight = HlStarLight()
starCoreLight.x = 0
starCoreLight.y = -45
starCoreLight.z = 25
starCoreRed = HlStarCore()
starCoreRed.x = 15
starCoreRed.y = 45
starCoreRed.z = 25
starCoreBlue = HlStarCore()
starCoreBlue.x = -15
starCoreBlue.y = 45
starCoreBlue.z = 25
starCoreLight.create(p)
starCoreRed.create(p)
starCoreBlue.create(p)
collisionFilterGroup = 0
collisionFilterMask = 0
# p.setCollisionFilterGroupMask(col, -1, collisionFilterGroup, collisionFilterMask)
# p.setCollisionFilterGroupMask(col2, -1, collisionFilterGroup, collisionFilterMask)
collisionFilterGroup = 0
collisionFilterMask = 0
enableCollision = 1
# p.setCollisionFilterPair(planeId, col, -1, -1, enableCollision)
# p.setCollisionFilterPair(planeId, col2, -1, -1, enableCollision)
p.setRealTimeSimulation(1)
# p.setGravity(0, 0, -10)
# a = 0
# b = 0
# orn = p.getQuaternionFromEuler([0, 0, 0])
# pivot = [0, 0, 10]
# cid = p.createConstraint(col, -1, -1, -1, p.JOINT_FIXED, [0, 0, 0], [0, 0, 0], [0, 0, 1])
# p.changeConstraint(cid, pivot, jointChildFrameOrientation=orn, maxForce=500)
# cid2 = p.createConstraint(col2, -1, -1, -1, p.JOINT_FIXED, [0, 0, 0], [0, 0, 0], [0, 0, 0])
while (p.isConnected()):
time.sleep(1. / 240.)
# maiskolben_1.doCollisionFilter(p,col2)
# print(maiskolben_1.hit)
# starCoreRed.doCollisionFilter(p,col2)
# print(starCoreRed.hit)
# trigger
# a = a + 0.2
# pivot = [0, a, 15]
# if (a > 80):
# a = -80
# # cid.btTransform([0, 0, -1])
# # resetBasePositionAndOrientation
# p.resetBasePositionAndOrientation(cid, [0, -80, 15], orn)
# # p.changeConstraint(cid, pivot, jointChildFrameOrientation=orn, maxForce=5000)
# p.changeConstraint(cid, pivot, jointChildFrameOrientation=orn, maxForce=500)
collider1.simulate(p)
# b = b + 0.02
# pivot = [0, 0, 5.5]
# orn2 = p.getQuaternionFromEuler([0, 0, b])
# p.changeConstraint(cid2, pivot, jointChildFrameOrientation=orn2, maxForce=50)
p.stepSimulation()
# p.setGravity(0, 0, -10)
<file_sep>/hyperlights/hyperlights.py
import pybullet
import math
import os
import numpy as np
import socket
from threading import Lock, Thread
#this script contains all the lights
class Hyperlights :
def __init__(self):
self.dirpath = os.getcwd() + "\\data\\"
# print(self.dirpath)
self.hit = []
self.pixel = []
self.pixelNum = 0
self.pixelMap = []
self.pixelOffset = 0
self.numJoints = 0
self.x = 0
self.y = 0
self.z = 0
self.orn = [0,0,0]
self.colSize = 0.1
# Color
self.enable = True
self.Master = 1.0
self.onColor_r = 255
self.onColor_g = 255
self.onColor_b = 255
self.offColor_r = 0
self.offColor_g = 0
self.offColor_b = 0
# Artnet part
self.update = True
self.artnetSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.ip = "127.0.0.1"
self.universe = 0
self.artnetPort = 6454
self.artnetData = []
self.artnetData2 = []
self.bIsSimplified = True
self.TARGET_IP = self.ip
self.SEQUENCE = 0
self.PHYSICAL = 0
self.UNIVERSE = self.universe
self.SUB = 0
self.NET = 0
self.PACKET_SIZE = 512
self.HEADER = bytearray()
self.BUFFER = bytearray(self.PACKET_SIZE)
for i in range(512):
self.artnetData.append(0)
self.artnetData2.append(0)
self.make_header()
def doCollisionFilter(self, p, obj):
i = 0
if self.enable:
for px in self.pixel:
# check for subpixel
subPixelCount = p.getNumJoints(px)
if subPixelCount > 0:
for j in range(0, subPixelCount):
resSub = p.getClosestPoints(obj.col, px,self.colSize, -1, j)
if resSub:
self.hit[i] = 1
else:
self.hit[i] = 0
i += 1
else:
res = p.getClosestPoints(obj.col, px, self.colSize )
# body = p.getBodyUniqueId(px)
if i >= self.pixelNum:
break
hit = 0
if res:
hit = 1
self.hit[i] = hit
i += 1
self.update = True
def sendData(self):
if self.enable:
if self.update:
self.make_header()
self.createArtnet()
# self.artnetSocket.sendto(bytes(self.packet), (self.ip, self.artnetPort))
# print("artnet to %s, uni %i" % (self.ip, self.universe))
# artnetSocket.sendto(bytes(self.packet), (self.ip, self.artnetPort))
##
# UTILS
##
@staticmethod
def shift_this(number, high_first=True):
# """Utility method: extracts MSB and LSB from number.
# Args:
# number - number to shift
# high_first - MSB or LSB first (true / false)
# Returns:
# (high, low) - tuple with shifted values
# """
low = (number & 0xFF)
high = ((number >> 8) & 0xFF)
if (high_first):
return((high, low))
else:
return((low, high))
print("Something went wrong")
return False
def make_header(self, uni=0):
# """Make packet header."""
# 0 - id (7 x bytes + Null)
self.HEADER = bytearray()
self.HEADER.extend(bytearray('Art-Net', 'utf8'))
self.HEADER.append(0x0)
# 8 - opcode (2 x 8 low byte first)
self.HEADER.append(0x00)
self.HEADER.append(0x50) # ArtDmx data packet
# 10 - prototocol version (2 x 8 high byte first)
self.HEADER.append(0x0)
self.HEADER.append(14)
# 12 - sequence (int 8), NULL for not implemented
self.HEADER.append(self.SEQUENCE)
# 13 - physical port (int 8)
self.HEADER.append(0x00)
# 14 - universe, (2 x 8 low byte first)
# self.HEADER.append(self.universe)
# self.HEADER.append(0)
if (self.bIsSimplified):
# not quite correct but good enough for most cases:
# the whole net subnet is simplified
# by transforming a single uint16 into its 8 bit parts
# you will most likely not see any differences in small networks
v = self.shift_this(self.universe + uni) # convert to MSB / LSB
# print(self.ip)
# print(self.universe)
# print(v)
self.HEADER.append(v[1])
self.HEADER.append(v[0])
# 14 - universe, subnet (2 x 4 bits each)
# 15 - net (7 bit value)
else:
# as specified in Artnet 4 (remember to set the value manually after):
# Bit 3 - 0 = Universe (1-16)
# Bit 7 - 4 = Subnet (1-16)
# Bit 14 - 8 = Net (1-128)
# Bit 15 = 0
# this means 16 * 16 * 128 = 32768 universes per port
# a subnet is a group of 16 Universes
# 16 subnets will make a net, there are 128 of them
self.HEADER.append(self.SUB << 4 | self.universe)
self.HEADER.append(self.NET & 0xFF)
# 16 - packet size (2 x 8 high byte first)
v = self.shift_this(self.PACKET_SIZE) # convert to MSB / LSB
self.HEADER.append(v[0])
self.HEADER.append(v[1])
def createArtnet(self):
i = self.pixelOffset
# lock = Lock()
# lock.acquire() # will block if lock is already held
# ... access shared resource
extended = False
# currently limited to 2 x 170 leds per light
for res in self.hit:
if i < 510:
if res == 1:
self.artnetData[i] = self.onColor_r
self.artnetData[i+1] = self.onColor_g
self.artnetData[i+2] = self.onColor_b
else:
self.artnetData[i] = self.offColor_r
self.artnetData[i+1] = self.offColor_g
self.artnetData[i+2] = self.offColor_b
i = i+3
elif i < 1020:
extended = True
# nasty hack for 2 universes per light
# need better way to do this
if res == 1:
self.artnetData2[i-510] = self.onColor_r
self.artnetData2[i+1-510] = self.onColor_g
self.artnetData2[i+2-510] = self.onColor_b
else:
self.artnetData2[i-510] = self.offColor_r
self.artnetData2[i+1-510] = self.offColor_g
self.artnetData2[i+2-510] = self.offColor_b
i = i+3
self.update = False
# lock.release()
self.packet = bytearray()
self.packet.extend(self.HEADER)
self.packet.extend(self.artnetData)
self.artnetSocket.sendto(bytes(self.packet), (self.ip, self.artnetPort))
if extended:
self.packet2 = bytearray()
self.packet2.extend(self.HEADER)
self.packet2.extend(self.artnetData2)
v = self.shift_this(self.universe + 1) # convert to MSB / LSB
self.packet2[14] = v[1]
self.packet2[15] = v[0]
self.artnetSocket.sendto(bytes(self.packet2), (self.ip, self.artnetPort))
def addPixel(self, p, model, pos, orn):
self.pixelNum += 1
pixel_1 = p.loadURDF(model, pos, orn, useMaximalCoordinates=False)
self.pixel.append(pixel_1)
# print("pixelID %d" % pixel_1)
def setCollisionFilterMask(self,p, enableCollision):
collisionFilterGroup = 0
collisionFilterMask = 0
for px in self.pixel:
p.setCollisionFilterGroupMask(px, -1, collisionFilterGroup, collisionFilterMask)
# p.setCollisionFilterPair(obj, px, -1, -1, enableCollision)
def fillHit(self, p):
# have to be called on init to fill the buffer
j = 0
for px in self.pixel:
self.numJoints = p.getNumJoints(px)
# print("numJoints %i " % (px.numJoints))
# print("add hit px:%d" % px)
# body = p.getBodyUniqueId(px)
# pixelMap.append(body)
if p.getNumJoints(px) > 0:
self.pixelNum += p.getNumJoints(px)+1
for i in range(0, p.getNumJoints(px)+1):
self.hit.append(i)
# n = p.getJointInfo(px,i)
# print("led %i , joint %s" % (i, n[1])) # extract name?
else:
self.hit.append(px)
self.setCollisionFilterMask(p,0)
print("pixnum: %d pixel: %d, hit:%d" % (self.pixelNum, len(self.pixel), len(self.hit)))
def create(self, p):
self.addPixel(p,self.dirpath + "pixel.urdf,", [self.x, self.y, self.z], [0,0,0,0])
self.fillHit(p)
class HlGrid (Hyperlights):
def create (self, p):
self.make_header()
d = math.pi/4
orn = p.getQuaternionFromEuler([d, 0, math.pi/2])
_x = self.x
_y = self.y
_z = self.z
dx = 9.0
dz = -3.0
self.addPixel(p,self.dirpath + "tristar_48g.urdf", [_x, _y, _z], orn)
orn = p.getQuaternionFromEuler([math.pi/2, 0, math.pi/2])
i = -1
self.addPixel(p,self.dirpath + "tristar_48g.urdf", [i * dx + _x, _y, dz + _z], orn)
i = -2
self.addPixel(p,self.dirpath + "tristar_48g.urdf", [i * dx + _x, _y, dz + _z], orn)
self.fillHit(p)
class HlGridR (Hyperlights):
def create (self, p):
self.make_header()
d = math.pi/4
orn = p.getQuaternionFromEuler([d, 0, math.pi/2])
_x = self.x
_y = self.y
_z = self.z
dx = -3.0
self.addPixel(p,self.dirpath + "tristar_48g.urdf", [_x, _y, _z], orn)
orn = p.getQuaternionFromEuler([0, 0, 0])
dz = -8.0
self.addPixel(p,self.dirpath + "tristar_48g.urdf", [dx + _x, _y, dz + _z], orn)
dz = -16.5
self.addPixel(p,self.dirpath + "tristar_48g.urdf", [dx + _x, _y, dz + _z], orn)
self.fillHit(p)
class HlWheel (Hyperlights):
def setRotation(self, p, angle):
_x = self.x
_y = self.y
_z = self.z
d = math.pi/2
self.orn = p.getQuaternionFromEuler([0,angle,d])
p.resetBasePositionAndOrientation(self.pixel[0], [_x, _y, _z ], self.orn)
def enableMotor(self, en):
if en == True:
self.enMotor = 1
else:
self.enMotor = 0
self.sendMotor()
def setMotor1Speed(self, speed):
self.speedMotor1 = speed
self.sendMotor()
def setMotor1Dir(self, dir):
if dir == True:
self.dirMotor1 = 1
else:
self.dirMotor1 = 0
self.sendMotor()
def sendMotor(self):
packet = bytearray()
packet.extend(self.HEADER)
v = self.shift_this(2)
packet[14] = v[1]
packet[15] = v[0]
packet.append(self.enMotor) # enalbe Motor
packet.append(self.speedMotor1) # Motor 1 speed
packet.append(self.speedMotor2) # Motor 2 speed
packet.append(self.dirMotor1 ) # Motor 1 dir
packet.append(self.dirMotor2 ) # Motor 2 dir
# print("motor Control")
# print(packet)
self.artnetSocket.sendto(bytes(packet), (self.ip, self.artnetPort))
def create (self, p):
self.enMotor = 0
self.speedMotor1 = 0
self.speedMotor2 = 0
self.dirMotor1 = 0
self.dirMotor2 = 0
self.make_header()
d = math.pi/2
self.orn = p.getQuaternionFromEuler([0, 0, d])
_x = self.x
_y = self.y
_z = self.z
self.addPixel(p,self.dirpath + "hlWheel.urdf", [_x, _y, _z], self.orn)
self.fillHit(p)
class Hl_A1 (Hyperlights):
def create (self, p):
self.ip = "192.168.2.73"
self.universe = 0
self.make_header()
self.pxiel = []
d = 0
orn = p.getQuaternionFromEuler([d, 0, 0])
_x = self.x
_y = self.y
_z = self.z
dx = 0.75
dy = 0.75
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-1 * dx + _x, 1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 1 * dx + _x, 1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-1 * dx + _x,-1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 1 * dx + _x,-1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-2 * dx + _x,-2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 2 * dx + _x, 0.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-2 * dx + _x, 2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 0 * dx + _x, 2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 2 * dx + _x, 2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-2 * dx + _x, 0.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 2 * dx + _x, -2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 0 * dx + _x,-2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-3 * dx + _x,-3.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-3 * dx + _x,-1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-3 * dx + _x, 1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-3 * dx + _x, 3.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-1 * dx + _x, 3.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-1 * dx + _x, -3.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 3 * dx + _x, 3.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 3 * dx + _x, 1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 3 * dx + _x,-1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 3 * dx + _x,-3.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [1 * dx + _x, 3.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [1 * dx + _x, -3.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 4 * dx + _x, 2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 4 * dx + _x, 0.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 4 * dx + _x,-2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 5 * dx + _x, 1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 5 * dx + _x,-1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ 6 * dx + _x, 0.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ -4 * dx + _x, 2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ -4 * dx + _x, 0.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ -4 * dx + _x,-2.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ -5 * dx + _x, 1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ -5 * dx + _x,-1.0 * dy + _y, _z], orn)
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [ -6 * dx + _x, 0.0 * dy + _y, _z], orn)
self.fillHit(p)
class HlPPPanel (Hyperlights):
def create (self, p):
self.ip = "192.168.2.80"
self.make_header()
self.pxiel = []
orn = [0,0,0,1]
d = 0.4
for i in range( -8 , 8):
h = (-i) * d + self.z
for j in range(-8,8 ):
self.addPixel(p,self.dirpath + "pixel.urdf", [j * d + self.x, self.y, h], orn)
self.fillHit(p)
class HlMaiskoblen (Hyperlights):
def create (self, p):
self.ip = "192.168.2.80"
self.pxiel = []
self.make_header()
for i in range(10):
h = (-i) * 0.4 + self.z + 4
orn = [0,0,0,1]
self.addPixel(p,self.dirpath + "pixel.urdf", [0.52263 + self.x, 0 +self.y, h], orn)
self.addPixel(p,self.dirpath + "pixel.urdf", [-0.52263+ self.x, 0 + self.y, h], orn)
self.addPixel(p,self.dirpath + "pixel.urdf", [0 + self.x, 0.52263 + self.y, h], orn)
self.addPixel(p,self.dirpath + "pixel.urdf", [0 + self.x, -0.52263+ self.y, h], orn)
self.addPixel(p,self.dirpath + "pixel.urdf", [0.36995 + self.x, 0.36995 + self.y, h], orn)
self.addPixel(p,self.dirpath + "pixel.urdf", [-0.36995+ self.x, -0.36995+ self.y, h], orn)
self.addPixel(p,self.dirpath + "pixel.urdf", [0.36995 + self.x, -0.36995+ self.y, h], orn)
self.addPixel(p,self.dirpath + "pixel.urdf", [-0.36995+ self.x, 0.36995 + self.y, h], orn)
self.fillHit(p)
class HlStarCore (Hyperlights):
def create (self, p):
self.make_header()
self.pixelOffset = 1
self.pxiel = []
h = self.z
# White Core
self.addPixel(p,self.dirpath + "pixel.urdf", [self.x, self.y, h], [0,0,0,1])
# RGB
offset = 2
d = math.pi / 2
rot = math.pi
sx = math.sin(math.pi/3) * offset
sy = math.cos(math.pi/3) * offset
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core.urdf", [self.x, offset + self.y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core.urdf", [sx + self.x, sy + self.y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core.urdf", [-sx + self.x, sy + self.y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core.urdf", [self.x, -offset + self.y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core.urdf", [-sx + self.x, -sy + self.y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core.urdf", [sx + self.x, -sy + self.y, h], orn)
self.fillHit(p)
class HlStarLight (Hyperlights):
def create (self, p):
self.make_header()
self.pixelOffset = 7
self.pxiel = []
h = self.z
_x = self.x
_y = self.y
offset = 1.25
d = math.pi / 2
rot = math.pi
sx = math.sin(math.pi/3) * offset
sy = math.cos(math.pi/3) * offset
# White Core 0 - center
self.addPixel(p,self.dirpath + "pixel.urdf", [_x, _y, h], [0,0,0,1] )
# RGB
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, offset + _y, h], orn )
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, sy + _y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, sy + _y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, -offset + _y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, -sy + _y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, -sy + _y, h], orn)
_x = self.x + 0
_y = self.y + 4
# White Core 1
self.addPixel(p,self.dirpath + "pixel.urdf", [_x, _y, h], [0,0,0,1] )
# RGB
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, offset + _y, h], orn )
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, sy + _y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, sy + _y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, -offset + _y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, -sy + _y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, -sy + _y, h], orn)
_x = self.x + math.sin(math.pi/3) * 4
_y = self.y + 2
# White Core center
self.addPixel(p,self.dirpath + "pixel.urdf", [_x, _y, h], [0,0,0,1] )
# RGB
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, offset + _y, h], orn )
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, sy + _y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, sy + _y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, -offset + _y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, -sy + _y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, -sy + _y, h], orn)
_x = self.x + math.sin(math.pi/3) * 4
_y = self.y - 2
# White Core 1
self.addPixel(p,self.dirpath + "pixel.urdf", [_x, _y, h], [0,0,0,1] )
# RGB
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, offset + _y, h], orn )
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, sy + _y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, sy + _y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, -offset + _y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, -sy + _y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, -sy + _y, h], orn)
_x = self.x + math.sin(math.pi/3) * 4
_y = self.y - 2
# White Core 2
self.addPixel(p,self.dirpath + "pixel.urdf", [_x, _y, h], [0,0,0,1] )
# RGB
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, offset + _y, h], orn )
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, sy + _y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, sy + _y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, -offset + _y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, -sy + _y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, -sy + _y, h], orn)
_x = self.x + math.sin(math.pi/3) * 4
_y = self.y - 2
# White Core 3
self.addPixel(p,self.dirpath + "pixel.urdf", [_x, _y, h], [0,0,0,1] )
# RGB
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, offset + _y, h], orn )
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, sy + _y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, sy + _y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, -offset + _y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, -sy + _y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, -sy + _y, h], orn)
_x = self.x
_y = self.y - 4
# White Core 4
self.addPixel(p,self.dirpath + "pixel.urdf", [_x, _y, h], [0,0,0,1] )
# RGB
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, offset + _y, h], orn )
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, sy + _y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, sy + _y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, -offset + _y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, -sy + _y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, -sy + _y, h], orn)
_x = self.x - math.sin(math.pi/3) * 4
_y = self.y + 2
# White Core 6
self.addPixel(p,self.dirpath + "pixel.urdf", [_x, _y, h], [0,0,0,1] )
# RGB
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, offset + _y, h], orn )
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, sy + _y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, sy + _y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, -offset + _y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, -sy + _y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, -sy + _y, h], orn)
_x = self.x - math.sin(math.pi/3) * 4
_y = self.y - 2
# White Core 7
self.addPixel(p,self.dirpath + "pixel.urdf", [_x, _y, h], [0,0,0,1] )
# RGB
orn = p.getQuaternionFromEuler([d, 0, 0])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, offset + _y, h], orn )
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, sy + _y, h], orn)
rot = math.pi /3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, sy + _y, h], orn)
rot = math.pi
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [_x, -offset + _y, h], orn)
rot = math.pi / -3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [-sx + _x, -sy + _y, h], orn)
rot = math.pi / 3
orn = p.getQuaternionFromEuler([d, 0, rot])
self.addPixel(p,self.dirpath + "pixel_core_s.urdf", [sx + _x, -sy + _y, h], orn)
self.fillHit(p)
<file_sep>/hyperlights/inputMidi.py
import pybullet
import math
import socket
import os
import threading
import numpy as np
import socket , pickle
import json
import time
from hyperlights.comm import inputData
# this is the midi input thread
class inputMidi:
def __init__(self):
self.port = 50505
self.ip = "127.0.0.1"
self.input_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self._lights = lambda: None
self._collider = lambda: None
self.alive = 0
self.running = True
def inputDataLoop(self):
# data_variable = inputData()
while (self.running == True):
self.input_sock.settimeout(5.0)
try:
(data, addr) = self.input_sock.recvfrom(10240)
# print(data)
# data_string = data.decode("utf-8")
data_variable = pickle.loads(data)
# data_variable = pickle.loads(data.decode("utf-8"))
# data_variable = json.loads(data)
# print(data_variable)
# print(str(data_variable.inpID))
# except:
# print("something went wrong")
# self.alive += 1
if data_variable.devID == 0:
self.alive = 0
if data_variable.inpID == 0:
if data_variable.inpVal != 0:
self._collider[0].enabled = True
# print("enable collider 0")
else:
self._collider[0].enabled = False
# print("disable collider 0")
if data_variable.inpID == 12:
speed = float(data_variable.inpVal) / (12.70 * 3.0 )
# print("collider 0 speed %f" % speed)
self._collider[0].setSpeed(speed,speed,speed)
if data_variable.inpID == 1:
if data_variable.inpVal != 0:
self._collider[1].enabled = True
# print("enable collider 1")
else:
self._collider[1].enabled = False
# print("disable collider 1")
if data_variable.inpID == 13:
speed = float(data_variable.inpVal) / (12.70 * 3.0 )
# print("collider 0 speed %f" % speed)
self._collider[1].setSpeed(speed,speed,speed)
if data_variable.devID == 1:
self.alive = 0
if data_variable.inpID == 0:
if data_variable.inpVal != 0:
self._lights[0].enableMotor(True)
else:
self._lights[0].enableMotor(False)
if data_variable.inpID == 1:
if data_variable.inpVal != 0:
self._lights[0].setMotor1Dir(True)
else:
self._lights[0].setMotor1Dir(False)
if data_variable.inpID == 12:
speed = int(data_variable.inpVal) * 2
self._lights[0].setMotor1Speed(speed)
except Exception as e:
# print.error(traceback.format_exc())
if str(e) != "timed out":
print(e)
self.alive += 1
if self.alive > 10:
self.running = False
# time.sleep(0.015)
print("end input thread")
def startInput(self, lights, collider):
self._lights = lights
self._collider = collider
# self.input_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.input_sock.bind(('',self.port))
# start_new_thread(self.sendData, ())
x = threading.Thread(target=self.inputDataLoop )
x.start()
print("starting input Thread")
def endInput(self):
if self.running:
self.running = False
packet = ""
self.input_sock.sendto(bytes(packet, 'utf-8'), (self.ip, self.port))
|
81534758087c3a03b504e3bae727c905c1dd6086
|
[
"Markdown",
"Python"
] | 21 |
Python
|
4ndreas/HyperLightControl
|
33eeb3e94f80a3af8e6cf2329121ef63ba74bab1
|
a7e6c501dcfd424d877bc2813c7f0db9070e0b97
|
refs/heads/master
|
<file_sep># automate /unfinished
A Windows automation engine handing out automation power to Lua scripts.
## Features
* Lua scripting
* Read process' memory
* Sends key strokes and mouse actions **even when the window is minimized**!
## Example
```
findWindow("Chrome", 3)
leftClick(20, 20)
```
Switches to the first tab of your Chrome window.
## Functions
### findProcess(name, cmpType)
Finds a process by name, sets it as default and returns it's handle.
*cmpType* defines how to match a process or window name:
* 0 - equals
* 1 - starts with
* 2 - ends with
* 3 - contains
### findProcess([w])
Finds the process of the window *w* or the default window, sets the process as default
and returns it's handle.
### findWindow(name, cmpType)
Finds a window by name, sets it as default and returns it's handle.
### read([p,] address, what)
Reads a value of type *what* from the process *p* or the default process at *address*.
*what* is a string argument that sets the type to be read:
* **i** - int, a signed 4 byte integer
* **I** - uint, an unsigned 4 byte integer
* **h** - short, a signed 2 byte integer
* **H** - ushort, an unsigned 2 byte integer
* **l** - long, a signed 8 byte integer
* **L** - long, an unsigned 8 byte integer
* **b** - unsigned byte
* **c** - char, a signed byte
* **s:n** - a string of **n** length
### typewrite([w,] text)
Sends *text* to the window *w* or the default window.
### keyDown([w,] keyCode)
Sends a key down action at the given key to the window *w* or the default window.
### keyUp([w,] keyCode)
Sends a key up action at the given key to the window *w* or the default window.
### leftClick([w,] x, y)
Sends a left click at *x*/*y* to the window *w* or the default window.
### rightClick([w,] x, y)
Sends a right click at *x*/*y* to the window *w* or the default window.
## Key Codes
* rbutton
* cancel
* mbutton
* back
* tab
* clear
* return
* shift
* control
* menu
* pause
* capital
* kana
* hangeul
* hangul
* junja
* final
* hanja
* kanji
* escape
* convert
* nonconvert
* accept
* modechange
* space
* prior
* next
* end
* home
* left
* up
* right
* down
* select
* print
* execute
* snapshot
* insert
* delete
* help
* lwin
* rwin
* apps
* sleep
* numpad0
* numpad1
* numpad2
* numpad3
* numpad4
* numpad5
* numpad6
* numpad7
* numpad8
* numpad9
* multiply
* add
* separator
* subtract
* decimal
* divide
* f1
* f2
* f3
* f4
* f5
* f6
* f7
* f8
* f9
* f10
* f11
* f12
* f13
* f14
* f15
* f16
* f17
* f18
* f19
* f20
* f21
* f22
* f23
* f24
* numlock
* scroll
* lshift
* rshift
* lcontrol
* rcontrol
* lmenu
* rmenu
* oem_1
* oem_2
* oem_3
* oem_4
* oem_5
* oem_6
* oem_7
* oem_8
* processkey
* attn
* crsel
* exsel
* ereof
* play
* zoom
* noname
* pa1
* oem_clear
* 0
* 1
* 2
* 3
* 4
* 5
* 6
* 7
* 8
* 9
<file_sep>#include <iostream>
#include <lua.hpp>
#include <string>
#include <windows.h>
#include <psapi.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>
#include <map>
#include <boost/assign.hpp>
#include "Shlwapi.h"
using namespace std;
using namespace boost::assign;
map<string, int> keyCodes = map_list_of("lbutton", VK_LBUTTON)
("rbutton", VK_RBUTTON)
("cancel", VK_CANCEL)
("mbutton", VK_MBUTTON)
("back", VK_BACK)
("tab", VK_TAB)
("clear", VK_CLEAR)
("return", VK_RETURN)
("shift", VK_SHIFT)
("control", VK_CONTROL)
("menu", VK_MENU)
("pause", VK_PAUSE)
("capital", VK_CAPITAL)
("kana", VK_KANA)
("hangeul", VK_HANGEUL)
("hangul", VK_HANGUL)
("junja", VK_JUNJA)
("final", VK_FINAL)
("hanja", VK_HANJA)
("kanji", VK_KANJI)
("escape", VK_ESCAPE)
("convert", VK_CONVERT)
("nonconvert", VK_NONCONVERT)
("accept", VK_ACCEPT)
("modechange", VK_MODECHANGE)
("space", VK_SPACE)
("prior", VK_PRIOR)
("next", VK_NEXT)
("end", VK_END)
("home", VK_HOME)
("left", VK_LEFT)
("up", VK_UP)
("right", VK_RIGHT)
("down", VK_DOWN)
("select", VK_SELECT)
("print", VK_PRINT)
("execute", VK_EXECUTE)
("snapshot", VK_SNAPSHOT)
("insert", VK_INSERT)
("delete", VK_DELETE)
("help", VK_HELP)
("lwin", VK_LWIN)
("rwin", VK_RWIN)
("apps", VK_APPS)
("sleep", VK_SLEEP)
("numpad0", VK_NUMPAD0)
("numpad1", VK_NUMPAD1)
("numpad2", VK_NUMPAD2)
("numpad3", VK_NUMPAD3)
("numpad4", VK_NUMPAD4)
("numpad5", VK_NUMPAD5)
("numpad6", VK_NUMPAD6)
("numpad7", VK_NUMPAD7)
("numpad8", VK_NUMPAD8)
("numpad9", VK_NUMPAD9)
("multiply", VK_MULTIPLY)
("add", VK_ADD)
("separator", VK_SEPARATOR)
("subtract", VK_SUBTRACT)
("decimal", VK_DECIMAL)
("divide", VK_DIVIDE)
("f1", VK_F1)
("f2", VK_F2)
("f3", VK_F3)
("f4", VK_F4)
("f5", VK_F5)
("f6", VK_F6)
("f7", VK_F7)
("f8", VK_F8)
("f9", VK_F9)
("f10", VK_F10)
("f11", VK_F11)
("f12", VK_F12)
("f13", VK_F13)
("f14", VK_F14)
("f15", VK_F15)
("f16", VK_F16)
("f17", VK_F17)
("f18", VK_F18)
("f19", VK_F19)
("f20", VK_F20)
("f21", VK_F21)
("f22", VK_F22)
("f23", VK_F23)
("f24", VK_F24)
("numlock", VK_NUMLOCK)
("scroll", VK_SCROLL)
("lshift", VK_LSHIFT)
("rshift", VK_RSHIFT)
("lcontrol", VK_LCONTROL)
("rcontrol", VK_RCONTROL)
("lmenu", VK_LMENU)
("rmenu", VK_RMENU)
("oem_1", VK_OEM_1)
("oem_2", VK_OEM_2)
("oem_3", VK_OEM_3)
("oem_4", VK_OEM_4)
("oem_5", VK_OEM_5)
("oem_6", VK_OEM_6)
("oem_7", VK_OEM_7)
("oem_8", VK_OEM_8)
("processkey", VK_PROCESSKEY)
("attn", VK_ATTN)
("crsel", VK_CRSEL)
("exsel", VK_EXSEL)
("ereof", VK_EREOF)
("play", VK_PLAY)
("zoom", VK_ZOOM)
("noname", VK_NONAME)
("pa1", VK_PA1)
("oem_clear", VK_OEM_CLEAR)
("0", 0x30)
("1", 0x31)
("2", 0x32)
("3", 0x33)
("4", 0x34)
("5", 0x35)
("6", 0x36)
("7", 0x37)
("8", 0x38)
("9", 0x39);
int parseKey(string text) {
std::transform(text.begin(), text.end(), text.begin(), ::tolower);
return keyCodes[text];
}
bool compare(string s1, string s2, int type) {
return (type == 0 && boost::equals(s1, s2)) ||
(type == 1 && boost::starts_with(s1, s2)) ||
(type == 2 && boost::ends_with(s1, s2)) ||
(type == 3 && boost::contains(s1, s2));
}
HANDLE getProcessHandle(string name, int cmptype) {
DWORD procs[1024];
EnumProcesses(procs, sizeof(procs), NULL);
for(int i = 0; i < sizeof(procs); i++) {
HANDLE h = OpenProcess(PROCESS_VM_READ, false, procs[i]);
char n[1024];
GetModuleBaseName(h, NULL, n, sizeof(n));
if(compare(n, name, cmptype)) {
return h;
}
CloseHandle(h);
}
return NULL;
}
const char* checkWindow_title;
int checkWindow_cmptype;
HWND checkWindow_result;
BOOL CALLBACK checkWindow(HWND h, LPARAM lParam) {
char title[1024];
GetWindowText(h, title, sizeof(title));
if(compare(title, checkWindow_title, checkWindow_cmptype)) {
checkWindow_result = h;
return false;
}
return true;
}
HWND getWindowHandle(string title, int cmptype) {
checkWindow_title = title.c_str();
checkWindow_cmptype = cmptype;
EnumWindows(checkWindow, 0);
return checkWindow_result;
}
int setLuaPath( lua_State* L, const char* path )
{
lua_getglobal( L, "package" );
lua_getfield( L, -1, "path" ); // get field "path" from table at top of stack (-1)
std::string cur_path = lua_tostring( L, -1 ); // grab path string from top of stack
cur_path.append( ";" ); // do your path magic here
cur_path.append( path );
lua_pop( L, 1 ); // get rid of the string on the stack we just pushed on line 5
lua_pushstring( L, cur_path.c_str() ); // push the new one
lua_setfield( L, -2, "path" ); // set the field "path" in table at -2 with value at top of stack
lua_pop( L, 1 ); // get rid of package table from top of stack
return 0; // all done!
}
class Engine {
public:
static HANDLE defaultHandle;
static HWND defaultHwnd;
static bool defaultHandleDecided, defaultHwndDecided;
static int findProcess(lua_State *L) {
HANDLE h;
if(lua_isstring(L, 1)) {
string name = lua_tostring(L, 1);
int cmptype = lua_tonumber(L, 2);
h = getProcessHandle(name, cmptype);
} else {
HWND hwnd = defaultHwnd;
if(lua_isuserdata(L, 1)) {
hwnd = (HWND)lua_touserdata(L, 1);
}
DWORD pid;
GetWindowThreadProcessId(hwnd, &pid);
h = OpenProcess(0x1F0FFF, false, pid);
}
lua_pushlightuserdata(L, h);
if(!defaultHandleDecided) {
defaultHandle = h;
}
return 1;
}
static int findWindow(lua_State *L) {
string title = lua_tostring(L, 1);
int cmptype = lua_tonumber(L, 2);
HWND h = getWindowHandle(title, cmptype);
lua_pushlightuserdata(L, h);
if(!defaultHwndDecided) {
defaultHwnd = h;
}
return 1;
}
static int typewrite(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
string text = lua_tostring(L, ++n);
for(int i = 0; i < text.length(); i++) {
PostMessage(h, WM_CHAR, text[i], 0);
}
return 0;
}
static int keyDown(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
const char* key = lua_tostring(L, ++n);
PostMessage(h, WM_KEYDOWN, parseKey(key), 0);
return 0;
}
static int keyUp(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
const char* key = lua_tostring(L, ++n);
PostMessage(h, WM_KEYUP, parseKey(key), 0);
return 0;
}
static int keyPress(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
const char* key = lua_tostring(L, ++n);
int code = parseKey(key);
PostMessage(h, WM_KEYDOWN, code, 0);
PostMessage(h, WM_KEYUP, code, 0);
return 0;
}
static int rightClick(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
POINT p;
if(lua_gettop(L) == n + 2) {
p.x = lua_tonumber(L, ++n);
p.y = lua_tonumber(L, ++n);
} else {
GetCursorPos(&p);
}
LPARAM lParam = MAKELPARAM(p.x, p.y);
PostMessage(h, WM_RBUTTONDOWN, MK_RBUTTON, lParam);
PostMessage(h, WM_RBUTTONUP, MK_RBUTTON, lParam);
return 0;
}
static int leftClick(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
POINT p;
if(lua_gettop(L) == n + 2) {
p.x = lua_tonumber(L, ++n);
p.y = lua_tonumber(L, ++n);
} else {
GetCursorPos(&p);
}
LPARAM lParam = MAKELPARAM(p.x, p.y);
PostMessage(h, WM_LBUTTONDOWN, MK_LBUTTON, lParam);
PostMessage(h, WM_LBUTTONUP, MK_LBUTTON, lParam);
return 0;
}
static int move(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
LPARAM lParam = MAKELPARAM(lua_tonumber(L, ++n), lua_tonumber(L, ++n));
PostMessage(h, WM_MOUSEMOVE, 0, lParam);
return 0;
}
static int leftDown(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
POINT p;
if(lua_gettop(L) == n + 2) {
p.x = lua_tonumber(L, ++n);
p.y = lua_tonumber(L, ++n);
} else {
GetCursorPos(&p);
}
LPARAM lParam = MAKELPARAM(p.x, p.y);
PostMessage(h, WM_LBUTTONDOWN, MK_LBUTTON, lParam);
return 0;
}
static int leftUp(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
POINT p;
if(lua_gettop(L) == n + 2) {
p.x = lua_tonumber(L, ++n);
p.y = lua_tonumber(L, ++n);
} else {
GetCursorPos(&p);
}
LPARAM lParam = MAKELPARAM(p.x, p.y);
PostMessage(h, WM_LBUTTONUP, MK_LBUTTON, lParam);
return 0;
}
static int rightDown(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
POINT p;
if(lua_gettop(L) == n + 2) {
p.x = lua_tonumber(L, ++n);
p.y = lua_tonumber(L, ++n);
} else {
GetCursorPos(&p);
}
LPARAM lParam = MAKELPARAM(p.x, p.y);
PostMessage(h, WM_RBUTTONDOWN, MK_RBUTTON, lParam);
return 0;
}
static int rightUp(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
POINT p;
if(lua_gettop(L) == n + 2) {
p.x = lua_tonumber(L, ++n);
p.y = lua_tonumber(L, ++n);
} else {
GetCursorPos(&p);
}
LPARAM lParam = MAKELPARAM(p.x, p.y);
PostMessage(h, WM_RBUTTONUP, MK_RBUTTON, lParam);
return 0;
}
static int drag(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
int fx = lua_tonumber(L, ++n),
fy = lua_tonumber(L, ++n),
tx = lua_tonumber(L, ++n),
ty = lua_tonumber(L, ++n);
int delay = 50;
if(lua_gettop(L) == n + 1) {
delay = lua_tonumber(L, ++n);
}
LPARAM lParam = MAKELPARAM(fx, fy);
PostMessage(h, WM_LBUTTONDOWN, MK_LBUTTON, lParam);
Sleep(delay);
POINT p;
GetCursorPos(&p);
SetCursorPos(p.x + 1, p.y);
Sleep(delay);
SetCursorPos(p.x, p.y);
lParam = MAKELPARAM(tx, ty);
PostMessage(h, WM_LBUTTONUP, MK_LBUTTON, lParam);
return 0;
}
static int read(lua_State *L) {
int n = 0;
HANDLE h = defaultHandle;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
int address = lua_tonumber(L, ++n);
string what = lua_tostring(L, ++n);
int count;
char lowerWhat = tolower(what[0]);
if(lowerWhat == 's') {
count = atoi(what.substr(2).c_str());
} else if(lowerWhat == 'i') {
count = 4;
} else if(lowerWhat == 'h') {
count = 2;
} else if(lowerWhat == 'l') {
count = 8;
} else {
count = 1;
}
byte buffer[count];
ReadProcessMemory(h, (LPVOID)address, (LPVOID)&buffer, count, NULL);
if(what[0] == 's') {
lua_pushstring(L, (char*)buffer);
} else if(what == "i") {
lua_pushnumber(L, *(int*)&buffer);
} else if(what == "I") {
lua_pushnumber(L, *(unsigned int*)&buffer);
} else if(what == "h") {
lua_pushnumber(L, *(short*)&buffer);
} else if(what == "H") {
lua_pushnumber(L, *(unsigned short*)&buffer);
} else if(what == "l") {
lua_pushnumber(L, *(int64_t*)&buffer);
} else if(what == "L") {
lua_pushnumber(L, *(uint64_t*)&buffer);
} else if(what == "b") {
lua_pushboolean(L, buffer[0]);
} else if (what == "c") {
lua_pushnumber(L, (char)buffer[0]);
} else {
lua_pushnumber(L, buffer[0]);
}
return 1;
}
static int write(lua_State *L) {
return 0;
}
static int wait(lua_State *L) {
int ms = lua_tonumber(L, 1);
Sleep(ms);
return 0;
}
static int include(lua_State *L) {
const char* filename = lua_tostring(L, 1);
char* path = strdup(filename);
PathRemoveFileSpec(path);
setLuaPath(L, (string(path) + string("\\?.lua")).c_str());
if(fopen(filename,"r")==0) {
filename = (string(filename) + ".lua").c_str();
}
luaL_dofile(L, filename);
return 0;
}
static int windowSize(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
RECT rect;
if(GetWindowRect(h, &rect))
{
int width = rect.right - rect.left;
int height = rect.bottom - rect.top;
lua_pushnumber(L, width);
lua_pushnumber(L, height);
return 2;
}
return 0;
}
static int isDown(lua_State *L) {
const char* key = lua_tostring(L, 1);
int state = GetKeyState(parseKey(key));
lua_pushboolean(L, (state < 0));
return 1;
}
static int focus(lua_State *L) {
int n = 0;
HWND h = defaultHwnd;
if(lua_isuserdata(L, 1)) {
h = (HWND)lua_touserdata(L, ++n);
}
PostMessage(h, WM_SETFOCUS, 0, 0);
return 0;
}
};
HANDLE Engine::defaultHandle;
HWND Engine::defaultHwnd;
bool Engine::defaultHandleDecided;
bool Engine::defaultHwndDecided;
bool executeScript(char* path, int argc, char* argv[]) {
lua_State *L = lua_open();
luaL_openlibs(L);
// Assigning functions:
lua_register(L, "findProcess", Engine::findProcess);
lua_register(L, "findWindow", Engine::findWindow);
lua_register(L, "read", Engine::read);
lua_register(L, "write", Engine::write);
lua_register(L, "wait", Engine::wait);
lua_register(L, "typewrite", Engine::typewrite);
lua_register(L, "keyDown", Engine::keyDown);
lua_register(L, "keyUp", Engine::keyUp);
lua_register(L, "keyPress", Engine::keyPress);
lua_register(L, "leftClick", Engine::leftClick);
lua_register(L, "rightClick", Engine::rightClick);
lua_register(L, "leftDown", Engine::leftDown);
lua_register(L, "leftUp", Engine::leftUp);
lua_register(L, "move", Engine::move);
lua_register(L, "drag", Engine::drag);
lua_register(L, "windowSize", Engine::windowSize);
lua_register(L, "include", Engine::include);
lua_register(L, "isDown", Engine::isDown);
lua_register(L, "focus", Engine::focus);
// Assigning variables:
lua_newtable(L);
for(int i = 0; i < argc; i++) {
lua_pushnumber(L, i + 1);
lua_pushstring(L, argv[i]);
lua_rawset(L, -3);
}
lua_setglobal(L, "args");
luaL_dofile(L, path);
if(lua_isstring(L, 1)) {
cerr << lua_tostring(L, 1) << endl;
}
return true;
}
int main(int argc, char* argv[]) {
const char* filename = argv[1];
if(fopen(filename,"r")==0) {
filename = (string(filename) + ".lua").c_str();
}
executeScript((char*)filename, argc, argv);
return 0;
}
|
613f8136e24ea655ae86cd7b39b8dfd840643224
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
zippoxer/automate
|
25ad45c53548660b8ee4f39006510b4cdfe02f58
|
f5abb0a598323f7ce1c4e2e8e31cbea04904ded0
|
refs/heads/master
|
<file_sep>package asteroids.fundamentals.blend;
import java.awt.CompositeContext;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
/**
*
* @author nilsg
*/
class MultiplyBlendingContext implements CompositeContext
{
@Override
public void compose(Raster src, Raster dstIn, WritableRaster dstOut)
{
int w = Math.min(src.getWidth(), dstIn.getWidth());
int h = Math.min(src.getHeight(), dstIn.getHeight());
int srcMinX = src.getMinX();
int srcMinY = src.getMinY();
int dstInMinX = dstIn.getMinX();
int dstInMinY = dstIn.getMinY();
int dstOutMinX = dstOut.getMinX();
int dstOutMinY = dstOut.getMinY();
int[] srcRgba = new int[4];
int[] dstRgba = new int[4];
for (int x = 0; x < w; x++)
{
for (int y = 0; y < h; y++)
{
src.getPixel(x + srcMinX, y + srcMinY, srcRgba);
dstIn.getPixel(x + dstInMinX, y + dstInMinY, dstRgba);
for (int i = 0; i < 3; i++)
{
dstRgba[i]= Math.min(dstRgba[i] *= srcRgba[i], 255);
}
dstOut.setPixel(x + dstOutMinX, y + dstOutMinY, dstRgba);
}
}
}
@Override
public void dispose()
{
}
}
<file_sep>package asteroids.sound;
public final class Sound
{
byte[][] wavData;
float pitchVariance;
boolean loop;
public Sound(byte[][] wavData, float p, boolean l)
{
this.wavData = wavData;
this.pitchVariance = p;
this.loop = l;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.state;
import asteroids.fundamentals.Input;
import java.awt.Color;
import java.awt.Graphics2D;
/**
*
* @author Raildex
*/
public class StateMachine
{
private final Input i;
public State currentState;
public StateMachine(Input i)
{
this.i = i;
}
public void setState(State e)
{
e.initState(i);
currentState = e;
}
public State getState(){
return currentState;
}
public void render(Graphics2D g)
{
currentState.render(g);
}
public void update(double delta)
{
currentState.update(delta);
}
}
<file_sep>package asteroids.object;
import asteroids.Asteroids;
import asteroids.camera.Camera;
import asteroids.state.ArcadeState;
import asteroids.state.State;
import java.awt.Graphics2D;
/**
*
* @author Raildex
*/
public abstract class GameObject
{
public double x;
public double y;
public float rotation;
public int width;
public int height;
public char faction;
public boolean destroyMe = false;
public GameObject(double x, double y,float rotation,int width, int height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.rotation = rotation;
this.faction = 'N';
}
abstract public void update(double delta);
abstract public void render(Graphics2D g, Camera c);
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.fundamentals;
/**
* Interface für die Gemeinsamkeiten der Kollisionsklassen (Box und Circle)
* @author Yannic
*/
public interface Collision {
public void setCoordinates(double x, double y);
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.object;
import asteroids.object.bullet.Bullet;
import asteroids.object.bullet.FireBullet;
import asteroids.object.bullet.Rocket;
import asteroids.object.sprite.Sprite;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
*
* @author Raildex
*/
public abstract class Weapon
{
/**
* Test Weapon
*/
public static Weapon testWeapon = new Weapon(0, 2)
{
@Override
public void setLevel(int level)
{
try
{
this.spray = true;
this.bullet = new FireBullet(new Sprite(ImageIO.read(this.getClass().
getResource("/gfx/bullets.png")).getSubimage(4, 42, 4,
11)), true, 2, 51, 0, 0, 8, 22);
this.bullet = new Rocket(new Sprite(ImageIO.read(this.getClass().
getResource("/gfx/bullets.png")).getSubimage(134, 42, 9,
14)), true, 2, 200, 0, 0, 32, 48,null);
this.doubleSide = true;
this.numBullets = 1;
this.interval = 20;
this.fireSound = "Laser_Shoot";
this.inaccuracy= 2f;
}
catch (IOException ex)
{
Logger.getLogger(Weapon.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
/**
* Level of the Weapon
*/
public int level;
/**
* Cost (Shop?) per Level Upgrade
*/
public final int costPerLevel;
/**
* Shotgun styled Spray
*/
public boolean spray;
/**
* Shots into the Direction the ship is heading and 180°
*/
public boolean doubleSide;
/**
* The number of Bullets shot when fired
*/
public byte numBullets;
/**
* The Power Consumption per shot per Level
*/
public int powerPerLevel;
/**
* Damage dealt per Level
*/
public final int damagePerLevel;
/**
* The Bullet to be fired
*/
public Bullet bullet;
/**
* The amount of time until the weapon can be fired again
*/
public int interval;
/**
* timer for shooting again
*/
public double fireTimer;
/**
* The Sound file to be played when the weapon is fired
*/
public String fireSound;
/**
* The amount of inaccuracy
*/
public float inaccuracy;
public Weapon(int costPerLevel, int damagePerLevel)
{
this.costPerLevel = costPerLevel;
this.damagePerLevel = damagePerLevel;
setLevel(0);
}
public abstract void setLevel(int level);
void update(double delta)
{
this.fireTimer += delta;
if (fireTimer >= interval)
{
fireTimer = interval;
}
}
public static enum Type
{
FRONT, REAR, LEFT, RIGHT
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.object.particle;
import asteroids.camera.Camera;
import asteroids.fundamentals.Image;
import asteroids.object.GameObject;
import java.awt.Graphics2D;
import java.util.ArrayList;
/**
*
* @author nilsg
*/
public class ParticleEmitter extends GameObject
{
private final float sprayAngle;
private final int particleAmount;
private final float random;
private final Image particleSprite;
ArrayList<Particle> particles;
private final int maxParticles;
private int sizeOfParticles;
private final int rate;
private final float speedOfParticles;
private int timer;
private final int particleLife;
public ParticleEmitter(double x, double y, float rotation, int width,
int height, int maxParticles, int rate, float speedOfParticles,
float sprayAngle, int particleAmount, int particleLife, float random,
Image particleSprite)
{
super(x, y, rotation, width, height);
particles = new ArrayList<>(maxParticles);
this.maxParticles = maxParticles;
this.rate = rate;
this.speedOfParticles = speedOfParticles;
this.sprayAngle = sprayAngle;
this.particleAmount = particleAmount;
this.particleLife = particleLife;
this.random = random;
this.particleSprite = particleSprite;
}
@Override
public void update(double delta)
{
timer++;
if (timer >= rate)
{
emitt();
timer = 0;
}
}
@Override
public void render(Graphics2D g, Camera c)
{
}
private void emitt()
{
for (int i = 0; i < particleAmount; i++)
{
if (particles.size() >= this.maxParticles)
{
Particle p = new Particle(
(-width / 2 + Math.random() * width + this.x),
(-height / 2 + Math.random() * height + this.y), 0,
sizeOfParticles, sizeOfParticles, null,
(int) (particleLife + Math.random() * random),
particleSprite);
}
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.background;
import asteroids.camera.Camera;
import asteroids.fundamentals.Updateable;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.ArrayList;
/**
*
* @author nilsg
*/
public class StarBackground extends Background implements Updateable
{
private final int maxStars;
private final Color starColor;
final int starSize;
final float starSpeed;
ArrayList<Star> stars;
public StarBackground(int maxStars, Color starColor, int starSize,
float starSpeed)
{
this.maxStars = maxStars;
this.starColor = starColor;
stars = new ArrayList<>();
this.starSize = starSize;
this.starSpeed = starSpeed;
}
@Override
public void render(Graphics2D g, Camera c)
{
g.setColor(Color.BLACK);
g.fillRect(0, 0, 1280, 720);
for (int i = 0; i < stars.size(); i++)
{
Star s = stars.get(i);
int alpha;
if (s.time <= 0.5f)
{
alpha =(int) ((s.time * 2f)*255);
}else
{
alpha =(int) ((1f-(s.time-0.5f)*2)*255);
}
Color starColor = new Color(this.starColor.getRed(),
this.starColor.getGreen(),
this.starColor.getBlue(), (int) (alpha));
g.setColor(starColor);
g.fillOval((int) s.x - s.size / 2,
(int) s.y - s.size / 2,
s.size, s.size);
}
}
@Override
public void update(double delta)
{
int x = (int) (Math.random() * 1280);
int y = (int) (Math.random() * 720);
if (stars.size() < maxStars)
{
float dx = (float) (-starSpeed / 2 + Math.random() * starSpeed);
float dy = (float) (-starSpeed / 2 + Math.random() * starSpeed);
stars.add(new Star(x, y, (float) Math.random(), dx, dy,(int)(this.starSize*Math.random())));
}
for (int i = 0; i < stars.size(); i++)
{
stars.get(i).update(delta);
if (stars.get(i).time >= 1)
{
stars.remove(i);
}
}
}
private static class Star implements Updateable
{
float x;
float y;
final float speed;
final float dx;
final float dy;
final int size;
public Star(int x, int y, float speed, float dx, float dy,int size)
{
this.x = x;
this.y = y;
this.speed = speed;
this.dx = dx;
this.dy = dy;
this.size=size;
}
float time;
@Override
public void update(double delta)
{
this.x += dx;
this.y += dy;
time += 0.01 * speed * delta;
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.state;
import asteroids.fundamentals.Input;
import java.awt.Graphics2D;
/**
*
* @author Raildex
*/
public abstract interface State
{
/**
* Renders the State
* @param g the Back Buffer
*/
public void render(Graphics2D g);
/**
* Updates the State
* @param delta the interpolation delta Time
*/
public void update(double delta);
/**
* Inits the State
* @param i
* @return
*/
public boolean initState(Input i);
/**
* Cleans up memory when removing the state
* @return
*/
public boolean exitState();
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.object;
import asteroids.fundamentals.Updateable;
/**
*
* @author nilsg
*/
public class ShipGenerator implements Updateable
{
String generatorName;
final float powerReplenish;
float power;
final int maxPower;
public ShipGenerator(String name,float powerReplenish, int maxPower)
{
this.generatorName = name;
this.powerReplenish = powerReplenish;
this.maxPower = maxPower;
}
@Override
public void update(double delta)
{
power+= powerReplenish*delta;
}
@Override
public String toString()
{
return "Ship Generator["+generatorName+" @ "+maxPower+" Power Units ]";
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.object.bullet;
import asteroids.fundamentals.Image;
import asteroids.object.bullet.Bullet.BulletType;
/**
*
* @author Raildex
*/
public class BulletEvent
{
/**
* Event Type for The Bullet when Colliding with an enemy
*/
public static final int COLLIDING_ENEMY = 1;
/**
* Event Type for the Bullet when Colliding with the Player
*/
public static final int COLLIDING_PLAYER = 10;
/**
* Event Type for the Bullet when fired
*/
public static final int BULLET_FIRED = 100;
/**
* Event Type for the Bullet when a certain Time is passed
*/
public static final int BULLET_TIMER = 1000;
/**
* Event Type for the Bullet when the Bullet dies
*/
public static final int BULLET_DIED = 10000;
/**
* The Event Type
*/
public int type;
/**
* The Bullet Type
*/
public BulletType t;
public Image bulletImage;
/**
* The X where the Event is called
*/
public double x;
/**
* The Y where the Event is called
*/
public double y;
/**
* The Rotation of the Event caller
*/
public float rot;
public BulletEvent(BulletType bulletType, double x, double y, float rot,
int type,Image bulletImage)
{
this.rot = rot;
this.t = bulletType;
this.type = type;
this.x = x;
this.y = y;
this.bulletImage = bulletImage;
}
}
<file_sep>package asteroids.fundamentals;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
*
* @author nilsg
*/
public class Input implements KeyListener
{
public final int LEFT = KeyEvent.VK_A;
public final int RIGHT = KeyEvent.VK_D;
public final int UP = KeyEvent.VK_W;
public final int DOWN = KeyEvent.VK_S;
public final int SPACE = KeyEvent.VK_SPACE;
public final int LEFT2 = KeyEvent.VK_LEFT;
public final int RIGHT2 = KeyEvent.VK_RIGHT;
public final int UP2 = KeyEvent.VK_UP;
public final int DOWN2 = KeyEvent.VK_DOWN;
public boolean leftDown;
public boolean rightDown;
public boolean upDown;
public boolean downDown;
public boolean actionDown;
public boolean jumpDown;
public boolean abortDown;
public boolean spaceDown;
@Override
public void keyTyped(KeyEvent e)
{
}
@Override
public void keyPressed(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_CONTROL:
actionDown = true;
break;
case KeyEvent.VK_ALT:
jumpDown = true;
break;
case KeyEvent.VK_ESCAPE:
abortDown = true;
break;
case KeyEvent.VK_ENTER:
actionDown = true;
break;
case LEFT:
leftDown = true;
break;
case RIGHT:
rightDown = true;
break;
case DOWN:
downDown = true;
break;
case UP:
upDown = true;
break;
case LEFT2:
leftDown = true;
break;
case RIGHT2:
rightDown = true;
break;
case DOWN2:
downDown = true;
break;
case UP2:
upDown = true;
break;
case SPACE:
spaceDown = true;
break;
}
}
@Override
public void keyReleased(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_CONTROL:
actionDown = false;
break;
case KeyEvent.VK_ALT:
jumpDown = false;
break;
case KeyEvent.VK_ESCAPE:
abortDown = false;
break;
case KeyEvent.VK_ENTER:
actionDown = false;
break;
case LEFT:
leftDown = false;
break;
case RIGHT:
rightDown = false;
break;
case DOWN:
downDown = false;
break;
case UP:
upDown = false;
break;
case LEFT2:
leftDown = false;
break;
case RIGHT2:
rightDown = false;
break;
case DOWN2:
downDown = false;
break;
case UP2:
upDown = false;
break;
case SPACE:
spaceDown = false;
break;
}
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.object;
import asteroids.fundamentals.Image;
import java.util.HashMap;
/**
*
* @author nilsg
*/
public abstract class Ship extends GameObject
{
protected final Image img;
protected ShipGenerator eng;
protected double accel;
protected final double maxAccel;
protected final double maxVelocity;
protected double dx;
protected double dy;
protected HashMap<Weapon.Type,Weapon> weapons;
public Ship(double x, double y, double maxAccel, double maxVel, float rot,
int w, int h, Image img)
{
super(x, y, rot, w, h);
this.maxAccel = maxAccel;
this.maxVelocity = maxVel;
this.img = img;
weapons = new HashMap<>();
}
@Override
public void update(double delta)
{
img.update(delta);
eng.update(delta);
if (dx >= maxVelocity)
{
dx = maxVelocity;
} else if (dx <= -maxVelocity)
{
dx = -maxVelocity;
}
if (dy >= maxVelocity)
{
dy = maxVelocity;
} else if (dy <= -maxVelocity)
{
dy = -maxVelocity;
}
x += dx * delta;
y += dy * delta;
for(Weapon w : weapons.values())
{
w.update(delta);
}
}
public final void setGenerator(ShipGenerator generator)
{
this.eng = generator;
}
public final void setWeapon(Weapon.Type t,Weapon w)
{
this.weapons.put(t, w);
}
abstract public void fire(Weapon w);
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.fundamentals;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
/**
*Umsetzung von Kollision als Kreis um ein Objekt. Kollisionserkennung durch Überprüfung der folgenden Bedingung:
* Radius(a)+Radius(b) kleiner geometrischer Abstand (Satz des Pythagoras) = Kollision (Die Kreise schneiden sich)
* Diese Überprüfung wird über die checkCollision-Methode durchgefuehrt, welche in der Arcade-State aufgerufen wird.
* @author Yannic
*/
public class CollisionCircle implements Collision{
public double x;
public double y;
public double radius;
private double add = 0.002;
private double cur = 1;
Color[] colors = new Color[6];
public CollisionCircle(double x, double y, double radius){
setCoordinates(x, y);
setRadius(radius);
for(int i = 0;i<colors.length;i++){
colors[i] = new Color((float)Math.random(),(float)Math.random(),(float)Math.random());
}
}
@Override
public void setCoordinates(double x, double y) {
this. x = x;
this.y = y;
}
public void render(Graphics g){
g.setColor(new Color((float)Math.random(),(float)Math.random(),(float)Math.random()));
g.setColor(Color.ORANGE);
//double r = Math.random()*radius*10; Quatsch
if(cur >= 7)cur = 1;
cur += add;
g.drawOval((int)(x-cur*radius),(int)( y-cur*radius),(int) (cur*radius*2),(int) (cur*radius*2));
/*for(int i = 1;i<3;i++){
if(cur>=i){
g.drawOval((int)(x-(cur-i+1)*radius),(int)( y-(cur-i+1)*radius),(int) ((cur-i+1)*radius*2),(int) ((cur-i+1)*radius*2));
}else{
g.drawOval((int)(x-(10-i+1+cur)*radius),(int)( y-(10-i+1+cur)*radius),(int) ((10-i+1+cur)*radius*2),(int) ((10-i+1+cur)*radius*2));
}
}*/
for(int i = 1;i<7;i++){
g.setColor(colors[i-1]);
if(cur>=i){
//g.drawOval((int)(x-(cur-i+1)*radius),(int)( y-(cur-i+1)*radius),(int) ((cur-i+1)*radius*2),(int) ((cur-i+1)*radius*2));
g.drawOval((int)(x-(cur-i+1)*Math.random()*radius),(int)( y-(cur-i+1)*Math.random()*radius),(int) ((cur-i+1)*radius*2),(int) ((cur-i+1)*radius*2));
}else{
g.drawOval((int)(x-(7-i+cur)*Math.random()*radius),(int)( y-(7-i+cur)*Math.random()*radius),(int) ((7-i+cur)*radius*2),(int) ((7-i+cur)*radius*2));
}
}
}
public void setRadius(double r){
radius = r;
}
/**
*
* @param c <b>Collidable</b>-Objekt, gegen das die Kollision geprüft wird.
* @return Gibt <b>true</b> zurück, falls es zu einer Kollision kommt, und <b>false</b>, falls nicht.
*/
public boolean checkCollision(CollisionCircle c){
double xDist = Math.abs(c.x-x);
double yDist = Math.abs(c.y-y);
if(Math.sqrt(xDist*xDist+yDist*yDist)<(c.radius+radius)){
System.out.println("My coordinates: "+x+ " "+y);
System.out.println("c coordinates: "+c.x+ " "+c.y);
System.out.println("xDistance: "+xDist);
System.out.println("yDistance: "+yDist);
System.out.println("Geometric Distance: "+Math.sqrt(xDist*xDist+yDist*yDist));
System.out.println("RadiusSum: "+(c.radius+radius));
return true;
}
return false;
}
}
<file_sep>package asteroids.fundamentals;
import java.awt.Color;
/**
* A Class representing Colours in the HSV Color Model.
*
* @author Raildex
* @see https://de.wikipedia.org/wiki/HSV-Farbraum
* @version 1.0
*/
public final class ColorHSV
{
/**
* Constructs a black HSV Color
*/
public ColorHSV()
{
this.hue = 360;
this.saturation = 1;
this.value = 1;
}
/**
* Hue Value, between 0 and 360 degrees
*/
private float hue;
/**
* Saturation, between 0f and 1f
*/
private float saturation;
/**
* Value, between 0f and 1f
*/
private float value;
/**
* Constructs a new Color in the HSV Color Model, based on a AWT Color
*
* @param rgb the Color to be converted
*/
public ColorHSV(Color rgb)
{
this(rgb.getRed() / 255f, rgb.getGreen() / 255f, rgb.getBlue() / 255f);
}
/**
* Constructs a new HSV Color
*
* @param hue
* @param saturation
* @param value
*/
public ColorHSV(double hue, double saturation, double value)
{
this.hue = (float) hue;
this.saturation = (float) saturation;
this.value = (float) value;
}
/**
* Constructs a new Color in the HSV Color Model based on separate R,G and B
* Values between 0 and 255
*
* @param r Red Component between 0 and 255
* @param g Green Component between 0 and 255
* @param b Blue Component between 0 and 255
*/
public ColorHSV(int r, int g, int b)
{
this(r / 255f, g / 255f, b / 255f);
}
public ColorHSV(float hue, float saturation, float value)
{
this.hue = hue;
this.saturation = saturation;
this.value = value;
}
@Override
public String toString()
{
return this.getClass().getName() + "[Hue= " + hue + "°, Saturation= " + saturation + ", Value= " + value + "]";
}
@Override
public boolean equals(Object o)
{
return (o instanceof ColorHSV) && (((ColorHSV) o).hue == this.hue && ((ColorHSV) o).value == this.value && ((ColorHSV) o).saturation == this.saturation);
}
@Override
public int hashCode()
{
return (int) (getSaturation() + getValue() * 255 + getHue() * 255);
}
/**
* @return the hue
*/
public float getHue()
{
return hue;
}
public void setHue(float hue)
{
this.hue = hue;
}
/**
* @return the saturation
*/
public float getSaturation()
{
return saturation;
}
public void setSaturation(float saturation)
{
this.saturation = saturation;
}
/**
* @return the value
*/
public float getValue()
{
return value;
}
public void setValue(float value)
{
this.value = value;
}
/**
* Converts the Color in HSV space into a color in RGB Space
*
* @return the HSV Color in RGB Space,
*/
public Color toRGB()
{
int h = (int) Math.floor(hue / 60);
float f = (hue / 60) - h;
float p = value * (1 - saturation);
float q = value * (1 - saturation * f);
float t = value * (1 - saturation * (1 - f));
if (h == 0 || h == 6)
{
return new Color(value, t, p);
}
else if (h == 1)
{
return new Color(q, value, p);
}
else if (h == 2)
{
return new Color(p, value, t);
}
else if (h == 3)
{
return new Color(p, q, value);
}
else if (h == 4)
{
return new Color(t, p, value);
}
else if (h == 5)
{
return new Color(value, p, q);
}
else
{
return new Color(value, t, p);
}
}
}
<file_sep># Asteroids
Asteroids - Projektarbeit HsH
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.object;
import asteroids.camera.Camera;
import asteroids.fundamentals.CollisionBox;
import asteroids.fundamentals.CollisionCircle;
import asteroids.fundamentals.Image;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
* Statisches Testobjekt mit Kollisionsbox zum Test vom Spielfunktionen (Aktuelle Grafik: Asteroid)
* @author Yannic
*/
public class StaticObject extends GameObject implements Collidable{
Image img;
public boolean collided = false;
CollisionBox c;
CollisionCircle cc;
double dx = 0;
double dy = 0;
public StaticObject(double x, double y, Image img){
super(x,y,0,img.getImage().getWidth(null),img.getImage().getHeight(null));
this.img = img;
cc = new CollisionCircle(x,y,Math.max(img.getImage().getWidth(null), img.getImage().getHeight(null))/2);
}
@Override
public void update(double delta) {
}
@Override
public void render(Graphics2D g, Camera c) {
if(!collided){
AffineTransform save = g.getTransform();
g.rotate(Math.toRadians(this.rotation), x, y);
g.drawImage(img.getImage(), (int) (-c.x + x - img.getImage().getWidth(
null) / 2),
(int) (-c.y + y - img.getImage().getHeight(null) / 2), null);
g.setTransform(save);
g.setColor(Color.red);
g.drawOval((int)(cc.x-img.getImage().getWidth(null)/2),(int) (cc.y - img.getImage().getHeight(null) / 2),(int) cc.radius*2,(int) cc.radius*2);
}
}
@Override
public void collided(Collidable c) {
collided = true;
destroyMe = true; //s. GameObject-Klasse
}
@Override
public boolean collisionAvailable() {
return !collided;
}
@Override
public String toString(){
return "StaticObject";
}
@Override
public CollisionCircle getCollisionCircle() {
return cc;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.state;
import asteroids.fundamentals.Input;
import asteroids.object.GameObject;
import java.awt.Graphics2D;
import java.util.ArrayList;
/**
*
* @author nilsg
*/
public class StoryState implements State
{
ArrayList<GameObject> objects;
public StoryState()
{
objects = new ArrayList<GameObject>();
}
@Override
public void render(Graphics2D g)
{
for(int i = 0; i < objects.size();i++)
{
GameObject o = objects.get(i);
}
}
@Override
public void update(double delta)
{
}
@Override
public boolean initState(Input i)
{
return true;
}
@Override
public boolean exitState()
{
return true;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.object;
import asteroids.Asteroids;
import asteroids.camera.Camera;
import asteroids.fundamentals.CollisionBox;
import asteroids.fundamentals.CollisionCircle;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
/**
* Klasse für grundlegende Bullet-Objekte mit einer Kollision, einer Lebenszeit-Spanne, einer Grafik, Schaden, Position, Rotation und Geschwindigkeit.
* @author nilsg
*/
public class Bullet extends GameObject implements Collidable
{
final BufferedImage bulletImage;
public final boolean playerBullet;
final int damage;
double lifeTime;
final int maxLifetime;
double dx;
double dy;
public boolean travel = false;
float initialRot;
double initialx;
double initialy;
PlayerShip p;
public boolean collided;
CollisionBox c;
CollisionCircle cc;
long creationTime;
public Bullet(BufferedImage bulletImage, boolean playerBullet, int damage,
int maxLifetime, double x, double y,double dx, double dy,float rot, char faction)
{
super(x, y,rot,bulletImage.getWidth(),bulletImage.getWidth());
this.faction = faction;
this.bulletImage = bulletImage;
this.playerBullet = playerBullet;
this.damage = damage;
this.maxLifetime = maxLifetime;
this.dx = dx;
this.dy = dy;
initialRot = rot;
initialx = x;
initialy = y;
creationTime = System.currentTimeMillis();
this.p = p;
c = new CollisionBox(x-bulletImage.getWidth()/2,y-bulletImage.getHeight()/2,bulletImage.getWidth(null),bulletImage.getHeight(null));
cc = new CollisionCircle(x,y,Math.max(bulletImage.getWidth(null), bulletImage.getHeight(null))/2);
}
@Override
public void update(double delta)
{
if (!collided /*&& lifeTime<600*/) {
lifeTime++;
//rotation += 5*delta;
//rotation %= 360;
if (travel) {
//dx+= 0.005;
//dy+= 0.005;
x += dx * Math.sin(Math.toRadians(rotation)) * delta;
y -= dy * Math.cos(Math.toRadians(rotation)) * delta;
Dimension d = Asteroids.getInstance().getDimensions();
if (x < 0) {
x += d.width;
} else if (x > d.width) {
x -= d.width;
}
if (y < 0) {
y += d.height;
} else if (y > d.height) {
y -= d.height;
}
c.setCoordinates(x-bulletImage.getWidth()/2,y-bulletImage.getHeight()/2);
cc.setCoordinates(x, y);
}
}
}
@Override
public void render(Graphics2D g, Camera c)
{
if(!collided){
AffineTransform save = g.getTransform();
g.rotate(Math.toRadians(this.rotation), x, y);
g.drawImage(bulletImage , (int) (-c.x + x - bulletImage.getWidth(
null) / 2),
(int) (-c.y + y - bulletImage.getHeight(null) / 2), null);
g.setTransform(save);
g.setColor(Color.green);
g.drawOval((int)(cc.x - cc.radius ), (int)(cc.y - cc.radius), (int)this.cc.radius*2,(int) this.cc.radius*2);
}
}
@Override
public void collided(Collidable c) {
collided = true;
destroyMe = true;
}
@Override
public boolean collisionAvailable() {
return !collided;
}
@Override
public CollisionCircle getCollisionCircle() {
return cc;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package asteroids.object;
import asteroids.fundamentals.CollisionCircle;
/**
* Allgemeines Interface für Dinge mit Kollision, sei es eine Kollisionsbox oder ein Kollisionskreis.<br>
*
* <b>Wird eventuell durch AWT.shape und dessen intersect Methode ersetzt!</b>
* @author Yannic
*
*/
public interface Collidable {
public CollisionCircle getCollisionCircle();
/**
*
* @param c Das Objekt, mit dem das Objekt kollidiert.
* Wird aufgerufen, wenn in der Arcade-State eine Kollision zweier Objekte passender Fraktion festgestellt wurde. Dient zur Umsetzung der Konsequenzen der Kollision.
*/
public void collided(Collidable c);
/**
* Abfrage-Funktion zur Verfügbarkeit der Kollision dieses Objekts. Wird von der Kollisionsabfrage in der Arcade-State berücksichtigt.
* @return Gibt zurück, ob das Objekt derzeit mit anderen Objekten kollidieren kann.
*/
public boolean collisionAvailable();
}
|
cf155c2051a5992020d4e5fb8b1caeaebc80cf23
|
[
"Markdown",
"Java"
] | 20 |
Java
|
Raildex/Asteroids
|
27bef35942122886bc0fef54b744351c194105db
|
e0c1f8df14d9b494a308815e8010249a446595ee
|
refs/heads/master
|
<file_sep>import axios from 'axios';
import * as types from 'src/store/ducks/wp-api/types';
import * as actions from 'src/store/ducks/wp-api/actions';
/**
* WordPress REST API middleware.
*/
const middleware = store => next => (action) => {
switch (action.type) {
/**
* FETCH - retrieve SPA/homepage relevant posts.
*/
case types.FETCH: {
axios
.get('wp-json/posts/1')
.then(response => {
store.dispatch(actions.contentFetched(response.data));
})
.catch(error => {
console.error('Request failed', error);
});
break;
}
default:
}
next(action);
};
export default middleware;
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import Post from './Post';
const Posts = ({
posts,
}) => {
return posts.map(post => <Post key={post.ID} {...post} />);
};
Posts.propTypes = {
posts: PropTypes.arrayOf(PropTypes.shape({
ID: PropTypes.number.isRequired,
})).isRequired,
};
export default Posts;
<file_sep>version: '3'
services:
wordpress:
image: visiblevc/wordpress
# required for mounting bindfs
cap_add:
- SYS_ADMIN
devices:
- /dev/fuse
ports:
- 8080:80
- 443:443
volumes:
- ./app:/app
- ./data:/data
- ./theme-virgo-coop:/app/wp-content/themes/virgo-coop
environment:
DB_NAME: wordpress
DB_PASS: <PASSWORD>
PLUGINS: >-
[wp-graphql]https://github.com/wp-graphql/wp-graphql/archive/v0.0.29.zip
db:
image: mariadb:10 # or mysql:5.7
volumes:
- data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: <PASSWORD>
phpmyadmin:
image: phpmyadmin/phpmyadmin
ports:
- 22222:80
volumes:
data:
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
const Post = ({
ID,
title,
content,
}) => (
<div className="virgo-post">
<p>{ID}</p>
<p>{title}</p>
<p dangerouslySetInnerHTML={{__html: content}} />
</div>
);
Post.propTypes = {
ID: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
content: PropTypes.string.isRequired,
}
export default Post;
<file_sep>export const FETCH = 'app/wp-api/FETCH';
export const FETCHED = 'app/wp-api/FETCHED';
<file_sep>import { createStore, applyMiddleware, compose } from 'redux';
import appReducer from './reducers';
import wpApi from './middlewares/wp-api';
let devTools = [];
if (window.devToolsExtension) {
devTools = [window.devToolsExtension()]
}
const wpApiMiddleware = applyMiddleware(wpApi);
const enhancers = compose(wpApiMiddleware, ...devTools);
const store = createStore(appReducer, enhancers);
export default store;
<file_sep>Thème WordPress pour Virgo Coop
===============================
* Thème basé sur https://github.com/Automattic/_s.
* Créé dans le contexte d'un WordPress dockerisé (https://github.com/visiblevc/wordpress-starter).
* Stack : Webpack, React, WordPress REST API.
## Mise en place
- `git clone …`
- `mkdir app data`
- `docker-compose up`
- installe WordPress tel que configuré selon le docker-compose.yml
- monte les volumes décrits dans le docker-compose.yml, y compris le thème Virgo Coop
- finaliser l'installation de WordPress sur http://localhost:8080/wp-admin/
- activer le thème Virgo Coop dans le back-office WordPress
- travailler sur le thème dans theme-virgo-coop/
- `npm run [build|watch]`
## TODO
Application React isomorphique dans un contexte WP-REST-API ?
- la solution https://prerender.io/ me paraît bancale, il faut màj etc.
- du coup, isomorphique « pur » => pre-rendering de la route demandée (Node.js) pour la SEO
- si isomorphique « pur » trop chiant, on peut imaginer un contenu statique optimisé pour la SEO, mais non-affiché, et garder une SPA classique à l'affichage (loading async de la route demandée). Le contenu statique serait alors toujours le même, quelle que soit la route demandée (ie. utiliser le fallback contenu de WordPress pour servir cette version SEO-aware statique, quelle que soit l'url)
- coté client, utilisation de React-Router + Redux (middleware) pour charger le contenu depuis l'API REST de WordPress, en fonction de la route
Routage ?
- bypasser le routage WP avec React-Router, pour toujours charger /
API fetching ?
- utilisation de GraphQL, via plugin https://github.com/wp-graphql/wp-graphql pour simplifier les payloads
- utilisation de Relay, vu que l'endpoint GraphQL exposé est Relay-compliant via https://github.com/ivome/graphql-relay-php/
- pour tester graphql : https://github.com/skevy/graphiql-app + `ngrok http 8080` pour taper sur http://localhost:8080/graphql
<file_sep> <?php wp_footer(); ?>
<!-- <script type="text/javascript" src="app.js"></script> -->
<script src="<?php echo get_bloginfo('template_directory') ?>/app.js"></script>
</body>
</html>
|
21a97c222becba84a911ee67e7c27ef4b51e03e2
|
[
"JavaScript",
"PHP",
"YAML",
"Markdown"
] | 8 |
JavaScript
|
virgo-coop/website
|
9d757ae8cde1c38ebff831cd37f3cd08fc012ead
|
fd99cb3622f706073435e0768ee72383fe68102d
|
refs/heads/master
|
<file_sep>import {combineReducers} from 'redux'
import header from './header'
import contentList from './contentList'
let reducer = combineReducers({
header,
contentList
})
export default reducer<file_sep>import * as TYPES from '../action-Type'
import {queryOrderData} from '../../../../api/order'
import {CHANGEREADYSTATE} from '../../../../component/ScrollView/action-Types'
let order = {
getOrderData(page){
return async dispatch=>{
dispatch({
type:CHANGEREADYSTATE,
payload:false
})
let result = await queryOrderData();
dispatch({
type:TYPES.ORDER_DATA,
payload:result.data,
currentPage:page
});
dispatch({
type:CHANGEREADYSTATE,
payload:true
})
}
}
}
export default order<file_sep>import React, { Component } from 'react'
import './Loading.scss'
class Loading extends Component {
render() {
let str = '加载中';
if (this.props.isend) {
str ='已完成'
}
return (
<div className='loading'>
{str}
</div>
)
}
}
export default Loading;<file_sep>import React, { Component } from 'react'
import NavHeader from '../../../component/NavHeader/NavHeader'
import './Main.scss'
class Main extends Component {
constructor(props,context){
super(props,context)
this.maxCount = 140;
this.state ={
count:this.maxCount,
startIndex:0
}
}
doEva(i){
this.setState({
startIndex:i+1
})
}
renderStar(){
let array=[];
for (let i = 0; i < 5; i++) {
let cls=i>= this.state.startIndex? 'star-item':'star-item light';
array.push(
<div onClick={()=>this.doEva(i)} key={i} className={cls}></div>
)
}
return array;
}
componentDidMount(){
this.refs.commentInput.addEventListener('compositionstart',()=>{
this.chineseInput = true
})
this.refs.commentInput.addEventListener('compositionend',(e)=>{
this.chineseInput = false;
this.onInput(e.target.value)
})
}
//ref={(ref)=>this.commentInput=ref}
onInput(value){
let num = value.length;
if (!this.chineseInput) {
this.setState({
count:this.maxCount-num
})
}
}
render() {
return (
<div className='content'>
<NavHeader title='评价'></NavHeader>
<div className='eva-content'>
<div className="star-area">
{this.renderStar()}
</div>
<div className="comment">
<textarea ref='commentInput' onChange={(e)=>this.onInput(e.target.value)} placeholder='亲,评论下呗'
name="" id="" cols="30" rows="10" className="comment-input"></textarea>
<span className="count">{this.state.count}</span>
</div>
<p className="product-name one-line">美味炸鸡</p>
</div>
<div className="submit">提交评价</div>
</div>
)
}
}
export default Main;<file_sep>import React, { Component } from 'react'
import {Provider} from 'react-redux'
import {HashRouter} from 'react-router-dom'
import store from '../store'
import '../../../component/reset.css'
import '../../../component/common.scss'
import Main from './Main'
class Container extends Component {
constructor(props,context){
super(props,context)
}
render() {
return (
<Provider store={store}>
<HashRouter>
<Main></Main>
</HashRouter>
</Provider>
)
}
}
export default Container;<file_sep>export const CHANGE_TAB = 'CHANGE_TAB';
export const GET_FILTER_DATA = 'GET_FILTER_DATA';
export const CHANGE_FILTER = 'CHANGE_FILTER';
export const GET_CATE_CONTENTLIST_DATA = 'GET_CATE_CONTENTLIST_DATA';
export const GET_FILTER_CATE_CONTENTLIST_DATA = 'GET_FILTER_CATE_CONTENTLIST_DATA';<file_sep>import {combineReducers} from 'redux'
import tabReducer from './tabReducer'
import menu from './menu'
import restanurant from './restanurant'
import comment from './comment'
let reducer = combineReducers({
tabReducer,
menu,
restanurant,
comment
})
export default reducer<file_sep>import React, { Component } from 'react'
class Loading extends Component {
constructor(props,context){
super(props,context)
}
render() {
return (
<div>
</div>
)
}
}
export default Loading;<file_sep>import * as TYPES from '../action-Type'
import action from '../action';
import {TABKEY} from '../config'
let tabs = {};
tabs[TABKEY.cate]={
key:TABKEY.cate,
text:'全部分类',
obj:{}
}
tabs[TABKEY.type]={
key:TABKEY.type,
text:'综合排序',
obj:{}
}
tabs[TABKEY.filter]={
key:TABKEY.filter,
text:'筛选',
obj:{}
}
export default function header(state={
tabs,
activeKey:TABKEY.cate,
filterData:{},
closePanel:true
},action){
state = JSON.parse(JSON.stringify(state));
switch(action.type){
case TYPES.CHANGE_TAB:
state.activeKey = action.payload.key;
state.closePanel = action.payload.closePanel;
break;
case TYPES.GET_FILTER_DATA:
state.filterData = action.data;
break;
case TYPES.CHANGE_FILTER:
state.tabs[action.payload.key]={
key:action.payload.key,
text:action.payload.item.name,
obj:action.payload.item
}
break;
}
return state
}
<file_sep>import * as TYPES from '../action-Type'
import {queryListData} from '../../../../api/contentList'
import {CHANGEREADYSTATE} from '../../../../component/ScrollView/action-Types'
let contentList = {
// getListData(){
// return {
// type:TYPES.LIST_DATA,
// payload:queryListData()
// }
// }
getListData(page){
return async dispatch=> {
dispatch({
type:CHANGEREADYSTATE,
payload:false
})
let result = await queryListData();
dispatch({
type:TYPES.LIST_DATA,
data:result.data.poilist,
page
});
dispatch({
type:CHANGEREADYSTATE,
payload:true
})
}
}
}
export default contentList<file_sep>import axios from './index1'
export function queryListData(){
return axios.get('http://localhost:3000/json/food.json')
}
export function queryRestanurant(){
return axios.get('http://localhost:3000/json/restanurant.json')
}
export function queryComment(){
return axios.get('http://localhost:3000/json/comments.json')
}<file_sep>import {CHANGEREADYSTATE} from './action-Types'
export default function scrollView(state={
readyToLoad:true
},action){
state = JSON.parse(JSON.stringify(state))
switch(action.type){
case CHANGEREADYSTATE:
state.readyToLoad = action.payload
console.log(action.payload)
}
return state
}<file_sep>import axios from './index1'
export function queryHeaderData(){
return axios.get('http://localhost:3000/json/head.json');
}
export function queryCateContentList(){
return axios.get('http://localhost:3000/json/list.json');
}
export function queryCateContentListFilter(){
return axios.get('http://localhost:3000/json/listparams.json');
}<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import action from '../../store/action';
import './ContentList.scss'
import ListItem from './ListItem/ListItem'
import ScrollView from '../../../../component/ScrollView/ScrollView'
class ContentList extends Component {
constructor(props,context){
super(props,context)
this.props.getListData(0);
this.state ={
isend:false
}
this.page = 0;
}
onLoadPage=()=>{
this.page++;
if (this.page>3) {
this.setState({
isend:true
})
}else{
this.props.getListData(this.page);
}
}
renderItems(){
let {list} = this.props;
return list.map((item,index)=>{
return (<ListItem key={index} itemData={item}></ListItem>)
})
}
render() {
return (
<div className='list-content'>
<h4 className='list-title'>
<span className='title-line'></span>
<span>附近商家</span>
<span className='title-line'></span>
</h4>
<ScrollView loadCallback={this.onLoadPage.bind(this)} isend={this.state.isend}>
{this.renderItems()}
</ScrollView>
</div>
)
}
}
export default connect(state=>({...state.contentList}),action.contentList)(ContentList);<file_sep>import * as TYPES from '../action-Type'
import {queryHeaderData} from '../../../../api/category'
let category = {
getHeaderData(){
return {
type:TYPES.HEAD_DATA,
payload:queryHeaderData()
}
}
}
export default category;<file_sep>import * as TYPES from '../action-Type'
import {queryListData} from '../../../../api/detail'
let menu = {
getListData(){
return async dispatch=>{
let result = await queryListData();
dispatch({
type:TYPES.GET_LIST_DATA,
data:result.data
})
}
},
getItemClick(payload){
return {
type:TYPES.LEFT_CLICK,
payload
}
},
addSelect(payload){
return {
type:TYPES.ADD_SELECT_ITEM,
payload
}
},
minusSelect(payload){
return {
type:TYPES.MINUS_SELECT_ITEM,
payload
}
},
showChoose(payload){
return {
type:TYPES.SHOW_CHOOSE_CONTENT,
payload
}
},
clearCarData(payload){
return {
type:TYPES.CLEAR_CAR,
payload
}
}
}
export default menu;<file_sep>module.exports ={
TABKEY:{
menu:'menu',
comment:'comment',
restanurant:'restanurant'
}
}<file_sep>import * as TYPES from '../action-Type'
import action from '../action/index'
export default function contentList(state={
list:[]
},action){
state = JSON.parse(JSON.stringify(state))
switch(action.type){
case TYPES.LIST_DATA:
if (action.page===0) {
state.list = action.data;
}else {
state.list = state.list.concat(action.data)
}
break;
}
return state
}<file_sep>import * as TYPES from '../action-Type'
import action from '../action'
export default function comment(state={
commentData:{},
commentList:[]
},action){
state=JSON.parse(JSON.stringify(state))
switch(action.type){
case TYPES.GET_COMMENT_DATA:
if (state.commentList.length>0) {
state.commentList=state.commentList.concat(action.payload.data.comments)
}else{
state.commentData = action.payload.data;
state.commentList = action.payload.data.comments;
}
break;
}
return state;
}<file_sep>import * as TYPES from '../action-Type'
import action from '../action';
import {TABKEY} from '../config'
export default function tabReducer(state={
tabs:[
{
name:'首页',
key:TABKEY.home
},
{
name:'订单',
key:TABKEY.order
},
{
name:'我的',
key:TABKEY.my
}
],
activeKey:TABKEY.home
},action){
state = JSON.parse(JSON.stringify(state))
switch(action.type){
case TYPES.CHANGETAB:
state.activeKey = action.payload.key;
break;
}
return state
}
<file_sep>import * as TYPES from '../action-Type'
import action from '../action'
export default function restanurant(state={
resData:{}
},action){
state = JSON.parse(JSON.stringify(state));
switch(action.type){
case TYPES.GET_RESTANURANT_DATA:
state.resData = action.payload.data
break;
}
return state;
}<file_sep>import * as TYPES from '../action-Type'
import action from '../action/index'
export default function category(state={
items:[]
},action){
state = JSON.parse(JSON.stringify(state));
switch(action.type){
case TYPES.HEAD_DATA:
state.items = action.payload.data.primary_filter;
break;
}
return state
}
<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import './ListItem.scss'
class ListItem extends Component {
constructor(props,context){
super(props,context)
}
renderBrand(a){
let b = a? <div className='brand brand-pin'>品牌</div>
: <div className='brand brand-xin'>新到</div>
return b
}
renderScore(data=''){
let score = parseFloat(data).toFixed(1).toString();
let fullstar,halfstar,nullstar;
let reg = /^(\d)\.(\d)$/g;
let num = reg.exec(score);
fullstar = parseInt(num[1]);
if (parseInt(num[2])>=5) {
halfstar = 1;
nullstar = 5-halfstar-fullstar;
}else{
halfstar=0;
nullstar = 5-fullstar;
}
let starjsx = [];
for (let i = 0; i < fullstar; i++) {
starjsx.push(<div key={i+'full'} className='star fullstar'></div>)
}
for (let i = 0; i < halfstar; i++) {
starjsx.push(<div key={i+'half'} className='star halfstar'></div>)
}
for (let i = 0; i < nullstar; i++) {
starjsx.push(<div key={i+'null'} className='star nullstar'></div>)
}
return starjsx
}
renderMonthNum(data){
if (parseFloat(data)>999) {
return '999+'
}else{
return data
}
}
renderMeituanFlag(data){
if (data) {
return <div className='item-meituan-flag'>美团专送</div>
}
return null;
}
renderOthers(data){
if (data.length<=0) {
return;
}
data=data.map((item,index)=>{
return (
<div className="other-info" key={index}>
<img src={item.icon_url} alt="" className="other-tag"/>
<div className="other-content">{item.info}</div>
</div>
)
})
return data;
}
render() {
let {pic_url,brand_type,name,
wm_poi_score,month_sale_num,
distance,mt_delivery_time,min_price_tip,
delivery_type,discounts2} = this.props.itemData;
return (
<div className='r-item-content scale-1px'>
<img className='item-img' src={pic_url} alt=""/>
{this.renderBrand(brand_type)}
<div className="item-info-content">
<p className="item-title">{name}</p>
<div className="item-desc clearfix">
<div className='item-score'>
{this.renderScore(wm_poi_score)}
</div>
<div className='item-count'>月售:{this.renderMonthNum(month_sale_num)}</div>
<div className='item-distance'> {distance}</div>
<div className='item-time'>{mt_delivery_time} |</div>
</div>
<div className="item-price">
<div className="item-pre-price">{min_price_tip}</div>
{this.renderMeituanFlag(delivery_type)}
</div>
<div className="item-others">
{this.renderOthers(discounts2)}
</div>
</div>
</div>
)
}
}
export default connect()(ListItem);<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import {Switch,Route,NavLink,withRouter,Redirect} from 'react-router-dom'
import NavHeader from '../../../component/NavHeader/NavHeader'
import './Main.scss'
import Menu from '../Menu/Menu';
import Comment from '../Comment/Comment';
import Restanurant from '../Restanurant/Restanurant';
class Main extends Component {
constructor(props,context){
super(props,context)
}
changeTab(){
}
renderTabs(){
let {tabs} = this.props;
return tabs.map((item,index)=>{
let {name,key} = item;
return (
<NavLink replace={true} to={'/'+key}
activeClassName='active'onClick={()=>this.changeTab.bind(this)}
key={key} className='tab-item'>{name}</NavLink>
)
})
}
render() {
return (
<div className='detail'>
<NavHeader title="黄焖鸡"></NavHeader>
<div className="tab-bar">
{this.renderTabs()}
</div>
<Switch>
<Route path='/menu' component={Menu}></Route>
<Route path='/comment' component={Comment}></Route>
<Route path='/restanurant' component={Restanurant}></Route>
<Redirect from='/' to='/menu'></Redirect>
</Switch>
</div>
)
}
}
export default withRouter(connect(state=>state.tabReducer)(Main));<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import './Order.scss'
import action from '../store/action';
import ListItem from './ListItem/ListItem'
import ScrollView from '../../../component/ScrollView/ScrollView'
import NavHeader from '../../../component/NavHeader/NavHeader'
class Order extends Component {
constructor(props,context){
super(props,context)
this.state={
isend:false
}
this.props.getOrderData(0);
this.page=0;
}
renderList(){
let {list} = this.props;
return list.map((item,index)=>{
return <ListItem key={index} itemData={item}></ListItem>
})
}
loadPage(){
this.page++;
if (this.page>3) {
this.setState({
isend:true
})
}else{
this.props.getOrderData(this.page);
}
}
render() {
return (
<div className='orders'>
<div className="header">订单</div>
<ScrollView loadCallback={this.loadPage.bind(this)} isend={this.state.isend}>
<div className="order-list">
{this.renderList()}
</div>
</ScrollView>
</div>
)
}
}
export default connect(state=>state.order,action.order)(Order);<file_sep>import header from './header'
import contentList from './contentList'
let action = {
header,
contentList
}
export default action<file_sep>import * as TYPES from '../action-Type'
import {queryFilterData} from '../../../../api/header'
let header = {
changeTab(payload) {
return {
type:TYPES.CHANGE_TAB,
payload
}
},
getFilterData(){
let payload = {
closePanel:false
};
return async dispatch =>{
let result = await queryFilterData();
dispatch({
type:TYPES.GET_FILTER_DATA,
data:result.data
});
// dispatch({
// type:TYPES.CHANGE_TAB,
// payload
// })
}
},
changeFilter(payload){
return {
type:TYPES.CHANGE_FILTER,
payload
}
}
}
export default header<file_sep>import React, { Component } from 'react'
import './NavHeader.scss'
class NavHeader extends Component {
constructor(props,context){
super(props,context)
}
render() {
return (
<div className='nav'>
<div className="back-icon" onClick={()=>{
window.history.go(-1)
}}>
</div>
<h4 className="title">
{this.props.title}
</h4>
</div>
)
}
}
export default NavHeader;<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import './SearchBar.scss'
class SearchBar extends Component {
constructor(props,context){
super(props,context)
}
render() {
return (
<div className='search-bar'>
<div className='bar-location'>
<div className="location-icon"></div>
<div className="location-text">北京市</div>
</div>
<div className='search-btn'>
<p className="place-holder">搜索</p>
</div>
</div>
)
}
}
export default connect()(SearchBar);<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import './ListItem.scss'
class ListItem extends Component {
constructor(props,context){
super(props,context)
}
renderTotalPrice(data,total,index){
return(
<div className='product-item' key={index} >
<span>...</span>
<div className='p-total-count'>总计{index}个菜,实付
<span className='total-price'>¥{total}</span>
</div>
</div>
)
}
renderProduct(data,total){
if (data.length<=0) {
return '';
}
let length = data.length;
data = JSON.parse(JSON.stringify(data))
data.push({type:'more'})
return data.map((item,index)=>{
let {product_name,product_count} = item;
if (item.type==='more') {
return this.renderTotalPrice(item,total,index);
}
return <div className='product-item' key={index}>{product_name}
<div className='p-count'>x{product_count}</div>
</div>
})
}
renderComment(data){
if (!data) {
return <div className='evalutaion clearfix'>
<div onClick={this.goEval} className='evaluation-btn'>评价</div>
</div>
}
}
goEval(){
window.location.href='/evaluation.html'
}
goDetail(){
window.location.href = '/detail.html';
}
render() {
let {poi_pic,poi_name,status_description,product_list,total,is_comment} = this.props.itemData;
return (
<div className='order-item'>
<div className="order-item-inner">
<img src={poi_pic} alt="" className="item-img"/>
<div className="item-right">
<div className="item-top" onClick={this.goDetail}>
<p className="order-name one-line">{poi_name}</p>
<div className="arrow"></div>
<div className="order-state">{status_description}</div>
</div>
<div className="item-bottom">
{this.renderProduct(product_list,total)}
</div>
</div>
</div>
{this.renderComment(is_comment)}
</div>
)
}
}
export default connect()(ListItem);<file_sep>import {createStore,applyMiddleware} from 'redux'
import reduxLogger from 'redux-logger'
import reduxThunk from 'redux-thunk'
import reduxPromise from 'redux-promise'
import reducer from './reducer'
let store = createStore(reducer,applyMiddleware(reduxLogger,reduxThunk,reduxPromise));
export default store
<file_sep>import * as TYPES from '../action-Type'
import action from '../action'
export default function order(state={
list:[]
},action){
state = JSON.parse(JSON.stringify(state));
switch(action.type){
case TYPES.ORDER_DATA:
if (action.page===0) {
state.list = action.payload.digestlist;
}else{
state.list = state.list.concat(action.payload.digestlist);
}
break;
}
return state
}<file_sep>import tabAction from './tabAction'
import restanurant from './restanurant'
import menu from './menu'
import comment from './comment'
let action = {
tabAction,
menu,
restanurant,
comment
}
export default action<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import {Route,Redirect,Switch,withRouter} from 'react-router-dom'
import NavHeader from '../../../component/NavHeader/NavHeader'
import Header from '../Header/Header'
import ContentList from '../ContentList/ContentList'
import '../../../component/reset.css'
class Main extends Component {
constructor(props,context){
super(props,context)
}
render() {
return (
<div className='category'>
<NavHeader title='分类'></NavHeader>
<Header></Header>
<ContentList ></ContentList>
</div>
)
}
}
export default withRouter(Main);<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import './MenuItem.scss'
import action from '../../store/action';
import Item from 'antd/lib/list/Item';
class MenuItem extends Component {
constructor(props,context){
super(props,context)
}
addSelectItem(){
this.props.addSelect({index:this.props._index})
}
minusSelectItem(){
this.props.minusSelect({index:this.props._index})
}
render() {
let {picture,name,praise_content,unit,
description,min_price,chooseCount}= this.props.data;
return (
<div className='menu-item'>
<img src={picture} className='img' alt=""/>
<div className="menu-item-right">
<p className="item-title">{name}</p>
<p className="item-desc two-line">{description}</p>
<p className="item-zan">{praise_content}</p>
<p className="item-price">¥{min_price}/
<span className='unit'>{unit}</span>
</p>
</div>
<div className="select-content">
{
chooseCount>0?<div onClick={()=>this.minusSelectItem()} className="minus"></div>:null
}
{
chooseCount>0?<div className="count">{chooseCount}</div>:null
}
<div onClick={()=>this.addSelectItem()} className="plus"></div>
</div>
</div>
)
}
}
export default connect(state=>state.menu,action.menu)(MenuItem);<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import './Header.scss'
import action from '../store/action';
import {TABKEY} from '../store/config'
class Header extends Component {
constructor(props,context){
super(props,context)
this.props.getFilterData();
}
changeTab=(key)=>{
let closePanel = false;
if ((this.props.activeKey===key)&& !this.props.closePanel) {
closePanel = true;
}
this.props.changeTab({key,closePanel})
}
revertActive=(key,dataList)=>{
if (key===TABKEY.cate) {
for (let i = 0; i < dataList.length; i++) {
for (let j = 0; j < dataList[i].sub_category_list.length; j++) {
dataList[i].sub_category_list[j].active =false;
}
}
}else if (key===TABKEY.type) {
for (let i = 0; i < dataList.length; i++) {
dataList[i].active = false;
}
}else {
for (let i = 0; i < dataList.length; i++) {
for (let j = 0; j < dataList[i].items.length; j++) {
dataList[i].items[j].active =false;
}
}
}
}
changeDoFilter=(item,key,dataList)=>{
this.revertActive(key,dataList);
item.active = true;
this.props.changeFilter({item,key});
let closePanel = !this.props.closePanel;
this.props.changeTab({key,closePanel})
this.props.getContentListFilterData({
filterData:item,
page:0,
isend:false
})
}
renderTabs(){
let {tabs,activeKey} = this.props;
let array=[];
for (const key in tabs) {
if (tabs.hasOwnProperty(key)) {
let item = tabs[key];
let cls = item.key+' item';
if (item.key===activeKey && !this.props.closePanel) {
cls+=' current'
}
array.push(
<div className={cls} key={item.key} onClick={()=>{this.changeTab(item.key)}}>
{item.text}
</div>
)
}
}
return array
}
renderCateInnerContent(items,cateList){
if (items.length===0) {
return ''
}
return items.sub_category_list.map((item,index)=>{
let cls = item.active?'cate-box-inner active':'cate-box-inner';
return (
<div className="cate-box" key={index} onClick={()=>this.changeDoFilter(item,TABKEY.cate,cateList)}>
<div className={cls}>
{item.name}({item.quantity})
</div>
</div>
)
})
}
renderCateContent(){
let cateList = this.props.filterData.category_filter_list||[];
return cateList.map((item,index)=>{
let {name,quantity} = item;
return (
<li key={index} className='cate-item'>
<p className="item-title">{name}<span className='item-count'>{quantity}</span></p>
<div className="item-conetnt clearfix">
{this.renderCateInnerContent(item,cateList)}
</div>
</li>
)
})
}
renderTypeContent(){
let typeList = this.props.filterData.sort_type_list||[];
return typeList.map((item,index)=>{
let cls = item.active?'type-item active':'type-item';
return (
<li key={index} className={cls} onClick={()=>this.changeDoFilter(item,TABKEY.type,typeList)}>
{item.name}
</li>
)
})
}
renderContent(){
let {tabs,activeKey} = this.props;
let array =[];
for (let key in tabs) {
if (tabs.hasOwnProperty(key)) {
let item = tabs[key];
let cls = item.key +'-panel';
if (item.key===activeKey) {
cls+=' current'
}
if (item.key===TABKEY.cate) {
array.push(
<ul key={item.key} className={cls}>
{this.renderCateContent()}
</ul>
)
}else if (item.key===TABKEY.type) {
array.push(
<ul key={item.key} className={cls}>
{this.renderTypeContent()}
</ul>
)
}else if (item.key===TABKEY.filter) {
array.push(
<ul key={item.key} className={cls}>
{this.renderFilterContent()}
</ul>
)
}
}
}
return array;
}
renderFilterInnerContent(items,filterList){
return items.map((item,index)=>{
let cls = item.icon?'cate-box-inner has-icon':'cate-box-inner';
if (item.active) {
cls+=' active';
}
return (
<div key={index} className='cate-box' onClick={()=>this.changeDoFilter(item,TABKEY.filter,filterList)}>
<div className={cls}>
{item.icon?<img src={item.icon} />:null} {item.name}
</div>
</div>
)
})
}
renderFilterContent(){
let filterList = this.props.filterData.activity_filter_list||[];
return filterList.map((item,index)=>{
return (
<li key={index} className='filter-item'>
<p className="filter-title">{item.group_title}</p>
<div className="item-content clearfix">
{this.renderFilterInnerContent(item.items,filterList)}
</div>
</li>
)
})
}
render() {
let cls = 'panel';
console.log(this.props.closePanel)
if (!this.props.closePanel) {
cls ='panel show'
}
return (
<div className='header'>
<div className='header-top'>
{this.renderTabs()}
</div>
<div className={cls}>
<div className="panel-inner">
{this.renderContent()}
</div>
</div>
</div>
)
}
}
export default connect(state=>({...state.header}),{
...action.header,
...action.contentList
})(Header);<file_sep>import React, { Component } from 'react'
import {connect} from 'react-redux'
import action from '../store/action';
import './ContentList.scss'
import ListItem from './ListItem/ListItem'
import ScrollView from '../../../component/ScrollView/ScrollView'
class ContentList extends Component {
constructor(props,context){
super(props,context)
this.props.getListData();
}
onLoadPage=()=>{
// if (this.props.page<=3) {
// this.props.getListData();
// }
if (this.props.filterData) {
let page = this.props.page;
this.props.getContentListFilterData({page});
}else{
this.props.getListData(this.props.page)
}
}
renderItems(){
let {list} = this.props;
return list.map((item,index)=>{
return (<ListItem key={index} itemData={item}></ListItem>)
})
}
render() {
return (
<div className='list-content'>
<ScrollView loadCallback={this.onLoadPage.bind(this)} isend={this.props.isend}>
{this.renderItems()}
</ScrollView>
</div>
)
}
}
export default connect(state=>({...state.contentList}),action.contentList)(ContentList);<file_sep>import axios from './index1'
export function queryFilterData(){
return axios.get('http://localhost:3000/json/filter.json');
}
|
d1bc1ee72fb64faf3d75db22b5619f61cf1a6e7e
|
[
"JavaScript"
] | 38 |
JavaScript
|
Alicevia/meituan
|
d3f8323c61f8e05e0ae68e5c478006ce010538ea
|
f18f6a389a07f38c44094e3cbe6fcc6f99f337d2
|
refs/heads/master
|
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import '../styles/Table.css';
class ControlPanel extends React.Component{
constructor(props) {
super(props);
this.state = {
};
}
activeModal(e) {
document.querySelector(".modal").classList.add("active");
}
closeModal(e){
document.querySelector(".modal").classList.remove("active");
}
render(){
return(
<div className="conten-panel">
<div className="conten-panel-barra">
<div className="panel-barra-up">
<div className="barra-item" onClick={this.activeModal}></div>
<div className="barra-item" onClick={this.activeModal}></div>
<div className="barra-item" onClick={this.activeModal}></div>
<div className="barra-item" onClick={this.activeModal}></div>
</div>
<div className="panel-barra-down">
<div className="barra-item-cir"></div>
<div className="barra-item" onClick={this.activeModal}></div>
</div>
</div>
<div className="conten-panel-table">
<div className="table-header">
<div className="title">Titulo</div>
<div className="buttom-table">
<a href="/" className="exit">Exit</a>
</div>
</div>
<div className="table-spy">
<input className="table-spy-input"
type="text"
placeholder="look for"
required/>
</div>
<div className="table-return"></div>
</div>
<div className="modal" >
<div className="modal-cont">
<div className="madal-title">Paso 1</div>
<input className="modal-input"
type="text"
placeholder="date"
required/>
<input className="modal-input"
type="text"
placeholder="date"
required/>
<input className="modal-input"
type="text"
placeholder="date"
required/>
<div className="modal-button">
<button className="modal-close" onClick={this.closeModal}>Clouse</button>
<button className="modal-accept" onClick={this.closeModal}>Accept</button>
</div>
</div>
</div>
</div>
);
}
}
export default ControlPanel
<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import ControlPanel from './ControlPanel.js';
import '../styles/login.css';
class Login extends React.Component{
constructor(props) {
super(props);
this.state = {
name: '',
pass:'',
email:''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
//alert(this.state.name+" "+this.state.pass);
ReactDOM.render(
//cambio al cargar los datos
<ControlPanel></ControlPanel>
,
document.getElementById('root')
);
event.preventDefault();
}
render(){
return (
<form className="conten" onSubmit={this.handleSubmit}>
<span className="conten-top-barra"/>
<div className="conten-login">
<img className="img-logo" src="https://www.viajarmilan.com/img/visitar-la-catedral-de-milan.jpg"/>
<input className="input-data-us"
type="text"
placeholder="Username"
value={this.state.name}
onChange={(e)=>this.setState({name:e.target.value})} required/>
<input className="input-data-pa"
type="password"
placeholder="<PASSWORD>"
value={this.state.pass}
onChange={(e)=>this.setState({pass:e.target.value})} required/>
<div className="position-recovery">
<a href="/Recovery" className="recovery">Password recovery?</a>
</div>
<input type="submit" className="start-login" value="login" />
</div>
</form>
);
}
}
export default Login<file_sep>import React from 'react';
import '../styles/login.css';
class Recovery extends React.Component{
constructor(props) {
super(props);
this.state = {
email:''
};
this.passwordRecovery = this.passwordRecovery.bind(this);
}
passwordRecovery(event) {
event.preventDefault();
}
render(){
return(
<form className="conten" onSubmit={this.passwordRecovery}>
<span className="conten-top-barra"/>
<div className="conten-login">
<img className="img-logo" src="https://www.viajarmilan.com/img/visitar-la-catedral-de-milan.jpg"/>
<h3 className="title-h3">please enter your email</h3>
<input className="input-data-us"
type="email"
placeholder="Email"
value={this.state.email}
onChange={(e)=>this.setState({email:e.target.value})} required/>
<div className="position-recovery">
<a href="/" className="recovery">Return login</a>
</div>
<input type="submit" className="start-login" value="validate" />
</div>
</form>
)
}
}
export default Recovery
<file_sep>import React from 'react';
import { ApolloClient, InMemoryCache } from '@apollo/client';/*iniciar el cliente */
import { ApolloProvider } from '@apollo/client';/*para envolver el app */
import { useQuery, gql } from '@apollo/client';/*la peticion */
const client = new ApolloClient({
uri: "https://rickandmortyapi.com/graphql",
cache: new InMemoryCache()
});
const EXCHANGE_RATES = gql`
{
characters {
results {
id
name
}
}
}
`;
function ExchangeRates() {
const { loading, error, data } = useQuery(EXCHANGE_RATES);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
return data.characters.results.map(character => {
return <p key={character.id}>{character.name}</p>;
});
}
class Apollo extends React.Component{
render(){
return(
<ApolloProvider client={client}>
<ExchangeRates></ExchangeRates>
</ApolloProvider>
)
}
}
export default Apollo
|
a0b989d189a08e36eb2937a6ab6f77951309b540
|
[
"JavaScript"
] | 4 |
JavaScript
|
TeamWalls/mdm-react-front1
|
62495d694e874ba7e4328b59a68b80d8622d8cd5
|
fc30b17fee63cfce4d5538f4abcd664ec2997132
|
refs/heads/master
|
<repo_name>GautchAA/beejee.local<file_sep>/views/main_view.php
<div class="row align-items-center">
<div class="col">
<h1>Задачи</h1>
</div>
<?php if($data['countPages']): ?>
<div class="col-auto sort-block">
<div class="btn-group mr-2" role="group" aria-label="First group">
<?php foreach ($data['sorts'] as $sort): ?>
<a href="<?= $sort['url'] ?>" role="button" class="btn<?php if($sort['checked']): ?> btn-primary<?php if($sort['checked'] == 2): ?> up<?php endif; ?><?php else: ?> btn-secondary<?php endif; ?>">
<?= $sort['name'] ?>
</a>
<?php endforeach; ?>
</div>
</div>
<?php endif; ?>
</div>
<?php if($data['countPages']): ?>
<div class="row">
<?php foreach ($data['tasks'] as $key => $task):?>
<div class="col-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-8">
<h5 class="card-title"><?= $task['name'] ?></h5>
<h6 class="card-subtitle mb-2 text-muted"><?= $task['email'] ?></h6>
<p class="card-text"><?= $task['body'] ?></p>
<?php if($user->auth()): ?>
<a href="task/edit/<?= $task['id'] ?>" class="card-link">Редактировать</a>
<a href="task/delete/<?= $task['id'] ?>" class="card-link">Удалить</a>
<?php endif; ?>
</div>
<div class="col-4">
<?php if ($task['status'] == 2): ?><div class="alert alert-info" role="alert"> Выполнено </div><?php endif ?>
<?php if ($task['change_admin']): ?><div class="alert alert-warning" role="alert"> Изменено администратором! </div><?php endif ?>
</div>
</div>
</div>
</div>
</div>
<?php endforeach ?>
</div>
<?php else: ?>
<a class="btn btn-primary" href="task/add" role="button">Создать задачу</a>
<?php endif; ?>
<?php if($data['countPages'] > 1): ?>
<nav aria-label="...">
<ul class="pagination pagination-lg">
<?php for ($page = 1; $page <= $data['countPages']; $page++): ?>
<li class="page-item<?php if($data['currentPage'] == $page): ?> active<?php endif; ?>">
<a href="<?= $data['urlPage'].$page ?>" class="page-link">
<?= $page ?>
</a>
</li>
<?php endfor; ?>
</ul>
</nav>
<?php endif; ?>
<file_sep>/index.php
<?php
session_start();
spl_autoload_register(function($class) {
$fileName = $class . '.php';
if (file_exists('controllers/'.$fileName)) require 'controllers/'.$fileName;
if (file_exists('models/'.$fileName)) require 'models/'.$fileName;
if (file_exists('views/'.$fileName)) require 'views/'.$fileName;
if (file_exists($fileName)) require $fileName;
});
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if (preg_match("/admin\/login\/?$/", $uri)){
AdminController::login();
}
elseif (preg_match("/admin\/logout\/?$/", $uri)){
AdminController::logout();
TaskController::add();
}
elseif (preg_match("/task\/add\/?$/", $uri)){
TaskController::add();
}
elseif (preg_match("/task\/delete\/([^\/]*)\/?$/", $uri, $params)){
TaskController::delete($params[1]);
}
elseif (preg_match("/task\/edit\/([^\/]*)\/?$/", $uri, $params)){
TaskController::edit($params[1]);
}
else{
MainController::index();
}
<file_sep>/views/task_edit_view.php
<h1>Редактирование задачи</h1>
<?php if($data['method'] == "post" && !count($data['error'])): ?>
<div class="alert alert-success" role="alert"> Задача изменена.</div>
<?php endif; ?>
<?php if(in_array('no_add', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Ошибка изменения, свяжитесь с администратором!</div>
<?php endif; ?>
<form method="post">
<div class="form-group">
<label for="task-name">Имя:</label>
<input type="text" class="form-control" id="task-name" name="task-name" aria-describedby="nameHelp" placeholder="Введите имя" value="<?= $data['task']['name'] ?>">
</div>
<?php if(in_array('name_empty', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Необходимо ввести имя!</div>
<?php endif; ?>
<div class="form-group">
<label for="task-email">Email:</label>
<input type="email" class="form-control" id="task-email" name="task-email" aria-describedby="emailHelp" placeholder="Введите email" value="<?= $data['task']['email'] ?>">
</div>
<?php if(in_array('email_empty', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Необходимо ввести email!</div>
<?php endif; ?>
<?php if(in_array('email_no_valid', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Некорректный email!</div>
<?php endif; ?>
<div class="form-group">
<label for="task-body">Задача:</label>
<textarea class="form-control" id="task-body" name="task-body" rows="3" ><?= $data['task']['body'] ?></textarea>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="task-status" name="task-status" <?php if($data['task']['status'] == 2): ?>checked<?php endif ?>>
<label class="form-check-label" for="task-status">Выполнена</label>
</div>
<button type="submit" class="btn btn-primary">Сохранить</button>
</form>
<file_sep>/controllers/TaskController.php
<?php
class TaskController
{
public static function add(){
$data = [];
$data['error'] = [];
$data['method'] = "get";
$name = '';
$email = '';
$body = '';
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$data['method'] = "post";
$task = new Task();
if (isset($_POST['task-name']) && $_POST['task-name'] !== "") {
$name = htmlspecialchars($_POST['task-name'], ENT_QUOTES, 'UTF-8');
}
else{
$data['error'][] = "name_empty";
}
if (isset($_POST['task-email']) && $_POST['task-email'] !== "") {
$email = htmlspecialchars($_POST['task-email'], ENT_QUOTES, 'UTF-8');
if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
$data['error'][] = "email_no_valid";
$email = "";
}
}
else{
$data['error'][] = "email_empty";
}
if (isset($_POST['task-body']) && $_POST['task-body'] !== "") {
$body = htmlspecialchars($_POST['task-body'], ENT_QUOTES, 'UTF-8');
}
if (!count($data['error']) && !$task->addTask(['name' => $name, 'email' => $email, 'body' => $body])) {
$data['error'][] = "no_add";
}
elseif(!count($data['error'])){
$name = "";
$body = "";
$email = "";
}
}
$data['name'] = $name;
$data['body'] = $body;
$data['email'] = $email;
View::render('task_add_view.php', 'template_view.php', $data);
}
public static function edit($id){
$user = new User();
if (!$user->auth()) {
return header('Location: /admin/login');
}
$data = [];
$data['error'] = [];
$data['method'] = "get";
$task = new Task();
$taskRender = $task->getTask($id);
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$change_admin = 0;
$data['method'] = "post";
if (isset($_POST['task-name']) && $_POST['task-name'] !== "") {
$taskRender['name'] = htmlspecialchars($_POST['task-name'], ENT_QUOTES, 'UTF-8');
}
else{
$data['error'][] = "name_empty";
}
if (isset($_POST['task-email']) && $_POST['task-email'] !== "") {
$taskRender['email'] = htmlspecialchars($_POST['task-email'], ENT_QUOTES, 'UTF-8');
if (!filter_var($taskRender['email'], FILTER_VALIDATE_EMAIL)){
$data['error'][] = "email_no_valid";
}
}
else{
$data['error'][] = "email_empty";
}
$body = "";
if (isset($_POST['task-body']) && $_POST['task-body'] !== "") {
$body = htmlspecialchars($_POST['task-body'], ENT_QUOTES, 'UTF-8');
}
if ($body !== $taskRender['body']) {
$taskRender['change_admin'] = 1;
}
$taskRender['body'] = $body;
$taskRender['status'] = isset($_POST['task-status']) ? 2: 1;
if (!count($data['error']) && !$task->updateTask($id, $taskRender)) {
$data['error'][] = "no_add";
}
}
$data['task'] = $taskRender;
View::render('task_edit_view.php', 'template_view.php', $data);
}
public static function delete($id){
$user = new User();
if (!$user->auth()) {
return header('Location: /admin/login');
}
$task = new Task();
$task->deleteTask($id);
View::render('task_delete_view.php', 'template_view.php');
}
}
<file_sep>/views/admin_login_view.php
<h1>Авторизация</h1>
<form method="post">
<div class="form-group">
<label for="user-name">Имя пользователя:</label>
<input type="text" class="form-control" id="user-name" name="user-name" aria-describedby="emailHelp" placeholder="Имя" value="<?= $data['name'] ?>">
</div>
<?php if(in_array('name_empty', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Необходимо ввести имя пользователя!</div>
<?php endif; ?>
<div class="form-group">
<label for="user-password">Пароль:</label>
<input type="password" class="form-control" id="user-password" name="user-password" placeholder="<PASSWORD>">
</div>
<?php if(in_array('password_empty', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Необходимо ввести пароль!</div>
<?php endif; ?>
<?php if(in_array('no_login', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Имя пользователя или пароль неверны!</div>
<?php endif; ?>
<button type="submit" class="btn btn-primary">Авторизоваться</button>
</form>
<file_sep>/views/task_add_view.php
<h1>Создать задачу</h1>
<?php if($data['method'] == "post" && !count($data['error'])): ?>
<div class="alert alert-success" role="alert"> Новая задача добавлена </div>
<?php endif; ?>
<?php if(in_array('no_add', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Ошибка добавления, свяжитесь с администратором!</div>
<?php endif; ?>
<form method="post">
<div class="form-group">
<label for="task-name">Имя:</label>
<input type="text" class="form-control" id="task-name" name="task-name" aria-describedby="nameHelp" placeholder="Введите имя" value="<?= $data['name'] ?>">
</div>
<?php if(in_array('name_empty', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Необходимо ввести имя!</div>
<?php endif; ?>
<div class="form-group">
<label for="task-email">Email:</label>
<input type="email" class="form-control" id="task-email" name="task-email" aria-describedby="emailHelp" placeholder="Введите email" value="<?= $data['email'] ?>">
</div>
<?php if(in_array('email_empty', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Необходимо ввести email!</div>
<?php endif; ?>
<?php if(in_array('email_no_valid', $data['error'])): ?>
<div class="alert alert-danger" role="alert"> Некорректный email!</div>
<?php endif; ?>
<div class="form-group">
<label for="task-body">Задача:</label>
<textarea class="form-control" id="task-body" name="task-body" rows="3" ><?= $data['body'] ?></textarea>
</div>
<button type="submit" class="btn btn-primary">Создать</button>
</form>
<file_sep>/beejee.sql
-- phpMyAdmin SQL Dump
-- version 4.9.2
-- https://www.phpmyadmin.net/
--
-- Хост: 127.0.0.1:3306
-- Время создания: Ноя 24 2020 г., 17:32
-- Версия сервера: 10.4.10-MariaDB
-- Версия PHP: 7.3.12
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- База данных: `beejee`
--
-- --------------------------------------------------------
--
-- Структура таблицы `tasks`
--
DROP TABLE IF EXISTS `tasks`;
CREATE TABLE IF NOT EXISTS `tasks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`body` text NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT 1,
`change_admin` tinyint(1) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `tasks`
--
INSERT INTO `tasks` (`id`, `name`, `email`, `body`, `status`, `change_admin`) VALUES
(1, 'Александр', '<EMAIL>', 'Первая задача', 1, 0),
(2, 'Александр', '<EMAIL>', 'Вторая задача', 1, 0),
(3, 'Иван', '<EMAIL>', '<NAME>', 1, 0),
(4, 'Петя', '<EMAIL>', '<NAME>', 1, 0),
(5, 'Галина', '<EMAIL>', 'Задача от галины', 1, 0);
-- --------------------------------------------------------
--
-- Структура таблицы `users`
--
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
--
-- Дамп данных таблицы `users`
--
INSERT INTO `users` (`id`, `name`, `password`) VALUES
(1, 'admin', '<PASSWORD>');
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/controllers/AdminController.php
<?php
class AdminController
{
public static function logout(){
$user = new User();
$user->logout();
}
public static function login(){
$user = new User();
$data = [];
$data['error'] = [];
$name = '';
$password = '';
if($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (isset($_POST['user-name']) && $_POST['user-name'] !== "") {
$name = htmlspecialchars($_POST['user-name'], ENT_QUOTES, 'UTF-8');
}
else{
$data['error'][] = "name_empty";
}
if (isset($_POST['user-password']) && $_POST['user-password'] !== "") {
$password = htmlspecialchars($_POST['user-password'], ENT_QUOTES, 'UTF-8');
}
else{
$data['error'][] = "password_empty";
}
if (!count($data['error']) && !$user->login($name, $password)) {
$data['error'][] = "no_login";
}
}
$data['name'] = $name;
View::render('admin_login_view.php', 'template_view.php', $data);
}
}
<file_sep>/models/Task.php
<?php
class Task extends Model
{
public function getTasks($filter = []){
$sort = "ORDER BY id DESC";
if (isset($filter['sort'])) {
switch ($filter['sort']) {
case 'name':
$sort = "ORDER BY name ";
break;
case 'name_desc':
$sort = "ORDER BY name DESC";
break;
case 'email':
$sort = "ORDER BY email";
break;
case 'email_desc':
$sort = "ORDER BY email DESC";
break;
case 'status':
$sort = "ORDER BY status";
break;
case 'status_desc':
$sort = "ORDER BY status DESC";
break;
}
}
$limit = "";
if (isset($filter['limit'])) {
$limit = "LIMIT ";
if (isset($filter['page'])) {
$limit .= ($filter['page'] * $filter['limit']).", ";
}
$limit .= $filter['limit'];
}
$query = "SELECT * FROM tasks WHERE status > 0 $sort $limit";
return $this->db->getRows($query);
}
public function getCountTasks($filter = []){
return $this->db->getRow("SELECT COUNT(*) as count FROM tasks WHERE status > 0")['count'];
}
public function getTask($id){
return $this->db->getRow("SELECT * FROM tasks WHERE id = $id");
}
public function addTask($task){
return $this->db->insert("tasks", $task);
}
public function updateTask($id, $task){
return $this->db->update("tasks", $task, "id = $id");
}
public function deleteTask($id){
return $this->db->update("tasks", ['status' => 0], "id = $id");
}
}
<file_sep>/models/User.php
<?php
class User extends Model
{
public function login($name, $password){
if ($user = $this->db->getRow("SELECT * FROM users WHERE name = '$name' AND password = '". MD5($password)."'")){
$_SESSION['id'] = $user['id'];
header('Location: /');
}
return false;
}
public function logout(){
unset($_SESSION['id']);
header('Location: /');
}
public function auth(){
return isset($_SESSION['id']);
}
}
<file_sep>/views/template_view.php
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width; initial-scale=1.0">
<title>Главная</title>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<link rel="stylesheet" href="/static/css/main.css">
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand" href="/">BeeJee</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="task/add">Создать задачу</a>
</li>
</ul>
<ul class="navbar-nav my-2 my-lg-0">
<?php if($user->auth()): ?>
<li class="nav-item active">
<a class="nav-link" href="/admin/logout">Выход</a>
</li>
<?php else: ?>
<li class="nav-item active">
<a class="nav-link" href="/admin/login">Вход</a>
</li>
<?php endif; ?>
</ul>
</div>
</nav>
</header>
<main class="container">
<?php include $content_view; ?>
</main>
<footer></footer>
</body>
</html>
<file_sep>/views/View.php
<?php
class View
{
public static function render($content_view, $view, $data = [])
{
$user = new User();
include 'views/'.$view;
}
}
<file_sep>/controllers/MainController.php
<?php
class MainController
{
public static function index(){
$task = new Task();
$data = [];
$filter = [];
$filter['limit'] = 3;
if (isset($_GET['sort'])) {
$filter['sort'] = $_GET['sort'];
}
$countTasks = $task->getCountTasks($filter);
$countPages = 0;
$currentPage = 1;
$urlPage = "/?page=";
if ($countTasks) {
$countPages = (int)(($countTasks + 2) / 3);
if (isset($_GET['page']) && $_GET['page'] > 0) {
$currentPage = $_GET['page'] > $countPages ? $countPages : $_GET['page'];
$filter['page'] = $currentPage - 1;
}
}
if (isset($_GET['sort'])) {
$urlPage = "/?sort=".$_GET['sort']."&page=";
}
$data['countPages'] = $countPages;
$data['currentPage'] = $currentPage;
$data['urlPage'] = $urlPage;
$tasks = $task->getTasks($filter);
$data['tasks'] = $tasks;
$sorts = [];
$sorts[] = ['name' => "По имени", 'url' => 'name', 'checked' => 0];
$sorts[] = ['name' => "По email", 'url' => 'email', 'checked' => 0];
$sorts[] = ['name' => "По статусу", 'url' => 'status', 'checked' => 0];
if (isset($_GET['sort'])) {
foreach ($sorts as $keySort => $sort) {
if ($sort['url'] === $_GET['sort']) {
$sorts[$keySort]['url'] = $sort['url']."_desc";
$sorts[$keySort]['checked'] = 1;
}
elseif ($sort['url']."_desc" === $_GET['sort']) {
$sorts[$keySort]['url'] = "";
$sorts[$keySort]['checked'] = 2;
}
}
}
foreach ($sorts as $keySort => $sort) {
if ($sort['url']) {
$sorts[$keySort]['url'] = "/?sort=".$sort['url'].($currentPage > 1?("&page=".$currentPage):"");
}
elseif($currentPage > 1){
$sorts[$keySort]['url'] = "/?page=".$currentPage;
}
else{
$sorts[$keySort]['url'] = "/";
}
}
$data['sorts'] = $sorts;
View::render('main_view.php', 'template_view.php', $data);
}
public static function page_404(){
View::render('404_view.php', 'template_view.php', $data);
}
}
|
ab80b0cd7f84b8358a10cf8d4638e4da04070e9b
|
[
"SQL",
"PHP"
] | 13 |
PHP
|
GautchAA/beejee.local
|
23d41727a7f652ebefc62d9b14338c13cda4770f
|
3baca8bec7631fcea24d2568ea94ede30ec4132f
|
refs/heads/master
|
<file_sep>package praktikum.pengolahan.citra.processors;
import javafx.scene.image.Image;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
public class ImageProcessor {
public static int[][][] imageToColors(Image image) {
int[][][] colors = new int[(int) image.getHeight()][(int) image.getWidth()][4];
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color color = image.getPixelReader().getColor(x, y);
colors[y][x] = new int[]{
(int) (color.getRed() * 255),
(int) (color.getGreen() * 255),
(int) (color.getBlue() * 255),
(int) (color.getOpacity())};
}
}
return colors;
}
public static double[][][] imageToColorsDoubled(Image image) {
double[][][] colors = new double[(int) image.getHeight()][(int) image.getWidth()][4];
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
Color color = image.getPixelReader().getColor(x, y);
colors[y][x] = new double[]{
color.getRed() * 255,
color.getGreen() * 255,
color.getBlue() * 255,
color.getOpacity()};
}
}
return colors;
}
public static int[][][] imageToColors(File imageFile) {
try {
Image image = new Image(new FileInputStream(imageFile));
return imageToColors(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static double[][][] imageToColorsDoubled(File imageFile) {
try {
Image image = new Image(new FileInputStream(imageFile));
return imageToColorsDoubled(image);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public static double[][][] imageToColorsDoubled(InputStream imageFile) {
Image image = new Image(imageFile);
return imageToColorsDoubled(image);
}
public static Image colorsToImage(int[][][] colors) {
int width = ColorOperation.getWidth(colors);
int height = ColorOperation.getHeight(colors);
WritableImage writableImage = new WritableImage(width, height);
PixelWriter pixelWriter = writableImage.getPixelWriter();
ColorOperation.performOperationsTo(colors, ((row, column) -> {
Color color = new Color(
ColorOperation.getRed(colors, row, column) / 255d,
ColorOperation.getGreen(colors, row, column) / 255d,
ColorOperation.getBlue(colors, row, column) / 255d,
ColorOperation.getAlpha(colors, row, column)
);
pixelWriter.setColor(column, row, color);
}));
return writableImage;
}
}<file_sep>package praktikum.pengolahan.citra.contracts;
public interface UpdateUI {
void update();
}
<file_sep>package praktikum.pengolahan.citra.contracts;
public interface ReactTo {
void pixelOn(int x, int y);
}
<file_sep>package praktikum.pengolahan.citra.processors;
import javafx.scene.image.Image;
import praktikum.pengolahan.citra.utils.Utils;
import static praktikum.pengolahan.citra.processors.ColorOperation.*;
import static praktikum.pengolahan.citra.processors.ImageProcessor.colorsToImage;
import static praktikum.pengolahan.citra.processors.ImageProcessor.imageToColors;
public class Effects {
public static int[][][] addBrightness(int beta, int[][][] colors) {
performOperationsTo(colors, (row, column) -> {
int newRed = Utils.getBoundedColor(getRed(colors, row, column) + beta);
setRed(colors, row, column, newRed);
int newGreen = Utils.getBoundedColor(getGreen(colors, row, column) + beta);
setGreen(colors, row, column, newGreen);
int newBlue = Utils.getBoundedColor(getBlue(colors, row, column) + beta);
setBlue(colors, row, column, newBlue);
});
return colors;
}
public static int[][][] grayScale(int[][][] inputColors) {
performOperationsTo(inputColors, (row, column) -> {
int red = getRed(inputColors, row, column);
int green = getGreen(inputColors, row, column);
int blue = getBlue(inputColors, row, column);
int newGrayScale = (red + green + blue) / 3;
setRed(inputColors, row, column, newGrayScale);
setGreen(inputColors, row, column, newGrayScale);
setBlue(inputColors, row, column, newGrayScale);
});
return inputColors;
}
public static int[][][] toGreen(int[][][] inputColors) {
performOperationsTo(inputColors, (row, column) -> {
// deactivate red channel
setRed(inputColors, row, column, 0);
// deactivate blue channel
setBlue(inputColors, row, column, 0);
});
return inputColors;
}
public static Image grayScale(Image inputImage) {
int[][][] colors = imageToColors(inputImage);
int[][][] grayScaled = grayScale(colors);
return colorsToImage(grayScaled);
}
public static int[][][] blackWhite(int[][][] inputColors) {
performOperationsTo(inputColors, (row, column) -> {
//all color channels are the same value so we only take one channel, this case is the first index (RED)
int greyColored = getRed(inputColors, row, column);
int blackOrWhite = Utils.binaryImageBound(greyColored)*255;
setRed(inputColors, row, column, blackOrWhite);
setGreen(inputColors, row, column, blackOrWhite);
setBlue(inputColors, row, column, blackOrWhite);
});
return inputColors;
}
}
<file_sep>package praktikum.pengolahan.citra.processors;
import praktikum.pengolahan.citra.contracts.PerformOperationsTo;
public class ColorOperation {
public static void performOperationsTo(int[][][] colors, PerformOperationsTo performOperationsTo) {
int width = getWidth(colors);
int height = getHeight(colors);
for (int row = 0; row < height; row++) {
for (int column = 0; column < width; column++) {
performOperationsTo.pixelOn(row, column);
}
}
}
public static void performOperationsTo(double[][][] colors, PerformOperationsTo performOperationsTo) {
int width = getWidth(colors);
int height = getHeight(colors);
for (int row = 0; row < height; row++) {
for (int column = 0; column < width; column++) {
performOperationsTo.pixelOn(row, column);
}
}
}
public static int getWidth(int[][][] data) {
return data[0].length;
}
public static int getWidth(double[][][] data) {
return data[0].length;
}
public static int getHeight(int[][][] data) {
return data.length;
}
public static int getHeight(double[][][] data) {
return data.length;
}
public static int getRed(int[][][] colors, int x, int y) {
return colors[x][y][0];
}
public static double getRed(double[][][] colors, int x, int y) {
return colors[x][y][0];
}
public static void setRed(int[][][] colors, int x, int y, int newValue) {
colors[x][y][0] = newValue;
}
public static int getGreen(int[][][] colors, int x, int y) {
return colors[x][y][1];
}
public static double getGreen(double[][][] colors, int x, int y) {
return colors[x][y][1];
}
public static void setGreen(int[][][] colors, int x, int y, int newValue) {
colors[x][y][1] = newValue;
}
public static int getBlue(int[][][] colors, int x, int y) {
return colors[x][y][2];
}
public static double getBlue(double[][][] colors, int x, int y) {
return colors[x][y][2];
}
public static void setBlue(int[][][] colors, int x, int y, int newValue) {
colors[x][y][2] = newValue;
}
public static int getAlpha(int[][][] colors, int x, int y) {
return colors[x][y][3];
}
}
<file_sep>package praktikum.pengolahan.citra.contracts;
public interface ApplyEffect {
void apply();
}
<file_sep>package praktikum.pengolahan.citra.contracts;
public interface ApplyWithParams {
void apply(int param);
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>praktikum.pengolahan.citra</groupId>
<artifactId>Praktikum-Pengolahan-Citra</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
<plugin>
<groupId>com.zenjava</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>8.8.3</version>
<configuration>
<mainClass>praktikum.pengolahan.citra.App</mainClass>
<verbose>true</verbose>
<jfxMainAppJarName>Praktikum Pengolahan Citra.jar</jfxMainAppJarName>
<vendor>N(one)</vendor>
<needShortcut>true</needShortcut>
<needMenu>true</needMenu>
<appName>Praktikum Pengolahan Citra</appName>
</configuration>
</plugin>
</plugins>
</build>
<developers>
<developer>
<name><NAME></name>
<email><EMAIL></email>
<organization>STMIK Bumigora</organization>
<url>https://github.com/khyrulimam/</url>
</developer>
</developers>
<licenses>
<license>
<name>GNU GENERAL PUBLIC LICENSE v3</name>
<url>https://www.gnu.org/licenses/gpl-3.0.en.html</url>
</license>
</licenses>
<properties>
<nd4j.version>1.0.0-alpha</nd4j.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.reactivex.rxjava2/rxjava -->
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjava</artifactId>
<version>2.1.12</version>
</dependency>
<dependency>
<groupId>io.reactivex.rxjava2</groupId>
<artifactId>rxjavafx</artifactId>
<version>2.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/gov.nist.math/jama -->
<dependency>
<groupId>gov.nist.math</groupId>
<artifactId>jama</artifactId>
<version>1.0.3</version>
</dependency>
</dependencies>
</project><file_sep>package praktikum.pengolahan.citra.utils;
import javafx.stage.FileChooser;
import org.apache.commons.io.IOUtils;
import praktikum.pengolahan.citra.App;
import java.io.*;
public class FileUtils {
private static FileChooser fileChooser;
public static final FileChooser.ExtensionFilter ALLOWED_IMAGE = new FileChooser.ExtensionFilter("File gambar", "*.png", "*.jpg", "*.jpeg");
public static File showChoseImageFileDialog() {
if (fileChooser == null) {
fileChooser = new FileChooser();
fileChooser.getExtensionFilters().add(ALLOWED_IMAGE);
fileChooser.setTitle(Constants.IMAGE_CHOOSER_DIALOG_TITLE);
}
return fileChooser.showOpenDialog(App.APP_STAGE);
}
public static File tmpFileFromInputStream(InputStream inputStream) throws IOException {
final File tempFile = File.createTempFile("tmp", "img");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(inputStream, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return tempFile;
}
}
<file_sep>#TODO
## Quick Analysis
- Histogram
- Resolution (**done**)
- Pixel position when hovered (**done**)
- Show color on hovered coordinat (**done**)
## Image Effects
- Grey (**done**)
- Contrast enhancement
- Black & White
- Brightness enhancement
|
1ad71661e9e009159d837aa35d09e368742c7aed
|
[
"Markdown",
"Java",
"Maven POM"
] | 10 |
Java
|
khrlimam/Praktikum-Pengolahan-Citra
|
a4d10a0a6d0549bf09f0a4b8538153419a4f4f7b
|
2cb6d41fd5697c4d70c108cbcf48b5f29d4be0c5
|
refs/heads/master
|
<repo_name>exlosir/WebServices<file_sep>/app/Http/Controllers/api/OrderUserController.php
<?php
namespace App\Http\Controllers\api;
use App\Order;
use App\OrderUser;
use App\Status;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
class OrderUserController extends Controller
{
public function getRespondedUser($id)
{
/* вставить в url
* id заказа
* */
$order = Order::find($id)->usersPivot;
$order1 = Order::find($id)->users;
foreach ($order1 as $index => $item) {
$item->status_master = $order[$index]->pivot->statuses_name;
}
return Response::json($order1);
}
public function add(Request $request)
{
/* @params
* user_id
* order_id
* */
$exists = OrderUser::where('user_id', $request->user_id)->where('order_id', $request->order_id)->get();
if ($exists->isEmpty()) {
$order = Order::find($request->order_id);
$user = User::find($request->user_id);
$statusId = Status::where('name', 'В ожидании')->get()->first()->id;
$created_updated_at = \Carbon\Carbon::now();
$order->users()->attach($user, array('status_id' => $statusId, 'created_at' => $created_updated_at, 'updated_at' => $created_updated_at));
return Response::json(true);
}
return Response::json(false);
}
public function executeOrderMaster(Request $request)
{
/* @params
* order_id
* */
$order = OrderUser::where('order_id', $request->order_id)->where('status_id', Status::where('name', 'Принят')->first()->id)->whereHas('order', function ($q) {
$q->where('status_id', Status::where('name', 'В исполнении')->first()->id);
})->get();
if (!$order->isEmpty()) {
$user = User::find($order->first()->user_id);
return Response::json($user);
}
return Response::json(false);
}
public function acceptMaster(Request $request,$order_id, $master_id) {
/* @params
* вставить в url
* order id
* master id (id пользователя в таблице users, который откликнулся на заказ)
* */
$order = Order::find($order_id);
$master = User::find($master_id);
$statusAcceptId = Status::where('name', 'Принят')->first()->id;
$statusWaitId = Status::where('name', 'В ожидании')->first()->id;
$statusDeclineId = Status::where('name', 'Отклонен')->first()->id;
$currUser = $order->usersPivot()->where('user_id', $master->id)->get(); //находим выбранного пользователя
$currUser->first()->pivot->status_id = $statusAcceptId; //изменяем его статус в Pivot таблице
$currUser->first()->pivot->save(); // сохраняем
/*Отклоняем всех, кроме выбранного пользователя*/
foreach($order->usersPivot as $user) { // перебираем всех пользователей
if($user->pivot->status_id == $statusWaitId){ // проверяем их статус = в ожидании
$user->pivot->status_id = $statusDeclineId; // меняем и сохраняем
$user->pivot->save();
}
}
/*Меняем статус заказа на 'В исполнении' */
$order->status_id = Status::where('name', 'В исполнении')->first()->id;
$order->save();
return Response::json(true);
}
}
<file_sep>/app/Http/Controllers/api/auth/RegisterController.php
<?php
namespace App\Http\Controllers\api\auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Response;
class RegisterController extends Controller
{
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required',
'login' => 'required',
'password' => '<PASSWORD>'
]);
if ($validator->fails()) return response()->json($validator->errors()); // если не прошел валидацию, выдать ошибку
$user = new User();
$user->email = $request->email;
$user->login = $request->login;
$user->password = <PASSWORD>($request->password);
$user->api_token = Str::random();
$user->save();
$user = User::find($user->id);
return Response::json($user)->setStatusCode(200, 'Succsessful creating account');
}
}
<file_sep>/app/Http/Controllers/OrderController.php
<?php
namespace App\Http\Controllers;
use App\Country;
use App\City;
use App\Order;
use App\OrderUser;
use App\Status;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use App\Category;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
class OrderController extends Controller
{
private $perPage = 5;
public function index($category = null) {
$categories = Category::children();
if(empty($category)) {
$orders = Order::where('status_id','!=',Status::where('name','Закрыт')->first()->id)->orderBy('created_at', 'desc')->paginate($this->perPage); // выбираем все заказы, т.к не выбрана категория
} else {
$orders = Order::where('status_id','!=',Status::where('name','Закрыт')->first()->id)->where('category_id',$category)->orderBy('created_at', 'desc')->paginate($this->perPage); //выбираем заказы указанной категории
if($orders->isEmpty()) { // если не было найдено заказов по такой категории, ищем все заказы по родительской категори
$cat = Category::find($category); // выбираем категорию
if(!empty($cat) && !$cat->parent_id){ // проверяем, является ли категория родительской
$parent_id = $cat->id;
$cat = Category::where('parent_id',$parent_id)->get()->pluck('id')->toarray(); // выбираем все дочерние категории
$cat[] = $parent_id; // добавляем ко всем дочерним родительскую категорию
$orders = Order::where('status_id','!=',Status::where('name','Закрыт')->first()->id)->whereIn('category_id',$cat)->paginate($this->perPage); // выбираем все заказы, которые относятся к родительской и ее дочерним категориям
}/*else { // дочерняя категория
$orders = Order::where('status_id','!=',Status::where('name','Закрыт')->first()->id)->where('category_id',$category)->orderBy('created_at', 'desc')->paginate(12); //выбираем заказы указанной категории
}*/
}
}
if(Gate::allows('userEmailConfirmed', auth()->user())) {
return view('orders.index', ['orders'=>$orders, 'categories'=>$categories]);
}else {
return view('orders.index_for_not_confirmed_email', ['orders'=>$orders, 'categories'=>$categories]);
}
}
public function search(Request $request) {
$categories = Category::children();
if(is_null($request->search)) {
$orders = Order::where('status_id','!=',Status::where('name','Закрыт')->first()->id)->paginate($this->perPage); //выбираем все заказы
}else {
$orders = Order::where('status_id', '!=', Status::where('name', 'Закрыт')->first()->id)->where('name', 'like', '%' . $request->search . '%')->orWhere('description', 'like', '%' . $request->search . '%')->paginate($this->perPage); //выбираем все заказы
}
if(Gate::allows('userEmailConfirmed', auth()->user())) {
return view('orders.index', ['orders'=>$orders, 'categories'=>$categories]);
}else {
return view('orders.index_for_not_confirmed_email', ['orders'=>$orders, 'categories'=>$categories]);
}
}
public function add() {
$categories = Category::children(null);
$countries = Country::all();
$cities = City::all();
return view('orders.add', ['categories'=>$categories, 'countries'=>$countries, 'cities'=>$cities]);
}
public function save(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required',
'description' => 'required',
'price' => 'required| between:1,5',
'category' => 'required',
'country' => 'required',
'city' => 'required',
'end_date' => 'required | date'
]);
if($validator->fails()){
return redirect()->back()->withInput()->withErrors($validator->errors());
}
$order = new Order();
$order->name = $request->name;
$order->description = $request->description;
$order->customer_id = $request->user()->id;
$order->price = $request->price;
$order->date_end = \Carbon\Carbon::parse($request->end_date)->format('Y-m-d H:i:s');
$order->status_id = Status::where('name','Открыт')->get()->first()->id;
$order->category_id = $request->category;
$order->country_id = $request->country;
$order->city_id = $request->city;
$order->street = $request->street;
$order->house = $request->house;
$order->building = $request->building;
$order->apartment = $request->apartment;
$order->timestamps;
$order->save();
return redirect()->route('orders')->with('success','Заказа успешно добавлен!');
}
public function indexMore($orderId) {
if(Gate::allows('userEmailConfirmed', auth()->user())) {
$order = Order::find($orderId);
return view('orders.more', ['order' => $order]);
} else {
return redirect()->back()->with('warning', 'Мы сожалеем, но для вас этот раздел закрыт, т.к вы не подтвердили E-mail!');
}
}
public function destroyOrder(Order $order) {
$order->usersPivot()->detach();
$order->delete();
return redirect()->route('orders')->with('success','Заказ успешно удален');
}
public function closeOrder(Request $request, Order $order) {
$statusOrderClosed = Status::where('name', 'Закрыт')->first()->id;
$order->status_id = $statusOrderClosed;
$order->save();
return redirect()->back()->with('success', 'Заказ успешно закрыт. Не забудьте оставить отзыв мастеру.');
}
public function myOrderIndex(Request $request, Order $order) {
if(Gate::allows('userEmailConfirmed', auth()->user())) {
$categories = Category::children();
$orders = Order::where('customer_id',$request->user()->id)->orderBy('created_at', 'desc')->paginate($this->perPage); // выбираем в
return view('orders.my-orders', ['orders'=>$orders, 'categories'=>$categories]);
}
return redirect()->back()->with('warning', 'Мы сожалеем, но для вас этот раздел закрыт, т.к вы не подтвердили E-mail!');
}
public function myOrdersForExecution(Request $request) {
if(Gate::allows('userEmailConfirmed', auth()->user())) {
$user = $request->user();
$orders = OrderUser::where('user_id', $user->id)->where('status_id', Status::where('name','Принят')->first()->id)->whereHas('order', function($q){
$q->where('status_id',Status::where('name','В исполнении')->first()->id);
})->paginate($this->perPage);
$categories = Category::children();
return view('orders.my-orders-for-execution', ['orders'=>$orders, 'categories'=>$categories]);
}
return redirect()->back()->with('warning', 'Мы сожалеем, но для вас этот раздел закрыт, т.к вы не подтвердили E-mail!');
}
}
<file_sep>/app/Http/Controllers/api/CategoryController.php
<?php
namespace App\Http\Controllers\api;
use App\Category;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
class CategoryController extends Controller
{
public function all() {
$categories = Category::all();
return Response::json($categories);
}
}
<file_sep>/app/Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public $timestamps = false;
public static function children($parent=null) {
return Category::where('parent_id',$parent)->where('published',1)->orderBy('name','desc')->get();
}
public static function childrenAll($parent=null) {
return Category::where('parent_id',$parent)->orderBy('name','desc')->get();
}
public function parent() {
return $this->belongsTo(Category::class, 'parent_id', 'id');
}
public function isPublished() {
return !! $this->published;
}
}
<file_sep>/routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
// Route::middleware('auth:api')->get('/user', function (Request $request) {
// return $request->user();
// });
Route::get('login', 'api\CountryController@country');
Route::post('register', 'api\auth\RegisterController@register');
Route::post('login', 'api\auth\AuthController@login');
Route::post('check-session', function(Request $request) {
if($request->api_token != null) {
$user = \App\User::where('api_token', $request->api_token)->get();
if (!$user->isEmpty())
return Response::json(true)->setStatusCode(200);
}
return Response::json(false)->setStatusCode(401);
});
Route::group(['middleware' => 'api'], function () {
/*Страны*/
Route::get('countries/get', 'api\CountryController@all');
/*Города*/
Route::get('cities/get', 'api\CityController@all');
/*Категории*/
Route::get('categories/get', 'api\CategoryController@all');
/*Пол*/
Route::get('genders/get', 'api\GendersController@all');
/*Заказы*/
Route::group(['prefix'=>'orders'], function() {
Route::get('/', 'api\OrdersController@allOrders');
Route::post('/search', 'api\OrdersController@searchOrders');
Route::get('/add', 'api\OrdersController@addOrder');
Route::post('/add/new/store', 'api\OrdersController@storeOrder');
Route::delete('{id}/destroy', 'api\OrdersController@destroyOrder');
Route::post('/{id}', 'api\OrdersController@aboutOrder');
/*Мои заказы*/
Route::get('/{id}/my-orders', 'api\OrdersController@myOrders');
Route::get('/{id}/order-master','api\OrderUserController@getRespondedUser');
Route::get('/for-execution', 'api\OrdersController@myOrdersForExecution');
Route::post('/feedback/save', 'api\OrdersController@closeAndFeedback');
Route::group(['prefix'=>'order-master'], function(){
Route::post('/add', 'api\OrderUserController@add');
Route::post('{order}/accept-master/{master}', 'api\OrderUserController@acceptMaster')->name('accept-master-order');
Route::get('/execute-master', 'api\OrderUserController@executeOrderMaster');
});
});
/*Профиль пользователя*/
Route::group(['prefix'=>'profile'], function(){
Route::get('/{id}', 'api\ProfileController@index');
Route::get('/cities/get', 'api\ProfileController@getCities');
Route::post('/{id}/update', 'api\ProfileController@update');
Route::post('/password/change/save', 'api\ProfileController@changePassword');
Route::delete('/{id}/destroy', 'api\ProfileController@destroy');
Route::post('/upload-image-profile', 'api\ProfileController@uploadImageProfile');
Route::get('/{id}/get-portfolio', 'api\ProfileController@getPortfolio');
});
});
<file_sep>/app/Http/Controllers/FeedbackController.php
<?php
namespace App\Http\Controllers;
use App\Order;
use App\OrderUser;
use App\Status;
use App\Rating;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class FeedbackController extends Controller
{
public function create(Request $request, Order $order) {
return view('orders.feedback.create', ['order'=>$order]);
}
public function store(Request $request, Order $order) {
$validator = Validator::make($request->all(), [
'description' => 'required',
'rating' => 'required|numeric|min:1|max:5'
]);
if($validator->fails()) return redirect()->back()->withErrors($validator->errors());
$statusAcceptId = Status::where('name', 'Принят')->first()->id; // получаем Id статуса с именем 'Принят'
$order_user = $order->usersPivot()->where('status_id', $statusAcceptId)->first()->pivot->id; // Получаем id мастера
$feedback = new Rating(); // создаем новый отзыв
$feedback->description = $request->description;
$feedback->order_user = $order_user;
$feedback->rating = $request->rating;
$feedback->timestamps;
$feedback->save();
$master = new User();
foreach($order->users as $item) { // получаем модель мастера
if($item->id == $order->usersPivot()->where('status_id', $statusAcceptId)->first()->pivot->user_id)
$master = $item;
}
/*Формируем рейтинг самому пользователю по среднему баллу*/
$arrayOrderUser = DB::table('order_user')->where('user_id', $master->id)->where('status_id', $statusAcceptId)->pluck('id'); // выбираем в связанной таблице order_user все значения, где пользователь был выбран в качестве мастера
$arrayFeedback = DB::table('rating_order')->whereIn('order_user', $arrayOrderUser)->pluck('rating'); // получаем все отзывы к этому мастеру и выбираем только колонку с рейтингом
$ratingUser = null;
foreach($arrayFeedback as $item) { // перебираем все рейтинги
$ratingUser += $item; // складываем между собой их
}
$ratingUser != 0 ? $ratingUser /= $arrayFeedback->count() : $ratingUser = 0;// получаем средний балл и присваиваем пользователю
$master->rating = $ratingUser;
$master->save();
return redirect()->route('orders')->with('success', 'Спасибо, что оставили отзыв ;)');
}
public function notResponded(Request $request) {
$user = auth()->user();
$ordersUser = $user->orders1;//получаем все заказы текущего пользователя
$orderMasters = OrderUser::whereIn('order_id', $ordersUser->pluck('id'))->get(); // получаем всех откликнувшихся на заказы
$orderMasters = $orderMasters->where('status_id',Status::where('name','Принят')->first()->id); // отфильтрованные значения только принятых к исполнению заказа
$allFeedbacks = Rating::whereIn('order_user', $orderMasters->pluck('id'))->get();
$notFeeds = $orderMasters->pluck('id')->diffKeys($allFeedbacks->pluck('order_user')); // получили количество мастеров, на который текущий пользователь не оставил отзыв
$orders = OrderUser::whereIn('id', $notFeeds)->get();
return view('orders.feedback.notFeeds',['orders'=>$orders]);
}
}
<file_sep>/app/Http/Controllers/ProfileController.php
<?php
namespace App\Http\Controllers;
use App\City;
use App\Country;
use App\Gender;
use App\Order;
use App\OrderUser;
use App\Role;
use App\Status;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class ProfileController extends Controller
{
public function index(Request $request) {
$user = $request->user();
$genders = Gender::all();
$countOrders = Order::where('customer_id', $user->id)->get()->count();
$countDoneOrders = OrderUser::where('user_id', $user->id)->where('status_id',Status::where('name', 'Принят')->first()->id)->whereHas('order', function($q){
$q->where('status_id', Status::where('name', 'Закрыт')->first()->id);
})->get()->count();
return view('profile.index')->with(['user'=>$user,'genders'=>$genders, 'countOrders'=>$countOrders, 'countDoneOrders'=>$countDoneOrders]);
}
// public function getCities(Country $country) {
// $cities = City::where('country_id',$country->id)->get();
// return $cities;
// }
public function save(Request $request) {
$validator = Validator::make($request->all(), [
'phone_number' => 'numeric|digits:11',
'email'=>'email'
]);
if($validator->fails()) return redirect()->back()->withErrors($validator->errors());
$user = $request->user();
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->patronymic = $request->patronymic;
$user->gender_id = $request->gender;
$user->country_id = $request->country;
$user->city_id = $request->city;
$user->birthday = $request->birthday;
$user->email = $request->email;
$user->phone_number = $request->phone_number;
if(!$user->isDirty())
return redirect()->back()->with('warning', 'Изменения не обнаружены. Данные не обновлены!');
$user->save();
return redirect()->back()->with('success', 'Данные успешно сохранены!');
}
public function uploadImage(Request $request) {
$validator = Validator::make($request->all(),[
'image'=>'required|mimes:jpg,jpeg,png|max:2048'
]);
if($validator->fails())
return redirect()->back()->withErrors($validator->errors()->first());
$image = $request->file('image');
$imageName = auth()->user()->email.'_'. Str::random().'.'.$image->getClientOriginalExtension();
$image->move(public_path("/profiles/".auth()->user()->email."/"), $imageName);
$user = Auth::user();
$user->image_profile = $imageName;
$user->save();
return redirect()->back()->with('success', 'Фотография успешно загружена!');
}
public function changePassword(Request $request) {
$validator = Validator::make($request->all(),[
'password'=>'<PASSWORD>|confirmed|min:6|max:18|string'
]);
if($validator->fails())
return redirect()->back()->withErrors($validator->errors()->first());
$user = auth()->user();
$user->password = Hash::make($request->password);
$user->save();
return redirect()->back()->with('success', 'Пароль успешно изменен!');
}
/*Удаление аккаунта*/
public function deleteAccount(Request $request) {
$user = $request->user();
if ($user->deleteAccount()) {
return redirect()->to('/logout')->with('success', 'Профиль успешно удален!');
}
return redirect()->back()->withErrors('Что-то пошло не так. Профиль не был удален!');
}
public function addRole(Request $request) {
$user = User::find($request->user()->id);
$role = Role::where('name', $request->roleName)->get();
if(!$user->roles()->get()->contains($role->first()->id)) {
$user->roles()->attach($role);
return json_encode(true);
}
return json_encode(false);
}
public function delRole(Request $request) {
$user = User::find($request->user()->id);
$role = Role::where('name', $request->roleName)->get();
if($user->roles()->get()->contains($role->first()->id)) {
$user->roles()->detach($role);
return json_encode(true);
}
return json_encode(false);
}
public function getRole(Request $request) {
$user = User::find($request->user()->id);
$role = Role::where('name', $request->roleName)->get();
return json_encode($user->roles()->get()->contains($role->first()->id));
}
public function getCountries() {
return Response::json($categories = Country::all());
}
public function getCities($id) {
$cities = City::where('country_id', $id)->get();
return Response::json($cities);
}
public function getCountryCity() {
$user = auth()->user();
return Response::json(['country'=>$user->country ? $user->country->name : null, 'city'=>$user->city ? $user->city->name : null]);
}
}
<file_sep>/app/Http/Controllers/api/ProfileController.php
<?php
namespace App\Http\Controllers\api;
use App\City;
use App\Country;
use App\Gender;
use App\Order;
use App\OrderUser;
use App\Status;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Str;
class ProfileController extends Controller
{
public function index($id) { /*Отображение страницы профиля*/
$user = User::where('id',$id)->with('city','country', 'gender')->first();
$countOrders = Order::where('customer_id', $user->id)->get()->count();
$countDoneOrders = OrderUser::where('user_id', $user->id)->where('status_id',Status::where('name', 'Принят')->first()->id)->whereHas('order', function($q){
$q->where('status_id', Status::where('name', 'Закрыт')->first()->id);
})->get()->count();
$user->countOrders = $countOrders ? $countOrders : null;
$user->countDoneOrders = $countDoneOrders ? $countDoneOrders : null;
return Response::json($user);
}
public function getCities(Request $request) {
return Response::json(City::where('country_id', $request->country_id)->get());
}
public function update(Request $request, $id) {
/* first_name
* last_name
* patronymic
* gender
* country
* city
* birthday
* email
* phone_number
* */
$user = User::find($id);
$user->first_name = $request->first_name;
$user->last_name = $request->last_name;
$user->patronymic = $request->patronymic;
$user->gender_id = Gender::where('name',$request->gender)->first()->id;
$user->country_id = Country::where('name',$request->country)->first()->id;
$user->city_id = City::where('name',$request->city)->first()->id;;
$user->birthday = $request->birthday;
$user->email = $request->email;
$user->phone_number = $request->phone_number;
if(!$user->isDirty())
return Response::json(['error', 'Изменения не были обнаружены']);
$user->save();
return Response::json(['success'=>'Данные успешно сохранены']);
}
public function changePassword(Request $request) {
/*password
password_confirmation
*/
$validator = Validator::make($request->all(),[
'password'=>'required|confirmed|min:6|string'
]);
if($validator->fails())
return Response::json($validator->errors())->setStatusCode(400);
$user = auth()->user();
$user->password = Hash::make($request->password);
$user->save();
return Response::json(['success'=>'Пароль успешно изменен'])->setStatusCode(200);
}
public function destroy($id) {
$user = User::find($id);
if(!is_null($user)){
if ($user->delete()) {
return Response::json('success')->setStatusCode(200);
}
}
return Response::json('error')->setStatusCode(400);
}
public function uploadImageProfile (Request $request) {
$user = User::where('api_token',$request->api_token)->first();
$image = $request->file('image');
$imageName = $user->email.'_'. Str::random().'.'.$image->getClientOriginalExtension();
$image->move(public_path("/profiles/".$user->email."/"), $imageName);
$user->update([
'image_profile'=>$imageName
]);
return Response::json("Фотография успешно сохранена!");
}
/**
* @param $id - пользователя
*/
public function getPortfolio($id) {
$feedbacks = DB::table('order_user')->
join('rating_order', 'order_user.id', '=', 'rating_order.order_user')->
join('orders', 'order_user.order_id', '=', 'orders.id')->
where('order_user.user_id', '=' ,$id)->
select('orders.id as order_id','orders.name as order_name', 'rating_order.description', 'rating_order.rating', 'rating_order.created_at as created')->
get();
if($feedbacks->isEmpty()) return Response::json(false);
return Response::json($feedbacks);
}
}
<file_sep>/app/Rating.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Rating extends Model
{
protected $table = 'rating_order';
public function masters() {
return $this->belongsTo(OrderUser::class, 'order_user', 'id');
}
public function scopeFeedbackCount (User $user) { // получаем количество не оставленных отзывов, где текущий пользователь является заказчиком
$count = $this->masters();
return $count;
}
}
<file_sep>/app/Http/Controllers/api/CountryController.php
<?php
namespace App\Http\Controllers\api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Country;
use Illuminate\Support\Facades\Response;
class CountryController extends Controller
{
public function all()
{
$country = Country::all();
return Response::json($country);
}
}
<file_sep>/public/0.js
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{
/***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/profile/AddRoleComponent.vue?vue&type=script&lang=js&":
/*!***********************************************************************************************************************************************************************************!*\
!*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/profile/AddRoleComponent.vue?vue&type=script&lang=js& ***!
\***********************************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
//
//
//
//
//
//
//
//
//
//
//
//
/* harmony default export */ __webpack_exports__["default"] = ({
data: function data() {
return {
checkbox: false,
checkboxVal: ''
};
},
methods: {
update: function update() {
if (this.checkbox) {
this.addRole();
this.checkboxVal = 'Мастер';
} else {
this.delRole();
this.checkboxVal = 'Не мастер';
}
},
addRole: function addRole() {
axios.post('/profile/add-role', {
roleName: 'Исполнитель'
});
},
delRole: function delRole() {
axios.post('/profile/del-role', {
roleName: 'Исполнитель'
});
},
getRole: function getRole() {
var _this = this;
axios.get('/profile/get-role', {
params: {
roleName: 'Исполнитель'
}
}).then(function (resp) {
// console.log('getrole = ' + resp.data);
_this.checkbox = resp.data; // console.log(this.checkbox);
});
}
},
mounted: function mounted() {
this.getRole(); // console.log(this.checkbox);
if (this.checkbox) {
this.checkboxVal = 'Мастер';
console.log(this.checkbox);
} else {
this.checkboxVal = 'Не мастер';
console.log(this.checkbox);
}
}
});
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/profile/AddRoleComponent.vue?vue&type=template&id=672501d2&":
/*!***************************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/components/profile/AddRoleComponent.vue?vue&type=template&id=672501d2& ***!
\***************************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"div",
{
staticClass: "tab-pane fade pl-3",
attrs: {
id: "nav-add-role",
role: "tabpanel",
"aria-labelledby": "nav-add-role-tab"
}
},
[
_c("h4", { staticClass: "lead mt-3" }, [
_vm._v(
"Чтобы получить возможность исполнять заказы, отметье галочкой поле"
)
]),
_vm._v(" "),
_c("form", { staticClass: "form-inline", attrs: { action: "/" } }, [
_c(
"div",
{ staticClass: "custom-control custom-checkbox my-1 mr-sm-2" },
[
_c("input", {
directives: [
{
name: "model",
rawName: "v-model",
value: _vm.checkbox,
expression: "checkbox"
}
],
staticClass: "custom-control-input pl-3",
attrs: {
type: "checkbox",
id: "customControlInline",
value: "checkboxValue"
},
domProps: {
checked: Array.isArray(_vm.checkbox)
? _vm._i(_vm.checkbox, "checkboxValue") > -1
: _vm.checkbox
},
on: {
change: [
function($event) {
var $$a = _vm.checkbox,
$$el = $event.target,
$$c = $$el.checked ? true : false
if (Array.isArray($$a)) {
var $$v = "checkboxValue",
$$i = _vm._i($$a, $$v)
if ($$el.checked) {
$$i < 0 && (_vm.checkbox = $$a.concat([$$v]))
} else {
$$i > -1 &&
(_vm.checkbox = $$a
.slice(0, $$i)
.concat($$a.slice($$i + 1)))
}
} else {
_vm.checkbox = $$c
}
},
function($event) {
return _vm.update()
}
]
}
}),
_vm._v(" "),
_c(
"label",
{
staticClass: "custom-control-label",
attrs: { for: "customControlInline" }
},
[_vm._v(_vm._s(_vm.checkboxVal))]
)
]
)
])
]
)
}
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ "./resources/js/components/profile/AddRoleComponent.vue":
/*!**************************************************************!*\
!*** ./resources/js/components/profile/AddRoleComponent.vue ***!
\**************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _AddRoleComponent_vue_vue_type_template_id_672501d2___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./AddRoleComponent.vue?vue&type=template&id=672501d2& */ "./resources/js/components/profile/AddRoleComponent.vue?vue&type=template&id=672501d2&");
/* harmony import */ var _AddRoleComponent_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./AddRoleComponent.vue?vue&type=script&lang=js& */ "./resources/js/components/profile/AddRoleComponent.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__["default"])(
_AddRoleComponent_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"],
_AddRoleComponent_vue_vue_type_template_id_672501d2___WEBPACK_IMPORTED_MODULE_0__["render"],
_AddRoleComponent_vue_vue_type_template_id_672501d2___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "resources/js/components/profile/AddRoleComponent.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./resources/js/components/profile/AddRoleComponent.vue?vue&type=script&lang=js&":
/*!***************************************************************************************!*\
!*** ./resources/js/components/profile/AddRoleComponent.vue?vue&type=script&lang=js& ***!
\***************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_AddRoleComponent_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/babel-loader/lib??ref--4-0!../../../../node_modules/vue-loader/lib??vue-loader-options!./AddRoleComponent.vue?vue&type=script&lang=js& */ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/profile/AddRoleComponent.vue?vue&type=script&lang=js&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_AddRoleComponent_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./resources/js/components/profile/AddRoleComponent.vue?vue&type=template&id=672501d2&":
/*!*********************************************************************************************!*\
!*** ./resources/js/components/profile/AddRoleComponent.vue?vue&type=template&id=672501d2& ***!
\*********************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_AddRoleComponent_vue_vue_type_template_id_672501d2___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./AddRoleComponent.vue?vue&type=template&id=672501d2& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/components/profile/AddRoleComponent.vue?vue&type=template&id=672501d2&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_AddRoleComponent_vue_vue_type_template_id_672501d2___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_AddRoleComponent_vue_vue_type_template_id_672501d2___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ })
}]);<file_sep>/app/Providers/AuthServiceProvider.php
<?php
namespace App\Providers;
use App\Rating;
use App\Role;
use App\Status;
use App\User;
use App\OrderUser;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
// 'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Gate::define('userEmailConfirmed', function ($user) {
if($user->confirmedEmail()) {
return true;
}
return false;
});
Gate::define('admin', function(User $user) {
$role = Role::where('name', 'Администратор')->get()->first();
return $user->roles->contains($role);
});
Gate::define('notRespondFeedback', function(User $user){
$ordersUser = $user->orders1;//получаем все заказы текущего пользователя
if($ordersUser->isEmpty()) return false;
$orderMasters = OrderUser::whereIn('order_id', $ordersUser->pluck('id'))->get(); // получаем всех откликнувшихся на заказы
$orderMasters = $orderMasters->where('status_id',Status::where('name','Принят')->first()->id); // отфильтрованные значения только принятых к исполнению заказа
$allFeedbacks = Rating::whereIn('order_user', $orderMasters->pluck('id'))->get();
// dd($orderMasters->pluck('id'), $allFeedbacks->pluck('order_user'));
$notFeeds = $orderMasters->pluck('id')->diffKeys($allFeedbacks->pluck('order_user')); // получили количество мастеров, на который текущий пользователь не оставил отзыв
// dd($orderMasters->pluck('id'), $allFeedbacks->pluck('order_user'), $notFeeds);
if($notFeeds->count() > 0)
return true;
return false;
});
}
}
<file_sep>/app/User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
// protected $fillable = [
// 'name', 'email', 'password','login', 'confirmed_email_token', 'email_verified_at'
// ];
protected $guarded = [];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
'image'=>'array',
];
public function gender() {
return $this->belongsTo(Gender::class,'gender_id','id');
}
public function city() {
return $this->belongsTo(City::class,'city_id','id');
}
public function country() {
return $this->belongsTo(Country::class,'country_id','id');
}
public function confirmedEmail() {
return !! $this->is_confirmed_email;
}
public function getEmailConfirmationToken() {
$this->update([
'confirmed_email_token'=> $token = Str::random()
]);
return $token;
}
public function confirmEmail() {
$this->update([
'confirmed_email_token' => null,
'is_confirmed_email'=> 1,
'email_verified_at' => \Carbon\Carbon::now()
]);
return $this;
}
public function deleteAccount() {
return $this->delete();
}
public function roles() {
return $this->belongsToMany(Role::class,'user_role');
}
public function hasRole($string) {
$roleName = Role::where('name', $string)->get();
}
public function orders1() {
return $this->hasMany(Order::class, 'customer_id','id');
}
public function orders() {
return $this->belongsToMany(Order::class, 'order_user', 'user_id', 'order_id')->withPivot('id','status_id', 'created_at', 'updated_at')->join('statuses', 'order_user.status_id', '=', 'statuses.id')->select('statuses.name as pivot_statuses_name');
}
public function ordersWithoutPivot() {
return $this->belongsToMany(Order::class, 'order_user', 'user_id', 'order_id');
}
public function hasRoleMaster() {
$roleMasterId = Role::where('name', 'Исполнитель')->first()->id;
if($this->roles->contains($roleMasterId))
return true;
return false;
}
public function CountMyOrders() {
// dd($request);
return $this->orders1()->count();
}
}
<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
// $this->call(UsersTableSeeder::class);
$this->call('GendersTableSeeder');
$this->call('CountriesTableSeeder');
$this->call('CitiesTableSeeder');
$this->call('RolesTableSeeder');
$this->call('UsersTableSeeder');
$this->call('StatusesTableSeeder');
}
}
<file_sep>/app/Http/Controllers/PortfolioController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Lang;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use App\Portfolio;
//use function MongoDB\BSON\toJSON;
class PortfolioController extends Controller
{
public function __construct()
{
App::setLocale('ru');
}
public function index() {
$elements = Portfolio::where('user_id', auth()->user()->id)->get();
return view('profile.portfolio', compact('elements'));
}
public function newElement(Request $request) {
$validator = Validator::make($request->all(),[
'image'=>'required|max:2048',
'image.*'=>'mimes:jpg,jpeg,png'
]);
if($validator->fails())
return redirect()->back()->withErrors($validator->errors()->first());
$images = [];
$portfolio = new Portfolio();
$portfolio->name = $request->name;
$portfolio->description = $request->description;
$portfolio->user_id = auth()->user()->id;
$portfolio->save();
foreach ($request->file('image') as $image) {
$imageName = "/profiles/".auth()->user()->email."/portfolio/element".$portfolio->id.'/img_1_portfolio_'. Str::random().'.'.$image->getClientOriginalExtension();
// $imageName = 'img_'.$portfolio->id.'_portfolio_'. Str::random().'.'.$image->getClientOriginalExtension();
// $images->add($imageName);
$images[] = $imageName;
$image->move(public_path("/profiles/".auth()->user()->email."/portfolio/element".$portfolio->id), $imageName);
}
$portfolio->image = $images;
// $portfolio->image = $images->toJson();
$portfolio->save();
// dd(json_encode($images));
return redirect()->back()->with('success', 'Ваша работа в портфолио успешно добавлена!');
}
public function deleteElement($id) {
$elem = Portfolio::find($id);
$elem->delete();
return redirect()->back()->with('success', Lang::get('messages.delete-portfolio'));
}
}
<file_sep>/public/js/main.js
/*Выдвижное меню*/
$('.burger-menu-icon').on('click',function(e){
e.preventDefault();
$(this).toggleClass('burger-menu-icon-active');
$('.nav-left-wrapper').toggleClass('nav-left-wrapper-active');
$('.nav-left').toggleClass('nav-left-active');
$('.nav-left-button').toggleClass('nav-left-button-active');
});
/*Подпись к инпутам*/
$(document).ready(function(){
$(".form").find('.form-input').each(function(){
_this = $(this);
_label = _this.prev();
if(_this.val() !== '')
_label.addClass('label-active');
});
$('.form').find('input, textarea, select').on('keyup blur focus change', function (e) {
var _this = $(this),
_label = _this.prev();
if(e.type === 'keyup') {
if(_this.val() === '') {
_label.removeClass('label-active label-focus');
}else {
_label.addClass('label-active label-focus');
}
}
else if (e.type === 'blur') {
if(_this.val() === '') {
_label.removeClass('label-active label-focus');
}else {
_label.removeClass('label-focus')
}
}
else if (_this.type === 'focus') {
if(_this.val() === '') {
_label.removeClass('label-focus');
}else {
_label.addClass('label-focus');
}
}
if( e.type === "focus") {
if(!_label.hasClass('label-active') && _this.val() === '') {
_label.addClass('label-active');
}else {
if(_this.val() === '')
_label.removeClass('label-active');
}
}
else if (e.type === 'keyup') {
if(!_label.hasClass('label-active') && _this.val() === '') {
_label.removeClass('label-active');
}else {
_label.addClass('label-active');
}
}
else if(e.type === 'change') {
if(_this.val() !== '') {
_label.addClass('label-active');
}else {
_label.removeClass('label-active');
}
}
// else if (e.type === 'load') {
// if(_this.val() === '') {
// _label.addClass('label-active');
// }
// }
});
$('#CategoryCollapse').collapse();
});
// $('.form').find('input, textarea, select').on('focus', function(e){
// e.preventDefault();
// if($(this).val() !== ''){
// $(this).prev().addClass('label-focus');
// }else {
// $(this).prev().removeClass('label-focus');
// }
// });
<file_sep>/app/Http/Controllers/ConfirmationEmailController.php
<?php
namespace App\Http\Controllers;
use App\Mail\EmailConfirmation;
use App\Role;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class ConfirmationEmailController extends Controller
{
public function request(Request $request)
{
$user = $request->user();
return view('profile.request-confirmation-email', compact('user'));
}
public function sendEmail(Request $request) {
$token = $request->user()->getEmailConfirmationToken();
// Mail::to($request->user()->email)->send(new EmailConfirmation($request->user(), $token));
Mail::to($request->user()->email)->send(new EmailConfirmation($request->user(), $token));
return redirect()->route('profile')->with('success', 'На вашу почту было отправлено письмо для подтверждения E-mail!');
}
public function confirm(User $user, $token) {
$user = User::where('email', $user->email)->where('confirmed_email_token', $token)->first();
if(! $user) {
return redirect()->route('request-confirmation-email', $user)->with('warning', 'Ссылка стала недействительной! Пожалуйста, попробуйте снова.');
}
$user->confirmEmail();
$role = Role::where('name', 'Заказчик')->get();
$user->roles()->attach($role);
return redirect()->route('profile')->with('success', 'Ваш почтовый адрес успешно подтвержден. Для вас стали доступны заказы!');
}
}
<file_sep>/readme.md
# Сайт для предоставления услуг разного профиля
### Release 0.0.1
- Инициализация проекта laravel
<file_sep>/app/Http/Controllers/OrderUserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
use App\Status;
use App\User;
use Illuminate\Support\Collection;
class OrderUserController extends Controller
{
public function add(Request $request, $order,$user) {
$order = Order::find($order);
$user = User::find($user);
$statusId = Status::where('name','В ожидании')->get()->first()->id;
$created_updated_at = \Carbon\Carbon::now();
$order->users()->attach($user,array('status_id'=>$statusId, 'created_at'=>$created_updated_at, 'updated_at'=>$created_updated_at));
return redirect()->back()->with('success', 'Ваше предложение принято! Ожидайте ответа Заказчика!');
}
public function acceptMaster(Request $request, Order $order, User $master) {
$statusAcceptId = Status::where('name', 'Принят')->first()->id;
$statusWaitId = Status::where('name', 'В ожидании')->first()->id;
$statusDeclineId = Status::where('name', 'Отклонен')->first()->id;
$currUser = $order->usersPivot()->where('user_id', $master->id)->get(); //находим выбранного пользователя
$currUser->first()->pivot->status_id = $statusAcceptId; //изменяем его статус в Pivot таблице
$currUser->first()->pivot->save(); // сохраняем
/*Отклоняем всех, кроме выбранного пользователя*/
foreach($order->usersPivot as $user) { // перебираем всех пользователей
if($user->pivot->status_id == $statusWaitId){ // проверяем их статус = в ожидании
$user->pivot->status_id = $statusDeclineId; // меняем и сохраняем
$user->pivot->save();
}
}
/*Меняем статус заказа на 'В исполнении' */
$order->status_id = Status::where('name', 'В исполнении')->first()->id;
$order->save();
return redirect()->route('user-page', $master->id)->with('success', 'Вы выбрали специалиста. Пожалуйста, уведомите его о своем решении! ');
}
public function getUsers() {
$order = Order::find(1);
dd($order->getMastersCount());
}
}
<file_sep>/app/OrderUser.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class OrderUser extends Model
{
public $table = 'order_user';
protected $primaryKey = 'id';
public function order() {
return $this->belongsTo(Order::class, 'order_id', 'id');
}
public function status() {
return $this->belongsTo(Status::class, 'status_id', 'id');
}
public function user() {
return $this->belongsTo(User::class, 'user_id', 'id');
}
}
<file_sep>/app/Http/Controllers/api/GendersController.php
<?php
namespace App\Http\Controllers\api;
use App\Gender;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
class GendersController extends Controller
{
public function all()
{
$genders = Gender::all();
return Response::json($genders);
}
}
<file_sep>/app/Http/Controllers/UserController.php
<?php
namespace App\Http\Controllers;
use App\Order;
use App\OrderUser;
use App\Status;
use Illuminate\Http\Request;
use App\User;
use App\Portfolio;
use App\Rating;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function user(Request $request, $id) {
$user = User::find($id);
$elements = Portfolio::where('user_id',$id)->take(6)->get();
$orderIds = DB::table('order_user')->where('user_id', $user->id)->get()->pluck('id')->toArray();
$feedbacks = Rating::whereIn('order_user', $orderIds)->get();
$countOrders = Order::where('customer_id', $user->id)->get()->count();
$countDoneOrders = OrderUser::where('user_id', $user->id)->where('status_id',Status::where('name', 'Принят')->first()->id)->whereHas('order', function($q){
$q->where('status_id', Status::where('name', 'Закрыт')->first()->id);
})->get()->count();
return view('user.page', compact(['user', 'elements', 'feedbacks', 'countOrders', 'countDoneOrders']));
}
public function extendUserPortfolio(Request $request, $id) {
$user = User::find($id);
$elements = Portfolio::where('user_id',$id)->paginate(12);
return view('user.extend-portfolio', compact(['user', 'elements']));
}
public function addRole(Request $request, $idRole) {
$user = User::find($request->user()->id);
if($request->input('method') == 'attach') {
$user->attach($idRole);
}else {
$user->detach($idRole);
}
}
}
<file_sep>/app/Order.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Rating;
class Order extends Model
{
public function user() {
return $this->belongsTo(User::class,'customer_id','id');
}
public function status() {
return $this->hasOne(Status::class, 'id', 'status_id');
}
public function location() {
$loc = $this->street ? ', ул. '. $this->street : '';
$loc = $this->house ? $loc . ', д.' .$this->house : '';
$loc = $this->building ? $loc . ', корп.' .$this->building : '';
$loc = $this->apartment ? $loc . ', кв.' .$this->apartment : '';
$loc_glob = $this->country->name . ', '. $this->city->name. '';
return $loc_glob . $loc;
}
public function category() {
return $this->hasOne(Category::class, 'id', 'category_id');
}
public function country() {
return $this->hasOne(Country::class, 'id', 'country_id');
}
public function city() {
return $this->hasOne(City::class, 'id', 'city_id');
}
public function endOrder() {
return \Carbon\Carbon::parse($this->date_end) < \Carbon\Carbon::now() ? \Carbon\Carbon::parse($this->date_end)->shortAbsoluteDiffForHumans(\Carbon\Carbon::now()) . ' назад' : \Carbon\Carbon::parse($this->date_end)->shortAbsoluteDiffForHumans(\Carbon\Carbon::now());
}
public function users() {
return $this->belongsToMany(User::class, 'order_user', 'order_id', 'user_id');
}
public function usersPivot() {
return $this->belongsToMany(User::class, 'order_user', 'order_id', 'user_id')->withPivot('id','status_id', 'created_at', 'updated_at')->join('statuses', 'order_user.status_id', '=', 'statuses.id')->select('statuses.name as pivot_statuses_name');
}
public function getMastersCount() {
return $this->users->count();
}
public function isFeedback() { //проверяет, существует ли отзыв к работе
$orderUserId = $this->usersPivot()->where('status_id', Status::where('name','Принят')->first()->id)->first()->pivot->id; //нашли мастера, которвый выполнял эту работу
$feedback = DB::table('rating_order')->where('order_user',$orderUserId)->get();
return $feedback->isEmpty();
}
public function isMaster(User $user) {
$mst = $this->usersPivot;
return $mst;
}
public function order_users () {
return $this->belongsTo(OrderUser::class, 'id','order_id');
}
}
<file_sep>/app/Http/Middleware/CheckAdmin.php
<?php
namespace App\Http\Middleware;
use App\Role;
use Closure;
class CheckAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$role = Role::where('name', 'Администратор')->get()->first()->id;
if(!$request->user()->roles->contains($role))
return redirect()->back()->withErrors('Доступ разрешен только админстратору!');
return $next($request);
}
}
<file_sep>/database/seeds/CitiesTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class CitiesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('cities')->insert([
'name'=>'Уфа'
]);
DB::table('cities')->insert([
'name'=>'Москва'
]);
DB::table('cities')->insert([
'name'=>'Санкт-Петербург'
]);
DB::table('cities')->insert([
'name'=>'Октябрьский'
]);
DB::table('cities')->insert([
'name'=>'Туймазы'
]);
DB::table('cities')->insert([
'name'=>'Сочи'
]);
DB::table('cities')->insert([
'name'=>'Кисловодск'
]);
}
}
<file_sep>/app/Http/Controllers/api/OrdersController.php
<?php
namespace App\Http\Controllers\api;
use App\Category;
use App\City;
use App\Country;
use App\Order;
use App\OrderUser;
use App\Rating;
use App\Status;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
class OrdersController extends Controller
{
public function allOrders() {
$orders = Order::where('status_id', '=', Status::where('name', 'Открыт')->first()->id)->with('country','city','status','category')->orderBy('created_at', 'desc')->get();
// $orders = new Collection();
// foreach(Order::all() as $order) {
// $order->status_id = $order->status()->first()->name;
// $order->country_id = $order->country()->first()->name;
// $order->city_id = $order->city()->first()->name;
// $order->category_id = $order->category()->first()->name;
// $orders->push($order);
// }
return Response::json($orders)->setStatusCode(200);
}
public function searchOrders(Request $request) {
// передать параметр search || POST запрос
$orders = Order::where('status_id', '!=', Status::where('name', 'Закрыт')->first()->id)->where('name', 'like', "%".$request->search."%")->orWhere('description', 'like', "%".$request->search."%")->with('country','city','status','category')->get();
return Response::json($orders);
}
public function addOrder(){
$categories = Category::all();
$countries = Country::all();
$cities = City::all();
return Response::json(['categories'=>$categories, 'countries'=>$countries, 'cities'=>$cities]);
}
public function storeOrder(Request $request) {
//POST запрос
$validator = Validator::make($request->all(), [
'name' => 'required',
'description' => 'required',
'price' => 'required',
'category' => 'required',
'country' => 'required',
'city' => 'required',
'date_end' => 'required'
]);
if($validator->fails()) return Response::json($validator->errors());
$order = new Order();
$order->name = $request->name;
$order->description = $request->description;
$order->customer_id = $request->user_id;
$order->price = $request->price;
$order->date_end = \Carbon\Carbon::parse($request->date_end)->format('Y-m-d H:i:s');
$order->status_id = Status::where('name','Открыт')->get()->first()->id;
$order->category_id = Category::where('name',$request->category)->first()->id;
$order->country_id = Country::where('name',$request->country)->first()->id;
$order->city_id = City::where('name',$request->city)->first()->id;
$order->street = $request->street;
$order->house = $request->house;
$order->building = $request->building;
$order->apartment = $request->apartment;
$order->timestamps;
$order->save();
return Response::json('Заказ успешно добавлен');
}
public function destroyOrder(Request $request, $id) {
$order = Order::find($id);
if($order->user->id == $request->user_id){
$order->delete();
return Response::json('Заказ успешно удален!');
}
return Response::json('Произошла ошибка во время удаления заказа!');
}
public function aboutOrder(Request $request, $id) {
$orders = Order::where('id',$id)->with('country','city','status','category', 'user')->get();
return Response::json($orders)->setStatusCode(200);
}
public function myOrders($id) {
/*$id - ид пользователя авторизованного*/
$orders = Order::where('customer_id',$id)->with('country','city', 'status', 'user', 'category')->get();
if(!$orders->isEmpty())
return Response::json($orders);
return Response::json('Список ваших заказов пуст');
}
public function myOrdersForExecution(Request $request) {
/* @params
* user_id
* */
$ord = new Collection();
$user = User::find($request->user_id);
$orders = OrderUser::where('user_id', $user->id)->where('status_id', Status::where('name','Принят')->first()->id)->whereHas('order', function($q){
$q->where('status_id',Status::where('name','В исполнении')->first()->id);
})->with('order', 'order.city', 'order.country', 'order.category', 'order.status')->get();
foreach ($orders as $order) {
$ord->push($order->order);
}
return Response::json($ord);
}
public function closeAndFeedback(Request $request) {
/*
* order_id
* rating
* description
* */
$statusOrderClosed = Status::where('name', 'Закрыт')->first()->id;
$order = Order::find($request->order_id);
$order->status_id = $statusOrderClosed;
$order->save();
$statusAcceptId = Status::where('name', 'Принят')->first()->id; // получаем Id статуса с именем 'Принят'
$order_user = $order->usersPivot()->where('status_id', $statusAcceptId)->first()->pivot->id; // Получаем id мастера
$feedback = new Rating(); // создаем новый отзыв
$feedback->description = $request->description;
$feedback->order_user = $order_user;
$feedback->rating = $request->rating;
$feedback->timestamps;
$feedback->save();
$master = new User();
foreach($order->users as $item) { // получаем модель мастера
if($item->id == $order->usersPivot()->where('status_id', $statusAcceptId)->first()->pivot->user_id)
$master = $item;
}
/*Формируем рейтинг самому пользователю по среднему баллу*/
$arrayOrderUser = DB::table('order_user')->where('user_id', $master->id)->where('status_id', $statusAcceptId)->pluck('id'); // выбираем в связанной таблице order_user все значения, где пользователь был выбран в качестве мастера
$arrayFeedback = DB::table('rating_order')->whereIn('order_user', $arrayOrderUser)->pluck('rating'); // получаем все отзывы к этому мастеру и выбираем только колонку с рейтингом
$ratingUser = null;
foreach($arrayFeedback as $item) { // перебираем все рейтинги
$ratingUser += $item; // складываем между собой их
}
$ratingUser != 0 ? $ratingUser /= $arrayFeedback->count() : $ratingUser = 0;// получаем средний балл и присваиваем пользователю
$master->rating = $ratingUser;
$master->save();
return Response::json('Спасибо что оставили отзыв');
}
}
<file_sep>/app/Http/Controllers/AdminController.php
<?php
namespace App\Http\Controllers;
use App\Order;
use App\OrderUser;
use App\Status;
use App\User;
use Illuminate\Http\Request;
class AdminController extends Controller
{
public function index() {
$countUsers = User::all()->count();
$countOrders = Order::all()->count();
$countDoneOrders = OrderUser::where('status_id', Status::where('name', 'Принят')->first()->id)->whereHas('order', function($q){
$q->where('status_id', Status::where('name', 'Закрыт')->first()->id);
})->get()->count();
return view('admin.index', compact(['countUsers', 'countOrders', 'countDoneOrders']));
}
}
<file_sep>/app/Http/Controllers/api/auth/AuthController.php
<?php
namespace App\Http\Controllers\api\auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
class AuthController extends Controller
{
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'login' => 'required',
'password' => '<PASSWORD>'
]);
if ($validator->fails()) return response()->json($validator->errors()); // если не прошел валидацию, выдать ошибку
$userHashedPassword = User::where('login', $request->login)->first()->password;
if (Hash::check($request->password, $userHashedPassword)) {
$user = User::where('login', $request->login)->with('city','country', 'gender')->first();
// dd($user);
if (!is_null($user)) {
$user->update(['api_token' => Str::random()]);
return Response::json($user)->setStatusCode(200, 'Successful authorization');
}
}
return Response::json('Неверный логин или пароль.')->setStatusCode(400);
}
}
<file_sep>/app/Http/Middleware/ApiAccess.php
<?php
namespace App\Http\Middleware;
use Closure;
use App\User;
use Illuminate\Support\Facades\Response;
class ApiAccess
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($request->route()->uri == 'api/register') return $next($request); // если маршрут на регистрацию, то не проверять токен
if ($request->route()->uri == 'api/login') return $next($request); // если маршрут на регистрацию, то не проверять токен
if ($request->route()->uri == 'api/check-session') return $next($request); // если маршрут на регистрацию, то не проверять токен
$user = User::where('api_token', $request->api_token)->get();
if (!$user->isEmpty())
return $next($request);
return response()->json('Unauthorization', 401);
}
}
<file_sep>/routes/web.php
<?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('index');
});
//Route::get('/email', function () {
// return view('mails.email-confirmation');
//});
Auth::routes();
Route::get('/logout', function () {
auth()->logout();
return redirect('/');
})->middleware('auth');
Route::group(['prefix'=>'admin', 'middleware'=>['auth', 'admin']], function() {
Route::get('/', 'AdminController@index')->name('admin');
/*Маршруты для стран*/
Route::resource('/country', 'CountryController');
/*Маршруты для городов*/
Route::resource('/city', 'CityController');
/*Маршруты для категорий*/
Route::resource('/category', 'CategoryController');
});
Route::group(['prefix'=>'profile', 'middleware'=>['auth']], function(){
/*Профиль*/
Route::get('/', 'ProfileController@index')->name('profile');
Route::post('/save', 'ProfileController@save')->name('profile_save');
Route::post('/upload-profile-image', 'ProfileController@uploadImage')->name('upload-profile-image');
Route::post('/add-role', 'ProfileController@addRole')->name('add-role-user');
Route::post('/del-role', 'ProfileController@delRole')->name('del-role-user');
Route::get('/get-role', 'ProfileController@getRole')->name('get-role-user');
Route::get('/get-countries', 'ProfileController@getCountries');
Route::get('/get-cities/{id}', 'ProfileController@getCities');
Route::get('/get-user-country-city', 'ProfileController@getCountryCity');
/*Изменение пароля*/
Route::post('/change-password', 'ProfileController@changePassword')->name('change-password');
/*Порфтолио*/
Route::group(['prefix'=>'portfolio'],function(){
Route::get('/','PortfolioController@index')->name('portfolio');
Route::post('/new', 'PortfolioController@newElement')->name('add-new-element-portfolio');
Route::delete('/delete/{id}', 'PortfolioController@deleteElement')->name('delete-elem-portfolio');
});
/*Подтверждение E-mail*/
Route::get('/request-confirmation-email', "ConfirmationEmailController@request")->name('request-confirmation-email')->middleware('checkUserConfirmedEmail');
Route::post('/send-confirmation-email', "ConfirmationEmailController@sendEmail")->name('send-confirmation-email');
Route::get('/confirm-email/{user}/{token}', "ConfirmationEmailController@confirm")->name('confirm-email')->middleware(['except'=>'auth']);
/*Удаление аккаунта*/
Route::delete('/delete-account', 'ProfileController@deleteAccount')->name('delete-account');
});
/*Отображение страниц пользователя и все что с ними связано*/
Route::group(['prefix'=>'user', 'middleware'=>['auth']],function(){
Route::get('/{id}', 'UserController@user')->name('user-page');
Route::get('/{id}/portfolio', 'UserController@extendUserPortfolio')->name('extend-user-portfolio');
/*Страница со своими заказами*/
Route::get('orders/my-orders/', 'OrderController@myOrderIndex')->name('my-orders');
Route::get('orders/my-orders/for-execution', 'OrderController@myOrdersForExecution')->name('my-orders-for-execution');
});
/*Заказы*/
Route::get('/orders/{category?}', 'OrderController@index')->name('orders');
Route::post('/orders/search-order/search', 'OrderController@search')->name('orders-search');
Route::group(['prefix'=>'orders', 'middleware'=>['auth']], function(){
Route::get('/new/add', 'OrderController@add')->name('add-order');
Route::post('/add/save', 'OrderController@save')->name('save-order');
Route::get('/{id}/more','OrderController@indexMore')->name('order-more');
Route::delete('/{order}/delete','OrderController@destroyOrder')->name('destroy-order');
Route::post('/{order}/close', 'OrderController@closeOrder')->name('close-order');
/*Отызывы*/
Route::get('/{order}/feedback/create', 'FeedbackController@create')->name('feedback-create');
Route::post('/{order}/feedback/store', 'FeedbackController@store')->name('feedback-store');
Route::get('/feedback/not-responded', 'FeedbackController@notResponded')->name('feedback-not-responded');
Route::group(['prefix'=>'order-master'], function() {
Route::post('{orderid}/add/{userid}', 'OrderUserController@add')->name('add-user-order');
Route::post('{order}/accept-master/{master}', 'OrderUserController@acceptMaster')->name('accept-master-order');
Route::get('/get-users', 'OrderUserController@getUsers')->name('get-users-order');
});
});<file_sep>/database/migrations/2014_10_12_000000_create_users_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id')->unsigned();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('patronymic')->nullable();
$table->bigInteger('gender_id')->unsigned()->nullable();
$table->date('birthday')->nullable();
$table->string('phone_number')->nullable();
$table->string('email')->unique();
$table->string('login');
$table->string('password');
$table->bigInteger('country_id')->unsigned()->nullable();
$table->bigInteger('city_id')->unsigned()->nullable();
$table->string('image_profile')->nullable();
$table->float('rating')->nullable();
$table->boolean('is_confirmed_email')->default(false);
$table->string('confirmed_email_token')->nullable();
$table->string('api_token')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
<file_sep>/app/Http/Controllers/api/CityController.php
<?php
namespace App\Http\Controllers\api;
use App\City;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Response;
class CityController extends Controller
{
public function all() {
$cities = City::all();
return Response::json($cities);
}
}
|
f0059de717545272101f470bfbd46e45bfe20687
|
[
"JavaScript",
"Markdown",
"PHP"
] | 33 |
PHP
|
exlosir/WebServices
|
b69794193fd97f0cab5da77ba3c7688f8413fc20
|
2cbf6233c38d0d9e2827fe6104524d95aa53ba40
|
refs/heads/master
|
<file_sep><?php
require "./vendor/autoload.php";
class BaseModel
{
/**
* @var string Collection name
*/
protected $collectionName;
/**
* @var MongoDB\Client Connection
*/
protected $client;
/**
* @var DataBase MongoDB Database
*/
protected $db;
/**
* @var Collection the collection
*/
protected $collection;
/**
* @var array Valid fields
*/
protected $fields;
public function __construct($collectionName)
{
$config = array();
include "config.php";
$this->client = new MongoDB\Client($config['uri']);
$this->db = $this->client->selectDatabase($config['db']);
$this->collectionName = $collectionName;
$this->collection = $this->db->selectCollection($collectionName);
}
/**
* Insert data
* @param array $data
* @return array Data result
*/
public function create(array $data)
{
$now = date("Y-m-d H:i:s");
$data['criacao'] = $now;
$data['alteracao'] = $now;
$data['_id'] = $this->getNextSequence($this->collectionName);
$result = $this->collection->insertOne($data);
return array('id' => $result->getInsertedId(), 'insertedCount' => $result->getInsertedCount());
}
/**
* @param int $order (Opcional) ordenação
* @param array $filters filtros
*/
public function read($limit = 0, $order = array(), $filters = array())
{
$options = array();
if ($limit != 0)
{
$options['limit'] = $limit;
}
if ( ! empty($order))
{
$options['sort'] = $this->buildOrderings($order);
}
$result = $this->collection->find(
$filters,
$options
);
return iterator_to_array($result);
}
/**
* Formata todas as ordenações para o MongoDB
* ASC = 1
* DESC = -1
*/
protected function buildOrderings($params)
{
$result = array_map(function($v){
$orders = array('asc' => 1, 'desc' => -1);
return isset($orders[$v]) ? $orders[$v] : 1;
}, $params);
return $result;
}
/**
* @param string $id Document ID
* @param array $data
*/
public function update($id, array $data)
{
$data['alteracao'] = date("Y-m-d H:i:s");
$result = $this->collection->updateOne(
array('_id' => (int) $id),
array('$set' => $data));
return array('matchedCount' => $result->getMatchedCount(), 'modifiedCount' => $result->getModifiedCount());
}
/**
* @param string $id document id
*/
public function delete($id)
{
$result = $this->collection->deleteOne(array('_id' => (int) $id));
return array('deletedCount' => $result->getDeletedCount());
}
/**
* Cria um valor auto-increment para a collection
* @param string $nameId Nome da collection
* @return string Valor sequencial gerado
*/
protected function getNextSequence($nameId)
{
$retval = $this->db->_counters->findOneAndUpdate(
array('_id' => $nameId),
array('$inc' => array("seq" => 1)),
array("new" => true, "upsert" => true, 'returnDocument'=> MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER)
);
return $retval['seq'];
}
}
<file_sep><?php
require "AbstractCRUD.php";
class Cidades extends AbstractCRUD
{
public function __construct()
{
parent::__construct('cidade');
$fields = array('nome', 'estadoId', 'criacao', 'alteracao');
$this->setFields($fields);
}
}
<file_sep><?php
/**
* Controller padrão para um CRUD
*
*/
include "./models/BaseModel.php";
abstract class AbstractCRUD
{
/**
* @var BaseCRUD objeto base das operações CRUD
*/
protected $db;
/**
* @var array Array associativo com os campos permitidos
*/
protected $fields;
public function __construct($collection)
{
$this->db = new BaseModel($collection);
}
public function setFields(array $fields)
{
$this->fields = $fields;
}
/**
* Metodo para Listagem conforme parametros
* @param array $parameters Parametros da listagem
* @return array array associativo que contem a listagem
*/
public function getList($parameters)
{
$params = $this->formatParametersList($parameters);
$list = $this->db->read($params['limit'], $params['order'], $params['filters']);
return $list;
}
/**
* @param array $parameters Parametros a serem formatados e filtrados
* @return array array associativo com os parametros necessarios
*/
protected function formatParametersList($parameters)
{
$limit = (isset($parameters['limit']) && is_numeric($parameters['limit'])) ? (int) $parameters['limit'] : 0;
unset($parameters['limit']);
$order = (isset($parameters['orderby']) && is_array($parameters['orderby'])) ? $this->filter($parameters['orderby']) : array();
unset($parameters['orderby']);
$filters = $this->filter($parameters);
return array('limit'=>$limit, 'order'=> $order, 'filters'=>$filters);
}
/**
* Operação Create do CRUD
* @param array $data array associativo com os dados a serem inseridos
* @return array resultado da operação
*/
public function postCreate($data)
{
$array = json_decode($data, TRUE);
$filtered = $this->filterFill($this->fields, $array, '');
return $this->db->create($filtered);
}
/**
* @param int $id ID do documento
* @param array $data os dados num array associativo
* @return array resultado
*/
public function putUpdate($id, $data)
{
$array = json_decode($data, TRUE);
$filtered = $this->filter($array);
$result = $this->db->update($id, $filtered);
return $result;
}
/**
* @param int $id ID do documento que vai ser eliminado
* @return array Resultado
*/
public function deleteObject($id)
{
$result = $this->db->delete($id);
return $result;
}
/**
* Filtra permitindo somente os campos que foram especificados
* @param array $array array asociativo a ser filtrado
* @return array array filtrado
*/
protected function filter(array $array)
{
$fields = $this->fields;
$filtered = array_filter($array, function($key) use ($fields){
return in_array($key, $fields);
}, ARRAY_FILTER_USE_KEY);
return $filtered;
}
/**
* Filtra e preenche com um valor default o array de dados
* @param array $items keys permitidos
* @param array $array array asociativo que vai ser filtrado
* @param mixed $default Valor default caso a key não existir no array asociativo
* @return array array filtrado
*/
protected function filterFill($items, array $array, $default = NULL)
{
$return = array();
is_array($items) OR $items = array($items);
foreach ($items as $item)
{
$return[$item] = array_key_exists($item, $array) ? $array[$item] : $default;
}
return $return;
}
}
<file_sep><?php
require "AbstractCRUD.php";
class Estados extends AbstractCRUD
{
public function __construct()
{
parent::__construct('estado');
$fields = array('nome', 'abreviacao', 'criacao', 'alteracao');
$this->setFields($fields);
}
}
<file_sep><?php
$config = array(
'uri' => 'mongodb://127.0.0.1/',
'db' => 'db_davidt',
);
<file_sep># Detalhes
* Servidor Apache
* PHP >= 5.6
* Slim Framework 2.6.3
### Banco de dados
O nome do banco de dados é *db_davidt*. Para alterar o nome do banco de dados editar o arquivo **models/config.php**
# EndPoints
## Listagens
```
GET api/{collection}?limit={int}&orderby[{field1}]={asc|desc}&orderby[{field2}]=[asc|desc]&field3=YYY&field4=ZZZ
```
Substituir {collection} por *cidades* ou *estados*
Podem ser pasados na URL os seguintes parâmetros:
* limit: O limite de objetos
* orderby: Permite a ordenação por mais de um campo de forma ascendente(asc) ou descendente(desc).
* O resto dos parâmetros são considerados filtros (campo e valor).
**Exemplo:**
```
GET api/cidades?limit=15&orderby[criacao]=asc&orderby[nome]=desc&estadoId=1
```
**Response**
```
[{"id": "2", "nome": "Niteroi", "estadoId": "1", "criacao":"2018-06-20 22:23:10", "alteracao": "2018-06-20 22:23:10"}, {...}, {...}, {...}, ...]
```
## Inserir
```
POST api/{collection}
```
Substituir {collection} por *cidades* ou *estados*
**Request Body (cidades)**
```
{"nome": "Niteroi", "estadoId": "1"}
```
**Request Body (estados)**
```
{"nome": "<NAME>", "abreviacao": "SP"}
```
**Response**
Retorna o id do novo documento e a quantidade de documentos inseridos (Sendo que a operação permite uma inserção por request o valor insertedCount vai tomar o valor de 1 se for inserido corretamente ou 0 em caso contrario).
```
{"id": "2", "insertedCount": "1"}
```
## Alterar
```
PUT api/{collection}/{_id}
```
Substituir {collection} por *cidades* ou *estados*
Substituir {_id} por o id do documento
**Reques Body (cidades)**
```
{"nome": "Niteroi", ...}
```
**Reques Body (estados)**
```
{"nome": "Acre", ...}
```
**Response**
Retorna a quantidade de documentos que coincidiram com o criterio da busca(matchedCount) e a quantidade de documentos alterados (modifiedCount).
```
{"matchedCount": "1", "modifiedCount": "0"}
```
## Excluir
```
DELETE api/{collection}/{_id}
```
Substituir {collection} por *cidades* ou *estados*
Substituir {_id} por o id do documento
**Response**
Retorna a quantidade de documentos excluidos(deletedCount).
```
{"deletedCount": "1"}
```
# Para POST, PUT
*Header request*
```
Content-Type: application/json; charset=utf-8
```
<file_sep><?php
/**
* Simmple REST
* Slim 2 + MongoDB
*
* PHP >= 5.6
*
* @author <NAME> <<EMAIL>>
*
*/
require 'Slim/Slim.php';
require 'includes/functions.php';
use \Slim\Slim as Slim;
Slim::registerAutoloader();
date_default_timezone_set('America/Sao_Paulo');
$app = new Slim();
$app->get('/', function (){
echo "Home";
});
/**
* GET api/{collection}/?limit={int}&orderby[{field1}]={asc|desc}&orderby[field2]=[asc|desc]&field3=YYY&field4=ZZZ
*
* Exemplo:
* GET api/cidades/?limit=15&orderby[field1]=asc&orderby[field2]=desc&fieldY=valorY&fieldZ=valorZ
*/
$app->get('/api/:controller', function ($controller) use ($app) {
$ctrl = createController($app, $controller);
$function = 'getList';
if (is_callable(array($ctrl, $function)))
{
$time = time();
$app->lastModified($time);
$app->expires($time + 300);
$params = $app->request->get();
response($app, $ctrl->$function($params));
} else
{
$app->notFound();
}
});
/**
* POST api/{collection}
* BODY
* {"field1": "zz", "field2": "yy"}
*
*/
$app->post('/api/:controller', function($controller) use ($app){
$ctrl = createController($app, $controller);
$function = 'postCreate';
if (is_callable(array($ctrl, $function)))
{
$data = $app->request->getBody();
response($app, $ctrl->$function($data));
} else
{
$app->notFound();
}
});
/**
* PUT api/{collection}/{_id}
* BODY
* {"field1": "yyy", "field2": "zzz"}
*
* Exemplo:
* PUT api/cidades/22
* BODY
* {"nome": "Campinas", "estadoId": "2"}
*/
$app->put('/api/:controller/:id', function($controller, $id) use ($app){
$ctrl = createController($app, $controller);
$function = 'putUpdate';
if (is_callable(array($ctrl, $function)))
{
$data = $app->request->getBody();
response($app, $ctrl->$function($id, $data));
} else
{
$app->notFound();
}
});
/**
* DELETE api/{collection}/{_id}
*
* Exemplo:
* DELETE api/cidades/123
*/
$app->delete('/api/:controller/:id', function($controller, $id) use ($app){
$ctrl = createController($app, $controller);
$function = 'deleteObject';
if (is_callable(array($ctrl, $function)))
{
response($app, $ctrl->$function($id));
} else
{
$app->notFound();
}
});
$app->run();
<file_sep><?php
/**
* @param \Slim\Slim $app Instancia da aplicação
* @param array $data Array asociativo da resposta
*/
function response(\Slim\Slim $app, $data)
{
$app->response->headers->set('Content-Type', 'application/json; charset=utf-8');
echo json_encode($data);
}
/**
* @param \Slim\Slim $app Instancia da aplicação
* @param string $controller Nome do controller
*/
function createController(\Slim\Slim $app, $controller)
{
$file = "./controllers/".$controller.".php";
if (file_exists($file))
{
require $file;
$class = ucfirst($controller);
if (class_exists($class))
{
return new $class();
}
$app->notFound();
}
$app->notFound();
}
|
4478c0dfa3a1869d73226a253697bb34c0a62ada
|
[
"Markdown",
"PHP"
] | 8 |
PHP
|
davicotico/Slim2-MongoDB-REST-Simple-CRUD
|
426ebbc3a95766fa9641c3f893fabedc91675f6b
|
956ac476839763e3c63eb285d82a1b0aea95c0ca
|
refs/heads/master
|
<repo_name>vladutcoman/AngularDemo<file_sep>/01-ngrx-basics-start/src/app/auth/store/auth.reducers.ts
import * as AuthActions from './auth.actions'
import { SIGNIN, LOGOUT } from './auth.actions';
export interface State {
token: string,
authentificated: boolean
}
const initialState: State = {
token: null,
authentificated: false
};
export function authReducer(state = initialState, action) {
switch(action.type) {
case (AuthActions.SIGNUP):
case (AuthActions.SIGNIN):
return {
...state,
authentificated: true
};
case (AuthActions.LOGOUT):
return {
...state,
token: null,
authentificated: false
};
case (AuthActions.SET_TOKEN):
return {
...state,
token: action.payload
};
default:
return state;
}
}<file_sep>/test-app/src/app/shared/data-storage.service.ts
import { Injectable } from "@angular/core";
import { HttpClient } from '@angular/common/http';
import { RecipeService } from "../recipes/recipe.service";
import { AuthService } from "../auth/auth.service";
@Injectable()
export class DataStorageService {
constructor(private http: HttpClient,
private recipeService: RecipeService,
private authService: AuthService) {}
storeRecipe() {
const token = this.authService.getToken();
return this.http.put('https://angulardemo-d33da.firebaseio.com/recipes.json?auth=' + token, this.recipeService.getRecipes());
}
}<file_sep>/test-app/src/app/core/header/header/header.component.ts
import { Component, OnInit } from '@angular/core';
import { DataStorageService } from 'src/app/shared/data-storage.service';
import { AuthService } from 'src/app/auth/auth.service';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
constructor(private dataStorageServiceL: DataStorageService, public authService: AuthService) { }
ngOnInit() {
}
onSaveData() {
this.dataStorageServiceL.storeRecipe()
.subscribe((response: Response) => {
console.log(response);
});
}
onLogout() {
this.authService.logout();
}
}
<file_sep>/practice-app/src/app/servers/servers.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-servers',
templateUrl: './servers.component.html',
styleUrls: ['./servers.component.css']
})
export class ServersComponent implements OnInit {
allowNewServe: boolean = false;
serverCreationStatus = 'No server created!';
serverName: string = 'Test';
serverCreated: boolean = false;
servers: string[] = ['Server1', 'Server2'];
show: boolean = true;
logs: number[] = [];
constructor() {
setTimeout(() => {
this.allowNewServe = true;
}, 2000);
}
ngOnInit() {
}
onCreateServer() {
this.serverCreated = true;
this.servers.push(this.serverName);
this.serverCreationStatus = 'Server was created! Name is: ' + this.serverName;
}
onUpdateName(event: any) {
this.serverName = event.target.value;
}
onDisplayDetails() {
this.logs.push(this.logs.length + 1);
this.show = !this.show;
}
getBColor(log) {
return log> 4 ? 'blue' : 'transparent';
}
}
|
8b65273b2a78c786e750b0d33724a32b38eb70c0
|
[
"TypeScript"
] | 4 |
TypeScript
|
vladutcoman/AngularDemo
|
2c7787b2cb6cf7bbae130c5dc6884cba19e7276d
|
336091aa4d39163bf9c8baa11a5af1e07e5ed791
|
refs/heads/master
|
<file_sep>class AddSettnigsToUsers < ActiveRecord::Migration
def change
add_column :users, :bg_color, :string
add_column :users, :lk_color, :string
end
end
<file_sep>class Post < ActiveRecord::Base
@@reply_to_regexp = /\A@([^\s]*)/
@@image_link = /.(gif|jpe?g|png)$/
@@youtube_link = /\A(https:)\/\/(www.youtube.com)\/(watch)/
#attr_accessible :content, :to
belongs_to :user
belongs_to :to, class_name: "User"
has_many :comments, foreign_key: "parent_post", dependent: :destroy
default_scope -> { order('created_at DESC') }
after_initialize :worst_idea_ever
before_save :start
# Возвращает посты от пользователей, за которыми следует пользователь
scope :from_users_followed_by, lambda { |user| followed_by(user) }
# аналогично, но только реплики
scope :from_users_replies, lambda { |user| followed_by_replies(user) }
validates :content, presence: true, length: { maximum: 200 }
validates :user_id, presence: true
validates :attachment, length: { maximum: 100 }
private
def self.followed_by(user)
followed_ids = %(SELECT followed_id FROM relationships
WHERE follower_id = :user_id)
where("user_id IN (#{followed_ids}) OR user_id = :user_id",
{ :user_id => user })
end
def self.followed_by_replies(user)
where(to_id: user, seen: false)
end
def start
extract_in_reply_to
#other
end
def extract_in_reply_to
if match = @@reply_to_regexp.match(content)
user = User.find_by_login(match[1])
if user
self.content = self.content.gsub("@#{user.login}","")
self.to=user
end
end
end
def worst_idea_ever
if match = @@reply_to_regexp.match(content)
self.seen = false
else
self.seen = true
end
if self.attachment
if @@image_link.match(self.attachment)
self.at_type = 1;
elsif @@youtube_link.match(self.attachment)
self.at_type = 2;
else
self.at_type = 3;
end
else
self.at_type = 0;
end
end
end
<file_sep>class User < ActiveRecord::Base
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i # У меня была проблема и я решил использовать регэкспы чтобы её решить.
VALID_LOGIN_REGEX = /\A[A-Za-z]+[A-Za-z-._\d]+[A-Za-z\d]\z/i # Теперь у меня две проблемы. И одна из них - тупой юмор.
has_many :posts, dependent: :destroy
has_many :comments, foreign_key: "parent_user"
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
has_many :replies, foreign_key: "to_id", class_name: "Post"
has_attached_file :avatar, default_url: "gravatar"
before_save { self.email = email.downcase }
after_initialize :def_values
before_create :create_remember_token
validates :login, presence: true,
format: { with: VALID_LOGIN_REGEX },
length: { within: 6..25},
uniqueness: { case_sensitive: true }
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
validates :bg_color, length: { is: 7 }
validates :lk_color, length: { is: 7 }
validates :hl_color, length: { is: 7 }
validates_attachment :avatar, :content_type => {content_type: /\Aimage\/.*\Z/},
:size => { less_than: 1.megabyte}
has_secure_password
def User.new_remember_token
SecureRandom.urlsafe_base64
end
def User.encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
def feed
Post.from_users_followed_by(self)
end
def news
Post.from_users_replies(self)
end
def following?(other_user)
relationships.find_by(followed_id: other_user.id)
end
def follow!(other_user)
relationships.create!(followed_id: other_user.id)
end
def unfollow!(other_user)
relationships.find_by(followed_id: other_user.id).destroy!
end
def self.find_by_login(login_name)
all = where(login: login_name)
return nil if all.empty?
all.first
end
private
def def_values
self.bg_color ||= '#FFFFFF'
self.lk_color ||= '#99CCCC'
self.hl_color ||= '#99CCCC'
end
def create_remember_token
self.remember_token = User.encrypt(User.new_remember_token)
end
end<file_sep>module UsersHelper
def avatar_for(user)
gravatar_id = Digest::MD5::hexdigest(user.email)
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
if user.avatar.url != "gravatar"
image_tag(user.avatar.url, class: "avatar")
else
image_tag(gravatar_url, class: "avatar")
end
end
end<file_sep>class UsersController < ApplicationController
before_action :signed_in_user,
only: [:index, :edit, :update, :destroy, :ssettings, :following, :followers]
before_action :correct_user, only: [:edit, :update, :ssettings]
before_action :admin_user, only: :destroy
respond_to :html, :json
def new
@user = User.new
respond_modal_with @user
end
def create
@user = User.new(user_params)
if @user.save
sign_in @user
flash[:success] = "Welcome to the Sample App!"
redirect_to @user
else
render 'new'
end
end
def index
@users = User.paginate(page: params[:page])
end
def show
@user = User.find(params[:id])
@posts = @user.posts.paginate(page: params[:page])
end
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
def ssettings
@user = User.find(params[:id])
select_style
if up8(:bg_color) && up8(:lk_color) && up8(:hl_color)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted."
redirect_to users_url
end
def following
@title = "Following"
@user = User.find(params[:id])
@users = @user.followed_users.paginate(page: params[:page])
render 'show_follow'
end
def followers
@title = "Followers"
@user = User.find(params[:id])
@users = @user.followers.paginate(page: params[:page])
render 'show_follow'
end
private
def user_params
params.require(:user).permit(:login, :email, :password,
:password_confirmation, :avatar)
end
def select_style
case params[:style_type]
when "1"
params[:bg_color] = "#FFFFCC" #background sunny
params[:lk_color] = "#FFCC00" #link sunny
params[:hl_color] = "#FFCC33" #hover sunny
when "2"
params[:bg_color] = "#FFDDFF" #background amaranth
params[:lk_color] = "#CC99CC" #link amaranth
params[:hl_color] = "#CC33FF" #hover amaranth
when "3"
params[:bg_color] = "#FFDDDD" #background blood
params[:lk_color] = "#CC6666" #link blood
params[:hl_color] = "#993333" #hover blood
when "4"
params[:bg_color] = "#DDDDFF" #background depth
params[:lk_color] = "#6666FF" #link depth
params[:hl_color] = "#3300FF" #hover depth
when "5"
params[:bg_color] = "#DDEEFF" #background sky
params[:lk_color] = "#66CCFF" #link sky
params[:hl_color] = "#66FFFF" #hover sky
when "6"
params[:bg_color] = "#DDFFDD" #backgroundjungle
params[:lk_color] = "#66CC66" #link jungle
params[:hl_color] = "#00CC00" #hover jungle
when "50"
params[:bg_color] = "#CCCCCC" #background shades
params[:lk_color] = "#999999" #link shades
params[:hl_color] = "#666666" #hover shades
when "8"
params[:bg_color] = "#DDFFFF" #background ice
params[:lk_color] = "#55EEBB" #link ice
params[:hl_color] = "#00EEBB" #hover ice
when "9"
params[:bg_color] = "#CC00FF" #background madness
params[:lk_color] = "#660099" #link madness
params[:hl_color] = "#330033" #hover madness
when "10"
params[:bg_color] = "#969696" #background karkat
params[:lk_color] = "#FFFFFF" #link karkat
params[:hl_color] = "#CCCCCC" #hover karkat
when "11"
params[:bg_color] = "#FFFFFF" #background blackandwhite
params[:lk_color] = "#111111" #link blackandwhite
params[:hl_color] = "#333333" #hover blackandwhite
else
params[:bg_color] = "#FFFFFF" #background normal
params[:lk_color] = "#44FFFF" #link normal
params[:hl_color] = "#99FFFF" #hover normal
end
end
def up8(sype) #что бы сократить размеры кода
@user.update_attribute(sype, params[sype])
end
# Before filters
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
<file_sep>class AddLinkHoverToUsers < ActiveRecord::Migration
def change
add_column :users, :hl_color, :string
end
end
<file_sep>Тестовое задание.
Если честно, больше нечего сказать.<file_sep># Be sure to restart your server when you modify this file.
AkaTwitter::Application.config.session_store :cookie_store, key: '_aka_twitter_session'
<file_sep>class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
validates :content, presence: true,
length: { maximum: 70}
end
<file_sep>class CommentsController < ApplicationController
before_action :signed_in_user
def create
@post = Post.find(params[:comment][:current_id])
@comment = @post.comments.create(comment_params)
@comment.parent_user = current_user.id
@comment.parent_post = @post.id
if @comment.save
flash[:success] = "Comment added"
redirect_to @post
else
flash[:error] = "Smthing wrong"
redirect_to @post
end
end
def destroy
@comment.destroy
end
private
def comment_params
params.require(:comment).permit(:content)
end
end<file_sep>class StaticPagesController < ApplicationController
before_action :signed_in_user, only: [:clear, :news]
@@reply_to_regexp = /\A@([^\s]*)/
def home
if signed_in?
@post = current_user.posts.build
@feed_items = current_user.feed.paginate(page: params[:page])
end
end
def news
@post = current_user.posts.build
@feed_items = current_user.news.paginate(page: params[:page], per_page: 2)
end
def clear
@news_items = current_user.news
@news_items.each do |item|
item.update_attribute(:seen, true)
end
redirect_to root_path
end
def help
end
def about
end
end
<file_sep>class AddToToPost < ActiveRecord::Migration
def change
add_column :posts, :to_id, :integer
end
end
<file_sep>class AddAttachmentToPosts < ActiveRecord::Migration
def change
add_column :posts, :attachment, :string
add_column :posts, :at_type, :int
end
end
<file_sep>module PostsHelper
def embed(url)
youtube_id = url.split("=").last
content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{youtube_id}")
end
def link(url_link)
begin
object = LinkThumbnailer.generate(url_link)
render partial: 'shared/site_thumbnail', locals: { feed_item: object }
rescue
link_to(url_link)
end
end
end
|
e761547fa33a01282a4ea6ee431870d75f16314c
|
[
"Markdown",
"Ruby"
] | 14 |
Ruby
|
quantumInverter/aka_twitter
|
835b7d55879b1723dce96c1a373f1fd68a035ad6
|
29e5aee1d281551df66a37261e1150fe45612265
|
refs/heads/master
|
<file_sep>let MyController = function ($scope) {
$scope.likeCount = 0;
$scope.word = 'likes';
$scope.likeClick = function () {
$scope.likeCount = $scope.likeCount + 1;
if ($scope.likeCount === 1) {
$scope.like = 'like';
} else {
$scope.like = 'likes';
}
};
};
MyController.$inject = ['$scope'];
export default MyController;
<file_sep>import angular from 'angular';
import MyController from './controllers/mycontroller';
angular.module('app', [])
.controller('MyController', MyController);
|
1625ef85232bfc309c2c957fe00c846d26c05851
|
[
"JavaScript"
] | 2 |
JavaScript
|
JRob1991/Assignment-23
|
5ba7deb153f14ad3c9526291713b10b10f43ef38
|
8bd7da2984f19af37f514683ede4a25380dfcefd
|
refs/heads/master
|
<repo_name>itunuworks/cohort-xx-day-1<file_sep>/README.md
# cohort-xx-day-1
<file_sep>/tests/oopTests.js
'use strict';
require('../apps/oop.js');
describe("Testing for OOP functionality in a hierachy of Classes, ", function(){
var boeing747 = new FixedWingAircraft('Gas Turbine', 'Wings', 4);
var bell204 = new RotaryWingAircraft('Gas Turbine', 'Overhead', 1);
var TBM850 = new FixedWingAircraft('TurboProp', 'Nose', 1);
var TB9 = new FixedWingAircraft('Internal Combustion', 'Nose', 1);
var B58 = new FixedWingAircraft('Internal Combustion', 'Wings', 2);
var fixed = new Aircraft('Fixed');
var rotary = new Aircraft ('Rotary');
it("An initialized 'Aircraft' should be of object type.", function(){
expect(typeof(fixed)).toBe(typeof({}));
expect(typeof(rotary)).toBe(typeof({}));
})
it("An initialized 'Aircraft' should be an instance of class Aircraft.", function(){
expect(fixed instanceof(Aircraft)).toBeTruthy();
expect(rotary instanceof(Aircraft)).toBeTruthy();
})
describe("Confirm the inheritance hierachy using 'instanceOf', ", function(){
it("An initialized 'FixedWingAircraft' is an instance of 'Aircraft'", function(){
expect(TBM850 instanceof(Aircraft)).toBeTruthy();
})
it("An initialized 'FixedWingAircraft' is an instance of 'FixedWingAircraft'", function(){
expect(TBM850 instanceof(FixedWingAircraft)).toBeTruthy();
})
it("An initialized 'RotaryWingAircraft' is an instance of 'Aircraft'", function(){
expect(bell204 instanceof(Aircraft)).toBeTruthy();
})
it("An initialized 'RotaryWingAircraft' is an instance of 'RotaryWingAircraft'", function(){
expect(bell204 instanceof(RotaryWingAircraft)).toBeTruthy();
})
})
describe("Confirm functionality of class prototypes.", function(){
it("An initialized FixedWingAircraft should connect with the totalLandingCycles property, ", function (){
expect(boeing747.totalLandingCycles).toBeDefined();
})
it("An initialized RotaryWingAircraft should NOT connect with the totalLandingCycles property, ", function (){
expect(bell204.totalLandingCycles).not.toBeDefined();
})
})
describe("Confirm functionality of Aircrafts sub Classes RotaryWingAircraft and FixedWingAircraft", function (){
it("An initialized FixedWingAircraft should have property 'wingConfig' as 'Fixed'.", function(){
expect(TB9.wingConfig).toEqual('Fixed');
})
it("An initialized RotaryWingAircraft should have property 'wingConfig' as 'Rotary'.", function(){
expect(bell204.wingConfig).toEqual('Rotary');
})
})
describe("Confirm polymorphism functioinality.", function(){
it("An initialized Aircraft, whose 'move' method gets called, should return, 'Yeeee!, I am flying'", function(){
expect(fixed.move()).toEqual('Yeeee!, I am flying');
})
it("An initialized FixedWingAircraft, whose 'move' method gets called, should return, 'Feels good taxiing at 450kmph. You wan try??'", function(){
expect(boeing747.move()).toEqual('Feels good taxiing at 450kmph. You wan try??');
})
it("An initialized RotaryWingAircraft, whose 'move' method gets called, should return, 'I am soo hovering at 500 feets. Can you dare??'", function(){
expect(bell204.move()).toEqual('I am soo hovering at 500 feets. Can you dare??');
})
})
})
|
07b6fdc565fe41a005055426f661600125cf7f78
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
itunuworks/cohort-xx-day-1
|
bee581278bf39ab765b15292fabc8b278a83a30c
|
2a463169e7a8aad52939dfea0eae8eb73d51e57e
|
refs/heads/master
|
<file_sep>desc 'This task sends the time report email'
task :send_email => :environment do
ReportMailer.report_email.deliver if Time.now.friday?
end
<file_sep>class ReportMailer < ActionMailer::Base
include JiraQuery
default from: '<EMAIL>'
default reply_to: '<EMAIL>'
def report_email
@start_of_week = (DateTime.now - 7).strftime("%D")
@now = DateTime.now.strftime("%D")
@current_month = Date::MONTHNAMES[Date.today.month]
# devops total hours
devops = [@example = [0,'ProjectLabel']]
devops.each do |t|
CLIENT.Issue.jql("project = 'Project' AND labels = #{example[1]} AND assignee in membersOf('example_jira_user_group')").each do |i|
t[0] += i.aggregatetimespent / 3600 if i.aggregatetimespent
end
end
mail(to: '<EMAIL>', subject: 'Example Time Report - ' + Time.now.strftime("%D"))
end
end
<file_sep>module JiraQuery
options = {
:username => ENV['JIRA_USERNAME'],
:password => ENV['<PASSWORD>'],
:site => ENV['JIRA_SITE'],
:context_path => '',
:auth_type => :basic,
:use_ssl => false
}
CLIENT = JIRA::Client.new(options)
end<file_sep># Be sure to restart your server when you modify this file.
TimeReporter::Application.config.session_store :cookie_store, key: '_time-reporter_session'
<file_sep>== Time reporter
This sends email reports for logged hours in a given Jira project with a given label, every Friday.
How it works:
- There's a rake task in lib/tasks/schedule.rake that grabs a template from mailers/report_mailer and delivers it to some email recipients via sendgrid.
- The task checks if Time.now is Friday, and the hosted version (https://dashboard.heroku.com/apps/time-reporter) uses Heroku's Scheduler to run every day at 12PM PST.
- You can edit the sender, replyto, and recipients list in report_mailer.rb
Setup:
1. git clone
2. change SMTP settings in environment.rb
3. change Jira report config in report_mailer.rb
4. change email addresses in report_mailer.rb
5. change report layout in report_email.html.slim to match your preference
|
1ef24812cad36c134cc40fa34d59c0e888314c4b
|
[
"RDoc",
"Ruby"
] | 5 |
Ruby
|
myarchin/time-reporter
|
c7c808b83147e45a6db14575c8cb5f327e2eeeab
|
21af0a643b30af46c020cce04effc98ea6c538af
|
refs/heads/master
|
<repo_name>vedatyrt/netcet<file_sep>/public/js/client.js
var userInput = null;
var window_focus = true;
var notificationStack = new Array;
var socket = io();
function handleResize() {
$("#chatdiv").height($(window).height() - ($("form").height() + 40));
}
function getUsername() {
while (!userInput) {
userInput = window.prompt("Enter Your Username ", "");
}
socket.emit('connected', userInput);
}
$('form').submit(function() {
if ($('#m').val()) {
var message = {
"user": userInput,
msg: $('#m').val(),
};
socket.emit('chat', message);
$('#m').val('');
}
return false;
});
socket.on('chat', function(message) {
$('#messagesBox').append(getMessageDiv(message, userInput));
if (message.user != userInput)
notifyUser(message);
scroll();
});
socket.on('connected', function(username) {
if (username != userInput)
$('#messagesBox').append('<div><div class="onemessage infomessage" user="' + username + '">' + ' # ' + username + ' geçerken uğradı.' + '</div></div>');
scroll();
});
socket.on('byby', function(username) {
if (username != userInput)
$('#messagesBox').append('<div><div class="onemessage infomessage" user="' + username + '">' + ' # ' + username + ' terketti buraları.' + '</div></div>');
scroll();
});
socket.on('error', function(err) {
alert(err.message);
//if(err.type = "invalidusername")
// getUsername();
});
function getMessageDiv(message, user) {
var clazz = "",
content = "",
divMessage = "";
if (message.user == userInput) {
clazz = "onemessage mymessage";
content = replaceURLWithHTMLLinks(message.msg);
divMessage = '<div align="right" user="' + message.user + '">' + content + ' [' + message.date + ']' + '</div>';
} else {
clazz = "onemessage othersmessage";
content = message.user + ' > ' + replaceURLWithHTMLLinks(message.msg);
divMessage = '<div user="' + message.user + '"> [' + message.date + '] ' + content + '</div>';
}
var divAll = '<div class="' + clazz + '">' + divMessage + '</div>';
return divAll;
}
//source : http://stackoverflow.com/questions/6707476/how-to-find-if-a-text-contains-url-string
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp, "<a href='$1' target='_blank'>$1</a>");
}
function scroll() {
var textdiv = $("#messagesBox");
var chatdiv = $("#chatdiv");
console.log(textdiv.height());
chatdiv.scrollTop(textdiv.outerHeight());
}
function notifyUser(message) {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('8.80 - ' + message.user, {
icon: 'https://raw.githubusercontent.com/agtokty/netcet/master/public/images/netcetlogo.PNG',
body: message.date + " " + message.msg,
});
notification.onclick = function() {
window.focus();
notification.close();
for (var i = 0; i < notificationStack.length; i++)
notificationStack[i].close();
notificationStack = new Array();
};
notificationStack.push(notification);
}
}
$(function() {
handleResize();
window.addEventListener("resize", handleResize);
window.onblur = function() {
window_focus = false;
}
window.onfocus = function() {
window_focus = true;
}
window.onbeforeunload = function() {
socket.emit('byby', userInput);
}
getUsername();
if (Notification.permission !== "granted")
Notification.requestPermission();
});<file_sep>/index.js
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var defaultPort = 881;
if (process.argv.indexOf("-port") != -1) {
var port = process.argv[process.argv.indexOf("-port") + 1];
var p = parseInt(port);
if (!isNaN(p))
defaultPort = p;
}
var path1 = __dirname + '/views/';
var currentUsers = new Array;
app.get('/', function(req, res) {
res.sendFile(path1 + '/index.html');
});
app.use(express.static(path.join(__dirname, 'public')));
io.on('connection', function(socket) {
socket.on('chat', function(msg) {
msg.date = getDate();
io.emit('chat', msg);
});
socket.on('connected', function(username) {
if (currentUsers.indexOf(username) == -1) {
currentUsers.push(username);
io.emit('connected', username);
} else {
io.emit('error', { "type": "invalidusername", "message": "This username already taken : " + username });
}
});
socket.on('byby', function(username) {
console.log(username + " ayrılıyor");
if (currentUsers.indexOf(username) != -1) {
removeUser(username);
io.emit('byby', username);
console.log(username + " ayrıldı");
}
});
});
http.listen(process.env.PORT || defaultPort, function() {
console.log('listening on *:' + defaultPort);
});
function removeUser(username) {
var newUserList = new Array;
for (var i = 0; i < currentUsers.length; i++) {
if (currentUsers[i] != username)
newUserList.push(currentUsers[i]);
}
currentUsers = newUserList;
console.log("currentUsers :" + currentUsers);
}
function getDate() {
var d = new Date();
var h = d.getHours() < 10 ? "0" + d.getHours() : d.getHours();
var m = d.getMinutes() < 10 ? "0" + d.getMinutes() : d.getMinutes();
var s = d.getSeconds() < 10 ? "0" + d.getSeconds() : d.getSeconds();
return h + ":" + m + ":" + s;
}
|
d42884c405a80f32617dee113366aaf39905b58a
|
[
"JavaScript"
] | 2 |
JavaScript
|
vedatyrt/netcet
|
6a528fca88bfaf540b8d6c495138be346d51c19f
|
4700e7f589a0139b3d4a633ab2c76d77a4c1b27d
|
refs/heads/master
|
<repo_name>channdara/chat_chat<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/adapter/ChatRoomListAdapter.kt
package com.mastertipsy.chat_chat.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.model.ChatRoom
import com.mastertipsy.chat_chat.model.User
import kotlinx.android.synthetic.main.item_view_chat_room_list.view.*
class ChatRoomListAdapter(option: FirestoreRecyclerOptions<ChatRoom>, private val user: User) :
FirestoreRecyclerAdapter<ChatRoom, ChatRoomListAdapter.ChatViewHolder>(option) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChatViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_view_chat_room_list, parent, false)
return ChatViewHolder(view, parent.context)
}
override fun onBindViewHolder(holder: ChatViewHolder, position: Int, model: ChatRoom) {
holder.bind(model)
}
inner class ChatViewHolder(private val view: View, private val context: Context) :
RecyclerView.ViewHolder(view) {
fun bind(room: ChatRoom) {
Glide.with(context).load(room.image).into(view.iv_room_image)
view.tv_room_name.text = room.name
view.tv_room_last_message.text = room.lastMessage
view.tv_room_last_active.text = room.lastActive.toDate().toString()
if (room.isRead.toString().contains(user.userID)) {
view.card_view_chat_room_item.setCardBackgroundColor(context.getColor(android.R.color.white))
} else {
view.card_view_chat_room_item.setCardBackgroundColor(context.getColor(R.color.color_secondary))
}
}
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/ui/activity/RegisterActivity.kt
package com.mastertipsy.chat_chat.ui.activity
import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Rect
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Patterns
import android.view.MotionEvent
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
import androidx.appcompat.widget.AppCompatImageButton
import androidx.appcompat.widget.AppCompatImageView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.model.AppConst
import com.mastertipsy.chat_chat.model.User
import com.mastertipsy.chat_chat.presentor.repository.RegisterRepository
import com.mastertipsy.chat_chat.presentor.view.RegisterView
import com.mastertipsy.chat_chat.util.AlertUtil
import com.mastertipsy.chat_chat.util.MediaUtil
import java.io.File
class RegisterActivity : AppCompatActivity(), RegisterView {
companion object {
fun start(context: Context) =
context.startActivity(Intent(context, RegisterActivity::class.java))
}
private lateinit var repo: RegisterRepository
private val layoutBottomSheet by lazy { findViewById<LinearLayout>(R.id.layout_bottom_sheet_media_picker) }
private val layoutCameraPicker by lazy { findViewById<LinearLayout>(R.id.layout_media_picker_camera) }
private val layoutGalleryPicker by lazy { findViewById<LinearLayout>(R.id.layout_media_picker_gallery) }
private val bottomSheet by lazy { BottomSheetBehavior.from(layoutBottomSheet) }
private val ivUserProfile by lazy { findViewById<AppCompatImageView>(R.id.iv_user_profile) }
private val btnBack by lazy { findViewById<AppCompatImageButton>(R.id.btn_back) }
private val btnBottomSheetClear by lazy { findViewById<AppCompatButton>(R.id.btn_bottom_sheet_clear) }
private val btnRegister by lazy { findViewById<AppCompatButton>(R.id.btn_register_send) }
private val etUsername by lazy { findViewById<AppCompatEditText>(R.id.et_register_username) }
private val etPassword by lazy { findViewById<AppCompatEditText>(R.id.et_register_password) }
private val etConfirmPassword by lazy { findViewById<AppCompatEditText>(R.id.et_register_confirm_password) }
private val etEmailAddress by lazy { findViewById<AppCompatEditText>(R.id.et_register_email) }
private val etPhoneNumber by lazy { findViewById<AppCompatEditText>(R.id.et_register_phone_number) }
private var imageUri: Uri? = null
private var imageFile: File? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_register)
repo = RegisterRepository(this, this)
setupListener()
}
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
if (ev?.action == MotionEvent.ACTION_DOWN) {
if (bottomSheet.state == BottomSheetBehavior.STATE_EXPANDED) {
val outRect = Rect()
layoutBottomSheet.getGlobalVisibleRect(outRect)
if (!outRect.contains(ev.rawX.toInt(), ev.rawY.toInt()))
bottomSheet.state = BottomSheetBehavior.STATE_COLLAPSED
}
}
return super.dispatchTouchEvent(ev)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode != Activity.RESULT_OK) return
val uri = if (requestCode == AppConst.GALLERY_CODE) {
data?.data
} else {
imageUri
}
uri?.let {
MediaUtil.compressImage(this, it)?.let { bitmap ->
ivUserProfile.setImageBitmap(bitmap)
imageFile = MediaUtil.createImageFile(this, bitmap)
}
}
bottomSheet.state = BottomSheetBehavior.STATE_COLLAPSED
}
override fun onRegisterSuccess(email: String) {
AlertUtil.showAlertDialog(
this,
getString(R.string.success),
getString(R.string.register_success),
DialogInterface.OnClickListener { dialog, _ ->
dialog.dismiss()
ChatRoomListActivity.startNewTaskClearTask(this, email)
}
)
}
override fun onError(message: String) {
AlertUtil.showAlertDialog(this, getString(R.string.error), message)
}
private fun setupListener() {
btnBack.setOnClickListener { onBackPressed() }
ivUserProfile.setOnClickListener {
if (bottomSheet.state == BottomSheetBehavior.STATE_COLLAPSED)
bottomSheet.state = BottomSheetBehavior.STATE_EXPANDED
}
layoutCameraPicker.setOnClickListener {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
val externalContentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val contentValues = ContentValues().apply {
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
}
imageUri = this.contentResolver.insert(externalContentUri, contentValues)
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(intent, AppConst.CAMERA_CODE)
}
layoutGalleryPicker.setOnClickListener {
val intent = Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI
)
startActivityForResult(intent, AppConst.GALLERY_CODE)
}
btnBottomSheetClear.setOnClickListener {
ivUserProfile.setImageDrawable(getDrawable(R.drawable.ic_user_hint))
imageUri = null
}
btnRegister.setOnClickListener {
if (!isAllDataValidated()) return@setOnClickListener
val user = User(
username = etUsername.text.toString(),
password = <PASSWORD>(),
emailAddress = etEmailAddress.text.toString(),
phoneNumber = etPhoneNumber.text.toString()
)
if (imageFile == null) {
repo.registerUser(user, null)
return@setOnClickListener
}
val uri = Uri.fromFile(imageFile)
repo.registerUser(user, uri)
}
}
private fun isAllDataValidated(): Boolean {
if (etUsername.text.isNullOrEmpty()) {
etUsername.error = getString(R.string.error_required_username)
etUsername.requestFocus()
return false
}
if (etUsername.text.toString().length > 64) {
etUsername.error = getString(R.string.error_username_too_long)
etUsername.requestFocus()
return false
}
if (etPassword.text.isNullOrEmpty()) {
etPassword.error = getString(R.string.error_required_password)
etPassword.requestFocus()
return false
}
if (etPassword.text.toString().length < AppConst.MAX_PASSWORD) {
etPassword.error = getString(R.string.error_password_greater_than_6)
etPassword.requestFocus()
return false
}
if (etConfirmPassword.text.isNullOrEmpty()) {
etConfirmPassword.error = getString(R.string.error_required_confirm_password)
etConfirmPassword.requestFocus()
return false
}
if (etEmailAddress.text.isNullOrEmpty()) {
etEmailAddress.error = getString(R.string.error_required_email)
etEmailAddress.requestFocus()
return false
}
if (etPhoneNumber.text.isNullOrEmpty()) {
etPhoneNumber.error = getString(R.string.error_required_phone_number)
etPhoneNumber.requestFocus()
return false
}
if (etPassword.text.toString() != etConfirmPassword.text.toString()) {
etConfirmPassword.error = getString(R.string.error_required_confirm_password_match)
etConfirmPassword.requestFocus()
return false
}
if (!Patterns.EMAIL_ADDRESS.matcher(etEmailAddress.text.toString()).matches()) {
etEmailAddress.error = getString(R.string.error_email_not_correct)
etEmailAddress.requestFocus()
return false
}
return true
}
}
<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/ui/activity/LoginActivity.kt
package com.mastertipsy.chat_chat.ui.activity
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Patterns
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.AppCompatEditText
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.model.AppConst
import com.mastertipsy.chat_chat.presentor.repository.LoginRepository
import com.mastertipsy.chat_chat.util.AlertUtil
import com.mastertipsy.chat_chat.presentor.view.LoginView
class LoginActivity : AppCompatActivity(), LoginView {
companion object {
fun startNewTaskClearTask(context: Context) {
val intent = Intent(context, LoginActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
context.startActivity(intent)
}
fun start(context: Context) {
context.startActivity(Intent(context, LoginActivity::class.java))
(context as Activity).finish()
}
}
private lateinit var repo: LoginRepository
private val btnGotoRegister by lazy { findViewById<AppCompatButton>(R.id.btn_login_register) }
private val btnLogin by lazy { findViewById<AppCompatButton>(R.id.btn_login) }
private val etEmail by lazy { findViewById<AppCompatEditText>(R.id.et_login_email) }
private val etPassword by lazy { findViewById<AppCompatEditText>(R.id.et_login_password) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
repo = LoginRepository(this, this)
setupListener()
}
override fun onLoginSuccess(email: String) {
ChatRoomListActivity.startNewTaskClearTask(this, email)
}
override fun onError(message: String) {
AlertUtil.showAlertDialog(this, getString(R.string.error), message)
}
private fun setupListener() {
btnGotoRegister.setOnClickListener { RegisterActivity.start(this) }
btnLogin.setOnClickListener {
if (!isAllDataValidated()) return@setOnClickListener
repo.login(etEmail.text.toString(), etPassword.text.toString())
}
}
private fun isAllDataValidated(): Boolean {
if (etEmail.text.isNullOrEmpty()) {
etEmail.error = getString(R.string.error_required_email)
etEmail.requestFocus()
return false
}
if (!Patterns.EMAIL_ADDRESS.matcher(etEmail.text.toString()).matches()) {
etEmail.error = getString(R.string.error_email_not_correct)
etEmail.requestFocus()
return false
}
if (etPassword.text.isNullOrEmpty()) {
etPassword.error = getString(R.string.error_required_password)
etPassword.requestFocus()
return false
}
if (etPassword.text.toString().length < AppConst.MAX_PASSWORD) {
etPassword.error = getString(R.string.error_password_greater_than_6)
etPassword.requestFocus()
return false
}
return true
}
}
<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/util/AlertUtil.kt
package com.mastertipsy.chat_chat.util
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.drawable.ColorDrawable
import android.view.Window
import com.mastertipsy.chat_chat.R
class AlertUtil {
companion object {
fun showAlertDialog(context: Context, title: String, message: String?) {
AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message ?: context.getString(R.string.error_unknown_error))
.setNegativeButton(context.getString(R.string.ok), null)
.show()
}
fun showAlertDialog(
context: Context,
title: String,
message: String?,
listener: DialogInterface.OnClickListener
) {
AlertDialog.Builder(context)
.setTitle(title)
.setMessage(message ?: context.getString(R.string.error_unknown_error))
.setNegativeButton(context.getString(R.string.ok), listener)
.show()
}
fun progressDialog(context: Context): Dialog = Dialog(context).apply {
requestWindowFeature(Window.FEATURE_NO_TITLE)
setCanceledOnTouchOutside(false)
setContentView(R.layout.custom_progress_bar)
window?.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
}
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/ui/activity/SplashActivity.kt
package com.mastertipsy.chat_chat.ui.activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.util.PermissionUtil
class SplashActivity : AppCompatActivity() {
private lateinit var permissionUtil: PermissionUtil
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
permissionUtil = PermissionUtil(this)
checkAllPermissions()
}
private fun checkAllPermissions() {
if (permissionUtil.isAllNeededPermissionsGranted()) {
checkLoggedInUser()
return
}
permissionUtil.requestAllNeededPermissions()
checkAllPermissions()
}
private fun checkLoggedInUser() {
val user = FirebaseAuth.getInstance().currentUser
if (user == null) {
LoginActivity.start(this)
return
}
ChatRoomListActivity.start(this, user.email ?: "")
}
}
<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/util/PermissionUtil.kt
package com.mastertipsy.chat_chat.util
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
class PermissionUtil(private val context: Context) {
private val permissionGranted = PackageManager.PERMISSION_GRANTED
private val permissionCamera = Manifest.permission.CAMERA
private val permissionReadStorage = Manifest.permission.READ_EXTERNAL_STORAGE
private val permissionWriteStorage = Manifest.permission.WRITE_EXTERNAL_STORAGE
fun isAllNeededPermissionsGranted(): Boolean =
isPermissionGranted(permissionCamera)
&& isPermissionGranted(permissionReadStorage)
&& isPermissionGranted(permissionWriteStorage)
fun requestAllNeededPermissions() {
val activity = context as Activity
val permissions = arrayOf(permissionCamera, permissionReadStorage, permissionWriteStorage)
ActivityCompat.requestPermissions(activity, permissions, 7888)
}
private fun isPermissionGranted(permission: String): Boolean =
ContextCompat.checkSelfPermission(context, permission) == permissionGranted
}<file_sep>/settings.gradle
include ':app'
rootProject.name='chat_chat'
<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/model/ChatRoom.kt
package com.mastertipsy.chat_chat.model
import com.google.firebase.Timestamp
class ChatRoom(
var roomID: String = "",
var image: String = "",
var isRead: List<String> = emptyList(),
var lastActive: Timestamp = Timestamp.now(),
var lastMessage: String = "",
var members: List<String> = emptyList(),
var name: String = "",
var type: Int = 0
) {
companion object {
const val collection = "ChatRoom"
const val image = "image"
const val lastActive = "lastActive"
const val lastMessage = "lastMessage"
const val members = "members"
const val name = "name"
const val isRead = "isRead"
const val type = "type"
fun fromMap(roomID: String, map: Map<String, Any>): ChatRoom {
return ChatRoom(
roomID,
map[image] as String,
map[isRead] as List<String>,
map[lastActive] as Timestamp,
map[lastMessage] as String,
map[members] as List<String>,
map[name] as String,
map[type] as Int
)
}
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/presentor/view/RegisterView.kt
package com.mastertipsy.chat_chat.presentor.view
interface RegisterView : BaseView {
fun onRegisterSuccess(email: String)
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/presentor/listener/RecyclerOnClickListener.kt
package com.mastertipsy.chat_chat.presentor.listener
interface RecyclerOnClickListener<T> {
fun onClick(item: T)
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/ui/activity/ChatRoomListActivity.kt
package com.mastertipsy.chat_chat.ui.activity
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatImageButton
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.adapter.ChatRoomListAdapter
import com.mastertipsy.chat_chat.model.ChatRoom
import com.mastertipsy.chat_chat.model.User
import com.mastertipsy.chat_chat.presentor.repository.ChatRoomListRepository
import com.mastertipsy.chat_chat.presentor.view.ChatRoomListView
import com.mastertipsy.chat_chat.util.AlertUtil
class ChatRoomListActivity : AppCompatActivity(), ChatRoomListView {
companion object {
const val EMAIL = "EMAIL"
fun startNewTaskClearTask(context: Context, email: String) {
val intent = Intent(context, ChatRoomListActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
intent.putExtra(EMAIL, email)
context.startActivity(intent)
}
fun start(context: Context, email: String) {
val intent = Intent(context, ChatRoomListActivity::class.java)
intent.putExtra(EMAIL, email)
context.startActivity(intent)
(context as Activity).finish()
}
}
private lateinit var repo: ChatRoomListRepository
private lateinit var adapter: ChatRoomListAdapter
private lateinit var user: User
private val userEmailAddress by lazy { intent.getStringExtra(EMAIL) }
private val ivMenu by lazy { findViewById<AppCompatImageButton>(R.id.iv_chat_room_list_menu) }
private val rvChatRoomList by lazy { findViewById<RecyclerView>(R.id.rv_chat_room_list) }
private val tvTitle by lazy { findViewById<AppCompatTextView>(R.id.tv_chat_room_list_title) }
private val progressBar by lazy { findViewById<ProgressBar>(R.id.progress_bar_chat_room_list) }
private val fabCreate by lazy { findViewById<FloatingActionButton>(R.id.fab_create_room) }
private var isAdapterInit: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat_room_list)
repo = ChatRoomListRepository(this, this)
repo.getUserByEmail(userEmailAddress)
setupListener()
}
override fun onStart() {
super.onStart()
if (!isAdapterInit) return
adapter.startListening()
}
override fun onStop() {
super.onStop()
adapter.stopListening()
}
@SuppressLint("SetTextI18n")
override fun onFetchUserSuccess(user: User) {
this.user = user
tvTitle.text = "${getString(R.string.hi)}, ${user.username}"
setupRecyclerView(user)
adapter.startListening()
progressBar.visibility = View.GONE
rvChatRoomList.visibility = View.VISIBLE
}
override fun onFetchRoomsSuccess(rooms: List<ChatRoom>) {}
override fun onError(message: String) {
AlertUtil.showAlertDialog(this, getString(R.string.error), message)
}
private fun setupListener() {
ivMenu.setOnClickListener {
FirebaseAuth.getInstance().signOut()
LoginActivity.startNewTaskClearTask(this)
}
fabCreate.setOnClickListener {
if (!isAdapterInit) return@setOnClickListener
CreateRoomActivity.start(this, user.userID)
}
}
private fun setupRecyclerView(user: User) {
rvChatRoomList.layoutManager = LinearLayoutManager(this)
val query = FirebaseFirestore.getInstance().collection(ChatRoom.collection)
.whereArrayContains(ChatRoom.members, user.userID)
val option = FirestoreRecyclerOptions.Builder<ChatRoom>()
.setQuery(query, ChatRoom::class.java)
.build()
adapter = ChatRoomListAdapter(option, user)
isAdapterInit = true
rvChatRoomList.adapter = adapter
}
}
<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/model/User.kt
package com.mastertipsy.chat_chat.model
class User(
var userID: String = "",
var profileImage: String = "",
var username: String = "",
var password: String = "",
var emailAddress: String = "",
var phoneNumber: String = ""
) {
companion object {
const val collection = "User"
const val profileImage = "profileImage"
const val username = "username"
const val emailAddress = "emailAddress"
const val phoneNumber = "phoneNumber"
fun fromMap(id: String, map: Map<String, Any>): User = User(
id,
map[profileImage] as String,
map[username] as String,
"********",
map[emailAddress] as String,
map[phoneNumber] as String
)
}
fun toMap() = hashMapOf(
User.profileImage to profileImage,
User.username to username,
User.emailAddress to emailAddress,
User.phoneNumber to phoneNumber
)
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/helper/SharedPreferencesHelper.kt
package com.mastertipsy.chat_chat.helper
import android.content.Context
class SharedPrefHelper {
companion object {
private const val PRIVATE = Context.MODE_PRIVATE
private const val PREF_NAME = "CHAT_CHAT"
private const val USER_ID = "USER_ID"
fun saveUserID(context: Context, uid: String) {
val pref = context.getSharedPreferences(PREF_NAME, PRIVATE)
pref.edit().putString(USER_ID, uid).apply()
}
fun loadUserID(context: Context): String {
val pref = context.getSharedPreferences(PREF_NAME, PRIVATE)
return pref.getString(USER_ID, null) ?: ""
}
fun removeUserID(context: Context) {
val pref = context.getSharedPreferences(PREF_NAME, PRIVATE)
pref.edit().remove(USER_ID).apply()
}
fun removeAll(context: Context) {
val pref = context.getSharedPreferences(PREF_NAME, PRIVATE)
pref.edit().clear().apply()
}
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/presentor/view/LoginView.kt
package com.mastertipsy.chat_chat.presentor.view
interface LoginView : BaseView {
fun onLoginSuccess(email: String)
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/presentor/view/CreateRoomView.kt
package com.mastertipsy.chat_chat.presentor.view
interface CreateRoomView : BaseView {
fun onRoomExisted()
fun onRoomNotExisted()
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/util/TextUtil.kt
package com.mastertipsy.chat_chat.util
import java.text.SimpleDateFormat
import java.util.*
class TextUtil {
companion object {
fun getCurrentDateTime(): String =
SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSSSSS", Locale.getDefault()).format(Date())
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/adapter/UserListAdapter.kt
package com.mastertipsy.chat_chat.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.model.User
import com.mastertipsy.chat_chat.presentor.listener.RecyclerOnClickListener
import kotlinx.android.synthetic.main.item_view_user_list.view.*
class UserListAdapter(
option: FirestoreRecyclerOptions<User>,
private val onClick: RecyclerOnClickListener<User>
) : FirestoreRecyclerAdapter<User, UserListAdapter.UserViewHolder>(option) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_view_user_list, parent, false)
return UserViewHolder(view, parent.context)
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int, model: User) {
holder.bind(model)
}
inner class UserViewHolder(private val view: View, private val context: Context) :
RecyclerView.ViewHolder(view) {
fun bind(user: User) {
Glide.with(context).load(user.profileImage).into(view.iv_user_image)
view.tv_username.text = user.username
itemView.setOnClickListener { onClick.onClick(user) }
}
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/presentor/repository/LoginRepository.kt
package com.mastertipsy.chat_chat.presentor.repository
import android.content.Context
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.helper.SharedPrefHelper
import com.mastertipsy.chat_chat.model.User
import com.mastertipsy.chat_chat.presentor.view.LoginView
import com.mastertipsy.chat_chat.util.AlertUtil
class LoginRepository(private val context: Context, private val view: LoginView) {
private val auth = FirebaseAuth.getInstance()
private val firestore = FirebaseFirestore.getInstance()
private val dialog = AlertUtil.progressDialog(context)
private val unknownError = context.getString(R.string.error_unknown_error)
fun login(email: String, password: String) {
dialog.show()
auth.signInWithEmailAndPassword(email, password).addOnCompleteListener { task ->
if (task.isSuccessful) {
saveUserID(email)
return@addOnCompleteListener
}
view.onError(task.exception?.message ?: unknownError)
dialog.dismiss()
}
}
private fun saveUserID(email: String) {
firestore.collection(User.collection).whereEqualTo(User.emailAddress, email).get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val uid = task.result?.documents?.get(0)?.id ?: ""
SharedPrefHelper.saveUserID(context, uid)
view.onLoginSuccess(email)
dialog.dismiss()
return@addOnCompleteListener
}
view.onError(task.exception?.message ?: unknownError)
dialog.dismiss()
}
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/presentor/repository/RegisterRepository.kt
package com.mastertipsy.chat_chat.presentor.repository
import android.content.Context
import android.net.Uri
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.helper.SharedPrefHelper
import com.mastertipsy.chat_chat.model.User
import com.mastertipsy.chat_chat.presentor.view.RegisterView
import com.mastertipsy.chat_chat.util.AlertUtil
import com.mastertipsy.chat_chat.util.TextUtil
class RegisterRepository(private val context: Context, private val view: RegisterView) {
private val auth = FirebaseAuth.getInstance()
private val storage = FirebaseStorage.getInstance()
private val firestore = FirebaseFirestore.getInstance()
private val dialog = AlertUtil.progressDialog(context)
private val unknownError = context.getString(R.string.error_unknown_error)
private val storagePath = "UserProfile"
fun registerUser(user: User, image: Uri?) {
dialog.show()
auth.createUserWithEmailAndPassword(user.emailAddress, user.password)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
auth.currentUser?.sendEmailVerification()
uploadUserProfile(user, image)
return@addOnCompleteListener
}
view.onError(task.exception?.message ?: unknownError)
dialog.dismiss()
}
}
private fun uploadUserProfile(user: User, image: Uri?) {
if (image == null) {
addUserToFirestore(user)
return
}
val imageName = "$storagePath/${TextUtil.getCurrentDateTime()}"
storage.reference.child(imageName).putFile(image)
.addOnCompleteListener { task ->
if (task.isSuccessful) {
storage.reference.child(imageName)
.downloadUrl.addOnCompleteListener { uri ->
user.profileImage = uri.result.toString()
addUserToFirestore(user)
}
return@addOnCompleteListener
}
view.onError(task.exception?.message ?: unknownError)
dialog.dismiss()
}
}
private fun addUserToFirestore(user: User) {
firestore.collection(User.collection).add(user.toMap())
.addOnCompleteListener { task ->
if (task.isSuccessful) {
saveUserID(user.emailAddress)
return@addOnCompleteListener
}
view.onError(task.exception?.message ?: unknownError)
dialog.dismiss()
}
}
private fun saveUserID(email: String) {
firestore.collection(User.collection).whereEqualTo(User.emailAddress, email).get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val uid = task.result?.documents?.get(0)?.id ?: ""
SharedPrefHelper.saveUserID(context, uid)
view.onRegisterSuccess(email)
dialog.dismiss()
return@addOnCompleteListener
}
view.onError(task.exception?.message ?: unknownError)
dialog.dismiss()
}
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/util/MediaUtil.kt
package com.mastertipsy.chat_chat.util
import android.content.Context
import android.database.Cursor
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.provider.MediaStore
import android.text.TextUtils
import androidx.loader.content.CursorLoader
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
class MediaUtil {
companion object {
fun compressImage(context: Context, uri: Uri): Bitmap? {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeStream(context.contentResolver.openInputStream(uri), null, options)
var tmpWidth = options.outWidth
var tmpHeight = options.outHeight
var scale = 1
while (true) {
if (tmpWidth / 2 < 500 || tmpHeight / 2 < 500)
break
tmpWidth /= 2
tmpHeight /= 2
scale *= 2
}
val secondOptions = BitmapFactory.Options()
secondOptions.inSampleSize = scale
val bitmap =
BitmapFactory.decodeStream(
context.contentResolver?.openInputStream(uri),
null,
secondOptions
)
bitmap?.let {
val exif = ExifInterface(getPath(context, uri))
exif.getAttribute(ExifInterface.TAG_ORIENTATION)?.let {
if (!TextUtils.isEmpty(it)) {
when (it.toInt()) {
ExifInterface.ORIENTATION_NORMAL -> {
return getRotatedImage(bitmap, 0f)
}
ExifInterface.ORIENTATION_ROTATE_90 -> {
return getRotatedImage(bitmap, 90f)
}
ExifInterface.ORIENTATION_ROTATE_180 -> {
return getRotatedImage(bitmap, 180f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> {
return getRotatedImage(bitmap, 270f)
}
}
}
}
}
return bitmap
}
fun createImageFile(context: Context, bitmap: Bitmap): File {
val file = File(context.externalCacheDir, "tmpImageFile")
var fos: FileOutputStream? = null
try {
file.createNewFile()
fos = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
} catch (e: IOException) {
} finally {
try {
fos?.let {
it.flush()
it.close()
}
} catch (e: IOException) {
}
}
return file
}
private fun getPath(context: Context, uri: Uri): String {
var cursor: Cursor? = null
return try {
val projection = arrayOf(MediaStore.Images.Media.DATA)
val loader = CursorLoader(context, uri, projection, null, null, null)
cursor = loader.loadInBackground()
val index = cursor?.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) ?: 0
cursor?.moveToFirst()
cursor?.getString(index).toString()
} finally {
cursor?.close()
}
}
private fun getRotatedImage(bitmap: Bitmap, rotate: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(rotate)
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
}
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/ui/activity/CreateRoomActivity.kt
package com.mastertipsy.chat_chat.ui.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.firestore.FirebaseFirestore
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.adapter.UserListAdapter
import com.mastertipsy.chat_chat.model.User
import com.mastertipsy.chat_chat.presentor.listener.RecyclerOnClickListener
class CreateRoomActivity : AppCompatActivity() {
companion object {
const val UID = "UID"
fun start(context: Context, uid: String) {
val intent = Intent(context, CreateRoomActivity::class.java)
intent.putExtra(UID, uid)
context.startActivity(Intent(context, CreateRoomActivity::class.java))
}
}
private lateinit var adapter: UserListAdapter
private val currentUserID by lazy { intent.getStringExtra(UID) }
private val rvUserList by lazy { findViewById<RecyclerView>(R.id.rv_user_list) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_creat_room)
setupRecyclerView()
}
override fun onStart() {
super.onStart()
adapter.startListening()
}
override fun onStop() {
super.onStop()
adapter.stopListening()
}
private fun setupRecyclerView() {
rvUserList.layoutManager = LinearLayoutManager(this)
val query = FirebaseFirestore.getInstance().collection(User.collection)
val option = FirestoreRecyclerOptions.Builder<User>()
.setQuery(query, User::class.java)
.build()
adapter = UserListAdapter(option, object : RecyclerOnClickListener<User> {
override fun onClick(item: User) {
val userList = listOf(item.userID, currentUserID)
FirebaseFirestore.getInstance()
.collection("ChatRoom")
.whereArrayContains("members", userList)
.get()
}
})
rvUserList.adapter = adapter
}
}
<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/model/AppConst.kt
package com.mastertipsy.chat_chat.model
class AppConst {
companion object {
const val CAMERA_CODE = 1
const val GALLERY_CODE = 2
const val MAX_PASSWORD = 6
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/presentor/repository/ChatRoomListRepository.kt
package com.mastertipsy.chat_chat.presentor.repository
import android.content.Context
import com.google.firebase.firestore.FirebaseFirestore
import com.mastertipsy.chat_chat.R
import com.mastertipsy.chat_chat.model.User
import com.mastertipsy.chat_chat.presentor.view.ChatRoomListView
class ChatRoomListRepository(context: Context, private val view: ChatRoomListView) {
private val firestore = FirebaseFirestore.getInstance()
private val unknownError = context.getString(R.string.error_unknown_error)
fun getUserByEmail(email: String) {
firestore.collection(User.collection)
.whereEqualTo(User.emailAddress, email)
.get()
.addOnFailureListener { view.onError(it.message ?: unknownError) }
.addOnSuccessListener { documents ->
for (doc in documents) {
val user = User.fromMap(doc.id, doc.data)
view.onFetchUserSuccess(user)
}
}
}
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/presentor/view/BaseView.kt
package com.mastertipsy.chat_chat.presentor.view
interface BaseView {
fun onError(message: String)
}<file_sep>/app/src/main/java/com/mastertipsy/chat_chat/presentor/view/ChatRoomListView.kt
package com.mastertipsy.chat_chat.presentor.view
import com.mastertipsy.chat_chat.model.ChatRoom
import com.mastertipsy.chat_chat.model.User
interface ChatRoomListView : BaseView {
fun onFetchUserSuccess(user: User)
fun onFetchRoomsSuccess(rooms: List<ChatRoom>)
}
|
e121a4ea7ae5cb19fad4fac9764dba9e325c1004
|
[
"Kotlin",
"Gradle"
] | 25 |
Kotlin
|
channdara/chat_chat
|
7d16d047197136085007f0daf3a01cbfd27574f2
|
c17da7c85d06d05b270729f81baf8cb24bef73dd
|
refs/heads/master
|
<file_sep>CREATE TABLE teams(
ID int primary key,
NAME VARCHAR(25),
RECENT_MATCH_POINTS int
);<file_sep><?php
include '../connection.php';
global $connect;
if (isset($_POST['t_s'])) {
# code...
$team_name = $_POST['team_name'];
$ti_query = "INSERT INTO teams(name) VALUES('$team_name');";
if ($connect->query($ti_query)) {
# code...
?><script>alert('Team Added!')</script><?php
}else{
?><script>alert('Could not add team!')</script><?php
}
}elseif (isset($_POST['t_p'])) {
# code...
$player_name = $_POST['player_name'];
$team_id = $_POST['team_id'];
$value = $_POST['value'];
$pi_query = "INSERT INTO players(NAME, VALUE, TEAM_ID, POINTS) VALUES('$player_name', '$value', '$team_id', '0');";
if ($connect->query($pi_query)) {
# code...
?><script>alert('Player Added!')</script><?php
}else{
?><script>alert('Could not add player!')</script><?php
}
}
$team_query = "SELECT * FROM teams;";
$team_res = $connect->query($team_query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<title>Add</title>
<style>
team_sub{
color: white;
}
</style>
</head>
<body>
<nav class='blue'>
<div class="nav-wrapper">
<a href="#" class="brand-logo" style='margin-left: 10px'>VPTG</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li><a href="index.php">Home</a></li>
<li><a href="add.php">Add Team/Player</a></li>
</ul>
</div>
</nav>
<center>
<div class='container card'>
<div class="row">
<form class="col s12" action='add.php' method='post'>
<h4>Add Team</h4>
<div class="row">
<div class="input-field col s12">
<input id="team_name" type="text" name='team_name' class="validate">
<label for="team_name">Enter team name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="team_sub" name='t_s' type="submit" class="btn blue" value="Add Team">
</div>
</div>
</form>
</div>
</div>
<div class='container card'>
<div class="row">
<form class="col s12" action='add.php' method='post'>
<h4>Add Player</h4>
<div class="row">
<div class="input-field col s12 m4 l4">
<input id="player_name" type="text" name='player_name' class="validate">
<label for="player_name">Enter player name</label>
</div>
<div class="input-field col s12 m4 l4">
<input id="value" type="text" name='value' class="validate">
<label for="value">Enter player value</label>
</div>
<div class="input-field col s12 m4 l4">
<select name='team_id'>
<option value="" disabled selected>Choose Team</option>
<?php while($team_row = $team_res->fetch_array()){?>
<option value="<?php echo $team_row['ID'];?>"><?php echo $team_row['NAME'];?></option>
<?php }?>
</select>
<label>Choose Team</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="team_sub" name='t_p' type="submit" class="btn blue" value="Add Team">
</div>
</div>
</form>
</div>
</div>
</center>
<script>
$(document).ready(function(){
$('select').formSelect();
});
</script>
</body>
</html><file_sep>CREATE TABLE league(
ID int primary key,
TOTALPLAYERS int,
COUNTRY varchar(25),
TOP_SCORER INT
);<file_sep>CREATE TABLE players(
ID int primary key AUTO_INCREMENT,
NAME VARCHAR(25),
TEAM_ID INT,
VALUE INT,
POINTS INT,
CONSTRAINT fk_team_player FOREIGN KEY (TEAM_ID) REFERENCES TEAMS(ID)
);
<file_sep><?php
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://localhost/vptg/Users/index.php?type=all',
CURLOPT_USERAGENT => 'Admin Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
$resp = json_decode($resp, false);
$resp = $resp->response;
// Close request to clear up some resources
curl_close($curl);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<title>Admin</title>
</head>
<body>
<nav class='blue'>
<div class="nav-wrapper">
<a href="#" class="brand-logo" style='margin-left: 10px'>VPTG</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li><a href="index.php">Home</a></li>
<li><a href="add.php">Add Team/Player</a></li>
</ul>
</div>
</nav>
<div class='container'>
<ul class='collapsible popout'>
<?php for($i = 0;$i<count($resp);$i++){?>
<li>
<div class="collapsible-header"><strong><?php echo $resp[$i]->name;?></strong></div>
<div class="collapsible-body">Rank: <strong><?php echo $i+1;?></strong></br>Points: <strong><?php echo $resp[$i]->points;?></strong></div>
</li>
<?php }?>
</ul>
</div>
<script>
$(document).ready(function(){
$('.collapsible').collapsible();
});
</script>
</body>
</html><file_sep><?php
include '../connection.php';
global $connect;
$id = $_POST['id'];
$points = $_POST['points'];
$p_query = "SELECT user_id, points FROM buy LEFT JOIN user_vgame ON buy.user_id = user_vgame.id WHERE player_id = '$id';";
$res = $connect->query($p_query);
while($row = $res->fetch_array()){
$new_points = $points + $row['points'];
$u_id = $row['user_id'];
$update_p = "UPDATE user_vgame SET points = '$new_points' WHERE id='$u_id';";
$connect->query($update_p);
}
$p2_query = "UPDATE players SET points = points+'$points' WHERE id='$id';";
if($connect->query($p2_query))
echo 'success';
else
echo 'fail';
?><file_sep>CREATE TABLE user_vgame(
ID int primary key AUTO_INCREMENT,
NAME VARCHAR(25),
EMAIL VARCHAR(25),
POINTS int,
PASSWORD VARCHAR(32),
BUDGET int,
LEAGUE_ID int,
CONSTRAINT FK_USERLEAGUE FOREIGN KEY (LEAGUE_ID) REFERENCES league(id)
);<file_sep><?php
include "../connection.php";
global $connect;
$method = $_SERVER['REQUEST_METHOD'];
switch($method){
case 'POST':
if (
isset($_POST['user_name'])
&& isset($_POST['password'])
){
$user_name = mysqli_real_escape_string($connect, $_POST['user_name']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
}
$query = "SELECT * FROM user_vgame WHERE NAME = '$user_name' AND PASSWORD = <PASSWORD>';";
$res = $connect->query($query);
if ($res->num_rows != 0) {
echo 'true';
return true;
} else {
echo 'fail';
return false;
}
break;
}
?><file_sep><?php
include "../connection.php";
global $connect;
$method = $_SERVER['REQUEST_METHOD'];
switch($method){
case 'POST':
if (
isset($_POST['user_name'])
&& isset($_POST['email'])
&& isset($_POST['password'])
){
$user_name = mysqli_real_escape_string($connect, $_POST['user_name']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
$password = mysqli_real_escape_string($connect, $_POST['password']);
$query = "INSERT INTO user_vgame (NAME, EMAIL, POINTS, PASSWORD, BUDGET) VALUES ('$user_name', '$email', 0, '$password', <PASSWORD>)";
if ($connect->query($query)) {
echo 'true';
return true;
} else {
echo 'fail';
return false;
}
break;
}
case 'GET':
if(isset($_GET['type']) && $_GET['type']=='all'){
$response = array();
$query = "SELECT * FROM user_vgame order by points desc";
$res = $connect->query($query);
while($row=$res->fetch_array()){
array_push($response, array('id'=>$row['ID'],'name'=>$row['NAME'],'points'=>$row['POINTS']));
}
echo json_encode(array('response'=>$response));
}
}
?><file_sep><?php
include '../connection.php';
global $connect;
$query = "SELECT players.id as id, players.name as name, value, points, teams.id as team_id, teams.name as team_name FROM players LEFT JOIN teams ON teams.id = players.team_id;";
$res = $connect->query($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<title>Admin</title>
</head>
<body>
<nav class='blue'>
<div class="nav-wrapper">
<a href="#" class="brand-logo" style='margin-left: 10px'>VPTG</a>
<ul id="nav-mobile" class="right hide-on-med-and-down">
<li><a href="add.php">Add Player/Team</a></li>
<li><a href="standings.php">Standings</a></li>
</ul>
</div>
</nav>
<div class='container'>
<ul class='collapsible popout'>
<?php while($row = $res->fetch_array()){?>
<li>
<div class="collapsible-header"><strong><?php echo $row['name'];?></strong></div>
<div class="collapsible-body">Team: <strong><?php echo $row['team_name'];?></strong></br>Value: <strong><?php echo $row['value'];?></strong></br>Points: <strong class='point<?php echo $row['id'];?>'><?php echo $row['points'];?></strong>
<div class='row'>
<div class='col s12 m8 l8'>
<div class="input-field">
<input id="points_text<?php echo $row['id'];?>" type="number" class="validate">
<label for="first_name">Enter points</label>
</div>
</div>
<div class='col s12 m4 l4'>
<a class="waves-effect waves-light btn" id='update<?php echo $row['id'];?>' onclick='update(<?php echo $row['id'];?>)'>Update</a>
</div>
</div>
</div>
</li>
<?php }?>
</ul>
</div>
<script>
$(document).ready(function(){
$('.collapsible').collapsible();
});
function update(id) {
var points = $('#points_text'+id).val();
$.ajax({
url:'admin.api.php',
type: 'POST',
data: {id: id, points: points},
success: function(res){
if(res == 'success'){
M.toast({html: 'Points updated successfully!'});
$('.point'+id).text(parseInt($('.point'+id).text())+parseInt(points));
$('#points_text'+id).val('');
}else{
M.toast({html: 'Could not update points!'});
}
}
});
}
</script>
</body>
</html><file_sep># VPTS
Backend api for virtual-player-transfer-game.
<file_sep><?php
include "../connection.php";
global $connect;
$method = $_SERVER['REQUEST_METHOD'];
switch($method){
case 'POST':
if (
isset($_POST['player_name'])
&& isset($_POST['team_id'])
&& isset($_POST['value'])
&& isset($_POST['points'])
){
$player_name = mysqli_real_escape_string($connect, $_POST['player_name']);
$team_id = mysqli_real_escape_string($connect, $_POST['team_id']);
$value = mysqli_real_escape_string($connect, $_POST['value']);
$points = mysqli_real_escape_string($connect, $_POST['points']);
$query = "INSERT INTO players (NAME, TEAM_ID, VALUE, POINTS) VALUES ('$player_name', '$team_id', '$value', '$points')";
if ($connect->query($query)) {
echo 'true';
return true;
} else {
echo 'fail';
return false;
}
break;
}
else if(isset($_POST['user_id']) && isset($_POST['player_id'])){
$user_id = $_POST['user_id'];
$player_id = $_POST['player_id'];
try{
$connect->beginTransaction();
$buy_query = "INSERT INTO buy(player_id, user_id) VALUES ('$player_id', '$user_id');";
if($connect->query($buy_query)){
$connect->commit();
}
}catch (Exception $e){
$connect->rollback();
echo 'false';
}
break;
}
case 'GET':
if (isset($_GET['type']) && $_GET['type'] == 'pool' && isset($_GET['user_id'])) {
# code...
$response = array();
$user_id = $_GET['user_id'];
$query = "SELECT players.id as id, players.name, value, points, teams.id as team_id, teams.name as team_name FROM players LEFT JOIN teams ON players.team_id = teams.id;";
$res = $connect->query($query);
while($row = $res->fetch_array()){
$player_id = $row['id'];
$query1 = "SELECT id FROM buy WHERE player_id = '$player_id' AND user_id = '$user_id';";
$res1 = $connect->query($query1);
if($res1->num_rows == 0){
$buy_id = 0;
}else{
$buy_id = 1;
}
array_push($response, array('buy_id'=>$buy_id, 'player_id'=>$player_id, 'user_id'=>$user_id, 'name'=>$row['name'], 'team_name'=>$row['team_name'], 'value'=>$row['value'], 'points'=>$row['points']));
}
echo json_encode(array('response'=>$response));
}else
if(isset($_GET['username'])){
$response = array();
$username = $_GET['username'];
$query = "SELECT user_vgame.id as id, name, points, budget, points FROM user_vgame WHERE name='$username' ";
$res = $connect->query($query);
$row = $res->fetch_array();
array_push($response, array('id'=>$row['id'], 'name'=>$row['name'], 'points'=>$row['points'], 'budget'=>$row['budget']));
echo json_encode(array('response'=>$response));
exit(0);
}elseif (isset($_GET['user_id']) && isset($_GET['player_id'])) {
# code...
$response = array();
$user_id = $_GET['user_id'];
$player_id = $_GET['player_id'];
$query2 = "SELECT * FROM players WHERE id='$player_id';";
$res2 = $connect->query($query2);
$row2 = $res2->fetch_array();
$value = $row2['VALUE'];
$query3 = "SELECT * FROM user_vgame WHERE id='$user_id';";
$res3 = $connect->query($query3);
$row3 = $res3->fetch_array();
$budget = $row3['BUDGET'];
$new_budget = $budget-$value;
if($new_budget >= 0 ){
$query4 = "INSERT INTO buy(user_id, player_id) VALUES('$user_id','$player_id');";
if($connect->query($query4)){
$query5 = "UPDATE user_vgame SET budget='$new_budget' WHERE id='$user_id';";
if($connect->query($query5)){
array_push($response, array('status'=>'success', 'budget'=>$new_budget));
}
}else{
array_push($response, array('status'=>'failed'));
}
}else {
array_push($response, array('status'=>'balance_error'));
}
echo json_encode(array('response'=>$response));
}
else if(isset($_GET['user_id'])){
$response = array();
$user_id = $_GET['user_id'];
$query = "SELECT buy.id as id, user_id, player_id, players.name, team_id, teams.name as team_name, players.points as points, value FROM buy LEFT JOIN players ON players.id = buy.player_id LEFT JOIN teams ON teams.id = players.team_id WHERE user_id='$user_id';";
$res = $connect->query($query);
while ($row = $res->fetch_array()) {
array_push($response, array('buy_id'=>$row['id'], 'player_id'=>$row['player_id'], 'user_id'=>$row['user_id'], 'name'=>$row['name'], 'team_name'=>$row['team_name'], 'points'=>$row['points'], 'value'=>$row['value']));
}
echo json_encode(array('players' => $response));
exit(0);
}elseif (isset($_GET['buy_id'])) {
# code...
$response = array();
$buy_id = $_GET['buy_id'];
$query1 = "SELECT * FROM buy WHERE id = '$buy_id';";
$res1 = $connect->query($query1);
$row1 = $res1->fetch_array();
$player_id = $row1['player_id'];
$user_id = $row1['user_id'];
$query2 = "SELECT * FROM players WHERE ID='$player_id';";
$res2 = $connect->query($query2);
$row2 = $res2->fetch_array();
$value = $row2['VALUE'];
$query3 = "SELECT * FROM user_vgame WHERE ID='$user_id';";
$res3 = $connect->query($query3);
$row3 = $res3->fetch_array();
$budget = $row3['BUDGET'];
$new_budget = $budget + $value;
$query4 = "DELETE FROM buy WHERE id='$buy_id';";
if($connect->query($query4)){
$query5 = "UPDATE user_vgame SET budget='$new_budget' WHERE id='$user_id';";
if($connect->query($query5)){
array_push($response, array('status'=>'success', 'budget'=>$new_budget));
}
}else{
array_push($response, array('status'=>'failed'));
}
echo json_encode(array('response'=>$response));
}
}
?>
|
3fc1ffb6d104ac01de8ab2029cf12759c9d93122
|
[
"Markdown",
"SQL",
"PHP"
] | 12 |
SQL
|
humblefool01/VPTS
|
8d077f833014a67948e9101a3efc9402dbe6311b
|
caf9c70436758054ee7339b8f56460a8e7a0b11f
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# Name: <NAME>
# Student number: 11038926
"""
This script parses and processes the data from a csv file
"""
import csv
import pandas as pd
import numpy
import json
# Global constants
INPUT = "data.csv"
OUTPUT_FILE = "data.json"
YEAR = 1980
MEASURE = "KTOE"
def processing(file):
"""
Function cleaning and processing file
Keep for every country the MEASURE value in the YEAR, both specified in the global constant, only top 20 countries
Delete the missing values
Delete OECD Total; gives a distored image of the values since OECD is the sum of all the other countries values
"""
# Delete INDICATOR, SUBJECT, FREQUENCY and Flag Code, not necessary
file = file.drop(['INDICATOR', 'SUBJECT', 'FREQUENCY', 'Flag Codes'], axis=1)
# Get only MEASURE
file = file.loc[file['MEASURE'] == MEASURE]
file = file.loc[file['TIME'] == YEAR]
# Delete the missing values
file = file.dropna()
# Delete OECD value
file = file.loc[file['LOCATION'] != 'OECD']
# Sort values
file = file.sort_values(by='Value', ascending=False)
# Save top 20 countries
file = file.head(20)
return(file)
if __name__ == "__main__":
# open input file
with open(INPUT) as in_file:
data_frame = pd.read_csv(in_file, skip_blank_lines=True)
# process data
data_frame = processing(data_frame)
# export to json
export = data_frame.to_json(OUTPUT_FILE, orient='records')
<file_sep>#!/usr/bin/env python
# Name: <NAME>
# Student number: 11038926
"""
This script parses and processes the data from a csv file
"""
import csv
import pandas as pd
import numpy
import json
# Global constants
INPUT = "NFA_2018.csv"
OUTPUT_FILE = "data.json"
data_variable = "EFConsPerCap"
def processing(file):
"""
Function cleaning and processing file
"""
# Delete INDICATOR, SUBJECT, FREQUENCY and Flag Code, not necessary
file = file.drop(['Percapita GDP (2010 USD)', 'UN_region', 'UN_subregion'], axis=1)
# Get only MEASURE
file = file.loc[file['record'] == data_variable]
# Delete the missing values
file = file.dropna()
file = file.rename(columns = {'ISO alpha-3 code' : 'CountryCode', 'crop_land' : 'Crop land', 'grazing_land' : 'Grazing land', 'forest_land' : 'Forest land', 'fishing_ground' : 'Fishing ground', 'built_up_land' : 'Build up land', 'carbon' : 'Carbon'} )
print(file)
return(file)
def average(file):
"""
Function calculating the average across the world for:
EFConsPerCap, Crop land, Grazing land, Forest land, Fishing grounds, Build up land, Carbon
"""
# column_names = ['Crop land', 'Grazing land', 'Forest land', 'Fishing ground', 'Build up land', 'Carbon']
averages = {'Crop land': file['Crop land'].mean(), 'Grazing land': file['Grazing land'].mean(), 'Forest land': file['Forest land'].mean(), 'Fishing ground': file['Fishing ground'].mean(), 'Build up land': file['Build up land'].mean(), 'Carbon': file['Carbon'].mean()}
world_average = pd.DataFrame(averages, index = ['0'])
return(world_average)
if __name__ == "__main__":
# open input file
with open(INPUT) as in_file:
data_frame = pd.read_csv(in_file, skip_blank_lines=True)
# process data
data_frame = processing(data_frame)
data_world = average(data_frame)
# export to json
export = data_frame.to_json(OUTPUT_FILE, orient='records')
export_world = data_world.to_json("data_world.json", orient='records')
<file_sep>#!/usr/bin/env python
# Name: <NAME>
# Student number: 11038926
"""
This script parses and processes the data from a csv file
"""
import csv
import pandas as pd
import numpy
import matplotlib.pyplot as plt
import json
# Global constants
INPUT_CSV = "input.csv"
USE_COLUMNS = ['Country', 'Region', 'Pop. Density (per sq. mi.)', 'Infant mortality (per 1000 births)', 'GDP ($ per capita) dollars']
OUTPUT_FILE = "output.json"
def processing(file):
"""
Function cleaning and processing file
Data has an outlier (as seen in histogram), namely Suriname (400.000), this value be replaced for NaN
"""
# remove whitespace
file.loc[:,'Region'] = file.loc[:,'Region'].str.strip()
# remove 'dollar' from GDP
file.loc[:,'GDP ($ per capita) dollars'] = file.loc[:,'GDP ($ per capita) dollars'].str.strip(' dollars')
# make from unknown 'Not a Number'
file.iloc[:,1] = file.iloc[:,1].replace('unknown', numpy.nan)
file.iloc[:,2] = file.iloc[:,2].replace('unknown', numpy.nan)
file.iloc[:,3] = file.iloc[:,3].replace('unknown', numpy.nan)
# replace comma by dot
file['Pop. Density (per sq. mi.)'] = file['Pop. Density (per sq. mi.)'].str.replace(',', '.')
file['Infant mortality (per 1000 births)'] = file['Infant mortality (per 1000 births)'].str.replace(',', '.')
# convert strings to floats
file.loc[:,'Pop. Density (per sq. mi.)'] = file.loc[:,'Pop. Density (per sq. mi.)'].astype('float')
file.loc[:,'Infant mortality (per 1000 births)'] = file.loc[:,'Infant mortality (per 1000 births)'].astype('float')
file.loc[:,'GDP ($ per capita) dollars'] = file.loc[:,'GDP ($ per capita) dollars'].astype('float')
# replace outliers
file = file.replace(400000, numpy.nan)
return(file)
def central_tendancy(file):
"""
Function computing and printing central tendancy and histogram
"""
# compute & print mean, median, mode and standard deviation
mean = file.mean()
median = file.median()
mode = file.mode()
sd = file.std()
print('Central Tendancy:')
print('The mean of the variable GDP ($ per capita) is %.1f' % mean)
print('The median of the variable GDP ($ per capita) is %i' % median)
print('The mode of the variable GDP ($ per capita) is %i' % mode)
print('The standard deviation of the variable GDP ($ per capita) is %.1f' % sd)
# plot histogram
plt.figure(1, figsize=(9,6))
plt.subplot(121)
plt.xlim(0,60000)
plt.xlabel('GDP ($ per capita)')
plt.title('Histogram of GDP ($ per capita)')
file.hist(bins=18)
return[]
def five_number(file):
"""
Function computing and printing five number summary and boxplot
"""
minimum = file.min()
f_quantile = file.quantile(0.25)
median = file.median()
t_quantile = file.quantile(0.75)
maximum = file.max()
print('\nFive Number Summary:')
print('The minimum of the variable Infant mortality (per 1000 births) is %.1f' % minimum)
print('The first quantile of the variable Infant mortality (per 1000 births) is %.1f' % f_quantile)
print('The median of the variable Infant mortality (per 1000 births) is %.1f' % median)
print('The third quantile of the variable Infant mortality (per 1000 births) is %.1f' % t_quantile)
print('The maximum of the variable Infant mortality (per 1000 births) is %.1f' % maximum)
# plot boxplot
plt.subplot(122)
file.plot.box()
plt.title('Boxplot of infant mortality (per 1000 births)')
plt.show()
return[]
if __name__ == "__main__":
# open input file
with open(INPUT_CSV) as csvfile:
data_frame = pd.read_csv(csvfile, index_col=0, usecols=USE_COLUMNS)
# process data
data_frame = processing(data_frame)
# central tendancy
central_tendancy(data_frame.loc[:,'GDP ($ per capita) dollars'])
# five number summary
five_number(data_frame.loc[:,'Infant mortality (per 1000 births)'])
# export to json
export = data_frame.to_json(OUTPUT_FILE, orient='index')
<file_sep>#!/usr/bin/env python
# Name: <NAME>
# Student number: 11038926
"""
This script parses and processes the data from a csv file
"""
import csv
import pandas as pd
import numpy
import json
# Global constants
INPUT = "KNMI_20190101.csv"
OUTPUT_FILE = "data.json"
def processing(file):
"""
Function cleaning and processing file
"""
# delete the first row (contains nothing)
file = file.drop(0, axis=0)
# change column names
file = file.rename(columns={'# STN':'STN', 'YYYYMMDD':'Date', ' SP':'SP'})
i = 1;
# convert Date to date time
for elementen in file.loc[:, 'Date']:
date_time = pd.to_datetime(elementen, format='%Y%m%d')
file.loc[i, 'Date'] = date_time
i += 1
# Delete STN, not necessary
file = file.drop('STN', axis=1)
return(file)
if __name__ == "__main__":
# open input file
with open(INPUT) as in_file:
data_frame = pd.read_csv(in_file, header=10, skip_blank_lines=True)
# process data
data_frame = processing(data_frame)
# export to json
export = data_frame.to_json(OUTPUT_FILE, orient='records')
<file_sep>// <NAME>, 11038926
// loading data
var requests = [d3v5.json("data.json"),d3v5.json("data_world.json")];
Promise.all(requests).then(function(response) {
// world pie chart data
var world_data = world_pie(response[1])
// world map data & map
var map = process(response[0]);
worldmap(map, world_data);
// default piechart, data and country name
var piedata = map.ARM.pie;
var name = "Armenia"
piechart(piedata, world_data, name);
});
function process(input) {
// initialize variables
var map = {};
// make dataset
Object.values(input).forEach(function(d){
// only 2014
if (d.year == 2014) {
var country_variables = {};
country_variables.country = d.country
country_variables.year = d.year
country_variables[d.record] = d.total
country_variables.pie = []
for (var i = 4; i < 10; i++){
pievalues = {}
pievalues.label = Object.keys(d)[i]
pievalues.value = d[Object.keys(d)[i]]
country_variables.pie.push(pievalues)
}
// calculate the fill category datamap
if (country_variables.EFConsPerCap < 1){
country_variables.fillKey = "low"
}
else if (country_variables.EFConsPerCap >= 1 && country_variables.EFConsPerCap < 2){
country_variables.fillKey = "medium"
}
else if (country_variables.EFConsPerCap >= 2 && country_variables.EFConsPerCap < 4){
country_variables.fillKey = "high"
}
else if (country_variables.EFConsPerCap >= 4 && country_variables.EFConsPerCap < 6){
country_variables.fillKey = "higher"
}
else if (country_variables.EFConsPerCap >= 6 && country_variables.EFConsPerCap < 9){
country_variables.fillKey = "super high"
}
else if (country_variables.EFConsPerCap >= 9){
country_variables.fillKey = "ultra high"
}
map[d.CountryCode] = country_variables
}
})
console.log(map)
return map;
}
function world_pie(input){
// prcess data
var pie_data = []
Object.values(input).forEach(function(d){
for (var i = 0; i < 6; i++){
pievalues = {}
pievalues.label = Object.keys(d)[i]
pievalues.value = d[Object.keys(d)[i]]
pie_data.push(pievalues)
}
})
return pie_data;
}
function worldmap(input, input_world){
var fillColor = d3v5.scaleThreshold()
.domain([1, 2, 4, 6, 9])
.range(d3v5.schemeRdYlGn[6]);
var datamap = new Datamap({
element: document.getElementById("container_map"),
geographyConfig: {
// pop up settings
popupTemplate: function(geography, data) {
var EF = Math.round(data.EFConsPerCap * 100) / 100;
return['<div class = "hoverinfo"><strong>'+
geography.properties.name +
'<br/>EF: ' + EF +
'</strong></div>'];},
// set highlight properties (upon mouseover)
highlightOnHover: true,
popupOnHover: true,
highlightFillColor: "#b5ccca",
highlightBorderColor: "#b5ccca"
},
data: input,
fills: function(geography, data){ return fillColor(data.EFConsPerCap);},
fills: {
"low": "#1a9850",
"medium": "#91cf60",
"high": "#d9ef8b",
"higher": "#fee08b",
"super high": "#fc8d59",
"ultra high": "#d73027",
defaultFill: "#E0EBE0"
},
done: function(map) {
// default setting
var code = "ARM"
var name = "Armenia"
map.svg.selectAll(".datamaps-subunit").on("click", function(geography){
code = geography.id;
name = geography.properties.name
// if country has no data, keep previous country, else update
if (typeof(input[code]) === "undefined"){
alert("This country has no data. Please try another one.")
}
else {
// delete elements of old piechart and make new one
update()
piechart(input[code].pie, input_world, name)
}
})
}
});
// Add legend
var d = d3v5.select("#container_map")
var g = d.select(".datamap").append("g")
.attr("transform", "translate(0,550)")
.call(legend)
function legend(g){
var width = 280;
const length = fillColor.range().length;
const x = d3v5.scaleLinear()
.domain([1, length - 1])
.rangeRound([width / length, width * (length - 1) / length]);
g.selectAll("rect")
.data(fillColor.range())
.join("rect")
.attr("height", 8)
.attr("x", function(d, i){return x(length - 1 - i);})
.attr("width", function(d, i) {return (x(i + 1) - x(i)); })
.attr("fill", function(d){return d;});
g.append("text")
.attr("y", -6)
.attr("fill", "currentColor")
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text("Ecological Footprint (global hectares)");
g.call(d3v5.axisBottom(x)
.tickSize(13)
.tickFormat(function(i) {return fillColor.domain()[i - 1]} )
.tickValues(d3v5.range(1, length)))
.select(".domain")
.remove();
// title
var t = d.select(".datamap").append("text")
.attr("transform", "translate(0,20)")
.style("text-anchor", "left")
.style("font-weight", "bold")
.style("font-size", "14pt")
.text("Ecological Footprint worldwide")
}
}
function piechart(input, input_world, name){
// set width hight radius
var w = 400
var h = 400
var radius = 100
// set legend dimensions
var legendRectSize = 25
var legendSpacing = 3
// define color scale
var colorScale = d3v5.scaleOrdinal()
.domain(["Crop land", "Grazing land", "Forest land", "Fishing ground", "Build up land", "Carbon"])
.range(["#d9ef8b", "#91cf60", "#1a9850", "#99c5e5", "#d1573c", "#919191"])
// world average pie
var arc = d3v5.arc()
.innerRadius(0)
.outerRadius(radius)
var svg = d3v5.select("#chart")
.append("svg")
.attr("width", "50%")
.attr("height", "400px")
.attr('viewBox','0 0 '+Math.min(w,h) +' '+Math.min(w,h) )
// add title
svg.append("text")
.attr("x", w/2)
.attr("y", 80)
.attr("text-anchor", "middle")
.style("font-weight", "bold")
.text("World average")
var svg1 = svg.append("g")
.attr("transform", "translate(" + Math.min(w,h)/2 + "," + Math.min(w,h)/2 + ")")
var pie = d3v5.pie()
.sort(null)
.value(function(d){ return d.value; })(input_world)
var path = svg1.selectAll('path')
.data(pie)
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d){ return colorScale(d.data.label); })
// per country pie
var svg = d3v5.select("#chart")
.append("svg")
.attr("width", "50%")
.attr("height", "400px")
.attr("float", "right")
.attr('viewBox','0 0 '+Math.min(w,h) +' '+Math.min(w,h) )
// add title
svg.append("text")
.attr("x", (w/2 - 100) )
.attr("y", 80)
.attr("text-anchor", "middle")
.style("font-weight", "bold")
.text(name);
var svg1 = svg.append("g")
.attr("transform", "translate(" + (Math.min(w,h)/2 - 100) + "," + Math.min(w,h)/2 + ")")
var pie = d3v5.pie()
.sort(null)
.value(function(d){ return d.value; })(input)
var path = svg1.selectAll('path')
.data(pie)
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d){ return colorScale(d.data.label); })
// tooltip
var tooltip = d3v5.select("#chart")
.append("div")
.attr("class", "tooltip_piechart")
tooltip.append("div")
.attr("class", "label")
tooltip.append("div")
.attr("class", "value")
path.on("mouseover", function(d){
var EF_per_cat = Math.round(d.data.value * 100) / 100;
tooltip.select(".label").html(d.data.label);
tooltip.select(".value").html("EF: " + EF_per_cat);
tooltip.style("display", "block");
});
path.on("mousemove", function(d){
tooltip.style("top", (d3v5.event.pageY - 00) + "px")
.style("left", (d3v5.event.pageX - 0) + "px");
});
path.on("mouseout", function(d){
tooltip.style("display", "none");
});
// legend
var legend = svg1.selectAll(".legend")
.data(colorScale.domain())
.enter()
.append("g")
.attr("class", "legend")
.attr("transform", function(d,i){
var height = legendRectSize + legendSpacing
var offset = height * colorScale.domain().length / 2
var horz = 5 * legendRectSize
var vert = i * height - offset
return "translate(" + horz + "," + (vert - 16) + ")";
})
legend.append("rect")
.attr("width", legendRectSize)
.attr("height", legendRectSize)
.style("fill", colorScale)
.style("stroke", colorScale)
legend.append("text")
.data(input)
.attr("x", legendRectSize + 2 * legendSpacing)
.attr("y", legendRectSize - 2 * legendSpacing)
.text(function(d){ return d.label; })
}
function update(){
var element = document.getElementById("chart")
while(element.firstChild){
element.removeChild(element.firstChild)
}
}
<file_sep>#!/usr/bin/env python
# Name: <NAME>
# Student number: 11038926
"""
This script visualizes data obtained from a .csv file
"""
import csv
import matplotlib.pyplot as plt
import numpy as np
# Global constants for the input file, first and last year
INPUT_CSV = "movies.csv"
START_YEAR = 2008
END_YEAR = 2018
# Global dictionary for the data
data_dict = {str(key): [] for key in range(START_YEAR, END_YEAR)}
# open csv and read Ratings into dictionary
with open(INPUT_CSV) as csvfile:
input_file = csv.DictReader(csvfile)
for row in input_file:
for key in range(START_YEAR, END_YEAR):
key = str(key)
if row['Year'] == key:
data_dict[key].append(float(row['Rating']))
# calculate the mean Rating for every year and put in dictionary
mean = {str(key): [] for key in range(START_YEAR, END_YEAR)}
for key in range(START_YEAR, END_YEAR):
key = str(key)
ratings = data_dict[key]
mean[key].append(round(sum(ratings)/len(ratings),2))
# VISUALIZE
# line with mean ratings by year
plt.subplot(211)
plt.plot(*zip(*sorted(mean.items())), 'r')
plt.ylim(0,10)
plt.title('Top 50: Average rating & number of movies by year')
plt.ylabel('Average rating')
# bar of number of movies in top 50 by year
number_movies = {str(key): [] for key in range(START_YEAR, END_YEAR)}
for key in range(START_YEAR, END_YEAR):
key = str(key)
number_movies[key].append(len(data_dict[key]))
#plt.subplot(212)
plt.subplot(212)
plt.plot(*zip(*sorted(number_movies.items())), 'b')
plt.xlabel('Years')
plt.ylabel('Number of movies')
plt.show()
if __name__ == "__main__":
print(data_dict)<file_sep># Data Processing 2019
By <NAME> - University of Amsterdam
Link to my site:
https://sofielohr.github.io/dataprocessing/
|
82a637d23a8b4d6deee6055a2fc4cb59580d7372
|
[
"JavaScript",
"Python",
"Markdown"
] | 7 |
Python
|
sofielohr/dataprocessing
|
93732d40443fa8e8c05e0f0c9d177c06387a40f3
|
e56864303f3fc6503b7ed190514714526654f45d
|
refs/heads/master
|
<file_sep>package com.duruo.util;
/**
* Created by @Author tachai
* date 2018/8/10 15:05
*
* @Email <EMAIL>
*/
public class Contain {
public static boolean contain(String content,String core){
if(content.indexOf(core)!=-1){
return true;
}
return false;
}
public static boolean containLast(String content,String core){
if (content.lastIndexOf(core)!=-1){
return true;
}
return false;
}
public static boolean containImage(String str){
if(str.indexOf(".jpg")!=-1||str.indexOf(".png")!=-1||str.indexOf(".jpeg")!=-1){
return true;
}
return false;
}
}
<file_sep><?php
if (!function_exists('curl_version')){
echo 'Please ensure curl is enabled on php|web<br />';
echo ' -- http://curl.haxx.se/libcurl/php/install.html<br />';
echo ' -- http://php.net/manual/en/curl.installation.php<br />';
die();
}
function moderate_url($image_url){
$ajax_url = "https://www.moderatecontent.com/api/?url=" . $image_url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $ajax_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$curl_result = curl_exec($ch);
curl_close($ch);
if ($curl_result === false){
$curl_result = (object)array();
$curl_result->error_code = 9999;
$curl_result->error = "Curl could not reach url.";
}
return json_encode($curl_result);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ModerateContent.com - The FREE Content Moderation API</title>
</head>
<body style="font-family: verdana;">
<a href="https://www.moderatecontent.com" target="_blank"><img src="http://www.moderatecontent.com/img/logo.png" alt="ModerateContent.com" /></a><hr />
<h1>Example: PHP - Curl && GET</h1>
<div id="this_is_where_we_put_the_results"><?php echo moderate_url("http://www.moderatecontent.com/img/logo.png"); ?></div>
</body>
</html>
<?php
die();<file_sep>package com.duruo.util;
import com.duruo.dto.Duihua;
import com.duruo.dto.Objectjson;
import com.duruo.dto.Task;
import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import java.util.*;
/**
* Created by @Author tachai
* date 2018/7/10 16:31
*
* @Email <EMAIL>
*/
@Slf4j
public class WeChatParseJson {
//无效代码
public static JsonObject parseJson(String key, JsonObject jsonObject) {
if (jsonObject.get("id").toString().equals(key)) {
return jsonObject;
} else {
JsonArray jsonArray = jsonObject.getAsJsonArray("answer");
if (jsonArray != null) {
int len = jsonArray.size();
for (int i = 0; i < len; i++) {
WeChatParseJson.parseJson(key, (JsonObject) jsonArray.get(i));
}
}
}
return null;
}
/**
* 清除任务
*
* @param weChatId
* @param flowName
* @return
*/
public static String clearTask(String weChatId, String flowName) {
Task task = new Task();
task.setUserId(weChatId);
task.setTaskName(flowName);
Duihua duihua = new Duihua();
duihua.setData(task);
duihua.setType("userTask");
duihua.setEdit("3");
String data = new Gson().toJson(duihua);
String res = HttpUtil.okhttp(PropertiesUtil.getProperty("duihua.url"), data);
log.info("删除任务;{}", flowName);
return res;
}
/**
* 删除session
* @param weChatId
// * @param flowName
* @return
*/
public static String clearSession(String weChatId) {
Task task = new Task();
task.setUserId(weChatId);
// task.setTaskName(flowName);
Duihua duihua = new Duihua();
duihua.setData(task);
duihua.setType("session");
duihua.setEdit("3");
String data = new Gson().toJson(duihua);
String res = HttpUtil.okhttp(PropertiesUtil.getProperty("duihua.url"), data);
log.info("删除session;{}", weChatId);
return res;
}
/**
* 多个数据源返回有数据的
*
* @param weChatId
* @param taskName1 要输入的流程名1
* @param taskName2 要输入的流程名2
* @return
*/
public static String checkNotNull(String weChatId, String taskName1, String taskName2, String taskName3) {
Task task = new Task();
task.setUserId(weChatId);
// 设置微信接口要的数据
task.setTaskName(taskName1);
Duihua duihua = new Duihua();
duihua.setData(task);
duihua.setType("userTask");
duihua.setEdit("1");
String data = new Gson().toJson(duihua);
//todo session里面
String res = HttpUtil.okhttp(PropertiesUtil.getProperty("duihua.url"), data);
task.setTaskName(taskName2);
duihua.setData(task);
String data1 = new Gson().toJson(duihua);
String res1 = HttpUtil.okhttp(PropertiesUtil.getProperty("duihua.url"), data1);
task.setTaskName(taskName3);
duihua.setData(task);
String data2 = new Gson().toJson(duihua);
String res2 = HttpUtil.okhttp(PropertiesUtil.getProperty("duihua.url"), data2);
//实时查询
Map<String, String> map = new Hashtable<>();
map.put("userId", weChatId);
duihua.setData(map);
duihua.setType("session");
duihua.setEdit("1");
String data0 = new Gson().toJson(duihua);
String res0 = HttpUtil.okhttp(PropertiesUtil.getProperty("duihua.url"), data0);
if (res0.length() > 50) {
log.info("返回的数据:{}", res0);
return res0;
} else if (res.length() > 50) {
log.info("返回的数据:{}", res);
clearTask(weChatId,taskName1);
clearSession(weChatId);
return res;
} else if (res1.length() > 50) {
log.info("返回的数据:{}", res1);
clearTask(weChatId,taskName2);
clearSession(weChatId);
return res1;
} else if(res2.length()>50) {
log.info("返回的数据:{}", res2);
clearTask(weChatId,taskName3);
clearSession(weChatId);
return res2;
}
return "空";
}
/**
* 一个流程里面
*
* @param weChatId
* @param taskName1
* @return
*/
public static String checkNotNull(String weChatId, String taskName1) {
Task task = new Task();
task.setUserId(weChatId);
//todo 设置微信接口要的数据
task.setTaskName(taskName1);
Duihua duihua = new Duihua();
duihua.setData(task);
duihua.setType("userTask");
duihua.setEdit("1");
String data = new Gson().toJson(duihua);
String res = HttpUtil.okhttp(PropertiesUtil.getProperty("duihua.url"), data);
return res;
}
/**
* 递归得到所有的json
*
* @param jsonObject
* @return
*/
public static List<Objectjson> diguiJson(List<Objectjson> listJson, JsonObject jsonObject) {
JsonArray jsonArray = jsonObject.getAsJsonArray("answer");
if (jsonArray != null) {
int len = jsonArray.size();
for (int i = 0; i < len; i++) {
JsonObject json = (JsonObject) jsonArray.get(i);
Objectjson objectjson = new Objectjson();
objectjson.setJsonObject(json);
objectjson.setKey(json.get("id").toString());
listJson.add(objectjson);
WeChatParseJson.diguiJson(listJson, json);
}
}
return listJson;
}
/**
* 通过id得到jsonObject对象
*
* @param id
* @param jsonObject
* @return
*/
public static JsonObject getJsonObjectById(Integer id, JsonObject jsonObject) {
List<Objectjson> list = new ArrayList<>();
List<Objectjson> temp = WeChatParseJson.diguiJson(list, jsonObject);
Objectjson objectjson = temp.stream().filter(u -> u.getKey().equals(id.toString()))
.findAny()
.orElse(null);
return objectjson.getJsonObject();
}
/**
* 通过问题id得到问题的值
*
* @param jsonObject
* @param id
* @return
*/
public static String getValueById(JsonObject jsonObject, Integer id) {
JsonObject jsonObject1 = getJsonObjectById(id, jsonObject);
JsonArray jsonArray = jsonObject1.getAsJsonArray("answer");
JsonObject jsonObject2 = (JsonObject) jsonArray.get(0);
if (null != jsonObject2.get("userInput")) {
//得到userInput中的值去掉首尾的“”
return com.duruo.util.StringUtils.trim(jsonObject2.get("userInput").getAsJsonArray().get(0).toString().trim(), '"');
} else {
return " ";
}
}
/**
* 得到json对象中userQuery中的值
*
* @return
*/
public static String getUserQuery(JsonObject jsonObject, Integer id) {
JsonObject jsonObject3 = WeChatParseJson.getJsonObjectById(id, jsonObject);
JsonArray jsonArray3 = jsonObject3.getAsJsonArray("userQuery");
if (null != jsonArray3) {
return com.duruo.util.StringUtils.trim(jsonArray3.get(jsonArray3.size() - 1).toString(), '"');
// return jsonArray3.get(jsonArray3.size()-1).toString().replace("\"","");
}
return null;
}
/**
* 递归json Answer对象
*
* @param key 递归的键
* @param n 递归的层数
* @param jsonObject 返回的json对象
* @return
*/
public static JsonObject recursionJson(String key, int n, JsonObject jsonObject) {
JsonObject json;
if (n == 0) {
return jsonObject;
} else {
JsonArray jsonArray = jsonObject.getAsJsonArray(key);
json = (JsonObject) jsonArray.get(0);
}
return recursionJson(key, n - 1, json);
}
/**
* @param key 递归的键
* @param n 递归的层数
* @param i 递归第几个对象
* @param jsonObject 返回的json对象
* @return
*/
public static JsonObject recursionJson(String key, int n, int i, JsonObject jsonObject) {
JsonObject json;
if (n == 0) {
return jsonObject;
} else {
JsonArray jsonArray = jsonObject.getAsJsonArray(key);
json = (JsonObject) jsonArray.get(i);
}
return recursionJson(key, n - 1, i, json);
}
/**
* 最后一层answer得到用户输入的值
*
* @param jsonObject 传入的json对象
* @param i 第几个问题的答案
* @return
*/
public static String getValue(JsonObject jsonObject, int i) {
JsonArray jsonArray = jsonObject.getAsJsonArray("answer");
JsonObject value = (JsonObject) jsonArray.get(i);
JsonObject value1 = (JsonObject) value.getAsJsonArray("answer").get(0);
if (null != value1.get("userInput")) {
return value1.get("userInput").getAsJsonArray().get(0).toString().trim();
} else {
return "false";
}
}
/**
* 解析微信json返回的值
*
* @param json
* @return
*/
public static JsonObject parseWeChatJson(JsonObject json) {
try {
JsonObject json1 = json.getAsJsonObject("info");
JsonObject json2 = json1.getAsJsonObject("taskInfo");
//实时查询中不会有taskInfo
if (null == json2) {
JsonObject json3 = json1.getAsJsonObject("tasks");
return json3;
} else {
JsonObject json3 = json2.getAsJsonObject("tasks");
return json3;
}
} catch (JsonIOException e) {
e.getStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 酒类零售许可证书
*
* @param jsonObject
* @return
*/
public static Map<String, String> liquorSigle(JsonObject jsonObject) {
Map<String, String> map = new HashMap<>();
map.put("companyName", WeChatParseJson.getValueById(jsonObject, 5001));
map.put("legalRepresentName", WeChatParseJson.getValueById(jsonObject, 5007));
map.put("enterpriseType", WeChatParseJson.getValueById(jsonObject, 5003));
//企业类型是有多种 选择最后一个值
map.put("enterpriseCategory", WeChatParseJson.getUserQuery(jsonObject, 5005));
map.put("businessAddress", WeChatParseJson.getValueById(jsonObject, 5017));
map.put("streetName", WeChatParseJson.getValueById(jsonObject, 5011));
map.put("businessArea", WeChatParseJson.getValueById(jsonObject, 5019));
map.put("legalRepresentPhone", WeChatParseJson.getValueById(jsonObject, 5009));
map.put("staffNumber", WeChatParseJson.getValueById(jsonObject, 5015));
map.put("faxNumber", WeChatParseJson.getValueById(jsonObject, 5013));
map.put("businessLicenseValidity", WeChatParseJson.getValueById(jsonObject, 5021));
map.put("foodLicenseValidity", WeChatParseJson.getValueById(jsonObject, 5023));
map.put("transactorName", WeChatParseJson.getValueById(jsonObject, 5025));
map.put("transactorPhone", WeChatParseJson.getValueById(jsonObject, 5027));
return map;
}
/**
* 解析公共卫生安全模块填表
*/
public static Map<String, String> publicHelth(JsonObject jsonObject) {
Map<String, String> map = new HashMap<>();
map.put("applyName", WeChatParseJson.getValueById(jsonObject, 7055));
map.put("operatingAddress", WeChatParseJson.getValueById(jsonObject, 7057));
map.put("competentDepartment", WeChatParseJson.getValueById(jsonObject, 7059));
map.put("totalArea", WeChatParseJson.getValueById(jsonObject, 7061));
map.put("ownerStreet", WeChatParseJson.getValueById(jsonObject, 7074));
map.put("ownerCommunity", WeChatParseJson.getValueById(jsonObject, 7076));
map.put("personName", WeChatParseJson.getValueById(jsonObject, 7078));
map.put("idCard", WeChatParseJson.getValueById(jsonObject, 7080));
map.put("headHealth", WeChatParseJson.getValueById(jsonObject, 7082));
map.put("postalCode", WeChatParseJson.getValueById(jsonObject, 7084));
map.put("contactTel", WeChatParseJson.getValueById(jsonObject, 7086));
map.put("totalWorkers", WeChatParseJson.getValueById(jsonObject, 7088));
map.put("directCustomerEmploy", WeChatParseJson.getValueById(jsonObject, 7090));
map.put("healthCertificateNumber", WeChatParseJson.getValueById(jsonObject, 7092));
//饮用水 选择最后一个值
map.put("drinkingWaterType", WeChatParseJson.getUserQuery(jsonObject, 7094).toUpperCase());
//空调 选择最后一个值
map.put("airConditioningType", WeChatParseJson.getUserQuery(jsonObject, 7105).toUpperCase());
//经济类型 选择最后一个值
JsonObject jsonObject3 = WeChatParseJson.getJsonObjectById(7063, jsonObject);
String temp = WeChatParseJson.getUserQuery(jsonObject, 7063);
if (WeChatParseJson.getUserQuery(jsonObject, 7063).equals("A")) {
temp = "企业";
} else if (WeChatParseJson.getUserQuery(jsonObject, 7063).equals("B")) {
temp = "企业分支机构";
} else if (WeChatParseJson.getUserQuery(jsonObject, 7063).equals("C")) {
temp = "个体工商户";
} else if (WeChatParseJson.getUserQuery(jsonObject, 7063).equals("D")) {
temp = "事业单位";
} else if (WeChatParseJson.getUserQuery(jsonObject, 7063).equals("E")) {
temp = "民办非企业单位";
}
map.put("economicType", temp);
return map;
}
/**
* 数字证书办理
*
* @param jsonObject
*/
public static Map<String, String> electronicDigital(JsonObject jsonObject) {
Map<String, String> map = new HashMap<>();
map.put("unitName", WeChatParseJson.getValueById(jsonObject, 8002));
map.put("unitMailingAddress", WeChatParseJson.getValueById(jsonObject, 8004));
map.put("postalCode", WeChatParseJson.getValueById(jsonObject, 8006));
map.put("unifiedCreditCode", WeChatParseJson.getValueById(jsonObject, 8008));
String value = WeChatParseJson.getValueById(jsonObject, 8010);
map.put("businessLicenseNumber",value.equals("无")?"":value);
String value1 = WeChatParseJson.getValueById(jsonObject, 8012);
map.put("accountOfHousing",value1.equals("无")?"":value1 );
String value2 = WeChatParseJson.getValueById(jsonObject, 8014);
map.put("organizationCode", value2.equals("无")?"":value2);
String value3 = WeChatParseJson.getValueById(jsonObject, 8014);
map.put("socialInsuranceNumber", value3.equals("无")?"":value3);
map.put("legalRepresentative", WeChatParseJson.getValueById(jsonObject, 8018));
map.put("legalIdCard", WeChatParseJson.getValueById(jsonObject, 8020));
map.put("legalLinkTel", WeChatParseJson.getValueById(jsonObject, 8022));
map.put("transactorName", WeChatParseJson.getValueById(jsonObject, 8024));
map.put("transactorIdCard", WeChatParseJson.getValueById(jsonObject, 8026));
map.put("transactorLinkTel", WeChatParseJson.getValueById(jsonObject, 8028));
map.put("email", WeChatParseJson.getValueById(jsonObject, 8030));
map.put("fax", WeChatParseJson.getValueById(jsonObject, 8032));
return map;
}
/**
* 生成特种设备按台套
*
* @param jsonObject
* @return
*/
public static Map<String, String> specialEquipment1(JsonObject jsonObject) {
Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
map.put("typeEquipment", WeChatParseJson.getValueById(jsonObject, 6028));
map.put("equipmentCategory", WeChatParseJson.getValueById(jsonObject, 6004));
map.put("productName", WeChatParseJson.getValueById(jsonObject, 6008));
map.put("model", WeChatParseJson.getValueById(jsonObject, 6032));
map.put("designUnitName", WeChatParseJson.getValueById(jsonObject, 6036));
map.put("constructionUnitName", WeChatParseJson.getValueById(jsonObject, 6040));
map.put("testMechanismName", WeChatParseJson.getValueById(jsonObject, 6044));
map.put("equipmentVariety", WeChatParseJson.getValueById(jsonObject, 6006));
map.put("deviceCode", WeChatParseJson.getValueById(jsonObject, 6030));
map.put("designServiceLife", WeChatParseJson.getValueById(jsonObject, 6034));
map.put("manufacturingUnitName", WeChatParseJson.getValueById(jsonObject, 6038));
map.put("supervisionAgency", WeChatParseJson.getValueById(jsonObject, 6042));
map.put("useUnitName", WeChatParseJson.getValueById(jsonObject, 6010));
map.put("useUnitAddress", WeChatParseJson.getValueById(jsonObject, 6012));
map.put("useUnitSocialCreditCode", WeChatParseJson.getValueById(jsonObject, 6018));
map.put("unitNumber", WeChatParseJson.getValueById(jsonObject, 6046));
map.put("useDate", WeChatParseJson.getValueById(jsonObject, 6048));
map.put("securityAdministrator", WeChatParseJson.getValueById(jsonObject, 6022));
map.put("unitRightName", WeChatParseJson.getValueById(jsonObject, 6050));
map.put("unitRightCreditCode", WeChatParseJson.getValueById(jsonObject, 6052));
map.put("inspectionName", WeChatParseJson.getValueById(jsonObject, 6056));
map.put("insectionCategory", WeChatParseJson.getValueById(jsonObject, 6058));
map.put("inspectionDate", WeChatParseJson.getValueById(jsonObject, 6062));
map.put("nextTestDate", WeChatParseJson.getValueById(jsonObject, 6066));
map.put("postalCode", WeChatParseJson.getValueById(jsonObject, 6020));
map.put("useEquipmentPlace", WeChatParseJson.getValueById(jsonObject, 6014));
map.put("unitTel", WeChatParseJson.getValueById(jsonObject, 6016));
map.put("mobilePhone", WeChatParseJson.getValueById(jsonObject, 6024));
map.put("linkTel", WeChatParseJson.getValueById(jsonObject, 6054));
map.put("insectionReportNumber", WeChatParseJson.getValueById(jsonObject, 6060));
map.put("testConclusion", WeChatParseJson.getValueById(jsonObject, 6064));
return map;
}
/**
* 生成特种设备按单位
*
* @param jsonObject
* @return
*/
public static Map<String, String> specialEquipment2(JsonObject jsonObject) {
Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
map.put("equipmentCategory", WeChatParseJson.getValueById(jsonObject, 6004));
map.put("productName", WeChatParseJson.getValueById(jsonObject, 6008));
map.put("equipmentVariety", WeChatParseJson.getValueById(jsonObject, 6006));
map.put("useUnitName", WeChatParseJson.getValueById(jsonObject, 6010));
map.put("useUnitAddress", WeChatParseJson.getValueById(jsonObject, 6012));
map.put("useUnitSocialCreditCode", WeChatParseJson.getValueById(jsonObject, 6018));
map.put("securityAdministrator", WeChatParseJson.getValueById(jsonObject, 6022));
map.put("postalCode", WeChatParseJson.getValueById(jsonObject, 6020));
map.put("unitTel", WeChatParseJson.getValueById(jsonObject, 6016));
map.put("mobilePhone", WeChatParseJson.getValueById(jsonObject, 6024));
map.put("equipmentNumber", WeChatParseJson.getValueById(jsonObject, 6026));
map.put("useEquipmentPlace", WeChatParseJson.getValueById(jsonObject, 6014));
return map;
}
/**
* 外来从业人员用工备案登记
* @param jsonObject
* @return
*/
public static Map<String,Object> recordRegistrationOfMaigrantWorkers(JsonObject jsonObject){
return null;
}
}
<file_sep>package com.duruo.po;
public class Enterprise {
private String creditcode;
private String realname;
private String email;
private String mobile;
private String userid;
private String contactsname;
private String contactsphone;
private String contactspost;
private String landline;
private String registdate;
private String companyaptitude;
private String companytypeid;
private String attachmentlogoid;
private String leasefile;
//上一年度注册资本:
private String registcapital;
private String legalperson;
private String registadress;
private String businessaddress;
private String serviceareaid;
private String servicessubcatalogids;
//上一年度营业收入
private String ywsr;
private String zcze;
//就业岗位数量
private String jobsnumber;
private String zzry;
private String fwqyhc;
private String zzqk;
private String introduce;
//税收总额
private String taxamount;
//上一年度净利润
private String profit;
private String ismatchingbase;
private String oldenterprise;
private String oldposition;
private String weworkdirectory;
private String overtcipher;
private String coordinate;
//经营范围
private String scopebusiness;
private String usertype;
//单位电话
private String worktelephone;
private String department;
private String annualrevenue;
private String annualtax;
private String expectedbenefit;
public String getCreditcode() {
return creditcode;
}
public void setCreditcode(String creditcode) {
this.creditcode = creditcode == null ? null : creditcode.trim();
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname == null ? null : realname.trim();
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email == null ? null : email.trim();
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile == null ? null : mobile.trim();
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid == null ? null : userid.trim();
}
public String getContactsname() {
return contactsname;
}
public void setContactsname(String contactsname) {
this.contactsname = contactsname == null ? null : contactsname.trim();
}
public String getContactsphone() {
return contactsphone;
}
public void setContactsphone(String contactsphone) {
this.contactsphone = contactsphone == null ? null : contactsphone.trim();
}
public String getContactspost() {
return contactspost;
}
public void setContactspost(String contactspost) {
this.contactspost = contactspost == null ? null : contactspost.trim();
}
public String getLandline() {
return landline;
}
public void setLandline(String landline) {
this.landline = landline == null ? null : landline.trim();
}
public String getRegistdate() {
return registdate;
}
public void setRegistdate(String registdate) {
this.registdate = registdate == null ? null : registdate.trim();
}
public String getCompanyaptitude() {
return companyaptitude;
}
public void setCompanyaptitude(String companyaptitude) {
this.companyaptitude = companyaptitude == null ? null : companyaptitude.trim();
}
public String getCompanytypeid() {
return companytypeid;
}
public void setCompanytypeid(String companytypeid) {
this.companytypeid = companytypeid == null ? null : companytypeid.trim();
}
public String getAttachmentlogoid() {
return attachmentlogoid;
}
public void setAttachmentlogoid(String attachmentlogoid) {
this.attachmentlogoid = attachmentlogoid == null ? null : attachmentlogoid.trim();
}
public String getLeasefile() {
return leasefile;
}
public void setLeasefile(String leasefile) {
this.leasefile = leasefile == null ? null : leasefile.trim();
}
public String getRegistcapital() {
return registcapital;
}
public void setRegistcapital(String registcapital) {
this.registcapital = registcapital == null ? null : registcapital.trim();
}
public String getLegalperson() {
return legalperson;
}
public void setLegalperson(String legalperson) {
this.legalperson = legalperson == null ? null : legalperson.trim();
}
public String getRegistadress() {
return registadress;
}
public void setRegistadress(String registadress) {
this.registadress = registadress == null ? null : registadress.trim();
}
public String getBusinessaddress() {
return businessaddress;
}
public void setBusinessaddress(String businessaddress) {
this.businessaddress = businessaddress == null ? null : businessaddress.trim();
}
public String getServiceareaid() {
return serviceareaid;
}
public void setServiceareaid(String serviceareaid) {
this.serviceareaid = serviceareaid == null ? null : serviceareaid.trim();
}
public String getServicessubcatalogids() {
return servicessubcatalogids;
}
public void setServicessubcatalogids(String servicessubcatalogids) {
this.servicessubcatalogids = servicessubcatalogids == null ? null : servicessubcatalogids.trim();
}
public String getYwsr() {
return ywsr;
}
public void setYwsr(String ywsr) {
this.ywsr = ywsr == null ? null : ywsr.trim();
}
public String getZcze() {
return zcze;
}
public void setZcze(String zcze) {
this.zcze = zcze == null ? null : zcze.trim();
}
public String getJobsnumber() {
return jobsnumber;
}
public void setJobsnumber(String jobsnumber) {
this.jobsnumber = jobsnumber == null ? null : jobsnumber.trim();
}
public String getZzry() {
return zzry;
}
public void setZzry(String zzry) {
this.zzry = zzry == null ? null : zzry.trim();
}
public String getFwqyhc() {
return fwqyhc;
}
public void setFwqyhc(String fwqyhc) {
this.fwqyhc = fwqyhc == null ? null : fwqyhc.trim();
}
public String getZzqk() {
return zzqk;
}
public void setZzqk(String zzqk) {
this.zzqk = zzqk == null ? null : zzqk.trim();
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce == null ? null : introduce.trim();
}
public String getTaxamount() {
return taxamount;
}
public void setTaxamount(String taxamount) {
this.taxamount = taxamount == null ? null : taxamount.trim();
}
public String getProfit() {
return profit;
}
public void setProfit(String profit) {
this.profit = profit == null ? null : profit.trim();
}
public String getIsmatchingbase() {
return ismatchingbase;
}
public void setIsmatchingbase(String ismatchingbase) {
this.ismatchingbase = ismatchingbase == null ? null : ismatchingbase.trim();
}
public String getOldenterprise() {
return oldenterprise;
}
public void setOldenterprise(String oldenterprise) {
this.oldenterprise = oldenterprise == null ? null : oldenterprise.trim();
}
public String getOldposition() {
return oldposition;
}
public void setOldposition(String oldposition) {
this.oldposition = oldposition == null ? null : oldposition.trim();
}
public String getWeworkdirectory() {
return weworkdirectory;
}
public void setWeworkdirectory(String weworkdirectory) {
this.weworkdirectory = weworkdirectory == null ? null : weworkdirectory.trim();
}
public String getOvertcipher() {
return overtcipher;
}
public void setOvertcipher(String overtcipher) {
this.overtcipher = overtcipher == null ? null : overtcipher.trim();
}
public String getCoordinate() {
return coordinate;
}
public void setCoordinate(String coordinate) {
this.coordinate = coordinate == null ? null : coordinate.trim();
}
public String getScopebusiness() {
return scopebusiness;
}
public void setScopebusiness(String scopebusiness) {
this.scopebusiness = scopebusiness == null ? null : scopebusiness.trim();
}
public String getUsertype() {
return usertype;
}
public void setUsertype(String usertype) {
this.usertype = usertype == null ? null : usertype.trim();
}
public String getWorktelephone() {
return worktelephone;
}
public void setWorktelephone(String worktelephone) {
this.worktelephone = worktelephone == null ? null : worktelephone.trim();
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department == null ? null : department.trim();
}
public String getAnnualrevenue() {
return annualrevenue;
}
public void setAnnualrevenue(String annualrevenue) {
this.annualrevenue = annualrevenue == null ? null : annualrevenue.trim();
}
public String getAnnualtax() {
return annualtax;
}
public void setAnnualtax(String annualtax) {
this.annualtax = annualtax == null ? null : annualtax.trim();
}
public String getExpectedbenefit() {
return expectedbenefit;
}
public void setExpectedbenefit(String expectedbenefit) {
this.expectedbenefit = expectedbenefit == null ? null : expectedbenefit.trim();
}
}<file_sep>package com.example.demo.pojo;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Objects;
@Entity
@Table(name = "fourth_level_risk", schema = "risk_assessment", catalog = "")
public class FourthLevelRiskDO {
private int id;
private String fourthLevelRiskCode;
private String fourthLevelRiskName;
private String fourthLevelRiskDescription;
private String firstLevelRiskCode;
private String secondLevelRiskCode;
private String thirdLevelRiskCode;
private Timestamp fourthLevelRiskDate;
private String fourthLevelRiskCompany;
private String fourthLevelRiskDepartment;
private String fourthLevelRiskApplication;
@Id
@Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "fourth_level_risk_code")
public String getFourthLevelRiskCode() {
return fourthLevelRiskCode;
}
public void setFourthLevelRiskCode(String fourthLevelRiskCode) {
this.fourthLevelRiskCode = fourthLevelRiskCode;
}
@Basic
@Column(name = "fourth_level_risk_name")
public String getFourthLevelRiskName() {
return fourthLevelRiskName;
}
public void setFourthLevelRiskName(String fourthLevelRiskName) {
this.fourthLevelRiskName = fourthLevelRiskName;
}
@Basic
@Column(name = "fourth_level_risk_description")
public String getFourthLevelRiskDescription() {
return fourthLevelRiskDescription;
}
public void setFourthLevelRiskDescription(String fourthLevelRiskDescription) {
this.fourthLevelRiskDescription = fourthLevelRiskDescription;
}
@Basic
@Column(name = "first_level_risk_code")
public String getFirstLevelRiskCode() {
return firstLevelRiskCode;
}
public void setFirstLevelRiskCode(String firstLevelRiskCode) {
this.firstLevelRiskCode = firstLevelRiskCode;
}
@Basic
@Column(name = "second_level_risk_code")
public String getSecondLevelRiskCode() {
return secondLevelRiskCode;
}
public void setSecondLevelRiskCode(String secondLevelRiskCode) {
this.secondLevelRiskCode = secondLevelRiskCode;
}
@Basic
@Column(name = "third_level_risk_code")
public String getThirdLevelRiskCode() {
return thirdLevelRiskCode;
}
public void setThirdLevelRiskCode(String thirdLevelRiskCode) {
this.thirdLevelRiskCode = thirdLevelRiskCode;
}
@Basic
@Column(name = "fourth_level_risk_date")
public Timestamp getFourthLevelRiskDate() {
return fourthLevelRiskDate;
}
public void setFourthLevelRiskDate(Timestamp fourthLevelRiskDate) {
this.fourthLevelRiskDate = fourthLevelRiskDate;
}
@Basic
@Column(name = "fourth_level_risk_company")
public String getFourthLevelRiskCompany() {
return fourthLevelRiskCompany;
}
public void setFourthLevelRiskCompany(String fourthLevelRiskCompany) {
this.fourthLevelRiskCompany = fourthLevelRiskCompany;
}
@Basic
@Column(name = "fourth_level_risk_department")
public String getFourthLevelRiskDepartment() {
return fourthLevelRiskDepartment;
}
public void setFourthLevelRiskDepartment(String fourthLevelRiskDepartment) {
this.fourthLevelRiskDepartment = fourthLevelRiskDepartment;
}
@Basic
@Column(name = "fourth_level_risk_application")
public String getFourthLevelRiskApplication() {
return fourthLevelRiskApplication;
}
public void setFourthLevelRiskApplication(String fourthLevelRiskApplication) {
this.fourthLevelRiskApplication = fourthLevelRiskApplication;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FourthLevelRiskDO that = (FourthLevelRiskDO) o;
return id == that.id &&
Objects.equals(fourthLevelRiskCode, that.fourthLevelRiskCode) &&
Objects.equals(fourthLevelRiskName, that.fourthLevelRiskName) &&
Objects.equals(fourthLevelRiskDescription, that.fourthLevelRiskDescription) &&
Objects.equals(firstLevelRiskCode, that.firstLevelRiskCode) &&
Objects.equals(secondLevelRiskCode, that.secondLevelRiskCode) &&
Objects.equals(thirdLevelRiskCode, that.thirdLevelRiskCode) &&
Objects.equals(fourthLevelRiskDate, that.fourthLevelRiskDate) &&
Objects.equals(fourthLevelRiskCompany, that.fourthLevelRiskCompany) &&
Objects.equals(fourthLevelRiskDepartment, that.fourthLevelRiskDepartment) &&
Objects.equals(fourthLevelRiskApplication, that.fourthLevelRiskApplication);
}
@Override
public int hashCode() {
return Objects.hash(id, fourthLevelRiskCode, fourthLevelRiskName, fourthLevelRiskDescription, firstLevelRiskCode, secondLevelRiskCode, thirdLevelRiskCode, fourthLevelRiskDate, fourthLevelRiskCompany, fourthLevelRiskDepartment, fourthLevelRiskApplication);
}
}
<file_sep>
### ModerateContent.com - The FREE Content Moderation API (https://www.moderatecontent.com)
Our free API provides a content rating for any image. Detect inappropriate content from adult to violent and more subtle ratings including smoking, alcohol and suggestive.
Examples of consuming the API with Python 2.7.<file_sep>package com.duruo.dto;
import lombok.Builder;
import lombok.Data;
import java.util.List;
/**
* Created by @Author tachai
* date 2018/6/27 10:20
*
* @Email <EMAIL>
*/
@Data
public class PostData {
private List<FlowData> FlowData;
@Builder.Default
private String FlowKey = "7522cf1d-ea2c-8605-7c83-c4e739338b14";
private String FlowSN;
private String ProjectId;
@Builder.Default
private String BizTable = "DB_Flow_Jjkc_Info";
@Builder.Default
private String NodeIsAuto = "True";
@Builder.Default
private String UpLoadFileId = "";
private DataFields dataFields;
@Builder.Default
private String ActionMode = "Save";
}
<file_sep>[TOC]
能翻个墙上个外网,不代表认知就高人一等。
有时候反而加重了一些人的无知和偏见,尤其是那些头脑本来就很偏执的人。对技术人员群体,尤其如此。墙外中文圈、华人圈混乱的很。虚伪,肮脏,丑陋甚至邪恶的地方不胜枚举。
曾看到一位公益机场大佬写的,大实话:谨慎对待墙外媒体,理性爱国。当下的中国,如果没有稳定,什么都不是。
国外的虚假、恶意、伪善新闻更多。作为一个人,应当有基本的独立思考能力、查证与辨别是非的能力。
## #墙外信息的价值:
墙外信息的价值仅在于一些人文社科、科学技术类工具资源和便利等。师夷长技以制夷。除了工具资源便利之外,有价值的可能只是一些思维方式和角度而已。(这方面不得不说国内教育和社会环境缺陷。上不愿意正视过去,下不愿意独立思考。)
需要警惕外网思想渗透、文化入侵和似是而非的所谓“自由平等民主”价值观。白左、虚无主义、宗教极端主义,所有那些让人变傻,愚弄误导人的洗脑信息。(当然,除了明面上,暗地里搞得东西更多)
有个段子:墙外转了一圈,中东那边是阿拉伯,落后封闭,南亚那些就不必提了,日韩除了净是些东洋鬼子的娱乐八卦,非洲网络几乎是史前文明,唯一有价值的欧美世界还充斥着各种极端言论、反华喷子、垃圾信息。
推荐阅读:
- 简书文章:https://www.jianshu.com/p/632e40db706a
### #推荐一些比较客观中立的媒体:
可以RSS订阅(opml源文件在GitHub相关插件数据中):
RSS链接被知乎污染,请从Github 的opml源文件中添加
opml文件,可导入RSS阅读器。
信息 资讯
[新西兰先驱报中文网](https://link.zhihu.com/?target=http%3A//www.chinesenzherald.co.nz/)
彭博社
纽约时报
FT中文网
界面新闻
MSNBC
郝芬顿邮报Huffpost
(题外话:中国文化里讲“道法术器势”,道法层面我们的底蕴、我们的根本极其深厚,但凡用心体会过古中国思想文化的人都隐隐约约、或多或少的明白点什么*(中国文化在焚书坑儒,汉末,五胡乱华,唐末,五代十国等几次动乱里都受过一些打击,秦汉开始某些核心的东西开始衰落或减少、避世,一直到宋末,宋以后的文化里出现许多混乱、失传、或遭篡改、甚至胡编滥造的现象,明清时期乱象丛生,到现代改革开放后,世事人心和文化到了扭曲偏歪到了一个极端;颠倒幻妄的地方太多太多,我们甚至把某些垃圾文化(如伪国学、满清遗毒)当成中华传统文化)*。反观西方世界,欧美的文化是什么?不到几百年,靠华而不实、虚头巴脑、肤浅幼稚、意淫妄想、浅薄愚妄的表面文章来搞宣传、搞文化输出。仔细想想,美国大片里除了烧钱烧出来的影视特效花里胡俏、乱人眼球、哗众取宠之外,有什么内涵和底蕴,对内心对人生有多大点价值和意义?
什么自由平等民主人权的美国价值观,在破除选举赞助法律、棱镜门、希拉里邮件门、希拉里还没上台前就暗杀纽约警察的时候,美国价值观的底裤早就被扒光了。口惠实不至,虚伪做作。
## #点滴
突然觉得有些时候,人类如果乱用滥用头脑或者心灵低陋恶劣的话,其实并不比某些动物过的更幸福、更高明、更快乐,更有价值和意义。

想起小学时学过的《西雅图酋长的宣言》,莫名有种共鸣和感动,似曾相识,淳朴、干净、真诚,有点像中国远古先秦时的古风。
放纵从来都不是自由,任由恶欲驱使摆弄自己的心灵、思想和身体,绝不是什么真正的快乐,这种所谓的快感就像吸毒、就像饮鸩止渴,不仅无益还会毒害身心。
越放纵,反而离自由越远。(这里有点不太喜欢用自由这个词,太粗糙太幼稚)
<file_sep>package com.duruo.service.impl;
import com.duruo.common.ServerResponse;
import com.duruo.dao.EvidenceFilesMapper;
import com.duruo.dao.RetailLicenseMapper;
import com.duruo.po.EvidenceFiles;
import com.duruo.service.IEvidenceFilesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by @Author tachai
* date 2018/6/25 15:15
*
* @Email <EMAIL>
*/
@Service("iEvidenceFilesService")
public class EvidenceFilesServiceImpl implements IEvidenceFilesService {
@Autowired
private EvidenceFilesMapper evidenceFilesMapper;
@Autowired
private RetailLicenseMapper retailLicenseMapper;
@Override
public ServerResponse<List<EvidenceFiles>> getEvidenceFiles(String deptId) {
if(!StringUtils.isBlank(deptId)){
}
List<EvidenceFiles> list= evidenceFilesMapper.listEvidenceFiles(deptId);
if(null != list){
return ServerResponse.createBySuccess(list,"查询成功");
}
return ServerResponse.createByErrorMessage("未找到相关的数据");
}
@Override
public ServerResponse<List<EvidenceFiles>> getEvidenceDetail(Integer licenseId) {
//使用悲观锁
// retailLicenseMapper.lockByPrimaryKey(licenseId);
List<EvidenceFiles> list= evidenceFilesMapper.listEvidenceFileDetail(licenseId);
if(null != list){
return ServerResponse.createBySuccess(list,"查询成功");
}
return ServerResponse.createByErrorMessage("未找到相关的数据"); }
}
<file_sep>### 文件服务器
## 基本信息
1. 地址192.168.127.12
1. 端口号22
1. sftp服务器
1. 文件存放地址/home/uftp
有两个目录分别是image和files
<file_sep>package com.duruo.common.intereceptor;
import com.alibaba.fastjson.JSONObject;
import com.duruo.util.DateTimeUtil;
import com.duruo.util.JWTUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Created by @Author tachai
* date 2018/7/17 13:42
*
* @Email <EMAIL>
*/
@Slf4j
public class AuthorityInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("preHandle");
JWTUtils util = new JWTUtils();
String jwt = request.getHeader("Authorization");
Date now = new Date();
try {
if(jwt == null){
System.out.println("用户未登录,验证失败");
log.error("当前时间:{},token验证失败,用户未登录", DateTimeUtil.dateToStr(now));
}else {
Claims c;
c = util.parseJWT(jwt);
// 这里换成其他的东西
if(c.get("user_id")!=null){
System.out.println("用户id" + c.get("user_id") + "已是登录状态");
log.info("当前时间:{},token验证成功,用户id:{}",DateTimeUtil.dateToStr(now),c.get("user_id"));
return true;
}
}
response.setContentType("application/json; charset=utf-8");
System.out.println("token解析错误,验证失败");
log.error("当前时间:{},token解析错误,验证失败",DateTimeUtil.dateToStr(now));
Map<String,String> map= new HashMap<>();
map.put("status","error");
map.put("msg","token解析错误,验证失败");
String json = JSONObject.toJSONString(map);
response.getWriter().print(json);
response.getWriter().flush();
response.getWriter().close();
}catch (Exception e){
e.getStackTrace();
response.setContentType("application/json; charset=utf-8");
System.out.println("token解析错误,验证失败");
log.error("当前时间:{},token解析错误,验证失败",DateTimeUtil.dateToStr(now));
Map<String,String> map= new HashMap<>();
map.put("status","error");
map.put("msg","token解析错误,验证失败");
String json = JSONObject.toJSONString(map);
response.getWriter().print(json);
response.getWriter().flush();
response.getWriter().close();
}
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
<file_sep>package com.duruo.vo;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/9/20 15:37
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
//用来接收 多轮对话前端数据判断是那个类型
@Data
public class Qchuang {
private String type;
private QchuangVo data;
}
<file_sep>//package com.example.demo;
//
//import com.example.demo.dao.*;
//import com.example.demo.pojo.*;
//import com.example.demo.service.ArticleService;
//import com.example.demo.service.CompanyService;
//import net.sf.json.JSON;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.context.SpringBootTest;
//import org.springframework.test.context.junit4.SpringRunner;
//
//import java.sql.Timestamp;
//import java.util.ArrayList;
//import java.util.Date;
//import java.util.List;
//
//import static org.aspectj.bridge.Version.getTime;
//
//@RunWith(SpringRunner.class)
//@SpringBootTest
//public class RiskAssessmentApplicationTests {
// @Autowired
// private UserPermissionDAO userPermissionDAO;
// @Autowired
// private UserDAO userDAO;
// @Autowired
// private CompanyService companyService;
// @Autowired
// private ComplantsDAO complantsDAO;
// @Autowired
// private ArticleService articleService;
// @Autowired
// private ArticleDAO articleDAO;
// @Autowired
// private CommentDAO commentDAO;
// @Test
// public void contextLoads() {
// }
// @Test
// public void Savecompany(){
// CompanyDO companyDO=new CompanyDO();
// companyDO.setCompanyName("红塔仁恒");
// companyDO.setCompanyPemission("3");
// companyDO.setCompanyDate(new Timestamp(new Date().getTime()));
// companyDO.setCompanyRepresentative("李钊");
// companyDO.setComplantsDO(new ComplantsDO("红塔仁恒风险上诉事件"));
// companyService.saveCompany(companyDO);
// }
// @Test
// public void updatecompany(){
// CompanyDO companyDO=companyService.findCompany(5);
// companyDO.setCompanyRepresentative("李冰");
// companyDO.setCompanyPemission("2");
// ComplantsDO complantsDO=companyDO.getComplantsDO();
// complantsDO.setComplantsName("张建上诉事件");
// companyDO.setComplantsDO(complantsDO);
// companyService.updateCompany(companyDO);
// }
// @Test
// public void deletecompany(){
// companyService.deleteCompany(2);
// }
// @Test
// public void findcompany(){
// CompanyDO companyDO=companyService.findCompany(5);
// System.out.println(com.alibaba.fastjson.JSON.toJSONString(companyDO));
// }
// @Test
// public void findcomplants(){
// ComplantsDO complantsDO=complantsDAO.findById(1);
// System.out.println(com.alibaba.fastjson.JSON.toJSONString(complantsDO));
// }
// @Test
// public void deletecomplants(){
// complantsDAO.deleteById(2);
// }
// @Test
// public void saveAuthor(){
// ArticleDO articleDO=new ArticleDO();
// articleDO.setTitle("中华纸业新闻网");
// articleDO.setContent("内容");
// CommentDO commentDO=new CommentDO("这个文章真好!");
// CommentDO commentDO1=new CommentDO("这个文章还不错哦");
//
// articleDO.addcomment(commentDO);
// articleDO.addcomment(commentDO1);
//
// articleService.saveArticle(articleDO);
//
// }
// @Test
// public void updateAuthor(){
// ArticleDO articleDO=articleService.findArticle(3);
// articleDO.setTitle("你的姿态,你的青睐");
// articleDO.setContent("我存在在我的存在");
// CommentDO commentDO=new CommentDO("不错哦");
// CommentDO commentDO1=new CommentDO("还可以的");
// articleService.updateArticle(articleDO);
// }
// @Test
// public void findAuthor(){
// ArticleDO articleDO=articleService.findArticle(3);
// System.out.println(com.alibaba.fastjson.JSON.toJSONString(articleDO));
// }
// @Test
// public void deleteAuthor(){
// articleService.deleteArticle(2);
// }
// @Test
// public void saveComments(){
// CommentDO commentDO=new CommentDO("关于互联网思维");
// commentDO.setArticleDO(articleService.findArticle(3));
// commentDAO.save(commentDO);
// }
// @Test
// public void deleteComments(){
// commentDAO.deleteById(7);
//
// }
//}
<file_sep>import urllib.request
urllib.request.urlopen("https://www.moderatecontent.com/api/?url=http://www.moderatecontent.com/img/logo.png").read()
<file_sep>package com.duruo.po;
public class ProjectBudget {
private Integer id;
private String sn;
private String enterpriseId;
//项目总预算
private String generalBudget;
//其中专项资金
private String specialFunds;
//自筹资金
private String selfFinancing;
//项目当年开发费用
private String developmentCost;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn == null ? null : sn.trim();
}
public String getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(String enterpriseId) {
this.enterpriseId = enterpriseId == null ? null : enterpriseId.trim();
}
public String getGeneralBudget() {
return generalBudget;
}
public void setGeneralBudget(String generalBudget) {
this.generalBudget = generalBudget == null ? null : generalBudget.trim();
}
public String getSpecialFunds() {
return specialFunds;
}
public void setSpecialFunds(String specialFunds) {
this.specialFunds = specialFunds == null ? null : specialFunds.trim();
}
public String getSelfFinancing() {
return selfFinancing;
}
public void setSelfFinancing(String selfFinancing) {
this.selfFinancing = selfFinancing == null ? null : selfFinancing.trim();
}
public String getDevelopmentCost() {
return developmentCost;
}
public void setDevelopmentCost(String developmentCost) {
this.developmentCost = developmentCost == null ? null : developmentCost.trim();
}
}<file_sep>package com.duruo.po;
import java.math.BigInteger;
import java.util.Date;
public class AuditData {
private String msgId;
private Integer bmId;
private String mediaId;
private String msgType;
private String picUrl;
private boolean status;
private boolean auditresult;
private String auditopinion;
private Date createTime;
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId;
}
public Integer getBmId() {
return bmId;
}
public void setBmId(Integer bmId) {
this.bmId = bmId;
}
public String getMediaId() {
return mediaId;
}
public void setMediaId(String mediaId) {
this.mediaId = mediaId;
}
public String getMsgType() {
return msgType;
}
public void setMsgType(String msgType) {
this.msgType = msgType == null ? null : msgType.trim();
}
public String getPicUrl() {
return picUrl;
}
public void setPicUrl(String picUrl) {
this.picUrl = picUrl == null ? null : picUrl.trim();
}
public boolean getAuditresult() {
return auditresult;
}
public void setAuditresult(boolean auditresult) {
this.auditresult = auditresult;
}
public String getAuditopinion() {
return auditopinion;
}
public void setAuditopinion(String auditopinion) {
this.auditopinion = auditopinion == null ? null : auditopinion.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}<file_sep># Aliyun-Cdi [](https://www.npmjs.org/package/aliyun-cdi) [](https://npmjs.org/package/aliyun-cdi) [](https://david-dm.org/zhujun24/aliyun-cdi)
[阿里云绿网内容检测API](https://help.aliyun.com/document_detail/28427.html) 封装
## 安装
```bash
npm install aliyun-cdi
```
## 示例
```js
var request = require('request');
var composeUrl = require('aliyun-cdi');
var url = composeUrl({
AccessKeyID: 'XXX', // 你申请的AccessKeyID
AccessKeySecret: 'XXX', // 你申请的AccessKeySecret
Action: 'ImageDetection', // Action
Scene: ['porn'], // 场景
ImageUrl: ['http://dun.163.com/res/sample/sex_2.jpg'] // 资源实例
});
request.post(url, function (err, res, body) {
if (res.statusCode === 200) {
console.log(body);
} else {
console.log(res.statusCode, err);
}
});
```
<file_sep>package com.example.demo.service;
import com.example.demo.dao.CompanyDAO;
import com.example.demo.dao.UserDAO;
import com.example.demo.pojo.CompanyDO;
import com.example.demo.pojo.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Service
public class CompanyServiceimpl implements CompanyService {
@Autowired
private CompanyDAO companyDAO;
@Override
public CompanyDO saveCompany(CompanyDO companyDO) {
return companyDAO.save(companyDO);
}
@Override
public CompanyDO updateCompany(CompanyDO companyDO) {
return companyDAO.saveAndFlush(companyDO);
}
@Override
public CompanyDO findCompany(int id) {
return companyDAO.findById(id);
}
@Override
public void deleteCompany(int id) {
companyDAO.deleteById(id);
}
}
<file_sep>
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && tab.url.indexOf('chrome://') === -1 && tab.url.indexOf('chrome-devtools://') === -1) {
chrome.tabs.executeScript(null, {file: "app.js"});
chrome.tabs.executeScript(null, {file: "contentscript.js"});
}
});
// Two-state browser action icon
chrome.storage.onChanged.addListener(function (changes, namespace) {
for (key in changes) {
var storageChange = changes[key];
if (key === 'on') {
if (storageChange.newValue === true) {
chrome.browserAction.setIcon({path: 'images/ba_icon_on.png'}, dummy);
} else {
chrome.browserAction.setIcon({path: 'images/ba_icon_off.png'}, dummy);
setBadgeTextForCurrentTab('');
}
}
}
});
// Init default options
chrome.runtime.onInstalled.addListener(function () {
chrome.storage.sync.get({
rawKeywords: defaultRawKeywords,
keywords: processRawKeywords(defaultRawKeywords),
strategy: defaultStrategy,
on: true
}, function (options) {
chrome.storage.sync.set(options, function () {
if (options.on === true) {
chrome.browserAction.setIcon({path: 'images/ba_icon_on.png'}, dummy);
} else {
chrome.browserAction.setIcon({path: 'images/ba_icon_off.png'}, dummy);
setBadgeTextForCurrentTab('');
}
});
})
});
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.storage.sync.get('on', function (items) {
chrome.storage.sync.set({
on: !items.on
});
});
});
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
if (message.name === 'keywordsWillBeProcessed') {
var text = (message.totalCount === 0) ? '' : message.totalCount.toString();
setBadgeTextForCurrentTab(text);
}
});
chrome.runtime.onUpdateAvailable.addListener(function(details) {
chrome.runtime.reload();
});
////////////////////////////////////////////////
function dummy() {}
function setBadgeTextForCurrentTab(text) {
chrome.tabs.query({active: true}, function (tabs) {
chrome.browserAction.setBadgeText({
text: text,
tabId: tabs[0].id
});
});
}
<file_sep>package com.duruo.controller;
import com.duruo.common.Const;
import com.duruo.common.ResponseCode;
import com.duruo.common.ServerResponse;
import com.duruo.dao.RetailLicenseMapper;
import com.duruo.po.EvidenceFiles;
import com.duruo.po.RetailLicense;
import com.duruo.po.User;
import com.duruo.service.impl.DocumentHandingServiceImpl;
import com.duruo.service.impl.EvidenceFilesServiceImpl;
import com.duruo.vo.PageHelp;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
/**
* Created by @Author tachai
* date 2018/6/25 13:48
*
* @Email <EMAIL>
*/
//文件审核
@Controller
@RequestMapping("/documentHanding/")
public class DocumentHandingConrroller {
@Autowired
private EvidenceFilesServiceImpl evidenceFilesService;
@Autowired
private RetailLicenseMapper retailLicenseMapper;
@Autowired
private DocumentHandingServiceImpl documentHandingService;
@RequestMapping("getlist.do")
@ResponseBody
public Object getList(HttpSession session, @RequestParam(value = "pageSize", defaultValue = "15") int pageSize, @RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber) {
Page page = PageHelper.startPage(pageNumber, pageSize);
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user != null) {
List<RetailLicense> list = retailLicenseMapper.list(user.getDeptId());
Long total = page.getTotal();
PageHelp pageHelp = new PageHelp();
pageHelp.setTotal(total);
pageHelp.setRows(list);
return pageHelp;
} else {
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getDesc());
}
}
@GetMapping("getdetail.do")
@ResponseBody
public ServerResponse<List<EvidenceFiles>> getListDetail(HttpSession session, Integer licenseId) {
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user != null) {
return evidenceFilesService.getEvidenceDetail(licenseId);
} else {
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getDesc());
}
}
@PostMapping("getLicence.do")
@ResponseBody
public ServerResponse<RetailLicense> getRetailLicense(HttpSession session, Integer licenseId) {
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user != null) {
return ServerResponse.createBySuccess(retailLicenseMapper.lockByPrimaryKey(licenseId));
} else {
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getDesc());
}
}
@GetMapping("getDonelist.do")
@ResponseBody
public Object getUndolist(HttpSession session,
@RequestParam(value = "pageSize", defaultValue = "15") int pageSize,
@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber) {
Page page = PageHelper.startPage(pageNumber, pageSize);
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user != null) {
List<RetailLicense> list = retailLicenseMapper.listDone(user.getDeptId());
if (list != null) {
// PageInfo pageResult=new PageInfo(list);
Long total = page.getTotal();
PageHelp pageHelp = new PageHelp();
pageHelp.setTotal(total);
pageHelp.setRows(list);
return pageHelp;
}
return null;
}
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getDesc());
}
@RequestMapping("updateOpinion")
@ResponseBody
public ServerResponse<String> updateOpinion(HttpSession session, Integer
licenseId, @RequestParam(value = "opinion", defaultValue = "预审通过") String opinion, String result) {
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user != null) {
return documentHandingService.updateOpinion(licenseId, opinion, result, user.getUserName());
} else {
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getDesc());
}
}
@PostMapping("getOption.do")
@ResponseBody
public ServerResponse<String> getOption(Integer licenseId) {
RetailLicense retailLicense = retailLicenseMapper.selectByPrimaryKey(licenseId);
if (null != retailLicense) {
return ServerResponse.createBySuccess(retailLicense.getOpinion(), "得到审核意见成功");
} else {
return ServerResponse.createByErrorMessage("没有相关的值");
}
}
}
<file_sep>package com.baidu.ai.api.ocr;
import com.baidu.ai.api.auth.AuthService;
import com.baidu.ai.api.utils.HttpUtil;
import com.baidu.aip.util.Base64Util;
import org.aspectj.util.FileUtil;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
/**
* Created by @Author tachai
* date 2018/6/30 17:06
*
* @Email <EMAIL>
*/
public class OcrService {
// 通用识别URL
private static String ocrHost = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
/**
* 传入图片存放地址
* @param filePath
* @return
*/
public static String generalOCR(String filePath){
try {
byte[] imgData = FileUtil.readAsByteArray(new File(filePath));
String imgStr = Base64Util.encode(imgData);
String params = URLEncoder.encode("image","UTF-8") + "=" + URLEncoder.encode(imgStr,"UTF-8");
/**
* 注意这里只是为了简化编码每一次都去获取access_token,线上环境access_token
* 客户端可自行缓存,过期后重新获取
*/
String accessToken = AuthService.getAuth();
String result = HttpUtil.post(ocrHost,accessToken,params);
JSONObject jsonObject = new JSONObject(result);
System.out.println(jsonObject);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
<file_sep>const state = {
applyId: -1, // 申请审核id
checkData: {}, // 图片识别结果
open: false, // 打开 flag
};
const mutations = {
POST_BEGIN_SETTLE_APPLY_ID(stat, id) {
stat.applyId = id;
},
POST_BEGIN_SETTLE_CHECK_DATA(stat, obj) {
stat.checkData = obj;
}
};
const actions = {
};
export default {
state,
mutations,
actions
}
<file_sep>package com.duruo.util;
import java.util.Calendar;
import java.util.Date;
/**
* Created by @Author tachai
* date 2018/8/18 15:26
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
public class Demo {
public static void main(String[] args) {
String idCard="330382198310235738";
Date regDete = new Date();
Date birthDate = DateTimeUtil.strToDate(idCard.substring(6,14),"yyyyMMdd");
if(regDete!=null){
Calendar cld = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.setTime(birthDate);
cld.setTime(regDete);
int yearReg=regDete.getYear();
int monthReg = regDete.getMonth();
int dayReg = cld.get(Calendar.DAY_OF_MONTH);
System.out.println("birth"+birthDate);
System.out.println("yearReg"+yearReg);
System.out.println("monthReg"+monthReg);
System.out.println("dayReg"+dayReg);
int age = yearReg-(Integer.parseInt(idCard.substring(6,10))-1900);
if(age>35){
System.out.println("注册公司时年龄大于35岁1");
// qchuang.setOpinion("注册公司时年龄大于35岁");
// qchuangMapper.updateByPrimaryKey(qchuang);
// return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
} else if(age==35) {
if(monthReg>birthDate.getMonth()){
//todo
System.out.println("注册公司时年龄大于35岁2");
// qchuang.setOpinion("注册公司时年龄大于35岁");
// qchuangMapper.updateByPrimaryKey(qchuang);
// return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
}else if(monthReg==birthDate.getMonth()){
if(dayReg>=cal.get(Calendar.DAY_OF_MONTH)){
System.out.println(dayReg+"注册日"+cal.get(Calendar.DAY_OF_MONTH)+"出生日");
System.out.println(birthDate.getMonth()+"出生月"+birthDate.getDay()+"出生日");
System.out.println("注册公司时年龄大于35岁3");
// qchuang.setOpinion("注册公司时年龄大于35岁");
// qchuangMapper.updateByPrimaryKey(qchuang);
// return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
}
}
}
}
}
}
<file_sep>package com.duruo.dto.FlowDataChild;
import lombok.Builder;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/6/27 10:39
*
* @Email <EMAIL>
*/
@Data
public class Core_Flow_Opinion {
private String Opinion;
private String Title;
private String ProjectID;
@Builder.Default
private String UserName = "方超";
@Builder.Default
private String UserUID = "fangchao";
@Builder.Default
private String UserOrgCode = "D_2F9FB5B2-FF91-456B-AC9F-8818DCD74BF5";
@Builder.Default
private String UserUnitCode = "";
@Builder.Default
private String UserOrgName = "科技创新服务中心";
@Builder.Default
private String UserUnitName = "";
@Builder.Default
private String CurrentNodeID = "6";
@Builder.Default
private String CurrentNodeName = "形式审核";
private String CurrentFlowName;
private String TaskID;
private String PreWorkId;
@Builder.Default
private String UserOrgPath = "C_20170417072903138.D_2F9FB5B2-FF91-456B-AC9F-8818DCD74BF5";
@Builder.Default
private String CompanyCode = "C_20170417072903138";
@Builder.Default
private String CompanyName = "徐汇区科学技术委员会";
}
<file_sep>package com.duruo.util;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.duruo.po.Qchuang;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by @Author tachai
* date 2018/9/26 14:31
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
//发送短信
@Slf4j
public class SentMessage {
/**
* 调用阿里云发送短信
* @param phoneNum
* @param type
* @param name
* @param content
*/
public static void sentMessage(String phoneNum,String type,String name,String content){
final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
//替换成你的AK
// final String accessKeyId = "<KEY>";//你的accessKeyId,参考本文档步骤2
final String accessKeyId = "LTAIG1t8Dm6yO8pg";//你的accessKeyId,参考本文档步骤2
// final String accessKeySecret = "<KEY>";//你的accessKeySecret,参考本文档步骤2
final String accessKeySecret = "<KEY>";//你的accessKeySecret,参考本文档步骤2
//初始化ascClient,暂时不支持多region(请勿修改)
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
accessKeySecret);
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
} catch (ClientException e) {
log.error(e.getMessage());
}
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象
SendSmsRequest request = new SendSmsRequest();
//使用post提交
request.setMethod(MethodType.POST);
//必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
request.setPhoneNumbers(phoneNum);
//必填:短信签名-可在短信控制台中找到
//todo
request.setSignName("青创扶持");
//必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
//SMS_145501391 发送验证码
//SMS_146290756 审核通过
//SMS_146280948 审核不通过
request.setTemplateCode(type);
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
Map<String, String> codeMap = new HashMap<>();
// todo 返回的给后台的 值
// String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
// codeMap.put("code", verifyCode);
codeMap.put("name",name);
codeMap.put("reson",content);
String code = new Gson().toJson(codeMap);
request.setTemplateParam(code);
// request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
//可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
// request.setOutId("yourOutId");
//请求失败这里会抛ClientException异常
Map<String, String> map = new HashMap<>();
try {
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
log.info("阿里短信状态码:{},{}", sendSmsResponse.getCode());
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
//请求成功
//
}
} catch (ClientException e) {
e.printStackTrace();
}
}
/**
* 调用行政服务中心短信
* @param phoneNum
* @param content
*/
public static void sendMessage(String phoneNum,String content){
Map<String,String> query= new HashMap<>();
query.put("phoneNum",phoneNum);
query.put("content",content);
String data = new Gson().toJson(query);
String result = HttpUtil.okhttpJSON(PropertiesUtil.getProperty("SMS.url"), data);
log.info("中心短信服务发送的:{},{},{}",phoneNum,content,result);
}
}
<file_sep>package com.duruo.dto;
import lombok.Builder;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/6/27 10:23
*
* @Email <EMAIL>
*/
@Data
public class DataFields {
@Builder.Default
private String ApproveUsers = "";
@Builder.Default
private String NodeID = "";
private String Title;
@Builder.Default
private String ApprovalFormURL = "http://fwpt.yc.c.c/FlowManagerModule/Form";
}
<file_sep>[管理密码]
密码=<PASSWORD>
[程序版本]
参数=1.88
[护眼提醒时间]
参数=0
[护眼提醒信息]
参数=伸伸腰,休息一下啦!
[护眼休息时间]
参数=0
[窗口拦截模式1]
参数=1
[窗口拦截模式2]
参数=0
[禁用任务管理器]
参数=0
[禁止修改系统时间]
参数=0
[禁止系统配置]
参数=0
[禁止系统管理工具]
参数=0
[禁止访问程序目录]
参数=0
[禁止系统命令行]
参数=0
[警告模式1]
参数=0
[警告模式2]
参数=0
[警告模式3]
参数=0
[警告模式4]
参数=0
[警告模式5]
参数=0
[警告模式6]
参数=0
[警告模式7]
参数=1
[警告标题]
参数=防护墙提醒
[警告内容]
参数=您访问的信息已经被安全拦截
[警告模式8]
参数=0
[记录窗口]
参数=0
[记录进程]
参数=0
[记录文件]
参数=0
[记录其他信息]
参数=0
[图像质量]
参数=30
[图像清理]
参数=300
[截图模式1]
参数=0
[截图模式2]
参数=1
[进程截图]
参数=0
[窗口截图]
参数=0
[程序运行进入监控状态]
参数=0
[程序运行进入托盘状态]
参数=0
[记录日志]
参数=0
<file_sep><?php
namespace Bad;
/**
* author 逆雪寒
* version 0.8.3
*/
class Rabbit {
const YES = 1;
const NO = 0;
private static $instance = NULL;
private $host = '';
public $trace = self::NO;
private function __construct($host,$port){
$this->host($host,$port);
}
public function __clone(){
trigger_error('Clone is not allow!',E_USER_ERROR);
}
/**
* 调试接口返回.
*
* @param string $msg .
* @return $this A reference to the current instance.
*/
private function trace($msg) {
if($this->trace){
exit($msg);
}
}
private function decode($data) {
$this->trace($data);
return json_decode($data,true);
}
private function host($host,$port) {
$this->host = "http://" . $host . ":" . $port."/";
}
public function factory($host = 'localhost',$port = 9394) {
if(is_null(self::$instance)) {
self::$instance = new self($host,$port);
}
return self::$instance;
}
private function request($do,Array $parameter = [],$method = 'GET') {
$query = '';
$ch = curl_init();
if($method != 'GET') {
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameter);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
}else{
$query = "?" . http_build_query($parameter);
}
curl_setopt($ch, CURLOPT_URL, $this->host.$do.$query);
curl_setopt($ch, CURLOPT_TIMEOUT,60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$data = curl_exec($ch);
if(curl_errno($ch)){
return false;
}
curl_close($ch);
return $data;
}
/**
* 内容过滤.
*
* @param string $contents 要过滤的内容
* @return bool or array
*/
public function filter($contents) {
$result = $this->request("filter",['contents' => $contents],'POST');
if($result !== false) {
$code = $this->decode($result);
if(isset($code['success']) && $code['success'] === self::NO) {
return false;
}
return $code;
}
return false;
}
/**
* 脏词删除.
*
* @param int $id 脏词id (必须)
* @return bool or array
*/
public function delete($id) {
if(!$id) return false;
$result = $this->request("delete",['id' => $id],'DELETE');
if($result !== false) {
$code = $this->decode($result);
if(isset($code['success']) && $code['success'] === self::NO) {
return false;
}
return true;
}
return false;
}
/**
* 添加脏词.
*
* @param array
* string $word 脏词
* int $category 脏词分类
* int $rate 黑名单OR灰名单 1 or 2
* int $correct 是否畸形纠正 1 or 2
* @return bool or array.
*/
public function create(Array $parameter) {
$result = $this->request("create",$parameter,'POST');
if($result !== false) {
$code = $this->decode($result);
if(isset($code['success']) && $code['success'] === self::NO) {
return false;
}
return true;
}
return false;
}
/**
* 修改脏词.
*
* @param array
* int $id 脏词id (必须)
* string $word 脏词
* int $category 脏词分类
* int $rate 黑名单OR灰名单 1 or 2
* int $correct 是否畸形纠正 1 or 2
* @return bool
*/
public function revise(Array $parameter) {
if(!isset($parameter['id']) || count($parameter) < 1) {
return false;
}
$result = $this->request("revise",$parameter,'PUT');
if($result !== false) {
$code = $this->decode($result);
if(isset($code['success']) && $code['success'] === self::NO) {
return false;
}
return true;
}
return false;
}
/**
* 查询脏词.
*
* @param array
* int $id 脏词id
* string $word 脏词
* int $category 脏词分类
* int $rate 黑名单OR灰名单 1 or 2
* int $correct 是否畸形纠正 1 or 2
* @return bool or array
*/
public function query(Array $parameter) {
$result = $this->request("query",$parameter,'GET');
if($result !== false) {
$code = $this->decode($result);
if(isset($code['success']) && $code['success'] === self::NO) {
return false;
}
return $code;
}
return false;
}
/**
* 脏词分类.
* ID:分类名 1:个性化 2:低俗信息 3:灌水信息 5:政治敏感 6:违约广告 7:跨站追杀 8:色情信息 9:违法信息 10:垃圾广告
* @return bool or array
*/
public function category() {
$result = $this->request("category");
if($result !== false) {
$code = $this->decode($result);
if(isset($code['success']) && $code['success'] === self::NO) {
return false;
}
return $code;
}
return false;
}
/**
* 脏词重新载入.
*
* @return bool
*/
public function reload() {
$result = $this->request("reload");
if($result !== false) {
$code = $this->decode($result);
if(isset($code['success']) && $code['success'] == self::NO) {
return false;
}
return true;
}
return false;
}
}
$rabbit = Rabbit::factory('127.0.0.1',9394);
// $rabbit->trace = true;
//$data = $rabbit->filter('万人敬仰+大兄弟 15009987776');
$data = $rabbit->create([
'word' => '什么狗屎+猪头三:phone',
'category' => 3,
'rate' => 1,
'correct' => 1
]);
//$data = $rabbit->delete(29);
// $data = $rabbit->reload();
var_dump($data);
<file_sep>package com.example.demo.dao;
import com.example.demo.pojo.RulesRegulationsDO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface RulesRegulationsDAO extends JpaRepository<RulesRegulationsDO,Long> {
RulesRegulationsDO findById(int id);
@Query("select r from RulesRegulationsDO r where r.rulesAndRegulationsNotice <> ?1")
List<RulesRegulationsDO> findByRulesAndRegulationsNotice(String n);
}
<file_sep>package com.example.demo.controller;
import com.example.demo.dao.*;
import com.example.demo.pojo.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;
@Controller
@EnableAutoConfiguration
@RequestMapping(value = "/main")
public class CompanyController {
@Autowired
private CompanyDAO companyDAO;
@Autowired
private FirstLevelRiskDAO firstLevelRiskDAO;
@Autowired
private SecondLevelRiskDAO secondLevelRiskDAO;
@Autowired
private ThirdLevelRiskDAO thirdLevelRiskDAO;
@Autowired
private FourthLevelRiskDAO fourthLevelRiskDAO;
@Autowired
private UserDAO userDAO;
@Autowired
private RiskEventLibraryDAO riskEventLibraryDAO;
@Autowired
private UserPermissionDAO userPermissionDAO;
@Autowired
private RiskDefinationDAO riskDefinationDAO;
@Autowired
private RulesRegulationsDAO rulesRegulationsDAO;
@RequestMapping(value = "/main_page")
public String index(HttpServletRequest request, Model model, HttpSession session, @PageableDefault(size = 5,sort = {"id"},direction = Sort.Direction.ASC)Pageable pageable){
UserDO user=(UserDO)session.getAttribute("user");
if(user.getPermission()==2){
model.addAttribute("new_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"刚创建",pageable).getTotalElements());
model.addAttribute("ready_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"待审批",pageable).getTotalElements());
model.addAttribute("pass_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"审批通过",pageable).getTotalElements());
model.addAttribute("failure_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"审批失败",pageable).getTotalElements());
model.addAttribute("published_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"已发布",pageable).getTotalElements());
model.addAttribute("ing_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"审批中",pageable).getTotalElements());
}else if(user.getPermission()==1){
model.addAttribute("new_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"刚创建",pageable).getTotalElements());
model.addAttribute("ready_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"待审批",pageable).getTotalElements());
model.addAttribute("pass_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"审批通过",pageable).getTotalElements());
model.addAttribute("failure_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"审批失败",pageable).getTotalElements());
model.addAttribute("published_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"已发布",pageable).getTotalElements());
model.addAttribute("ing_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"审批中",pageable).getTotalElements());
}
model.addAttribute("index",1);
System.out.println("request.getServletPath:"+request.getServletPath());
System.out.println("request.getRealPath:"+request.getRealPath("WebAppConfigurer.java"));
System.out.println("+request.getServletPath"+request.getServletContext().getRealPath("com.example.demo.controller.CompanyController"));
return "index";
}
@RequestMapping(value = "/Risk_management_strategy")
public String Risk_management_strategy(Model model,HttpSession session){
UserDO user=(UserDO)session.getAttribute("user");
return "index2";
}
@RequestMapping(value = "/group_topic")
public String group_topic(Model model, HttpSession session){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
return "group_topic";
}
@RequestMapping(value = "/yueyang_topic")
public String yueyang_topic(Model model, HttpSession session){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
return "yueyang_topic";
}
@RequestMapping(value = "/kaisheng_topic")
public String kaisheng_topic(Model model, HttpSession session){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
return "kaisheng_topic";
}
@RequestMapping(value = "/guanhao_topic")
public String guanhao_topic(Model model, HttpSession session){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
return "guanhao_topic";
}
@RequestMapping(value = "/group_list")
public String group_list(Model model, HttpSession session){
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("company",companyDAO.findAll());
FirstLevelRiskDO firstLevelRiskDO = new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
model.addAttribute("first_level_pass",firstLevelRiskDAO.findBystatus("审批通过"));
model.addAttribute("first_level_publish",firstLevelRiskDAO.findBycompanyandstatus(user.getUserCompany(),"已发布"));
model.addAttribute("first_level_ing",firstLevelRiskDAO.findBystatus("审批中"));
model.addAttribute("first_level_failure",firstLevelRiskDAO.findBystatus("审批失败"));
CompanyDO companyDO=new CompanyDO();
model.addAttribute("co",companyDO);
Date date = new Date();
UserDO userDO=new UserDO();
model.addAttribute("uo",userDO);
model.addAttribute("user",userDAO.findbycompany(user.getUserCompany()));
Timestamp nousedate = new Timestamp(date.getTime());
model.addAttribute("permission",userPermissionDAO.findAll());
model.addAttribute("riskeventlibrary_group",riskEventLibraryDAO.findBycompany("集团"));
model.addAttribute("riskeventlibrary_company",riskEventLibraryDAO.findBycompany("集团"));
model.addAttribute("riskeventlibrary_defination",riskDefinationDAO.findAll());
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
model.addAttribute("first_level_publish",firstLevelRiskDAO.findBystatus("已发布"));
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("first_level_pass",firstLevelRiskDAO.findBystatus("审批通过"));
model.addAttribute("first_level_review_ready",firstLevelRiskDAO.findBystatus("待审批"));
model.addAttribute("first_level_ing",firstLevelRiskDAO.findBystatus("审批中"));
model.addAttribute("first_level_failure",firstLevelRiskDAO.findBystatus("审批失败"));
return "group_main";
}
@RequestMapping(value = "/company_list")
public String company_list(Model model, HttpSession session){
model.addAttribute("company",companyDAO.findAll());
FirstLevelRiskDO firstLevelRiskDO = new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
SecondLevelRiskDO secondLevelRiskDO = new SecondLevelRiskDO();
model.addAttribute("so",secondLevelRiskDO);
ThirdLevelRiskDO thirdLevelRiskDO = new ThirdLevelRiskDO();
model.addAttribute("to",thirdLevelRiskDO);
UserDO user=(UserDO)session.getAttribute("user");
Date date = new Date();
FourthLevelRiskDO fourthLevelRiskDO=new FourthLevelRiskDO();
model.addAttribute("fouo",fourthLevelRiskDO);
Timestamp nousedate = new Timestamp(date.getTime());
System.out.println(user.getWorkerName());
model.addAttribute("first_level_review_ready",firstLevelRiskDAO.findBycompanyandstatus(user.getUserCompany(),"待审批"));
model.addAttribute("first_level_review_ing",firstLevelRiskDAO.findBycompanyandstatus(user.getUserCompany(),"审批中"));
model.addAttribute("first_level_review_pass",firstLevelRiskDAO.findBycompanyandstatus(user.getUserCompany(),"审批通过"));
model.addAttribute("first_level_review_failure",firstLevelRiskDAO.findBycompanyandstatus(user.getUserCompany(),"审批失败"));
model.addAttribute("first_level_publish",firstLevelRiskDAO.findBycompanyandstatus(user.getUserCompany(),"已发布"));
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany(user.getUserCompany()));
model.addAttribute("second_level",secondLevelRiskDAO.findBycompany(user.getUserCompany()));
model.addAttribute("third_level",thirdLevelRiskDAO.findBycompany(user.getUserCompany()));
model.addAttribute("fourth_level",fourthLevelRiskDAO.findBycompany(user.getUserCompany()));
RiskDefinationDO riskDefinationDO=new RiskDefinationDO();
model.addAttribute("rdo",riskDefinationDO);
RiskEventLibraryDO riskEventLibraryDO=new RiskEventLibraryDO();
model.addAttribute("rio",riskEventLibraryDO);
CompanyDO companyDO=new CompanyDO();
model.addAttribute("co",companyDO);
UserDO userDO=new UserDO();
model.addAttribute("uo",userDO);
model.addAttribute("user",userDAO.findbycompany(user.getUserCompany()));
model.addAttribute("permission",userPermissionDAO.findbycompany(user.getUserCompany()));
model.addAttribute("riskeventlibrary_group",riskEventLibraryDAO.findBycompany("集团"));
model.addAttribute("riskeventlibrary_company",riskEventLibraryDAO.findBycompany("集团"));
model.addAttribute("riskeventlibrary_defination",riskDefinationDAO.findAll());
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
model.addAttribute("ready_create_first_level",firstLevelRiskDAO.findBycompanyandstatus(user.getUserCompany(),"待创建"));
System.out.println(user.getId());
return "company_main";
}
@RequestMapping(value = "/risk_list")
public String risk_list(Model model,HttpSession session){
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("first_level_pass",firstLevelRiskDAO.findBystatus("审批通过"));
model.addAttribute("first_level_publish",firstLevelRiskDAO.findBystatus("已发布"));
model.addAttribute("first_level_ing",firstLevelRiskDAO.findBystatus("审批中"));
model.addAttribute("first_level_failure",firstLevelRiskDAO.findBystatus("审批失败"));
model.addAttribute("first_level_review_ready",firstLevelRiskDAO.findBystatus("待审批"));
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
model.addAttribute("first_level_review_ready",firstLevelRiskDAO.findBystatus("待审批"));
return "risk_list";
}
@RequestMapping(value = "/select")
public String select(Model model,HttpSession session){
UserDO user=(UserDO)session.getAttribute("user");
String company = user.getUserCompany();
String group = "集团";
if (group.equals(company)){
return "redirect:/main/group_list";
} else {
return "redirect:/main/company_list";
}
}
@RequestMapping(value = "list_all/{id}")
public String list_all(Model model, HttpSession session, @PathVariable(value = "id") int id){
model.addAttribute("first_level",firstLevelRiskDAO.findById(id));
UserDO user=(UserDO)session.getAttribute("user");
Date date = new Date();
Timestamp nousedate = new Timestamp(date.getTime());
FirstLevelRiskDO firstLevelRiskDO = new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
SecondLevelRiskDO secondLevelRiskDO = new SecondLevelRiskDO();
model.addAttribute("so",secondLevelRiskDO);
ThirdLevelRiskDO thirdLevelRiskDO = new ThirdLevelRiskDO();
model.addAttribute("to",thirdLevelRiskDO);
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany(user.getUserCompany()));
FourthLevelRiskDO fourthLevelRiskDO=new FourthLevelRiskDO();
model.addAttribute("fouo",fourthLevelRiskDO);
String First_RISK_CODE=firstLevelRiskDAO.findById(id).getFirstLevelRiskCode();
model.addAttribute("second_level",secondLevelRiskDAO.findByFirstLevelRiskCode(First_RISK_CODE));
model.addAttribute("third_level",thirdLevelRiskDAO.findByFirstLevelRiskCode(First_RISK_CODE));
model.addAttribute("fourth_level",fourthLevelRiskDAO.findByFirstLevelRiskCode(First_RISK_CODE));
model.addAttribute("id",id);
model.addAttribute("status",firstLevelRiskDAO.findById(id).getFirstLevelRiskStatus());
RiskDefinationDO riskDefinationDO=new RiskDefinationDO();
model.addAttribute("rdo",riskDefinationDO);
RiskEventLibraryDO riskEventLibraryDO=new RiskEventLibraryDO();
model.addAttribute("rio",riskEventLibraryDO);
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "list_all";
}
@RequestMapping(value = "/search")
public String search(Model model, @RequestParam(value = "key")String key,HttpSession session){
model.addAttribute("company",companyDAO.findAll());
FirstLevelRiskDO firstLevelRiskDO = new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
SecondLevelRiskDO secondLevelRiskDO = new SecondLevelRiskDO();
model.addAttribute("so",secondLevelRiskDO);
ThirdLevelRiskDO thirdLevelRiskDO = new ThirdLevelRiskDO();
model.addAttribute("to",thirdLevelRiskDO);
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany(user.getUserCompany()));
Date date = new Date();
FourthLevelRiskDO fourthLevelRiskDO=new FourthLevelRiskDO();
model.addAttribute("fouo",fourthLevelRiskDO);
Timestamp nousedate = new Timestamp(date.getTime());
model.addAttribute("first_level",firstLevelRiskDAO.findAll());
model.addAttribute("second_level",secondLevelRiskDAO.findAll());
model.addAttribute("third_level",thirdLevelRiskDAO.findAll());
model.addAttribute("fourth_level",fourthLevelRiskDAO.findAll());
model.addAttribute("key_return",key);
return "search_all";
}
@RequestMapping(value = "/group_management")
public String group_management(Model model,HttpSession session){
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("company",companyDAO.findAll());
model.addAttribute("user",userDAO.findbycompany(user.getUserCompany()));
model.addAttribute("permission",userPermissionDAO.findbycompany(user.getUserCompany()));
model.addAttribute("worknum",user.getWorkNumber());
model.addAttribute("user_permission",user.getPermission());
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "group_management";
}
@RequestMapping(value = "/add")
public String add(Model model, HttpSession session, @ModelAttribute(value = "co") CompanyDO companyDO){
companyDO.setId(0);
Date date = new Date();
String companyname=companyDO.getCompanyName();
Timestamp nousedate = new Timestamp(date.getTime());
companyDO.setCompanyDate(nousedate);
companyDO.setCompanyPemission("1");
companyDAO.save(companyDO);
model.addAttribute("company",companyDAO.findAll());
FirstLevelRiskDO firstLevelRiskDO = new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("first_level_pass",firstLevelRiskDAO.findBystatus("审批通过"));
model.addAttribute("first_level_publish",firstLevelRiskDAO.findBystatus("已发布"));
model.addAttribute("first_level_ing",firstLevelRiskDAO.findBystatus("审批中"));
model.addAttribute("first_level_failure",firstLevelRiskDAO.findBystatus("审批失败"));
UserDO user=(UserDO)session.getAttribute("user");
CompanyDO companyDO1=new CompanyDO();
model.addAttribute("co",companyDO1);
model.addAttribute("company_add_success",1);
model.addAttribute("new_company_name",companyname);
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "group_company_management";
}
@RequestMapping(value = "/del/{id}")
public String del(Model model, HttpSession session,@PathVariable(value = "id") int id){
String companyname= companyDAO.findById(id).getCompanyName();
companyDAO.deleteById(id);
model.addAttribute("company",companyDAO.findAll());
FirstLevelRiskDO firstLevelRiskDO = new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("first_level_pass",firstLevelRiskDAO.findBystatus("审批通过"));
model.addAttribute("first_level_publish",firstLevelRiskDAO.findBystatus("已发布"));
model.addAttribute("first_level_ing",firstLevelRiskDAO.findBystatus("审批中"));
model.addAttribute("first_level_failure",firstLevelRiskDAO.findBystatus("审批失败"));
UserDO user=(UserDO)session.getAttribute("user");
CompanyDO companyDO1=new CompanyDO();
model.addAttribute("co",companyDO1);
model.addAttribute("company_del_success",1);
model.addAttribute("new_company_name",companyname);
model.addAttribute("user",userDAO.findAll());
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "group_company_management";
}
@RequestMapping(value = "/edit/{id}")
public String edit(Model model, HttpSession session, @PathVariable(value = "id") int id){
model.addAttribute("company",companyDAO.findAll());
FirstLevelRiskDO firstLevelRiskDO = new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("first_level_pass",firstLevelRiskDAO.findBystatus("审批通过"));
model.addAttribute("first_level_publish",firstLevelRiskDAO.findBystatus("已发布"));
model.addAttribute("first_level_ing",firstLevelRiskDAO.findBystatus("审批中"));
model.addAttribute("first_level_failure",firstLevelRiskDAO.findBystatus("审批失败"));
UserDO user=(UserDO)session.getAttribute("user");
CompanyDO companyDO1=new CompanyDO();
model.addAttribute("id",id);
model.addAttribute("co",companyDAO.findById(id));
model.addAttribute("user",userDAO.findAll());
model.addAttribute("company_edit",1);
model.addAttribute("user_permission",user.getPermission());
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "group_company_management";
}
@RequestMapping(value = "/update/{id}")
public String update(Model model, HttpSession session, @ModelAttribute(value = "co") CompanyDO companyDO,@PathVariable(value = "id") int id){
String companyname=companyDO.getCompanyName();
System.out.println(companyDO.getId());
companyDAO.update(companyDO.getCompanyName(),companyDO.getCompanyRepresentative(),id);
model.addAttribute("company",companyDAO.findAll());
FirstLevelRiskDO firstLevelRiskDO = new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("first_level_pass",firstLevelRiskDAO.findBystatus("审批通过"));
model.addAttribute("first_level_publish",firstLevelRiskDAO.findBystatus("已发布"));
model.addAttribute("first_level_ing",firstLevelRiskDAO.findBystatus("审批中"));
model.addAttribute("first_level_failure",firstLevelRiskDAO.findBystatus("审批失败"));
UserDO user=(UserDO)session.getAttribute("user");
CompanyDO companyDO1=new CompanyDO();
model.addAttribute("co",companyDO1);
model.addAttribute("company_update_success",1);
model.addAttribute("new_company_name",companyname);
model.addAttribute("user",userDAO.findAll());
model.addAttribute("user_permission",user.getPermission());
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "group_company_management";
}
@RequestMapping(value = "/permission")
public String permission(Model model,HttpSession session){
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("permission",userPermissionDAO.findbycompany(user.getUserCompany()));
model.addAttribute("worknum",user.getWorkNumber());
model.addAttribute("user_permission",user.getPermission());
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "group_permission";
}
@RequestMapping(value = "/company")
public String company(Model model,HttpSession session){
model.addAttribute("company",companyDAO.findAll());
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("user_permission",user.getPermission());
CompanyDO companyDO=new CompanyDO();
model.addAttribute("co",companyDO);
model.addAttribute("user_permission",user.getPermission());
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "group_company_management";
}
@RequestMapping(value = "/update", method = RequestMethod.POST,produces="text/plain;charset=UTF-8")
@ResponseBody
public String doupdate(Model model, @RequestBody JSONObject jsonObject,HttpSession session) {
// Iterator iterator = jsonObject.keys();
System.out.println(jsonObject);
String id = jsonObject.getString("ID");
int ID = Integer.parseInt(id);
String ableManageUser=jsonObject.getString("能否管理用户");
String ableCreateNewProject = jsonObject.getString("能否创建新项目");
String ableExaminationApprovalProject = jsonObject.getString("能否审批新项目");
String ableModifyProject = jsonObject.getString("能否修改项目");
String ablePushProject = jsonObject.getString("能否发布项目");
userPermissionDAO.update(
ableManageUser,
ableCreateNewProject,
ableExaminationApprovalProject,
ableModifyProject,
ablePushProject,
ID);
model.addAttribute("msg", 1);
model.addAttribute("permission",userPermissionDAO.findAll());
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("user_permission",user.getPermission());
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "group_permission";
}
@RequestMapping(value = "update_success")
public String update_success(Model model,HttpSession session){
UserDO user=(UserDO)session.getAttribute("user");
UserDO userDO=new UserDO();
model.addAttribute("uo",userDO);
model.addAttribute("user_permission",user.getPermission());
model.addAttribute("user",userDAO.findbycompany(user.getUserCompany()));
model.addAttribute("permission",userPermissionDAO.findbycompany(user.getUserCompany()));
model.addAttribute("msg",1);
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
model.addAttribute("point_permission",1);
model.addAttribute("worknum",user.getWorkNumber());
return "user_management";
}
@RequestMapping(value = "/chart_risk_all")
public void chart_risk_all(HttpSession session, HttpServletResponse response){
List<Map> list= new ArrayList<>();
Map<String,Object> map_original = new HashMap<>();
map_original.put("id","0.0");
map_original.put("parent","");
map_original.put("name","中华纸业风险分布");
list.add(map_original);
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findAll()){
Map<String,Object> map = new HashMap<>();
String id="1."+firstLevelRiskDO.getFirstLevelRiskCode().substring(1);
map.put("id",id);
map.put("parent","0.0");
String value=firstLevelRiskDO.getFirstLevelRiskDescription();
String name=firstLevelRiskDO.getFirstLevelRiskName();
map.put("name",name);
// map.put("value",value);
System.out.println(map);
list.add(map);
System.out.println(list);
}
int i=1;
int n=1;
for(SecondLevelRiskDO secondLevelRiskDO:secondLevelRiskDAO.findAll()){
Map<String,Object> map = new HashMap<>();
String id="2."+i;
map.put("id",id);
String name=secondLevelRiskDO.getSecondLevelRiskName();
String value=secondLevelRiskDO.getSecondLevelRiskDescription();
String parent="1."+secondLevelRiskDO.getFirstLevelRiskCode().substring(1);
map.put("parent",parent);
map.put("name",name);
// map.put("value",value);
list.add(map);
for(ThirdLevelRiskDO thirdLevelRiskDO:thirdLevelRiskDAO.findAll()){
if(thirdLevelRiskDO.getSecondLevelRiskCode().equals(secondLevelRiskDO.getSecondLevelRiskCode())){
Map<String,Object> map1 = new HashMap<>();
String id1="3."+n;
String name1=thirdLevelRiskDO.getThirdLevelRiskName();
String value1=thirdLevelRiskDO.getThirdLevelRiskDescription();
System.out.println(thirdLevelRiskDO.getThirdLevelRiskCode());
String parent1=id;
map1.put("id",id1);
map1.put("parent",parent1);
map1.put("name",name1);
map1.put("value",n);
// map.put("value",value);
list.add(map1);
n=n+1;
}
}
i=i+1;
}
// for(FourthLevelRiskDO fourthLevelRiskDO:fourthLevelRiskDAO.findAll()){
// Map<String,Object> map = new HashMap<>();
// int id=fourthLevelRiskDO.getId();
// String name=fourthLevelRiskDO.getFourthLevelRiskName();
// String value=fourthLevelRiskDO.getFourthLevelRiskDescription();
// int parent=firstLevelRiskDAO.findByriskcode(fourthLevelRiskDO.getFirstLevelRiskCode()).getId();
// map.put("id",Integer.toString(id));
// map.put("parent",Integer.toString(parent));
// map.put("name",name);
//// map.put("value",value);
// list.add(map);
// }
JSONArray json=JSONArray.fromObject(list);
System.out.println(json.toString());
try {
response.setContentType("text/html;charset=utf–8");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(json.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
@RequestMapping(value = "project_allocation")
public String project_allocation(Model model,HttpSession session){
UserDO user=(UserDO)session.getAttribute("user");
Date date = new Date();
List<UserDO> userDOList=new ArrayList<>();
List<FirstLevelRiskDO> firstLevelRiskDOS=new ArrayList<>();
for(UserDO userDO:userDAO.findbycompany("岳阳林纸")) {
userDOList.add(userDO);
}
for(UserDO userDO1:userDAO.findbycompany("凯胜园林")) {
userDOList.add(userDO1);
}
for(UserDO userDO2:userDAO.findbycompany("冠豪高新")) {
userDOList.add(userDO2);
}
for(UserDO userDO3:userDAO.findbycompany("红塔仁恒")) {
userDOList.add(userDO3);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("岳阳林纸")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("红塔仁恒")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("凯胜园林")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("冠豪高新")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
FirstLevelRiskDO firstLevelRiskDO=new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
model.addAttribute("first_ready",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("first_finish",firstLevelRiskDOS);
model.addAttribute("user",userDOList);
return "project_allocation";
}
@RequestMapping(value = "project_allocation_success")
public String project_allocation_success(Model model,HttpSession session){
UserDO user=(UserDO)session.getAttribute("user");
Date date = new Date();
List<FirstLevelRiskDO> firstLevelRiskDOS=new ArrayList<>();
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("岳阳林纸")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("红塔仁恒")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("凯胜园林")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("冠豪高新")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
List<UserDO> userDOList=new ArrayList<>();
for(UserDO userDO:userDAO.findbycompany("岳阳林纸")) {
userDOList.add(userDO);
}
for(UserDO userDO1:userDAO.findbycompany("凯胜园林")) {
userDOList.add(userDO1);
}
for(UserDO userDO2:userDAO.findbycompany("冠豪高新")) {
userDOList.add(userDO2);
}
for(UserDO userDO3:userDAO.findbycompany("红塔仁恒")) {
userDOList.add(userDO3);
}
FirstLevelRiskDO firstLevelRiskDO=new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
model.addAttribute("first_ready",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("first_finish",firstLevelRiskDOS);
model.addAttribute("user",userDOList);
model.addAttribute("allocation_success",1);
return "project_allocation";
}
@RequestMapping(value = "/search_list")
public String search_list(Model model,HttpSession session,@RequestParam(value = "condition") String condition,@RequestParam(value = "value") String value){
UserDO user=(UserDO)session.getAttribute("user");
Date date = new Date();
model.addAttribute("value",value);
if(condition.equals("风险查询")){
model.addAttribute("first",firstLevelRiskDAO.findAllBykeyLike(value));
model.addAttribute("second",secondLevelRiskDAO.findAllBykeyLike(value));
model.addAttribute("third",thirdLevelRiskDAO.findAllBykeyLike(value));
model.addAttribute("fourth",fourthLevelRiskDAO.findAllBykeyLike(value));
return "search_risk_list";
}else if(condition.equals("风险事件查询")){
model.addAttribute("risk_event_group",riskEventLibraryDAO.findBykey(value,"集团"));
model.addAttribute("risk_event_yueyang",riskEventLibraryDAO.findBykey(value,"岳阳林纸"));
model.addAttribute("risk_event_hongta",riskEventLibraryDAO.findBykey(value,"红塔仁恒"));
model.addAttribute("risk_event_kaisheng",riskEventLibraryDAO.findBykey(value,"凯胜园林"));
model.addAttribute("risk_event_guanhao",riskEventLibraryDAO.findBykey(value,"冠豪高新"));
return "search_risk_event";
}
return null;
}
@RequestMapping(value = "/notification_project/{type}")
public String notification_project(Model model, HttpSession session, @PageableDefault(size = 5,sort = {"id"},direction = Sort.Direction.ASC)Pageable pageable,@PathVariable(value = "type") String type){
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("new_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"刚创建",pageable).getTotalElements());
model.addAttribute("ready_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"待审批",pageable).getTotalElements());
model.addAttribute("pass_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"审批通过",pageable).getTotalElements());
model.addAttribute("failure_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"审批失败",pageable).getTotalElements());
model.addAttribute("published_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"已发布",pageable).getTotalElements());
model.addAttribute("ing_count",firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"审批中",pageable).getTotalElements());
Page<FirstLevelRiskDO> page=firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(),"刚创建",pageable);
if(user.getPermission()==1) {
if (type.equals("new_project")) {
page = firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(), "刚创建", pageable);
model.addAttribute("first_new", page);
model.addAttribute("Total_page", page.getTotalPages());
model.addAttribute("Total_elements", page.getTotalElements());
model.addAttribute("current_page", pageable.getPageNumber());
return "notification_new_project";
} else if (type.equals("pass")) {
page = firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(), "审批通过", pageable);
model.addAttribute("first_new", page);
model.addAttribute("Total_page", page.getTotalPages());
model.addAttribute("Total_elements", page.getTotalElements());
model.addAttribute("current_page", pageable.getPageNumber());
return "notification_my_passed_project";
} else if (type.equals("failure")) {
page = firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(), "审批失败", pageable);
model.addAttribute("first_new", page);
model.addAttribute("Total_page", page.getTotalPages());
model.addAttribute("Total_elements", page.getTotalElements());
model.addAttribute("current_page", pageable.getPageNumber());
return "notification_my_failure_project";
} else if (type.equals("published")) {
page = firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(), "已发布", pageable);
model.addAttribute("first_new", page);
model.addAttribute("Total_page", page.getTotalPages());
model.addAttribute("Total_elements", page.getTotalElements());
model.addAttribute("current_page", pageable.getPageNumber());
return "notification_my_published_project";
} else if (type.equals("ready")) {
page = firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(), "待审批", pageable);
model.addAttribute("first_new", page);
model.addAttribute("Total_page", page.getTotalPages());
model.addAttribute("Total_elements", page.getTotalElements());
model.addAttribute("current_page", pageable.getPageNumber());
return "notification_ready_project";
} else if (type.equals("ing")) {
page = firstLevelRiskDAO.findByfirstLevelRiskPerson_setup(user.getWorkerName(), "审批中", pageable);
model.addAttribute("first_new", page);
model.addAttribute("Total_page", page.getTotalPages());
model.addAttribute("Total_elements", page.getTotalElements());
model.addAttribute("current_page", pageable.getPageNumber());
return "notification_my_ing_project";
}
}else if (user.getPermission()==2){
model.addAttribute("new_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"刚创建",pageable).getTotalElements());
model.addAttribute("ready_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"待审批",pageable).getTotalElements());
model.addAttribute("pass_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"审批通过",pageable).getTotalElements());
model.addAttribute("failure_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"审批失败",pageable).getTotalElements());
model.addAttribute("published_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"已发布",pageable).getTotalElements());
model.addAttribute("ing_count",firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"审批中",pageable).getTotalElements());
if(type.equals("new_project")){
page=firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"刚创建",pageable);
model.addAttribute("first_new",page);
model.addAttribute("Total_page",page.getTotalPages());
model.addAttribute("Total_elements",page.getTotalElements());
model.addAttribute("current_page",pageable.getPageNumber());
return "notification_new_project";
}else if(type.equals("pass")){
page=firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"审批通过",pageable);
model.addAttribute("first_new",page);
model.addAttribute("Total_page",page.getTotalPages());
model.addAttribute("Total_elements",page.getTotalElements());
model.addAttribute("current_page",pageable.getPageNumber());
return "notification_my_passed_project";
}else if(type.equals("failure")){
page=firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"审批失败",pageable);
model.addAttribute("first_new",page);
model.addAttribute("Total_page",page.getTotalPages());
model.addAttribute("Total_elements",page.getTotalElements());
model.addAttribute("current_page",pageable.getPageNumber());
return "notification_my_failure_project";
}else if(type.equals("published")){
page=firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"已发布",pageable);
model.addAttribute("first_new",page);
model.addAttribute("Total_page",page.getTotalPages());
model.addAttribute("Total_elements",page.getTotalElements());
model.addAttribute("current_page",pageable.getPageNumber());
return "notification_my_published_project";
}else if(type.equals("ready")){
page=firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"待审批",pageable);
model.addAttribute("first_new",page);
model.addAttribute("Total_page",page.getTotalPages());
model.addAttribute("Total_elements",page.getTotalElements());
model.addAttribute("current_page",pageable.getPageNumber());
return "notification_ready_project";
}else if(type.equals("ing")){
page=firstLevelRiskDAO.findByFirstLevelRiskApplication_setup(user.getWorkerName(),"审批中",pageable);
model.addAttribute("first_new",page);
model.addAttribute("Total_page",page.getTotalPages());
model.addAttribute("Total_elements",page.getTotalElements());
model.addAttribute("current_page",pageable.getPageNumber());
return "notification_my_ing_project";
}
}
return null;
}
@RequestMapping(value = "/websocket_user")
public String websocket_user(Model model,HttpSession session){
return "index_test";
}
@RequestMapping(value = "/websocket_admin")
public String websocket_admin(Model model,HttpSession session){
return "admin";
}
@RequestMapping(value = "/websocket_chatroom")
public String websocket_chatroom(Model model,HttpSession session){
return "index_chatroom";
}
}
<file_sep>package com.duruo.dto.FlowDataChild;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/6/27 10:37
*
* @Email <EMAIL>
*/
@Data
public class db_flow_jjkc_cyry_info {
private String Id;
private String Num;
private String Name;
private String Age;
private String Education;
private String MajorName;
private String Post;
private String WorkingHours;
private String Remark;
}
<file_sep># IOPdemo
利用百度大脑识别图片技术的接口,来实现图片黄反识别。
1、百度大脑首页https://ai.baidu.com/
,进入右上角的控制台,登陆(如果没有先注册)。
2、进入产品黄反识别,新建应用,就有AppID,API Key,Secret Key。
3、在程序中使用上面生成的key,调用接口,进行图片识别。
<file_sep># 越翻墙越爱国

[笑傲江湖Messi](https://www.jianshu.com/u/d2a8479ca51a)
关注
2018.04.01 21:47 字数 1690 阅读 185评论 0喜欢 0
下午以及晚上的一段时间,都用来翻墙了,先看的是李敖,然后看的是丁仲礼院士、张维为、李世默还有一位英国学者,看到现在看的我情绪激昂,我内心的对自己国家、民族的自信在不断复苏,然后也更理性、更包容地看待这个世界已经无数的不同的人。
借用网友的话,要是大陆完全放开网络管制,让更多人可以翻墙,大家一定会爱国的,但是这也只是一个很片面的认识,中国这么多人,你无法保证所有人都可以理性地去看待,比如我被灌输了那么久的民主、自由,被西方的电影、教育方式等等,你有没有想过,西方的民主是不是画出的一个理性主意的大饼呢,让你充饥,然后让你不断地去比较,你却无法意识到,很简单的例子,平时你是多么轻易地陷入到比较的陷阱里面的,这让你更多地去放大社会中的一些问题,很多地时候我们都是肤浅的人,肤浅地被操纵,民众这样一个词的存在就会决定有操作的可能性,丁仲礼院士和柴静的访谈,可以看做当初肤浅的我和现在看完视频之后理性的我。不可否定柴静这个人很优秀,也不能说她人格有问题,被包装的名人,你无法触摸到,你所听到的、甚至看到的只是一个美化的东西,平静和谐的现实下面很可能是暗流涌动。首先看着两人的对话,我很佩服丁院士,当柴静质问他的时候,有些问题我都能反驳她,她像大多数受到西方影响的知识分子一样,对西方是仰视,像张维为说的,为什么不能平时,没让你去俯视,我们中国人大多数不敢,我想这与我们百十年来的被压迫历史有关系吧,我们潜意识里认为西方的都是正确的,西方的科学、知识就是真理,我们延续几千年的文化一文不值了,我们中国现在也有科学、真理了,为什么却把科学最基本的质疑精神都给丢弃了。气候变暖就是这样一个东西,二氧化碳含量的上升是一个事实,雾霾天气越来越多是个事实,可是我们发展啦,这是工业化带来的必然后果哈,西方的实验室模拟出来的结果,被媒体奉为真理,它可以督促政府,但我看到的更多的是制造恐慌,发达国家的行动呢,都不愿意放弃自己的发展,实力是一个国家立足的根本,还有就是是人类毁灭而不是地球毁灭,这是一个很重要的东西,现在想想操纵人们的公愤是多么可怕,当社会都愤怒的时候,你才会发现无知是多么可怕,让社会有那么多噪音,写着写着我的想法有些极端了、有些人身攻击了,这是不合适的,我给自己的要求就是这些东西不涉及人的人格,只是针对每个人根深蒂固的意识形态。
当你一个人的时候,你可以像每个人都理智、善良社会该多美好哈,可是中国是13亿多的人,世界是六十多亿的人,这看是复杂的系统,很多因果的关系在此处都失去作用了,像大数据一样,你得看它涌现出的一些问题,而不是仅是凭借理论去推导、预测问题。
我们的不自信,跟我们民族的谦虚有一定关系,还有就是鸦片战争以后我们都只是西方的学生,在科技面前,中国的文化对发展变的一文不值,我们屈服在西方科技的铁蹄之下,包括知识界,要是我我也会这样,师从国外的学者,一日为师终生为父,可是你终归回到了东方中国,发现我们的国家一团糟,理想主意刺激着你不断地批判(我有特指,我很烦王小波这些所谓的批判者,或者那些所谓的公知,可能有些个人偏见,但是我想想就气氛),气氛完你再想一想你这个模式跟西方的意识形态多么相似,我主导了科技革命,现如今世界的文明也是我们构建的,一份理所当然的傲慢偏见,听不进去一丝意见,辩论本身就是不断强化自己的偏见,你把它当做一个秀就可以了。中国发展真的太快了,威胁到西方的统治地位了,发达国家就是剥削发展中国家,本国的消费需要其他的国家来买单,虽然有些危言耸听,但这就是事实,这是存在。它的地位受到威胁了,西方有些思维就是零和博弈,无论文明多么地发展,一些规则就是那么原始,强者生存,落后就要挨打这就是真理,对中国的经济封锁、技术封锁这是明摆着的事实,无可否认。
所以,用我们学到的西方科学精神来说,无论什么东西都要有怀疑的精神,要独立、深刻的思考,而不只是简单地吸收,但这并不是要你不去接触,去闭关锁国。不让你去俯视,但你要有最起码的平视的勇气,为什么他们可以理所当然地优越,吸收、转化,取自于你、综合于我、再次超越你,这点中国人做的最好。
共勉每一位追求真知的知识分子。<file_sep>package com.duruo.controller;
import ch.qos.logback.core.util.FileUtil;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.baidu.aip.util.Base64Util;
import com.duruo.common.Const;
import com.duruo.common.DataSourceContextHolder;
import com.duruo.common.ResponseCode;
import com.duruo.common.ServerResponse;
import com.duruo.dao.CorpMapper;
import com.duruo.dao.EvidenceFilesMapper;
import com.duruo.dao.QchuangMapper;
import com.duruo.dao.RetailLicenseMapper;
import com.duruo.dto.Query;
import com.duruo.po.*;
import com.duruo.po.Qchuang;
import com.duruo.util.*;
import com.duruo.util.StringUtils;
import com.duruo.vo.*;
import com.duruo.webserviceClient.WebServiceClient2;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.iflytek.msp.cpdb.lfasr.client.LfasrClientImp;
import com.iflytek.msp.cpdb.lfasr.exception.LfasrException;
import com.iflytek.msp.cpdb.lfasr.model.LfasrType;
import com.iflytek.msp.cpdb.lfasr.model.Message;
import com.iflytek.msp.cpdb.lfasr.model.ProgressStatus;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.*;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
/**
* Created by @Author tachai
* date 2018/8/14 15:23
* GitHub https://github.com/TACHAI
* Email <EMAIL> wechatroutine/qchuang.do
*/
//https://can.xmduruo.com:4000/wechatroutine/webWord.do
@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping("/wechatroutine/")
@Slf4j
public class WeChatRoutine {
@Autowired
private CorpMapper corpMapper;
@Autowired
private QchuangMapper qchuangMapper;
@Autowired
private RetailLicenseMapper retailLicenseMapper;
@Autowired
private EvidenceFilesMapper evidenceFilesMapper;
//网页
@PostMapping("webWord.do")
@ResponseBody
public ServerResponse<String> webWord(HttpServletRequest request, HttpServletResponse response, String word, String sessionId) {
log.info("SESSION_ID:{}", sessionId);
log.info("word:{}", word);
Query query = new Query();
query.setUserId(sessionId);
if (StringUtils.isNum(word)) {
query.setQuery(word);
} else {
word = word.toString().replaceAll("[\\pP‘’“”]", "").toUpperCase();
query.setQuery(word);
}
String data = new Gson().toJson(query);
// String result = HttpUtil.okhttp("http://192.168.127.12:82/shxh/mes!recvWeb.so", data);
String result = HttpUtil.okhttp(PropertiesUtil.getProperty("weixin.url"), data);
// String result = HttpUtil.okhttp("http://192.168.127.12:82/shxh/mes!recvWebTest.so", data);
JsonParser parser = new JsonParser();
System.out.println(result);
log.info("webWord.do返回的值:{}",result);
if(result==null){
log.error("webWord.do返回的值为空");
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
JsonObject jsonObject=null;
try{
jsonObject = (JsonObject) parser.parse(result);
}catch (Exception e){
log.error("webWord.do发生错误返回的值:{}{}",result,e.getMessage());
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
// JsonObject jsonObject1 = (JsonObject) jsonObject.get("info");
if (jsonObject.get("answer") != null) {
result = jsonObject.get("answer").toString();
String msgid = jsonObject.get("msgid").getAsString();
return ServerResponse.createBySuccess(StringUtils.trim(StringUtils.trim(result, '"'), '"'), msgid);
// if (result.indexOf("上海市及徐汇区有很多企业扶持政策可以申请") != -1) {
//
// } else {
//
// }
// System.out.println(result);
}
return ServerResponse.createBySuccess("我会学习的", "未识别");
}
/**
* 自助机
* @param request
* @param response
* @param word
* @param sessionId
* @return
*/
@PostMapping("zzj.do")
@ResponseBody
public ServerResponse<String> zzj(HttpServletRequest request, HttpServletResponse response, String word, String sessionId) {
log.info("SESSION_ID:{}", sessionId);
log.info("word:{}", word);
Query query = new Query();
query.setUserId(sessionId);
if (StringUtils.isNum(word)) {
query.setQuery(word);
} else {
word=word.toString().replaceAll("[\\pP‘’“”]", "").toUpperCase();
query.setQuery(word);
}
String data = new Gson().toJson(query);
String result = HttpUtil.okhttp(PropertiesUtil.getProperty("zzj.url"), data);
JsonParser parser = new JsonParser();
System.out.println(result);
log.info("webWord.do返回的值:{}",result);
if(result==null){
log.error("webWord.do返回的值为空");
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
JsonObject jsonObject=null;
try{
jsonObject = (JsonObject) parser.parse(result);
}catch (Exception e){
log.error("webWord.do发生错误返回的值:{}{}",result,e.getMessage());
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
// JsonObject jsonObject1 = (JsonObject) jsonObject.get("info");
if (jsonObject.get("answer") != null) {
result = jsonObject.get("answer").toString();
String msgid = jsonObject.get("msgid").getAsString();
return ServerResponse.createBySuccess(StringUtils.trim(StringUtils.trim(result, '"'), '"'), msgid);
}
return ServerResponse.createBySuccess("我会学习的", "未识别");
}
//政务大厅
@PostMapping("zwdt.do")
@ResponseBody
public ServerResponse<String> zwdt(HttpServletRequest request, HttpServletResponse response, String word, String sessionId) {
log.info("SESSION_ID:{}", sessionId);
log.info("word:{}", word);
Query query = new Query();
query.setUserId(sessionId);
if (StringUtils.isNum(word)) {
query.setQuery(word);
} else {
word = word.toString().replaceAll("[\\pP‘’“”]", "").toUpperCase();
query.setQuery(word);
}
String data = new Gson().toJson(query);
String result = HttpUtil.okhttp(PropertiesUtil.getProperty("zwdt.url"), data);
JsonParser parser = new JsonParser();
System.out.println(result);
log.info("webWord.do返回的值:{}",result);
if(result==null){
log.error("webWord.do返回的值为空");
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
JsonObject jsonObject=null;
try{
jsonObject = (JsonObject) parser.parse(result);
}catch (Exception e){
log.error("webWord.do发生错误返回的值:{}{}",result,e.getMessage());
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
// JsonObject jsonObject1 = (JsonObject) jsonObject.get("info");
if (jsonObject.get("answer") != null) {
result = jsonObject.get("answer").toString();
String msgid = jsonObject.get("msgid").toString();
return ServerResponse.createBySuccess(StringUtils.trim(StringUtils.trim(result, '"'), '"'), msgid);
// if (result.indexOf("上海市及徐汇区有很多企业扶持政策可以申请") != -1) {
//
// } else {
//
// }
// System.out.println(result);
}
return ServerResponse.createBySuccess("我会学习的", "未识别");
}
//模型
@PostMapping("moxing.do")
@ResponseBody
public ServerResponse<String> moxing(HttpServletRequest request, HttpServletResponse response, String word, String sessionId) {
log.info("SESSION_ID:{}", sessionId);
log.info("word:{}", word);
Query query = new Query();
query.setUserId(sessionId);
if (StringUtils.isNum(word)) {
query.setQuery(word);
} else {
word = word.toString().replaceAll("[\\pP‘’“”]", "").toUpperCase();
query.setQuery(word);
}
String data = new Gson().toJson(query);
// String result = HttpUtil.okhttp("http://192.168.127.12:82/shxh/mes!recvWebTest.so", data);
String result = HttpUtil.okhttp(PropertiesUtil.getProperty("moxing.url"), data);
JsonParser parser = new JsonParser();
System.out.println(result);
log.info("webWord.do返回的值:{}",result);
if(result==null){
log.error("webWord.do返回的值为空");
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
JsonObject jsonObject=null;
try{
jsonObject = (JsonObject) parser.parse(result);
}catch (Exception e){
log.error("webWord.do发生错误返回的值:{}{}",result,e.getMessage());
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
// JsonObject jsonObject1 = (JsonObject) jsonObject.get("info");
if (jsonObject.get("answer") != null) {
result = jsonObject.get("answer").toString();
String msgid = jsonObject.get("msgid").toString();
return ServerResponse.createBySuccess(StringUtils.trim(StringUtils.trim(result, '"'), '"'), msgid);
// if (result.indexOf("上海市及徐汇区有很多企业扶持政策可以申请") != -1) {
//
// } else {
//
// }
// System.out.println(result);
}
return ServerResponse.createBySuccess("我会学习的", "未识别");
}
@PostMapping("test.do")
@ResponseBody
public ServerResponse<String> test(HttpServletRequest request, HttpServletResponse response, String word, String sessionId) {
log.info("SESSION_ID:{}", sessionId);
log.info("word:{}", word);
Query query = new Query();
query.setUserId(sessionId);
if (StringUtils.isNum(word)) {
query.setQuery(word);
} else {
word = word.toString().replaceAll("[\\pP‘’“”]", "").toUpperCase();
query.setQuery(word);
}
String data = new Gson().toJson(query);
// String result = HttpUtil.okhttp("http://192.168.127.12:82/shxh/mes!recvMoxing.so", data);
String result = HttpUtil.okhttp(PropertiesUtil.getProperty("test.url"), data);
JsonParser parser = new JsonParser();
System.out.println(result);
log.info("webWord.do返回的值:{}",result);
if(result==null){
log.error("webWord.do返回的值为空");
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
JsonObject jsonObject=null;
try{
jsonObject = (JsonObject) parser.parse(result);
}catch (Exception e){
log.error("webWord.do发生错误返回的值:{}{}",result,e.getMessage());
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
// JsonObject jsonObject1 = (JsonObject) jsonObject.get("info");
if (jsonObject.get("answer") != null) {
result = jsonObject.get("answer").toString();
String msgid = jsonObject.get("msgid").toString();
return ServerResponse.createBySuccess(StringUtils.trim(StringUtils.trim(result, '"'), '"'), msgid);
}
return ServerResponse.createBySuccess("我会学习的", "未识别");
}
//微信
@PostMapping("byWord.do")
@ResponseBody
public ServerResponse<String> byWord(HttpSession session, @RequestParam("word") String word) throws UnsupportedEncodingException {
String temp = URLDecoder.decode(word, "utf-8");
//todo
JSONObject json = new JSONObject(temp);
System.out.println(json.get("word"));
// System.out.println(session.getId());
Query query = new Query();
query.setUserId(session.getId());
String wordTemp = json.get("word").toString().replaceAll("[\\pP‘’“”]", "").toUpperCase();
query.setQuery(wordTemp);
String data = new Gson().toJson(query);
// String result = HttpUtil.okhttp("http://192.168.127.12:82/shxh/mes!recvWeb.so", data);
String result = HttpUtil.okhttp("http://139.219.105.178:82/shxh/mes!recvWebTest.so", data);
JsonParser parser = new JsonParser();
System.out.println(result);
JsonObject jsonObject = (JsonObject) parser.parse(result);
// JsonObject jsonObject1 = (JsonObject) jsonObject.get("info");
if (jsonObject.get("answer") != null) {
result = jsonObject.get("answer").toString();
String response = StringUtils.trim(StringUtils.trim(result, '"'), '"');
String msgid = jsonObject.get("msgid").getAsString();
// String reg = "/[a-zA-z]+:\/\/[^\s]*/g";
// String url="";
// while ((url = reg.exec(response)) != null) {
// response = response
// .replace(url,
// "< a href='"+url+"' target='_blank'><font color='blue'>请点这里哦~</font></ a>");
// }//这里的reg就是上面的正则表达式
// response = response.replace("/\r\n/g", "<br/>");
// response = response.replace("/\\n/g", "<br/>");
// System.out.println(result);
return ServerResponse.createBySuccess(response,msgid);
}
return ServerResponse.createBySuccess("我会学习的", "未识别");
}
// 用户满意度返回
@PostMapping("csr.do")
@ResponseBody
public ServerResponse<String> sendCSR(String msgid,String csr,String suggestion){
//http://192.168.127.12:82/shxh/mes!csr.so
// {"msgid":obj.msgid,"csr":0,"suggestion":""}
Map<String,String> map = new HashMap<>();
map.put("msgid",msgid);
map.put("csr",csr);
map.put("suggestion",suggestion);
String data = new Gson().toJson(map);
String result = HttpUtil.okhttp("http://192.168.127.12:82/shxh/mes!csr.so", data);
JsonParser parser = new JsonParser();
if(result==null){
log.error("csr.do返回的值为空msgid:{}",msgid);
}
JsonObject jsonObject=null;
try{
jsonObject = (JsonObject) parser.parse(result);
if (jsonObject.toString().indexOf("404")!=-1){
log.error("csr.do发生错误msgid:{}{}",msgid,jsonObject.toString());
}
}catch (Exception e){
log.error("csr.do发生错误返回的值msgid:{}{}{}",msgid,result,e.getMessage());
}
return ServerResponse.createBySuccessMessage(result);
}
// 微信接收语音
@PostMapping("byVice.do")
@ResponseBody
public ServerResponse<String> byVice(HttpSession session, @RequestParam("file") MultipartFile[] files) {
//接收文件
//多文件上传
String fileName = "";
log.info(files[0].getOriginalFilename() + "+++++______+++++" + files[0].getName());
if (files != null && files.length >= 1) {
BufferedOutputStream bw = null;
try {
fileName = files[0].getOriginalFilename();
log.info(fileName + "fileName----");
//判断是否有文件(实际生产中要判断是否是音频文件)
if (!org.apache.commons.lang3.StringUtils.isBlank(fileName)) {
//创建输出文件对象
log.info(fileName + "fileName+++");
File outFile = new File(PropertiesUtil.getProperty("outVoice.Path") + session.getId() + fileName);
//拷贝文件到输出文件对象
files[0].transferTo(outFile);
// FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//下面是给讯飞转义
/*
* 转写类型选择:标准版和电话版分别为:
* LfasrType.LFASR_STANDARD_RECORDED_AUDIO 和 LfasrType.LFASR_TELEPHONY_RECORDED_AUDIO
* */
LfasrType type = LfasrType.LFASR_STANDARD_RECORDED_AUDIO;
// 等待时长(秒)
int sleepSecond = 1;
// 初始化LFASR实例
LfasrClientImp lc = null;
try {
//初始化这里要加appid
//"5b724a39","33213dc3772dbf009d6775d02bb7888f"
lc = LfasrClientImp.initLfasrClient();
} catch (LfasrException e) {
// 初始化异常,解析异常描述信息
Message initMsg = JSON.parseObject(e.getMessage(), Message.class);
System.out.println("ecode=" + initMsg.getErr_no());
System.out.println("failed=" + initMsg.getFailed());
}
// 获取上传任务ID
String task_id = "";
HashMap<String, String> params = new HashMap<>();
params.put("has_participle", "true");
try {
// 上传音频文件
Message uploadMsg = lc.lfasrUpload(PropertiesUtil.getProperty("outVoice.Path") + session.getId() + fileName, type, params);
// 判断返回值
int ok = uploadMsg.getOk();
if (ok == 0) {
// 创建任务成功
task_id = uploadMsg.getData();
System.out.println("task_id=" + task_id);
} else {
// 创建任务失败-服务端异常
System.out.println("ecode=" + uploadMsg.getErr_no());
System.out.println("failed=" + uploadMsg.getFailed());
}
} catch (LfasrException e) {
// 上传异常,解析异常描述信息
Message uploadMsg = JSON.parseObject(e.getMessage(), Message.class);
System.out.println("ecode=" + uploadMsg.getErr_no());
System.out.println("failed=" + uploadMsg.getFailed());
}
// 循环等待音频处理结果
while (true) {
try {
// 睡眠1min。另外一个方案是让用户尝试多次获取,第一次假设等1分钟,获取成功后break;失败的话增加到2分钟再获取,获取成功后break;再失败的话加到4分钟;8分钟;……
Thread.sleep(sleepSecond * 1000);
System.out.println("waiting ...");
} catch (InterruptedException e) {
}
try {
// 获取处理进度
Message progressMsg = lc.lfasrGetProgress(task_id);
// 如果返回状态不等于0,则任务失败
if (progressMsg.getOk() != 0) {
System.out.println("task was fail. task_id:" + task_id);
System.out.println("ecode=" + progressMsg.getErr_no());
System.out.println("failed=" + progressMsg.getFailed());
// 服务端处理异常-服务端内部有重试机制(不排查极端无法恢复的任务)
// 客户端可根据实际情况选择:
// 1. 客户端循环重试获取进度
// 2. 退出程序,反馈问题
continue;
} else {
ProgressStatus progressStatus = JSON.parseObject(progressMsg.getData(), ProgressStatus.class);
if (progressStatus.getStatus() == 9) {
// 处理完成
System.out.println("task was completed. task_id:" + task_id);
break;
} else {
// 未处理完成
System.out.println("task was incomplete. task_id:" + task_id + ", status:" + progressStatus.getDesc());
continue;
}
}
} catch (LfasrException e) {
// 获取进度异常处理,根据返回信息排查问题后,再次进行获取
Message progressMsg = JSON.parseObject(e.getMessage(), Message.class);
System.out.println("ecode=" + progressMsg.getErr_no());
System.out.println("failed=" + progressMsg.getFailed());
}
}
// 获取任务结果
try {
Message resultMsg = lc.lfasrGetResult(task_id);
System.out.println(resultMsg.getData());
// 如果返回状态等于0,则任务处理成功
if (resultMsg.getOk() == 0) {
// 打印转写结果
//todo 得到语音转化结果
//解析讯飞平台得到的结果
JsonParser parser = new JsonParser();//创建json解析器
JsonArray jsonArray = (JsonArray) parser.parse(resultMsg.getData());
JsonObject kdjson = jsonArray.get(0).getAsJsonObject();
String word = StringUtils.trim(kdjson.get("onebest").toString(), '"');
System.out.println(word + "解析得到的结果");
Query query = new Query();
query.setUserId(session.getId());
query.setQuery(word.replaceAll("[\\pP‘’“”]", "").toUpperCase());
String data = new Gson().toJson(query);
String result = HttpUtil.okhttp(PropertiesUtil.getProperty("query.url"), data);
// JsonParser parser = new JsonParser();
System.out.println(result);
JsonObject jsonObject = (JsonObject) parser.parse(result);
if (jsonObject.get("state").toString().indexOf("10000") != -1) {
System.out.println(jsonObject.get("state").toString());
}
if (jsonObject.get("state").toString().indexOf("11000") != -1 || jsonObject.get("state").toString().indexOf("10003") != -1) {
System.out.println("发生了错误");
} else {
JsonObject jsonObject1 = (JsonObject) jsonObject.get("info");
if (jsonObject1.get("ask") != null) {
result = jsonObject1.get("ask").toString();
return ServerResponse.createBySuccess(result, "返回结果成功");
}
}
System.out.println(resultMsg.getData());
} else {
// 转写失败,根据失败信息进行处理
System.out.println("ecode=" + resultMsg.getErr_no());
System.out.println("failed=" + resultMsg.getFailed());
}
} catch (LfasrException e) {
// 获取结果异常处理,解析异常描述信息
Message resultMsg = JSON.parseObject(e.getMessage(), Message.class);
System.out.println("ecode=" + resultMsg.getErr_no());
System.out.println("failed=" + resultMsg.getFailed());
}
return ServerResponse.createByErrorMessage("返回结果失败");
}
@PostMapping("qchuang.do")
@ResponseBody
public Map<String, String> qchuang( @RequestBody com.duruo.vo.Qchuang qchuang){
if(qchuang!=null){
if(qchuang.getType().indexOf("sendMessage")!=-1){
return sendMessage(qchuang.getData().getQueryInfo(),qchuang.getData().getUserId());
}else if(qchuang.getType().indexOf("checkSUCC")!=-1){
// return checkSUCC(qchuang.getData().getQueryInfo(),qchuang.getData().getUserId());
return checkSUCC(qchuang.getData().getQueryInfo(),qchuang.getData().getUserId());
}else if(qchuang.getType().indexOf("checkMessage")!=-1){
return checkMessage(qchuang.getData().getQueryInfo(),qchuang.getData().getUserId());
}else if(qchuang.getType().indexOf("")!=-1){
return checkDreamStar(qchuang.getData().getUserId());
}
}
// log.info("checkSUCC:{},{}", queryInfo, userId);
Map<String, String> map = new HashMap<>();
map.put("answer", "96794927C872FD98AD1982B61BBE2223");
return map;
}
//todo 验证梦之星
private Map<String,String> checkDreamStar(String userId) {
return null;
}
//最近有没有好的政府补贴政策
//多轮对话调用的接口
//本地查询接口已过时
@Deprecated
public Map<String, String> checkUniScId(String queryInfo, String userId) {
// //切换数据源到oracle
// DataSourceContextHolder.setDBType("oracle");
//
// Corp corp = corpMapper.selectByUniScId(queryInfo);
//
// //切换数据源到mysql
// DataSourceContextHolder.setDBType("mysql");
Map<String, String> map = new HashMap<>();
//新增一条数据
Qchuang qchuang = new Qchuang();
// log.info();
qchuang.setId(userId);
//+++++++++++++++++++++++++++改为内网写接口
// Map<String,String> query= new HashMap<>();
// query.put("queryInfo",queryInfo);
// String data = new Gson().toJson(query);
// String result = HttpUtil.okhttp(PropertiesUtil.getProperty("fanren.url"), data);
// JsonParser parser = new JsonParser();
// System.out.println(result);
// JsonObject jsonObject = (JsonObject) parser.parse(result);
//
// if(jsonObject.has("answer")&&jsonObject.get("answer").toString().indexOf("064B1A7993B253AA9290385B930E6CA4")!=-1){
//
// Gson gs = new Gson();
// Corp corp =(Corp) gs.fromJson(jsonObject.get("corp"),Corp.class);
//
// qchuang.setPersonName(corp.getPersonName());
// qchuang.setCompanyName(corp.getCorpName());
// qchuang.setRegScope(corp.getBusinessScope());
// //营业地址为空所以写这个
// qchuang.setBusinessAddress(corp.getAddress());
//
// qchuang.setRegCapital(corp.getRegCapital().toString());
// qchuang.setRegDate(DateTimeUtil.strToDate(corp.getEstablishDate().substring(0, 9).replace("月", "").replace(" ",""), "dd-MM-yy"));
// qchuang.setAgencyCode(queryInfo);
// qchuang.setCreateDate(new Date());
// qchuangMapper.insert(qchuang);
// map.put("answer", "064B1A7993B253AA9290385B930E6CA4");
//
// return map;
// }else {
// if(jsonObject.has("opinion")){
// qchuang.setOpinion(jsonObject.get("opinion").getAsString());
// }
// map.put("answer", "96794927C872FD98AD1982B61BBE22231");
// }
//
//+++++++++++++++++++++++++++
Corp corp = corpMapper.selectByUniScId(queryInfo);
//todo 上线要把这个注释加上
// Qchuang qchuang1 = qchuangMapper.selectByUniScId(queryInfo);
//
// if(qchuang1!=null&&qchuang.getStatus()==2){
// qchuang.setOpinion("该企业已经注册过");
// qchuangMapper.insert(qchuang);
// return map;
// }
if (corp != null) {
//0.企业状态存在,则判断
if(org.apache.commons.lang3.StringUtils.isNotBlank(corp.getCorpStatus())){
if (corp.getCorpStatus().indexOf("1") == -1) {
map.put("answer", "96794927C872FD98AD1982B61BBE22232");
log.info("checkUniScId-0:{}","96794927C872FD98AD1982B61BBE22232");
qchuang.setOpinion("该企业为非正常营业");
qchuangMapper.insert(qchuang);
return map;
}
}
//1.判断企业经营范围(中介和劳务派遣打回)
if (corp.getBusinessScope().indexOf("劳务派遣") != -1 || corp.getBusinessScope().indexOf("中介") != -1) {
map.put("answer", "96794927C872FD98AD1982B61BBE22232");
log.info("checkUniScId-1:{}","96794927C872FD98AD1982B61BBE22232");
qchuang.setOpinion("介于查询到您的公司经营范围中含有“中介”或“劳务派遣”所以无法帮您线上办理。如有疑问,请与线下进行办理哦。地址:上海市南宁路999号五楼咨询窗口");
qchuangMapper.insert(qchuang);
return map;
}
// 2.判断企业注册时间(判断注册时间是否为“上一年”如:2018年办理,判断企业注册时间是否为2017年,之前注册的都打回)
Date date = new Date();
//date.getYear()是得到从1900年开始的年龄
//date.getYear();
if(date.getYear()-100!=Integer.parseInt(corp.getEstablishDate().substring(7, 9))){
if(date.getMonth()<6){
//todo 18年办的也可以在18年5.31前办
//17年可以在5.31前办
if (date.getYear() - 101 != Integer.parseInt(corp.getEstablishDate().substring(7, 9))) {
map.put("answer", "96794927C872FD98AD1982B61BBE22232");
log.info("checkUniScId-2:{}","96794927C872FD98AD1982B61BBE22232");
qchuang.setOpinion("您已超出此事项申请时间,无法办理,如有疑问,请与线下进行咨询哦。地址:上海市南宁路999号五楼咨询窗口");
qchuangMapper.insert(qchuang);
return map;
}
}else {
map.put("answer", "96794927C872FD98AD1982B61BBE22232");
log.info("checkUniScId-2:{}","96794927C872FD98AD1982B61BBE22232");
qchuang.setOpinion("您已超出此事项申请时间,无法办理,如有疑问,请与线下进行咨询哦。地址:上海市南宁路999号五楼咨询窗口");
qchuangMapper.insert(qchuang);
return map;
}
}
////3.判断企业注册资金(判断注册资金是不是200W以下,以上的都打回)
if (corp.getCurrency().indexOf("人民币") == -1) {
map.put("answer", "96794927C872FD98AD1982B61BBE22232");
log.info("checkUniScId-3:{}","96794927C872FD98AD1982B61BBE22232");
//对不起您的注册资金大于200万元人民币,无法办理此事项,如有疑问,请与线下进行咨询哦。地址:上海市南宁路999号五楼咨询窗口
qchuang.setOpinion("您的企业类型不符合办理条件,无法办理此事项,如有疑问,请与线下进行咨询哦。地址:上海市南宁路999号五楼咨询窗口");
qchuangMapper.insert(qchuang);
return map;
}
if (corp.getRegCapital().compareTo(new BigDecimal(200)) > 0) {
map.put("answer", "96794927C872FD98AD1982B61BBE22232");
log.info("checkUniScId-3-2:{}","96794927C872FD98AD1982B61BBE22232");
qchuang.setOpinion("您的注册资金大于200万元人民币,无法办理此事项,如有疑问,请与线下进行咨询哦。地址:上海市南宁路999号五楼咨询窗口");
qchuangMapper.insert(qchuang);
return map;
}
// 4.判断企业营业地点(是否是在徐汇)
//可以不做判断
// if (corp.getBusinessAddress().indexOf("徐汇") == -1) {
// map.put("answer", "96794927C872FD98AD1982B61BBE2223");
// log.info("checkUniScId-4:{}","96794927C872FD98AD1982B61BBE2223");
// return map;
// }
////5.是否是合伙企业(合伙企业不能办)
// 5.根据企业类型来判断不能办理
/**
* 外国承包商 00010500
* 分公司 00010200
* 非公司法人机构 00010400
* 合伙企业 00010600
* 合伙企业分支机构 00010700
* 个人分支机构 00010900
* 农民专业合作社分支机构 00040300
*/
String type = corp.getCorpType();
if(type!=null){
if(type.equals("00010500")||type.equals("00010200")||type.equals("00010400")||type.equals("00010600")||type.equals("00010700")||type.equals("00010900")||type.equals("00040300")){
map.put("answer", "96794927C872FD98AD1982B61BBE22232");
log.info("checkUniScId-5:{}","96794927C872FD98AD1982B61BBE22232");
qchuang.setOpinion("您的企业类型不符合办理条件,无法办理此事项,如有疑问,请与线下进行咨询哦。地址:上海市南宁路999号五楼咨询窗口");
qchuangMapper.insert(qchuang);
return map;
}
}
qchuang.setPersonName(corp.getPersonName());
qchuang.setCompanyName(corp.getCorpName());
qchuang.setRegScope(corp.getBusinessScope());
//营业地址为空所以写这个
qchuang.setBusinessAddress(corp.getAddress());
qchuang.setRegCapital(corp.getRegCapital().toString());
qchuang.setRegDate(DateTimeUtil.strToDate(corp.getEstablishDate().substring(0, 9).replace("月", "").replace(" ",""), "dd-MM-yy"));
qchuang.setAgencyCode(queryInfo);
qchuang.setCreateDate(new Date());
qchuangMapper.insert(qchuang);
map.put("answer", "064B1A7993B253AA9290385B930E6CA4");
return map;
}
// return "没有找到相关的工商信息,可能输入的同一信用代码有误";
map.put("answer", "96794927C872FD98AD1982B61BBE22231");
return map;
}
/**
* 社会统一代码
* 最新的从内网法人库查询
* @param queryInfo
* @param userId
* @return
*/
public Map<String, String> checkSUCC(String queryInfo, String userId ) {
Map<String, String> map = new HashMap<>();
//新增一条数据
Qchuang qchuang = qchuangMapper.selectByIdcard(userId);
if(qchuang!=null){
qchuangMapper.deleteByPrimaryKey(qchuang.getId());
}else {
qchuang = new Qchuang();
}
// log.info();
qchuang.setId(userId);
//+++++++++++++++++++++++++++改为内网写接口
log.info("进来了,内网查询接口");
//todo 公司名称核重
Qchuang qchuang1 = qchuangMapper.selectByUniScId(queryInfo);
//该企业已经注册过了
if(qchuang1!=null&&qchuang.getStatus()!=null){
qchuang.setOpinion("该企业已经申请过");
qchuangMapper.insert(qchuang);
map.put("answer", "96794927C872FD98AD1982B61BBE2223");
return map;
}
Map<String,String> query= new HashMap<>();
query.put("queryInfo",queryInfo);
String data = new Gson().toJson(query);
String result = HttpUtil.okhttpJSON(PropertiesUtil.getProperty("fanren.url"), data);
JsonParser parser = new JsonParser();
System.out.println(result);
JsonObject jsonObject = (JsonObject) parser.parse(result);
if(jsonObject.has("opinion")){
qchuang.setOpinion(jsonObject.get("opinion").getAsString());
log.info("查询返回数据opinion:{}",jsonObject.get("opinion").getAsString());
}
if(jsonObject.has("answer")&&jsonObject.get("answer").toString().indexOf("064B1A7993B253AA9290385B930E6CA4")!=-1){
Gson gs = new Gson();
Corp corp =(Corp) gs.fromJson(jsonObject.get("corp"),Corp.class);
// todo 把证照库中的营业执照存到青创的社保账单字段
if(jsonObject.getAsJsonObject("workApplyvo").has("imStuff")&&jsonObject.getAsJsonObject("workApplyvo").get("imStuff").getAsString()!=null){
qchuang.setSsbAddress(jsonObject.getAsJsonObject("workApplyvo").get("imStuff").getAsString());
}
// 公司名称核重
if (corp.getCorpName()!=null){
Qchuang qchuang2 = qchuangMapper.selectByCompanyName(corp.getCorpName());
if(qchuang2!=null&&qchuang2.getStatus()!=null){
qchuang.setOpinion("该企业已经申请过,如有疑问请线下咨询");
qchuangMapper.insert(qchuang);
map.put("answer", "96794927C872FD98AD1982B61BBE2223");
return map;
}
}
qchuang.setPersonName(corp.getPersonName());
qchuang.setCompanyName(corp.getCorpName());
qchuang.setRegScope(corp.getBusinessScope());
//营业地址为空所以写这个
qchuang.setBusinessAddress(corp.getAddress());
qchuang.setRegCapital(corp.getRegCapital().toString());
qchuang.setRegDate(DateTimeUtil.strToDate(corp.getEstablishDate().substring(0, 9).replace("月", "").replace(" ",""), "dd-MM-yy"));
qchuang.setAgencyCode(queryInfo);
qchuang.setCreateDate(new Date());
qchuangMapper.insert(qchuang);
map.put("answer", "064B1A7993B253AA9290385B930E6CA4");
return map;
}else {
qchuangMapper.insert(qchuang);
map.put("answer", "96794927C872FD98AD1982B61BBE2223");
// map.put("answer", "96794927C872FD98AD1982B61BBE22231");
}
return map;
}
//短信服务 阿里云弃用
// @PostMapping("sentMessage.do")
// @ResponseBody
@Deprecated
public Map<String, String> sentMessage(String phoneNum, String userId) {
log.info("sentMessage:{},{}", phoneNum, userId);
//sentMessage 中心平台
// String sessionId = WebServiceClient2.login();
// log.info("sentMessage-sessionId:{}", sessionId);
//
// Map<String, String> map = new HashMap<>();
//
// if(sessionId.indexOf("ERROR")!=-1){
//
// }else {
//
// String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
//
//
// String result = WebServiceClient2.sentMessage(sessionId,"您的验证码"+verifyCode+",请勿泄漏于他人",phoneNum);
// if(result.indexOf("ERROR")==-1){
//
// Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
// qchuang.setOpinion(verifyCode);
// qchuang.setContactNumber(phoneNum);
// qchuangMapper.updateByPrimaryKeySelective(qchuang);
//
// map.put("answer", "064B1A7993B253AA9290385B930E6CA4");
// return map;
// }
//
// }
//
// //否的MD5编码
// map.put("answer", "96794927C872FD98AD1982B61BBE2223");
// return map;
final String product = "Dysmsapi";//短信API产品名称(短信产品名固定,无需修改)
final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名(接口地址固定,无需修改)
//替换成你的AK
final String accessKeyId = "LTAIG1t8Dm6yO8pg";//你的accessKeyId,参考本文档步骤2
final String accessKeySecret = "<KEY>";//你的accessKeySecret,参考本文档步骤2
//初始化ascClient,暂时不支持多region(请勿修改)
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
accessKeySecret);
try {
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
} catch (ClientException e) {
log.error(e.getMessage());
}
IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象
SendSmsRequest request = new SendSmsRequest();
//使用post提交
request.setMethod(MethodType.POST);
//必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为00+国际区号+号码,如“0085200000000”
request.setPhoneNumbers(phoneNum);
//必填:短信签名-可在短信控制台中找到
request.setSignName("青创扶持");
//必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
//SMS_145501391 发送验证码
//SMS_146290756 审核通过
//SMS_146280948 审核不通过
request.setTemplateCode("SMS_147196028");
//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
Map<String, String> codeMap = new HashMap<>();
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
codeMap.put("code", verifyCode);
String code = new Gson().toJson(codeMap);
request.setTemplateParam(code);
// request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
//可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
//request.setSmsUpExtendCode("90997");
//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
// request.setOutId("yourOutId");
//请求失败这里会抛ClientException异常
Map<String, String> map = new HashMap<>();
try {
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
log.info("阿里短信状态码:{},{}", sendSmsResponse.getCode(),userId);
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
//请求成功
//todo 插数据到数据库 verifyCode
//Map<String, String> map = new HashMap<>();
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
qchuang.setOpinion(verifyCode);
qchuang.setContactNumber(phoneNum);
qchuangMapper.updateByPrimaryKeySelective(qchuang);
map.put("answer", "064B1A7993B253AA9290385B930E6CA4");
return map;
}
} catch (ClientException e) {
e.printStackTrace();
}
map.put("answer", "96794927C872FD98AD1982B61BBE2223");
return map;
}
//短信服务 中心
public Map<String,String> sendMessage(String phoneNum,String userId){
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
String content = "您申请的青年创业一次扶持事项的短信验证码是"+verifyCode+"请勿告诉他人。";
SentMessage.sendMessage(phoneNum, content);
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
qchuang.setOpinion(verifyCode);
qchuang.setContactNumber(phoneNum);
qchuangMapper.updateByPrimaryKeySelective(qchuang);
Map<String, String> map = new HashMap<>();
map.put("answer", "064B1A7993B253AA9290385B930E6CA4");
return map;
}
//验证短信
// @PostMapping("checkMessage.do")
// @ResponseBody
public Map<String, String> checkMessage(String token, String userId) {
log.info("checkMessage:{},{}", token, userId);
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
Map<String, String> map = new HashMap<>();
if (token.equals(qchuang.getOpinion())) {
map.put("answer", "064B1A7993B253AA9290385B930E6CA4");
return map;
}
map.put("answer", "96794927C872FD98AD1982B61BBE2223");
return map;
}
// 接收身份证图片和银行卡图片
@PostMapping("picture.do")
@ResponseBody
public ServerResponse<String> picture(String userId, @RequestParam("file") MultipartFile[] files) {
//接收文件
//多文件上传
String fileName = "";
log.info(files[0].getOriginalFilename() + "+++++______+++++" + files[0].getName());
if (files != null && files.length >= 1) {
BufferedOutputStream bw = null;
try {
fileName = userId+files[0].getOriginalFilename();
log.info(fileName + "fileName----");
String reson="";
if (!org.apache.commons.lang3.StringUtils.isBlank(fileName)) {
//创建输出文件对象
log.info(fileName + "fileName+++");
// File outFile = new File(PropertiesUtil.getProperty("img.Path") + userId + fileName);
// //拷贝文件到输出文件对象
// files[0].transferTo(outFile);
SFTPUtil.uploadFile(PropertiesUtil.getProperty("evidenceFiles.Path"), fileName, files[0].getInputStream());
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
JSONObject jsonObject = OCR.checkBackCard(files[0].getBytes());
//如果银行卡存在
if (org.apache.commons.lang3.StringUtils.isNotBlank(jsonObject.getJSONObject("result").getString("bank_name"))) {
String bankName = jsonObject.getJSONObject("result").getString("bank_name");
String bank_card_number = jsonObject.getJSONObject("result").getString("bank_card_number");
// bank_card_number.length();
reson=bank_card_number;
qchuang.setPersonBank(bankName);
qchuang.setPersonBankid(bank_card_number);
//保存银行卡的存储地址
qchuang.setBankAddress(PropertiesUtil.getProperty("evidenceFiles.Path") + fileName);
qchuangMapper.updateByPrimaryKeySelective(qchuang);
// SFTPUtil.uploadFile(PropertiesUtil.getProperty("evidenceFiles.Path"), fileName, files[0].getInputStream());
qchuang.setOpinion(reson);
qchuangMapper.updateByPrimaryKey(qchuang);
return sentWord(userId,"064B1A7993B253AA9290385B930E6CA4");
}
JSONObject jsonObject1 = OCR.checkIdcard(files[0].getBytes());
//如果身份证正面存在
//保存身份证的存储地址
if (jsonObject1.get("words_result") != null) {
if (org.apache.commons.lang3.StringUtils.isNotBlank(jsonObject1.getJSONObject("words_result").getJSONObject("姓名").getString("words"))) {
qchuang.setIdcardAddress(PropertiesUtil.getProperty("evidenceFiles.Path") + fileName);
String name = jsonObject1.getJSONObject("words_result").getJSONObject("姓名").getString("words");
if (qchuang.getPersonName().indexOf(name) == -1) {
// 不是本人
qchuang.setOpinion("不是本人的身份证");
qchuangMapper.updateByPrimaryKey(qchuang);
return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
}
if (org.apache.commons.lang3.StringUtils.isNotBlank(jsonObject1.getJSONObject("words_result").getJSONObject("住址").getString("words"))) {
String address = jsonObject1.getJSONObject("words_result").getJSONObject("住址").getString("words");
qchuang.setHouseholdReg(address);
}
if (org.apache.commons.lang3.StringUtils.isNotBlank(jsonObject1.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words"))) {
String idCard = jsonObject1.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
//todo 法人核重
Qchuang qchuang1 =qchuangMapper.selectByIdcard(idCard);
if(qchuang1!=null&&qchuang1.getStatus()!=null){
qchuang.setOpinion("该法人已经申请过,不能在次申请");
qchuangMapper.updateByPrimaryKey(qchuang);
return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
}
//todo 判断是否是35岁
Date regDete = qchuang.getRegDate();
Date birthDate = DateTimeUtil.strToDate(idCard.substring(6,14),"yyyyMMdd");
if(regDete!=null){
Calendar cld = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.setTime(birthDate);
cld.setTime(regDete);
int yearReg=regDete.getYear();
int monthReg = regDete.getMonth();
int dayReg = cld.get(Calendar.DAY_OF_MONTH);
int age = yearReg-(Integer.parseInt(idCard.substring(6,10))-1900);
if(age>35){
qchuang.setOpinion("注册公司时年龄大于35岁");
qchuangMapper.updateByPrimaryKey(qchuang);
return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
} else if(age==35) {
if(monthReg>birthDate.getMonth()){
//todo
qchuang.setOpinion("注册公司时年龄大于35岁");
qchuangMapper.updateByPrimaryKey(qchuang);
return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
}else if(monthReg==birthDate.getMonth()){
if(dayReg>=cal.get(Calendar.DAY_OF_MONTH)){
qchuang.setOpinion("注册公司时年龄大于35岁");
qchuangMapper.updateByPrimaryKey(qchuang);
return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
}
}
}
}
qchuang.setIdCard(idCard);
}
qchuangMapper.updateByPrimaryKeySelective(qchuang);
// SFTPUtil.uploadFile(PropertiesUtil.getProperty("evidenceFiles.Path"), fileName, files[0].getInputStream());
qchuang.setOpinion(reson);
qchuangMapper.updateByPrimaryKey(qchuang);
return sentWord(userId,"064B1A7993B253AA9290385B930E6CA4");
}
}
JSONObject jsonObject2 = OCR.checkIdcardBack(files[0].getBytes());
if (jsonObject2.get("words_result") != null && jsonObject2.getJSONObject("words_result").has("失效日期")) {
if (org.apache.commons.lang3.StringUtils.isNotBlank(jsonObject2.getJSONObject("words_result").getJSONObject("失效日期").getString("words"))) {
String date = jsonObject2.getJSONObject("words_result").getJSONObject("失效日期").getString("words");
//20270123
String year = date.substring(0,4);
String month = date.substring(4,6);
String day = date.substring(6,8);
String time = year+"-"+month+"-"+day;
Date source = DateTimeUtil.strToDate(time,"yyyy-MM-dd");
Date target = new Date();
target.getDay();
String temp = DateTimeUtil.dateToStr(target);
temp = temp.substring(0,10);
target = DateTimeUtil.strToDate(temp,"yyyy-MM-dd");
// 当前日期大于身份证过期日期 身份证过期了
if(target.getTime()>source.getTime()){
qchuang.setOpinion("身份证过期了");
qchuangMapper.updateByPrimaryKey(qchuang);
return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
}
EvidenceFiles evidenceFile = new EvidenceFiles();
evidenceFile.setDeptId(72);
evidenceFile.setMatterId(10000);
evidenceFile.setMsgId(userId);
evidenceFile.setPath(PropertiesUtil.getProperty("evidenceFiles.Path")+userId+files[0].getOriginalFilename());
Date fileDate = new Date();
evidenceFile.setCreateTime(fileDate);
evidenceFile.setDeptName("徐汇区社会保障局");
evidenceFile.setMatterName("青年创业扶持");
// type 身份证背面不带人脸的一面
evidenceFile.setType("身份证背面");
// qchuangMapper.updateByPrimaryKeySelective(qchuang);
// SFTPUtil.uploadFile(PropertiesUtil.getProperty("evidenceFiles.Path"), fileName, files[0].getInputStream());
qchuang.setOpinion(reson);
qchuangMapper.updateByPrimaryKey(qchuang);
return sentWord(userId,"064B1A7993B253AA9290385B930E6CA4");
}
}
//todo 加到里面去
return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
// FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sentWord(userId,"96794927C872FD98AD1982B61BBE2223");
}
//人脸图片
@PostMapping("getFace.do")
public String face(String userId, @RequestParam("file") MultipartFile[] files) {
//接收文件
//多文件上传
String fileName = "";
log.info(files[0].getOriginalFilename() + "+++++______+++++" + files[0].getName());
if (files != null && files.length >= 1) {
BufferedOutputStream bw = null;
try {
fileName = userId + files[0].getOriginalFilename();
log.info(fileName + "fileName----");
//判断是否有文件(实际生产中要判断是否是音频文件)
if (!org.apache.commons.lang3.StringUtils.isBlank(fileName)) {
EvidenceFiles evidenceFile = new EvidenceFiles();
//保存到数据库
evidenceFile.setMsgId(userId);
evidenceFile.setPath(PropertiesUtil.getProperty("evidenceFiles.Path")+fileName);
Date fileDate = new Date();
evidenceFile.setCreateTime(fileDate);
evidenceFile.setType("人脸图片");
// evidenceFile.setLicenseId(license.getId());
//上传人脸图片
SFTPUtil.uploadFile(PropertiesUtil.getProperty("evidenceFiles.Path"),fileName, files[0].getInputStream());
evidenceFilesMapper.insert(evidenceFile);
//todo 要做人脸识别
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
//log.info("getImg.do IdcardAddress:{}",qchuang.getIdcardAddress());
//取身份证图片 todo 空指针
int temp = qchuang.getIdcardAddress().lastIndexOf('/');
String directory = qchuang.getIdcardAddress().substring(0,temp+1);
String idfileName = qchuang.getIdcardAddress().substring(temp+1);
byte[] idresult = SFTPUtil.downloadFile(directory,idfileName);
byte[] face = files[0].getBytes();
//todo 人脸识别
//JSONObject jsonObject =FACE.checkFace(URLEncoder.encode(Base64Util.encode(face)), URLEncoder.encode(Base64Util.encode(idresult)));
try{
JSONObject jsonObject =FACE.checkFace(Base64Util.encode(face), Base64Util.encode(idresult));
log.info("人脸识别:{}",jsonObject.toString());
// 将申请表地址改为存人脸分数
if(jsonObject.has("result")){
if(jsonObject.getJSONObject("result").has("score")){
if(jsonObject.getJSONObject("result").get("score").toString().equals("0")){
qchuang.setAppleformAddress("0");
}else {
qchuang.setAppleformAddress(jsonObject.getJSONObject("result").get("score").toString().substring(0,5));
}
}
}
}catch (Exception e){
log.error("人脸识别错误:{}",e.getMessage());
}
qchuangMapper.updateByPrimaryKeySelective(qchuang);
// return "redirect:http://webbot.xzfwzx.xuhui.gov.cn/qiangming/index.html?userId="+userId;
return "redirect:http://webbot.xzfwzx.xuhui.gov.cn/commit/commit.html?userId="+userId;
}
}catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "redirect:http://webbot.xzfwzx.xuhui.gov.cn/index.html?userId="+userId;
}
/**
* 青创审核
* @param session
* @param userId
* @param opinion
* @return
*/
@PostMapping("opinion.do")
@ResponseBody
public ServerResponse<String> opinion(HttpSession session,String userId,@RequestParam(value = "opinion", defaultValue = "预审通过") String opinion,String result){
// PortalMyNoteCacheService.getInstance().getMyNoteListResponse(CommonHttpUtil.getIdentity());
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user != null) {
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
qchuang.setOpinion(opinion);
qchuang.setStatus(Integer.parseInt(result));
//String sessionId = WebServiceClient2.login();
//log.info("sentMessage-sessionId:{}", sessionId);
if(result.equals("0")){
// 审核成功后发送通知 阿里云短信平台
// SentMessage.sentMessage(qchuang.getContactNumber(),"SMS_147201031",qchuang.getPersonName(),"");
SentMessage.sendMessage(qchuang.getContactNumber(),"尊敬的"+qchuang.getPersonName()+"先生/女士,您于"+DateTimeUtil.dateToStr(qchuang.getCreateDate())+"申请的青年创业一次性开办费已通过审核,补贴将于3个月内由徐汇区社会保障基金专户划拨到法定代表人(经营者)个人帐户,请耐心等待~");
}else if(result.equals("2")) {
// 审核失败后发送通知
// SentMessage.sentMessage(qchuang.getContactNumber(),"SMS_147201030",qchuang.getPersonName(),opinion);
SentMessage.sendMessage(qchuang.getContactNumber(),"尊敬的"+qchuang.getPersonName()+"先生/女士,您于"+DateTimeUtil.dateToStr(qchuang.getCreateDate())+"申请的青年创业一次性开办费由于"+opinion+"未通过审核,如有疑问请电话咨询:24092222*3507。您可以按照咨询建议准备相关材料前往徐汇区行政服务中心南宁路999号二号楼五楼办理。(办理时间:星期一至星期五上午9:00~11:30,下午13:30~16:30");
// if(sessionId.indexOf("ERROR")!=-1){
//
// }else {
// // 徐汇短信平台
// String returnResult = WebServiceClient2.sentMessage(sessionId, "尊敬的"+qchuang.getPersonName()+"先生/女士您好,很遗憾的通知您,您申请的青年创业一次性扶持因为"+opinion+"未通过", qchuang.getContactNumber());
// log.info("sentMessage-失败:{}", returnResult);
// }
}
int result1=qchuangMapper.updateByPrimaryKeySelective(qchuang);
return result1>0?ServerResponse.createBySuccessMessage("审核成功"):ServerResponse.createBySuccessMessage("审核失败");
} else {
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getDesc());
}
}
@RequestMapping("springUpload.do")
// @ResponseBody
public String springUpload(HttpSession session, HttpServletRequest request, String deptId, String MsgId, String matterId, String deptName, String matterName, String flowName) throws IllegalStateException, IOException, SftpException ,Exception{
if (!org.apache.commons.lang3.StringUtils.isBlank(MsgId)) {
Date date = new Date();
try {
//插入文件list信息
RetailLicense license = new RetailLicense();
license.setCreateTime(date);
license.setDeptId(Integer.parseInt(deptId));
// MsgId(微信id)为
license.setMsgId(MsgId);
license.setMatterId(Integer.parseInt(matterId));
license.setMatterName(matterName);
license.setStatus("未审核");
int result = retailLicenseMapper.insert(license);
if (result > 0) {
log.info("事项插入成功:{}", MsgId);
} else {
log.error("事项插入失败:{}", MsgId);
}
} catch (Exception e) {
// retailLicenseMapper.deleteByPrimaryKey(MsgId+matterId);
// evidenceFilesMapper.deleteByMsgId(MsgId);
// return ServerResponse.createByErrorMessage("该用户已上传过该事项文件,正在清空,请再上传一次");
}
//青创
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(MsgId);
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if (multipartResolver.isMultipart(request)) {
//将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//获取multiRequest 中所有的文件名
// Iterator iter = multiRequest.getFileNames();
Iterator iter = multiRequest.getFileNames();
EvidenceFiles evidenceFile = new EvidenceFiles();
while (iter.hasNext()) {
//一次遍历所有文件
List<MultipartFile> files = multiRequest.getFiles(iter.next().toString());
//防止插空的数据
for(int i=0;i<files.size();i++){
MultipartFile file = files.get(i);
try{
if (!org.apache.commons.lang3.StringUtils.isBlank(file.getOriginalFilename())) {
String fileName = MsgId + "_" + matterId + "_" + file.getName() + "_" + file.getOriginalFilename();
String path = PropertiesUtil.getProperty("evidenceFiles.Path") + fileName;
log.info("文件名:{}", file.getOriginalFilename());
log.info("属性", file.getName());
System.out.println(file.getName());
RetailLicense license = retailLicenseMapper.selectByTimeAndMsgId(MsgId, date);
// if (file.getName().indexOf("银行卡") != -1) {
// if (Contain.containImage(file.getOriginalFilename())) {
//
// JSONObject jsonObject = OCR.checkBackCard(file.getBytes());
// //如果银行卡存在
// if(jsonObject.getJSONObject("result")!=null){
// if(org.apache.commons.lang3.StringUtils.isNotBlank(jsonObject.getJSONObject("result").getString("bank_name"))){
// String bankName = jsonObject.getJSONObject("result").getString("bank_name");
// String bank_card_number = jsonObject.getJSONObject("result").getString("bank_card_number");
// qchuang.setPersonBank(bankName);
// qchuang.setPersonBankid(bank_card_number);
// //保存银行卡的存储地址
//// qchuang.setBankAddress(PropertiesUtil.getProperty("img.Path") + fileName);
// qchuang.setBankAddress(path);
// }
// }
// }
// }
// if (file.getName().indexOf("身份证") != -1) {
// if (Contain.containImage(file.getOriginalFilename())) {
//
// JSONObject jsonObject1 = OCR.checkIdcard(file.getBytes());
// //如果身份证存在
// if (jsonObject1.get("words_result") != null) {
// if(org.apache.commons.lang3.StringUtils.isNotBlank(jsonObject1.getJSONObject("words_result").getJSONObject("姓名").getString("words"))){
// String name = jsonObject1.getJSONObject("words_result").getJSONObject("姓名").getString("words");
// //保存身份证的存储地址
// qchuang.setIdcardAddress(path);
//// qchuang.setIdcardAddress(PropertiesUtil.getProperty("img.Path") + fileName);
//// if (qchuang.getPersonName().indexOf(name) == -1) {
//// return sentWord(userId,"否");
//// }
// String address = jsonObject1.getJSONObject("words_result").getJSONObject("住址").getString("words");
// qchuang.setHouseholdReg(address);
// String idCard = jsonObject1.getJSONObject("words_result").getJSONObject("公民身份号码").getString("words");
// qchuang.setIdCard(idCard);
// }
// }
// }
// }
//保存到数据库
evidenceFile.setDeptId(Integer.parseInt(deptId));
evidenceFile.setMatterId(Integer.parseInt(matterId));
evidenceFile.setMsgId(MsgId);
evidenceFile.setPath(path);
Date fileDate = new Date();
evidenceFile.setCreateTime(fileDate);
evidenceFile.setDeptName(deptName);
evidenceFile.setMatterName(matterName);
evidenceFile.setType(file.getName());
evidenceFile.setLicenseId(license.getId());
//覆盖上传
evidenceFilesMapper.insert(evidenceFile);
//上传到本地服务器
// file.transferTo(new File(path));
// 上传到文件服务器
SFTPUtil.uploadFile(PropertiesUtil.getProperty("evidenceFiles.Path"), fileName, file.getInputStream());
}
}catch (Exception e){
log.info("青创文件错误:{}",e.getMessage());
}
}
}
qchuang.setStatus(1);
qchuangMapper.updateByPrimaryKeySelective(qchuang);
}
// todo 改成人脸识别或签名
return "redirect:http://webbot.xzfwzx.xuhui.gov.cn/face/huoti.html?userId="+MsgId;
} else {
return "redirect:/404.html";
}
}
/**
* 青创身份证图片
* @param response
* @param userId
*/
@RequestMapping("getImg.do")
public void getImg(HttpServletResponse response, String userId) {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
//证明材料不能为空
if (null != userId) {
//调用方法下载 到应用服务器
// UpAndDownload.downloadFileByPath(response,filePath);
log.info("getImg.do userId:{}",userId);
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
log.info("getImg.do IdcardAddress:{}",qchuang.getIdcardAddress());
// 调用SFTP方法下载文件
UpAndDownload.downloadFileByFilePath(response,qchuang.getIdcardAddress());
System.out.println("成功下载");
}
}
/**
* 签名图片
* @param userId
* @param signatureAddress
* @return
*/
@PostMapping("saveSignatureAddress.do")
@ResponseBody
public ServerResponse<String> saveSignatureAddress(String userId,String signatureAddress){
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
qchuang.setSignatureAddress(signatureAddress);
qchuang.setStatus(1);
int result = qchuangMapper.updateByPrimaryKeySelective(qchuang);
if(result>0){
}
// return "redirect:/success.html";
return ServerResponse.createBySuccessMessage("返回成功");
}
/**
* 青创银行卡图片
* @param response
* @param userId
*/
@RequestMapping("getbankImg.do")
public void getbankImg(HttpServletResponse response, String userId) {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
//证明材料不能为空
if (null != userId) {
//调用方法下载 到应用服务器
// UpAndDownload.downloadFileByPath(response,filePath);
log.info("getImg.do userId:{}",userId);
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
log.info("getImg.do IdcardAddress:{}",qchuang.getBankAddress());
// 调用SFTP方法下载文件
UpAndDownload.downloadFileByFilePath(response,qchuang.getIdcardAddress());
System.out.println("成功下载");
}
}
/**
* 青创普通图片
* @param response
* @param userId
* @param type 图片类型
*/
@RequestMapping("commonImg.do")
public void getcommonImg(HttpServletResponse response, String userId,String type) {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
EvidenceFiles evidenceFiles = null;
try {
type = URLDecoder.decode(type, "utf-8");
// licenseId = URLDecoder.decode(licenseId, "utf-8");
evidenceFiles = evidenceFilesMapper.selByTypeAndmsgId(userId,type);
//获得文件名
// String[] fileNames = evidenceFile.getPath().split("_");
//String directory = qchuang.getIdcardAddress().substring(0,temp+1);
int temp = evidenceFiles.getPath().lastIndexOf('/');
String idfileName = evidenceFiles.getPath().substring(temp+1);
//如果使用中文会丢失名字只留下后缀名
response.setHeader("Content-Disposition", "attachment;filename=" + new String(idfileName.getBytes(), "ISO-8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//证明材料不能为空
if (null != userId) {
//调用方法下载 到应用服务器
// UpAndDownload.downloadFileByPath(response,filePath);
log.info("commonImg.do userId:{}",userId);
evidenceFiles = evidenceFilesMapper.selByTypeAndmsgId(userId,type);
log.info("commonImg.do IdcardAddress:{}",evidenceFiles.getPath());
// 调用SFTP方法下载文件
UpAndDownload.downloadFileByFilePath(response,evidenceFiles.getPath());
System.out.println("成功下载");
}
}
//查询青创文件列表
@GetMapping("getlist.do")
@ResponseBody
public ServerResponse<List<EvidenceFiles>> listFile(HttpSession session, String userId){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user != null) {
return ServerResponse.createBySuccess(evidenceFilesMapper.listByMsgId(userId));
} else {
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getDesc());
}
}
@PostMapping("getdetail.do")
@ResponseBody
public ServerResponse<QchaungVO> getdetail(HttpSession session,String userId){
User user = (User) session.getAttribute(Const.CURRENT_USER);
if (user != null) {
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
QchaungVO qchuangVO = new QchaungVO();
BeanUtils.copyProperties(qchuang,qchuangVO);
Date date = new Date();
log.info("当前年份:{}",date.getYear()+1900);
qchuangVO.setAge(date.getYear()+1900-Integer.parseInt(qchuang.getIdCard().substring(6,10))+"");
qchuangVO.setApplyDate(DateTimeUtil.dateToStr(qchuang.getCreateDate()));
return ServerResponse.createBySuccess(qchuangVO);
} else {
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getDesc());
}
}
//查询进度
@PostMapping("queryProgress.do")
@ResponseBody
public ServerResponse<String> queryProgress(String number,String code){
Qchuang qchuang = qchuangMapper.selectByIdcard(number);
if(qchuang!=null||qchuang.getAppleformAddress().indexOf(code)!=-1){
if(qchuang.getStatus()==1){
return ServerResponse.createBySuccessMessage("该用户正在审核");
}else if(qchuang.getStatus()==0){
return ServerResponse.createBySuccessMessage("该用户已审核通过");
}else if(qchuang.getStatus()==2){
return ServerResponse.createBySuccessMessage("该用户未通过原因是:"+qchuang.getOpinion());
}
return ServerResponse.createBySuccessMessage("该用户通过申核条件");
}
return ServerResponse.createBySuccessMessage("未找到相关信息或者验证码错误");
}
@PostMapping("checkUser.do")
@ResponseBody
public ServerResponse<String> checkUser(String number){
Qchuang qchuang = qchuangMapper.selectByIdcard(number);
if(qchuang!=null){
String phoneNum = qchuang.getContactNumber();
log.info("wechatroutine/checkUser.do:{}",phoneNum);
if(phoneNum==null){
return ServerResponse.createByErrorMessage("该用户的手机号为空");
}
// String sessionId = WebServiceClient2.login();
// log.info("sentMessage-sessionId:{}", sessionId);
// String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
//
// String result = WebServiceClient2.sentMessage(sessionId,"您的验证码"+verifyCode+",请勿泄漏于他人",phoneNum);
// if(result.indexOf("ERROR")==-1){
// log.info("sentMessage-发送短信错误:{}", result);
// qchuang.setAppleformAddress(verifyCode);
// //qchuang.setContactNumber(phoneNum);
// qchuangMapper.updateByPrimaryKeySelective(qchuang);
// return ServerResponse.createBySuccessMessage("已发送短信");
// }
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
String content = "您申请的青年创业一次性开办费扶持事项查询的短信验证码是"+verifyCode+"请勿告诉他人。";
SentMessage.sendMessage(phoneNum, content);
qchuang.setAppleformAddress(verifyCode);
qchuang.setContactNumber(phoneNum);
qchuangMapper.updateByPrimaryKeySelective(qchuang);
}
return ServerResponse.createByErrorMessage("未找到相关信息");
}
@PostMapping("returnReson.do")
@ResponseBody
public ServerResponse<String> returnReson(String userId){
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(userId);
if(qchuang!=null&&qchuang.getOpinion()!=null){
return ServerResponse.createBySuccessMessage(qchuang.getOpinion());
}
return ServerResponse.createByErrorMessage("未找到该用户,请重新输入");
}
private ServerResponse<String> sentWord(String userId,String word){
Query query = new Query();
query.setUserId(userId);
if (StringUtils.isNum(word)) {
query.setQuery(word);
} else {
query.setQuery(word.toString().replaceAll("[\\pP‘’“”]", "").toUpperCase());
}
String data = new Gson().toJson(query);
String result = HttpUtil.okhttp("http://192.168.127.12:82/shxh/mes!recvWeb.so", data);
JsonParser parser = new JsonParser();
System.out.println(result);
JsonObject jsonObject = (JsonObject) parser.parse(result);
// JsonObject jsonObject1 = (JsonObject) jsonObject.get("info");
if (jsonObject.get("answer") != null) {
result = jsonObject.get("answer").toString();
return ServerResponse.createBySuccess(StringUtils.trim(StringUtils.trim(result, '"'), '"'), "返回后台数据");
// System.out.println(result);
}
return ServerResponse.createBySuccess("十分抱歉,这个问题对于我还比较陌生,不过我已经做下相关记录。请问您还有什么事项想要了解吗?", "未识别");
}
}
<file_sep>/**
* 通用ajax请求数据组件
*
*/
window.ZLSH = window.ZLSH || {};
ZLSH.request = (function($){
var cgiMap = {
'0' : 'http://shenhe.video.qq.com/fcgi-bin/lock_video_list?',
'1' : 'http://shenhe.video.qq.com/fcgi-bin/audit_video_list?',
'2' : 'http://shenhe.video.qq.com/fcgi-bin/audit_video_list?'
};
function request(cgi, param){
cgi = cgi || cgiMap['0'];
param = param || {};
this.cgi = cgi;
this.param = {
otype : 'json',
offset : 0,
limit : 10,
audit_result : 1
};
this.timeout = 8000;
this.check = null;
this.error = null;
this.success = null;
$.extend(this.param, param);
}
$.extend(request.prototype, {
setParam : function(param){
$.extend(this.param, param);
},
getParam : function(key){
return this.param[key];
},
setFn : function(key, fn){
var me = this;
if($.isFunction(fn) && typeof(key)=='string'){
me[key] = fn;
}
},
buildUrl : function(){
var sb = [];
sb.push(this.cgi);
var paramStr = $.param(this.param);
sb.push(paramStr);
return sb.join('');
},
query : function(callback){
var me = this;
var url = me.buildUrl();
$.ajax({
url : url,
dataType : "jsonp",
timeout : me.timeout,
cache : false,
complete : function(){
},
error : function(msg) {
me.error && me.error(msg);
},
success : function(json) {
var flag = true;
if($.isFunction(me.check)){
flag = me.check(json);
}
if(!flag){
me.error && me.error(json);
}else{
me.success && me.success(json);
if($.isFunction(callback)) callback.call(me, json);
}
}
});
}
});
request.defaultInit = function(type, param){
type = '' + type;
type = type || '0';
var cgi = cgiMap[type];
var req = new request(cgi, param);
return req;
};
return request;
})(jQuery);
<file_sep>package com.example.demo.controller;
import com.example.demo.dao.RulesRegulationsDAO;
import com.example.demo.pojo.RulesRegulationsDO;
import com.example.demo.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
@Controller
@EnableAutoConfiguration
@RequestMapping(value = "/rule")
public class RuleRegulationController {
@Autowired
private RulesRegulationsDAO rulesRegulationsDAO;
@RequestMapping(value = "/list")
public String list(Model model, HttpSession session){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
return "rule_regulation_management";
}
@RequestMapping(value = "/notice")
public String notice(Model model, HttpSession session){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
RulesRegulationsDO rulesRegulationsDO=new RulesRegulationsDO();
model.addAttribute("ro",rulesRegulationsDO);
return "rule_regulation_management_notice";
}
@RequestMapping(value = "/standard")
public String standard(Model model, HttpSession session){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
RulesRegulationsDO rulesRegulationsDO=new RulesRegulationsDO();
model.addAttribute("ro",rulesRegulationsDO);
return "rule_regulation_management_standard";
}
@RequestMapping(value = "/statistic")
public String statistic(Model model, HttpSession session){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
RulesRegulationsDO rulesRegulationsDO=new RulesRegulationsDO();
model.addAttribute("ro",rulesRegulationsDO);
return "rule_regulation_management_statistic";
}
@RequestMapping(value="/uploading_document_notice",produces="text/plain;charset=UTF-8")
public String uploading_document_notice(@RequestParam("file") MultipartFile file,
HttpServletRequest request,Model model) {
System.out.println("+++++++++++++++++++++++++++++++++++" + file);
String contentType = file.getContentType();
String fileName =file.getOriginalFilename();
System.out.println("fileName-->" + fileName);
System.out.println("getContentType-->" + contentType);
String filePath = "C:\\Users\\songyu\\downloaddocument\\";
System.out.println("filepath--->"+filePath);
RulesRegulationsDO rulesRegulationsDO =new RulesRegulationsDO();
File file1 = new File(filePath , fileName);
String filename1 = fileName;
System.out.println(filename1);
if(file1.exists()){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
model.addAttribute("uploading_success",0);
return "rule_regulation_management_notice";
}else {
try {
UploadUtil.uploadFile(file.getBytes(), filePath, fileName);
model.addAttribute("uploading_success",1);
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
rulesRegulationsDO.setId(0);
rulesRegulationsDO.setRulesAndRegulationsNotice(fileName);
rulesRegulationsDAO.save(rulesRegulationsDO);
return "rule_regulation_management_notice";
} catch (Exception e) {
// TODO: handle exception
}
}
//返回json
return null;
}
@RequestMapping(value="/uploading_document_statistic",produces="text/plain;charset=UTF-8")
public String uploading_document_statistic(@RequestParam("file") MultipartFile file, @RequestParam(value = "key") String key,
HttpServletRequest request,Model model) {
System.out.println("+++++++++++++++++++++++++++++++++++" + file);
String contentType = file.getContentType();
String fileName =file.getOriginalFilename();
System.out.println("fileName-->" + fileName);
System.out.println("getContentType-->" + contentType);
String filePath = "C:\\Users\\songyu\\downloaddocument\\";
System.out.println("filepath--->"+filePath);
RulesRegulationsDO rulesRegulationsDO =new RulesRegulationsDO();
File file1 = new File(filePath , fileName);
String filename1 = fileName;
System.out.println(filename1);
if(file1.exists()){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
model.addAttribute("uploading_success",0);
return "rule_regulation_management_statistic";
}else {
try {
UploadUtil.uploadFile(file.getBytes(), filePath, fileName);
model.addAttribute("uploading_success",1);
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
rulesRegulationsDO.setId(0);
if (key.equals("全球统计")){
rulesRegulationsDO.setGlobalStatistics(fileName);
}else if(key.equals("全国统计")){
rulesRegulationsDO.setNationalTatistics(fileName);
}else if(key.equals("省市统计")){
rulesRegulationsDO.setProvincialStatistics(fileName);
}
rulesRegulationsDAO.save(rulesRegulationsDO);
model.addAttribute("uploading_success",1);
return "rule_regulation_management_statistic";
} catch (Exception e) {
// TODO: handle exception
}
}
return "null";
}
@RequestMapping(value="/uploading_document_standard",produces="text/plain;charset=UTF-8")
public String uploading_document_standard(@RequestParam("file") MultipartFile file, @RequestParam(value = "key") String key,
HttpServletRequest request,Model model) {
System.out.println("+++++++++++++++++++++++++++++++++++" + file);
String contentType = file.getContentType();
String fileName =file.getOriginalFilename();
System.out.println("fileName-->" + fileName);
System.out.println("getContentType-->" + contentType);
String filePath = "C:\\Users\\songyu\\downloaddocument\\";
System.out.println("filepath--->"+filePath);
RulesRegulationsDO rulesRegulationsDO =new RulesRegulationsDO();
File file1 = new File(filePath , fileName);
String filename1 = fileName;
System.out.println(filename1);
if(file1.exists()){
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
model.addAttribute("uploading_success",0);
return "rule_regulation_management_standard";
}else {
try {
UploadUtil.uploadFile(file.getBytes(), filePath, fileName);
model.addAttribute("uploading_success",1);
rulesRegulationsDO.setId(0);
if (key.equals("基础标准")){
rulesRegulationsDO.setRulesAndRegulationsStandardArmy(fileName);
}else if(key.equals("方法标准")){
rulesRegulationsDO.setRulesAndRegulationsStandardMethod(fileName);
}else if(key.equals("产品标准")){
rulesRegulationsDO.setRulesAndRegulationsStandardProduct(fileName);
}
rulesRegulationsDAO.save(rulesRegulationsDO);
model.addAttribute("uploading_success",1);
model.addAttribute("rule_regulation",rulesRegulationsDAO.findAll());
return "rule_regulation_management_standard";
} catch (Exception e) {
// TODO: handle exception
}
}
return "null";
}
@RequestMapping("/downloading_document/{fileName}")
public String downloadFile10(HttpServletRequest request, HttpServletResponse response, @PathVariable(value = "fileName") String fileName) {
if (fileName != null) {
//设置文件路径
String filePath = "C:\\Users\\songyu\\downloaddocument\\";
String fileName1 = fileName+".doc";
File file = new File(filePath , fileName1);
System.out.println("+++++++++++++++++++++"+file);
if (file.exists()) {
System.out.println("+++++++++++++++++++++"+file);
response.setContentType("application/force-download");// 设置强制下载不打开
try {
response.setHeader("Content-Disposition", "attachment; fileName="+ fileName1 +";filename*=utf-8''"+ URLEncoder.encode(fileName1,"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
@RequestMapping("/download_standard")
public String download_standard(HttpServletRequest request, HttpServletResponse response) {
String fileName = "标准文件样本";
if (fileName != null) {
//设置文件路径
String filePath = "C:\\Users\\songyu\\downloaddocument\\";
String fileName1 = fileName+".doc";
File file = new File(filePath , fileName1);
System.out.println("+++++++++++++++++++++"+file);
if (file.exists()) {
System.out.println("+++++++++++++++++++++"+file);
response.setContentType("application/force-download");// 设置强制下载不打开
try {
response.setHeader("Content-Disposition", "attachment; fileName="+ fileName1 +";filename*=utf-8''"+ URLEncoder.encode(fileName1,"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
@RequestMapping("/download_statistic")
public String download_statistic(HttpServletRequest request, HttpServletResponse response) {
String fileName = "标准统计样本";
if (fileName != null) {
//设置文件路径
String filePath = "C:\\Users\\songyu\\downloaddocument\\";
String fileName1 = fileName+".doc";
File file = new File(filePath , fileName1);
System.out.println("+++++++++++++++++++++"+file);
if (file.exists()) {
System.out.println("+++++++++++++++++++++"+file);
response.setContentType("application/force-download");// 设置强制下载不打开
try {
response.setHeader("Content-Disposition", "attachment; fileName="+ fileName1 +";filename*=utf-8''"+ URLEncoder.encode(fileName1,"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
}
<file_sep>package com.duruo.po;
import lombok.Data;
import java.util.Date;
/**
* Created by @Author tachai
* date 2018/7/25 16:25
*
* @Email <EMAIL>
*/
@Data
public class PersonalInformationCollection {
//单位名称
private String unitName;
//社会保险登记码
private String insuranceCode;
//姓名
private String persionName;
//曾用名
private String oldName;
//身份证号码
private String idCard;
//性别
private String sex;
//民族
private String nation;
//政治面貌
private String politicalOutlook;
//受教育程度
private String educationalLevel;
//户籍地址
private String permanentAddress;
//详细地址
private String detailedAddress;
//户籍类别
private String householdRegistrationCategory;
//本市居住地地址
private String localAddress;
//联系电话
private String linkTel;
//邮政编码
private String postalCode;
//居住地街道
private String residentialStreet;
//其他联系方式
private String otherWaysContact;
//日期
private Date createDate;
}
<file_sep>package com.example.demo.service;
import com.example.demo.disputespojo.LegalDisputesDO;
import java.util.List;
public interface LegalDisputesService {
LegalDisputesDO saveLegalDisputes(LegalDisputesDO legalDisputesDO);
void deleteLegalDisputes(int id);
LegalDisputesDO findLegalDisputes( int id);
LegalDisputesDO findLegalDisputesbymonthnum( int id);
LegalDisputesDO updateLegalDisputes(LegalDisputesDO legalDisputesDO);
List<LegalDisputesDO> findall();
}
<file_sep>/*
Copyright (c) 2008 notmasteryet
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
/* generic readers */
var base64alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
/* RFC 4648 */
function Base64Reader(base64)
{
this.position = 0;
this.base64 = base64;
this.bits = 0;
this.bitsLength = 0;
this.readByte = function(){
if(this.bitsLength == 0)
{
var tailBits = 0;
while(this.position < this.base64.length && this.bitsLength < 24)
{
var ch = this.base64.charAt(this.position);
++this.position;
if(ch > " ")
{
var index = base64alphabet.indexOf(ch);
if(index < 0) throw "Invalid character";
if(index < 64)
{
if(tailBits > 0) throw "Invalid encoding (padding)";
this.bits = (this.bits << 6) | index;
}
else
{
if(this.bitsLenght < 8) throw "Invalid encoding (extra)";
this.bits <<= 6;
tailBits += 6;
}
this.bitsLength += 6;
}
}
if(this.position >= this.base64.length)
{
if(this.bitsLength == 0)
return -1;
else if(this.bitsLength < 24)
throw "Invalid encoding (end)";
}
if(tailBits == 6)
tailBits = 8;
else if(tailBits == 12)
tailBits = 16;
this.bits = this.bits >> tailBits;
this.bitsLength -= tailBits;
}
this.bitsLength -= 8
var code = (this.bits >> this.bitsLength) & 0xFF;
return code;
};
// extensions
this.read = function(buffer, index, count){
var i = 0;
while(i < count){
var rb = this.readByte();
if(rb == -1) return i;
buffer[index + i] = rb;
i++;
}
return i;
};
this.skip = function(count){
for(var i=0;i<count;i++) this.readByte();
};
this.readChar = function(){
var rb = this.readByte();
return rb == -1 ? null : String.fromCharCode(rb);
};
this.readChars = function(chars){
var txt = '';
for(var i=0;i<chars;i++){
var c = this.readChar();
if (!c) return txt;
txt += c;
}
return txt;
};
this.readInt = function(){
var bytes = [];
if (this.read(bytes, 0, 4) != 4) throw "Out of bounds";
return (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3];
};
}<file_sep>package com.duruo.service;
import com.duruo.common.ServerResponse;
/**
* Created by @Author tachai
* date 2018/7/19 19:34
*
* @Email <EMAIL>
*/
public interface IReturnWeiXinService {
ServerResponse<String> getWeChatId(String weChatId, String matterName);
ServerResponse<String> sentPublicPlace(String weChatId, String matterName);
ServerResponse<String> sentOtherWorkingHoursApply(String weChatId, String matterName);
ServerResponse<String> sentElectronicDigitalApply(String weChatId, String matterId);
ServerResponse<String> sentTZSB1(String weChatId,String matterId);
ServerResponse<String> sentTZSB2(String weChatId,String matterId);
ServerResponse<String> recordRegistrationOfMaigrantWorkers(String weChatId,String matterId);
}
<file_sep>package com.example.demo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.example.demo.disputespojo.*;
import com.example.demo.service.LegalDisputesService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class LegalDIsputesApplication {
@Autowired
LegalDisputesService legalDisputesService;
@Test
public void saveLegalDisputes(){
LegalDisputesDO legalDisputesDO=new LegalDisputesDO();
legalDisputesDO.setDate(new Date());
legalDisputesDO.setMonthnum(1);
legalDisputesDO.setAdministrativeDisputesDO(new AdministrativeDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setCasualtiesOutsideRoadDamageDisputesDO(new CasualtiesOutsideRoadDamageDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setConstructionContractDisputesDO(new ConstructionContractDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setFinancialDamageDisputesDO(new FinancialDamageDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setFreightTransportContractDisputesDO(new FreightTransportContractDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setRailwayEmployeesLaborDisputesDO(new RailwayEmployeesLaborDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setHouseDisputesDO(new HouseDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setIntellectualPropertyDisputesDO(new IntellectualPropertyDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setLaborDispatchingDisputesDO(new LaborDispatchingDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setLandDisputesDO(new LandDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setOtherContractDisputesDO(new OtherContractDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setOtherDamageDisputesDO(new OtherDamageDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setOtherLaborDisputesDO(new OtherLaborDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setOtherPropertyDisputesDO(new OtherPropertyDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setPassengerTransportContractDisputesDO(new PassengerTransportContractDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setRailwayEmployeesRetireDisputesDO(new RailwayEmployeesRetireDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setRentContractDisputesDO(new RentContractDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setSalePurchaseContractDisputesDO(new SalePurchaseContractDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setStockDisputesDO(new StockDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesDO.setTravelerDamageDisputesDO(new TravelerDamageDisputesDO(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1));
legalDisputesService.saveLegalDisputes(legalDisputesDO);
}
// @Test
// public void findlegaldisputes(){
// LegalDisputesDO legalDisputesDO=legalDisputesService.findLegalDisputes(1);
// System.out.println(JSON.toJSON(legalDisputesDO));
// String str=JSON.toJSONString(legalDisputesDO);
// JSONArray jsonArray =new JSONArray();
// System.out.println(json.get);
// }
@Test
public void findiniinfo(HttpServletRequest httpServletRequest){
System.out.println(httpServletRequest.getServletContext().getInitParameter("encoding"));
}
}
<file_sep>/*
This is the script file for the options page. It handles loading the options from localStorage as well as writing them back to localStorage and the background page.
Author: <NAME>
Date Created: 10/22/2012
Date Updated: 11/5/2012
Copyright 2013 <NAME>
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.
*/
// This function sets the default values for the options page. If the user has not set any options yet, the values set by this function will be used.
function default_options()
{
// These variables hold the elements on the page that will have default values.
var text_on = document.getElementById("text_active");
var image_on = document.getElementById("image_active");
var blocked_words = document.getElementById("blocked_words");
var image_blocked_words = document.getElementById("image_blocked_words");
var word_or_sentence = document.getElementById("word_or_sentence");
var scanner_sensitivity = document.getElementById("scanner_sensitivity");
var range2 = document.getElementById("range2");
// This loop will set the text filter to on.
for (var i = 0; i < text_on.children.length; i++)
{
if (text_on.children[i].value == "true")
{
text_on.children[i].checked = "true";
break;
}
}
// This loop will set the image filter to on.
for (var i = 0; i < image_on.children.length; i++)
{
if (image_on.children[i].value == "true")
{
image_on.children[i].checked = "true";
break;
}
}
// The following two lines initialize the text boxes with suggested words to block on.
blocked_words.value = "sex\nbreast\nboob\npenis\ndick\nvagina\nfuck\ndamn\nhell\nmasturbate\nmasturbation\nhandjob\nblowjob\nfellatio\nnaked\nnude";
image_blocked_words.value = "sex\nbreast\nboob\npenis\nvagina\ndick\nfuck\nmasturbate\nmasturbation\nhandjob\nblowjob\nfellatio\nnaked\nnude";
//word_or_sentence.children[0].checked = 'true'; // error with this feature
scanner_sensitivity.children[0].value = 50;
range2.innerHTML = "50%";
}
// This function updates an html element to show the change in a the slider bar value for the image scanner sensitivity.
function showValue(newValue)
{
document.getElementById("range2").innerHTML= document.getElementById("scanner_sensitivity").children[0].value + "%";
}
function load_options()
{
// These variables hold all the elements of the page that we need to set holding the options previously chosen.
var text_on = document.getElementById("text_active");
var blocked_words = document.getElementById("blocked_words");
var whitelisted_websites = document.getElementById("whitelisted_websites");
//var replace_sentence = document.getElementById("word_or_sentence"); // error with this feature
var block_paragraph_checkbox = document.getElementById("block_paragraph_checkbox");
var block_webpage_checkbox = document.getElementById("block_webpage_checkbox");
var num_for_paragraph = document.getElementById("num_for_paragraph");
var num_for_webpage = document.getElementById("num_for_webpage");
var image_on = document.getElementById("image_active");
var image_blocked_words = document.getElementById("image_blocked_words");
var image_whitelisted_websites = document.getElementById("image_whitelisted_websites");
var image_scanner = document.getElementById("image_scanner");
var scanner_sensitivity = document.getElementById("scanner_sensitivity");
var range2 = document.getElementById("range2");
var saved_note = document.getElementById("saved_note");
if (localStorage["text_on"] == "true")
text_on.children[0].checked = true;
else
text_on.children[1].checked = true;
// Regardless of whether or not the text filter is on, we will load all the previously saved options so that it is easier to turn the filter back on later.
// Sets the text in the blocked words box
if (localStorage["blocked_words"])
blocked_words.value = localStorage["blocked_words"];
// Sets the text in the whitelisted websites box
if (localStorage["whitelisted_websites"])
whitelisted_websites.value = localStorage["whitelisted_websites"];
/* // error with this feature
// If localStorage["replace_sentence"] is true, we want to check the option to replace the sentence. (radio button)
if (localStorage["replace_sentence"] == "true")
replace_sentence.children[2].checked = true;
else
replace_sentence.children[0].checked = true;
*/
// Sets the block paragraph checkbox
if (localStorage["block_paragraph"] == "true")
block_paragraph_checkbox.checked = true;
else
block_paragraph_checkbox.checked = false;
// Sets the block webpage checkbox
if (localStorage["block_webpage"] == "true")
block_webpage_checkbox.checked = true;
else
block_webpage_checkbox.checked = false;
// Sets the textbox for the paragraph threshold
if (localStorage["num_to_block_paragraph"])
num_for_paragraph.value = localStorage["num_to_block_paragraph"];
// Sets the textbox for the webpage threshold
if (localStorage["num_to_block_webpage"])
num_for_webpage.value = localStorage["num_to_block_webpage"];
// Sets the radio button for the image filter on/off
if (localStorage["image_on"] == "true")
image_on.children[0].checked = true;
else
image_on.children[1].checked = true;
// Populates the blocked words textbox
if (localStorage["image_blocked_words"])
image_blocked_words.value = localStorage["image_blocked_words"];
// Populates the whitelisted websites box
if (localStorage["image_whitelisted_websites"])
image_whitelisted_websites.value = localStorage["image_whitelisted_websites"];
// Sets the image scanner checkbox to either checked or not checked.
if (localStorage["image_scanner"] == "true")
image_scanner.children[0].checked = true;
else
image_scanner.children[0].checked = false;
// Sets the image scanner sensitivity.
scanner_sensitivity.children[0].value = localStorage["scanner_sensitivity"];
range2.innerHTML = localStorage["scanner_sensitivity"] + "%";
// Check if there is a saved note and that it is not empty. If so, load the note with the date/time the options were saved.
if (localStorage["saved_note"] && localStorage["saved_note"] != "")
{
saved_note.innerHTML = "The last time the options were saved was: " + localStorage["month"] + "-" + localStorage["day"] + "-" + localStorage["year"] + " at " + localStorage["hour"] + ":" + localStorage["minute"] + " " + localStorage["morning"] + ". With note: " + localStorage["saved_note"];
}
// Otherwise, if there is a saved date/time, just load that. NOTE: if there is a saved note, there will be a saved date/time
else if (localStorage["year"])
{
saved_note.innerHTML = "The last time the options were saved was: " + localStorage["month"] + "-" + localStorage["day"] + "-" + localStorage["year"] + " at " + localStorage["hour"] + ":" + localStorage["minute"] + " " + localStorage["morning"] + ". With no note.";
}
}
function load_page()
{
if (localStorage["text_on"] || localStorage["image_on"])
load_options();
else
default_options();
}
// This function will prompt the user, asking if they want to make a note why they changed the settings. If they answer yes, then a prompt box will appear.
// The function will then store the date, time, and the note in localStorage so that they can be loaded. It will also change the current html of the options page
// So that the note, date/time will appear immediately.
function store_date_and_note (date)
{
var prompt_choice = window.prompt("Do you wish to save a note explaining why you changed the settings?", "Note");
var year = String(date.getFullYear());
var month = String(date.getMonth() + 1);
var day = String(date.getDate());
var hour = date.getHours();
var minute = date.getMinutes();
var AM_or_PM = "AM";
// Make sure that the hour has a '0' before single-digit minutes.
if (minute < 10)
{
minute = '0' + minute;
}
// Convert 24 hour into 12 hour
switch (hour)
{
case 12:
AM_or_PM = "PM";
break;
case 13:
hour = 1;
AM_or_PM = "PM";
break;
case 14:
hour = 2;
AM_or_PM = "PM";
break;
case 15:
hour = 3;
AM_or_PM = "PM";
break;
case 16:
hour = 4;
AM_or_PM = "PM";
break;
case 17:
hour = 5;
AM_or_PM = "PM";
break;
case 18:
hour = 6;
AM_or_PM = "PM";
break;
case 19:
hour = 7;
AM_or_PM = "PM";
break;
case 20:
hour = 8;
AM_or_PM = "PM";
break;
case 21:
hour = 9;
AM_or_PM = "PM";
break;
case 22:
hour = 10;
AM_or_PM = "PM";
break;
case 23:
hour = 11;
AM_or_PM = "PM";
break;
case 0:
hour = 12;
break;
}
hour = String(hour);
// If there is a note, save the note along with the date and time, and update the options page accordingly.
if (prompt_choice != null)
{
localStorage["saved_note"] = prompt_choice;
localStorage["year"] = year;
localStorage["month"] = month;
localStorage["day"] = day;
localStorage["hour"] = hour;
localStorage["minute"] = minute;
localStorage["morning"] = AM_or_PM;
document.getElementById("saved_note").innerHTML = "The last time the options were saved was: " + month + "-" + day + "-" + year + " at " + hour + ":" + minute + " " + AM_or_PM + ". With note: " + prompt_choice;
}
// Otherwise, save the date and time and update the options page accordingly.
else
{
localStorage["saved_note"] = "";
localStorage["year"] = year;
localStorage["month"] = month;
localStorage["day"] = day;
localStorage["hour"] = hour;
localStorage["minute"] = minute;
localStorage["morning"] = AM_or_PM;
document.getElementById("saved_note").innerHTML = "The last time the options were saved was: " + month + "-" + day + "-" + year + " at " + hour + ":" + minute + " " + AM_or_PM + ". With no note.";
}
}
function save_and_update_background()
{
// This variable holds the options object in the background page for easy access.
var background = chrome.extension.getBackgroundPage().options;
// These variables hold all the options chosen.
// This is a boolean value that tells if the text filter is on/off.
var text_on = document.getElementById("text_active").children[0].checked;
// This is a string value that holds all the blocked words.
var blocked_words = document.getElementById("blocked_words").value;
// This is a string value that holds all the whitelisted websites.
var whitelisted_websites = document.getElementById("whitelisted_websites").value;
// This is a boolean value. It is true if the user wants to replace the entire sentence containing a blocked word, and false otherwise.
// var replace_sentence = document.getElementById("word_or_sentence").children[2].checked; // error with this feature
// This is a boolean value. True means the user wants to block a paragraph after a specified number of blocked words.
var block_paragraph_checkbox = document.getElementById("block_paragraph_checkbox").checked;
// This is a boolean value. True means the user wants to block the webpage after a specified number of blocked words.
var block_webpage_checkbox = document.getElementById("block_webpage_checkbox").checked;
// This is an integer. It gives the threshold for blocking a paragraph. If the user did not give a number, this will have the value NaN.
var num_for_paragraph = parseInt(document.getElementById("num_for_paragraph").value);
// This is an integer. It gives the threshold for blocking a webpage.
var num_for_webpage = parseInt(document.getElementById("num_for_webpage").value);
// This is a boolean. True means the image filter is on.
var image_on = document.getElementById("image_active").children[0].checked;
// This is a string. It contains all the words used to block images.
var image_blocked_words = document.getElementById("image_blocked_words").value;
// This is a string. It contains the list of whitelisted websites.
var image_whitelisted_websites = document.getElementById("image_whitelisted_websites").value;
// This is a boolean. True means the image scanner is on.
var image_scanner = document.getElementById("image_scanner").children[0].checked;
// This is an integer between 0 and 100. It tells the sensitivity of the image scanner as a percentage.
var scanner_sensitivity = document.getElementById("scanner_sensitivity").children[0].value;
// This element holds the time that the save button was clicked.
var time = new Date();
// Calls the function that stores the date/time as well as updates the page.
store_date_and_note(time);
// Sets the text filter on/off
localStorage["text_on"] = text_on;
background.text_on = text_on;
// Store the blocked words string.
localStorage["blocked_words"] = blocked_words;
background.blocked_words = blocked_words;
// Store the whitelisted websites string.
localStorage["whitelisted_websites"] = whitelisted_websites;
background.whitelisted_websites = whitelisted_websites;
// Store the option to block word or sentence as a boolean.
// localStorage["replace_sentence"] = replace_sentence; // error with this feature
// background.replace_sentence = replace_sentence; // error with this feature
// Store the option to block the paragraph as a boolean.
localStorage["block_paragraph"] = block_paragraph_checkbox;
background.block_paragraph = block_paragraph_checkbox;
if (block_paragraph_checkbox)
{
// If we are going to block the paragraph, store the number of words after which we will block it. It will be stored as an integer.
// We have to make sure that a value was entered into the box. If no value was entered (NaN or not a number) then assign a value of '1'.
if (isNaN(num_for_paragraph))
{
localStorage["num_to_block_paragraph"] = 1;
background.num_for_paragraph = 1;
}
else
{
// We have to make sure that a positive number is entered. If a negative number is entered, then assume that the positive of that number was intended.
// To do this, we simply store the absolute value of whatever number they used.
localStorage["num_to_block_paragraph"] = Math.abs(num_for_paragraph);
background.num_for_paragraph = Math.abs(num_for_paragraph);
}
}
// Store the option to block the webpage as a boolean.
localStorage["block_webpage"] = block_webpage_checkbox;
background.block_webpage = block_webpage_checkbox;
// If we are going to block the webpage, store the number of words after which we will block it. It will be stored as a string.
if (block_webpage_checkbox)
{
// If we are going to block the webpage, store the number of words after which we will block it. It will be stored as an integer.
// We have to make sure that a value was entered into the box. If no value was entered (NaN or not a number) then assign a value of '1'.
if (isNaN(num_for_webpage))
{
localStorage["num_to_block_webpage"] = 1;
background.num_for_webpage = 1;
}
else
{
localStorage["num_to_block_webpage"] = Math.abs(num_for_webpage);
background.num_for_webpage = Math.abs(num_for_webpage);
}
}
// Stores the option for turing the image filter on/off
localStorage["image_on"] = image_on;
background.image_on = image_on;
// Store the blocked words.
localStorage["image_blocked_words"] = image_blocked_words;
background.image_blocked_words = image_blocked_words;
// Store the whitelisted websites.
localStorage["image_whitelisted_websites"] = image_whitelisted_websites;
background.image_whitelisted_websites = image_whitelisted_websites;
// Store if the scanner is on.
localStorage["image_scanner"] = image_scanner;
background.image_scanner = image_scanner;
// Store the scanner sensitivity
localStorage["scanner_sensitivity"] = scanner_sensitivity;
background.scanner_sensitivity = scanner_sensitivity;
}
function save_button()
{
var choice = window.confirm("Are you sure you want to save?");
if (choice == true)
{
save_and_update_background();
}
}
// These are the event handlers for the options page.
// This event is when the slider bar is changed. It will update the html value of the number that shows the value of the slider bar.
document.getElementById("scanner_sensitivity").children[0].addEventListener('change', showValue);
// This event will load the options, populating all the fields, and checking the appropriate radio/checkbox buttons.
document.addEventListener('DOMContentLoaded', load_page);
// This event handles what happens when the save button is clicked.
document.getElementById("save_button").children[0].addEventListener('click', save_button);
<file_sep>==UserScript==
@icon httpsstatic.zhihu.comstaticfavicon.ico
@name 屏蔽知乎热门内容
@author 眼已望穿
@description 屏蔽网页上知乎并不好看的热门内容
@match .zhihu.com
@version 1.0.0
@namespace httpsgreasyfork.orgusers180436
==UserScript==
(function () {
var hideHotContent = function (nodes, flag) {
for (var node of nodes) {
if (node.textContent.indexOf('热门内容') === 0) {
if (flag) {
node.children[0].click()
} else {
node.children[0].click()
node.style.display = 'none';
}
}
}
};
观察者模式
var MutationObserver = window.MutationObserver window.WebKitMutationObserver window.MozMutationObserver;
创建观察者对象
var observer = new MutationObserver(function (mutations) {
for (var mutation of mutations) {
if (mutation.type === 'childList') {
hideHotContent(mutation.addedNodes);
}
}
});
配置观察选项
var config = {
childList true
}
传入目标节点和观察选项
var observedEle = document.getElementsByClassName('TopstoryMain')[0].children[0];
observer.observe(observedEle, config);
初次调用
var items = document.getElementsByClassName('TopstoryItem');
hideHotContent(items, true);
})();<file_sep>
<center><strong><b>适用于个人/家庭的信息管理库分享(侧重信息过滤与内容筛选)</b></strong></center>
---
<a href="https://t.me/dlts0987">
<img border="0" src="https://img.shields.io/badge/channel-Telegram-green.svg" />
</a>
反垃圾与不良信息的工具、技术、经验,防治信息焦虑等信息病,保护精神卫生与身心健康。当信息的主人,而不是奴隶。
> 致力于实现系统、全面、精确的信息过滤与内容筛选。已经集成绝大部分常用过滤,比如对内容过滤、url拦截过滤、精确的部分过滤、图片过滤,知乎豆瓣、简书天涯、贴吧等常用平台的过滤。方便省心,一步到位式过滤筛选。相关配置数据、常用关键词库在相应文件夹,请根据需要自取。
>
> 国内个人或家庭类的内容筛选、过滤防护工具出奇的少而粗浅,更多的内容安全(信息过滤、内容审核、文本分析等)集中在平台端和服务器,主要面向企业用户和媒体。
>
> Information management library for individuals and families (focusing on information filtering and content filtering).Tools, techniques and experience for anti-spam and adverse information, prevention and treatment of information anxiety and other information diseases, and protection of mental health and physical and mental health. Be the master of the message, not the slave.
>
> Hope omni-directional, mutiple level filters. Most commonly used filters have been integrated, such as content filtering, url interception filtering, accurate partial filtering, image filtering, and filtering on popular platforms such as zhihu.com, tianya and tieba.Convenient and convenient, one-step filtering and screening.
***
***\*\#tags \#keywords\**:工具关键词:** 系统精确过滤、内容拦截器,过滤器,Intercept,屏蔽替换隐藏,滤除,killfile,封锁,ProfanityFilter,anti-spam,anti-nsfw,anti-annoy,儿童未成年人保护,安全上网,家长控制,反黄护盾,过程中参考了很多,净网类、过滤拦截、屏蔽替换、内容审核。。
- #GITHUB等项目收集,希望更多志同道合者共同参与补充完善
- #Intelligent information management - anti-spam and bad information-智能信息管理 负面过滤 反垃圾与不良信息
- #Other tools and scripts that may be used-可能用到的一些其他工具和脚本
- #Related plug-in data-相关插件脚本数据
- #ABOUT RSS
- Library (including development-related)-相关领域收藏库(包括开发相关)
相关插件--数据备份包:包含有过滤方案的完整附件。
关键词库:主要集中在“智能信息管理”文件夹。(在外面的是常用词库,全部词库在“2017敏感信息词库大全.zip”中)
相关领域收藏库(包括开发相关):集中了各种”黑科技“、开发版等工具,有兴趣折腾可以试一下。
可能用到的一些其他工具和脚本也附在相关文件夹。正向筛选类请私信我邮箱。
文章地址:https://www.zhihu.com/people/cloud-88-84/posts
[联系邮箱:<EMAIL>](mailto:<EMAIL>)(如果有什么建议/或者在具体实践方面 有问题或困难,欢迎联系)
------
Telegraph文章(需科学上网):
- [前言-04-09-2](https://telegra.ph/前言-04-09-2)
- [前言-04-09](https://telegra.ph/前言-04-09)
- [关于Telegram与Slack-04-09](https://telegra.ph/关于Telegram与Slack-04-09)
- [关于信息输入-04-09](https://telegra.ph/关于信息输入-04-09)
- [个人家庭信息过滤方案-04-09](https://telegra.ph/个人家庭信息过滤方案-04-09)
- [关于小内存手机使用的一些经验以16GiPhone为例大多数可跨平台原理一样安卓可参考-04-09](https://telegra.ph/关于小内存手机使用的一些经验以16GiPhone为例大多可跨平台原理一样安卓可参考-04-09)
- [关于手机的工具本质减轻网络副作用远离舍本逐末加强线下真实回归真实生活的一些想法与实践-04-09](https://telegra.ph/关于手机的工具本质减轻网络副作用远离舍本末加强线下真实回归真实生活的一些想法与实践-04-09)
- [关于科学上网-04-09](https://telegra.ph/关于科学上网-04-09)
- [补充其他需注意需警惕的地方-04-09](https://telegra.ph/补充其他需注意需警惕的地方-04-09)
- [关于附件以及其他分享-04-09](https://telegra.ph/关于附件以及其他分享-04-09)
| Article | https://www.zhihu.com/people/cloud-88-84/posts |
| :------ | :--------------------------------------------- |
| Email | <EMAIL> |
<svg class="octicon octicon-mark-github v-align-middle" height="32" viewBox="0 0 16 16" version="1.1" width="32" aria-hidden="true"><path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z"/></svg>
前言: 大多数人可能都觉得,不想要太高太远的,但其实也没必要成为某些东西的傀儡和牺牲品。 独立自主,做个有心人。关于信息过滤、内容筛选,反三俗反互联网垃圾与不良信息,保护脑袋与心灵的干净,不定期分享一些技术、工具、经验。
由于近期工作学习较忙,暂时只发布信息内容处理、信息过滤部分,未能好好整理。大部分工具都是开源共享的,其中的设置可能并不完全贴合于每个人,可以自行调整。更重要的是,我们要有想去改变的意识、思维和实践方法。
https://www.zhihu.com/people/cloud-88-84/posts
#适合注重内在干净、精神卫生与身心健康的人们。保护精神卫生与身心健康,实现信息过滤与内容筛选,防沉迷,保护未成年儿童、注重内在的有心人以及其他所有可爱的人。
曾见过有太多人年纪轻轻、在学校里就理想破灭、在垃圾与不良信息洪流中耽搁,屈服于一些本来完全可以不受影响的东西;而社会更是个大染缸。很多人跳进去不久就随波逐流、失去本心、麻木不仁、与世浮沉,最后变成行尸走肉,成为某些东西的傀儡和牺牲品。
#可以实现的信息处理流程:层层过滤、减毒、灭活、逆向贴标签,极简聚合等等(当然,一切都是智能化、批量化、自动化的)。反垃圾与不良信息,更主动的上网管理、信息内容管理。
<file_sep>package com.duruo.controller;
import com.duruo.common.Const;
import com.duruo.common.ResponseCode;
import com.duruo.common.ServerResponse;
import com.duruo.dao.DeptMapper;
import com.duruo.po.Dept;
import com.duruo.po.User;
import com.duruo.vo.OpptionsVo;
import net.sf.jsqlparser.expression.operators.arithmetic.Concat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
/**
* Created by @Author tachai
* date 2018/6/14 19:06
*
* @Email <EMAIL>
*/
@RestController
@RequestMapping("/dept/")
public class DeptController {
@Autowired
private DeptMapper deptMapper;
@GetMapping("list.do")
public ServerResponse<List<OpptionsVo>> list(HttpSession session){
User user=(User) session.getAttribute(Const.CURRENT_USER);
if(user!=null){
List<Dept> list=deptMapper.list();
List<OpptionsVo> opptionsVoList = new ArrayList<>();
list.forEach(e->{
OpptionsVo opptionsVo=new OpptionsVo();
opptionsVo.setValue(e.getDeptId());
opptionsVo.setText(e.getDeptName());
opptionsVoList.add(opptionsVo);
});
return ServerResponse.createBySuccess(opptionsVoList,"查询成功");
}else {
return ServerResponse.createByErrorMessage(ResponseCode.NEED_LOGIN.getDesc());
}
}
}
<file_sep>package com.duruo.controller;
import com.duruo.common.MatterCode;
import com.duruo.common.ServerResponse;
import com.duruo.dao.EvidenceFilesMapper;
import com.duruo.po.EvidenceFiles;
import com.duruo.service.IReturnWeiXinService;
import com.duruo.util.PropertiesUtil;
import com.duruo.util.ToWorld;
import com.duruo.util.WeChatParseJson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date;
import java.util.Map;
/**
* Created by @Author tachai
* date 2018/7/4 20:11
*
* @Email <EMAIL>
*/
@Controller
@RequestMapping("/wechat/")
public class ReturnWeiXin {
@Autowired
private EvidenceFilesMapper evidenceFilesMapper;
@Autowired
private IReturnWeiXinService returnWeiXinService;
//酒类文件
@PostMapping("getWeChatIdLiquor.do")
@ResponseBody
public ServerResponse<String> getWeChatId(String weChatId, String matterName) {
return returnWeiXinService.getWeChatId(weChatId,matterName);
}
/**
* 接收微信传过来的卫生许可证的信息
*
* @param weChatId
* @return
*/
@PostMapping("sentPublicPlace.do")
@ResponseBody
public ServerResponse<String> sentPublicPlace(String weChatId, String matterName) {
return returnWeiXinService.sentPublicPlace(weChatId,matterName);
}
/**
* 网页接收上海市企业实行不定时工作制和综合计算工时工作制申请表信息
*
* @param weChatId
* @return
*/
@PostMapping("sentOtherWorkingHoursApply.do")
@ResponseBody
public ServerResponse<String> sentOtherWorkingHoursApply(String weChatId, String matterName) {
return returnWeiXinService.sentOtherWorkingHoursApply(weChatId,matterName);
}
/**
* 微信传上海市法人一证通申请表信息
*/
@PostMapping("sentElectronicDigitalApply.do")
@ResponseBody
public ServerResponse<String> sentElectronicDigitalApply(String weChatId, String matterId) {
return returnWeiXinService.sentElectronicDigitalApply(weChatId,matterId);
}
/**
* 生成微信特种设备(按台套)
* @param weChatId
* @param matterId
* @return
*/
@PostMapping("sentTZSB1.do")
@ResponseBody
public ServerResponse<String> sentTZSB1(String weChatId,String matterId){
return returnWeiXinService.sentTZSB1(weChatId,matterId);
}
/**
* 生成微信特种设备(按单位)
* @param weChatId
* @param matterId
* @return
*/
@PostMapping("sentTZSB2.do")
@ResponseBody
public ServerResponse<String> sentTZSB2(String weChatId,String matterId){
return returnWeiXinService.sentTZSB2(weChatId,matterId);
}
/**
* 生成外来从业人员用工备案登记
* @param weChatId
* @param matterId
* @return
*/
@PostMapping("wlcyryygbadj.do")
@ResponseBody
public ServerResponse<String> recordRegistrationOfMaigrantWorkers(String weChatId,String matterId){
return returnWeiXinService.recordRegistrationOfMaigrantWorkers(weChatId,matterId);
}
/**
* 公共接口接收微信Id去查对话数据 无效代码
* @param weChatId
* @param matterName
* @param type
* @param matterId
* @param deptId
* @param deptName
* @return
*/
@PostMapping("sentDuihuaData.do")
@ResponseBody
public ServerResponse<String> sentData(String weChatId,String matterName,String type,String matterId,String deptId,String deptName) {
if (null != weChatId) {
String res = WeChatParseJson.checkNotNull(weChatId.toString(),"数字证书流程","餐饮流程","食品销售流程");
JsonParser parser = new JsonParser();//创建json解析器
if (res.length()>40) {
JsonObject jsonObject = (JsonObject) parser.parse(res);
JsonObject jsonObject1 = WeChatParseJson.parseWeChatJson(jsonObject);
// 这里要替换成公共卫生许可证
Map<String, String> map = WeChatParseJson.liquorSigle(jsonObject1);
String fileName = weChatId + "-" + matterId + "-" + matterName + "-" + type;
ToWorld.createWord(fileName, MatterCode.ELECTRONIC_DIGITAL, map);
// 要把数据插入到数据库中
EvidenceFiles evidenceFile = new EvidenceFiles();
//保存到数据库
//todo 这里的部门id要换
evidenceFile.setDeptId(Integer.parseInt(deptId));
evidenceFile.setMatterId(Integer.parseInt(matterId));
// MsgId变成weChatId要放传过来的值
evidenceFile.setMsgId(weChatId);
//存路径
String path = PropertiesUtil.getProperty("outWord.Path") + fileName + ".doc";
evidenceFile.setPath(path);
Date date = new Date();
evidenceFile.setCreateTime(date);
evidenceFile.setDeptName(deptName);
evidenceFile.setMatterName(matterName);
evidenceFile.setType(type);
evidenceFilesMapper.insert(evidenceFile);
return ServerResponse.createBySuccessMessage("接收数据成功,已生成Word");
}else {
return ServerResponse.createByErrorMessage("对话返回的值为空");
}
}
return ServerResponse.createByErrorMessage("数据为空,接收数据失败");
}
}
<file_sep>package com.duruo.util;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by @Author tachai
* date 2018/7/17 11:03
*
* @Email <EMAIL>
*/
@Slf4j
public class StringUtils {
/**
* 去除前后指定字符
* @param args 目标字符串
* @param beTrim 要删除的指定字符
* @return 删除之后的字符串
*/
public static String trim(String args,char beTrim){
int st = 0;
int len = args.length();
char[] val = args.toCharArray();
char sbeTrim = beTrim;
while (val[st]<=sbeTrim){
st++;
}
while (val[len-1]<=sbeTrim){
len--;
}
return ((st>0)||(len<args.length()))?args.substring(st,len):args;
}
/**
* @param str
* @return
*/
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
return pattern.matcher(str).matches();
}
/**
* 判断字符串中包含数字是数字有小数点正负号
* @param str
* @return
*/
public static boolean isNum(String str){
Pattern pattern = Pattern.compile("\\+?\\-?[0-9]+.?[0-9]*");
Matcher matcher = pattern.matcher(str);
int i=0;
while (matcher.find()) {
System.out.println(matcher.group());
i++;
}
if(i>1){
return false;
}
return true;
}
public static void main(String[] args) {
// String mm = "是的范德萨发asda+123.asda似懂非懂";
//// Pattern pattern = Pattern.compile("([\\+\\-]?\\d*?\\.?\\d*?)");
// Pattern pattern = Pattern.compile("\\+?\\-?[0-9]+.?[0-9]*");
// Matcher matcher = pattern.matcher(mm);
// int i=0;
// while (matcher.find()) {
// System.out.println(matcher.group());
// i++;
// }
String temp ="04-1月 -17 12.00.00.000000000 上午";
Date mm1 = DateTimeUtil.strToDate(temp.substring(0,9).toString().replace("月", "").replace(" ",""), "dd-MM-yy");
System.out.println(mm1.toString());
}
}
<file_sep>### Server-web02知识库后台
## 基本信息
1. ip 192.168.127.12
1. 端口号:22 80
1. [地址](http://192.168.127.12):http://192.168.127.12
1. 项目地址:/mnt/apache-tomcat-9.0.12/webapps/xuhuiCMS/
<file_sep>package com.duruo.dao;
import com.duruo.po.ProjectBudgetDetail;
import java.util.List;
public interface ProjectBudgetDetailMapper {
int deleteByPrimaryKey(Integer id);
int insert(ProjectBudgetDetail record);
int insertSelective(ProjectBudgetDetail record);
ProjectBudgetDetail selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(ProjectBudgetDetail record);
int updateByPrimaryKey(ProjectBudgetDetail record);
List<ProjectBudgetDetail> selectListBudgetDtailBySN(String sn);
}<file_sep># DrServer-01 服务器
## 基本信息
* ip 172.16.31.10
* 端口号22 80 3306
* [域名](http://webbot.xzfwzx.xuhui.gov.cn):http://webbot.xzfwzx.xuhui.gov.cn
* 所有项目的根路径:/usr/local/tomcat/apache-tomcat-9.0.11/webapps/
### 青创项目及聊天接口(根路径/admin)
1. [青创项目后台](http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/admin):http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/admin
1. [自助机接口](http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/zzj.do):http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/zzj.do
1. [微信接口](http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/webWord.do):http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/webWord.do
1. [一网通接口](http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/zwdt.do):http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/zwdt.do
1. [模型接口](http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/moxing.do):http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/moxing.do
1. [测试接口](http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/test.do):http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/test.do
1. [用户满意度接口](http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/csr.do):http://webbot.xzfwzx.xuhui.gov.cn/wechatroutine/csr.do
### 知识库后台的报表页面
1. [页面地址](http://webbot.xzfwzx.xuhui.gov.cn/bigScreen/index.html):http://webbot.xzfwzx.xuhui.gov.cn/bigScreen/index.html
项目地址是:根路径/bigScreen/ 这里是单独的页面,页面的数据展示接口及其处理是在
/js/bigScreen.js
### 青创人脸识别(根路径/face)
1. [页面地址](http://webbot.xzfwzx.xuhui.gov.cn/face/huoti.html):http://webbot.xzfwzx.xuhui.gov.cn/face/huoti.html
### 青创签名(根路径/qiangming)
1. [页面地址](http://webbot.xzfwzx.xuhui.gov.cn/qiangming/index.html):http://webbot.xzfwzx.xuhui.gov.cn/qiangming/index.html
### 模型聊天页面(根路径/moxing)
1. [页面地址](http://webbot.xzfwzx.xuhui.gov.cn/moxing/index.html):http://webbot.xzfwzx.xuhui.gov.cn/moxing/index.html
注意这个项目是vue项目,如果改动需要修改源代码后打包,同时依赖青创项目的模型接口
### 测试聊天页面(根路径/test)
1. [页面地址](http://webbot.xzfwzx.xuhui.gov.cn/test/index.html):http://webbot.xzfwzx.xuhui.gov.cn/test/index.html
注意这个项目是vue项目,如果改动需要修改源代码后打包,同时依赖青创项目的测试接口
### 一网通(根路径/zwdt)
1. [页面地址](http://webbot.xzfwzx.xuhui.gov.cn/zwdt/index.html):http://webbot.xzfwzx.xuhui.gov.cn/zwdt/index.html
同上
### 自助机(根路径/xhzzj)
1. [页面地址](http://webbot.xzfwzx.xuhui.gov.cn/xhzzj/index.html):http://webbot.xzfwzx.xuhui.gov.cn/xhzzj/index.html
同上
#
以上出现问题都可以重启tomcat :tomcat路径是/usr/local/tomcat/apache-tomcat-9.0.11/bin
<file_sep>package com.duruo.common;
/**
* Created by @Author tachai
* date 2018/9/15 15:16
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
public class DataSourceContextHolder {
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDBType(String dbType) {
contextHolder.set(dbType);
}
public static String getDBType() {
return ((String) contextHolder.get());
}
public static void clearDBType() {
contextHolder.remove();
}
}
<file_sep>zlsh
====
资料审核系统
<file_sep>(function() {
'use strict';
CreateNode();
let CurrentPage = 0;
let inCurrentPage = false;
window.onblur = ()=>{
inCurrentPage = false;
}
window.onfocus = ()=>{
inCurrentPage = true;
}
function getValue(Time){
let arr =[
{
key:"Ãë",
cir:60,
},
{
key:"·Ö",
cir:60,
},
{
key:"ʱ",
cir:24,
},
{
key:"Ìì",
cir:Infinity,
}
];
let word = "";
for(let unit of arr){
//console.log(Time,unit.cir,word);
if(Time>0){
word = unit.key + word;
}
word = Time%unit.cir + " "+word;
Time = parseInt(Time/unit.cir);
if(Time < 1){break};
}
return word;
}
window.onmousemove = ()=>{
inCurrentPage = true;
setInterval(()=>{
if(inCurrentPage){
let Time = ++CurrentPage;
document.querySelector(".wasted_time").innerText = ("- "+getValue(Time));
}
},1000);
window.onmousemove = "";
}
function CreateNode(){
let div=document.createElement("div");
div.setAttribute("class","wasted_time");
let style=document.createElement("style");
div.appendChild(document.createTextNode("- 0 Ãë"));
style.appendChild(document.createTextNode(`
.wasted_time{
font-size:14px;
position:fixed;
display:block;
text-align:center;
cursor:default;
padding:3px 20px;
border-radius:3px;
background-color:rgb(208, 212, 206);
right:17px;
bottom:3px;
z-index:999999;
color:rgb(17, 82, 17);
text-shadow:0 0 0.1px rgba(0,0,0,0.5);
user-select:none;
box-shadow:0 0 7px 0 rgba(18, 80, 18,0.4),0 0 0 1px rgba(0,0,0,0.3);
}
`));
document.querySelector("body").appendChild(div);
document.querySelector("body").appendChild(style);
};
})();<file_sep>package com.example.demo.listener;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionSubscribeEvent;
/**
*
* 功能描述:springboot使用,订阅事件
*
* <p> 创建时间:Jan 4, 2018 </p>
* <p> 贡献者:小D学院, 官网:www.xdclass.net </p>
*
* @author <a href="mailto:<EMAIL>">小D老师</a>
* @since 0.0.1
*/
@Component
public class SubscribeEventListener implements ApplicationListener<SessionSubscribeEvent>{
/**
* 在事件触发的时候调用这个方法
*
* StompHeaderAccessor 简单消息传递协议中处理消息头的基类,
* 通过这个类,可以获取消息类型(例如:发布订阅,建立连接断开连接),会话id等
*
*/
@Override
public void onApplicationEvent(SessionSubscribeEvent event) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
System.out.println("【SubscribeEventListener监听器事件 类型】"+headerAccessor.getCommand().getMessageType());
}
}
<file_sep>/* eslint-disable */
/* base64转blob二进制 */
export const base64ToBlob = (base64Str) => {
const arr = base64Str.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
};
<file_sep>var doughnut, boxes;
var startOfDay = 2*60*60*1000;
function initDoughnut() {
doughnut = $("#doughnutChart").drawDoughnutChart([
{ title: "Cummed", get value() { return cums.length; }, color: "#DB8288" },
{ title: "Prostate Milked", get value() { return milks.length; }, color: "#FEFDD9" },
{ title: "Ruined", get value() { return ruins.length; }, color: "#E3F1F4" }
], {
summaryTitle: 'TOTAL'
});
}
function updateDoughnut() {
doughnut.update();
}
function initBoxes() {
var $ticket = $('#ticket-box');
var $feels = $('#feels-box');
var $ticketPageContainer = $('#ticket-box .ticket-pages');
var $ticketPages = $('#ticket-box .ticket-page');
var ticketPageIndex = 0;
switchBox('feels');
$('.switch, .switchHl').click(function() {
switchBox($(this).data('box'));
});
/*$feels.find('.smileyContainer').click(function() {
stats.addEvent('feeled', Date.now(), $(this).find('[data-feel]').data('feel'));
$(this).parent().animate({opacity: 0}, {always: function() {
$(this).css({visibility: 'hidden'});
if (!$feels.find('.smileyContainer').parent().filter(function() {return $(this).css('visibility') !== 'hidden';}).length) {
switchBox('tickets');
}
}});
});*/
$('#ticket-box .arrowRight').click(function() {
switchPage(ticketPageIndex + 1);
});
$('#ticket-box .arrowLeft').click(function() {
switchPage(ticketPageIndex - 1);
});
function switchBox(box) {
if (box === 'feels') {
/*$feels.find('.smileyContainer').parent().css({opacity: 1, visibility: 'visible'});*/
$ticket.hide();
$feels.show();
} else {
$feels.hide();
$ticket.show();
}
$('.switchHl').addClass('switch').removeClass('switchHl');
$('.switch[data-box="' + box + '"]').addClass('switchHl').removeClass('switch');
}
function switchPage(page) {
ticketPageIndex = (page + $ticketPages.length) % $ticketPages.length;
$ticketPageContainer.animate({scrollLeft: $ticketPageContainer.scrollLeft() + $ticketPages.eq(ticketPageIndex).position().left});
}
}
$(document).on('click', '[data-role]', function() {({
'report-cpr': function() {
showModal('cpr')
},
'report-edge': function() {
showModal('edges');
},
'lock': function() {
showModal('lock-up');
},
'add-edges': function() {
var amount = +$('#modalBackground > .modal[data-form="edges"] input[data-role="amount"]').val();
if (!amount || amount < 0 || amount % 1) {
alert('Please enter a valid amount.');
} else {
for (var i = 0; i < amount; ++i) {
stats.addEvent('edged');
}
hideModal();
}
},
'answer': function() {
var form = $(this).closest('.modal[data-form]').data('form');
if (form === 'cpr') {
stats.addEvent($(this).data('answer'));
hideModal();
}
},
'cancel-modal': function() {
hideModal();
}
}[$(this).data('role')] || function(){}).apply(this, arguments);});
$(document).on('keypress', '#modalBackground input', function(e) {
if (e.which == 13) {
$(e.target).parent().find('[data-type="submit"]').eq(0).click();
}
});
function showModal(form) {
var $form = $('#modalBackground > .modal[data-form="' + form + '"]');
if (!$form.is(':visible')) {
$('#modalBackground > .modal').not($form).hide();
$form.show();
if (form === 'edges') {
$form.find('input[data-role="amount"]').val('');
setTimeout(function() {
$form.find('input[data-role="amount"]').focus();
}, 1);
}
}
$('#modalBackground').show();
}
function hideModal() {
$('#modalBackground').hide();
}<file_sep>/* eslint-disable */
export const removeHeadZero = (val) => {
if (val == 0) {
return 0;
}
return val.replace(/^0+/g, '');
};
<file_sep>package com.example.demo.dao;
import com.example.demo.pojo.FirstLevelRiskDO;
import com.example.demo.pojo.FourthLevelRiskDO;
import com.example.demo.pojo.SecondLevelRiskDO;
import com.example.demo.pojo.ThirdLevelRiskDO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface ThirdLevelRiskDAO extends JpaRepository<ThirdLevelRiskDO,Long> {
@Query("select t.thirdLevelRiskName from ThirdLevelRiskDO t where t.thirdLevelRiskCode=?1")
String findnamebycode(String s);
@Query("select t from ThirdLevelRiskDO t where t.secondLevelRiskCode=?1 order by t.thirdLevelRiskCode asc ")
List<ThirdLevelRiskDO> findBySecondLevelRiskCode(String s);
@Modifying
@Query("delete from ThirdLevelRiskDO t where t.secondLevelRiskCode=?1")
void deleteBySecondLevelRiskCode(String a);
@Modifying
@Query("delete from ThirdLevelRiskDO t where t.firstLevelRiskCode=?1")
void deleteByFirstLevelRiskCode(String a);
void deleteById(int id);
@Query("select t from ThirdLevelRiskDO t where t.thirdLevelRiskCompany=?1 order by t.thirdLevelRiskCode asc")
List<ThirdLevelRiskDO> findBycompany(String company);
ThirdLevelRiskDO findById(int id);
@Query("SELECT t from ThirdLevelRiskDO t where t.firstLevelRiskCode=?1 order by t.thirdLevelRiskCode asc")
List<ThirdLevelRiskDO> findByFirstLevelRiskCode(String fr);
@Modifying
@Query("update ThirdLevelRiskDO set "+
"thirdLevelRiskCode=?1," +
"thirdLevelRiskName=?2," +
"thirdLevelRiskDescription=?3"+
" where id=?4"
)
int update(
String secondLevelRiskCode,
String secondLevelRiskName,
String thirdLevelRiskDescription,
int id
);
@Query("select t from ThirdLevelRiskDO t where t.thirdLevelRiskCode like %?1% or t.thirdLevelRiskName like %?1% or t.thirdLevelRiskDescription like %?1% or t.secondLevelRiskCode like %?1% or t.thirdLevelRiskApplication like %?1% or t.firstLevelRiskCode like %?1% or t.thirdLevelRiskCompany like %?1% or t.thirdLevelRiskDepartment like %?1%")
List<ThirdLevelRiskDO> findAllBykeyLike(String key);
@Query("select max(id) from ThirdLevelRiskDO t ")
int findidmax();
@Query("SELECT t from ThirdLevelRiskDO t where t.thirdLevelRiskCode=?1")
ThirdLevelRiskDO findByThirdLevelRiskCode(String third);
@Query("select t from ThirdLevelRiskDO t where t.thirdLevelRiskName=?1")
ThirdLevelRiskDO findByname(String name);
@Query("select t from ThirdLevelRiskDO t where t.secondLevelRiskCode=?1")
Page<ThirdLevelRiskDO> findByPage(String secondLevelRiskCode, Pageable pageable);
@Query("select t from ThirdLevelRiskDO t where t.firstLevelRiskCode=?1")
Page<ThirdLevelRiskDO> findByPage_first(String firstLevelRiskCode, Pageable pageable);
@Query("select t from ThirdLevelRiskDO t where t.thirdLevelRiskName=?1")
Page<ThirdLevelRiskDO> findByPage_thirdLevelRiskName(String thirdLevelRiskName, Pageable pageable);
Page<ThirdLevelRiskDO> findAll(Pageable pageable);
@Query("select t from ThirdLevelRiskDO t where t.thirdLevelRiskCode=?1")
ThirdLevelRiskDO findBycode(String name);
}
<file_sep>
rabbit-兔兔不良
============
特点
-------------------
* 基于多脏词匹配
* 脏词畸形纠正
* 基于官方大量脏词库,跟上社会动态。。。。
* 自定义脏词
安装
-------------------
下载符合自己机器的版本,运行即可
$ ./rabbit
###支持的参数:
Usage of ./rabbit:
-apikey string
application apikey (default "<KEY>")
-host string
bind address (default "127.0.0.1")
-interval int
auto reload time interval (default 12)
-log string
log file path (default "rabbit.log")
-port int
port the rabbit will listen on (default 9394)
其他默认就好。主要讲下这参数
-interval 设置重载脏词库的时间,单位是小时。默认 12个小时后自动重新加载一次。
#### -apikey 默认是一个测试key,如果要线上正式使用,请联系我拿apikey 加我qq,加时候请说明(拿apikey).qq: 237852571
-------------------
API 测试后台
-------------------
####在线测试后台: http://tutusoft.net 可以先体验下。
目前内置了一个,基本的 脏词 增删改查的 管理后台。
启动rabbit服务后, http://你绑定的IP:端口
在里面你可以测试拦截效果。添加自定义脏词等。 可以通过这些API 开发你自己的 不良信息拦截监控后台。
-------------------
sdk
-------------------
php: https://github.com/nixuehan/rabbit/tree/master/php-sdk
python: https://github.com/nixuehan/rabbit/tree/master/python-sdk
nodejs: 待续
golang: 待续
-------------------
使用所要知道的
-------------------
* 黑名单和灰名单: 分别对应值: 1 和 2 比如: 撸撸射 是黑名单 苍井空是灰名单
这样在拦截后,我会返回一个rate ,你就可以在代码做判断了。到底是拦截呢 还是事后在人工审查。
* 脏词库分两部分: 一份是官方的,一份是你自定义的。 内容过来了会先经过官方的核心脏词库过滤 然后到你自定义的。官方会不断更新脏词库。让你省心。以后我会开放脏词库,让大家来一起更新。
* 畸形纠正: 自定义脏词的时候,会有这个东西。默认的所有数字类型会转成 阿拉伯数字、繁体会转成简体。然后进行判断。但这样就会有误伤。 比如 血案+六四 那么当内容是: 血案呀,今天我被割到手指。在641寝室被割的。 那么这个内容就会被 血案+六四 给命中了。 所以 血案+六四 这个脏词添加的时候。 畸形纠正 我们选择值 2 进行关闭。 那么 六四在底层不会被转换成64. 那误伤率就大大减少了。
* 脏词类型: 违法、色情、政治敏感等。。。我定义了9个类型。您自己看着办。
* 脏词组合: 脏词是可以组合的。比如: 天猫招工+空闲+结算 目前最多匹配3个。 还支持几个内置联系类型: qq phone url 比如: 信用卡套现:phone 、 轻松赚钱+曰结:qq 等
###记得重载脏词
修改完脏词后,记得进入 http://你绑定的IP:端口号 里面进行 脏词重新载入。否则不生效的哦。当然也支持 curl 操作
--------
API文档
--------
有了API,你就可以很方便的把服务接入你自己的项目了
###过滤API
POST /filter
参数: contents=蒙汗药
返回格式:json
具体返回值说明:
{"Category":"9","CategoryName":"违法信息","Hit":"1","Id":"38509","Rate":"2","Word":"蒙汗药"}
```javascript
Hit: 是否命中, 0 否 1 是
Category: 脏词的分类id
CategoryName: 脏词所属分类名
Id: 脏词ID,利用这个ID就可以编辑脏词
Rate: 黑名单或白名单,1 黑名单 2灰名单(自己review内容)
Word: 脏词
```
--------
###过滤色情图片
####目前是根据图片的 人类肤色 比例来进行打分,聊胜于无吧。-_-!别跟我说黑人XXOO无法识别。建议配合人工审核后台使用
POST /porn
参数: file=/data/thumb/xxoo.jpg 或 file = http://sd.com/xxoo.jpg
返回格式:json
具体返回值说明:
{"score":86}
```javascript
score: 建议:65 - 85判断为性感 85以上为色情
```
###添加脏词
POST /create
参数:
category: 分类id. 可通过分类查询接口了解
word: 脏词
rate: 黑名单或灰名单. 1黑名单 2灰名单
correct: 是否支持畸形纠正. 1 是 2否
返回格式:json
具体返回值说明: { "success": 1 }
--------
###删除脏词
DELETE /delete
参数: id=1
返回格式:json
具体返回值说明: { "success": 1 }
--------
###修改脏词
PUT /revise
参数:
id: 脏词id.主键
category: 分类id.请通过分类查询接口了解
word: 脏词
rate: 黑名单或灰名单. 1黑名单 2灰名单
correct: 是否支持畸形纠正. 1 是 2 否
返回格式:json
具体返回值说明: { "success": 1 }
--------
###脏词查询
GET /query
参数:
id: 脏词id.主键
category: 分类id.请通过分类查询接口了解
word: 脏词
rate: 黑名单或灰名单. 1黑名单 2灰名单
correct: 是否支持畸形纠正. 1 是 2否
start: 记录开始数(分页使用)
end: 记录结束数(分页使用)
返回格式:json
具体返回值说明: [ { "Id": 9, "Category": 2, "CategoryName": "低俗信息", "Word": "我做你做不做", "Correct": 1, "Rate": 1 }, { "Id": 8, "Category": 2, "CategoryName": "低俗信息", "Word": "发问了你", "Correct": 1, "Rate": 1 } ]
```javascript
Category: 脏词的分类id
CategoryName: 脏词所属分类名
Id: 脏词ID,利用这个ID就可以编辑脏词
Rate: 黑名单或白名单,1 黑名单 2灰名单(自己review内容)
Word: 脏词
Correct: 是否畸形纠正
```
--------
###脏词分类
GET /category
参数:无
返回格式:json
[{"Category_id":1,"Category_name":"个性化"},{"Category_id":2,"Category_name":"低俗信息"},{"Category_id":3,"Category_name":"灌水信息"},{"Category_id":5,"Category_name":"政治敏感"},{"Category_id":6,"Category_name":"违约广告"},{"Category_id":7,"Category_name":"跨站追杀"},{"Category_id":8,"Category_name":"色情信息"},{"Category_id":9,"Category_name":"违法信息"},{"Category_id":10,"Category_name":"垃圾广告"}]
--------
###脏词重载
GET /reload
说明:添加或修改脏词后,重载才会生效
返回格式:json
具体返回值说明: { "success": 1 }
----------
压测数据
----------
硬件配置: 阿里云主机 CPU: 1核 内存: 1024 MB
压测的数据如下。内容共计:371个字数、817个字符:
```javascript
wrk.method = "POST"
wrk.body = "contents=原来,7日中午,张某夫妇带着儿子张峰(化名,现年2岁半)和女儿张娟(化名,现年1岁),来到位于银海区银滩镇龙潭村委会的姐夫刘某家吃饭。吃饭过程中,张峰和张娟被放在刘某房间玩耍,调皮的张峰在床头的夹层里翻出一包东西,他以为是零食,顺手抓了几颗放进嘴里。一旁的张娟见哥哥吃东西,她也爬过来拿着往嘴里塞两人的举动引起张某夫妇的注意。等走近一看,发现孩子们吃的东西竟是老鼠药。吓坏了的张某赶紧抱起儿子张峰,并从其嘴里抠出两粒老鼠药。“快送医院!”目睹眼前这一幕后,刘某急忙大喊。回过神来的夫妇,立即抱起两个孩子冲出门外,并拨打了120急救电话其间,由于担心路上被堵,刘某的妻子建议先把孩子送到附近派出所,再通过民警送往医医。当天下午,经过约一小时的急救和洗胃,张峰和张娟脱离了生命危险。随后,两人被安排在儿科儿童病房进行观察。8日下午,两人的各项身体指标,都已恢复正常医生提醒家长,蒙汗药是一种烈性毒药,千万不要放在小孩够得到的地方"
wrk.headers["Content-Type"] = "application/form-data"
```
跑下
```javascript
./wrk -t2 -c100 -d60s --script=../post.lua http://10.161.171.74:9394/filter
```
两线程 100个连接 60秒 数据如下:
```javascript
Running 1m test @ http://10.16.17.74:9394/filter
2 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 12.82ms 10.94ms 90.37ms 88.89%
Req/Sec 4.63k 1.06k 6.85k 63.33%
552582 requests in 1.00m, 70.62MB read
Requests/sec: 9207.21
Transfer/sec: 1.18MB
```
两线程 3000个连接 60秒 数据如下:
```javascript
Running 30s test @ http://10.16.17.74:9394/filter
2 threads and 3000 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 314.93ms 97.50ms 1.82s 84.51%
Req/Sec 4.48k 1.60k 7.33k 78.82%
266017 requests in 30.04s, 33.99MB read
Requests/sec: 8854.35
Transfer/sec: 1.13MB
```
两线程 4000个连接 60秒 开始出现 timeout了...阿里云服务器也就如此了。数据如下:
```javascript
Running 30s test @ http://10.161.171.74:9394/filter
2 threads and 4000 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 375.02ms 133.17ms 1.95s 78.31%
Req/Sec 4.22k 1.68k 8.15k 69.59%
249464 requests in 30.10s, 31.88MB read
Socket errors: connect 0, read 871, write 0, timeout 136
Requests/sec: 8288.02
Transfer/sec: 1.06MB
```
换我的MAC 压测下。配置如下:Intel Core i5 1.6 GHz .内存 8 GB.
```javascript
wrk -t8 -c100 -d60s --script=./post.lua http://127.0.0.1:9394/filter
```
数据如下:
```javascript
Running 1m test @ http://127.0.0.1:9394/filter
8 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 7.76ms 12.46ms 245.15ms 90.71%
Req/Sec 2.62k 637.00 12.44k 79.64%
1253342 requests in 1.00m, 198.42MB read
Requests/sec: 20853.38
Transfer/sec: 3.30MB
```
依然是我的MAC 测试下长内容性能和多脏词匹配。内容:4420个字数、9916个字符。脏词:网络+兼职+日入:qq
```javascript
wrk -t8 -c100 -d60s --script=./post.lua http://127.0.0.1:9394/filter
```
数据如下:
```javascript
Running 1m test @ http://127.0.0.1:9394/filter
8 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 13.27ms 16.38ms 219.79ms 87.87%
Req/Sec 1.33k 235.26 4.59k 73.11%
636879 requests in 1.00m, 100.82MB read
Requests/sec: 10596.88
Transfer/sec: 1.68MB
```
----------
未来计划?
----------
在写一个完善的监控后台,方便管理存在的脏词和查看已被拦截的内容
----------
遇到问题了?
----------
加群: 243663452 找我
<file_sep>推荐文章:
[如何搭建属于自己的 RSS 服务,高效精准获取信息#内容过滤](https://sspai.com/post/41302#2.3%20%E6%96%87%E7%AB%A0%E8%BF%87%E6%BB%A4)
[docker快速部署](https://odcn.top/2019/03/18/2940/docker%E7%9A%84tiny-tiny-rss%E5%AE%B9%E5%99%A8%E9%95%9C%E5%83%8F%E9%83%A8%E7%BD%B2%E6%96%B9%E6%B3%95%EF%BC%8C%E4%B8%80%E6%9D%A1docker-compose%E5%91%BD%E4%BB%A4%E8%A7%A3%E5%86%B3%E9%97%AE%E9%A2%98/)
<file_sep>package com.IOPdemo.sysmanage.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.IOPdemo.sysmanage.util.Upload;
/**
* 图片上传action
* @author Administrator
*
*/
public class UploadAction extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String fileName = Upload.upload(request, response);
HttpSession session = request.getSession();
session.setAttribute("fileName", "upload/"+fileName);
response.sendRedirect("index.jsp");
}
}
<file_sep>package com.duruo.dto;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/8/14 15:34
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
@Data
public class Query {
private String query;
private String userId;
}
<file_sep>package com.example.demo.dao;
import com.example.demo.pojo.UserDO;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Transactional
public interface UserDAO extends JpaRepository<UserDO,Long> {
void deleteById(int id);
List<UserDO> findByDepartment(String d);
UserDO getById(int id);
List<UserDO> findById(int id);
Page<UserDO> findByPermission(int permission, Pageable pageable);
@Query("select u from UserDO u where u.menuRole = ?1 and u.department = ?2")
List<UserDO> findreviewerById(String position,String department);
@Modifying
@Query("update UserDO set " +
"username=?1," +
"password=?2," +
"userEmail=?3," +
"mobilePhone=?4,"+
"userAddress=?5,"+
"userMessage=?6"+
" where id=?7"
)
int updateUser(
String username,
String password,
String userEmail,
String mobilePhone,
String userAddress,
String userMessage,
int id
);
@Modifying
@Query("update UserDO set " +
"username=?1," +
"password=?2," +
"workerName=?3," +
"workNumber=?4"+
" where id=?5"
)
int updateUserbydepartment(
String username,
String password,
String workerName,
String workNumber,
int id
);
List<UserDO> findAll(Specification specification);
@Query("select ul from UserDO ul where ul.username=:username and ul.password=:password")
UserDO findOne(@Param("username") String username, @Param("password") String password);
@Query("select u from UserDO u where u.userCompany=?1 order by u.workNumber desc ")
List<UserDO> findbycompany(String d);
@Query("select u from UserDO u where u.userCompany like %?1% order by u.workNumber desc ")
List<UserDO> findbycompanylike(String d);
@Query("select u from UserDO u where u.workerName like %?1% and u.userCompany=?2 order by u.workNumber desc ")
List<UserDO> findbynamelike(String d,String c);
@Query("select u from UserDO u where u.department like %?1% and u.userCompany=?2 order by u.workNumber desc ")
List<UserDO> findbydepartmentlike(String d,String c);
@Query("select u from UserDO u where u.mobilePhone like %?1% and u.userCompany=?2 order by u.workNumber desc ")
List<UserDO> findbymobilePhonelike(String d,String c);
}
<file_sep>var eventArr = ['contextmenu', 'dragstart', 'mouseup', 'copy', 'beforecopy', 'selectstart', 'select', 'keydown'];
function runScript(window) {
var document = window["document"],
$ = window["jQuery"],
unbind = function(ele) {
eventArr.forEach(function(evt) {
ele['on' + evt] = null;
if ($) {
$(ele).unbind(evt);
}
try {
if (/frame/i.test(ele.tagName)) {
runScript(ele.contentWindow);
}
} catch (err) {}
});
};
[window, document].forEach(unbind);
for (var i = 0, all = document.all, len = all.length; i < len; i++) {
var ele = all[i];
if (ele && ele.nodeType === 1) {
unbind(ele);
}
}
}
window.onload = function(){
runScript(window);
};
window.onhashchange = function(){
setTimeout(
function(){
runScript(window);
},400);
};<file_sep>$objc("NSBundle").$bundleWithPath("/System/Library/PrivateFrameworks/DocumentCamera.framework").$load();
$define({
type: "ICDocCamExtractedDocumentViewController",
events: {
"viewDidLoad": () => {
self.$ORIGviewDidLoad();
let tintColor = $color("tint").runtimeValue();
self.$recropButtonItem().$setTintColor(tintColor);
self.$compactFilterButtonItem().$setTintColor(tintColor);
self.$rotateButtonItem().$setTintColor(tintColor);
self.$trashButtonItem().$setTintColor(tintColor);
}
}
});
$define({
type: "DocCamVC: DCDocumentCameraViewController_InProcess",
events: {
"documentCameraControllerDidCancel": sender => dismiss(sender),
"documentCameraController:didFinishWithDocInfoCollection:imageCache:warnUser:": (sender, info, cache) => {
let document = $objc("DCScannedDocument").$alloc().$initWithDocInfoCollection_imageCache(info, cache);
let count = document.$docInfos().$count();
let images = [];
for (let idx=0; idx<count; ++idx) {
let image = document.$imageOfPageAtIndex(idx);
images.push(image.rawValue());
}
dismiss(sender, () => $share.sheet(images));
}
}
});
function dismiss(vc, blk) {
let handler = blk ? $block("void", blk) : null;
vc.$dismissViewControllerAnimated_completion(true, handler);
}
function showCamera() {
let camVC = $objc("DocCamVC").$alloc().$initWithDelegate(null);
let rootVC = $ui.controller.runtimeValue();
rootVC.$presentViewController_animated_completion(camVC, true, null);
}
showCamera();
<file_sep>package com.duruo.po;
public class ProjectBudgetDetail {
private Integer id;
private String sn;
private String enterpriseId;
private String decomposeDetailed;
private String specialFunds;
private String selfFinancing;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn == null ? null : sn.trim();
}
public String getEnterpriseId() {
return enterpriseId;
}
public void setEnterpriseId(String enterpriseId) {
this.enterpriseId = enterpriseId == null ? null : enterpriseId.trim();
}
public String getDecomposeDetailed() {
return decomposeDetailed;
}
public void setDecomposeDetailed(String decomposeDetailed) {
this.decomposeDetailed = decomposeDetailed == null ? null : decomposeDetailed.trim();
}
public String getSpecialFunds() {
return specialFunds;
}
public void setSpecialFunds(String specialFunds) {
this.specialFunds = specialFunds == null ? null : specialFunds.trim();
}
public String getSelfFinancing() {
return selfFinancing;
}
public void setSelfFinancing(String selfFinancing) {
this.selfFinancing = selfFinancing == null ? null : selfFinancing.trim();
}
}<file_sep>/* eslint-disable */
import Vue from 'vue';
import { Notification } from 'element-ui';
import { delayForceLogout } from 'src/config/delayForceLogout';
import { http } from './ajaxConfig';
import { clearAllCookie } from './cookie';
import { storage } from './storageConfig';
/*
* vm: vm实例;
* pararms: '请求参数' [Obj]; url: [Str];method: 'get'[Str]
* success: 'success(res) cb'[Fn]; error: 'error(err) cb'[Fn];
* handle: '实现的功能(用于notify Str)' [Str]
* before: cb[Fn]; after: cb[Fn]
* noSuccessNotify: [Boolean] 不启用成功提示flag
* */
export const notifyAjaxWithoutAction = ({ vm, param, url, method, handle,
noSuccessNotify=false, silence=false,
success, error, before, after, }) => {
if (before) { before() }
http[method](url, param)
.then((res) => {
if (!noSuccessNotify) {
vm.$notify.success({
message: ('成功' + handle),
duration: 1000,
});
}
if (success) { success(res) }
if (after) { after() }
})
.catch((err) => {
console.log(err);
if (after) { after() }
if (error) { error(err) }
if (silence) return;
errorHandler(err);
});
};
export const errorHandler = (err) => {
const forceLogout = () => {
clearAllCookie();
storage.clear();
window.location.href = '#/login';
};
if (err.status === 520) {
Notification.error({
title: `系统服务异常 [${err.status}]`,
message: err.body && err.body.errorMsg ? err.body.errorMsg : ''
});
if (err.body.errorCode === '11004' ||
err.body.errorCode === '11005' ||
err.body.errorCode === '11019' ||
err.body.errorCode === '11015' ||
err.body.errorCode === '11018' ||
err.body.errorCode === '11022' ||
err.body.errorCode === '11024') {
delayForceLogout(forceLogout);
}
} else if (err.status === 500) {
Notification.error({
title: `系统服务异常 [${err.status}]`,
message: err.body && err.body.errorMsg ? err.body.errorMsg : ''
});
} else {
Notification.error({
title: '网络服务异常',
message: '返回状态:' + err.status
});
}
};
<file_sep><!doctype html>
<!--
This is the options page for the extension
Author: <NAME>
Date Created: 10/22/2012
Date Updated: 11/5/2012
-->
<html>
<head>
<title> Options</title>
</head>
<body>
<!-- Container div to ensure that anything after the heading can use the leftmost space of the page. -->
<div id = "header">
<!-- div for the logo image. -->
<div id = "logo" style = "padding: 10px; float: left;">
<!-- The link to the image. It must remain a constant size so that the div that contains it remains constant, so that the div containing the title will align with the bottom of the image. -->
<img src = "joseph'slogo.png" width = "150" height = "150">
</div>
<!-- div for the title. It will be to the left of the logo, and aligned with the bottom of the logo. -->
<div id ="title" style ="padding-left: 20px; float: left; padding-top: 60px;">
<h1 style = "font-size: 60px; font-weight: bold; font-family: 'Book Antiqua', 'Engravers MT', 'Times New Roman';"> Web Cleaner Options </h1>
</div>
<!-- This next line ensures that the 'header' div will contain both 'logo' and 'title', and allow for other divs to fall beneath the header. -->
<div style = "clear: both;"></div>
</div> <!-- End of header div -->
<!-- The container div for all the text filter options. -->
<div id = "text_options" style = "padding: 30px; float: left; width: 600px; vertical-align: top;">
<h1> Text Filter </h1>
<!-- The radio button form for turning the text filter on/off -->
<form id = "text_active">
<input type = "radio" name = "text_on" value = "true">On
<input type = "radio" name = "text_on" value = "false">Off
</form>
<br>
<p> The Text Filter works by searching for the words listed below in within the document. When it finds one of these words, it will replace it with '*'s.
Also, the filter will 'expand' the words, blocking a word if any part of that word appears in the list below. In other words, if you listed 'both' as a blocked word,
then the word 'bother' will also be blocked, since the word 'both' appears in 'bother'. Any websites entered into the 'Whitelisted Websites' box will not be filtered.</p>
<!-- Container div for the two input boxes, so that they can go side-by-side and then other options can
come below them. The vertical alignment is top so that the two boxes are at the same height.-->
<div id = "text_boxes" style = "vertical-align: top;">
<!-- The div for the blocked words textbox. It is listed as inline-block so we can use vertical-align. -->
<div id = "word_box" style = "display: inline-block; float: left; vertical-align: top;">
<h2>Blocked Words</h2>
<!-- This will not have any words hard-coded into it, but will be dynamically filled with a JavaScript Function from the settings in localstorage.
It is the text area where users put words that they want scrubbed out.-->
<textarea id = "blocked_words" rows = "8" columns = "60" style = "resize: none;">
</textarea>
</div> <!-- End of word_box div -->
<!-- The div for the whitelisted websites box. It must have the same styling as the 'word_box' div, except that it has extra left padding to separate it from the 'word_box' div. -->
<div id = "website_box" style = "padding-left: 50px; display: inline-block; float: left; vertical-align: top;">
<h2>Whitelisted Websites</h2>
<!-- This is the text box where users can list the websites that they don't want scrubbed. -->
<textarea id = "whitelisted_websites" rows = "8" columns = "60" style = "resize: none;"></textarea>
</div>
<!-- This is necessary to ensure that the wrapper div actually encompasses both box divs. -->
<div style = "clear: both;"></div>
<p>When entering words/websites into the above boxes, please only place one word/website per line with no punctuation. Also, please use the following format for websites: www.foxnews.com</p>
</div> <!-- End of text_boxes wrapper div. -->
<!--
<!-- The container div for the radio button form that controls wether or not the word or the sentence is replaced.
<div id = "replace_word/sentence/paragraph">
<!-- This form contains 2 radio buttons that allows the user to choose between replacing the entire word or replacing the sentence containing the word.
<form id = "word_or_sentence">
<input type = "radio" name = "WordOrSentence" value = "word"> Only replace the blocked word. <br>
<input type = "radio" name = "WordOrSentence" value = "sentence"> Replace the entire sentence containing the blocked word.
</form> <!-- this ends the word_or_sentence form
-->
<br>
<!-- This form contains 2 checkboxes to allow the user to replace the entire page after a certain number of blocked words, or block the entire page after a certain number of blocked words. -->
<form id = "block_page/paragraph" style = "display: inline;">
<input type = "checkbox" id = "block_paragraph_checkbox" name = "block_paragraph"> Replace all paragraphs containing <input type = "text" id = "num_for_paragraph" name = "number_for_paragraph" maxlength = "3" size = "2" style = "text-align: right; display: inline;">or more instances of blocked words. <br>
<input type = "checkbox" id = "block_webpage_checkbox" name = "block_webpage"> Block the webpage after finding <input type = "text" id = "num_for_webpage" name = "number_for_webpage" maxlength = "3" size = "2" style = "text-align: right; display: inline;">or more instances of blocked words on the webpage.
</form> <!-- this ends the block_page/paragraph form -->
</div> <!-- End of replace_word/sentence div. -->
</div><!-- End of text_options div. -->
<!-- The container div for all the image filter options. It will appear to the left of the text options. -->
<div id = "image_options" style = "margin-left: 100px; padding: 30px; float: left; vertical-align:top; width: 600px;">
<h1> Image Filter </h1>
<!-- The radio button form for turning the image filter on/off -->
<form id = "image_active">
<input type = "radio" name = "image_on" value = "true">On
<input type = "radio" name = "image_on" value = "false">Off
</form>
<br>
<p> The Image Filter works by searching an image name and search tags for any of the words listed below in the 'Words to Block Images On' box.
If a match is found, then the image will be blocked. As with the Text Filter, the words are expanded, so if a listed word appears as part of a word that
in the image name or tag, then the image will still be blocked. Any websites entered into the 'Whitelisted Websites' box will not be filtered. </p>
<!-- The div that contains the two text areas used to specify blocked words and whitelisted websites. -->
<div id = "image_text_boxes" style = "vertical-align: top;">
<!-- The div that holds the box that contains the words to block images on. -->
<div id = "image_word_box" style = "display: inline-block; float: left; vertical-align: top;">
<h2>Words to Block Images On</h2>
<textarea id = "image_blocked_words" rows = "8" columns = "60" style = "resize: none;">
</textarea>
</div> <!-- The end of image_word_box div -->
<!-- The div that holds the box containing the whitelisted websites -->
<div id = "image_website_box" style = "padding-left: 50px; display: inline-block; float: left; vertical-align: top;">
<h2>Whitelisted Websites</h2>
<textarea id = "image_whitelisted_websites" rows = "8" columns = "60" style = "resize: none;"></textarea>
</div> <!-- the end of image_website_box div -->
<!-- This is used to ensure that the container div wraps around the two floating divs -->
<div style = "clear: both;"></div>
<p>When entering words/websites into the above boxes, please only place one word/website per line with no punctuation. Also, please use the following format for websites: www.foxnews.com</p>
</div> <!-- The end of the image_text_boxes div -->
<p> The Image Scanner is an additional option to the Image Filter. When turned on, if an image passes the Image Filter, it will be passed
into a scanner, where the number of skin pixels will be detected. Then, the number of skin pixels will be compared to the total number of pixels in the image
with the result being a percentage. If this percentage is above the percentage specified by the slider bar, then the image will be blocked.
<br>
<br>
NOTE: Due to the nature of this scanner, when it is working properly it may block close-up facial images.
</p>
<!-- The form that holds the checkbox indicating if the image scanner is on or off. -->
<form id = "image_scanner">
<input type = "checkbox" name = "image_scanner_on" value = "true"> Use Image Scanner
</form>
<br>
<!-- The slider bar for the sensitivity of the image scanner -->
<form id = "scanner_sensitivity">
<input type = "range" min = "0" max = "100" step = "1">
<span id = "range2"></span>
</form>
<br>
<br>
<br>
<br>
<br>
<div id = "buttons" style = "float: right;">
<p id = "saved_note" style = "display: inline;"></p>
<form id = "save_button" style = "display: inline;">
<input type = "button" value = "Save">
</form>
</div> <!-- End of buttons div -->
</div> <!-- The end of the image_options div -->
<script src = "options.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta http-equiv="x-ua-compatible" content="ie=edge"/>
<title>AdminLTE 3 | Dashboard 2</title>
<!-- Font Awesome Icons -->
<link rel="stylesheet" href="/font-awesome/css/font-awesome.min.css"/>
<!-- Theme style -->
<link rel="stylesheet" href="/datatables/dataTables.bootstrap4.min.css"/>
<link rel="stylesheet" href="/css/adminlte.min.css"/>
<link rel="stylesheet" href="https://3vshej.cn/AdminLTE/AdminLTE-2.4/dist/css/AdminLTE.min.css"/>
<!-- Google Font: Source Sans Pro -->
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet"/>
<style>
.operation{
padding-top: 200px;
}
.form-control {
display: block;
width: 100%;
padding: .375rem .75rem;
font-size: 1rem;
line-height: 1.5;
color: #495057;
background-color: #fff;
background-clip: padding-box;
border: 1px solid #ced4da;
border-radius: .25rem;
box-shadow: inset 0 0 0 transparent;
transition: border-color .15s ease-in-out,box-shadow .15s ease-in-out;
}
.table td, .table th {
padding: 0;
vertical-align: top;
border-top: 1px solid #dee2e6;
}
.operation_origial_information{
width: 400px;
}
.table td, .table th{
vertical-align: middle;
}
</style>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
<!-- Navbar -->
<div th:include="top::topbar"></div>
<!-- /.navbar -->
<!-- Main Sidebar Container -->
<aside class="main-sidebar sidebar-dark-primary elevation-4" style="height: 100%">
<!-- Brand Logo -->
<!-- Sidebar -->
<div class="sidebar page-header-image page-header" th:include="sidebar::sidebar"></div>
<!-- /.sidebar -->
</aside>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h5>集团专题</h5>
</div><!-- /.col -->
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item"><a href="#">企业门户体系</a></li>
<li class="breadcrumb-item active">新闻热点</li>
<li class="breadcrumb-item active">集团专题</li>
</ol>
</div><!-- /.col -->
</div><!-- /.row -->
</div><!-- /.container-fluid -->
</div>
<!-- /.content-header -->
<!-- Main content -->
<section class="content">
<div class="container-fluid">
<!-- /.slider -->
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-header">
</div>
<!-- /.card-header -->
<div class="card-body">
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class=""></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1" class=""></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2" class="active"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item">
<img class="d-block w-100" src="http://pic1.win4000.com/wallpaper/2018-05-23/5b052c567746b.jpg" alt="First slide"/>
</div>
<div class="carousel-item active carousel-item-left">
<img class="d-block w-100" src="http://pic1.win4000.com/wallpaper/2018-05-23/5b052c5761ddc.jpg" alt="Second slide"/>
</div>
<div class="carousel-item carousel-item-next carousel-item-left">
<img class="d-block w-100" src="http://pic1.win4000.com/wallpaper/2018-05-23/5b052c5828fa0.jpg" alt="Third slide"/>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
</div>
<div class="row">
<div class="col-12 m-t-30">
<h4 class="m-b-0"></h4>
<p class="text-muted m-t-0 font-12">新闻热点</p>
<div class="card-deck">
<div class="card">
<img class="card-img-top img-responsive" src="http://www.cppinet.com/ChinaWeb/kindeditor/attached/image/20170406/20170406162318_265.png" alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">习近平主席出访芬兰,见证中芬60亿浆纸项目签约</h4>
<p class="card-text">当地时间4月5日,就在国家主席习近平对芬兰进行国事访问期间,国家开发银行于芬兰经济事务部分别与芬兰贸易投资旅游总署(Finpro)、阳光凯迪(芬兰)有限公司、中工国际及芬兰北方工业公司签署三个战略合作协议,项目总金额总计超过20亿欧元。
其中,中工国际工程股份有限公司罗艳董事长与芬兰北方生化公司黑肯·尼瓦拉主席在首都赫尔辛基签署了芬兰生物炼化厂(纸浆厂)项目商务合同。合同金额为8亿欧元,工期为30个月。根据该合同,中工国际将在芬兰拉普兰德地区凯米哈维市建设一座年产40万吨的生物炼化厂(纸浆厂),提供包括设计、供货、土建、安装、调试和人员培训等服务。这是中工国际明确将浆纸领域作为公司“三相联动”战略的发展方向之后签署的第一个浆纸领域商务合同。项目建设工期30个月,开车及性能测试时间12个月。
芬兰Boreal Bioref生物炼化厂(纸浆厂)项目交易对方为芬兰北方生化公司(Boreal Bioref Ltd.),注册地址为芬兰凯米哈维市库曼涅米街2号(Kuumaniemenkatu 2, 98100 Kemij?rvi, Finland),法定代表人为<NAME>,该公司是凯米哈维市政府发起设立的林业项目开发公司。
芬兰Boreal Bioref生物炼化厂(纸浆厂)项目合同金额为8亿欧元,约合58.62亿元人民币。这次林浆项目成为中工国际“三相联动”战略的成功示范,北欧针叶浆是国内稀缺的重要资源,通过芬兰项目可以帮助中工进军浆纸产业,长期持续发展更添动力。本月初,中工国际出资3750欧元与瑞典林浆产业公司共同发起设立林浆产业基金管理公司,并出资不超过1亿美元发起设立林浆产业投资基金,产业基金以纸浆厂项目为核心,适当考虑向浆纸产业链上下游延伸。
这是习近平担任国家主席后,历次出访中,第三次签约制浆造纸行业的国际协议</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
<div class="card">
<img class="card-img-top img-responsive" src="http://img95.699pic.com/photo/50059/0689.jpg_wh300.jpg!/fh/300" alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">2018中国国际造纸创新发展论坛及2018国际造纸技术报告会将于8月底在上海举行</h4>
<p class="card-text">为了促进我国造纸工业的发展,更好地展示造纸行业的科技发展成果,为造纸及相关行业搭建交流、沟通的平台,2018中国国际造纸科技展览会及会议将于2018年8月29—31日在上海世博展览馆举行。同期举办2018中国国际造纸科技展览会、2018中国国际造纸创新发展论坛、2018国际造纸技术报告会和企业技术交流会等活动。会议有关事项如下:
会议内容
(一)2018中国国际造纸创新发展论坛
2018年是中国改革开放四十周年,科技创新在中国经济发展过程中起到了至关重要的作用。创新是引领发展的第一动力,是建设现代化经济体系的战略支撑。党的十九大报告明确指出,加快建设创新型国家,加强国家创新体系建设,强化战略科技力量。当前,中国正在实施创新驱动发展战略,以应对复杂发展环境变化、提高中国核心竞争力,加快转变经济发展方式、保持我国经济持续健康发展。创新的本质是进化,创新的目的是发展。为此,由中国造纸学会、中国造纸协会、中国制浆造纸研究院有限公司共同主办的“2018中国国际造纸创新发展论坛”以“创新赋能生态•进化重塑未来”为主题,针对造纸行业的创新发展、生态构建、进化模式、未来趋势、前沿探索等热点话题,搭建以企业为主体、市场为导向的沟通合作平台。
主要议题
主旨演讲
• 政策解读:造纸产业政策规划及2035材料强国
战略解读
报告发布
• 2018中国造纸产业竞争力报告
• 2018中国造纸化学品产业发展报告
主题演讲
• 科技创新:科技创新驱动传统工业重获新动能
• 发展创新:全局战略思维决定企业发展路径
• 合作创新:芬兰浆纸领域投资政策和投资机会
• 技术创新: 北美浆纸行业现状对中国的影响及发展趋势和机会
• 市场分析:全球造纸原料动态与分析——也谈废纸
专题演讲
• 模式创新:打通产业生态链 再造服务新模式
• 装备创新:原料结构变化下的设备选型与配置
• 环保创新: 废纸制浆污泥全新解决方案 促进废纸纤维充分利用
高端对话
• 对话主题:创新生态进化论 迎接产业新周期
</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
<div class="card">
<img class="card-img-top img-responsive" src="http://seopic.699pic.com/photo/50029/6409.jpg_wh1200.jpg" alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">新时代下的新机遇与新挑战,2018中国纸业高层峰会在鞍山成功举办</h4>
<p class="card-text">会议正式开始后,中国造纸协会秘书长钱毅做了《纸业新时代面临的形势、机遇与挑战》的主旨报告。钱秘书长指出:中国造纸行业正处在重要的战略转型期,存在着产品结构不合理、部分产品结构性和阶段性过剩,原料对外依存度不断提高,技术创新能力不强,中小企业数量偏多及信息化水平、资源利用效率、环境治理能力较低等一系列问题,需要在转型期内解决。他表示:行业需团结在一起共同面对挑战,完成时代赋予的使命,推动造纸工业实现由大到强的战略转变,构建符合我国国情的现代造纸工业生产体系,实现绿色纸业发展目标。</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12 m-t-30">
<p class="text-muted m-t-0 font-12">新闻热点</p>
<!--<p class="text-muted m-t-0 font-12"><code>card-columns</code></p>-->
<div class="card-columns">
<div class="card">
<img class="card-img-top img-fluid" src="http://img95.699pic.com/photo/50052/2903.jpg_wh300.jpg" alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">真空辊密封条临界接触密封新技术</h4>
<p class="card-text">真空辊是造纸机最昂贵的辊筒之一,因密封条使用而导致的备用辊筒订购、停机换辊造成的生产损失、更换密封条、电力消耗等费用巨大。本文介绍一种真空辊密封条临界接触密封新技术,可以减少密封条与辊筒的磨擦,同时又保证了真空辊的密封条件。
1 真空辊密封条接触式密封技术
真空箱和筒体内壁之间必须采用密封装置进行良好的密封,如图1所示,主要有密封槽、密封条、弹性装置等部件组成。
为了降低真空辊的功率消耗和运行噪音、尽量延长密封条的使用时间,有国外造纸机械装备公司发明了一种“真空辊密封条无接触式密封技术”。该技术基本原理:在密封条的下部和侧面各有1个气胎,密封条下部的气胎可称为“加压气胎”,密封条侧面的气胎称为“锁紧气胎”。在使用时,“加压气胎”首先充气,使密封条接触辊筒内壁,然后“锁紧气胎”充气、“加压气胎”泄压,通过一种特殊的设计结构,密封条稍微回落并定位,此时密封条和辊筒内壁之间出现微小间隙,保证真空箱真空度的同时又避免了密封条的磨损。由于振动的存在,使用一段时间后,密封条可能会出现下落,此时密封条与筒体之间的间隙增大,真空箱的真空度因此受到影响而下降。此时,通过一套自动检测和控制系统,“加压气胎”和“锁定气胎”再次动作,使密封条和筒体内壁之间的间隙重新恢复到设定状态。如此周而复始,保证密封条密封性。
结构主要由密封槽、密封条、橡胶气胎组成,密封条和橡胶气胎都安装在密封槽内,密封条装在橡胶气胎的上部,密封条的上部和辊筒筒体的内壁接触,橡胶气胎装在密封槽的底部。密封槽的两侧槽口的高度不同,左侧密封槽的两侧内壁中部、右侧密封槽两侧内壁的上部都加工有凸台,密封条在相应部位加工有凹槽。
图2a是密封条刚开始使用时的结构,密封条侧面凹槽距密封槽侧壁凸台下部还有一段距离,在橡胶气胎的作用下,密封条压在筒体内壁上逐渐磨损并上移,直至如图2b所示,密封条侧面凹槽的下部靠上密封槽侧壁凸台下部,由于密封槽侧壁凸台的阻挡,密封条不能继续移动,密封条和筒体内壁之间达到临界接触状态,密封条不再继续磨损,此时,由于密封条和筒体内壁之间处于临界接触状态,在保证密封性的同时,密封条和筒体内壁之间的摩擦很小或没有摩擦,密封条和筒体内壁之间因摩擦而产生电力消耗也大幅度降低。
该技术可使密封条的寿命大幅度延长,功率消耗和运转噪音也大幅度降低。但结构复杂,密封条频繁的升降,仍然会造成密封条的磨损,密封条仍需定期更换。
</p>
</div>
</div>
<div class="card p-3">
<p>国内外学者对纤维素改性利用进行了大量的研究,制备得到功能性新材料并在生物医药、化工、制浆造纸等领域取得新的突破。2,2,6,6-四甲基哌啶-1-氧自由基(TEMPO)是一种哌啶类氮氧自由基,在含有TEMPO的共氧化体系下,当伯醇与仲醇同时存在时,能选择性氧化伯醇羟基对仲羟基没有影响,而且反应条件简单、温和。TEMPO/NaBr/NaClO是一种分步氧化,首先将伯羟基氧化成醛基,然后再氧化成羧基,本文主要探讨在TEMPO/NaBr/NaClO体系下,针叶材纤维素上C-6位伯羟基被氧化成醛基再到羧基的变化规律,研究了温度、时间、次氯酸钠对氧化反应的影响。</p>
<footer>
<small class="text-muted">
Someone famous in <cite title="Source Title">Source Title</cite>
</small>
</footer>
</div>
<div class="card">
<img class="card-img-top img-fluid" src="http://img95.699pic.com/photo/50051/4092.jpg_wh300.jpg" alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">微细瓦楞纸板及其市场应用前景</h4>
<p class="card-text">根据市场需求,瓦楞纸板按其强度、挺度、缓冲性能等可分为不同规格。瓦楞的楞型按照大小顺序,用英文字母依次排列为D、K、A、C、B、E、F、G、N、O,市场上最为常见的是A、B、C、E这4种楞型,从E-O楞统称为微细瓦楞。
微细瓦楞纸板的生产是个系统工程,从楞型设计、瓦楞辊结构和精度、单面机的形式、生产线所有设备的运行精度到用纸的选择、运行时与理想速度相匹配的纸张张力控制、温湿度控制、胶糊的调制和上胶量的控制以及纸板质量控制等,都有与A、C、B等常规瓦楞纸板对应的不同的特定要求。
微细瓦楞纸板的特点是楞数多、瓦楞原纸定量轻且强度低。以每300mm长度的瓦楞为例,G型楞数为185±12个,N型楞数为200±15个,O型楞数为267个,而B型楞数为50±2个。同样直径的一对瓦楞辊,微细瓦楞其啮合的楞数比B型瓦楞增加了3-5倍。</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
<div class="card card-inverse card-primary p-3 text-center">
<p>纸张充分浸湿后,通常强度会大幅度下降,此时的强度称为湿强度。如果纸张抄造过程中添加增强剂,纸张仍能保持干强度15%以上的湿强度,这样的增强剂称为湿强剂。纸张的湿强度为干强度15%以上,即为湿强纸。
1935年,脲甲醛树脂(UF)作为表面施胶剂,热处理后便可使纸张具有一定的湿强度。随后又可开发出UF树脂,可以直接加入浆内。1942年,开发出三聚氰胺甲醛树脂(MF)。在1946年阳离子型改性UF树脂试制成功,价格较低,为大量生产湿强纸创造了条件。1960年,研制出聚酰胺聚胺环氧氯丙烷树脂(PPE或PAE),在中碱性条件下熟化,提高纸张湿强度。
水溶PVA纤维及低温水溶PVA纤维最早由日本开发出来。 20世纪70年代末我国开始研究PVA水溶纤维,1986年工业化生产水溶PVA纤维。水溶PVA纤维在纺织行业应用较早,充当功能性差别化纤维,逐步拓宽到造纸、医疗卫生等行业。
本实验以一种低定量特种纸为研究对象,从化学助剂的选择和配比,以及特种纤维的选用,研究如何提高特种纸湿强。</p>
<footer>
<small>
Someone famous in <cite title="Source Title">Source Title</cite>
</small>
</footer>
</div>
<div class="card text-center">
<div class="card-body">
<h4 class="card-title">壁纸中增塑剂检测方法</h4>
<p class="card-text">邻苯二甲酸酯,又称酞酸酯,缩写PAEs,是邻苯二甲酸形成的酯的统称。主要用于聚氯乙烯材料,令聚氯乙烯由硬塑胶变为有弹性的塑胶,起到增塑剂的作用。它被普遍应用于地板和壁纸中,对人体的健康有严重的危害。
1提取方法
增塑剂提取方法有:超声提取、微波提取、索勒斯提取和冲击提取等。要求提取速度快,提取时间短,样品与溶剂之间没有交叉污染,不需要接触,操作人员的健康损害更轻。
我国邻苯二甲酸酯的检测不仅要在基质覆盖检测中进行改进,而且还要引进一些先进的提取技术。
2检测方法
有气相色谱法、红外分光光度法、反相液相色谱法、傅立叶变换红外光谱法等。
2.1光谱法
采用衰减全反射傅立叶变换红外光谱技术,建立PVC中多种PAEs的定量测定方法。该方法可用于分析PVC中的四种PAEs,而不受矩阵的干扰,特别适用于装配线的质量控制。
2.2色谱及联用技术色谱法
色谱和组合技术色谱可以分离各种复杂混合物,气相色谱和高效液相色谱在PAEs检测中有很多应用。PAEs检测的主要方法是GB/T21911-21911的气相色谱法。
以苯甲酸苄酯为内标,同时建立17种PAEUSE-GC-MS方法,样品含量较少为内标定量;将邻苯二甲酸丙烯酯作为内标,建立了一种简单、快速、准确的测定PVC产品中7种PAEs的GC-MS法。
使用高效液相色谱法测定各种PVC产品中6种PAEs的方法,对PAEs的异构体均具有良好的分离度,显示了液相色谱(HPLC)方法的优越性。回收率为70.4%-113.6%,标准差为0.3%-5.8%。</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
<div class="card">
<img class="card-img img-fluid" src="http://img95.699pic.com/photo/50032/4527.jpg_wh300.jpg" alt="Card image"/>
</div>
<div class="card p-3 text-right">
<p>主操作员接班后,要进行卫生处理,尤其是粉尘的吹扫工作,仔细检查纵刀磨损情况、纸张分切尺寸及令数,确认无误后再开机生产。重点观察叠纸部分抽吸箱运行情况,如发现叠纸部分存在抽吸不均现象,应及时加大抽吸箱吹风纸头气压,待纸张能平稳通过叠纸部时,叠纸部压纸轮及时向前提到合理位置。车速逐步提高到300m/min左右,观察理纸部分是否有折角、理纸不齐、窜纸等情况。调整正常后,切纸机可按照此设定情况使车速稳定在300m/min持续生产,副操作员及时配合主操作员更换栈板(目前切纸机具有不停机换栈板功能)。以80g/m2双胶纸(1800 mm纸辊)为例,规格为889mm×1194mm常规件纸,每车8个退纸架,整车上辊质量约为19.6t,从开始到分切完,大约用时80min。</p>
<footer>
<small class="text-muted">
Someone famous in <cite title="Source Title">Source Title</cite>
</small>
</footer>
</div>
<div class="card">
<div class="card-body">
<h4 class="card-title">高湿强特种纸的研究</h4>
<p class="card-text">以一种低定量特种纸为研究对象,对纤维原料、打浆工艺、多元增强体系和特种增强纤维进行研究,研发高湿强特种纸。结果显示:雄狮浆成纸抗张强度优于思茅松浆;随着打浆度的提高,雄狮浆产生切断、压溃、润胀和分丝帚化,有利于对化学助剂的吸附,增加成纸纤维间结合点;多元增强体系增加PAE的留着,特种增强纤维水溶PVA纤维起到纤维粘结剂的作用,提高成纸的湿强度。
纸张充分浸湿后,通常强度会大幅度下降,此时的强度称为湿强度。如果纸张抄造过程中添加增强剂,纸张仍能保持干强度15%以上的湿强度,这样的增强剂称为湿强剂。纸张的湿强度为干强度15%以上,即为湿强纸。
1935年,脲甲醛树脂(UF)作为表面施胶剂,热处理后便可使纸张具有一定的湿强度。随后又可开发出UF树脂,可以直接加入浆内。1942年,开发出三聚氰胺甲醛树脂(MF)。在1946年阳离子型改性UF树脂试制成功,价格较低,为大量生产湿强纸创造了条件。1960年,研制出聚酰胺聚胺环氧氯丙烷树脂(PPE或PAE),在中碱性条件下熟化,提高纸张湿强度。
水溶PVA纤维及低温水溶PVA纤维最早由日本开发出来。 20世纪70年代末我国开始研究PVA水溶纤维,1986年工业化生产水溶PVA纤维。水溶PVA纤维在纺织行业应用较早,充当功能性差别化纤维,逐步拓宽到造纸、医疗卫生等行业。
本实验以一种低定量特种纸为研究对象,从化学助剂的选择和配比,以及特种纤维的选用,研究如何提高特种纸湿强。</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
</div>
</div>
</div>
<!-- Main row -->
<!-- /.row -->
</div><!--/. container-fluid -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- Control Sidebar -->
<aside class="control-sidebar control-sidebar-dark">
<!-- Control sidebar content goes here -->
</aside>
<!-- /.control-sidebar -->
<!-- Main Footer -->
<footer class="main-footer">
<!-- To the right -->
<div class="float-right d-sm-none d-md-block">
Anything you want
</div>
<!-- Default to the left -->
<strong>Copyright © 2014-2018 <a href="https://adminlte.io">AdminLTE.io</a>.</strong> All rights reserved.
</footer>
</div>
<!-- ./wrapper -->
<!-- REQUIRED SCRIPTS -->
<!-- jQuery -->
<script src="/jquery/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="/js/adminlte.js"></script>
<!-- OPTIONAL SCRIPTS -->
<script src="/js/demo.js"></script>
<!-- PAGE -->
<!-- SparkLine -->
<script src="/sparkline/jquery.sparkline.min.js"></script>
<!-- jVectorMap -->
<script src="/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- SlimScroll 1.3.0 -->
<script src="/slimScroll/jquery.slimscroll.min.js"></script>
<!-- ChartJS 1.0.2 -->
<script src="/chartjs-old/Chart.min.js"></script>
<!-- PAGE SCRIPTS -->
<script src="/js/pages/dashboard2.js"></script>
<script th:inline="javascript">
$(function () {
var add_success=[[${add_success}]];
var del_success=[[${del_success}]];
var risk_library_edit=[[${risk_library_edit}]];
var risk_library_update_success=[[${risk_library_update_success}]];
if(add_success==1){
alert("创建成功!");
};
if(del_success==1){
alert("删除成功!")
};
if(risk_library_update_success==1){
alert("更新成功!")
};
if(risk_library_edit==1){
$("#modal-risk_library_edit").modal('show');
};
$(".fa-trash-o").click(function () {
var id= $(this).parent().siblings(".id").html();
$("#del_risk_library_ready").modal('show');
$("#del_confirm").click(function () {
window.location.href='/riskeventlibrary/del/'+id;
})
});
$(".fa-edit").click(function () {
var id= $(this).parent().siblings(".id").html();
window.location.href='/riskeventlibrary/edit/'+id;
});
})
</script>
<script>
$(function () {
$(".fa-eye").click(function () {
var id =$(this).parent().siblings(".id").html();
window.location.href='/riskeventlibrary/risk_recognize/'+id;
});
$(".fa-hourglass-end").click(function () {
var id =$(this).parent().siblings(".id").html();
window.location.href='/riskeventlibrary/risk_analysis/'+id;
});
$(".fa-hand-rock-o").click(function () {
var id =$(this).parent().siblings(".id").html();
window.location.href='/riskeventlibrary/risk_controller/'+id;
})
})
</script>
</body>
</html>
<file_sep>package com.example.demo.controller;
import com.example.demo.dao.UserDAO;
import com.example.demo.pojo.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Controller
@EnableAutoConfiguration
public class LoginController {
@Autowired
private UserDAO userDAO;
/**
* 登录页面
*
* @return
*/
@RequestMapping(value = {"/login"})
public String login() {
return "login";
}
/**
* 认证
*session就是一个map结构
* @return
*/
@RequestMapping(value = "/oauth", method = RequestMethod.POST)
public String oauthUser(String username, String password, Model model, HttpSession session) {
UserDO user = userDAO.findOne(username, password);
if (user != null) {
session.setAttribute("user", user);
// return "redirect:/main/select";
return "redirect:/main/main_page";
} else {
model.addAttribute("msg", "登录失败!账号或密码错误");
return "login";
}
}
@RequestMapping(value = "/logout")
public String logout(HttpSession session,Model model) {
// session.invalidate();
session.removeAttribute("user");
model.addAttribute("logout",1);
return "login";
}
/**
* 伯乐注册
*/
@RequestMapping(value = {"/boleReg"})
public String boleReg(Model model) {
UserDO uo = new UserDO();
model.addAttribute("uo", uo);
return "user_add_bole";
}
}<file_sep>package com.example.demo.dao;
import com.example.demo.pojo.CommentDO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;
public interface CommentDAO extends JpaRepository<CommentDO,Long> {
CommentDO findById(int id);
@Transactional
@Modifying
@Query("delete from CommentDO c where c.id = ?1")
void deleteById(int id);
}
<file_sep>package com.duruo.service.impl;
import com.duruo.common.ServerResponse;
import com.duruo.dao.*;
import com.duruo.dto.DataFields;
import com.duruo.dto.FlowData;
import com.duruo.dto.FlowDataChild.*;
import com.duruo.dto.PostData;
import com.duruo.po.*;
import com.duruo.service.IStAuditService;
import com.duruo.util.*;
import com.duruo.vo.StAuditVo;
import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.Cookie;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.*;
import org.apache.http.impl.client.*;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.*;
/**
* Created by @Author tachai
* date 2018/6/19 14:38
*
* @Email <EMAIL>
*/
@Slf4j
@Service("iStAuditService")
public class StAuditServiceImpl implements IStAuditService {
@Autowired
private ProjectdetailMapper projectdetailMapper;
@Autowired
private EnterpriseMapper enterpriseMapper;
@Autowired
private PersionsMapper persionsMapper;
@Autowired
private ProjectBudgetMapper projectBudgetMapper;
@Autowired
private ProjectBudgetDetailMapper projectBudgetDetailMapper;
@Autowired
private FilePathMapper filePathMapper;
@Autowired
private AuditTempDataMapper auditTempDataMapper;
// 构造登录
protected CloseableHttpClient _client;
private CookieStore _cookies;
private void init() {
_cookies = new BasicCookieStore();
HttpClientBuilder hcb = HttpClientBuilder.create();
// hcb.setProxy(new HttpHost("127.0.0.1", 8888));
hcb.setRedirectStrategy(new LaxRedirectStrategy());
// User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
hcb.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.82 Safari/537.36");
hcb.setDefaultCookieStore(_cookies);
_client = hcb.build();
}
@Override
public ServerResponse<List<StAuditVo>> list(String realname, String project) {
List<StAuditVo> list = projectdetailMapper.getAllStAuditVo(realname, project);
if (list != null) {
return ServerResponse.createBySuccess(list, "查询成功");
} else {
return ServerResponse.createByErrorMessage("查询失败");
}
}
@Override
public ServerResponse<Enterprise> getEnterprise(String sn) {
Projectdetail project = projectdetailMapper.selectByPrimaryKey(sn);
//todo 可能会报错没有找到project
Enterprise enterprise = enterpriseMapper.selectByPrimaryKey(project.getEnterpriseId());
if (enterprise != null) {
return ServerResponse.createBySuccess(enterprise, "获得企业信息成功");
} else {
return ServerResponse.createByErrorMessage("没有找到企业信息");
}
}
@Override
public ServerResponse<Projectdetail> getProjectdetail(String sn) {
Projectdetail project = projectdetailMapper.selectByPrimaryKey(sn);
if (null != project) {
return ServerResponse.createBySuccess(project, "查询成功");
} else {
return ServerResponse.createByErrorMessage("没有找到相关项目");
}
}
@Override
public ServerResponse<List<Persions>> getListPersions(String sn) {
Projectdetail project = projectdetailMapper.selectByPrimaryKey(sn);
if (null != project) {
List<Persions> list = persionsMapper.getListPersions(sn);
return ServerResponse.createBySuccess(list, "获得当前项目人员列表");
} else {
return ServerResponse.createByErrorMessage("没有找到相关项目");
}
}
@Override
public ServerResponse<ProjectBudget> getProjectBudget(String sn) {
Projectdetail project = projectdetailMapper.selectByPrimaryKey(sn);
if (null != project) {
ProjectBudget projectBudget = projectBudgetMapper.selectBySN(sn);
return ServerResponse.createBySuccess(projectBudget, "查询预算成功");
} else {
return ServerResponse.createByErrorMessage("没有找到相关项目");
}
}
@Override
public ServerResponse<List<ProjectBudgetDetail>> getListBudgetDetail(String sn) {
Projectdetail project = projectdetailMapper.selectByPrimaryKey(sn);
if (null != project) {
List<ProjectBudgetDetail> list = projectBudgetDetailMapper.selectListBudgetDtailBySN(sn);
return ServerResponse.createBySuccess(list, "查询列表成功");
} else {
return ServerResponse.createByErrorMessage("没有找到相关项目");
}
}
@Override
public ServerResponse<String> getOpinion(String sn) {
Projectdetail project = projectdetailMapper.selectByPrimaryKey(sn);
if (null != project) {
return ServerResponse.createBySuccess(project.getAuditOpinion(), "获得审核信息");
} else {
return ServerResponse.createByErrorMessage("获得审核信息失败");
}
}
//新增数据给后台
@Override
public ServerResponse<String> updateOpinion(String opinion, String sn, String status) {
Projectdetail projectdetail = projectdetailMapper.selectByPrimaryKey(sn);
// Enterprise enterprise = enterpriseMapper.selectByPrimaryKey(projectdetail.getEnterpriseId());
if (null != projectdetail) {
if (!StringUtils.isBlank(opinion)) {
projectdetail.setAuditOpinion(opinion);
}
int result = projectdetailMapper.updateByPrimaryKeySelective(projectdetail);
return ServerResponse.createBySuccessMessage("更新数据成功");
}
return ServerResponse.createByErrorMessage("更新数据失败");
}
//提交数据给科委系统
@Override
public ServerResponse<String> postOpinion(String opinion, String sn, String status) {
Projectdetail projectdetail = projectdetailMapper.selectByPrimaryKey(sn);
// Enterprise enterprise = enterpriseMapper.selectByPrimaryKey(projectdetail.getEnterpriseId());
if (null != projectdetail) {
if (!StringUtils.isBlank(opinion)) {
projectdetail.setAuditOpinion(opinion);
}
projectdetail.setXmstatuscode(status);
projectdetailMapper.updateByPrimaryKeySelective(projectdetail);
//返回审核结果给科委系统
String url = PropertiesUtil.getProperty("kewei.url");
PostData postData = new PostData();
// 填充数据到postData中去
//第一个list
//泛型传惨脑袋爆炸
List<FlowData> flowDataList = new ArrayList<>();
FlowData<List<db_flow_jjkc_info>> flowData = new FlowData();
List<db_flow_jjkc_info> infoList = new ArrayList<>();
db_flow_jjkc_info info = new db_flow_jjkc_info();
info.setTitle(projectdetail.getProject());
//这里是前短穿过 来的值
if (Integer.parseInt(status) == 12) {
info.setStatus("待专家一次评审");
info.setSHYJ("通过");
} else {
info.setStatus("待修改");
info.setSHYJ("退回");
}
info.setStatusCode(status);
Date date = new Date();
String dateToStr = DateTimeUtil.dateToStr(date);
info.setModifyTime(dateToStr);
info.setProjectCode(projectdetail.getId());
info.setTechnicalFieldCode(CheckTechnicalCode.strToCode(projectdetail.getTechnical()));
info.setTechnicalField(projectdetail.getTechnical());
info.setCheckbox1("1");
info.setCheckbox2("1");
info.setSHYJTzqy("");
info.setSHYJ1("");
info.setSHYJ2("");
infoList.add(info);
flowData.setDb_flow_jjkc_info(infoList);
flowDataList.add(flowData);
// postData.setFlowData(flowDataList);
List<db_flow_jjkc_cyry_info> cyrylist = new ArrayList<>();
cyrylist.add(new db_flow_jjkc_cyry_info());
FlowData<List<db_flow_jjkc_cyry_info>> flowData2 = new FlowData();
flowData2.setDb_flow_jjkc_cyry_info(cyrylist);
flowDataList.add(flowData2);
List<db_flow_jjkc_kfys_info> kfyslist = new ArrayList<>();
kfyslist.add(new db_flow_jjkc_kfys_info());
FlowData<List<db_flow_jjkc_kfys_info>> flowData3 = new FlowData();
flowData3.setDb_flow_jjkc_kfys_info(kfyslist);
flowDataList.add(flowData3);
List<db_flow_jjkc_qtfj_info> qtfjlist = new ArrayList<>();
qtfjlist.add(new db_flow_jjkc_qtfj_info());
FlowData<List<db_flow_jjkc_qtfj_info>> flowData4 = new FlowData();
flowData4.setDb_flow_jjkc_qtfj_info(qtfjlist);
flowDataList.add(flowData4);
FlowData<List<Core_Flow_Opinion>> flowData1 = new FlowData();
//第二个list
List<Core_Flow_Opinion> opinionList = new ArrayList<>();
Core_Flow_Opinion flow_opinion = new Core_Flow_Opinion();
if (Integer.parseInt(status) == 12) {
flow_opinion.setOpinion("基本符合申报要求,同意申报。");
} else {
flow_opinion.setOpinion(projectdetail.getAuditOpinion());
}
flow_opinion.setOpinion(projectdetail.getAuditOpinion());
System.out.print(projectdetail.getAuditOpinion());
flow_opinion.setTitle("企业研发费用加计扣除申报流程");
flow_opinion.setProjectID(projectdetail.getSn());
flow_opinion.setUserName("方超");
flow_opinion.setUserUID("fangchao");
flow_opinion.setUserOrgCode("D_2F9FB5B2-FF91-456B-AC9F-8818DCD74BF5");
flow_opinion.setUserUnitCode("");
flow_opinion.setUserOrgName("科技创新服务中心");
flow_opinion.setUserUnitName("");
flow_opinion.setCurrentNodeID("6");
flow_opinion.setCurrentNodeName("形式审核");
flow_opinion.setCurrentFlowName(projectdetail.getProject());
flow_opinion.setTaskID("");
flow_opinion.setPreWorkId(projectdetail.getStatus());
flow_opinion.setUserOrgPath("C_20170417072903138.D_2F9FB5B2-FF91-456B-AC9F-8818DCD74BF5");
flow_opinion.setCompanyCode("C_20170417072903138");
flow_opinion.setCompanyName("徐汇区科学技术委员会");
opinionList.add(flow_opinion);
flowData1.setCore_Flow_Opinion(opinionList);
flowDataList.add(flowData1);
// flowDataList.add(flowData);
postData.setFlowData(flowDataList);
postData.setFlowKey(projectdetail.getId());
postData.setFlowSN(projectdetail.getRealSn());
postData.setProjectId(projectdetail.getSn());
postData.setBizTable("DB_Flow_Jjkc_Info");
postData.setNodeIsAuto("True");
postData.setUpLoadFileId("");
DataFields dataFields = new DataFields();
dataFields.setApproveUsers("");
dataFields.setNodeID("");
dataFields.setTitle(projectdetail.getProject());
dataFields.setApprovalFormURL("http://fwpt.yc.c.c/FlowManagerModule/Form");
postData.setDataFields(dataFields);
postData.setActionMode("Save");
String data = new Gson().toJson(postData);
System.out.println("测试生成的json:+++++" + data);
//保存cookie
final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
OkHttpClient httpClient = new OkHttpClient().newBuilder()
.cookieJar(new CookieJar() {
@Override
public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) {
cookieStore.put(httpUrl.host(), list);
}
@Override
public List<Cookie> loadForRequest(HttpUrl httpUrl) {
List<Cookie> cookies = cookieStore.get(httpUrl.host());
return cookies != null ? cookies : new ArrayList<Cookie>();
}
}).build();
// RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), data);
//okHttp提交form表单
FormBody formBody = new FormBody.Builder()
.add("formJson", data)
.build();
Request request = new Request.Builder()
.url(url)
.header("Cookie", "UIthemeColor=%231e71b1; LoginUserKey=7B54E67704C8A1BBAD8A6D9914F5688B7B10E92BDB72B2688709E3EB79B1B7993DA27D76469A3B72017CC1195C45A8245D47A8632C6A69C526311CCDA1A3FD703E9FAE76132B754A75B6D246D176CABC187D3A3C5A52A80B5620A36C9324ACB8B27AFAEB<KEY>; FrontLoginKey=<KEY>88A7E62CB4254E40A38208A9D4E")
.post(formBody)
.build();
//创建/Call
Call call = httpClient.newCall(request);
//加入队列 异步操作
call.enqueue(new Callback() {
//请求错误回调方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("连接失败");
log.error("提交信息给科委失败:{}", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.code() == 200) {
// System.out.println(response.body().string());
//string方法只能用一次,多了会报错
log.error("提交信息给科委成功:{}", response.body().string());
}
}
});
return ServerResponse.createBySuccessMessage("添加人工审核意见成功");
}
return ServerResponse.createByErrorMessage("该项目不存在");
}
@Override
public ServerResponse<String> checkAll()throws Exception {
List<Enterprise> listEnterPrise = enterpriseMapper.listEnterPrise();
listEnterPrise.forEach(enterprise -> {
String tel=enterprise.getWorktelephone();
String phone=enterprise.getContactsphone();
//这个暂时用不了
// Projectdetail project = projectdetailMapper.selectByEnterpriseId(enterprise.getCreditcode());
Projectdetail project = projectdetailMapper.selectByPrimaryKey(enterprise.getCreditcode());
//注意判断project是否为空容易报空指针异常
if(null!=project&&project.getSn()!=""){
if(CheckProject.checkPhone(tel)||CheckProject.checkTel(tel)){
project.setAuditOpinion(" ");
}else {
project.setAuditOpinion("【企业信息】:企业号码格式不对;");
}
if(StringUtils.isEmpty( enterprise.getContactsname())){
project.setAuditOpinion(project.getAuditOpinion()+"【加计扣除联系人】:联系人姓名不能为空;");
}
if(CheckProject.checkPhone(phone)||CheckProject.checkTel(phone)){
}else {
project.setAuditOpinion(project.getAuditOpinion()+"【加计扣除联系人】:联系人联系号码格式不对;");
}
projectdetailMapper.updateByPrimaryKeySelective(project);
}
});
List<Projectdetail> listProjectdetail = projectdetailMapper.listProjectdetail();
listProjectdetail.forEach(project->{
if(null!=project&&project.getSn()!=""){
if(!CheckProject.checkWords(project.getTrts())){
project.setAuditOpinion(project.getAuditOpinion()+"【技术路线或者技术方案模块】:内容偏少,建议补充;");
}
if(!CheckProject.checkWords(project.getCip())){
project.setAuditOpinion(project.getAuditOpinion()+"【核心创新点模块】:内容偏少,建议详实一点;");
}
if(!CheckProject.checkWords(project.getWbrdc())){
project.setAuditOpinion(project.getAuditOpinion()+"【项目工作基础与研发条件模块】:内容偏少,建议补充;");
}
projectdetailMapper.updateByPrimaryKeySelective(project);
}
});
List<Persions> list = persionsMapper.getListPersion();
list.forEach(e -> {
Projectdetail project = projectdetailMapper.selectByPrimaryKey(e.getSn());
if(null!=project&&project.getSn()!=""){
if (!CheckProject.checkAge(e.getAge().trim())) {
project.setAuditOpinion(project.getAuditOpinion()+"【项目参与人员】:请确实认"+e.getPersionName()+"的出生年月是否正确;");
}
projectdetailMapper.updateByPrimaryKeySelective(project);
}
});
List<ProjectBudget> listProjectBudget = projectBudgetMapper.listProjectBudget();
listProjectBudget.forEach(projectBudget -> {
Projectdetail project = projectdetailMapper.selectByPrimaryKey(projectBudget.getSn());
if(null!=project&&project.getSn()!=""){
Double generalBudget=Double.parseDouble(projectBudget.getGeneralBudget());
Double specialFunds=Double.parseDouble(projectBudget.getSpecialFunds());
Double selfFinancing=Double.parseDouble(projectBudget.getSelfFinancing());
Double developmentCost=Double.parseDouble(projectBudget.getDevelopmentCost());
//一个条件一个意见
if(generalBudget!=(selfFinancing+specialFunds)||selfFinancing==0||developmentCost>=(generalBudget*1.2)){
project.setAuditOpinion(project.getAuditOpinion()+"【项目开发预算】:建议核实项目开发预算;");
log.info("【项目开发预算】:建议核实项目开发预算:{}",project.getSn());
}
List<ProjectBudgetDetail> budgetDetailList = projectBudgetDetailMapper.selectListBudgetDtailBySN(project.getSn());
if(budgetDetailList.size()<2){
if(null!=budgetDetailList){
ProjectBudgetDetail budgetDetail=budgetDetailList.get(0);
if(null !=budgetDetail){
String temp=budgetDetail.getDecomposeDetailed();
if(temp.split("\\s+").length>1){
project.setAuditOpinion(project.getAuditOpinion()+"【预算分解明细】:明细只有一行建议分行填写;");
}
}
}
}
if(StringUtils.isBlank(project.getAuditOpinion())){
project.setAuditOpinion("【表格内容无明显错误】");
}
projectdetailMapper.updateByPrimaryKeySelective(project);
}
});
List<Projectdetail> listProjectdetail2 = projectdetailMapper.listProjectdetail();
//附件文件校验
listProjectdetail2.forEach(e -> {
List<FilePath> listFilePath = filePathMapper.list(Integer.parseInt(e.getSn()));
if (listFilePath.size() != 0) {
Set<String> set = new HashSet<>();
for (FilePath filePath : listFilePath) {
//OCR 判断第一文件
String strTemp = filePath.getName().substring(filePath.getName().lastIndexOf("."));
if (filePath.getTypeCode().equals("1000")) {
set.add("1000");
//如果是pdf则转图片
if (strTemp.equals(".pdf")) {
//将pdf文件转文图片
try{
List<String> imageList = PdfToImage.pdfToImagePath(filePath.getPath());
JSONObject json = OCR.checkOne(imageList.get(0));
// if (json.toString().length() < 200) {
// e.setAuditOpinion(e.getAuditOpinion() + "【优惠明细表或辅助账汇总表】内容不够详细,建议直接从税务申报系统中直接导出");
// }
filePath.setToString(json.toString());
}catch (Exception e1){
log.error("错误"+e1.getMessage());
}
//将文本解析后得到的数据存到filepath的tostring路径中
filePathMapper.updateByPrimaryKeySelective(filePath);
} else if (strTemp.equals(".jpg")) {
try{
JSONObject json = OCR.checkOne(filePath.getPath());
if (json.toString().indexOf("总经理办公室决议") != -1 && json.toString().indexOf("公司董事会决议") != -1) {
e.setAuditOpinion(e.getAuditOpinion() + "【立项决议书】立项决议书应明确到底是董事会决议还是总经理办公会议决议");
}
filePath.setToString(json.toString());
//将文本解析后得到的数据存到filepath的tostring路径中
}catch (Exception e2){
log.error(e2.getMessage());
}
filePathMapper.updateByPrimaryKeySelective(filePath);
//OCR判断第二个文件
}
} else if (filePath.getTypeCode().equals("2000")) {
set.add("2000");
// String strTemp = filePath.getName().substring(filePath.getName().lastIndexOf("."));
if (strTemp.equals(".pdf")) {
try{
//将pdf文件转文图片
List<String> imageList = PdfToImage.pdfToImagePath(filePath.getPath());
JSONObject json = OCR.checkOne(imageList.get(0));
//todo 第二个表判断还没做完
if (json.toString().indexOf("总经理办公室决议") != -1 && json.toString().indexOf("公司董事会决议") != -1) {
e.setAuditOpinion(e.getAuditOpinion() + "【立项决议书】立项决议书应明确到底是董事会决议还是总经理办公会议决议");
}
filePath.setToString(json.toString());
//将文本解析后得到的数据存到filepath的tostring路径中
}catch (Exception e3){
log.error(e3.getMessage());
}
filePathMapper.updateByPrimaryKeySelective(filePath);
// Iterator<String> iterator = imageList.iterator();
// while (iterator.hasNext()){
// //生成的文件路径
// System.out.println(iterator.next());
// }
} else if (strTemp.equals(".jpg") || strTemp.equals(".png")) {
try{
JSONObject json = OCR.checkOne(filePath.getPath());
if (json.toString().indexOf("总经理办公室决议") != -1 && json.toString().indexOf("公司董事会决议") != -1) {
e.setAuditOpinion(e.getAuditOpinion() + "【立项决议书】立项决议书应明确到底是董事会决议还是总经理办公会议决议");
}
filePath.setToString(json.toString());
//将文本解析后得到的数据存到filepath的tostring路径中
}catch (Exception e4){
log.error(e4.getMessage());
}
filePathMapper.updateByPrimaryKeySelective(filePath);
}
} else if (filePath.getTypeCode().equals("3000")) {
set.add("3000");
// checkstrTemp(strTemp, filePath);
if (strTemp.equals(".pdf")) {
try{
List<String> imageList = PdfToImage.pdfToImagePath(filePath.getPath());
JSONObject json = OCR.checkOne(imageList.get(0));
Object listWords = json.get("words_result");
if(listWords.toString().indexOf("2015")!=-1||listWords.toString().indexOf("2016")!=-1){
e.setAuditOpinion(e.getAuditOpinion() + "【申报单位诚信承诺书】诚信承诺书填写年份不对,请填写当年年份");
}
filePath.setToString(json.toString());
//将文本解析后得到的数据存到filepath的tostring路径中
}catch (Exception e5){
}
filePathMapper.updateByPrimaryKeySelective(filePath);
} else if (strTemp.equals(".jpg") || strTemp.equals(".png")) {
try {
JSONObject json = OCR.checkOne(filePath.getPath());
filePath.setToString(json.toString());
//将文本解析后得到的数据存到filepath的tostring路径中
}catch (Exception e6){
}
filePathMapper.updateByPrimaryKeySelective(filePath);
}
} else if (filePath.getTypeCode().equals("4000")) {
set.add("4000");
if (strTemp.equals(".pdf")) {
try {
List<String> imageList = PdfToImage.pdfToImagePath(filePath.getPath());
JSONObject json = OCR.checkOne(imageList.get(0));
filePath.setToString(json.toString());
//将文本解析后得到的数据存到filepath的tostring路径中
}catch (Exception e7){
}
filePathMapper.updateByPrimaryKeySelective(filePath);
} else if (strTemp.equals(".jpg") || strTemp.equals(".png")) {
try{
JSONObject json = OCR.checkOne(filePath.getPath());
filePath.setToString(json.toString());
//将文本解析后得到的数据存到filepath的tostring路径中
}catch (Exception e8){
}
filePathMapper.updateByPrimaryKeySelective(filePath);
}
}
}
if (set.size() < 4) {
e.setAuditOpinion(e.getAuditOpinion() + "【附件文件缺失】前4项文件都是必须上传的");
}
projectdetailMapper.updateByPrimaryKeySelective(e);
}
});
return ServerResponse.createBySuccessMessage("查看数据库");
}
// //验证后缀名
// public void checkstrTemp(String strTemp, FilePath filePath) {
// if (strTemp.equals(".pdf")) {
// List<String> imageList = PdfToImage.pdfToImagePath(filePath.getPath());
// JSONObject json = OCR.checkOne(imageList.get(0));
// filePath.setToString(json.toString());
// //将文本解析后得到的数据存到filepath的tostring路径中
// filePathMapper.updateByPrimaryKeySelective(filePath);
// } else if (strTemp.equals(".jpg") || strTemp.equals(".png")) {
// JSONObject json = OCR.checkOne(filePath.getPath());
// filePath.setToString(json.toString());
// //将文本解析后得到的数据存到filepath的tostring路径中
// filePathMapper.updateByPrimaryKeySelective(filePath);
// }
// }
public String check() {
List<Projectdetail> listProjectdetail2 = projectdetailMapper.listProjectdetail();
listProjectdetail2.forEach(e -> {
List<FilePath> listFilePath = filePathMapper.list(Integer.parseInt(e.getSn()));
if (listFilePath.size() != 0) {
Set<String> set = new HashSet<>();
for (FilePath filePath : listFilePath) {
//OCR 判断第一文件
if (filePath.getTypeCode().equals("1000")) {
set.add("1000");
//如果是pdf则转图片
String strTemp = filePath.getName().substring(filePath.getName().lastIndexOf("."));
if (strTemp.equals(".pdf")) {
//将pdf文件转文图片
List<String> imageList = PdfToImage.pdfToImagePath(filePath.getPath());
;
JSONObject json = OCR.checkOne(imageList.get(0));
// if(json.toString().length()<500){
// e.setAuditOpinion(e.getAuditOpinion()+"【优惠明细表或辅助账汇总表】内容不够详细,建议直接从税务申报系统中直接导出");
// }
}
//OCR判断第二个文件
} else if (filePath.getTypeCode().equals("2000")) {
set.add("2000");
String strTemp = filePath.getName().substring(filePath.getName().lastIndexOf("."));
if (strTemp.equals(".pdf")) {
//将pdf文件转文图片
List<String> imageList = PdfToImage.pdfToImagePath(filePath.getPath());
// JSONObject json = OCR.checkOne(imageList.get(0));
// //todo 第二个表判断还没做完
// if(json.toString().indexOf("总经理办公室决议")!=-1&&json.toString().indexOf("公司董事会决议")!=-1){
// e.setAuditOpinion(e.getAuditOpinion()+"【立项决议书】立项决议书应明确到底是董事会决议还是总经理办公会议决议");
// }
// Iterator<String> iterator = imageList.iterator();
// while (iterator.hasNext()){
// //生成的文件路径
// System.out.println(iterator.next());
// }
}
} else if (filePath.getTypeCode().equals("3000")) {
set.add("3000");
String strTemp = filePath.getName().substring(filePath.getName().lastIndexOf("."));
if (strTemp.equals(".pdf")) {
//将pdf文件转文图片
List<String> imageList = PdfToImage.pdfToImagePath(filePath.getPath());
}
} else if (filePath.getTypeCode().equals("4000")) {
set.add("4000");
// String strTemp = filePath.getName().substring(filePath.getName().lastIndexOf("."));
//
// if(strTemp.equals(".pdf")) {
// //将pdf文件转文图片
// List<String> imageList = PdfToImage.pdfToImagePath(filePath.getPath());
// }
}
}
// if(set.size()<4){
// e.setAuditOpinion(e.getAuditOpinion()+"【附件文件缺失】前4项文件都是必须上传的");
// }
// projectdetailMapper.updateByPrimaryKeySelective(e);
}
// listFilePath.size()
});
return null;
}
// 登录
private void login() throws ClientProtocolException, IOException {
String urlPre="http://172.16.31.10:10061/Login/Index?isLogin="+Math.random();
HttpGet get = new HttpGet(urlPre);
HttpResponse responsePre = _client.execute(get);
ResponseHandler<String> rhPre = new BasicResponseHandler();
@SuppressWarnings("unused")
String htmlPre = rhPre.handleResponse(responsePre);
//上面是登录前的前置操作
String url = "http://172.16.31.10:10061/Login/CheckLogin";
HttpPost request = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Account", "zhouyichun"));
params.add(new BasicNameValuePair("Password", "<PASSWORD>"));
params.add(new BasicNameValuePair("VerifyCode", ""));
request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = _client.execute(request);
ResponseHandler<String> rh = new BasicResponseHandler();
@SuppressWarnings("unused")
String html = rh.handleResponse(response);
System.out.println(html);
}
// @Override
// public ServerResponse<String> getAll() {
//
// try {
// init();
// login();
//
//// /CMS/CXFWQ/XMSB/XMSB_ProjectModifyRecord/FormalCheckPageJsonList?EnterpriseName=&Tax1=&Tax2=&ProjectName=&Yysr1=&Yysr2=&TechnicalField=&Years=2017&ProjectNum=&PStatus=&nodeId=6&_search=false&nd=1544578232144&rows=20&page=1&sidx=submited+desc%2C+notcheck+desc%2Csortcode++&sord=asc
//
// String dateTime=new Date().getTime()+"";//1544509492808
// System.out.println("当前的时间戳:"+dateTime);
// String url = "http://fwpt.yc.c.c/CMS/CXFWQ/XMSB/XMSB_ProjectModifyRecord/FormalCheckProjectsPageJsonList?ProjectName&Xmzys1&Xmzys2&Zczj1&Zczj2&EnterpriseName&TechnicalField&Zxzj1&Zxzj2&Xmdnkf1&Xmdnkf2&Years=2017&ProjectNum&PStatus&nodeId=6&_search=false&nd="+dateTime+"&rows=3000&page=1&sidx=ranksort%2Csort%2CEnterpriseId+desc%2Csortcode%2Ccreatetime+desc%2C+sn+desc%2Cwid+desc%2Cshyj+&sord=desc";
// HttpPost request = new HttpPost(url);
// request.setHeader("Content-Type","application/json");
// //org.apache.http.cookie.Cookie cookie =_cookies.getCookies().get(0);
//
//
// HttpResponse response = _client.execute(request);
// ResponseHandler<String> rh = new BasicResponseHandler();
// @SuppressWarnings("unused")
// String html = rh.handleResponse(response);
// // 得到json 数据
// log.info("response:{}",response.toString());
// log.info("html:{}",html);
// JsonParser parser = new JsonParser();
// JsonObject allObject = (JsonObject) parser.parse(html);
//
//
// log.info("json解析:",allObject.toString());
// System.out.println(html);
// } catch (Exception e) {
// return ServerResponse.createByErrorMessage("发生了错误"+e.getMessage());
// }
// return ServerResponse.createBySuccessMessage("成功了");
// }
@Override
public ServerResponse<String> getAll() {
try {
String dateTime=new Date().getTime()+"";//1544509492808
System.out.println("当前的时间戳:"+dateTime);
String url = "http://fwpt.yc.c.c/CMS/CXFWQ/XMSB/XMSB_ProjectModifyRecord/FormalCheckProjectsPageJsonList?ProjectName&Xmzys1&Xmzys2&Zczj1&Zczj2&EnterpriseName&TechnicalField&Zxzj1&Zxzj2&Xmdnkf1&Xmdnkf2&Years=2017&ProjectNum&PStatus&nodeId=6&_search=false&nd="+dateTime+"&rows=3000&page=1&sidx=ranksort%2Csort%2CEnterpriseId+desc%2Csortcode%2Ccreatetime+desc%2C+sn+desc%2Cwid+desc%2Cshyj+&sord=desc";
OkHttpClient httpClient = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url(url)
.header("Cookie", "UIthemeColor=%231e71b1; LoginUserKey="+PropertiesUtil.getProperty("kewei.userKey")+"; FrontLoginKey="+PropertiesUtil.getProperty("kewei.loginKey"))
.build();
//创建/Call
Call call = httpClient.newCall(request);
//加入队列 异步操作
call.enqueue(new Callback() {
//请求错误回调方法
@Override
public void onFailure(Call call, IOException e) {
System.out.println("连接失败");
log.error("提交信息给科委失败:{}", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.code() == 200) {
JsonParser parser = new JsonParser();
JsonObject allObject = parser.parse(response.body().string()).getAsJsonObject();
log.info("allObject:{}",allObject.toString());
JsonArray array = allObject.getAsJsonArray("rows");
for (int i=0;i<array.size();i++){
AuditTempData atd = new AuditTempData();
atd.setId(array.get(i).getAsJsonObject().get("id").getAsString());
atd.setSn(array.get(i).getAsJsonObject().get("sn").isJsonNull()?"":array.get(i).getAsJsonObject().get("sn").getAsString());
atd.setEnterpriseid(array.get(i).getAsJsonObject().get("enterpriseid").isJsonNull()?"":array.get(i).getAsJsonObject().get("enterpriseid").getAsString());
//
atd.setEnterprisename(array.get(i).getAsJsonObject().get("enterprisename").isJsonNull()?"":array.get(i).getAsJsonObject().get("enterprisename").getAsString());
//projectname
atd.setProjectname(array.get(i).getAsJsonObject().get("projectname").isJsonNull()?"":array.get(i).getAsJsonObject().get("projectname").getAsString());
//projectid
atd.setProjectid(array.get(i).getAsJsonObject().get("projectid").isJsonNull()?"":array.get(i).getAsJsonObject().get("projectid").getAsString());
//technicalfield
atd.setTechnicalfield(array.get(i).getAsJsonObject().get("technicalfield").isJsonNull()?"":array.get(i).getAsJsonObject().get("technicalfield").getAsString());
//zjpdjg
atd.setZjpdjg(array.get(i).getAsJsonObject().get("zjpdjg").isJsonNull()?"":array.get(i).getAsJsonObject().get("zjpdjg").getAsString());
atd.setCreateTime(new Date());
AuditTempData auditTempData =auditTempDataMapper.selectByPrimaryKey(atd.getId());
if(auditTempData==null){
int result = auditTempDataMapper.insertSelective(atd);
}
}
}
}
});
} catch (Exception e) {
return ServerResponse.createByErrorMessage("发生了错误"+e.getMessage());
}
return ServerResponse.createBySuccessMessage("成功了");
}
@Override
public ServerResponse<List<AuditTempData>> listAll(String realname, String project) {
List<AuditTempData> list = auditTempDataMapper.listAll(realname, project);
if (list != null) {
return ServerResponse.createBySuccess(list, "查询成功");
} else {
return ServerResponse.createByErrorMessage("查询失败");
}
}
@Override
public ServerResponse<String> delectById(String id) {
int result = auditTempDataMapper.deleteByPrimaryKey(id);
if(result>0){
return ServerResponse.createBySuccessMessage("删除成功");
}
return ServerResponse.createByErrorMessage("删除失败");
}
}
<file_sep>(function() {
var states = ['unset', 'one', 'two', 'three', 'all'];
var $nodes = $(states.map(function(state) {
return '#daygrid li.' + state;
}).join(', '));
var schedule = $nodes.get().map(function(){ return 0; });
display();
$nodes.click(function() {
var index = $nodes.index(this);
this.classList.remove(states[schedule[index]]);
schedule[index] = (schedule[index] + 1) % states.length;
this.classList.add(states[schedule[index]]);
document.getElementsByName('schedule')[0].value = JSON.stringify(schedule);
});
function display() {
$nodes.each(function(i, node) {
node.classList.remove.apply(node.classList, states);
node.classList.add(states[schedule[i]]);
});
}
window.updateSchedule = function() {
try {
var newSchedule = JSON.parse(document.getElementsByName('schedule')[0].value);
if (newSchedule instanceof Array && newSchedule.length === schedule.length && newSchedule.every(function(s) {
return typeof s === 'number' && s >= 0 && s < states.length;
})) {
schedule = newSchedule;
}
} catch (e) {}
display();
};
}());<file_sep>package com.example.demo.pojo;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "user_permission", schema = "risk_assessment", catalog = "")
public class UserPermissionDO {
private int id;
private String userName;
private String userCompany;
private String userDepartment;
private String workNumber;
private String ableManageUser;
private String ableCreateNewProject;
private String ableExaminationApprovalProject;
private String ableModifyProject;
private String ablePushProject;
@Id
@Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "user_name")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Basic
@Column(name = "user_company")
public String getUserCompany() {
return userCompany;
}
public void setUserCompany(String userCompany) {
this.userCompany = userCompany;
}
@Basic
@Column(name = "user_department")
public String getUserDepartment() {
return userDepartment;
}
public void setUserDepartment(String userDepartment) {
this.userDepartment = userDepartment;
}
@Basic
@Column(name = "work_number")
public String getWorkNumber() {
return workNumber;
}
public void setWorkNumber(String workNumber) {
this.workNumber = workNumber;
}
@Basic
@Column(name = "able_manage_user")
public String getAbleManageUser() {
return ableManageUser;
}
public void setAbleManageUser(String ableManageUser) {
this.ableManageUser = ableManageUser;
}
@Basic
@Column(name = "able_create_new_project")
public String getAbleCreateNewProject() {
return ableCreateNewProject;
}
public void setAbleCreateNewProject(String ableCreateNewProject) {
this.ableCreateNewProject = ableCreateNewProject;
}
@Basic
@Column(name = "able_examination_approval_project")
public String getAbleExaminationApprovalProject() {
return ableExaminationApprovalProject;
}
public void setAbleExaminationApprovalProject(String ableExaminationApprovalProject) {
this.ableExaminationApprovalProject = ableExaminationApprovalProject;
}
@Basic
@Column(name = "able_modify_project")
public String getAbleModifyProject() {
return ableModifyProject;
}
public void setAbleModifyProject(String ableModifyProject) {
this.ableModifyProject = ableModifyProject;
}
@Basic
@Column(name = "able_push_project")
public String getAblePushProject() {
return ablePushProject;
}
public void setAblePushProject(String ablePushProject) {
this.ablePushProject = ablePushProject;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserPermissionDO that = (UserPermissionDO) o;
return id == that.id &&
Objects.equals(userName, that.userName) &&
Objects.equals(userCompany, that.userCompany) &&
Objects.equals(userDepartment, that.userDepartment) &&
Objects.equals(workNumber, that.workNumber) &&
Objects.equals(ableManageUser, that.ableManageUser) &&
Objects.equals(ableCreateNewProject, that.ableCreateNewProject) &&
Objects.equals(ableExaminationApprovalProject, that.ableExaminationApprovalProject) &&
Objects.equals(ableModifyProject, that.ableModifyProject) &&
Objects.equals(ablePushProject, that.ablePushProject);
}
@Override
public int hashCode() {
return Objects.hash(id, userName, userCompany, userDepartment, workNumber, ableManageUser, ableCreateNewProject, ableExaminationApprovalProject, ableModifyProject, ablePushProject);
}
}
<file_sep>package com.duruo.vo.form;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/7/6 15:15
*
* @Email <EMAIL>
*/
@Data
public class PublicPlaceHealthPermitVO {
//申请人名称
private String applyName;
//经营地址
private String operatingAddress;
//主管部门
private String competentDepartment;
//经营总面积m2
private String totalArea;
//经济类型
private String economicType;
//所属街道
private String ownerStreet;
//所属社区-----+++++
private String ownerCommunity;
//姓名
private String personName;
//身份证
private String idCard;
//卫生负责人
private String headHealth;
//邮政编码
private String postalCode;
//联系电话
private String contactTel;
//职工总数
private String totalWorkers;
//直接为客户服务从业人员数
private String directCustomerEmploy;
//持健康合格证人数
private String healthCertificateNumber;
//经营范围
private String scopeBusiness;
//空调类型
private String airConditioningType;
//饮用水类别
private String drinkingWaterType;
//公共用具种类
private String publicUtensilsType;
//清洗方式
private String cleaningMethod;
//消毒方式
private String disinfectionMethod;
//使用一次性用具种类
private String disposableUtensilsType;
}
<file_sep>### 中心服务器短信接口+法人库+证照库
## 基本信息
1. 服务器windowServer2012
1. 项目地址C:\Users\zwww\Desktop\sqlAPP
#### 短信接口
url http://a323cca1.ngrok.io/sendSMS/sentMessage
#### 法人库 证照库
url http://a323cca1.ngrok.io/bildle/queryInfo**<file_sep><?php
function moderate_url($image_url){
$url = "https://www.moderatecontent.com/api/?url=" . $image_url;
$file_get_contents_result = file_get_contents($url);
if ($file_get_contents_result === false){
$file_get_contents_result = (object)array();
$file_get_contents_result->error_code = 9999;
$file_get_contents_result->error = "file_get_contents could not reach url.";
}
return json_encode($file_get_contents_result);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>ModerateContent.com - The FREE Content Moderation API</title>
</head>
<body style="font-family: verdana;">
<a href="https://www.moderatecontent.com" target="_blank"><img src="http://www.moderatecontent.com/img/logo.png" alt="ModerateContent.com" /></a><hr />
<h1>Example: PHP - file_get_contents && GET</h1>
<div id="this_is_where_we_put_the_results"><?php echo moderate_url("http://www.moderatecontent.com/img/logo.png"); ?></div>
</body>
</html>
<?php
die();<file_sep>spring.datasource.url=jdbc:mysql://localhost:3306/risk_assessment?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.database=MYSQL
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.format_sql=true
spring.jackson.serialization.indent-output=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.thymeleaf.cache=false
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
server.max-http-header-size=10000000
server.servlet.context-path=/risk_assessment
<file_sep>import urllib2
urllib2.urlopen("https://www.moderatecontent.com/api/?url=http://www.moderatecontent.com/img/logo.png").read()
<file_sep>package com.duruo.vo.form;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/7/9 10:29
*
* @Email <EMAIL>
*/
/**
* 法人一证通数字证书
*/
@Data
public class ElectronicDigitalVO {
//服务类型
private String serviceType;
//单位名称
private String unitName;
//单位邮寄地址
private String unitMailingAddress;
//邮政编码
private String postalCode;
//统一社会信用代码
private String unifiedCreditCode;
//工商营业执照注册号
private String businessLicenseNumber;
//住房公积金账号
private String accountOfHousing;
//组织机构代码证号
private String organizationCode;
//社会保险号
private String socialInsuranceNumber;
//单位法人代表姓名
private String legalRepresentative;
//法人代表身份证号码
private String legalIdCard;
//法人代表联系电话
private String legalLinkTel;
//办理人姓名
private String transactorName;
//办理人身份证号
private String transactorIdCard;
//办理人联系电话transactorlinkTel
private String transactorLinkTel;
//传真
private String fax;
//电子邮箱地址
private String email;
}
<file_sep>package com.example.demo.dao;
import com.example.demo.pojo.UserPermissionDO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Transactional
public interface UserPermissionDAO extends JpaRepository<UserPermissionDO,Long> {
void deleteById(int id);
@Modifying
@Query("update UserPermissionDO set "+
"ableManageUser=?1," +
"ableCreateNewProject=?2," +
"ableExaminationApprovalProject=?3," +
"ableModifyProject=?4," +
"ablePushProject=?5" +
" where id=?6"
)
int update(
String ableManageUser,
String ableCreateNewProject,
String ableExaminationApprovalProject,
String ableModifyProject,
String ablePushProject,
int id
);
@Modifying
@Query("update UserPermissionDO set "+
"userName=?1," +
"workNumber=?2" +
" where id=?3"
)
int updateUserbydepartment(
String userName,
String workNumber,
int id
);
@Query("select u from UserPermissionDO u order by u.workNumber desc ")
List<UserPermissionDO> findByorder();
@Query("select u from UserPermissionDO u where u.userCompany=?1 order by u.workNumber desc ")
List<UserPermissionDO> findbycompany(String d);
@Query("select u from UserPermissionDO u where u.id=?1")
UserPermissionDO findById( int id);
UserPermissionDO findByWorkNumber(String w);
@Query("select u from UserPermissionDO u where u.workNumber=:worknumber and u.ableCreateNewProject=:ableCreateNewProject")
List<UserPermissionDO> findByWorkNumberAndAbleCreateNewProject(@Param("worknumber") String a, @Param("ableCreateNewProject") String b);
List<UserPermissionDO> findDistinctByAbleCreateNewProjectAndAbleManageUser(String a,String b);
List<UserPermissionDO> findByWorkNumberNotLike(String a);
List<UserPermissionDO> findByAbleCreateNewProjectNot(String a);
}
<file_sep>package com.duruo.controller;
import com.duruo.common.ServerResponse;
import com.duruo.po.User;
import com.duruo.service.impl.UserServiceImpl;
import com.duruo.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
* Created by @Author tachai
* date 2018/12/4 9:19
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
@RequestMapping("/token/")
@Controller
public class TokenController {
@Autowired
private UserServiceImpl userService;
@ResponseBody
@RequestMapping("login.do")
public Map<String,String> login(String userName,String userPassword){
ServerResponse<User> response=userService.login(userName,userPassword);
Map<String,String > map = new HashMap<>();
if(response.isSuccess()){
// 登录成功 设置jwt
JWTUtils utils = new JWTUtils();
//设置信息
Map<String,Object> payload = new HashMap<>();
payload.put("user_id",response.getData().getUserId());
try {
String jwt = utils.createJWT("jwt","",600000,payload);
map.put("status","success");
map.put("token",jwt);
// map.put("user_id",response.getData().getUserId()+"");
return map;
} catch (Exception e) {
e.printStackTrace();
}
map.put("status","error");
map.put("msg","发生了错误");
return map;
}
map.put("status","error");
map.put("msg",response.getMsg());
return map;
}
@ResponseBody
@RequestMapping("test.do")
public Map<String,String> test(String content){
Map<String,String> map = new HashMap<>();
map.put("status","success");
map.put("content",content);
return map;
}
}
<file_sep>package com.example.demo.controller;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.model.InMessage;
import com.example.demo.model.OutMessage;
@Controller
public class GameInfoController {
@MessageMapping("/v1/chat")
@SendTo("/topic/game_chat")
public OutMessage gameInfo(InMessage message){
return new OutMessage(message.getContent());
}
}
<file_sep>package com.duruo.service;
import com.duruo.common.ServerResponse;
import com.duruo.po.PersonalInformationCollection;
/**
* Created by @Author tachai
* date 2018/7/27 14:56
*
* @Email <EMAIL>
*/
public interface IWebFormService {
ServerResponse<String> getPersionCollection(String weChatId, String matterName, PersonalInformationCollection personal);
}
<file_sep>package com.duruo.webserviceClient;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
//import org.apache.axiom.om.OMAbstractFactory;
//import org.apache.axiom.om.OMElement;
//import org.apache.axiom.om.OMFactory;
//import org.apache.axiom.om.OMNamespace;
//import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
//import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.rpc.client.RPCServiceClient;
import javax.xml.namespace.QName;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import java.util.HashMap;
import java.util.Map;
//import org.apache.axis.encoding.XMLType;
//import org.apache.axis.message.MessageElement;
//import org.apache.axis.message.SOAPHeaderElement;
//import org.apache.axis.types.Schema;
//
//import java.util.Date;
/**
* Created by @Author tachai
* date 2018/10/10 16:25
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
@Slf4j
public class WebServiceClient2 {
//public static final String targetEndpoint = "http://172.16.31.10:9080/WebUCP/webservices/UCPCXFService?wsdl";
public static final String targetEndpoint = "http://172.16.31.10:9080/WebUCP/webservices/UCPCXFService";
public static final String targetNamespace = "http://impl.cxf.service.webucp.wondersgroup.com";
// public static final String targetNamespace = "http://172.16.31.10:9080/WebUCP/webservices/UCPCXFService";
public static final String method = "login";
public static final String NAME = "weiruan";
public static final String PASSWORD = "<PASSWORD>";
public static String login() {
log.info("WebService发送请求......");
try {
RPCServiceClient client = new RPCServiceClient();
Options options = client.getOptions();
options.setTo(new EndpointReference(targetEndpoint));
options.setTimeOutInMilliSeconds(1000 * 60 * 5);// 毫秒单位
options.setAction(method);
Object[] response = client.invokeBlocking(new QName(targetNamespace, method), new Object[]{NAME,PASSWORD}, new Class[]{String.class});
String results = (String) response[0];
log.info("WebService请求返回结果: \r\n{}", results);
return results;
} catch (Exception e) {
log.error("WebService请求异常, Cause:{}, Message:{}", e.getCause(), e.getMessage());
e.printStackTrace();
return null;
}
}
public static String logoff(){
try {
// 直接引用远程的wsdl文件
// 以下都是套路
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(targetEndpoint);
call.setOperationName("login");// WSDL里面描述的接口名称
call.addParameter(new QName(targetNamespace,"account"),
org.apache.axis.encoding.XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);// 接口的参数
call.addParameter(new QName(targetNamespace,"password"),
org.apache.axis.encoding.XMLType.XSD_STRING,
javax.xml.rpc.ParameterMode.IN);
call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);// 设置返回类型
String temp = "weiruan";
String temp2 = "weiruan";
String result = (String) call.invoke(new QName(targetNamespace, method),new Object[] { "weiruan","weiruan"});
//String result = (String) call.invoke(new Object[] { "weiruan","weiruan"});
// 给方法传递参数,并且调用方法
System.out.println("result is " + result);
return result;
} catch (Exception e) {
System.err.println(e.toString());
return "发生了错误";
}
}
/**
* 立即发送短信
* @param sessionId
* @param content
* @param phoneNum
* @return
*/
public static String sentMessage(String sessionId,String content,String phoneNum){
log.info("WebService发送请求......");
try {
RPCServiceClient client = new RPCServiceClient();
Options options = client.getOptions();
options.setTo(new EndpointReference(targetEndpoint));
options.setTimeOutInMilliSeconds(1000 * 60 * 5);// 毫秒单位
options.setAction("sendProxySMS");
Object[] response = client.invokeBlocking(new QName(targetNamespace, "sendProxySMS"), new Object[]{sessionId,phoneNum,content}, new Class[]{String.class});
String results = (String) response[0];
log.info("WebService请求返回结果: \r\n{}", results);
return results;
} catch (Exception e) {
log.error("WebService请求异常, Cause:{}, Message:{}", e.getCause(), e.getMessage());
e.printStackTrace();
return null;
}
}
/**
* 发送短信
* @param sessionId
* @param receiveNumbers
* @param content
* @return
*/
public static String sendSMS(String sessionId,String receiveNumbers,String content){
log.info("WebService发送请求......");
try {
RPCServiceClient client = new RPCServiceClient();
Options options = client.getOptions();
options.setTo(new EndpointReference(targetEndpoint));
options.setTimeOutInMilliSeconds(1000 * 60 * 5);// 毫秒单位
options.setAction("sendSMS");
Object[] response = client.invokeBlocking(new QName(targetNamespace, "sendSMS"), new Object[]{sessionId,"NORM",receiveNumbers,null,content,null,false}, new Class[]{String.class});
String results = (String) response[0];
log.info("WebService请求返回结果: \r\n{}", results);
return results;
} catch (Exception e) {
log.error("WebService请求异常, Cause:{}, Message:{}", e.getCause(), e.getMessage());
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
// String mm = login();
// //String mm = logoff();
//
// String ss = sentMessage(mm,"日了狗,一首凉凉","13767094798");
//
// //用不了
// //String ll = sendSMS(mm,"13767094798","日了狗");
//
// System.out.println(ss);
//System.out.println(ss);
Map<String,String> query= new HashMap<>();
query.put("queryInfo","91310104MA1FR74W65");
String data = new Gson().toJson(query);
System.out.println(data);
}
}
<file_sep>package com.duruo.webserviceClient.xuhuisms;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by Apache CXF 2.2.5
* Mon Oct 08 14:24:48 CST 2018
* Generated source version: 2.2.5
*
*/
@WebService(targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", name = "UCPCXFService")
@XmlSeeAlso({ObjectFactory.class})
public interface UCPCXFService {
@RequestWrapper(localName = "logoff", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.Logoff")
@ResponseWrapper(localName = "logoffResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.LogoffResponse")
@WebMethod
public void logoff(
@WebParam(name = "arg0", targetNamespace = "")
String arg0
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "sendHugeSms", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendHugeSms")
@ResponseWrapper(localName = "sendHugeSmsResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendHugeSmsResponse")
@WebMethod
public String sendHugeSms(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1,
@WebParam(name = "arg2", targetNamespace = "")
String arg2,
@WebParam(name = "arg3", targetNamespace = "")
javax.xml.datatype.XMLGregorianCalendar arg3,
@WebParam(name = "arg4", targetNamespace = "")
String arg4,
@WebParam(name = "arg5", targetNamespace = "")
String arg5
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "getNotificationList", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetNotificationList")
@ResponseWrapper(localName = "getNotificationListResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetNotificationListResponse")
@WebMethod
public byte[] getNotificationList(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "login", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.Login")
@ResponseWrapper(localName = "loginResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.LoginResponse")
@WebMethod
public String login(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "receiveSMS", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.ReceiveSMS")
@ResponseWrapper(localName = "receiveSMSResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.ReceiveSMSResponse")
@WebMethod
public byte[] receiveSMS(
@WebParam(name = "arg0", targetNamespace = "")
String arg0
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "sendSpSMS", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendSpSMS")
@ResponseWrapper(localName = "sendSpSMSResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendSpSMSResponse")
@WebMethod
public String sendSpSMS(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1,
@WebParam(name = "arg2", targetNamespace = "")
String arg2,
@WebParam(name = "arg3", targetNamespace = "")
javax.xml.datatype.XMLGregorianCalendar arg3,
@WebParam(name = "arg4", targetNamespace = "")
String arg4,
@WebParam(name = "arg5", targetNamespace = "")
String arg5,
@WebParam(name = "arg6", targetNamespace = "")
boolean arg6,
@WebParam(name = "arg7", targetNamespace = "")
String arg7
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "getNotifications", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetNotifications")
@ResponseWrapper(localName = "getNotificationsResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetNotificationsResponse")
@WebMethod
public byte[] getNotifications(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "getSendRequestId", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetSendRequestId")
@ResponseWrapper(localName = "getSendRequestIdResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetSendRequestIdResponse")
@WebMethod
public String getSendRequestId(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "getSendMessageIdByTaskId", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetSendMessageIdByTaskId")
@ResponseWrapper(localName = "getSendMessageIdByTaskIdResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetSendMessageIdByTaskIdResponse")
@WebMethod
public String getSendMessageIdByTaskId(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "getReceiveFileAttachment", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetReceiveFileAttachment")
@ResponseWrapper(localName = "getReceiveFileAttachmentResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetReceiveFileAttachmentResponse")
@WebMethod
public byte[] getReceiveFileAttachment(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "getSendMessageIdByRequestId", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetSendMessageIdByRequestId")
@ResponseWrapper(localName = "getSendMessageIdByRequestIdResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.GetSendMessageIdByRequestIdResponse")
@WebMethod
public String getSendMessageIdByRequestId(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "sendProxySMS", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendProxySMS")
@ResponseWrapper(localName = "sendProxySMSResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendProxySMSResponse")
@WebMethod
public String sendProxySMS(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1,
@WebParam(name = "arg2", targetNamespace = "")
String arg2
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "sendSMS", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendSMS")
@ResponseWrapper(localName = "sendSMSResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendSMSResponse")
@WebMethod
public String sendSMS(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1,
@WebParam(name = "arg2", targetNamespace = "")
String arg2,
@WebParam(name = "arg3", targetNamespace = "")
javax.xml.datatype.XMLGregorianCalendar arg3,
@WebParam(name = "arg4", targetNamespace = "")
String arg4,
@WebParam(name = "arg5", targetNamespace = "")
String arg5,
@WebParam(name = "arg6", targetNamespace = "")
boolean arg6
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "sendVoice", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendVoice")
@ResponseWrapper(localName = "sendVoiceResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendVoiceResponse")
@WebMethod
public String sendVoice(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1,
@WebParam(name = "arg2", targetNamespace = "")
String arg2,
@WebParam(name = "arg3", targetNamespace = "")
javax.xml.datatype.XMLGregorianCalendar arg3,
@WebParam(name = "arg4", targetNamespace = "")
String arg4,
@WebParam(name = "arg5", targetNamespace = "")
String arg5,
@WebParam(name = "arg6", targetNamespace = "")
String arg6,
@WebParam(name = "arg7", targetNamespace = "")
boolean arg7
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "checkSession", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.CheckSession")
@ResponseWrapper(localName = "checkSessionResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.CheckSessionResponse")
@WebMethod
public String checkSession(
@WebParam(name = "arg0", targetNamespace = "")
String arg0
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "sendEmail", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendEmail")
@ResponseWrapper(localName = "sendEmailResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendEmailResponse")
@WebMethod
public String sendEmail(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1,
@WebParam(name = "arg2", targetNamespace = "")
String arg2,
@WebParam(name = "arg3", targetNamespace = "")
javax.xml.datatype.XMLGregorianCalendar arg3,
@WebParam(name = "arg4", targetNamespace = "")
String arg4,
@WebParam(name = "arg5", targetNamespace = "")
String arg5,
@WebParam(name = "arg6", targetNamespace = "")
String arg6,
@WebParam(name = "arg7", targetNamespace = "")
String arg7,
@WebParam(name = "arg8", targetNamespace = "")
String arg8,
@WebParam(name = "arg9", targetNamespace = "")
boolean arg9
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "sendFax", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendFax")
@ResponseWrapper(localName = "sendFaxResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.SendFaxResponse")
@WebMethod
public String sendFax(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1,
@WebParam(name = "arg2", targetNamespace = "")
String arg2,
@WebParam(name = "arg3", targetNamespace = "")
String arg3,
@WebParam(name = "arg4", targetNamespace = "")
javax.xml.datatype.XMLGregorianCalendar arg4,
@WebParam(name = "arg5", targetNamespace = "")
String arg5,
@WebParam(name = "arg6", targetNamespace = "")
String arg6,
@WebParam(name = "arg7", targetNamespace = "")
String arg7,
@WebParam(name = "arg8", targetNamespace = "")
String arg8,
@WebParam(name = "arg9", targetNamespace = "")
String arg9,
@WebParam(name = "arg10", targetNamespace = "")
boolean arg10
);
@WebResult(name = "return", targetNamespace = "")
@RequestWrapper(localName = "receive", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.Receive")
@ResponseWrapper(localName = "receiveResponse", targetNamespace = "http://cxf.service.webucp.wondersgroup.com/", className = "xuhuisms.ReceiveResponse")
@WebMethod
public byte[] receive(
@WebParam(name = "arg0", targetNamespace = "")
String arg0,
@WebParam(name = "arg1", targetNamespace = "")
String arg1,
@WebParam(name = "arg2", targetNamespace = "")
String arg2
);
}
<file_sep>package com.duruo.dao;
import com.duruo.po.User;
import com.duruo.po.UserPo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Integer userId);
int insert(UserPo record);
int insertSelective(UserPo record);
UserPo selectByPrimaryKey(Integer userId);
int updateByPrimaryKeySelective(UserPo record);
int updateByPrimaryKey(UserPo record);
User selectLogin(@Param("userName") String userName, @Param("userPassword") String userPassWord);
int checkUsername(String userName);
List<UserPo> selectByCondition(UserPo user);
int updatePassword(@Param("newPassword") String newPassword,@Param("userId") Integer userId);
}<file_sep>package com.example.demo.controller;
import com.example.demo.dao.*;
import com.example.demo.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Controller
@EnableAutoConfiguration
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserDAO userDAO;
@Autowired
private CompanyDAO companyDAO;
@Autowired
private FirstLevelRiskDAO firstLevelRiskDAO;
@Autowired
private SecondLevelRiskDAO secondLevelRiskDAO;
@Autowired
private ThirdLevelRiskDAO thirdLevelRiskDAO;
@Autowired
private FourthLevelRiskDAO fourthLevelRiskDAO;
@Autowired
private UserPermissionDAO userPermissionDAO;
@Autowired
private RiskEventLibraryDAO riskEventLibraryDAO;
@Autowired
private RiskDefinationDAO riskDefinationDAO;
@Autowired
private RulesRegulationsDAO rulesRegulationsDAO;
@RequestMapping(value = "/user_add")
public String userAddPage(Model model) {
UserDO uo = new UserDO();
model.addAttribute("uo", uo);
model.addAttribute("company",companyDAO.findAll());
return "register";
}
@RequestMapping(value = "/doadd")
public String userAdd(Model model,@ModelAttribute(value = "uo") UserDO userDO,HttpSession session) {
List<UserDO> userDOList=userDAO.findAll();
String username=userDO.getUsername();
System.out.println(username);
for (UserDO userDO1:userDOList){
System.out.println(userDO1.getUsername());
if(userDO1.getUsername().equals(username)){
System.out.println("+++++++++++++++++++++++++++++++++++++"+"用户已存在");
UserDO uo = new UserDO();
model.addAttribute("uo", uo);
model.addAttribute("company",companyDAO.findAll());
model.addAttribute("user_name_exist",1);
return "register";
}
}
for (UserDO userDO1:userDOList){
if(userDO1.getWorkNumber().equals(userDO.getWorkNumber())){
UserDO uo = new UserDO();
model.addAttribute("uo", uo);
model.addAttribute("company",companyDAO.findAll());
model.addAttribute("user_WorkNumber_exist",1);
return "register";
}
}
userDO.setId(0);
String a = "1";
String b = "2";
String c = "3";
String d = "4";
String e = "5";
String f = "6";
String worknum = userDO.getWorkNumber();
String company = userDO.getUserCompany();
String department = userDO.getDepartment();
if (a.equals(worknum.substring(0, 1))) {
userDO.setPermission(1);
userDO.setMenuRole("初级用户");
} else if (b.equals(worknum.substring(0, 1))) {
userDO.setPermission(2);
userDO.setMenuRole("高级用户");
} else if (c.equals(worknum.substring(0, 1))) {
userDO.setPermission(3);
userDO.setMenuRole("初级管理员");
} else if (d.equals(worknum.substring(0, 1))) {
userDO.setPermission(4);
userDO.setMenuRole("中级管理员");
} else if (e.equals(worknum.substring(0, 1))) {
userDO.setPermission(5);
userDO.setMenuRole("高级管理员");
} else if (f.equals(worknum.substring(0, 1))) {
userDO.setPermission(6);
userDO.setMenuRole("顶级管理员");
}
userDO.setUserGroup("中华纸业");
userDO.setStatus("在职");
userDAO.save(userDO);
int userpermission = userDO.getPermission();
UserPermissionDO userPermissionDO = new UserPermissionDO();
userPermissionDO.setId(0);
userPermissionDO.setWorkNumber(worknum);
userPermissionDO.setUserName(username);
userPermissionDO.setUserCompany(company);
userPermissionDO.setUserDepartment(department);
userDO.setWorkNumber(worknum);
System.out.println(userDO.getPermission());
if (userpermission == 1) {
userPermissionDO.setAbleManageUser("不能");
userPermissionDO.setAbleCreateNewProject("不能");
userPermissionDO.setAbleExaminationApprovalProject("不能");
userPermissionDO.setAbleModifyProject("能");
userPermissionDO.setAblePushProject("不能");
userPermissionDAO.save(userPermissionDO);
model.addAttribute("username",userDO.getUsername());
model.addAttribute("password",<PASSWORD>());
return "register_success";
} else if (userpermission == 2) {
userPermissionDO.setAbleManageUser("不能");
userPermissionDO.setAbleCreateNewProject("不能");
userPermissionDO.setAbleExaminationApprovalProject("不能");
userPermissionDO.setAbleModifyProject("能");
userPermissionDO.setAblePushProject("能");
userPermissionDAO.save(userPermissionDO);
model.addAttribute("username",userDO.getUsername());
model.addAttribute("password",<PASSWORD>());
return "register_success";
} else if (userpermission == 3 | userpermission == 4 ) {
userPermissionDO.setAbleManageUser("能");
userPermissionDO.setAbleCreateNewProject("不能");
userPermissionDO.setAbleExaminationApprovalProject("不能");
userPermissionDO.setAbleModifyProject("不能");
userPermissionDO.setAblePushProject("不能");
userPermissionDAO.save(userPermissionDO);
model.addAttribute("username",userDO.getUsername());
model.addAttribute("password",<PASSWORD>());
return "register_success";
} else if(userpermission == 5 | userpermission == 6){
userPermissionDO.setAbleManageUser("能");
userPermissionDO.setAbleCreateNewProject("不能");
userPermissionDO.setAbleExaminationApprovalProject("不能");
userPermissionDO.setAbleModifyProject("不能");
userPermissionDO.setAblePushProject("不能");
userPermissionDAO.save(userPermissionDO);
model.addAttribute("username",userDO.getUsername());
model.addAttribute("password",<PASSWORD>());
return "register_success";
}
return null;
}
@RequestMapping(value = "/department_doadd")
public String department_doadd(final RedirectAttributes redirectAttributes, @ModelAttribute(value = "uo") UserDO userDO, HttpSession session) {
UserDO user=(UserDO)session.getAttribute("user");
List<UserDO> userDOList=userDAO.findByDepartment(user.getDepartment());
String username=userDO.getUsername();
System.out.println(username);
for (UserDO userDO1:userDOList){
System.out.println(userDO1.getUsername());
if(userDO1.getUsername().equals(username)){
redirectAttributes.addFlashAttribute("add_failure","用户名已存在!");
return "redirect:/user/user_management";
}
}
for (UserDO userDO1:userDOList){
if(userDO1.getWorkNumber().equals(userDO.getWorkNumber())){
redirectAttributes.addFlashAttribute("add_failure","工号已存在!");
return "redirect:/user/user_management";
}
}
userDO.setId(0);
String a = "1";
String b = "2";
String c = "3";
String d = "4";
String e = "5";
String f = "6";
String worknum = userDO.getWorkNumber();
String company = user.getUserCompany();
String department = user.getDepartment();
if (a.equals(worknum.substring(0, 1))) {
userDO.setPermission(1);
userDO.setMenuRole("初级用户");
} else if (b.equals(worknum.substring(0, 1))) {
userDO.setPermission(2);
userDO.setMenuRole("高级用户");
} else if (c.equals(worknum.substring(0, 1))) {
userDO.setPermission(3);
userDO.setMenuRole("初级管理员");
} else if (d.equals(worknum.substring(0, 1))) {
userDO.setPermission(4);
userDO.setMenuRole("中级管理员");
} else if (e.equals(worknum.substring(0, 1))) {
userDO.setPermission(5);
userDO.setMenuRole("高级管理员");
} else if (f.equals(worknum.substring(0, 1))) {
userDO.setPermission(6);
userDO.setMenuRole("顶级管理员");
}
userDO.setUserGroup("中华纸业");
userDO.setStatus("在职");
userDO.setDepartment("风控部");
userDO.setUserCompany(company);
userDO.setPosition("普通员工");
userDAO.save(userDO);
int userpermission = userDO.getPermission();
UserPermissionDO userPermissionDO = new UserPermissionDO();
userPermissionDO.setId(0);
userPermissionDO.setWorkNumber(worknum);
userPermissionDO.setUserName(username);
userPermissionDO.setUserCompany(company);
userPermissionDO.setUserDepartment(department);
userDO.setWorkNumber(worknum);
System.out.println(userDO.getPermission());
UserDO userDO1=new UserDO();
userPermissionDAO.save(userPermissionDO);
redirectAttributes.addFlashAttribute("add_success","用户 "+username);
return "redirect:/user/user_management";
}
@RequestMapping(value = "/register_success")
public String register_success(HttpSession session, Model model){
return "register_success";
}
@RequestMapping(value = "/user_information")
public String user_information(HttpSession session, Model model){
UserDO user=(UserDO)session.getAttribute("user");
int id = user.getId();
UserDO userDO = userDAO.getById(id);
model.addAttribute("uo",userDO);
model.addAttribute("user",user);
model.addAttribute("success",1);
model.addAttribute("company",companyDAO.findAll());
return "user_information";
}
@RequestMapping(value = "/personal_information_del_success/{id}")
public String personal_information_del_success(@PathVariable(value = "id") int did,Model model,HttpSession session){
UserDO user=(UserDO)session.getAttribute("user");
int id = user.getId();
UserDO userDO = userDAO.getById(id);
model.addAttribute("uo",userDO);
model.addAttribute("user",user);
model.addAttribute("success",1);
model.addAttribute("usermanagement",userDAO.findByDepartment(user.getDepartment()));
model.addAttribute("del_user_name",1);
return "用户信息";
}
//
@RequestMapping(value = "/add")
public String add(Model model,@ModelAttribute(value = "uo") UserDO userDO,HttpSession session){
userDO.setId(0);
userDO.setPermission(2);
userDO.setUserGroup("集团");
userDAO.save(userDO);
model.addAttribute("company",companyDAO.findAll());
FirstLevelRiskDO firstLevelRiskDO = new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
model.addAttribute("ready_first_level",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("first_level_pass",firstLevelRiskDAO.findBystatus("审批通过"));
model.addAttribute("first_level_publish",firstLevelRiskDAO.findBystatus("已发布"));
model.addAttribute("first_level_ing",firstLevelRiskDAO.findBystatus("审批中"));
model.addAttribute("first_level_failure",firstLevelRiskDAO.findBystatus("审批失败"));
CompanyDO companyDO=new CompanyDO();
model.addAttribute("co",companyDO);
UserDO user=(UserDO)session.getAttribute("user");
Date date = new Date();
UserDO userDO1=new UserDO();
model.addAttribute("uo",userDO1);
model.addAttribute("user",userDAO.findAll());
Timestamp nousedate = new Timestamp(date.getTime());
model.addAttribute("user_add_success",1);
model.addAttribute("worknum",user.getWorkNumber());
return "group_user_management";
}
@RequestMapping(value = "/del/{id}")
public String del(Model model, HttpSession session,@PathVariable(value = "id") int id){
String username= userDAO.getById(id).getUsername();
int pid =userPermissionDAO.findByWorkNumber(userDAO.getById(id).getWorkNumber()).getId();
userDAO.deleteById(id);
userPermissionDAO.deleteById(pid);
UserDO user=(UserDO)session.getAttribute("user");
UserDO userDO=new UserDO();
model.addAttribute("uo",userDO);
model.addAttribute("user",userDAO.findbycompany(user.getUserCompany()));
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
model.addAttribute("user_del_success",1);
return "user_management";
}
@RequestMapping(value = "/edit/{id}")
public String edit(Model model, HttpSession session, @PathVariable(value = "id") int id){
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("id",id);
model.addAttribute("uo1",userDAO.getById(id));
System.out.println("++++++++++++++++++++++++++++++"+userDAO.getById(id).getPassword());
model.addAttribute("user_edit",1);
UserDO userDO=new UserDO();
model.addAttribute("uo",userDO);
model.addAttribute("user",userDAO.findbycompany(user.getUserCompany()));
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
model.addAttribute("password",userDAO.getById(id).getPassword());
return "user_management";
}
@RequestMapping(value = "/update/{id}")
public String update(Model model, HttpSession session, @ModelAttribute(value = "uo1") UserDO userDO,@PathVariable(value = "id") int id){
UserDO user=(UserDO)session.getAttribute("user");
String workNumber=userDAO.getById(id).getWorkNumber();
userDAO.updateUserbydepartment(userDO.getUsername(),userDO.getPassword(),userDO.getWorkerName(),workNumber,id);
int pid =userPermissionDAO.findByWorkNumber(workNumber).getId();
userPermissionDAO.updateUserbydepartment(userDO.getUsername(),workNumber,pid);
UserDO userDO1=new UserDO();
model.addAttribute("uo",userDO1);
model.addAttribute("user_update_success",1);
model.addAttribute("user",userDAO.findbycompany(user.getUserCompany()));
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
return "user_management";
}
@RequestMapping(value = "user_update")
public String user_update(Model model, HttpSession session, @ModelAttribute(value = "uo") UserDO userDO){
UserDO user=(UserDO)session.getAttribute("user");
int id = user.getId();
String workNumber=user.getWorkNumber();
System.out.println(userDO.getId());
userDAO.updateUser(userDO.getUsername(),userDO.getPassword(),userDO.getUserEmail(),userDO.getMobilePhone(),userDO.getUserAddress(),userDO.getUserMessage(),id);
int pid =userPermissionDAO.findByWorkNumber(workNumber).getId();
userPermissionDAO.updateUserbydepartment(userDO.getUsername(),workNumber,pid);
UserDO userDO1=userDAO.getById(id);
model.addAttribute("uo",userDO1);
model.addAttribute("user",user);
model.addAttribute("user_update_success",1);
return "user_information";
}
@RequestMapping(value = "/user_management")
public String user(Model model,HttpSession session){
model.addAttribute("company",companyDAO.findAll());
CompanyDO companyDO=new CompanyDO();
UserDO userDO=new UserDO();
UserDO user=(UserDO)session.getAttribute("user");
model.addAttribute("uo",userDO);
model.addAttribute("user_permission",user.getPermission());
model.addAttribute("user",userDAO.findbycompany(user.getUserCompany()));
model.addAttribute("permission",userPermissionDAO.findbycompany(user.getUserCompany()));
model.addAttribute("ableManageUser",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleManageUser());
model.addAttribute("ableCreateNewProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleCreateNewProject());
model.addAttribute("ableExaminationApprovalProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleExaminationApprovalProject());
model.addAttribute("ableModifyProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAbleModifyProject());
model.addAttribute("ablePushProject",userPermissionDAO.findByWorkNumber(user.getWorkNumber()).getAblePushProject());
model.addAttribute("worknum",user.getWorkNumber());
return "user_management";
}
@RequestMapping(value = "/search")
public String search(Model model,HttpSession session,@RequestParam(value = "condition") String condition,@RequestParam(value = "value") String value){
UserDO user=(UserDO)session.getAttribute("user");
Date date = new Date();
List<FirstLevelRiskDO> firstLevelRiskDOS=new ArrayList<>();
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("岳阳林纸")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("红塔仁恒")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("凯胜园林")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
for(FirstLevelRiskDO firstLevelRiskDO:firstLevelRiskDAO.findBycompany("冠豪高新")) {
firstLevelRiskDOS.add(firstLevelRiskDO);
}
List<UserDO> userDOList=new ArrayList<>();
if(condition.equals("用户名")){
for(UserDO userDO:userDAO.findbynamelike(value,"岳阳林纸")) {
userDOList.add(userDO);
}
for(UserDO userDO1:userDAO.findbynamelike(value,"凯胜园林")) {
userDOList.add(userDO1);
}
for(UserDO userDO2:userDAO.findbynamelike(value,"冠豪高新")) {
userDOList.add(userDO2);
}
for(UserDO userDO3:userDAO.findbynamelike(value,"红塔仁恒")) {
userDOList.add(userDO3);
}
}else if(condition.equals("公司")){
for(UserDO userDO:userDAO.findbycompanylike(value)) {
userDOList.add(userDO);
}
}else if(condition.equals("部门")){
for(UserDO userDO:userDAO.findbydepartmentlike(value,"岳阳林纸")) {
userDOList.add(userDO);
}
for(UserDO userDO1:userDAO.findbydepartmentlike(value,"凯胜园林")) {
userDOList.add(userDO1);
}
for(UserDO userDO2:userDAO.findbydepartmentlike(value,"冠豪高新")) {
userDOList.add(userDO2);
}
for(UserDO userDO3:userDAO.findbydepartmentlike(value,"红塔仁恒")) {
userDOList.add(userDO3);
}
}else if(condition.equals("手机号")){
for(UserDO userDO:userDAO.findbymobilePhonelike(value,"岳阳林纸")) {
userDOList.add(userDO);
}
for(UserDO userDO1:userDAO.findbymobilePhonelike(value,"凯胜园林")) {
userDOList.add(userDO1);
}
for(UserDO userDO2:userDAO.findbymobilePhonelike(value,"冠豪高新")) {
userDOList.add(userDO2);
}
for(UserDO userDO3:userDAO.findbymobilePhonelike(value,"红塔仁恒")) {
userDOList.add(userDO3);
}
}
FirstLevelRiskDO firstLevelRiskDO=new FirstLevelRiskDO();
model.addAttribute("fo",firstLevelRiskDO);
model.addAttribute("first_ready",firstLevelRiskDAO.findBycompany("未分配"));
model.addAttribute("user",userDOList);
model.addAttribute("search",1);
model.addAttribute("first_finish",firstLevelRiskDOS);
return "project_allocation";
}
}<file_sep>function textNodesUnder(el){
var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
while(n=walk.nextNode()) a.push(n);
return a;
}
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
function nodesToArray(nodeList) {
if (!(nodeList) instanceof NodeList) return [];
return Array.prototype.slice.call(nodeList, 0);
}
function selectAll(selector) {
return document.querySelectorAll(selector);
}
function select(selector) {
return document.querySelector(selector);
}
function parseURL(url) {
var parser = document.createElement('a'),
searchObject = {},
queries, split, i;
// Let the browser do the work
parser.href = url;
// Convert query string to object
queries = parser.search.replace(/^\?/, '').split('&');
for( i = 0; i < queries.length; i++ ) {
if (!queries[i]) continue;
split = queries[i].split('=');
searchObject[split[0]] = split[1];
}
return {
protocol: parser.protocol,
host: parser.host,
hostname: parser.hostname,
port: parser.port,
pathname: parser.pathname,
search: parser.search,
searchObject: searchObject,
hash: parser.hash
};
}
function toQueryString(obj) {
var parts = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
}
}
return parts.join("&");
}
// Turn raw keywords configuration to keywards array
function processRawKeywords (input) {
var separators = ',,;; '.split('');
var keywords = [];
if (!input || !input.trim()) return keywords;
var lines = input.replace("\r", "").split("\n").filter(function (line) {
return !line.startsWith('-') && !!line.trim();
});
lines.forEach(function (line) {
var words = line.split(new RegExp(separators.join('|')))
.map(function (item) { return item.trim(); })
.filter(function (item) { return !!item; });
keywords = keywords.concat(words);
});
return keywords;
}
function toAmazon(node) {
var parts = parseURL(node.href);
if (parts.pathname.indexOf('ref=') === -1) {
parts.pathname += '/ref=as_li_ss_tl'
} else {
parts.pathname = parts.pathname.replace(/ref=.+$/, "ref=as_li_ss_tl");
}
parts.searchObject.tag = 'zhihu02-23';
parts.searchObject.linkCode = 'as2';
parts.searchObject.camp = '536';
parts.searchObject.creative = '3132';
node.href = ''.concat(
parts.protocol,
'//',
parts.hostname,
parts.pathname,
'?',
toQueryString(parts.searchObject),
parts.hash
);
}
function toITunes(node) {
var parts = parseURL(node.href);
parts.searchObject.at = '1010l9jL';
node.href = ''.concat(
parts.protocol,
'//',
parts.hostname,
parts.pathname,
'?',
toQueryString(parts.searchObject),
parts.hash
);
}
var defaultRawKeywords = `
男神,女神,女汉子,黑木耳,粉木耳,婊,长发及腰,颜值,颜扣
撕逼,傻逼,傻逼,装逼,基情,基友,屌丝,捡肥皂,直男癌,小鲜肉
呵呵哒,么么哒,萌萌哒,草泥马,卧槽,次奥,操你,尼玛,呵呵
真心,走心,讲真,走肾,有钱,任性,duang
粑粑,麻麻,乃们,伦家,母上大人,射射,肿么,醉了,这货,给跪了
碉堡,约炮,然并卵,正能量,高端大气,叶良辰,高端大气,霸气侧漏
神马,有木有,伤不起,你懂的,然后就没有然后,钱途,即视感
元芳,你怎么看,认真你就,不觉明厉,不动然拒,细思极恐,注孤生,的节奏
`.trim();
// var brandIcon = '✿';
var brandIcon = '.';
var strategies = {
'hideMatchingWords': {label: '隐藏匹配词'},
'hideMatchingBlock': {label: '隐藏整块文字'}
};
var defaultStrategy = 'hideMatchingBlock';
<file_sep>
// 引入 ajax
import { getUri } from 'src/config/gwConfig';
import { notifyAjaxWithoutAction } from 'src/config/usualAjax';
// 引入 缓存等
import { storage } from 'src/config/storageConfig';
import STORAGE from 'src/localStorage/index';
import { cookie } from 'src/config/cookie';
import COOKIE from 'src/cookie/index';
// ajax 模板
const vm = this;
const param = {};
notifyAjaxWithoutAction({
vm, param, url: getUri(''), method: 'get', handle: 'aaa',
before() { vm.loading = true; },
success(res) {},
after() { vm.loading = false; }
});
<file_sep>import Vue from 'vue';
import Vuex from 'vuex';
import globalUse from './modules/global';
import beginSettle from './modules/beginSettle';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
globalUse, // 公用
beginSettle // 开始结算
}
});
<file_sep>/**
*
*
*/
window.ZLSH = window.ZLSH || {};
ZLSH.shenhe = (function($){
var url1 = 'http://shenhe.video.qq.com/fcgi-bin/audit_locked_video'; //审核
var url2 = 'http://shenhe.video.qq.com/fcgi-bin/reset_audited_video'; //重置
/**
* param = {type:0, videoArr:[], callback: fn}
*
*/
function shenhe(param){
if(!param || !$.isArray(param.videoArr) || param.videoArr.length==0) return;
param.type = param.type || 0;
if(0 == param.type){
audit(param);
}else{
reset(param);
}
}
/**
* 审核视频
*/
function audit(param){
action(url1, param);
}
/**
* 修改已审核过的视频
*
*/
function reset(param){
action(url2, param);
}
function action(url, param){
var varr = param.videoArr;
$.ajax({
url : url+'?g_tk='+$.getToken(), //需要检验csrf
data : {
value : JSON.stringify(varr),
otype : 'json'
},
type : 'post',
dataType : 'jsonp',
error : function(e){
if($.isFunction(param.error)){
param.error(e);
}
},
success : function(json){
if(!json || json.returncode != 0){
if($.isFunction(param.error)){
param.error(json);
}
}else{
if($.isFunction(param.success)){
param.success(json);
}
}
}
});
}
return {
shenhe : shenhe
};
})(jQuery);<file_sep># ArtificialReview
## 说明
> 基于Spring+SpringMVC+MyBatis的人工审核系统后台
> 联系人邮箱:<EMAIL>
> gitHub[地址](https://github.com/TACHAI/ArtificialReviewSystem)
## 项目介绍
该项目包括事项材料接收审核,青创事项的网上办理,科委的研发加计扣除的无障碍数据采集和数据回填
微信、一网通、自助机的聊天接口
### 项目地址
[地址](https://can.xmduruo.com:4000/login.html) https://can.xmduruo.com:4000/login.html
### 组织结构
```lua
Articial
|--lib
|--src
|--main
|--java
|--com.baidu.ai.api--百度通用图像(包括人脸,身份证,银行卡,文档图片等)api的封装
|--auth
|--ocr
|--utils
|--com.duruo
|--commmon--通用接口过滤器等
|--controller--前台数据接口
|--dao--数据访问层
|--dto--内部数据转换层
|--po--表实体对象
|--service--业务逻辑层
|--util--工具类
|--vo--视图视图层
|--webserviceClient--webservice访问层
|--resources
|--webapp
|--pom.xml
```
## 环境搭建
### 开发工具
工具|说明|官网
----|----|----
IDEA|开发IDE|https://www.jetbrains.com/idea/download
X-shell|Linux远程连接工具| http://www.netsarang.com/download/software.html
Navicat|数据库连接工具|http://www.formysql.com/xiazai.html
### 开发环境
工具|版本号|下载
----|----|----
JDK|1.8| https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
Mysql|5.7|https://www.mysql.com/
Tomcat|8.5|
nginx|1.10|http://nginx.org/en/download.html
<file_sep>package com.duruo.vo;
import com.duruo.po.*;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/9/25 19:52
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
//这里是给页面展现用的
@Data
public class QchaungVO extends com.duruo.po.Qchuang {
private String age;
private String applyDate;
private String applyDate1;
}
<file_sep>package com.example.demo.service;
import com.example.demo.dao.ArticleDAO;
import com.example.demo.dao.CompanyDAO;
import com.example.demo.pojo.ArticleDO;
import com.example.demo.pojo.CompanyDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Transactional
@Service
public class ArticleServiceimpl implements ArticleService {
@Autowired
private ArticleDAO articleDAO;
@Override
public ArticleDO saveArticle(ArticleDO articleDO) {
return articleDAO.save(articleDO);
}
@Override
public ArticleDO updateArticle(ArticleDO articleDO) {
return articleDAO.saveAndFlush(articleDO);
}
@Override
public ArticleDO findArticle(int id) {
return articleDAO.findById(id);
}
@Override
public void deleteArticle(int id) {
articleDAO.deleteById(id);
}
}
<file_sep>/**
* 格式化时间
*
* @param {String} str
* @returns 格式化后的时间
*/
/* eslint-disable */
export const formatTime = (date, transform) => {
if( !date ){
date = new Date();
} else if( typeof date == 'number' ){
date = new Date( date );
} else if( isNaN(Date.parse(date)) ){
date = new Date( Date.parse(date.replace(/-/g, "/")));
} else{
date = new Date( Date.parse(date) );
}
transform = transform || 'yyyy-MM-dd HH:mm:ss';
const mon = date.getMonth() + 1,
dd = date.getDate(),
hh = date.getHours(),
mm = date.getMinutes(),
ss = date.getSeconds();
const year = date.getFullYear(),
month = mon < 10 ? '0' + mon : mon,
day = dd < 10 ? '0' + dd : dd,
hour = hh < 10 ? '0' + hh : hh,
minute = mm < 10 ? '0' + mm : mm,
second = ss < 10 ? '0' + ss : ss;
transform = transform.replace('yyyy',year)
.replace('MM',month).replace('dd',day)
.replace('HH',hour).replace('mm',minute)
.replace('ss', second);
return transform;
};
export const formatEmptyStr = (str) => {
return str !== null && str !== undefined && str !== '' ? str : '-';
};
export const formatStrTime = (dateStr, transform) => {
const date = new Date(dateStr);
if (date) {
transform = transform || 'yyyy-MM-dd HH:mm:ss';
const mon = date.getMonth() + 1,
dd = date.getDate(),
hh = date.getHours(),
mm = date.getMinutes(),
ss = date.getSeconds();
const year = date.getFullYear(),
month = mon < 10 ? '0' + mon : mon,
day = dd < 10 ? '0' + dd : dd,
hour = hh < 10 ? '0' + hh : hh,
minute = mm < 10 ? '0' + mm : mm,
second = ss < 10 ? '0' + ss : ss;
transform = transform.replace('yyyy',year)
.replace('MM',month).replace('dd',day)
.replace('HH',hour).replace('mm',minute)
.replace('ss', second);
return transform;
} else {
return '';
}
};
export const formatAngelTime = (str) => {
if (!str || str.indexOf('T') === -1) { return '' }
return str.split('+')[0].replace('T', ' ')
};
<file_sep>package com.duruo.service.impl;
import com.duruo.common.ServerResponse;
import com.duruo.dao.QchuangMapper;
import com.duruo.po.Qchuang;
import com.duruo.service.IQchuangService;
import com.duruo.util.DateTimeUtil;
import com.duruo.vo.QchaungVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by @Author tachai
* date 2018/9/14 19:03
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
@Service("iQchuangService")
public class QchuangServiceImpl implements IQchuangService {
@Autowired
private QchuangMapper qchuangMapper;
/**
* @param qchuang
* @return
*/
@Override
public ServerResponse<String> add(Qchuang qchuang) {
if(qchuang!=null){
//判断该用户是否注册过
Qchuang qchuang1 = qchuangMapper.selectByIdcard(qchuang.getIdCard());
if(qchuang1!=null)
return ServerResponse.createByErrorMessage("该用户已经注册过");
//判断是否插入成功
qchuang.setIsDelete(1);
qchuang.setStatus(1);
int result = qchuangMapper.insert(qchuang);
if(result>0){
return ServerResponse.createBySuccessMessage("新增成功");
}
return ServerResponse.createByErrorMessage("新增失败");
}
return ServerResponse.createByErrorMessage("传入的值为空");
}
@Override
public ServerResponse<String> update(Qchuang qchuang) {
if(qchuang!=null){
Qchuang qchuang1 = qchuangMapper.selectByIdcard(qchuang.getIdCard());
if(qchuang1!=null){
int result = qchuangMapper.updateByPrimaryKeySelective(qchuang);
return result>0?ServerResponse.createBySuccessMessage("更新成功"):ServerResponse.createByErrorMessage("更新失败");
}
return ServerResponse.createByErrorMessage("该用户不存在");
}
return ServerResponse.createByErrorMessage("传入的参数为空");
}
@Override
public ServerResponse<String> del(String id) {
if(id!=null){
Qchuang qchuang = qchuangMapper.selectByPrimaryKey(id);
if(qchuang!=null){
qchuang.setIsDelete(0);
int result = qchuangMapper.updateByPrimaryKeySelective(qchuang);
return result>0?ServerResponse.createBySuccessMessage("删除成功"):ServerResponse.createByErrorMessage("删除失败");
}
return ServerResponse.createByErrorMessage("该法人不存在");
}
return ServerResponse.createByErrorMessage("传入的值为空");
}
@Override
public ServerResponse<List<QchaungVO>> list(String companyName, String startTime, String endTime) {
List<Qchuang> list = qchuangMapper.list(companyName, startTime, endTime);
List<QchaungVO> listvo = new ArrayList<>();
list.forEach(e->{
QchaungVO vo = new QchaungVO();
BeanUtils.copyProperties(e,vo);
//注册时间
vo.setApplyDate1(DateTimeUtil.dateToStr(e.getRegDate()));
//申请时间
vo.setApplyDate(DateTimeUtil.dateToStr(e.getCreateDate()));
listvo.add(vo);
});
return ServerResponse.createBySuccess(listvo);
}
@Override
public ServerResponse<List<QchaungVO>> donelist(String companyName, String startTime, String endTime){
List<Qchuang> list = qchuangMapper.donelist(companyName,startTime,endTime);
List<QchaungVO> listvo = new ArrayList<>();
list.forEach(e->{
QchaungVO vo = new QchaungVO();
BeanUtils.copyProperties(e,vo);
//注册时间
vo.setApplyDate1(DateTimeUtil.dateToStr(e.getRegDate()));
//申请时间
vo.setApplyDate(DateTimeUtil.dateToStr(e.getCreateDate()));
listvo.add(vo);
});
return ServerResponse.createBySuccess(listvo); }
}
<file_sep>package com.duruo.util;
import com.jcraft.jsch.*;
import lombok.Data;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
import java.util.Vector;
/**
* Created by @Author tachai
* date 2018/7/20 18:43
*
* @Email <EMAIL>
*/
@Data
public class SFTPUtil {
private static final Logger logger= LoggerFactory.getLogger(SFTPUtil.class);
private ChannelSftp sftp;
private Session session;
/**SFTP 登录用户名*/
private static String userName = PropertiesUtil.getProperty("sftp.user");
//SFTP登录密码
private static String password = PropertiesUtil.getProperty("sftp.pass");
//SFTP ip
private static String ip = PropertiesUtil.getProperty("sftp.server.ip");
//SFTP port
private int port;
/**
* 构造基于密码的ftp对象
* @param userName
* @param password
* @param ip
* @param port
*/
public SFTPUtil(String userName,String password,String ip,int port){
this.userName=userName;
this.password=<PASSWORD>;
this.ip=ip;
this.port=port;
}
/**
* 上传文件到文件服务器
* @param directory
* @param fileName
* @param in
* @return
* @throws SftpException
*/
public static boolean uploadFile(String directory,String fileName,InputStream in) throws SftpException {
SFTPUtil sftpUtil = new SFTPUtil(userName,password,ip,22);
logger.info("开始连接sftp服务器");
boolean result = sftpUtil.upload(directory,fileName,in);
logger.info("开始连接sftp服务器,结束上传,上传结果"+result);
return result;
}
public static byte[] downloadFile(String directory, String downloadFile) throws IOException, SftpException {
SFTPUtil sftpUtil = new SFTPUtil(userName,password,ip,22);
logger.info("开始连接sftp服务器");
byte[] result = sftpUtil.download(directory,downloadFile);
logger.info("开始连接sftp服务器,结束上传,上传结果");
return result;
}
private boolean connectServer(String ip,int port,String userName,String password){
// boolean isSuccess=false;
try {
JSch jsch = new JSch();
session = jsch.getSession(userName,ip,port);
if(password !=null){
session.setPassword(password);
}
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
} catch (JSchException e) {
e.printStackTrace();
}
return sftp.isConnected();
}
/**
* 关闭连接 server
*/
public void disConnect(){
if(sftp != null){
if(sftp.isConnected()){
sftp.disconnect();
}
}
if(session != null){
if(session.isConnected()){
session.disconnect();
}
}
}
/**
* 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
// * @param basePath 服务器的基础路径
* @param directory 上传到该目录
* @param sftpFileName sftp端文件名
* @param inputStream 输入流
*/
private boolean upload( String directory, String sftpFileName, InputStream inputStream) throws SftpException {
boolean uploaded = true;
if(connectServer(ip,22,userName,password)){
try {
// sftp.cd(basePath);
sftp.cd(directory);
//上传文件
sftp.put(inputStream,sftpFileName);
} catch (SftpException e) {
logger.error("上传文件失败,可能目录不存在"+e.getStackTrace());
uploaded = false;
e.printStackTrace();
// //目录不存在,则创建文件夹
// String [] dirs=directory.split("/");
// String tempPath=basePath;
// for(String dir:dirs){
// if(null== dir || "".equals(dir)) continue;
// tempPath+="/"+dir;
// try{
// sftp.cd(tempPath);
// }catch(SftpException ex){
// sftp.mkdir(tempPath);
// sftp.cd(tempPath);
// }
// }
}finally {
disConnect();
}
}
return uploaded;
}
/**
* 下载文件
* @param directory 下载目录
* @param downloadFile 下载的文件
* @param saveFile 存在本地的路径
* @throws SftpException
* @throws FileNotFoundException
*/
public void download(String directory,String downloadFile,String saveFile) throws SftpException, FileNotFoundException {
if(directory != null && !"".equals(directory)){
sftp.cd(directory);
}
File file = new File(saveFile);
sftp.get(downloadFile,new FileOutputStream(file));
}
/**
* 下载文件
* @param directory 下载目录
* @param downloadFile 下载的文件名
* @return 字节数组
*/
private byte[] download(String directory, String downloadFile) throws SftpException, IOException {
if(connectServer(ip,22,userName,password)){
try {
if (directory != null && !"".equals(directory)) {
sftp.cd(directory);
}
InputStream is = sftp.get(downloadFile);
byte[] fileData = IOUtils.toByteArray(is);
return fileData;
}catch (Exception e ){
logger.error("下载文件失败"+e.getStackTrace());
}finally {
disConnect();
}
}
return null;
}
/**
* 删除文件
* @param directory 要删除文件所在目录
* @param deleteFile 要删除的文件
*/
public void delete(String directory, String deleteFile) throws SftpException{
sftp.cd(directory);
sftp.rm(deleteFile);
}
/**
* 列出目录下的文件
* @param directory 要列出的目录
*/
public Vector<?> listFiles(String directory) throws SftpException {
return sftp.ls(directory);
}
}
<file_sep>/**
* 仅作记录用
* */
/* 开始结算 */
const POST_BEGIN_SETTLE_APPLY_ID = 'POST_BEGIN_SETTLE_APPLY_ID';
const POST_BEGIN_SETTLE_CHECK_DATA = 'POST_BEGIN_SETTLE_CHECK_DATA';
<file_sep>package com.duruo.vo.form;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/7/5 10:45
*
* @Email <EMAIL>
*/
@Data
public class ApplyLiquorVO {
private String weChatId;
//单位名称
private String companyName;
//企业类型
private String enterpriseType;
//法定代表人(负责人)
private String legalRepresentName;
//负责人联系电话、手机
private String legalRepresentPhone;
//企业分类
private String enterpriseCategory;
//所属街道
private String streetName;
//传真
private String faxNumber;
//餐饮服务(食品流通)许可证有效期
private String foodLicenseValidity;
//经营地址
private String businessAddress;
//经营面积
private String businessArea;
//员工人数
private String staffNumber;
//工商执照有效期
private String businessLicenseValidity;
//办理人
private String transactorName;
//办理人联系电话、手机
private String transactorPhone;
}
<file_sep>package com.duruo.vo.form;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/7/7 13:19
*
* @Email <EMAIL>
*/
//海市企业实行不定时工作制和综合计算工时工作制申请表
@Data
public class OtherWorkingHoursApplyVO {
//企业名称
private String enterprise;
//机构代码
private String organizationCode;
//职工总人数
private String totalWorkers;
//企业注册地所在区县
private String registeredAddress;
//地址
private String address;
//电话
private String phone;
//邮编
private String postcode;
//联系人
private String linkman;
//实行不定时工作制的岗位
private String untimeStation;
//实行不定时工作制的岗位的人数
private String untimePeoples;
//实行综合计算工时工作制的岗位
private String multipleTimeStation;
//实行综合计算工时工作制的岗位人数
private String multipleTimePeoples;
//综合计算工时工作制的周期
private String multipleTimeCycle;
//企业生产经营特点
private String productionCharacteristics;
//申请岗位的说明
private String postDescription;
}
<file_sep>var crypto = require('crypto');
var encodeStr = function (str) {
return str.replace(/!/g, '%21').replace(/\(/g, '%28').replace(/\)/g, '%29');
};
// 获取参数
function getParams(params) {
var defaultParams = {
Async: params.Async || false,
// Text: '这样做的历史原因是你要是真删了万一以后给你一个需求,要求恢复删除数据',
// ImageUrl: '["http://dun.163.com/res/sample/sex_2.jpg"]',
Scene: JSON.stringify(params.Scene || []),
// RegionId: 'cn-hangzhou',
AccessKeyId: params.AccessKeyID,
Format: params.Format || 'JSON',
SignatureMethod: 'HMAC-SHA1',
SignatureVersion: '1.0',
SignatureNonce: Math.random().toString(36).substring(2),
Timestamp: new Date().toISOString(),
Action: params.Action,
Version: params.Version || '2016-06-21'
};
if (params.Action === 'ImageDetection') {
defaultParams.ImageUrl = encodeStr(JSON.stringify(params.ImageUrl || []));
} else if (params.Action === 'TextKeywordFilter') {
defaultParams.Text = encodeStr(params.Text);
}
return defaultParams;
}
//签名编码
function percentEncode(str) {
var res = encodeURIComponent(str);
res = res.replace(/\+/g, '%20');
res = res.replace(/\*/g, '%2A');
res = res.replace(/%7E/g, '~');
return res;
}
//签名
function getSignature(params, AccessKeySecret) {
var keys = [];
for (var key in params) {
keys.push(key);
}
keys = keys.sort();
var _keys = [];
for (var i = 0, len = keys.length; i < len; i++) {
_keys.push(percentEncode(keys[i]) + '=' + percentEncode(params[keys[i]]));
}
var queryString = _keys.join('&');
var stringToSign = 'POST&%2F&' + percentEncode(queryString);
var hmac = crypto.createHmac('sha1', AccessKeySecret + '&');
hmac.update(stringToSign);
return hmac.digest('base64');
}
// 构建url
function composeUrl(config) {
var requestUrl = 'http://green.aliyuncs.com/?';
var apiParams = getParams(config);
var sign = getSignature(apiParams, config.AccessKeySecret);
apiParams.Signature = sign;
for (var key in apiParams) {
requestUrl += (key + '=' + encodeURIComponent(apiParams[key]) + '&');
}
return requestUrl;
}
module.exports = composeUrl;
<file_sep>package com.duruo.dao;
import com.duruo.po.Projectdetail;
import com.duruo.vo.StAuditVo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ProjectdetailMapper {
int deleteByPrimaryKey(String sn);
int insert(Projectdetail record);
int insertSelective(Projectdetail record);
Projectdetail selectByPrimaryKey(String sn);
int updateByPrimaryKeySelective(Projectdetail record);
int updateByPrimaryKey(Projectdetail record);
List<StAuditVo> getAllStAuditVo(@Param("realname") String realname,@Param("project") String project);
List<Projectdetail> listProjectdetail();
Projectdetail selectByEnterpriseId(String enterpriseId);
}<file_sep>package com.duruo.controller;
import com.duruo.dao.EvidenceFilesMapper;
import com.duruo.dao.RetailLicenseMapper;
import com.duruo.dto.BusinessLicence;
import com.duruo.po.EvidenceFiles;
import com.duruo.po.RetailLicense;
import com.duruo.util.*;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.jcraft.jsch.SftpException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.Iterator;
/**
* Created by @Author tachai
* date 2018/6/23 19:17
*
* @Email <EMAIL>
*/
@Slf4j
@Controller
@RequestMapping("/uploadFile/")
public class UploadFileController {
@Autowired
private EvidenceFilesMapper evidenceFilesMapper;
@Autowired
private RetailLicenseMapper retailLicenseMapper;
//保存文件
private boolean saveFile(MultipartFile file, String MsgId) {
//判断文件是否为空
if (!file.isEmpty()) {
try {
File filepath = new File(PropertiesUtil.getProperty("file.Path"));
if (!filepath.exists())
filepath.mkdirs();
//文件保存路径
String savePath = PropertiesUtil.getProperty("evidenceFiles.Path") + MsgId + "_" + file.getOriginalFilename();
System.out.println("文件名" + file.getOriginalFilename());
//上传
file.transferTo(new File(savePath));
} catch (Exception e) {
e.printStackTrace();
}
}
return false;
}
//文件上传
//@Param("files")MultipartFile[] files,
@RequestMapping("springUpload.do")
// @ResponseBody
public String springUpload(HttpSession session, HttpServletRequest request, String deptId, String MsgId, String matterId, String deptName, String matterName, String flowName) throws IllegalStateException, IOException, SftpException {
// clearTask(weChatId,taskName3);
// clearSession(weChatId);
if (!StringUtils.isBlank(MsgId)) {
Date date = new Date();
try {
//插入文件list信息
RetailLicense license = new RetailLicense();
license.setCreateTime(date);
license.setDeptId(Integer.parseInt(deptId));
// MsgId(微信id)为
license.setMsgId(MsgId);
license.setMatterId(Integer.parseInt(matterId));
license.setMatterName(matterName);
license.setStatus("未审核");
int result = retailLicenseMapper.insert(license);
if (result > 0) {
log.info("事项插入成功:{}", MsgId);
} else {
log.error("事项插入失败:{}", MsgId);
}
} catch (Exception e) {
// retailLicenseMapper.deleteByPrimaryKey(MsgId+matterId);
// evidenceFilesMapper.deleteByMsgId(MsgId);
// return ServerResponse.createByErrorMessage("该用户已上传过该事项文件,正在清空,请再上传一次");
}
//清除任务
String res = WeChatParseJson.clearTask(MsgId, flowName);
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if (multipartResolver.isMultipart(request)) {
//将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//获取multiRequest 中所有的文件名
Iterator iter = multiRequest.getFileNames();
EvidenceFiles evidenceFile = new EvidenceFiles();
while (iter.hasNext()) {
//一次遍历所有文件
MultipartFile file = multiRequest.getFile(iter.next().toString());
//防止插空的数据
if (!StringUtils.isBlank(file.getOriginalFilename())) {
String fileName = MsgId + "_" + matterId + "_" + file.getName() + "_" + file.getOriginalFilename();
String path = PropertiesUtil.getProperty("evidenceFiles.Path") + fileName;
log.info("文件名:{}", file.getOriginalFilename());
log.info("属性", file.getName());
System.out.println(file.getName());
//保存到数据库
evidenceFile.setDeptId(Integer.parseInt(deptId));
evidenceFile.setMatterId(Integer.parseInt(matterId));
evidenceFile.setMsgId(MsgId);
evidenceFile.setPath(path);
Date fileDate = new Date();
evidenceFile.setCreateTime(fileDate);
evidenceFile.setDeptName(deptName);
evidenceFile.setMatterName(matterName);
evidenceFile.setType(file.getName());
RetailLicense license = retailLicenseMapper.selectByTimeAndMsgId(MsgId, date);
evidenceFile.setLicenseId(license.getId());
//判断该文件是否存在,存在则不通过.不覆盖上传
// EvidenceFiles evidence = evidenceFilesMapper.selectByTypeAndMsgId(file.getName(), MsgId);
// if (evidence != null) {
// //该文件已存在
// return ServerResponse.createByErrorMessage("该文件已存在");
// } else {
// evidenceFilesMapper.insert(evidenceFile);
// //上传
// file.transferTo(new File(path));
// }
//覆盖上传
evidenceFilesMapper.insert(evidenceFile);
//上传到本地服务器
// file.transferTo(new File(path));
// 上传到文件服务器
SFTPUtil.uploadFile(PropertiesUtil.getProperty("evidenceFiles.Path"), fileName, file.getInputStream());
}
}
}
return "redirect:/success.html";
} else {
return "redirect:/404.html";
}
}
/**
* 无用代码
*
* @param response
* @param licenseId
*/
@RequestMapping("downloadLiquor.do")
public void getFile(HttpServletResponse response, Integer licenseId) {
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
EvidenceFiles evidenceFile = null;
try {
// type = URLDecoder.decode(type, "utf-8");
// msgId = URLDecoder.decode(msgId, "utf-8");
String type = "酒类商品零售许申请表";
evidenceFile = evidenceFilesMapper.selectByTypeAndLicenseId(type, licenseId);
//获得文件名
String[] fileNames = evidenceFile.getPath().split("_");
//如果使用中文会丢失名字只留下后缀名
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileNames[fileNames.length - 1].getBytes(), "ISO-8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//酒类经营许可证不为空
//证明材料不能为空
if (null != evidenceFile) {
String filePath = evidenceFile.getPath();
UpAndDownload.downloadFileByPath(response, filePath);
System.out.println("成功下载");
}
}
@RequestMapping("aiUpload.do")
public String aiUpload(HttpSession session, HttpServletRequest request, String deptId, String MsgId, String matterId, String deptName, String matterName, String flowName) throws IllegalStateException, IOException, SftpException {
if (!StringUtils.isBlank(MsgId)) {
Date date = new Date();
RetailLicense newlicense = new RetailLicense();
try {
//插入文件list信息
newlicense.setCreateTime(date);
newlicense.setDeptId(Integer.parseInt(deptId));
// MsgId(微信id)为
newlicense.setMsgId(MsgId);
newlicense.setMatterId(Integer.parseInt(matterId));
newlicense.setMatterName(matterName);
newlicense.setStatus("未审核");
newlicense.setStatus("未审核");
int result = retailLicenseMapper.insert(newlicense);
if (result > 0) {
log.info("事项插入成功:{}", MsgId);
} else {
log.error("事项插入失败:{}", MsgId);
}
} catch (Exception e) {
// retailLicenseMapper.deleteByPrimaryKey(MsgId+matterId);
// evidenceFilesMapper.deleteByMsgId(MsgId);
// return ServerResponse.createByErrorMessage("该用户已上传过该事项文件,正在清空,请再上传一次");
}
BusinessLicence businessLicence = new BusinessLicence();
//清除任务
String res = WeChatParseJson.clearTask(MsgId, flowName);
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if (multipartResolver.isMultipart(request)) {
//将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
//获取multiRequest 中所有的文件名
Iterator iter = multiRequest.getFileNames();
EvidenceFiles evidenceFile = new EvidenceFiles();
while (iter.hasNext()) {
//一次遍历所有文件
MultipartFile file = multiRequest.getFile(iter.next().toString());
//防止插空的数据
if (!StringUtils.isBlank(file.getOriginalFilename())) {
String fileName = MsgId + "_" + matterId + "_" + file.getName() + "_" + file.getOriginalFilename();
String path = PropertiesUtil.getProperty("evidenceFiles.Path") + fileName;
//文件名例子 wp_ss_20160212_0003.png
log.info("文件名:{}", file.getOriginalFilename());
log.info("属性", file.getName());
System.out.println(file.getName() + "---------" + file.getOriginalFilename());
RetailLicense license = retailLicenseMapper.selectByTimeAndMsgId(MsgId, date);
// 读取营业执照
if (file.getName().indexOf("营业执照") != -1) {
if (Contain.containImage(file.getOriginalFilename())) {
//todo 做扫描 ai预审
JSONObject jsonObject = OCR.checkBusinessLicense(file.getBytes());
JsonParser jsonParser = new JsonParser();
Object jsonObject1 = jsonObject.get("words_result");
JsonObject jsonArray = (JsonObject) jsonParser.parse(jsonObject1.toString());
businessLicence.setSocialCreditCode(com.duruo.util.StringUtils.trim(jsonArray.get("社会信用代码").getAsJsonObject().get("words").toString(), '"'));
businessLicence.setLegalPerson(com.duruo.util.StringUtils.trim(jsonArray.get("法人").getAsJsonObject().get("words").toString(), '"'));
businessLicence.setEstablishmentDate(com.duruo.util.StringUtils.trim(jsonArray.get("成立日期").getAsJsonObject().get("words").toString(), '"'));
businessLicence.setIdNumber(com.duruo.util.StringUtils.trim(jsonArray.get("证件编号").getAsJsonObject().get("words").toString(), '"'));
businessLicence.setAddress(com.duruo.util.StringUtils.trim(jsonArray.get("地址").getAsJsonObject().get("words").toString(), '"'));
businessLicence.setUnitName(com.duruo.util.StringUtils.trim(jsonArray.get("单位名称").getAsJsonObject().get("words").toString(), '"'));
businessLicence.setValidityPeriod(com.duruo.util.StringUtils.trim(jsonArray.get("有效期").getAsJsonObject().get("words").toString(), '"'));
}
}
// 读取申请表审核
if (file.getName().indexOf("申请表") != -1) {
//todo 做输入流 ai预审
// file.getInputStream();
String result = "";
if (file.getOriginalFilename().indexOf(".docx") != -1) {
result = ReadWorderUtil.docxCheck(file.getInputStream(), businessLicence);
if(!StringUtils.isBlank(result)){
license.setOpinion("【申请表】:"+result);
retailLicenseMapper.updateByPrimaryKeySelective(license);
}
} else if (file.getOriginalFilename().indexOf(".doc") != -1) {
result = ReadWorderUtil.docCheck(file.getInputStream(), businessLicence);
if(!StringUtils.isBlank(result)){
license.setOpinion("【申请表】:"+result);
retailLicenseMapper.updateByPrimaryKeySelective(license);
}
}
}
//保存到数据库
evidenceFile.setDeptId(Integer.parseInt(deptId));
evidenceFile.setMatterId(Integer.parseInt(matterId));
evidenceFile.setMsgId(MsgId);
evidenceFile.setPath(path);
Date fileDate = new Date();
evidenceFile.setCreateTime(fileDate);
evidenceFile.setDeptName(deptName);
evidenceFile.setMatterName(matterName);
evidenceFile.setType(file.getName());
evidenceFile.setLicenseId(license.getId());
//覆盖上传
evidenceFilesMapper.insert(evidenceFile);
// 上传到文件服务器
SFTPUtil.uploadFile(PropertiesUtil.getProperty("evidenceFiles.Path"),fileName,file.getInputStream());
}
}
}
return "redirect:/success.html";
} else {
return "redirect:/404.html";
}
}
}
<file_sep># 自制全文RSS汇总(附 推荐工具)
[](https://www.douban.com/people/SilentPenguin/) [](https://www.douban.com/people/SilentPenguin/) 2015-10-28 18:20:50
Feedburner目前在大陆被墙。以下订阅地址,不能直接点开。请复制进Inoreader、Feedly等阅读器,直接订阅即可
【RSS列表】
NEXT@36氪 //20170308新增
http://feeds.feedburner.com/L/next
FT中文网 - 一周十大热门文章
http://feeds.feedburner.com/herokuapp/fttop10
FT中文网 - 今日焦点
http://feeds.feedburner.com/herokuapp/ftnews
新京报
http://feeds.feedburner.com/bjnews1
BBC中文网
http://feeds.feedburner.com/BBC_Chinese.......http://feeds.feedburner.com/52/NOxB
纽约时报中文网 国际纵览
http://feeds.feedburner.com/52/lclb
Tech2Pocket
http://feeds.feedburner.com/Tech2pocket
子夜书社(Podcast 需用支持m3u8的播客客户端订阅)
http://feeds.feedburner.com/xbdlm
中华读书报
http://feeds.feedburner.com/52/TFHc
新京报•书评周刊
http://feeds.feedburner.com/xinjingbao_book
南方都市报•阅读周刊
http://feeds.feedburner.com/nandu_book
东方早报•上海书评
http://feeds.feedburner.com/shanghaibook
财新周刊
http://feeds.feedburner.com/52/tEtn
V2EX 周报(一周热门)
http://feeds.feedburner.com/52/azhb
—————————
【推荐的RSS工具】
1. Huginn:神器。以上RSS源,全部借助Huginn制作
2. Feed43:网页 → 摘要rss
3. Feedity:网页 → 摘要rss
4. fivefilters:摘要rss → 全文rss
5. feedex:摘要rss → 全文rss
6. FeedSoSo:摘要rss → 全文rss
7. kindle4rss:摘要rss → 全文rss 20170308新增
8. Tumblr2RSS: Tumblr Dashboard → RSS (Tumblr某账号转rss,直接二级域名加/rss即可)
9. Pull Feed:Github 的PR → 全文rss
10. emails2rss:Emails → RSS
11. 知乎 转 RSS
12. Google Groups 转 RSS
13. Jianshu RSS:简书 转 rss
14. Bilibili2RSS:**********更新 转 RSS 20170424新增
15. v2ex的节点rss:v2ex 转 rss
16. publicate:Twitter 转 rss 20170509新增
17. hnrss:Hacker News 转 RSS 20170522新增
18. 微博看看:微博 转 RSS 20170605新增 详见这里
19. github-issues-rss:Github Issue 转 rss 20170612新增
\20. reddit:链接后面,参数前面,加.rss即可。如 <https://www.reddit.com/r/Anki/top/.rss?sort=top&t=week&limit=5> limit控制条目数量 20170720新增
\21. [fetchrss](http://fetchrss.com/instagram):Instagram 转 RSS 20180116新增
\22. [twitrss](https://twitrss.me/):Twitter 转 RSS 20180116新增 ————————— 【不再维护的RSS源:阅读价值不高、兴趣转移等】 豆瓣新上线的美剧(评分>8.0) (节制**,不看电视剧了) <http://feeds.feedburner.com/177/WYCr> 新浪新知/新闻极客 <http://feeds.feedburner.com/herokuapp/sinaxz> 知乎前端 <http://feeds.feedburner.com/52/NKBp> 知乎热门回答(内容太水,很多抖机灵) <http://feeds.feedburner.com/52/KziC> 豆瓣最受欢迎的书评 <http://feeds.feedburner.com/52/IITF> 豆瓣热点内容 <http://feeds.feedburner.com/52/VIgP> 知乎编辑推荐(和知乎官方源约95%一致) <http://feeds.feedburner.com/52/DkCm>
【转载请注明本文链接:<https://www.douban.com/note/522518464/>】<file_sep>package com.duruo.po;
import java.util.Date;
public class EvidenceFiles {
private Integer id;
private Integer licenseId;
private String msgId;
private Integer matterId;
private String type;
private Integer deptId;
private String path;
private String matterName;
private String deptName;
private Date createTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMsgId() {
return msgId;
}
public void setMsgId(String msgId) {
this.msgId = msgId == null ? null : msgId.trim();
}
public Integer getMatterId() {
return matterId;
}
public void setMatterId(Integer matterId) {
this.matterId = matterId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type == null ? null : type.trim();
}
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path == null ? null : path.trim();
}
public String getMatterName() {
return matterName;
}
public void setMatterName(String matterName) {
this.matterName = matterName == null ? null : matterName.trim();
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName == null ? null : deptName.trim();
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getLicenseId() {
return licenseId;
}
public void setLicenseId(Integer licenseId) {
this.licenseId = licenseId;
}
}<file_sep>// ==UserScript==
// @name RARBG Advanced Filters
// @namespace http://tampermonkey.net/
// @version 1.39
// @description Additional quality of life filters: - Show or hide category icons; - Show or hide torrent thumbnails; - Show or hide movie and tv filters (Removes torrents with KORSUB and 720p); - Show or hide porn; - Filter based on minimum IMDB rating;
// @author Kxmode
// @match *://rarbg.to/*
// @match *://rarbgmirror.org/*
// @match *://rarbgmirror.com/*
// @match *://rarbgproxy.org/*
// @match *://rarbgunblock.com/*
// @match *://www.rarbg.is/*
// @match *://rarbgmirror.xyz/*
// @match *://rarbg.unblocked.lol/*
// @match *://rarbg.unblockall.org/*
// @match *://rarbgaccess.org/*
// @match *://rarbg2018.org/*
// @match *://rarbgtorrents.org/*
// @grant none
// @require //ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// ==/UserScript==
$(function() {
// Define general variables
var nonStandardUrlParams = (GetParameterByName("category%5B%5D") !== null || GetParameterByName("category[]") !== null) ? true : false,
arrayCurrentUrlParams = -1,
showAdvancedOptions = false,
showIcon,
showTorrentThumbnail, // TODO: child of showIcon (=true)
showMoviesTVFilters,
showPorn,
genreFilter = "",
currentUrlNormal,
currentUrlAbnormal,
i;
// Define Category specific filters
var minRating,
gameGroup,
musicGenre,
showKORSUB,
show720p;
// Define array of known RARBG categories
var arrayMovies = ["movies", 14, 17, 42, 44, 45, 46, 47, 48, 50, 51, 52].map(String),
arrayTVShows = [18, 41, 49].map(String),
arrayGames = [27, 28, 29, 30, 31, 32, 40].map(String),
arrayMusic = [23, 24, 25, 26].map(String),
arraySoftware = [33, 34, 43].map(String),
arrayNonPorn = [14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52].map(String);
// Define conditional checks
var isCategoryMovies,
isCategoryTVShows,
isCategoryGames,
isCategoryMusic,
isCategorySoftware,
isCategoryNonPorn;
// Define booleans
var categoryMoviesArray,
categoryTVShowsArray,
categoryGamesArray,
categoryMusicArray,
categorySoftwareArray,
categoryNonPornArray;
// This logic normalizes RARBG's inconsistent URL parameter types (e.g. category=movies, category%5B%5D=48, category=1;18;41;49;, and category[]=42)
if (nonStandardUrlParams)
{
currentUrlNormal = new RegExp("[\?&]category%5B%5D=([^]*)").exec(window.location.href); // Grab all URL parameters %5B%5D
currentUrlAbnormal = new RegExp("[\?&]category\[[^\[\]]*\]=([^]*)").exec(window.location.href); // Grab all URL parameters []
if (currentUrlNormal === null && currentUrlAbnormal === null) // If neither unique parameter exists, then stop this logic, and return nothing
{
return null;
}
else // Otherwise...
{
if (currentUrlAbnormal !== null) // If URL parameters is [] (abnormal)
{
arrayCurrentUrlParams = String(currentUrlAbnormal).match(/(=)\w+/g).map(String); // Create an array of values separated by the equal sign
}
else // Otherwise conclude URL parameters are normal (%5B%5D)
{
arrayCurrentUrlParams = String(currentUrlNormal).match(/(=)\w+/g).map(String); // Create an array of values separated by the equal sign
}
for (i = 0; i < arrayCurrentUrlParams.length; i++) // Iterate through array look for equal signs
{
arrayCurrentUrlParams[i] = arrayCurrentUrlParams[i].replace("=", ""); // Remove the equal sign from the array
}
}
}
else if (GetParameterByName("category") !== null || arrayCurrentUrlParams.length > -1) // Otherwise this is a standard URL parameter
{
arrayCurrentUrlParams = GetParameterByName("category").split(";").map(String); // Create an array of values separated by the semicolon
}
// Compares current url parameters with known RARBG categories. If the value is greater than -1 we have at least one match.
if (GetParameterByName("category") !== null || arrayCurrentUrlParams.length > -1)
{
// Navigate through each array to find and set the match to true. For now there can only be one match.
for (i = 0; i < arrayCurrentUrlParams.length; i++)
{
isCategoryMovies = arrayMovies.indexOf(arrayCurrentUrlParams[i]);
categoryMoviesArray = (isCategoryMovies !== -1) ? true : false;
}
for (i = 0; i < arrayCurrentUrlParams.length; i++)
{
isCategoryTVShows = arrayTVShows.indexOf(arrayCurrentUrlParams[i]);
categoryTVShowsArray = (isCategoryTVShows !== -1) ? true : false;
}
for (i = 0; i < arrayCurrentUrlParams.length; i++)
{
isCategoryGames = arrayGames.indexOf(arrayCurrentUrlParams[i]);
categoryGamesArray = (isCategoryGames !== -1) ? true : false;
}
for (i = 0; i < arrayCurrentUrlParams.length; i++)
{
isCategoryMusic = arrayMusic.indexOf(arrayCurrentUrlParams[i]);
categoryMusicArray = (isCategoryMusic !== -1) ? true : false;
}
for (i = 0; i < arrayCurrentUrlParams.length; i++)
{
isCategorySoftware = arraySoftware.indexOf(arrayCurrentUrlParams[i]);
categorySoftwareArray = (isCategorySoftware !== -1) ? true : false;
}
for (i = 0; i < arrayCurrentUrlParams.length; i++)
{
isCategoryNonPorn = arrayNonPorn.indexOf(arrayCurrentUrlParams[i]);
categoryNonPornArray = (isCategoryNonPorn !== -1) ? true : false;
}
}
// Method to grab the Parameter name and value (Note: single use only. See line 60 for multiple URL parameters and if needed move to function.)
function GetParameterByName(name, url) {
// credit: https://stackoverflow.com/a/901144 (Modified by Kxmode)
// Used under StackOverflow's standard CC BY-SA 3.0 license
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$|((%\d\D)*\D\d*))'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// Method to activate and deactive filters inside the Advanced Filter's HTML box
function ToggleFilter(target, data, bool, optional)
{
optional = (optional !== undefined) ? true : false;
var targetID = target.replace("#","");
if (bool)
{
if (!optional)
{
$(target).find("i").removeClass("fa-eye-slash").addClass("fa-eye");
$(target).removeClass("disabled");
}
$(target).attr(data, "true");
window.localStorage.setItem(targetID, true);
}
else
{
if (!optional)
{
$(target).find("i").removeClass("fa-eye").addClass("fa-eye-slash");
$(target).addClass("disabled");
}
$(target).attr(data, "false");
window.localStorage.setItem(targetID, false);
}
}
// Method to show and hide the Advanced Filter's HTML box
function ToggleAdvancedFilters(bool, isClicked)
{
isClicked = (isClicked !== undefined) ? true : false;
var parentTarget = $(".new-search form");
var target = $(".advanced-search");
if (GetParameterByName("category") !== null && isClicked === false)
{
$("#shadvbutton").attr("data-shadvbutton", "true");
window.localStorage.setItem("shadvbutton", true);
parentTarget.removeAttr("style");
parentTarget.removeClass("disabled");
target.show();
}
else if (GetParameterByName("category") === null && isClicked === false)
{
$("#shadvbutton").attr("data-shadvbutton", "false");
window.localStorage.setItem("shadvbutton", false);
parentTarget.attr("style", "width: 100%; border-right: 1px solid #9faabc;");
target.hide();
}
else
{
if (bool) {
showhideadvsearch('show');
parentTarget.removeAttr("style");
parentTarget.removeClass("disabled");
target.show();
} else {
parentTarget.attr("style", "width: 100%; border-right: 1px solid #9faabc;");
target.hide();
}
}
}
$("#searchTorrent").parent().addClass("new-search");
// Removes extra space between Recommended torrents and search bar
$("#searchTorrent").parent().parent().find("div:nth-of-type(2)").remove();
for(i = 1; i <= 4; i++)
{
$("#searchTorrent").parent().parent().find("br:nth-of-type(1)").remove();
}
// Attaches FontAwesome script to display active and inactive "eye" icons. fontawesome.io for more info.
$("head").append( '<script src="//use.fontawesome.com/2d73a39974.js"></script>');
// Attaches CSS for the custom Advanced Filters HTML box.
$("head").append( '<style>\n' +
'.content-rounded .new-search,\n' +
'.content-rounded div.new-search div { margin-left: auto; }\n' +
'.new-search { width: 1200px; display: flex; display: -webkit-flex; display: -moz-flex; margin: 30px auto; }\n' +
'.new-search div { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; }\n' +
'.new-search div { border-radius: 0; -moz-border-radius: 0; -webkit-border-radius: 0; }\n' +
'.new-search form { width: 70%; border-radius: 0; -moz-border-radius: 0; -webkit-border-radius: 0; }\n' +
'.new-search form { border: 0; border-top: 1px solid #9faabc; border-bottom: 1px solid #9faabc; border-left: 1px solid #9faabc; }\n' +
'.new-search .divadvscat { width: 157px; display: inline-block; height: auto; padding: 7px; float: none; }\n' +
'.new-search .divadvclearcats { padding: 10px; }\n' +
'.new-search .advanced-search { width: 30%; background: #e7f3fb; font-size: 110%; padding: 5px; border: 1px solid #9faabc; float: left; }\n' +
'.new-search .advanced-search { border: 0; border-top: 1px solid #9faabc; border-bottom: 1px solid #9faabc; border-right: 1px solid #9faabc; }\n' +
'.new-search .advanced-search h4 { padding: 0; margin: 0 0 10px 0; text-align: center; }\n' +
'.advanced-search .section-wrapper { border: 1px dotted #9faabc; padding: 10px; }\n' +
'.advanced-search .section-wrapper:first-child { border-bottom: 0; }\n' +
'.advanced-search .no-border { border: 0; }\n' +
'.advanced-search .divadvscat { width: auto; border: 1px solid transparent; cursor: pointer; }\n' +
'.advanced-search .divadvscat i { padding-right: 2px; }\n' +
'.advanced-search .disabled { border: 1px solid #DDD; background-color: #f5f5f5; color: #999; }\n' +
'.advanced-search .centered { text-align: center; }\n' +
'.section-wrapper .imdb-rating-search { width: 155px; }\n' +
'.section-wrapper .gaming-group-search { width: auto; }\n' +
'.section-wrapper .imdb-rating-search input { width: 30%; }\n' +
'.section-wrapper .gaming-group-search input { width: 50%; }\n' +
'.section-wrapper input { border: 0; margin-left: 10px; border: 1px solid #9faabc; text-align: center; }\n' +
'.clearfix:before, .clearfix:after { display: table; content: ""; line-height: 0;}\n' +
'.section-wrapper input.text-left { text-align: left; }\n' +
'</style>');
// Creates the HTML for category specific filters
if (GetParameterByName("category") === null || categorySoftwareArray)
{
genreFilter = '<div class="section-wrapper no-border" style="border-top: 1px dotted #9faabc;">\n';
}
else
{
genreFilter = '<div class="section-wrapper">\n';
}
// TODO: Handle for: if (GetParameterByName("category") !== null || arrayCurrentUrlParams.length > -1 || nonStandardUrlParams) ----------
if (GetParameterByName("category") !== null || nonStandardUrlParams)
{
if (categoryMoviesArray || categoryTVShowsArray)
{
genreFilter += '<div id="jQIMDB" class="divadvscat imdb-rating-search centered">Min Rating <input name="minprice" type="text" /></div>\n' +
'<div id="jQKORSUB" class="divadvscat" title="Hides low-quality KORSUB torrents"><i class="fa fa-eye fa-1x"></i> KORSUB</div>\n' +
'<div id="jQ720p" class="divadvscat" title="Hides 720p torrents"><i class="fa fa-eye fa-1x"></i> 720p</div>';
}
else if (categoryGamesArray)
{
genreFilter += '<div id="jQGamingGroup" class="divadvscat gaming-group-search centered">Torrent Group <input name="gamegroup" class="text-left" type="text" /></div>\n';
}
else if (categoryMusicArray)
{
genreFilter += '<div id="jQMusicGenre" class="divadvscat music-group-genre centered">Genre <input name="musicgenre" class="text-left" type="text" /></div>\n';
}
else if (categorySoftwareArray)
{
// genreFilter += '<div id="jQcategoryFilter" class="divadvscat centered">Software Filters Coming Soon</div>\n'; // Not enough to warrant this for now
}
else if (categoryNonPornArray)
{
genreFilter += '<div id="jQcategoryFilter" class="divadvscat centered">Non Porn Filters Coming Soon</div>\n';
}
}
else
{
// genreFilter += '<div id="jQcategoryFilter" class="divadvscat centered">All Filters Coming Soon</div>\n'; // Not enough to warrant this for now
}
genreFilter += '</div>\n';
// Creates the Advanced Filter HTML box
var AdvancedFiltersHTML = '<div class="advanced-search">\n' +
'<div class="section-wrapper">\n' +
'<div id="jQIcon" class="divadvscat"><i class="fa fa-eye fa-1x"></i> Category Icons</div>\n' +
'<div id="jQTorrentThumbnail" class="divadvscat"><i class="fa fa-eye fa-1x"></i> Torrent Images</div>\n' + // Eventually make this a child of Show Thumbnails
'<div id="jQShowPorn" class="divadvscat"><i class="fa fa-eye fa-1x"></i> Porn</div>\n' +
'</div>\n' +
genreFilter +
'<div class="section-wrapper no-border">\n' +
'<span class="jQUpdateFilters btn btn-primary btn-mini">Update Page with Filters</span>\n' +
'<span class="jQResetFilters btn btn-mini">Reset Filters</span>\n' +
'</div>\n' +
'<div class="clearfix"></div>\n' +
'</div>';
// Attaches Advanced Filters HTML box to RARBG
$("#searchTorrent").parent().append(AdvancedFiltersHTML);
// TODO: Likely going to need to move the ToggleFilter and ToggleAdvancedFilters method calls into this gated logic
if (nonStandardUrlParams)
{
ToggleFilter("#shadvbutton", "data-shadvbutton", showAdvancedOptions, true);
ToggleAdvancedFilters(true, true);
}
else
{
showAdvancedOptions = ((window.localStorage.getItem("shadvbutton") == "true") ? true : false);
ToggleFilter("#shadvbutton", "data-shadvbutton", showAdvancedOptions, true);
ToggleAdvancedFilters(showAdvancedOptions);
}
// Logic for HTML box icons
showIcon = ((window.localStorage.getItem("jQIcon") == "false") ? false : true);
ToggleFilter("#jQIcon", "data-icon", showIcon);
showTorrentThumbnail = ((window.localStorage.getItem("jQTorrentThumbnail") == "false") ? false : true);
ToggleFilter("#jQTorrentThumbnail", "data-torrent-thumbs", showTorrentThumbnail);
showPorn = ((window.localStorage.getItem("jQShowPorn") == "false") ? false : true);
ToggleFilter("#jQShowPorn", "data-porn", showPorn);
showKORSUB = ((window.localStorage.getItem("jQKORSUB") == "false") ? false : true);
ToggleFilter("#jQKORSUB", "data-korsub", showKORSUB);
show720p = ((window.localStorage.getItem("jQ720p") == "false") ? false : true);
ToggleFilter("#jQ720p", "data-720p", show720p);
$("#shadvbutton").on("click", function() {
showAdvancedOptions = ($(this).attr("data-shadvbutton") == "false") ? true : false;
ToggleFilter("#shadvbutton", "data-shadvbutton", showAdvancedOptions, true);
ToggleAdvancedFilters(showAdvancedOptions, true);
});
$("#jQIcon").on("click", function() {
showIcon = ($(this).attr("data-icon") == "false") ? true : false;
ToggleFilter("#jQIcon", "data-icon", showIcon);
});
$("#jQTorrentThumbnail").on("click", function() {
showTorrentThumbnail = ($(this).attr("data-torrent-thumbs") == "false") ? true : false;
ToggleFilter("#jQTorrentThumbnail", "data-torrent-thumbs", showTorrentThumbnail);
});
$("#jQShowPorn").on("click", function() {
showPorn = ($(this).attr("data-porn") == "false") ? true : false;
ToggleFilter("#jQShowPorn", "data-porn", showPorn);
});
$("#jQKORSUB").on("click", function() {
showKORSUB = ($(this).attr("data-korsub") == "false") ? true : false;
ToggleFilter("#jQKORSUB", "data-korsub", showKORSUB);
});
$("#jQ720p").on("click", function() {
show720p = ($(this).attr("data-720p") == "false") ? true : false;
ToggleFilter("#jQ720p", "data-720p", show720p);
});
// Movies and TV Shows only
if (categoryMoviesArray || categoryTVShowsArray)
{
if (window.localStorage.getItem("minimum-rating") > 0)
{
var mr = window.localStorage.getItem("minimum-rating");
$("#jQIMDB").find("input").attr("value", mr);
minRating = mr;
}
else
{
$("#jQIMDB").find("input").attr("value", 0);
}
}
// Games only
if (categoryGamesArray)
{
if(window.localStorage.getItem("game-group") !== undefined)
{
var gg = window.localStorage.getItem("game-group");
$("#jQGamingGroup").find("input").attr("value", gg);
gameGroup = gg;
}
else
{
$("#jQGamingGroup").find("input").removeAttr("value");
}
}
// Music only
if (categoryMusicArray)
{
if(window.localStorage.getItem("music-genre") !== undefined)
{
var mg = window.localStorage.getItem("music-genre");
$("#jQMusicGenre").find("input").attr("value", mg);
musicGenre = mg;
}
else
{
$("#jQMusicGenre").find("input").removeAttr("value");
}
}
// Input click event
$("#jQIMDB input, #jQGamingGroup input, #jQMusicGenre input").on("keydown", function() {
if (event.which == 13 || event.keyCode == 13) {
$(".jQUpdateFilters").click();
}
});
// Events for the "Update Filters" button
$(".jQUpdateFilters").on("click", function () {
if (categoryMoviesArray || categoryTVShowsArray)
{
var minRating = $("#jQIMDB").parent().find("input").val();
window.localStorage.setItem("minimum-rating", minRating);
}
if (categoryGamesArray)
{
var gameGroup = $("#jQGamingGroup").parent().find("input").val();
window.localStorage.setItem("game-group", gameGroup);
}
if (categoryMusicArray)
{
var musicGenre = $("#jQMusicGenre").parent().find("input").val();
window.localStorage.setItem("music-genre", musicGenre);
}
location.reload();
});
// Events for the "Reset Filters" button
$(".jQResetFilters").on("click", function() {
window.localStorage.removeItem("jQIcon");
window.localStorage.removeItem("jQTorrentThumbnail");
window.localStorage.removeItem("jQKORSUB");
window.localStorage.removeItem("jQ720p");
window.localStorage.removeItem("jQShowPorn");
window.localStorage.removeItem("minimum-rating");
window.localStorage.removeItem("game-group");
window.localStorage.removeItem("music-genre");
location.reload();
});
// Removes Movie filters after clicking the "View all" link
$(".tdlinkfull2").on("click", function() {
if ($(this).text() === "View all")
{
window.localStorage.removeItem("jQKORSUB");
window.localStorage.removeItem("jQ720p");
window.localStorage.removeItem("minimum-rating");
window.localStorage.removeItem("game-group");
window.localStorage.removeItem("music-genre");
}
});
// CATEGORY SPECIFIC =================================================================================================
// Hides torrents with seeders equal to or lower than a number [TODO: make this a form input filter]
// use inArray method from work (Configurator height normalizer)
/*
if (parseInt(title.indexOf("720p")) > 0)
{
$(this).parents(".lista2").remove();
}
*/
// Logic to hide porn
if (!showPorn)
{
$.each($(".tdlinkfull2"), function() {
var targetText = $(this).text().toLowerCase();
if (targetText == "xxx")
{
$(this).parent().parent().remove();
}
});
$.each($(".divadvscat a"), function() {
var targetText = $(this).text().toLowerCase();
if(targetText == "xxx (18+)")
{
$(this).parent().remove();
}
});
}
// Loops through all available torrents
$.each($(".lista a"), function(index, value) {
var title = $(this).attr("title");
var icon = $(this).find("img").attr("src");
if (title !== undefined)
{
// Logic to hide KORSUB torrents
if (!showKORSUB)
{
if (parseInt(title.indexOf("KORSUB")) > 0)
{
$(this).parents(".lista2").remove();
}
}
// Logic to hide 720p torrents
if (!show720p)
{
if (parseInt(title.indexOf("720p")) > 0)
{
$(this).parents(".lista2").remove();
}
}
// Creates the logic for category specific filters
if (GetParameterByName("category") !== null || nonStandardUrlParams)
{
if (categoryMoviesArray || categoryTVShowsArray)
{
// IMDB Ratings
$.each($("span"), function(index, value) {
var ratings = $(this).text();
var imdb = ratings.indexOf("IMDB: ") + 6;
if (ratings !== undefined && imdb !== -1)
{
minRating = parseFloat(minRating);
var rateValue = parseFloat(ratings.substring(imdb,ratings.length-3));
if (!isNaN(rateValue))
{
if (showMoviesTVFilters) { $(this).attr("style", "display: block;"); }
if (rateValue <= minRating)
{
$(this).parents(".lista2").remove();
}
}
}
});
}
// Game Torrent Group
else if (categoryGamesArray)
{
$.each($(".lista2t a"), function(index, value) {
if ($(this).attr("title") !== undefined)
{
var torrentTitle = $(this).attr("title");
var searchValue = torrentTitle.toLowerCase().indexOf(gameGroup);
var compareValue = torrentTitle.substring(searchValue,torrentTitle.length);
if (searchValue === -1 && gameGroup !== null)
{
$(this).parents(".lista2").remove();
}
}
});
}
else if (categoryMusicArray)
{
$.each($(".lista2t .lista span:last-child"), function(index, value) {
$(this).addClass("RYANALLEN");
var genreTitle = $(this).text();
if (genreTitle !== undefined)
{
var searchValue = genreTitle.toLowerCase().indexOf(musicGenre);
var compareValue = genreTitle.substring(searchValue,genreTitle.length);
if (searchValue === -1 && musicGenre !== null)
{
$(this).parents(".lista2").remove();
}
}
});
}
// Coming soon
else if (categorySoftwareArray) { }
else if (categoryNonPornArray) { }
}
}
// Logic to hide porn
if (!showPorn)
{
if (title !== undefined)
{
title = title.indexOf("XXX");
if (title >= 0)
{
$(this).parents(".lista2").remove();
}
}
if (icon !== undefined)
{
icon = icon.indexOf("cat_new4.gif");
if (icon >= 0)
{
$(this).parents(".lista2").remove();
}
}
}
});
// NON-CATEGORY SPECIFIC =================================================================================================
// Logic to hide icons
if (!showIcon)
{
$(".lista2t tr td:nth-of-type(1)").attr("style","display:none;");
}
else
{
// TODO: Make child of showIcon (=true)
// Logic to show torrent thumbnails
if (showTorrentThumbnail)
{
$(".lista2t").find("tr:first-child td:first-child").text("Thumbnail");
$.each($(".lista2t .lista2"), function() {
var anchor = $(this);
$.each(anchor.find(".lista"), function() {
var image = $(this).find("a");
var target = anchor.find(":nth-child(1) a");
if (image.attr("onmouseover") !== undefined)
{
var href = image.attr("href");
var sourceThumb = image.attr("onmouseover");
var val1 = sourceThumb.lastIndexOf("//dyncdn.me/");
var val2 = sourceThumb.indexOf("\' border=0>')")-1;
var imageID = sourceThumb.substring(val1,val2);
var thumbnailImage = "<img src=\'" + imageID + "' />";
image.removeAttr("onmouseover").removeAttr("onmouseout");
target.find("img").replaceWith(thumbnailImage);
target.attr("href", href);
anchor.find("td:nth-child(1)").attr( "align", "center" );
}
});
});
}
}
});<file_sep>package com.duruo.service.impl;
import com.duruo.common.ServerResponse;
import com.duruo.dao.RetailLicenseMapper;
import com.duruo.po.RetailLicense;
import com.duruo.service.IDocumentHandingService;
import com.duruo.util.HttpUtil;
import com.duruo.util.IdUtils;
import com.duruo.util.PropertiesUtil;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Created by @Author tachai
* date 2018/7/18 9:25
*
* @Email <EMAIL>
*/
@Service("iDocumentHandingService")
public class DocumentHandingServiceImpl implements IDocumentHandingService{
@Autowired
private RetailLicenseMapper retailLicenseMapper;
@Override
public ServerResponse<String> updateOpinion(Integer licenseId, String opinion, String result,String userName) {
RetailLicense retailLicense = retailLicenseMapper.selectByPrimaryKey(licenseId);
if(retailLicense.getStatus().indexOf("已审核")<=-1){
retailLicense.setStatus("已审核"+"_"+result);
retailLicense.setCreateTime(new Date());
retailLicense.setUserName(userName);
retailLicense.setOpinion(opinion);
retailLicenseMapper.updateByPrimaryKeySelective(retailLicense);
// 返回结果给微信客户端
String url= PropertiesUtil.getProperty("return.weixin");
Map<String,String> map= new HashMap<>();
map.put("MsgId", IdUtils.getId(retailLicense.getMsgId()));
map.put("WeChatId",retailLicense.getMsgId());
// if("false".equals(result)){
// map.put("auditresult",result);
// }else {
//
// }
map.put("auditresult",result);
System.out.println(result);
map.put("auditopinion",opinion);
String data=new Gson().toJson(map);
//得到返回的数据
// String res = HttpUtil.okhttp(url,data);
HttpUtil.okhttp(url,data);
System.out.println("+++++++++++"+data);
// if(org.apache.commons.lang.StringUtils.isBlank(res)){
// return ServerResponse.createByErrorMessage("处理失败");
// }
return ServerResponse.createBySuccessMessage("审核成功");
}else {
return ServerResponse.createByErrorMessage("该数据已被另外一位同事审核");
}
}
}
<file_sep>/*
This is the background page for the extension. It's primary purpose is to hold the options selected in memory to enable quick access to them. It will also communicate with the content script.
This script will also contain the code called when buttons are clicked in the options page.
Author: <NAME>
Date Created: 11/2/2012
Date Modified: 2/2/2013
Copyright 2013 <NAME>
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.
*/
// The background page is reloaded each time the extension is enabled after being disabled (the background page unloads when disabled).
// Therefore, I can use the background page to track when the extension is enabled by running a function each time the extension is enabled.
// However, the background page will also re-load when chrome is started, and stops when chrome exits. So we need to figure that out.
// If the background page can access see what other processes are running, then it will be able to tell when the browser just started?
// This initializes localStorage when the extension is installed.
function initialize_options()
{
if (localStorage.getItem("install_date"))
return;
localStorage["install_date"] = new Date().getTime();
localStorage["text_on"] = true;
localStorage["blocked_words"] = "sex\nbreast\nboob\npenis\ndick\nvagina\nfuck\ndamn\nhell\nmasturbate\nmasturbation\nhandjob\nblowjob\nfellatio\nnaked\nnude";
localStorage["whitelisted_websites"] = "";
localStorage["replace_sentence"] = false;
localStorage["block_paragraph"] = false;
localStorage["block_webpage"] = false;
localStorage["image_on"] = true;
localStorage["image_blocked_words"] = "sex\nbreast\nboob\npenis\nvagina\ndick\nfuck\nmasturbate\nmasturbation\nhandjob\nblowjob\nfellatio\nnaked\nnude\nbra \npanties\nrisque\nraunch\nmaxim\nplayboy\nstripper\nprostitute\nlingerie";
localStorage["image_whitelisted_websites"] = "";
localStorage["scanner_sensitivity"] = 50;
}
initialize_options();
// Will need to load the variables upon the first check from the content script. This will be done by checking to see if text_on is null. If it is, the background script will execute a function that will
// load the options from localStorage. If text_on is not null, that means the options have already been loaded and they will be used.
/*
This funtion takes in the options object which is declared below. It then reads in the options in localStorage and sets the options in the options object accordingly.
*/
function load_variables(options)
{
// All the following are in if statements to ensure that the option actually exists in localStorage. For example, if someone never turned on the block paragraph option, then that option wouldn't exist in localStorage
// and would throw an error if we tried to read from it. We then need another if statement for all the boolean values so that we get a boolean value and not the string that is returned by localStorage.
// Sets the text filter option
if (localStorage["text_on"])
{
if (localStorage["text_on"] == "true")
{
options.text_on = true;
}
else
{
options.text_on = false;
}
}
// Sets the blocked words list
if (localStorage["blocked_words"])
options.blocked_words = localStorage["blocked_words"];
// Sets the whitelisted websites list
if (localStorage["whitelisted_websites"])
options.whitelisted_websites = localStorage["whitelisted_websites"];
// Sets the replace sentence options
if (localStorage["replace_sentence"])
{
if (localStorage["replace_sentence"] == "true")
{
options.replace_sentence = true;
}
else
{
options.replace_sentence = false;
}
}
// Sets the block paragraph option
if (localStorage["block_paragraph"])
{
if (localStorage["block_paragraph"] == "true")
{
options.block_paragraph = true;
}
else
{
options.block_paragraph = false;
}
}
// Sets the block webpage option
if (localStorage["block_webpage"])
{
if (localStorage["block_webpage"] == "true")
{
options.block_webpage = true;
}
else
{
options.block_webpage = false;
}
}
// Sets the threshold for blocking a paragraph
if (localStorage["num_to_block_paragraph"])
options.num_for_paragraph = localStorage["num_to_block_paragraph"];
// Sets the threshold for blocking a webpage
if (localStorage["num_to_block_webpage"])
options.num_for_webpage = localStorage["num_to_block_webpage"];
// Sets the image filter option
if (localStorage["image_on"])
{
if (localStorage["image_on"] == "true")
{
options.image_on = true;
}
else
{
options.image_on = false;
}
}
// Sets the list of words to block images on
if (localStorage["image_blocked_words"])
options.image_blocked_words = localStorage["image_blocked_words"];
// Sets the whitelisted websites for the image filter
if (localStorage["image_whitelisted_websites"])
options.image_whitelisted_websites = localStorage["image_whitelisted_websites"];
// Sets the image scanner option
if (localStorage["image_scanner"])
{
if (localStorage["image_scanner"] == "true")
{
options.image_scanner = true;
}
else
{
options.image_scanner = false;
}
}
// Sets the sensitivity of the image scanner
if (localStorage["scanner_sensitivity"])
options.scanner_sensitivity = localStorage["scanner_sensitivity"];
}
// This is an object that holds all the options available for the user to set.
var options = new Object();
// This is a boolean value that tells if the text filter is on/off.
options.text_on = null;
// This is a string value that holds all the blocked words.
options.blocked_words = null;
// This is a string value that holds all the whitelisted websites.
options.whitelisted_websites = null;
// This is a boolean value. It is true if the user wants to replace the entire sentence containing a blocked word, and false otherwise.
options.replace_sentence = null;
// This is a boolean value. True means the user wants to block a paragraph after a specified number of blocked words.
options.block_paragraph = null;
// This is a boolean value. True means the user wants to block the webpage after a specified number of blocked words.
options.block_webpage = null;
// This is an integer. It gives the threshold for blocking a paragraph. If the user did not give a number, this will have the value NaN.
options.num_for_paragraph = null;
// This is an integer. It gives the threshold for blocking a webpage.
options.num_for_webpage = null;
// This is a boolean. True means the image filter is on.
options.image_on = null;
// This is a string. It contains all the words used to block images.
options.image_blocked_words = null;
// This is a string. It contains the list of whitelisted websites.
options.image_whitelisted_websites = null;
// This is a boolean. True means the image scanner is on.
options.image_scanner = null;
// This is an integer between 0 and 100. It tells the sensitivity of the image scanner as a percentage.
options.scanner_sensitivity = null;
// Function to pass options object to content script.
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.greeting == "request_options")
{
//window.alert("Get options message recieved."); // used for testing.
if (options.text_on == null)
{
//window.alert("Loading variables from localStorage."); // used for testing. Test Case 002
load_variables(options);
// line below used for testing in Test Cases 002
//window.alert("Options object after variable load: " + "\ntext_on " + options.text_on + "\n" + "blocked_words " + options.blocked_words + "\n" + "whitelisted_websites " + options.whitelisted_websites + '\n' + "replace_sentence " + options.replace_sentence + '\n' + "block_paragraph " + options.block_paragraph + '\n' + "block_webpage " + options.block_webpage + '\n' + "num_paragraph " + options.num_for_paragraph + '\n'+ "num_webpage " + options.num_for_webpage + '\n' + "image_on " + options.image_on + '\n' + "image_blocked_words " + options.image_blocked_words + '\n' + "image_whitelist " + options.image_whitelisted_websites + '\n'+ "image_scanner " + options.image_scanner + '\n' + "scanner_sensitivity " + options.scanner_sensitivity); //Used for testing.
}
//window.alert("No need for loading options object."); // Used for testing. Test Case 002. same for line below
//window.alert("Options object: " + "\ntext_on " + options.text_on + "\n" + "blocked_words " + options.blocked_words + "\n" + "whitelisted_websites " + options.whitelisted_websites + '\n' + "replace_sentence " + options.replace_sentence + '\n' + "block_paragraph " + options.block_paragraph + '\n' + "block_webpage " + options.block_webpage + '\n' + "num_paragraph " + options.num_for_paragraph + '\n'+ "num_webpage " + options.num_for_webpage + '\n' + "image_on " + options.image_on + '\n' + "image_blocked_words " + options.image_blocked_words + '\n' + "image_whitelist " + options.image_whitelisted_websites + '\n'+ "image_scanner " + options.image_scanner + '\n' + "scanner_sensitivity " + options.scanner_sensitivity); //Used for testing.
sendResponse({farewell: options});
}
});
<file_sep>package com.duruo.dto.FlowDataChild;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/6/27 10:37
*
* @Email <EMAIL>
*/
@Data
public class db_flow_jjkc_kfys_info {
private String Id;
private String Num;
private String DecomposeDetailed;
private String SpecialFunds;
private String SelfFinancing;
private String Remark;
}
<file_sep>
var href = "";
var host = "";
var title="";
var is_iframe = false;
var titleInterval;
try {
href=window.location.href;
host = href.split("/")[2];
} catch (e) {
//因为一些IFRAME权限读取TOP的属性,因此这里要TRY一下,并给一个默认值
href = window.location.href+"";
host = href.split("/")[2]+"";
}
//侦听alt键
/*
Mousetrap.bind('alt',function(){
doResumeSafe();
},'keyup');
*/
/*
$("html").dblclick(function(){
doResumeSafe();
});
*/
function doResumeSafe()
{
if(!hasSetSafeMode)
{
hasSetSafeMode=true;
}
else
{
if($("#fhzd_head_css_safe_mode").length>0)
{
doFindDelSafeMode();
}
else
{
//恢复
var head = document.getElementsByTagName('body').item(0);
if(head!=undefined)
{
//document.title="3";
if($("#fhzd_head_css_safe_mode").length==0)
{
var style = document.createElement('style');
style.type = 'text/css';
style.id='fhzd_head_css_safe_mode';
style.innerText="img {-webkit-mask-image: url(http://fhzd.org/360/source/mask.png)}";
head.appendChild(style);
}
}
}
}
}
function findTitle()
{
var title=(document.title + "");
if(title.indexOf("_百度贴吧")!=-1)
{
var tieba_title=title.split("_百度贴吧")[0];
if(fbgp.blackTiebaArr.indexOf(tieba_title)!=-1)
{
window.location.href="http://fhzd.org/zimingPlugin/wang_ye_jing_hua_qi/page/redirect.html";//chrome.extension.getURL('source/page/webConfirm.html');
clearInterval(titleInterval);
}
}
else{
clearInterval(titleInterval);
}
}
try{
if (window.frames.length != parent.frames.length) {
is_iframe=true;
}
}
catch(e)
{
//alert(e);
}
var fbgp;
chrome.extension.sendRequest({evt : "request_data"}, onFirstGetData);
var hao123Arr=[];
function onFirstGetData(_bgp)
{
fbgp=_bgp;
//alert(fbgp);
if( fbgp && fbgp.status == "start")
{
if(!is_iframe && fbgp.storage["limit_mode"]=="on" && String(location.href).indexOf("fhzd.org")==-1 && (String(location.href).indexOf("http://")!=-1 || String(location.href).indexOf("https://")!=-1))
{
if(!checkIsInLimitList(host))
{
var str="";
var data=fbgp.storage["limit_data"];
//data.replace(/http:\/\//, "");
//data.replace(/www/, "");
data.replace(/\*\./, "");
var arr2= data.split("\n");
for (var i = 0; i < arr2.length; i++) {
str+=arr2[i]+"_|_";
}
str=encodeURIComponent(str);
window.stop();
window.location.href="http://www.fhzd.org/360/redirect/?data="+str;
}
return;
}
if(fbgp.css)
{
if(host.indexOf("tieba.baidu.com")!=-1)
{
titleInterval=setInterval("findTitle();",200);
}
var arr=fbgp.css;
for(var i=arr.length-1;i>=0;i--)
{
if(arr[i].indexOf("##")!=-1)
{
var lineArr=arr[i].split("##");
var cssHost=lineArr[0];
if(host.indexOf(cssHost)!=-1)
{
var str=lineArr[1];
cssStr+=str+'{display:none;visibility:hidden;}\n';
//对hao123特别关照
if(host.indexOf("www.hao123.com")!=-1)
{
hao123Arr.push(str);
}
}
}
}
}
setFindHead();
}
}
var cssStr="";
var findHeadInterval;
function setFindHead()
{
//if(cssStr.length>0)
//{
findHeadInterval=setInterval("doFindHead();",100);
//}
}
var cssFindStep=0;
var hasSetSafeMode=false;
//var a=0;
function doFindHead()
{
//a++;
//document.title=a+"";
try{
var head = document.getElementsByTagName('body').item(0);
var cssTag=$("#fhzd_head_css");
if(head!=undefined )
{
//alert(1);
var isSE=(host.indexOf("www.soso.com")!=-1 || host.indexOf("www.sogou.com")!=-1 || host.indexOf("www.baidu.com")!=-1 || host.indexOf("www.haosou.com")!=-1 || host.indexOf("cn.bing.com")!=-1 || host.indexOf("www.youdao.com")!=-1);
if(cssStr.length>0)
{
//对百度搜索结果要特殊处理
if(host.indexOf("www.baidu.com")==-1)
{
//非百度的,把定时器设长点
clearInterval(findHeadInterval);
if(cssFindStep==0 && host.indexOf("www.hao123.com")!=-1)
{
clearInterval(findHeadInterval);
cssFindStep=1;
findHeadInterval=setInterval("doFindHead();",1000);
}
}
//alert(checkIsInSuperWhiteList(host)+" "+isSE)
if(cssTag.length==0 && (!checkIsInSuperWhiteList(host) || isSE))
{
var style = document.createElement('style');
style.type = 'text/css';
style.id='fhzd_head_css';
style.innerText=cssStr;
head.appendChild(style);
}
if(host.indexOf("www.hao123.com")!=-1)
{
for(var i=0;i<hao123Arr.length;i++)
{
$(hao123Arr[i]).css({"display":"none"});
}
}
}
if(fbgp.storage["safe_mode"]+""=="on" && !hasSetSafeMode && !checkIsInSuperWhiteList(host) && fbgp.status == "start")
{
hasSetSafeMode=true;
var style = document.createElement('style');
style.type = 'text/css';
style.id='fhzd_head_css_safe_mode';
style.innerText="img {-webkit-mask-image: url(http://fhzd.org/360/source/mask.png)}";
head.appendChild(style);
}
}
}
catch(e)
{
//alert(e);
}
}
function toggleSafeMode()
{
//document.title="1";
try
{
if(fbgp && fbgp.status == "start")
{
//document.title="2";
var head = document.getElementsByTagName('body').item(0);
if(head!=undefined)
{
//document.title="3";
if($("#fhzd_head_css_safe_mode").length>0)
{
//document.title="4";
doFindDelSafeMode();
//$("#fhzd_head_css_safe_mode").remove();
}
else
{
//document.title="5";
//alert(3);
//safe_mode_key=0;
var style = document.createElement('style');
style.type = 'text/css';
style.id='fhzd_head_css_safe_mode';
style.innerText="img {-webkit-mask-image: url(http://fhzd.org/360/source/mask.png)}";
head.appendChild(style);
}
}
}
}
catch(ee)
{
//alert(ee);
}
}
function doFindDelSafeMode()
{
$("#fhzd_head_css_safe_mode").each(function(){
$(this).remove();
});
}
function checkIsInSuperWhiteList(_host) {
var arr2= fbgp.super_white_list.split("#");
try
{
//判断是否在白名单贴吧
var mt="_百度贴吧";
var tieba_title="";
var url=location.href+"";
var title=document.title+"";
if(url.indexOf("http://tieba.baidu.com/f")==0)
{
//贴吧 某贴首页
if(title.indexOf(mt)!=-1)
{
tieba_title=title.split(mt)[0];
}
}
else if(url.indexOf("http://tieba.baidu.com/p/")==0)
{
//贴吧 帖子内容页
if(title.indexOf(mt)!=-1)
{
var arr=title.split("_");
tieba_title=arr[arr.length-2];
}
}
if(tieba_title!="" && fbgp.storage["white_tieba"].indexOf(tieba_title)!=-1)
{
return true;
}
}
catch(ee)
{
}
for (var i = 0; i < arr2.length; i++) {
if (_host.indexOf(arr2[i]) != -1 && arr2[i].length > 2) {
return true;
}
}
return false;
}
function checkIsInLimitList(_host) {
if(fbgp.webConfirmIgnoreMap["http://"+host]=="yes" || fbgp.webConfirmIgnoreMap["https://"+host]=="yes")
{
return true;
}
var data=fbgp.storage["limit_data"];
data=data.replace(/http:\/\//gi, "");
data=data.replace(/https:\/\//gi, "");
data=data.replace(/www\./gi, "");
data=data.replace(/\*\./gi, "");
//alert(_host+"\n\n"+data);
var arr2= data.split("\n");
for (var i = 0; i < arr2.length; i++) {
var item=arr2[i].split(" ")[1];
if (_host.indexOf(item) != -1 && item.length > 2) {
////alert(1);
return true;
}
}
return false;
}
<file_sep>package com.duruo.po;
import java.math.BigDecimal;
public class Corp {
private String corpInfoId;
private String organCode;
private String entityId;
private String corpName;
private String corpType;
private String personName;
private String address;
private String areaCode;
private String zip;
private String telephone;
private String establishDate;
private BigDecimal regCapital;
private String currency;
private String businessScope;
private String personCertType;
private String personCertCode;
private String industryCode;
private String organizers;
private String fundingSrc;
private String regNo;
private String receivingOrgan;
private String repealReason;
private String repealDate;
private String changeDate;
private String changeItem;
private String repealOrgan;
private String branchNum;
private String representNum;
private String regUpdDate;
private String taxpayersCode;
private String taxCode;
private String taxRegDate;
private String taxChgeContent;
private String taxChgeDate;
private String taxRepealReason;
private String taxRepealDate;
private String taxRepealOrgan;
private String businessAddress;
private String taxUpdDate;
private String organcodeDate;
private String orgcodeChgdate;
private String orgcodeRepealdate;
private String qsUpdDate;
private String bdResult;
private String qykId;
private String updTime;
private String fundsCode;
private String fundsOpenDate;
private String fundsRepealDate;
private String fundsaddCode;
private String fundsaddOpenDate;
private String fundsaddRepealDate;
private String fundsUpdDate;
private String socialSecurityCode;
private String socialSecurityUpdDate;
private String socialSecurityOpenDate;
private String fundsaddUpdDate;
private String socialSecurityRepealDate;
private String lkStatus;
private String isZmq;
private String trimCorpName;
private String corpStatus;
private String insertTime;
private String isGsl;
private String uniScId;
public String getCorpInfoId() {
return corpInfoId;
}
public void setCorpInfoId(String corpInfoId) {
this.corpInfoId = corpInfoId == null ? null : corpInfoId.trim();
}
public String getOrganCode() {
return organCode;
}
public void setOrganCode(String organCode) {
this.organCode = organCode == null ? null : organCode.trim();
}
public String getEntityId() {
return entityId;
}
public void setEntityId(String entityId) {
this.entityId = entityId == null ? null : entityId.trim();
}
public String getCorpName() {
return corpName;
}
public void setCorpName(String corpName) {
this.corpName = corpName == null ? null : corpName.trim();
}
public String getCorpType() {
return corpType;
}
public void setCorpType(String corpType) {
this.corpType = corpType == null ? null : corpType.trim();
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName == null ? null : personName.trim();
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address == null ? null : address.trim();
}
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode == null ? null : areaCode.trim();
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip == null ? null : zip.trim();
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone == null ? null : telephone.trim();
}
public String getEstablishDate() {
return establishDate;
}
public void setEstablishDate(String establishDate) {
this.establishDate = establishDate == null ? null : establishDate.trim();
}
public BigDecimal getRegCapital() {
return regCapital;
}
public void setRegCapital(BigDecimal regCapital) {
this.regCapital = regCapital;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency == null ? null : currency.trim();
}
public String getBusinessScope() {
return businessScope;
}
public void setBusinessScope(String businessScope) {
this.businessScope = businessScope == null ? null : businessScope.trim();
}
public String getPersonCertType() {
return personCertType;
}
public void setPersonCertType(String personCertType) {
this.personCertType = personCertType == null ? null : personCertType.trim();
}
public String getPersonCertCode() {
return personCertCode;
}
public void setPersonCertCode(String personCertCode) {
this.personCertCode = personCertCode == null ? null : personCertCode.trim();
}
public String getIndustryCode() {
return industryCode;
}
public void setIndustryCode(String industryCode) {
this.industryCode = industryCode == null ? null : industryCode.trim();
}
public String getOrganizers() {
return organizers;
}
public void setOrganizers(String organizers) {
this.organizers = organizers == null ? null : organizers.trim();
}
public String getFundingSrc() {
return fundingSrc;
}
public void setFundingSrc(String fundingSrc) {
this.fundingSrc = fundingSrc == null ? null : fundingSrc.trim();
}
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo == null ? null : regNo.trim();
}
public String getReceivingOrgan() {
return receivingOrgan;
}
public void setReceivingOrgan(String receivingOrgan) {
this.receivingOrgan = receivingOrgan == null ? null : receivingOrgan.trim();
}
public String getRepealReason() {
return repealReason;
}
public void setRepealReason(String repealReason) {
this.repealReason = repealReason == null ? null : repealReason.trim();
}
public String getRepealDate() {
return repealDate;
}
public void setRepealDate(String repealDate) {
this.repealDate = repealDate == null ? null : repealDate.trim();
}
public String getChangeDate() {
return changeDate;
}
public void setChangeDate(String changeDate) {
this.changeDate = changeDate == null ? null : changeDate.trim();
}
public String getChangeItem() {
return changeItem;
}
public void setChangeItem(String changeItem) {
this.changeItem = changeItem == null ? null : changeItem.trim();
}
public String getRepealOrgan() {
return repealOrgan;
}
public void setRepealOrgan(String repealOrgan) {
this.repealOrgan = repealOrgan == null ? null : repealOrgan.trim();
}
public String getBranchNum() {
return branchNum;
}
public void setBranchNum(String branchNum) {
this.branchNum = branchNum == null ? null : branchNum.trim();
}
public String getRepresentNum() {
return representNum;
}
public void setRepresentNum(String representNum) {
this.representNum = representNum == null ? null : representNum.trim();
}
public String getRegUpdDate() {
return regUpdDate;
}
public void setRegUpdDate(String regUpdDate) {
this.regUpdDate = regUpdDate == null ? null : regUpdDate.trim();
}
public String getTaxpayersCode() {
return taxpayersCode;
}
public void setTaxpayersCode(String taxpayersCode) {
this.taxpayersCode = taxpayersCode == null ? null : taxpayersCode.trim();
}
public String getTaxCode() {
return taxCode;
}
public void setTaxCode(String taxCode) {
this.taxCode = taxCode == null ? null : taxCode.trim();
}
public String getTaxRegDate() {
return taxRegDate;
}
public void setTaxRegDate(String taxRegDate) {
this.taxRegDate = taxRegDate == null ? null : taxRegDate.trim();
}
public String getTaxChgeContent() {
return taxChgeContent;
}
public void setTaxChgeContent(String taxChgeContent) {
this.taxChgeContent = taxChgeContent == null ? null : taxChgeContent.trim();
}
public String getTaxChgeDate() {
return taxChgeDate;
}
public void setTaxChgeDate(String taxChgeDate) {
this.taxChgeDate = taxChgeDate == null ? null : taxChgeDate.trim();
}
public String getTaxRepealReason() {
return taxRepealReason;
}
public void setTaxRepealReason(String taxRepealReason) {
this.taxRepealReason = taxRepealReason == null ? null : taxRepealReason.trim();
}
public String getTaxRepealDate() {
return taxRepealDate;
}
public void setTaxRepealDate(String taxRepealDate) {
this.taxRepealDate = taxRepealDate == null ? null : taxRepealDate.trim();
}
public String getTaxRepealOrgan() {
return taxRepealOrgan;
}
public void setTaxRepealOrgan(String taxRepealOrgan) {
this.taxRepealOrgan = taxRepealOrgan == null ? null : taxRepealOrgan.trim();
}
public String getBusinessAddress() {
return businessAddress;
}
public void setBusinessAddress(String businessAddress) {
this.businessAddress = businessAddress == null ? null : businessAddress.trim();
}
public String getTaxUpdDate() {
return taxUpdDate;
}
public void setTaxUpdDate(String taxUpdDate) {
this.taxUpdDate = taxUpdDate == null ? null : taxUpdDate.trim();
}
public String getOrgancodeDate() {
return organcodeDate;
}
public void setOrgancodeDate(String organcodeDate) {
this.organcodeDate = organcodeDate == null ? null : organcodeDate.trim();
}
public String getOrgcodeChgdate() {
return orgcodeChgdate;
}
public void setOrgcodeChgdate(String orgcodeChgdate) {
this.orgcodeChgdate = orgcodeChgdate == null ? null : orgcodeChgdate.trim();
}
public String getOrgcodeRepealdate() {
return orgcodeRepealdate;
}
public void setOrgcodeRepealdate(String orgcodeRepealdate) {
this.orgcodeRepealdate = orgcodeRepealdate == null ? null : orgcodeRepealdate.trim();
}
public String getQsUpdDate() {
return qsUpdDate;
}
public void setQsUpdDate(String qsUpdDate) {
this.qsUpdDate = qsUpdDate == null ? null : qsUpdDate.trim();
}
public String getBdResult() {
return bdResult;
}
public void setBdResult(String bdResult) {
this.bdResult = bdResult == null ? null : bdResult.trim();
}
public String getQykId() {
return qykId;
}
public void setQykId(String qykId) {
this.qykId = qykId == null ? null : qykId.trim();
}
public String getUpdTime() {
return updTime;
}
public void setUpdTime(String updTime) {
this.updTime = updTime == null ? null : updTime.trim();
}
public String getFundsCode() {
return fundsCode;
}
public void setFundsCode(String fundsCode) {
this.fundsCode = fundsCode == null ? null : fundsCode.trim();
}
public String getFundsOpenDate() {
return fundsOpenDate;
}
public void setFundsOpenDate(String fundsOpenDate) {
this.fundsOpenDate = fundsOpenDate == null ? null : fundsOpenDate.trim();
}
public String getFundsRepealDate() {
return fundsRepealDate;
}
public void setFundsRepealDate(String fundsRepealDate) {
this.fundsRepealDate = fundsRepealDate == null ? null : fundsRepealDate.trim();
}
public String getFundsaddCode() {
return fundsaddCode;
}
public void setFundsaddCode(String fundsaddCode) {
this.fundsaddCode = fundsaddCode == null ? null : fundsaddCode.trim();
}
public String getFundsaddOpenDate() {
return fundsaddOpenDate;
}
public void setFundsaddOpenDate(String fundsaddOpenDate) {
this.fundsaddOpenDate = fundsaddOpenDate == null ? null : fundsaddOpenDate.trim();
}
public String getFundsaddRepealDate() {
return fundsaddRepealDate;
}
public void setFundsaddRepealDate(String fundsaddRepealDate) {
this.fundsaddRepealDate = fundsaddRepealDate == null ? null : fundsaddRepealDate.trim();
}
public String getFundsUpdDate() {
return fundsUpdDate;
}
public void setFundsUpdDate(String fundsUpdDate) {
this.fundsUpdDate = fundsUpdDate == null ? null : fundsUpdDate.trim();
}
public String getSocialSecurityCode() {
return socialSecurityCode;
}
public void setSocialSecurityCode(String socialSecurityCode) {
this.socialSecurityCode = socialSecurityCode == null ? null : socialSecurityCode.trim();
}
public String getSocialSecurityUpdDate() {
return socialSecurityUpdDate;
}
public void setSocialSecurityUpdDate(String socialSecurityUpdDate) {
this.socialSecurityUpdDate = socialSecurityUpdDate == null ? null : socialSecurityUpdDate.trim();
}
public String getSocialSecurityOpenDate() {
return socialSecurityOpenDate;
}
public void setSocialSecurityOpenDate(String socialSecurityOpenDate) {
this.socialSecurityOpenDate = socialSecurityOpenDate == null ? null : socialSecurityOpenDate.trim();
}
public String getFundsaddUpdDate() {
return fundsaddUpdDate;
}
public void setFundsaddUpdDate(String fundsaddUpdDate) {
this.fundsaddUpdDate = fundsaddUpdDate == null ? null : fundsaddUpdDate.trim();
}
public String getSocialSecurityRepealDate() {
return socialSecurityRepealDate;
}
public void setSocialSecurityRepealDate(String socialSecurityRepealDate) {
this.socialSecurityRepealDate = socialSecurityRepealDate == null ? null : socialSecurityRepealDate.trim();
}
public String getLkStatus() {
return lkStatus;
}
public void setLkStatus(String lkStatus) {
this.lkStatus = lkStatus == null ? null : lkStatus.trim();
}
public String getIsZmq() {
return isZmq;
}
public void setIsZmq(String isZmq) {
this.isZmq = isZmq == null ? null : isZmq.trim();
}
public String getTrimCorpName() {
return trimCorpName;
}
public void setTrimCorpName(String trimCorpName) {
this.trimCorpName = trimCorpName == null ? null : trimCorpName.trim();
}
public String getCorpStatus() {
return corpStatus;
}
public void setCorpStatus(String corpStatus) {
this.corpStatus = corpStatus == null ? null : corpStatus.trim();
}
public String getInsertTime() {
return insertTime;
}
public void setInsertTime(String insertTime) {
this.insertTime = insertTime == null ? null : insertTime.trim();
}
public String getIsGsl() {
return isGsl;
}
public void setIsGsl(String isGsl) {
this.isGsl = isGsl == null ? null : isGsl.trim();
}
public String getUniScId() {
return uniScId;
}
public void setUniScId(String uniScId) {
this.uniScId = uniScId == null ? null : uniScId.trim();
}
}<file_sep>const hotSeachApi =
"https://api.weibo.cn/2/guest/page?gsid=_2AkMtqmJ0f8Nhq<KEY>jaIx-wwDEieKb9pOvJRMxHRl-wT9kqnAAtRV6Bm0NBHg_Q_-5Rx4sx0moY_1sSSEoN2zx&uid=1009882141998&wm=3333_2001&i=ddd48a6&b=0&from=1084393010&checktoken=745495b139d5d0943c12418acc7a08f8&c=<PASSWORD>&networktype=wifi&v_p=60&skin=default&s=ffffffff&v_f=1&did=10dc157a640f1c1bd53cbacbad02326f&lang=zh_CN&sflag=1&ft=0&moduleID=pagecard&uicode=10000011&featurecode=10000085&feed_mypage_card_remould_enable=1&luicode=10000003&count=20&extparam=filter_type%3Drealtimehot%26mi_cid%3D100103%26pos%3D0_0%26c_type%3D30%26display_time%3D1526132043&containerid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot&fid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot&page=1";
const hotWeiboApi =
"https://api.weibo.cn/2/guest/statuses_unread_hot_timeline?gsid=_2AkMsWcS5f8NhqwJRmPEdxGnjaIx-wwDEieKaBTViJRMxHRl-wT9jqhUHtRV6Bm0NBJtwNGf7sD9vWinqTxfteTn6j0PV&uid=1009882141998&wm=3333_2001&i=ddd48a6&b=0&from=1085193010&checktoken=745495b139d5d0943c12418acc7a08f8&c=iphone&networktype=4g&v_p=60&skin=default&s=ef3ddddd&v_f=1&did=10dc157a640f1c1bd53cbacbad02326f&lang=zh_CN&sflag=1&ua=iPhone9,2__weibo__8.5.1__iphone__os11.3&ft=0&aid=01AtRD1ZgBBPGE25lc8nv6Zf3kE2dc9EyFhUimttlBTNKYNmA.&cum=47EFCA86";
let containerid = {
"热门":"102803",
"小时":"102803_ctg1_9999_-_ctg1_9999",
"昨日":"102803_ctg1_8899_-_ctg1_8899",
"前日":"102803_ctg1_8799_-_ctg1_8799",
"周榜":"102803_ctg1_8698"
}
const template = {
views: [
{
type: "label",
props: {
id: "label",
textColor: $color("black"),
align: $align.center,
font: $font(14)
},
layout: function(make, view) {
make.right.top.bottom.inset(0);
make.left.inset(15);
}
},
{
type: "label",
props: {
id: "icon",
bgcolor: $rgb(254, 158, 25),
text: "热",
textColor: $color("white"),
radius: 2,
font: $font("bold", 11),
align: $align.center,
alpha: 0.8,
hidden: true
},
layout: function(make, view) {
make.right.inset(15);
make.width.equalTo(15);
make.height.equalTo(15);
make.centerY.equalTo();
},
events: {
tapped: function(sender) {}
}
}
]
};
const template2 = {
views: [
{
type: "label",
props: {
id: "label",
textColor: $color("black"),
align: $align.left,
font: $font(14),
lines:2
},
layout: function(make, view) {
make.right.inset(0);
make.centerY.equalTo()
make.left.inset(60);
}
},{
type: "label",
props: {
id: "name",
textColor: $color("black"),
align: $align.left,
font: $font("bold",13),
lines:2,
autoFontSize:true
},
layout: function(make, view) {
make.centerY.equalTo()
make.left.inset(10);
make.width.equalTo(40)
}
},
]
};
function weiboList(mode,temp) {
return {
type: "list",
props: {
id: mode,
template: temp,
//data:options
bgcolor: $color("clear"),
hidden: true,
rowHeight:mode=="fireList"?40:35,
actions: [
{
title: "微博",
color: $rgb(246,22,31), // default to gray
handler: function(sender, indexPath) {
$cache.set("app","weibo")
$app.openURL(sender.data[indexPath.row].label.info);
}
},
{
title: "墨客",
color:$rgb(69,134,209),
handler: function(sender, indexPath) {
$cache.set("app","moke")
if(mode == "fireList"){
$app.openURL("moke:///status?mid="+sender.data[indexPath.row].label.id)
}else{
let text = /.、([\s\S]*)/g.exec(sender.data[indexPath.row].label.text)[1]
$app.openURL("moke:///search/statuses?query="+encodeURI(text))
}
}
}
]
},
layout: function(make, view) {
make.left.right.top.inset(0)
make.bottom.inset(40)
},
events: {
didSelect: function(sender, indexPath) {
let app = $cache.get("app")||"weibo"
if(app=="weibo") $app.openURL(sender.data[indexPath.row].label.info);
else{
if(mode == "fireList"){
$app.openURL("moke:///status?mid="+sender.data[indexPath.row].label.id)
}else{
let text = /.、([\s\S]*)/g.exec(sender.data[indexPath.row].label.text)[1]
$app.openURL("moke:///search/statuses?query="+encodeURI(text))
}
}
}
}
};
}
weekInfo=""
function show() {
$ui.render({
props: {
title: "微博热点",
id: "weibo",
// navBarHidden:true,
},
views: [
weiboList("hotList",template),
weiboList("trendList",template),
weiboList("fireList",template2),
{
type: "tab",
props: {
id:"tab",
items: ["re搜", "趋势", "热门","小时","昨日","前日","zhou榜"],
bgcolor: $color("white"),
radius:5
},
layout: function(make, view) {
make.bottom.inset(15);
make.centerX.equalTo();
},
events: {
changed: function(sender) {
$ui.toast("载入中...",10)
if (sender.index == 0) getHotSearch();
else if (sender.index == 1) {
getHotSearch("trend");
} else if (sender.index == 2) {
getFire(containerid.热门);
}else if (sender.index == 3) {
getFire(containerid.小时);
}else if (sender.index == 4) {
getFire(containerid.昨日);
}else if (sender.index == 5) {
getFire(containerid.前日);
}else if (sender.index == 6) {
getFire(containerid.周榜);
week()
}
}
}
}
]
});
}
function week(){
$http.request({
method: "POST",
url: hotWeiboApi,
header: {
"User-Agent": "Weibo/27683 (iPhone; iOS 11.3; Scale/3.00) "
},
form: {
refresh: "pulldown",
group_id: "102803",
extparam: "discover|new_feed",
fid: "102803",
lon: "116.233115",
uicode: "10000225",
containerid: "102803_ctg1_8699_-_ctg1_8699",
featurecode: "10000225",
refresh_sourceid: "10000365",
since_id: "4242760586282015",
need_jump_scheme: "1"
},
handler: function(resp) {
let data = resp.data;
if (data.errmsg) {
alert(data.errmsg);
return;
}
weekInfo = data.cards[1].desc_extr
$ui.toast(data.cards[1].desc_extr,0.8)
}
})
}
function getFire(containerid="102803") {
$http.request({
method: "POST",
url: hotWeiboApi,
header: {
"User-Agent": "Weibo/27683 (iPhone; iOS 11.3; Scale/3.00) "
},
form: {
refresh: "pulldown",
group_id: "102803",
extparam: "discover|new_feed",
fid: "102803",
lon: "116.233115",
uicode: "10000225",
containerid: containerid,
featurecode: "10000225",
refresh_sourceid: "10000365",
since_id: "4242760586282015",
need_jump_scheme: "1"
},
handler: function(resp) {
let data = resp.data;
if (data.errmsg) {
alert(data.errmsg);
return;
}
// $clipboard.text=JSON.stringify(data)
$("hotList").hidden = true;
$("trendList").hidden = true;
$("fireList").hidden = false;
$("fireList").data = [];
if($("tab").index==2)
$ui.toast(data.remind_text_old, 1);
else if($("tab").index==6)
$ui.toast(weekInfo,1)
else
$ui.clearToast()
let hots = data.statuses;
for(let i=0;i<hots.length;i++){
$("fireList").data = $("fireList").data.concat({
label:{
text:hots[i].text,
info:hots[i].scheme,
id:/.*mblogid=([\s\S]*)/g.exec(hots[i].scheme)[1]
},
name:{
text:hots[i].user.name
}
})
}
}
});
}
function getHotSearch(mode = "hotSearch") {
// $ui.toast("载入中", 10);
$http.get({
url: hotSeachApi,
handler: function(resp) {
let data = resp.data;
if (data.errmsg) {
alert(data.errmsg);
return;
}
mode = mode == "hotSearch" ? 0 : data.cards.length - 1;
let hotCards = data.cards[mode].card_group;
$("hotList").data = [];
$("trendList").data = [];
if (mode == 0) {
$("hotList").hidden = false;
$("trendList").hidden = true;
$("fireList").hidden = true;
} else {
$("hotList").hidden = true;
$("trendList").hidden = false;
$("fireList").hidden = true;
}
for (let i = 0; i < hotCards.length; i++) {
let icon = {};
let prefix = "";
if (mode == 0) {
let num = i;
if (i == 0) num = "🏆";
else if (i == 1) num = "🥇";
else if (i == 2) num = "🥈";
else if (i == 3) num = "🥉";
prefix = num + "、";
if (hotCards[i].icon) {
if (hotCards[i].icon.indexOf("re") > 0) {
icon.hidden = false;
icon.text = "热";
icon.bgcolor = $rgb(254, 158, 25);
} else if (hotCards[i].icon.indexOf("xin") > 0) {
icon.hidden = false;
icon.text = "新";
icon.bgcolor = $rgb(254, 73, 95);
} else if (hotCards[i].icon.indexOf("jian") > 0) {
icon.hidden = false;
icon.text = "荐";
icon.bgcolor = $rgb(76, 173, 254);
} else if (hotCards[i].icon.indexOf("fei") > 0) {
icon.hidden = false;
icon.text = "沸";
icon.bgcolor = $rgb(247, 98, 0);
}
}
$("hotList").data = $("hotList").data.concat({
label: {
text: prefix + hotCards[i].desc,
info: hotCards[i].scheme
},
icon: icon
});
} else {
if (hotCards[i].icon) {
if (hotCards[i].icon.indexOf("sheng") > 0) {
icon.hidden = false;
icon.text = "⤴︎";
icon.bgcolor = $rgb(254, 75, 95);
}
}
$("trendList").data = $("trendList").data.concat({
label: {
text: prefix + hotCards[i].desc,
info: hotCards[i].scheme
},
icon: icon
});
}
}
$ui.toast(timeConvert(data.pageInfo.starttime)+" 更新", 1);
}
});
// alert($props($("tab")))
}
function timeConvert(unixTime){
let date = new Date(unixTime*1000);
// Hours part from the timestamp
let hours = date.getHours();
// Minutes part from the timestamp
let minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
let seconds = "0" + date.getSeconds();
let year = date.getFullYear()
let month = date.getMonth()+1
let dateN = date.getDate()
// Will display time in 10:30:23 format
let formattedTime = year + "-"+month+"-"+dateN+ " "+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
return formattedTime
}
function run() {
show();
getHotSearch();
}
run();
<file_sep>package com.example.demo.pojo;
import javax.persistence.*;
import java.util.Objects;
@Entity
@Table(name = "user", schema = "risk_assessment", catalog = "")
public class UserDO {
private int id;
private Integer permission;
private String password;
private String username;
private String department;
private String sex;
private String status;
private String position;
private String menuRole;
private String mobilePhone;
private String workNumber;
private String workerName;
private String userCompany;
private String userGroup;
private String userEmail;
private String userAddress;
private String userMessage;
private Integer userNewProjectCount;
@Id
@Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "permission")
public Integer getPermission() {
return permission;
}
public void setPermission(Integer permission) {
this.permission = permission;
}
@Basic
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
@Basic
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Basic
@Column(name = "department")
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Basic
@Column(name = "sex")
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Basic
@Column(name = "status")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Basic
@Column(name = "position")
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Basic
@Column(name = "menu_role")
public String getMenuRole() {
return menuRole;
}
public void setMenuRole(String menuRole) {
this.menuRole = menuRole;
}
@Basic
@Column(name = "mobile_phone")
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
@Basic
@Column(name = "work_number")
public String getWorkNumber() {
return workNumber;
}
public void setWorkNumber(String workNumber) {
this.workNumber = workNumber;
}
@Basic
@Column(name = "worker_name")
public String getWorkerName() {
return workerName;
}
public void setWorkerName(String workerName) {
this.workerName = workerName;
}
@Basic
@Column(name = "user_company")
public String getUserCompany() {
return userCompany;
}
public void setUserCompany(String userCompany) {
this.userCompany = userCompany;
}
@Basic
@Column(name = "user_group")
public String getUserGroup() {
return userGroup;
}
public void setUserGroup(String userGroup) {
this.userGroup = userGroup;
}
@Basic
@Column(name = "user_email")
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
@Basic
@Column(name = "user_address")
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
}
@Basic
@Column(name = "user_message")
public String getUserMessage() {
return userMessage;
}
public void setUserMessage(String userMessage) {
this.userMessage = userMessage;
}
@Basic
@Column(name = "user_new_project_count")
public Integer getUserNewProjectCount() {
return userNewProjectCount;
}
public void setUserNewProjectCount(Integer userNewProjectCount) {
this.userNewProjectCount = userNewProjectCount;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserDO that = (UserDO) o;
return id == that.id &&
Objects.equals(permission, that.permission) &&
Objects.equals(password, that.password) &&
Objects.equals(username, that.username) &&
Objects.equals(department, that.department) &&
Objects.equals(sex, that.sex) &&
Objects.equals(status, that.status) &&
Objects.equals(position, that.position) &&
Objects.equals(menuRole, that.menuRole) &&
Objects.equals(mobilePhone, that.mobilePhone) &&
Objects.equals(workNumber, that.workNumber) &&
Objects.equals(workerName, that.workerName) &&
Objects.equals(userCompany, that.userCompany) &&
Objects.equals(userGroup, that.userGroup) &&
Objects.equals(userEmail, that.userEmail) &&
Objects.equals(userAddress, that.userAddress) &&
Objects.equals(userMessage, that.userMessage) &&
Objects.equals(userNewProjectCount, that.userNewProjectCount);
}
@Override
public int hashCode() {
return Objects.hash(id, permission, password, username, department, sex, status, position, menuRole, mobilePhone, workNumber, workerName, userCompany, userGroup, userEmail, userAddress, userMessage, userNewProjectCount);
}
}
<file_sep>
var isWebConfirmInitOver=false;
var webConfirmDataUrl="http://www.fhzd.org/soft_data/black_domain.txt";
var webConfirm={};
webConfirm.init=function(_newPath)
{
if(_newPath!=storage["webconfirm_path"])
{
storage["webconfirm_path"]=_newPath;
webConfirm.getData();
}
else{
webConfirm.onGetData(storage["webConfirmData"],"success_local");
}
}
webConfirm.getData=function()
{
//alert("load black domain");
$.get(webConfirmDataUrl,webConfirm.onGetData);
}
webConfirm.onGetData=function(data,status)
{
if(status=="success" || status=="success_local")
{
if(status=="success")
{
storage["webConfirmDataSt"]=new Date().getTime()+"";
}
var arr=data.split("\r\n");
var str="";
for(var i=0;i<arr.length;i++)
{
var line=String(arr[i]);
if(line.indexOf("http://*.")==-1 && line.length>2)
{
line="http://*."+line+"\n";
}
str+=line;
}
storage["webConfirmData"]=str;
//alert(str);
isWebConfirmInitOver=true;
//storage["webConfirmData"]="";
createRequestData();
}
//loadNextData();
}
<file_sep>[TOC]
互联网信息内容垃圾过滤 :信息控制,智能过滤,内容质量审查,文字图片过滤
云过滤,人工智能,不良与垃圾信息过滤技术
片面,虚假,夸张,不实信息,诈骗等互联网不良与垃圾信息,简单干净,纯粹阅读
符合新闻道德的
客观公正,严谨,中肯,
真实,理性,正直
恪守新闻道德的媒体:为天下,尊重事实,正道,仁爱慈悲,符合人道,国民幸福,
不得自私、攻讦、诽谤、抄袭、造谣。(六)不侵犯个人隐私
准确、完整或核实构筑公信力
内容预先分级(过滤、屏蔽、替换、警示):极端、低俗恶俗等词汇过滤隐藏
伪道德,伪成熟,伪国学,成功学,励志鸡汤,网络暴力,污秽下流
引诱利用他人贪婪和恐惧的
网站信息挖掘,资讯追踪(时刻监视网络信息),项目相关情报收集,天机智讯,Google Alert:暂时使用插件过滤和Ctrl+F提示。
敏感词库:
技术类论坛过滤
知乎关键词:在系统,个人设置有一半,另一半主要是新闻热点,低俗恶俗庸俗内容。娱乐时尚等
微信关键词
RSS订阅类、自媒体过滤屏蔽
邮箱过滤屏蔽:
豆瓣关键词
天涯论坛,
新闻类媒体
简书类鸡汤套路文:
外网过滤屏蔽:
新加坡,英国,以色列,德国,俄国等媒体参考。主要屏蔽政治经济类
论坛贴吧评论
非道德、无礼、冒犯性词汇,恶性事件/暴力(伤害性、侮辱性和煽动性),常见大V等迷信崇拜、名人丑闻/明星绯闻,社会热点过滤,头条热搜过滤,营销软文过滤,娱乐八卦过滤,网络小说自动屏蔽:
反洗脑、思想毒奶、各种主义、近代史中遗毒(封建迂腐、满清谄媚、病态变态)、白左病毒、文革余毒,对立观念,恐吓、偏见,歧视,政治,不道德,黄赌毒,女权,各种社会运动、过度负面,负能量,时尚娱乐,游戏,传销,币圈,炒股炒币
其他低质量low内容:
总结:短句式+口语化+动词=杀伤力的情绪文案,顺口溜,画面感
低俗恶俗,低劣鄙陋、诱导、挑逗、煽动性、恶意、攻击性、情绪化词汇,扭曲偏歪词汇,狭隘,暴力、极端:
这种人
甚至
竟然
必定
如果不
可怕
鄙视
应该
后果
极端,政治词汇过滤,狭隘
真伪,威权,独裁专制,恐怖,无知,封闭狭隘
涉政涉及敏感 过滤:民族,中共,法轮,基督,共产党,江泽民,统治,斗争
中国政府,北京政府,政府,中国,人权,竟然,甚至,即使,共产,组织,政,国,利用,阴谋论,手段,!,必定,必须,毛泽东,习近平
白名单:主要纯技术、学习、云服务类
note.youdao.com
yinxiang.com
github.com
icloud.com
douban.com
jianshu.com
getpocket.com
mindzip.net
shouqu.me
segmentfault.com
inoreader.com
feedly.com
yilan.io
360doc.com
zhihu.com
搜索引擎:
sougo.com
baidu.com
google.com
自动屏蔽日语(3个词以上),日本姓氏
<file_sep>module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= grunt.template.today("yyyy-mm-dd HH:MM:ss") %>\n' + '<%= pkg.homepage ? "* " + pkg.homepage + "\\n" : "" %>' + ' * Copyright (c) <%= grunt.template.today("yyyy") %>\n * Powered by <%= pkg.author.team%>' + '\n */\n',
concat: {
options: {
separator: ';'
},
module: {
nonull: true,
files: {
'<%= pkg.cfg.releasePath %>/zlsh.lib.js': [
"./htdocs/js/lib/txv.core.min.js",
"./htdocs/js/lib/bootstrap.min.js",
"./htdocs/js/lib/jquery.simplePagination.js",
"./htdocs/js/lib/json2.js",
],
'<%= pkg.cfg.releasePath %>/zlsh.main.js': [
"./htdocs/js/common/*.js",
"./htdocs/js/typemap.js",
"./htdocs/js/dataquery.js",
"./htdocs/js/main.js",
]
}
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> <%= grunt.template.today("yyyy-mm-dd") %> */\n'//添加banner
},
release: {
options: {
report: "min",
footer:'\n/*! <%= pkg.name %> 最后修改于: <%= grunt.template.today("yyyy-mm-dd") %> */'//添加footer
},
files: [{
expand: true,
cwd: '<%= pkg.cfg.releasePath %>',
src: ['**/*.js'],
dest: '<%= pkg.cfg.releasePath %>',
rename: function(dest, src) {
return dest + src.replace(/\.js$/, ".js");
}
}]
}
},
watch: {
js: {
files: ['./htdocs/**/*.js'],
tasks: ['copy:js'],
options: {
interval: 300
}
},
html: {
files: ['./htdocs/**/*.html'],
tasks: ['copy:html'],
options: {
interval: 300
}
},
css: {
files: ['./htdocs/**/*.css'],
tasks: ['copy:css'],
options: {
interval: 300
}
}
},
copy: {
js : {
files :[{
expand : true,
cwd: '<%= pkg.cfg.devpath %>',
src: ['**/*.js'],
dest : '\\\\10.6.207.60\\livesvn\\ancheltong\\shenhe\\htdocs',
filter : 'isFile'
}]
},
html : {
files :[{
expand : true,
cwd: '<%= pkg.cfg.devpath %>',
src: ['**/*.html'],
dest : '\\\\10.6.207.60\\livesvn\\ancheltong\\shenhe\\htdocs',
filter : 'isFile'
}]
},
css : {
files :[{
expand : true,
cwd: '<%= pkg.cfg.devpath %>',
src: ['**/*.css'],
dest : '\\\\10.6.207.60\\livesvn\\ancheltong\\shenhe\\htdocs',
filter : 'isFile'
}]
}
},
clean : {
distjs: {
files: [{
expand: true,
cwd: '<%= pkg.cfg.releasePath %>',
src: ['**/*.js']
}]
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-banner');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('core', ['clean', 'concat', 'uglify']);
grunt.registerTask('build', ['core', 'copy:html', 'copy:js']);
grunt.registerTask('default', ['build']);
};<file_sep>// JavaScript Document
/*
本人写的一个可以用鼠标拖拽的窗体<br />
功能类似JS里边的window.open()<br />
然而有时候我们想要改变open出来页面的外观却难以办到<br />
所以就小小的写了这个东西,希望大家喜欢和加以完善<br />
主要函数说明
dailog 主要用于构建对话框体
参数 url,title,width,height,margin_top,margin_left,scrolling
参数说明 要在窗体显示的文档URL,窗体的标题,窗体宽,窗体高,距离浏览器顶部的距离,距离浏览器左边的距离
dailog_move 控制窗体的移动
参数 eventObj,moveObj
参数说明 eventObj鼠标拖拽的对象,moveObj拖拽鼠标移动的对象
1--原创,欢迎修改完善 欢迎加我QQ279074838交流学习-
修改:
1、这次修改了窗体在超长页面不能正确定位的BUG
2、窗体是否可滑动
2009-5-6
*/
var isMove=false//窗体移动状态
function dailog(content,title,width,height,margin_top,margin_left,scrolling)
{
if(document.getElementById("dailog_body")!=null)
{
//alert("只能打开一个窗口")
return false;
}
//对话框体
var dailog_body=document.createElement("div");
dailog_body.id="dailog_body"
//dailog_body.style.top=margin_top;
dailog_body.style.cssText = "top:expression(this.parentNode.scrollTop +"+margin_top+"+ 'px');"
dailog_body.style.left=margin_left;
dailog_body.style.height=height;
dailog_body.style.width=width;
dailog_body.style.position="absolute";
dailog_body.style.border="1px solid #EFEFEF";
//标题
var dailog_title=document.createElement("div");
dailog_title.id="dailog_title"
dailog_title.style.top=0;
dailog_title.style.left=0;
dailog_title.style.height=25;
dailog_title.style.width=width;
dailog_title.style.color="#ffffff";
dailog_title.style.fontWeight="bold";
dailog_title.style.cursor="default"
dailog_title.style.background="#0099FF";
dailog_title.innerHTML="<div style='float:left;height:25px;width:50%;font-family:微软雅黑;font-size:14px;line-height:25px;text-indent:5px'>"+title+"</div><div id='os' style='float:right;height:20px;width:16px;font-family:微软雅黑;font-size:14px;line-height:20px;margin-right:1px'><a href='javascript:dailog_close()' title='关闭'>×</a></div>"
//内容
var dailog_content=document.createElement("div");
dailog_content.id="dailog_content"
dailog_content.style.top=0;
dailog_content.style.left=0;
dailog_content.style.height=height-20;
dailog_content.style.width=width;
dailog_content.innerHTML=content;
dailog_content.style.padding="5px 5px 5px 5px";
dailog_title.onmouseover=Function(dailog_move(dailog_title,dailog_body));
dailog_body.appendChild(dailog_title)
dailog_body.appendChild(dailog_content)
document.body.appendChild(dailog_body);
$(dailog_body).css({"left":margin_left+"px","top":margin_top+"px"});
alert(dailog_body);
}
/*function chageBorderColor(obj,arg)//关闭按钮外观改变函数
{
obj.style.border=""+arg+"px solid #000"
}*/
function dailog_close()//窗体关闭函数
{
document.body.removeChild(dailog_body)
}
function dailog_move(eventObj,moveObj)//窗体移动函数
{
var x,y;
eventObj.onmousedown=function()//鼠标按下的时候
{
isMove=true;//移动状态为true
with(moveObj)
{
style.position="absolute";
var temp1=offsetLeft;
var temp2=offsetTop;
x=window.event.clientX;
y=window.event.clientY;
document.onmousemove=function()
{
if(!isMove)return false;
with(this)
{
style.left=temp1+window.event.clientX-x+"px";
style.top=temp2+window.event.clientY-y+"px";
}
}
}
document.onmouseup=new Function("isMove=false");
}
}<file_sep>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUi from 'element-ui'
import store from 'src/store/index'
import VueResource from 'vue-resource'
import App from './App'
import router from './router'
import { cookie } from './config/cookie'
import COOKIE from 'src/cookie/index'
import * as filters from 'src/config/filterConfig'
Vue.config.productionTip = false;
Vue.use(ElementUi);
Vue.use(VueResource);
Vue.http.options.emulateJSON = true;// requestHeader compatible
/* 全局 filters */
Object.keys(filters).forEach(i => Vue.filter(i, filters[i]));
router.beforeEach((to, from, next) => {
/* 以检测cookie 判断 跳转 */
if (cookie(COOKIE.userId) === null ||
cookie(COOKIE.userName) === null ||
cookie(COOKIE.auth) === null) {
if (to.path.indexOf('login') === -1) { // ---不在登陆页
next({ path: '/login' });
} else {
next();
}
} else {
next();
}
});
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
});
<file_sep>// JavaScript Document
var MAX_CASE_TXT_LENGTH=500;
var bgp=chrome.extension.getBackgroundPage();
var pageMode=bgp.storage["newTabPageMode"];
var imageTabList=new Array();
var curLoadIndex=0;
try
{
$(document).ready(function () {
if(!bgp.is_jian)
{
document.body.innerHTML=bgp.s2t(document.body.innerHTML);
}
init();
});
}
catch(e)
{
alert(e+" from newTab.js");
}
function init()
{
var cv=(chrome.app.getDetails().version+"");
$("#title").text("净网 V"+cv);
$("#_save_black_list_btn").click(function(){
saveBlackList();
});
createBlackList();
$("#_save_white_list_btn").click(function(){
saveWhiteList();
});
createWhiteList();
$("#_save_my_key_word_btn").click(function(){
saveMyKeyWord();
});
createKeyWordList();
$("#_save_my_limit_btn").click(function(){
saveMyLimit();
});
$("#_save_my_wtb_btn").click(function(){
saveMyWhiteTieba();
});
$("#_save_my_btb_btn").click(function(){
saveMyBlackTieba();
});
createCheckSysBlack();
createCheckPer();
createLimitList();
createWhiteTieba();
createBlackTieba();
createAdminCode();
}
function createCheckSysBlack()
{
if(bgp.storage["user_sys_black_list"]=="true")
{
$("#_check0").attr("checked","checked");
}
$("#_check0").click(function(){
if($("#_check0").attr("checked")=="checked")
{
chrome.extension.sendRequest({evt: "request_save_use_sys_black",value:"true"}, function(){});
}
else
{
chrome.extension.sendRequest({evt: "request_save_use_sys_black",value:"false"}, function(){});
}
});
}
function createCheckPer()
{
if(bgp.storage["show_ai_per"]=="on")
{
$("#_check1").attr("checked","checked");
}
$("#_check1").click(function(){
if($("#_check1").attr("checked")=="checked")
{
chrome.extension.sendRequest({evt: "request_save_show_ai_per",value:"on"}, function(){});
}
else
{
chrome.extension.sendRequest({evt: "request_save_show_ai_per",value:"off"}, function(){});
}
});
}
function saveBlackList()
{
var text=$("#_black_list_text").attr("value");
chrome.extension.sendRequest({evt: "request_save_my_black_list",value:text}, function(){});
alert("保存成功!");
}
function createBlackList()
{
var list=bgp.storage["myBlackList"];
$("#_black_list_text").attr("value",list);
}
function saveWhiteList()
{
var text=$("#_white_list_text").attr("value");
chrome.extension.sendRequest({evt: "request_save_my_white_list",value:text}, function(){});
alert("保存成功!");
}
function createWhiteList()
{
var list=bgp.storage["my_white_list_3"];
$("#_white_list_text").attr("value",list);
}
function saveMyKeyWord()
{
var text=$("#_my_key_word").attr("value");
chrome.extension.sendRequest({evt: "request_save_my_key_word",value:text}, function(){});
alert("保存成功!");
}
function createKeyWordList()
{
var list=bgp.storage["my_key_word"];
$("#_my_key_word").attr("value",list);
}
function saveMyLimit()
{
var text=$("#_my_limit").attr("value");
chrome.extension.sendRequest({evt: "request_save_my_limit",value:text}, function(){});
alert("保存成功!");
}
function createLimitList()
{
var list=bgp.storage["limit_data"];
$("#_my_limit").attr("value",list);
}
function createWhiteTieba()
{
var list=bgp.storage["white_tieba"];
$("#_my_wtb").attr("value",list);
}
function createBlackTieba()
{
var list=bgp.storage["my_black_tieba"];
$("#_my_btb").attr("value",list);
}
function createAdminCode()
{
var list=bgp.storage["admin_code"];
$("#_admin_code").attr("value",list);
if(bgp.storage["admin_code"]=="000000")
{
$("#_admin_code_tips").html("[已成为管理员]");
}
}
function saveMyWhiteTieba()
{
var text=$("#_my_wtb").attr("value");
chrome.extension.sendRequest({evt: "request_save_my_white_tieba",value:text}, function(){});
alert("保存成功!");
}
function saveMyBlackTieba()
{
var text=$("#_my_btb").attr("value");
chrome.extension.sendRequest({evt: "request_save_my_black_tieba",value:text}, function(){});
alert("保存成功!");
}
var frameWidth=192;
var frameHeight=120;
function getDateFormat()
{
var date=new Date();
var y=date.getYear();
var m=(date.getMonth()+1);
var d=date.getDate();
return y+"-"+m+"-"+d;
}
function showTipsFrame(_title,_content)
{
bgp=chrome.extension.getBackgroundPage();
var closeBtn=document.getElementById("div_knowledge_frame_close_btn");
var div=document.getElementById("div_knowledge_frame");
var divContent=document.getElementById("div_knowledge_frame_content");
var title=document.getElementById("div_knowledge_title");
if(div.style.display=="none")
{
div.style.display="block";
}
else
{
div.style.display="none";
return;
}
title.innerHTML=_title
closeBtn.addEventListener("click",function(e){
div=document.getElementById("div_knowledge_frame");
div.style.display="none";
});
divContent.innerHTML=_content;
}
function setFlashSize(_w,_h)
{
//alert(_w+" "+_h);
try
{
var zujian=thisMovie("zujian");
zujian.style.width=_w+"px";
zujian.style.height=_h+"px";
}
catch(e)
{
alert(e+"");
}
}
function thisMovie(movieName) {
if (navigator.appName.indexOf("Microsoft") != -1) {
return window[movieName]
}else{
return document[movieName]
}
}
<file_sep>package com.duruo.service;
import com.duruo.common.ServerResponse;
import com.duruo.po.User;
import com.duruo.po.UserPo;
import com.duruo.vo.UserVo;
import java.util.List;
/**
* Created by @Author tachai
* date 2018/6/10 17:20
*
* @Email <EMAIL>
*/
public interface IUseService {
ServerResponse<User> login(String username, String password);
ServerResponse<UserVo> selectById(Integer id);
// ServerResponse<List<User>> select
ServerResponse<List<UserVo>> list(UserPo user);
ServerResponse<String> insertUser(UserPo user);
ServerResponse<String> deleteUser(Integer userId);
ServerResponse<String> updateUser(UserPo user);
ServerResponse<String> resetPassword(Integer userId);
}
<file_sep>package com.duruo.util;
import com.duruo.common.DataSourceContextHolder;
import com.duruo.dao.CorpMapper;
import com.duruo.po.Corp;
import org.springframework.beans.factory.annotation.Autowired;
import javax.xml.crypto.Data;
import java.math.BigDecimal;
import java.util.Date;
/**
* Created by @Author tachai
* date 2018/9/17 12:16
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
public class CheckQchuang {
@Autowired
private CorpMapper corpMapper;
private String checkUniScId(String uniScId){
//切换数据源到oracle
DataSourceContextHolder.setDBType("oracle");
Corp corp = corpMapper.selectByUniScId(uniScId);
//切换数据源到mysql
DataSourceContextHolder.setDBType("mysql");
if(corp!=null){
// 1.判断企业经营范围(中介和劳务派遣打回)
if(corp.getBusinessScope().indexOf("劳务派遣")!=-1||corp.getBusinessScope().indexOf("中介")!=-1){
return "否";
}
// 2.判断企业注册时间(判断注册时间是否为“上一年”如:2018年办理,判断企业注册时间是否为2017年,之前注册的都打回)
Date date = new Date();
date.getYear();
if(corp.getEstablishDate().indexOf(date.getYear()-1+"")!=-1){
return "否";
}
////3.判断企业注册资金(判断注册资金是不是200W以下,以上的都打回)
if(corp.getRegCapital().compareTo(new BigDecimal(2000000))>0){
return "否";
}
// 4.判断企业营业地点(是否是在徐汇)
//可以不做判断
if(corp.getBusinessAddress().indexOf("徐汇")==-1){
return "否";
}
////5.是否是合伙企业(合伙企业不能办)
}
return "没有找到相关的工商信息,可能输入的同一信用代码有误";
}
public static void main(String[] args) {
String date = "02-12月-93 12.00.00.000000000 上午";
System.out.println(DateTimeUtil.strToDate(date.substring(0,9).replace("月",""),"dd-MM-yy"));
Date now = new Date();
System.out.println(now.getYear()-100);
}
}
<file_sep>// ==UserScript==
// @name Web Search Result Domain Filter
// @namespace WebSearchResultDomainFilter
// @description Filter search result based on domain names on web search of Bing, DuckDuckGo, Google, Yahoo. Some include search for news, books, etc. All exclude search for images and videos.
// @author jcunews
// @homepageURL https://greasyfork.org/en/users/85671-jcunews
// @version 1.0.1
// @license GNU AGPLv3
// @include *://www.bing.com/search*
// @include *://www.bing.com/news/search*
// @include *://duckduckgo.com/*
// @include *://www.google.*/search*
// @include *://www.google.*.*/search*
// @include *://search.yahoo.com/yhs/search*
// @include *://*.search.yahoo.com/search*
// @grant none
// ==/UserScript==
(function(filter, rx, getItems, getHostName, itemSelector, itemLinkSelector, setupEditFilterLink, cssPatch, items, ele, i, j, excLink, link, createFilterLink, filterEditor, gg) {
filter = JSON.parse(localStorage.WebSearchResultDomainFilter || "[]");
rx = filter.join("|").replace(/\./g, "\\.") ? (new RegExp(filter.join("|").replace(/\./g, "\\."))) : null;
cssPatch = "";
excLink = document.createElement("DIV");
filterEditor = document.createElement("DIV");
gg = location.hostname.indexOf(".google.") > 0;
function trim(s) {
return s.replace(/^(\s+|\r+|\n+)|(\s+|\r+|\n+)$/g, "");
}
function updateFilter() {
localStorage.WebSearchResultDomainFilter = JSON.stringify(filter);
rx = filter.join("|").replace(/\./g, "\\.");
rx = rx ? (new RegExp(filter.join("|").replace(/\./g, "\\."))) : null;
}
function abortEvent(ev) {
ev.preventDefault();
if (ev.stopPropagation) ev.stopPropagation();
if (ev.stopImmediatePropagation) ev.stopImmediatePropagation();
}
function processItems(items, i, link, lnk, hn) {
if (getItems) {
items = getItems();
} else items = document.querySelectorAll(itemSelector);
for (i = items.length-1; i >= 0; i--) {
link = items[i].querySelector(itemLinkSelector);
if (!link) continue;
if (!link.parentNode.querySelector(".domainFilterLink")) {
lnk = excLink.cloneNode(true);
lnk.addEventListener("click", function(ev) {
hn = getHostName(this.parentNode.querySelector("A"));
if (!confirm('Do you want to hide all search result from below domain name?\n\n' + hn + '\n\nNote:\nSubdomain is not included.\ni.e. hiding "abc.com" will not hide "sub.abc.com" or vice versa.')) return;
filter.push(hn);
updateFilter();
processItems();
abortEvent(ev);
}, true);
link.parentNode.appendChild(lnk);
if (gg && ((lnk.offsetLeft + lnk.offsetWidth) >= link.parentNode.offsetWidth)) {
lnk.style.cssText = "position:absolute;top:" + (((link.parentNode.offsetHeight - lnk.offsetHeight) / 2) >> 0) + "px;right:-" + lnk.offsetWidth + "px;margin-left:0";
link.parentNode.parentNode.insertBefore(lnk, link.parentNode);
}
}
if (rx) {
items[i].style.display = rx.test(getHostName(link)) ? "none" : "";
} else items[i].style.display = "";
}
}
if ((/www\.bing\.com\/search/).test(location.href)) {
itemSelector = "#b_results .b_algo";
itemLinkSelector = "h2 > a";
createFilterLink = function() {
editFilterLink = document.createElement("A");
editFilterLink.style.marginLeft = "3ex";
return b_tween.appendChild(editFilterLink);
};
cssPatch = '#b_results{width:580px}';
} else
if ((/www\.bing\.com\/news\/search/).test(location.href)) {
itemSelector = "#algocore .newsitem";
itemLinkSelector = ".title";
createFilterLink = function(ele) {
editFilterLink = document.createElement("A");
editFilterLink.style.cssText = 'float:left;margin:.85em 0 0 3ex';
ele = document.querySelector(".nf .menu > ul");
return ele.appendChild(editFilterLink);
};
cssPatch = '.search .newsitem .caption a.title{display:inline!important}';
} else
if ((/duckduckgo\.com/).test(location.hostname)) {
itemSelector = "#links .result";
itemLinkSelector = ".result__title > a";
createFilterLink = function(ele) {
ele = document.querySelector(".organic-filters");
if (!ele || !ele.childElementCount) return;
editFilterLink = document.createElement("A");
return ele.appendChild(editFilterLink);
};
cssPatch = '#b_results{width:580px}';
if (window.nrn) {
window._nrn = window.nrn;
window.nrn = function(res) {
res = window._nrn.apply(this, arguments);
processItems();
return res;
};
}
} else
if ((/www\.google\./).test(location.hostname)) {
itemSelector = "#rso .g";
itemLinkSelector = ".r a";
createFilterLink = function() {
editFilterLink = document.createElement("A");
editFilterLink.style.marginLeft = "10ex";
return resultStats.appendChild(editFilterLink);
};
} else
if ((/search\.yahoo\.com/).test(location.hostname)) {
itemLinkSelector = ".title > a, h4 > a";
getItems = function() {
return Array.prototype.slice.call(document.querySelectorAll(".searchCenterMiddle > li, .compArticleList > li")).filter(
function(v) {
return !(/\bsys_/).test(v.firstElementChild.className);
}
);
};
createFilterLink = function(ele) {
editFilterLink = document.createElement("A");
if (window["refiner-time"]) {
editFilterLink.style.cssText = 'margin-left:6ex';
return window["refiner-time"].appendChild(editFilterLink);
} else {
ele = document.querySelector("#sidebar .bd");
return ele.appendChild(editFilterLink);
}
};
cssPatch = '.search .newsitem .caption a.title{display:inline!important}';
getHostName = function(link, a) {
a = unescape(link.href).match(/\/RU=(http.*?)\/R[A-Z]=/);
if (a) {
a = a[1].match(/\/\/(.*?)\//)[1];
} else a = link.hostname;
return a;
};
}
if (!(getItems || itemSelector)) return;
if (!getHostName) {
getHostName = function(link) {
return link.hostname;
};
}
filterEditor.id = "filterEditor";
filterEditor.innerHTML = `
<style>${cssPatch}
.domainFilterLink{display:inline-block;margin-left:1ex;border-radius:4px;padding:0 .5ex;background-color:#d00;color:#fff;font-size:10pt;font-weight:bold;cursor:pointer}
#domainFilterEditLink{cursor:pointer}
#domainFilterEditor{display:none;position:fixed;z-index:999;left:33%;top:20%;right:33%;border-radius:5px;padding:15px;background-color:#ccc}
#domainFilterEditor textarea{margin-bottom:15px;width:100%;min-width:100%;max-width:100%;height:20em;min-height:5em;max-height:30em;box-sizing:border-box}
#domainFilterEditor div{padding:.3em 1ex;background-color:#000;color:#fff;font-weight:bold}
#domainFilterEditor table{width:100%;text-align:center}
#domainFilterEditor button{width:10ex}
</style>
<div id="domainFilterEditor">
<style></style>
<div>Edit Domain Filter</div>
<textarea id="domainFilterEditorEdit"></textarea>
<table><tr>
<td><button id="domainFilterEditorOk">OK</button></td>
<td><button id="domainFilterEditorCancel">Cancel</button></td>
</tr></table>
</div>`;
document.body.appendChild(filterEditor);
domainFilterEditorOk.addEventListener("click", function(ev, txt) {
txt = trim(domainFilterEditorEdit.value);
filter = txt.split("\n").reduce(function(prev, cur) {
cur = trim(cur);
if (cur) prev.push(cur);
return prev;
}, []);
updateFilter();
processItems();
domainFilterEditor.firstElementChild.innerHTML = "";
abortEvent(ev);
}, true);
domainFilterEditorCancel.addEventListener("click", function(ev) {
domainFilterEditor.firstElementChild.innerHTML = "";
abortEvent(ev);
}, true);
excLink.textContent = "X";
excLink.title = "Exclude this domain name from search result";
excLink.className = "domainFilterLink";
(function addEditFilterLink() {
if (editFilterLink = createFilterLink()) {
editFilterLink.textContent = "Edit Domain Filter";
editFilterLink.title = "Edit search result domain filter";
editFilterLink.id = "domainFilterEditLink";
editFilterLink.addEventListener("click", function(ev, txt) {
txt = filter.join("\n");
domainFilterEditorEdit.value = txt + (txt ? "\n" : "");
domainFilterEditor.firstElementChild.innerHTML = `
body>*{display:none!important}
#filterEditor{display:block!important}
#domainFilterEditor{display:block}`;
abortEvent(ev);
}, true);
processItems();
} else setTimeout(addEditFilterLink, 1000);
})();
})();
<file_sep>export default {
USER_MENU_TREE: 'USER_MENU_TREE', // --- 用户操作树,,get_user_menu_tree
ROUTER_PATH: '', // --- 用户访问路径
CLUB_NAME: 'CLUB_NAME',
USER_REAL_NAME: 'USER_REAL_NAME',
USER_FUNCTION: 'USER_FUNCTION', // 按钮权限
// CHECK_RESULT: 'CHECK_RESULT', //
/* 后门 */
/* 此用window.localStorage 赋值 */
CLEAR_GET_TOHANDLE_LIST_TIMER: 'CLEAR_GET_TOHANDLE_LIST_TIMER', // 获取待处理列表timer
CLEAR_GET_HAVEHANDLE_LIST_TIMER: 'CLEAR_GET_HAVEHANDLE_LIST_TIMER', // 获取已处理列表timer
CLEAR_GET_INHANDLE_LIST_TIMER: 'CLEAR_GET_INHANDLE_LIST_TIMER',
CLEAR_UNDO_MSG_TIMER: 'CLEAR_UNDO_MSG_TIMER', //
};
<file_sep>package com.duruo.vo;
import lombok.Data;
/**
* Created by @Author tachai
* date 2018/6/19 14:20
*
* @Email <EMAIL>
*/
@Data
public class StAuditVo {
//企业id
private String creditcode;
//项目id
private String sn;
//企业名称
private String realname;
//项目名称
private String project;
//项目编号
private String projectnum;
//项目所属技术领域
private String technical;
//项目总预算
private String generalBudget;
//项目专项资金
private String specialFunds;
//项目自筹资金
private String selfFinancing;
//项目当年开发费用
private String developmentCost;
//专家评定结果
private String shyj2;
}
<file_sep>package com.duruo.util;
import com.duruo.common.Const;
import com.duruo.po.User;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by @Author tachai
* date 2018/6/10 17:02
*
* @Email <EMAIL>
*/
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
User user=(User)request.getSession().getAttribute(Const.CURRENT_USER);
if(user!=null){
return true;
}else {
response.sendRedirect("login.html");
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
<file_sep>function replaceObj(theObj, temObj) {
Object.keys(temObj).forEach((key) => {
if (!theObj.hasOwnProperty(key)) return;
if (typeof theObj[key] === 'object') { // 数组或对象
if (theObj[key] instanceof Array) { // 数组
theObj[key] = temObj[key];
} else { // 对象
replaceObj(theObj[key], temObj[key]);
}
} else { // 普通类型
theObj[key] = temObj[key];
}
});
}
export default replaceObj;
<file_sep>package com.duruo.util;
import com.alibaba.fastjson.JSON;
import com.duruo.common.ServerResponse;
import com.duruo.dto.Query;
import com.google.gson.*;
import com.iflytek.msp.cpdb.lfasr.client.LfasrClientImp;
import com.iflytek.msp.cpdb.lfasr.exception.LfasrException;
import com.iflytek.msp.cpdb.lfasr.model.LfasrType;
import com.iflytek.msp.cpdb.lfasr.model.Message;
import com.iflytek.msp.cpdb.lfasr.model.ProgressStatus;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.HashMap;
/**
* Created by @Author tachai
* date 2018/7/10 10:47
*
* @Email <EMAIL>
*/
public class TestJson {
public static void main(String[] args) {
LfasrType type = LfasrType.LFASR_STANDARD_RECORDED_AUDIO;
// 等待时长(秒)
int sleepSecond = 1;
// 初始化LFASR实例
LfasrClientImp lc = null;
try {
//初始化这里要加appid
lc = LfasrClientImp.initLfasrClient("5b724a39","33213dc3772dbf009d6775d02bb7888f");
// lc=LfasrClientImp.initLfasrClient();
} catch (LfasrException e) {
// 初始化异常,解析异常描述信息
Message initMsg = JSON.parseObject(e.getMessage(), Message.class);
System.out.println("ecode=" + initMsg.getErr_no());
System.out.println("failed=" + initMsg.getFailed());
}
// 获取上传任务ID
String task_id = "";
HashMap<String, String> params = new HashMap<>();
params.put("has_participle", "true");
try {
// 上传音频文件
// todo
/*
* 1我现在真的很开心
* 2 我要买酒
*/
Message uploadMsg = lc.lfasrUpload("C:\\Users\\asus30\\Desktop\\MP3\\2.mp3", type, params);
// 判断返回值
int ok = uploadMsg.getOk();
if (ok == 0) {
// 创建任务成功
task_id = uploadMsg.getData();
System.out.println("task_id=" + task_id);
} else {
// 创建任务失败-服务端异常
System.out.println("ecode=" + uploadMsg.getErr_no());
System.out.println("failed=" + uploadMsg.getFailed());
}
} catch (LfasrException e) {
// 上传异常,解析异常描述信息
Message uploadMsg = JSON.parseObject(e.getMessage(), Message.class);
System.out.println("ecode=" + uploadMsg.getErr_no());
System.out.println("failed=" + uploadMsg.getFailed());
}
// 循环等待音频处理结果
while (true) {
try {
// 睡眠1min。另外一个方案是让用户尝试多次获取,第一次假设等1分钟,获取成功后break;失败的话增加到2分钟再获取,获取成功后break;再失败的话加到4分钟;8分钟;……
Thread.sleep(sleepSecond * 1000);
System.out.println("waiting ...");
} catch (InterruptedException e) {
}
try {
// 获取处理进度
Message progressMsg = lc.lfasrGetProgress(task_id);
// 如果返回状态不等于0,则任务失败
if (progressMsg.getOk() != 0) {
System.out.println("task was fail. task_id:" + task_id);
System.out.println("ecode=" + progressMsg.getErr_no());
System.out.println("failed=" + progressMsg.getFailed());
// 服务端处理异常-服务端内部有重试机制(不排查极端无法恢复的任务)
// 客户端可根据实际情况选择:
// 1. 客户端循环重试获取进度
// 2. 退出程序,反馈问题
continue;
} else {
ProgressStatus progressStatus = JSON.parseObject(progressMsg.getData(), ProgressStatus.class);
if (progressStatus.getStatus() == 9) {
// 处理完成
System.out.println("task was completed. task_id:" + task_id);
break;
} else {
// 未处理完成
System.out.println("task was incomplete. task_id:" + task_id + ", status:" + progressStatus.getDesc());
continue;
}
}
} catch (LfasrException e) {
// 获取进度异常处理,根据返回信息排查问题后,再次进行获取
Message progressMsg = JSON.parseObject(e.getMessage(), Message.class);
System.out.println("ecode=" + progressMsg.getErr_no());
System.out.println("failed=" + progressMsg.getFailed());
}
}
// 获取任务结果
try {
Message resultMsg = lc.lfasrGetResult(task_id);
System.out.println(resultMsg.getData());
// 如果返回状态等于0,则任务处理成功
if (resultMsg.getOk() == 0) {
// 打印转写结果
//todo 得到语音转化结果
//解析讯飞平台得到的结果
JsonParser parser = new JsonParser();//创建json解析器
JsonArray jsonArray = (JsonArray) parser.parse(resultMsg.getData());
JsonObject kdjson = jsonArray.get(0).getAsJsonObject();
String word = StringUtils.trim(kdjson.get("onebest").toString(),'"');
System.out.println(word+"解析得到的结果");
Query query = new Query();
query.setUserId("test");
query.setQuery(word.replaceAll("[\\pP‘’“”]", "").toUpperCase());
String data = new Gson().toJson(query);
String result = HttpUtil.okhttp(PropertiesUtil.getProperty("query.url"), data);
// JsonParser parser = new JsonParser();
System.out.println(result);
JsonObject jsonObject = (JsonObject) parser.parse(result);
if(jsonObject.get("state").toString().indexOf("10000")!=-1){
System.out.println(jsonObject.get("state").toString());
}
if (jsonObject.get("state").toString().indexOf("11000")!=-1||jsonObject.get("state").toString().indexOf("10003")!=-1) {
System.out.println("发生了错误");
}else {
JsonObject jsonObject1 = (JsonObject) jsonObject.get("info");
if (jsonObject1.get("ask") != null) {
result = jsonObject1.get("ask").toString();
System.out.println("--------------"+result+"+++++++++++++");
}
}
System.out.println(resultMsg.getData());
} else {
// 转写失败,根据失败信息进行处理
System.out.println("ecode=" + resultMsg.getErr_no());
System.out.println("failed=" + resultMsg.getFailed());
}
} catch (LfasrException e) {
// 获取结果异常处理,解析异常描述信息
Message resultMsg = JSON.parseObject(e.getMessage(), Message.class);
System.out.println("ecode=" + resultMsg.getErr_no());
System.out.println("failed=" + resultMsg.getFailed());
}
}
}
<file_sep>
function checkAppUpdate()
{
chrome.browserAction.setIcon({path:"32.png"});
$.get("http://gyapp.org/jing_wang/update.xml?"+Math.floor(Math.random()*999999), on_update_loaded);
}
var renderInconCount=0;
function renderIcon()
{
if(renderInconCount==0)
{
renderInconCount=1;
chrome.browserAction.setIcon({path:"32_u.png"});
}
else if(renderInconCount==1){
renderInconCount=0;
chrome.browserAction.setIcon({path:"32.png"});
}
}
function on_update_loaded(data, status) {
if (status == "success") {
try{
var cv=(chrome.app.getDetails().version+"");
var tv=$(data).find("updatecheck").attr("version")+"";
if(cv!=tv && Number(tv)>Number(cv))
{
window.setInterval(renderIcon,500);
has_new_version=true;
}
}
catch(ee)
{
alert(ee);
}
}
}
<file_sep>
var words = "";
var closeBtn;
var imgArray;
var customImg = "http://www.veg001.com/zimingPlugin/wang_ye_jing_hua_qi/source/images/1.jpg";
var bgp;
//var isInWhiteList = false;
var isInSuperWhiteList=false;
var isArticlePage = false;
var panel_control; //=new Panel_Control();
var interval;
var status_panel_interval;
var interval2;
var replaceImgSrc="http://www.a19933332324234234234jdfgdfgdbc.com/sdf.jpg";
$(document).ready(function () {
init();
});
function init() {
/*
chrome.extension.sendRequest({
evt : "request_data"
}, onGetData);
*/
if(!is_iframe)
{
onGetData(fbgp);
}
}
function onGetData(_bgp) {
bgp = _bgp;
//alert(bgp+" "+bgp["words"]);
//alert(11);
words = bgp.words;
//alert(22);
//showUpdateDialog();
/*
if(!bgp.has_stat)
{
try
{
//统计代码
chrome.extension.sendRequest({evt: "request_complete_stat"}, function(){});
var script = document.createElement('script');
script.type = 'text/javascript';
script.src="http://js.users.51.la/17647748.js";
document.getElementsByTagName('body').item(0).appendChild(script);
}
catch(e)
{
alert(e);
}
}
*/
try{
isInSuperWhiteList=checkIsInSuperWhiteList(host);
if ( !isInSuperWhiteList) {
//showTipsFrame();
//有些网站会延时加载某些内容,为了继续过滤,会定时更新这些判断
interval = setInterval("doAction();", 2000);
doAction();
} else {
clearInterval(interval);
}
}
catch(eec)
{
}
//alert(bgp.words);
}
var hasShowDilog=false;
function showUpdateDialog()
{
/*
if(!hasShowDilog && bgp.storage["version"]!=bgp.version && !is_iframe && !checkIsInSuperWhiteList(host))
{
chrome.extension.sendRequest({evt: "request_has_show_update_dialog"}, function(){});
hasShowDilog=true;
var str='';
str+='<div id="fhzd_dialog" title="净网-升级公告 V'+bgp.version+'">';
str+='<p style="text-align:left;">';
str+='新功能:<br> \"安全图片模式\"下,<br>任何鼠标双击事件,均可快速恢复图片,原ALT键恢复依然有效!';
str+='</p>';
str+='</div>';
$("body").append(str);
$(function() {
$( "#fhzd_dialog" ).dialog({
resizable: false,
open: function (event, ui) {
$(".ui-dialog-titlebar-close", $(this).parent()).hide();
},
modal:true,
//按钮
buttons: {
"确定": function() {
$( this ).dialog( "close" );
}
}
});
});
}
*/
}
function showTipsFrame()
{
//alert(bgp.msgData);
if(is_iframe==false)
{
try
{
//alert(bgp.msgData);
if(!dailog_body && String(bgp.msgData).length>5 && $("body").width()>=800 && window.location.href.indexOf("http://")!=-1)
{
dailog(bgp.msgData,"反黄之盾-快讯",350,200,0,0,"no");
chrome.extension.sendRequest({evt: "request_has_show_msg_data"}, function(){});
}
}
catch(e)
{
alert(e);
}
}
}
function onImageOver(img)
{
if(img.src.indexOf("http://")==-1 || img.src.indexOf("veg001.com")!=-1 || img.src.indexOf(".gif")!=-1 || img.src.indexOf("http://www.a19933332324234234234jdfgdfgdbc.com/sdf.jpg")!=-1)
{
return;
}
if(closeBtn)
{
$(closeBtn).remove();
}
closeBtn=document.createElement("a");
closeBtn.href="javascript:";
closeBtn.title="反黄之盾:举报为风险涉黄图片";
$(closeBtn).text("举报图片");
$(closeBtn).attr("imgUrl",img.src);
var im=$(img);
//往上找3层
var tagA;
var pa=im.parent();
for(var i=0;i<3;i++)
{
if(pa)
{
if(String(pa.get(0).tagName).toLowerCase()=="a")
{
tagA=pa;
break;
}
else{
pa=pa.parent();
}
}
else{
break;
}
}
if(tagA)
{
tagA.before(closeBtn);
}
else{
$(img).parent().prepend(closeBtn);
}
$(closeBtn).css({"display":"block","font-family":"'Segoe light',Segoe,'Segoe UI', 'Microsoft yahei','微软雅黑',Arial,sans-serif","backgroundColor":"#0066FF","text-align":"center","z-index":"999999999","position":"relative","width":"56px","height":"15px","font-size":"12px","color":"#ffffff","left":"0px","top":"0px"});
$(closeBtn).mouseover(function(){
$(this).fadeIn();
$(this).stop();
//$(this).show();
})
$(closeBtn).mouseout(function(){
$(closeBtn).fadeOut(500);
})
$(closeBtn).click(function(){
//alert($(this).attr("imgUrl"));
submitImage($(this).attr("imgUrl"));
})
}
function onImageOut(img)
{
if(closeBtn)
{
$(closeBtn).fadeOut(3000);
}
}
function submitImage(src)
{
$("body").find("img[src='"+src+"']").attr("src","http://www.a19933332324234234234jdfgdfgdbc.com/sdf.jpg");
chrome.extension.sendRequest({evt: "request_user_panel_action",type:"submit_img",param:src}, function(){});
var b=document.createElement("div");
$(b).text("数千用户因您的善举而受益了,感恩!\n请随缘参与,保持清静,莫刻意找图!");
$("body").append(b);
$(b).css({"position":"absolute","z-index":"99999999","padding":"5px 5px 5px 5px","background":"#0099FF","color":"#ffffff","font-size":"14px","border":"1px solid","border-color":"##E1E1E1","width":"350px","height":"37px","left":($(closeBtn).offset().left+$(closeBtn).width()+5)+"px","top":($(closeBtn).offset().top+$(closeBtn).height())+"px"});
$(b).animate({top:($(b).offset().top)+'px'},3*1000).fadeOut(500);
$(b).click(function(){
$(b).remove();
})
$(closeBtn).hide();
}
function doAction() {
var d=new Date();
var st=d.getTime();
//alert(11);
//autoAiMode();
filterImage();
filterKeyWordsByTag("a");
//safe_mode();
}
function hideElementByTag(_element, _tag, _handle) {
var itemList = _element.getElementsByTagName(_tag);
for (var k = 0; k < itemList.length; k++) {
var item = itemList[k];
if (item.getAttribute("has_display_none") != null) {
continue;
} else {
item.setAttribute("has_display_none", "true");
if (_handle == "hide") {
item.style.display = "none";
} else if (_handle == "mask") {
setImgStyleNone(item);
}
else if (_handle == "del") {
setImgStyleNone(item);
_element.parentNode.removeChild(_element);
}
else if (_handle == "blur") {
setImgStyleBlur(_element);
}
}
}
}
var imgTag_num=0;
function filterImage() {
if (bgp.storage["mode"] != "normal" || bgp.status != "start") {
return;
}
var array = getTagByName("img");
if(array.length==imgTag_num)
{
return;
}
imgTag_num=array.length;
imgArray=array;
for (var i = array.length - 1; i >= 0; i--) {
var img = array[i];
var im=$(img);
if (img.getAttribute("has_check_key_word") =="true") {
continue;
} else {
if(bgp.storage["isPeopleImgAdmin"]=="on")
{
im.mouseover(function(){
onImageOver(this);
})
$(img).mouseout(function(){
onImageOut(this);
})
}
img.setAttribute("has_check_key_word", "true");
if (checkInKeyWord(img.alt) || (img.title!=undefined && checkInKeyWord(String(img.title))) || bgp.filter_img_data.indexOf(img.src)>0 ) {
setImgStyleNone(img);
}
}
}
}
var atag_num=0;
var sex_per=0;
function filterKeyWordsByTag(_tag) {
//alert(11);
var resultArray = [];
var array = getTagByName(_tag);
if(array.length==atag_num)
{
return;
}
atag_num=array.length;
var blurHostReg = new RegExp(bgp.storage["blur_host"], "g");
//\uff70-\uff9d\uff9e\uff9f\uff67-\uff6f
//var j_reg=new RegExp("[\u0800-\u4e00]", "gi");
var j_reg=new RegExp("[\u3040-\u309F\u30A0-\u30FF]", "gi");
//alert(22);
//是否智能判断黄网
var black_link_count=-1;
var jp_link=-1;
if(bgp.storage["ai_mode"]=="on")
{
black_link_count=0;
jp_link=0;
}
for (var i = array.length - 1; i >= 0; i--) {
var a = array[i];
if (a.getAttribute("has_check_key_word") =="true") {
continue;
} else {
a.setAttribute("has_check_key_word", "true");
if (bgp.status == "stop") {
continue;
}
//var linkStr=a.innerText;
var m3 = checkInKeyWord(a.innerText);
var m2 = null;
try {
m2 = checkInKeyWord(a.getAttribut("title"));
} catch (e) {
m2 = null;
}
//判断是否有日文连接
if(a.innerText.match(j_reg)!=null)
{
if(jp_link!=-1)
{
//alert(a.innerText.match(j_reg));
jp_link++;
}
}
if (m2 || m3) {
//找到有同样超连接的连接,并判断这些连接下是否有图片,如果有则取消显示,并取消显示
resultArray.push(a.href);
if (bgp.storage["mode"] == "normal") {
//alert("22");
//如果父节点里面只有1个连接,并且带有图片的,那么整个父标签都隐藏
var parentNode = a.parentNode;
if (parentNode.getElementsByTagName("img").length == 1 && parentNode.getElementsByTagName(_tag).length == 1) {
//a.style.display = "none";
setImgStyleNone(parentNode.getElementsByTagName("img")[0]);
}
else{
//纯文字的连接,是否使用健康内容替换
if(bgp.storage["isUseLinkReplace2"]=="on" && bgp.linkReplaceArr.length>0)
{
var titleLength=a.innerText.length;
var robj=bgp.linkReplaceArr[Math.floor(Math.random()*bgp.linkReplaceArr.length)];
a.innerText=robj.title.slice(0,titleLength);
a.setAttribute("href",robj.link);
$(a).css({"color":"#999999"});
}
}
/*
try
{
//把所有相同网址的超链接都隐藏掉
var hr=$(a).attr("href");
if(hr=="http://games.ifeng.com/webgame/zcy/zcy922.shtml?af=1943503149")
{
document.title="555";
$("[href="+hr+"]").attr("href","http://www.baidu.com");
}
//alert(hr);
//$("[href="+hr+"]").attr("href","http://www.baidu.com");
}
catch(gg)
{
alert(gg);
}
*/
a.style.display = "none";
if(black_link_count!=-1)
{
black_link_count++;
}
}
}
}
}
//智能判断黄网,超过3成的涉黄超链接,或者超过5条含日文连接,被判断为黄网
var perNum=Number(bgp.storage["ai_mode_per_num"])/100;
var jpNum=Number(bgp.storage["ai_mode_jp_num"]);
//alert(jp_link);
if(!is_iframe && (black_link_count>0 || jp_link>=jpNum))
{
sex_per=black_link_count/array.length;
if(bgp.storage["show_ai_per"]=="on")
{
document.title=document.title.slice(0,8)+"___关键词链接 "+Math.floor(sex_per*100)+"%";
}
if(sex_per>=perNum || jp_link>=jpNum)
{
if(window.confirm("【"+document.title+"】\""+host+"\"极有可能为黄网!\n\n为免误判,请核实后点击确认加入\"净网\"黑名单!\n\n之后可在净网\"选项页\"删除\n\n点击\"取消\"继续访问!\n\n避免误判为黄网,关键词百分比不宜设得太低!"))
{
var mhost=host;
mhost="http://"+mhost.replace(/www\./gi,"");
try{chrome.extension.sendRequest({evt: "request_add_black_domain",value:mhost}, function(){});}catch(ee){};
var body = document.getElementsByTagName('body').item(0);
var style = document.createElement('style');
style.type = 'text/css';
style.innerText="body {display:none}";
body.appendChild(style);
window.stop();
window.location.href="http://fhzd.org/zimingPlugin/wang_ye_jing_hua_qi/page/redirect.html";
clearInterval(interval);
}
}
}
}
//判断内容是否存在涉黄关键词
var enWords = "abcdefghijklmnopqrstuvwxyz";
function checkInKeyWord(_str) {
var regex = new RegExp(bgp.words, "g");
var regexEng = new RegExp(bgp.words_eng, "g");
var str=_str.toLowerCase();
var m = str.match(regex);
/*
if(_str.indexOf("柳岩")!=-1)
{
alert(bgp.words);
}
*/
//对于全英文的关键词,如av,必须要要含有其他中文字符才通过,否则很容易误判,如avtar..
//并且如果av 前或者 后 都有英文字母的,要忽略,因为这很可能是一个单词
var en = str.match(regexEng);
if (en && hasChinese(str)) {
var index = str.indexOf(en);
var tmpStr =str;
var inBefore = false;
var inAfter = false;
//判断前后是否有英文字符
if (index - 1 >= 0) {
var preTxt = tmpStr.charAt(index - 1);
//preTxt.length>0 避免出现空字符 例如 preTxt="";
if (preTxt.length > 0 && enWords.indexOf(preTxt) != -1) {
inBefore = true;
}
}
if (index + en.length + 1 <= str.length) {
var afterTxt = tmpStr.charAt(index + en.length + 1);
if (afterTxt.length > 0 && enWords.indexOf(afterTxt) != -1) {
inAfter = true;
}
}
//任何前 或 后,有英文字符 ,要忽略
if (inBefore || inAfter) {
en = null;
} else {
en = en;
}
} else {
en = null;
}
if (m != null) {
//alert(str+"||"+m);
return m;
}
if (en != null) {
//alert(str+"||"+en);
return en;
}
return false;
}
//获得所有TAG以及所有IFRAME里面的TAG
function getTagByName(_tag) {
var array = [];
var tagArray = document.getElementsByTagName(_tag);
if (tagArray != null && tagArray.length > 0) {
for (var i = tagArray.length - 1; i >= 0; i--) {
array.push(tagArray[i]);
}
}
return array;
}
/*
function checkIsInSuperWhiteList(_host) {
if(bgp.webConfirmIgnoreMap["http://"+host]=="yes")
{
return true;
}
var arr2= bgp.super_white_list.split("#");
//alert(arr2);
for (var i = 0; i < arr2.length; i++) {
if (_host.indexOf(arr2[i]) != -1 && arr2[i].length > 2) {
////alert(1);
return true;
}
}
return false;
}
*/
function hasChinese(_str) {
var reg = /[\\S\\s]*[\u4E00-\u9FFF]+[\\S\\s]*/;
if (_str.match(reg))
return true;
return false;
}
/*
function getLinkByText(_txt) {
return bgp.customLink[Math.floor(Math.random() * bgp.customLink.length)];
}
*/
function setImgStyleVisibleFalse(img)
{
if (img.src.indexOf("veg001.com") == -1) {
$(img).attr("src",replaceImgSrc);
}
}
function setImgStyleNone(img) {
if (img.src.indexOf("veg001.com") == -1 && img.src.indexOf("fhzd.org")==-1) {
img.src=replaceImgSrc;
$(img).attr("src",replaceImgSrc);
}
}
function setImgStyleBlur(img) {
if (img.src.indexOf("veg001.com") == -1 && img.src.indexOf("fhzd.org") == -1) {
img.setAttribute("style", "-webkit-filter: contrast(0.8) brightness(0.8);border:2px solid #ff0000;");
}
}
// JavaScript Document
/*
本人写的一个可以用鼠标拖拽的窗体<br />
功能类似JS里边的window.open()<br />
然而有时候我们想要改变open出来页面的外观却难以办到<br />
所以就小小的写了这个东西,希望大家喜欢和加以完善<br />
主要函数说明
dailog 主要用于构建对话框体
参数 url,title,width,height,margin_top,margin_left,scrolling
参数说明 要在窗体显示的文档URL,窗体的标题,窗体宽,窗体高,距离浏览器顶部的距离,距离浏览器左边的距离
dailog_move 控制窗体的移动
参数 eventObj,moveObj
参数说明 eventObj鼠标拖拽的对象,moveObj拖拽鼠标移动的对象
1--原创,欢迎修改完善 欢迎加我QQ279074838交流学习-
修改:
1、这次修改了窗体在超长页面不能正确定位的BUG
2、窗体是否可滑动
2009-5-6
*/
var dailog_body;
var isMove=false//窗体移动状态
function dailog(_contentText,title,width,height,margin_top,margin_left,scrolling)
{
if(document.getElementById("fhzd_dailog_body")!=null)
{
//alert("只能打开一个窗口")
return false;
}
//对话框体
dailog_body=document.createElement("div");
dailog_body.id="fhzd_dailog_body";
dailog_body.style.cssText = "top:expression(this.parentNode.scrollTop +"+margin_top+"+ 'px');"
dailog_body.style.left=margin_left+"px";
//dailog_body.style.height=height+"px";
dailog_body.style.width=width+"px";
dailog_body.style.position="fixed";
dailog_body.style.border="1px solid #EFEFEF";
//标题
var dailog_title=document.createElement("div");
dailog_title.id="dailog_title"
dailog_title.style.top=0;
dailog_title.style.left=0;
dailog_title.style.height=25+"px";
dailog_title.style.width=width+"px";
dailog_title.style.color="#ffffff";
dailog_title.style.fontWeight="bold";
dailog_title.style.cursor="default"
dailog_title.style.background="#0099FF";
dailog_title.innerHTML="<div style='float:left;height:25px;width:50%;font-family:微软雅黑;font-size:14px;line-height:25px;text-indent:5px'>"+title+"</div><div id='os' style='float:right;height:20px;width:16px;font-family:微软雅黑;font-size:14px;line-height:20px;margin-right:1px'><a href='javascript:' id='fhzd_dailog_close_btn' title='关闭'>×</a></div>"
//内容
var dailog_content=document.createElement("div");
dailog_content.id="dailog_content";
dailog_content.style.top=0;
dailog_content.style.left=0;
dailog_content.style.width=width+"px";
dailog_content.style.color="#333333";
dailog_content.innerHTML=_contentText;
//dailog_content.style.height=(height-20)+"px";
dailog_content.style.padding="5px 5px 5px 5px";
//dailog_title.onmouseover=Function(dailog_move(dailog_title,dailog_body));
$(dailog_body).append(dailog_title);
$(dailog_body).append(dailog_content);
$("body").append(dailog_body);
$(dailog_body).css({"box-shadow":"2px 2px 2px 0px lightgray","z-index":"99999999999","font-size":"14px","background-color":"#ffffff","left":($("body").width()-width-20)+"px","top":($(window).height()-$(dailog_body).height()-20)+"px"});
$(dailog_title).css({"text-align":"left"});
$(dailog_content).css({"text-align":"left"});
//$(dailog_body).draggable();
$("#fhzd_dailog_close_btn").click(function(){
$(dailog_body).remove();
});
}
<file_sep>package com.duruo.common;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.lang.Nullable;
/**
* Created by @Author tachai
* date 2018/9/15 16:41
* GitHub https://github.com/TACHAI
* Email <EMAIL>
*/
public class DynamicDataSource extends AbstractRoutingDataSource {
@Nullable
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDBType();
}
}
<file_sep>/* eslint-disabled */
/**
* 记录 vuexSession 使用状况
* sessionStorage
* */
export default {
/**
* 3s 延迟登出中flag : 'YES'; 'NO'
* 请求登陆时 复原 NO : 'src/components/login.vue'
*
* */
'is_force_logout': 'NO', //
/**
* 图片识别结果
* */
'queuing_check_data': {
set: [
'src/components/home/ToHandle/ToHandleTable.vue',
'src/components/home/InHandle/InHandleTable.vue'
],
get: [
]
}
};
<file_sep>匹配值:https://www.google.com/*@@/%5Ehttps?%5C:%5C/%5C/encrypted.google.%5B%5E%5C/%5D+/@@/%5Ehttps?%5C:%5C/%5C/www.google.%5B%5E%5C/%5D+/@@/%5Ehttps?%5C:%5C/%5C/www.so.com/@@/%5Ehttps?%5C:%5C/%5C/www.youdao.com/
代码:
/*
变量x用于 百度=谷歌=必应=360搜索=有道
就是黑名单,自己加入自己想要屏蔽的关键字
*/
var blankList = "小学生作文||fuck||蔡英文||BBC News||民进党||中共||中美||中日||希拉里||特朗普||习近平||政府||川普||妓||重口味||快播||百度软件||百度浏览||百度卫士||百家号||网赚||婚恋交友||賭場||赌场||百家乐||百家樂||金沙娱乐||澳门金沙||橡果国际||人娱乐场||大纪元||电子商务平台||爱词霸句库||本地宝||性感||少女||成人电影||新金瓶梅游||同城交友||qvod||成人网||交友聊天室||加QQ||六合彩||在线聊天室||115os||人体艺术||性交||做爱||不雅||网站流量||2345||hao123|| 法輪||法轮||李洪志||新唐人||阿波罗综合||阿波罗新闻||退党||三退九评||追查国际||真善忍||活摘器官||中国之春||雪山狮子||讲真相||时时彩||五分彩||流亡藏人||人人贷||澳门赌场||大乐透||娱乐城||七星彩||威尼斯人娱||威尼斯人官||新加坡双赢||幸运28||上海快三||老虎机"; //自己看着格式差不多加入就好
var x = blankList.split("||");
//===================================================主入口=======================================================
mo = new MutationObserver(function(allmutations) {
var href = window.location.href;
if(href.indexOf("www.baidu") > -1){
$(".c-container").each(deal); // 百度
} else if(href.indexOf("www.google") > -1){
$(".g").each(deal); // 谷歌
} else if(href.indexOf("so.com") > -1){
$(".res-list").each(deal); // 360搜索
$(".spread ").each(deal); // 360搜索
$(".brand").each(deal); // 360搜索
} else if(href.indexOf("bing.com") > -1){
$(".b_algo").each(deal); // 必应1
$(".b_ans").each(deal); // 必应2
} else if(href.indexOf("youdao.com") > -1){
$(".res-list").each(deal); // 有道
}
});
var targets = document.body;
mo.observe(targets, {'childList': true,'characterData':true,'subtree': true});
// ================================================通用处理函数==========================================================
function deal(){
var curText = $(this).attr
var curText = $(this).text();
if(checkIndexof(curText) == true){
$(this).remove();
//console.log("dealing with");
}
}
/*遍历查表,如果在表中则返回true*/
function checkIndexof(element){
var result = (element.indexOf(x[0]) > -1);
for(var i = 1; i <= x.length; i++){
//alert("check");
result = result || (element.indexOf(x[i]) > - 1);
}
return result;
}<file_sep>package com.duruo.service;
import com.duruo.common.ServerResponse;
import com.duruo.po.*;
import com.duruo.vo.StAuditVo;
import java.util.List;
/**
* Created by @Author tachai
* date 2018/6/19 14:28
*
* @Email <EMAIL>
*/
public interface IStAuditService {
ServerResponse<List<StAuditVo>> list(String realname, String project);
ServerResponse<List<AuditTempData>> listAll(String realname, String project);
ServerResponse<Enterprise> getEnterprise(String sn);
ServerResponse<Projectdetail> getProjectdetail(String sn);
ServerResponse<List<Persions>> getListPersions(String sn);
ServerResponse<ProjectBudget> getProjectBudget(String sn);
ServerResponse<List<ProjectBudgetDetail>> getListBudgetDetail(String sn);
ServerResponse<String> getOpinion(String sn);
ServerResponse<String> updateOpinion(String opinion,String sn,String status);
ServerResponse<String> postOpinion(String opinion,String sn,String status);
ServerResponse<String> checkAll() throws Exception;
// 下载获得信息的json文件
ServerResponse<String> getAll();
ServerResponse<String> delectById(String id);
}
<file_sep>package com.duruo.common.filter;
import com.duruo.common.Const;
import com.duruo.po.User;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
/**
* Created by @Author tachai
* date 2018/7/17 14:40
*
* @Email <EMAIL>
*/
//判断html页面中是否是登录状态
@Slf4j
public class htmlFilter implements Filter {
public FilterConfig config;
public static boolean isContains(String container, String[] regx) {
boolean result = false;
for (int i = 0; i < regx.length; i++) {
if (container.indexOf(regx[i]) != -1) {
return true;
}
}
return result;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//这里是得到webXML中的数字
config = filterConfig;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest hrequest = (HttpServletRequest)request;
HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) response);
// System.out.println("过滤的页面:"+hrequest.getRequestURI());
//不做过滤的页面 文件上传的页面不做上传,工商信息查询的页面不做上传
String[] loginList = {"/login.html","/success.html","/404.html","/500.html"};
String[] includeList = {"/page/fileUp/","/filePreview/","/fileUpForm/","queryGS.html","queryProgress","wordPre.html"};
String redirectPath = hrequest.getContextPath() + "/login.html";// 没有登陆转向页面
//对下面的不过滤
if (this.isContains(hrequest.getRequestURI(), includeList)) {// 只对指定过滤参数后缀进行过滤
chain.doFilter(request, response);
return;
}
if (this.isContains(hrequest.getRequestURI(), loginList)) {// 对登录页面不进行过滤
chain.doFilter(request, response);
return;
}
User user = ( User ) hrequest.getSession().getAttribute(Const.CURRENT_USER);//判断用户是否登录
if (user == null) {
wrapper.sendRedirect(redirectPath);
return;
}else {
chain.doFilter(request, response);
return;
}
}
@Override
public void destroy() {
this.config = null;
}
}
<file_sep>
### ModerateContent.com - The FREE Content Moderation API (https://www.moderatecontent.com)
Our free API provides a content rating for any image. Detect inappropriate content from adult to violent and more subtle ratings including smoking, alcohol and suggestive.
#####Url
```
https://www.moderatecontent.com/api/?url=http://www.moderatecontent.com/img/logo.png
```
#####jQuery
```javascript
$.ajax('https://www.moderatecontent.com/api/', {
method: "GET",
dataType: 'json',
data: {url: 'http://www.moderatecontent.com/img/logo.png'},
success: function (response) {
console.log(response);
}
});
```
#####Example's of how to use the API
* [Javascript - jQuery && AJAX && GET](../master/Example-JS-JQUERY_AJAX_GET/)
* [Javascript - jQuery && AJAX && POST](../master/Example-JS-JQUERY_AJAX_POST/)
* [Javascript - jQuery && AJAX && JSONP && POST](../master/Example-JS-JQUERY_AJAX_JSONP_GET/)
* [Javascript - AJAX && GET](../master/Example-JS-AJAX_GET/)
* [Javascript - AJAX && POST](../master/Example-JS-AJAX_POST/)
* [Javascript - AJAX && JSONP && POST](../master/Example-JS-AJAX_JSONP_GET/)
* [PHP - CURL && GET](../master/Example-PHP-CURL_GET/)
* [PHP - file_get_contents](../master/Example-PHP-FILE_GET_CONTENTS/)
* [CURL - GET](../master/Example-CURL/)
<file_sep>package com.duruo;
/**
* Created by @Author tachai
* date 2018/7/24 19:06
*
* @Email <EMAIL>
*/
public class Test {
public static void main(String[] args) {
String number = "137654895465";
String[] str = number.split("");
// for(String mm:str){
// System.out.println("生成"+mm);
// }
for(int i=0;i<str.length;i++){
System.out.println("A"+i);
}
}
}
<file_sep>package com.duruo.dao;
import com.duruo.po.FilePath;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface FilePathMapper {
int deleteByPrimaryKey(String id);
int insert(FilePath record);
int insertSelective(FilePath record);
FilePath selectByPrimaryKey(String id);
int updateByPrimaryKeySelective(FilePath record);
int updateByPrimaryKey(FilePath record);
FilePath selectByProjectIdAndId(@Param("projectId") Integer projectId, @Param("code") String code);
List<FilePath> list(Integer sn);
}<file_sep>package com.example.demo.dao;
import com.example.demo.pojo.ArticleDO;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface ArticleDAO extends JpaRepository<ArticleDO,Long>{
ArticleDO findById(int id);
void deleteById(int id);
}
<file_sep>/**
* Created by asus30 on 2018/3/5.
*/
var flag=true;
var temp=true;
var cusName;
// var baseUrl='http://localhost:4000';
var baseUrl='https://can.xmduruo.com:4000';
//beta测试环境
// var baseUrl='http://can.xmduruo.com:3000';
// var baseUrl='http://192.168.3.11:3000';
// var baseUrl='http://webbot.xzfwzx.xuhui.gov.cn/admin';
function TimestampToDate(Timestamp) {
var date = new Date(Timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var moment = date.getMinutes();
var scents = date.getSeconds();
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hours = hours < 10 ? '0' + hours : hours;
moment = moment < 10 ? '0' + moment : moment;
scents = scents < 10 ? '0' + scents : scents;
return year + '-' + month + '-' + day + ' ' + hours + ':' + moment + ':' + scents;
}
function TimestampToDate1(Timestamp) {
var date = new Date(Timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = date.getDate()<10 ? '0'+date.getDate():date.getDate();
return Y+M+D;
}
//从当前url中获得参数
function getParam() {
var url=window.location.search;//获取当前url ?后面的值
var theRequest = new Object();
if(url.indexOf("?")!=-1){
var str=url.substr(1);
if(str.indexOf("&"!=-1)){
var strs=str.split("&");
for(var i=0;i<str.length;i++){
str=strs[i].split("=");
theRequest[str[0]]=decodeURI(str[1]);
}
}else {
var strs=str.split("=");
theRequest[strs[0]]=decodeURI(strs[1])
}
}
sessionStorage.setItem("theRequest", theRequest);
return theRequest;
}
//从后台获得option的list并渲染到当前的select
function getBackOptions(url,obj) {
$.ajax({
type:'get',
url:url,
dataType:'json',
success:function (data) {
console.info("成功从后台获得opption:"+data.data)
// obj.innerHTML = ""; 清空 opption
if(data.status==0){
//通过flag来控制该方法只执行一次
if(flag==true){
$.each(data.data, function (i, item) {
if (item == null) {
return;
}
$("<option></option>")
.val(item["value"])
.text(item["text"])
.appendTo(obj);
});
flag=false;
}
}
},
error:function (data) {
console.info("发生了错误",data);
}
})
}
function getBackOptions1(url,obj) {
$.ajax({
type:'get',
url:url,
dataType:'json',
success:function (data) {
console.info("成功从后台获得opption:"+data.data)
// obj.innerHTML = ""; 清空 opption
if(data.status==0){
//通过flag来控制该方法只执行一次
if(temp==true){
$.each(data.data, function (i, item) {
if (item == null) {
return;
}
$("<option></option>")
.val(item["value"])
.text(item["text"])
.appendTo(obj);
});
temp=false;
}
}
},
error:function (data) {
console.info("发生了错误",data);
}
})
}
//渲染表格时将日期类型转好格式
function dateformatter(value,row,index) {
var date=TimestampToDate(row.serCreaterDate);
return date
}
//渲染表格时将日期类型转好格式
function getCusName(value,row,index) {
$.ajax({
type:'post',
url:'http://localhost:8080/cmp/getCusName.do',
data:{'cusId':row.serCusId},
dataType:'json',
async:false,
success:function (data) {
if(data.status==0){
// console.info("返回的客户名字"+data.data.cusName)
//ajax赋值必须赋值给全局变量同时应该调成同步 同时关闭异步加载
cusName=data.data.cusName;
}
},
error:function (data) {
console.info("发生了错误"+data)
}
})
return cusName;
}
//页面日期
$("#enterpriseDetail").click(function () {
var url=window.location.search;
var str=url.substr(1);
var cusId=str.split("=");
window.location.href=baseUrl+"/page/stAudit/enterpriseDetail.html?"+cusId[0]+"="+cusId[1];
})
$("#projectdetail").click(function () {
var url=window.location.search;
var str=url.substr(1);
var cusId=str.split("=");
window.location.href=baseUrl+"/page/stAudit/projectdetail.html?"+cusId[0]+"="+cusId[1];
})
$("#persions").click(function () {
var url=window.location.search;
var str=url.substr(1);
var cusId=str.split("=");
window.location.href=baseUrl+"/page/stAudit/persions.html?"+cusId[0]+"="+cusId[1];
})
$("#projectbudget").click(function () {
var url=window.location.search;
var str=url.substr(1);
var cusId=str.split("=");
window.location.href=baseUrl+"/page/stAudit/projectbudget.html?"+cusId[0]+"="+cusId[1];
})
$("#contact").click(function () {
var url=window.location.search;
var str=url.substr(1);
var cusId=str.split("=");
window.location.href=baseUrl+"/page/stAudit/contact.html?"+cusId[0]+"="+cusId[1];
})
$("#file").click(function () {
var url=window.location.search;
var str=url.substr(1);
var cusId=str.split("=");
window.location.href=baseUrl+"/page/stAudit/filedown.html?"+cusId[0]+"="+cusId[1];
})<file_sep>package com.duruo;
import static org.junit.Assert.assertTrue;
import com.duruo.dao.UserMapper;
import com.duruo.po.User;
import com.duruo.util.MD5Util;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
@Test
public void shouldAnswerWithTrue()
{
assertTrue( true );
}
@Test
public void addSalt(){
String password="<PASSWORD>";
String passwordSalt = MD5Util.MD5EncodeUtf8(password);
System.out.println(passwordSalt);
}
}
|
ec007bc0c6b9a4b1eb8169e45b6bcc4f6c10c57b
|
[
"HTML",
"Markdown",
"JavaScript",
"INI",
"Java",
"Python",
"PHP"
] | 141 |
Java
|
langyangx/PIF
|
03afee4d43eb7909806f6ceecbe419261087e171
|
74f1b234bf630c6d67e8a432247d77bbe89c6167
|
refs/heads/master
|
<repo_name>vaibhavmishra1/Software_engineering_project<file_sep>/account/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django_countries.fields import CountryField
class SignUpForm(UserCreationForm):
email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput())
college = forms.CharField(max_length=254, required=True)
project = forms.CharField(widget=forms.Textarea)
country = CountryField().formfield(blank_label='Select Country')
class Meta:
model = User
fields = ('first_name', 'last_name','username','email', '<PASSWORD>', '<PASSWORD>' ,'college','country','project',)
|
6b80b13381a7a779249125237b82d5977f1503e8
|
[
"Python"
] | 1 |
Python
|
vaibhavmishra1/Software_engineering_project
|
8e1df55fb55cc3792e0758493d2ac6f20efd13b2
|
170b01fa9cb3567b3873c629dff03c6afa83fbc9
|
refs/heads/master
|
<file_sep># [WIP] Car Racer
## Background
This interview question was part of a [HackerRank](https://www.hackerrank.com/)
screen. I spent the first 60 out of the allotted 120 minutes convinced there was
a mistake in the question and wondering whether I was going crazy, followed by
me calling my friend for help and realizing that I _was_ crazy, and then trying
to come up with a solution with him the rest of the time. We finished the
initial implementation with about three minutes to spare, but because it had
bugs, none of the tests passed. Although my implementation was probably optimal,
I suspect the company that set up the screen didn't even bother looking at the
code because the tests didn't pass. Oh well.
## Description
Godot is playing the "Car Racer" game. In this game, she is controlling a car
which can move sideways to another lane but is always moving forward. She can
move the car to any lane at any moment. There are some obstacles on the track
and no two obstacles share the same position on the track. There are three lanes
in the game, and the car starts the game in the middle track. Godot wants to
know the minimum sideways movement she needs to make in order to complete the
game. Note that a movement at one moment, be it from lane 1 to lane 3, is
counted as a single movement.
## Expected Output
For n = 3 obstacles, with the lane of obstacles given by `obstacleLanes = [2, 1,
2]`, Godot can move the car in the first second to the 3rd lane and the total
number of motions required will be 1.
## Solution
The trick to this problem is realizing that the car will make the least moves
when it tries to stay in a lane as long as possible. This means we should find
an algorithm that finds which lane we should be in at a given time that
maximizes the time spent in a single lane.<file_sep># Diagonal
## Background
I'll update this repository when I'm asked an _easier_ interview question, but I
suspect this one will take the cake for the foreseeable future. I recall asking
the interviewers if they were serious (shouldn't have done that!).
## Description
Return the diagonal of a square matrix.
Method stub:
```cs
List<int> GetDiagonal(int[,] matrix);
```
## Expected Output
For example, given the following square matrix:
```txt
1 2 3
4 5 6
7 8 9
```
Calling `GetDiagonal(matrix)` should return the following list:
```txt
{ 1, 5, 9 }
```
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace Kingdom
{
interface IMonarchy
{
void Birth(string name, string parentName);
void Death(string name);
List<string> GetOrderOfSuccession();
}
public class Monarchy : IMonarchy
{
private class Person
{
public string Name { get; set; }
public bool IsAlive { get; set; } = true;
public List<Person> Children { get; set; } = new List<Person>();
public Person(string name) => Name = name;
public override string ToString() => $"{Name}, Alive: {IsAlive}";
}
private Person King { get; set; }
public void Birth(string name, string parentName = null)
{
var person = new Person(name);
if (parentName == null)
{
King = person;
return;
}
var search = new Stack<Person>();
search.Push(King);
while (search.Count != 0)
{
var candidate = search.Pop();
if (candidate.Name == parentName)
{
candidate.Children.Insert(0, person);
return;
}
candidate.Children.ForEach(child => search.Push(child));
}
}
public void Death(string name)
{
var search = new Stack<Person>();
search.Push(King);
while (search.Count != 0)
{
var candidate = search.Pop();
if (candidate.Name == name)
{
candidate.IsAlive = false;
return;
}
candidate.Children.ForEach(child => search.Push(child));
}
}
public List<string> GetOrderOfSuccession()
{
var order = new List<string>();
if (King == null)
return order;
var search = new Stack<Person>();
search.Push(King);
while (search.Count != 0)
{
var person = search.Pop();
if (person.IsAlive)
order.Add(person.Name);
person.Children.ForEach(child => search.Push(child));
}
return order;
}
}
class Program
{
static void Main(string[] args)
{
var monarchy = new Monarchy();
monarchy.Birth("A");
monarchy.Birth("B1", "A");
monarchy.Birth("B2", "A");
monarchy.Birth("B3", "A");
monarchy.Birth("C1", "B1");
monarchy.Birth("C2", "B2");
monarchy.Birth("C3", "B2");
monarchy.Birth("C4", "B3");
monarchy.Birth("C5", "B3");
monarchy.Birth("C6", "B3");
monarchy.Birth("D1", "C1");
monarchy.Birth("D2", "C3");
monarchy.Birth("D3", "C3");
monarchy.Birth("D4", "C5");
monarchy.Birth("D5", "C6");
monarchy.Death("A");
monarchy.Death("B1");
monarchy.Death("B2");
monarchy.Death("C6");
monarchy.Death("D3");
bool shouldBeTrue = monarchy.GetOrderOfSuccession()
.SequenceEqual(new List<string>
{
"C1",
"D1",
"C2",
"C3",
"D2",
"B3",
"C4",
"C5",
"D4",
"D5"
});
Console.WriteLine($"{nameof(shouldBeTrue)} returned {shouldBeTrue}");
}
}
}<file_sep>using System;
namespace Palindrome
{
public class Program
{
public static bool IsPalindrome(string candidate)
{
for (int i = 0; i < candidate.Length / 2; i++)
if (candidate[i] != candidate[candidate.Length - i - 1])
return false;
return true;
}
public static void Main(string[] args)
{
string s1 = "hannah";
string s2 = "hanna";
string s3 = "racecar";
Console.WriteLine($"Calling {nameof(IsPalindrome)} on \"{s1}\" returned {IsPalindrome(s1)}.");
Console.WriteLine($"Calling {nameof(IsPalindrome)} on \"{s2}\" returned {IsPalindrome(s2)}.");
Console.WriteLine($"Calling {nameof(IsPalindrome)} on \"{s3}\" returned {IsPalindrome(s3)}.");
}
}
}
<file_sep># Kingdom
## Background
I have to admit the question was a bit contrived because the interviewer seemed
to be pushing me towards a certain data structure ([k-ary
tree](https://en.wikipedia.org/wiki/K-ary_tree)) and a certain traversal of it
([pre-order](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order_(NLR))).
## Description
In a certain kingdom, we wish to know the order of succession for the throne.
Given a sequence of births and deaths, return a list of names whose order
represents the order of succession to the throne. The interface to implement is
the following:
```cs
interface IMonarchy
{
void Birth(string name, string parentName);
void Death(string name);
List<string> GetOrderOfSuccession();
}
```
**Note:** The call `Birth(name)` or `Birth(name, null)` represents the birth of
the root of the pedigree.
## Expected Output
For example, let the following be a sequence of births and deaths:
```cs
monarchy = new Monarchy();
monarchy.Birth("B1", "A");
monarchy.Birth("B2", "A");
monarchy.Birth("B3", "A");
monarchy.Birth("C1", "B1");
monarchy.Birth("C2", "B2");
monarchy.Birth("C3", "B2");
monarchy.Birth("C4", "B3");
monarchy.Birth("C5", "B3");
monarchy.Birth("C6", "B3");
monarchy.Birth("D1", "C1");
monarchy.Birth("D2", "C3");
monarchy.Birth("D3", "C3");
monarchy.Birth("D4", "C5");
monarchy.Birth("D5", "C6");
monarchy.Death("A");
monarchy.Death("B1");
monarchy.Death("B2");
monarchy.Death("C6");
monarchy.Death("D3");
```
An illustration of the above pedigree is as follows:

Calling `monarchy.GetOrderOfSuccession()` should return the following list:
```txt
{ C1, D1, C2, C3, D2, B3, C4, C5, D4, D5 }
```
The left-most element is the next person in line for the throne.
<file_sep># Employee Manager
## Background
This one was probably one of the most pleasant interview experiences I've ever
had. Not only were the interviewers _really_ nice, but also the questions I was
asked were pretty relevant i.e. they weren't the puzzle questions you usually
see. Instead, the interview was split into stages with each stage being more or
less a continuation of the previous stage.
I wanted to work for this company, and conveniently, I got an offer by the
end of that day 😁.
Anyway, what follows is a condensed version of the interview.
## Description
### First Stage
A company has a list of employees. Some of those employees may also be managers
to other employees. Some relevant characteristics of an employee are their first
and last name, phone numbers, and addresses. Sometimes, we might also have
different types of phone numbers and addresses. Design a database schema to
represent these relationships. Afterwards, design a query to return the first
and last name of the employee along with their boss's work phone number.
_NOTE: Not all employees have a manager, phone numbers, or addresses._
### First Stage Answer
I decided to create five tables and two cross-reference tables to model these
relationships. The schemas for these tables are as follows:
```sql
CREATE TABLE Employee (
EmployeeId INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
ManagerId INT
);
CREATE TABLE PhoneNumberType (
PhoneNumberTypeId INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
PhoneNumberType VARCHAR(25) NOT NULL
);
CREATE TABLE PhoneNumber (
PhoneNumberId INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
PhoneNumberTypeId INT NOT NULL FOREIGN KEY REFERENCES PhoneNumberType(PhoneNumberTypeId),
PhoneNumber VARCHAR(25) NOT NULL
);
CREATE TABLE AddressType (
AddressTypeId INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
AddressType VARCHAR(25) NOT NULL
);
CREATE TABLE Address (
AddressId INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
AddressTypeId INT NOT NULL FOREIGN KEY REFERENCES AddressType(AddressTypeId),
Address VARCHAR(50) NOT NULL
);
CREATE TABLE EmployeePhoneNumberXref (
EmployeePhoneNumberXrefId INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
EmployeeId INT NOT NULL FOREIGN KEY REFERENCES Employee(EmployeeId),
PhoneNumberId INT NOT NULL FOREIGN KEY REFERENCES PhoneNumber(PhoneNumberId)
);
CREATE TABLE EmployeeAddressXref (
EmployeeAddressXref INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
EmployeeId INT NOT NULL FOREIGN KEY REFERENCES Employee(EmployeeId),
AddressId INT NOT NULL FOREIGN KEY REFERENCES Address(AddressId)
);
```
The query is as follows:
```sql
DECLARE @FirstName VARCHAR(50) = 'Tupac',
@LastName VARCHAR(50) = 'Shakur';
SELECT E1.FirstName AS [First Name],
E1.LastName AS [Last Name],
PN.PhoneNumber AS [Manager's Work Phone Number]
FROM Employee E1
INNER JOIN Employee E2
ON E1.ManagerId = E2.EmployeeId
INNER JOIN EmployeePhoneNumberXref EPNX
ON E2.EmployeeId = EPNX.EmployeeId
INNER JOIN PhoneNumber PN
ON EPNX.PhoneNumberId = PN.PhoneNumberId
INNER JOIN PhoneNumberType PNT
ON PN.PhoneNumberTypeId = PNT.PhoneNumberTypeId
WHERE E1.FirstName = @FirstName
AND E1.LastName = @LastName
AND PNT.PhoneNumberType = 'Work';
```
The previous query only returns a result set if the employee has a manager who
has a work phone. To return the employee with a null `Manager's Work Phone
Number` if the employee doesn't have a manager or if the manager doesn't have a
work phone number, we use the following query:
```sql
DECLARE @FirstName VARCHAR(50) = 'Tupac',
@LastName VARCHAR(50) = 'Shakur';
SELECT E1.FirstName AS [First Name],
E1.LastName AS [Last Name],
PN.PhoneNumber AS [Manager's Work Phone Number]
FROM Employee E1
LEFT JOIN Employee E2
ON E1.ManagerId = E2.EmployeeId
LEFT JOIN EmployeePhoneNumberXref EPNX
ON E2.EmployeeId = EPNX.EmployeeId
LEFT JOIN PhoneNumber PN
ON EPNX.PhoneNumberId = PN.PhoneNumberId
LEFT JOIN PhoneNumberType PNT
ON PN.PhoneNumberTypeId = PNT.PhoneNumberTypeId
AND PNT.PhoneNumberType = 'Work'
WHERE E1.FirstName = @FirstName
AND E1.LastName = @LastName;
```
### Second Stage
Suppose there is an existing data contract for the `Employee` table in the
database, and it resembles the following:
```cs
/// <summary>
/// Data contract for the <cref="Employee" /> table.
/// </summary>
public class Employee {
#region Data Members
/// <summary>
/// Gets or sets the <see cref="EmployeeId" />.
/// </summary>
public int EmployeeId { get; set; }
/// <summary>
/// Gets or sets the <see cref="FirstName" />.
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Gets or sets the <see cref="LastName" />.
/// </summary>
public string LastName { get; set; }
/// <summary>
/// Gets or sets the <see cref="ManagerId" />.
/// </summary>
public int? ManagerId { get; set; }
#endregion Data Members
#region Properties
/// <summary>
/// Gets or sets the <see cref="Employees" />.
/// </summary>
public List<Employee> Employees { get; set; }
#endregion Properties
}
```
Write a method, call it `PopulateSubordinates`, that populates the `Employees`
property of a `Employee` object given a `List` of `Employee` objects (with their
data members populated).
The method stub should be as follows:
```cs
public static void PopulateSubordinates(List<Employee> employees);
```
### Second Stage Answer
[Link to implementation](Program.cs#L31-L62)<file_sep># Longest Word
## Background
This one was the first interview I've participated in where I was on the giving
end. The kid looked promising, but he was a bit sloppy. He wanted to write the
implementation in Python (the language he was most comfortable with), but wasn't
comfortable with the syntax (e.g. started function declarations with `fun`,
didn't understand how to write a `for` loop properly), and had loads of syntax
errors (some of which made me go "hmm...") and bugs.
**Update**: Turns out you can interview someone even worse. This person didn't
even _understand_ the concept of a for-loop. I'm not sure how management
screened this guy (if at all).
## Description
Return the (first) longest word in a sentence.
Method stub:
```cs
string LongestWord(string sentence);
```
## Expected Output
The sentence `"The quick brown fox jumps over the lazy dog."` should return
`"quick"`.
The sentence `"Lorem ipsum dolor sit amet, consectetur adipiscing elit."` should
return `"consectetur"`.<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace EmployeeManager
{
class Program
{
static void Main(string[] args)
{
var employees = GetEmployees();
PopulateSubordinates(employees);
ShowHierarchy(employees);
}
/// <summary>
/// Prints out the employee hierarchy for <paramref name="employees" />.
/// </summary>
private static void ShowHierarchy(List<Employee> employees)
{
foreach (Employee employee in employees)
{
Console.WriteLine($"{employee}");
if (employee.Employees != null)
{
Console.WriteLine($"|-- {string.Join(", ", employee.Employees)}");
}
}
}
/// <summary>
/// Populates each <see cref="Employee" /> object in <paramref
/// name="employees" /> with its subordinate employees.
/// </summary>
/// <param name="employees">the list of employees</param>
public static void PopulateSubordinates(List<Employee> employees)
{
// Create a mapping between a `Employee.ManagerId` and all employees
// who have that `Employee.ManagerId`.
var dictionary = new Dictionary<int, List<Employee>>();
foreach (Employee employee in employees.Where(x => x.ManagerId.HasValue))
{
if (dictionary.ContainsKey(employee.ManagerId.Value))
{
dictionary[employee.ManagerId.Value].Add(employee);
}
else
{
dictionary.Add(employee.ManagerId.Value, new List<Employee> { employee });
}
}
// Populate each employee object with its list of subordinate
// employees.
foreach (Employee employee in employees)
{
if (dictionary.ContainsKey(employee.EmployeeId))
{
employee.Employees = dictionary[employee.EmployeeId];
}
}
}
/// <summary>
/// Mocks a database call that maps the result set of `SELECT * FROM
/// Employee` with a C# <see cref="List{Employee}" />.
/// </summary>
/// <returns>a list of employees</returns>
private static List<Employee> GetEmployees()
{
return new List<Employee>
{
new Employee
{
EmployeeId = 1,
FirstName = "Tupac",
LastName = "Shakur"
},
new Employee
{
EmployeeId = 2,
FirstName = "Marshall",
LastName = "Mathers",
ManagerId = 1
},
new Employee
{
EmployeeId = 3,
FirstName = "Calvin",
LastName = "Broadus",
ManagerId = 1
},
new Employee
{
EmployeeId = 4,
FirstName = "Robert",
LastName = "Fitzgerald",
ManagerId = 2
},
new Employee
{
EmployeeId = 5,
FirstName = "Gary",
LastName = "Grice",
ManagerId = 2
},
new Employee
{
EmployeeId = 6,
FirstName = "Clifford",
LastName = "Smith"
},
new Employee
{
EmployeeId = 7,
FirstName = "Corey",
LastName = "Woods"
},
new Employee
{
EmployeeId = 8,
FirstName = "Dennis",
LastName = "Coles"
},
new Employee
{
EmployeeId = 9,
FirstName = "Jason",
LastName = "Hunter",
ManagerId = 7
},
new Employee
{
EmployeeId = 10,
FirstName = "Lamont",
LastName = "Hawkins",
ManagerId = 7
},
new Employee
{
EmployeeId = 11,
FirstName = "Jamel",
LastName = "Irief",
ManagerId = 6
},
new Employee
{
EmployeeId = 12,
FirstName = "Darryl",
LastName = "Hill",
ManagerId = 11
},
};
}
}
}
<file_sep>using System.Collections.Generic;
namespace EmployeeManager
{
/// <summary>
/// Data contract for the <cref="Employee" /> table.
/// </summary>
public class Employee
{
#region Data Members
/// <summary>
/// Gets or sets the <see cref="EmployeeId" />.
/// </summary>
public int EmployeeId { get; set; }
/// <summary>
/// Gets or sets the <see cref="FirstName" />.
/// </summary>
public string FirstName { get; set; }
/// <summary>
/// Gets or sets the <see cref="LastName" />.
/// </summary>
public string LastName { get; set; }
/// <summary>
/// Gets or sets the <see cref="ManagerId" />.
/// </summary>
public int? ManagerId { get; set; }
#endregion Data Members
#region Properties
/// <summary>
/// Gets or sets the <see cref="Employees" />.
/// </summary>
public List<Employee> Employees { get; set; }
#endregion Properties
/// <summary>
/// Returns the name of this <see cref="Employee" />.
/// <summary>
/// <returns>the name of this <see cref="Employee" /></returns>
public override string ToString() => $"{FirstName} {LastName}";
}
}<file_sep># Interviews
A collection of interview questions I've (received | given) and their answers,
sometimes in the spirit of ([l'esprit
d'escalier](https://en.wikipedia.org/wiki/L%27esprit_de_l%27escalier) |
[afterwit](https://en.wiktionary.org/wiki/afterwit) |
[jerk-storing](https://en.wikipedia.org/wiki/The_Comeback_(Seinfeld)#George's_Comeback)).
## Questions
* [Car Racer](./CarRacer/README.md)
* [Diagonal](./Diagonal/README.md)
* [Employee Manager](./EmployeeManager/README.md)
* [Kingdom](./Kingdom/README.md)
* [Longest Word](./LongestWord/README.md)
* [Palindrome](./Palindrome/README.md)<file_sep># Palindrome
## Background
This one was for a position in a completely new city. I had big plans to start a
new life there, but was still a little unsure about it all. In the end, I didn't
get offered the position, but I did spend a lot of time contemplating what
moving to a new city would be like, and it was exciting. The problem itself
wasn't that interesting/difficult, but I'll remember it.
## Description
Determine whether a string is a palindrome.
Method stub:
```cs
bool IsPalindrome(string candidate);
```
## Expected Output
The string `"hannah"` should return `true`.
The string `"hanna"` should return `false`.
The string `"racecar"` should return `true`.<file_sep>using System;
using System.Linq;
using System.Text;
namespace LongestWord
{
public class Program
{
public static string LongestWord(string sentence)
{
string[] words = sentence.Split(' ', StringSplitOptions.RemoveEmptyEntries);
// Remove punctuation.
for (int i = 0; i < words.Length; i++)
words[i] = words[i].StripPunctuation();
// Find longest word.
string longestWord = string.Empty;
foreach (var word in words)
if (word.Length > longestWord.Length)
longestWord = word;
return longestWord;
}
public static void Main(string[] args)
{
string s1 = "The quick brown fox jumps over the lazy dog.";
string s2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
Console.WriteLine($"Calling {nameof(LongestWord)} on \"{s1}\" returned \"{LongestWord(s1)}\".");
Console.WriteLine($"Calling {nameof(LongestWord)} on \"{s2}\" returned \"{LongestWord(s2)}\".");
}
}
public static class StringExtensions
{
public static string StripPunctuation(this string s)
{
var sb = new StringBuilder();
foreach (char ch in s)
if (!char.IsPunctuation(ch))
sb.Append(ch);
return sb.ToString();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
namespace Diagonal
{
class Program
{
static void Main(string[] args)
{
var matrix = new int[3, 3]
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
var diagonal = GetDiagonal(matrix);
bool shouldBeTrue = diagonal.SequenceEqual(new List<int> { 1, 5, 9 });
Console.WriteLine($"{nameof(shouldBeTrue)} returned {shouldBeTrue}");
}
/// <summary>
/// Returns a list containing the diagonal elements of the matrix.
/// </summary>
/// <param name="matrix">The matrix.</param>
/// <returns>A list containing the diagonal elements of the matrix.</returns>
static List<int> GetDiagonal(int[,] matrix)
{
var list = new List<int>();
for (int i = 0, j = 0; i < matrix.GetLength(0); i++, j++)
{
list.Add(matrix[i, j]);
}
return list;
}
/// <summary>
/// Returns a random n x n matrix with elements ranging from 0 to 9.
/// </summary>
/// <param name="n">The size of the matrix to be returned.</param>
/// <returns>A random n x n matrix with elements ranging from 0 to 9.</returns>
static int[,] GetMatrix(int n)
{
var random = new Random();
var matrix = new int[n, n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i, j] = random.Next(10);
return matrix;
}
/// <summary>
/// Prints the matrix.
/// </summary>
/// <param name="matrix">The matrix.</param>
static void PrintMatrix(int[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
Console.Write($"{matrix[i, j]} ");
System.Console.WriteLine();
}
}
}
}
|
1e0c6f0b8b900251adcf983527d402f5a77d9829
|
[
"Markdown",
"C#"
] | 13 |
Markdown
|
adyavanapalli/Interviews
|
5b28e56f271dbf4bc4c8900d02e10b7bacf721d8
|
2da49361cf6ecb119352c70225caaed6c22ecc43
|
refs/heads/master
|
<repo_name>eduzera/magerecord<file_sep>/lib/magerecord/sale.rb
module MageRecord
class Sale < MagentoDatabase
self.table_name = :sales_flat_invoice_grid
belongs_to :order
end
end<file_sep>/lib/magerecord/order.rb
module MageRecord
class Order < MagentoDatabase
self.table_name = :sales_flat_order
has_one :sale
# ignore canceled orders
default_scope { where status: [:processing, :complete] }
scope :only_complete, -> {where status: [:complete]}
belongs_to :customer
has_one :billing_address, -> { where address_type: 'billing' }, class_name: :OrderAddress, foreign_key: :parent_id
has_one :shipping_address, -> { where address_type: 'shipping' }, class_name: :OrderAddress, foreign_key: :parent_id
has_many :items, class_name: :OrderItem
has_many :products, through: :items
has_many :bills
end
end
<file_sep>/lib/magerecord/order_address.rb
module MageRecord
class OrderAddress < MagentoDatabase
self.table_name = :sales_flat_order_address
belongs_to :order, foreign_key: :parent_id
end
end
<file_sep>/lib/magerecord/stock.rb
module MageRecord
class Stock < MagentoDatabase
self.table_name = :cataloginventory_stock_item
belongs_to :product
end
end
<file_sep>/lib/magerecord/customer.rb
module MageRecord
class Customer < EavRecord
self.table_name = :customer_entity
belongs_to :store
belongs_to :website
has_many :addresses, foreign_key: :parent_id
has_many :orders
def fullname
firstname_sql = "SELECT entity_varchar.value "+
"FROM customer_entity AS entity "+
"LEFT JOIN eav_attribute AS ea ON entity.entity_type_id = ea.entity_type_id "+
"LEFT JOIN customer_entity_varchar AS entity_varchar ON entity.entity_id = entity_varchar.entity_id "+
"AND ea.attribute_id = entity_varchar.attribute_id "+
"AND ea.backend_type = 'varchar' "+
"WHERE ea.attribute_code = 'firstname' "+
"AND entity.entity_id = #{self.id}"
lastname_sql = "SELECT entity_varchar.value "+
"FROM customer_entity AS entity "+
"LEFT JOIN eav_attribute AS ea ON entity.entity_type_id = ea.entity_type_id "+
"LEFT JOIN customer_entity_varchar AS entity_varchar ON entity.entity_id = entity_varchar.entity_id "+
"AND ea.attribute_id = entity_varchar.attribute_id "+
"AND ea.backend_type = 'varchar' "+
"WHERE ea.attribute_code = 'lastname' "+
"AND entity.entity_id = #{self.id}"
firstname = self.class.connection.execute(firstname_sql).first
lastname = self.class.connection.execute(lastname_sql).first
(firstname + lastname).join(' ')
end
def self.find_by_name(name)
sql = "SELECT entity.entity_id , entity_varchar.value "+
"FROM customer_entity AS entity "+
"LEFT JOIN eav_attribute AS ea ON entity.entity_type_id = ea.entity_type_id "+
"LEFT JOIN customer_entity_varchar AS entity_varchar ON entity.entity_id = entity_varchar.entity_id "+
"AND ea.attribute_id = entity_varchar.attribute_id "+
"AND ea.backend_type = 'varchar' "+
"WHERE ea.attribute_code = 'firstname' "+
"AND entity_varchar.value LIKE '%#{name}%'"
self.connection.execute(sql).collect{|x| OpenStruct.new({id: x[0], fullname: Customer.find(x[0]).fullname})}
end
end
end
<file_sep>/lib/magerecord/magento_database.rb
module MageRecord
class MagentoDatabase < ActiveRecord::Base
self.abstract_class = true
def self.connect(options={})
MageRecord::MagentoDatabase.establish_connection(
adapter: options[:adapter],
host: options[:host],
database: options[:database],
username: options[:username],
password: options[:<PASSWORD>],
secure_auth: options[:secure_auth]
)
end
end
end<file_sep>/lib/magerecord/bill.rb
module MageRecord
class Bill < MagentoDatabase
self.table_name = :sales_flat_invoice
belongs_to :order
end
end
|
7e79400d16e77d9df1b6117cdcd2b7da287f86b4
|
[
"Ruby"
] | 7 |
Ruby
|
eduzera/magerecord
|
cd6613f6fdc835407e5a2caa6a1fac217a1cd9d5
|
7f8bf8a6214320765c54927327d253f1368e6944
|
refs/heads/main
|
<repo_name>rsoria21/Journal<file_sep>/app.js
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const _ = require("lodash");
const homeStartingContent = "Hey, wow so it my time to shine huh? Okay! Welcome, look around and explore. I hope you like what you see. Oh and yes those buttons work, press on them and explore what you can compose";
const aboutContent = "Hey, Glad you made it this far. So I'm basically a place to keep your thoughts for the day.";
const contactContent = "Whoa slow down there, this is a demo! Hey, but this is where he contact info would be.";
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
let posts = [];
app.get("/", function (req, res) {
res.render("home", {
startingContent: homeStartingContent,
posts: posts
});
});
app.get("/about", function (req, res) {
res.render("about", { aboutContent: aboutContent });
});
app.get("/contact", function (req, res) {
res.render("contact", { contactContent: contactContent });
});
app.get("/compose", function (req, res) {
res.render("compose");
});
app.post("/compose", function (req, res) {
const post = {
title: req.body.postTitle,
content: req.body.postBody
};
posts.push(post);
res.redirect("/");
});
app.get("/posts/:postName", function (req, res) {
const requestedTitle = _.lowerCase(req.params.postName);
posts.forEach(function (post) {
const storedTitle = _.lowerCase(post.title);
if (storedTitle === requestedTitle) {
res.render("post", {
title: post.title,
content: post.content
});
}
});
});
app.listen(3000, function () {
console.log("Server started on port 3000");
});
|
55cf36246d0942949f1f234a668241a8ac3dc991
|
[
"JavaScript"
] | 1 |
JavaScript
|
rsoria21/Journal
|
4eaaf04bb02af32f725d23c8ade2230e147f74ef
|
adebc4f6c153dc2b43ffc81226648bb8e31bf57e
|
refs/heads/master
|
<file_sep># node-libuuid
## Description
A node C binding to the libuuid library's uuid_generate().
NOTE: The uuid returned is lowercased.
## Prerequisites
You must have libuuid installed on your machine.
In Ubuntu:
apt-get install uuid-dev
## Install
npm install libuuid
## Usage
var libuuid = require('libuuid');
var uuid_val = libuuid.create();
console.log(" UUID = ", uuid_val);
// If you want to use libuuid as a drop in replacement for node-uuid then simply do
var uuid = require('libuuid').create;
var uuid_val = uuid();
console.log(" UUID = ", uuid_val);
<file_sep>module.exports=require('./build/default/libuuid.node');
|
1230efd609440372e7b4c8882f107870b819bf95
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
charlesdaniel/node-libuuid
|
2d548a25d84a088768e3acd6413dd329748ac7ca
|
4863d0451196cd30d4daea506533a2bed18c6b76
|
refs/heads/master
|
<repo_name>andremarasca/ProjetosGit<file_sep>/PilhaGenerica/Pilha.c
#include <stdio.h>
#include <stdlib.h>
#include "Pilha.h"
struct nodo
{
void *elemento;
Nodo *proximo;
};
//Cabecalhos estaticos das funcoes da pilha
// static pra evitar que sejam chamados
// sem ser por "orientacao objeto"
static void empilha (Pilha *p, void *elemento);
static int desempilha (Pilha *p);
static void *topo (Pilha *p);
static int vazia(Pilha *p);
// A funcao abaixo coloca um novo elemento
// no inicio da pilha, pra isso o novo
// elemento deve apontar pro inicio da pilha
// e o topo da pilha eh atualizado para esse
// novo elemento
static void empilha (Pilha *p, void *elemento)
{
Nodo *novo = (Nodo *) malloc(sizeof(Nodo));
novo->elemento = elemento;
novo->proximo = p->primeiro;
p->primeiro = novo;
}
// O desempilha verifica se a pilha esta vazia.
// Se estiver vazia nao tem mais como desempilhar.
// Se nao estiver vazia, salva o topo atual da pilha,
// muda a topo da pilha para o proximo Nodo,
// desaloca o elemento do nodo que vai ser desempilhado,
// e por fim desaloca o ponteiro para o nodo
// que vai ser desempilhado
static int desempilha (Pilha *p)
{
if(vazia(p))
return 0;
Nodo *q = p->primeiro;
p->freeelemento(q->elemento);
p->primeiro = q->proximo;
free(q);
return 1;
}
// essa funcao verifica se a pilha esta vazia,
// se estiver vazia, entao retorna NULL,
// caso contrario, retorna o ponteiro para
// o elemento do nodo do topo da pilha.
static void *topo (Pilha *p)
{
if(vazia(p))
return NULL;
return p->primeiro->elemento;
}
// a funcao abaixo retorna 1 se a pilha esta vazia
// caso contrario retorna 0
static int vazia(Pilha *p)
{
if(p->primeiro == NULL)
return 1;
return 0;
}
// A funcao abaixo recebe a funcao que limpa elemento
// como calback, aloca uma pilha nova, ajusta os ponteiros
// de funcao e retorna o ponteiro para a pilha alocada
Pilha *NewPilha(void (*freeelemento)(void *elemento))
{
Pilha *p = (Pilha *) malloc(sizeof(Pilha));
p->primeiro = NULL;
p->empilha = empilha;
p->desempilha = desempilha;
p->topo = topo;
p->vazia = vazia;
p->freeelemento = freeelemento;
return p;
}
// Desaloca o objeto Pilha
// enquanto nao estiver vazia
// vai desempilhando
void DestroiPilha(Pilha *p)
{
while(!p->vazia(p))
p->desempilha(p);
free(p);
}
<file_sep>/FilaGenerica/Fila.h
#ifndef PILHA_H_INCLUDED
#define PILHA_H_INCLUDED
typedef struct fila Fila;
typedef struct nodo Nodo;
struct fila
{
Nodo *primeiro;
Nodo *ultimo;
void (*enfila) (Fila *p, void *elemento);
int (*desenfila) (Fila *p);
void *(*topo) (Fila *p);
int (*vazia) (Fila *p);
void (*freeelemento)(void *elemento);
};
Fila *NewFila(void (*freeelemento)(void *elemento));
void DestroiFila(Fila *p);
#endif // PILHA_H_INCLUDED
<file_sep>/FilaGenerica/Fila.c
#include <stdio.h>
#include <stdlib.h>
#include "Fila.h"
struct nodo
{
void *elemento;
Nodo *proximo;
};
//Cabecalhos estaticos das funcoes da fila
// static pra evitar que sejam chamados
// sem ser por "orientacao objeto"
static void enfila (Fila *p, void *elemento);
static int desenfila (Fila *p);
static void *topo (Fila *p);
static int vazia(Fila *p);
// A funcao enfila abaixo recebe um elemento
// coloca num bloco novo, manda esse bloco
// apontar pro vazio, pois ele vai ser o ultimo.
// Em seguida, se o novo nodo eh o primeiro
// ele se torna o primeiro e ultimo ao mesmo tempo
// caso contrario, o proximo do atual ultimo
// aponta pra ele e ele se torna o ultimo
static void enfila (Fila *f, void *elemento)
{
Nodo *novo = (Nodo *)malloc(sizeof(Nodo));
novo->elemento = elemento;
novo->proximo = NULL;
if(f->primeiro == NULL)
f->primeiro = novo;
else
f->ultimo->proximo = novo;
f->ultimo = novo;
}
// O desenfila recebe a fila, retorna 0
// se nao tem mais nada pra desenfilar
// e retorna 1 se desenfilou com sucesso.
// Salva o ponteiro do primeiro pois sera
// removido. Se for o unico elemento da fila
// o primeiro e o ultimo se tornam NULL.
// caso contraio, o segundo vira o primeiro
static int desenfila (Fila *f)
{
if(f->primeiro == NULL)
return 0;
Nodo *tmp = f->primeiro;
if(f->primeiro == f->ultimo)
f->primeiro = f->ultimo = NULL;
else
f->primeiro = tmp->proximo;
free(tmp);
return 1;
}
// essa funcao verifica se a fila esta vazia,
// se estiver vazia, entao retorna NULL,
// caso contrario, retorna o ponteiro para
// o elemento do nodo do topo da fila.
static void *topo (Fila *f)
{
if(vazia(f))
return NULL;
return f->primeiro->elemento;
}
// a funcao abaixo retorna 1 se a fila esta vazia
// caso contrario retorna 0
static int vazia(Fila *f)
{
if(f->primeiro == NULL)
return 1;
return 0;
}
// A funcao abaixo recebe a funcao que limpa elemento
// como calback, aloca uma fila nova, ajusta os ponteiros
// de funcao e retorna o ponteiro para a fila alocada
Fila *NewFila(void (*freeelemento)(void *elemento))
{
Fila *f = (Fila *) malloc(sizeof(Fila));
f->primeiro=NULL;
f->ultimo=NULL;
f->enfila = enfila;
f->desenfila = desenfila;
f->topo = topo;
f->vazia = vazia;
f->freeelemento = freeelemento;
return f;
}
// Desaloca o objeto Fila
// enquanto nao estiver vazia
// vai desenfilando
void DestroiFila(Fila *f)
{
while(!f->vazia(f))
f->desenfila(f);
free(f);
}
<file_sep>/README.md
# Códigos Uteis
<file_sep>/FilaGenerica/main.c
#include <stdio.h>
#include <stdlib.h>
#include "Fila.h"
typedef struct item Item;
// Estrutura com o item desejado
struct item {
int x, y;
};
// Funcao necessaria para dar free nos itens alocados
// Note que a estrutura poderia ter conter uma matriz dinamica
// Em que a desalocacao eh mais complicada que apenas chamar free
void freeFilaItem(void *item)
{
Item *x = (Item *) item;
free(x);
}
// Funcao necessaria para alocar o elemento a ser enfilado
// Note que isso torna a fila generica, uma vez que a alocacao
// eh dinamica, dessa forma, qualquer tipo de dado pode ser usado
// dentro da estrutura Item
Item *NewItem(int x, int y)
{
Item *item = (Item *) malloc(sizeof(Item));
item->x = x;
item->y = y;
return item;
}
// Para pegar um item deve-se chamar o topo
// Ao fazer isso deve-se atribuir o retorno
// para um ponteiro de Item, pra evitar ser
// um processo tedioso eu fiz uma funcao
Item *topoFilaItem(Fila *f)
{
Item *item = (Item *) f->topo(f);
return item;
}
// Funcao principal contendo um exemplo de uso da fila
// Todas as funcoes foram utilizada eh um exemplo completo
int main(void)
{
// A fila foi implementada com ponteiros de funcao
// em uma struct, sendo assim, todas as funcoes
// necessarias para seu funcionamento estao encapsuladas
Fila *f = NewFila(freeFilaItem);
int i;
for(i = 0; i < 100; i++)
{
// ao inserir um item na fila eh necessario
// fazer a tipagem para ponteiro de void
f->enfila(f, (void *) NewItem(i, 100 - i));
}
FILE *arq = fopen("Saida.txt", "w+");
while(!f->vazia(f))
{
Item *item = topoFilaItem(f);
fprintf(arq, "%d %d\n", item->x, item->y);
f->desenfila(f);
}
fclose(arq);
DestroiFila(f);
return 0;
}
<file_sep>/PilhaFilaProntas/Pilha.c
#include <stdio.h>
#include <stdlib.h>
typedef struct nodo
{
int elemento;
struct nodo *proximo;
}Nodo;
typedef struct pilha
{
Nodo *primeiro;
}Pilha;
void inicializa(Pilha *p)
{
p->primeiro = NULL;
}
void empilha (Pilha *p,int elemento)
{
Nodo *novo = (Nodo *)malloc(sizeof(Nodo));
novo->elemento = elemento;
novo->proximo = p->primeiro;
p->primeiro = novo;
}
int desempilha (Pilha *p)
{
Nodo *q = p->primeiro;
int x = q->elemento;
p->primeiro = q->proximo;
free(q);
return x;
}
int pilhavazia(Pilha *p)
{
if(p->primeiro == NULL) return 1;
return 0;
}
int main (void)
{
Pilha pilha;
inicializa(&pilha);
int i;
for(i=0;i<100;i++) empilha(&pilha,i);
while(!pilhavazia(&pilha)) printf("%d\n",desempilha(&pilha));
return 0;
}
<file_sep>/PilhaGenerica/Pilha.h
#ifndef PILHA_H_INCLUDED
#define PILHA_H_INCLUDED
typedef struct pilha Pilha;
typedef struct nodo Nodo;
struct pilha
{
Nodo *primeiro;
void (*empilha) (Pilha *p, void *elemento);
int (*desempilha) (Pilha *p);
void *(*topo) (Pilha *p);
int (*vazia) (Pilha *p);
void (*freeelemento)(void *elemento);
};
Pilha *NewPilha(void (*freeelemento)(void *elemento));
void DestroiPilha(Pilha *p);
#endif // PILHA_H_INCLUDED
<file_sep>/PilhaFilaProntas/Fila.c
#include <stdio.h>
#include <stdlib.h>
typedef struct nodo
{
int elemento;
struct nodo *proximo;
} Nodo;
typedef struct fila
{
Nodo *primeiro;
Nodo *ultimo;
} Fila;
void inicializa (Fila *f)
{
f->primeiro=NULL;
f->ultimo=NULL;
}
void enfila (Fila *f, int elemento)
{
Nodo *novo = (Nodo *)malloc(sizeof(Nodo));
novo->elemento = elemento;
novo->proximo = NULL;
if(f->primeiro == NULL)
{
f->primeiro = novo;
f->ultimo = novo;
}
else
{
f->ultimo->proximo = novo;
f->ultimo = novo;
}
}
int desenfila (Fila *f)
{
if(f->primeiro == NULL) return -1;
Nodo *tmp = f->primeiro;
int x = tmp->elemento;
if(f->primeiro == f->ultimo) f->primeiro = f->ultimo = NULL;
else
{
f->primeiro = tmp->proximo;
}
free(tmp);
return x;
}
int filavazia (Fila *f)
{
if(f->primeiro == NULL) return 1;
return 0;
}
int main (void)
{
Fila fila;
inicializa (&fila);
int i;
for (i = 0; i < 100; i++) enfila (&fila, i);
while (!filavazia (&fila)) printf("%d\n", desenfila (&fila));
return 0;
}
|
87e8ba4eb07ad147f1893b47ae9cebdc3a5f45ca
|
[
"Markdown",
"C"
] | 8 |
C
|
andremarasca/ProjetosGit
|
d16d882454b1a429e9abc6ac94109497977f44d1
|
c0d95876136d00024187455cc09772f8a765d768
|
refs/heads/master
|
<repo_name>dhananjaysinghar/Spring-Async-with-Combine-Ops<file_sep>/src/main/java/com/test/TestController.java
package com.test;
import java.util.concurrent.CompletableFuture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private TestService testService;
@GetMapping("/get")
public ResponseEntity<String> getAllData() throws Exception {
CompletableFuture<String> get1 = testService.get1();
CompletableFuture<String> get2 = testService.get2();
CompletableFuture<String> get3 = testService.get3();
// Wait until they are all done
CompletableFuture.allOf(get1, get2, get3);
return ResponseEntity.ok(get1.get() + " " + get2.get() + " " + get3.get());
}
}
<file_sep>/src/main/java/com/test/TestService.java
package com.test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class TestService {
@Async
public CompletableFuture<String> get1() {
sleep(10);
System.out.println("get1 :: "+Thread.currentThread().getName());
return CompletableFuture.completedFuture("Hello ");
}
@Async
public CompletableFuture<String> get2() {
sleep(2);
System.out.println("get2 :: "+Thread.currentThread().getName());
return CompletableFuture.completedFuture("Dhananjay");
}
@Async
public CompletableFuture<String> get3() {
sleep(5);
System.out.println("get3 :: "+Thread.currentThread().getName());
return CompletableFuture.completedFuture("!!");
}
public void sleep(int time) {
try {
TimeUnit.SECONDS.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/resources/application.properties
message=Hi Dhananjaya Current Time is :
|
093b52c90f9a8b94eefd7c73a152f2f451c479bf
|
[
"Java",
"INI"
] | 3 |
Java
|
dhananjaysinghar/Spring-Async-with-Combine-Ops
|
af8ea43fa332562c4a8908ff6c7846bd7bc78e2e
|
92f2859b2d09767b6bbdd6babec6f2ce66cd6d60
|
refs/heads/master
|
<file_sep>from django import forms
from django.db.models import Q
from django.forms.widgets import CheckboxSelectMultiple
from django.utils.translation import gettext_lazy as _
from .models import Guest, Gift
class LoginForm(forms.Form):
error_msg = _('Nieprawidłowe hasło lub login')
username = forms.CharField(label='Login')
password = forms.CharField(label=_('<PASSWORD>'), widget=forms.PasswordInput)
class GuestForm(forms.ModelForm):
class Meta:
model = Guest
exclude = ['username', 'is_accompanying_person', 'eligible_for_afters']
def __init__(self, *args, **kwargs):
super(GuestForm, self).__init__(*args, **kwargs)
guest = kwargs['instance']
if not guest.is_accompanying_person:
del self.fields['name']
del self.fields['surname']
if not guest.eligible_for_afters:
del self.fields['attending_afters']
def as_my_p(self):
return self._html_output(
normal_row='<p%(html_class_attr)s data-toggle="tooltip" data-placement="left" title="%(help_text)s">%(label)s %(field)s</p>',
error_row='%s',
row_ender='</p>',
help_text_html='%s',
errors_on_separate_row=True,
)
GuestFormSet = forms.modelformset_factory(Guest, form=GuestForm, extra=0)
class GiftForm(forms.Form):
gifts = forms.MultipleChoiceField()
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(GiftForm, self).__init__(*args, **kwargs)
self.fields['gifts'].widget = CheckboxSelectMultiple()
self.fields['gifts'].choices = list(map(lambda g: (g.id, g.name), Gift.objects.filter(Q(user=None) | Q(user=user))))
self.fields['gifts'].initial = list(map(lambda g: g.id, Gift.objects.filter(user=user)))
self.fields['gifts'].required = False
self.taken_gifts = list(Gift.objects.exclude(user=None).exclude(user=user))
<file_sep>from wedding_guests.views import Home
def test_example():
assert True
<file_sep># Generated by Django 2.0.4 on 2018-06-09 07:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0004_auto_20180516_2113'),
]
operations = [
migrations.AlterField(
model_name='guest',
name='gift',
field=models.CharField(blank=True, max_length=50, verbose_name='Prezent'),
),
]
<file_sep>[pytest]
DJANGO_SETTINGS_MODULE = ai_project.settings
<file_sep># Generated by Django 2.0.4 on 2018-06-13 09:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0009_auto_20180612_2328'),
]
operations = [
migrations.AlterField(
model_name='guest',
name='gift',
field=models.CharField(blank=True, help_text='W celu uniknięcia powtarzania się upominków,\n możesz wpisać tutaj swój prezent.', max_length=50, verbose_name='Prezent'),
),
migrations.AlterField(
model_name='guest',
name='wants_bus',
field=models.BooleanField(default=False, help_text='Zapewniamy dojazd spod kościoła na salę weselną zaraz po mszy\n i z powrotem do Poznania na koniec wesela (koło 4 w nocy).', verbose_name='Chcę jechać autobusem'),
),
]
<file_sep># Generated by Django 2.1.3 on 2018-12-22 13:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0012_gift'),
]
operations = [
migrations.DeleteModel(
name='Page',
),
migrations.RemoveField(
model_name='guest',
name='gift',
),
]
<file_sep>from django.apps import AppConfig
class WeddingGuestsConfig(AppConfig):
name = 'wedding_guests'
<file_sep>from django.shortcuts import render, redirect, render_to_response
from django.views.generic.base import TemplateView
from django.views import View
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import JsonResponse
from django.contrib import messages
from django.utils.translation import gettext_lazy as _
from .forms import LoginForm, GuestFormSet, GiftForm
from .models import Guest, Gift
class HomeView(View):
def get(self, request):
login_form = LoginForm()
return render(request, 'home.html', {'login_form': login_form})
def post(self, request):
login_form = LoginForm(request.POST)
if login_form.is_valid():
username = login_form.cleaned_data['username']
password = <PASSWORD>_form.cleaned_data['<PASSWORD>']
user = authenticate(username=username, password=<PASSWORD>)
if user is not None:
login(request, user)
else:
login_form.add_error(None, login_form.error_msg)
return render(request, 'home.html', {'login_form': login_form})
class RSVPView(LoginRequiredMixin, View):
def get(self, request, active_tab=0):
guests = Guest.objects.filter(username=request.user)
formset = GuestFormSet(queryset=guests)
gift_form = GiftForm(user=request.user)
gift_urls = {gift.id: gift.url for gift in Gift.objects.all()}
if 0 > active_tab or active_tab > len(formset):
active_tab = 0
return render(request, 'rsvp.html',
{'formset': formset, 'gift_form': gift_form, 'gift_urls': gift_urls, 'active_tab': active_tab})
def post(self, request, active_tab=0):
formset = GuestFormSet(request.POST)
gift_form = GiftForm(request.POST, user=request.user)
if formset.is_valid() and gift_form.is_valid():
formset.save()
chosen_gift_ids = gift_form.cleaned_data['gifts']
Gift.objects.filter(user=request.user).update(user=None)
Gift.objects.filter(id__in=chosen_gift_ids).update(user=request.user)
messages.success(request, _('Poprawna aktualizacja formularza'))
return redirect('rsvp_tab_active', active_tab)
def logout_view(request):
logout(request)
return redirect('home')
class Wedding(TemplateView):
template_name = 'wedding.html'
class Commute(TemplateView):
template_name = 'commute.html'
class Accommodation(TemplateView):
template_name = 'accommodation.html'
class Contact(TemplateView):
template_name = 'contact.html'
def handler404(request, exception, template_name="404.html"):
response = render_to_response(template_name)
response.status_code = 404
return response
<file_sep># Generated by Django 2.1.3 on 2019-01-25 17:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0016_guest_is_accompanying_person'),
]
operations = [
migrations.AddField(
model_name='guest',
name='attending_afters',
field=models.CharField(choices=[('Yes', 'Tak'), ('No', 'Nie'), ('Maybe', 'Nie określono')], default='Maybe', max_length=5, verbose_name='Będę na poprawinach'),
),
migrations.AddField(
model_name='guest',
name='eligible_for_afters',
field=models.BooleanField(default=False),
),
migrations.AlterField(
model_name='guest',
name='wants_bus',
field=models.BooleanField(default=False, help_text='Więcej informacji w zakładce dojazd.', verbose_name='Chcę jechać busem'),
),
]
<file_sep># Generated by Django 2.0.4 on 2018-05-16 18:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Guest',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30, verbose_name='Imię')),
('surname', models.CharField(max_length=50, verbose_name='Nazwisko')),
('attending', models.CharField(choices=[('Yes', 'Tak'), ('No', 'Nie'), ('Maybe', 'Nie określono')], default='Maybe', max_length=5, verbose_name='Będę na weselu')),
('wants_bus', models.BooleanField(default=False, help_text='Zapewniamy dojazd spod kościoła na salę weselną zaraz po mszy\n i z powrotem do Poznania na koniec wesela (koło 4 w nocy).')),
('is_vegetarian', models.BooleanField(default=False, help_text='Informacja ta pomoże nam przy wyborze menu')),
('gift', models.CharField(max_length=50, verbose_name='Prezent')),
('comments', models.CharField(max_length=200, verbose_name='Dodatkowy komentarz')),
('username', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import gettext_lazy as _
class Guest(models.Model):
YES, NO, MAYBE = 'Yes', 'No', 'Maybe'
ATTENDING_STATUSES = (
(YES, _('Tak')),
(NO, _('Nie')),
(MAYBE, _('Nie określono'))
)
username = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(_('Imię'), max_length=30)
surname = models.CharField(_('Nazwisko'), max_length=50)
attending = models.CharField(
_('Będę na weselu'), max_length=len(MAYBE), default=MAYBE, choices=ATTENDING_STATUSES
)
attending_afters = models.CharField(
_('Będę na poprawinach'), max_length=len(MAYBE), default=MAYBE, choices=ATTENDING_STATUSES,
help_text=_('Więcej informacji w zakładce Ślub i Wesele')
)
wants_bus = models.BooleanField(
_('Chcę jechać busem'),
default=False,
help_text=_('Więcej informacji w zakładce dojazd.')
)
is_vegetarian = models.BooleanField(
_('Preferuję dania wegetariańskie'),
default=False,
help_text=_('Informacja ta pomoże nam przy wyborze menu')
)
comments = models.TextField(_('Dodatkowy komentarz'), blank=True, max_length=200)
is_accompanying_person = models.BooleanField(default=False)
eligible_for_afters = models.BooleanField(default=False)
def __str__(self):
return '{} {}'.format(self.name, self.surname)
class Gift(models.Model):
name = models.CharField('Nazwa', max_length=100)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
url = models.URLField(blank=True, null=True)
def __str__(self):
return self.name
<file_sep># Generated by Django 2.1.3 on 2019-01-02 10:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0014_remove_gift_is_reserved'),
]
operations = [
migrations.AddField(
model_name='gift',
name='url',
field=models.URLField(blank=True, null=True),
),
]
<file_sep># Generated by Django 2.0.4 on 2018-06-12 21:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0008_page_url'),
]
operations = [
migrations.AlterField(
model_name='page',
name='image',
field=models.ImageField(blank=True, upload_to='', verbose_name='Zdjęcie'),
),
]
<file_sep># Generated by Django 2.1.3 on 2019-01-08 20:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0015_gift_url'),
]
operations = [
migrations.AddField(
model_name='guest',
name='is_accompanying_person',
field=models.BooleanField(default=False),
),
]
<file_sep>{% load i18n %}
<nav class="navbar navbar-expand-md navbar-light">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav mr-auto">
<a class="nav-item nav-link" href="{% url 'home' %}" id="menu-home">{% trans 'Strona główna' %}</a>
{% if request.user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'rsvp' %}" id="menu-rsvp">RSVP</a>
{% endif %}
<a class="nav-item nav-link" href="{% url 'wedding' %}" id="menu-wedding">{% trans 'Ślub i wesele' %}</a>
<a class="nav-item nav-link" href="{% url 'commute' %}" id="menu-commute">{% trans 'Dojazd' %}</a>
<a class="nav-item nav-link" href="{% url 'contact' %}" id="menu-contact">{% trans 'Kontakt' %}</a>
{% if user.is_authenticated %}
<a class="nav-item nav-link" href="{% url 'logout' %}">{% trans 'Wyloguj' %}</a>
{% endif %}
</div>
</div>
</nav>
<file_sep># Generated by Django 2.0.4 on 2018-06-12 21:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0007_page_order_no'),
]
operations = [
migrations.AddField(
model_name='page',
name='url',
field=models.CharField(default=None, max_length=15, verbose_name='Url'),
preserve_default=False,
),
]
<file_sep>from .base_settings import *
from .dev_settings import *
<file_sep># Generated by Django 2.0.4 on 2018-06-12 20:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0005_auto_20180609_0945'),
]
operations = [
migrations.CreateModel(
name='Page',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30, verbose_name='Nazwa')),
('header', models.CharField(max_length=100, verbose_name='Nagłówek')),
('content', models.TextField(verbose_name='Treść')),
('image', models.ImageField(upload_to='', verbose_name='Zdjęcie')),
],
),
migrations.AlterField(
model_name='guest',
name='name',
field=models.CharField(editable=False, max_length=30, verbose_name='Imię'),
),
migrations.AlterField(
model_name='guest',
name='surname',
field=models.CharField(editable=False, max_length=50, verbose_name='Nazwisko'),
),
]
<file_sep>{% extends "base.html" %}
{% load static %}
{% load i18n %}
{% block content %}
<div class="row wedding-row">
<div class="col-md-5">
<img src="{% static 'wedding_guests/images/kosciol.jpg' %}" class="rounded"/>
<a class="see-on-map" target="_blank" href="https://www.google.com/maps/dir//Kościół+Rzymskokatolicki+Pw.+św.+Franciszka+Serafickiego+(dawniej+Bernardynów),+Garbary+22,+61-854+Poznań/">
<button class="btn btn-default btn-border">{% trans 'Zobacz na mapie' %}</button>
</a>
</div>
<div class="col-md-7">
<div class="vertical-center">
{% trans 'Ślub odbędzie się 27 kwietnia 2019 roku o godzinie 14:00 w kościele św. <NAME>go w Poznaniu. Kościół znajduje się na ulicy Garbary, przy Placu Bernardyńskim, zaraz obok liceum, w którym się poznaliśmy.' %}
</div>
</div>
</div>
<div class="row wedding-row">
<div class="col-md-7">
<div class="vertical-center">
{% trans 'Wesele planujemy rozpocząć około godziny 16:00 w Pałacu Jaśminowym w Batorowie, około 25km od kościoła. Na terenie pałacu odbędą się dwa wesela jednocześnie, nasze będzie w Sali Jaśminowej. Gdyby komuś się nudziło, to może pójść na wesele obok. Planujemy się bawić do 4:00.' %}
</div>
</div>
<div class="col-md-5">
<img src="{% static 'wedding_guests/images/jasminowy.jpg' %}" class="rounded"/>
<a class="see-on-map" target="_blank" href="https://www.google.com/maps/dir//Pałac+Jaśminowy,+Zakrzewska+15,+62-080+Batorowo/">
<button class="btn btn-default btn-border">{% trans 'Zobacz na mapie' %}</button>
</a>
</div>
</div>
<div class="row wedding-row" style="font-size: 1.5em">
{% trans 'Dzień po weselu zapraszamy członków rodziny na poprawiny. Odbędą się one na terenie Pałacu Jaśminowego, w namiocie bankietowym. Poprawiny będą miały charakter popołudniowego obiadku, nikt nie będzie już zmuszany do tańczenia. Przyjdźcie w strojach mniej formalnych.' %}
</div>
{% endblock %}
{% block js %}
<script>
$("#menu-wedding").addClass("active");
</script>
{% endblock js %}
<file_sep># Generated by Django 2.0.4 on 2018-06-13 10:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0010_auto_20180613_1133'),
]
operations = [
migrations.AlterField(
model_name='guest',
name='name',
field=models.CharField(max_length=30, verbose_name='Imię'),
),
migrations.AlterField(
model_name='guest',
name='surname',
field=models.CharField(max_length=50, verbose_name='Nazwisko'),
),
]
<file_sep>from django.urls import path
from . import views
urlpatterns = [
path('logout', views.logout_view, name='logout'),
path('wedding', views.Wedding.as_view(), name='wedding'),
path('commute', views.Commute.as_view(), name='commute'),
path('accommodation', views.Accommodation.as_view(), name='accommodation'),
path('contact', views.Contact.as_view(), name='contact'),
path('rsvp', views.RSVPView.as_view(), name='rsvp'),
path('rsvp/<int:active_tab>/', views.RSVPView.as_view(), name='rsvp_tab_active'),
path('', views.HomeView.as_view(), name='home'),
]
<file_sep># Generated by Django 2.0.4 on 2018-05-16 19:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0003_auto_20180516_2059'),
]
operations = [
migrations.AlterField(
model_name='guest',
name='comments',
field=models.TextField(blank=True, max_length=200, verbose_name='Dodatkowy komentarz'),
),
migrations.AlterField(
model_name='guest',
name='gift',
field=models.CharField(blank=True, editable=False, max_length=50, verbose_name='Prezent'),
),
]
<file_sep># Generated by Django 2.0.4 on 2018-06-12 20:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0006_auto_20180612_2223'),
]
operations = [
migrations.AddField(
model_name='page',
name='order_no',
field=models.IntegerField(default=None, verbose_name='Nr porządkowy'),
preserve_default=False,
),
]
<file_sep># Generated by Django 2.0.4 on 2018-05-16 18:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='guest',
name='is_vegetarian',
field=models.BooleanField(default=False, help_text='Informacja ta pomoże nam przy wyborze menu', verbose_name='Preferuję dania wegetariańskie'),
),
migrations.AlterField(
model_name='guest',
name='wants_bus',
field=models.BooleanField(default=False, help_text='Zapewniamy dojazd spod kościoła na salę weselną zaraz po mszy\n i z powrotem do Poznania na koniec wesela (koło 4 w nocy).', verbose_name='Chcę jechać autobusem'),
),
]
<file_sep># Generated by Django 2.0.4 on 2018-05-16 18:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0002_auto_20180516_2059'),
]
operations = [
migrations.AlterField(
model_name='guest',
name='comments',
field=models.TextField(max_length=200, verbose_name='Dodatkowy komentarz'),
),
]
<file_sep>{% extends "base.html" %}
{% load custom_filters %}
{% load i18n %}
{% block content %}
<div class="container">
{% for message in messages %}
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endfor %}
{% for dict in formset.errors %}
{% for error in dict.values %}
{{ error }}
{% endfor %}
{% endfor %}
<ul class="nav nav-tabs" role="tablist">
{% for guest_form in formset %}
<li role="presentation" class="nav-item">
<a href="#tab-{{ guest_form.initial.id }}" data-toggle="tab" aria-controls="tab-{{ guest_form.initial.id }}"
role="tab" data-toggle="tab" class="nav-link"
onclick="$('#rsvp_form').attr('action', '{% url 'rsvp_tab_active' forloop.counter0 %}')">
{{ guest_form.instance }}
</a>
</li>
{% endfor %}
<li role="presentation" class="ml-auto nav-item" id="gifts-nav-tab">
<a href="#tab-gifts" data-toggle="tab" aria-controls="tab-gifts" role="tab"
data-toggle="tab" class="nav-link"
onclick="$('#rsvp_form').attr('action', '{% url 'rsvp_tab_active' formset|length %}')">
{% trans 'Wybór prezentów' %}
</a>
</li>
</ul>
<form id="rsvp_form" method="post" action="">
{% csrf_token %}
{{ formset.management_form }}
<div class="tab-content">
{% for guest_form in formset %}
<div class="tab-pane fade" id="tab-{{ guest_form.initial.id }}">
{{ guest_form.as_my_p }}
</div>
{% endfor %}
<div class="tab-pane fade" id="tab-gifts">
<p>{% blocktrans %}Poniżej zamieszczamy listę proponowanych prezentów. Jeśli macie inne pomysły albo nie ma już nic na liście, to nie krępujcie się sprawić nam coś innego.
Są tu także prezenty zarezerwowane już przez innych, co powinno zapobiec ich ewentualnemu zdublowaniu.
W sumie to nie musicie nam nic dawać. Największym prezentem dla nas jest Wasza obecność w tym wyjątkowym dla nas dniu :){% endblocktrans %}</p>
<h5>{% trans 'Lista proponowanych prezentów:' %}</h5>
{% for gift_id, gift_name in gift_form.gifts.field.choices %}
<label for="id-gift-{{ gift_id }}">
<input id="id-gift-{{ gift_id }}"
type="checkbox"
name="gifts"
value="{{ gift_id }}"
{% if gift_id in gift_form.gifts.field.initial %}
checked=""
{% endif %}
>
{{ gift_name }}
{% with gift_urls|get_item:gift_id as gift_url %}
{% if gift_url %}
<a href="{{ gift_url }}" target="_blank">(link)</a>
{% endif %}
{% endwith %}
{% if gift_id in gift_form.gifts.field.initial %}
{% trans '- zarezerwowane przez Ciebie' %}
{% endif %}
</label>
<br>
{% endfor %}
<br>
{% if gift_form.taken_gifts %}
<h5>{% trans 'Prezenty zarezerwowane przez innych:' %}</h5>
<ul style="padding-left: 30px">
{% for gift in gift_form.taken_gifts %}
<li>
{{ gift.name }}
{% with gift_urls|get_item:gift.id as gift_url %}
{% if gift_url %}
<a href="{{ gift_url }}" target="_blank">(link)</a>
{% endif %}
{% endwith %}
</li>
{% endfor %}
</ul>
{% endif %}
</div>
<button id="rsvp-button" class="btn btn-default btn-border" type="submit">{% trans 'Zapisz zmiany' %}</button>
</div>
</form>
</div>
{% endblock %}
{% block js %}
<script>
$("#menu-rsvp").addClass("active");
var activeTab = {{ active_tab }};
$(".nav-tabs .nav-item a").eq(activeTab).addClass("active");
$(".tab-content div").eq(activeTab).addClass("active");
$('.tab-pane').eq(activeTab).addClass('show active');
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
$(".alert").fadeTo(4000, 500).slideUp(500, function(){
$(".alert").slideUp(500);
});
</script>
{% endblock js %}
<file_sep>from django.contrib import admin
from .models import Guest, Gift
class GuestAdmin(admin.ModelAdmin):
list_display = ('__str__', 'attending', 'attending_afters', 'wants_bus', 'is_vegetarian', 'comments')
list_filter = ('attending', 'wants_bus', 'is_vegetarian', 'attending_afters', 'eligible_for_afters')
admin.site.register(Guest, GuestAdmin)
admin.site.register(Gift)
<file_sep># Generated by Django 2.1.3 on 2018-12-22 18:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wedding_guests', '0013_auto_20181222_1447'),
]
operations = [
migrations.RemoveField(
model_name='gift',
name='is_reserved',
),
]
<file_sep># Wedding website
This project was created to manage our wedding invitations. Guests could read more about the wedding, confirm their arrival and choose gifts.
### Installation
This projected is updated as it was used by us. It's not prepared for public use yet. Feel free to contact us if you want to use it and need some help.
|
8e332fe67b88ae19e053990cb7a962e98cd5d465
|
[
"Markdown",
"Python",
"HTML",
"INI"
] | 29 |
Python
|
pmiara/wedding
|
3c857886422ef295c47ff88f61d32a8d9f17c7f3
|
509b393fe8d9a6c5f41751cb963f0ff0d4b72baf
|
refs/heads/master
|
<file_sep>const Joi = require('joi');
const User = require('../models/User');
const bcrypt = require('bcrypt');
const validation = Joi.object({
password: Joi.string()
.pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')),
});
exports.me_get = async (req, res) => {
try {
const user = await User.findById({_id: req.user.userId}, {
_id: 1,
email: 1,
createdDate: 1,
});
res.status(200).json({user});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.me_delete = async (req, res) => {
try {
const {userRole} = req.user;
if (userRole !== 'SHIPPER') {
return res.status(400).json({
message: 'You dont have permission for operation',
});
}
await User.findByIdAndDelete({_id: req.user.userId}, (err) => {
if (err) {
return res.status(400).json({message: e.message});
}
});
res.status(200).json({message: 'Profile deleted successfully'});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.me_password = async (req, res) => {
try {
const {oldPassword, newPassword} = req.body;
await validation.validateAsync({password: newPassword});
const user = await User.findOne({
_id: req.user.userId,
});
const isMatch = await bcrypt
.compare(oldPassword, user.password);
if (!isMatch) {
return res.status(400).json({
message: 'Wrong oldPassword. Please try agein',
});
}
const hashedpassword = await bcrypt.hash(newPassword, 12);
await User.updateOne(user, {password: hashedpassword});
} catch (e) {
res.status(500).json({message: e.message});
}
};
<file_sep>const {Schema, model, Types} = require('mongoose');
const schema = new Schema({
assigned_truck: {
type: Types.ObjectId,
ref: 'Truck',
default: null,
},
email: {type: String, required: true, unique: true},
password: {type: String, required: true},
createdDate: {type: Date, default: Date.now},
role: {
type: String,
enum: ['DRIVER', 'SHIPPER'],
},
});
module.exports = model('User', schema);
<file_sep>const {Schema, model, Types} = require('mongoose');
const data = require('../data/data');
const schema = new Schema({
created_by: {
type: Types.ObjectId,
ref: 'User',
required: true,
},
assigned_to: {
type: Types.ObjectId,
ref: 'User',
default: null,
},
pickup_address: String,
delivery_address: String,
status: {
type: String,
enum: [...data.load.statuses],
required: true,
default: 'NEW',
},
state: {
type: String,
enum: [...data.load.states],
},
dimensions: {
length: Number,
width: Number,
height: Number,
},
payload: Number,
name: String,
created_date: {type: Date, default: Date.now},
logs: [{
message: String,
date: {
type: Date,
default: Date.now,
},
}],
});
module.exports = model('Load', schema);
<file_sep>const bcrypt = require('bcrypt');
const Joi = require('joi');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const config = require('config');
const generator = require('generate-password');
const schemaReg = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().pattern(/^[a-zA-Z0-9]{3,30}$/).required(),
role: Joi.string().required(),
});
const schemaLog = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().pattern(/^[a-zA-Z0-9]{3,30}$/).required(),
});
exports.auth_register_post = async (req, res) => {
try {
const {email, password, role} = req.body;
const value = schemaReg.validate({email, password, role});
if (value.error) {
return res.status(400).json({message: value.error.message});
}
const person = await User.findOne({email});
if (person) {
return res.status(400).json({
message: 'This user already exist',
});
}
const hashedpassword = await bcrypt.hash(password, 12);
const user = new User({
email, password: <PASSWORD>, role,
});
await user.save();
res.status(200).json({message: 'Success'});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.auth_login_post = async (req, res) => {
try {
const {email, password} = req.body;
const value = schemaLog.validate({email, password});
if (value.error) {
return res.status(400).json({message: value.error.message});
}
const user = await User.findOne({email});
if (!user) {
return res.status(400).json({message: 'User not found'});
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).json({
message: 'Wrong password. Please try agein',
});
}
const token = jwt.sign({
userId: user.id,
userRole: user.role,
},
config.get('jwtSecret'),
{
expiresIn: '1h',
},
);
res.status(200).json({message: 'Success', jwt_token: token});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.auth_forgotPassword_post = async (req, res) => {
try {
const {email} = req.body;
const user = await User.findOne({email});
if (!user) {
return res.status(400).json({message: 'User not found'});
}
const password = generator.generate({
length: 10,
numbers: true,
});
const hashedpassword = await bcrypt.hash(password, 12);
await User.updateOne(user, {password: <PASSWORD>});
console.log(password);
res.status(200).json({message: 'New password sent to your email address'});
} catch (e) {
res.status(500).json({message: e.message});
}
};
<file_sep>const fs = require('fs');
const path = require('path');
module.exports = (req, res, next) => {
const addZeroes = (time) => time < 10 ? '0' + time : time;
const time = new Date();
const hour = addZeroes(time.getHours());
const minutes = addZeroes(time.getMinutes());
const seconds = addZeroes(time.getSeconds());
const mainTime = `${hour}:${minutes}:${seconds}`;
const info = `${mainTime}, method: ${req.method}, url: ${req.url}`;
console.log(info);
fs.appendFile(path.join(__dirname, '..', 'log.log'), info + '\n', () => {});
next();
};
<file_sep>const {Schema, model, Types} = require('mongoose');
const data = require('../data/data');
const schema = new Schema({
created_by: {
type: Types.ObjectId,
ref: 'User',
required: true,
},
assigned_to: {
type: Types.ObjectId,
ref: 'User',
default: null,
},
status: {
type: String,
enum: [
data.truck.statuses.free,
data.truck.statuses.load,
],
default: 'IS',
},
type: {
type: String,
enum: [...data.truck.types],
required: true,
},
created_date: {type: Date, default: Date.now},
});
module.exports = model('Truck', schema);
<file_sep>const {Router} = require('express');
const router = Router();
const usersController = require('../controllers/usersController');
router.get('/me', usersController.me_get);
router.delete('/me', usersController.me_delete);
router.patch('/me/password', usersController.me_password);
module.exports = router;
<file_sep>const Load = require('../models/Load');
const User = require('../models/User');
const Truck = require('../models/Truck');
const data = require('../data/data');
const Joi = require('joi');
const loadValidate = Joi.object({
name: Joi.string().required(),
payload: Joi.number().required(),
pickup_address: Joi.string().required(),
delivery_address: Joi.string().required(),
dimensions: {
length: Joi.number().required(),
width: Joi.number().required(),
height: Joi.number().required(),
},
});
exports.loads_get = async (req, res) => {
try {
let loads;
const skip = req.query.offset ?? 0;
const limit = req.query.limit ?? 10;
const {userId, userRole} = req.user;
if (userRole == 'DRIVER') {
loads = await Load.find({
assigned_to: userId,
}).skip(skip).limit(limit);
}
if (userRole == 'SHIPPER') {
loads = await Load.find({
created_by: userId,
}).skip(skip).limit(limit);
}
if (!loads) {
return res.status(400).json({message: 'Loads not found'});
}
res.status(200).json({loads});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.loads_post = async (req, res) => {
try {
const {userId, userRole} = req.user;
if (userRole !== 'SHIPPER') {
return res.status(400).json({
message: 'You dont have permission for operation',
});
}
const value = loadValidate.validate({...req.body});
if (value.error) {
return res.status(400).json({message: value.error.message});
}
const {
name,
payload,
pickupAddress,
deliveryAddress,
dimensions,
} = req.body;
const load = new Load({
created_by: userId,
name,
payload,
pickup_address: pickupAddress,
delivery_address: deliveryAddress,
dimensions,
});
await load.save();
res.status(200).json({message: 'Load created successfully'});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.loads_active_get = async (req, res) => {
try {
const {userId, userRole} = req.user;
if (userRole !== 'DRIVER') {
return res.status(400).json({
message: 'You dont have permission for operation',
});
}
const load = await Load.findOne({
assigned_to: userId,
status: 'ASSIGNED',
}, {__v: 0, logs: {_id: 0}});
if (!load) {
return res.status(400).json({
message: 'You dont have active loads',
});
}
res.status(200).json({load});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.loads_active_state_patch = async (req, res) => {
try {
const states = data.load.states;
const {userId, userRole} = req.user;
if (userRole !== 'DRIVER') {
return res.status(400).json({
message: 'You dont have permission for operation',
});
}
const load = await Load.findOne({
assigned_to: userId, status: 'ASSIGNED',
});
if (!load) {
return res.status(400).json({
message: 'You dont have active loads',
});
}
const currentState = states.indexOf(load.state)+1;
if (currentState == states.length - 1) {
await load.updateOne({
state: states[currentState],
status: 'SHIPPED',
$push: {
logs: {
message:
`Load changed from ${load.state} to ${states[currentState]}`,
},
},
});
await Truck.findOneAndUpdate({assigned_to: load.assigned_to}, {
status: data.truck.statuses.free,
});
} else {
await load.updateOne({
state: states[currentState],
$push: {
logs: {
message:
`Load state changed from ${load.state} to ${states[currentState]}`,
},
},
});
}
res.status(200).json({
message:
`Load state changed to ${states[currentState]}`,
});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.loads_id_get = async (req, res) => {
try {
const {userId, userRole} = req.user;
if (userRole !== 'SHIPPER') {
return res.status(400).json({
message: 'You dont have permission for operation',
});
}
const load = await Load.find({
_id: req.params.loadId,
created_by: userId,
}, {__v: 0, logs: {_id: 0}});
if (!load) {
return res.status(400).json({message: 'Load not found'});
}
res.status(200).json({load});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.loads_id_put = async (req, res) => {
try {
const {userId, userRole} = req.user;
if (userRole !== 'SHIPPER') {
return res.status(400).json({
message: 'You dont have permission for operation',
});
}
const value = loadValidate.validate({...req.body});
if (value.error) {
return res.status(400).json({message: value.error.message});
}
const load = await Load.findOne({
_id: req.params.loadId,
status: 'NEW',
created_by: userId,
});
if (!load) {
return res.status(400).json({message: 'Load not found'});
}
await Load.updateOne(load, {...req.body});
res.status(200).json({
message: `Load details changed successfully`,
});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.loads_id_delete = async (req, res) => {
try {
const {userId, userRole} = req.user;
if (userRole !== 'SHIPPER') {
return res.status(400).json({
message: 'You dont have permission for operation',
});
}
const load = await Load.findOneAndDelete({
_id: req.params.loadId,
status: 'NEW',
created_by: userId,
});
if (!load) {
return res.status(400).json({message: 'Load not found'});
}
res.status(200).json({message: `Load deleted successfully`});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.loads_id_post = async (req, res) => {
try {
const {userRole} = req.user;
const loadId = req.params.loadId;
if (userRole !== 'SHIPPER') {
return res.status(400).json({
message: 'You dont have permission for operation',
});
}
const load = await Load.findByIdAndUpdate({
_id: loadId,
}, {status: 'POSTED'});
if (!load) {
return res.status(400).json({
message: 'Load not found',
});
}
const {
length: loadLen,
width: loadWdt,
height: loadHgt,
} = load.dimensions;
const loadPld = load.payload;
const neededCars = data.truck.dims.filter( (el) => {
return el.length >= +loadLen &&
el.width >= +loadWdt &&
el.height >= +loadHgt &&
el.weight >= +loadPld;
},
).map( (truck) => truck.name);
let foundedDriver;
await User.find({role: 'DRIVER'})
.populate('assigned_truck')
.then( (driver) => {
foundedDriver = driver.find( (dr) => {
return dr.assigned_truck.status == 'IS' ?
neededCars.includes(dr.assigned_truck.type) :
false;
});
});
let message;
if (!!foundedDriver) {
await foundedDriver.assigned_truck.updateOne({
status: 'OL',
});
await load.updateOne({
state: 'En route to Pick Up',
status: 'ASSIGNED',
assigned_to: foundedDriver._id,
$push: {
logs: {
message:
`For ${load._id} fouded driver ${foundedDriver._id}
* status changed to 'ASSIGNED'`,
},
}});
message = 'Load posted successfully';
} else {
await load.updateOne({
status: 'NEW',
$push: {
logs: {
message: `Driver not found *** status changed to 'NEW'`,
},
}});
message = 'Driver not found';
}
res.status(200).json({
message,
driver_found: !!foundedDriver,
});
} catch (e) {
res.status(500).json({message: e.message});
}
};
exports.loads_id_info_get = async (req, res) => {
try {
const {userRole} = req.user;
if (userRole !== 'SHIPPER') {
return res.status(400).json({
message: 'You dont have permission for operation',
});
}
const load = await Load.findById({_id: req.params.loadId}, {__v: 0});
if (!load) {
return res.status(400).json({message: 'Load not found'});
}
await User.findOne({_id: load.assigned_to})
.populate('assigned_truck')
.then( (driver) => {
return res.status(200).json({load, truck: driver.assigned_truck});
});
return res.status(200).json({load});
} catch (e) {
res.status(500).json({message: e.message});
}
};
<file_sep>module.exports = {
truck: {
statuses: {
free: 'IS',
load: 'OL',
},
types: ['SPRINTER', 'SMALL STRAIGHT', 'LARGE STRAIGHT'],
dims: [
{
name: 'SPRINTER',
weight: 1700,
length: 300,
width: 250,
height: 170,
},
{
name: 'SMALL STRAIGHT',
weight: 2500,
length: 500,
width: 250,
height: 170,
},
{
name: 'LARGE STRAIGHT',
weight: 4000,
length: 700,
width: 350,
height: 200,
},
],
},
load: {
statuses: ['NEW', 'POSTED', 'ASSIGNED', 'SHIPPED'],
states: [
'En route to Pick Up',
'Arrived to Pick Up',
'En route to delivery',
'Arrived to delivery',
],
},
};
|
3642c67976783d226a3b2c1064761f5e76672ed2
|
[
"JavaScript"
] | 9 |
JavaScript
|
OlegKavun/truck_uber
|
c7c70d53fd16f47cc2327b95b1c097821b754e4d
|
88761185af83321a60e51e3652d6696e96aff014
|
refs/heads/master
|
<file_sep>package uib.programacion2.arrays.ordenacion;
import java.io.IOException;
import java.util.Arrays;
/**
* Created by Tony on 26/4/17.
*/
public class Shell {
public static void main(String[] args) throws IOException {
int[] lista = {23, 234, 54, 434, 213, 54, 76, 23, 21, 13, 9, 2, 6, 3, 1};
System.out.println("Inicio");
System.out.println(Arrays.toString(lista));
System.out.println();
ordenar(lista);
}
//Falta bool para saber si ya esta ordenado
private static void ordenar(int[] lista) {
for (int i = 0; i < lista.length - 1; i++) {
for (int j = 1; j < lista.length - i; j++) {
int antes = 0;
int aux = 0;
if (lista[j] < lista[j - 1]) {
aux = lista[j - 1];
lista[j - 1] = lista[j];
lista[j] = aux;
}
System.out.println("J " + j + "\t-\t" + Arrays.toString(lista));
}
System.out.println("\nI " + i + " - " + Arrays.toString(lista) + "\n");
}
}
}
<file_sep>package uib.programacion2.ficheros.aleatorio.producto;
public class Main {
public static void main(String[] argumentos) {
String nombre = "productos.dat";
boolean fin = false;
while (!fin) {
borrarPantalla();
System.out.println();
System.out.println("===== MENU =====");
System.out.println("----------------------------------------------");
System.out.println("1 - Escritura de Articulo");
System.out.println("2 - Lectura de Articulo");
System.out.println("3 - Modificación de Articulo");
System.out.println("4 - Listado de Productos");
System.out.println("----------------------------------------------");
System.out.println("q - Salir");
System.out.println();
System.out.print("Introduzca la acción que desea ejecutar: ");
char opcion = LT.llegirCaracter();
switch (opcion) {
case '1':
alta(nombre);
break;
case '2':
lectura(nombre);
break;
case '3':
modificacion(nombre);
break;
case '4':
listado(nombre);
break;
default:
fin = true;
}
}
}
private static void borrarPantalla() {
for (int i = 0; i < 50; i++) {
System.out.println();
}
}
private static void alta(String nombre) {
boolean terminar = false;
Producto producto = new Producto();
ProductoInOut ficheroOut = new ProductoInOut(nombre);
while (!terminar) {
System.out.println("[ Alta de Articulo ] ");
producto.lectura();
ficheroOut.escrituraAdd(producto);
borrarPantalla();
System.out.print("¿Dar de alta otro Articulo? (s/n): ");
String res = LT.llegirLinia();
if (res.length() == 0 || res.charAt(0) != 's')
terminar = true;
}
ficheroOut.cierre();
}
public static void lectura(String nombre) {
boolean terminar = false;
ProductoInOut ficheroIn = new ProductoInOut(nombre);
int numProducto;
Producto producto;
while (!terminar) {
borrarPantalla();
System.out.println("[ Lectura de Articulo ] ");
System.out.print("Introduzca el Articulo que desea leer: ");
numProducto = LT.llegirSencer();
producto = ficheroIn.lectura(numProducto);
if (!producto.productoVacio()) {
System.out.println("Articulo " + numProducto + ": " + producto.toString());
}
System.out.print("¿Leer otro Articulo? (s/n): ");
String res = LT.llegirLinia();
if (res.length() == 0 || res.charAt(0) != 's')
terminar = true;
}
ficheroIn.cierre();
}
private static void modificacion(String nombre) {
boolean terminar = false;
ProductoInOut ficheroIn = new ProductoInOut(nombre);
int numProducto;
while (!terminar) {
borrarPantalla();
System.out.println("[ Modificación de Articulo ] \n");
System.out.print("Introduce el Articulo que desea modificar: ");
numProducto = LT.llegirSencer();
Producto producto = ficheroIn.lectura(numProducto);
if (!producto.productoVacio()) {
System.out.println("Articulo :" + numProducto + ":");
System.out.println(producto.toString());
System.out.println();
System.out.print("¿Modificar código de Articulo? (NO -> ENTER): ");
Integer nuevoCodigo = LT.llegirSencer();
if (nuevoCodigo != null)
producto.setCodigo(nuevoCodigo);
System.out.print("¿Modificar nombre de Articulo? (NO -> ENTER): ");
String nuevoNombre = LT.llegirLinia();
if (nuevoNombre != null && nuevoNombre.length() > 0)
producto.setNombre(nuevoNombre);
System.out.print("¿Modificar NIF de Articulo? (NO -> ENTER): ");
String nuevoNif = LT.llegirLinia();
if (nuevoNombre != null && nuevoNombre.length() > 0)
producto.setNif(nuevoNif);
System.out.print("¿Modificar dirección de Articulo? (NO -> ENTER): ");
String nuevaDireccion = LT.llegirLinia();
if (nuevoNombre != null && nuevoNombre.length() > 0)
producto.setDireccion(nuevaDireccion);
System.out.print("¿Modificar teléfono de Articulo? (NO -> ENTER): ");
Integer nuevoTelefono = LT.llegirSencer();
if (nuevoTelefono != null)
producto.setTelefono(nuevoTelefono);
ficheroIn.escritura(numProducto, producto);
}
System.out.print("¿Desea modificar otro Articulo? (s/n): ");
String res = LT.llegirLinia();
if (res.length() == 0 || res.charAt(0) != 's')
terminar = true;
}
ficheroIn.cierre();
}
private static void listado(String nombre) {
borrarPantalla();
System.out.println("[ Listando Productos ] \n");
ProductoInOut ficheroIn = new ProductoInOut(nombre);
Producto producto = ficheroIn.lectura();
while (!producto.productoVacio()) {
System.out.println(producto.toString());
producto = ficheroIn.lectura();
}
System.out.println();
ficheroIn.cierre();
System.out.print("<< VOLVER MENU PULSAR ENTER >> ");
LT.llegirCaracter();
}
}
<file_sep>/*
EXEPCIÓN NO PREDEFINIDA
*/
package uib.programacion2.ficheros.aleatorio.producto;
public class ProductoInexistente extends Exception {
public ProductoInexistente(String mensaje) {
super(mensaje);
}
}
<file_sep>package uib.programacion2.graficos.puzzle_viejo;
import javax.swing.*;
import java.awt.*;
/**
* Created by Tony on 12/4/17.
*/
public class Dibujar extends JComponent {
private Casilla[][] casillas;
private int dim_total;
private int dim_casilla;
public Dibujar(Casilla[][] casillas, int dim_total, int dim_casilla) {
this.casillas = casillas;
this.dim_total = dim_total;
this.dim_casilla = dim_casilla;
}
@Override
public void paint(Graphics g) {
g.setColor(Color.WHITE);
for (int fila = 0; fila < casillas.length; fila++) {
for (int columna = 0; columna < casillas[fila].length; columna++) {
int coordX = (columna * dim_casilla);
int coordY = (fila * dim_casilla);
if (casillas[fila][columna].getBlanca())
g.fillRect(coordX, coordY, (coordX + dim_casilla), (coordY + dim_casilla));
else
g.drawImage(casillas[fila][columna].getImagen(), coordX, coordY, dim_casilla, dim_casilla, null);
}
}
g.setColor(Color.BLACK);
//Dibujar cuadrícula
int y = 0;
for (int i = 1; i <= dim_total + 1; i++) {
int x = 0;
for (int j = 1; j <= dim_total + 1; j++) {
g.drawLine(x, y, x, dim_total);
g.drawLine(x, y, dim_total, y);
x += dim_casilla;
}
y += dim_casilla;
}
}
}<file_sep>package uib.programacion2.graficos.graphics2d;
/**
* Created by Tony on 10/5/17.
*
* Array de Rectangulos de tamaño aleatorio, y aplicarle un algoritmo de ordenación en función de su area
*
* Después de ordenadorlos, hacer UI que al hacer click cambie el rectangulo que se visualiza
*
*/
public class Main {
}
<file_sep>package uib.programacion2.arrays.ordenacion;
import java.io.IOException;
import java.util.Arrays;
/**
* Created by Tony on 26/4/17.
*/
public class Seleccion {
public static void main(String[] args) throws IOException {
int[] lista = {23, 234, 54, 434, 213, 59, 76, 25, 21, 13, 9, 2, 6, 3, 1};
System.out.println("Inicio");
System.out.println(Arrays.toString(lista));
System.out.println();
ordenar(lista);
}
private static void ordenar(int[] lista) {
for (int i = 0; i < lista.length; i++) {
int aux = 0;
int menor = i;
for (int j = i; j < lista.length; j++) {
if (lista[j] < lista[menor])
menor = j;
}
aux = lista[menor];
lista[menor] = lista[i];
lista[i] = aux;
System.out.println(Arrays.toString(lista));
}
}
}
<file_sep>package uib.programacion2.ficheros.aleatorio.articulo;
import java.io.IOException;
import java.io.RandomAccessFile;
public class ArticuloInOut {
private RandomAccessFile objetoInOut = null;
public ArticuloInOut(String nombre) {
try {
objetoInOut = new RandomAccessFile(nombre, "rw");
} catch (IOException e) {
e.printStackTrace();
}
}
public Articulo lectura() {
Articulo articulo = new Articulo();
try {
if (objetoInOut.getFilePointer() < objetoInOut.length()) {
try {
leerProducto(articulo);
return articulo;
} catch (IOException error) {
}
return articulo;
} else {
return articulo;
}
} catch (IOException error) {
}
return articulo;
}
public Articulo lectura(int numProducto) {
Articulo articulo = new Articulo();
try {
if ((objetoInOut.length()) > ((long) (numProducto - 1) * Articulo.DIM_ARTICULO)) {
try {
objetoInOut.seek((long) (numProducto - 1) * Articulo.DIM_ARTICULO);
leerProducto(articulo);
return articulo;
} catch (IOException error) {
}
} else {
throw new ArticuloInexistente("Articulo INEXISTENTE");
}
} catch (IOException error) {
} catch (ArticuloInexistente error) {
System.err.println("ATENCIÓN: " + error.getMessage());
}
return articulo;
}
public void escritura(int numProducto, Articulo articulo) {
try {
if ((objetoInOut.length()) > ((long) (numProducto - 1) * Articulo.DIM_ARTICULO)) {
try {
objetoInOut.seek((long) (numProducto - 1) * Articulo.DIM_ARTICULO);
escribirProducto(articulo);
} catch (IOException error) {
}
} else {
throw new ArticuloInexistente("Articulo INEXISTENTE");
}
} catch (IOException error) {
} catch (ArticuloInexistente error) {
System.err.println("ATENCIÓN: " + error.getMessage());
}
}
public void escrituraAdd(Articulo articulo) {
try {
objetoInOut.seek(objetoInOut.length());
escribirProducto(articulo);
} catch (IOException error) {
}
}
private void escribirProducto(Articulo articulo) throws IOException {
objetoInOut.writeInt(articulo.getCodigo());
objetoInOut.writeChars(articulo.getDescripcion());
objetoInOut.writeChars(articulo.getProveedor());
objetoInOut.writeInt(articulo.getExistencias());
}
private void leerProducto(Articulo articulo) throws IOException {
//Leer int de Código
articulo.setCodigo(objetoInOut.readInt());
String descripcion = "";
for (int i = 0; i < Articulo.DIM_DESC / 2; i++)
descripcion += objetoInOut.readChar();
articulo.setDescripcion(descripcion);
String proveedor = "";
for (int i = 0; i < Articulo.DIM_PROV / 2; i++)
proveedor += objetoInOut.readChar();
articulo.setProveedor(proveedor);
//Leer int de existencias
articulo.setExistencias(objetoInOut.readInt());
}
public void cierre() {
if (objetoInOut != null) {
try {
objetoInOut.close();
} catch (IOException error) {
}
}
}
}
<file_sep>package uib.programacion2.ficheros.practica;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
* Created by Tony on 5/4/17.
*/
public class JugadorInOut {
private static final int CHARS_NICK = 40;
static final int DIM_NICK = Character.SIZE / Byte.SIZE * CHARS_NICK; // 40 chars
static final int DIM_PUNTUACION = Integer.SIZE / Byte.SIZE; // int
static final int DIM_EQUIPO = Integer.SIZE / Byte.SIZE; // int
static final int DIM_JUGADA = Integer.SIZE / Byte.SIZE; // int
static final int DIM_JUGADOR = DIM_PUNTUACION + DIM_NICK + DIM_EQUIPO + DIM_JUGADA;
private RandomAccessFile objetoInOut = null;
private int numeroJugadores;
public JugadorInOut(String nombre) {
try {
objetoInOut = new RandomAccessFile(nombre, "rw");
numeroJugadores = (int) objetoInOut.length() / DIM_JUGADOR;
} catch (IOException e) {
System.err.println("Error al abrir el fichero de Jugadores por equipos:");
e.printStackTrace();
}
}
private void reiniciarPuntero() {
try {
objetoInOut.seek(0);
} catch (IOException e) {
System.err.println("Error al iniciar el puntero del fichero de Jugadores por equipos:");
e.printStackTrace();
}
}
public Jugador[] leerJugadores() {
reiniciarPuntero();
Jugador[] jugadores = new Jugador[numeroJugadores];
try {
for (int i = 0; i < numeroJugadores; ++i)
jugadores[i] = leerJugador();
return jugadores;
} catch (IOException e) {
System.err.println("Error al leer Jugadores por equipos:");
e.printStackTrace();
}
return jugadores;
}
public void escrituraAdd(Jugador jugador) {
try {
objetoInOut.seek(objetoInOut.length());
escribirJugador(jugador);
} catch (IOException e) {
System.err.println("Error al escribir Jugador en el fichero de Jugadores por equipos:");
e.printStackTrace();
}
}
private void escribirJugador(Jugador jugador) throws IOException {
String nick = jugador.getNick();
if (nick.length() > CHARS_NICK)
nick = nick.substring(0, CHARS_NICK);
//Escribir los caracteres del Nick
for (int i = 0; i < nick.length(); i++)
objetoInOut.writeChar(nick.charAt(i));
//Rellenar con espacios hasta ocupar la dimensión del Nick
for (int i = nick.length(); i < CHARS_NICK; i++)
objetoInOut.writeChar(' ');
//Escribir el int de la puntuación
objetoInOut.writeInt(jugador.getPuntuacion());
//Guardar el Equipo del Jugador como un int que servirá para identificar el Equipo
int idEquipo = 0;
Equipo equipo = jugador.getEquipo();
switch (equipo) {
case ATACANTE:
idEquipo = 1;
break;
case DEFENSOR:
idEquipo = 2;
break;
}
objetoInOut.writeInt(idEquipo);
//Guardar la Jugada del Jugador como un int que servirá para identificar la Jugada
int idJugada = 0;
Jugada jugada = jugador.getJugada();
switch (jugada) {
case NINGUNA:
idJugada = 1;
break;
case DEFENSA:
idJugada = 2;
break;
case CAPTURA:
idJugada = 3;
break;
case ASESINO:
idJugada = 4;
break;
case MEDICO:
idJugada = 5;
break;
}
objetoInOut.writeInt(idJugada);
}
private Jugador leerJugador() throws IOException {
Jugador jugador = new Jugador();
String nick = "";
for (int i = 0; i < DIM_NICK / 2; i++)
nick += objetoInOut.readChar();
jugador.setNick(nick.trim());
//Leer int de Puntuación
jugador.setPuntuacion(objetoInOut.readInt());
//Leer int de Equipo
int idEquipo = objetoInOut.readInt();
Equipo equipo = null;
switch (idEquipo) {
case 1:
equipo = Equipo.ATACANTE;
break;
case 2:
equipo = Equipo.DEFENSOR;
break;
}
jugador.setEquipo(equipo);
//Leer int de Jugada
int idJugada = objetoInOut.readInt();
Jugada jugada = null;
switch (idJugada) {
case 1:
jugada = Jugada.NINGUNA;
break;
case 2:
jugada = Jugada.DEFENSA;
break;
case 3:
jugada = Jugada.CAPTURA;
break;
case 4:
jugada = Jugada.ASESINO;
break;
case 5:
jugada = Jugada.MEDICO;
break;
}
//Leer int de Jugada
jugador.setJugada(jugada);
return jugador;
}
public void cierre() {
if (objetoInOut != null) {
try {
objetoInOut.close();
} catch (IOException e) {
System.err.println("Error al cerrar el fichero de Jugadores por equipos:");
e.printStackTrace();
}
}
}
}
<file_sep>package uib.programacion2.ficheros.practica;
import java.io.*;
/**
* Created by Tony on 5/4/17.
*
* Practica 1
*
*/
public class Main {
public static void main(String[] argumentos) {
String ficheroJugadores = "jugadores.dat";
boolean fin = false;
while (!fin) {
System.out.println();
System.out.println("===== MENU =====");
System.out.println("----------------------------------------------");
System.out.println("1 - Insertar Jugadores");
System.out.println("2 - Ver Jugadores");
System.out.println("3 - Crear y mostrar fichero de Equipos");
System.out.println("4 - Crear y mostrar fichero de Jugadas destacadas");
System.out.println("----------------------------------------------");
System.out.println("q - Salir");
System.out.println();
System.out.print("Introduzca la acción que desea ejecutar: ");
char opcion = LT.llegirCaracter();
switch (opcion) {
case '1':
insertar(ficheroJugadores);
break;
case '2':
lectura(ficheroJugadores);
break;
case '3':
separarEquipos(ficheroJugadores);
break;
case '4':
jugadasDestacadas();
break;
default:
fin = true;
}
}
}
private static void borrarPantalla() {
for (int i = 0; i < 50; i++) {
System.out.println();
}
}
private static void insertar(String ficheroJugadores) {
try {
System.out.println("[ Inserción de Jugadores ] ");
System.out.println("\n¿Cuantos jugadores quieres insertar?");
int num_jugadores = LT.llegirSencer();
FileOutputStream fos = new FileOutputStream(ficheroJugadores);
ObjectOutputStream oos = new ObjectOutputStream(fos);
System.out.println("\nInserta los datos de los " + num_jugadores + " con las puntuaciones de mayor a menor.");
for (int i = 1; i <= num_jugadores; i++) {
System.out.println();
System.out.println("Nick del jugador " + i + ":");
String nick = LT.llegirLinia();
System.out.println("Puntuacion del jugador " + i + ":");
int puntuacion = LT.llegirSencer();
System.out.println("Equipo del jugador " + i);
System.out.println("\tATACANTE (1)");
System.out.println("\tDEFENSOR (2)");
int seleccionEquipo = LT.llegirSencer();
System.out.println("Jugada destacada del jugador " + i);
System.out.println("\tNINGUNA (1)");
System.out.println("\tDEFENSA (2)");
System.out.println("\tCAPTURA (3)");
System.out.println("\tASESINO (4)");
System.out.println("\tMEDICO (5)");
int seleccionJugada = LT.llegirSencer();
Equipo equipo;
switch (seleccionEquipo) {
case 1:
equipo = Equipo.ATACANTE;
break;
case 2:
default:
equipo = Equipo.DEFENSOR;
break;
}
Jugada jugada;
switch (seleccionJugada) {
case 2:
jugada = Jugada.DEFENSA;
break;
case 3:
jugada = Jugada.CAPTURA;
break;
case 4:
jugada = Jugada.ASESINO;
break;
case 5:
jugada = Jugada.MEDICO;
break;
case 1:
default:
jugada = Jugada.NINGUNA;
break;
}
Jugador jugador = new Jugador(nick, puntuacion, equipo, jugada);
oos.writeObject(jugador);
System.out.println("\nJugador " + i + " insertado correctamente\n\n");
}
oos.writeObject(Jugador.CENTINELA);
oos.close();
} catch (Exception e) {
System.err.println("Error al insertar Jugadores:");
e.printStackTrace();
}
}
public static void lectura(String ficheroJugadores) {
System.out.println("[ Lectura de Jugadores ]");
System.out.println();
System.out.println(" Contenido del fichero de Jugadores:\n");
try {
FileInputStream fis = new FileInputStream(ficheroJugadores);
ObjectInputStream ois = new ObjectInputStream(fis);
Jugador jugador = (Jugador) ois.readObject();
int numJugador = 1;
while (!jugador.esCentinela()) {
System.out.println(numJugador + " - " + jugador.toString());
jugador = (Jugador) ois.readObject();
numJugador++;
}
ois.close();
} catch (Exception e) {
System.err.println("Error al leer fichero de Jugadores:");
e.fillInStackTrace();
}
}
public static void separarEquipos(String ficheroJugadores) {
System.out.println("[ Separar Jugadores por Equipo ]");
System.out.println();
eliminarFicherosEquipos();
JugadorInOut jugadoresDefensaInOut = new JugadorInOut("defensores.dat");
JugadorInOut jugadoresAtaqueInOut = new JugadorInOut("atacantes.dat");
try {
FileInputStream fis = new FileInputStream(ficheroJugadores);
ObjectInputStream ois = new ObjectInputStream(fis);
Jugador jugador = (Jugador) ois.readObject();
while (!jugador.esCentinela()) {
switch (jugador.getEquipo()) {
case DEFENSOR:
jugadoresDefensaInOut.escrituraAdd(jugador);
break;
case ATACANTE:
jugadoresAtaqueInOut.escrituraAdd(jugador);
break;
}
jugador = (Jugador) ois.readObject();
}
ois.close();
} catch (Exception e) {
System.err.println("Error al leer fichero de Jugadores:");
e.printStackTrace();
}
//Cerrar los ficheros para guardar los cambios
jugadoresDefensaInOut.cierre();
jugadoresAtaqueInOut.cierre();
//Abrir los ficheros para leer los datos guardados
jugadoresDefensaInOut = new JugadorInOut("defensores.dat");
jugadoresAtaqueInOut = new JugadorInOut("atacantes.dat");
System.out.println("Jugadores del equipo DEFENSA:\n");
for (Jugador defensa : jugadoresDefensaInOut.leerJugadores())
System.out.println(defensa.toString());
System.out.println("\nJugadores del equipo ATAQUE:\n");
for (Jugador atacante : jugadoresAtaqueInOut.leerJugadores())
System.out.println(atacante.toString());
//Cerrar ficheros
jugadoresDefensaInOut.cierre();
jugadoresAtaqueInOut.cierre();
}
public static void jugadasDestacadas() {
if (!new File("defensores.dat").exists() || !new File("defensores.dat").exists()) {
System.err.println("Aún no se han creado los ficheros de Jugadores por equipos");
return;
}
System.out.println("[ Jugadores con Jugadas destacadas ]");
System.out.println();
//Abrir archivo TXT donde se guardarán los datos
JugadorTextOut ficheroTextoOut = new JugadorTextOut("destacadas.txt");
//Abrir fichero aleatorio del equipo Defensa
JugadorInOut jugadoresDefensaInOut = new JugadorInOut("defensores.dat");
System.out.println("Guardando jugadas destacadas del equipo DEFENSA..");
//Escribir cabecera
ficheroTextoOut.escribir("Jugadas destacadas del equipo DEFENSA:");
ficheroTextoOut.escribir("");
System.out.println("\nJugadas destacadas del equipo DEFENSA:\n");
for (Jugador defensa : jugadoresDefensaInOut.leerJugadores())
if (defensa.getJugada() != Jugada.NINGUNA) {
System.out.println(defensa.toString());
ficheroTextoOut.escribir(defensa.toString());
}
jugadoresDefensaInOut.cierre();
JugadorInOut jugadoresAtaqueInOut = new JugadorInOut("atacantes.dat");
System.out.println("Guardando jugadas destacadas del equipo ATAQUE..");
//Escribir cabecera
ficheroTextoOut.escribir("");
ficheroTextoOut.escribir("Jugadas destacadas del equipo ATAQUE:");
ficheroTextoOut.escribir("");
System.out.println("\nJugadas destacadas del equipo DEFENSA:\n");
for (Jugador atacante : jugadoresAtaqueInOut.leerJugadores())
if (atacante.getJugada() != Jugada.NINGUNA) {
System.out.println(atacante.toString());
ficheroTextoOut.escribir(atacante.toString());
}
jugadoresAtaqueInOut.cierre();
//Cerrar fichero TXT
ficheroTextoOut.cierre();
System.out.println("\nLas jugadas destacadas han sido guardadas en el fichero jugadas.txt satisfactoriamente!");
}
/**
* Elimina los ficheros de atacantes y defensores generados anteriormente
*/
private static void eliminarFicherosEquipos() {
File ficheroDefensores = new File("defensores.dat");
File ficheroAtacantes = new File("atacantes.dat");
if (ficheroDefensores.exists())
ficheroDefensores.delete();
if (ficheroAtacantes.exists())
ficheroAtacantes.delete();
}
}
<file_sep>package uib.programacion2.ficheros.aleatorio.articulo;
public class Main {
public static void main(String[] argumentos) {
String nombre = "articulos.dat";
boolean fin = false;
while (!fin) {
borrarPantalla();
System.out.println();
System.out.println("===== MENU =====");
System.out.println("----------------------------------------------");
System.out.println("1 - Generar 10 ficheros de Movimientos");
System.out.println("1 - Fusionar ficheros de Movimientos");
System.out.println("3 - Actualizar fichero de Articulo");
System.out.println("4 - Listar Articulos con bajas existencias");
System.out.println("5 - Listar todos los Articulos");
System.out.println("----------------------------------------------");
System.out.println("q - Salir");
System.out.println();
System.out.print("Introduzca la acción que desea ejecutar: ");
char opcion = LT.llegirCaracter();
switch (opcion) {
case '1':
alta(nombre);
break;
case '2':
lectura(nombre);
break;
case '3':
modificacion(nombre);
break;
case '4':
listado(nombre);
break;
default:
fin = true;
}
}
}
private static void borrarPantalla() {
for (int i = 0; i < 50; i++) {
System.out.println();
}
}
private static void alta(String nombre) {
boolean terminar = false;
Articulo articulo = new Articulo();
ArticuloInOut ficheroOut = new ArticuloInOut(nombre);
while (!terminar) {
System.out.println("[ Alta de Articulo ] ");
articulo.lectura();
ficheroOut.escrituraAdd(articulo);
borrarPantalla();
System.out.print("¿Dar de alta otro Articulo? (s/n): ");
String res = LT.llegirLinia();
if (res.length() == 0 || res.charAt(0) != 's')
terminar = true;
}
ficheroOut.cierre();
}
public static void lectura(String nombre) {
boolean terminar = false;
ArticuloInOut ficheroIn = new ArticuloInOut(nombre);
int numArticulo;
Articulo articulo;
while (!terminar) {
borrarPantalla();
System.out.println("[ Lectura de Articulo ] ");
System.out.print("Introduzca el Articulo que desea leer: ");
numArticulo = LT.llegirSencer();
articulo = ficheroIn.lectura(numArticulo);
if (!articulo.articuloVacio()) {
System.out.println("Articulo " + numArticulo + ": " + articulo.toString());
}
System.out.print("¿Leer otro Articulo? (s/n): ");
String res = LT.llegirLinia();
if (res.length() == 0 || res.charAt(0) != 's')
terminar = true;
}
ficheroIn.cierre();
}
private static void modificacion(String nombre) {
boolean terminar = false;
ArticuloInOut ficheroIn = new ArticuloInOut(nombre);
int numArticulo;
while (!terminar) {
borrarPantalla();
System.out.println("[ Modificación de Articulo ] \n");
System.out.print("Introduce el Articulo que desea modificar: ");
numArticulo = LT.llegirSencer();
Articulo articulo = ficheroIn.lectura(numArticulo);
if (!articulo.articuloVacio()) {
System.out.println("Articulo :" + numArticulo + ":");
System.out.println(articulo.toString());
System.out.println();
System.out.print("¿Modificar código de Articulo? (NO -> ENTER): ");
Integer nuevoCodigo = LT.llegirSencer();
if (nuevoCodigo != null)
articulo.setCodigo(nuevoCodigo);
System.out.print("¿Modificar descripcion de Articulo? (NO -> ENTER): ");
String nuevaDesc = LT.llegirLinia();
if (nuevaDesc != null && nuevaDesc.length() > 0)
articulo.setDescripcion(nuevaDesc);
System.out.print("¿Modificar proveedor de Articulo? (NO -> ENTER): ");
String nuevoProv = LT.llegirLinia();
if (nuevaDesc != null && nuevaDesc.length() > 0)
articulo.setProveedor(nuevoProv);
System.out.print("¿Modificar existencias de Articulo? (NO -> ENTER): ");
Integer nuevasExist = LT.llegirSencer();
if (nuevasExist != null)
articulo.setExistencias(nuevasExist);
ficheroIn.escritura(numArticulo, articulo);
}
System.out.print("¿Desea modificar otro Articulo? (s/n): ");
String res = LT.llegirLinia();
if (res.length() == 0 || res.charAt(0) != 's')
terminar = true;
}
ficheroIn.cierre();
}
private static void listado(String nombre) {
borrarPantalla();
System.out.println("[ Listando Articulos ] \n");
ArticuloInOut ficheroIn = new ArticuloInOut(nombre);
Articulo articulo = ficheroIn.lectura();
while (!articulo.articuloVacio()) {
System.out.println(articulo.toString());
articulo = ficheroIn.lectura();
}
System.out.println();
ficheroIn.cierre();
System.out.print("<< VOLVER MENU PULSAR ENTER >> ");
LT.llegirCaracter();
}
}
|
4569052a0f32f699194c252ddd7e0bce8cedd2fe
|
[
"Java"
] | 10 |
Java
|
antoni-alvarez/UIB-Programacion2
|
a6dfc387c5b26d5c4313022dfd9ef5412ebabead
|
40f48294f4cef378c5716031cdb7552532dbdb28
|
refs/heads/master
|
<repo_name>danimoussalli/Clase01-JS<file_sep>/clase01-ejercicio3.js
// Pedir un texto mediante prompt, luego otro, concatenarlos y mostrarlo en un alert
var texto1 = prompt('Ingresa un texto');
var texto2 = prompt('Ingresa otro texto');
alert(texto1 + ' ' + texto2);
<file_sep>/clase01-ejercicio1.js
/*Pedir nombre mediante prompt y mostrarlo en consola junto con
algún texto de saludo. Ej: Hola Juan!*/
var nombre = prompt('¿Como te llamas?');
console.log('Hola' + ' ' + nombre);
|
66a33e710c2e4af3bf31195829ef3b8546fbac64
|
[
"JavaScript"
] | 2 |
JavaScript
|
danimoussalli/Clase01-JS
|
fa7db695b60fe80b1e467d90b58da03878d4fb5b
|
b5bfbc6863a7a0c5961938739f9b78a3c886e309
|
refs/heads/master
|
<repo_name>vicziani/jtechlog-falling-gems<file_sep>/README.md
Falling Gems játék
==================
A Falling Gems egy egyszerű ügyességi és logikai játék.
Mavennel buildelhető, a letöltést követően az `mvn package` paranccsal
buildelhető, az elkészült jar állomány `java -jar jtechlog-falling-gems-1.0.0.jar`
paranccsal futtatható.
A játék 2000-ben készült, így olyan objektumorientált programozási paradigmáknak
híján van, mint a high cohesion vagy low coupling.
Felhasznált technológiák: Java SE, AWT
viczian.istvan a gmail-en<file_sep>/src/main/java/fallinggems/FallingGemsPanel.java
package fallinggems;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JPanel;
public class FallingGemsPanel extends JPanel implements MouseListener {
private static final int WIDTH = 600;
private static final int HEIGHT = 200;
// Offscreen kép
private Image imageBuffer;
// Annak grafikus buffere
private Graphics graphicsBuffer;
// Háttérkép
private Image hatter;
// Vesztettél kép
private Image vesztettkep;
// Kövek
private Image[] kokepek = new Image[7];
// Tábla
int[][] tabla = new int[9][9];
// Véletlenszám generátor
private Random generator = new Random();
// Pontszám
int pont;
// Kivalásztott-e már egy követ?
boolean valasztott = false;
// A kiválasztott kő indexe
private int xindex, yindex;
// Tábla helyzete a 0,0-hoz képest
private int xoffset = 10;
private int yoffset = 10;
// Vesztett-e
private boolean vesztett = false;
// Mutatja, hogy éppen megy az egyik kő
boolean menes = false;
// Hibakeresés
public static final boolean DEBUG = false;
public FallingGemsPanel() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
// Háttér, vesztett kép és a kövek képeinek betöltése MediaTracker-rel
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(hatter, 0);
tracker.addImage(vesztettkep, 1);
for (int i = 0; i < 7; i++) {
tracker.addImage(kokepek[i], i + 2);
}
try {
tracker.waitForAll();
} catch (Exception e) {
System.err.println("Hiba a kepek betoltesekor: " + e);
}
}
public void reset() {
// Vesztett állapot false-ra állítása
vesztett = false;
// Pont nullázása
pont = 0;
// Tábla beállítása
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
tabla[i][j] = 0;
}
}
}
@Override
public void addNotify() {
super.addNotify();
// Offscreen technika
imageBuffer = createImage(WIDTH, HEIGHT);
graphicsBuffer = imageBuffer.getGraphics();
// Első három kő leejtése
ejtes();
// MouseListener hozzaadasa
addMouseListener(this);
}
@Override
public void update(Graphics g) {
paint(g);
}
@Override
public void paint(Graphics g) {
//Ide kell rajzolni
Graphics actg;
actg = graphicsBuffer;
actg.drawImage(hatter, 0, 0, this);
if (!vesztett) {
// Kövek kirajzolása
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (tabla[i][j] != 0) {
actg.drawImage(kokepek[tabla[i][j] - 1], xoffset + i * 20 + 3, yoffset + j * 20 + 3, this);
}
}
}
// A választás jelölése
if (valasztott) {
actg.drawRect(xoffset + xindex * 20 + 16, yoffset + yindex * 20 + 16, 2, 2);
}
} else {
actg.drawImage(vesztettkep, xoffset, yoffset, this);
}
// Pontszám
actg.drawString("Pontszám: " + pont, 220, 180);
// Frissítés
g.drawImage(imageBuffer, 0, 0, this);
}
public boolean tele() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (tabla[i][j] == 0) {
return false;
}
}
}
return true;
}
public void ejtes() {
for (int i = 0; i < 3; i++) {
int x = generator.nextInt(9);
int y = generator.nextInt(9);
while (tabla[x][y] != 0) {
x = generator.nextInt(9);
y = generator.nextInt(9);
}
tabla[x][y] = generator.nextInt(7) + 1;
if (tele()) {
vesztett = true;
}
}
}
public int melyikSor(int x) {
int melyik = (x - xoffset) / 20;
if ((melyik >= 0) && (melyik < 9)) {
return melyik;
}
return -1;
}
public int melyikOszlop(int y) {
int melyik = (y - yoffset) / 20;
if ((melyik >= 0) && (melyik < 9)) {
return melyik;
}
return -1;
}
public int minszomszedpluszegy(int[][] tabla, int x, int y) {
// Szomszédok közül a legkisebb kiválasztása, majd hozzáadunk egyet
int[] ertekek = new int[4];
int legkisebb = 100;
ertekek[0] = (x > 0) && (tabla[x - 1][y] >= 0) ? tabla[x - 1][y] : 100;
ertekek[1] = (x < 8) && (tabla[x + 1][y] >= 0) ? tabla[x + 1][y] : 100;
ertekek[2] = (y > 0) && (tabla[x][y - 1] >= 0) ? tabla[x][y - 1] : 100;
ertekek[3] = (y < 8) && (tabla[x][y + 1] >= 0) ? tabla[x][y + 1] : 100;
if ((ertekek[0] <= ertekek[1]) && (ertekek[0] <= ertekek[2]) && (ertekek[0] <= ertekek[3])) {
legkisebb = ertekek[0] + 1;
}
if ((ertekek[1] <= ertekek[0]) && (ertekek[1] <= ertekek[2]) && (ertekek[1] <= ertekek[3])) {
legkisebb = ertekek[1] + 1;
}
if ((ertekek[2] <= ertekek[0]) && (ertekek[2] <= ertekek[1]) && (ertekek[2] <= ertekek[3])) {
legkisebb = ertekek[2] + 1;
}
if ((ertekek[3] <= ertekek[0]) && (ertekek[3] <= ertekek[1]) && (ertekek[3] <= ertekek[2])) {
legkisebb = ertekek[3] + 1;
}
if (legkisebb >= 100) {
return -1;
} else {
return legkisebb;
}
}
public void tablakiir(int[][] tabla) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (tabla[j][i] >= 0) {
System.out.print("+");
}
System.out.print(tabla[j][i]);
}
System.out.println();
}
System.out.println("---");
}
public void mehet(int x1, int y1, int x2, int y2) {
// Új tábla feltöltése: -2 - fal, -1 - üres
int[][] megoldtabla = new int[9][9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
megoldtabla[i][j] = (tabla[i][j] == 0) ? -1 : -2;
}
}
megoldtabla[x1][y1] = 0;
megoldtabla[x2][y2] = -1;
for (;;) {
boolean valtoztatott = false;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
// if (debug) {
// tablakiir(megoldtabla);
// }
if (megoldtabla[i][j] == -1) {
megoldtabla[i][j] = minszomszedpluszegy(megoldtabla, i, j);
if (megoldtabla[i][j] != -1) {
valtoztatott = true;
}
}
}
}
// Ha a célpont értéke megváltozott
if (megoldtabla[x2][y2] != -1) {
if (DEBUG) {
System.out.println("Ide lehet kovet mozgatni.");
}
// Menetelés útvonalának kiszámolása
int[][] utvonal = new int[2][81];
int actx = x2;
int acty = y2;
for (int i = megoldtabla[x2][y2]; i >= 0; i--) {
utvonal[0][i] = actx;
utvonal[1][i] = acty;
if ((actx > 0) && (megoldtabla[actx - 1][acty] == i - 1)) {
actx--;
continue;
}
if ((actx < 8) && (megoldtabla[actx + 1][acty] == i - 1)) {
actx++;
continue;
}
if ((acty > 0) && (megoldtabla[actx][acty - 1] == i - 1)) {
acty--;
continue;
}
if ((acty < 8) && (megoldtabla[actx][acty + 1] == i - 1)) {
acty++;
continue;
}
}
// Menetelő thread elindítása
menes = true;
Meno meno = new Meno(this, utvonal, megoldtabla[x2][y2]);
meno.start();
return;
}
// Ha egy változtatás sem történt a ciklus során
if (!valtoztatott) {
if (DEBUG) {
System.out.println("Ide nem lehet kovet mozgatni.");
}
return;
}
}
}
public int min(int x, int y) {
if (x <= y) {
return x;
}
return y;
}
public boolean otosben(int x, int y) {
// Vízszintes keresés
int startindex = (x - 4 >= 0) ? x - 4 : 0;
int stopindex = (x + 4 <= 8) ? x + 4 : 8;
int azonosszinu = 0;
for (int i = startindex; i <= stopindex; i++) {
if (tabla[i][y] == tabla[x][y]) {
azonosszinu++;
} else {
azonosszinu = 0;
}
if (azonosszinu == 5) {
return true;
}
}
// Függőleges keresés
startindex = (y - 4 >= 0) ? y - 4 : 0;
stopindex = (y + 4 <= 8) ? y + 4 : 8;
azonosszinu = 0;
for (int i = startindex; i <= stopindex; i++) {
if (tabla[x][i] == tabla[x][y]) {
azonosszinu++;
} else {
azonosszinu = 0;
}
if (azonosszinu == 5) {
return true;
}
}
// Átlós keresés (bal föntről)
azonosszinu = 0;
for (int i = -4; i <= 4; i++) {
if ((x + i >= 0) && (x + i <= 8) && (y + i >= 0) && (y + i <= 8) && (tabla[x + i][y + i] == tabla[x][y])) {
azonosszinu++;
}
if ((x + i >= 0) && (x + i <= 8) && (y + i >= 0) && (y + i <= 8) && (tabla[x + i][y + i] != tabla[x][y])) {
azonosszinu = 0;
}
if (azonosszinu == 5) {
return true;
}
}
// Átlós keresés (jobb föntről)
azonosszinu = 0;
for (int i = -4; i <= 4; i++) {
if ((x - i >= 0) && (x - i <= 8) && (y + i >= 0) && (y + i <= 8) && (tabla[x - i][y + i] == tabla[x][y])) {
azonosszinu++;
}
if ((x - i >= 0) && (x - i <= 8) && (y + i >= 0) && (y + i <= 8) && (tabla[x - i][y + i] != tabla[x][y])) {
azonosszinu = 0;
}
if (azonosszinu == 5) {
return true;
}
}
return false;
}
public int sullyed() {
int db = 0;
int[][] ujtabla = new int[9][9];
for (int i = 0; i < 9; i++) {
System.arraycopy(tabla[i], 0, ujtabla[i], 0, 9);
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if ((tabla[i][j] != 0) && (otosben(i, j))) {
ujtabla[i][j] = 0;
db++;
}
}
}
for (int i = 0; i < 9; i++) {
System.arraycopy(ujtabla[i], 0, tabla[i], 0, 9);
}
return db;
}
@Override
public void mousePressed(MouseEvent evt) {
if (vesztett) {
reset();
ejtes();
repaint();
}
int x = evt.getX();
int y = evt.getY();
if ((vesztett) || (menes)) {
return;
}
if (!valasztott) {
xindex = melyikSor(x);
yindex = melyikOszlop(y);
if (DEBUG) {
System.out.println("Kivalasztott cella: " + Integer.toString(xindex) + "," + Integer.toString(yindex));
}
if ((xindex != -1) && (yindex != -1) && (tabla[xindex][yindex] != 0)) {
// Kijelölés
if (DEBUG) {
System.out.println("Kivalasztva.");
}
valasztott = true;
repaint();
}
} else {
int newxindex = melyikSor(x);
int newyindex = melyikOszlop(y);
if ((newxindex == xindex) && (newyindex == yindex)) {
// Kijelölés törlése
if (DEBUG) {
System.out.println("Kivalasztas torolve.");
}
valasztott = false;
repaint();
} else {
if (DEBUG) {
System.out.println("Kivalasztott cella: " + Integer.toString(newxindex) + "," + Integer.toString(newyindex));
}
if ((newxindex != -1) && (newyindex != -1) && (tabla[newxindex][newyindex] == 0)) {
if (DEBUG) {
System.out.println("Mozgas ellenorzese.");
}
mehet(xindex, yindex, newxindex, newyindex);
}
}
}
if (DEBUG) {
System.out.println("A \"mouseDown\" esemeny vege.");
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
public void setHatter(Image hatter) {
this.hatter = hatter;
}
public void setKokepek(Image[] kokepek) {
this.kokepek = kokepek;
}
public void setVesztettkep(Image vesztettkep) {
this.vesztettkep = vesztettkep;
}
}
<file_sep>/src/main/java/fallinggems/FallingGemsApplication.java
package fallinggems;
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class FallingGemsApplication extends JFrame {
private FallingGemsPanel panel = new FallingGemsPanel();
public FallingGemsApplication() {
super("Falling Gems");
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
Image hatter = Toolkit.getDefaultToolkit().getImage(FallingGemsApplication.class.getResource("/GemBack.gif"));
Image vesztettkep = Toolkit.getDefaultToolkit().getImage(FallingGemsApplication.class.getResource("/YouLoose.gif"));
Image[] kokepek = new Image[7];
for (int i = 0; i < 7; i++) {
kokepek[i] = Toolkit.getDefaultToolkit().getImage(FallingGemsApplication.class.getResource("/" + i + ".gif"));
}
panel.setHatter(hatter);
panel.setVesztettkep(vesztettkep);
panel.setKokepek(kokepek);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(panel, BorderLayout.CENTER);
pack();
}
public static void main(String[] args) {
FallingGemsApplication app = new FallingGemsApplication();
app.setVisible(true);
}
}
|
ba8f0315b16beab810ad10d6cc89137c1a8fde56
|
[
"Markdown",
"Java"
] | 3 |
Markdown
|
vicziani/jtechlog-falling-gems
|
4ef549cc7bf5dd74466d4b6ce762faef383225e8
|
c8a54429ee44c7065c917141985612e484766232
|
refs/heads/master
|
<repo_name>JeffreyMJohnson/Graphics<file_sep>/Rendering_Geometry/source/main.cpp
//#include "SolarSystemApp.h"
#include "RenderingGeometryApp.h"
void main()
{
//SolarSystemApp* app = new SolarSystemApp();
RenderingGeometryApp* app = new RenderingGeometryApp();
if (app->StartUp())
{
while (app->Update())
{
app->Draw();
}
app->ShutDown();
}
delete app;
return;
}<file_sep>/README.md
# Graphics
Tutorial projects for Computer Graphics section of AIE game programming course.
<file_sep>/OBJ_Loader/source/main.cpp
#include "OBJLoaderApp.h"
void main()
{
OBJLoaderApp* app = new OBJLoaderApp();
if (app->StartUp())
{
while (app->Update())
{
app->Draw();
}
app->ShutDown();
}
delete app;
return;
}<file_sep>/OBJ_Loader/source/FlyCamera.cpp
#include "FlyCamera.h"
FlyCamera::FlyCamera(GLFWwindow* window)
{
mWindow = window;
Mouse::Init();
Mouse::SetMode(Mouse::Cursor_Mode::DISABLED);
Keyboard::Init();
}
void FlyCamera::SetPerspective(const float fov, const float aspectRatio, const float near, const float far)
{
mProjectionTransform = glm::perspective(fov, aspectRatio, near, far);
UpdateProjectViewTransform();
}
void FlyCamera::SetRotationSpeed(const float rotSpeed)
{
mRotSpeed = rotSpeed;
}
void FlyCamera::SetSpeed(const float speed)
{
mSpeed = speed;
}
void FlyCamera::Rotate(float angle, glm::vec3 axis)
{
mWorldTransform = glm::rotate(mWorldTransform, angle, axis);
mViewTransform = glm::inverse(mWorldTransform);
UpdateProjectViewTransform();
}
void FlyCamera::Translate(glm::vec3 distance)
{
mWorldTransform = glm::translate(mWorldTransform, distance);
mViewTransform = glm::inverse(mWorldTransform);
UpdateProjectViewTransform();
}
void FlyCamera::Update(float deltaTime)
{
Mouse::Update();
glm::vec3 direction = glm::vec3(0);
if (Keyboard::IsKeyPressed(Keyboard::KEY_W) || Keyboard::IsKeyRepeat(Keyboard::KEY_W))
{
direction = glm::vec3(0, 0, -1);
}
else if (Keyboard::IsKeyPressed(Keyboard::KEY_X) || Keyboard::IsKeyRepeat(Keyboard::KEY_X))
{
direction = glm::vec3(0, 0, 1);
}
else if (Keyboard::IsKeyPressed(Keyboard::KEY_A) || Keyboard::IsKeyRepeat(Keyboard::KEY_A))
{
direction = glm::vec3(-1, 0, 0);
}
else if (Keyboard::IsKeyPressed(Keyboard::KEY_D) || Keyboard::IsKeyRepeat(Keyboard::KEY_D))
{
direction = glm::vec3(1, 0, 0);
}
Translate(deltaTime * mSpeed * direction);
int deltaX = Mouse::GetPosX() - Mouse::GetPrevPosX();
//std::cout << "directionX: " << Mouse::GetDirectionX() << " Prev: " << Mouse::GetPrevPosX() << " Current: " << Mouse::GetPosX() << std::endl;
if (Mouse::IsButtonPressed(Mouse::LEFT))
{
//double sensitivity = .005;
pitch = 0; //rotate around x axis
yaw = 0; //rotate around y axis
//calc mouse offset
double deltaX = Mouse::GetPosX() - Mouse::GetPrevPosX();
double deltaY = Mouse::GetPosY() - Mouse::GetPrevPosY();//reversed because y is upper in gl
//add offset to yaw and pitch values
yaw += deltaX;
pitch += deltaY;
//constrain view to prevent hijinks
if (pitch > 89.0)
{
pitch = 89.0;
}
if (pitch < -89.0)
{
pitch = -89.0;
}
Rotate(yaw * sensitivity, glm::vec3(0, 1, 0));
Rotate(pitch * sensitivity, glm::vec3(1, 0, 0));
}
else
{
mCursorXPos = -1;
pitch = 0;
yaw = 0;
}
}<file_sep>/OBJ_Loader/include/FlyCamera.h
#pragma once
#include "Camera.h"
#include "Mouse.h"
#include "Keyboard.h"
#include <GLFW\glfw3.h>
#include <iostream>
class FlyCamera : public Camera
{
public:
FlyCamera(GLFWwindow* window);
void SetPerspective(const float fov, const float aspectRatio, const float near, const float far);
void SetSpeed(const float speed);
void SetRotationSpeed(const float rotSpeed);
void Rotate(float angle, glm::vec3 axis);
void Translate(glm::vec3 distance);
void Update(float deltaTime);
void Scroll_Callback(GLFWwindow* window, double xOffset, double yOffset);
private:
float mSpeed = 1.0f;
float mRotSpeed = 1.0f;
glm::vec3 mUp;
GLFWwindow* mWindow = nullptr;
double mCursorXPos = 0;
double mCursorYPos = 0;
double sensitivity = .005;
double pitch = 0; //rotate around x axis
double yaw = 0; //rotate around y axis
};<file_sep>/Textures/source/main.cpp
#define STB_IMAGE_IMPLEMENTATION
#include "TexturesApp.h"
void main()
{
TexturesApp* app = new TexturesApp();
if (app->StartUp())
{
while (app->Update())
{
app->Draw();
}
app->ShutDown();
}
delete app;
return;
}<file_sep>/Rendering_Geometry/source/Shader.cpp
#include "Shader.h"
const bool Shader::LoadShader(const char * vertexPath, const char * fragmentPath)
{
uint vertex = LoadSubShader(GL_VERTEX_SHADER, vertexPath);
uint fragment = LoadSubShader(GL_FRAGMENT_SHADER, fragmentPath);
int success = GL_FALSE;
mProgram = glCreateProgram();
glAttachShader(mProgram, vertex);
glAttachShader(mProgram, fragment);
glLinkProgram(mProgram);
glDeleteShader(vertex);
glDeleteShader(fragment);
glGetProgramiv(mProgram, GL_LINK_STATUS, &success);
if (success == GL_FALSE)
{
int length = 0;
glGetProgramiv(mProgram, GL_INFO_LOG_LENGTH, &length);
char* log = new char[length];
glGetProgramInfoLog(mProgram, length, 0, log);
std::cout << "Error linking shader program.\n" << log << std::endl;
delete[] log;
return false;
}
return true;
}
void Shader::FreeShader()
{
glDeleteProgram(mProgram);
}
void Shader::SetUniform(const char * name, const UniformType type, const void * value)
{
GLint location = glGetUniformLocation(mProgram, name);
switch (type)
{
case MAT4:
glUniformMatrix4fv(location, 1, false, (const GLfloat*)value);
break;
case VEC4:
glUniform4fv(location, 1, (GLfloat*)value);
break;
case FLO1:
glUniform1f(location, *(GLfloat*)value);
break;
}
}
uint Shader::LoadSubShader(uint shaderType, const char * path)
{
std::ifstream stream(path);
std::string contents = std::string(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>());
char* code = new char[contents.length() + 1];
strncpy_s(code, contents.length()+ 1, contents.c_str(), contents.length());
uint shader = glCreateShader(shaderType);
glShaderSource(shader, 1, &code, 0);
GLint success = GL_FALSE;
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (success == GL_FALSE)
{
int length = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length);
char* log = new char[length];
glGetShaderInfoLog(shader, length, 0, log);
std::cout << "Error compiling shader.\n" << log << std::endl;
delete[] log;
}
delete[] code;
return shader;
}
<file_sep>/Textures/include/Timer.h
#pragma once
struct Timer
{
float DeltaTime = 0;
float CurrentTime = 0;
float LastTime = 0;
float Update(float currentTime)
{
CurrentTime = currentTime;
DeltaTime = CurrentTime - LastTime;
LastTime = CurrentTime;
return DeltaTime;
}
};
<file_sep>/Textures/include/Camera.h
#pragma once
#include <glm\glm.hpp>
#include <glm\ext.hpp>
#include <glm\gtx\transform.hpp>
class Camera
{
public:
void Update(const float deltaTime);
void SetLookAt(const glm::vec3 from, const glm::vec3 to, const glm::vec3 up);
void SetPosition(const glm::vec3 position);
const glm::mat4 GetWorldTransform();
const glm::mat4 GetView();
const glm::mat4 GetProjection();
protected:
glm::mat4 mWorldTransform = glm::mat4();//logical update
glm::mat4 mViewTransform = glm::mat4();//draw transform
glm::mat4 mProjectionTransform = glm::mat4();
glm::mat4 mProjectionViewTransform = glm::mat4(); //projectionview * projectionTransform - draw transform
void UpdateProjectViewTransform();
};<file_sep>/Textures/source/TexturesApp.cpp
#include "TexturesApp.h"
bool TexturesApp::StartUp()
{
if (!glfwInit())
{
return false;
}
mWindow = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE, nullptr, nullptr);
if (nullptr == mWindow)
{
glfwTerminate();
return false;
}
glfwMakeContextCurrent(mWindow);
if (ogl_LoadFunctions() == ogl_LOAD_FAILED)
{
glfwDestroyWindow(mWindow);
glfwTerminate();
return false;
}
//std::string err = tinyobj::LoadObj(shapes, materials, MODEL_FILE_PATH);
//if (err.length() != 0)
//{
// std::cout << "Error loading OBJ file:\n" << err << std::endl;
// return false;
//}
//CreateOpenGLBuffers(shapes);
InitCamera();
// create shaders
/*const char* vsSource = "#version 330\n \
layout(location=0) in vec4 Position; \
layout(location=1) in vec4 Colour; \
out vec4 vColour; \
uniform mat4 ProjectionView; \
void main() \
{ \
vColour = Colour; \
gl_Position = ProjectionView * Position;\
}";
const char* fsSource = "#version 330\n \
in vec4 vColour; \
out vec4 FragColor; \
void main() \
{\
FragColor = vColour;\
}";
int success = GL_FALSE;
uint vertexShader = glCreateShader(GL_VERTEX_SHADER);
uint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vertexShader, 1, (const char**)&vsSource, 0);
glCompileShader(vertexShader);
glShaderSource(fragmentShader, 1, (const char**)&fsSource, 0);
glCompileShader(fragmentShader);
mShaderProgramID = glCreateProgram();
glAttachShader(mShaderProgramID, vertexShader);
glAttachShader(mShaderProgramID, fragmentShader);
glLinkProgram(mShaderProgramID);
glGetProgramiv(mShaderProgramID, GL_LINK_STATUS, &success);
if (success == GL_FALSE) {
int infoLogLength = 0;
glGetProgramiv(mShaderProgramID, GL_INFO_LOG_LENGTH, &infoLogLength);
char* infoLog = new char[infoLogLength];
glGetProgramInfoLog(mShaderProgramID, infoLogLength, 0, infoLog);
printf("Error: Failed to link shader program!\n");
printf("%s\n", infoLog);
delete[] infoLog;
}
glDeleteShader(fragmentShader);
glDeleteShader(vertexShader);*/
const char* vsSource = "#version 410\n \
layout(location=0) in vec4 Position; \
layout(location=1) in vec2 TexCoord; \
out vec2 vTexCoord; \
uniform mat4 ProjectionView; \
void main() { \
vTexCoord = TexCoord; \
gl_Position= ProjectionView * Position;\
}";
const char* fsSource = "#version 410\n \
in vec2 vTexCoord; \
out vec4 FragColor; \
uniform sampler2D diffuse; \
void main() { \
FragColor = texture(diffuse,vTexCoord);\
}";
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, (const char**)&vsSource, 0);
glCompileShader(vertexShader);
unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, (const char**)&fsSource, 0);
glCompileShader(fragmentShader);
mShaderProgramID = glCreateProgram();
glAttachShader(mShaderProgramID, vertexShader);
glAttachShader(mShaderProgramID, fragmentShader);
glLinkProgram(mShaderProgramID);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
glUseProgram(mShaderProgramID);
uint projectionViewUniform = glGetUniformLocation(mShaderProgramID, "ProjectionView");
glUniformMatrix4fv(projectionViewUniform, 1, false, glm::value_ptr(mCamera->GetProjection() * mCamera->GetView()));
//load texture data
int imageWidth = 0, imageHeight = 0, imageFormat = 0;
unsigned char* data = stbi_load(CRATE_TEXTURE_PATH, &imageWidth, &imageHeight, &imageFormat, STBI_default);
if (data == nullptr)
{
std::cout << "error loading texture.\n";
}
glGenTextures(1, &mTexture);
glBindTexture(GL_TEXTURE_2D, mTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, imageWidth, imageHeight,
0, GL_RGB, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
stbi_image_free(data);
CreateBuffers();
if (DEBUG_MODE)
{
int major = ogl_GetMajorVersion();
int minor = ogl_GetMinorVersion();
printf("GL: %i.%i\n", major, minor);
}
glClearColor(CLEAR_COLOR.r, CLEAR_COLOR.g, CLEAR_COLOR.b, CLEAR_COLOR.a);
glEnable(GL_DEPTH_TEST);
return true;
}
void TexturesApp::ShutDown()
{
delete mCamera;
glfwDestroyWindow(mWindow);
glfwTerminate();
}
bool TexturesApp::Update()
{
if (glfwWindowShouldClose(mWindow) || glfwGetKey(mWindow, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
return false;
}
timer.Update(glfwGetTime());
mCamera->Update(timer.DeltaTime);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
return true;
}
void TexturesApp::Draw()
{
//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
//glUseProgram(mShaderProgramID);
//uint projectionViewUniform = glGetUniformLocation(mShaderProgramID, "ProjectionView");
//glUniformMatrix4fv(projectionViewUniform, 1, false, glm::value_ptr(mCamera->GetProjection() * mCamera->GetView()));
//for (uint i = 0; i < mGLInfo.size(); ++i)
//{
// glBindVertexArray(mGLInfo[i].mVAO);
// glDrawElements(GL_TRIANGLES, mGLInfo[i].mIndexCount, GL_UNSIGNED_INT, 0);
//}
// use our texture program
glUseProgram(mShaderProgramID);
// bind the camera
int loc = glGetUniformLocation(mShaderProgramID, "ProjectionView");
glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(mCamera->GetProjection() * mCamera->GetView()));
// set texture slot
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mTexture);
// tell the shader where it is
loc = glGetUniformLocation(mShaderProgramID, "diffuse");
glUniform1i(loc, 0);
// draw
glBindVertexArray(mGLInfo.mVAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, nullptr);
glfwSwapBuffers(mWindow);
glfwPollEvents();
}
void TexturesApp::InitCamera()
{
mCamera = new FlyCamera(mWindow);
mCamera->SetSpeed(10.0f);
mCamera->SetRotationSpeed(10.0f);
mCamera->SetPerspective(CAMERA_FOV, (float)WINDOW_WIDTH / WINDOW_HEIGHT, CAMERA_NEAR, CAMERA_FAR);
mCamera->SetLookAt(CAMERA_FROM, CAMERA_TO, CAMERA_UP);
}
void TexturesApp::CreateBuffers()
{
float vertexData[] = {
-5, 0, 5, 1, 0, 1,
5, 0, 5, 1, 1, 1,
5, 0, -5, 1, 1, 0,
-5, 0, -5, 1, 0, 0,
};
unsigned int indexData[] = {
0, 1, 2,
0, 2, 3,
};
glGenVertexArrays(1, &mGLInfo.mVAO);
glBindVertexArray(mGLInfo.mVAO);
glGenBuffers(1, &mGLInfo.mVBO);
glBindBuffer(GL_ARRAY_BUFFER, mGLInfo.mVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4,
vertexData, GL_STATIC_DRAW);
glGenBuffers(1, &mGLInfo.mIBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mGLInfo.mIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * 6,
indexData, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 6, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 6, ((char*)0) + 16);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}<file_sep>/OBJ_Loader/include/GameApp.h
#pragma once
#include <gl_core_4_4.h>
#include <GLFW\glfw3.h>
#include <aie\Gizmos.h>
#include <glm\glm.hpp>
#include <glm\ext.hpp>
#include <glm\gtx\transform.hpp>
#include "Timer.h"
#include "Camera.h"
class GameApp
{
public:
virtual bool StartUp() = 0;
virtual void ShutDown() = 0;
virtual bool Update() = 0;
virtual void Draw() = 0;
GLFWwindow* mWindow = nullptr;
Timer timer = Timer();
};<file_sep>/OBJ_Loader/include/OBJLoaderApp.h
#pragma once
#include <vector>
#include <string>
#include "GameApp.h"
#include "FlyCamera.h"
#include "Keyboard.h"
#include "tiny_obj_loader\tiny_obj_loader.h"
#include "fbx_loader\FBXFile.h"
using glm::vec2;
using glm::vec3;
using glm::vec4;
using glm::mat4;
typedef unsigned int uint;
class OBJLoaderApp : public GameApp
{
public:
const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;
const char* WINDOW_TITLE = "OBJ Loader";
const vec4 CLEAR_COLOR = vec4(.25f, .25f, .25f, 1);
const float CAMERA_FOV = glm::pi<float>() * .25f;
const float CAMERA_NEAR = .1f;
const float CAMERA_FAR = 1000.0f;
const vec3 CAMERA_FROM = vec3(10, 10, 10);
const vec3 CAMERA_TO = vec3(0);
const vec3 CAMERA_UP = vec3(0, 1, 0);
const char* OBJ_MODEL_FILE_PATH = "../OBJ_Loader/resources/models/bunny.obj";
const char* FBX_MODEL_FILE_PATH = "../OBJ_Loader/resources/models/Bunny.fbx";
const bool DEBUG_MODE = true;
bool StartUp();
void ShutDown();
bool Update();
void Draw();
private:
typedef struct OpenGLInfo
{
uint mVAO;
uint mVBO;
uint mIBO;
uint mIndexCount;
} GLInfo;
struct Vertex
{
vec4 postion;
vec4 color;
vec4 normal;
vec2 UV;
};
struct Geometry
{
std::vector<Vertex> vertices;
std::vector<uint> indices;
};
FlyCamera* mCamera = nullptr;
uint mShaderProgramID = 0;
std::vector<GLInfo> mGLInfo;
void InitCamera();
bool LoadGeometry(const char* path);
//Geometry& LoadGeometry(const char* path);
bool LoadGLBuffers(OpenGLInfo& renderObject, const Geometry& geometry);
};
<file_sep>/Textures/source/Camera.cpp
#include "Camera.h"
void Camera::Update(const float deltaTime)
{
}
void Camera::SetLookAt(const glm::vec3 from, const glm::vec3 to, const glm::vec3 up)
{
mViewTransform = glm::lookAt(from, to, up);
mWorldTransform = glm::inverse(mViewTransform);
}
void Camera::SetPosition(const glm::vec3 position)
{
mWorldTransform = glm::translate(mWorldTransform, position);
mViewTransform = glm::inverse(mWorldTransform);
UpdateProjectViewTransform();
}
const glm::mat4 Camera::GetWorldTransform()
{
return mWorldTransform;
}
const glm::mat4 Camera::GetView()
{
return glm::inverse(mWorldTransform);
}
const glm::mat4 Camera::GetProjection()
{
return mProjectionTransform;
}
void Camera::UpdateProjectViewTransform()
{
mProjectionViewTransform = mProjectionTransform * mViewTransform;
}<file_sep>/Rendering_Geometry/include/Color.h
#pragma once
#include "glm\vec4.hpp"
const glm::vec4 WHITE = glm::vec4(1);
const glm::vec4 BLACK = glm::vec4(0, 0, 0, 1);
const glm::vec4 WIRE_FRAME = glm::vec4(0);<file_sep>/Rendering_Geometry/include/RenderingGeometryApp.h
#pragma once
#include "GameApp.h"
#include "FlyCamera.h"
#include "Keyboard.h"
#include "Shader.h"
using glm::vec3;
using glm::vec4;
using glm::mat4;
typedef unsigned int uint;
struct Vertex
{
vec4 position;
vec4 color;
};
class RenderingGeometryApp : public GameApp
{
public:
const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;
const char* WINDOW_TITLE = "Rendering Geometry";
const vec4 CLEAR_COLOR = vec4(.25f, .25f, .25f, 1);
const float CAMERA_FOV = glm::pi<float>() * .25f;
const float CAMERA_NEAR = .1f;
const float CAMERA_FAR = 1000.0f;
const vec3 CAMERA_FROM = vec3(10, 10, 10);
const vec3 CAMERA_TO = vec3(0);
const vec3 CAMERA_UP = vec3(0, 1, 0);
const bool DEBUG_MODE = true;
bool StartUp();
void ShutDown();
bool Update();
void Draw();
private:
Shader* mShader = new Shader();
FlyCamera* mCamera = nullptr;
uint mVAO = 0;
uint mVBO = 0;
uint mIBO = 0;
const uint ROWS = 25;
const uint COLS = 25;
void InitCamera();
void GenerateGrid(uint rows, uint cols);
void LoadGLBuffer(Vertex* vertices, uint verticesSize, uint* indeces, uint indecesCount);
};
<file_sep>/Rendering_Geometry/source/RenderingGeometryApp.cpp
#include "RenderingGeometryApp.h"
bool RenderingGeometryApp::StartUp()
{
if (!glfwInit())
{
return false;
}
mWindow = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE, nullptr, nullptr);
if (nullptr == mWindow)
{
glfwTerminate();
return false;
}
glfwMakeContextCurrent(mWindow);
if (ogl_LoadFunctions() == ogl_LOAD_FAILED)
{
glfwDestroyWindow(mWindow);
glfwTerminate();
return false;
}
InitCamera();
// create shaders
//mShader->LoadShader("../Rendering_Geometry/source/Simple_Vertex_Shader.glsl", "../Rendering_Geometry/source/Simple_Fragment_Shader.glsl");
mShader->LoadShader("../Rendering_Geometry/source/Vertex_Shader_2.glsl", "../Rendering_Geometry/source/Simple_Fragment_Shader.glsl");
GenerateGrid(ROWS, COLS);
glBindVertexArray(mVAO);
glUseProgram(mShader->GetProgram());
mShader->SetUniform("ProjectionView", Shader::MAT4, glm::value_ptr(mCamera->GetProjection() * mCamera->GetView()));
mShader->SetUniform("time", Shader::FLO1, &timer.DeltaTime);
float height = .5f;
mShader->SetUniform("heightScale", Shader::FLO1, &height);
if (DEBUG_MODE)
{
int major = ogl_GetMajorVersion();
int minor = ogl_GetMinorVersion();
printf("GL: %i.%i\n", major, minor);
}
glClearColor(CLEAR_COLOR.r, CLEAR_COLOR.g, CLEAR_COLOR.b, CLEAR_COLOR.a);
glEnable(GL_DEPTH_TEST);
//init model transforms
return true;
}
void RenderingGeometryApp::ShutDown()
{
delete mCamera;
delete mShader;
glfwDestroyWindow(mWindow);
glfwTerminate();
}
bool RenderingGeometryApp::Update()
{
if (glfwWindowShouldClose(mWindow) || glfwGetKey(mWindow, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
return false;
}
timer.Update(glfwGetTime());
mCamera->Update(timer.DeltaTime);
mShader->SetUniform("time", Shader::FLO1, &timer.CurrentTime);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
return true;
}
void RenderingGeometryApp::Draw()
{
uint indexCount = (ROWS - 1) * (COLS - 1) * 6;
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
mShader->SetUniform("ProjectionView", Shader::MAT4, glm::value_ptr(mCamera->GetProjection() * mCamera->GetView()));
/*uint projectionViewUniform = glGetUniformLocation(mShader->GetProgram(), "ProjectionView");
glUniformMatrix4fv(projectionViewUniform, 1, false, glm::value_ptr(mCamera->GetProjection() * mCamera->GetView()));*/
glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_INT, 0);
glfwSwapBuffers(mWindow);
glfwPollEvents();
}
void RenderingGeometryApp::InitCamera()
{
mCamera = new FlyCamera(mWindow);
mCamera->SetSpeed(10.0f);
mCamera->SetRotationSpeed(10.0f);
mCamera->SetPerspective(CAMERA_FOV, (float)WINDOW_WIDTH / WINDOW_HEIGHT, CAMERA_NEAR, CAMERA_FAR);
mCamera->SetLookAt(CAMERA_FROM, CAMERA_TO, CAMERA_UP);
}
void RenderingGeometryApp::GenerateGrid(uint rows, uint cols)
{
uint verticesSize = rows * cols;
Vertex* vertices = new Vertex[verticesSize];
for (uint r = 0; r < rows; r++)
{
for (uint c = 0; c < cols; c++)
{
vertices[r * cols + c].position = vec4((float)c, 0, (float)r, 1);
vec3 color = vec3(sinf((c / (float)(cols - 1))*(r / (float)(rows - 1))));
vertices[r*cols + c].color = vec4(color, 1);
}
}
uint indecesCount = (rows - 1) * (cols - 1) * 6;
uint* indeces = new uint[indecesCount];
uint index = 0;
for (uint r = 0; r < (rows - 1); r++)
{
for (uint c = 0; c < (cols - 1); c++)
{
//triangle 1
indeces[index++] = r*cols + c;
indeces[index++] = (r + 1)*cols + c;
indeces[index++] = (r + 1)*cols + (c + 1);
//triangle 2
indeces[index++] = r*cols + c;
indeces[index++] = (r + 1)*cols + (c + 1);
indeces[index++] = r*cols + (c + 1);
}
}
//create and bind buffers to a VAO
LoadGLBuffer(vertices, verticesSize, indeces, indecesCount);
delete[] vertices;
delete[] indeces;
}
void RenderingGeometryApp::LoadGLBuffer(Vertex* vertices, uint verticesSize, uint* indeces, uint indecesCount)
{
glGenVertexArrays(1, &mVAO);
glBindVertexArray(mVAO);
glGenBuffers(1, &mVBO);
glBindBuffer(GL_ARRAY_BUFFER, mVBO);
glBufferData(GL_ARRAY_BUFFER, verticesSize * sizeof(Vertex), vertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(vec4)));
glGenBuffers(1, &mIBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indecesCount * sizeof(uint), indeces, GL_STATIC_DRAW);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
<file_sep>/Textures/include/TexturesApp.h
#pragma once
#include <vector>
#include <string>
#include "GameApp.h"
#include "FlyCamera.h"
#include "stb\stb_image.h"
#include "tiny_obj_loader\tiny_obj_loader.h"
using glm::vec3;
using glm::vec4;
using glm::mat4;
typedef unsigned int uint;
class TexturesApp : public GameApp
{
public:
const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;
const char* WINDOW_TITLE = "Texture Loader";
const vec4 CLEAR_COLOR = vec4(.25f, .25f, .25f, 1);
const float CAMERA_FOV = glm::pi<float>() * .25f;
const float CAMERA_NEAR = .1f;
const float CAMERA_FAR = 1000.0f;
const vec3 CAMERA_FROM = vec3(10, 10, 10);
const vec3 CAMERA_TO = vec3(0);
const vec3 CAMERA_UP = vec3(0, 1, 0);
const char* MODEL_FILE_PATH = "../OBJ_Loader/resources/models/bunny.obj";
const char* CRATE_TEXTURE_PATH = "resources/textures/crate.png";
const bool DEBUG_MODE = true;
bool StartUp();
void ShutDown();
bool Update();
void Draw();
private:
typedef struct OpenGLInfo
{
uint mVAO;
uint mVBO;
uint mIBO;
uint mIndexCount;
} GLInfo;
FlyCamera* mCamera = nullptr;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
uint mShaderProgramID = 0;
GLInfo mGLInfo;
uint mTexture = 0;
void InitCamera();
//void CreateOpenGLBuffers(std::vector<tinyobj::shape_t>& shapes);
void CreateBuffers();
};<file_sep>/Rendering_Geometry/include/Shader.h
#pragma once
#include <string>
#include <fstream>
#include <iostream>
#include "gl_core_4_4.h"
#include "GLFW\glfw3.h"
typedef unsigned int uint;
class Shader
{
public:
enum UniformType
{
MAT4,
VEC4,
FLO1
};
const bool LoadShader(const char* vertexPath, const char* fragmentPath);
void FreeShader();
const uint GetProgram() { return mProgram; }
void SetUniform(const char* name, const UniformType type, const void* value);
private:
uint mProgram = 0;
uint LoadSubShader(uint shaderType, const char* path);
};<file_sep>/OBJ_Loader/source/OBJLoaderApp.cpp
#include "OBJLoaderApp.h"
bool OBJLoaderApp::StartUp()
{
if (!glfwInit())
{
return false;
}
mWindow = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE, nullptr, nullptr);
if (nullptr == mWindow)
{
glfwTerminate();
return false;
}
glfwMakeContextCurrent(mWindow);
if (ogl_LoadFunctions() == ogl_LOAD_FAILED)
{
glfwDestroyWindow(mWindow);
glfwTerminate();
return false;
}
//load model file
LoadGeometry(OBJ_MODEL_FILE_PATH);
//LoadGeometry(FBX_MODEL_FILE_PATH);
InitCamera();
// create shaders
const char* vsSource = "#version 330\n \
layout(location=0) in vec4 Position; \
layout(location=1) in vec4 Colour; \
out vec4 vColour; \
uniform mat4 ProjectionView; \
void main() \
{ \
vColour = Colour; \
gl_Position = ProjectionView * Position;\
}";
const char* fsSource = "#version 330\n \
in vec4 vColour; \
out vec4 FragColor; \
void main() \
{\
FragColor = vColour;\
}";
int success = GL_FALSE;
uint vertexShader = glCreateShader(GL_VERTEX_SHADER);
uint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vertexShader, 1, (const char**)&vsSource, 0);
glCompileShader(vertexShader);
glShaderSource(fragmentShader, 1, (const char**)&fsSource, 0);
glCompileShader(fragmentShader);
mShaderProgramID = glCreateProgram();
glAttachShader(mShaderProgramID, vertexShader);
glAttachShader(mShaderProgramID, fragmentShader);
glLinkProgram(mShaderProgramID);
glGetProgramiv(mShaderProgramID, GL_LINK_STATUS, &success);
if (success == GL_FALSE) {
int infoLogLength = 0;
glGetProgramiv(mShaderProgramID, GL_INFO_LOG_LENGTH, &infoLogLength);
char* infoLog = new char[infoLogLength];
glGetProgramInfoLog(mShaderProgramID, infoLogLength, 0, infoLog);
printf("Error: Failed to link shader program!\n");
printf("%s\n", infoLog);
delete[] infoLog;
}
glDeleteShader(fragmentShader);
glDeleteShader(vertexShader);
glUseProgram(mShaderProgramID);
uint projectionViewUniform = glGetUniformLocation(mShaderProgramID, "ProjectionView");
glUniformMatrix4fv(projectionViewUniform, 1, false, glm::value_ptr(mCamera->GetProjection() * mCamera->GetView()));
if (DEBUG_MODE)
{
int major = ogl_GetMajorVersion();
int minor = ogl_GetMinorVersion();
printf("GL: %i.%i\n", major, minor);
}
glClearColor(CLEAR_COLOR.r, CLEAR_COLOR.g, CLEAR_COLOR.b, CLEAR_COLOR.a);
glEnable(GL_DEPTH_TEST);
return true;
}
void OBJLoaderApp::ShutDown()
{
delete mCamera;
glfwDestroyWindow(mWindow);
glfwTerminate();
}
bool OBJLoaderApp::Update()
{
if (glfwWindowShouldClose(mWindow) || glfwGetKey(mWindow, GLFW_KEY_ESCAPE) == GLFW_PRESS)
{
return false;
}
timer.Update(glfwGetTime());
mCamera->Update(timer.DeltaTime);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
return true;
}
void OBJLoaderApp::Draw()
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glUseProgram(mShaderProgramID);
uint projectionViewUniform = glGetUniformLocation(mShaderProgramID, "ProjectionView");
glUniformMatrix4fv(projectionViewUniform, 1, false, glm::value_ptr(mCamera->GetProjection() * mCamera->GetView()));
for (uint i = 0; i < mGLInfo.size(); ++i)
{
glBindVertexArray(mGLInfo[i].mVAO);
glDrawElements(GL_TRIANGLES, mGLInfo[i].mIndexCount, GL_UNSIGNED_INT, 0);
}
glfwSwapBuffers(mWindow);
glfwPollEvents();
}
void OBJLoaderApp::InitCamera()
{
mCamera = new FlyCamera(mWindow);
mCamera->SetSpeed(10.0f);
mCamera->SetRotationSpeed(10.0f);
mCamera->SetPerspective(CAMERA_FOV, (float)WINDOW_WIDTH / WINDOW_HEIGHT, CAMERA_NEAR, CAMERA_FAR);
mCamera->SetLookAt(CAMERA_FROM, CAMERA_TO, CAMERA_UP);
}
bool OBJLoaderApp::LoadGeometry(const char * path)
{
bool success = true;
//find extension
std::string sPath(path);
std::string ext = sPath.substr(sPath.find_last_of('.'));
Geometry geometry;
if (ext == ".obj")
{
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::material_t> materials;
std::string err = tinyobj::LoadObj(shapes, materials, path);
if (err.length() != 0)
{
std::cout << "Error loading OBJ file:\n" << err << std::endl;
success = false;
}
//hard coding only using first shape, can change to loop here
if (success)
{
auto shape = shapes[0];
auto mesh = shape.mesh;
geometry.vertices.resize(mesh.positions.size());
uint posIndex = 0;
uint normalIndex = 0;
uint UVIndex = 0;
bool hasNormals = mesh.normals.size() == mesh.positions.size();
bool hasUVs = mesh.texcoords.size() == mesh.positions.size();
//obj has vectors of floats, my struct and shaders uses glm vecs so need to build myself
for (uint vertexCount = 0; posIndex < mesh.positions.size(); vertexCount++)
{
float x = mesh.positions[posIndex++];
float y = mesh.positions[posIndex++];
float z = mesh.positions[posIndex++];
geometry.vertices[vertexCount].postion = vec4(x, y, z, 1);
if (hasNormals)
{
x = mesh.normals[normalIndex++];
y = mesh.normals[normalIndex++];
z = mesh.normals[normalIndex++];
geometry.vertices[vertexCount].normal = vec4(x, y, z, 1);
}
if (hasUVs)
{
x = mesh.texcoords[UVIndex++];
y = mesh.texcoords[UVIndex++];
geometry.vertices[vertexCount].UV = vec2(x, y);
}
}
geometry.indices = mesh.indices;
}
}
else if (ext == ".fbx")
{
FBXFile file;
success = file.load(path, FBXFile::UNITS_METER, false, false, false);
if (!success)
{
std::cout << "Error loading FBX file:\n";
}
else
{
//hardcoding to use single mesh, can loop here if needed.
FBXMeshNode* mesh = file.getMeshByIndex(0);
geometry.vertices.resize(mesh->m_vertices.size());
for (int i = 0; i < mesh->m_vertices.size();i++)
{
auto xVert = mesh->m_vertices[i];
geometry.vertices[i].postion = xVert.position;
geometry.vertices[i].color = xVert.colour;
geometry.vertices[i].normal = xVert.normal;
geometry.vertices[i].UV = xVert.texCoord1;
}
geometry.indices = mesh->m_indices;
file.unload();
}
}
else
{
std::cout << "Unsupported format. Only support .obj or .fbx files.\n";
success = false;
}
if (!success)
{
return false;
}
GLInfo renderObject;
LoadGLBuffers(renderObject, geometry);
mGLInfo.push_back(renderObject);
return true;
}
bool OBJLoaderApp::LoadGLBuffers(OpenGLInfo & renderObject, const Geometry & geometry)
{
glGenVertexArrays(1, &renderObject.mVAO);
glGenBuffers(1, &renderObject.mVBO);
glGenBuffers(1, &renderObject.mIBO);
glBindVertexArray(renderObject.mVAO);
//uint floatCount = shapes[meshIndex].mesh.positions.size();
//floatCount += shapes[meshIndex].mesh.normals.size();
//floatCount += shapes[meshIndex].mesh.texcoords.size();
renderObject.mIndexCount = geometry.indices.size();
glBindBuffer(GL_ARRAY_BUFFER, renderObject.mVBO);
glBufferData(GL_ARRAY_BUFFER, geometry.vertices.size() * sizeof(Vertex), geometry.vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, renderObject.mIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, geometry.indices.size() * sizeof(uint), geometry.indices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);//position
glEnableVertexAttribArray(1);//color in shader right now.
//glEnableVertexAttribArray(2);//normal
//glEnableVertexAttribArray(3);//UV coord
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
//THIS NEEDS TO BE CHANGED WHEN SHADER IS UPDATED
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(vec4) * 2));// 1));
//glVertexAttribPointer(2, 4, GL_FLOAT, GL_TRUE, sizeof(Vertex), (void*)(sizeof(vec4) * 2));
//glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(sizeof(vec4) * 3));
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return true;
}
/*
void OBJLoaderApp::CreateOpenGLBuffers(std::vector<tinyobj::shape_t>& shapes)
{
mGLInfo.resize(shapes.size());
for (uint meshIndex = 0; meshIndex < shapes.size(); ++meshIndex)
{
glGenVertexArrays(1, &mGLInfo[meshIndex].mVAO);
glGenBuffers(1, &mGLInfo[meshIndex].mVBO);
glGenBuffers(1, &mGLInfo[meshIndex].mIBO);
glBindVertexArray(mGLInfo[meshIndex].mVAO);
uint floatCount = shapes[meshIndex].mesh.positions.size();
floatCount += shapes[meshIndex].mesh.normals.size();
floatCount += shapes[meshIndex].mesh.texcoords.size();
std::vector<float> vertexData;
vertexData.reserve(floatCount);
vertexData.insert(vertexData.end(), shapes[meshIndex].mesh.positions.begin(), shapes[meshIndex].mesh.positions.end());
vertexData.insert(vertexData.end(), shapes[meshIndex].mesh.normals.begin(), shapes[meshIndex].mesh.normals.end());
mGLInfo[meshIndex].mIndexCount = shapes[meshIndex].mesh.indices.size();
glBindBuffer(GL_ARRAY_BUFFER, mGLInfo[meshIndex].mVBO);
glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(float), vertexData.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mGLInfo[meshIndex].mIBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, shapes[meshIndex].mesh.indices.size() * sizeof(uint), shapes[meshIndex].mesh.indices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);//position
glEnableVertexAttribArray(1);//normal data
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, 0, (void*)(sizeof(float)*shapes[meshIndex].mesh.positions.size()));
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
*/
//void OBJLoaderApp::CreateOpenGLBuffers(FbxScene* scene)
//{
// FbxNode* rootNode = scene->GetRootNode();
// mGLInfo.resize(rootNode->GetChildCount());
//
//
//
// //for (uint meshIndex = 0; meshIndex < shapes.size(); ++meshIndex)
// for (uint meshIndex = 0; meshIndex < rootNode->GetChildCount(); ++meshIndex)
// {
// glGenVertexArrays(1, &mGLInfo[meshIndex].mVAO);
// glGenBuffers(1, &mGLInfo[meshIndex].mVBO);
// glGenBuffers(1, &mGLInfo[meshIndex].mIBO);
// glBindVertexArray(mGLInfo[meshIndex].mVAO);
//
// FbxMesh* mesh = rootNode->GetChild(meshIndex)->GetMesh();
//
// uint floatCount = mesh->mPolygonVertices.Size();
// //shapes[meshIndex].mesh.positions.size();
// floatCount += mesh->norm
// //shapes[meshIndex].mesh.normals.size();
// floatCount += shapes[meshIndex].mesh.texcoords.size();
//
//
// std::vector<float> vertexData;
// vertexData.reserve(floatCount);
//
// vertexData.insert(vertexData.end(), shapes[meshIndex].mesh.positions.begin(), shapes[meshIndex].mesh.positions.end());
//
// vertexData.insert(vertexData.end(), shapes[meshIndex].mesh.normals.begin(), shapes[meshIndex].mesh.normals.end());
//
// mGLInfo[meshIndex].mIndexCount = shapes[meshIndex].mesh.indices.size();
//
// glBindBuffer(GL_ARRAY_BUFFER, mGLInfo[meshIndex].mVBO);
// glBufferData(GL_ARRAY_BUFFER, vertexData.size() * sizeof(float), vertexData.data(), GL_STATIC_DRAW);
//
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mGLInfo[meshIndex].mIBO);
// glBufferData(GL_ELEMENT_ARRAY_BUFFER, shapes[meshIndex].mesh.indices.size() * sizeof(uint), shapes[meshIndex].mesh.indices.data(), GL_STATIC_DRAW);
//
// glEnableVertexAttribArray(0);//position
// glEnableVertexAttribArray(1);//normal data
//
// glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
// glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, 0, (void*)(sizeof(float)*shapes[meshIndex].mesh.positions.size()));
//
// glBindVertexArray(0);
// glBindBuffer(GL_ARRAY_BUFFER, 0);
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// }
//}
/*
void OBJLoaderApp::PrintFBXNode(FbxNode* node)
{
using namespace std;
const char* name = node->GetName();
FbxDouble3 translation = node->LclTranslation.Get();
FbxDouble3 rotation = node->LclRotation.Get();
FbxDouble3 scaling = node->LclScaling.Get();
// Print the contents of the node
printf("<node name='%s' translation='(%f,%f,%f)' rotation='(%f,%f,%f)' scaling='(%f,%f,%f)'>\n",
name,
translation[0], translation[1], translation[2],
rotation[0], rotation[1], rotation[2],
scaling[0], scaling[1], scaling[2]
);
// Print the node's attributes.
for (int i = 0; i < node->GetNodeAttributeCount(); i++)
PrintFBXAttribute(node->GetNodeAttributeByIndex(i));
// Recursively print the children.
for (int j = 0; j < node->GetChildCount(); j++)
PrintFBXNode(node->GetChild(j));
mNumTabs--;
PrintTabs();
printf("</node>\n");
}
void OBJLoaderApp::PrintFBXAttribute(FbxNodeAttribute* attribute)
{
if (!attribute) return;
FbxString typeName = GetAttributeTypeName(attribute->GetAttributeType());
FbxString attrName = attribute->GetName();
PrintTabs();
// Note: to retrieve the character array of a FbxString, use its Buffer() method.
printf("<attribute type='%s' name='%s'/>\n", typeName.Buffer(), attrName.Buffer());
}
void OBJLoaderApp::PrintTabs()
{
for (int i = 0; i < mNumTabs; i++)
printf("\t");
}
FbxString OBJLoaderApp::GetAttributeTypeName(FbxNodeAttribute::EType type) {
switch (type) {
case FbxNodeAttribute::eUnknown: return "unidentified";
case FbxNodeAttribute::eNull: return "null";
case FbxNodeAttribute::eMarker: return "marker";
case FbxNodeAttribute::eSkeleton: return "skeleton";
case FbxNodeAttribute::eMesh: return "mesh";
case FbxNodeAttribute::eNurbs: return "nurbs";
case FbxNodeAttribute::ePatch: return "patch";
case FbxNodeAttribute::eCamera: return "camera";
case FbxNodeAttribute::eCameraStereo: return "stereo";
case FbxNodeAttribute::eCameraSwitcher: return "camera switcher";
case FbxNodeAttribute::eLight: return "light";
case FbxNodeAttribute::eOpticalReference: return "optical reference";
case FbxNodeAttribute::eOpticalMarker: return "marker";
case FbxNodeAttribute::eNurbsCurve: return "nurbs curve";
case FbxNodeAttribute::eTrimNurbsSurface: return "trim nurbs surface";
case FbxNodeAttribute::eBoundary: return "boundary";
case FbxNodeAttribute::eNurbsSurface: return "nurbs surface";
case FbxNodeAttribute::eShape: return "shape";
case FbxNodeAttribute::eLODGroup: return "lodgroup";
case FbxNodeAttribute::eSubDiv: return "subdiv";
default: return "unknown";
}
}
*/
|
5fb9b8461b75ac3fbf97471b424ebd2c3b767451
|
[
"Markdown",
"C",
"C++"
] | 19 |
C++
|
JeffreyMJohnson/Graphics
|
fed524574c11281a2f0afe21ac6cc9d521930951
|
11d7bed1a457b29b790d5f994a722cf46577f742
|
refs/heads/master
|
<file_sep>'use strict';
const {
utils: {
doOperationInQueue,
javascript: { getQueueId },
stringify,
},
constants: {
aws: { database: { tableNames: { BALANCES, WITHDRAWS } } }
}
} = require( '@bitcoin-api/full-stack-api-private' );
const getFeeData = require( './getFeeData' );
const doWithdrawMoney = require( './doWithdrawMoney' );
module.exports = Object.freeze( async ({ event, user }) => {
console.log( 'running /withdraws - POST function' );
const requestBody = (!!event && !!event.body && event.body) || {};
const rawAmount = (
requestBody.amount
) || null;
const rawShouldIncludeFeeInAmount = (
requestBody.includeFeeInAmount
) || false;
const rawAddress = requestBody.address;
const rawEnviroWithdrawAmount = requestBody.enviroWithdrawAmount;
console.log( `
🐒THE POWER OF NOW🍌🏯!
A withdraw is being attempted,👷🏾♀️
running withdrawMoney, here are the parameters:
${ stringify({
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount
}) }
` );
const feeData = await getFeeData();
const withdrawMoneyResults = await doOperationInQueue({
queueId: getQueueId({ type: WITHDRAWS, id: user.userId }),
doOperation: () => doOperationInQueue({
queueId: getQueueId({ type: BALANCES, id: user.userId }),
doOperation: () => doWithdrawMoney({
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount,
feeData,
user,
}),
}),
});
return withdrawMoneyResults;
});
<file_sep>
'use strict';
const {
constants: {
environment: {
isProductionMode
}
},
utils: {
database: { metadata: { getFeeToPayFromFeeData } },
}
} = require( '@bitcoin-api/full-stack-api-private' );
const stagingTransactionFee = 0.00001000;
module.exports = Object.freeze( ({
blessedWithdraw,
}) => {
const feeEstimateAmount = (
isProductionMode ? getFeeToPayFromFeeData({
feeData: blessedWithdraw.feeData,
shouldReturnAdvancedResponse: true
}).baseFee : stagingTransactionFee
);
return feeEstimateAmount;
});
<file_sep>'use strict';
module.exports = Object.freeze({
formatting: require( './formatting' ),
validation: require( './validation' ),
});
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
// import Button from '@material-ui/core/Button';
// import { story } from '../../../../constants';
// import { setState } from '../../../../reduxX';
// import Link from '@material-ui/core/Link';
// import Typography from '@material-ui/core/Typography';
// import Divider from '@material-ui/core/Divider';
// import LegalSection from './LegalSection';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'green',
width: '90%',
maxWidth: 500,
// minWidth: 300,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
innerBox: {
marginTop: 27,
marginBottom: 27,
// backgroundColor: 'pink',
width: '100%',
height: 710,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.innerBox,
},
e(
'iframe',
{
style: {
touchAction: 'pan-y'
},
frameBorder: '0',
allowFullScreen: false,
// allow: true,
// sandbox: false,
width: '100%',
height: '100%',
src: 'https://master.d2lq8bb1axbb9y.amplifyapp.com/?height=450',
loading: 'lazy',
}
)
)
);
};
// <iframe src="https://www.w3schools.com" title="W3Schools Free Online Web Tutorials"></iframe><file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase,
}
},
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_EMAIL_DELIVERY_RESULTS
}
}
}
},
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
constants: {
exchangeEmailDeliveryResults: {
types: {
success
}
},
verificationCode
}
} = require( '../../../../../../exchangeUtils' );
const searchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
email: '#email',
emailMessageId: '#emailMessageId',
creationDate: '#creationDate',
type: '#type',
}),
nameValues: f({
email: 'email',
emailMessageId: 'emailMessageId',
creationDate: 'creationDate',
type: 'type',
}),
valueKeys: f({
email: ':email',
success: ':success',
searchStartTime: ':searchStartTime',
searchEndTime: ':searchEndTime',
}),
valueValues: f({
success
}),
});
const getIfMessageIdIsValidBasedOnCurrentResults = Object.freeze( ({
exchangeEmailDeliverySuccessResults,
emailMessageId
}) => {
for( const eedr of exchangeEmailDeliverySuccessResults ) {
if( eedr.emailMessageId === emailMessageId ) {
const messageIdIsValidBasedOnCurrentResults = true;
return messageIdIsValidBasedOnCurrentResults;
}
}
const messageIdIsValidBasedOnCurrentResults = false;
return messageIdIsValidBasedOnCurrentResults;
});
module.exports = Object.freeze( async ({
email,
emailMessageId,
expiryDate,
}) => {
console.log(
'running verifyEmailMessageIdIsValid with the ' +
`following values: ${ stringify({
email,
emailMessageId,
expiryDate,
})}`
);
const {
nameKeys,
nameValues,
valueKeys,
valueValues,
} = attributes;
let messageIdIsValid = false;
const searchStartTime = expiryDate - verificationCode.expiryTime;
const searchEndTime = expiryDate - 1;
let paginationValueToUse = null;
do {
const searchParams = {
TableName: EXCHANGE_EMAIL_DELIVERY_RESULTS,
Limit: searchLimit,
ScanIndexForward: false,
ProjectionExpression: [
nameKeys.emailMessageId,
].join( ', ' ),
KeyConditionExpression: (
`${ nameKeys.email } = ${ valueKeys.email } and ` +
`${ nameKeys.creationDate } between ` +
`${ valueKeys.searchStartTime } and ` +
`${ valueKeys.searchEndTime }`
),
FilterExpression: (
`${ nameKeys.type } = ${ valueKeys.success }`
),
ExpressionAttributeNames: {
[nameKeys.email]: nameValues.email,
[nameKeys.emailMessageId]: nameValues.emailMessageId,
[nameKeys.type]: nameValues.type,
[nameKeys.creationDate]: nameValues.creationDate,
},
ExpressionAttributeValues: {
[valueKeys.email]: email,
[valueKeys.success]: valueValues.success,
[valueKeys.searchStartTime]: searchStartTime,
[valueKeys.searchEndTime]: searchEndTime,
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams,
});
const exchangeEmailDeliverySuccessResults = ultimateResults;
const messageIdIsValidBasedOnCurrentResults = (
getIfMessageIdIsValidBasedOnCurrentResults({
exchangeEmailDeliverySuccessResults,
emailMessageId,
})
);
if( messageIdIsValidBasedOnCurrentResults ) {
messageIdIsValid = true;
}
if( !messageIdIsValid && !!paginationValue ) {
paginationValueToUse = paginationValue;
}
else {
paginationValueToUse = null;
}
} while( !!paginationValueToUse );
if( !messageIdIsValid ) {
const error = new Error(
'The provided email verification link has been expired. ' +
'Please try creating your ' +
'account again. Sorry for any inconvenience.'
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
console.log(
'verifyEmailMessageIdIsValid executed successfully -'
);
});
<file_sep>'use strict';
const fs = require( 'fs' );
const safeWriteErrorToFile = Object.freeze( ({
safeErrorReport,
safeErrorsPath
}) => {
const stream = fs.createWriteStream(
safeErrorsPath,
{
flags: 'a'
}
);
stream.write(
`==--==--==--==--==--==--==--==--==--==--==--==--==\n` +
`Safe Error Occurred - ${ (new Date()).toLocaleString() }\n` +
`${ JSON.stringify( safeErrorReport, null, 4 ) }\n` +
`==--==--==--==--==--==--==--==--==--==--==--==--==\n`
);
stream.end();
});
module.exports = Object.freeze( (
{ moduleName = __dirname } = { moduleName: __dirname }
) => {
if( !process.env.SAFE_WRITE_ERROR_FILE_PATH ) {
throw new Error( 'missing SAFE_WRITE_ERROR_PATH env value' );
}
const safeErrorsPath = (
`${ process.env.SAFE_WRITE_ERROR_FILE_PATH }/safeErrors.txt`
);
const safeWriteError = Object.freeze( err => {
console.log( 'running safeWriteError with err:', err );
console.log( 'safeErrorsPath:', safeErrorsPath );
try {
const now = new Date();
const safeErrorReport = {
moduleName,
moduleDirname: __dirname,
moduleFilename: __filename,
name: err.name,
className: err.className,
class: err.class,
status: err.status,
statusCode: err.statusCode,
code: err.code,
message: err.message,
stack: err.stack,
type: err.type,
typeOf: typeof err,
instanceOfError: err instanceof Error,
powerOfNow: now.getTime(),
powerOfNowString: now.toLocaleString(),
shortMessage: err.shortMessage,
command: err.command,
exitCode: err.exitCode,
signal: err.signal,
signalDescription: err.signalDescription,
stdout: err.stdout,
stderr: err.stderr,
failed: err.failed,
timedOut: err.killed,
isCanceled: err.isCanceled,
killed: err.killed
};
safeWriteErrorToFile({
safeErrorReport,
safeErrorsPath
});
console.log( 'safeWriteError executed successfully' );
}
catch( errInWritingSafeError ) {
console.log(
'an error occur in writing safe error:', errInWritingSafeError
);
}
});
return safeWriteError;
});
<file_sep>'use strict';
const {
transactions: {
transactionId: {
prefix,
minLength,
maxLength
}
}
} = require( '../../constants' );
module.exports = Object.freeze( ({
transactionId,
}) => {
const transactionIdIsValid = (
!!transactionId &&
(typeof transactionId === 'string') &&
transactionId.startsWith( prefix ) &&
(transactionId.length >= minLength) &&
(transactionId.length <= maxLength)
);
return transactionIdIsValid;
});
<file_sep>'use strict';
const getOrAssignAddressData = require( './getOrAssignAddressDatum' );
const runWalhallaAddressMode = require( './runWalhallaAddressMode' );
const {
getFormattedEvent,
beginningDragonProtection,
getResponse,
handleError,
stringify
} = require( '../../../utils' );
const fiveMiniutes = 5 * 60 * 1000;
exports.handler = Object.freeze( async rawEvent => {
console.log( 'running /addresses - POST function' );
try {
const event = getFormattedEvent({
rawEvent,
shouldGetBodyFromEvent: true,
});
const isWalhallaAddressMode = (
!!event.body &&
!!event.body.walhallaAddressMode &&
(
event.body.walhallaAddressMode ===
process.env.WALHALLA_ADDRESS_MODE_SECRET
) &&
!!event.body.exchangeUserId &&
(typeof event.body.exchangeUserId === 'string') &&
(event.body.exchangeUserId.length > 5) &&
(event.body.exchangeUserId.length < 75)
);
if( isWalhallaAddressMode ) {
console.log(
'/addresses - POST function running Walhalla Address Mode🏛'
);
const walhallaAddressModeResults = await runWalhallaAddressMode({
event,
});
const results = Object.assign(
{},
walhallaAddressModeResults || {}
);
const response = getResponse({ body: results });
console.log(
'/addresses - POST function ' +
'Walhalla Address Mode🏛 ' +
'executed successfully ' +
`returning values: ${ stringify( response ) }`
);
return response;
}
const { user } = await beginningDragonProtection({
queueName: 'getAddress',
event,
necessaryDragonDirective: 2,
ipAddressMaxRate: 15,
ipAddressTimeRange: fiveMiniutes,
advancedCodeMaxRate: 15,
advancedCodeTimeRange: fiveMiniutes,
});
const responseBody = await getOrAssignAddressData({ user });
const response = getResponse({ body: responseBody });
console.log(
'/addresses - POST function executed successfully ' +
`returning values: ${ stringify( response ) }`
);
return response;
}
catch( err ) {
console.log( 'error in request to /addresses - POST:', err );
return handleError( err );
}
});
<file_sep>#!/bin/sh
version="$1"
####
#### Common Code
####
pushd ../../../../0-commonCode/api
npm version "$version"
popd
pushd ../../../../0-commonCode/exchange
npm version "$version"
popd
####
#### Backend
####
pushd ../../../../1-backend/commonUtilities
npm version "$version"
popd
# ####
# #### Backend Giraffe Lick Leaf
# ####
pushd ../../../../1-backend/giraffeDeploy/commonUtilities
npm version "$version"
popd
<file_sep>'use strict';
// Part of https://gist.github.com/vlucas/2bd40f62d20c1d49237a109d491974eb
const crypto = require( 'crypto' );
const algorithm = 'aes-256-cbc';
const IV_LENGTH = 16; // For AES, this is always 16
const ValidationError = require( '../errors/ValidationError' );
const {
encryptionIdToEncryptionPassword,
} = require( '../theKeys' );
const encrypt = Object.freeze( ({
text,
encryptionId
}) => {
const encryptionPassword = encryptionIdToEncryptionPassword[
encryptionId
];
if( !encryptionPassword ) {
const errorMessage = (
`invalid encryptionId: ${ encryptionId }`
);
throw new ValidationError( errorMessage );
}
const iv = crypto.randomBytes( IV_LENGTH );
const cipher = crypto.createCipheriv(
algorithm,
Buffer.from( encryptionPassword ),
iv
);
const encrypted = cipher.update( text );
const encryptedFinalForm = Buffer.concat( [ encrypted, cipher.final() ] );
const encryptedText = (
`${ iv.toString('hex') }:${ encryptedFinalForm.toString('hex') }`
);
return encryptedText;
});
const decrypt = Object.freeze( ({
text,
encryptionId
}) => {
const decryptPassword = encryptionIdToEncryptionPassword[ encryptionId ];
if( !decryptPassword ) {
const errorMessage = (
`invalid encryptionId: ${ encryptionId }`
);
throw new ValidationError( errorMessage );
}
const textParts = text.split(':');
const iv = Buffer.from( textParts.shift(), 'hex' );
const encryptedText = Buffer.from( textParts.join(':'), 'hex' );
const decipher = crypto.createDecipheriv(
algorithm,
Buffer.from( decryptPassword ),
iv
);
const decrypted = decipher.update( encryptedText );
const decryptedFinalForm = Buffer.concat(
[ decrypted, decipher.final() ]
);
const decryptedText = decryptedFinalForm.toString();
return decryptedText;
});
module.exports = Object.freeze({
encrypt,
decrypt,
});
<file_sep>import { createElement as e } from 'react';
import { setState } from '../../reduxX';
import { story } from '../../constants';
// import { usefulComponents } from '..';
// import login from './login';
import Box from '@material-ui/core/Box';
// import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'green',
// width: '90%',
// borderRadius: 4,
display: 'flex',
lineHeight: 1.5,
// display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginTop: 20,
width: '100%',
// textAlign: 'left',
textAlign: 'center',
},
innerContainer: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center',
// marginTop: 20,
width: '95%',
// textAlign: 'left',
// textAlign: 'left',
},
text: {
fontSize: 14,
width: '52%',
},
linkText: {
fontSize: 14,
color: 'lightblue',
width: '48%',
cursor: 'pointer',
}
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.innerContainer,
},
e(
'div',
{
style: styles.text,
},
'Forgot your password?'
),
e(
'div',
{
style: styles.linkText,
onClick: () => {
setState(
[
'notLoggedInMode',
'mainMode'
],
story
.NotLoggedInMode
.mainModes
.forgotMyPasswordMode
);
},
},
'Reset My Password'
)
)
);
};
<file_sep>export default ({
time = Date.now(),
} = {
time: Date.now(),
}) => {
// new Date( year, month, day, hours, minutes, seconds, milliseconds );
const date = new Date( time );
const startOfDayDate = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate()
);
const startOfDayTime = startOfDayDate.getTime();
const dayData = {
time,
date,
startOfDayDate,
startOfDayTime,
};
return dayData;
};
<file_sep>'use strict';
const {
utils: {
stringify,
bitcoin: {
formatting: {
getAmountNumber
},
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const { doBitcoinRequest } = require( '@bitcoin-api/full-stack-backend-private' );
const errorTypes = Object.freeze({
invalidAddressError: 'invalidAddressError',
invalidMoneyInNode: 'invalidMoneyInNode',
unexpectedIssueInWithdraw: 'unexpectedIssueInWithdraw',
});
const getErrorType_LogSuccessAndReturnResponse = Object.freeze( ({
errorType
}) => {
console.log(
(
'withdrawBitcoinFromNode - ' +
'getErrorType executed successfully, ' +
'returning ' +
'error type:'
),
errorType
);
return errorType;
});
const getErrorType = Object.freeze( ({ err }) => {
console.log(
'running withdrawBitcoinFromNode - getErrorType on error:', err
);
const exitCode = Math.abs(
Number(
!!err &&
err.exitCode
)
);
if( exitCode === 5 ) {
return getErrorType_LogSuccessAndReturnResponse({
errorType: errorTypes.invalidAddressError,
});
}
else if( [ 4, 6 ].includes( exitCode ) ) {
return getErrorType_LogSuccessAndReturnResponse({
errorType: errorTypes.invalidMoneyInNode,
});
}
return getErrorType_LogSuccessAndReturnResponse({
errorType: errorTypes.unexpectedIssueInWithdraw,
});
});
module.exports = Object.freeze( async ({
addressToSendTo,
amount,
shouldIncludeFeeInAmount
}) => {
console.log(`
performing withdrawBitcoinFromNode
with the following values: ${
stringify({
addressToSendTo,
amount,
shouldIncludeFeeInAmount
})
}
`);
const amountNumber = getAmountNumber( amount );
const comment = '';
const commentTo = '';
const withdrawMoneyArgs = [
'sendtoaddress',
addressToSendTo,
amountNumber,
comment,
commentTo
];
if( shouldIncludeFeeInAmount ) {
const subtractFeeFromAmount = true;
withdrawMoneyArgs.push( subtractFeeFromAmount );
}
const {
invalidAddressErrorOccurred = false,
notEnoughMoneyErrorOccurred = false,
transactionId = null,
} = await doBitcoinRequest({ args: withdrawMoneyArgs }).then(
transactionId => {
console.log(
'withdrawBitcoinFromNode executed successfully, ' +
`the transactionId is "${ transactionId }".`
);
return {
transactionId,
};
}, err => {
const errorType = getErrorType({ err });
console.log(
'withdrawBitcoinFromNode',
'error in withdrawing bitcoins:',
err,
stringify({ errorType })
);
if( errorType === errorTypes.invalidAddressError ) {
console.log(
'withdrawBitcoinFromNode executed successfully ' +
'- invalid withdraw address'
);
return {
invalidAddressErrorOccurred: true,
};
}
else if( errorType === errorTypes.invalidMoneyInNode ) {
console.log(
'withdrawBitcoinFromNode executed successfully - ' +
'broke case - The bitcoin node does not have ' +
'enough money.'
);
return {
notEnoughMoneyErrorOccurred: true,
};
}
console.log( 'error in withdrawBitcoinFromNode:', err );
throw err;
}
);
return {
invalidAddressErrorOccurred,
notEnoughMoneyErrorOccurred,
transactionId,
};
});
<file_sep>'use strict';
const execa = require( 'execa' );
const pemPath = process.env.PEM_PATH;
const lickFileDestinationUrl = process.env.LICK_FILE_DESTINATION;
const tigerHomeDestinationPath = process.env.TIGER_HOME_DESTINATION_PATH;
module.exports = Object.freeze( async ({
pathToLickFile,
}) => {
console.log( 'running sendLickFile' );
const fullDestinationUrl = (
`${ lickFileDestinationUrl }:${ tigerHomeDestinationPath }/treeDeploy`
);
const execaInstance = execa(
'scp',
[
'-i',
pemPath,
pathToLickFile,
fullDestinationUrl
]
);
execaInstance.stdout.pipe( process.stdout );
execaInstance.stderr.pipe( process.stderr );
await execaInstance;
console.log( 'sendLickFile executed successfully' );
});
<file_sep>'use strict';
const {
utils: {
// doOperationInQueue,
// javascript: { getQueueId },
aws: {
dino: {
getDatabaseEntry,
updateDatabaseEntry,
},
},
stringify
},
constants: {
aws: {
database: {
tableNames: { ADDRESSES },
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
// idempotent
module.exports = Object.freeze( async ({
userId,
address,
amount,
// TODO: remove lock, unnecessary
}) => {
// {
// doOperationInQueue({
// queueId: getQueueId({
// type: ADDRESSES,
// id: userId
// }),
// doOperation: async () =>
console.log(
'running updateAddressAmount with the following values ' +
stringify({
userId,
address,
amount
})
);
const existingAddressDataFresh = await getDatabaseEntry({
tableName: ADDRESSES,
value: userId,
sortValue: address
});
// safeguard
if( !existingAddressDataFresh ) {
console.log(
'weird case, attempting to update address that has ' +
'been (most likely) reclaimed - no-op'
);
return;
}
const newAddressData = Object.assign(
{},
existingAddressDataFresh,
{
amount
}
);
await updateDatabaseEntry({
tableName: ADDRESSES,
entry: newAddressData
});
console.log( 'updateAddressAmount executed successfully' );
});
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
validation: {
getIfTransactionIdIsValid,
getIfExchangeUserIdIsValid,
// getIfRaffleDrawIdIsValid
},
constants: {
transactions: {
transactionId: { prefix }
}
}
} = require( '../../../../../../../exchangeUtils' );
const {
raffle: {
getIfRaffleIdIsValid,
// getIfRaffleDrawIdIsValid
},
} = require( '../../../../../../../enchantedUtils' );
const getDecryptedPseudoSpecialId = require( './getDecryptedPseudoSpecialId' );
// const {
// constants: {
// timeNumbers
// }
// } = require( '../../../../../../utils' );
const minimumTime = 1;
const maximumTime = 9604340079791;
const getIfIsValidTime = Object.freeze( ({
time,
}) => {
const timeIsValid = (
!Number.isNaN( time ) &&
(time >= minimumTime) &&
(time <= maximumTime)
);
return timeIsValid;
});
const throwMissingPageInfoError = Object.freeze( () => {
const validationError = new Error(
'missing required values: ' +
'time, powerId, and specialId all need to be defined'
);
validationError.bulltrue = true;
validationError.statusCode = 400;
throw validationError;
});
module.exports = Object.freeze( ({
rawRaffleId,
rawTime,
rawPowerId,
rawSpecialId,
}) => {
console.log(
`running validateAndGetValues with the following values - ${
stringify({
rawRaffleId,
rawTime,
rawPowerId,
rawSpecialId,
})
}`
);
if( !getIfRaffleIdIsValid({ raffleId: rawRaffleId }) ) {
const validationError = new Error(
`invalid raffleId: ${ rawRaffleId }`
);
validationError.bulltrue = true;
validationError.statusCode = 400;
throw validationError;
}
const values = {
raffleId: rawRaffleId,
};
if( !!rawTime ) {
const time = Number( rawTime );
if( !getIfIsValidTime({ time }) ) {
const validationError = new Error(
`invalid time: ${ time }`
);
validationError.bulltrue = true;
validationError.statusCode = 400;
throw validationError;
}
if( !rawPowerId || !rawSpecialId ) {
return throwMissingPageInfoError();
}
values.time = time;
}
if( !!rawPowerId ) {
const transactionId = `${ prefix }${ rawPowerId }`;
if( !getIfTransactionIdIsValid({ transactionId }) ) {
const validationError = new Error(
`invalid powerId: ${ rawPowerId }`
);
validationError.bulltrue = true;
validationError.statusCode = 400;
throw validationError;
}
if( !rawTime || !rawSpecialId ) {
return throwMissingPageInfoError();
}
values.transactionId = transactionId;
}
if( !!rawSpecialId ) {
if( typeof rawSpecialId !== 'string' ) {
const validationError = new Error(
`invalid specialId: ${ rawSpecialId }`
);
validationError.bulltrue = true;
validationError.statusCode = 400;
throw validationError;
}
const decryptedPseudoSpecialId = getDecryptedPseudoSpecialId({
rawSpecialId,
});
if(
!getIfExchangeUserIdIsValid({
exchangeUserId: rawSpecialId,
})
) {
const validationError = new Error(
`invalid specialId: ${ rawSpecialId }`
);
validationError.bulltrue = true;
validationError.statusCode = 400;
throw validationError;
}
if( !rawTime || !rawPowerId ) {
return throwMissingPageInfoError();
}
values.specialId = rawSpecialId;
}
console.log(
`validateAndGetValues executed successfully,
returning values - ${ stringify( values )
}`
);
return values;
});
<file_sep>import { createElement as e /*, useState, useEffect*/ } from 'react';
import Box from '@material-ui/core/Box';
import TitleBar from './TitleBar';
import ReferralSpace from './ReferralSpace';
// import Typography from '@material-ui/core/Typography';
// import { getState } from '../../reduxX';
// import componentDidMount from './componentDidMount';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
backgroundColor: 'beige',
width: '100%',
maxWidth: 620,
// height: 50,
marginTop: 20,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e( TitleBar ),
e( ReferralSpace )
);
};
<file_sep>
'use strict';
const {
constants: {
withdraws: {
states: {
// pending,
verifying,
// waiting,
realDealing
},
},
aws: { database: { tableNames: { WITHDRAWS } } },
},
utils: {
database: {
metadata: {
getFeeData
}
},
doOperationInQueue,
// javascript: {
// getQueueId
// },
aws: {
dino: {
getDatabaseEntry,
updateDatabaseEntry
},
},
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const getTheActualFee = require( './getTheActualFee' );
const {
getFeeEstimateAmount
} = require( '../../utils' );
module.exports = Object.freeze( async ({
userId,
ultraKey,
getQueueId,
idForGetQueueId,
}) => {
console.log(
'running realDealTheWithdraw for withdraw: ' +
stringify({
userId: userId,
ultraKey: ultraKey
})
);
await doOperationInQueue({
queueId: getQueueId({ type: WITHDRAWS, id: idForGetQueueId }),
doOperation: async () => {
const blessedWithdraw = await getDatabaseEntry({
tableName: WITHDRAWS,
value: userId,
sortValue: ultraKey
});
if(
!blessedWithdraw ||
(blessedWithdraw.state !== realDealing)
) {
throw new Error(
'realDealTheWithdraw - ' +
`invalid blessed withdraw ${
stringify( blessedWithdraw )
}`
);
}
const feeEstimateAmount = getFeeEstimateAmount({
blessedWithdraw
});
const actualFee = await getTheActualFee({
transactionId: blessedWithdraw.transactionId,
});
const itsTimeForARealDeal = actualFee < feeEstimateAmount;
console.log(`
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Real Deal the Withdraw
--------------------------------------------------------------------------------
🌳 fee estimate amount => ${ feeEstimateAmount }
🌳 actual fee => ${ actualFee }
--------------------------------------------------------------------------------
Is it time for a real deal? ${ itsTimeForARealDeal ? 'yes' : 'no' }
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
`);
const valuesToMerge = {};
if( itsTimeForARealDeal ) {
const newFeeData = getFeeData({
fee: actualFee,
feeMultiplier: 1,
megaServerId: blessedWithdraw.feeData.bitcoinNodeUrl,
noKeyProperty: true,
businessFeeData: blessedWithdraw.feeData.businessFeeData,
});
Object.assign(
valuesToMerge,
{
feeData: newFeeData,
metadataToAdd: {
realDealData: {
previousFeeData: blessedWithdraw.feeData,
newFeeData,
timeOfRealDealFeeDataChange: Date.now(),
},
timeOfVerifyStateSet: Date.now(),
about: 'successful withdraw with fee refund',
}
}
);
}
else {
Object.assign(
valuesToMerge,
{
metadataToAdd: {
realDealData: {
previousFeeData: blessedWithdraw.feeData,
actualFee,
timeOfRealDealFeeDataAnalysis: Date.now(),
noRealDeal: true,
},
timeOfVerifyStateSet: Date.now(),
about: 'successful withdraw',
}
}
);
}
const newWithdrawDatabaseEntry = Object.assign(
{},
blessedWithdraw,
{
state: verifying,
},
valuesToMerge
);
await updateDatabaseEntry({
tableName: WITHDRAWS,
entry: newWithdrawDatabaseEntry
});
},
});
console.log(
'realDealTheWithdraw executed successfully for: ' +
stringify({
userId: userId,
ultraKey: ultraKey
})
);
});
<file_sep>'use strict';
require( 'dotenv' ).config({ path: '../.env' });
const axios = require( 'axios' );
(async () => {
try {
const axiosInstance = axios.create({
baseURL: `http://localhost:${ process.env.PORT }`,
});
const apiCallResults = await axiosInstance.get( '/' );
console.log(
'results:',
JSON.stringify( {
status: apiCallResults.status,
data: apiCallResults.data,
}, null, 4 )
);
}
catch( err ) {
console.log(
'an error occured:',
JSON.stringify( {
message: err.message,
statusCode: err.response.status,
}, null, 4 )
);
}
})();
<file_sep>import { createElement as e } from 'react';
// import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import { moneyActions } from '../../../../constants';
const getStyles = ({
dialogMode
}) => {
const {
color,
} = dialogMode ? {
color: 'white',
} : {
color: 'black',
};
return {
amountText: {
color,
fontSize: 14,
marginLeft: 5,
marginTop: 3,
},
};
};
export default ({
excitingElements,
moneyAction,
dialogMode,
}) => {
const styles = getStyles({
dialogMode
});
if(
[
moneyActions.types.regal.addressAmountUpdate,
moneyActions.types.regal.withdraw.start,
moneyActions.types.regal.withdraw.success,
moneyActions.types.regal.withdraw.failed,
].includes( moneyAction.type )
) {
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
`address: ${ moneyAction.address }`
)
);
}
};<file_sep>import { createElement as e, useEffect } from 'react';
import { getState } from '../../../reduxX';
import { usefulComponents } from '../../../TheSource';
import VoteStation from './VoteStation';
import componentDidMount from './componentDidMount';
import Paper from '@material-ui/core/Paper';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Divider from '@material-ui/core/Divider';
const getStyles = () => {
const {
backgroundColor,
} = getState( 'mainStyleObject' );
return {
outerContainer: {
width: 300,
// height: 200,
backgroundColor,
// borderRadius: 25,
// borderStyle: 'solid',
// borderWidth: 5,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
// color: 'white',
marginTop: 20,
},
titleTextBox: {
width: '100%',
backgroundColor: 'beige',
},
titleText: {
paddingTop: 10,
paddingBottom: 10,
color: 'black',
fontSize: 16,
textAlign: 'center',
// padding: 15,
},
divider: {
backgroundColor: 'black',
width: '100%',
},
divider2: {
backgroundColor: 'black',
width: '100%',
marginBottom: 30,
}
};
};
const staticVoteData = {
voteId: 'usaElection',
votingPeriodEnd: Date.now() + (360 * 60 * 1000),
// votingPeriodEnd: Date.now() - (360 * 60 * 1000),
choiceToChoiceData: {
trump: {
image: 'https://computerstorage.s3.amazonaws.com/images/trump-choice.jpg'
},
biden: {
image: 'https://computerstorage.s3.amazonaws.com/images/biden-choice.jpg'
}
}
};
export default () => {
const {
voteId,
votingPeriodEnd,
choiceToChoiceData,
} = staticVoteData;
const userData = getState( 'loggedInMode', 'userData' );
useEffect( () => {
Promise.resolve().then( async () => {
await componentDidMount({ voteId });
});
}, [ voteId, userData ] );
const styles = getStyles();
const mainElements = [
e(
Box,
{
style: styles.titleTextBox
},
e(
Typography,
{
style: styles.titleText
},
'Vote for 2020 Presidential Candidate'
),
e(
Divider,
{
style: styles.divider,
}
),
e(
usefulComponents.crypto.CurrentAmount,
{
width: '100%',
height: 60,
}
),
e(
Divider,
{
style: styles.divider2,
}
)
),
];
const localError = getState( 'presidentialVote2020', 'localError' );
if( !!localError ) {
mainElements.push(
e(
Box,
{
style: styles.titleText
},
'Error'
)
);
}
else {
const choiceInput = getState( 'presidentialVote2020', 'choiceInput' );
const currentChoice = getState( 'presidentialVote2020', 'currentChoice' );
const currentVoteType = getState( 'presidentialVote2020', 'currentVoteType' );
const currentAmount = getState( 'presidentialVote2020', 'currentAmount' );
const currentMetadata = getState( 'presidentialVote2020', 'currentMetadata' );
mainElements.push(
e(
VoteStation,
{
voteId,
choiceInput,
currentChoice,
currentVoteType,
currentAmount,
currentMetadata,
votingPeriodEnd,
choiceToChoiceData,
}
)
);
}
return e(
Paper,
{
style: styles.outerContainer,
},
...mainElements
);
};
<file_sep>'use strict';
const {
utils: {
redis: {
doRedisFunction,
},
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
giraffeAndTreeStatusUpdate,
constants
} = require( '@bitcoin-api/giraffe-utils' );
const resetTotalTempTigerDomain = require( './resetTotalTempTigerDomain' );
const log = Object.freeze( ( ...args ) => {
console.log( '🎄📫doPostInitializationAction (tree🌴) - ', ...args );
});
module.exports = Object.freeze( ({
deployId,
deployCommand
}) => async () => {
log(
'running leaf feel tongue doPostInitializationAction function ' +
'with the following values:',
stringify({
deployId,
deployCommand
})
);
await resetTotalTempTigerDomain({
log,
});
await doRedisFunction({
performFunction: async ({
redisClient
}) => {
await giraffeAndTreeStatusUpdate({
redisClient,
eventName: constants.eventNames.leaf.tongueFeel,
// eventName: constants.eventNames.giraffe.lick,
information: {
deployId,
eventOrder: 1,
deployCommand
}
});
},
functionName: 'leaf feel tongue'
});
log(
'leaf feel tongue doPostInitializationAction function ' +
'executed successfully'
);
});
<file_sep>cd
rm -rf tigerScript
mkdir tigerScript
mkdir tigerScript/addressGenerator
mkdir tigerScript/feeDataBot
mkdir tigerScript/withdrawsBot
mkdir tigerScript/depositsBot
mkdir tigerScript/productionCredentials/addressGenerator
mkdir tigerScript/productionCredentials/feeDataBot
mkdir tigerScript/productionCredentials/withdrawsBot
mkdir tigerScript/productionCredentials/depositsBot
mkdir tigerScript/stagingCredentials/addressGenerator
mkdir tigerScript/stagingCredentials/feeDataBot
mkdir tigerScript/stagingCredentials/withdrawsBot
mkdir tigerScript/stagingCredentials/depositsBot
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
// import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import GameBox from './GameBox';
import { games } from '../../../../constants';
import { getState } from '../../../../reduxX';
const getStyles = () => {
const windowWidth = getState( 'windowWidth' );
return {
outerContainer: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
width: '100%',
maxWidth: 600,
// height: 300,
marginTop: 25,
marginBottom: 25,
// backgroundColor: 'green',
},
titleTextContainer: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
width: '100%',
// maxWidth: 600,
// height: 300,
// backgroundColor: 'green',
},
titleText: {
width: '100%',
textAlign: 'center',
fontSize: 22,
marginTop: 22,
// textDecoration: 'underline',
// height: 300,
// backgroundColor: 'green',
},
gameBoxGrid: (windowWidth > 650) ? {
width: '100%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
} : {
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
gameBox: {
width: 250,
height: 250,
backgroundColor: 'beige',
marginTop: 20,
marginBottom: 20,
alignSelf: 'center'
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.titleTextContainer,
},
e(
Typography,
{
style: styles.titleText,
},
'Game Previews'
)
),
e(
Box,
{
style: styles.gameBoxGrid,
},
e(
GameBox,
{
nameOfTheGame: 'Satoshi Slot',
// smallButtonText: true,
// noActionOnClick: true,
gameStateName: games.slot,
mainScreen: e(
Box,
{
style: {
borderRadius: 10,
width: 250,
height: 216,
backgroundColor: 'beige',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}
},
e(
Typography,
{
style: {
// marginTop: 18,
width: '100%',
fontSize: 125,
textAlign: 'center',
userSelect: 'none',
}
},
'🎰'
)
)
}
),
e(
GameBox,
{
// nameOfTheGame: `The Dragon's Talisman`,
nameOfTheGame: `The Dragon's Talisman`,
gameStateName: games.theDragonsTalisman,
backgroundColor: 'green',
mainScreen: e(
Box,
{
style: {
borderRadius: 10,
width: 250,
height: 216,
backgroundColor: 'green',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}
},
e(
Box,
{
style: {
width: 200,
height: 200,
borderRadius: '50%',
backgroundColor: 'lightgreen',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center'
}
},
e(
Typography,
{
style: {
marginTop: 18,
width: '100%',
fontSize: 125,
textAlign: 'center',
userSelect: 'none',
}
},
'🐲'
)
)
)
}
)
)
);
};
<file_sep>import { createElement as e } from 'react';
import Drawer from '@material-ui/core/Drawer';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Divider from '@material-ui/core/Divider';
import { getState, setState } from '../../reduxX';
import { story } from '../../constants';
import { actions } from '../../utils';
const getStyles = () => {
const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: mainStyleObject.backgroundColor,
width: '100%',
// height: 200,
display: 'flex',
flexDirection: 'column',
// justifyContent: 'space-between',
// alignItems: 'center',
justifyContent: 'flex-start',
alignItems: 'center',
color: 'white',
},
listItem: {
width: 200
},
};
};
const UltraListItem = ({
isLoading,
style,
mode,
text,
isDesktopMode = false
}) => {
return e(
ListItem,
{
disabled: isLoading,
button: true,
style,
onClick: () => {
const setStateArgs = [
{
keys: [
'loggedInMode',
'mode',
],
value: mode
},
];
if( !isDesktopMode ) {
setStateArgs.push({
keys: [
'loggedInMode',
'drawerIsOpen',
],
value: false
});
}
setState( ...setStateArgs );
},
},
e(
ListItemText,
{
primary: text,
}
)
);
};
export default Object.freeze( () => {
const drawerIsOpen = getState(
'loggedInMode',
'drawerIsOpen'
);
const styles = getStyles();
const isLoading = getState( 'isLoading' );
// TODO: add close button in large mode
const windowWidth = getState( 'windowWidth' );
const isDesktopMode = (windowWidth > 1025);
return e(
Drawer,
{
variant: isDesktopMode ? 'persistent' : undefined,
anchor: 'right',
open: drawerIsOpen,
onClose: () => {
setState(
[
'loggedInMode',
'drawerIsOpen'
],
false
);
},
},
e(
UltraListItem,
{
isLoading,
style: styles.listItem,
mode: story.LoggedInMode.modes.base,
isDesktopMode,
text: 'Home',
}
),
e(
UltraListItem,
{
isLoading,
style: styles.listItem,
mode: story.LoggedInMode.modes.exchange,
isDesktopMode,
text: 'Exchange',
}
),
e(
UltraListItem,
{
isLoading,
style: styles.listItem,
mode: story.LoggedInMode.modes.coinFlip,
isDesktopMode,
text: 'Talisman Toss',
}
),
e(
UltraListItem,
{
isLoading,
style: styles.listItem,
mode: story.LoggedInMode.modes.slot,
isDesktopMode,
text: 'Satoshi Slot',
}
),
e(
UltraListItem,
{
isLoading,
style: styles.listItem,
mode: story.LoggedInMode.modes.withdraw,
isDesktopMode,
text: 'Withdraw',
}
),
e(
UltraListItem,
{
isLoading,
style: styles.listItem,
mode: story.LoggedInMode.modes.destinyRaffle,
isDesktopMode,
text: 'Feed',
}
),
// e(
// UltraListItem,
// {
// isLoading,
// style: styles.listItem,
// mode: story.LoggedInMode.modes.settings,
// isDesktopMode,
// text: 'Settings',
// }
// ),
e(
Divider,
{
style: {
backgroundColor: 'black'
}
}
),
e(
ListItem,
{
button: true,
disabled: isLoading,
style: styles.listItem,
onClick: async () => {
await actions.signOut();
},
},
e(
ListItemText,
{
primary: 'Logout',
}
)
)
);
});<file_sep>'use strict';
const {
runSpiritual,
mongo,
constants: {
mongo: {
collectionNames
}
},
backgroundExecutor
} = require( '@bitcoin-api/full-stack-backend-private' );
const {
constants: {
computerServerServiceNames: {
juiceCamel
}
},
utils: {
javascript: {
getIfEnvValuesAreValid
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const getCanonicalAddressData = require( './getCanonicalAddressData' );
const updateAddressData = require( './updateAddressData' );
const updateUserBalanceData = require( './updateUserBalanceData' );
const serviceName = juiceCamel;
getIfEnvValuesAreValid([
{
type: getIfEnvValuesAreValid.envValidationTypes.string,
key: 'MONGO_DB_URL'
},
{
type: getIfEnvValuesAreValid.envValidationTypes.string,
key: 'REDIS_URL'
},
]);
const getSpiritual = Object.freeze( ({
mongoConnectResults,
}) => Object.freeze( async () => {
console.log(
'***** Running updateTransactionData *****🐉🐉🐉🐉'
);
const mongoCollections = mongoConnectResults.collections;
const canonicalAddressData = await getCanonicalAddressData();
const {
userIdToBitcoinNodeAmountIn
} = await updateAddressData({
canonicalAddressData,
mongoCollections
});
await updateUserBalanceData({
userIdToBitcoinNodeAmountIn,
mongoCollections
});
console.log(
'***** updateTransactionData ' +
'executed successfully *****🐉🐉🐉🐉🔥🔥🔥🔥'
);
}));
module.exports = Object.freeze( async () => {
try {
backgroundExecutor.start();
const mongoConnectResults = await mongo.connect({
collectionNames: [
collectionNames.address_data,
collectionNames.user_data,
]
});
const spiritual = getSpiritual({
mongoConnectResults
});
await runSpiritual({
spiritual,
serviceName,
});
}
catch( err ) {
const errorMessage = (
`error in bitcoin runUpdateTransactionDataWorker: ${ err }`
);
console.error( errorMessage );
console.error( err.stack );
}
});<file_sep>'use strict';
module.exports = Object.freeze( ({
passwordResetCodeLink,
appName = 'DynastyBitcoin.com',
}) => {
const emailHtml = (
`<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>${ appName } Password Reset</title>
<style>
/* -------------------------------------
GLOBAL RESETS
email template source: https://github.com/leemunroe/responsive-html-email-template
------------------------------------- */
/*All the styling goes here*/
img {
border: none;
-ms-interpolation-mode: bicubic;
max-width: 100%;
}
body {
background-color: #f6f6f6;
font-family: sans-serif;
-webkit-font-smoothing: antialiased;
font-size: 14px;
line-height: 1.4;
margin: 0;
padding: 0;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
table {
border-collapse: separate;
mso-table-lspace: 0pt;
mso-table-rspace: 0pt;
width: 100%; }
table td {
font-family: sans-serif;
font-size: 14px;
vertical-align: top;
}
/* -------------------------------------
BODY & CONTAINER
------------------------------------- */
.body {
background-color: #f6f6f6;
width: 100%;
}
/* Set a max-width, and make it display as block so it will automatically stretch to that width, but will also shrink down on a phone or something */
.container {
display: block;
margin: 0 auto !important;
/* makes it centered */
max-width: 580px;
padding: 10px;
width: 580px;
}
/* This should also be a block element, so that it will fill 100% of the .container */
.content {
box-sizing: border-box;
display: block;
margin: 0 auto;
max-width: 580px;
padding: 10px;
}
/* -------------------------------------
HEADER, FOOTER, MAIN
------------------------------------- */
.main {
background: #ffffff;
border-radius: 3px;
width: 100%;
}
.wrapper {
box-sizing: border-box;
padding: 20px;
}
.content-block {
padding-bottom: 10px;
padding-top: 10px;
}
.footer {
clear: both;
margin-top: 10px;
text-align: center;
width: 100%;
}
.footer td,
.footer p,
.footer span,
.footer a {
color: #999999;
font-size: 11px;
text-align: center;
}
/* -------------------------------------
TYPOGRAPHY
------------------------------------- */
h1,
h2,
h3,
h4 {
color: #000000;
font-family: sans-serif;
font-weight: 400;
line-height: 1.4;
margin: 0;
margin-bottom: 30px;
}
h1 {
font-size: 35px;
font-weight: 300;
text-align: center;
text-transform: capitalize;
}
p,
ul,
ol {
font-family: sans-serif;
font-size: 14px;
font-weight: normal;
margin: 0;
margin-bottom: 15px;
}
p li,
ul li,
ol li {
list-style-position: inside;
margin-left: 5px;
}
a {
color: #3498db;
text-decoration: underline;
}
/* -------------------------------------
BUTTONS
------------------------------------- */
.btn {
box-sizing: border-box;
width: 100%; }
.btn > tbody > tr > td {
padding-bottom: 15px; }
.btn table {
width: auto;
}
.btn table td {
background-color: #ffffff;
border-radius: 5px;
text-align: center;
}
.btn a {
background-color: #ffffff;
border: solid 1px #3498db;
border-radius: 5px;
box-sizing: border-box;
color: #3498db;
cursor: pointer;
display: inline-block;
font-size: 14px;
font-weight: bold;
margin: 0;
padding: 12px 25px;
text-decoration: none;
text-transform: capitalize;
}
.btn-primary table td {
background-color: #3498db;
}
.btn-primary a {
background-color: #3498db;
border-color: #3498db;
color: #ffffff;
}
/* -------------------------------------
OTHER STYLES THAT MIGHT BE USEFUL
------------------------------------- */
.last {
margin-bottom: 0;
}
.first {
margin-top: 0;
}
.align-center {
text-align: center;
}
.align-right {
text-align: right;
}
.align-left {
text-align: left;
}
.clear {
clear: both;
}
.mt0 {
margin-top: 0;
}
.mb0 {
margin-bottom: 0;
}
.preheader {
color: transparent;
display: none;
height: 0;
max-height: 0;
max-width: 0;
opacity: 0;
overflow: hidden;
mso-hide: all;
visibility: hidden;
width: 0;
}
.powered-by a {
text-decoration: none;
}
hr {
border: 0;
border-bottom: 1px solid #f6f6f6;
margin: 20px 0;
}
/* -------------------------------------
RESPONSIVE AND MOBILE FRIENDLY STYLES
------------------------------------- */
@media only screen and (max-width: 620px) {
table[class=body] h1 {
font-size: 28px !important;
margin-bottom: 10px !important;
}
table[class=body] p,
table[class=body] ul,
table[class=body] ol,
table[class=body] td,
table[class=body] span,
table[class=body] a {
font-size: 16px !important;
}
table[class=body] .wrapper,
table[class=body] .article {
padding: 10px !important;
}
table[class=body] .content {
padding: 0 !important;
}
table[class=body] .container {
padding: 0 !important;
width: 100% !important;
}
table[class=body] .main {
border-left-width: 0 !important;
border-radius: 0 !important;
border-right-width: 0 !important;
}
table[class=body] .btn table {
width: 100% !important;
}
table[class=body] .btn a {
width: 100% !important;
}
table[class=body] .img-responsive {
height: auto !important;
max-width: 100% !important;
width: auto !important;
}
}
/* -------------------------------------
PRESERVE THESE STYLES IN THE HEAD
------------------------------------- */
@media all {
.ExternalClass {
width: 100%;
}
.ExternalClass,
.ExternalClass p,
.ExternalClass span,
.ExternalClass font,
.ExternalClass td,
.ExternalClass div {
line-height: 100%;
}
.apple-link a {
color: inherit !important;
font-family: inherit !important;
font-size: inherit !important;
font-weight: inherit !important;
line-height: inherit !important;
text-decoration: none !important;
}
.apple-link-2 a {
color: inherit !important;
font-family: inherit !important;
font-size: 11px;
font-weight: inherit !important;
line-height: inherit !important;
text-decoration: none !important;
}
#MessageViewBody a {
color: inherit;
text-decoration: none;
font-size: inherit;
font-family: inherit;
font-weight: inherit;
line-height: inherit;
}
.btn-primary table td:hover {
background-color: #34495e !important;
}
.btn-primary a:hover {
background-color: #34495e !important;
border-color: #34495e !important;
}
}
</style>
</head>
<body class="">
<span class="preheader">Your ${ appName } password reset link is here!</span>
<table role="presentation" border="0" cellpadding="0" cellspacing="0" class="body">
<tr>
<td> </td>
<td class="container">
<div class="content">
<!-- START CENTERED WHITE CONTAINER -->
<table role="presentation" class="main">
<!-- START MAIN CONTENT AREA -->
<tr>
<td class="wrapper">
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<p>Hello Crypto Enthusiast!</p>
<p>To reset your password and to log into your <b>${ appName }</b> account, please press the button below to take you to your password reset page☺️:</p>
<table role="presentation" border="0" cellpadding="0" cellspacing="0" class="btn btn-primary">
<tbody>
<tr>
<td align="left">
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td> <a href="${ passwordResetCodeLink }" target="_blank">Reset Your Password</a> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<p>${ appName }</p>
</td>
</tr>
</table>
</td>
</tr>
<!-- END MAIN CONTENT AREA -->
</table>
<!-- END CENTERED WHITE CONTAINER -->
<!-- START FOOTER -->
<div class="footer">
<table role="presentation" border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="content-block">
<span class="apple-link-2">If this email is unexpected or unrecognized, please contact us via our customer support email: <EMAIL></span>
</td>
</tr>
</table>
</div>
<!-- END FOOTER -->
</div>
</td>
<td> </td>
</tr>
</table>
</body>
</html>`
);
return emailHtml;
});<file_sep>'use strict';
const AWS = require( 'aws-sdk' );
module.exports = Object.freeze({
sesv2: new AWS.SESV2(),
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry
},
},
doOperationInQueue,
stringify
},
constants: {
users: {
balanceTypes: { bitcoinNodeIn, normalWithdraw }
},
aws: {
database: {
tableNames: { BALANCES, USERS }
}
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
javascript: { getQueueId },
} = require( '../../../../../../utils' );
const assignAddressToUser = require( '../assignAddressToUser' );
const updateHasGottenAddressStatusForUser = require( './updateHasGottenAddressStatusForUser' );
module.exports = Object.freeze( ({
user
}) => doOperationInQueue({
queueId: getQueueId({ type: USERS, id: user.userId }),
doOperation: async () => {
console.log( 'Running addBalanceEntryAndAssignNewAddress' );
const addressDatum = await assignAddressToUser({
user
});
if( !!addressDatum ) {
const { userId } = user;
await updateDatabaseEntry({
tableName: BALANCES,
entry: {
userId,
[bitcoinNodeIn]: {},
[normalWithdraw]: {},
creationDate: Date.now(),
}
});
await updateHasGottenAddressStatusForUser({
userId
});
}
console.log(
'addBalanceEntryAndAssignNewAddress executed successfully - ' +
`returning addressDatum: ${ stringify( addressDatum ) }`
);
return addressDatum;
}
}));<file_sep>'use strict';
module.exports = Object.freeze({
getFeeData: require( './getFeeData' ),
getFeeToPayFromFeeData: require( './getFeeToPayFromFeeData' ),
metaGetFeeToPayFromFeeData: require( './metaGetFeeToPayFromFeeData' ),
});
<file_sep>'use strict';
const pseudoDecrypt = require( './pseudo' );
module.exports = ({
rawSpecialId,
}) => {
const psuedoOmega1 = pseudoDecrypt({
text: rawSpecialId
});
return psuedoOmega1;
};
<file_sep>import { actions } from '../utils';
import { getState, setState } from '../reduxX';
export default () => {
window.history.pushState(
{
key: 'exchange'
},
'exchange'
);
window.onpopstate = () => {
const freeGameMode = !!getState( 'notLoggedInMode', 'freeGame' );
if( freeGameMode ) {
setState(
[ 'notLoggedInMode', 'freeGame' ],
null
);
return;
}
const isOnRestPage = actions.getIsOnRestPage();
if( !isOnRestPage ) {
window.location = '/';
}
else {
window.history.back();
}
};
};
<file_sep>import { createElement as e } from 'react';
// import { getState/*, setState*/ } from '../../reduxX';
// import { bitcoinExchange } from '../../utils';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
luluLemonButtons: {
width: '85%',
height: 40,
// margin: 20,
marginTop: 10,
marginBottom: 10,
marginLeft: 10,
marginRight: 10,
// margin: 20,
// margin: 20,
padding: 5,
backgroundColor: 'darkgreen',
// backgroundColor: '#FF9900',
borderRadius: 15,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
theText: {
color: 'beige',
userSelect: 'none',
}
};
};
export default ({
text,
onClick
}) => {
const styles = getStyles();
return e(
'div',
{
style: styles.luluLemonButtons,
onClick,
},
e(
'div',
{
style: styles.theText,
},
text
)
);
};
<file_sep>'use strict';
module.exports = Object.freeze({
getLoginTokenId: require( './getLoginTokenId' ),
getLoginTokenIdComponents: require( './getLoginTokenIdComponents' ),
});
<file_sep>'use strict';
const uuidv4 = require( 'uuid' ).v4;
const getRedisClient = require( 'get-redis-client' );
const {
obliterateOperationFromQueue,
constants: {
TIMEOUT,
OPERATION_TIMEOUT
}
} = require( './tools' );
const doOperationInQueueCore = require( './doOperationInQueueCore' );
const timeout = TIMEOUT;
const operationTimeout = OPERATION_TIMEOUT;
module.exports = Object.freeze( async ({
queueId,
operation = () => Promise.resolve(),
operationArgs = [],
}) => {
const doOperation = operation;
const doOperationArgs = operationArgs;
if( !queueId ) {
throw new Error( 'error in doOperationInQueue: missing queueId' );
}
const operationId = uuidv4();
const redisClient = getRedisClient();
console.log( '🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒' );
console.log( `🐴Running do Operation "${ operationId }" in Queue🐴` );
console.log( '🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒🔒' );
try {
const doOperationInQueueCoreResults = await doOperationInQueueCore({
redisClient,
operationId,
doOperation,
doOperationArgs,
queueId,
timeout,
operationTimeout,
});
redisClient.quit();
console.log( '🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓' );
console.log(
`🦄Do Operation "${ operationId }" ` +
`in Queue Executed Successfully🦄`
);
console.log( '🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓🔓' );
return doOperationInQueueCoreResults;
}
catch( err ) {
console.log( '🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀' );
console.log(
'🐺error in doOperationInQueue🐺:',
`err: ${ err } - \n`,
`operationId: "${ operationId }"`
);
console.log( '🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀🦀' );
console.log(
'obliterating operation from queue ' +
'and destorying the client before finally throwing the error'
);
try {
await obliterateOperationFromQueue({
redisClient,
queueId,
operationId,
errorMessage: err.message || 'doOperationError'
});
}
catch( obliterateOperationFromQueueErr ) {
console.log(
'🦆really weird error, error in obliterating operation ' +
`"${ operationId }" from queue after other ` +
`error ${ err } occurred, here is the obliteration error: ` +
obliterateOperationFromQueueErr
);
}
redisClient.quit();
throw err;
}
});<file_sep>import { createElement as e } from 'react';
// import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
// import { moneyActions } from '../../../../constants';
// import { getState } from '../../../../reduxX';
const weekday = [
"Sunday",
'Monday',
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
const monthNames = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
const numberEnglish = [
'th',
'st',
'nd',
'rd',
'th',
'th',
'th',
'th',
'th',
'th',
];
const getStyles = ({
dialogMode
}) => {
const {
color,
} = dialogMode ? {
color: 'white',
} : {
color: 'black',
};
// const mainStyleObject = getState( 'mainStyleObject' );
return {
timeText: {
color,
fontSize: 12,
marginLeft: 5,
marginTop: 3,
}
};
};
const getHours = ({
theDate,
}) => {
const hours1 = theDate.getHours();
const hours2 = hours1 % 12;
if( hours2 === 0 ) {
return 12;
}
return hours2;
};
const getSecondsWithAddedZeroIfNecessary = ({
theDate,
}) => {
const rawSeconds = theDate.getSeconds();
if( rawSeconds < 10 ) {
const minutes = `0${ rawSeconds }`;
return minutes;
}
return rawSeconds;
};
const getMinutesWithAddedZeroIfNecessary = ({
theDate,
}) => {
const rawMinutes = theDate.getMinutes();
if( rawMinutes < 10 ) {
const minutes = `0${ rawMinutes }`;
return minutes;
}
return rawMinutes;
};
export default ({
excitingElements,
moneyAction,
dialogMode,
}) => {
const styles = getStyles({
dialogMode,
});
const theDate = new Date( moneyAction.time );
const hours = theDate.getHours();
const isPM = hours > 12;
const theDateDate = theDate.getDate();
const minutes = getMinutesWithAddedZeroIfNecessary({
theDate
});
const swaggyTime = (
`${ getHours({ theDate }) }:` +
`${ minutes }:` +
`${ getSecondsWithAddedZeroIfNecessary({ theDate }) } ` +
`${ isPM ? 'PM' : 'AM' }, ` +
`${ weekday[ theDate.getDay() ] } ` +
`${ monthNames[ theDate.getMonth() ] } ` +
`${ theDateDate }` +
`${ numberEnglish[ theDateDate % 10 ] } ` +
`${ theDate.getFullYear() }`
);
excitingElements.push(
e(
Typography,
{
style: styles.timeText
},
swaggyTime
)
);
};
<file_sep>'use strict';
const handleCase = require( './handleCase' );
exports.handler = Object.freeze( async event => {
console.log( '📩Running handleEEDRs' );
try {
await handleCase({
event,
});
console.log(
'💌☢️🐑handleEEDRs executed successfully'
);
}
catch( err ) {
console.log( '📧🦌error in handleEEDRs:', err );
}
});
<file_sep>#!/bin/sh
####
#### Common Code
####
pushd ../../../../0-commonCode/api
npm install @bitcoin-api/redis-streams-utils@latest --save
npm install do-redis-request@latest --save
npm install drf@latest --save
npm install drq@latest --save
npm install get-redis-client@latest --save
npm install
popd
<file_sep>'use strict';
const {
constants: {
exchanges
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
http: {
headers
}
} = require( '../utils/constants' );
const oneDay = 24 * 60 * 60 * 1000;
module.exports = Object.freeze({
loginTokens: {
expiryTime: oneDay,
numberOfAllowedSignedInLoginTokens: 5,
},
headers,
// headers: {
// loginToken: '<PASSWORD>',
// userId: 'user-id',
// },
verificationCode: {
expiryTime: oneDay,
},
javascript: {
styleSpacer: '__style__',
},
urls: {
exchangeUrl: process.env.EXCHANGE_URL,
},
exchanges,
exchangeEmailDeliveryResults: {
snsNotificationTypes: {
Delivery: 'Delivery',
Bounce: 'Bounce',
Complaint: 'Complaint',
},
types: {
success: 'success',
block: 'block',
review: 'review',
},
},
// IN FUTURE: can move to common code
transactions: {
transactionId: {
prefix: 'transaction_',
minLength: 3,
maxLength: 120,
},
},
exchangeUsers: {
exchangeUserId: {
prefix: 'exchange_user_',
minLength: 3,
maxLength: 100,
},
},
passwordResetCode: {
prc: 'prc',
},
});<file_sep>
'use strict';
const {
constants: {
aws: {
database: {
tableNames: { METADATA },
metadataPartitionKeyValues
}
},
},
utils: {
aws: {
dino: {
getDatabaseEntry,
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
// 💡💡💡💡💡💡used by ePOST/withdraws
module.exports = Object.freeze( async () => {
console.log( 'running getFeeData' );
const tableName = METADATA;
const value = metadataPartitionKeyValues.feeData;
const feeData = await getDatabaseEntry({ tableName, value });
console.log( 'getFeeData executed successfully' );
return feeData;
});<file_sep>'use strict';
// const {
// utils: {
// stringify,
// },
// } = require( '@bitcoin-api/full-stack-api-private' );
const {
transactions,
alien,
} = require( '../../constants' );
module.exports = Object.freeze( () => {
const theOracleOfDelphiDefi = {
[transactions.types.addBitcoin]: {
addressToData: {},
},
[transactions.types.withdrawBitcoin]: {
totalAmount: 0,
},
[transactions.types.exchange]: {
totalBitcoinAmount: 0,
totalCryptoAmount: 0,
},
[transactions.types.dream]: {
totalCryptoAmount: 0,
},
[transactions.types.vote]: {
totalCryptoAmount: 0,
},
[transactions.types.raffle]: {
totalCryptoAmount: 0,
},
[transactions.types.bonus]: {
totalCryptoAmount: 0,
totalBitcoinAmount: 0,
},
[transactions.types.setAlienBalance]: {
[alien.currencies.busd.key]: {
totalCryptoAmount: '0',
},
[alien.currencies.m.key]: {
totalCryptoAmount: '0',
},
},
};
return theOracleOfDelphiDefi;
});
<file_sep>import { createElement as e } from 'react';
// import { getState } from '../../../reduxX';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Tickets from './Tickets';
import BuyTicketPolygon from './BuyTicketPolygon';
// import ViewDraws from './ViewDraws';
import DrawsBar from './DrawsBar';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: 'beige',
width: '100%',
marginTop: 10,
marginBottom: 10,
// height: 200,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
text: {
width: '90%',
color: 'black',
},
};
};
export default ({
raffleDatum
}) => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Typography,
{
style: styles.text,
},
`Lotus Season ${ raffleDatum.raffleNumber }`
),
e(
Typography,
{
style: styles.text,
},
`Flower Pot: ${ raffleDatum.cryptoPot } DB`
),
e(
Typography,
{
style: styles.text,
},
`Petal Pick Cost: ${ raffleDatum.ticketCryptoPrice } DB`
),
e(
Typography,
{
style: styles.text,
},
`House Flower Pot: ${ raffleDatum.houseCut * 100 }%`
),
e(
Typography,
{
style: styles.text,
},
`Lotus Season Start: ${
new Date( raffleDatum.previousRaffleEndHour ).toLocaleString()
}`
),
// ...choiceElements,
e(
DrawsBar,
{
raffleDatum,
}
),
e(
Tickets,
{
raffleDatum,
}
),
!!raffleDatum.winHour && e(
Typography,
{
style: styles.text,
},
`Winning Draw Time: ${
new Date( raffleDatum.winHour ).toLocaleString()
}`
),
!!raffleDatum.winChoice && e(
Typography,
{
style: styles.text,
},
`Winning Numbers: ${ raffleDatum.winChoice }`
),
!!raffleDatum.numberOfWinners && e(
Typography,
{
style: styles.text,
},
`Number of Winners: ${ raffleDatum.numberOfWinners }`
),
!!raffleDatum.winCryptoPayout && e(
Typography,
{
style: styles.text,
},
`Winning Payout: ${ raffleDatum.winCryptoPayout } DB`
),
!!raffleDatum.winData && raffleDatum.winData.hasWon && e(
Typography,
{
style: styles.text,
},
'Winner!🎉🎊🥳'
),
!raffleDatum.winRaffleDrawId && e(
BuyTicketPolygon,
{
raffleId: raffleDatum.raffleId,
}
)
);
};
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( ({
// module.exports = Object.freeze( async ({
voteId,
}) => {
console.log(
'running getMetadataVoteData with ' +
`the following values - ${ stringify({
voteId,
}) }`
);
const metadataVoteData = {
choices: [ 'trump', 'biden' ],
votingEndTime: Date.now() + (6 * 60 * 1000),
};
console.log(
`getMetadataVoteData executed successfully - returning values ${
stringify( metadataVoteData )
}`
);
return metadataVoteData;
});
<file_sep>'use strict';
const {
utils: {
aws: {
dinoCombos: {
balances: {
verifyBalanceOnNewWithdraw
}
}
},
stringify,
javascript,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const doTheActualWithdraw = require( './doTheActualWithdraw' );
const realDealTheWithdraw = require( './realDealTheWithdraw' );
const addTransactionAndUpdateExchangeUserDeluxe = require( './addTransactionAndUpdateExchangeUserDeluxe' );
const { backgroundExecutor } = require( '../utils' );
const getVanguardValues = Object.freeze( ({
pendingWithdrawDatum: {
isExchangeWithdraw,
exchangeUserId,
userId
}
}) => {
if( isExchangeWithdraw ) {
return {
getQueueId: javascript.getVanguardQueueId,
idForGetQueueId: exchangeUserId,
isExchangeWithdraw
};
}
return {
getQueueId: javascript.getQueueId,
idForGetQueueId: userId,
isExchangeWithdraw
};
});
module.exports = Object.freeze( async ({
pendingWithdrawData
}) => {
console.log(
`Running doWithdraws for ${ pendingWithdrawData.length } ` +
'pending withdraws.'
);
try {
for( const pendingWithdrawDatum of pendingWithdrawData ) {
const {
getQueueId,
idForGetQueueId,
isExchangeWithdraw
} = getVanguardValues({ pendingWithdrawDatum });
console.log(
'doWithdraws vanguard values: ' +
stringify({
idForGetQueueId,
isExchangeWithdraw
})
);
const {
withdrawOccurredSuccessfully,
} = await doTheActualWithdraw({
pendingWithdrawDatum,
getQueueId,
idForGetQueueId,
});
if( withdrawOccurredSuccessfully ) {
backgroundExecutor.addOperation({
operation: async () => {
await realDealTheWithdraw({
userId: pendingWithdrawDatum.userId,
ultraKey: pendingWithdrawDatum.ultraKey,
getQueueId,
idForGetQueueId,
});
}
});
}
backgroundExecutor.addOperation({
operation: async () => {
await verifyBalanceOnNewWithdraw({
userId: pendingWithdrawDatum.userId,
ultraKey: pendingWithdrawDatum.ultraKey,
isExchangeWithdraw,
idForGetQueueId,
addTransactionAndUpdateExchangeUserDeluxe: (
async () => {}
// getAddTransactionAndUpdateExchangeUserDeluxe({
// userId: pendingWithdrawDatum.userId,
// ultraKey: pendingWithdrawDatum.ultraKey,
// })
),
});
}
});
if( isExchangeWithdraw ) {
backgroundExecutor.addOperation({
operation: async () => {
await addTransactionAndUpdateExchangeUserDeluxe({
exchangeUserId: pendingWithdrawDatum.exchangeUserId,
userId: pendingWithdrawDatum.userId,
ultraKey: pendingWithdrawDatum.ultraKey,
});
}
});
}
}
console.log( 'doWithdraws - executed successfully' );
}
catch( err ) {
const results = {
unexpectedError: err
};
console.log(
'doWithdraws - executed successfully (error case!) - ' +
'an error occurred, ' +
`returning results: ${ stringify( results ) }`
);
return results;
}
});<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( async ({
collection,
query,
newValue,
createIfDoesNotExist = true,
}) => {
console.log(
'running updateMongoEntry with the following values: ' +
stringify({ query, newValue })
);
await collection.updateOne(
query,
newValue,
{
upsert: createIfDoesNotExist,
}
);
console.log( 'updateMongoEntry executed successfully' );
});<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry,
}
},
// stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
LOGIN_TOKENS
},
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
loginTokens: {
getSignedOutLoginToken
}
} = require( '../../../../../../exchangeUtils' );
module.exports = Object.freeze( async ({
ipAddress,
loginTokens,
}) => {
console.log( 'running signOutLoginTokens' );
for( const loginToken of loginTokens ) {
if( !loginToken.signedOut ) {
const signedOutLoginToken = getSignedOutLoginToken({
loginToken,
ipAddress,
otherKeyValues: {
isDeleteUserSignedOut: true,
}
});
console.log(
'signing out token with id: ' +
signedOutLoginToken.loginTokenId
);
await updateDatabaseEntry({
tableName: LOGIN_TOKENS,
entry: signedOutLoginToken,
});
}
}
console.log( 'signOutLoginTokens executed successfully' );
});
<file_sep>'use strict';
module.exports = require( '../../../utils/javascript/getFormattedEvent' );<file_sep>import { createElement as e } from 'react';
// import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import { moneyActions } from '../../../../constants';
const getStyles = ({
dialogMode
}) => {
const {
color,
} = dialogMode ? {
color: 'white',
} : {
color: 'black',
};
// const mainStyleObject = getState( 'mainStyleObject' );
return {
amountText: {
color,
fontSize: 14,
marginLeft: 5,
marginTop: 3,
},
};
};
export default ({
excitingElements,
moneyAction,
dialogMode,
}) => {
const styles = getStyles({
dialogMode,
});
if(
moneyAction.type ===
moneyActions.types.game.talismanFlip
) {
const isWinningFlip = moneyAction.amount > 0;
const gameAmount = Math.abs( moneyAction.amount );
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
'Win: ' +
(isWinningFlip ? 'yes!🥳' : 'no')
),
e(
Typography,
{
style: styles.amountText
},
'DB wagered: ' +
`${ gameAmount } DB`
),
);
if( isWinningFlip ) {
const winningAmount = 2 * gameAmount;
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
'DB won: ' +
`${ winningAmount } DB`
),
);
}
}
else if(
moneyAction.type ===
moneyActions.types.game.talismanLotus
) {
const gameAmount = Math.abs( moneyAction.amount );
if( moneyAction.winData ) {
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
'DB wagered: ' +
`${ moneyAction.winData.amount } DB`
),
e(
Typography,
{
style: styles.amountText
},
'DB Jackpot Won: ' +
`${ gameAmount } DB 🎈🎉🎊🎁🥳🎈, congrats!`
)
);
}
else {
const isWinningFlip = moneyAction.amount > 0;
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
'Win: ' +
(isWinningFlip ? 'yes!🥳' : 'no')
),
e(
Typography,
{
style: styles.amountText
},
'DB wagered: ' +
`${ gameAmount } DB`
),
);
if( isWinningFlip ) {
const winningAmount = 2 * gameAmount;
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
'DB won: ' +
`${ winningAmount } DB`
),
);
}
}
}
else if (
moneyAction.type ===
moneyActions.types.game.slot
) {
const gameAmount = Math.abs( moneyAction.amount );
if( moneyAction.amount === 0 ) {
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
'Tie game - no DB change'
),
);
}
else if( moneyAction.amount > 0 ) {
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
`Won: ${ gameAmount } DB`
),
);
}
else if( moneyAction.amount < 0 ) {
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
`Lost: ${ gameAmount } DB`
),
);
}
}
else if(
moneyAction.type ===
moneyActions.types.game.lotus.pickPetal
) {
const petalPrice = Math.abs( moneyAction.amount );
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
`Petal Price: ${ petalPrice } DB`
),
e(
Typography,
{
style: styles.amountText
},
`Petal Numbers: ${ moneyAction.choice }`
)
);
}
else if(
moneyAction.type ===
moneyActions.types.game.lotus.unpickPetal
) {
const petalPrice = Math.abs( moneyAction.amount );
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
`Petal Price (refund): ${ petalPrice } DB`
),
e(
Typography,
{
style: styles.amountText
},
`Petal Numbers: ${ moneyAction.choice }`
)
);
}
else if(
moneyAction.type ===
moneyActions.types.game.lotus.flowerPotPayout
) {
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
`Flower Pot Winning Payout: ${ moneyAction.amount } DB`
),
e(
Typography,
{
style: styles.amountText
},
'Congratulations!!! 🥳🎊🎉🎈'
)
);
}
};
<file_sep>#!/bin/sh
####
#### Backend
####
pushd ../../../../1-backend/addressGenerator
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install @bitcoin-api/full-stack-backend-private@latest --save
npm install
popd
pushd ../../../../1-backend/feeDataBot
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install @bitcoin-api/full-stack-backend-private@latest --save
npm install
popd
pushd ../../../../1-backend/withdrawsBot
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install @bitcoin-api/full-stack-exchange-private@latest --save
npm install @bitcoin-api/full-stack-backend-private@latest --save
npm install
popd
pushd ../../../../1-backend/depositsBot
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install @bitcoin-api/full-stack-exchange-private@latest --save
npm install @bitcoin-api/full-stack-backend-private@latest --save
npm install
popd
####
#### Backend Giraffe Lick Leaf
####
pushd ../../../../1-backend/giraffeDeploy/giraffe
npm install @bitcoin-api/giraffe-utils@latest --save
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install
popd
pushd ../../../../1-backend/giraffeDeploy/tree
npm install @bitcoin-api/giraffe-utils@latest --save
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install
popd
####
#### API
####
pushd ../../../../2-api
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install @bitcoin-api/full-stack-exchange-private@latest --save
npm install
popd
####
#### Beyond
####
pushd ../../../../infrastructure/scripts/x-universal/megaActions/dbOperations
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install @bitcoin-api/full-stack-exchange-private@latest --save
npm install
popd
pushd ../../../../infrastructure/scripts/x-universal/megaActions/dbOperationOnAll
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install @bitcoin-api/full-stack-exchange-private@latest --save
npm install
popd
<file_sep>'use strict';
const {
utils: {
stringify,
aws: {
dino: {
classicalUpdateDatabaseEntry
}
}
},
constants: {
aws: {
database: {
tableNames: {
METADATA
},
}
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
metadataKeys: {
dreamLotus
},
}
},
},
} = require( '@bitcoin-api/full-stack-exchange-private' );
module.exports = Object.freeze( async ({
jackpotAmount,
winAmount
}) => {
/*
1. update jackpotAmount to zero
2. update unhappyDreamCount
*/
const newAmount = jackpotAmount - winAmount;
console.log(
'running updateJackpotMetadata with the following values: ' +
stringify({
jackpotAmount,
winAmount,
'newAmount = jackpotAmount - winAmount =': newAmount,
})
);
await classicalUpdateDatabaseEntry({
tableName: METADATA,
value: dreamLotus,
expressionAttributeNames: {
'#jackpotAmount': 'jackpotAmount',
'#unhappyDreamCount': 'unhappyDreamCount',
},
expressionAttributeValues: {
':jackpotAmount' : newAmount,
':unhappyDreamCount': 0,
},
updateExpression: (
'SET #jackpotAmount = :jackpotAmount, ' +
'#unhappyDreamCount = :unhappyDreamCount'
),
});
console.log(
'updateJackpotMetadata executed successfully: ' +
stringify({
responseKeys: Object.keys( {} )
})
);
});
<file_sep>'use strict';
const {
transactions,
} = require( '../../../../../../constants' );
const getCryptoAmountNumber = require(
'../../../../../crypto/getCryptoAmountNumber'
);
const {
utils: {
bitcoin: {
formatting: { getAmountNumber }
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( ({
theOracleOfDelphiDefi,
}) => {
const {
[transactions.types.bonus]: {
totalBitcoinAmount,
totalCryptoAmount,
},
} = theOracleOfDelphiDefi;
const bonusData = {
lastUpdated: Date.now(),
bitcoin: {
amount: getAmountNumber( totalBitcoinAmount ),
},
crypto: {
amount: getCryptoAmountNumber( totalCryptoAmount ),
},
};
return bonusData;
});
<file_sep>'use strict';
const {
utils: {
stringify,
business: {
getIsValidWithdrawAmount
},
bitcoin: {
validation: { getIsValidAddress },
formatting: { getAmountNumber }
}
},
// constants: {
// environment: {
// isProductionMode
// }
// }
} = require( '@bitcoin-api/full-stack-api-private' );
const {
errors: { ValidationError },
} = require( '../../../../../utils' );
const validateAndGetEnviroWithdrawAmount = Object.freeze( ({
rawEnviroWithdrawAmount
}) => {
if( !rawEnviroWithdrawAmount ) {
return 0;
}
if( typeof rawEnviroWithdrawAmount !== 'number' ) {
const validationError = new ValidationError(
`invalid enviroWithdrawAmount: ${ rawEnviroWithdrawAmount }`
);
validationError.bulltrue = true;
throw validationError;
}
if(
(rawEnviroWithdrawAmount < 0) ||
(rawEnviroWithdrawAmount > 69)
) {
const validationError = new ValidationError(
`invalid enviroWithdrawAmount: ${ rawEnviroWithdrawAmount }`
);
validationError.bulltrue = true;
throw validationError;
}
return rawEnviroWithdrawAmount;
});
module.exports = Object.freeze( ({
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount,
}) => {
console.log(
`running validateAndGetValues with values: ${ stringify({
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount,
})}`
);
const withdrawAmount = getAmountNumber( rawAmount );
const theWithdrawAmountIsInvalid = !getIsValidWithdrawAmount({
withdrawAmount
});
if( theWithdrawAmountIsInvalid ) {
const validationError = new ValidationError(
`invalid withdraw amount: ${ withdrawAmount }`
);
validationError.bulltrue = true;
throw validationError;
}
else if(
(
(typeof rawAddress !== 'string') ||
(rawAddress.length > 100)
) ||
!getIsValidAddress( rawAddress )
) {
const validationError = new ValidationError(
`invalid withdraw address: ${ rawAddress }`
);
validationError.bulltrue = true;
throw validationError;
}
else if( typeof rawShouldIncludeFeeInAmount !== 'boolean' ) {
const validationError = new ValidationError(
`invalid shouldIncludeFeeInAmount: ${
rawShouldIncludeFeeInAmount
}`
);
validationError.bulltrue = true;
throw validationError;
}
const enviroWithdrawAmount = validateAndGetEnviroWithdrawAmount({
rawEnviroWithdrawAmount
});
return {
withdrawAmount,
addressToSendTo: rawAddress,
shouldIncludeFeeInAmount: rawShouldIncludeFeeInAmount,
enviroWithdrawAmount,
};
});
<file_sep>import { default as validateAndGetInitializationValues } from './validateAndGetInitializationValues';
import { default as makeApiCall } from '../makeApiCall';
import { http } from '../../constants';
export default class BitcoinExchange {
constructor( initializationValues ) {
Object.assign(
this,
validateAndGetInitializationValues( initializationValues )
);
}
async createUser({
email,
password,
googleCode
}) {
return await makeApiCall({
resource: 'exchange-users',
method: 'POST',
headers: {
email,
password,
[http.headers.grecaptchaGoogleCode]: googleCode,
}
// body: {
// email,
// password,
// // googleCode,
// },
});
}
async verifyEmail({
email,
password,
verifyEmailCode,
googleCode,
}) {
return await makeApiCall({
resource: 'verify-user',
method: 'POST',
headers: {
email,
password,
[http.headers.grecaptchaGoogleCode]: googleCode,
[http.headers.verifyEmailCode]: verifyEmailCode,
}
});
}
async login({
email,
password,
googleCode,
}) {
return await makeApiCall({
resource: 'login',
method: 'POST',
headers: {
email,
password,
[http.headers.grecaptchaGoogleCode]: googleCode,
},
});
}
async initializeResetPassword({
email,
googleCode,
}) {
return await makeApiCall({
resource: 'login/password',
method: 'POST',
headers: {
email,
[http.headers.grecaptchaGoogleCode]: googleCode,
},
});
}
async resetPasswordDo({
passwordResetCode,
newPassword,
googleCode,
}) {
return await makeApiCall({
resource: 'login/password',
method: 'PATCH',
headers: {
[http.headers.grecaptchaGoogleCode]: googleCode,
[http.headers.newPassword]: newPassword,
[http.headers.passwordResetCode]: passwordResetCode,
},
});
}
async getUser({
userId,
loginToken,
}) {
return await makeApiCall({
resource: `exchange-users/${ userId }`,
method: 'GET',
headers: {
'login-token': loginToken,
'user-id': userId,
},
});
}
async addAddress({
userId,
loginToken,
googleCode,
}) {
return await makeApiCall({
resource: 'addresses',
method: 'POST',
headers: {
[ http.headers.userId ]: userId,
[ http.headers.loginToken ]: loginToken,
[ http.headers.grecaptchaGoogleCode ]: googleCode,
},
});
}
async withdraw({
userId,
amount,
address,
loginToken,
fullWithdraw,
googleCode
}) {
return await makeApiCall({
resource: 'withdraws',
method: 'POST',
body: {
amount,
address,
fullWithdraw,
},
headers: {
'login-token': loginToken,
'user-id': userId,
[ http.headers.grecaptchaGoogleCode ]: googleCode,
},
});
}
async signOut({
userId,
loginToken
}) {
return await makeApiCall({
resource: 'logout',
method: 'POST',
body: {},
headers: {
'login-token': loginToken,
'user-id': userId,
},
});
}
async deleteUser({
userId,
loginToken
}) {
return await makeApiCall({
resource: `exchange-users/${ userId }`,
method: 'DELETE',
headers: {
'login-token': loginToken,
'user-id': userId,
},
});
}
async vote({
userId,
loginToken,
amount,
voteId,
choice,
}) {
return await makeApiCall({
resource: `votes/${ voteId }`,
method: 'POST',
headers: {
'login-token': loginToken,
'user-id': userId,
},
body: {
amount,
choice,
},
});
}
async getVote({
userId,
loginToken,
voteId,
}) {
return await makeApiCall({
resource: `votes/${ voteId }`,
method: 'GET',
headers: {
'login-token': loginToken,
'user-id': userId,
},
});
}
async getRaffleData({
userId,
loginToken,
lastKey,
lastTime,
}) {
let queryString = ``;
if( !!lastTime && !!lastKey ) {
queryString += `?lastTime=${ lastTime }&lastKey=${ lastKey }`;
}
const resource = `raffles${ queryString }`;
return await makeApiCall({
resource,
method: 'GET',
headers: {
'login-token': loginToken,
'user-id': userId,
},
});
}
async getRaffleDraws({
userId,
loginToken,
raffleId,
lastTime,
lastKey,
startTime,
endTime
}) {
let queryString = `?startTime=${ startTime }&endTime=${ endTime }`;
if( !!lastTime && !!lastKey ) {
queryString += `&lastTime=${ lastTime }&lastKey=${ lastKey }`;
}
return await makeApiCall({
resource: `raffle-draws/${ raffleId }${ queryString }`,
method: 'GET',
headers: {
'login-token': loginToken,
'user-id': userId,
},
});
}
async getRaffleTickets({
userId,
loginToken,
raffleId,
time,
powerId,
specialId,
}) {
return await makeApiCall({
resource: (!!time && !!powerId && !!specialId) ? (
`raffle-tickets/${ raffleId }?time=${ time }&powerId=${ powerId }&specialId=${ specialId }`
) : (
`raffle-tickets/${ raffleId }`
),
method: 'GET',
headers: {
'login-token': loginToken,
'user-id': userId,
},
});
}
async exchange({
userId,
loginToken,
amountWantedInCryptos,
amountWantedInBitcoin,
googleCode,
}) {
const values = {
resource: 'exchanges',
method: 'POST',
headers: {
'login-token': loginToken,
'user-id': userId,
[http.headers.grecaptchaGoogleCode]: googleCode,
},
body: {}
};
if( !!amountWantedInCryptos ) {
Object.assign(
values.body,
{
type: 'btcToCrypto',
data: {
amountInCryptoWanted: Number( amountWantedInCryptos ),
}
}
);
}
else {
Object.assign(
values.body,
{
type: 'cryptoToBTC',
data: {
amountInBitcoinWanted: Number( amountWantedInBitcoin ),
}
}
);
}
return await makeApiCall( values );
}
async enchantedLuck({
userId,
loginToken,
// mode,
amount,
googleCode,
}) {
return await makeApiCall({
resource: 'dreams',
method: 'POST',
headers: {
'login-token': loginToken,
'user-id': userId,
[http.headers.grecaptchaGoogleCode]: googleCode,
},
body: {
amount: amount,
// mode
}
});
}
async enchantedSlot({
userId,
loginToken,
googleCode,
}) {
return await makeApiCall({
resource: 'dreams-slot',
method: 'POST',
headers: {
'login-token': loginToken,
'user-id': userId,
[http.headers.grecaptchaGoogleCode]: googleCode,
},
body: {}
});
}
async enchantedLuckJackpot({
userId,
loginToken,
// mode,
amount,
googleCode,
}) {
return await makeApiCall({
resource: 'dreams-lotus',
method: 'POST',
headers: {
'login-token': loginToken,
'user-id': userId,
[http.headers.grecaptchaGoogleCode]: googleCode,
},
body: {
amount: amount,
// mode
}
});
}
async getJackpotData({
userId,
loginToken,
// googleCode,
}) {
return await makeApiCall({
resource: 'dreams-lotus',
method: 'GET',
headers: {
'login-token': loginToken,
'user-id': userId,
// [http.headers.grecaptchaGoogleCode]: googleCode,
},
// body: {
// amount: amount,
// // mode
// }
});
}
async postRaffleTicket({
userId,
loginToken,
raffleId,
numbers,
action,
googleCode
}) {
return await makeApiCall({
resource: `raffles/${ raffleId }`,
method: 'POST',
headers: {
'login-token': loginToken,
'user-id': userId,
[http.headers.grecaptchaGoogleCode]: googleCode,
},
body: {
numbers,
action,
}
});
}
async getFeeData() {
return await makeApiCall({
resource: 'fee-data',
method: 'GET',
headers: {},
// body: {
// amount: amount,
// // mode
// }
});
}
async getTransactions({
userId,
loginToken,
lastTransactionId,
lastTime,
smallBatch = false,
}) {
let query = '';
if( !!lastTransactionId && !!lastTime ) {
query += (
`?lastTransactionId=${ lastTransactionId }` +
`&lastTime=${lastTime}`
);
}
if( smallBatch ) {
if( !query ) {
query += '?';
}
else {
query += '&';
}
query += 'smallBatch=true';
}
return await makeApiCall({
resource: `transactions${ query }`,
method: 'GET',
headers: {
[http.headers.userId]: userId,
[http.headers.loginToken]: loginToken,
}
});
}
}<file_sep>'use strict';
const {
constants: {
aws: { database: { tableNames: { WITHDRAWS } } },
},
utils: {
doOperationInQueue
}
} = require( '@bitcoin-api/full-stack-api-private' );
const doTheActualWithdrawCore = require( './doTheActualWithdrawCore' );
module.exports = Object.freeze( async ({
pendingWithdrawDatum,
getQueueId,
idForGetQueueId
}) => {
const doTheActualWithdrawResults = await doOperationInQueue({
queueId: getQueueId({ type: WITHDRAWS, id: idForGetQueueId }),
doOperation: doTheActualWithdrawCore,
doOperationArgs: [{
existingWithdrawDatum: pendingWithdrawDatum,
}]
});
return doTheActualWithdrawResults;
});
<file_sep>'use strict';
const doOperationInQueue = require( '../../../../doOperationInQueue' );
const nativeGetQueueId = require( '../../../../javascript/getQueueId' );
const getVanguardQueueId = require( '../../../../javascript/getVanguardQueueId' );
const stringify = require( '../../../../stringify' );
const getDatabaseEntry = require( '../../../dino/getDatabaseEntry' );
const {
aws: {
database: {
tableNames: {
WITHDRAWS, BALANCES
}
}
},
withdraws: {
states: {
verifying,
verifyingToFail,
complete,
failed
}
}
} = require( '../../../../../constants' );
const refreshBalance = require( './refreshBalance' );
const updateWithdraw = require( './updateWithdraw' );
const getVanguardValues = Object.freeze( ({
isExchangeWithdraw,
userId,
idForGetQueueId
}) => {
if( isExchangeWithdraw ) {
return {
getQueueId: getVanguardQueueId,
chosenIdForGetQueueId: idForGetQueueId,
};
}
return {
getQueueId: nativeGetQueueId,
chosenIdForGetQueueId: userId,
};
});
module.exports = Object.freeze( async ({
userId,
ultraKey,
isExchangeWithdraw = false,
idForGetQueueId,
addTransactionAndUpdateExchangeUserDeluxe,
}) => {
if(
isExchangeWithdraw &&
!(
!!addTransactionAndUpdateExchangeUserDeluxe &&
!!idForGetQueueId
)
) {
throw new Error(
'verifyBalanceOnNewWithdraw: missing isExchangeWithdraw values'
);
}
const {
getQueueId,
chosenIdForGetQueueId,
} = getVanguardValues({
isExchangeWithdraw,
userId,
idForGetQueueId
});
console.log(
'running verifyBalanceOnNewWithdraw for withdraw: ' +
stringify({
isExchangeWithdraw,
chosenIdForGetQueueId,
userId,
ultraKey
})
);
await doOperationInQueue({
queueId: getQueueId({ type: WITHDRAWS, id: chosenIdForGetQueueId }),
doOperation: async () => {
const coreFunction = async () => {
const blessedWithdraw = await getDatabaseEntry({
tableName: WITHDRAWS,
value: userId,
sortValue: ultraKey
});
if( !blessedWithdraw ) {
throw new Error(
'doTheActualWithdrawCore - ' +
`invalid blessed withdraw ${
stringify( blessedWithdraw )
}`
);
}
if( blessedWithdraw.state === verifying ) {
await updateWithdraw({
withdraw: blessedWithdraw,
state: complete,
extraMetadata: {
timeOfSuccessfulCompletion: Date.now(),
},
});
}
else if( blessedWithdraw.state === verifyingToFail ) {
await updateWithdraw({
withdraw: blessedWithdraw,
state: failed,
extraMetadata: {
timeOfFailure: Date.now(),
},
});
}
else {
throw new Error(
'doTheActualWithdrawCore - ' +
'invalid blessed withdraw state: ' +
blessedWithdraw.state
);
}
if( isExchangeWithdraw ) {
// TODO: Remove this part, maybe move balance out
// TODO: probably not be necessary to pass in values
return await addTransactionAndUpdateExchangeUserDeluxe({
blessedWithdrawState: blessedWithdraw.state,
});
}
else {
return await refreshBalance({
userId: userId,
normalWithdrawId: blessedWithdraw.normalWithdrawId,
});
}
};
if( isExchangeWithdraw ) {
return await coreFunction();
}
return doOperationInQueue({
queueId: getQueueId({ type: BALANCES, id: userId }),
doOperation: async () => {
return await coreFunction();
},
});
}
});
console.log( 'verifyBalanceOnNewWithdraw executed successfully🦕🦖' );
});
<file_sep>import * as usefulComponents from './usefulComponents';
import * as zanzibarRealms from './zanzibarRealms';
import * as votePolygons from './votePolygons';
export {
usefulComponents,
zanzibarRealms,
votePolygons,
};
export { default as Dialog } from './Dialog';
export { default as CoolInfoPolygon } from './CoolInfoPolygon';
export { default as GetUserPolygon } from './GetUserPolygon';
export { default as LoginPolygon } from './LoginPolygon';
export { default as SignOutButton } from './SignOutButton';
export { default as DeleteUserButton } from './DeleteUserButton';
export { default as SignUpPolygon } from './SignUpPolygon';
export { default as UserDataPolygon } from './UserDataPolygon';
export { default as WithdrawPolygon } from './WithdrawPolygon';
export { default as TitlePolygon } from './TitlePolygon';
export { default as VerifyEmailPolygon } from './VerifyEmailPolygon';
export { default as BlankSpace } from './BlankSpace';
export { default as LoadingPage } from './LoadingPage';
export { default as ExchangePolygon } from './ExchangePolygon';
export { default as MoneyActionsPolygon } from './MoneyActionsPolygon';
export { default as ReferralIdPolygon } from './ReferralIdPolygon';
<file_sep>'use strict';
module.exports = Object.freeze( ({ min, max }) => {
const ceilingMinimum = Math.ceil( min );
const floorMaximum = Math.floor( max );
const randomIntegerInclusive = Math.floor(
Math.random() *
(floorMaximum - ceilingMinimum + 1)
) + ceilingMinimum;
return randomIntegerInclusive;
});<file_sep>import { getState, setState } from '../../reduxX';
import { bitcoinExchange } from '..';
export default async ({
setToLoading = true,
} = { setToLoading: true }) => {
try {
if( setToLoading ) {
setState( 'isLoading', true );
}
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
const {
raffleData,
lastValues: {
lastKey,
lastTime,
},
ownSpecialId,
} = await bitcoinExchange.getRaffleData({
userId,
loginToken
});
setState(
[
'destinyRaffle',
'data'
],
raffleData,
[
'destinyRaffle',
'selectedNumberOne'
],
'',
[
'destinyRaffle',
'selectedNumberTwo'
],
'',
[
'destinyRaffle',
'lastKey'
],
lastKey,
[
'destinyRaffle',
'lastTime'
],
lastTime,
[
'destinyRaffle',
'ownSpecialId'
],
ownSpecialId
);
if( setToLoading ) {
setState( 'isLoading', false );
}
}
catch( err ) {
console.log( 'error in getting raffle data:', err );
if( setToLoading ) {
setState( 'isLoading', false );
}
throw err;
}
};<file_sep>'use strict';
const {
utils: {
// stringify,
// },
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const validateAndGetValues = require( './validateAndGetValues' );
// const ensurePasswordResetCodeIsValid = require( './ensurePasswordResetCodeIsValid' );
const updateExchangeUser = require( './updateExchangeUser' );
const doLogin = require( '../../../../../../sacredElementals/crypto/doLogin' );
module.exports = Object.freeze( async ({
ipAddress,
passwordResetCode,
rawNewPassword,
rawGoogleCode,
exchangeUserId,
}) => {
console.log(
'running resetPasswordDo with the following values:',
stringify({
ipAddress,
rawGoogleCode: !!rawGoogleCode,
rawNewPassword: !!rawNewPassword,
passwordResetCode,
exchangeUserId,
})
);
const {
newPassword,
} = await validateAndGetValues({
ipAddress,
rawGoogleCode,
rawNewPassword,
});
// await ensurePasswordResetCodeIsValid({
// passwordResetCode,
// exchangeUserId,
// });
const {
email
} = await updateExchangeUser({
exchangeUserId,
newPassword,
passwordResetCode,
});
const {
userId,
loginToken,
} = await doLogin({
event: {
headers: {
email,
password: <PASSWORD>,
}
},
ipAddress,
});
const resetPasswordDoResults = {
userId,
loginToken,
};
console.log(
'resetPasswordDo executed successfully: ' +
stringify( resetPasswordDoResults )
);
return resetPasswordDoResults;
});<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
getExchangeDatabaseEntry
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
module.exports = Object.freeze({
getExchangeDatabaseEntry,
});
<file_sep>export default ({
time = Date.now(),
previous = false,
} = {
time: Date.now(),
previous: false,
}) => {
const nextDate = new Date( time );
const changeInDate = previous ? -1 : 1;
nextDate.setDate( nextDate.getDate() + changeInDate );
const startOfNextDayDate = new Date(
nextDate.getFullYear(),
nextDate.getMonth(),
nextDate.getDate()
);
const startOfNextDayTime = startOfNextDayDate.getTime();
const nextDayData = {
time,
startOfNextDayDate,
startOfNextDayTime,
};
return nextDayData;
};
<file_sep>'use strict';
const getIfApiIsActive = require( '../business/getIfApiIsActive' );
const f = Object.freeze;
module.exports = f( async ({
redisClient
}) => {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'running getDragonsToInspectBankStatus'
);
const bankIsOpen = await getIfApiIsActive({ redisClient });
if( !bankIsOpen ) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'The dragons have determined that the bank is CLOSED🐲🐉🔥🔥🔥.' +
'So, customer, what are you still doing here? ' +
'PLEASE LEAVE NOW!!🦵🥾🤕'
);
// NOTE: customer-centric as always, like JB
const error = new Error(
'Api is currently not active, it will be later, ' +
'please consider trying again later. Your bitcoin are ' +
'always secured with Bitcoin-Api.io!'
);
error.bulltrue = true;
throw error;
}
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 -\n' +
'Bank IS open.' +
'\ngetDragonsToInspectBankStatus executed successfully.'
);
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry,
}
},
// stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_USERS
},
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
module.exports = Object.freeze( async ({
exchangeUser,
ipAddress,
}) => {
console.log( 'running signOutExchangeUser' );
const signedOutExchangeUser = Object.assign(
{},
exchangeUser,
{
metadata: Object.assign(
{},
exchangeUser.metadata,
{
deletion: {
date: Date.now(),
ipAddress,
email: exchangeUser.email,
},
}
)
}
);
delete signedOutExchangeUser.email;
delete signedOutExchangeUser.emailToVerify;
await updateDatabaseEntry({
tableName: EXCHANGE_USERS,
entry: signedOutExchangeUser,
});
console.log( 'signOutLoginTokens executed successfully' );
});
<file_sep>import { getState, setState } from '../../reduxX';
import bitcoinExchange from '../bitcoinExchangeInstance';
export default async () => {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
try {
const jackpotData = await bitcoinExchange.getJackpotData({
userId,
loginToken,
});
setState({
keys: [
'loggedInMode',
'coinFlip',
'jackpotAmount'
],
value: jackpotData.jackpotAmount,
});
}
catch( err ) {
console.log( 'error getting jackpot data', err );
}
};
<file_sep>'use strict';
const {
constants: {
aws: {
database: {
tableNames: { ADDRESSES },
}
},
},
utils: {
aws: {
dino: {
searchDatabase,
}
},
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const f = Object.freeze;
const attributes = f({
nameKeys: f({
userId: '#userId',
amount: '#amount',
address: '#address',
conversionDate: '#conversionDate',
// timeUntilReclamationAfterConversionDate: '#timeUntilReclamationAfterConversionDate',
}),
nameValues: f({
userId: 'userId',
amount: 'amount',
address: 'address',
conversionDate: 'conversionDate',
// timeUntilReclamationAfterConversionDate: 'timeUntilReclamationAfterConversionDate',
}),
valueKeys: f({
userId: ':userId',
amount: ':amount',
}),
valueValues: f({
amount: 0,
})
});
module.exports = f( async ({
user,
}) => {
console.log( 'running getUnusedAddressDatum' );
const {
nameKeys,
nameValues,
valueKeys,
valueValues
} = attributes;
const searchParams = {
TableName: ADDRESSES,
ProjectionExpression: [
nameKeys.address,
nameKeys.conversionDate,
// nameKeys.timeUntilReclamationAfterConversionDate,
].join( ', ' ),
Limit: 10000,
ScanIndexForward: false,
KeyConditionExpression: (
`${ nameKeys.userId } = ${ valueKeys.userId }`
),
FilterExpression: (
`${ nameKeys.amount } = ${ valueKeys.amount }`
),
ExpressionAttributeNames: {
[nameKeys.userId]: nameValues.userId,
[nameKeys.amount]: nameValues.amount,
[nameKeys.address]: nameValues.address,
[nameKeys.conversionDate]: nameValues.conversionDate,
// [nameKeys.timeUntilReclamationAfterConversionDate]: nameValues.timeUntilReclamationAfterConversionDate,
},
ExpressionAttributeValues: {
[valueKeys.userId]: user.userId,
[valueKeys.amount]: valueValues.amount,
},
};
const addressData = (await searchDatabase({
searchParams,
})).ultimateResults;
if( addressData.length < 1 ) {
console.log(
'getUnusedAddressDatum executed successfully, ' +
'no addresses found for user'
);
return null;
}
const unusedAddressDatum = addressData[0];
console.log(
'getUnusedAddressDatum executed successfully, there is one: ' +
stringify( unusedAddressDatum )
);
return unusedAddressDatum;
});
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
transactions: {
types: {
identity
},
},
identityTransactions: {
types: {
recalculate,
refresh
}
}
} = require( '../../../../constants' );
module.exports = Object.freeze( ({
type,
data
}) => {
console.log(
'running getIfShouldSearchDb:',
stringify({ type, data })
);
if(
(type === identity) &&
[ recalculate, refresh ].includes( data.identityType )
) {
console.log(
'getIfShouldSearchDb executed successfully:',
'✅YES should search'
);
return true;
}
console.log(
'getIfShouldSearchDb executed successfully:',
'😬no need for search'
);
return false;
});
<file_sep>'use strict';
const queueIdSeparator = '___';
module.exports = Object.freeze(
({ type, id }) => (
`queue${ queueIdSeparator }` +
`${ type }${ queueIdSeparator }` +
`${ type }${ id }`
)
);<file_sep>export default ({
choice
}) => {
const numbers = choice.split( '-' ).map( choiceNumberString => {
const choiceNumber = Number( choiceNumberString );
return choiceNumber;
});
return numbers;
};<file_sep>import { getState, setState } from '../../../reduxX';
import { bitcoinExchange } from '../../../utils';
export default async () => {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
const currentLastKey = getState( 'destinyRaffle', 'lastKey' );
const currentLastTime = getState( 'destinyRaffle', 'lastTime' );
if( !currentLastKey || !currentLastTime ) {
// @safeguard
return;
}
const {
raffleData,
lastValues: {
lastKey,
lastTime,
},
} = await bitcoinExchange.getRaffleData({
userId,
loginToken,
lastKey: currentLastKey,
lastTime: currentLastTime,
});
const currentData = getState( 'destinyRaffle', 'data' );
const newData = currentData.concat( raffleData );
setState(
[
'destinyRaffle',
'data'
],
newData,
[
'destinyRaffle',
'lastKey'
],
lastKey,
[
'destinyRaffle',
'lastTime'
],
lastTime
);
};<file_sep>'use strict';
const {
stringify,
throwStandardError,
} = require( '../../../../../utils' );
const {
validation: {
getIfPasswordResetCodeIsValid
}
} = require( '../../../../../exchangeUtils' );
module.exports = Object.freeze( ({
passwordResetCode,
}) => {
console.log(
'running validateAndGetDecodedPasswordResetCode ' +
'with the following values:',
stringify({
passwordResetCode: passwordResetCode,
})
);
const prcValidationResults = getIfPasswordResetCodeIsValid({
passwordResetCode,
});
if( !prcValidationResults.isValid ) {
return throwStandardError({
logMessage: (
'validateAndGetDecodedPasswordResetCode - ' +
`Invalid password reset code: ${ passwordResetCode }`
),
message: 'Invalid password reset link',
statusCode: 400,
bulltrue: true,
});
}
const {
exchangeUserId,
expiryTime
} = prcValidationResults.data;
if( expiryTime <= Date.now() ) {
return throwStandardError({
message: 'Password reset link has expired',
statusCode: 400,
bulltrue: true,
});
}
const decodedPasswordResetCode = {
exchangeUserId
};
console.log(
'validateAndGetDecodedPasswordResetCode executed successfully, ' +
'returning the decoded password reset code values:',
stringify( decodedPasswordResetCode )
);
return decodedPasswordResetCode;
});
<file_sep>'use strict';
const {
utils: {
doOperationInQueue,
javascript: {
getQueueId
},
stringify,
aws: {
dino: {
// getDatabaseEntry,
updateDatabaseEntry,
},
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: { EXCHANGE_USERS }
}
},
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
exchangeUsers: {
getIfExchangeUserExists
},
aws: {
dino: {
getExchangeDatabaseEntry,
}
}
} = require( '../../../../../exchangeUtils' );
module.exports = Object.freeze( async ({
email,
password,
verifyEmailCode,
ipAddress,
exchangeUserId,
}) => {
console.log(
'running verifyUserEmail ' +
`with the following values - ${ stringify({
email,
password,
verifyEmailCode,
ipAddress,
exchangeUserId,
}) }`
);
await doOperationInQueue({
queueId: getQueueId({ type: EXCHANGE_USERS, id: exchangeUserId }),
doOperation: async () => {
await doOperationInQueue({
queueId: getQueueId({ type: EXCHANGE_USERS, id: email }),
doOperation: async () => {
const exchangeUserExists = await getIfExchangeUserExists({
email,
});
if( exchangeUserExists ) {
const error = new Error(
`user with email ${ email } already exists`
);
error.statusCode = 409;
error.bulltrue = true;
throw error;
}
const exchangeUser = await getExchangeDatabaseEntry({
tableName: EXCHANGE_USERS,
value: exchangeUserId
});
const newExchangeUser = Object.assign(
{},
exchangeUser,
{
email,
metadata: Object.assign(
{},
exchangeUser.metadata,
{
verification: {
date: Date.now(),
ipAddress,
emailMessageId: (
exchangeUser.emailMessageId
),
emailToVerify: (
exchangeUser.emailToVerify
),
}
}
)
}
);
delete newExchangeUser.emailToVerify;
delete newExchangeUser.verifyEmailCode;
delete newExchangeUser.emailMessageId;
await updateDatabaseEntry({
tableName: EXCHANGE_USERS,
entry: newExchangeUser,
});
}
});
},
});
const responseValues = {};
console.log(
'verifyUserEmail executed successfully - ' +
`returning values: ${ stringify( responseValues ) }`
);
return responseValues;
});
<file_sep>import { createElement as e, useState } from 'react';
import { getState, setState, resetReduxX } from '../../reduxX';
import { bitcoinExchange } from '../../utils';
import { usefulComponents } from '..';
export default () => {
const [ clickCount, setClickCount ] = useState( 0 );
const isWarningMode = (clickCount < 4);
const isLoading = getState( 'isLoading' );
return e(
usefulComponents.POWBlock,
{
marginBottom: 40,
backgroundColor: isWarningMode ? 'darkred' : 'red',
onClick: async () => {
if( isWarningMode ) {
return setClickCount( clickCount + 1 );
}
try {
setState( 'isLoading', true );
const userId = getState(
'auth',
'userId'
);
const loginToken = getState(
'auth',
'loginToken'
);
await bitcoinExchange.deleteUser({
userId,
loginToken,
});
resetReduxX();
localStorage.clear();
}
catch( err ) {
setState( 'isLoading', false );
alert(
`error in deleting user: ${
(
!!err &&
!!err.response &&
!!err.response.data &&
!!err.response.data.message &&
err.response.data.message
) || 'internal server error'
}`
);
setClickCount( 0 );
}
},
text: isWarningMode ? (
'Delete User (requires 5 clicks)'
) : 'Delete User (are you sure?)',
isLoadingMode: isLoading,
marginTop: 100,
}
);
};
<file_sep>'use strict';
require( 'dotenv' ).config();
const yargs = require( 'yargs' );
const request = require( 'request-promise' );
const {
apiUrl,
token,
withdrawAddress
} = require( './values' );
const performOperation = async () => {
try {
const uri = `${ apiUrl }/withdraws`;
const body = {
address: withdrawAddress,
// address: [ 'ete', '34 '],
amount: 0.00007,
// includeFeeInAmount: true,
// enviroWithdrawAmount: 0.00002,
};
console.log(`
doing withdraw with body: ${ JSON.stringify( {
body
}, null, 4 ) }
`);
const response = await request({
uri,
method: 'POST',
json: true,
headers: {
'Content-Type': 'application/json',
'Token': token,
},
body,
resolveWithFullResponse: true,
});
console.log(`
The Results: ${ JSON.stringify( {
response: response.body
}, null, 4 ) }
`);
}
catch( err ) {
console.log(
'an error occurred in the request:',
err.message,
err.statusCode,
);
}
};
const theNumber = yargs.argv.theNumber || 1;
for( let i = 1; i <= theNumber; i++ ) {
performOperation();
}
<file_sep># v2
* constants metadata: new type-creationDate-index, new type (common api)
* support for adding raffle transactions (common exchange)
# v3
* new validation code to common exchange (common exchange)
* pagination fix - super ensure all results are gotten (common exchange)
# v4
* added validation and env validation function (common api)
* added bonuses (common exchange)
# v5
* Optimized ATAEUE (common exchange)
# v6
* drqPrivate (common api)
* no-search-default ATAEUE (common exchange)
# v6.1
* scan (common API)
* identity refresh transaction ataeue (common exchange)
# v7
* scan DB (common api)
* classical update DB (common api)
* constants: db dreamType lotus (common exchange)
* constants: Jackpot db key (common exchange)
* constants: searchId db transactions dreamLotus (common exchange)
* constants: queueIds -> jackpot win (common exchange)
* ataueu: handle dream lotus (common exchange)
# v8
* constants: constant dream types slot (common exchange)
* ataueu: handle dream slot (common exchange)
# v9 (in progress)
* BSC integration (alien evolution)<file_sep>'use strict';
const {
constants: {
withdraws: {
states: {
pending,
waiting,
},
},
aws: { database: { tableNames: { WITHDRAWS } } },
// environment: {
// isProductionMode
// }
},
utils: {
business: {
getIsValidWithdrawAmount
},
aws: {
dino: {
getDatabaseEntry,
updateDatabaseEntry
},
},
stringify,
bitcoin: {
validation: {
getIsValidAddress
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( async ({
userId, ultraKey
}) => {
console.log( 'running setUpWithdraw' );
const blessedWithdraw = await getDatabaseEntry({
tableName: WITHDRAWS,
value: userId,
sortValue: ultraKey
});
// safeguard
if( !blessedWithdraw || (blessedWithdraw.state !== pending) ) {
throw new Error(
'setUpWithdraw - ' +
`invalid blessed withdraw ${ stringify( blessedWithdraw ) }`
);
}
await updateDatabaseEntry({
tableName: WITHDRAWS,
entry: Object.assign(
{},
blessedWithdraw,
{
state: waiting
}
)
});
const {
amount,
addressToSendTo
} = blessedWithdraw;
const theWithdrawAmountIsInvalid = !getIsValidWithdrawAmount({
withdrawAmount: amount
});
if( theWithdrawAmountIsInvalid ) {
throw new Error(
'setUpWithdraw: ' +
`invalid amount attempted to be withdrew: ${ amount }`
);
}
else if( !getIsValidAddress( addressToSendTo ) ) {
throw new Error(
'setUpWithdraw: ' +
`invalid address specified: ${ addressToSendTo }`
);
}
const retrievedData = {
blessedWithdraw
};
console.log(
'setUpWithdraw executed successfully retrieved data: ' +
stringify( retrievedData )
);
return retrievedData;
});
<file_sep>'use strict';
const { database } = require( '../../aws' );
const stringify = require( '../../../stringify' );
const getEntriesToPutNowAndToPutLater = require(
'./getEntriesToPutNowAndToPutLater'
);
const getParams = require( './getParams' );
const handleUnprocessedItems = require( './handleUnprocessedItems' );
const handleResponseData = require( './handleResponseData' );
const putMultipleDatabaseEntries = Object.freeze( ({
tableName,
entries,
theResolve = null,
theReject = null
}) => {
console.log(
'running putMultipleDatabaseEntries.index ' +
'with the following values: ' +
stringify({ tableName, entries })
);
const {
entriesToPutNow,
entriesToPutLater
} = getEntriesToPutNowAndToPutLater({ entries });
const params = getParams({ tableName, entriesToPutNow })
console.log(
'database.putMultipleDatabaseEntries.index - ' +
`entriesToPutNow: ${ stringify( entriesToPutNow ) }, ` +
`params: ${ stringify( params ) }, `
);
return new Promise((
resolve,
reject
) => database.batchWrite( params, ( err, data ) => {
theResolve = theResolve || resolve;
theReject = theReject || reject;
if( !!err ) {
console.log(
'Error in batchWrite with the following values: ' +
stringify( params )
);
return theReject( err );
}
console.log(
'database.putMultipleDatabaseEntries.index: ' +
'aws.database.batchWrite retrieved results: ' +
stringify( data )
);
if(
!!data.UnprocessedItems &&
(Object.keys( data.UnprocessedItems ).length > 0)
) {
return handleUnprocessedItems({
putMultipleDatabaseEntries,
tableName,
entries,
theResolve,
theReject,
});
}
return handleResponseData({
data,
tableName,
entriesToPutNow,
entriesToPutLater,
putMultipleDatabaseEntries,
theResolve,
theReject
});
}));
});
module.exports = putMultipleDatabaseEntries;<file_sep>#!/usr/bin/env node
'use strict';
const argv = require( 'yargs' ).argv;
if( argv.mode === 'production' ) {
require( 'dotenv' ).config({
path: `${ __dirname }/../../productionCredentials/depositsBot/.env`
});
}
else {
require( 'dotenv' ).config({
path: `${ __dirname }/../../stagingCredentials/depositsBot/.env`
});
}
const {
mongo,
constants: {
mongo: {
collectionNames
}
}
} = require( '@bitcoin-api/full-stack-backend-private' );
const cleanAll = Object.freeze( async ({
collectionName,
collection,
}) => {
console.log(`
Running cleanAll: ${ JSON.stringify({
collectionName,
}, null, 4 )}
`);
await mongo.remove({
collection,
query: {},
justOne: false,
});
console.log(`
cleanAll executed successfully: ${ JSON.stringify({
collectionName,
}, null, 4 )}
`);
});
const cleanTheLocalDinoCache = Object.freeze( async ({
collections
}) => {
const [
userData, addressData
] = await Promise.all([
cleanAll({
collectionName: collectionNames.user_data,
collection: collections.user_data,
}),
cleanAll({
collectionName: collectionNames.address_data,
collection: collections.address_data,
}),
]);
console.log(`
cleanTheLocalDinoCache Results: ${ JSON.stringify({
userData,
addressData
}, null, 4 ) }
`);
});
(async () => {
const {
collections,
disconnect
} = await mongo.connect({
collectionNames: [
collectionNames.address_data,
collectionNames.user_data,
]
});
try {
console.log( '🧹cleaning the local dino cache🦖' );
await cleanTheLocalDinoCache({
collections
});
disconnect();
console.log( '🧽local dino cache cleaned successfully🦕' );
} catch( err ) {
disconnect();
console.log( '❌here is the mega error:', err );
}
})();<file_sep>'use strict';
const {
utils: {
bitcoin: {
formatting: { getAmountNumber }
}
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
transactions: {
types,
}
} = require( '../../../../../../constants' );
module.exports = Object.freeze( ({
theOracleOfDelphiDefi,
}) => {
const {
[types.withdrawBitcoin]: {
totalAmount
},
} = theOracleOfDelphiDefi;
const bitcoinWithdrawsData = {
currentState: 'power_omega',
lastUpdated: Date.now(),
totalAmount: getAmountNumber( totalAmount )
};
return bitcoinWithdrawsData;
});
<file_sep>'use strict';
const stringify = require( '../../../stringify' );
module.exports = Object.freeze( ({ tableName, entriesToPutNow }) => {
console.log(
'running putMultipleDatabaseEntries.getParams ' +
'with the following values: ' +
stringify({ tableName, entriesToPutNow })
);
const putCommands = [];
for( const entry of entriesToPutNow ) {
putCommands.push({ PutRequest: { Item: entry } });
}
const params = { RequestItems: { [ tableName ]: putCommands } };
console.log(
'putMultipleDatabaseEntries.getParams executed successfully ' +
`returning params: ${ stringify( params ) }`
);
return params;
});
<file_sep>'use strict';
const oneHour = 1000 * 60 * 60;
module.exports = Object.freeze( () => {
const thePowerOfNow = Date.now();
const timeFromHourUnder = thePowerOfNow % oneHour;
const currentHour = thePowerOfNow - timeFromHourUnder;
return currentHour;
});
<file_sep>'use strict';
require( 'dotenv' ).config();
const yargs = require( 'yargs' );
const { argv } = yargs;
const { delay } = require( 'bluebird' );
const request = require( 'request-promise' );
const {
exchangeApiUrl,
loginToken,
exchangeUserId,
withdrawAddress,
grecaptchaBypassHeaderKeyValue
} = require( './values' );
const withdraw = async i => {
try {
const uri = `${ exchangeApiUrl }/withdraws`;
const amount = yargs.argv.amount || yargs.argv.a || 0.00004;
const address = withdrawAddress;
await request({
uri,
json: true,
headers: {
'Content-Type': 'application/json',
'login-token': loginToken,
'user-id': exchangeUserId,
'grecaptcha-google-code': grecaptchaBypassHeaderKeyValue,
},
method: 'POST',
body: {
amount,
address,
// enviroWithdrawAmount: 0.000002,
},
resolveWithFullResponse: true,
});
console.log( `withdraw ${ i } end: ${ amount } BTC withdraw to "${ address }" successful` );
}
catch( err ) {
console.log( 'an error occurred in the request:', err.message );
}
};
(async () => {
const withdraws = [];
const numberOfWithdraws = argv.numberOfWithdraws || argv.n || 1;
for( let i = 1; i <= numberOfWithdraws; i++ ) {
await delay( 100 );
console.log(
`withdraw ${ i } start: ` +
'making request to POST /withdraws exchange API endpoint'
);
withdraws.push( withdraw( i ) );
}
await withdraws;
})();
<file_sep>'use strict';
const {
constants: {
environment: {
isProductionMode
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
if( isProductionMode ) {
process.env.BITCOIN_REQUEST_MODE = 'livenet';
}
const bitcoinRequest = require( 'bitcoin-request' );
module.exports = Object.freeze(({
args
}) => {
return bitcoinRequest({
command: args,
});
});<file_sep>import {
createElement as e,
} from 'react';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import doEnchantedLuck from './doEnchantedLuck';
import { getState } from '../../../../reduxX';
export default ({
freeGameMode
}) => {
const isLoading = getState( 'isLoading' );
return e(
Box,
{
style: {
width: '100%',
// height: 90,
marginTop: 50,
// backgroundColor: 'white',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
},
e(
Button,
{
disabled: isLoading,
style: {
// color: 'black',
// backgroundColor: 'white',
color: 'white',
borderColor: 'white',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
fontSize: 24,
},
onClick: async () => {
await doEnchantedLuck({
freeGameMode,
});
},
variant: 'outlined'
},
'0.0001 DB Spin'
// 'Buy $Barmy'
)
);
};
<file_sep>'use strict';
const uuidv4 = require( 'uuid/v4' );
const {
utils: {
doOperationInQueue,
stringify,
business: {
getIsValidWithdrawAmount
},
javascript: {
getQueueId
},
database:{
metadata: {
metaGetFeeToPayFromFeeData
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser,
getExchangeUser,
}
}
},
constants: {
transactions: {
types,
bitcoinWithdrawTypes
},
aws: {
database: {
tableNames: {
EXCHANGE_USERS
}
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
exchangeUsers: {
getBalanceData
}
} = require( '../../../../../exchangeUtils' );
const {
constants: {
http: {
headers
}
}
} = require( '../../../../../utils' );
const validateAndGetValues = require( './validateAndGetValues' );
const getFeeData = require( '../../../../withdraws/POST/withdrawMoney/getFeeData' );
const getMagnaFeeData = require( '../../../../withdraws/POST/withdrawMoney/doWithdrawMoney/getMagnaFeeData' );
const ensureExchangeUserHasEnoughMoney = require( './ensureExchangeUserHasEnoughMoney' );
const putVanguardWithdraw = require( './putVanguardWithdraw' );
// const exchangeFeeToAdd = 0.000001;
const doWithdrawCore = Object.freeze( async ({
exchangeUserId,
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount,
rawShouldDoFullWithdraw,
ipAddress,
rawGoogleCode,
}) => {
const {
withdrawAmount,
addressToSendTo,
shouldIncludeFeeInAmount,
enviroWithdrawAmount,
shouldDoFullWithdraw,
} = await validateAndGetValues({
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount,
rawShouldDoFullWithdraw,
ipAddress,
rawGoogleCode,
});
if( shouldDoFullWithdraw ) {
console.log(
'doWithdraw: ' +
'doing full withdraw - getting the exchange user'
);
const exchangeUser = await getExchangeUser({
exchangeUserId,
});
const balanceData = getBalanceData({
exchangeUser,
});
const totalAmountUserHas = (
balanceData.summary.bitcoin.totalAmount
);
const totalWithdrawAmount = (
totalAmountUserHas -
(
// exchangeFeeToAdd +
enviroWithdrawAmount
)
);
console.log(
'doWithdraw: ' +
'got the exchange user and here is the relevant money data ' +
`for the user: ${
stringify({
totalAmountUserHas,
// exchangeFeeToAdd,
enviroWithdrawAmount,
['the calculation']: (
`const totalWithdrawAmount = (
totalAmountUserHas -
(
/* exchangeFeeToAdd + */
enviroWithdrawAmount
)
);`
),
totalWithdrawAmount
})
}`
);
const theWithdrawAmountIsInvalid = !getIsValidWithdrawAmount({
withdrawAmount: totalWithdrawAmount
});
if(
theWithdrawAmountIsInvalid ||
(totalWithdrawAmount < 0.00025)
) {
const validationError = new Error(
`invalid withdraw amount: ${ totalWithdrawAmount }`
);
validationError.bulltrue = true;
validationError.statusCode = 400;
throw validationError;
}
const feeData = getMagnaFeeData({
feeData: await getFeeData(),
enviroWithdrawAmount,
// exchangeFeeToAdd,
});
const metaFeeToPay = metaGetFeeToPayFromFeeData(
{
shouldIncludeFeeInAmount: true
},
{
feeData,
}
);
const withdrawId = uuidv4();
await addTransactionAndUpdateExchangeUser({
noLocka: true,
exchangeUserId,
type: types.withdrawBitcoin,
data: {
address: addressToSendTo,
amount: totalWithdrawAmount,
fee: metaFeeToPay,
withdrawId,
bitcoinWithdrawType: bitcoinWithdrawTypes.start,
isFullWithdraw: true,
feeIncludedInAmount: true,
},
});
await putVanguardWithdraw({
addressToSendTo,
amount: totalWithdrawAmount,
feeData,
shouldIncludeFeeInAmount: true,
withdrawId,
exchangeUserId,
});
const doWithdrawResults = {};
console.log(
'doWithdraw - withdraw full amount - ' +
`executed successfully - returning values ${
stringify( doWithdrawResults )
}`
);
return doWithdrawResults;
}
const feeData = getMagnaFeeData({
feeData: await getFeeData(),
enviroWithdrawAmount,
// exchangeFeeToAdd,
});
const {
metaFeeToPay
} = await ensureExchangeUserHasEnoughMoney({
withdrawAmount,
shouldIncludeFeeInAmount,
feeData,
exchangeUserId,
});
const withdrawId = uuidv4();
await addTransactionAndUpdateExchangeUser({
noLocka: true,
exchangeUserId,
type: types.withdrawBitcoin,
data: {
address: addressToSendTo,
amount: withdrawAmount,
fee: metaFeeToPay,
withdrawId,
bitcoinWithdrawType: bitcoinWithdrawTypes.start,
feeIncludedInAmount: shouldIncludeFeeInAmount,
},
});
await putVanguardWithdraw({
addressToSendTo,
amount: withdrawAmount,
feeData,
shouldIncludeFeeInAmount,
withdrawId,
exchangeUserId,
});
const doWithdrawResults = {};
console.log(
`doWithdraw executed successfully - returning values ${
stringify( doWithdrawResults )
}`
);
return doWithdrawResults;
});
module.exports = Object.freeze( async ({
event,
ipAddress,
exchangeUserId
}) => {
const requestBody = event.body;
const rawAmount = (
requestBody.amount
) || null;
const rawShouldIncludeFeeInAmount = (
requestBody.includeFeeInAmount
) || false;
const rawShouldDoFullWithdraw = (
requestBody.fullWithdraw
) || false;
const rawAddress = requestBody.address;
// const rawEnviroWithdrawAmount = requestBody.enviroWithdrawAmount;
const rawEnviroWithdrawAmount = null; // NOTE: for now
const rawGoogleCode = event.headers[ headers.grecaptchaGoogleCode ];
console.log(
`running doWithdraw with the following values - ${ stringify({
exchangeUserId,
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount,
rawShouldDoFullWithdraw,
ipAddress,
rawGoogleCode
}) }`
);
const doWithdrawResults = await doOperationInQueue({
queueId: getQueueId({ type: EXCHANGE_USERS, id: exchangeUserId }),
doOperation: async () => {
return await doWithdrawCore({
exchangeUserId,
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount,
rawShouldDoFullWithdraw,
ipAddress,
rawGoogleCode,
});
}
});
console.log(
`doWithdraw executed successfully - returning values ${
stringify( doWithdrawResults )
}`
);
return doWithdrawResults;
});
<file_sep>#!/bin/sh
####
#### Common Code
####
pushd ../../../../0-commonCode/exchange
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install
popd
####
#### Backend
####
pushd ../../../../1-backend/commonUtilities
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install bqe@latest --save
npm install bitcoin-request@latest --save
npm install
popd
####
#### Backend Giraffe Lick Leaf
####
pushd ../../../../1-backend/giraffeDeploy/commonUtilities
npm install @bitcoin-api/full-stack-api-private@latest --save
npm install
popd
<file_sep>export { default as getBitcoinAmountNumber } from './getBitcoinAmountNumber';<file_sep>'use strict';
const { database } = require( '../aws' );
const stringify = require( '../../stringify' );
const searchDatabase = Object.freeze( ({
searchParams,
theResolve = null,
theReject = null,
}) => {
const ultraLimit = searchParams.Limit;
if( !ultraLimit ) {
return Promise.reject( new Error( 'missing ultraLimit' ) );
}
console.log(
'Running database.searchDatabase with the following values: ' +
stringify({ searchParams })
);
return new Promise( (
resolve, reject
) => database.query( searchParams, ( err, data = {} ) => {
theResolve = theResolve || resolve;
theReject = theReject || reject;
if( !!err ) {
console.log(
'Error in database.searchDatabase ' +
'with the following values: ' +
stringify( searchParams )
);
return theReject( err );
}
const results = ( !!data.Items && data.Items ) || [];
const ultimateResults = results.slice();
if( !!data && !!data.LastEvaluatedKey ) {
const paginationValue = Object.assign( {}, data.LastEvaluatedKey );
console.log(
'database.searchDatabase: ' +
'the limit has been hit, returning the super response -- ' +
`pagination value: ${ stringify( paginationValue ) }`
);
return theResolve({
ultimateResults,
paginationValue
});
}
console.log(
'database.searchDatabase successfully executed, ' +
`retrieved ${ ultimateResults.length } results`
);
theResolve({
ultimateResults,
paginationValue: null
});
}));
});
module.exports = searchDatabase;<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase,
}
},
stringify,
},
constants: {
metadata: {
types: {
raffle
}
}
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
TRANSACTIONS
},
secondaryIndices: {
exchangeUserIdCreationDateIndex,
}
}
},
raffles: {
types: {
putTicket,
payout
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
crypto: {
getCryptoAmountNumber
}
} = require( '../../../../../exchangeUtils' );
const {
raffle: {
getChoiceTimeData
}
} = require( '../../../../../enchantedUtils' );
const searchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
exchangeUserId: '#exchangeUserId',
searchId: '#searchId',
type: '#type',
creationDate: '#creationDate',
}),
nameValues: f({
exchangeUserId: 'exchangeUserId',
searchId: 'searchId',
type: 'type',
creationDate: 'creationDate',
}),
valueKeys: f({
exchangeUserId: ':exchangeUserId',
searchId: ':searchId',
type: ':type',
startTime: ':startTime',
endTime: ':endTime'
}),
valueValues: f({
type: raffle,
})
});
module.exports = Object.freeze( async ({
raffleId,
exchangeUserId,
startTime = 1,
endTime = Date.now(),
}) => {
console.log(
'running getRaffleDataForExchangeUser ' +
`with the following values - ${ stringify({
raffleId,
exchangeUserId,
startTime,
endTime,
}) }`
);
const rawRaffleDataForExchangeUser = {
choiceToPutTicketData: {},
winData: null
};
let paginationValueToUse = null;
let iterationCount = 0;
do {
console.log(
'getRaffleDataForExchangeUser - ' +
'running transactions search: ' +
stringify({
paginationValueToUse,
iterationCount,
})
);
const searchParams = {
TableName: TRANSACTIONS,
IndexName: exchangeUserIdCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: true,
// ProjectionExpression: [
// // attributes
// ].join( ', ' ), // TODO:
KeyConditionExpression: (
`${ attributes.nameKeys.exchangeUserId } = ` +
`${ attributes.valueKeys.exchangeUserId } and ` +
`${ attributes.nameKeys.creationDate } between ` +
`${ attributes.valueKeys.startTime } and ` +
`${ attributes.valueKeys.endTime }`
),
FilterExpression: (
`${ attributes.nameKeys.type } = ` +
`${ attributes.valueKeys.type } and ` +
`${ attributes.nameKeys.searchId } = ` +
`${ attributes.valueKeys.searchId }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.exchangeUserId]: attributes.nameValues.exchangeUserId,
[attributes.nameKeys.type]: attributes.nameValues.type,
[attributes.nameKeys.searchId]: attributes.nameValues.searchId,
[attributes.nameKeys.creationDate]: attributes.nameValues.creationDate,
},
ExpressionAttributeValues: {
[attributes.valueKeys.exchangeUserId]: exchangeUserId,
[attributes.valueKeys.type]: attributes.valueValues.type,
[attributes.valueKeys.searchId]: raffleId,
[attributes.valueKeys.startTime]: startTime,
[attributes.valueKeys.endTime]: endTime,
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const raffleTransactions = ultimateResults;
for( const transaction of raffleTransactions ) {
if( transaction.raffleType === putTicket ) {
const existingPutTicketData = (
rawRaffleDataForExchangeUser.choiceToPutTicketData[
transaction.choice
]
) || {
amount: 0
};
const newAmount = getCryptoAmountNumber(
transaction.amount +
existingPutTicketData.amount
);
if( newAmount === 0 ) {
delete rawRaffleDataForExchangeUser
.choiceToPutTicketData[ transaction.choice ];
}
else {
rawRaffleDataForExchangeUser.choiceToPutTicketData[
transaction.choice
] = {
amount: newAmount,
lastCancelTime: getChoiceTimeData({
timestamp: transaction.creationDate
}).lastCancelTime,
};
}
}
else if( transaction.raffleType === payout ) {
if( !!rawRaffleDataForExchangeUser.winData ) {
throw new Error(
'getRaffleDataForExchangeUser error - ' +
`multiple payouts for raffle ${ raffleId }: ` +
JSON.stringify( transaction, null, 4 )
);
}
rawRaffleDataForExchangeUser.winData = {
hasWon: true,
amount: transaction.amount
};
}
}
if( !!paginationValue ) {
paginationValueToUse = paginationValue;
iterationCount++;
}
else if( !!paginationValueToUse ) {
paginationValueToUse = null;
}
} while( !!paginationValueToUse );
const raffleDataForExchangeUser = {
choices: Object.keys(
rawRaffleDataForExchangeUser.choiceToPutTicketData
).map(
choice => {
const putTicketData = (
rawRaffleDataForExchangeUser
.choiceToPutTicketData[ choice ]
);
return {
choice,
amount: Math.abs( putTicketData.amount ),
lastCancelTime: putTicketData.lastCancelTime
};
}
),
winData: rawRaffleDataForExchangeUser.winData || {
hasWon: false,
amount: 0
}
};
console.log(
'getRaffleDataForExchangeUser executed successfully, ' +
`returning raffleDataForExchangeUser ${ stringify(
raffleDataForExchangeUser
) }`
);
return raffleDataForExchangeUser;
});<file_sep>'use strict';
module.exports = Object.freeze({
dino: require( './dino' ),
dinoCombos: require( './dinoCombos' ),
});
<file_sep>export { default as getDecodedPasswordResetCode } from './getDecodedPasswordResetCode';
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
crypto: {
getCryptoAmountNumber
}
},
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
dream: {
getJackpotMetadata,
}
} = require( '../../../../../enchantedUtils' );
module.exports = Object.freeze( async ({
// event,
// ipAddress,
exchangeUserId
}) => {
console.log(
`running 😎 getDreamsLotusJackpotData 😎
with the following values - ${
stringify({
exchangeUserId,
// ipAddress,
// rawAmount,
// rawGoogleCode,
})
}`
);
const jackpotMetadata = await getJackpotMetadata();
const rawJackpotAmount = jackpotMetadata.jackpotAmount;
const jackpotAmount = getCryptoAmountNumber( rawJackpotAmount );
const jackpotData = {
jackpotAmount,
};
console.log(
`😎 getDreamsLotusJackpotData 😎
executed successfully -
returning the following values - ${
stringify( jackpotData )
}`
);
return jackpotData;
});
<file_sep>'use strict';
module.exports = Object.freeze({
jsonEncoder: require( './jsonEncoder' ),
getVanguardQueueId: require( './getVanguardQueueId' ),
getQueueId: require( './getQueueId' ),
getRandomIntInclusive: require( './getRandomIntInclusive' ),
getEnvNumberValue: require( './getEnvNumberValue' ),
getIfEnvValuesAreValid: require( './getIfEnvValuesAreValid' ),
});<file_sep>'use strict';
const getTemplarCode = require( './getTemplarCode' );
const getETCData = require( './getETCData' );
const { users: { USER_ID_LENGTH } } = require( '../constants' );
const getReturnCode = Object.freeze( ({
userId,
megaCode
}) => {
console.log( 'running getReturnCode' );
const returnCode = `${ megaCode }${ userId }`;
console.log( 'getReturnCode executed successfully, returning returnCode' );
return returnCode;
});
const getDecodedReturnCode = Object.freeze( ({
returnCode,
}) => {
console.log( 'running getDecodedReturnCode' );
const userIdIndex = (returnCode.length - USER_ID_LENGTH);
const userId = returnCode.substring( userIdIndex );
const megaCode = returnCode.substring( 0, userIdIndex );
console.log(
'getDecodedReturnCode executed successfully, ' +
'returning decodedReturnCode'
);
return {
userId,
megaCode
};
});
module.exports = Object.freeze({
getReturnCode,
getDecodedReturnCode,
getTemplarCode,
getETCData,
});<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
// const {
// constants: {
// exchanges: {
// bounds
// }
// },
// } = require( '@bitcoin-api/full-stack-exchange-private' );
// const {
// enchantedModes,
// enchantedModesToEnchantedData
// minAmount,
// maxAmount
// } = require( './localConstants' );
// const {
// crypto: {
// getCryptoAmountNumber
// }
// } = require( '../../../../../exchangeUtils' );
const {
constants: {
google: {
captcha: {
actions
}
}
},
business: {
verifyGoogleCode
}
} = require( '../../../../../utils' );
module.exports = Object.freeze( async ({
// rawAmount,
ipAddress,
rawGoogleCode,
}) => {
console.log(
`running validateAndGetValues with values: ${ stringify({
// rawAmount,
ipAddress,
rawGoogleCode,
}) }`
);
// if(
// !rawMode ||
// (typeof rawMode !== 'string') ||
// !enchantedModes[ rawMode ]
// ) {
// const validationError = new Error(
// `invalid mode: ${ rawMode }`
// );
// validationError.bulltrue = true;
// validationError.statusCode = 400;
// throw validationError;
// }
// if(
// !rawAmount ||
// (typeof rawAmount !== 'number') ||
// (rawAmount < minAmount) ||
// (rawAmount > maxAmount)
// ) {
// const validationError = new Error(
// `invalid amount: ${ rawAmount }`
// );
// validationError.bulltrue = true;
// validationError.statusCode = 400;
// throw validationError;
// }
await verifyGoogleCode({
rawGoogleCode,
ipAddress,
expectedAction: actions.slotSpin,
});
const results = {
// amount: enchantedModesToEnchantedData[ rawMode ].cryptoAmount,
// amount: getCryptoAmountNumber( rawAmount )
};
console.log(
'validateAndGetValues executed successfully, ' +
'here are the values: ' +
stringify( results )
);
return results;
});
<file_sep>'use strict';
const updateBalance = require( '../../updateBalance' );
const {
withdraws: {
states: {
complete,
pending
}
},
users: {
balanceTypes: {
normalWithdraw
}
},
} = require( '../../../../../../constants' );
const getWithdrawData = require( './getWithdrawData' );
module.exports = Object.freeze( async ({
userId,
// totalAmountForCurrentWithdraw,
normalWithdrawId,
// withdrawId
}) => {
console.log( 'running refreshBalance' );
const {
totalWithdrawAmount,
balanceIsInTransformationState,
} = await getWithdrawData({
userId,
});
await updateBalance({
userId,
newBalance: totalWithdrawAmount,
balanceType: normalWithdraw,
balanceId: normalWithdrawId,
state: balanceIsInTransformationState ? pending : complete,
shouldDoOperationWithLock: false
});
console.log( 'refreshBalance executed successfully' );
});<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
validation: {
getIfVoteIdIsValid
}
} = require( '../../../../../../exchangeUtils' );
module.exports = Object.freeze( ({
rawVoteId,
}) => {
console.log(
`running validateAndGetValues
with the following values - ${ stringify({
voteId: rawVoteId,
})
}`
);
const voteIdIsInvalid = !getIfVoteIdIsValid({
voteId: rawVoteId,
});
if( voteIdIsInvalid ) {
console.log(
'validateAndGetValues - invalid voteId provided'
);
const err = new Error( 'invalid voteId provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
const values = {
voteId: rawVoteId,
};
console.log(
'validateAndGetValues executed successfully - got values: ' +
stringify( values )
);
return values;
});
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const execa = require( 'execa' );
const del = 'delete';
const getExecaArgs = Object.freeze( ({
mainFileName,
}) => {
const args = [
del,
mainFileName,
];
return args;
});
module.exports = Object.freeze( async ({
log,
trueTigerPath,
mainFileName
}) => {
log(
'🛑🐯running stopPmTiger - ' +
stringify({
trueTigerPath,
mainFileName
})
);
try {
await execa(
'pm2',
getExecaArgs({
mainFileName
}),
{
cwd: trueTigerPath
}
);
}
catch( err ) {
log(
'🛑🐯stopPmTiger acceptable error',
'in stopping pm2 instance:',
err
);
}
log( '🛑🐯stopPmTiger executed successfully' );
});
<file_sep>import * as destinyRaffle from './destinyRaffle';
export {
destinyRaffle,
};
<file_sep>import { createElement as e } from 'react';
import { getState } from '../../../../reduxX';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
// import {
// usefulComponents
// } from '../../../../TheSource';
import Box from '@material-ui/core/Box';
// import DayBox from './DayBox';
// import Buttons from './Buttons';
// import Typography from '@material-ui/core/Typography';
// import Button from '@material-ui/core/Button';
import ViewDraws from './ViewDraws';
import ViewAllTickets from './ViewAllTickets';
// const getAlignItems = () => {
// const windowWidth = getState( 'windowWidth' );
// const largeScreenMode = (windowWidth > 700);
// console.log(`
// MEGA LOG: ${ JSON.stringify( {
// windowWidth,
// largeScreenMode
// }, null, 4 ) }
// `);
// if( largeScreenMode ) {
// return 'top';
// }
// return 'center';
// };
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
const windowWidth = getState( 'windowWidth' );
const largeScreenMode = (windowWidth > 700);
const {
metaContainer,
spacerBox,
} = largeScreenMode ? {
metaContainer: {
justifyContent: 'space-between',
flexDirection: 'row',
alignItems: 'start',
},
spacerBox: {
},
} : {
metaContainer: {
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
},
spacerBox: {
height: 20,
width: 5,
},
};
return {
metaContainer: Object.assign(
{
width: '90%',
display: 'flex',
// flexDirection,
// justifyContent,
// alignItems: 'center',
// alignItems: 'top',
// alignItems,
marginTop: 15,
marginBottom: 15,
},
metaContainer
),
spacerBox: Object.assign(
{},
spacerBox
),
};
};
export default ({
raffleDatum
}) => {
const styles = getStyles();
return e(
Box,
{
style: styles.metaContainer,
},
e(
ViewDraws,
{
raffleDatum,
}
),
e(
Box,
{
style: styles.spacerBox
}
),
e(
ViewAllTickets,
{
raffleDatum,
}
)
);
};
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
deployCommands,
}
} = require( '@bitcoin-api/giraffe-utils' );
const depositsBotSpecialTigerFunction = require( './depositsBotSpecialTigerFunction' );
const f = Object.freeze;
const deployCommandToSpecialTigerFunctionData = f({
[deployCommands.feeDataBot]: f({}),
[deployCommands.withdrawsBot]: f({}),
[deployCommands.depositsBot]: f({
specialTigerFunction: depositsBotSpecialTigerFunction
}),
});
module.exports = Object.freeze( async ({
deployCommand,
log,
}) => {
log( `🐯🌈🍁running performTigerEnlightenmentSpecialFunction -
${ stringify({
deployCommand
})}
`
);
const {
specialTigerFunction = async () => {},
} = deployCommandToSpecialTigerFunctionData[ deployCommand ];
await specialTigerFunction({
log
});
log(
'🐯🌈🍁performTigerEnlightenmentSpecialFunction executed successfully'
);
});
<file_sep>export default password => {
const passwordIsValid = (
!!password &&
(typeof password === 'string') &&
(password.length >= 8) &&
(password.length <= 100)
);
return passwordIsValid;
};
<file_sep>'use strict';
const STATUS_CODE_MESSAGE = 'validation_error';
class ValidationError extends Error {
constructor( message ) {
super( message );
this.statusCode = 400;
this.statusCodeMessage = STATUS_CODE_MESSAGE;
}
}
ValidationError.statusCodeMessage = STATUS_CODE_MESSAGE;
module.exports = ValidationError;<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import { story } from '../../../../constants';
import { setState } from '../../../../reduxX';
// import Link from '@material-ui/core/Link';
// import Typography from '@material-ui/core/Typography';
// import Divider from '@material-ui/core/Divider';
// import LegalSection from './LegalSection';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'beige',
width: '100%',
maxWidth: 620,
minWidth: 300,
// height: 40,
// backgroundColor: 'pink',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
row: {
width: '100%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
marginTop: 25,
marginBottom: 30,
},
outerContainerRow2: {
width: 160,
backgroundColor: 'white',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
marginTop: 35,
borderRadius: 5,
},
row2Title: {
color: 'black',
width: '91%',
// width: '100%',
// marginLeft: 10,
marginTop: 10,
},
row2Divider: {
width: '91%',
backgroundColor: 'black',
},
row2: {
width: '91%',
// width: '100%',
backgroundColor: 'white',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
borderRadius: 10,
// marginTop: 30,
},
button: {
// backgroundColor: 'beige',
// width: '85%',
// height: 40,
color: 'white',
},
link: {
color: 'black',
paddingTop: 10,
paddingBottom: 10,
// marginRight: 20,
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.row,
},
e(
Button,
{
style: styles.button,
onClick: () => {
setState(
[ 'dialogMode' ],
story.dialogModes.about
);
},
},
'About'
),
e(
Button,
{
style: styles.button,
onClick: () => {
setState(
[ 'dialogMode' ],
story.dialogModes.faq
);
},
},
'FAQ'
)
),
// e(
// Divider,
// {
// style: {
// width: '64%',
// backgroundColor: 'beige',
// marginTop: 30,
// }
// }
// ),
// e(
// Box,
// {
// style: styles.outerContainerRow2,
// },
// e(
// Typography,
// {
// style: styles.row2Title,
// },
// 'On the Web'
// ),
// e(
// Divider,
// {
// style: styles.row2Divider,
// }
// ),
// e(
// Box,
// {
// style: styles.row2,
// },
// e(
// Link,
// {
// style: styles.link,
// href: 'https://twitter.com/DynastyBitcoin',
// target: '_blank',
// rel: 'noopener',
// },
// 'Twitter'
// )//,
// // e(
// // Link,
// // {
// // style: styles.link,
// // href: 'https://discord.gg/TdHHvsg',
// // target: '_blank'
// // },
// // 'Discord'
// // )
// )
// )
);
};
<file_sep>'use strict';
const {
utils: {
aws: { dino: { updateDatabaseEntry } },
database: {
metadata: {
getFeeData
}
}
},
constants: {
aws: {
database: {
// tableNameToKey,
tableNames: { METADATA },
// metadataPartitionKeyValues: { feeData }
}
},
environment: {
isProductionMode
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
doBitcoinRequest,
constants: {
megaServerId
}
} = require( '@bitcoin-api/full-stack-backend-private' );
const feeMultiplier = isProductionMode ? 0.15 : 1;
// const feeMultiplier = isProductionMode ? 0.008 : 1;
const defaultFeeRate = 0.0002;
// const blessingFee = 0.00000100;
// const trinityFee = 0;
// const sacramentFee = 0;
/*
0.0002 feerate equals 1.07 Canadian Dollar default
[for a 1kB transaction (supposedly default is 250kB)]
Mar. 25, 2:04 a.m. UTC
*/
// update march 26 2021: the above was from 2020
module.exports = Object.freeze( () => {
console.log( 'running updateFee, YES🐺💰💰💰💰' );
const args = [
'estimatesmartfee',
'6'
];
return doBitcoinRequest({ args }).then( results => {
const parsedBitcoinRequestResults = JSON.parse( results );
const rawFeerateValue = parsedBitcoinRequestResults.feerate;
const rawFeerateValueAsNumber = Number( rawFeerateValue );
const fee = Number.isNaN( rawFeerateValueAsNumber ) ? (
defaultFeeRate
) : rawFeerateValueAsNumber;
const tableName = METADATA;
const entry = getFeeData({
fee,
feeMultiplier,
businessFeeData: {
// can customize fee values here
// payroll: {
// amount: 0.00001,
// },
// insurance: {
// amount: 0.00002,
// },
// commission: {
// amount: 0.00003,
// },
},
megaServerId
});
return updateDatabaseEntry({
tableName,
entry,
});
}).then( () => {
console.log(`
updateFee executed successfully, YES YES YES🐺💰💰💰💰
`);
});
});
<file_sep>import getUserData from './getUserData';
import setPage from './setPage';
import { actions } from '../../../utils';
export default () => {
return Promise.resolve().then( async () => {
try {
setPage();
await getUserData();
}
catch( err ) {
console.log( 'error componentDidMount for LoggedInMode', err );
actions.signOut();
}
});
};
<file_sep>'use strict';
const GMAIL_DOT_COM = 'gmail.com';
const getPureEmailFromGmail = Object.freeze( ({
lowerCaseEmailFirstPart,
}) => {
const emailFirstPartSplitWithPlus = (
lowerCaseEmailFirstPart.split( '+' )
);
const pureEmailFirstPart = emailFirstPartSplitWithPlus[ 0 ];
const pureEmailFirstPartNoDots = pureEmailFirstPart.replace( /\./g, '' );
const pureEmail = `${ pureEmailFirstPartNoDots }@${ GMAIL_DOT_COM }`;
return pureEmail;
});
// assumes email has been validated already
module.exports = Object.freeze( ({
rawEmail
}) => {
const lowerCaseEmail = rawEmail.toLowerCase();
const lowerCaseEmailParts = lowerCaseEmail.split( '@' );
if( lowerCaseEmailParts.length !== 2 ) {
// NOTE: safeguard
const err = new Error( 'invalid email provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
const isGoogleEmail = (
lowerCaseEmailParts[ lowerCaseEmailParts.length - 1 ] ===
GMAIL_DOT_COM
);
if( isGoogleEmail ) {
return getPureEmailFromGmail({
lowerCaseEmailFirstPart: lowerCaseEmailParts[0]
});
}
return lowerCaseEmail;
});
<file_sep>'use strict';
module.exports = Object.freeze({
getIfAddressShouldBeReclaimed: require( './getIfAddressShouldBeReclaimed' ),
});
<file_sep>'use strict';
const {
constants: {
aws: {
database: {
tableNames: {
METADATA
},
}
},
},
utils: {
stringify,
aws: {
dino: {
getDatabaseEntry
},
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
metadataKeys: {
dreamLotus
}
}
},
},
} = require( '@bitcoin-api/full-stack-exchange-private' );
module.exports = Object.freeze( async () => {
console.log(
'running getJackpotMetadata with the following values: ' +
stringify({})
);
const jackpotMetadata = await getDatabaseEntry({
tableName: METADATA,
value: dreamLotus,
});
if( !jackpotMetadata ) {
// safeguard
throw new Error( 'weird error: missing jackpot metadata' );
}
console.log(
'getJackpotMetadata executed successfully: ' +
stringify({
responseKeys: Object.keys( jackpotMetadata )
})
);
return jackpotMetadata;
});
<file_sep>'use strict';
module.exports = Object.freeze({
getCryptoAmountNumber: require( './getCryptoAmountNumber' ),
});
<file_sep>import { createElement as e, useEffect } from 'react';
import { getState, setState } from '../../../reduxX';
import { story } from '../../../constants';
import { grecaptcha, actions } from '../../../utils';
import {
VerifyEmailPolygon,
usefulComponents
} from '../../../TheSource';
const getStyles = () => {
const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: mainStyleObject.backgroundColor,
width: 300,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
color: 'white',
},
};
};
export default () => {
useEffect( () => {
actions.scroll();
grecaptcha.showGrecaptcha();
return () => {
setState({
keys: [ 'ultraTools', 'fastMessageData' ],
value: null
});
Promise.resolve().then( async () => {
try {
await grecaptcha.hideGrecaptcha();
}
catch( err ) {
console.log( 'error in hiding grecaptcha:', err );
}
});
};
}, [] );
const isLoading = getState( 'isLoading' );
const styles = getStyles();
const createElementArguments = [
'div',
{
style: styles.outerContainer,
},
e(
usefulComponents.FastMessage,
{
marginTop: 20,
marginBottom: 20,
}
),
e( VerifyEmailPolygon ),
e(
usefulComponents.Nav,
{
isLoadingMode: isLoading,
marginTop: 100,
marginBottom: 40,
text: 'Home',
onClick: () => {
setState(
[ 'notLoggedInMode', 'mainMode' ],
story.NotLoggedInMode.mainModes.initialChoiceMode
);
},
}
)
];
return e( ...createElementArguments );
};
<file_sep>'use strict';
module.exports = Object.freeze( ({ min, max }) => {
min = Math.ceil( min );
max = Math.floor( max );
return Math.floor( Math.random() * ( max - min + 1 ) ) + min;
});<file_sep>'use strict';
const lotteryTypes = {
twoNumber: 'twoNumber',
};
module.exports = Object.freeze({
raffle: {
raffleId: {
prefix: 'raffle_',
maxLength: 100,
minLength: 10,
},
raffleDrawId: {
prefix: 'raffle_draw_',
maxLength: 122,
minLength: 10,
},
lotteryTypes,
bounds: {
[lotteryTypes.twoNumber]: {
minTicketNumber: 1,
maxTicketNumber: 36
},
},
}
});
<file_sep># Tree Update Instructions
S=server
H=home
## Full
S) Recreate Tree Folders
H) ./plantTree
S) Install Tree NPM
### ➕
# Partial
H) Run Giraffe
S) Run Tree
<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const safeWriteReportToFile = require( './safeWriteReportToFile' );
module.exports = Object.freeze( ({
userId,
ultraKey,
feeData,
balanceBeforeWithdraw,
balanceAfterWithdraw,
amount,
feeToChargeTheBitcoinNode,
transactionId,
shouldIncludeFeeInAmount
}) => {
const balanceDifference = balanceBeforeWithdraw - balanceAfterWithdraw;
const theActualFee = balanceDifference - amount;
const withdrawReport = {
['Balance before withdraw']: balanceBeforeWithdraw,
['Balance after withdraw']: balanceAfterWithdraw,
['Balance difference']: balanceDifference,
['Amount withdrew']: amount,
['Desired fee (base fee)']: feeToChargeTheBitcoinNode,
['Actual fee']: theActualFee,
['Desired fee - acutal fee']: feeToChargeTheBitcoinNode - theActualFee,
['The metadata']: {
userId,
ultraKey,
feeData,
transactionId
},
['Should Include Fee in Amount']: shouldIncludeFeeInAmount,
};
console.log(`
🦕Here is the Grand Withdraw Report🦖
${stringify( withdrawReport )}
`);
safeWriteReportToFile({
withdrawReport
});
});<file_sep>'use strict';
const getCryptoAmountNumber = require( '../../crypto/getCryptoAmountNumber' );
module.exports = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const voteBalanceDataFromExchangeUser = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.vote &&
exchangeUser.moneyData.vote
) || null;
const voteBalanceData = {};
if( !voteBalanceDataFromExchangeUser ) {
voteBalanceData.crypto = {
totalAmount: 0,
};
}
else {
voteBalanceData.crypto = {
totalAmount: getCryptoAmountNumber(
voteBalanceDataFromExchangeUser.crypto.amount
) || 0,
};
}
balanceData.vote = voteBalanceData;
});
<file_sep>'use strict';
module.exports = Object.freeze({
minAmount: 0.00001,
// maxAmount: 0.00008,
maxAmount: 0.001, //00
});<file_sep>'use strict';
const {
accessCodeTools: {
getReturnCode,
getETCData
},
} = require( '../../../../utils' );
const getUserId = require( './getUserId' );
const addUserToDatabase = require( './addUserToDatabase' );
module.exports = Object.freeze( async ({
ipAddress
}) => {
console.log( 'running doLogin' );
const {
megaCode,
encryptedTemplarCode,
encryptionId
} = getETCData();
const userId = getUserId();
await addUserToDatabase({
userId,
accessCode: encryptedTemplarCode,
metadata: {
experientialIdentifier: 3.01,
initialIpAddress: ipAddress,
creationDate: Date.now(),
// bypassed activation
isHumanInformation: {
humanIpAddress: 'Ip Man (<NAME>)',
humanScore: 420,
isHuman: true,
timeOfHumanProof: 'Right now baby!!!',
},
privacyPolicy: {
agrees: true,
ipAddressOfAgreement: 'drIp (Wunna Gunna)',
timeOfAgreement: 'The Power of Now'
},
tos: {
agrees: true,
ipAddressOfAgreement: '69',
timeOfAgreement: 'Protoss'
},
},
encryptionId,
});
const token = getReturnCode({ userId, megaCode });
console.log(
'doLogin executed successfully, returning the token in an object.'
);
return {
token
};
});<file_sep>'use strict';
const getFeeToPayFromFeeData = require( './getFeeToPayFromFeeData' );
const stringify = require( '../../stringify' );
const getMetaFeeToPay = Object.freeze( (
shouldIncludeFeeInAmount,
...getFeeToPayFromFeeDataArgs
) => {
if( shouldIncludeFeeInAmount ) {
const modifiedGetFeeToPayFromFeeDataArgs = [
...getFeeToPayFromFeeDataArgs
];
modifiedGetFeeToPayFromFeeDataArgs[0] = Object.assign(
{},
modifiedGetFeeToPayFromFeeDataArgs[0],
{
shouldReturnAdvancedResponse: true
}
);
const {
businessFee,
} = getFeeToPayFromFeeData( ...modifiedGetFeeToPayFromFeeDataArgs );
return businessFee;
}
return getFeeToPayFromFeeData( ...getFeeToPayFromFeeDataArgs );
});
module.exports = Object.freeze( (
metaGetFeeToPayFromFeeDataOptions,
...getFeeToPayFromFeeDataArgs
) => {
const logValues = (
!metaGetFeeToPayFromFeeDataOptions.pleaseDoNotLogAnything
);
if( logValues ) {
console.log(
'Running 🤠META😈⚔️🐸 metaGetFeeToPayFromFeeData🚨' +
'🔥🔥🔥🔥🔥🔥🔥🔥🔥' +
` here are the ultra values: ${
stringify({
metaGetFeeToPayFromFeeDataOptions,
getFeeToPayFromFeeDataArgs: [
...getFeeToPayFromFeeDataArgs
]
})
}`
);
}
const metaFeeToPay = getMetaFeeToPay(
metaGetFeeToPayFromFeeDataOptions.shouldIncludeFeeInAmount,
...getFeeToPayFromFeeDataArgs
);
// const metaFeeToPay = (
// metaGetFeeToPayFromFeeDataOptions.shouldIncludeFeeInAmount
// ) ? 0 : getFeeToPayFromFeeData( ...getFeeToPayFromFeeDataArgs );
if( logValues ) {
console.log(
'🌲🤠META😈⚔️🐸 metaGetFeeToPayFromFeeData🚨' +
'🔥🔥🔥🔥🔥🔥🔥🔥🔥' +
` executed successfully, here is the power result: ${
stringify({
feeToPay: metaFeeToPay,
})
}`
);
}
return metaFeeToPay;
});<file_sep>'use strict';
const delay = require( '../../../delay' );
const stringify = require( '../../../stringify' );
const timeToWaitBeforeNextBatchPutInSeconds = 1;
module.exports = Object.freeze( ({
data,
tableName,
entriesToPutNow,
entriesToPutLater,
putMultipleDatabaseEntries,
theResolve,
theReject
}) => {
console.log(
'running putMultipleDatabaseEntries.handleResponseData ' +
'with the following values: ' +
stringify({
data,
tableName,
entriesToPutNow,
entriesToPutLater,
})
);
if( entriesToPutLater.length > 0 ) {
const retryTime = timeToWaitBeforeNextBatchPutInSeconds * 1000;
console.log(
'putMultipleDatabaseEntries.handleResponseData ' +
'executed successfully, there are still entries left to put ' +
stringify( entriesToPutLater ) +
' retrying putMultipleDatabaseEntries in ' +
`${ timeToWaitBeforeNextBatchPutInSeconds } seconds.`
);
return delay( retryTime ).then( () => {
return putMultipleDatabaseEntries({
tableName,
entries: entriesToPutLater,
theResolve,
theReject
});
});
}
console.log(
'database.putMultipleDatabaseEntries.handleResponseData executed ' +
'successfully, put all requested entries: ' +
'\n\n --- database.putMultipleDatabaseEntries is complete ---'
);
theResolve();
});<file_sep>import { createElement as e } from 'react';
// import CowCowCheckbox from '../../../usefulComponents/CowCowCheckbox';
import { getState } from '../../../../reduxX';
import { bitcoin } from '../../../../utils';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
backgroundColor: 'beige',
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
headerText: {
width: '100%',
paddingTop: 10,
color: 'black',
fontSize: 16,
textAlign: 'center',
fontWeight: 'bold',
},
text: {
width: '100%',
paddingTop: 5,
paddingBottom: 20,
color: 'black',
fontSize: 16,
textAlign: 'center',
// padding: 15,
},
};
};
const noValueText = '-';
const getTotalWithdrawAmount = ({
fullWithdraw,
}) => {
const amount = getState( 'withdrawPolygon', 'amount' );
const fee = getState( 'withdrawPolygon', 'fee' );
const feeAsNumber = Number( fee );
if( !!fullWithdraw && feeAsNumber ) {
const totalBitcoinAmount = getState(
'loggedInMode',
'userData'
).balanceData.summary.bitcoin.totalAmount;
// const totalWithdrawAmount = bitcoin.getBitcoinAmountNumber(
// totalBitcoinAmount
//- feeAsNumber
// );
const totalWithdrawAmount = totalBitcoinAmount;
if( totalWithdrawAmount < 0 ) {
return noValueText;
}
// return `${ totalWithdrawAmount } BTC (includes fee)`;
return `${ totalWithdrawAmount } BTC`;
}
const amountAsNumber = Number( amount );
const shouldDisplayTotalWithdrawAmount = (
(
!!amount &&
(amountAsNumber !== 0)
) &&
(
!!fee &&
(feeAsNumber !== 0)
)
);
if( shouldDisplayTotalWithdrawAmount ) {
const totalWithdrawAmount = bitcoin.getBitcoinAmountNumber(
amountAsNumber + feeAsNumber
);
return `${ totalWithdrawAmount } BTC`;
}
return noValueText;
};
export default () => {
const styles = getStyles();
const fullWithdraw = getState( 'withdrawPolygon', 'fullWithdraw' );
const totalWithdrawAmount = getTotalWithdrawAmount({
fullWithdraw
});
return e(
Box,
{
style: styles.outerContainer,
},
e(
Typography,
{
style: styles.headerText
},
fullWithdraw ? (
'Total Withdraw Amount'
) :'Estimated Total Withdraw Amount'
),
e(
Typography,
{
style: styles.text
},
totalWithdrawAmount
)
);
};
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
getDatabaseEntry,
updateDatabaseEntry
},
},
},
constants: {
aws: {
database: {
tableNames: { USERS }
}
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( async ({
userId
}) => {
console.log(
`running updateHasGottenAddressStatusForUser for user ${ userId }`
);
const existingUserData = await getDatabaseEntry({
value: userId,
tableName: USERS,
});
if( !existingUserData ) {
throw new Error(
`weird error: no existing user data for user with id ${ userId }`
);
}
const newUserData = Object.assign(
{},
existingUserData,
{
hasGottenAddress: true
}
);
await updateDatabaseEntry({
tableName: USERS,
entry: newUserData
});
console.log(
'updateHasGottenAddressStatusForUser ' +
`executed successfully for user ${ userId }`
);
});
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
crypto: {
getCryptoAmountNumber
}
},
} = require( '@bitcoin-api/full-stack-exchange-private' );
module.exports = Object.freeze( ({
cryptoPot,
numberOfWinners,
houseCut,
}) => {
console.log(
'running getCryptoPayout: ' +
stringify({
cryptoPot,
numberOfWinners,
houseCut,
})
);
const rawCryptoPayout = (
( cryptoPot * ( 1 - houseCut ) ) / numberOfWinners
);
const cryptoPayout = getCryptoAmountNumber( rawCryptoPayout );
console.log(
'getCryptoPayout executed successfully - ' +
`here is the crypto payout: ${ cryptoPayout } Cryptos`
);
return cryptoPayout;
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase,
}
},
stringify,
javascript: {
getEnvNumberValue
}
},
} = require( '@bitcoin-api/full-stack-api-private' );
const constants = require( '../../../../../constants' );
const {
aws: {
database: {
tableNames: {
TRANSACTIONS
},
secondaryIndices: {
exchangeUserIdCreationDateIndex,
}
}
},
} = constants;
const processTransactions = require( './processTransactions' );
const f = Object.freeze;
const attributes = f({
nameKeys: f({
exchangeUserId: '#exchangeUserId',
}),
nameValues: f({
exchangeUserId: 'exchangeUserId',
}),
valueKeys: f({
exchangeUserId: ':exchangeUserId',
}),
});
const searchLimit = getEnvNumberValue({
key: 'ORACLE_HALLUCINATION_SEARCH_LIMIT',
min: 1,
max: 2000000,
shouldBeInteger: true,
defaultValue: 5000
});
const oracleHallucination = Object.freeze( async ({
exchangeUserId,
theOracleOfDelphiDefi,
withdrawIdToData = {},
voteIdToData = {},
// transactionToAdd = null,
transactionToAdd,
paginationValueToUse = null, // will be null on first time always
iterationCount = 0, // will be 0 on first time always
transactionCount = 0,
searchDb,
}) => {
console.log(
'🐐☢️⏫⏫⏫running oracleHallucination: ' +
stringify({
exchangeUserId,
theOracleOfDelphiDefi,
withdrawIdToData,
voteIdToData,
transactionToAdd,
paginationValueToUse,
iterationCount,
transactionCount,
searchDb,
})
);
if( searchDb ) {
const searchParams = {
TableName: TRANSACTIONS,
IndexName: exchangeUserIdCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: true,
KeyConditionExpression: (
`${ attributes.nameKeys.exchangeUserId } = ${ attributes.valueKeys.exchangeUserId }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.exchangeUserId]: attributes.nameValues.exchangeUserId,
},
ExpressionAttributeValues: {
[attributes.valueKeys.exchangeUserId]: exchangeUserId,
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const transactions = ultimateResults.slice();
transactionCount += transactions.length;
processTransactions({
transactions,
theOracleOfDelphiDefi,
withdrawIdToData,
voteIdToData,
});
paginationValueToUse = paginationValue;
}
if( !paginationValueToUse ) {
transactionCount++;
processTransactions({
transactions: [
transactionToAdd
],
theOracleOfDelphiDefi,
withdrawIdToData,
voteIdToData,
});
const hallucinationInsights = {
transactionCount,
existingAtaueu: {
oracleGhost: {
theOracleOfDelphiDefi,
withdrawIdToData,
},
},
}; // what do you see 👀......
console.log(
'🐐☢️⏫⏫⏫oracleHallucination executed successfully - ' +
`${ stringify({ hallucinationInsights })}`
);
return hallucinationInsights;
}
return await oracleHallucination({
exchangeUserId,
theOracleOfDelphiDefi,
withdrawIdToData,
voteIdToData,
transactionToAdd,
paginationValueToUse,
iterationCount: iterationCount + 1,
transactionCount,
searchDb,
});
});
module.exports = oracleHallucination;
<file_sep>'use strict';
module.exports = Object.freeze({
getBalanceDataForUser: require( './getBalanceDataForUser' ),
updateBalance: require( './updateBalance' ),
verifyBalanceOnNewWithdraw: require( './verifyBalanceOnNewWithdraw' ),
getIfUserHasEnoughMoneyToMakeTheWithdraw: require( './getIfUserHasEnoughMoneyToMakeTheWithdraw' ),
});<file_sep>import { createElement as e, useState } from 'react';
// import { getState } from '../../../../reduxX';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
const getStyles = ({
width,
maxWidth,
minWidth,
isOpen
}) => {
return {
outerContainer: {
backgroundColor: '#D0D2A8',
width,
maxWidth,
minWidth,
height: isOpen ? undefined : 61,
// minHeight: 75,
borderRadius: 10,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
topBar: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
width: '94%',
marginTop: 10,
marginBottom: 15,
},
leftTopBarPlaceHolder: {
width: 50,
},
rightButton: {
width: 50,
},
titleText: {
fontSize: 16,
color: 'black',
fontWeight: 'bold',
},
contentsBox: {
width: '100%',
backgroundColor: '#D0D2A8',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
borderRadius: 10,
alignItems: 'center',
},
contentsInsideBox: {
width: '90%',
// backgroundColor: '#D0D2A8',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
}
};
};
export default ({
title,
ContentComponent = Box,
contentProps = {},
width = '48%',
maxWidth = '100%',
minWidth = 265,
showHideButtonIsDisabled = false,
// width: '48%',
// maxWidth: '48%',
// minWidth: 300,
}) => {
const [ isOpen, setIsOpen ] = useState( false );
// const [ isOpen, setIsOpen ] = useState( true );
const styles = getStyles({
width,
maxWidth,
minWidth,
isOpen
});
return e(
Box,
{
style: styles.outerContainer
},
e(
Box,
{
style: styles.topBar,
},
e(
Box,
{
style: styles.leftTopBarPlaceHolder,
}
),
e(
Typography,
{
style: styles.titleText,
},
title
),
e(
Button,
{
disabled: showHideButtonIsDisabled,
style: styles.rightButton,
onClick: () => {
setIsOpen( !isOpen );
},
},
isOpen ? 'Hide' : 'View'
)
),
isOpen && e(
Box,
{
style: styles.contentsBox,
},
e(
Box,
{
style: styles.contentsInsideBox,
},
e(
ContentComponent,
contentProps
)
)
)
);
};
<file_sep>'use strict';
const {
utils: {
stringify,
aws: {
dino: {
classicalUpdateDatabaseEntry,
}
}
},
constants: {
aws: {
database: {
tableNames: {
METADATA
}
}
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
metadataKeys: {
dreamLotus
},
}
},
},
} = require( '@bitcoin-api/full-stack-exchange-private' );
const theMod = 200;
module.exports = Object.freeze( async ({
dino,
}) => {
console.log(
'running handleDreamsLotusLose with the following values: ' +
stringify({
dino
})
);
const amountToAdd = Math.abs(
dino.amount / theMod
);
const results = await classicalUpdateDatabaseEntry({
tableName: METADATA,
value: dreamLotus,
expressionAttributeNames: {
'#unhappyDreamCount': 'unhappyDreamCount',
'#jackpotAmount': 'jackpotAmount',
},
expressionAttributeValues: {
':amountToAdd': amountToAdd,
':unhappyDreamCountIncrementAmount': 1,
},
updateExpression: (
'ADD #unhappyDreamCount :unhappyDreamCountIncrementAmount, #jackpotAmount :amountToAdd'
),
returnValues: 'ALL_NEW',
});
const updatedJackpotData = results.Attributes;
console.log(
'✅handleDreamsLotusLose executed successfully ' +
`here is the updated jackpot data: ${
stringify( updatedJackpotData )
}`
);
});
<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../../../../../reduxX';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
// import {
// usefulComponents
// } from '../../../../../TheSource';
import { gameData } from '../../../../../../constants';
import Box from '@material-ui/core/Box';
// import Typography from '@material-ui/core/Typography';
// import Button from '@material-ui/core/Button';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
const sortByUser = gameData.destinyRaffle.sortByUser;
const sortByTicket = gameData.destinyRaffle.sortByTicket;
const getStyles = () => {
return {
metaContainer: {
width: '100%',
// height: 25,
// backgroundColor: 'green',
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
},
};
};
export default ({
raffleDatum,
isLocalLoading,
}) => {
const styles = getStyles();
const { raffleId } = raffleDatum;
const {
sortByOption
} = getState(
'destinyRaffle',
'raffleIdToTicketData'
)[ raffleId ] || {
sortByOption: gameData.destinyRaffle.sortByTicket
};
return e(
Box,
{
style: styles.metaContainer
},
e(
FormControl,
{
styles: styles.formControl,
disabled: isLocalLoading
},
e(
InputLabel,
{},
'Sort by'
),
e(
Select,
{
value: sortByOption,
onChange: event => {
const raffleIdToTicketData = getState(
'destinyRaffle',
'raffleIdToTicketData'
);
const newRaffleIdToTicketData = Object.assign(
{},
raffleIdToTicketData,
{
[raffleId]: Object.assign(
{},
raffleIdToTicketData[ raffleId ],
{
sortByOption: event.target.value,
}
)
}
);
setState(
[ 'destinyRaffle', 'raffleIdToTicketData' ],
newRaffleIdToTicketData
);
},
},
e(
MenuItem,
{
value: sortByTicket,
},
'Petal'
),
e(
MenuItem,
{
value: sortByUser,
},
'User'
)
)
)
);
};
<file_sep>'use strict';
const { database } = require( '../aws' );
const stringify = require( '../../stringify' );
module.exports = Object.freeze( ({
tableName,
entry
}) => {
const TableName = tableName;
const Item = Object.assign(
entry,
{
lastUpdated: Date.now(),
}
);
const params = {
TableName,
Item
};
console.log(
'Running database.updateDatabaseEntry with the following values: ' +
stringify( params )
);
return new Promise(
( resolve, reject ) => database.put( params, ( err, data ) => {
if( !!err ) {
console.log(
'Error in database.updateDatabaseEntry ' +
'with the following values: ' +
stringify( params )
);
return reject( err );
}
console.log(
'database.updateDatabaseEntry successfully executed'
);
resolve( data );
})
);
});
<file_sep>'use strict';
const {
getFormattedEvent,
getResponse,
handleError,
beginningDragonProtection,
} = require( '../../../utils' );
const getFeeData = require( './getFeeData' );
const fiveMiniutes = 5 * 60 * 1000;
exports.handler = Object.freeze( async rawEvent => {
console.log( 'running the /fee_data - GET function' );
try {
const event = getFormattedEvent({
rawEvent
});
await beginningDragonProtection({
queueName: 'getFeeData',
event,
megaCodeIsRequired: false,
ipAddressMaxRate: 20,
ipAddressTimeRange: fiveMiniutes,
});
const feeData = await getFeeData();
console.log(
'/fee_data - GET function executed successfully, ' +
'returning values: ' +
JSON.stringify( feeData, null, 4 )
);
return getResponse({ body: feeData });
}
catch( err ) {
console.log( `error in /fee_data - GET function: ${ err }` );
return handleError( err );
}
});<file_sep>import { getState, setState } from '../../../../reduxX';
import {
bitcoinExchange,
actions,
// delay,
dynastyBitcoin,
grecaptcha,
javascript
} from '../../../../utils';
import { google, gameData } from '../../../../constants';
// import { spinDinocoin } from './dinocoinActions';
const slotImageNamesLastIndex = gameData.slot.slotImageNames.length - 1;
const minSlotNumber = 1;
const maxSlotNumber = 3;
const getSlotNumberImageIndices = () => {
const slotNumberImageIndicesSet = new Set();
while( slotNumberImageIndicesSet.size < 3 ) {
slotNumberImageIndicesSet.add(
javascript.getRandomIntInclusive( 0, slotImageNamesLastIndex )
);
}
const slotNumberImageIndices = Array.from( slotNumberImageIndicesSet );
return slotNumberImageIndices;
};
const doPaidGameAction = async () => {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
const googleCode = await grecaptcha.safeGetGoogleCode({
action: google.grecapcha.actions.slotSpin,
});
return await bitcoinExchange.enchantedSlot({
userId,
loginToken,
googleCode,
});
};
const doFreeGameAction = () => {
const slotNumber1 = javascript.getRandomIntInclusive(
minSlotNumber,
maxSlotNumber
);
const slotNumber2 = javascript.getRandomIntInclusive(
minSlotNumber,
maxSlotNumber
);
const slotNumber3 = javascript.getRandomIntInclusive(
minSlotNumber,
maxSlotNumber
);
const currentFreeGameModeBalance = getState(
'notLoggedInMode',
'freeGameModeBalance',
);
if(
(
slotNumber1 ===
slotNumber2
) &&
(
slotNumber2 ===
slotNumber3
)
) {
setState(
[
'notLoggedInMode',
'freeGameModeBalance'
],
dynastyBitcoin.getDynastyBitcoinAmount(
currentFreeGameModeBalance + 0.0007
)
);
}
else if(
!(
(
slotNumber1 !==
slotNumber2
) &&
(
slotNumber2 !==
slotNumber3
) &&
(
slotNumber1 !==
slotNumber3
)
)
) {
setState(
[
'notLoggedInMode',
'freeGameModeBalance'
],
dynastyBitcoin.getDynastyBitcoinAmount(
currentFreeGameModeBalance - 0.0001
)
);
}
return {
resultValues: {
slotNumbers: [
slotNumber1,
slotNumber2,
slotNumber3,
]
}
};
};
export default async ({
freeGameMode,
}) => {
setState( 'isLoading', true );
try {
const {
// happyDream,
// hasTied,
resultValues,
} = freeGameMode ? doFreeGameAction() : (
await doPaidGameAction()
);
setState(
{
keys: [ 'isLoading' ],
value: false,
},
{
keys: [ 'loggedInMode', 'slot', 'slotNumber1' ],
value: resultValues.slotNumbers[0],
},
{
keys: [ 'loggedInMode', 'slot', 'slotNumber2' ],
value: resultValues.slotNumbers[1],
},
{
keys: [ 'loggedInMode', 'slot', 'slotNumber3' ],
value: resultValues.slotNumbers[2],
},
{
keys: [ 'loggedInMode', 'slot', 'slotNumberImageIndices' ],
value: getSlotNumberImageIndices(),
},
);
// await delay({ timeout: 1000 });
if( !freeGameMode ) {
await actions.refreshUserData({ setToLoading: false });
}
}
catch( error ) {
setState( 'isLoading', false );
console.log( 'the error:', error );
alert(
`error in slot: ${
(
!!error &&
!!error.response &&
!!error.response.data &&
!!error.response.data.message &&
error.response.data.message
) || 'internal server error'
}`
);
}
};
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry,
}
},
doOperationInQueue,
stringify,
redis: {
doRedisFunction,
doRedisRequest,
},
javascript: {
getQueueId,
jsonEncoder: {
decodeJson
}
},
},
constants: {
redis: {
listIds,
},
aws: {
database: {
tableNames: {
ADDRESSES,
}
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils:{
aws: {
dino: {
getExchangeDatabaseEntry
}
}
},
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_USERS,
}
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const { throwStandardError } = require( '../../../../../../utils' );
const ensureNoExistingAddress = require( './ensureNoExistingAddress' );
// const {
// auth: {
// authorizeUser
// },
// } = require( '../../../../utils' );
module.exports = Object.freeze( async ({
exchangeUserId,
}) => {
console.log(
'running 🏰runAsgardAddressMode🏰 ' +
`with the following values: ${ stringify({
exchangeUserId,
}) }`
);
await ensureNoExistingAddress({
exchangeUserId,
});
await doOperationInQueue({
queueId: getQueueId({ type: EXCHANGE_USERS, id: exchangeUserId }),
doOperation: async () => {
const exchangeUser = await getExchangeDatabaseEntry({
tableName: EXCHANGE_USERS,
value: exchangeUserId,
});
if( !exchangeUser ) {
// safeguard
throw new Error(
'🏰runAsgardAddressMode🏰 error - ' +
'exchange user with id ' +
`"${ exchangeUserId }" does not exist`
);
}
await ensureNoExistingAddress({
exchangeUserId,
exchangeUser,
});
const rawUnusedAddressData = await doRedisFunction({
performFunction: async ({
redisClient
}) => {
const rawUnusedAddressData = await doRedisRequest({
client: redisClient,
command: 'rpop',
redisArguments: [
listIds.unusedAddressData
],
});
return rawUnusedAddressData;
},
functionName: 'getting fresh address',
});
if( !rawUnusedAddressData ) {
return throwStandardError({
logMessage: (
'🏰runAsgardAddressMode🏰 NO-OP - ' +
'no fresh addresses available'
),
message: (
'Standard Error: No fresh addresses ' +
'are currently available. ' +
'Please try again later. ' +
'Thank you for your patience and understanding.'
),
statusCode: 400,
bulltrue: true,
});
}
const unusedAddressData = decodeJson( rawUnusedAddressData );
const newMoneyData = Object.assign(
{},
exchangeUser.moneyData || {}
);
if( !newMoneyData.bitcoin ) {
newMoneyData.bitcoin = [];
}
const newBitcoinMoneyDatum = {
amount: 0,
address: unusedAddressData.address,
creationDate: Date.now(),
};
newMoneyData.bitcoin.push( newBitcoinMoneyDatum );
const newExchangeUser = Object.assign(
{},
exchangeUser,
{
moneyData: newMoneyData
}
);
const updates = [];
const updateExchangeUser = updateDatabaseEntry({
tableName: EXCHANGE_USERS,
entry: newExchangeUser,
});
updates.push( updateExchangeUser );
const newAddressDatum = Object.assign(
{},
unusedAddressData,
{
userId: process.env.EXCHANGE_TOKEN_USER_ID,
conversionDate: Date.now(),
isExchangeAddress: true,
exchangeUserId,
}
);
const createAddressDatabaseEntry = updateDatabaseEntry({
tableName: ADDRESSES,
entry: newAddressDatum,
});
updates.push( createAddressDatabaseEntry );
await Promise.all( updates );
}
});
console.log(
'🏰runAsgardAddressMode🏰 executed successfully'
);
});
<file_sep>import {
enchanted
} from '../../../../../../../../utils';
import getNumbersAvsNumbersB from '../getNumbersAvsNumbersB';
const sortChoices = ({ choices }) => {
choices.sort( ( choiceA, choiceB ) => {
const numbersA = enchanted.destinyRaffle.getNumbersFromChoice({
choice: choiceA,
});
const numbersB = enchanted.destinyRaffle.getNumbersFromChoice({
choice: choiceB,
});
return getNumbersAvsNumbersB({
numbersA,
numbersB
});
});
};
const characterToName1 = {
a: 'Darth',
b: 'Ultra',
c: 'Mega',
d: 'Imperial',
e: 'Shiny',
f: 'Nebula',
0: 'Prince',
1: 'Advanced',
2: 'Noble',
3: 'Duke',
4: 'Upper',
5: 'Honorable',
6: 'Righteous',
7: 'Virtuous',
8: 'Golden',
9: 'Sovereign',
};
const characterToName2 = {
a: 'Satoshi',
b: 'Vader',
c: 'Chaos',
d: 'Apple',
e: 'Sky',
f: 'Ocean',
0: 'Mountain',
1: 'Tree',
2: 'Paladin',
3: 'Bird',
4: 'Camel',
5: 'Window',
6: 'Oxygen',
7: 'Rocket',
8: 'Chef',
9: 'Algebra',
};
const getName = ({
specialId
}) => {
// specialId = specialId.substring( 'exchange_user_'.length );
const character1 = specialId[0];
const character2 = specialId[1];
// const character3 = specialId[2];
const nameParts = [];
if( !!characterToName1[ character1 ] ) {
nameParts.push( characterToName1[ character1 ] );
}
else {
nameParts.push( 'Crypto' );
}
if( !!characterToName2[ character2 ] ) {
nameParts.push( characterToName2[ character2 ] );
}
else {
nameParts.push( 'Gamer' );
}
const name = nameParts.join( ' ' );
return name;
};
const putOwnProcessedDataFirst = ({
sortByUserProcessedData
}) => {
for( let i = 0; i < sortByUserProcessedData.length; i++ ) {
if( sortByUserProcessedData[ i ].own ) {
const ownUserData = sortByUserProcessedData[ i ];
sortByUserProcessedData.splice( i, 1 );
sortByUserProcessedData.unshift( ownUserData );
return;
}
}
};
export default ({
data,
ownSpecialId
}) => {
const specialIdToData = {};
for( const { choice, specialId } of data ) {
if( !specialIdToData[ specialId ] ) {
specialIdToData[ specialId ] = {
choices: [
choice,
]
};
}
else {
specialIdToData[ specialId ].choices.push(
choice
);
}
}
const specialIds = Object.keys( specialIdToData );
specialIds.forEach( specialId => {
sortChoices({
choices: specialIdToData[ specialId ].choices
});
});
const sortByUserProcessedData = [];
specialIds.forEach( specialId => {
const data = specialIdToData[ specialId ];
const processedData = {
name: getName({ specialId }),
choices: data.choices,
own: (specialId === ownSpecialId),
};
sortByUserProcessedData.push( processedData );
// sortByTicketProcessedData.push( data );
});
sortByUserProcessedData.sort( ( datumA, datumB ) => {
return (datumB.choices.length - datumA.choices.length);
});
putOwnProcessedDataFirst({
sortByUserProcessedData
});
return sortByUserProcessedData;
};<file_sep>'use strict';
const {
constants: {
redis: {
streamIds,
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const localStreamIds = Object.freeze({
altruisticCodeRateLimiterQueueId: 'altruisticCodeRateLimiterQueueId',
});
const getPowerQueueId = Object.freeze( ({
queueName,
hashedElement,
}) => {
return `${ queueName }-${ hashedElement }`;
});
module.exports = Object.freeze({
utils: Object.freeze({
getPowerQueueId,
getDragonDirective: require( './getDragonDirective' )
}),
constants: Object.freeze({
ipAddressRateLimiterQueueId: streamIds.ipAddressRateLimiterQueueId,
advancedCodeRateLimiterQueueId: streamIds.advancedCodeRateLimiterQueueId,
altruisticCodeRateLimiterQueueId: localStreamIds.altruisticCodeRateLimiterQueueId,
dragonErrorStatusCode: 403,
maxRateLimiterStreamLength: 200000
}),
});
<file_sep>'use strict';
const {
utils: {
bitcoin: {
formatting: { getAmountNumber }
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
transactions: {
types,
}
} = require( '../../../../../../constants' );
module.exports = Object.freeze( ({
exchangeUser,
theOracleOfDelphiDefi,
}) => {
const bitcoinData = (
exchangeUser &&
exchangeUser.moneyData &&
exchangeUser.moneyData.bitcoin
) || [];
const newBitcoinData = bitcoinData.slice();
const {
[types.addBitcoin]: {
addressToData,
},
} = theOracleOfDelphiDefi;
for( const address of Object.keys( addressToData ) ) {
const data = theOracleOfDelphiDefi[
types.addBitcoin
].addressToData[ address ];
// NOTE: can optimize
for( const newBitcoinDatum of newBitcoinData ) {
if( newBitcoinDatum.address === address ) {
Object.assign(
newBitcoinDatum,
{
lastUpdated: Date.now(),
amount: getAmountNumber( data.amount ),
}
);
}
}
}
return newBitcoinData;
});
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
width: '100%',
// height: 100,
// backgroundColor: 'pink',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
alignItems: 'center'
},
text: {
width: '90%',
// height: 100,
color: 'black',
marginTop: 15,
marginBottom: 5,
// padding: 5,
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Typography,
{
style: styles.text,
},
'Our mission at DynastyBitcoin.com is to provide ' +
'high quality Bitcoin games and fun crypto technology.'
),
e(
Typography,
{
style: styles.text,
},
'Here are some of our core values at DynastyBitcoin.com: ' +
'security, transparency, strength, kindness, ' +
'ethical business operations, ' +
'and of course, high quality ' +
`technology that's super fun!!!😁🌞🥳🎊🎈🎉`
),
e(
Typography,
{
style: styles.text,
},
'Stay tuned for exciting new features and updates - ' +
'follow Dynasty Bitcoin on Twitter for the latest DynastyBitcoin.com crypto news and fun tweets ',
e(
'a',
{
target: '_blank',
href: 'https://twitter.com/DynastyBitcoin'
},
'🐦➡️@DynastyBitcoin'
),
'!'
)
);
};
<file_sep>export default ({
timeout
}) => {
if( !timeout ) {
throw new Error( 'missing delay timeout' );
}
return new Promise( resolve => setTimeout( resolve, timeout ) );
};
<file_sep>'use strict';
const {
utils: {
javascript: { getQueueId },
doOperationInQueue,
aws: {
dino: {
getDatabaseEntry,
updateDatabaseEntry
}
},
stringify,
},
constants: {
aws: {
database: {
tableNames: { METADATA },
}
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( async ({
currentRafflePotAmount,
raffleId,
}) => {
console.log(
'running updateRafflePot with the following values: ' +
stringify({
currentRafflePotAmount,
raffleId,
})
);
await doOperationInQueue({
queueId: getQueueId({ type: METADATA, id: raffleId }),
doOperation: async () => {
const raffleData = await getDatabaseEntry({
tableName: METADATA,
value: raffleId,
});
if( !raffleData ) {
throw new Error(
'updateRafflePot - WEIRD ISSUE: ' +
`raffle with raffleId "${ raffleId }" not found`
);
}
if( !!raffleData.winRaffleDrawId ) {
throw new Error(
'updateRafflePot - ' +
`raffle with id "${ raffleId }" ` +
'has already finished'
);
}
const newRaffleData = Object.assign(
{},
raffleData,
{
cryptoPot: currentRafflePotAmount
}
);
await updateDatabaseEntry({
tableName: METADATA,
entry: newRaffleData,
});
}
});
console.log( 'updateRafflePot executed successfully' );
});
<file_sep>'use strict';
const {
constants: {
withdraws: {
states: {
// pending,
// verifying,
verifyingToFail,
// waiting,
realDealing
},
},
aws: { database: { tableNames: { WITHDRAWS } } },
// environment: {
// isProductionMode
// }
},
utils: {
// database: { metadata: { getFeeToPayFromFeeData } },
// business: {
// // getIsValidWithdrawAmount
// },
aws: {
dino: {
// getDatabaseEntry,
updateDatabaseEntry
},
},
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
doBitcoinRequest,
constants
} = require( '@bitcoin-api/full-stack-backend-private' );
const {
getFeeEstimateAmount
} = require( '../../../utils' );
const getBalance = Object.freeze( () => doBitcoinRequest({ args: [ 'getbalance' ] }));
const setUpWithdraw = require( './setUpWithdraw' );
const setTheBitcoinNodeFee = require( './setTheBitcoinNodeFee' );
const withdrawBitcoinFromNode = require( './withdrawBitcoinFromNode' );
const displayAndSaveWithdrawReport = require( './displayAndSaveWithdrawReport' );
// const stagingTransactionFee = 0.00001000;
module.exports = Object.freeze( async ({
existingWithdrawDatum,
}) => {
console.log(`
performing doTheActualWithdrawCore
with the following values: ${
stringify( {
existingWithdrawDatum
} )
}
`);
const {
userId,
ultraKey,
} = existingWithdrawDatum;
const {
blessedWithdraw
} = await setUpWithdraw({
userId, ultraKey
});
const {
amount,
feeData,
addressToSendTo,
shouldIncludeFeeInAmount,
} = blessedWithdraw;
const feeToChargeTheBitcoinNode = getFeeEstimateAmount({
blessedWithdraw
});
console.log( 'Request to doTheActualWithdrawCore - setting the fee' );
const chosenFeeToChargeTheBitcoinNode = await setTheBitcoinNodeFee({
blessedWithdraw,
});
console.log(`
Request to doTheActualWithdrawCore - withdrawing the money: ${
JSON.stringify( {
amount,
shouldIncludeFeeInAmount,
}, null, 4 )
}
`);
const balanceBeforeWithdraw = await getBalance();
const {
notEnoughMoneyErrorOccurred,
transactionId,
invalidAddressErrorOccurred,
} = await withdrawBitcoinFromNode({
addressToSendTo,
amount,
shouldIncludeFeeInAmount,
});
if( notEnoughMoneyErrorOccurred ) {
console.log(
'The Api had insufficient funds ' +
'(or similar error) for performing the withdraw. ' +
'The withdraw will be marked as verify-to-fail.'
);
await updateDatabaseEntry({
tableName: WITHDRAWS,
entry: Object.assign(
{},
blessedWithdraw,
{
state: verifyingToFail,
metadataToAdd: {
timeOfFailedWithdraw: Date.now(),
about: (
'withdraw attempt with invalid money error in ' +
'bitcoin node'
),
}
}
)
});
console.log(`
Request to doTheActualWithdrawCore - executed successfully🦍🙊
case: no withdraw - not enough bitcoin
`);
return {
withdrawOccurredSuccessfully: false,
};
}
else if( invalidAddressErrorOccurred ) {
console.log( 'marking the withdraw as verify-to-fail' );
await updateDatabaseEntry({
tableName: WITHDRAWS,
entry: Object.assign(
{},
blessedWithdraw,
{
state: verifyingToFail,
metadataToAdd: {
timeOfFailedWithdraw: Date.now(),
about: (
'withdraw attempt with invalid ' +
'address to send bitcoins to: ' +
`"${ addressToSendTo }"`
),
}
}
)
});
console.log(`
Request to doTheActualWithdrawCore - executed successfully🦍🙉
case: no withdraw - invalid address
`);
return {
withdrawOccurredSuccessfully: false,
};
}
const balanceAfterWithdraw = await getBalance();
displayAndSaveWithdrawReport({
userId,
ultraKey,
feeData,
balanceBeforeWithdraw,
balanceAfterWithdraw,
amount,
feeToChargeTheBitcoinNode,
transactionId,
shouldIncludeFeeInAmount,
});
await updateDatabaseEntry({
tableName: WITHDRAWS,
entry: Object.assign(
{},
blessedWithdraw,
{
transactionId,
state: realDealing,
metadata: Object.assign(
{},
blessedWithdraw.metadata,
{
timeStatusWasSetToRealDeal: Date.now(),
locationOfWithdraw: constants.megaServerId,
chosenFeeToChargeTheBitcoinNode,
}
),
}
)
});
console.log(`
Request to doTheActualWithdrawCore - executed successfully🏯🦖
case: successful withdraw
`);
return {
withdrawOccurredSuccessfully: true,
};
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase
}
},
stringify,
javascript: {
getEnvNumberValue
}
},
constants: {
aws: {
database: {
tableNames: {
WITHDRAWS
},
secondaryIndex: {
stateCreationDateIndex
}
}
},
withdraws: {
states: {
pending
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const f = Object.freeze;
const attributes = f({
nameKeys: f({
ultraKey: '#ultraKey',
userId: '#userId',
state: '#state',
isExchangeWithdraw: '#isExchangeWithdraw',
exchangeUserId: '#exchangeUserId',
}),
nameValues: f({
ultraKey: 'ultraKey',
userId: 'userId',
state: 'state',
isExchangeWithdraw: 'isExchangeWithdraw',
exchangeUserId: 'exchangeUserId',
}),
valueKeys: f({
state: ':state',
}),
valueValues: f({
state: pending,
})
});
const searchLimit = getEnvNumberValue({
key: 'GET_PENDING_WITHDRAW_DATA_SEARCH_LIMIT',
min: 1,
max: 2000000,
shouldBeInteger: true,
defaultValue: 1000
});
const getPendingWithdrawData = Object.freeze( async ({
pendingWithdrawData = [],
paginationValueToUse = null,
iterationCount = 0
} = {
pendingWithdrawData: [],
paginationValueToUse: null,
iterationCount: 0
}) => {
console.log(
'running getPendingWithdrawData: ' +
stringify({
['number of pending withdraw datas🐉']: pendingWithdrawData.length,
paginationValueToUse,
iterationCount
})
);
const searchParams = {
TableName: WITHDRAWS,
IndexName: stateCreationDateIndex,
ProjectionExpression: [
attributes.nameKeys.ultraKey,
attributes.nameKeys.userId,
attributes.nameKeys.state,
attributes.nameKeys.isExchangeWithdraw,
attributes.nameKeys.exchangeUserId,
].join( ', ' ),
Limit: searchLimit,
ScanIndexForward: true,
KeyConditionExpression: (
`${ attributes.nameKeys.state } = ${ attributes.valueKeys.state }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.state]: attributes.nameValues.state,
[attributes.nameKeys.userId]: attributes.nameValues.userId,
[attributes.nameKeys.ultraKey]: attributes.nameValues.ultraKey,
[attributes.nameKeys.isExchangeWithdraw]: attributes.nameValues.isExchangeWithdraw,
[attributes.nameKeys.exchangeUserId]: attributes.nameValues.exchangeUserId,
},
ExpressionAttributeValues: {
[attributes.valueKeys.state]: attributes.valueValues.state,
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
pendingWithdrawData.push( ...ultimateResults );
if( !paginationValue ) {
console.log(
'getPendingWithdrawData executed successfully: ' +
stringify({
['number of pending withdraw datas🐉 retrieved']: (
pendingWithdrawData.length
),
})
);
return pendingWithdrawData;
}
return await getPendingWithdrawData({
pendingWithdrawData,
paginationValueToUse: paginationValue,
iterationCount: iterationCount + 1,
});
});
module.exports = getPendingWithdrawData;<file_sep>import bitcoinExchange from '../../../bitcoinExchangeInstance';
import { getState } from '../../../../reduxX';
import { raffles } from '../../../../constants';
const getAllData = async ({
raffleId,
}) => {
const allTicketData = [];
let nextPageInfo = null;
do {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
const params = {
userId,
loginToken,
raffleId,
};
if( !!nextPageInfo ) {
Object.assign(
params,
nextPageInfo
);
}
const {
tickets,
pageInfo
} = await bitcoinExchange.getRaffleTickets( params );
allTicketData.push( ...tickets );
if( !!pageInfo ) {
nextPageInfo = pageInfo;
}
else if( !!nextPageInfo ) {
nextPageInfo = null;
}
} while( nextPageInfo );
return allTicketData;
};
const getProcessedTicketData = ({ allTicketData }) => {
allTicketData.sort( ( datumA, datumB ) => {
return datumA.time - datumB.time;
});
const userIdToChoice = {};
allTicketData.forEach( ticketDatum => {
if( ticketDatum.action === raffles.actions.buy ) {
userIdToChoice[ ticketDatum.specialId ] = (
userIdToChoice[ ticketDatum.specialId ] || {}
);
userIdToChoice[ ticketDatum.specialId ][ ticketDatum.choice ] = (
ticketDatum
);
}
else {
if( !!userIdToChoice[ ticketDatum.specialId ] ) { // safeguard
delete userIdToChoice[
ticketDatum.specialId
][
ticketDatum.choice
];
}
}
});
const processedTicketData = [];
const userIds = Object.keys( userIdToChoice );
for( const userId of userIds ) {
const choices = Object.keys( userIdToChoice[ userId ] );
for( const choice of choices ) {
processedTicketData.push(
userIdToChoice[ userId ][ choice ]
);
}
}
processedTicketData.sort( ( datumA, datumB ) => {
return datumA.time - datumB.time;
});
const finalProcessedTicketData = processedTicketData.map(
({ choice, time, specialId }) => ({ choice, time, specialId })
);
return finalProcessedTicketData;
};
export default async ({
raffleId,
}) => {
const allTicketData = await getAllData({
raffleId,
});
const processedTicketData = getProcessedTicketData({
allTicketData
});
return processedTicketData;
};
<file_sep>import { createElement as e, useState, useEffect, Suspense, lazy } from 'react';
// import Amplify from 'aws-amplify';
// import aws_exports from './aws-exports';
import { setUpReduxX, getState } from './reduxX';
import { story } from './constants';
import componentDidMount from './componentDidMount';
// import Dialog from './TheSource/Dialog';
// import PrivacyPolicyRealm from './TheSource/zanzibarRealms/ArgonRealms/PrivacyPolicyRealm';
// import TermsOfServiceRealm from './TheSource/zanzibarRealms/ArgonRealms/TermsOfServiceRealm';
import Box from '@material-ui/core/Box';
// const componentDidMount = lazy(() => import('./componentDidMount'));
// import TheActualApp from './TheActualApp';
import LoadingPage from './TheSource/LoadingPage';
const PrivacyPolicyRealm = lazy(() => import('./TheSource/zanzibarRealms/ArgonRealms/PrivacyPolicyRealm'));
const TermsOfServiceRealm = lazy(() => import('./TheSource/zanzibarRealms/ArgonRealms/TermsOfServiceRealm'));
const Dialog = lazy(() => import('./TheSource/Dialog'));
const TheActualApp = lazy(() => import('./TheActualApp'));
// import Dialog from './TheSource/Dialog';
// Amplify.configure( aws_exports );
const StandardSuspense = ({ children }) => {
return e(
Suspense,
{
fallback: e( 'div' ),
},
children
);
};
const getStyles = () => {
const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: mainStyleObject.backgroundColor,
// backgroundColor: 'orange',
// width: '100%',
// height: '100%',
width: '100%',
// height: 500,
display: 'flex',
flexDirection: 'column',
// justifyContent: 'space-between',
// alignItems: 'center',
justifyContent: 'flex-start',
alignItems: 'center',
color: 'white',
},
// spiritual: {
// width: 300,
// height: 600,
// backgroundColor: 'beige',
// }
};
};
/*
<Dialog fullScreen open={open} onClose={handleClose} TransitionComponent={Transition}>
<AppBar className={classes.appBar}>
<Toolbar>
<IconButton edge="start" color="inherit" onClick={handleClose} aria-label="close">
<CloseIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
Sound
</Typography>
<Button autoFocus color="inherit" onClick={handleClose}>
save
</Button>
</Toolbar>
</AppBar>
<List>
<ListItem button>
<ListItemText primary="Phone ringtone" secondary="Titania" />
</ListItem>
<Divider />
<ListItem button>
<ListItemText primary="Default notification ringtone" secondary="Tethys" />
</ListItem>
</List>
</Dialog>
*/
export default ({
websiteName = 'DynastyBitcoin.com',
websiteAbbreviation = 'DB',
supportEmail = '<EMAIL>',
safeMode = false,
}) => {
useEffect( () => {
componentDidMount();
}, [] );
setUpReduxX( useState );
const styles = getStyles();
const metaMode = getState( 'metaMode' );
const createElementArguments = [
Box,
{
style: styles.outerContainer,
},
e(
StandardSuspense,
{},
e( Dialog )
),
// TODO: add snack
];
if( metaMode === story.metaModes.privacyPolicy ) {
createElementArguments.push(
e(
Suspense,
{
fallback: e( 'div' ),
},
e(
PrivacyPolicyRealm,
{
websiteName,
websiteAbbreviation,
supportEmail
}
)
)
);
}
else if( metaMode === story.metaModes.termsOfService ) {
createElementArguments.push(
e(
Suspense,
{
fallback: e( 'div' ),
},
e(
TermsOfServiceRealm,
{
websiteName,
websiteAbbreviation,
supportEmail
}
)
)
);
}
else {
createElementArguments.push(
e(
Suspense,
{
fallback: e( LoadingPage, { fullDogeStyle: true } ),
},
e(
TheActualApp,
{
websiteName,
safeMode
}
)
)
);
}
return e( ...createElementArguments );
};
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase,
},
}
},
constants: {
aws: {
database: {
tableNames: { ADDRESSES },
addressesTable: {
secondaryIndexNames: {
addressIndex
}
}
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const f = Object.freeze;
const attributes = f({
nameKeys: f({
// userId: '#userId',
address: '#address',
// amount: '#amount',
}),
nameValues: f({
// userId: 'userId',
address: 'address',
// amount: 'amount',
}),
valueKeys: f({
address: ':address',
}),
});
module.exports = Object.freeze( async ({
address
}) => {
console.log( `running getAddressDatum with address: ${ address }` );
const dynamicAttributes = f({
valueValues: f({
address
}),
});
const searchParams = {
TableName: ADDRESSES,
IndexName: addressIndex,
// ProjectionExpression: [].join( ', ' ),
Limit: 5,
KeyConditionExpression: (
`${ attributes.nameKeys.address } = ${ attributes.valueKeys.address }`
),
ExpressionAttributeNames: {
// [attributes.nameKeys.userId]: attributes.nameValues.userId,
[attributes.nameKeys.address]: attributes.nameValues.address,
// [attributes.nameKeys.amount]: attributes.nameValues.amount,
},
ExpressionAttributeValues: {
[attributes.valueKeys.address]: dynamicAttributes.valueValues.address
},
};
const addressData = (
await searchDatabase({
searchParams,
doSingleSearch: true
})
).ultimateResults;
if( addressData.length === 0 ) {
console.log(
'getAddressDatum executed successfully, ' +
`no database address data found for address: ${ address }`
);
return null;
}
else if( addressData.length > 1 ) {
// NOTE: safeguard: shouldn't get here in normal operation
throw new Error(
'updateAddressData: ' +
'WEIRD ERROR: wrong number of addresses found: ' +
addressData.length
);
}
const addressDatum = addressData[ 0 ];
console.log( 'getAddressDatum executed successfully' );
return addressDatum;
});<file_sep>import { createElement as e } from 'react';
// import { setState } from '../../../../reduxX';
// import { validation } from '../../../../utils';
// import placeBet from './placeBet';
// import cancelBet from './cancelBet';
const getStyles = () => {
return {
payoutPolygon: {
width: '100%',
height: 300,
backgroundColor: 'yellow',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
payoutPolygonText: {
padding: 5,
color: 'black',
}
};
};
export default ({
resultAmount,
resultChoice,
currentAmount,
}) => {
const styles = getStyles();
return e(
'div',
{
style: styles.payoutPolygon
},
e(
'div',
{
style: styles.payoutPolygonText
},
(resultAmount !== 0 ) ? (
'Won vote! ' +
`Received payout of ${ resultAmount } Cryptos ` +
`voting for ${ resultChoice } using ${ currentAmount } ` +
`Cryptos.`
) : (
'Lost vote - ' +
`Voted for ${ resultChoice } using ${ currentAmount } ` +
`Cryptos.`
)
)
);
};
<file_sep>'use strict';
const authorizeUser = require( '../../auth/authorizeUser' );
const runAdvancedCodeDragonInspection = require(
'../runAdvancedCodeDragonInspection'
);
const ensureTheUserCompliesWithTheDragonDirective = require(
'./ensureTheUserCompliesWithTheDragonDirective'
);
// const {
// utils: {
// stringify,
// }
// } = require( '@npm.m.stecky.efantis/commonprivate' );
const f = Object.freeze;
module.exports = f( async ({
megaCode,
queueName,
redisClient,
dragonFindings,
advancedCodeMaxRate,
advancedCodeTimeRange,
necessaryDragonDirective,
}) => {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'running 🐊getDragonsToInspectTheMegaCode🐊'
);
const { user } = await authorizeUser({
returnCode: megaCode
});
ensureTheUserCompliesWithTheDragonDirective({
user,
necessaryDragonDirective,
dragonFindings
});
await runAdvancedCodeDragonInspection({
redisClient,
megaCode,
queueName,
maxRate: advancedCodeMaxRate,
timeRange: advancedCodeTimeRange,
});
dragonFindings.user = user;
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 -\n' +
'Yes, the dragon code has been inspected and ' +
'everything is going as planned.☢️🐑'
);
});
<file_sep>import { createElement as e, useEffect } from 'react';
import { getState } from '../../reduxX';
// import getUserData from './componentDidMount/getUserData';
import componentDidMount from './componentDidMount';
import Drawer from './Drawer';
import {
TitlePolygon,
UserDataPolygon,
LoadingPage,
DeleteUserButton,
ExchangePolygon,
MoneyActionsPolygon,
ReferralIdPolygon,
} from '../../TheSource';
import {
DestinyRafflePolygon,
CoinExperiencePolygon,
SlotPolygon
} from '../../TheEnchantedSource';
import WithdrawsPage from './WithdrawsPage';
import { story } from '../../constants';
import Box from '@material-ui/core/Box';
const getStyles = () => {
const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: mainStyleObject.backgroundColor,
width: '100%',
// height: 200,
display: 'flex',
flexDirection: 'column',
// justifyContent: 'space-between',
// alignItems: 'center',
justifyContent: 'flex-start',
alignItems: 'center',
color: 'white',
},
};
};
export default () => {
useEffect( () => {
componentDidMount();
}, [] );
const styles = getStyles();
const createElementArguments = [
Box,
{
style: styles.outerContainer,
}
];
const userData = getState( 'loggedInMode', 'userData' );
if( !!userData ) {
const mode = getState( 'loggedInMode', 'mode' );
createElementArguments.push(
e( Drawer ),
);
if( mode === story.LoggedInMode.modes.exchange ) {
createElementArguments.push(
e( TitlePolygon ),
e( ExchangePolygon )
);
}
// else if( mode === story.LoggedInMode.modes.vote ) {
// createElementArguments.push(
// e( TitlePolygon ),
// e( votePolygons.UsaElectionPolygon ),
// );
// }
else if( mode === story.LoggedInMode.modes.coinFlip ) {
createElementArguments.push(
e(
TitlePolygon,
{
backgroundColor: 'lightgreen',
}
),
e( CoinExperiencePolygon ),
);
}
else if( mode === story.LoggedInMode.modes.slot ) {
createElementArguments.push(
e(
TitlePolygon,
{
backgroundColor: '#FFCC66',
}
),
e( SlotPolygon )
);
}
else if( mode === story.LoggedInMode.modes.destinyRaffle ) {
createElementArguments.push(
e(
TitlePolygon,
{
// backgroundColor: 'lightgreen',
}
),
e( DestinyRafflePolygon ),
);
}
else if( mode === story.LoggedInMode.modes.withdraw ) {
createElementArguments.push(
e( TitlePolygon ),
e( WithdrawsPage )
);
}
else if( mode === story.LoggedInMode.modes.settings ) {
createElementArguments.push(
e( TitlePolygon ),
e( DeleteUserButton )
);
}
else {
createElementArguments.push(
e( TitlePolygon ),
e( UserDataPolygon ),
e( MoneyActionsPolygon ),
e( ReferralIdPolygon )
// e( ExchangePolygon ),
// e( SignOutButton ),
);
}
}
else {
createElementArguments.push(
e( LoadingPage )
);
}
return e( ...createElementArguments );
};
<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../../../../reduxX';
import { bitcoinExchange/*, delay*/ } from '../../../../../utils';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
// import DayBox from './DayBox';
// import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import { getViewDrawsContainerId } from './viewDrawsTools';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
buttonsContainer: {
backgroundColor: '#D0D2A8',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
marginBottom: 15,
},
button: {
// color: 'black',
},
};
};
const handleClickOnRightButtonLoadNewDraws = async ({
raffleId,
lastTime,
index,
lastKey,
startTime,
endTime
// setIsLocalLoading,
}) => {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
const {
draws,
pageInfo
} = await bitcoinExchange.getRaffleDraws({
userId,
loginToken,
raffleId,
lastTime,
lastKey,
startTime,
endTime
});
const raffleIdToDrawData = getState(
'destinyRaffle',
'raffleIdToDrawData'
);
const newAllDraws = raffleIdToDrawData[ raffleId ].allDraws.slice();
newAllDraws.push( draws );
const newRaffleIdToDrawData = Object.assign(
{},
raffleIdToDrawData,
{
[raffleId]: {
allDraws: newAllDraws,
index: index + 1,
startTime,
endTime,
}
}
);
if( !!pageInfo ) {
Object.assign(
newRaffleIdToDrawData[ raffleId ],
{
lastTime: pageInfo.lastTime,
lastKey: pageInfo.lastKey,
}
);
}
setState(
[ 'destinyRaffle', 'raffleIdToDrawData' ],
newRaffleIdToDrawData
);
};
const scrollUpViewDrawsBox = ({ raffleId }) => {
const viewDrawsBox = document.getElementById(
getViewDrawsContainerId({ raffleId })
);
if( !!viewDrawsBox ) {
viewDrawsBox.scrollTop = 0;
}
};
const getIfRightButtonIsDisabled = ({
allDraws,
index,
isLocalLoading,
lastTime,
lastKey,
}) => {
if( isLocalLoading ) {
return true;
}
if(
(index === (allDraws.length - 1)) &&
(!lastTime || !lastKey)
) {
return true;
}
return false;
};
export default ({
raffleDatum,
isLocalLoading,
setIsLocalLoading,
}) => {
const styles = getStyles();
const { raffleId } = raffleDatum;
const drawData = getState(
'destinyRaffle',
'raffleIdToDrawData'
)[ raffleId ] || {
allDraws: [ [] ],
lastTime: null,
index: 0,
startTime: 22,
endTime: Date.now(),
};
const {
index,
allDraws,
lastTime,
lastKey,
startTime,
endTime,
} = drawData;
const leftButtonIsDisabled = (
isLocalLoading ||
(index === 0)
);
const rightButtonIsDisabled = getIfRightButtonIsDisabled({
allDraws,
index,
isLocalLoading,
lastTime,
lastKey,
});
return e(
Box,
{
style: styles.buttonsContainer,
},
e(
Button,
{
disabled: leftButtonIsDisabled,
style: styles.button,
onClick: () => {
const raffleIdToDrawData = getState(
'destinyRaffle',
'raffleIdToDrawData'
);
const newRaffleIdToDrawData = Object.assign(
{},
raffleIdToDrawData,
{
[raffleId]: Object.assign(
{},
raffleIdToDrawData[ raffleId ],
{
index: index - 1,
}
)
}
);
setState(
[ 'destinyRaffle', 'raffleIdToDrawData' ],
newRaffleIdToDrawData
);
scrollUpViewDrawsBox({ raffleId });
},
},
'<'
),
e(
Button,
{
style: styles.button,
disabled: rightButtonIsDisabled,
onClick: async () => {
try {
const newIndex = index + 1;
if( !!allDraws[ newIndex ] ) {
const raffleIdToDrawData = getState(
'destinyRaffle',
'raffleIdToDrawData'
);
const newRaffleIdToDrawData = Object.assign(
{},
raffleIdToDrawData,
{
[raffleId]: Object.assign(
{},
raffleIdToDrawData[ raffleId ],
{
index: newIndex,
}
)
}
);
setState(
[ 'destinyRaffle', 'raffleIdToDrawData' ],
newRaffleIdToDrawData
);
scrollUpViewDrawsBox({ raffleId });
return;
}
setIsLocalLoading( true );
// await delay({ timeout: 2000 });
await handleClickOnRightButtonLoadNewDraws({
raffleId,
lastTime,
index,
lastKey,
startTime,
endTime,
});
scrollUpViewDrawsBox({ raffleId });
setIsLocalLoading( false );
}
catch( err ) {
setIsLocalLoading( true );
console.log( 'error in loading draws:', err );
}
},
},
'>'
)
);
};
<file_sep>import { createElement as e } from 'react';
import { setState/*, getState*/ } from '../../../../reduxX';
import { story } from '../../../../constants';
import Box from '@material-ui/core/Box';
// import Button from '@material-ui/core/Button';
import { Typography } from '@material-ui/core';
const getStyles = () => {
return {
buttonBox: {
// backgroundColor: 'beige',
width: '90%' ,
maxWidth: 500,
minWidth: 320,
// height: 100,
// marginTop: 40,
// marginTop: 40,
marginBottom: 25,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'flex-start',
},
buttonTextBox: {
cursor: 'pointer',
// marginTop: 15,
// marginBottom: 15,
// width: '90%',
// fontSize: 14,
},
buttonText: {
// backgroundColor: 'black',
color: '#696969',
cursor: 'pointer',
fontSize: 12,
// marginTop: 15,
// marginBottom: 15,
// width: '90%',
// fontSize: 14,
}
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.buttonBox,
// elevation: 10,
},
e(
Box,
{
style: styles.buttonTextBox,
},
e(
Typography,
{
size: 'small',
onClick: () => {
setState( 'metaMode', story.metaModes.privacyPolicy );
},
// variant: 'contained',
style: styles.buttonText,
},
'Privacy Policy'
),
),
e(
Box,
{
style: styles.buttonTextBox,
// elevation: 10,
},
e(
Typography,
{
// size: 'small',
onClick: () => {
setState( 'metaMode', story.metaModes.termsOfService );
},
// variant: 'contained',
style: styles.buttonText,
},
'Terms of Service'
)
)
);
};
<file_sep>'use strict';
const {
utils: {
stringify,
redis: {
doRedisFunction,
},
},
constants: {
environment: {
isProductionMode
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const execa = require( 'execa' );
const {
giraffeAndTreeStatusUpdate,
constants: {
deployCommands,
eventNames
}
} = require( '@bitcoin-api/giraffe-utils' );
const f = Object.freeze;
const credentialsFolderName = isProductionMode ? (
'productionCredentials'
) : 'stagingCredentials';
const pemPath = process.env.PEM_PATH;
const lickFileDestinationUrl = process.env.LICK_FILE_DESTINATION;
const tigerHomeDestinationPath = process.env.TIGER_HOME_DESTINATION_PATH;
const zarbonSpot = process.env.ZARBON_SPOT;
const deployCommandToTigerSpotData = f({
[deployCommands.feeDataBot]: f({
tigerSpot: `${ zarbonSpot }/feeDataBot`,
tigerKeySpot: (
`${ zarbonSpot }/${ credentialsFolderName }/feeDataBot/.env`
),
tigerKeyFolderStructure: [
'feeDataBot',
],
}),
[deployCommands.withdrawsBot]: f({
tigerSpot: `${ zarbonSpot }/withdrawsBot`,
tigerKeySpot: (
`${ zarbonSpot }/${ credentialsFolderName }/withdrawsBot/.env`
),
tigerKeyFolderStructure: [
'withdrawsBot',
],
}),
[deployCommands.depositsBot]: f({
tigerSpot: `${ zarbonSpot }/depositsBot`,
tigerKeySpot: (
`${ zarbonSpot }/${ credentialsFolderName }/depositsBot/.env`
),
tigerKeyFolderStructure: [
'depositsBot',
],
}),
});
const log = Object.freeze( ( ...args ) => {
console.log( '😛🍁handleTongueFeel - ', ...args );
});
module.exports = Object.freeze( async ({
information: {
deployCommand,
deployId,
// eventOrder
}
}) => {
log( 'running handleTongueFeel' );
const {
tigerSpot,
tigerKeySpot,
tigerKeyFolderStructure
} = deployCommandToTigerSpotData[ deployCommand ];
log( 'removing node modules from:', stringify([
tigerSpot,
]) );
await execa(
'rm',
[
'-rf',
'./node_modules'
],
{
cwd: tigerSpot
}
);
log( 'node modules successfully removed' );
const fullDestinationUrl = (
`${ lickFileDestinationUrl }:` +
`${ tigerHomeDestinationPath }/tempTigerScript`
);
const execaScpArgs = [
'-i',
pemPath,
'-r',
tigerSpot,
fullDestinationUrl
];
const execaScpOptions = {};
const fullEnvDestinationUrl = (
`${ lickFileDestinationUrl }:` +
`${ tigerHomeDestinationPath }/tigerScript/` +
`${ credentialsFolderName }/` +
tigerKeyFolderStructure.join( '/' ) +
'/.env'
);
const execaEnvScpArgs = [
'-i',
pemPath,
tigerKeySpot,
fullEnvDestinationUrl
];
const execaEnvScpOptions = {};
log(
`teleporting with the following values ${ stringify({
execaScpArgs,
execaScpOptions,
execaEnvScpArgs,
execaEnvScpOptions
})}`
);
await Promise.all([
execa( 'scp', execaScpArgs, execaScpOptions ),
execa( 'scp', execaEnvScpArgs, execaEnvScpOptions ),
]);
log( 'teleported successfully' );
log( 'giraffe telepathy now' );
await doRedisFunction({
performFunction: ({
redisClient
}) => giraffeAndTreeStatusUpdate({
redisClient,
eventName: eventNames.giraffe.lickComplete,
information: {
deployId,
eventOrder: 2,
deployCommand,
}
}),
functionName: 'giraffe realizes leaf feels tongue (lick complete)'
});
log( '🦒⚡️🧠giraffe telepathy successful' );
log( 'handleTongueFeel executed successfully successfully' );
});
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
// import Typography from '@material-ui/core/Typography';
import { getState } from '../../../reduxX';
// import { actions } from '../../utils';
// import * as constants from '../../../constants';
// import { UltraDataContainer } from '../usefulComponents';
// import Divider from '@material-ui/core/Divider';
import ExcitingBlock from './ExcitingBlock';
import NextBlock from './NextBlock';
const getStyles = ({
dialogMode
}) => {
// const mainStyleObject = getState( 'mainStyleObject' );
const {
outerContainerWidth,
outerContainerHeight,
outerContainerBackgroundColor,
} = dialogMode ? {
outerContainerWidth: '100%',
outerContainerHeight: '100%',
outerContainerBackgroundColor: 'white',
} : {
outerContainerWidth: '90%',
outerContainerHeight: '80%',
outerContainerBackgroundColor: 'black',
};
return {
outerContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
// backgroundColor: '#FF9900',
backgroundColor: outerContainerBackgroundColor,
width: outerContainerWidth,
minWidth: 300,
height: outerContainerHeight,
marginBottom: 20,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
scrollSwagContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
// backgroundColor: 'green',
width: '100%',
height: '100%',
// borderRadius: 50,
marginTop: 5,
marginBottom: 5,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
overflowY: 'scroll',
},
};
};
const getExcitingBlocks = ({
dialogMode,
moneyActions,
}) => {
const excitingBlocks = moneyActions.map( moneyAction => {
return e(
ExcitingBlock,
{
moneyAction,
dialogMode,
}
);
});
return excitingBlocks;
};
export default ({
dialogMode,
moneyActions,
}) => {
const styles = getStyles({
dialogMode,
});
const lastTransactionId = getState(
'transactionsPolygon',
'lastTransactionId'
);
const lastTime = getState(
'transactionsPolygon',
'lastTime'
);
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.scrollSwagContainer,
},
...getExcitingBlocks({
dialogMode,
moneyActions
}),
(
!!lastTransactionId &&
!!lastTime
) ? e(
NextBlock,
{
dialogMode,
}
) : null
)
);
};
/*
ABOUT STATE
transactionsPolygon: {
moneyActions: [
{},
{},
...
],
lastX,
lastY,
lastZ
},
ABOUT APPEARANCE
common elements
type - time
exciting blocks, with load more special exciting block
*/
<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../../reduxX';
// import { actions, grecaptcha } from '../../../utils';
// import { TitlePolygon } from '../../../TheSource';
import Box from '@material-ui/core/Box';
// import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
// import Typography from '@material-ui/core/Typography';
// import { story } from '../../../constants';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'pink',
width: '100%',
marginTop: 28,
// height: 100,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
inputContainer: {
padding: 20,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'beige',
borderRadius: 20,
},
input: {
width: 250,
},
};
};
export default () => {
const styles = getStyles();
const isLoading = getState( 'isLoading' );
const emailInput = getState( 'forgotMyPasswordPolygon', 'emailInput' );
const inputIsDisabled = (
isLoading
);
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.inputContainer,
},
e(
TextField,
{
disabled: inputIsDisabled,
style: styles.input,
value: emailInput,
type: 'email',
label: 'email',
autoComplete: 'email',
onSubmit: () => {},
onChange: event => {
const newText = event.target.value;
if( newText.length > 200 ) {
return;
}
setState(
[
'forgotMyPasswordPolygon',
'emailInput'
],
newText.trim()
);
},
}
)
)
);
};
<file_sep>'use strict';
module.exports = Object.freeze( ({
addressDatum
}) => {
console.log(
'running getIfAddressShouldBeReclaimed ' +
`for address ${ addressDatum.address }`
);
if( addressDatum.amount > 0 ) {
console.log(
'getIfAddressShouldBeReclaimed - address is used. ' +
'the address should not be reclaimed'
);
return false;
}
const expiryDate = (
addressDatum.conversionDate +
addressDatum.timeUntilReclamationAfterConversionDate
);
const addressHasExpired = Date.now() > expiryDate;
if( addressHasExpired ) {
console.log(
'getIfAddressShouldBeReclaimed - address is unused ' +
'and is expired, it should be reclaimed'
);
return true;
}
console.log(
'getIfAddressShouldBeReclaimed - address is unused ' +
'and has not expired yet, it should not be reclaimed'
);
return false;
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase
}
},
stringify,
},
constants: {
environment: {
isProductionMode
}
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
TRANSACTIONS
},
// tableNameToKey,
secondaryIndices: {
searchIdCreationDateIndex
}
}
},
raffles: {
types: {
putTicket
},
actions: {
buy,
// cancel
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const searchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
searchId: '#searchId',
raffleType: '#raffleType',
choice: '#choice',
creationDate: '#creationDate',
}),
nameValues: f({
raffleType: 'raffleType',
searchId: 'searchId',
choice: 'choice',
creationDate: 'creationDate',
}),
valueKeys: f({
raffleType: ':raffleType',
searchId: ':searchId',
choice: ':choice',
currentHour: ':currentHour',
}),
});
module.exports = Object.freeze( async ({
raffleId,
choice,
currentHour,
}) => {
console.log(
'running getWinnerExchangeUserIds, YES🦖👑👑👑 - ' +
'using the following values: ' +
stringify({
raffleId,
choice,
currentHour,
})
);
const exchangeUserIdToWinData = {};
let paginationValueToUse = null;
let iterationCount = 0;
do {
console.log(
'getWinnerExchangeUserIds - ' +
'running transactions search: ' +
stringify({
exchangeUserIdToWinData,
paginationValueToUse,
iterationCount,
})
);
const searchParams = {
TableName: TRANSACTIONS,
IndexName: searchIdCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: true,
// ProjectionExpression: [
// attributes.nameKeys.amount,
// attributes.nameKeys.creationDate,
// attributes.nameKeys.action,
// ].join( ', ' ), // TODO:
KeyConditionExpression: (
`${ attributes.nameKeys.searchId } = ${ attributes.valueKeys.searchId } and ` +
`${ attributes.nameKeys.creationDate } <= ${ attributes.valueKeys.currentHour }`
),
FilterExpression: (
`${ attributes.nameKeys.raffleType } = ${ attributes.valueKeys.raffleType } and ` +
`${ attributes.nameKeys.choice } = ${ attributes.valueKeys.choice }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.searchId]: attributes.nameValues.searchId,
[attributes.nameKeys.raffleType]: attributes.nameValues.raffleType,
[attributes.nameKeys.choice]: attributes.nameValues.choice,
[attributes.nameKeys.creationDate]: attributes.nameValues.creationDate,
},
ExpressionAttributeValues: {
[attributes.valueKeys.searchId]: raffleId,
[attributes.valueKeys.raffleType]: putTicket,
[attributes.valueKeys.choice]: choice,
[attributes.valueKeys.currentHour]: isProductionMode ? currentHour : Date.now(),
// [attributes.valueKeys.currentHour]: Date.now(),
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const raffleTransactions = ultimateResults;
for( const transaction of raffleTransactions ) {
if( transaction.action === buy ) {
exchangeUserIdToWinData[ transaction.exchangeUserId ] = true;
}
else {
delete exchangeUserIdToWinData[ transaction.exchangeUserId ];
}
}
if( !!paginationValue ) {
paginationValueToUse = paginationValue;
iterationCount++;
}
else if( !!paginationValueToUse ) {
paginationValueToUse = null;
}
} while( !!paginationValueToUse );
const winnerExchangeUserIds = Object.keys( exchangeUserIdToWinData );
console.log(
'getWinnerExchangeUserIds executed successfully✅✅✅✅✅✅ - ' +
'here are the winnerExchangeUserIds: ' +
stringify( winnerExchangeUserIds )
);
return winnerExchangeUserIds;
});
<file_sep>import { createElement as e, lazy, Suspense } from 'react';
import { getState } from '../../reduxX';
import { story } from '../../constants';
// import InitialChoiceMode from './InitialChoiceMode';
import LoadingPage from '../../TheSource/LoadingPage';
const InitialChoiceMode = lazy(() => import('./InitialChoiceMode'));
const SignUpMode = lazy(() => import('./SignUpMode'));
const AfterSignUpMode = lazy(() => import('./AfterSignUpMode'));
const VerifyUserMode = lazy(() => import('./VerifyUserMode'));
const LoginMode = lazy(() => import('./LoginMode'));
const ForgotMyPasswordMode = lazy(() => import('./ForgotMyPasswordMode'));
const PasswordResetMode = lazy(() => import('./PasswordResetMode'));
const FreeGameMode = lazy(() => import('./FreeGameMode'));
const StandardSuspense = ({ children }) => {
return e(
Suspense,
{
fallback: e( 'div' ),
},
children
);
};
const getStyles = () => {
const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: mainStyleObject.backgroundColor,
// backgroundColor: 'lightgreen',
// width: 300,
width: '100%',
// height: 200,
display: 'flex',
flexDirection: 'column',
// justifyContent: 'space-between',
// alignItems: 'center',
justifyContent: 'flex-start',
alignItems: 'center',
color: 'white',
},
};
};
export default ({
websiteName
}) => {
const styles = getStyles();
const mainMode = getState( 'notLoggedInMode', 'mainMode' );
const freeGame = getState( 'notLoggedInMode', 'freeGame' );
const createElementArguments = [
'div',
{
style: styles.outerContainer,
}
];
if( mainMode === story.NotLoggedInMode.mainModes.signUpMode ) {
createElementArguments.push(
e(
StandardSuspense,
{},
e( SignUpMode )
)
);
}
else if( mainMode === story.NotLoggedInMode.mainModes.loginMode ) {
createElementArguments.push(
e(
StandardSuspense,
{},
e( LoginMode )
)
);
}
else if( mainMode === story.NotLoggedInMode.mainModes.afterSignUpMode ) {
createElementArguments.push(
e(
StandardSuspense,
{},
e(
AfterSignUpMode,
{
websiteName
}
)
)
);
}
else if( mainMode === story.NotLoggedInMode.mainModes.verifyUserMode ) {
createElementArguments.push(
e(
StandardSuspense,
{},
e( VerifyUserMode )
)
);
}
else if( mainMode === story.NotLoggedInMode.mainModes.forgotMyPasswordMode ) {
createElementArguments.push(
e(
StandardSuspense,
{},
e( ForgotMyPasswordMode )
)
);
}
else if( mainMode === story.NotLoggedInMode.mainModes.passwordResetMode ) {
createElementArguments.push(
e(
StandardSuspense,
{},
e( PasswordResetMode )
)
);
}
else if( !!freeGame ) {
createElementArguments.push(
e(
StandardSuspense,
{},
e( FreeGameMode )
)
);
}
else {
createElementArguments.push(
e(
Suspense,
{
fallback: e( LoadingPage, { fullDogeStyle: true } ),
},
e(
InitialChoiceMode,
{
websiteName
}
)
)
);
}
return e( ...createElementArguments );
};
<file_sep>import { getState, setState, resetReduxX } from '../../reduxX';
import { bitcoinExchange, actions, grecaptcha } from '../../utils';
import { google } from '../../constants';
export default async () => {
const googleCode = await grecaptcha.safeGetGoogleCode({
action: google.grecapcha.actions.exchange,
});
if( !googleCode ) {
console.log( 'unable to get google code' );
return;
}
const amountWantedInCryptos = getState( 'exchangePolygon', 'amountWantedInCryptos' );
if( amountWantedInCryptos ) {
setState( 'isLoading', true );
try {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
await bitcoinExchange.exchange({
userId,
loginToken,
amountWantedInCryptos,
googleCode
});
await actions.refreshUserData({ setToLoading: false });
resetReduxX({
listOfKeysToInclude: [
[ 'isLoading' ],
[ 'exchangePolygon', 'amountWantedInBitcoin' ],
[ 'exchangePolygon', 'amountWantedInCryptos' ],
]
});
}
catch( error ) {
setState( 'isLoading', false );
console.log( 'the error:', error );
alert(
`error in doing exchange: ${
(
!!error &&
!!error.response &&
!!error.response.data &&
!!error.response.data.message &&
error.response.data.message
) || 'internal server error'
}`
);
}
}
const amountWantedInBitcoin = getState( 'exchangePolygon', 'amountWantedInBitcoin' );
if( !!amountWantedInBitcoin ) {
setState( 'isLoading', true );
try {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
await bitcoinExchange.exchange({
userId,
loginToken,
amountWantedInBitcoin,
googleCode,
});
await actions.refreshUserData({ setToLoading: false });
resetReduxX({
listOfKeysToInclude: [
[ 'isLoading' ],
[ 'exchangePolygon', 'amountWantedInBitcoin' ],
[ 'exchangePolygon', 'amountWantedInCryptos' ],
]
});
}
catch( error ) {
setState( 'isLoading', false );
console.log( 'the error:', error );
alert(
`error in doing exchange: ${
(
!!error &&
!!error.response &&
!!error.response.data &&
!!error.response.data.message &&
error.response.data.message
) || 'internal server error'
}`
);
}
}
};
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
width: '100%',
// height: 100,
// backgroundColor: 'pink',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
alignItems: 'center'
},
text: {
width: '90%',
// height: 100,
color: 'black',
marginTop: 15,
marginBottom: 5,
// padding: 5,
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Typography,
{
style: styles.text,
},
'Your Referral ID can be used ' +
'for special promotions to get free Bitcoin, ' +
'free Dynasty Bitcoin, and more! ' +
'This Referral ID is okay to share publicly.'
),
e(
Typography,
{
style: styles.text,
},
'Follow ',
e(
'a',
{
target: '_blank',
href: 'https://twitter.com/DynastyBitcoin'
},
'@DynastyBitcoin on Twitter'
),
' to keep up to date with the latest DynastyBitcoin.com ' +
'promotions and giveaways!'
),
);
};
<file_sep>#!/bin/bash
pushd ../../../../../1-backend/giraffeDeploy/giraffe
npm install
popd
pushd ../../../../../1-backend/giraffeDeploy
if [ "$1" == "--force=true" ]; then
npm run depositsBotSF
else
npm run depositsBotS
fi
popd<file_sep>'use strict';
const {
constants: {
environment: {
isProductionMode
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const f = Object.freeze;
const tableNames = isProductionMode ? f({
exchangeUsers: 'bitcoin_api_exchangeUsers',
loginTokens: 'bitcoin_api_loginTokens',
transactions: 'bitcoin_api_transactions',
exchangeEmailDeliveryResults: 'bitcoin_api_exchangeEmailDeliveryResults',
}) : f({
exchangeUsers: 'bitcoin_api_exchangeUsers_staging',
loginTokens: 'bitcoin_api_loginTokens_staging',
transactions: 'bitcoin_api_transactions_staging',
exchangeEmailDeliveryResults: 'bitcoin_api_exchangeEmailDeliveryResults_staging',
});
// const rawVotesData = {
// usaelection: {
// choices: [ 'trump', 'biden' ]
// }
// };
// const votes = {
// ids: { /* usaelection: 'usaelection', */ },
// choices: { usaelection: [ 'trump', 'biden' ], },
// };
// const voteIds = Object.keys( rawVotesData );
// for( const voteId of voteIds ) {
// votes.ids[ voteId ] = voteId;
// votes.choices[ voteId ] = rawVotesData[ voteId ].choices;
// }
// votes.voteIds = voteIds;
module.exports = f({
aws: {
database: {
tableNames: {
EXCHANGE_USERS: tableNames.exchangeUsers,
LOGIN_TOKENS: tableNames.loginTokens,
TRANSACTIONS: tableNames.transactions,
EXCHANGE_EMAIL_DELIVERY_RESULTS: tableNames.exchangeEmailDeliveryResults,
},
tableNameToKey: {
[tableNames.exchangeUsers]: 'exchangeUserId',
[tableNames.loginTokens]: 'exchangeUserId',
[tableNames.transactions]: 'exchangeUserId',
[tableNames.exchangeEmailDeliveryResults]: 'email',
},
tableNameToSortKey: {
[tableNames.loginTokens]: 'expiryTime',
[tableNames.transactions]: 'transactionId',
[tableNames.exchangeEmailDeliveryResults]: 'creationDate',
},
secondaryIndices: {
emailIndex: 'email-index',
exchangeUserIdCreationDateIndex: 'exchangeUserId-creationDate-index',
searchIdCreationDateIndex: 'searchId-creationDate-index',
},
metadataKeys: {
dreamLotus: 'dreamLotus'
},
searchIds: {
dreamLotus: 'dreamLotus'
},
},
},
alien: {
currencies: {
busd: {
key: 'busd',
},
m: {
key: 'm',
},
},
},
transactions: {
types: {
identity: 'identity',
addBitcoin: 'addBitcoin',
withdrawBitcoin: 'withdrawBitcoin',
exchange: 'exchange',
dream: 'dream',
vote: 'vote',
raffle: 'raffle',
bonus: 'bonus',
setAlienBalance: 'setAlienBalance',
},
bitcoinWithdrawTypes: {
start: 'start',
failed: 'failed',
success: 'success',
},
transactionId: {
prefix: 'transaction_',
minLength: 3,
maxLength: 120,
},
},
exchangeUsers: {
exchangeUserId: {
prefix: 'exchange_user_',
minLength: 3,
maxLength: 100,
},
},
withdraws: {
states: {
no_withdraws_are_currently_being_processed: 'no_withdraws_are_currently_being_processed',
withdraw_is_being_processed: 'withdraw_is_being_processed',
}
},
exchanges: {
bounds: {
crypto: {
max: 69000,
min: 0.00001,
},
bitcoin: {
max: 69,
min: 0.00000001,
}
},
rates: {
cryptoOverBTC: 1000,
},
types: {
btcToCrypto: 'btcToCrypto',
cryptoToBTC: 'cryptoToBTC'
}
},
identityTransactions: {
types: {
pure: 'pure',
recalculate: 'recalculate',
refresh: 'refresh',
}
},
dreams: {
types: {
coin: 'coin',
lotus: 'lotus',
slot: 'slot',
}
},
votes: {
types: {
doVote: 'doVote',
payout: 'payout',
}
},
raffles: {
types: {
putTicket: 'putTicket',
payout: 'payout',
},
actions: {
buy: 'buy',
buyUpdate: 'buyUpdate',
cancel: 'cancel'
}
},
queues: {
queueBaseIds: {
lotusDreamsJackpotWin: 'lotusDreamsJackpotWin',
}
}
});<file_sep>import { getState, setState, resetReduxX } from '../../../reduxX';
import {
bitcoinExchange,
actions,
// delay,
dynastyBitcoin,
grecaptcha
} from '../../../utils';
import { google, gameData, games } from '../../../constants';
import { spinDinocoin } from './dinocoinActions';
const getRandomIntInclusive = ( min, max ) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
};
const doFreeGameAction = () => {
const coinNumber = getRandomIntInclusive( 1, 4 );
const won = (coinNumber > 1);
const balance = getState( 'notLoggedInMode', 'freeGameModeBalance' );
const chosenAmount = dynastyBitcoin.getDynastyBitcoinAmount(
getState(
'notLoggedInMode',
'coinFlip',
'selectedAmount'
)
);
setState(
[ 'notLoggedInMode', 'freeGameModeBalance' ],
dynastyBitcoin.getDynastyBitcoinAmount(
balance + (won ? chosenAmount : -chosenAmount)
)
);
return {
happyDream: won
};
};
const doPaidGameAction = async ({
chosenAmount,
}) => {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
const coinFlipMode = getState(
'loggedInMode',
'coinFlip',
'mode'
);
const gameModes = gameData[ games.theDragonsTalisman ].modes;
const isJackpotMode = coinFlipMode === gameModes.jackpot;
if( isJackpotMode ) {
const googleCode = await grecaptcha.safeGetGoogleCode({
action: google.grecapcha.actions.lotusCoinFlip,
});
return await bitcoinExchange.enchantedLuckJackpot({
userId,
loginToken,
amount: chosenAmount,
googleCode,
});
}
const googleCode = await grecaptcha.safeGetGoogleCode({
action: google.grecapcha.actions.coinFlip,
});
return await bitcoinExchange.enchantedLuck({
userId,
loginToken,
amount: chosenAmount,
googleCode,
});
};
export default async ({
freeGameMode,
min,
max,
}) => {
// const amount = getState( 'coinExperiencePolygon', 'amount' );
const mainStateMode = freeGameMode ? 'notLoggedInMode' : 'loggedInMode';
const chosenAmount = dynastyBitcoin.getDynastyBitcoinAmount(
getState(
mainStateMode,
'coinFlip',
'selectedAmount'
)
);
if(
(chosenAmount < min) ||
(chosenAmount > max)
) {
return;
}
setState( 'isLoading', true );
try {
// beginningSpinDinocoin({
// action: 'win',
// });
const {
happyDream
} = freeGameMode ? (
doFreeGameAction()
) : (await doPaidGameAction({
chosenAmount,
}));
// ) : (await bitcoinExchange.enchantedLuck({
// userId,
// loginToken,
// amount: chosenAmount,
// // mode: enchantedLuck.modes.a,
// }));
// await delay({ timeout: 1000 });
spinDinocoin({
action: happyDream ? 'win' : 'lose',
});
if( !freeGameMode ) {
await actions.refreshUserData({ setToLoading: false });
}
resetReduxX({
listOfKeysToInclude: [
[ 'isLoading' ],
[ 'coinExperiencePolygon', 'amount' ],
]
});
}
catch( error ) {
setState( 'isLoading', false );
console.log( 'the error:', error );
alert(
`error in doing exchange: ${
(
!!error &&
!!error.response &&
!!error.response.data &&
!!error.response.data.message &&
error.response.data.message
) || 'internal server error'
}`
);
}
};
<file_sep>'use strict';
const {
utils: {
redis: {
rhinoCombos: {
giraffeAndTreeStatusUpdate
},
doRedisFunction,
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const { eventNames } = require( './constants' );
const sendErrorToDeployStream = Object.freeze( ({
isGiraffe,
}) => doRedisFunction({
performFunction: ({
redisClient
}) => giraffeAndTreeStatusUpdate({
redisClient,
eventName: eventNames.common.error,
information: {
errorMessage: 'control-c style exit function invoked',
isGiraffe: (isGiraffe === '🦒'),
}
}),
functionName: 'control-c style exit function'
}));
module.exports = Object.freeze( ({
isGiraffe
}) => {
console.log( 'initializing control-c send error listener' );
process.on( 'SIGINT', async () => {
await sendErrorToDeployStream({
isGiraffe
});
process.exit();
});
console.log( 'control-c send error listener successfully initialized' );
});<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
transactions: {
types,
},
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
exchangeUsers: {
getBalanceData,
},
crypto: {
cryptoToBTC,
btcToCrypto,
},
constants: {
exchanges
}
} = require( '../../../../../exchangeUtils' );
// const doWithdraw = require( './doWithdraw' );
module.exports = Object.freeze( ({
exchangeUserId,
exchangeUser,
type,
data,
}) => {
console.log( 'running getAddTransactionValues' );
const addTransactionValues = {
noLocka: true,
exchangeUserId,
type: types.exchange,
};
if( type === exchanges.types.btcToCrypto ) {
const {
amountInCryptoWanted
} = data;
const amountInBTCNeeded = cryptoToBTC({
amountInCrypto: amountInCryptoWanted
});
const balanceData = getBalanceData({
exchangeUser,
});
const amountOfBitcoinUserHas = balanceData.summary.bitcoin.totalAmount;
console.log(`
getAddTransactionValues does user have enough
📈 || 📉 ?
${ stringify({
amountOfBitcoinUserHas,
amountInBTCNeeded,
}) }
`);
if( amountOfBitcoinUserHas < amountInBTCNeeded ) {
const error = new Error(
'User does not have enough bitcoin to perform ' +
'the requested exchange. ' +
'The requested exchange requires ' +
`${ amountInBTCNeeded } BTC. ` +
`User only has ${ amountOfBitcoinUserHas } BTC.`
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
Object.assign(
addTransactionValues,
{
data: {
exchangeType: exchanges.types.btcToCrypto,
amountInCryptoWanted,
amountInBTCNeeded,
},
}
);
}
else {
const {
amountInBitcoinWanted
} = data;
const amountInCryptoNeeded = btcToCrypto({
amountInBtc: amountInBitcoinWanted
});
const balanceData = getBalanceData({
exchangeUser,
});
const amountOfCryptoUserHas = balanceData.summary.crypto.totalAmount;
console.log(`
getAddTransactionValues does user have enough
📈 || 📉 ?
${ stringify({
amountOfCryptoUserHas,
amountInCryptoNeeded,
}) }
`);
if( amountOfCryptoUserHas < amountInCryptoNeeded ) {
const error = new Error(
'User does not have enough bitcoin to perform ' +
'the requested exchange. ' +
'The requested exchange requires ' +
`${ amountInCryptoNeeded } Cryptos. ` +
`User only has ${ amountOfCryptoUserHas } Cryptos.`
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
Object.assign(
addTransactionValues,
{
data: {
exchangeType: exchanges.types.cryptoToBTC,
amountInBitcoinWanted,
amountInCryptoNeeded
},
}
);
}
console.log(
'getAddTransactionValues executed successfully,',
'here is the add transaction data:',
stringify( addTransactionValues )
);
return addTransactionValues;
});<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( async ({
collection,
query = {},
queryOptions = {},
projectionOptions,
sortOptions,
}) => {
console.log(
'running mongo search with the following values: ' +
stringify({ query, queryOptions })
);
const results = await new Promise( ( resolve, reject ) => {
const mongoSearch = collection.find(
query,
queryOptions,
);
if( !!projectionOptions ) {
mongoSearch.project( projectionOptions );
}
if( !!sortOptions ) {
mongoSearch.sort( sortOptions );
}
mongoSearch.toArray( ( err, data ) => {
if( !!err ) {
return reject( err );
}
resolve( data );
});
});
console.log(
'mongo search executed successfully - ',
`got ${ results.length } results`
);
return results;
});<file_sep>import { createElement as e, useEffect } from 'react';
import { getState } from '../../reduxX';
import { actions } from '../../utils';
import { pages } from '../../constants';
import { UltraDataContainer } from '../usefulComponents';
import Divider from '@material-ui/core/Divider';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import AddressSection from './AddressSection';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
backgroundColor: 'beige',
width: '100%',
maxWidth: 620,
marginTop: 20,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'left',
},
titleTextBox: {
width: '100%',
backgroundColor: 'beige',
},
titleText: {
paddingTop: 5,
paddingBottom: 5,
color: 'black',
fontSize: 18,
textAlign: 'center',
// padding: 15,
},
};
};
const marginTop = 5;
const SwaggyDivider = () => {
return e(
Divider,
{
style: {
backgroundColor: 'black',
width: '80%',
minWidth: 320,
marginBottom: 17,
marginTop: 5,
// maxWidth: '100%',
}
}
);
};
export default () => {
useEffect( () => {
actions.setLastVisitedPage({
loggedInMode: true,
page: pages.loggedInMode.base,
});
}, [] );
const styles = getStyles();
const {
// userId,
// email,
balanceData,
} = getState( 'loggedInMode', 'userData' );
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.titleTextBox
},
e(
Typography,
{
style: styles.titleText
},
'Account Summary'
)
),
// e(
// UltraDataContainer,
// {
// text: `Email: ${ email }`,
// marginTop,
// }
// ),
// e( SwaggyDivider ),
e(
UltraDataContainer,
{
heading: (
'Bitcoin'
),
lines: [
`Balance: ${ balanceData.summary.bitcoin.totalAmount } BTC`,
e(
Typography,
{
key: 'ultraKeyKeydfd',
style: {
width: '88%',
textAlign: 'left',
wordBreak: 'break-word',
// textIndent: 20,
color: 'black',
fontSize: 14,
marginBottom: 10,
}
},
'(Deposits appear after 6 confirmations)'
),
// `Deposit Address: ${ balanceData.bitcoin.depositAddress || 'currently unavailable' }`,
e(
AddressSection,
{
key: 'argon',
balanceData,
}
)
],
marginTop,
}
),
e( SwaggyDivider ),
e(
UltraDataContainer,
{
heading: (
`Dynasty Bitcoin`
),
lines: [
`Balance: ${ balanceData.summary.crypto.totalAmount } DB`
],
marginTop,
}
)//,
// e( SwaggyDivider )
);
};
<file_sep>#!/bin/bash
echo "****☢️🐑 Teleporting Mega Monkies ****"
echo "👾👾👾👾👾👾👾👾👾👾"
echo "🦍🦍🦍🦍🦍"
echo "👾👾👾👾👾👾👾👾👾👾"
deployCommand="$1"
pemPath="a/b/c/pem-file-name.pem"
destinationUserName="ec2-user"
destinationUrl="ec2-xxx.compute-1yyy.amazonaws.com"
sourceBaseCodePath="/Users/username/code"
destinationBaseCodePath="/home/ec2-user/code"
echo '👾👾👾👾👾👾👾👾👾👾'
echo '👽👽🛸0-COMMONCODE: API'
echo '👾👾👾👾👾👾👾👾👾👾'
apiSourcePath="${sourceBaseCodePath}/zanzibar-realms/0-commonCode/api"
apiDestinationPath="${destinationBaseCodePath}/0-commonCode/api"
scp \
-i "${pemPath}" \
-r \
"${apiSourcePath}/constants" \
"${apiSourcePath}/utils" \
"${apiSourcePath}/index.js" \
"${apiSourcePath}/package.json" \
"${apiSourcePath}/package-lock.json" \
"${destinationUserName}@${destinationUrl}:${apiDestinationPath}"
echo '👾👾👾👾👾👾👾👾👾👾'
echo '👽👽🛸0-COMMONCODE: EXCHANGE'
echo '👾👾👾👾👾👾👾👾👾👾'
exchangeSourcePath="${sourceBaseCodePath}/zanzibar-realms/0-commonCode/exchange"
exchangeDestinationPath="${destinationBaseCodePath}/0-commonCode/exchange"
scp \
-i "${pemPath}" \
-r \
"${exchangeSourcePath}/constants" \
"${exchangeSourcePath}/utils" \
"${exchangeSourcePath}/index.js" \
"${exchangeSourcePath}/package.json" \
"${exchangeSourcePath}/package-lock.json" \
"${destinationUserName}@${destinationUrl}:${exchangeDestinationPath}"
echo ' 👾👾👾👾👾👾👾👾👾👾'
echo '👽👽🛸1-BACKEND: COMMON UTILITIES'
echo '👾👾👾👾👾👾👾👾👾👾'
backendSourcePath="${sourceBaseCodePath}/zanzibar-realms/1-backend/commonUtilities"
backendDestinationPath="${destinationBaseCodePath}/1-backend/commonUtilities"
scp \
-i "${pemPath}" \
-r \
"${backendSourcePath}/doBitcoinRequest" \
"${backendSourcePath}/mongo" \
"${backendSourcePath}/constants.js" \
"${backendSourcePath}/deadFunction.js" \
"${backendSourcePath}/getSafeWriteError.js" \
"${backendSourcePath}/index.js" \
"${backendSourcePath}/package-lock.json" \
"${backendSourcePath}/package.json" \
"${backendSourcePath}/runGiraffeEvolutionProcedure.js" \
"${backendSourcePath}/runSpiritual.js" \
"${backendSourcePath}/signalOnStatusToCommandCenter.js" \
"${destinationUserName}@${destinationUrl}:${backendDestinationPath}"
echo '👾👾👾👾👾👾👾👾👾👾'
echo '👽👽🛸1-BACKEND: GIRAFFE-UTILS'
echo '👾👾👾👾👾👾👾👾👾👾'
giraffeUtilsSourcePath="${sourceBaseCodePath}/zanzibar-realms/1-backend/giraffeDeploy/commonUtilities"
giraffeUtilsDestinationPath="${destinationBaseCodePath}/1-backend/giraffe-utils"
scp \
-i "${pemPath}" \
-r \
"${giraffeUtilsSourcePath}/constants.js" \
"${giraffeUtilsSourcePath}/getTimeInfo.js" \
"${giraffeUtilsSourcePath}/index.js" \
"${giraffeUtilsSourcePath}/listenForEventsAndExecuteActions.js" \
"${giraffeUtilsSourcePath}/package-lock.json" \
"${giraffeUtilsSourcePath}/package.json" \
"${giraffeUtilsSourcePath}/sendErrorToDeployStreamOnControlC.js" \
"${destinationUserName}@${destinationUrl}:${giraffeUtilsDestinationPath}"
echo '👾👾👾👾👾👾👾👾👾👾'
echo '👽👽🛸PUBLIC-NPM: BITCOIN-ADDRESS-VALIDATION'
echo '👾👾👾👾👾👾👾👾👾👾'
bitcoinAddressValidationSourcePath="${sourceBaseCodePath}/bitcoin-address-validation"
bitcoinAddressValidationDestinationPath="${destinationBaseCodePath}/x-public/bitcoin-address-validation"
scp \
-i "${pemPath}" \
-r \
"${bitcoinAddressValidationSourcePath}/src" \
"${bitcoinAddressValidationSourcePath}/.npmignore" \
"${bitcoinAddressValidationSourcePath}/LICENSE" \
"${bitcoinAddressValidationSourcePath}/package-lock.json" \
"${bitcoinAddressValidationSourcePath}/package.json" \
"${bitcoinAddressValidationSourcePath}/README.md" \
"${destinationUserName}@${destinationUrl}:${bitcoinAddressValidationDestinationPath}"
echo '👾👾👾👾👾👾👾👾👾👾'
echo '👽👽🛸PUBLIC-NPM: BITCOIN-API'
echo '👾👾👾👾👾👾👾👾👾👾'
bitcoinApiSourcePath="${sourceBaseCodePath}/bitcoin-api"
bitcoinApiDestinationPath="${destinationBaseCodePath}/x-public/bitcoin-api"
scp \
-i "${pemPath}" \
-r \
"${bitcoinApiSourcePath}/LICENSE" \
"${bitcoinApiSourcePath}/package-lock.json" \
"${bitcoinApiSourcePath}/package.json" \
"${bitcoinApiSourcePath}/README.md" \
"${destinationUserName}@${destinationUrl}:${bitcoinApiDestinationPath}"
# if [ $deployCommand == 'drq' ]; then
# sourcePath="${sourceBaseCodePath}/drq"
# destinationPath="${destinationBaseCodePath}/drq"
# scp \
# -i "${pemPath}" \
# -r \
# "${sourcePath}/doOperationInQueueCore" \
# "${sourcePath}/.npmignore" \
# "${sourcePath}/index.js" \
# "${sourcePath}/LICENSE" \
# "${sourcePath}/package.json" \
# "${sourcePath}/package-lock.json" \
# "${sourcePath}/README.md" \
# "${sourcePath}/tools.js" \
# "${destinationUserName}@${destinationUrl}:${destinationPath}"
# elif [ $deployCommand == 'bqe' ]; then
# sourcePath="${sourceBaseCodePath}/background-executor"
# destinationPath="${destinationBaseCodePath}/openSource/bqe"
# scp \
# -i "${pemPath}" \
# -r \
# "${sourcePath}/getStart" \
# "${sourcePath}/getAddOperation.js" \
# "${sourcePath}/index.js" \
# "${sourcePath}/LICENSE" \
# "${sourcePath}/package.json" \
# "${sourcePath}/package-lock.json" \
# "${sourcePath}/README.md" \
# "${destinationUserName}@${destinationUrl}:${destinationPath}"
# elif [ $deployCommand == 'bitcoin-request' ]; then
# sourcePath="${sourceBaseCodePath}/bitcoin-request"
# destinationPath="${destinationBaseCodePath}/bitcoin-request"
# scp \
# -i "${pemPath}" \
# -r \
# "${sourcePath}/index.js" \
# "${sourcePath}/LICENSE" \
# "${sourcePath}/package.json" \
# "${sourcePath}/package-lock.json" \
# "${sourcePath}/README.md" \
# "${destinationUserName}@${destinationUrl}:${destinationPath}"
# elif [ $deployCommand == 'drf' ]; then
# sourcePath="${sourceBaseCodePath}/drf"
# destinationPath="${destinationBaseCodePath}/drf"
# scp \
# -i "${pemPath}" \
# -r \
# "${sourcePath}/.npmignore" \
# "${sourcePath}/index.js" \
# "${sourcePath}/LICENSE" \
# "${sourcePath}/package.json" \
# "${sourcePath}/package-lock.json" \
# "${sourcePath}/README.md" \
# "${destinationUserName}@${destinationUrl}:${destinationPath}"
# elif [ $deployCommand == 'redis-streams-utils' ]; then
# sourcePath="${sourceBaseCodePath}/redis-streams-utils"
# destinationPath="${destinationBaseCodePath}/redis-streams-utils"
# scp \
# -i "${pemPath}" \
# -r \
# "${sourcePath}/redisStreamsUtils" \
# "${sourcePath}/.npmignore" \
# "${sourcePath}/LICENSE" \
# "${sourcePath}/package.json" \
# "${sourcePath}/package-lock.json" \
# "${sourcePath}/README.md" \
# "${destinationUserName}@${destinationUrl}:${destinationPath}"
# else
# echo "Invalid deploy command"
# fi
echo "👾👾👾👾👾👾👾👾👾👾"
echo "🦍🦍🦍🦍🦍"
echo "👾👾👾👾👾👾👾👾👾👾"
echo "****☢️🐑 The Mega Monkies Were Teleported Successfully ****"<file_sep>import { createElement as e } from 'react';
import { setState } from '../../../../reduxX';
import { story } from '../../../../constants';
// import LuluLemonButton from './LuluLemonButton';
import Button from '@material-ui/core/Button';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
width: 69,
height: 40,
backgroundColor: 'darkgreen',
borderRadius: 4,
// marginTop: 30,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
color: 'white',
},
};
};
export default () => {
const styles = getStyles();
return e(
Button,
{
style: styles.outerContainer,
onClick: () => {
setState( 'metaMode', story.metaModes.zeroPointEnergy );
}
},
'Back'
);
};
<file_sep>'use strict';
module.exports = Object.freeze({
emails: require( './emails' ),
});
<file_sep>import { bitcoinExchange, actions } from '../../../utils';
import { getState } from '../../../reduxX';
export default async ({
raffleId,
numbers,
action,
googleCode,
}) => {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
await bitcoinExchange.postRaffleTicket({
userId,
loginToken,
raffleId,
numbers,
action,
googleCode
});
await Promise.all([
actions.refreshUserData({ setToLoading: false }),
actions.refreshDensityRaffleData({ setToLoading: false }),
actions.refreshes.refreshRaffleTickets({ raffleId })
]);
};<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
google: {
captcha: {
actions
}
}
},
validation: {
getIfEmailIsValid
},
formatting: {
getFormattedEmail,
},
business: {
verifyGoogleCode
}
} = require( '../../../../../utils' );
const {
validation: {
getIfPasswordIsValid
}
} = require( '../../../../../exchangeUtils' );
module.exports = Object.freeze( async ({
rawEmail,
rawPassword,
rawVerifyEmailCode,
rawGoogleCode,
ipAddress
}) => {
console.log(
`running validateAndGetValues
with the following values - ${ stringify({
email: rawEmail,
password: <PASSWORD>,
verifyEmailCode: rawVerifyEmailCode,
googleCode: rawGoogleCode,
ipAddress
})
}`
);
const emailIsInvalid = !getIfEmailIsValid({
email: rawEmail,
});
if( emailIsInvalid ) {
const err = new Error( 'invalid email provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
const passwordIsInvalid = !getIfPasswordIsValid({
password: <PASSWORD>
});
if( passwordIsInvalid ) {
const err = new Error( 'invalid password provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
const verifyEmailCodeIsInvalid = (
!rawVerifyEmailCode ||
(
!rawVerifyEmailCode ||
(typeof rawVerifyEmailCode !== 'string') ||
(rawVerifyEmailCode.length < 5) ||
(rawVerifyEmailCode.length > 169)
)
);
if( verifyEmailCodeIsInvalid ) {
const err = new Error( 'invalid email code provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
await verifyGoogleCode({
rawGoogleCode,
ipAddress,
expectedAction: actions.verifyUser
});
const validValues = {
email: getFormattedEmail({
rawEmail
}),
password: <PASSWORD>,
verifyEmailCode: rawVerifyEmailCode
};
console.log(
'validateAndGetValues executed successfully - got values ' +
stringify( validValues )
);
return validValues;
});
<file_sep>'use strict';
module.exports = Object.freeze(
amount => Number(
(Math.round( Number(amount) * 100000000 ) / 100000000).toFixed(8)
)
);<file_sep>import { setState } from '../../../reduxX';
import { bitcoinExchange, grecaptcha } from '../../../utils';
import { google } from '../../../constants';
export default async ({
isLoading,
emailInput,
passwordInput,
callback,
}) => {
if( isLoading ) {
return;
}
try {
setState( 'isLoading', true );
const googleCode = await grecaptcha.safeGetGoogleCode({
action: google.grecapcha.actions.signUp,
});
if( !googleCode ) {
setState( 'isLoading', false );
return;
}
await bitcoinExchange.createUser({
email: emailInput,
password: <PASSWORD>Input,
googleCode,
});
setState( 'isLoading', false );
if( !!callback ) {
callback();
}
}
catch( err ) {
console.log( 'the error:', err );
console.log( 'the error keys:', Object.keys( err ) );
setState( 'isLoading', false );
alert(
`error in creating user: ${
(
!!err &&
!!err.response &&
!!err.response.data &&
!!err.response.data.message &&
err.response.data.message
) || 'internal server error'
}`
);
}
};
<file_sep>export { default as AboutCoinFlip } from './AboutCoinFlip';
export { default as AboutSlot } from './AboutSlot';
export { default as AboutDestinyRaffle } from './AboutDestinyRaffle';
<file_sep>'use strict';
const {
utils: {
aws: {
dinoCombos: {
balances: {
getIfUserHasEnoughMoneyToMakeTheWithdraw
}
}
},
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
throwNotEnoughBitcoinOnTokenError
} = require( '../../common' );
module.exports = Object.freeze( async ({
withdrawAmount,
feeData,
userId,
shouldIncludeFeeInAmount
}) => {
console.log(
`☢️🐑running ensureUserHasEnoughMoney with the following values: ${
stringify({
withdrawAmount,
userId,
feeData,
shouldIncludeFeeInAmount
})
}`
);
const userDoesNotHaveEnoughMoneyToMakeTheWithdraw = !(
await getIfUserHasEnoughMoneyToMakeTheWithdraw({
withdrawAmount,
feeData,
userId,
shouldIncludeFeeInAmount,
})
);
if( userDoesNotHaveEnoughMoneyToMakeTheWithdraw ) {
console.log(
'ensureUserHasEnoughMoney error - ' +
'This user does not have enough money to make the withdraw.🦀'
);
throw throwNotEnoughBitcoinOnTokenError();
}
console.log(
'ensureUserHasEnoughMoney executed successfully - ' +
'The user has enough money to do this withdraw.🐲🐉'
);
});
<file_sep>'use strict';
require( 'dotenv' ).config();
Object.assign(
process.env,
{
AWS_ACCESS_KEY_ID: process.env.ADD_TRANSACTION_AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY: process.env.ADD_TRANSACTION_AWS_SECRET_ACCESS_KEY,
AWS_REGION: process.env.ADD_TRANSACTION_AWS_REGION,
}
);
const {
exchangeUserId,
// raffleId,
} = require( '../values' );
const addTransactionAndUpdateExchangeUser = require( process.env.IRELAND_ATAUEUP );
const params = {
exchangeUserId: exchangeUserId,
// exchangeUserId: 'exchange_user_a1bda9f18d4<KEY>',
// type: 'raffle',
// data: {
// // raffleId,
// // amount: -2,
// // raffleType: 'putTicket',
// // choice: '1-36',
// // // choice: '2-36',
// // action: 'buy',
// // raffleId,
// // amount: 2,
// // raffleType: 'putTicket',
// // choice: '1-36',
// // action: 'cancel',
// // raffleId: 'raffle_1602141854902',
// // amount: 500,
// // raffleType: 'payout',
// // raffleDrawId: 'raffle_draw_832193712939',
// }
type: 'dream',
data: {
dreamType: 'lotus',
searchId: 'dreamLotus',
amount: 0.0003,
},
// type: 'bonus',
// data: {
// searchId: 'test-1',
// cryptoAmount: 0,
// bitcoinAmount: -0.0001
// },
// type: 'identity',
// data: {
// // identityType: 'pure',
// // identityType: 'recalculate',
// identityType: 'refresh',
// }
};
(async () => {
try {
console.log(
'adding transaction',
JSON.stringify({
params,
}, null, 4)
);
await addTransactionAndUpdateExchangeUser( params );
console.log(`
Adding Transaction Results: ${ JSON.stringify( {
// responseB: response.body,
}, null, 4 ) }
`);
}
catch( err ) {
console.log( 'an error occurred in the request:', err.message );
}
})();
<file_sep>import { setState } from '../reduxX';
import { actions } from '../utils';
export default () => {
if( actions.getIsLoggedIn() ) {
return;
}
const userId = localStorage.getItem( 'userId' );
const loginToken = localStorage.getItem( 'loginToken' );
if(
!!userId &&
!!loginToken
) {
setState(
{
keys: [ 'auth', 'userId' ],
value: userId
},
{
keys: [ 'auth', 'loginToken' ],
value: loginToken
}
);
}
};
<file_sep>'use strict';
const MONEY_ACTIONS = {
types: {
regal: {
addressAmountUpdate: 'bitcoinAddressAmountUpdate',
exchange: {
btcToCrypto: 'exchangeBtcToCrypto',
cryptoToBTC: 'exchangeCryptoToBTC',
},
withdraw: {
start: 'withdrawStart',
success: 'withdrawSuccess',
failed: 'withdrawFailed',
},
},
game: {
talismanFlip: 'talismanFlip',
slot: 'slot',
lotus: {
pickPetal: 'lotusPickPetal',
unpickPetal: 'lotusUnpickPetal',
flowerPotPayout: 'lotusFlowerPotPayout',
},
},
}
};
const transactions = {
addBitcoin: {
"address": "3DythSzb7uFMtW5tcNoNXc9L7X1MgATBYj",
"amount": 0.0093,
"creationDate": 1604768290517,
"exchangeUserId": "exchange_user_dd458c14943d4af3875c037e760d6e34",
"lastUpdated": 1604768290549,
"transactionId": "transaction_bf85041743474c56831fb09e2c0cae9c_1604768290549",
"type": "addBitcoin"
},
withdraws: {
start: {
"address": "1P5EJXuvag6RygC4nfe7n4fick8PzwKm7Z",
"amount": 0.0005,
"bitcoinWithdrawType": "start",
"creationDate": 1614658351279,
"exchangeUserId": "exchange_user_3fc87acac3c84240b788af5ee78e930b",
"fee": 0.00011687,
"feeIncludedInAmount": false,
"lastUpdated": 1614658351558,
"transactionId": "transaction_42903594df2548738f95ea2cece2c8e5_1614658351558",
"type": "withdrawBitcoin",
"withdrawId": "f733556a-bd45-468f-9bf8-c96c615537a8"
},
success: {
"address": "1P5EJXuvag6RygC4nfe7n4fick8PzwKm7Z",
"amount": 0.0005,
"bitcoinWithdrawType": "success",
"creationDate": 1614658354930,
"exchangeUserId": "exchange_user_3fc87acac3c84240b788af5ee78e930b",
"fee": 0.00001682,
"lastUpdated": 1614658354958,
"transactionId": "transaction_6bf9be69e87d4c608fcda6ac3c014cb3_1614658354958",
"type": "withdrawBitcoin",
"withdrawId": "f733556a-bd45-468f-9bf8-c96c615537a8"
}
},
exchange: {
btcToCrypto: {
"amountInBTCNeeded": 0.00001,
"amountInCryptoWanted": 0.01,
"creationDate": 1605495474189,
"exchangeType": "btcToCrypto",
"exchangeUserId": "exchange_user_3fc87acac3c84240b788af5ee78e930b",
"lastUpdated": 1605495474529,
"transactionId": "transaction_045900dcac1748b2bec522458895f6ea_1605495474528",
"type": "exchange"
},
cryptoToBTC: {
"amountInBitcoinWanted": 0.001,
"amountInCryptoNeeded": 1,
"creationDate": 1611920097918,
"exchangeType": "cryptoToBTC",
"exchangeUserId": "exchange_user_3fc87acac3c84240b788af5ee78e930b",
"lastUpdated": 1611920098238,
"transactionId": "transaction_05f3b698ec714c3b8ace96c97b32a502_1611920098237",
"type": "exchange"
},
},
game: {
dream: {
coin: {
"amount": 0.1,
"creationDate": 1602595964030,
"dreamType": "coin",
"exchangeUserId": "exchange_user_3fc87acac3c84240b788af5ee78e930b",
"happyDream": true,
"lastUpdated": 1602595964109,
"transactionId": "transaction_22f504f8204d4d69803f626cca5cffc6_1602595964109",
"type": "dream"
},
coinLose: {
"amount": 0.1,
"creationDate": 1602595964030,
"dreamType": "coin",
"exchangeUserId": "exchange_user_3fc87acac3c84240b788af5ee78e930b",
"happyDream": true,
"lastUpdated": 1602595964109,
"transactionId": "transaction_22f504f8204d4d69803f626cca5cffc6_1602595964109",
"type": "dream"
},
},
dreamSlot: {
slotWin: {
"amount": 0.0007,
"creationDate": 1621721764176,
"dreamType": "slot",
"exchangeUserId": "exchange_user_1c5f8ad1162e463d84bdeee485e1de36",
"happyDream": true,
"hasTied": false,
"lastUpdated": 1621721764179 + 7200000,
"resultValues": {
"slotNumbers": [ 2, 2, 2 ]
},
"transactionId": "transaction_725cs9294a4584916be57da68173d4f3_1621721764176",
"type": "dream"
},
slotTie: {
"amount": 0,
"creationDate": 1621721764176,
"dreamType": "slot",
"exchangeUserId": "exchange_user_1c5f8ad1162e463d84bdeee485e1de36",
"happyDream": false,
"hasTied": true,
"lastUpdated": 1621721764179 + 3600000,
"resultValues": {
"slotNumbers": [ 1, 2, 3 ]
},
"transactionId": "transaction_725c929e4a4584916bef7da68173d4f3_1621721764176",
"type": "dream"
},
slotLose: {
"amount": -0.0001,
"creationDate": 1621721764176,
"dreamType": "slot",
"exchangeUserId": "exchange_user_1c5f8ad1162e463d84bdeee485e1de36",
"happyDream": false,
"hasTied": false,
"lastUpdated": 1621721764179,
"resultValues": {
"slotNumbers": [ 3, 3, 2 ]
},
"transactionId": "transaction_725c9d294a458491bef57da68173d4f3_1621721764176",
"type": "dream"
},
},
raffle: {
buyTicket: {
"action": "buy",
"amount": -0.1,
"choice": "5-26",
"creationDate": 1606662344982,
"exchangeUserId": "exchange_user_dd458c14943d4af3875c037e760d6e34",
"lastUpdated": 1606662345081,
"raffleType": "putTicket",
"searchId": "raffle_b7b31b2f-6d5e-4f16-a504-481429a26454_1606546881055",
"transactionId": "transaction_3d5c357982fc4b39b98ce0d9179a2ac1_1606662345081",
"type": "raffle"
},
cancelTicket: {
"action": "cancel",
"amount": 0.1,
"choice": "4-9",
"creationDate": 1606662211541,
"exchangeUserId": "exchange_user_dd458c14943d4af3875c037e760d6e34",
"lastUpdated": 1606662211700,
"raffleType": "putTicket",
"searchId": "raffle_b7b31b2f-6d5e-4f16-a504-481429a26454_1606546881055",
"transactionId": "transaction_8811e90ea35744d281a7b87cc80d17f1_1606662211700",
"type": "raffle"
},
payout: {
"amount": 0.582,
"creationDate": 1606546880630,
"exchangeUserId": "exchange_user_3fc87acac3c84240b788af5ee78e930b",
"lastUpdated": 1606546880875,
"raffleDrawId": "raffle_draw_f0501686-febc-43ef-a46a-620416ae34d2_1606546880135",
"raffleType": "payout",
"searchId": "raffle_6000d566-ad67-43e1-8755-57eceb086bdc_1604035560000",
"transactionId": "transaction_cbb11874045d4e979cc034da789d773e_1606546880874",
"type": "raffle"
}
}
},
};
const firstBatchOfMoneyActions = [
{
type: MONEY_ACTIONS.types.game.slot,
amount: transactions.game.dreamSlot.slotWin.amount,
time: transactions.game.dreamSlot.slotWin.creationDate,
happyDream: transactions.game.dreamSlot.slotWin.happyDream,
hasTied: transactions.game.dreamSlot.slotWin.hasTied,
resultValues: transactions.game.dreamSlot.slotWin.resultValues,
transactionId: transactions.game.dreamSlot.slotWin.transactionId,
},
{
type: MONEY_ACTIONS.types.game.slot,
amount: transactions.game.dreamSlot.slotLose.amount,
time: transactions.game.dreamSlot.slotLose.creationDate,
happyDream: transactions.game.dreamSlot.slotLose.happyDream,
hasTied: transactions.game.dreamSlot.slotLose.hasTied,
resultValues: transactions.game.dreamSlot.slotLose.resultValues,
transactionId: transactions.game.dreamSlot.slotLose.transactionId,
},
{
type: MONEY_ACTIONS.types.game.slot,
amount: transactions.game.dreamSlot.slotTie.amount,
time: transactions.game.dreamSlot.slotTie.creationDate,
happyDream: transactions.game.dreamSlot.slotTie.happyDream,
hasTied: transactions.game.dreamSlot.slotTie.hasTied,
resultValues: transactions.game.dreamSlot.slotTie.resultValues,
transactionId: transactions.game.dreamSlot.slotTie.transactionId,
},
];
const secondBatchOfMoneyActions = [
{
type: MONEY_ACTIONS.types.regal.addressAmountUpdate,
address: transactions.addBitcoin.address,
amount: transactions.addBitcoin.amount,
time: transactions.addBitcoin.creationDate,
transactionId: transactions.addBitcoin.transactionId,
},
{
type: MONEY_ACTIONS.types.regal.withdraw.start,
amount: transactions.withdraws.start.amount,
address: transactions.withdraws.start.address,
time: transactions.withdraws.start.creationDate,
fee: transactions.withdraws.start.fee,
feeIncludedInAmount: transactions.withdraws.start.feeIncludedInAmount,
transactionId: transactions.withdraws.start.transactionId,
},
{
type: MONEY_ACTIONS.types.regal.withdraw.success,
amount: transactions.withdraws.success.amount,
address: transactions.withdraws.success.address,
time: transactions.withdraws.success.creationDate,
fee: transactions.withdraws.success.fee,
// feeIncludedInAmount: transactions.withdraws.success.feeIncludedInAmount,
transactionId: transactions.withdraws.success.transactionId,
},
{
type: MONEY_ACTIONS.types.regal.exchange.btcToCrypto,
exchangeType: transactions.exchange.btcToCrypto.exchangeType,
amountInBTCNeeded: 0.0069,
amountInCryptoWanted: 6.9,
time: transactions.exchange.btcToCrypto.creationDate + 6000000,
transactionId: transactions.exchange.btcToCrypto.transactionId + '69',
},
{
type: MONEY_ACTIONS.types.regal.exchange.btcToCrypto,
exchangeType: transactions.exchange.btcToCrypto.exchangeType,
amountInBTCNeeded: 0.0042,
amountInCryptoWanted: 4.2,
time: transactions.exchange.btcToCrypto.creationDate + 42000000,
transactionId: transactions.exchange.btcToCrypto.transactionId + '420',
},
{
type: MONEY_ACTIONS.types.regal.exchange.btcToCrypto,
exchangeType: transactions.exchange.btcToCrypto.exchangeType,
amountInBTCNeeded: 0.00888,
amountInCryptoWanted: 8.88,
time: transactions.exchange.btcToCrypto.creationDate + 888000000,
transactionId: transactions.exchange.btcToCrypto.transactionId + '888',
},
{
type: MONEY_ACTIONS.types.regal.withdraw.failed,
amount: transactions.withdraws.success.amount,
address: transactions.withdraws.success.address,
time: transactions.withdraws.success.creationDate,
fee: transactions.withdraws.success.fee,
// feeIncludedInAmount: transactions.withdraws.success.feeIncludedInAmount,
transactionId: transactions.withdraws.success.transactionId,
},
{
type: MONEY_ACTIONS.types.regal.exchange.btcToCrypto,
exchangeType: transactions.exchange.btcToCrypto.exchangeType,
amountInBTCNeeded: transactions.exchange.btcToCrypto.amountInBTCNeeded,
amountInCryptoWanted: transactions.exchange.btcToCrypto.amountInCryptoWanted,
time: transactions.exchange.btcToCrypto.creationDate,
transactionId: transactions.exchange.btcToCrypto.transactionId,
},
{
type: MONEY_ACTIONS.types.regal.exchange.cryptoToBTC,
exchangeType: transactions.exchange.cryptoToBTC.exchangeType,
amountInCryptoNeeded: transactions.exchange.cryptoToBTC.amountInCryptoNeeded,
amountInBitcoinWanted: transactions.exchange.cryptoToBTC.amountInBitcoinWanted,
time: transactions.exchange.cryptoToBTC.creationDate,
transactionId: transactions.exchange.cryptoToBTC.transactionId,
},
{
type: MONEY_ACTIONS.types.game.talismanFlip,
amount: transactions.game.dream.coin.amount,
time: transactions.game.dream.coin.creationDate,
transactionId: transactions.game.dream.coin.transactionId,
},
{
type: MONEY_ACTIONS.types.game.talismanFlip,
amount: -transactions.game.dream.coinLose.amount,
time: transactions.game.dream.coinLose.creationDate,
transactionId: transactions.game.dream.coinLose.transactionId,
},
{
type: MONEY_ACTIONS.types.game.lotus.pickPetal,
amount: transactions.game.raffle.buyTicket.amount,
choice: transactions.game.raffle.buyTicket.choice,
time: transactions.game.raffle.buyTicket.creationDate,
lotusSeasonId: transactions.game.raffle.buyTicket.searchId,
transactionId: transactions.game.raffle.buyTicket.transactionId,
},
{
type: MONEY_ACTIONS.types.game.lotus.unpickPetal,
amount: transactions.game.raffle.cancelTicket.amount,
choice: transactions.game.raffle.cancelTicket.choice,
time: transactions.game.raffle.cancelTicket.creationDate,
lotusSeasonId: transactions.game.raffle.cancelTicket.searchId,
transactionId: transactions.game.raffle.cancelTicket.transactionId,
},
{
type: MONEY_ACTIONS.types.game.lotus.flowerPotPayout,
amount: transactions.game.raffle.payout.amount,
time: transactions.game.raffle.payout.creationDate,
lotusSeasonId: transactions.game.raffle.payout.searchId,
petalDrawId: transactions.game.raffle.payout.raffleDrawId,
transactionId: transactions.game.raffle.payout.transactionId,
}
];
module.exports = Object.freeze({
firstBatchOfMoneyActions,
// firstBatchOfMoneyActions: [],
secondBatchOfMoneyActions,
// secondBatchOfMoneyActions: [],
});<file_sep>'use strict';
module.exports = Object.freeze( ({
loginTokenId
}) => {
if(
!loginTokenId ||
(typeof loginTokenId !== 'string')
) {
throw new Error(
'getLoginTokenIdComponents: ' +
`invalid loginTokenId: ${ loginTokenId }`
);
}
const splitLoginTokenId = loginTokenId.split( '-' );
if( splitLoginTokenId.length !== 2 ) {
throw new Error(
'getLoginTokenIdComponents: ' +
`invalid loginTokenId: ${ loginTokenId }`
);
}
const [ loginTokenTag, baseId ] = splitLoginTokenId;
if(
!(
(
loginTokenTag ===
'login_token'
) &&
(
!!baseId &&
(baseId.length === 96)
)
)
) {
throw new Error(
'getLoginTokenIdComponents: ' +
`invalid loginTokenId: ${ loginTokenId }`
);
}
return {
baseId
};
});<file_sep>'use strict';
const {
exchanges: {
rates: {
cryptoOverBTC
}
}
} = require( '../constants' );
const {
utils: {
bitcoin: {
formatting: { getAmountNumber }
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( ({
amountInCrypto
}) => {
const amountInBTC = getAmountNumber( amountInCrypto / cryptoOverBTC );
return amountInBTC;
});
<file_sep>import { createElement as e, useState, useEffect } from 'react';
import { getState } from '../../../reduxX';
// import { getState, setState } from '../../../reduxX';
// import { gameData, games } from '../../../constants';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'lightGreen',
// maxWidth: 620,
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
},
theText: {
fontSize: 16,
textAlign: 'center',
maxWidth: '90%',
}
};
};
const getDisplayValue = ({
isJackpotMode,
freeGameMode,
freeGameJackpotAmount,
}) => {
if( !isJackpotMode ) {
return '💎';
}
if( freeGameMode ) {
return `${ freeGameJackpotAmount } DB`;
}
// if not logged in, get fake one
const jackpotAmount = getState(
'loggedInMode',
'coinFlip',
'jackpotAmount'
);
if( typeof jackpotAmount !== 'number' ) {
return '-';
}
return `${ jackpotAmount } DB`;
};
export default ({
isJackpotMode,
freeGameMode
}) => {
const [ freeGameJackpotAmount, setFreeGameJackpotAmount ] = useState( 1 );
useEffect( () => {
if( freeGameMode && isJackpotMode ) {
const intervalID = setInterval( () => {
setFreeGameJackpotAmount( freeGameJackpotAmount + 1 );
}, 3500 );
return () => {
clearInterval( intervalID );
};
}
}, [ freeGameMode, freeGameJackpotAmount, isJackpotMode ] );
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Typography,
{
style: styles.theText,
},
getDisplayValue({
isJackpotMode,
freeGameMode,
freeGameJackpotAmount,
})
)
);
};
<file_sep>'use strict';
const {
utils: {
bitcoin: {
validation: { getIsValidAddress }
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = getIsValidAddress;<file_sep>'use strict';
const {
getFormattedEvent,
beginningDragonProtection,
handleError,
getResponse,
} = require( '../../../utils' );
const doLogin = require( './doLogin' );
const twoHours = 2 * 60 * 60 * 1000;
exports.handler = Object.freeze( async rawEvent => {
console.log( 'running /tokens - POST function' );
try {
const event = getFormattedEvent({
rawEvent,
});
const {
ipAddress
} = await beginningDragonProtection({
queueName: 'post_tokens',
event,
ipAddressMaxRate: 2,
ipAddressTimeRange: twoHours,
megaCodeIsRequired: false,
});
const doLoginResults = await doLogin({
ipAddress
});
console.log( '/tokens - POST function executed successfully' );
const response = getResponse({
body: doLoginResults
});
return response;
}
catch( err ) {
console.log( 'error in /tokens - POST function', err );
return handleError( err );
}
});<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase
}
},
stringify,
},
constants: {
// aws: {
// database: {
// tableNames: {
// METADATA
// },
// tableNameToKey,
// secondaryIndex: {
// typeCreationDateIndex
// }
// }
// },
// metadata: {
// types: {
// raffleDraw
// }
// },
environment: {
isProductionMode
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
TRANSACTIONS
},
secondaryIndices: {
searchIdCreationDateIndex
}
}
},
raffles: {
types: {
putTicket
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
constants,
exchangeUsers: {
getHiddenGhostId
}
// javascript: {
// getHashedValue
// }
} = require( '../../../../../../../exchangeUtils' );
// const {
// javascript: {
// getHashedValue
// }
// } = require( '../../../../../../../utils' );
const getEncryptedPseudoSpecialId = require( './getEncryptedPseudoSpecialId' );
// const getEncryptedExchangeUserId = require(
// '../../../../../../sacredElementals/crypto/getEncryptedExchangeUserId'
// );
// const searchLimit = isProductionMode ? 5000 : 100;
const searchLimit = isProductionMode ? 5000 : 3;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
searchId: '#searchId',
raffleType: '#raffleType',
}),
nameValues: f({
searchId: 'searchId',
raffleType: 'raffleType',
}),
valueKeys: f({
searchId: ':searchId',
raffleType: ':raffleType',
}),
});
// const key = tableNameToKey[ METADATA ];
module.exports = Object.freeze( async ({
raffleId,
time,
transactionId,
specialId,
}) => {
console.log(
'running getTicketsData with the following values: ' +
stringify({
raffleId,
time,
transactionId,
specialId,
})
);
// TODO: filter raffleType putTicket
const searchParams = {
TableName: TRANSACTIONS,
IndexName: searchIdCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: true,
// ProjectionExpression: [
// attributes.nameKeys.amount,
// attributes.nameKeys.creationDate,
// attributes.nameKeys.action,
// ].join( ', ' ), // TODO:
KeyConditionExpression: (
`${ attributes.nameKeys.searchId } = ${ attributes.valueKeys.searchId }`
),
FilterExpression: (
`${ attributes.nameKeys.raffleType } = ${ attributes.valueKeys.raffleType }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.searchId]: attributes.nameValues.searchId,
[attributes.nameKeys.raffleType]: attributes.nameValues.raffleType,
},
ExpressionAttributeValues: {
[attributes.valueKeys.searchId]: raffleId,
[attributes.valueKeys.raffleType]: putTicket,
},
ExclusiveStartKey: (!!time && !!specialId && !!transactionId) ? {
creationDate: time,
exchangeUserId: specialId,
transactionId,
searchId: raffleId
} : undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const tickets = ultimateResults.map( ({
choice,
action,
creationDate,
exchangeUserId,
}) => {
const specialId = getHiddenGhostId({
exchangeUserId,
});
return {
choice,
time: creationDate,
specialId,
action,
};
});
const pageInfo = !!paginationValue ? {
time: paginationValue.creationDate,
powerId: paginationValue.transactionId.substring(
constants.transactions.transactionId.prefix.length
),
specialId: getEncryptedPseudoSpecialId({
exchangeUserId: paginationValue.exchangeUserId,
}),
} : null;
const ticketsData = {
tickets,
pageInfo,
};
console.log(
'getTicketsData executed successfully - got ' +
`${ ultimateResults.length } draws - ` +
`the search limit is: ${ searchLimit }`
);
return ticketsData;
});
<file_sep>import { grecaptcha } from '../utils';
import setUpNavigation from './setUpNavigation';
// import processQueryString from './processQueryString';
import goToRightUrlIfNecessary from './goToRightUrlIfNecessary';
import processPath from './processPath';
import keepTrackOfWindowSize from './keepTrackOfWindowSize';
import runChronicTasks from './runChronicTasks';
import loadGrecaptcha from './loadGrecaptcha';
export default () => {
goToRightUrlIfNecessary();
setUpNavigation();
loadGrecaptcha();
grecaptcha.hideGrecaptcha();
processPath();
keepTrackOfWindowSize();
runChronicTasks();
};
<file_sep>import { createElement as e, useEffect } from 'react';
import { getState, setState } from '../../../reduxX';
import { validation } from '../../../utils';
// import { story } from '../../../constants';
import { grecaptcha, actions } from '../../../utils';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import {
TitlePolygon,
} from '../../../TheSource';
import resetPassword from './resetPassword';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'pink',
width: 300,
// height: 200,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
titleText: {
width: '100%',
color: 'white',
},
usernameInput: {
backgroundColor: 'beige',
color: 'black',
width: '100%',
},
passwordInput: {
width: '100%',
// height: 69,
backgroundColor: 'beige',
// borderStyle: 'solid',
// borderColor: '#4051B5',
// borderWidth: '2px 2px 0px 2px',
// borderRadius: 3,
// color: 'white',
marginTop: 15,
},
repeatPasswordInput: {
marginTop: 20,
width: '100%',
backgroundColor: 'beige',
borderRadius: 3,
},
buttonContainer: {
marginTop: 40,
width: '100%',
// height: 200,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
button: {
color: 'black',
width: '100%',
backgroundColor: 'beige',
},
};
};
export default () => {
useEffect( () => {
actions.scroll();
grecaptcha.showGrecaptcha();
return () => {
Promise.resolve().then( async () => {
try {
await grecaptcha.hideGrecaptcha();
}
catch( err ) {
console.log( 'error in hiding grecaptcha:', err );
}
});
};
}, [] );
const isLoading = getState( 'isLoading' );
const styles = getStyles();
const email = getState(
'notLoggedInMode',
'passwordReset',
'email'
);
const passwordResetCode = getState(
'notLoggedInMode',
'passwordReset',
'passwordResetCode'
);
const passwordInput = getState(
'notLoggedInMode',
'passwordReset',
'passwordInput'
);
const repeatPasswordInput = getState(
'notLoggedInMode',
'passwordReset',
'repeatPasswordInput'
);
const resetPasswordIsDisabled = !(
!isLoading &&
!!passwordResetCode &&
validation.isValidEmail( email ) &&
validation.isValidPassword( passwordInput ) &&
(
passwordInput ===
repeatPasswordInput
)
);
return e(
Box,
{
style: styles.outerContainer,
},
e(
TitlePolygon,
{
shouldHaveHomeButton: true,
marginBottom: 39,
}
),
e(
Typography,
{
style: styles.titleText,
},
`Reset Password`
),
e(
'form',
{
id: 'resetPasswordForm'
},
e(
TextField,
{
style: styles.usernameInput,
disabled: true,
type: 'email',
autoComplete: 'username',
onChange: () => {},
value: email,
},
),
e(
TextField,
{
// variant: 'outlined',
label: 'new password',
disabled: isLoading,
style: styles.passwordInput,
type: 'password',
autoComplete: 'new-password',
onChange: event => {
const newText = event.target.value;
if( newText.length > 200 ) {
return;
}
setState(
[
'notLoggedInMode',
'passwordReset',
'passwordInput'
],
newText.trim()
);
},
// value: '<EMAIL>'
value: passwordInput,
}
),
e(
TextField,
{
// variant: 'outlined',
label: 'repeat new password',
disabled: isLoading,
style: styles.repeatPasswordInput,
autoComplete: 'new-password',
type: 'password',
onChange: event => {
const newText = event.target.value;
if( newText.length > 200 ) {
return;
}
setState(
[
'notLoggedInMode',
'passwordReset',
'repeatPasswordInput'
],
newText.trim()
);
},
// value: '<EMAIL>'
value: repeatPasswordInput
}
),
),
e(
Box,
{
style: styles.buttonContainer,
},
e(
Button,
{
disabled: resetPasswordIsDisabled,
form: 'resetPasswordForm',
style: styles.button,
onClick: async () => {
try {
setState( 'isLoading', true );
await resetPassword();
setState( 'isLoading', false );
}
catch( err ) {
setState( 'isLoading', false );
alert(
`error in resetting password: ${
(
!!err &&
!!err.response &&
!!err.response.data &&
!!err.response.data.message &&
err.response.data.message
) || 'internal server error'
}`
);
}
},
},
'Reset Password and Login'
)
)
);
};
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import { getState, setState } from '../../../../reduxX';
// import { story } from '../../../../constants';
import Button from '@material-ui/core/Button';
import addAddress from './addAddress';
// import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'pink',
// width: '100%',
// width: 300,
// height: 230,
display: 'flex',
justifyContent: 'space-around',
flexDirection: 'column',
alignItems: 'center'
},
innerContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
backgroundColor: 'black',
width: '100%',
maxWidth: 620,
minWidth: 310,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 4,
marginTop: 25,
},
button: {
// backgroundColor: mainStyleObject.backgroundColor,
backgroundColor: 'beige',
width: '98%',
maxWidth: 620,
minWidth: 310,
// height: '20%',
marginTop: 5,
marginBottom: 5,
marginLeft: 5,
marginRight: 5,
},
};
};
export default () => {
const styles = getStyles();
const isLoading = getState( 'isLoading' );
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.innerContainer,
},
e(
Button,
{
disabled: isLoading,
style: styles.button,
onClick: async () => {
try {
setState( 'isLoading', true );
await addAddress();
setState( 'isLoading', false );
}
catch( err ) {
setState( 'isLoading', false );
alert(
`error in getting address: ${
(
!!err &&
!!err.response &&
!!err.response.data &&
!!err.response.data.message &&
err.response.data.message
) || 'internal server error'
}`
);
}
},
},
'Get Bitcoin Deposit Address'
)
)
);
};
<file_sep>import ArgonInformation from './ArgonInformation';
import { createElement as e } from 'react';
export default () => {
return e(
ArgonInformation,
{
title: 'Terms of Service',
lastUpdatedDate: 'July 1st 2020',
titleContentsAndMore: [
{
contents: 'PLEASE READ THE TERMS OF SERVICE CAREFULLY. YOU AGREE TO BE BOUND BY THE ENTIRE TERMS OF SERVICE WHEN YOU CLICK "AGREE TO THE TERMS OF SERVICE" OR BY USING DYNASTYBITCOIN.COM SERVICES. FAILURE TO ABIDE TO THESE TERMS MAY RESULT IN SUSPENSION OR TERMINATION OF YOUR ACCESS TO DYNASTYBITCOIN.COM SERVICES.'
},
{
title: 'Abbreviations and Equivalent Terms',
contents: (
'The following terms in this document have their abbreviations ' +
'and their equivalent meanings listed as follows:'
)
},
{
contents: (
'• DYNASTYBITCOIN.COM: is equivalent to "DB", "us", or "we". This refers to the website DynastyBitcoin.com and any associated technologies.'
)
},
{
contents: (
'• THE USER: is equivalent to "you", the "customer", or your "company" that uses DynastyBitcoin.com services.'
)
},
{
title: 'Customer Agreement',
contents: (
'In you using DB services, you are above 21 years of age and are legally allowed in your jurisdiction to make a binding agreement. Also in using DB services, you agree with and are fully capable of fulfilling the terms set forth in this Terms of Service. In the case where these terms are violated, you agree to be liable to us.'
)
},
// {
// title: 'Restricted Regions',
// contents: (
// 'Individuals in the United States of America or Europe are not allowed to use DB services. In using DB services and in agreeing to the terms, you agree you are not using DB services from these restricted locations.'
// )
// },
{
title: 'Changes to the Terms of Service',
contents: (
'In order to best serve our customers, DB may modify the Terms of Service at any time. If material changes are made to the Terms of Service, you will be notified. The last material update is indicated at the top of this Terms of Service in the "Last Updated" section. If you do not agree to the updated version, you must cease to use DB as soon as the new Terms of Service is has been put into place. By continuing to use DB when the new Terms of Service becomes valid, that indicates that you accept the new Terms of Service and agree to be bound by its terms.'
)
},
{
title: 'General Terms',
contents: (
'Cryptocurrency is a new financial technology and by nature there are risks involved in using them. DB strives manage your cryptocurrencies in the most safe and secure way possible. DB is not responsible for any Bitcoin or digital currency stolen or lost due to negligence on the part of the user (e.g. mismanaged or leaked account login credentials, or hacks directed towards users such as phishing scams). DB is not responsible for any lost or stolen Bitcoin or digital currency. DB only holds small amounts of Bitcoin, the rest is stored in cold storage, contact <EMAIL> if you want to make a large withdraw.'
)
},
{
title: 'Unacceptable Use or Conduct',
contents: (
'• Using DynastyBitcoin.com to finance anything illegal is strictly against the DynastyBitcoin.com Terms of Service. If there is any suspected or discovered criminal activity being facilitated by DB technology, it will immediately be investigated by DB and appropriate action will be taken.'
)
},
{
contents: (
'• any suspected activity related to money laundering'
)
},
{
contents: (
'• providing false or inaccurate information'
)
},
{
contents: (
'• abusing DB technology through hacking or other malicious interactions with DB and its technology'
)
},
{
contents: (
`• disrupting others' user experience`
)
},
// {
// title: 'Inactive Accounts',
// contents: (
// 'Unused accounts expire. A DB account is considered to be "Inactive" after twelve (12) consecutive months of no logins. Inactive accounts may be deleted and any digital assets (including Bitcoin and Dynasty Bitcoin) on Inactive accounts may be removed.'
// )
// },
{
title: 'Account Deletion',
contents: (
'If you want your account and/or your personally identifiable information to be deleted, please email <EMAIL>.'
)
},
{
title: 'Abuse of Technology',
contents: (
'Any abuse of DB systems will result in suspended accounts.'
)
},
{
title: 'Third-Party Content',
contents: (
'In using DB services, we may provide access to third-party content through DB content (e.g. links to Twitter pages). The usage of that third-party content including the data you share while interacting with that content is entirely between you and that third-party and DB is not legally tied to those third-parties in any way. DB does not endorse or represent any third-party companies in any way and does not provide any warranties associated with them. Use this third-party content at your own risk.'
)
},
{
title: 'Non-Advisory',
contents: (
'DB is not a business advisor in any way. DB will give no monetary or legal advice. All information provided by DB is for informational purposes only. You are solely responsible for the way you use DB services.'
)
},
{
title: 'Limitation Of Liability',
contents: (
'IN NO EVENT SHALL WE, OUR SERVICE PROVIDERS, OUR SUBCONTRACTORS, OR OUR LICENSORS BE LIABLE FOR ANY PUNITIVE, SPECIAL, INCIDENTAL, CONSEQUENTIAL, OR INDIRECT DAMAGES (ALSO THIS INCLUDES LOSS OF GOODWILL, LOSS OF USE, LOST PROFITS, OR LOSS OF DATA, WITH NO LIMITATION), RESULTING FROM OR IN ASSOCIATION WITH THESE TERMS OF SERVICE, OR THE OPERATION OF DYNASTYBITCOIN.COM SERVICES, YOUR VIEWING OF, USAGE OF, ACCESS TO, ERROR IN ACCESSING, OR INABILITY TO ACCESS DATA, SOFTWARE, LINKED CONTENT, INFORMATION, OR OTHER SERVICES OBTAINED THROUGH THE DYNASTYBITCOIN.COM SERVICES, OR THE ACT OF ANY OTHER BUSINESS USING OR INTERACTING WITH OUR SERVICES, WHETHER OR NOT WE, OUR SERVICE PROVIDERS, OUR SUBCONTRACTORS, OR OUR LICENSORS HAVE BEEN MADE AWARE OF OR HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, AN ALSO WHETHER SUCH LIABILITY WAS A RESULT OF ANY CLAIM BASED UPON BREACH OF WARRANTY, BREACH OF CONTRACT, TORT, NEGLIGENCE, PRODUCT LIABILITY OR OTHERWISE.'
)
},
{
title: 'Indemnification',
contents: (
`In using DB services, you agree to indemnify, defend and hold us, our consultants, employees, subsidiaries, partners, affiliates, and licensors, free from harm against any damages, liabilities, claims, costs, losses, and expenses (this includes attorney fees and fees for any other services or professionals used) that resulted from or is in any way related to your usage of DB services, you violating any individual's rights, or you violating the Terms of Service.`
)
},
{
title: 'Arbitration',
contents: (
'You and DB agree to arbitrate any legal dispute that occurs as a result of using DB services or any dispute regarding the Terms of Service. ARBITRATION PREVENTS YOU FROM SUING IN COURT AND HAVING A JURY TRIAL. YOU AND DB WILL NOT INITIATE A CLASS ACTION, CLASS ARBITRATION OR REPRESENTATIVE ACTION OR PROCEEDING AGAINST EACH OTHER. You and DB will maintain confidentiality of any arbitration proceedings, judgments and awards, including, but not limited to all information associated with the arbitration and any information related to the dispute in question. Any claim resulting from or associated with the Terms of Service must be filed within one (1) year after the claim arose. If the claim is not filed within that time period, the claim is permanently barred.'
)
},
{
title: 'No Waiver',
contents: (
'None of the terms in this Terms of Service will be waived in the case of us failing to exercise or to enforce any of the terms in the Terms of Service. Failure to exercise any right does not constitute a waiver of that right.'
)
},
{
title: 'Contact',
contents: (
`For any questions, complaints, suggestions, or comments about this Terms of Service or any other aspect of DynastyBitcoin.com services, please don't hesitate to contact us through email at <EMAIL>.`
)
},
]
}
);
};
<file_sep>export { default as UsaElectionPolygon } from './UsaElectionPolygon';
<file_sep>import { setState, resetReduxX } from '../../../../reduxX';
import { bitcoinExchange, grecaptcha } from '../../../../utils';
import { google } from '../../../../constants';
export default async ({
amount,
address,
userId,
loginToken,
fullWithdraw
}) => {
try {
setState( 'isLoading', true );
const googleCode = await grecaptcha.safeGetGoogleCode({
action: google.grecapcha.actions.withdraw,
});
if( !googleCode ) {
// NOTE: safeguard
return setState( 'isLoading', false );
}
await bitcoinExchange.withdraw({
userId,
amount,
address,
loginToken,
fullWithdraw,
googleCode
});
resetReduxX({
listOfKeysToInclude: [
[ 'withdrawPolygon', 'amount' ],
[ 'withdrawPolygon', 'address' ],
[ 'withdrawPolygon', 'fullWithdraw' ]
]
});
setState( 'isLoading', false );
console.log( 'successfully withdrew bitcoin' );
}
catch( err ) {
console.log( 'error in withdrawing bitcoin:', err );
resetReduxX({
listOfKeysToInclude: [
[ 'withdrawPolygon', 'amount' ],
[ 'withdrawPolygon', 'address' ]
]
});
setState( 'isLoading', false );
alert(
`error in withdraw: ${
(
!!err &&
!!err.response &&
!!err.response.data &&
!!err.response.data.message &&
err.response.data.message
) || 'internal server error'
}`
);
}
};
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const execa = require( 'execa' );
module.exports = Object.freeze( async ({
log,
trueTigerPath,
}) => {
log(
'💎💎running deleteTrueTigerPath - ' +
stringify({
trueTigerPath
})
);
await execa(
'rm',
[
'-rf',
trueTigerPath
],
// {}
);
// await execa(
// 'mkdir',
// [
// trueTigerPath
// ],
// // {}
// );
log( '💎💎deleteTrueTigerPath executed successfully' );
});
<file_sep>'use strict';
const bluebird = require( 'bluebird' );
const {
doBitcoinRequest
} = require( '@bitcoin-api/full-stack-backend-private' );
const DELAY_BETWEEN_GETS_IN_MS = 0.2;
module.exports = Object.freeze( ({ transactionIds }) => {
console.log(
'running getTransactionIdToTransactionData with transaction ids: ' +
JSON.stringify( transactionIds, null, 4 )
);
return bluebird.mapSeries( transactionIds, transactionId => {
const args = [
'gettransaction',
transactionId
];
return doBitcoinRequest({ args }).then( rawResult => {
const unformattedTransactionDatum = JSON.parse( rawResult );
const {
amount,
confirmations,
time,
timereceived
} = unformattedTransactionDatum;
const preformattedTransactionDatum = {
transactionId,
amount,
numberOfConfirmations: confirmations,
timeSent: time * 1000,
timeReceived: timereceived * 1000,
};
return bluebird.delay( DELAY_BETWEEN_GETS_IN_MS ).then(
() => preformattedTransactionDatum
);
});
}).then( preformattedTransactionDatum => {
const transctionIdToTransactionData = {};
for( const {
transactionId,
amount,
numberOfConfirmations,
timeSent,
timeReceived,
} of preformattedTransactionDatum ) {
transctionIdToTransactionData[ transactionId ] = {
amount,
numberOfConfirmations,
timeSent,
timeReceived,
};
}
console.log(
'getTransactionIdToTransactionData executed succesfully, ' +
'returning transctionIdToTransactionData: ' +
JSON.stringify( transctionIdToTransactionData, null, 4 )
);
return transctionIdToTransactionData;
});
});
<file_sep>'use strict';
const {
raffle: {
raffleDrawId: {
prefix,
maxLength,
minLength
}
}
} = require( '../constants' );
module.exports = Object.freeze( ({
raffleDrawId,
}) => {
const raffleDrawIdIsValid = (
!!raffleDrawId &&
(typeof raffleDrawId === 'string') &&
raffleDrawId.startsWith( prefix ) &&
(raffleDrawId.length >= minLength) &&
(raffleDrawId.length <= maxLength)
);
return raffleDrawIdIsValid;
});
<file_sep>#!/bin/bash
echo "****🐯🐅 The Set Up Tigers 🐅🐯****"
echo "👾👾👾👾👾👾👾👾👾👾"
echo "🐯🐅🐯🐅🐯🐅"
echo "👾👾👾👾👾👾👾👾👾👾"
######################################################
######################################################
# These values need to be customized for your computer and remote Linux server
######
mode="staging" # OR "production"
pemPath="/Users/user-name/user-files/super-secret-path/linux-server-access-file.pem"
sourceRepoPath="/Users/user-name/my-code-folder/bitcoin-api"
destinationUserName="btc_lover"
destinationUrl="xxx.com"
destinationHomePath="/x"
######################################################
######################################################
### The code below is taken care of by Bitcoin-Api😁✌🕊💕🏛 ###
sourcePath="${sourceRepoPath}/1-backend"
destinationPath="${destinationHomePath}/tigerScript"
addressGeneratorPath="${sourcePath}/addressGenerator"
feeDataBotPath="${sourcePath}/feeDataBot"
withdrawsBotPath="${sourcePath}/withdrawsBot"
credentialsPath="${sourcePath}/${mode}Credentials"
depositsBotPath="${sourcePath}/depositsBot"
for tigerPath in \
$addressGeneratorPath \
$feeDataBotPath \
$withdrawsBotPath \
$depositsBotPath
do
pushd $tigerPath
rm -rf ./node_modules
popd
done
scp \
-i $pemPath \
-r \
$addressGeneratorPath \
$feeDataBotPath \
$withdrawsBotPath \
$credentialsPath \
$depositsBotPath \
"${destinationUserName}@${destinationUrl}:${destinationPath}"
echo "👾👾👾👾👾👾👾👾👾👾"
echo "🐯🐅🐯🐅🐯🐅"
echo "👾👾👾👾👾👾👾👾👾👾"
echo "****🐯🐅 The Set Up Tigers Set Up the Necessary Circumstances 🐅🐯****"
<file_sep>'use strict';
module.exports = require( '@bitcoin-api/full-stack-api-private' ).utils.stringify;
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
// import Typography from '@material-ui/core/Typography';
// import { moneyActions } from '../../../../constants';
import addBitcoinAddress from './addBitcoinAddress';
import addBitcoinFee from './addBitcoinFee';
import addBitcoinAmount from './addBitcoinAmount';
import addTime from './addTime';
import addType from './addType';
import addExchangeData from './addExchangeData';
import addGameData from './addGameData';
import addBonus from './addBonus';
const getStyles = ({
dialogMode,
}) => {
const {
backgroundColor,
} = dialogMode ? {
backgroundColor: 'black',
} : {
backgroundColor: 'beige',
};
return {
outerContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
backgroundColor,
// width: '94%',
width: 550,
maxWidth: '94%',
// height: 60,
marginTop: 10,
marginBottom: 10,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'left',
},
};
};
export default ({
moneyAction,
dialogMode,
}) => {
const styles = getStyles({
dialogMode,
});
const excitingElements = [];
addType({
excitingElements,
moneyAction,
dialogMode,
});
addBitcoinAddress({
excitingElements,
moneyAction,
dialogMode,
});
addBitcoinAmount({
excitingElements,
moneyAction,
dialogMode,
});
addBitcoinFee({
excitingElements,
moneyAction,
dialogMode,
});
addExchangeData({
excitingElements,
moneyAction,
dialogMode,
});
addGameData({
excitingElements,
moneyAction,
dialogMode,
});
addBonus({
excitingElements,
moneyAction,
dialogMode,
});
addTime({
excitingElements,
moneyAction,
dialogMode,
});
return e(
Box,
{
style: styles.outerContainer,
},
...excitingElements
);
};
<file_sep>'use strict';
const {
utils: {
stringify,
bitcoin: {
formatting: { getAmountNumber },
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
crypto: {
getCryptoAmountNumber
},
constants: {
exchanges
}
} = require( '../../../../../exchangeUtils' );
const {
errors: { ValidationError },
business: {
verifyGoogleCode,
},
constants: {
google: {
captcha
}
}
} = require( '../../../../../utils' );
// const doWithdraw = require( './doWithdraw' );
module.exports = Object.freeze( async ({
rawType,
rawData,
rawGoogleCode,
ipAddress,
}) => {
console.log(
'running validateAndGetValues with the following values:',
stringify({
rawType,
rawData,
rawGoogleCode: !!rawGoogleCode,
ipAddress,
})
);
const values = {};
if(
!rawType ||
(typeof rawType !== 'string') ||
!exchanges.types[ rawType ]
) {
const error = new ValidationError( 'invalid type provided' );
error.bulltrue = true;
throw error;
}
values.type = rawType;
if( values.type === exchanges.types.btcToCrypto ) {
if(
!rawData ||
(typeof rawData !== 'object') ||
!rawData.amountInCryptoWanted ||
(typeof rawData.amountInCryptoWanted !== 'number') ||
(rawData.amountInCryptoWanted > exchanges.bounds.crypto.max) ||
(rawData.amountInCryptoWanted < exchanges.bounds.crypto.min)
) {
const error = new ValidationError( 'invalid data provided' );
error.bulltrue = true;
throw error;
}
values.data = {
amountInCryptoWanted: getCryptoAmountNumber(
rawData.amountInCryptoWanted
)
};
}
else if( values.type === exchanges.types.cryptoToBTC ) {
if(
!rawData ||
(typeof rawData !== 'object') ||
!rawData.amountInBitcoinWanted ||
(typeof rawData.amountInBitcoinWanted !== 'number') ||
(rawData.amountInBitcoinWanted > exchanges.bounds.bitcoin.max) ||
(rawData.amountInBitcoinWanted < exchanges.bounds.bitcoin.min)
) {
const error = new ValidationError( 'invalid data provided' );
error.bulltrue = true;
throw error;
}
values.data = {
amountInBitcoinWanted: getAmountNumber(
rawData.amountInBitcoinWanted
)
};
}
await verifyGoogleCode({
rawGoogleCode,
ipAddress,
expectedAction: captcha.actions.exchange,
});
console.log(
'validateAndGetValues executed successfully - returning values: ' +
stringify( values )
);
return values;
});<file_sep>'use strict';
module.exports = Object.freeze({
doBitcoinRequest: require( './doBitcoinRequest' ),
signalOnStatusToCommandCenter: require( './signalOnStatusToCommandCenter' ),
constants: require( './constants' ),
mongo: require( './mongo' ),
runGiraffeEvolutionProcedure: require( './runGiraffeEvolutionProcedure' ),
runSpiritual: require( './runSpiritual' ),
backgroundExecutor: require( 'bqe' ),
deathFunction: require( './deathFunction' ),
getSafeWriteError: require( './getSafeWriteError' ),
});<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const validateAndGetValues = require( './validateAndGetValues' );
const runAsgardAddressMode = require( './runAsgardAddressMode' );
module.exports = Object.freeze( async ({
exchangeUserId,
rawGoogleCode,
ipAddress,
}) => {
console.log(
'🦝🦝🦝running addAddress🦝🦝🦝 ' +
`with the following values: ${ stringify({
exchangeUserId,
rawGoogleCode,
ipAddress
}) }`
);
await validateAndGetValues({
rawGoogleCode,
ipAddress,
});
await runAsgardAddressMode({
exchangeUserId,
});
const addAddressResults = {
addressPostOperationSuccessful: true,
};
console.log(
'🍕🦝🍔🦝🍱🦝addAddress executed successfully🍕🦝🍔🦝🍱🦝 ' +
`returning the following values: ${ stringify( addAddressResults ) }`
);
return addAddressResults;
});<file_sep>'use strict';
const {
utils: {
doOperationInQueue,
stringify,
// aws: {
// dinoCombos: {
// addresses: {
// reclaimAddress
// }
// },
// },
// database: {
// addresses: {
// getIfAddressShouldBeReclaimed
// }
// }
},
constants: {
aws: {
database: {
tableNames: { ADDRESSES }
}
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
javascript: { getQueueId },
} = require( '../../../../../utils' );
const addBalanceEntryAndAssignNewAddress = require( './addBalanceEntryAndAssignNewAddress' );
const getUnusedAddressDatum = require( './getUnusedAddressDatum' );
const assignAddressToUser = require( './assignAddressToUser' );
module.exports = Object.freeze( async ({
user,
}) => doOperationInQueue({
queueId: getQueueId({ type: ADDRESSES, id: user.userId }),
doOperation: async () => {
const { userId } = user;
console.log(
`running getAddressDatum ${ stringify({
userId
}) }`
);
if( !user.hasGottenAddress ) {
const newAddressDatum = await addBalanceEntryAndAssignNewAddress({
user,
});
console.log(
'getAddressDatum executed successfully ' +
`returning ${ stringify({ newAddressDatum }) }`
);
return newAddressDatum;
}
const unusedAddressDatum = await getUnusedAddressDatum({
user,
});
if( !!unusedAddressDatum ) {
console.log( 'unused address exists for user case' );
// const addressShouldBeReclaimed = getIfAddressShouldBeReclaimed({
// addressDatum: unusedAddressDatum
// });
// if( addressShouldBeReclaimed ) {
// console.log(
// 'unused address has expired! ' +
// 'Reclaiming the address.'
// );
// await reclaimAddress({
// address: unusedAddressDatum.address,
// noLocka: true,
// });
// }
// else {
console.log(
'getAddressDatum executed successfully ' +
`returning ${ stringify({ unusedAddressDatum }) }`
);
return unusedAddressDatum;
// }
}
const newAddressDatum = await assignAddressToUser({
user,
});
console.log(
'getAddressDatum executed successfully ' +
`returning ${ stringify({ newAddressDatum }) }`
);
return newAddressDatum;
}
}));<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry
}
},
doOperationInQueue,
javascript: {
getQueueId
},
stringify,
},
constants: {
aws: {
database: {
tableNames: {
USERS
}
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
accessCodeTools: { getETCData, getReturnCode }
} = require( '../../../../utils' );
module.exports = Object.freeze( async ({
user
}) => {
const { userId } = user;
console.log(
`running updateTokenValue with the following values: ${ stringify({
userId,
})}`
);
const {
encryptedTemplarCode,
megaCode,
encryptionId
} = getETCData();
await doOperationInQueue({
queueId: getQueueId({ type: USERS, id: userId }),
doOperation: async () => {
const newUserEntry = Object.assign(
{},
user,
{
accessCode: encryptedTemplarCode,
encryptionId
}
);
await updateDatabaseEntry({
tableName: USERS,
entry: newUserEntry,
});
}
});
const returnCode = getReturnCode({
userId,
megaCode
});
console.log(
`updateTokenValue executed successfully for user ${ userId }, ` +
`returning returnCode of length ${ returnCode.length }`
);
return {
returnCode
};
});
<file_sep>'use strict';
module.exports = Object.freeze({
getAmountNumber: require( './getAmountNumber' ),
});
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const roadmapItems = [
`Auto-Flip for Dragon's Talisman Bitcoin game`,
`"Dragon Fire" server updates - increase play limits!`,
`New secret financial product`,
`Multiplayer Dragon's Talisman Bitcoin game mode`,
`More fun games and tech!👾📲💻🎮🕹`
];
export default ({
color = 'white',
headerFontSize = 21,
marginTop = 37,
marginBottom = 45,
}) => {
const roadmapItemElements = roadmapItems.map( roadmapItem => {
return e(
Typography,
{
style: {
width: '85%',
color,
marginBottom: 10,
}
},
`• ${ roadmapItem }`
);
});
return e(
Box,
{
style: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
width: '100%',
maxWidth: 620,
marginTop,
marginBottom,
textAlign: 'left',
}
},
e(
Typography,
{
style: {
width: '90%',
color,
marginBottom: 10,
fontWeight: 'bold',
fontSize: headerFontSize,
}
},
'🛣Dynasty Bitcoin Project Roadmap🗺'
),
...roadmapItemElements
);
};
<file_sep>'use strict';
require( 'dotenv' ).config();
const getIfEnvValuesAreValid = require( process.env.IRELAND_ULTRA_ENV_TEST_PATH );
const { envValidationTypes } = getIfEnvValuesAreValid;
(() => {
try {
getIfEnvValuesAreValid([
{
type: envValidationTypes.string,
key: 'ENV_TEST_UNDEFINED',
undefinedAllowed: true
},
{
type: envValidationTypes.string,
key: 'ENV_TEST_STRING',
},
{
type: envValidationTypes.number,
key: 'ENV_TEST_NUMBER',
},
{
type: envValidationTypes.url,
key: 'ENV_TEST_URL',
},
{
type: envValidationTypes.string,
key: 'ENV_TEST_EXTRA_VALIDATION',
extraValidation: envValue => {
if( !envValue.includes( 'x' ) ) {
throw new Error( 'missing x' );
}
},
},
]);
}
catch( err ) {
console.log( 'an error occurred:', err );
}
})();<file_sep>'use strict';
module.exports = Object.freeze({
addresses: require( './addresses' ),
balances: require( './balances' ),
});<file_sep>import axios from 'axios';
import { apiUrl } from '../../constants';
const httpMethodToAxiosMethod = Object.freeze({
GET: 'get',
POST: 'post',
PATCH: 'patch',
DELETE: 'delete',
});
export default Object.freeze( async ({
resource,
body,
method,
headers = {},
}) => {
if( !!process.env.REACT_APP_LOGS_ON ) {
console.log(
'Make API Call: Making API Call:',
{
resource,
method,
body,
headers
}
);
}
const url = `${ apiUrl }/${ resource }`;
const axiosArgs = [ url ];
if( !!body ) {
axiosArgs.push( body );
}
const axiosOptions = {};
axiosOptions.headers = Object.assign(
{},
{
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': "*"
},
headers
);
const instance = axios.create( axiosOptions );
const axiosMethod = httpMethodToAxiosMethod[ method ];
try {
const response = await instance[ axiosMethod ]( ...axiosArgs );
const { data } = response;
if( !!process.env.REACT_APP_LOGS_ON ) {
console.log(
'Making API Call:',
{
data
}
);
}
return data;
}
catch( err ) {
const errorMessage = (
!!err &&
!!err.response &&
!!err.response.data &&
!!err.response.data.message &&
err.response.data.message
) || 'internal server error';
console.log( 'API call error:', errorMessage );
throw err;
}
});
<file_sep>import { createElement as e, useEffect } from 'react';
import CloseButton from './CloseButton';
import MainContents from './MainContents';
import { actions } from '../../../../utils';
// import { getState/*, setState*/ } from '../../reduxX';
// import { bitcoinExchange } from '../../utils';
// import LuluLemonButton from './LuluLemonButton';
import Paper from '@material-ui/core/Paper';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
width: '100%',
maxWidth: 620,
// height: '100%',
backgroundColor: 'green',
borderRadius: 4,
// marginTop: 25,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
// marginBottom: 30,
},
topBar: {
width: '83%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginTop: 16,
},
titleText: {
fontSize: 26,
color: 'white',
textAlign: 'left',
},
secondBar: {
width: '83%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
},
secondText: {
width: '100%',
textAlign: 'left',
fontSize: 16,
color: 'white',
},
};
};
export default ({
title,
titleContentsAndMore,
lastUpdatedDate,
}) => {
const styles = getStyles();
useEffect( () => {
actions.scroll();
}, [] );
return e(
Paper,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.topBar,
},
e(
Typography,
{
style: styles.titleText,
},
title
),
e( CloseButton )
),
e(
Box,
{
style: styles.secondBar,
},
e(
Typography,
{
style: styles.secondText,
},
`Last Updated: ${ lastUpdatedDate }`
)
),
e(
MainContents,
{
titleContentsAndMore,
}
)
);
};
<file_sep>'use strict';
const {
utils: {
bitcoin: {
formatting: { getAmountNumber }
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
withdraws: {
states: {
no_withdraws_are_currently_being_processed
}
},
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
module.exports = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const bitcoinWithdrawsBalanceDataFromExchangeUser = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.bitcoinWithdraws &&
exchangeUser.moneyData.bitcoinWithdraws
) || null;
const bitcoinWithdrawsBalanceData = {};
if( !bitcoinWithdrawsBalanceDataFromExchangeUser ) {
Object.assign(
bitcoinWithdrawsBalanceData,
{
totalAmount: 0,
currentState: no_withdraws_are_currently_being_processed,
}
);
}
else {
Object.assign(
bitcoinWithdrawsBalanceData,
{
totalAmount: getAmountNumber(
bitcoinWithdrawsBalanceDataFromExchangeUser.totalAmount
),
currentState: (
bitcoinWithdrawsBalanceDataFromExchangeUser.currentState
),
}
);
}
balanceData.bitcoinWithdraws = bitcoinWithdrawsBalanceData;
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase,
}
},
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
TRANSACTIONS,
},
secondaryIndices: {
exchangeUserIdCreationDateIndex,
}
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const quickSearchLimit = 100;
const normalSearchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
exchangeUserId: '#exchangeUserId',
voteId: '#voteId',
choice: '#choice',
amount: '#amount',
creationDate: '#creationDate',
voteType: '#voteType',
eventSeriesId: '#eventSeriesId',
}),
nameValues: f({
exchangeUserId: 'exchangeUserId',
voteId: 'voteId',
choice: 'choice',
amount: 'amount',
creationDate: 'creationDate',
voteType: 'voteType',
eventSeriesId: 'eventSeriesId',
}),
valueKeys: f({
exchangeUserId: ':exchangeUserId',
voteIdToConsider: ':voteIdToConsider',
}),
});
const getSearchParamsComponents = Object.freeze( ({
shouldGetEventSeriesId,
}) => {
const projectionExpressionKeys = [
attributes.nameKeys.choice,
attributes.nameKeys.amount,
attributes.nameKeys.creationDate,
attributes.nameKeys.voteType,
];
const expressionAttributeNames = {
[attributes.nameKeys.exchangeUserId]: attributes.nameValues.exchangeUserId,
[attributes.nameKeys.voteId]: attributes.nameValues.voteId,
[attributes.nameKeys.choice]: attributes.nameValues.choice,
[attributes.nameKeys.amount]: attributes.nameValues.amount,
[attributes.nameKeys.creationDate]: attributes.nameValues.creationDate,
[attributes.nameKeys.voteType]: attributes.nameValues.voteType,
};
if( shouldGetEventSeriesId ) {
projectionExpressionKeys.push( attributes.nameKeys.eventSeriesId );
expressionAttributeNames[ attributes.nameKeys.eventSeriesId ] = attributes.nameValues.eventSeriesId;
}
const projectionExpression = projectionExpressionKeys.join( ', ' );
return {
projectionExpression,
expressionAttributeNames
};
});
module.exports = Object.freeze( async ({
exchangeUserId,
voteId,
shouldGetEventSeriesId = false,
}) => {
console.log(
'running getMostRecentVoteTransaction with ' +
'the following values: ' +
stringify({
exchangeUserId,
voteId,
})
);
const {
projectionExpression,
expressionAttributeNames,
} = getSearchParamsComponents({
shouldGetEventSeriesId
});
let iterationCount = 0;
let paginationValueToUse = null;
do {
console.log(
'getMostRecentVoteTransaction - ' +
'running transactions search: ' +
stringify({
paginationValueToUse,
iterationCount,
})
);
const searchLimit = (
iterationCount > 0
) ? normalSearchLimit : quickSearchLimit;
/*
{
"amount": -0.3,
"choice": "mayweather",
"creationDate": 1600611891313,
"eventSeriesId": "test_event_series_id_2",
"exchangeUserId": "exchange_user_8266676140114f7190b0f41c48cbc767",
"lastUpdated": 1600611891701,
"transactionId": "transaction_46fc428cad324dc6a9cb9c73f0bd8428_1600611891700",
"type": "vote",
"voteId": "mmaFight",
"voteType": "doVote"
}
*/
const searchParams = {
TableName: TRANSACTIONS,
IndexName: exchangeUserIdCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: false,
ProjectionExpression: projectionExpression,
KeyConditionExpression: (
`${ attributes.nameKeys.exchangeUserId } = ${ attributes.valueKeys.exchangeUserId }`
),
FilterExpression: (
`${ attributes.nameKeys.voteId } = ${ attributes.valueKeys.voteIdToConsider }`
),
ExpressionAttributeNames: expressionAttributeNames,
ExpressionAttributeValues: {
[attributes.valueKeys.exchangeUserId]: exchangeUserId,
[attributes.valueKeys.voteIdToConsider]: voteId,
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
if( ultimateResults.length > 0 ) {
const mostRecentTransaction = ultimateResults[0];
console.log(
'getMostRecentVoteTransaction ' +
'executed successfully, got the most recent transaction: ' +
stringify( mostRecentTransaction )
);
return mostRecentTransaction;
}
if( !!paginationValue ) {
paginationValueToUse = paginationValue;
iterationCount++;
}
else if( !!paginationValueToUse ) {
paginationValueToUse = null;
}
} while( !!paginationValueToUse );
console.log(
'getMostRecentVoteTransaction ' +
'executed successfully no vote transaction found, ' +
'returning null'
);
return null;
});
<file_sep>import { createElement as e, useState } from 'react';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import makeStyles from '@material-ui/core/styles/makeStyles';
import useTheme from '@material-ui/core/styles/useTheme';
import MobileStepper from '@material-ui/core/MobileStepper';
import Button from '@material-ui/core/Button';
import Divider from '@material-ui/core/Divider';
import KeyboardArrowLeft from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';
const getStyles = () => {
return {
buttonPaper: {
borderRadius: 4,
backgroundColor: 'black',
width: 320,
// height: 320,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
},
button: {
backgroundColor: 'green',
color: 'white',
marginTop: 15,
marginBottom: 15,
width: '90%',
},
howItWorksTextSection: {
borderRadius: 4,
backgroundColor: 'black',
width: '100%',
paddingTop: 5,
// paddingBottom: 5,
},
howItWorksText: {
color: 'white',
fontSize: 20,
fontWeight: 'bold',
width: '100%',
textAlign: 'center',
},
text: {
color: 'black',
},
icon: {
fontSize: 50,
},
};
};
const tutorialSteps = [
{
label: 'Create an account with your email',
imgPath: 'https://images.unsplash.com/photo-1512341689857-198e7e2f3ca8?auto=format&fit=crop&w=400&h=250&q=60',
},
{
label: 'Deposit Bitcoin into your account',
imgPath: 'https://images.unsplash.com/photo-1512341689857-198e7e2f3ca8?auto=format&fit=crop&w=400&h=250&q=60',
},
{
label: 'Exchange your Bitcoin for Dynasty Bitcoin',
imgPath: 'https://images.unsplash.com/photo-1512341689857-198e7e2f3ca8?auto=format&fit=crop&w=400&h=250&q=60',
},
{
label: 'Play fun games using your Dynasty Bitcoin!🎮',
imgPath: 'https://images.unsplash.com/photo-1512341689857-198e7e2f3ca8?auto=format&fit=crop&w=400&h=250&q=60',
},
{
label: 'Exchange your Dynasty Bitcoin for Bitcoin and withdraw with 0 platform fees!😃 (Bitcoin network fee only)',
// label: 'tetst',
imgPath: 'https://images.unsplash.com/photo-1512341689857-198e7e2f3ca8?auto=format&fit=crop&w=400&h=250&q=60',
},
{
label: [
'Follow ',
e(
'a',
{
key: 'daLinky',
href: 'https://twitter.com/DynastyBitcoin',
target: '_blank',
style: {
color: 'lightblue',
}
},
`@DynastyBitcoin on Twitter`
),
' for exciting updates about new Bitcoin games and fun new crypto technology!👩🔬🧑🔬📈'
],
// label: 'tetst',
imgPath: 'https://images.unsplash.com/photo-1512341689857-198e7e2f3ca8?auto=format&fit=crop&w=400&h=250&q=60',
},
];
const useStyles = makeStyles((/*theme*/) => ({
root: {
width: 320,
flexGrow: 1,
// display: 'flex',
// justifyContent: 'space-between',
},
header: {
display: 'flex',
alignItems: 'center',
height: 75,
width: '100%',
// paddingLeft: theme.spacing(4),
backgroundColor: 'black',
},
headerText: {
width: '100%',
color: 'white',
textAlign: 'center',
padding: 5,
},
img: {
height: 255,
width: 320,
overflow: 'hidden',
display: 'block',
// width: '100%',
},
mobileStepper: {
// height:
borderRadius: 4,
backgroundColor: 'black',
borderColor: 'white',
color: 'white',
},
mobileStepperButton: {
// height:
backgroundColor: 'black',
color: 'white',
},
dot: {
backgroundColor: 'grey'
},
dotActive: {
backgroundColor: 'white',
}
}));
export default () => {
const styles = getStyles();
const classes = useStyles();
const theme = useTheme();
const [activeStep, setActiveStep] = useState(0);
const maxSteps = tutorialSteps.length;
const handleNext = () => {
setActiveStep((prevActiveStep) => prevActiveStep + 1);
};
const handleBack = () => {
setActiveStep((prevActiveStep) => prevActiveStep - 1);
};
return e(
Paper,
{
style: styles.buttonPaper,
elevation: 5,
},
e(
'div',
{
style: styles.howItWorksTextSection,
},
e(
Typography,
{
style: styles.howItWorksText,
},
'How It Works'
)
),
e(
Divider,
{
style: {
backgroundColor: 'white',
width: '50%',
}
}
),
// e(
// Typography,
// {
// style: styles.howItWorksText,
// },
// 'How it Works'
// ),
// e(
// PersonAddIcon,
// {
// style: styles.icon,
// }
// ),
// e(
// Typography,
// {
// style: styles.text,
// },
// 'Login using your email'
// )
e(
'div',
{
className: classes.root,
},
e(
'div',
{
className: classes.header,
// square: true,
elevation: 0,
},
e(
Typography,
{
className: classes.headerText,
},
tutorialSteps[activeStep].label
)
),
// e(
// 'img',
// {
// className: classes.img,
// src: tutorialSteps[activeStep].imgPath,
// alt: tutorialSteps[activeStep].label,
// }
// ),
e(
MobileStepper,
{
// className: ,
classes: {
root: classes.mobileStepper, // class name, e.g. `classes-nesting-root-x`
dot: classes.dot, // class name, e.g. `classes-nesting-label-x`
dotActive: classes.dotActive,
},
height: 32,
steps: maxSteps,
position: 'static',
variant: 'dots',
// variant: 'text',
activeStep,
nextButton: e(
Button,
{
className: classes.mobileStepperButton,
size: 'small',
onClick: handleNext,
disabled: (activeStep === maxSteps - 1)
},
'Next',
(theme.direction === 'rtl') ? e( KeyboardArrowLeft ) : e( KeyboardArrowRight ),
),
backButton: e(
Button,
{
className: classes.mobileStepperButton,
size: 'small',
onClick: handleBack,
disabled: (activeStep === 0)
},
'Back',
(theme.direction === 'rtl') ? e( KeyboardArrowRight ) : e( KeyboardArrowRight ),
),
}
)
)
);
};
<file_sep>import { createElement as e } from 'react';
// import { getState, setState } from '../../reduxX';
// import { story } from '../../constants';
import {
usefulComponents,
// POWBlock,
} from '../../TheSource';
import Box from '@material-ui/core/Box';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
// backgroundColor: 'beige',
width: '100%',
// backgroundColor: 'pink',
maxWidth: 620,
// height: 300,
marginTop: 20,
marginBottom: 20,
// borderRadius: '50%',
// backgroundColor: 'pink',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'left',
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
usefulComponents.crypto.CurrentAmount,
{
backgroundColor: 'beige',
crypto: true,
width: 160,
// maxWidth = undefined,
// fontWeight = 'bold',
// height = 100,
// color = 'black',
// textVersion = 'a',
// borderRadius = 4,
// freeGameMode,
}
)
);
};
<file_sep>'use strict';
const doRedisRequest = require( 'do-redis-request' );
const streams = require( '@bitcoin-api/redis-streams-utils' );
const THE_QUEUE_NAME = 'Q';
const TIMEOUT = 10000;
const OPERATION_TIMEOUT = 20000;
const PAGINATION_COUNT = 5000;
const MAX_STREAM_LENGTH = 700000;
const START = 'start';
const END = 'end';
const getOperationTime = streams.getOperationTime;
// const getOperationTimeKey = streams.getOperationTimeKey;
const getIncrementedTimeKeyData = streams.getIncrementedTimeKeyData;
const xRangeWithPagination = Object.freeze( async ({
redisClient,
startTime,
endTime,
}) => {
return await streams.xRangeWithPagination({
redisClient,
startTime,
endTime,
queueName: THE_QUEUE_NAME,
paginationCount: PAGINATION_COUNT
});
});
const getKeyValues = Object.freeze(
({ keyValueList }) => streams.getKeyValues({
keyValueList,
numberKeys: [ 'timeout', 'operationTimeout' ],
})
);
const getRedisXAddArguments = Object.freeze( ({
queueId,
operationId,
state,
timeout,
operationTimeout,
errorMessage,
}) => {
const xAddArguments = [
THE_QUEUE_NAME,
'MAXLEN',
'~',
MAX_STREAM_LENGTH,
'*',
'queueId',
queueId,
'operationId',
operationId,
'state',
state
];
if( !!timeout ) {
xAddArguments.push( 'timeout', timeout );
}
if( !!operationTimeout ) {
xAddArguments.push( 'operationTimeout', operationTimeout );
}
if( !!errorMessage ) {
xAddArguments.push( 'errorMessage', errorMessage.substring( 500 ) );
}
return xAddArguments;
});
const obliterateOperationFromQueue = Object.freeze( async ({
queueId,
operationId,
redisClient,
errorMessage
}) => {
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`running obliterateOperationFromQueue - ${ JSON.stringify({
errorMessage
}, null, 4 )
}`
);
const thisRequestTimeKey = await doRedisRequest({
client: redisClient,
command: 'xadd',
redisArguments: getRedisXAddArguments({
queueId,
operationId,
state: END,
errorMessage
}),
});
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`obliterateOperationFromQueue success`
);
return thisRequestTimeKey;
});
const delay = Object.freeze(
timeout => new Promise( resolve => setTimeout( resolve, timeout ) )
);
module.exports = Object.freeze({
getKeyValues,
getRedisXAddArguments,
obliterateOperationFromQueue,
getOperationTime,
delay,
xRangeWithPagination,
getIncrementedTimeKeyData,
constants: Object.freeze({
START,
END,
THE_QUEUE_NAME,
TIMEOUT,
OPERATION_TIMEOUT
}),
});<file_sep>'use strict';
const {
utils: {
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
aws: {
ses: {
sendEmail
}
},
constants: {
urls: {
exchangeUrl,
}
},
} = require( '../../../../../../../exchangeUtils' );
const {
validation: {
getIfEmailIsValid
}
} = require( '../../../../../../../utils' );
const getEmailHtml = require( './getEmailHtml' );
module.exports = Object.freeze( async ({
email,
displayEmail,
passwordResetCode,
}) => {
console.log(
`running sendPasswordResetEmail
with the following values - ${
stringify({
email,
displayEmail,
passwordResetCode,
})
}`
);
if( !exchangeUrl ) {
throw new Error(
'🤖set up error: missing exchangeUrl ' +
'This error was thrown in ' +
`"${ __dirname }" "${ __filename }".`
);
}
const passwordResetCodeLink = (
`${ exchangeUrl }/` +
'mode/password_reset/' +
`password_reset_code/${ passwordResetCode }/` +
`email/${ displayEmail }`
);
console.log(
'🦒here is the password reset code link: ' +
passwordResetCodeLink
);
const html = getEmailHtml({
passwordResetCodeLink,
appName: process.env.EXCHANGE_APP_NAME,
});
const text = (
'Your password reset link is ' +
`"${ passwordResetCodeLink }".`
);
const fromEmailAddress = process.env.EXCHANGE_MANAGEMENT_EMAIL;
if( !getIfEmailIsValid({ email: fromEmailAddress }) ) {
throw new Error(
'🤖set up error: missing environment variable ' +
'"EXCHANGE_MANAGEMENT_EMAIL". This error was thrown in ' +
`"${ __dirname }" "${ __filename }".`
);
}
const {
emailMessageId,
} = await sendEmail({
subject: 'Password Reset',
html,
text,
toEmailAddress: displayEmail,
fromEmailAddress,
});
const sendPasswordResetEmailResults = {
emailMessageId,
};
console.log(
'sendPasswordResetEmail executed successfully - ' +
`results: ${
stringify( sendPasswordResetEmailResults )
}`
);
});
<file_sep>import { browser, validation } from '../utils';
import { setState } from '../reduxX';
import { pathValues, story } from '../constants';
export default () => {
const url = window.location.href;
const formattedPathName = (
browser.getParsedUrl( url ).pathname.substring( 1 )
);
if( !formattedPathName ) {
return;
}
const splitPath = formattedPathName.split( '/' );
if( splitPath[ splitPath.length - 1 ] === '' ) {
splitPath.pop();
}
if( splitPath[0] === pathValues.mode ) {
if(
(splitPath[1] === pathValues.account_verification) &&
(splitPath.length === 6) &&
(splitPath[2] === pathValues.verification_code) &&
(
(splitPath[3].length > 5) &&
(splitPath[3].length < 500)
) &&
(splitPath[4] === pathValues.email) &&
validation.isValidEmail( splitPath[5] )
) {
window.history.replaceState(
{
key: 'exchange'
},
document.title,
'/'
);
const verificationCode = splitPath[3];
const email = decodeURIComponent( splitPath[5] );
setState(
{
keys: [ 'verifyEmailPolygon', 'emailInput' ],
value: email,
},
{
keys: [ 'verifyEmailPolygon', 'verifyEmailCodeInput' ],
value: verificationCode,
},
{
keys: [ 'notLoggedInMode', 'mainMode' ],
value: story.NotLoggedInMode.mainModes.verifyUserMode
}
);
} else if(
(splitPath[1] === pathValues.password_reset) &&
(splitPath.length === 6) &&
(splitPath[2] === pathValues.password_reset_code) &&
validation.isValidPasswordResetCode({
passwordResetCode: splitPath[3],
}).isValid &&
(splitPath[4] === pathValues.email) &&
validation.isValidEmail( splitPath[5] )
) {
window.history.replaceState(
{
key: 'exchange'
},
document.title,
'/'
);
const passwordResetCode = splitPath[3];
const email = decodeURIComponent( splitPath[5] );
setState(
{
keys: [ 'notLoggedInMode', 'passwordReset', 'email' ],
value: email,
},
{
keys: [ 'notLoggedInMode', 'passwordReset', 'passwordResetCode' ],
value: passwordResetCode,
},
{
keys: [ 'notLoggedInMode', 'mainMode' ],
value: story.NotLoggedInMode.mainModes.passwordResetMode,
}
);
}
}
};<file_sep>'use strict';
const {
constants: {
redis: {
streamIds
},
deploy: {
eventNames
}
},
utils: {
redis: {
doRedisFunction,
doRedisRequest,
rhinoCombos: {
giraffeAndTreeStatusUpdate
},
streams,
},
stringify,
javascript: {
jsonEncoder
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const getGetIfTigerShouldHideResults = Object.freeze(({
tigerShouldHide = false,
deployCommand = null,
deployId = null,
eventOrder = null,
} = {
tigerShouldHide: false,
deployCommand: null,
deployId: null,
eventOrder: null,
}) => ({
tigerShouldHide,
deployCommand,
deployId,
eventOrder,
}));
const getIfTigerShouldHide = Object.freeze( async ({
serviceName
}) => doRedisFunction({
performFunction: async ({
redisClient
}) => {
console.log(
'🐅🏞running getIfTigerShouldHide - ' +
stringify({
serviceName
})
);
const readStartTime = Date.now() - (5 * 60 * 1000);
const deployEventRawDataResults = await doRedisRequest({
client: redisClient,
command: 'xread',
redisArguments: [
'STREAMS',
streamIds.zarbonDeploy,
readStartTime
],
});
const deployEventRawData = (
!!deployEventRawDataResults &&
!!deployEventRawDataResults[0] &&
!!deployEventRawDataResults[0][1] &&
deployEventRawDataResults[0][1]
) || [];
const theLastDeployEventRawData = deployEventRawData[
deployEventRawData.length - 1
] || null;
if( !theLastDeployEventRawData ) {
console.log(
'🐅🏞getIfTigerShouldHide - executed successfully - ' +
'no deploy event data (no-op)'
);
return getGetIfTigerShouldHideResults();
}
const theLastDeployEventData = {
timeKey: theLastDeployEventRawData[0],
keyValues: streams.getKeyValues({
keyValueList: theLastDeployEventRawData[1],
}),
};
const {
// timeKey,
keyValues,
} = theLastDeployEventData;
const eventName = keyValues.eventName;
const information = jsonEncoder.decodeJson(
keyValues.information
);
const eventOrder = Number( information.eventOrder );
if(
(eventName === eventNames.leaf.tigerCommand) &&
(information.deployCommand === serviceName) &&
!Number.isNaN( eventOrder ) &&
!!information.deployId &&
!information.forceDeploy
) {
const values = {
tigerShouldHide: true,
deployId: information.deployId,
deployCommand: information.deployCommand,
eventOrder,
};
console.log(
'🐅🏞getIfTigerShouldHide - executed successfully - ' +
`the tiger should hide - ${ stringify( values ) }`
);
return getGetIfTigerShouldHideResults( values );
}
console.log(
'🐅🏞getIfTigerShouldHide - executed successfully - ' +
'no relevant deploy event data (no-op)'
);
return getGetIfTigerShouldHideResults();
},
functionName: (
'seeing if tiger should hide for improvement based on ' +
'spiritual enlightenment'
)
}));
module.exports = Object.freeze( async ({
serviceName,
}) => {
console.log(
'🦒💁♀️running runGiraffeEvolutionProcedure: ' +
stringify({ serviceName })
);
const {
tigerShouldHide,
deployCommand,
deployId,
eventOrder
} = await getIfTigerShouldHide({
serviceName
});
if( !tigerShouldHide ) {
console.log(
'🦒💁♀️runGiraffeEvolutionProcedure executed successfully - ' +
'tiger does not need to hide'
);
return;
}
console.log(
'🦒💁♀️runGiraffeEvolutionProcedure - ' +
'enlightening the tiger💡🐅'
);
await doRedisFunction({
performFunction: ({
redisClient
}) => giraffeAndTreeStatusUpdate({
redisClient,
eventName: eventNames.tiger.tigerEnlightenment,
information: {
deployId,
deployCommand,
eventOrder: eventOrder + 1,
}
}),
functionName: (
'informing everyone of the tiger wave of consciousness'
),
});
console.log(
'🦒💁♀️runGiraffeEvolutionProcedure executed successfully - ' +
'tiger will be hidden for enlightenment'
);
await new Promise( () => {
setInterval( () => {
console.log( 'The unknown zone👾' );
}, 3 * 60 * 1000 );
});
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry,
}
},
javascript: {
getQueueId
},
doOperationInQueue,
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_EMAIL_DELIVERY_RESULTS
}
}
}
},
} = require( '@bitcoin-api/full-stack-exchange-private' );
const addEEDR = Object.freeze( async ({
email,
type,
data,
}) => {
await doOperationInQueue({
queueId: getQueueId({
type: EXCHANGE_EMAIL_DELIVERY_RESULTS,
id: email,
}),
doOperation: async () => {
const eedr = Object.assign(
{
email,
type,
creationDate: Date.now(),
},
data
);
await updateDatabaseEntry({
tableName: EXCHANGE_EMAIL_DELIVERY_RESULTS,
entry: eedr,
});
}
});
});
module.exports = Object.freeze( async ({
emailAddresses,
type,
data,
}) => {
console.log(
'running addEEDRToDatabase with the following ' +
'values: ' +
stringify({
emailAddresses,
type,
data,
})
);
for( const email of emailAddresses ) {
await addEEDR({
email,
type,
data,
});
}
console.log(
'addEEDRToDatabase executed successfully'
);
});
<file_sep>'use strict';
const emailRegex = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
module.exports = Object.freeze( ({
email,
}) => {
if( !email || (typeof email !== 'string') ) {
return false;
}
const emailIsValid = !!email.match( emailRegex );
return emailIsValid;
});<file_sep>export { default as hideGrecaptcha } from './hideGrecaptcha';
export { default as showGrecaptcha } from './showGrecaptcha';
export { default as safeGetGoogleCode } from './safeGetGoogleCode';<file_sep>'use strict';
const {
utils: {
stringify,
redis: {
doRedisFunction,
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
giraffeAndTreeStatusUpdate,
constants: {
deployCommands,
eventNames,
}
} = require( '@bitcoin-api/giraffe-utils' );
const stopPmTiger = require( './stopPmTiger' );
const deleteTrueTigerPath = require( './deleteTrueTigerPath' );
const copyAndPasteToTrueTiger = require( './copyAndPasteToTrueTiger' );
const installNodeModules = require( './installNodeModules' );
const startPmTiger = require( './startPmTiger' );
const performTigerEnlightenmentSpecialFunction = require( './performTigerEnlightenmentSpecialFunction' );
const treeTigerHome = process.env.TREE_TIGER_HOME;
const log = Object.freeze( ( ...args ) => {
console.log( '🐯🔦handleTigerEnlightenment - ', ...args );
});
const f = Object.freeze;
const deployCommandToTigerSpotData = f({
[deployCommands.feeDataBot]: f({
tigerFolder: 'feeDataBot',
mainFileName: 'UpdateFeeDataWorker.js',
}),
[deployCommands.withdrawsBot]: f({
tigerFolder: 'withdrawsBot',
mainFileName: 'WithdrawMoneyDoer.js',
}),
[deployCommands.depositsBot]: f({
tigerFolder: 'depositsBot',
mainFileName: 'UpdateDepositData.js',
}),
});
module.exports = Object.freeze( async ({
information: {
deployId,
deployCommand,
}
}) => {
log( `running handleTigerEnlightenment - ${ stringify({
deployCommand
})}` );
const {
tigerFolder,
mainFileName
} = deployCommandToTigerSpotData[ deployCommand ];
const tempTigerPath = `${ treeTigerHome }/tempTigerScript/${ tigerFolder }`;
const trueTigerLobby = `${ treeTigerHome }/tigerScript`;
const trueTigerPath = `${ trueTigerLobby }/${ tigerFolder }`;
log( 'pm2 stopping then starting:', stringify({
tempTigerPath,
trueTigerPath,
mainFileName
}) );
await stopPmTiger({
log,
trueTigerPath,
mainFileName
});
await deleteTrueTigerPath({
log,
trueTigerPath,
});
await copyAndPasteToTrueTiger({
log,
tempTigerPath,
trueTigerLobby,
});
await installNodeModules({
log,
trueTigerPath,
});
await performTigerEnlightenmentSpecialFunction({
log,
deployCommand,
});
await startPmTiger({
log,
trueTigerPath,
mainFileName
});
const aMessage = eventNames.leaf.serviceIsGood;
log(
'successfully stopped and started the ' +
'further enlightened tiger🌊🐅 ' +
`now creating a message ${ aMessage } for everyone💌`
);
await doRedisFunction({
performFunction: ({
redisClient
}) => giraffeAndTreeStatusUpdate({
redisClient,
eventName: aMessage,
information: {
deployId,
eventOrder: 5,
deployCommand,
}
}),
functionName: '🌲tree engages with summoned tiger telepathically🐅'
});
log(
`successfully sent message ${ aMessage } for everyone💌`
);
log( '🐅💁♀️handleTigerEnlightenment executed successfully' );
});
<file_sep>'use strict';
const yargs = require( 'yargs' );
require( 'dotenv' ).config();
const isCanadaProductionMode = yargs.argv.mode === 'canada';
if( isCanadaProductionMode ) {
process.env.BITCOIN_API_ENV = 'production';
}
else {
process.env.BITCOIN_API_ENV = 'staging';
}
const getRedisUrl = () => {
if( isCanadaProductionMode ) {
const redisUrl = process.env.CANADA_REDIS_URL;
process.env.REDIS_URL = redisUrl;
return redisUrl;
}
else if( yargs.argv.mode === 'ireland' ) {
const redisUrl = process.env.IRELAND_REDIS_URL;
process.env.REDIS_URL = redisUrl;
return redisUrl;
}
throw new Error( 'invalid mode' );
};
const redisUrl = getRedisUrl();
const {
utils: {
redis: {
doRedisRequest,
getClient,
}
},
} = require( 'api' );
const getIsArgumentValid = argument => (
!!argument ||
(argument === 0) ||
(argument === '0')
);
(async () => {
const client = getClient({
url: redisUrl
});
try {
const {
command,
a,
b,
c,
d,
e
} = yargs.argv;
const redisArguments = [];
if( getIsArgumentValid( a ) ) {
redisArguments.push( a );
if( getIsArgumentValid( b ) ) {
redisArguments.push( b );
if( getIsArgumentValid( c ) ) {
redisArguments.push( c );
if( getIsArgumentValid( d ) ) {
redisArguments.push( d );
if( getIsArgumentValid( e ) ) {
redisArguments.push( e );
}
}
}
}
}
const results = await doRedisRequest({
client,
command: command,
redisArguments
});
console.log(`
Redis Results: ${ JSON.stringify( {
results,
}, null, 4 ) }
`);
}
catch( err ) {
console.log(`
DO COMMAND ERROR: ${ err }
`);
}
client.quit();
})();<file_sep>#!/usr/bin/env node
'use strict';
const argv = require( 'yargs' ).argv;
if( argv.mode === 'production' ) {
require( 'dotenv' ).config({
path: `${ __dirname }/../../productionCredentials/giraffe/.env`
});
}
else {
require( 'dotenv' ).config({
path: `${ __dirname }/../../stagingCredentials/giraffe/.env`
});
}
const giraffeDeploy = require( './giraffeDeploy' );
giraffeDeploy();
/*
MAKE GIRAFFE UTILS NPM
------
LINUX SCRIPT
* setup folder structure for temp tigers (temp tiger path TTP)
1. G: create lick file
2. G: send lick file
3. L: receives lick file
4. G: send tigers to TTP
4/5. L/T: send telepathy to tiger to enlighten (or enlighen by force)
6: L: cancel pm2, delete TP, copy TTP to TP, npm i, run special function, pm2 start, send serviceIsGood
*/<file_sep>'use strict';
module.exports = Object.freeze({
getIfTransactionIdIsValid: require( './getIfTransactionIdIsValid' ),
getIfExchangeUserIdIsValid: require( './getIfExchangeUserIdIsValid' ),
});
<file_sep>import { createElement as e, useEffect } from 'react';
import {
setState
} from '../../reduxX';
import { actions } from '../../utils';
import { story, pages } from '../../constants';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import HelpOutlineIcon from '@material-ui/icons/HelpOutline';
import BlurLinearIcon from '@material-ui/icons/BlurLinear';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
emptyBox: {
width: 49,
height: 49,
},
helpIcon: {
color: 'white',
fontSize: 25,
},
titleBox: {
width: '100%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
// justifyContent: 's',
alignItems: 'center',
},
titleTextBox: {
// width: '100%',
// backgroundColor: 'beige',
backgroundColor: 'black',
color: 'white',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
titleText: {
paddingTop: 10,
// paddingBottom: 10,
// color: 'black',
color: 'white',
fontSize: 20,
// fontWeight: 'bold',
textAlign: 'center',
// padding: 15,
},
subtitleText: {
// backgroundColor: 'white',
color: 'white',
// color: 'black',
borderRadius: 6,
borderWidth: 1,
borderColor: 'white',
borderStyle: 'solid',
// fontWeight: 'bold',
fontSize: 16,
textAlign: 'center',
marginTop: 9,
paddingTop: 2,
paddingBottom: 2,
paddingRight: 5,
paddingLeft: 5
},
};
};
export default ({
noDinoCoin,
setNoDinoCoin
}) => {
useEffect( () => {
actions.scroll();
actions.setLastVisitedPage({
loggedInMode: true,
page: pages.loggedInMode.coinFlip,
});
}, [] );
const styles = getStyles();
const subtitleText = 'Coin Toss Game';
return e(
Box,
{
style: styles.titleBox,
},
e(
IconButton,
{
onClick: () => {
setNoDinoCoin( !noDinoCoin );
},
},
e(
BlurLinearIcon,
{
style: styles.helpIcon,
}
)
),
e(
Box,
{
style: styles.titleTextBox
},
e(
Typography,
{
style: styles.titleText,
variant: 'h1',
},
`The Dragon's Talisman`
),
e(
Typography,
{
style: styles.subtitleText,
variant: 'h2',
},
subtitleText
)
),
e(
IconButton,
{
onClick: () => {
setState(
[
'dialogMode'
],
story.dialogModes.games.aboutCoinFlip
);
},
},
e(
HelpOutlineIcon,
{
style: styles.helpIcon,
}
)
)
);
};
<file_sep>'use strict';
const {
utils: {
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const getDragonDirective = Object.freeze( ({
user
}) => {
if(
!!user.metadata.isHumanInformation &&
!!user.metadata.isHumanInformation.humanIpAddress &&
!!user.metadata.isHumanInformation.humanScore &&
!!user.metadata.isHumanInformation.isHuman &&
!!user.metadata.isHumanInformation.timeOfHumanProof &&
!!user.metadata.privacyPolicy &&
!!user.metadata.privacyPolicy.agrees &&
!!user.metadata.privacyPolicy.ipAddressOfAgreement &&
!!user.metadata.privacyPolicy.timeOfAgreement &&
!!user.metadata.tos &&
!!user.metadata.tos.agrees &&
!!user.metadata.tos.ipAddressOfAgreement &&
!!user.metadata.tos.timeOfAgreement
) {
return 2;
}
return 1;
});
module.exports = Object.freeze( ({
user
}) => {
console.log(
'running 🔥🦖getDragonDirective🐊🔥 - ' +
'🐉🐲Getting the dragon directive for the following user: ' +
stringify({
user,
})
);
const dragonDirective = getDragonDirective({
user
});
console.log(
'🔥🦖getDragonDirective🐊🔥 executed successfully for ' +
`user ${ user.userId } - ` +
`this user has 🎇🐉🐲dragon directive🐲🐉🎇 ` +
`${ dragonDirective }.`
);
return dragonDirective;
});
<file_sep>'use strict';
module.exports = Object.freeze( ({
loginToken,
ipAddress,
otherKeyValues = {}
}) => {
const signedOutLoginToken = Object.assign(
{},
loginToken,
otherKeyValues,
{
signedOut: true,
signedOutIpAddress: ipAddress,
signedOutTime: Date.now(),
}
);
return signedOutLoginToken;
});
<file_sep>import { getState, setState, resetReduxX } from '../../reduxX';
import bitcoinExchangeInstance from '../bitcoinExchangeInstance';
export default async () => {
const loginToken = getState( 'auth', 'loginToken' );
const userId = getState( 'auth', 'userId' );
if(
!!loginToken &&
!!userId
) {
setState( 'isLoading', true );
try {
await bitcoinExchangeInstance.signOut({
userId,
loginToken
});
}
catch( err ) {
console.log( 'error in signing out:', err );
// return;
}
}
resetReduxX();
localStorage.clear();
};
<file_sep>import { google } from '../../constants';
import delay from '../delay';
const timeBetweenTries = 50;
const maxNumberOfTries = 40;
const hideGrecaptcha = async ({
iterationCount = 0,
shouldOnlyTryOnce = false
} = {
iterationCount: 0,
shouldOnlyTryOnce: false
}) => {
const captcha = document.getElementsByClassName(
google.grecapcha.badgeClassName
)[0];
if(
!!captcha &&
(captcha.style.visibility !== 'hidden')
) {
captcha.style.visibility = 'hidden';
return;
}
else if(
shouldOnlyTryOnce ||
(iterationCount > maxNumberOfTries)
) {
return;
}
await delay({ timeout: timeBetweenTries });
return await hideGrecaptcha({
iterationCount: iterationCount + 1,
});
};
export default hideGrecaptcha;<file_sep>'use strict';
const uuidv4 = require( 'uuid/v4' );
const {
verificationCode: {
expiryTime
}
} = require( '../../constants' );
module.exports = Object.freeze( ({
baseId,
expiryDate = (Date.now() + expiryTime),
}) => {
return (
`${ baseId }_${ expiryDate }_${ uuidv4().split( '-' ).join( '' ) }`
);
});<file_sep>import { createElement as e } from 'react';
import { setState/*, getState*/ } from '../../../../reduxX';
import { story } from '../../../../constants';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
const getStyles = () => {
return {
buttonPaper: {
borderRadius: 4,
backgroundColor: 'beige',
width: 300,
// height: 100,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
// marginBottom: 30,
},
buttonTop: {
backgroundColor: 'black',
color: 'white',
marginTop: 25,
marginBottom: 20,
width: '90%',
},
buttonBottom: {
backgroundColor: 'black',
color: 'white',
marginTop: 30,
marginBottom: 15,
width: '90%',
},
};
};
export default () => {
const styles = getStyles();
return e(
Paper,
{
style: styles.buttonPaper,
elevation: 5,
},
e(
Button,
{
onClick: () => {
setState(
['notLoggedInMode', 'mainMode' ],
story.NotLoggedInMode.mainModes.signUpMode
);
},
variant: 'contained',
style: styles.buttonTop,
},
'Create New Account'
),
e(
Button,
{
onClick: () => {
setState(
['notLoggedInMode', 'mainMode' ],
story.NotLoggedInMode.mainModes.loginMode
);
},
variant: 'contained',
style: styles.buttonBottom,
},
'Login to Existing Account'
)
);
};
<file_sep>'use strict';
const {
constants: {
environment: {
isProductionMode
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const execa = require( 'execa' );
const treeTigerSpot = `${ process.env.TREE_TIGER_HOME }/tigerScript`;
module.exports = Object.freeze( async ({
log,
}) => {
log( 'running depositsBotSpecialTigerFunction' );
const localDatabaseCacheCleanScriptPath = (
`${ treeTigerSpot }/depositsBot/scripts`
);
log(
'cleaning local cache databases at using script at path ' +
`"${ localDatabaseCacheCleanScriptPath }"`
);
const commandArgs = [
'cleanTheLocalDinoCache.js'
];
if( isProductionMode ) {
commandArgs.push(
'--mode=production'
);
}
else {
commandArgs.push(
'--mode=staging'
);
}
const execaInstance = execa(
'node',
commandArgs,
{
cwd: localDatabaseCacheCleanScriptPath
}
);
execaInstance.stdout.pipe(process.stdout);
execaInstance.stderr.pipe(process.stderr);
await execaInstance;
log(
'depositsBotSpecialTigerFunction executed successfully - ' +
'cache database successfully cleaned'
);
});
<file_sep>'use strict';
const {
utils: {
business: { getBalance }
},
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze({
getBalance,
getIfApiIsActive: require( './getIfApiIsActive' ),
getIfApiIsOnData: require( './getIfApiIsOnData' ),
verifyGoogleCode: require( './verifyGoogleCode' ),
});
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const execa = require( 'execa' );
module.exports = Object.freeze( async ({
log,
trueTigerPath,
}) => {
log(
'🔽⏬running installNodeModules - ' +
stringify({
trueTigerPath
})
);
await execa(
'npm',
[
'install',
'--only=prod'
],
{
cwd: trueTigerPath
}
);
log( '🔽⏬installNodeModules executed successfully' );
});
<file_sep>import { createElement as e } from 'react';
// import { getState } from '../../../../reduxX';
import AmountInput from './AmountInput';
import FullWithdrawSelect from './FullWithdrawSelect';
import TotalWithdrawAmount from './TotalWithdrawAmount';
import Box from '@material-ui/core/Box';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
width: '100%',
// backgroundColor: mainStyleObject.backgroundColor,
backgroundColor: 'beige',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer
},
e( AmountInput ),
e( FullWithdrawSelect ),
e( TotalWithdrawAmount )
);
};
<file_sep>export { default as DestinyRaffleTitle } from './DestinyRaffleTitle';<file_sep>'use strict';
const {
utils: {
// stringify,
bitcoin: {
formatting: { getAmountNumber }
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const getCryptoAmountNumber = require( '../../crypto/getCryptoAmountNumber' );
module.exports = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const exchangeBalanceDataFromExchangeUser = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.exchange &&
exchangeUser.moneyData.exchange
) || null;
const exchangeBalanceData = {};
if( !exchangeBalanceDataFromExchangeUser ) {
Object.assign(
exchangeBalanceData,
{
bitcoin: {
totalAmount: 0,
},
crypto: {
totalAmount: 0,
},
}
);
}
else {
Object.assign(
exchangeBalanceData,
{
bitcoin: {
totalAmount: getAmountNumber(
!!exchangeBalanceDataFromExchangeUser.bitcoin &&
!!exchangeBalanceDataFromExchangeUser.bitcoin.amount &&
exchangeBalanceDataFromExchangeUser.bitcoin.amount
) || 0,
},
crypto: {
totalAmount: getCryptoAmountNumber(
!!exchangeBalanceDataFromExchangeUser.crypto &&
!!exchangeBalanceDataFromExchangeUser.crypto.amount &&
exchangeBalanceDataFromExchangeUser.crypto.amount
) || 0,
},
}
);
}
balanceData.exchange = exchangeBalanceData;
});
<file_sep>import { delay } from '../../utils';
import ensureGoogleCaptchaIsInCorrectState from './ensureGoogleCaptchaIsInCorrectState';
import chronicJackpotDataRefresh from './chronicJackpotDataRefresh';
const runFunctionForever = ({
functionToRun,
retryTime = 3000,
}) => new Promise( async ( /*resolve, reject */ ) => {
const runFunctionRecursion = async () => {
try {
await functionToRun();
}
catch( err ) {
console.log( 'error in chronic task:', err );
}
await delay({ timeout: retryTime });
runFunctionRecursion();
};
runFunctionRecursion();
});
const runChronicTasks = async () => {
const chronicTasks = [
runFunctionForever({
retryTime: 500,
functionToRun: async () => {
await ensureGoogleCaptchaIsInCorrectState();
},
}),
runFunctionForever({
retryTime: 15000,
// retryTime: 6000,
functionToRun: async () => {
await chronicJackpotDataRefresh();
},
})
];
try {
await Promise.all( chronicTasks );
}
catch( err ) {
console.log( 'error in running chronic tasks:', err );
}
};
export default runChronicTasks;
<file_sep>'use strict';
// const argv = require( 'yargs' ).argv;
const {
utils: {
stringify,
},
// constants: {
// aws: { database: { tableNames: { BALANCES, WITHDRAWS } } }
// }
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser
}
}
},
constants: {
transactions: {
types: {
identity
}
},
identityTransactions: {
types: {
refresh
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
module.exports = Object.freeze( async ({
ultimateResult,
}) => {
const { exchangeUserId } = ultimateResult;
console.log(
'running refreshExistingAtaeue with the following values:',
stringify({ exchangeUserId })
);
await addTransactionAndUpdateExchangeUser({
exchangeUserId,
type: identity,
data: {
identityType: refresh,
}
});
console.log(
'refreshExistingAtaeue executed successfully for:',
stringify({ exchangeUserId })
);
});
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const getCurrentRafflePotAmountData = require( './getCurrentRafflePotAmountData' );
const updateRafflePot = require( './updateRafflePot' );
module.exports = Object.freeze( async ({
putTicketEvent
}) => {
console.log(
'running doManagePutTicketEvent with the following values: ' +
stringify({
putTicketEvent
})
);
const { currentRafflePotAmount } = await getCurrentRafflePotAmountData({
putTicketEvent
});
await updateRafflePot({
currentRafflePotAmount,
raffleId: putTicketEvent.raffleId,
});
console.log( 'doManagePutTicketEvent executed successfully' );
});
<file_sep>'use strict';
module.exports = Object.freeze({
redis: require( './redis' ),
doOperationInQueue: require( './doOperationInQueue' ),
stringify: require( './stringify' ),
business: require( './business' ),
database: require( './database' ),
javascript: require( './javascript' ),
aws: require( './aws' ),
bitcoin: require( './bitcoin' ),
server: require( './server' ),
delay: require( './delay' ),
validation: require( './validation' ),
});
<file_sep>'use strict';
const {
backgroundExecutor
} = require( '@bitcoin-api/full-stack-backend-private' );
module.exports = Object.freeze({
backgroundExecutor,
getFeeEstimateAmount: require( './getFeeEstimateAmount' ),
});<file_sep>'use strict';
const {
utils: {
delay
}
} = require( '@bitcoin-api/full-stack-api-private' );
const getSafeWriteError = require( './getSafeWriteError' );
const signalOnStatusToCommandCenter = require( './signalOnStatusToCommandCenter' );
const runGiraffeEvolutionProcedure = require( './runGiraffeEvolutionProcedure' );
module.exports = Object.freeze(({
serviceName,
spiritual,
retryTimeInSeconds = 10,
}) => new Promise( async ( resolve, reject ) => {
const safeWriteError = getSafeWriteError({ moduleName: serviceName });
const retryTime = retryTimeInSeconds * 1000;
const runFunctionRecursion = async () => {
try {
await spiritual();
await signalOnStatusToCommandCenter({
serviceName,
});
await runGiraffeEvolutionProcedure({
serviceName,
});
}
catch( err ) {
safeWriteError( err );
return reject( err );
}
console.log(
'running ☢️🐑⚡️spirit function again in ' +
`${ retryTimeInSeconds } seconds`
);
await delay( retryTime );
runFunctionRecursion();
};
runFunctionRecursion();
}));<file_sep>'use strict';
const fullStackApi = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
stringify,
},
} = fullStackApi;
const fullStackExchange = require(
'@bitcoin-api/full-stack-exchange-private'
);
const transactionTypes = fullStackExchange.constants.transactions.types;
const exchangeTypes = fullStackExchange.constants.exchanges.types;
const bitcoinWithdrawTypes = fullStackExchange.constants.transactions.bitcoinWithdrawTypes;
const dreamTypes = fullStackExchange.constants.dreams.types;
const raffleTypes = fullStackExchange.constants.raffles.types;
const utils = require( '../../../../../utils' );
const moneyActionsTypes = utils.constants.moneyActions.types;
module.exports = Object.freeze( ({
transactions,
}) => {
console.log(
`running 🗺mappyMappyTransactions🗺 with the following values - ${
stringify({
['number of transactions']: transactions.length,
})
}`
);
const moneyActions = transactions.map( transaction => {
const moneyAction = {
time: transaction.creationDate,
transactionId: transaction.transactionId,
};
switch( transaction.type ) {
case( transactionTypes.addBitcoin ): {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.regal.addressAmountUpdate,
amount: transaction.amount,
address: transaction.address,
}
);
break;
}
case( transactionTypes.exchange ): {
if( transaction.exchangeType === exchangeTypes.btcToCrypto ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.regal.exchange.btcToCrypto,
amountInBTCNeeded: transaction.amountInBTCNeeded,
amountInCryptoWanted: transaction.amountInCryptoWanted,
}
);
}
else if( transaction.exchangeType === exchangeTypes.cryptoToBTC ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.regal.exchange.cryptoToBTC,
amountInCryptoNeeded: transaction.amountInCryptoNeeded,
amountInBitcoinWanted: transaction.amountInBitcoinWanted,
}
);
}
else {
throw new Error(
'mappyMappyTransactions ' +
'invalid transaction exchangeType: ' +
transaction.exchangeType
);
}
break;
}
case( transactionTypes.withdrawBitcoin ): {
if( transaction.bitcoinWithdrawType === bitcoinWithdrawTypes.start ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.regal.withdraw.start,
amount: transaction.amount,
address: transaction.address,
fee: transaction.fee,
feeIncludedInAmount: transaction.feeIncludedInAmount
}
);
}
else if( transaction.bitcoinWithdrawType === bitcoinWithdrawTypes.failed ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.regal.withdraw.failed,
amount: transaction.amount,
address: transaction.address,
fee: transaction.fee,
feeIncludedInAmount: transaction.feeIncludedInAmount
}
);
}
else if( transaction.bitcoinWithdrawType === bitcoinWithdrawTypes.success ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.regal.withdraw.success,
amount: transaction.amount,
address: transaction.address,
fee: transaction.fee,
feeIncludedInAmount: transaction.feeIncludedInAmount
}
);
}
else {
throw new Error(
'mappyMappyTransactions ' +
'invalid transaction bitcoinWithdrawType: ' +
transaction.bitcoinWithdrawType
);
}
break;
}
case( transactionTypes.dream ): {
if( transaction.dreamType === dreamTypes.coin ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.game.talismanFlip,
amount: transaction.amount,
}
);
}
else if( transaction.dreamType === dreamTypes.lotus ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.game.talismanLotus,
amount: transaction.amount,
winData: transaction.jackpotWinData,
}
);
}
else if( transaction.dreamType === dreamTypes.slot ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.game.slot,
amount: transaction.amount,
happyDream: transaction.happyDream,
resultValues: transaction.resultValues,
hasTied: transaction.hasTied,
}
);
}
else {
throw new Error(
'mappyMappyTransactions ' +
'invalid dream type: ' +
transaction.dreamType
);
}
break;
}
case( transactionTypes.raffle ): {
if( transaction.raffleType === raffleTypes.putTicket ) {
if( transaction.amount < 0 ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.game.lotus.pickPetal,
amount: transaction.amount,
choice: transaction.choice,
lotusSeasonId: transaction.searchId,
}
);
}
else {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.game.lotus.unpickPetal,
amount: transaction.amount,
choice: transaction.choice,
lotusSeasonId: transaction.searchId,
}
);
}
}
else if( transaction.raffleType === raffleTypes.payout ) {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.game.lotus.flowerPotPayout,
amount: transaction.amount,
lotusSeasonId: transaction.search,
petalDrawId: transaction.raffleDrawId,
}
);
}
else {
throw new Error(
'mappyMappyTransactions ' +
'invalid raffle transaction type: ' +
transaction.raffleType
);
}
break;
}
case( transactionTypes.bonus ): {
Object.assign(
moneyAction,
{
type: moneyActionsTypes.regal.bonus,
bitcoinAmount: transaction.bitcoinAmount,
cryptoAmount: transaction.cryptoAmount,
bonusNameId: transaction.searchId,
}
);
break;
}
default:
throw new Error(
'mappyMappyTransactions ' +
`invalid transaction type: ${ transaction.type }`
);
}
return moneyAction;
});
console.log( '🗺mappyMappyTransactions🗺 executed successfully' );
return moneyActions;
});<file_sep>import { createElement as e } from 'react';
// import { setState } from '../../constants';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
width: '100%',
backgroundColor: 'darkgreen',
// height: 100,
// backgroundColor: 'darkgreen',
// borderRadius: 12,
// padding: 20,
// marginTop: 30,
// marginBottom: 30,
marginTop: 18,
// height: 400,
// maxHiegh: 400,
// display: 'flex',
// flexDirection: 'column',
// justifyContent: 'center',
// alignItems: 'center',
overflowY: 'scroll',
},
};
};
const getContentsStyles = ({
isTopSection
}) => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
contentsSection: isTopSection ? {
width: '100%',
// height: 100,
// borderRadius: 12,
// padding: 20,
marginTop: 0,
// marginTop: 30,
// display: 'flex',
// flexDirection: 'flex-start',
// justifyContent: 'center',
// alignItems: 'center',
} : {
width: '100%',
// height: 100,
// borderRadius: 12,
// padding: 20,
marginTop: 17,
marginBottom: 17,
// marginTop: 30,
// display: 'flex',
// flexDirection: 'flex-start',
// justifyContent: 'center',
// alignItems: 'center',
},
titleText: {
paddingTop: 5,
paddingLeft: 18,
paddingRight: 18,
paddingBottom: 5,
color: 'white',
fontSize: 22,
textAlign: 'left',
},
text: {
paddingTop: 5,
paddingLeft: 18,
paddingRight: 18,
paddingBottom: 5,
color: 'white',
fontSize: 18,
textAlign: 'left',
lineHeight: 1.3,
}
};
};
const Section = ({
title,
contents,
isTopSection = false,
titleCount,
}) => {
const styles = getContentsStyles({
isTopSection
});
return e(
Box,
{
style: styles.contentsSection,
},
title && e(
Typography,
{
style: styles.titleText
},
`${ titleCount }. ${ title }`
),
e(
Typography,
{
style: styles.text
},
contents
)
);
};
export default ({
titleContentsAndMore = []
}) => {
const styles = getStyles();
let titleCount = 0;
const elementsToAdd = titleContentsAndMore.map( ({
title,
contents,
}) => {
if( !!title ) {
titleCount++;
}
return e(
Section,
{
title,
contents,
titleCount
}
);
});
return e(
'div',
{
style: styles.outerContainer
},
...elementsToAdd
);
};
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
javascript: {
getCoolCoolId
},
constants: {
timeNumbers: {
hour
}
}
} = require( '../../../../../../utils' );
const {
constants: {
passwordResetCode: {
prc
}
}
} = require( '../../../../../../exchangeUtils' );
module.exports = Object.freeze( ({
exchangeUserId,
}) => {
console.log(
'running getPasswordResetCode with the following values:',
stringify({
exchangeUserId
})
);
const expiryTime = Date.now() + hour;
const passwordResetCode = (
`${ prc }-${ exchangeUserId }-${ getCoolCoolId() }-${ expiryTime }`
);
console.log(
'getPasswordResetCode executed successfully,',
`here's the passwordResetCode:`,
passwordResetCode
);
return passwordResetCode;
});
<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../../reduxX';
import { WatermelonInput } from '../../usefulComponents';
export default () => {
const address = getState( 'withdrawPolygon', 'address' );
const isLoading = getState( 'isLoading' );
return e(
WatermelonInput,
{
width: 300,
value: address,
borderRadius: 0,
baseComponentName: 'box',
title: 'Address to Send BTC to',
// marginTop: 0,
// marginBottom: 0,
isLoadingMode: isLoading,
onChange: event => {
const text = event.target.value;
if( text.length > 50 ) {
return;
}
setState( [ 'withdrawPolygon', 'address' ], text.trim() );
},
}
);
};
<file_sep>'use strict';
module.exports = Object.freeze( ({
awsAccountNumber,
instancePrefix,
stageSuffix,
awsRegion,
}) => {
const policyData = [
// {
// name: 'role_lambda_api_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditorxxxtentacion",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// ]
// }
// ]
// },
// },
// {
// name: 'user_megaActions_dbOperationOnAll',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "MonkeyEditor",
// "Effect": "Allow",
// "Action": "dynamodb:Scan",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// ]
// }
// },
// {
// name: 'user_megaActions_dbOperations',
// // ATAUEU
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid1",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// ]
// }
// },
// {
// name: 'user_feeDataBot',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid1",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'user_withdrawsBot',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "MonkeyEditor",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_withdraws${ stageSuffix }/index/state-creationDate-index`
// },
// {
// "Sid": "VisualMonkeyEditor2323",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_withdraws${ stageSuffix }`
// },
// {
// "Sid": "UltraMonkeyEditor",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_withdraws${ stageSuffix }`
// },
// {
// "Sid": "UltraMonkeyEditorGorilla",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_withdraws${ stageSuffix }`
// },
// {
// "Sid": "MonkeyEditorOfBananaTown",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_balances${ stageSuffix }`
// },
// {
// "Sid": "TrustedMegaMonkeyEditor",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_balances${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'user_depositsBot',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor0",
// "Effect": "Allow",
// "Action": [
// "dynamodb:Query",
// "dynamodb:GetItem",
// "dynamodb:PutItem",
// "dynamodb:DeleteItem"
// ],
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_addresses${ stageSuffix }`
// },
// {
// "Sid": "VisualEditor3",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_balances${ stageSuffix }`
// },
// {
// "Sid": "VisualEditor4",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_balances${ stageSuffix }`
// },
// {
// "Sid": "VisualEditor5",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_addresses${ stageSuffix }/index/address-index`
// }
// ]
// }
// },
// {
// name: 'eFunction_addTransactionAndUpdateExchangeUser',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid1",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem"
// ],
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }`
// },
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }/index/exchangeUserId-creationDate-index`
// },
// {
// "Sid": "Sid3",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem",
// "dynamodb:PutItem"
// ],
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'user_deployApiFunctions',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": "iam:PassRole",
// "Resource": [
// `arn:aws:iam::${ awsAccountNumber }:role/bitcoin_api_lambda_infrastructure_emptyLambda`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_api_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_api_tokens_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_api_tokens_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_api_tokens_put${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_api_addresses_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_api_feeData_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_api_withdraws_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_service_cacheOnAndOffStatus${ stageSuffix }`
// ]
// },
// {
// "Sid": "VisualEditor2",
// "Effect": "Allow",
// "Action": [
// "lambda:GetFunction",
// "lambda:CreateFunction",
// "lambda:UpdateFunctionCode",
// "lambda:UpdateFunctionConfiguration"
// ],
// "Resource": [
// // `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:bitcoin_api_infrastructure_emptyLambda`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }api_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }api_tokens_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }api_tokens_patch${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }api_tokens_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }api_tokens_put${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }api_addresses_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }api_feeData_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }api_withdraws_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }service_cacheOnAndOffStatus${ stageSuffix }`,
// ]
// }
// ]
// }
// },
// {
// name: 'user_deployExchangeFunctions',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": "iam:PassRole",
// "Resource": [
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_eUsers_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_eUsers_eUserId_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_eUsers_eUserId_delete${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_verifyUser_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_login_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_login_password_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_login_password_patch${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_withdraws_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_transactions_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_logout_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_exchanges_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_dreams_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_dreamsLotus_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_dreamsLotus_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_dreamsSlot_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_addresses_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_votes_voteId_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_votes_voteId_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_raffles_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_raffles_raffleId_post${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_raffleDraws_raffleId_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eApi_raffleTickets_raffleId_get${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eService_handleEEDRs${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eService_handleTransactionsStream${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eService_manageRafflePutTicketEvents${ stageSuffix }`,
// `arn:aws:iam::${ awsAccountNumber }:role/${ instancePrefix }lambda_eService_doRaffleDraw${ stageSuffix }`
// ]
// },
// {
// "Sid": "VisualEditor2",
// "Effect": "Allow",
// "Action": [
// "lambda:GetFunction",
// "lambda:CreateFunction",
// "lambda:UpdateFunctionCode",
// "lambda:UpdateFunctionConfiguration"
// ],
// "Resource": [
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_eUsers_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_eUsers_eUserId_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_eUsers_eUserId_delete${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_verifyUser_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_login_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_login_password_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_login_password_patch${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_withdraws_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_transactions_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_logout_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_exchanges_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_dreams_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_dreamsLotus_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_dreamsLotus_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_dreamsSlot_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_addresses_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_votes_voteId_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_votes_voteId_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_raffles_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_raffles_raffleId_post${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_raffleDraws_raffleId_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eApi_raffleTickets_raffleId_get${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eService_handleEEDRs${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eService_handleTransactionsStream${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eService_manageRafflePutTicketEvents${ stageSuffix }`,
// `arn:aws:lambda:${ awsRegion }:${ awsAccountNumber }:function:${ instancePrefix }eService_doRaffleDraw${ stageSuffix }`
// ]
// }
// ]
// },
// },
// {
// name: 'eFunction_mongolianBeginningDragonProtection',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor0",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_loginTokens${ stageSuffix }`,
// }
// ]
// }
// },
// {
// name: 'role_lambda_api_tokens_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditorxxxtentacion",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_users${ stageSuffix }`
// ]
// }
// ]
// }
// },
// {
// name: 'role_lambda_api_tokens_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_users${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_balances${ stageSuffix }`,
// ]
// }
// ]
// }
// },
// {
// name: 'role_lambda_api_tokens_put',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_users${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// ]
// },
// {
// "Sid": "TRUSTEDMONKEYDIRECTIVE",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_users${ stageSuffix }`
// ]
// }
// ]
// },
// },
// {
// name: 'role_lambda_api_addresses_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_users${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// ]
// },
// {
// "Sid": "Sid3",
// "Effect": "Allow",
// "Action": [
// "dynamodb:Query"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_addresses${ stageSuffix }`
// ]
// },
// {
// "Sid": "Sid3xxx",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_addresses${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_users${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_balances${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// ]
// }
// ]
// },
// },
// {
// name: 'role_lambda_api_feeData_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditorxxxtentacion",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// ]
// }
// ]
// },
// },
// {
// name: 'role_lambda_api_withdraws_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_users${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_balances${ stageSuffix }`
// ]
// },
// {
// "Sid": "Sid3",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_withdraws${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_balances${ stageSuffix }`,
// ]
// }
// ]
// }
// },
// {
// name: 'role_lambda_service_cacheOnAndOffStatus',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`,
// ]
// }
// ]
// },
// },
// {
// name: 'role_lambda_eApi_eUsers_eUserId_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor0",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_loginTokens${ stageSuffix }`
// },
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_eUsers_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor0",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }/index/email-index`
// },
// {
// "Sid": "VisualEditorYYZ",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeEmailDeliveryResults${ stageSuffix }`
// },
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// {
// "Sid": "VisualEditor2",
// "Effect": "Allow",
// "Action": "ses:SendEmail",
// "Resource": "*"
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_eUsers_eUserId_delete',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor0",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// {
// "Sid": "VisdfgdfsgacxzzxualEditor0",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// {
// "Sid": "VisualEditodsfsdf",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_loginTokens${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_verifyUser_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor0",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }/index/email-index`
// },
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem",
// "dynamodb:GetItem"
// ],
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// {
// "Sid": "VisualEditor2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem",
// "dynamodb:GetItem"
// ],
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// {
// "Sid": "VisualEditorYYZ",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeEmailDeliveryResults${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_addresses_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// ]
// },
// {
// "Sid": "Sid3xxx",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_addresses${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// ]
// }
// ]
// },
// },
// {
// name: 'role_lambda_eApi_transactions_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid3xxx",
// "Effect": "Allow",
// "Action": [
// "dynamodb:Query"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }/index/exchangeUserId-creationDate-index`
// ]
// }
// ]
// },
// },
// {
// name: 'role_lambda_eApi_login_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor0",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }/index/email-index`
// },
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_loginTokens${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_login_password_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor0",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }/index/email-index`
// },
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// {
// "Sid": "VisualEditorQYZ",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// {
// "Sid": "VisualEditorYYZ",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeEmailDeliveryResults${ stageSuffix }`
// },
// {
// "Sid": "VisualEditorEMAIL",
// "Effect": "Allow",
// "Action": "ses:SendEmail",
// "Resource": "*"
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_login_password_patch',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditorQYZ",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// },
// {
// "Sid": "VisualEditorsdsd",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }/index/email-index`
// },
// {
// "Sid": "VisualEditor1zxcxzc",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_loginTokens${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_logout_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_loginTokens${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_dreamsLotus_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditorxxx",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// },
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": "dynamodb:UpdateItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_dreamsLotus_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditorxxx",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// },
// ]
// }
// },
{
name: 'role_lambda_eApi_dreamsSlot_post',
policy: {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditorxxx",
"Effect": "Allow",
"Action": "dynamodb:GetItem",
"Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
},
]
}
},
// {
// name: 'role_lambda_eApi_withdraws_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`
// ]
// },
// {
// "Sid": "Sid123",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_withdraws${ stageSuffix }`
// ]
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_votes_voteId_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:Query"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }/index/exchangeUserId-creationDate-index`
// ]
// },
// ]
// }
// },
// {
// name: 'role_lambda_eApi_votes_voteId_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`,
// ]
// },
// ]
// }
// },
// {
// name: 'role_lambda_eApi_raffles_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": [
// "dynamodb:Query"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }/index/type-creationDate-index`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }/index/exchangeUserId-creationDate-index`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }/index/searchId-creationDate-index`
// ]
// },
// ]
// }
// },
// {
// name: 'role_lambda_eApi_raffleDraws_raffleId_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "SidXyz",
// "Effect": "Allow",
// "Action": [
// "dynamodb:Query"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }/index/type-creationDate-index`,
// ]
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_raffleTickets_raffleId_get',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "SidXyz",
// "Effect": "Allow",
// "Action": [
// "dynamodb:Query"
// ],
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }/index/searchId-creationDate-index`
// // "Resource": [
// // `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }/index/type-creationDate-index`,
// // ]
// }
// ]
// }
// },
// {
// name: 'role_lambda_eApi_raffles_raffleId_post',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "SidXyz",
// "Effect": "Allow",
// "Action": [
// "dynamodb:GetItem"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`,
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeUsers${ stageSuffix }`,
// ]
// },
// {
// "Sid": "SidWin",
// "Effect": "Allow",
// "Action": [
// "dynamodb:Query"
// ],
// "Resource": [
// `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }/index/exchangeUserId-creationDate-index"`
// ]
// },
// ]
// }
// },
// {
// name: 'role_lambda_eService_handleEEDRs',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor1",
// "Effect": "Allow",
// "Action": [
// "dynamodb:PutItem"
// ],
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_exchangeEmailDeliveryResults${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'role_lambda_eService_handleTransactionsStream',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "VisualEditor122",
// "Effect": "Allow",
// "Action": [
// "dynamodb:UpdateItem"
// ],
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// },
// // {
// // "Sid": "VisualEditor1",
// // "Effect": "Allow",
// // "Action": [
// // "dynamodb:PutItem"
// // ],
// // "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// // }
// ]
// }
// },
// {
// name: 'role_lambda_eService_manageRafflePutTicketEvents',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid1",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }/index/type-creationDate-index`
// },
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }/index/searchId-creationDate-index`
// },
// {
// "Sid": "Sid2pointFive",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// },
// {
// "Sid": "Sid3",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// },
// {
// "Sid": "Sid4xxx",
// "Effect": "Allow",
// "Action": "dynamodb:DeleteItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// }
// ]
// }
// },
// {
// name: 'role_lambda_eService_doRaffleDraw',
// policy: {
// "Version": "2012-10-17",
// "Statement": [
// {
// "Sid": "Sid1",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }/index/type-creationDate-index`
// },
// {
// "Sid": "Sid2",
// "Effect": "Allow",
// "Action": "dynamodb:Query",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_transactions${ stageSuffix }/index/searchId-creationDate-index`
// },
// {
// "Sid": "Sid2pointFive",
// "Effect": "Allow",
// "Action": "dynamodb:GetItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// },
// {
// "Sid": "Sid3",
// "Effect": "Allow",
// "Action": "dynamodb:PutItem",
// "Resource": `arn:aws:dynamodb:${ awsRegion }:${ awsAccountNumber }:table/bitcoin_api_metadata${ stageSuffix }`
// }
// ]
// }
// },
];
return policyData;
});<file_sep>export { default as FreeDestinyRaffle } from './FreeDestinyRaffle';<file_sep>'use strict';
const oneMinute = 1000 * 60;
const fiveMinutes = oneMinute * 5;
const oneHour = fiveMinutes * 12;
module.exports = Object.freeze( ({
timestamp,
}) => {
const timeFromHourUnder = timestamp % oneHour;
const hourUnder = timestamp - timeFromHourUnder;
const timeToHourOver = oneHour - timeFromHourUnder;
const hourAbove = timestamp + timeToHourOver;
const lastCancelTime = hourAbove - fiveMinutes;
const choiceTimeData = {
hourUnder,
hourAbove,
lastCancelTime,
};
return choiceTimeData;
});
<file_sep>export { default as getDynastyBitcoinAmount } from './getDynastyBitcoinAmount';<file_sep>'use strict';
const crypto = require( 'crypto' );
module.exports = Object.freeze( stringToHashInStandardizedWay => {
const standardHashedString = crypto.createHash(
'md5'
).update(
stringToHashInStandardizedWay
).digest( 'hex' );
return standardHashedString;
});
<file_sep>import { createElement as e } from 'react';
import { getState } from '../../../reduxX';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = ({
width,
height,
color,
fontWeight,
balanceFontSize,
backgroundColor,
borderRadius,
maxWidth,
}) => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
amountDisplayOuterContainer: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
height,
width,
maxWidth,
backgroundColor,
borderRadius,
// alignSelf: 'flex-end',
},
amountDisplayTopText: {
color,
// fontSize,
textAlign: 'center',
width: '100%',
fontWeight,
},
amountDisplayAmountText: {
color,
fontSize: balanceFontSize,
textAlign: 'center',
width: '100%',
},
};
};
const getText = ({
textVersion,
crypto
}) => {
if( textVersion === 'b' ) {
return `Current ${ crypto ? 'Dynasty Bitcoin' : 'Bitcoin' } Amount`;
}
else if( textVersion === 'c' ) {
return 'Balance';
}
return `Current Amount in ${ crypto ? 'Dynasty Bitcoin' : 'Bitcoin' }`;
};
export default ({
backgroundColor = 'beige',
crypto = true,
width = 160,
maxWidth,
fontWeight = 'bold',
height = 100,
color = 'black',
textVersion = 'a',
borderRadius = 4,
freeGameMode,
noTitleText = false,
balanceFontSize = 16,
}) => {
const styles = getStyles({
width,
height,
color,
fontWeight,
backgroundColor,
borderRadius,
maxWidth,
balanceFontSize,
});
const balanceAmountText = freeGameMode ? (
getState( 'notLoggedInMode', 'freeGameModeBalance' )
) : (
getState( 'loggedInMode', 'userData' ).balanceData.summary[
crypto ? 'crypto' : 'bitcoin'
].totalAmount
);
const balanceText = (
`${ balanceAmountText } ${ crypto ? 'DB' : 'BTC' }`
);
return e(
Box,
{
style: styles.amountDisplayOuterContainer,
},
!noTitleText && e(
Typography,
{
style: styles.amountDisplayTopText,
},
getText({
textVersion,
crypto,
})
),
e(
Typography,
{
style: styles.amountDisplayAmountText
},
balanceText
)
);
};
<file_sep>'use strict';
const updateDatabaseEntry = require( '../../../dino/updateDatabaseEntry' );
const {
aws: {
database: { tableNames: { WITHDRAWS } }
},
} = require( '../../../../../constants' );
module.exports = Object.freeze( async ({
withdraw,
state,
extraMetadata,
}) => {
console.log( 'running update withdraw' );
const newMetadata = Object.assign(
{},
withdraw.metadata,
extraMetadata || {},
withdraw.metadataToAdd || {}
);
delete withdraw.metadataToAdd;
const newWithdraw = Object.assign(
{},
withdraw,
{
state,
metadata: newMetadata
}
);
await updateDatabaseEntry({
tableName: WITHDRAWS,
entry: newWithdraw
});
console.log( 'update withdraw executed successfully' );
});
<file_sep>'use strict';
const {
utils: {
aws: {
dinoCombos: {
balances: {
getBalanceDataForUser
}
}
}
},
constants: {
balances: {
states: {
normal,
transformation
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
getFormattedEvent,
getResponse,
handleError,
stringify,
beginningDragonProtection,
} = require( '../../../utils' );
exports.handler = Object.freeze( async rawEvent => {
console.log( 'running the /tokens - GET function' );
try {
const event = getFormattedEvent({
rawEvent,
});
const {
user,
// dragonDirective,
} = await beginningDragonProtection({
queueName: 'getUser',
event,
ipAddressMaxRate: 40,
ipAddressTimeRange: 10000,
advancedCodeMaxRate: 40,
advancedCodeTimeRange: 10000,
});
const {
balance,
moneyOutIsInTransformationState
} = await getBalanceDataForUser({
userIdOrUser: user
});
const balanceData = {
amount: balance,
status: moneyOutIsInTransformationState ? transformation : normal,
};
// const tokenIsActivated = (dragonDirective >= 2);
const response = {
// isActivated: tokenIsActivated,
balanceData,
};
console.log(
'/tokens - GET function executed successfully, ' +
'returning values: ' +
stringify( response, null, 4 )
);
return getResponse({ body: response });
}
catch( err ) {
console.log( `error in /tokens - GET function: ${ err }` );
return handleError( err );
}
});<file_sep>#!/usr/bin/env node
'use strict';
const Web3 = require( 'web3' );
const main = async () => {
const web3 = new Web3( 'https://bsc-dataseed1.binance.org:443' );
// const loader = setupLoader({ provider: web3 }).web3;
const account = web3.eth.accounts.create();
console.log(`
MEGA LOG: ${ JSON.stringify( {
account
}, null, 4 ) }
`);
};
(async () => {
try {
await main();
}
catch( err ) {
console.log( 'an error occurred:', err );
}
})();
<file_sep>'use strict';
const drqPrivate = require( './drqPrivate' );
module.exports = Object.freeze( async ({
queueId,
doOperation,
doOperationArgs,
}) => {
return await drqPrivate({
queueId,
operation: doOperation,
operationArgs: doOperationArgs,
});
});
<file_sep>'use strict';
const {
aws: {
database: {
tableNameToKey,
tableNames: { METADATA },
metadataPartitionKeyValues
}
},
withdraws: {
limits: {
maximumWithdrawAmount,
}
}
} = require( '../../../constants' );
const stringify = require( '../../stringify' );
const validateBusinessFeeData = Object.freeze( ({
businessFeeData,
}) => {
if(
!businessFeeData ||
(typeof businessFeeData !== 'object') ||
Array.isArray( businessFeeData )
) {
throw new Error(
'validateBusinessFee: invalid business fee - ' +
'business fee data does not exist or is not an object'
);
}
const businessKeys = Object.keys( businessFeeData );
for( const businessKey of businessKeys ) {
const businessValue = businessFeeData[ businessKey ];
if(
!businessValue ||
(typeof businessValue !== 'object') ||
Array.isArray( businessValue )
) {
throw new Error(
'validateBusinessFee: invalid business fee data value ' +
`associated with business key: "${ businessKey }"`
);
}
if(
(typeof businessValue.amount !== 'number') ||
(businessValue.amount < 0) ||
(businessValue.amount > maximumWithdrawAmount)
) {
throw new Error(
'validateBusinessFee: invalid business fee data amount ' +
`associated with business key: "${ businessKey }"`
);
}
}
});
module.exports = Object.freeze( ({
fee,
feeMultiplier,
businessFeeData = {},
megaServerId,
noKeyProperty = false,
}) => {
console.log( 'running getFeeData' );
validateBusinessFeeData({
businessFeeData,
});
const tableName = METADATA;
const feeData = {
amount: fee,
multiplier: feeMultiplier,
bitcoinNodeUrl: megaServerId,
businessFeeData,
};
const shouldAddKeyProperty = !noKeyProperty;
if( shouldAddKeyProperty ) {
const key = tableNameToKey[ tableName ];
feeData[ key ] = metadataPartitionKeyValues.feeData;
}
console.log(
'getFeeData executed successfully - ' +
`got fee data ${ stringify( feeData ) }`
);
return feeData;
});<file_sep>'use strict';
// const argv = require( 'yargs' ).argv;
const {
utils: {
stringify,
},
// constants: {
// aws: { database: { tableNames: { BALANCES, WITHDRAWS } } }
// }
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( async ({
allItems,
}) => {
console.log(
'running refreshExistingAtaeue endGameOperation ' +
'with the following values:',
stringify({ 'allItems.length': allItems.length })
);
});
<file_sep>import { createElement as e } from 'react';
import { getState } from '../../../reduxX';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import QrStronghold from './QrStronghold';
import ButtonArmament from './ButtonArmament';
const getStyles = ({
isDialogDesktopMode,
}) => {
return {
outerContainer: {
// backgroundColor: 'pink',
width: '100%',
// display: 'flex',
// justifyContent: 'center',
// flexDirection: 'column',
// alignItems: 'center'
},
daBox: {
width: '100%',
// height: 150,
// backgroundColor: 'lightgreen',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
alignItems: 'center',
},
titleTextBox: {
marginTop: isDialogDesktopMode ? 0 : 20,
width: '100%',
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
alignItems: 'center',
},
titleText: {
textAlign: 'center',
fontSize: 18,
// marginTop: 20,
// marginBottom: 20,
},
};
};
export default ({
isDialogDesktopMode,
}) => {
const styles = getStyles({
isDialogDesktopMode,
});
const userData = getState( 'loggedInMode', 'userData' );
const address = (
!!userData &&
!!userData.balanceData &&
!!userData.balanceData.bitcoin &&
!!userData.balanceData.bitcoin.depositAddress &&
userData.balanceData.bitcoin.depositAddress
);
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.daBox,
},
e(
Box,
{
style: styles.titleTextBox,
},
e(
Typography,
{
style: styles.titleText,
},
'Bitcoin Deposit Address'
),
!!address ? e(
QrStronghold,
{
address
}
) : e( ButtonArmament )
)
)
);
};
<file_sep>'use strict';
const STATUS_CODE_MESSAGE = 'not_found_error';
class NotFoundError extends Error {
constructor( message ) {
super( message );
this.statusCode = 404;
this.statusCodeMessage = STATUS_CODE_MESSAGE;
}
}
NotFoundError.statusCodeMessage = STATUS_CODE_MESSAGE;
module.exports = NotFoundError;<file_sep>'use strict';
const {
utils: {
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( ({
logMessage = '',
message = 'Internal server error',
statusCode = 400,
bulltrue = false,
}) => {
console.log(
'‼️🛎🌊 An error occurred: ' +
logMessage || message,
stringify({
errorMessage: message,
statusCode,
bulltrue,
})
);
const userDoesNotExistError = new Error(
message
);
Object.assign(
userDoesNotExistError,
{
statusCode,
bulltrue
}
);
throw userDoesNotExistError;
});<file_sep>export { default as getNumbersFromChoice } from './getNumbersFromChoice'; <file_sep>'use strict';
require( 'dotenv' ).config();
const request = require( 'request-promise' );
const { argv } = require('yargs');
const {
exchangeApiUrl,
exchangeUserId,
loginToken
} = require( './values' );
const getUser = async () => {
try {
const uri = `${ exchangeApiUrl }/exchange-users/${ exchangeUserId }`;
const response = await request({
uri,
json: true,
headers: {
'Content-Type': 'application/json',
'login-token': loginToken,
'user-id': exchangeUserId,
},
method: 'GET',
resolveWithFullResponse: true,
});
console.log(`
The Results: ${ JSON.stringify( {
['response body']: response.body,
}, null, 4 ) }
`);
}
catch( err ) {
console.log( 'an error occurred in the request:', err.message );
}
};
const numberOfTries = argv.n || 1;
(async () => {
for( let i = 1; i <= numberOfTries; i++ ) {
console.log( 'doing get: ', i );
getUser();
}
})();
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
validation: {
getIfEmailIsValid
},
formatting: {
getFormattedEmail
},
constants: {
google: {
captcha: {
actions: {
signUp
}
}
}
}
} = require( '../../../../../../utils' );
const {
validation: {
getIfPasswordIsValid
}
} = require( '../../../../../../exchangeUtils' );
const verifyGoogleCode = require( './verifyGoogleCode' );
// const emailWhitelist = Object.freeze([
// '<EMAIL>',
// '<EMAIL>',
// '<EMAIL>',
// '<EMAIL>'
// ]);
module.exports = Object.freeze( async ({
rawEmail,
rawPassword,
rawGoogleCode,
ipAddress
}) => {
console.log(
`running validateAndGetValues
with the following values - ${ stringify({
email: rawEmail,
password: <PASSWORD>,
googleCode: rawGoogleCode,
ipAddress
})
}`
);
const emailIsInvalid = !getIfEmailIsValid({
email: rawEmail,
});
if( emailIsInvalid ) {
const err = new Error( 'invalid email provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
// if( !emailWhitelist.includes( rawEmail ) ) {
// const err = new Error(
// `Email address "${ rawEmail }" is not invited yet -
// please email <EMAIL> to be invited!`
// );
// err.bulltrue = true;
// err.statusCode = 400;
// throw err;
// }
const passwordIsInvalid = !getIfPasswordIsValid({
password: <PASSWORD>
});
if( passwordIsInvalid ) {
const err = new Error( 'invalid password provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
const {
isHumanScore,
isHumanTime,
} = await verifyGoogleCode({
rawGoogleCode,
ipAddress,
expectedAction: signUp,
});
const displayEmail = rawEmail.toLowerCase();
const email = getFormattedEmail({
rawEmail
});
const validValues = {
email,
displayEmail,
password: <PASSWORD>,
isHumanScore,
isHumanTime,
};
console.log(
'validateAndGetValues executed successfully - got values ' +
stringify( validValues )
);
return validValues;
});
<file_sep>'use strict';
const encodeJson = Object.freeze( json => {
const encodedJson = (
Buffer.from( JSON.stringify( json ) ).toString( 'base64' )
);
return encodedJson;
});
const decodeJson = Object.freeze( encodedJson => {
const json = JSON.parse(
Buffer.from( encodedJson, 'base64' ).toString( 'ascii' )
);
return json;
});
module.exports = Object.freeze({
encodeJson,
decodeJson
});
<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( async ({
collection,
query,
justOne = true,
}) => {
console.log(
'running mongo.remove with the following values: ' +
stringify({ query, justOne })
);
if( justOne ) {
await collection.deleteOne( query );
}
else {
await collection.deleteMany( query );
}
console.log( 'mongo.remove executed successfully' );
});<file_sep>import { createElement as e, useState } from 'react';
import { getState } from '../../../../../reduxX';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
import {
usefulComponents
} from '../../../../../TheSource';
import Juice from './Juice';
// import Box from '@material-ui/core/Box';
// import Typography from '@material-ui/core/Typography';
// import Button from '@material-ui/core/Button';
// const getStyles = () => {
// // const mainStyleObject = getState( 'mainStyleObject' );
// const windowWidth = getState( 'windowWidth' );
// return {
// metaContainer: {
// width: '90%',
// display: 'flex',
// flexDirection: 'row',
// // justifyContent: 'flex-start',
// justifyContent: (windowWidth > 700) ? 'flex-start' : 'center',
// alignItems: 'center',
// marginTop: 15,
// marginBottom: 15,
// },
// };
// };
export default ({
raffleDatum
}) => {
// const styles = getStyles();
// const [ isLocalLoading, setIsLocalLoading ] = useState( true ); // TODO: CHANGE TO THIS
const [ isLocalLoading, setIsLocalLoading ] = useState( false );
const isLoading = getState( 'isLoading' );
const showHideButtonIsDisabled = (
isLocalLoading ||
isLoading
);
return e(
usefulComponents.OpenableBox,
{
title: 'All User Petals',
showHideButtonIsDisabled,
ContentComponent: Juice,
contentProps: {
raffleDatum,
isLocalLoading,
setIsLocalLoading,
},
}
);
};<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
getExchangeUser
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
exchangeUsers: {
getBalanceData
}
} = require( '../../../../../../exchangeUtils' );
module.exports = Object.freeze( async ({
exchangeUserId,
}) => {
console.log(
'running validateAndGetExchangeUser'
);
const exchangeUser = await getExchangeUser({
exchangeUserId,
});
const balanceData = getBalanceData({
exchangeUser,
});
const bitcoin = balanceData.summary.bitcoin.totalAmount;
const cryptos = balanceData.summary.crypto.totalAmount;
console.log(
'validateAndGetExchangeUser - ' +
'user balance exchangeUser and its balance: ' +
stringify({ bitcoin })
);
if( bitcoin > 0 ) {
const error = new Error(
'cannot delete an account that has bitcoin or crypto in it'
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
else if( cryptos > 0 ) {
const error = new Error(
'cannot delete an account that has crypto in it'
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
console.log(
'validateAndGetExchangeUser executed successfully - ' +
'user will be deleted'
);
return exchangeUser;
});
<file_sep>'use strict';
const {
runSpiritual
} = require( '@bitcoin-api/full-stack-backend-private' );
const {
constants: {
computerServerServiceNames: {
monkeyPaw
}
},
utils: {
javascript: {
getIfEnvValuesAreValid
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
backgroundExecutor
} = require( './utils' );
getIfEnvValuesAreValid([
{
type: getIfEnvValuesAreValid.envValidationTypes.string,
key: 'WITHDRAW_REPORTS_PATH'
},
{
type: getIfEnvValuesAreValid.envValidationTypes.string,
key: 'REDIS_URL'
},
]);
// const oneSecond = 1000;
// const tenSeconds = 10 * oneSecond;
// let lastOnStatusSignal = 0;
const getPendingWithdrawData = require( './getPendingWithdrawData' );
const doWithdraws = require( './doWithdraws' );
const serviceName = monkeyPaw;
const spiritual = Object.freeze( async () => {
console.log(
'***** Running withdrawBitcoins ***** 🐉🐉🐉🐉'
);
// if( 1 === 1 ) {
// await new Promise( resolve => setTimeout( resolve, 3000 ) );
// console.log(
// '***** withdrawBitcoins fake done ***** 🐉🐉🐉🐉'
// );
// return;
// }
const pendingWithdrawData = await getPendingWithdrawData();
const {
unexpectedError = null,
} = (
(
await doWithdraws({ pendingWithdrawData })
) ||
{
unexpectedError: null
}
);
if( !!unexpectedError ) {
console.error(
'An unexpected error occurred in withdrawBitcoins:',
unexpectedError
);
throw unexpectedError;
// TODO: if is redis error throw instead of forever error
// the task is to find redis errors
// console.log( 'ending withdrawBitcoins, forever' );
// return await deathFunction({
// name: serviceName
// });
}
console.log(
'withdrawBitcoins executed successfully, 🐉🐉🐉🐉🔥🔥🔥🔥'
);
});
module.exports = Object.freeze( async () => {
try {
backgroundExecutor.start();
await runSpiritual({
serviceName,
spiritual,
});
}
catch( err ) {
const errorMessage = (
`error in withdrawBitcoinsForever: ${ err }`
);
console.error( errorMessage );
}
});
<file_sep>'use strict';
const bitcoinAddressValidation = require( '@bitcoin-api/bitcoin-address-validation' );
const { environment: { isProductionMode } } = require( '../../../constants' );
module.exports = Object.freeze( value => {
const isValidAddress = bitcoinAddressValidation(
value,
isProductionMode ? 'mainnet' : 'testnet'
);
return isValidAddress;
});<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry
}
},
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_USERS
},
}
}
},
utils: {
exchangeUsers: {
getTheOracleOfDelphiDefi
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const flamingoCrescent = require( '../../../../../sacredElementals/crypto/flamingoCrescent/index' );
const {
javascript: {
getHashedPassword,
// getExchangeUserIdData,
// verificationCodeTools: {
// getVerificationCode
// }
},
} = require( '../../../../../exchangeUtils' );
module.exports = Object.freeze( async ({
email,
displayEmail,
password,
ipAddress,
exchangeUserId,
emailMessageId,
verifyEmailCode,
isHumanScore,
isHumanTime,
}) => {
console.log(
`running addNewUserToDatabase
with the following values - ${
stringify({
email,
displayEmail,
password,
exchangeUserId,
emailMessageId,
verifyEmailCode,
isHumanScore,
isHumanTime,
})
}`
);
// const {
// exchangeUserId,
// baseId
// } = getExchangeUserIdData();
const hashedPassword = getHashedPassword({
password,
});
const flamingoHashedPassword = flamingoCrescent({
text: hashedPassword
});
// const verifyEmailCode = getVerificationCode({
// baseId,
// });
const userObject = {
displayEmail,
exchangeUserId,
emailMessageId,
verifyEmailCode,
emailToVerify: email,
hashedPassword: <PASSWORD>,
metadata: {
creation: {
date: Date.now(),
ipAddress,
isHumanScore,
isHumanTime,
}
},
transactionCount: 0,
existingAtaueu: {
oracleGhost: {
theOracleOfDelphiDefi: getTheOracleOfDelphiDefi(),
withdrawIdToData: {},
},
}
};
await updateDatabaseEntry({
tableName: EXCHANGE_USERS,
entry: userObject,
});
const responseObject = {};
console.log(
'addNewUserToDatabase executed successfully - ' +
`returning values: ${ stringify( responseObject ) }`
);
return responseObject;
});
<file_sep>'use strict';
const STATUS_CODE_MESSAGE = 'bad_request';
class BadRequestError extends Error {
constructor( message ) {
super( message );
this.statusCode = 400;
this.statusCodeMessage = STATUS_CODE_MESSAGE;
}
}
BadRequestError.statusCodeMessage = STATUS_CODE_MESSAGE;
module.exports = BadRequestError;<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
aws: {
database: {
tableNames: {
EXCHANGE_USERS,
}
}
}
} = require( '../../../constants' );
const getExchangeDatabaseEntry = require( '../dino/getExchangeDatabaseEntry' );
module.exports = Object.freeze( async ({
exchangeUserId,
}) => {
console.log(
'running getExchangeUser ' +
`with the following values: ${ stringify({
exchangeUserId,
}) }`
);
const exchangeUser = await getExchangeDatabaseEntry({
tableName: EXCHANGE_USERS,
value: exchangeUserId,
});
console.log(
'getExchangeUser successfully executed, got exchange user: ' +
stringify( exchangeUser )
);
return exchangeUser;
});
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
random,
} = require( '../../../../../../exchangeUtils' );
// const percentageToWin = 0.01; 100
// const percentageToWin = 0.001; 1000
// const percentageToWin = 0.0001; 10000
// const percentageToWin = 0.00001; 100000
const percentageToWin = 0.00001;
const coinNumberMultiplier = 1000000000;
const coinNumberThreshold = (1 - percentageToWin) * coinNumberMultiplier;
module.exports = Object.freeze( () => {
console.log(
`𓏧 𓏲 𓏲 𓏲 𓋒 𓏲 𓏲 𓏲 𓏲 𓏧 🌸Lotus Flipping the Jackpot 𓏧 𓏲 𓏲 𓏲 𓋒 𓏲 𓏲 𓏲 𓏲 𓏧\n` +
' - \n' +
`need to get coinNumber higher than or equal to ${ coinNumberThreshold }`
);
const jackpotCoinNumber = random.getRandomIntegerInclusive({
min: 1,
max: coinNumberMultiplier
});
const hasWonThisChallengeOfFate = jackpotCoinNumber > coinNumberThreshold;
console.log(
`𓏧 𓏲 𓏲 𓏲 𓋒 𓏲 𓏲 𓏲 𓏲 𓏧 🌸Lotus Flipping the Jackpot 𓏧 𓏲 𓏲 𓏲 𓋒 𓏲 𓏲 𓏲 𓏲 𓏧\n` +
' - \n' +
'executed successfully: ' + stringify({
jackpotCoinNumber,
hasWonThisChallengeOfFate
})
);
return hasWonThisChallengeOfFate;
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase
}
},
stringify,
},
// constants: {
// aws: {
// database: {
// secondaryIndex: {
// typeCreationDateIndex
// },
// }
// },
// }
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
TRANSACTIONS
},
secondaryIndices: {
searchIdCreationDateIndex
}
}
},
// transactions: {
// types: {
// raffle
// }
// },
raffles: {
types: {
putTicket
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const searchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
// raffleId: '#raffleId',
raffleType: '#raffleType',
searchId: '#searchId',
amount: '#amount',
}),
nameValues: f({
// raffleId: 'raffleId',
raffleType: 'raffleType',
searchId: 'searchId',
amount: 'amount',
}),
valueKeys: f({
// raffleId: ':raffleId',
raffleType: ':raffleType',
searchId: ':searchId',
}),
});
module.exports = Object.freeze( async ({
putTicketEvent
}) => {
console.log(
'running getCurrentRafflePotAmountData with the following values: ' +
stringify({
putTicketEvent
})
);
let currentRafflePotAmount = 0;
let paginationValueToUse = null;
let iterationCount = 0;
do {
console.log(
'getCurrentRafflePotAmountData - ' +
'running transactions search: ' +
stringify({
currentRafflePotAmount,
paginationValueToUse,
iterationCount,
})
);
const searchParams = {
TableName: TRANSACTIONS,
IndexName: searchIdCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: true,
ProjectionExpression: [
attributes.nameKeys.amount,
// attributes.nameKeys.creationDate,
// attributes.nameKeys.action,
].join( ', ' ), // TODO:
KeyConditionExpression: (
`${ attributes.nameKeys.searchId } = ${ attributes.valueKeys.searchId }`
),
FilterExpression: (
// `${ attributes.nameKeys.raffleId } = ${ attributes.valueKeys.raffleId } and ` +
`${ attributes.nameKeys.raffleType } = ${ attributes.valueKeys.raffleType }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.raffleType]: attributes.nameValues.raffleType,
[attributes.nameKeys.searchId]: attributes.nameValues.searchId,
[attributes.nameKeys.amount]: attributes.nameValues.amount,
// [attributes.nameKeys.raffleId]: attributes.nameValues.raffleId,
},
ExpressionAttributeValues: {
[attributes.valueKeys.searchId]: putTicketEvent.raffleId,
[attributes.valueKeys.raffleType]: putTicket,
// [attributes.valueKeys.raffleId]: command.raffleId,
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const rafflePutTicketTransactions = ultimateResults;
for( const transaction of rafflePutTicketTransactions ) {
currentRafflePotAmount += transaction.amount;
}
if( !!paginationValue ) {
paginationValueToUse = paginationValue;
iterationCount++;
}
else if( !!paginationValueToUse ) {
paginationValueToUse = null;
}
} while( !!paginationValueToUse );
const currentRafflePotAmountData = {
currentRafflePotAmount: Math.abs( currentRafflePotAmount )
};
console.log(
'getCurrentRafflePotAmountData executed successfully ' +
'returning currentRafflePotAmountData: ' +
stringify( currentRafflePotAmountData )
);
return currentRafflePotAmountData;
});
<file_sep>cd
rm -rf npmFolders
mkdir npmFolders
mkdir npmFolders/0-commonCode
mkdir npmFolders/0-commonCode/api
mkdir npmFolders/0-commonCode/exchange
mkdir npmFolders/1-backend
mkdir npmFolders/1-backend/commonUtilities
mkdir npmFolders/1-backend/giraffe-utils
mkdir npmFolders/x-public
mkdir npmFolders/x-public/bitcoin-api
mkdir npmFolders/x-public/bitcoin-address-validation
<file_sep>'use strict';
const BEP20 = artifacts.require("BEP20");
module.exports = function(deployer) {
deployer.deploy(BEP20);
};
<file_sep>'use strict';
const {
utils: {
stringify,
database:{
metadata: {
metaGetFeeToPayFromFeeData
},
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
getExchangeUser
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
exchangeUsers: {
getBalanceData
}
} = require( '../../../../../exchangeUtils' );
module.exports = Object.freeze( async ({
withdrawAmount,
shouldIncludeFeeInAmount,
feeData,
exchangeUserId,
}) => {
console.log( 'running ensureExchangeUserHasEnoughMoney' );
const exchangeUser = await getExchangeUser({
exchangeUserId,
});
const balanceData = getBalanceData({
exchangeUser,
});
const metaFeeToPay = metaGetFeeToPayFromFeeData(
{
shouldIncludeFeeInAmount
},
{
feeData,
}
);
const totalRequestedWithdrawAmount = withdrawAmount + metaFeeToPay;
const totalAmountExchangeUserHas = balanceData.summary.bitcoin.totalAmount;
console.log(
'ensureExchangeUserHasEnoughMoney - ' +
'here are the values to be considered: ' +
stringify({
totalRequestedWithdrawAmount,
totalAmountExchangeUserHas
})
);
if( totalRequestedWithdrawAmount > totalAmountExchangeUserHas ) {
const error = new Error(
'user does not have enough money to perform ' +
'the requested withdraw'
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
console.log(
'ensureExchangeUserHasEnoughMoney executed successfully - ' +
'exchange user has enough money to perform the withdraw'
);
return {
metaFeeToPay
};
});<file_sep>'use strict';
const axios = require( 'axios' );
const nodeQueryString = require( 'querystring' );
const {
google: {
captcha: {
verifyUrl,
bypassHeaderKeyValue,
}
}
} = require( '../constants' );
const {
utils: {
stringify,
},
constants: {
environment: {
isProductionMode
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const invalidGrecaptchaBypassHeaderKeyValues = Object.freeze([
'0',
'null',
'undefined'
]);
const grecaptchaBypassHeaderKeyValueIsValid = (
!!bypassHeaderKeyValue &&
!invalidGrecaptchaBypassHeaderKeyValues.includes( bypassHeaderKeyValue )
);
module.exports = Object.freeze( async ({
rawGoogleCode,
ipAddress,
expectedAction
}) => {
console.log(
'running verifyGoogleCode with the following values: ' +
stringify({
rawGoogleCode,
ipAddress,
expectedAction,
})
);
if(
!isProductionMode &&
(
process.env.SHOULD_NOT_CONSIDER_GOOGLE_CODE_IN_STAGING_MODE ===
'yes'
)
) {
console.log(
'verifyGoogleCode executed successfully - ' +
'SHOULD_NOT_CONSIDER_GOOGLE_CODE_IN_STAGING_MODE ' +
'🌞 staging bypass mode 🌞'
);
return {
isHumanScore: 69.22,
isHumanTime: 54321,
};
}
const googleCodeIsInvalid = !(
!!rawGoogleCode &&
(typeof rawGoogleCode === 'string') &&
(rawGoogleCode.length > 2) &&
(rawGoogleCode.length < 10000)
);
if( googleCodeIsInvalid ) {
const err = new Error( 'invalid Google code provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
if(
grecaptchaBypassHeaderKeyValueIsValid &&
(rawGoogleCode === bypassHeaderKeyValue)
) {
console.log(
'verifyGoogleCode executed successfully - 🐸 bypass mode 🐸'
);
return {
isHumanScore: 22.69,
isHumanTime: 12345,
};
}
try {
const response = await axios.post(
verifyUrl,
nodeQueryString.stringify({
secret: process.env.EXCHANGE_GRECAPTCHA_SECRET_KEY,
response: rawGoogleCode,
remoteip: ipAddress,
}),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
console.log(
'verifyGoogleCode - response data from Google verification: ' +
stringify( response.data )
);
const {
success,
score,
action,
challenge_ts,
} = response.data;
if(
!success ||
(action !== expectedAction)
) {
const err = new Error( 'could not verify Google code' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
console.log( 'verifyGoogleCode executed successfully' );
return {
isHumanScore: score,
isHumanTime: challenge_ts,
};
}
catch( err ) {
console.log( 'error in verifyGoogleCode:', err );
const error = new Error( 'invalid googleCode provided' );
error.bulltrue = true;
error.statusCode = 400;
throw error;
}
});
<file_sep>cd
cd treeDeploy/giraffeDeploy/tree
npm install
<file_sep>import { getState, setState } from '../../reduxX';
import bitcoinExchange from '../bitcoinExchangeInstance';
export default async ({
setToLoading = true,
} = { setToLoading: true }) => {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
try {
if( setToLoading ) {
setState( 'isLoading', true );
}
// const userData = {
// "userId": "exchange_user_bb791f9e86a94436aaeb0a2a10bce5f4",
// "email": "<EMAIL>",
// "balanceData": {
// "bitcoin": {
// "totalAmount": 1,
// "depositAddress": "2ND8JVqU3GTgU6wJFd2m2eZxadcaoiK4E1H"
// },
// "bitcoinWithdraws": {
// "totalAmount": 0,
// "currentState": "power_omega"
// },
// "crypto": {
// "totalAmount": 0
// },
// "exchange": {
// "bitcoin": {
// "totalAmount": -0.9
// },
// "crypto": {
// "totalAmount": 900
// }
// },
// "summary": {
// "bitcoin": {
// "totalAmount": 0.1
// },
// "crypto": {
// "totalAmount": 900
// }
// }
// }
// };
const userData = await bitcoinExchange.getUser({
userId,
loginToken,
});
const setStateArguments = [
{
keys: [ 'loggedInMode', 'userData' ],
value: userData
}
];
if( setToLoading ) {
setStateArguments.push(
{
keys: 'isLoading',
value: false
}
);
}
setState( ...setStateArguments );
}
catch( err ) {
console.log( 'error getting user data', err );
if( setToLoading ) {
setState( 'isLoading', false );
}
throw err;
}
};
<file_sep>'use strict';
const getIfEnvValueIsTruthful = require( './getIfEnvValueIsTruthful' );
module.exports = Object.freeze( ({
envKeys
}) => {
envKeys.forEach( envKey => {
if( !getIfEnvValueIsTruthful({ envKey }) ) {
throw new Error(
`🧞♀️env value "${ envKey }" not set🧞♀️`
);
}
});
});
<file_sep>'use strict';
module.exports = Object.freeze( async ({ returnCode }) => {
if(
!returnCode ||
(typeof returnCode !== 'string') ||
(returnCode.length < 420) ||
(returnCode.length > 869)
) {
throw new Error( 'invalid megaCode' );
}
});<file_sep>import { getState, setState } from '../../reduxX';
import { bitcoinExchange } from '../../utils';
export default async () => {
const moneyActions = getState(
'transactionsPolygon',
'moneyActions'
);
if( !!moneyActions ) {
return;
}
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
const getTransactionsResults = await bitcoinExchange.getTransactions({
userId,
loginToken,
smallBatch: true,
});
setState(
[
'transactionsPolygon',
'moneyActions'
],
getTransactionsResults.moneyActions,
[
'transactionsPolygon',
'lastTransactionId'
],
getTransactionsResults.lastTransactionId,
[
'transactionsPolygon',
'lastTime'
],
getTransactionsResults.lastTime
);
};
<file_sep>#!/usr/bin/env node
'use strict';
const argv = require( 'yargs' ).argv;
const isProductionMode = argv.mode === 'production';
if( isProductionMode ) {
require( 'dotenv' ).config({ path: `${ __dirname }/../productionCredentials/.env` });
}
else {
require( 'dotenv' ).config({ path: `${ __dirname }/../stagingCredentials/.env` });
}
const {
utils: {
aws: {
dinoCombos: {
getExchangeUser
}
}
},
// constants: {
// transactions: {
// types: {
// bonus
// }
// }
// }
} = require( '@bitcoin-api/full-stack-exchange-private' );
const fs = require( 'fs' );
const getBalanceData = require( process.env.GET_BALANCE_DATA_PATH );
const writeUserDataToFile = Object.freeze( ({
exchangeUserId,
userData
}) => {
const stream = fs.createWriteStream(
`${ __dirname }/userData.txt`,
{
flags: 'a'
}
);
stream.write(
`==--==--==--==--==--==--==--==--==--==--==--==--==\n` +
`User Data ${ exchangeUserId } - ${ (new Date()).toLocaleString() }\n` +
`${ JSON.stringify( userData, null, 4 ) },\n` +
{
[process.env.EU1]: '👑🐸',
[process.env.EU2]: '🦃',
[process.env.EU3]: '👸❤️',
[process.env.EU4]: '🌈🐑',
[process.env.EU5]: '🐳',
[process.env.EU6]: '🧑🏿⚕️',
}[ exchangeUserId ] + '\n' +
`==--==--==--==--==--==--==--==--==--==--==--==--==\n`
);
stream.end();
});
const getUserData = async ({
exchangeUserId
}) => {
const exchangeUser = await getExchangeUser({
exchangeUserId,
});
if( !exchangeUser ) {
throw new Error(
'holy fuck fuck duck no exchangeUser for ' +
`exchange user ID ${ exchangeUserId }`
);
}
const balanceData = getBalanceData({
exchangeUser
});
const userData = {
'Balance Summary': balanceData.summary,
'Total BTC Balance': (
Math.round(
(
balanceData.summary.bitcoin.totalAmount +
(balanceData.summary.crypto.totalAmount/1000)
) * 100000000 ) / 100000000
).toFixed(8),
'Transaction Count': exchangeUser.transactionCount,
};
writeUserDataToFile({
exchangeUserId,
userData
});
};
(async () => {
const exchangeUserId = argv.e || (
isProductionMode ? (
process.env.PRODUCTION_EXCHANGE_USER_ID
) : process.env.STAGING_EXCHANGE_USER_ID
);
try {
if( !exchangeUserId ) {
throw new Error( `invalid exchangeUserId: ${ exchangeUserId }` );
}
await getUserData({
exchangeUserId,
});
}
catch( err ) {
console.log(
`error in getting exchange user ${ exchangeUserId }:`,
err
);
}
})();
<file_sep>'use strict';
const yargs = require( 'yargs' );
const isProductionMode = (yargs.argv.mode === 'production');
const c = 'c';
const type = (
yargs.argv.type ||
yargs.argv.t ||
'uc'
);
if( isProductionMode ) {
console.log( '☢︎🐑 is production mode' );
require( 'dotenv' ).config({
path: `${ __dirname }/productionCredentials/.env`
});
process.env.BITCOIN_API_ENV = 'production';
}
else {
console.log( '🐲🐉 is staging mode' );
require( 'dotenv' ).config({
path: `${ __dirname }/stagingCredentials/.env`
});
process.env.BITCOIN_API_ENV = 'staging';
}
const environmentVariables = Object.assign( {}, process.env );
const {
// AWS
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
AWS_REGION,
AWS_ACCOUNT_NUMBER,
// Redis
REDIS_URL,
// Common
NODE_ENV,
API_PREFIX,
DO_NOT_SHOW_REAL_ERRORS,
MEGA_CODE_ENCRYPTION_PASSWORD_4,
MEGA_CODE_ENCRYPTION_ID_4,
LOGGER_COLOUR_OFF,
ROOT_LOGGER_PATH,
LOG_LEVELS,
LOG_LEVELS_ON_FOR_COMPONENTS,
IS_LAMBDA,
AWS_NODEJS_CONNECTION_REUSE_ENABLED,
BITCOIN_API_ENV,
SHOULD_CONSIDER_BANK_STATUS_IN_STAGING_MODE,
SHOULD_NOT_CONSIDER_GOOGLE_CODE_IN_STAGING_MODE,
// GOOGLE_CAPTCHA_KEY,
// GOOGLE_CAPTCHA_SECRET,
BITCOIN_API_BASE_URL,
// BITCOIN_API_PRIVACY_POLICY_URL,
// BITCOIN_API_TERMS_OF_SERVICE_URL,
// BITCOIN_API_API_DOCUMENTATION_URL,
// BITCOIN_API_TOKEN_FOR_MONITORING_TESTS,
MAINTENANCE_MODE_CODE,
MAINTENANCE_MODE_MESSAGE,
// PATCH_TOKENS_BYPASS_IS_HUMAN_TEST_SECRET,
// WEBSITE_DO_NOT_GATHER_DATA_KEY,
// WEBSITE_DO_NOT_GATHER_DATA_SECRET,
// CORONA_VIRUS_BITCOIN_API_IO_TOKEN,
// CORONA_VIRUS_DONATION_ADDRESS_QR_CODE_URL,
// CORONA_VIRUS_DONATION_ADDRESS,
} = environmentVariables;
const getFunctionDataFunctions = require( './007getFunctionDataFunctions' );
const rawFunctionData = [];
Object.keys(
getFunctionDataFunctions
).forEach( getFunctionDataFunctionKey => {
const getFunctionDataFunction = getFunctionDataFunctions[
getFunctionDataFunctionKey
];
const rawFunctionDataPortion = getFunctionDataFunction({
isProductionMode,
environmentVariables
});
rawFunctionData.push( ...rawFunctionDataPortion );
});
const functionData = [];
for( const rawFunctionDatum of rawFunctionData ) {
if( process.env.BITCOIN_API_ENV !== 'production' ) {
const functionDatum = Object.assign(
{},
rawFunctionDatum,
{
name: `${ API_PREFIX }${ rawFunctionDatum.name }_staging`,
role: (
'arn:aws:iam::' +
`${ AWS_ACCOUNT_NUMBER }:role/` +
`${ API_PREFIX }lambda_${ rawFunctionDatum.name }_staging`
),
}
);
functionData.push( functionDatum );
}
else {
const functionDatum = Object.assign(
{},
rawFunctionDatum,
{
name: `${ API_PREFIX }${ rawFunctionDatum.name }`,
role: (
'arn:aws:iam::' +
`${ AWS_ACCOUNT_NUMBER }:role/` +
`${ API_PREFIX }lambda_${ rawFunctionDatum.name }`
),
}
);
functionData.push( functionDatum );
}
}
const commonPathsToInclude = [
'./utils',
'./package.json',
'./node_modules',
];
const commonEnvironmentVariables = {
DO_NOT_SHOW_REAL_ERRORS,
LOGGER_COLOUR_OFF,
IS_LAMBDA,
NODE_ENV,
LOG_LEVELS,
LOG_LEVELS_ON_FOR_COMPONENTS,
ROOT_LOGGER_PATH,
REDIS_URL,
AWS_NODEJS_CONNECTION_REUSE_ENABLED,
BITCOIN_API_ENV,
BITCOIN_API_BASE_URL,
SHOULD_CONSIDER_BANK_STATUS_IN_STAGING_MODE,
SHOULD_NOT_CONSIDER_GOOGLE_CODE_IN_STAGING_MODE,
MAINTENANCE_MODE_CODE,
MAINTENANCE_MODE_MESSAGE,
MEGA_CODE_ENCRYPTION_PASSWORD_4,
MEGA_CODE_ENCRYPTION_ID_4,
};
const execa = require( 'execa' );
const bluebird = require( 'bluebird' );
const AWS = require( 'aws-sdk' );
const fs = require( 'fs' );
AWS.config.update({
accessKeyId: AWS_ACCESS_KEY_ID,
secretAccessKey: AWS_SECRET_ACCESS_KEY,
region: AWS_REGION,
});
const cache = Object.seal({
emptyFunctionCode: null
});
const lambda = new AWS.Lambda();
const ROOT_PATH = `${ __dirname }/`;
/*
Deploy Lambda Script:
remove node modules
install production node modules
for each lambda function data
-zip folders
-update code
*/
const removeNodeModulesAndOldDist = () => {
if( type === c ) {
return Promise.resolve();
}
console.log( 'running removeNodeModulesAndOldDist' );
const command = 'rm';
const args = [
'-rf',
'./node_modules',
'./dist'
];
const options = {
cwd: ROOT_PATH
};
return execa( command, args, options ).then( () => {
console.log( 'removeNodeModulesAndOldDist executed successfully' );
return execa( 'mkdir', [ 'dist' ], options );
});
};
const installNodeModules = ({
production = false
} = { production: false }) => {
if( type === c ) {
return;
}
console.log( 'running installNodeModules, production:', production );
const command = 'npm';
const args = [
'install'
];
if( !!production ) {
args.push( '--only=prod' );
}
const options = {
cwd: ROOT_PATH
};
return execa(
command,
args,
options
).then( () => {
console.log(
'installNodeModules executed successfully',
'production:', production
);
});
};
const getOrCreateFunction = async ({
functionNickname,
functionName
}) => {
console.log( `running getOrCreateFunction for: ${ functionNickname }` );
const params = {
FunctionName: functionName,
};
try {
await new Promise( ( resolve, reject ) => {
lambda.getFunction(
params,
( err, data ) => {
if( !!err || !data ) {
reject( err );
}
else {
resolve();
}
}
);
});
console.log(
'getOrCreateFunction: ' +
`${ functionName }(${ functionNickname }) ` +
'already exists'
);
}
catch( err ) {
if( err.statusCode === 404 ) {
console.log(
`getOrCreateFunction: ${ functionName } does not exist, ` +
'creating function'
);
if( !cache.emptyFunctionCode ) {
cache.emptyFunctionCode = await new Promise(
( resolve, reject ) => {
fs.readFile(
`${ __dirname }/emptyLambda.js.zip`,
( err, zipFile ) => {
if( !!err ) {
return reject( err );
}
resolve( zipFile );
}
);
}
);
}
await new Promise( ( resolve, reject ) => {
lambda.createFunction(
{
Code: {
ZipFile: cache.emptyFunctionCode
},
FunctionName: functionName,
Handler: "index.handler",
MemorySize: 128,
Publish: true,
Role: `arn:aws:iam::${ AWS_ACCOUNT_NUMBER }:role/bitcoin_api_lambda_infrastructure_emptyLambda`,
Runtime: "nodejs12.x",
Timeout: 30,
VpcConfig: {}
},
( err, data ) => {
if( !!err || !data ) {
reject( err );
}
else {
resolve();
}
}
);
});
}
else {
throw err;
}
}
console.log(
`getOrCreateFunction: executed successfully for ${ functionName }` +
`(${ functionNickname })`
);
};
const zipFunctionCode = ({
zipFileName,
functionSpecificPathsToInclude,
}) => {
console.log( 'running zipFunctionCode' );
const zipFilePath = `./dist/${ zipFileName }.zip`;
const command = 'zip';
const pathsToIncludeSet = new Set(
functionSpecificPathsToInclude.concat( commonPathsToInclude )
);
const pathsToInclude = Array.from( pathsToIncludeSet );
console.log( 'zipFileName:', zipFileName );
console.log( 'paths to include:', JSON.stringify( pathsToInclude ) );
const args = [ zipFilePath, '-r' ].concat( pathsToInclude );
const options = {
cwd: ROOT_PATH
};
return execa(
command,
args,
options
).then( () => {
return new Promise( ( resolve, reject ) => {
fs.readFile( zipFilePath, ( err, zipFile ) => {
if( !!err ) {
return reject( err );
}
resolve( zipFile );
});
});
}).then( zipFile => {
console.log(
'zipFunctionCode executed successfully for', zipFileName
);
const results = {
zipFile
};
return results;
});
};
const uploadFunction = ({
nickname,
name,
zipFile
}) => {
console.log( `running uploadFunction for: ${ nickname }` );
const params = {
FunctionName: name,
ZipFile: zipFile
};
return new Promise( ( resolve, reject ) => {
lambda.updateFunctionCode( params, ( err/*, data*/ ) => {
if( !!err ) {
return reject( err );
}
console.log(
'uploadFunction executed successfully for', nickname
);
resolve();
});
});
};
const updateFunctionConfiguration = ({
nickname,
name,
handler,
role,
environmentVariables = {},
timeout = 30,
memory = 128
}) => {
console.log( `running updateFunctionConfiguration for: ${ nickname }` );
const params = {
FunctionName: name,
Handler: handler,
Role: role,
Environment: {
Variables: Object.assign(
{},
commonEnvironmentVariables,
environmentVariables
)
},
Runtime: 'nodejs12.x',
Timeout: timeout,
MemorySize: memory,
};
return new Promise( ( resolve, reject ) => {
lambda.updateFunctionConfiguration( params, ( err/*, data*/ ) => {
if( !!err ) {
return reject( err );
}
console.log(
'updateFunctionConfiguration executed successfully for',
nickname
);
resolve();
});
});
};
const deployFunction = async ({
nickname,
name,
handler,
role,
pathsToInclude,
environmentVariables,
timeout,
memory
}) => {
await getOrCreateFunction({
functionNickname: nickname,
functionName: name
});
if(
type.includes( 'update' ) ||
type.includes( 'u' )
) {
const { zipFile } = await zipFunctionCode({
zipFileName: name,
functionSpecificPathsToInclude: pathsToInclude,
});
await uploadFunction({ nickname, name, zipFile });
}
if(
type.includes( 'config' ) ||
type.includes( 'c' )
) {
await updateFunctionConfiguration({
nickname,
name,
handler,
role,
environmentVariables,
timeout,
memory
});
}
};
const getSelectedFunctionData = Object.freeze( () => {
if( !!yargs.argv.functions ) {
const selectedFunctions = yargs.argv.functions.split( ',' );
const selectedFunctionData = functionData.filter(
({ nickname }) => selectedFunctions.includes( nickname )
);
return selectedFunctionData;
}
return functionData;
});
const deployFunctions = Object.freeze( () => {
console.log( 'running deployFunctions' );
return removeNodeModulesAndOldDist().then( () => {
return installNodeModules({ production: true });
}).then( () => {
const selectedFunctionData = getSelectedFunctionData();
return bluebird.map( selectedFunctionData, ({
nickname,
name,
handler,
role,
pathsToInclude,
environmentVariables,
timeout,
memory
}) => {
return deployFunction({
nickname,
name,
handler,
role,
pathsToInclude,
environmentVariables,
timeout,
memory
});
}, { concurrency: 10 } );
}).then( () => {
return installNodeModules();
}).then( () => {
console.log( 'deployFunctions successfully executed' );
}).catch( err => {
console.log( 'an error occurred in deployFunctions:', err );
});
});
deployFunctions();
<file_sep>export default ({
numbersA,
numbersB
}) => {
for( let i = 0; i < numbersA.length; i++ ) {
const same = numbersA[i] === numbersB[i];
if( !same ) {
if( numbersA[i] > numbersB[i] ) {
return 1;
}
else {
return -1;
}
}
}
return 0;
};
<file_sep>import { createElement as e } from 'react';
import { getState } from '../../reduxX';
import { actions } from '../../utils';
import { usefulComponents } from '../../TheSource';
export default () => {
const isLoading = getState( 'isLoading' );
return e(
usefulComponents.POWBlock,
{
marginBottom: 40,
onClick: () => {
actions.signOut();
},
text: 'Logout',
isLoadingMode: isLoading,
marginTop: 100,
}
);
};
<file_sep>'use strict';
const doDraw = require( './doDraw' );
exports.handler = Object.freeze( async () => {
console.log( '🎟Running doRaffleDraw' );
try {
await doDraw();
console.log( '✅🎟doRaffleDraw executed successfully' );
}
catch( err ) {
console.log( '❌🎟error in doRaffleDraw:', err );
}
});
<file_sep># Total Kingdom Update Instructions
S=server
H=home
CO=Champion Update Only
## King and Champion Update
OPTIONAL H) 1bupdateKing / setup king
S) Recreate NPM Folders
H) 1aUpdateNobilityRank.sh x.y.z (OPTIONAL for cleanliness: 1bupdateKing and 2updateChampion)
H) 0sendKingdom.sh
S) Publish King Kingdom
## Champion Update
S) Recreate NPM Folders
H) 2updateChampion (CO version patch before)
H) 0sendKingdom.sh
S) Publish Champion Kingdom
H) 3updatePeon
<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
raffles: {
actions
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const getTransactionAmountCore = Object.freeze( ({
ticketCryptoPrice,
action,
currentAmountForChoice,
}) => {
const negativeTicketCryptoPrice = -ticketCryptoPrice;
if( action === actions.buy ) {
if( currentAmountForChoice !== 0 ) {
const error = new Error(
'cannot buy ticket, already ' +
'bought ticket for selected numbers'
);
error.bulltrue = true;
error.statusCode = 400;
throw error;
}
return negativeTicketCryptoPrice;
}
if( currentAmountForChoice !== negativeTicketCryptoPrice ) {
const error = new Error(
'cannot cancel ticket, have ' +
'not yet bought ticket for selected numbers'
);
error.bulltrue = true;
error.statusCode = 400;
throw error;
}
return ticketCryptoPrice;
});
module.exports = Object.freeze( ({
ticketCryptoPrice,
action,
currentAmountForChoice,
}) => {
console.log(
`running getTransactionAmount
with the following values - ${
stringify({
ticketCryptoPrice,
action,
currentAmountForChoice,
})
}`
);
const transactionAmount = getTransactionAmountCore({
ticketCryptoPrice,
action,
currentAmountForChoice,
});
console.log(
`getTransactionAmount executed successfully
returning transaction amount: ${ transactionAmount } Cryptos`
);
return transactionAmount;
});<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const execa = require( 'execa' );
module.exports = Object.freeze( async ({
log,
tempTigerPath,
trueTigerLobby,
}) => {
log(
'📸📝running copyAndPasteToTrueTiger - ' +
stringify({
tempTigerPath,
trueTigerLobby
})
);
await execa(
'cp',
[
'-r',
tempTigerPath,
trueTigerLobby
]//,
// {}
);
log( '📸📝copyAndPasteToTrueTigerPath executed successfully' );
});
<file_sep>const toFixedConstant = 5;
const amountMultiplier = 100000;
export default amount => {
const dynastyBitcoinAmount = Number(
(
Math.round(
Number(amount) * amountMultiplier
) / amountMultiplier
).toFixed( toFixedConstant )
);
return dynastyBitcoinAmount;
};
<file_sep>#!/bin/bash
echo "****⛏🌳 Planting the Tree ****"
echo "👾👾👾👾👾👾👾👾👾👾"
echo "🌲"
echo "🎄🎄🎄🎄"
echo "🌳"
echo "🌷"
echo "🍁"
echo "👾👾👾👾👾👾👾👾👾👾"
echo "⛳️Digging the hole for the tree"
######################################################
######################################################
# These values need to be customized for your computer and remote Linux server
######
mode="staging" # OR "production"
pemPath="/Users/user-name/user-files/super-secret-path/linux-server-access-file.pem"
sourceRepoPath="/Users/user-name/my-code-folder/bitcoin-api-full-stack"
destinationUserName="ec2-user"
destinationUrl="ec2-instance-name.ec2-instance-region.compute.amazonaws.com"
destinationHomePath="/home/ec2-user"
######################################################
######################################################
### The code below is taken care of by Bitcoin-Api😁✌🕊💕🏛 ###
treePath="${sourceRepoPath}/1-backend/giraffeDeploy/tree"
destinationPath="${destinationHomePath}/treeDeploy/giraffeDeploy"
treenvPath="${sourceRepoPath}/1-backend/${mode}Credentials/tree"
treenvDestinationPath="${destinationHomePath}/treeDeploy/stagingCredentials/tree/.env"
for environmentalActivistPath in \
$treePath
do
pushd $environmentalActivistPath
rm -rf ./node_modules
popd
done
echo "⛰The planting has commenced🌋"
scp \
-i $pemPath \
-r \
$treePath \
"${destinationUserName}@${destinationUrl}:${destinationPath}"
scp \
-i $pemPath \
$treenvPath \
"${destinationUserName}@${destinationUrl}:${treenvDestinationPath}"
echo "💦A new tree lives☀️"
echo "👾👾👾👾👾👾👾👾👾👾"
echo "🌲"
echo "🎄🎄🎄🎄"
echo "🌳"
echo "🌷"
echo "🍁"
echo "****⛏🌳 Successfully Planted Tree ****"<file_sep>'use strict';
const stringify = require( '../../stringify' );
const doRedisRequest = require( '../doRedisRequest' );
const jsonEncoder = require( '../../javascript/jsonEncoder' );
const {
redis: {
streamIds
}
} = require( '../../../constants' );
module.exports = Object.freeze( async ({
redisClient,
eventName,
information
}) => {
console.log(
'🦒🌲💁♀️⏫',
'running giraffeAndTreeStatusUpdate with the following values:',
stringify({
eventName,
information,
})
);
const formattedInformation = Object.assign(
{},
{
time: Date.now(),
},
information
);
const powerInformation = jsonEncoder.encodeJson( formattedInformation );
const redisArguments = [
streamIds.zarbonDeploy,
'MAXLEN',
'~',
1000,
'*',
'eventName',
eventName,
'information',
powerInformation
];
const operationStartTimeKey = await doRedisRequest({
client: redisClient,
command: 'xadd',
redisArguments,
});
const results = {
operationStartTimeKey
};
console.log(
'🦒🌲💁♀️⏫',
'giraffeAndTreeStatusUpdate executed successfully - ' +
`returning results ${ stringify({ results }) }`
);
return results;
});
<file_sep>import { createElement as e, useEffect, Suspense, lazy } from 'react';
import { getState } from '../reduxX';
import { actions } from '../utils';
import getLoginCredentialsFromLocalStorage from './getLoginCredentialsFromLocalStorage';
// import NotLoggedInMode from './NotLoggedInMode';
import LoadingPage from '../TheSource/LoadingPage';
const LoggedInMode = lazy(() => import('./LoggedInMode'));
const NotLoggedInMode = lazy(() => import('./NotLoggedInMode'));
// import ColourSwitcher from '../TheSource/usefulComponents/ColourSwitcher';
const getStyles = () => {
const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: mainStyleObject.backgroundColor,
// backgroundColor: 'lightblue',
width: '100%',
// height: 200,
display: 'flex',
flexDirection: 'column',
// justifyContent: 'space-between',
// alignItems: 'center',
justifyContent: 'flex-start',
alignItems: 'center',
color: 'white',
},
};
};
export default ({
websiteName,
safeMode,
}) => {
useEffect( () => {
getLoginCredentialsFromLocalStorage();
}, [] );
const styles = getStyles();
const createElementArguments = [
'div',
{
style: styles.outerContainer,
},
];
const isLoggedIn = actions.getIsLoggedIn();
if( isLoggedIn ) {
createElementArguments.push(
e(
Suspense,
{
fallback: e('div')
},
e(
LoggedInMode,
{
safeMode,
}
)
)
);
}
else {
createElementArguments.push(
e(
Suspense,
{
fallback: e( LoadingPage, { fullDogeStyle: true } ),
},
e(
NotLoggedInMode,
{
websiteName
}
)
)
);
}
return e( ...createElementArguments );
};
<file_sep>'use strict';
const doRedisRequest = require( 'do-redis-request' );
const {
getKeyValues,
constants: {
END,
THE_QUEUE_NAME,
// TIMEOUT
},
delay,
} = require( '../tools' );
const getIfPreviousOperationIsStillRunning = Object.freeze( ({
data,
previousOperationId,
previousOperationQueueId,
queueId,
operationId,
}) => {
for( const datum of data ) {
if(
(
datum.keyValues.operationId ===
previousOperationId
) &&
(
datum.keyValues.queueId ===
previousOperationQueueId
) &&
(datum.keyValues.state === END)
) {
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
'👁🗨previous operation: ' +
`${ previousOperationId } - ` +
'waitForPreviousOperationToFinish - ' +
'previous operation finished before the timeout'
);
return false;
}
}
return true;
});
const waitForPreviousOperationToFinish = Object.freeze( async ({
redisClient,
whenThePreviousOperationWillBeFinishedForSure,
queueId,
firstLastTimeKey,
operationId,
previousOperationStartKeyValues
}) => {
const previousOperationId = previousOperationStartKeyValues.operationId;
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`👁🗨previous operation: ${ previousOperationId } - ` +
'running waitForPreviousOperationToFinish'
);
const timeOfWaitStart = Date.now();
let previousOperationIsStillRunning = true;
let lastTimeKey = firstLastTimeKey;
while( previousOperationIsStillRunning ) {
const timeUntilPreviousOperationIsFinishedForSure = (
whenThePreviousOperationWillBeFinishedForSure -
Date.now()
);
if( timeUntilPreviousOperationIsFinishedForSure <= 0 ) {
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`👁🗨previous operation: ${ previousOperationId } - ` +
'waitForPreviousOperationToFinish - ' +
'previous operation did not finish before timeout'
);
previousOperationIsStillRunning = false;
}
else {
const results = await doRedisRequest({
client: redisClient,
command: 'xread',
redisArguments: [
'BLOCK',
timeUntilPreviousOperationIsFinishedForSure,
'STREAMS',
THE_QUEUE_NAME,
lastTimeKey
]
});
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`👁🗨previous operation: ${ previousOperationId } - ` +
'waitForPreviousOperationToFinish got results ' +
'(or null) after waiting ' +
`${ (Date.now() - timeOfWaitStart)/1000 } seconds.`
);
const rawData = (
!!results &&
!!results[0] &&
!!results[0][1] &&
results[0][1]
) || null;
if( !rawData || (rawData.length < 1) ) {
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`👁🗨previous operation: ${ previousOperationId } - ` +
'waitForPreviousOperationToFinish - ' +
'previous operation did not finish before timeout'
);
previousOperationIsStillRunning = false;
}
else {
const data = rawData.map( entry => {
return {
timeKey: entry[0],
keyValues: getKeyValues({
keyValueList: entry[1],
}),
};
});
if(
getIfPreviousOperationIsStillRunning({
data,
previousOperationId,
previousOperationQueueId: (
previousOperationStartKeyValues.queueId
),
queueId,
operationId
})
) {
lastTimeKey = data[ data.length - 1 ].timeKey;
}
else {
previousOperationIsStillRunning = false;
}
}
}
}
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`👁🗨previous operation: ${ previousOperationId } - ` +
'waitForPreviousOperationToFinish executed successfully'
);
});
module.exports = Object.freeze( async ({
redisClient,
whenThePreviousOperationWillBeFinishedForSure,
queueId,
firstLastTimeKey,
operationId,
previousOperationStartKeyValues,
timeout
}) => {
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
'running waitUntilItIsTime'
);
await new Promise( async ( resolve, reject ) => {
let previousOperationHasFinished = false;
let previousOperationTimedOut = false;
let errorOccurred = false;
delay( timeout ).then( () => {
if( !errorOccurred && !previousOperationHasFinished ) {
previousOperationTimedOut = true;
const error = new Error(
`timeout error: operation: ${ operationId } - ` +
`Waiting on queue with id "${ queueId }" - ` +
`the timeout of ${ timeout/1000 } ` +
`seconds was hit before ` +
'this operation could be performed.'
);
return reject( error );
}
});
try {
await waitForPreviousOperationToFinish({
redisClient,
whenThePreviousOperationWillBeFinishedForSure,
queueId,
firstLastTimeKey,
operationId,
previousOperationStartKeyValues,
});
if( !errorOccurred && !previousOperationTimedOut ) {
previousOperationHasFinished = true;
return resolve();
}
}
catch( err ) {
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`waitUntilItIsTime, error occured: ${ err }`
);
if( !previousOperationTimedOut && !previousOperationHasFinished ) {
errorOccurred = true;
return reject( err );
}
}
});
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
'waitUntilItIsTime executed successfully'
);
});
<file_sep>'use strict';
const metaGetFeeToPayFromFeeData = require( '../../../../../database/metadata/metaGetFeeToPayFromFeeData' );
const stringify = require( '../../../../../stringify' );
const searchDatabase = require( '../../../../dino/searchDatabase' );
const {
aws: {
database: { tableNames: { WITHDRAWS } }
},
withdraws: {
states: {
complete,
failed,
manualFail,
// verifying,
verifyingToFail,
// realDealing,
// waiting,
// pending
}
},
} = require( '../../../../../../constants' );
const beginningOfTime = 1;
const endOfTime = 696969696969696969696;
// it never ends🐉
const f = Object.freeze;
const attributes = f({
nameKeys: f({
userId: '#userId',
ultraKey: '#ultraKey',
amount: '#amount',
state: '#state',
feeData: '#feeData',
withdrawId: '#withdrawId',
shouldIncludeFeeInAmount: '#shouldIncludeFeeInAmount',
}),
nameValues: f({
userId: 'userId',
ultraKey: 'ultraKey',
amount: 'amount',
state: 'state',
feeData: 'feeData',
withdrawId: 'withdrawId',
shouldIncludeFeeInAmount: 'shouldIncludeFeeInAmount',
}),
valueKeys: f({
state: ':state',
userId: ':userId',
startTime: ':startTime',
endTime: ':endTime',
failed: ':failed',
manualFail: ':manualFail',
// withdrawId: ':withdrawId',
}),
valueValues: f({
state: complete,
startTime: beginningOfTime,
endTime: endOfTime,
failed,
manualFail,
}),
});
module.exports = Object.freeze( async ({
userId,
// amountOffset,
// normalWithdrawId
// withdrawId
}) => {
console.log(
`running getWithdrawData - ${ stringify({
userId,
// amountOffset,
// normalWithdrawId
}) }`
);
const withdrawData = {
totalWithdrawAmount: 0, // + amountOffset,
balanceIsInTransformationState: false,
};
// let totalWithdrawAmount = 0 + amountOffset;
let paginationValue = {
ultraKey: 2
};
const dragonValues = Object.seal({
iterationCount: 0,
['🐲']: '🐉',
});
const dynamicAttributes = f({
valueValues: f({
userId,
// withdrawId
}),
});
while( !!paginationValue ) {
dragonValues.iterationCount++;
console.log(
'getting all withdraws: ' +
`search iteration count ${ dragonValues.iterationCount }`
);
const searchParams = {
TableName: WITHDRAWS,
ProjectionExpression: [
attributes.nameKeys.ultraKey,
attributes.nameKeys.feeData,
attributes.nameKeys.amount,
attributes.nameKeys.state,
attributes.nameKeys.withdrawId,
attributes.nameKeys.shouldIncludeFeeInAmount,
].join( ', ' ),
Limit: 2220,
ScanIndexForward: true,
KeyConditionExpression: (
`${ attributes.nameKeys.userId } = ` +
`${ attributes.valueKeys.userId } and ` +
`${ attributes.nameKeys.ultraKey } between ` +
`${ attributes.valueKeys.startTime } and ` +
attributes.valueKeys.endTime
),
FilterExpression: (
`${ attributes.nameKeys.state } <> ${ attributes.valueKeys.failed } and ` +
`${ attributes.nameKeys.state } <> ${ attributes.valueKeys.manualFail }`
// `${ attributes.nameKeys.state } <> ${ attributes.valueKeys.manualFail } and ` +
// `${ attributes.nameKeys.withdrawId } <> ${ attributes.valueKeys.withdrawId }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.userId]: attributes.nameValues.userId,
[attributes.nameKeys.ultraKey]: attributes.nameValues.ultraKey,
[attributes.nameKeys.feeData]: attributes.nameValues.feeData,
[attributes.nameKeys.amount]: attributes.nameValues.amount,
[attributes.nameKeys.state]: attributes.nameValues.state,
[attributes.nameKeys.withdrawId]: attributes.nameValues.withdrawId,
[attributes.nameKeys.shouldIncludeFeeInAmount]: attributes.nameValues.shouldIncludeFeeInAmount,
},
ExpressionAttributeValues: {
[attributes.valueKeys.userId]: dynamicAttributes.valueValues.userId,
[attributes.valueKeys.startTime]: attributes.valueValues.startTime,
[attributes.valueKeys.endTime]: attributes.valueValues.endTime,
[attributes.valueKeys.failed]: attributes.valueValues.failed,
[attributes.valueKeys.manualFail]: attributes.valueValues.manualFail,
// [attributes.valueKeys.withdrawId]: dynamicAttributes.valueValues.withdrawId,
},
ExclusiveStartKey: {
userId,
ultraKey: paginationValue.ultraKey,
}
};
const searchResults = await searchDatabase({
searchParams,
});
const withdraws = searchResults.ultimateResults;
for( const withdraw of withdraws ) {
const withdrawShouldBeConsideredToHaveValidValue = ![
// INCLUDES
// complete: 'complete',
// pending: 'pending',
// realDealing: 'realDealing',
// verifying: 'verifying',
// waiting: 'waiting'
// DOES NOT INCLUDE
verifyingToFail,
// failed, manualFail, // NOTE: already filtered
].includes( withdraw.state );
if( withdrawShouldBeConsideredToHaveValidValue ) {
const { amount, feeData, shouldIncludeFeeInAmount } = withdraw;
// const fee = shouldIncludeFeeInAmount ? 0 : (
// getFeeToPayFromFeeData({
// feeData,
// pleaseDoNotLogAnything: true,
// })
// );
const feeToPay = metaGetFeeToPayFromFeeData(
{
shouldIncludeFeeInAmount,
pleaseDoNotLogAnything: true
},
{
feeData,
pleaseDoNotLogAnything: true,
}
);
const totalAmountForWithdraw = amount + feeToPay;
withdrawData.totalWithdrawAmount += totalAmountForWithdraw;
}
if(
!withdrawData.balanceIsInTransformationState &&
![
// INCLUDES
// pending: 'pending',
// realDealing: 'realDealing',
// verifying: 'verifying',
// waiting: 'waiting'
// verifyingToFail: 'verifyingToFail',
// DOES NOT INCLUDE
complete,
// failed, manualFail, // NOTE: already filtered
].includes( withdraw.state )
) {
withdrawData.balanceIsInTransformationState = true;
}
}
if( !!searchResults.paginationValue ) {
paginationValue = searchResults.paginationValue;
}
else {
paginationValue = null;
}
}
console.log(
'getWithdrawData executed successfully, here is the ' +
`withdrawData: ${ stringify( withdrawData ) }`
);
return withdrawData;
});
<file_sep>import { createElement as e } from 'react';
// import { getState } from '../../reduxX';
// import { story } from '../../constants';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
// import Typography from '@material-ui/core/Typography';
// import FullscreenIcon from '@material-ui/icons/Fullscreen';
// import IconButton from '@material-ui/core/IconButton';
const getStyles = ({
dialogMode,
isLoading,
moneyActions,
}) => {
const {
outerContainerWidth,
outerContainerHeight,
outerContainerBackgroundColor,
textColor,
} = dialogMode ? {
outerContainerWidth: '100%',
outerContainerHeight: '100%',
outerContainerBackgroundColor: 'white',
textColor: 'black',
} : {
outerContainerWidth: '90%',
outerContainerHeight: '80%',
outerContainerBackgroundColor: 'black',
textColor: 'white',
};
const {
textSize,
fontWeight
} = !!moneyActions ? {
textSize: 22,
} : {
textSize: 16,
fontWeight: 'bold',
};
return {
outerContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
// backgroundColor: '#FF9900',
backgroundColor: outerContainerBackgroundColor,
width: outerContainerWidth,
minWidth: 300,
height: outerContainerHeight,
marginBottom: 20,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
theTextBox: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
maxWidth: '95%',
},
theText: {
textColor,
textAlign: 'center',
fontSize: textSize,
fontWeight,
}
};
};
export default ({
dialogMode,
moneyActions
}) => {
// const isLoading = getState( 'isLoading' );
const styles = getStyles({
dialogMode,
moneyActions,
});
const text = !moneyActions ? (
'Loading Transactions...'
) : (
'Currently no transactions. Deposit some Bitcoin to start!🤠'
);
return e(
Box,
{
style: styles.outerContainer
},
e(
Box,
{
style: styles.theTextBox,
},
e(
Typography,
{
style: styles.theText
},
text
)
)
);
};
<file_sep>'use strict';
module.exports = Object.freeze({
moneyActions: require( './moneyActions' ),
});
<file_sep>'use strict';
const doOperationInQueue = require( '../../../doOperationInQueue' );
const getDatabaseEntry = require( '../../dino/getDatabaseEntry' );
const updateDatabaseEntry = require( '../../dino/updateDatabaseEntry' );
const getQueueId = require( '../../../javascript/getQueueId' );
const {
aws: { database: { tableNames: { BALANCES } } },
users: {
balanceTypes
},
normalWithdraws: {
normalWithdrawsIds
},
megaServerIdToMegaServerData
} = require( '../../../../constants' );
const getBalanceData = require( '../../../business/getBalanceData' );
const getIfBalanceIsValid = Object.freeze(
({ balance }) => (
(typeof balance === 'number') &&
!Number.isNaN( balance ) &&
balance >= 0
)
);
const safeGetNewBalance = Object.freeze( ({
existingBalanceData,
getNewBalance
}) => {
const calculatedBalance = getNewBalance({
existingBalanceData
});
const newBalanceIsValid = getIfBalanceIsValid({
balance: calculatedBalance
});
if( !newBalanceIsValid ) {
throw new Error(
'unexpected error, ' +
'invalid balance after getNewBalance: ' +
calculatedBalance
);
}
return calculatedBalance;
});
module.exports = Object.freeze( async ({
userId,
balanceType,
balanceId,
state = null,
shouldDoOperationWithLock = true,
newBalance = null,
getNewBalance = null,
}) => {
if( balanceType === balanceTypes.bitcoinNodeIn ) {
if( !megaServerIdToMegaServerData[ balanceId ] ) {
throw new Error(
`unexpected error, invalid balance id: ${ balanceId }`
);
}
}
else if( balanceType === balanceTypes.normalWithdraw ) {
if( !normalWithdrawsIds[ balanceId ] ) {
throw new Error(
`unexpected error, invalid balance id: ${ balanceId }`
);
}
}
else {
throw new Error(
`unexpected error, invalid balance type: ${ balanceType }`
);
}
const newBalanceIsValid = getIfBalanceIsValid({
balance: newBalance
});
if(
(!newBalanceIsValid && !getNewBalance) ||
(newBalanceIsValid && !!getNewBalance)
) {
throw new Error(
`unexpected error, invalid new balance input`
);
}
console.log(
'running updateBalance --- ' +
`user: ${ userId }, ` +
`balance type: ${ balanceType }, ` +
`balance id: ${ balanceId }, ` +
`state: ${ state }, ` +
`shouldDoOperationWithLock: ${ shouldDoOperationWithLock }`
);
const doOperation = async () => {
const tableName = BALANCES;
const value = userId;
const existingBalanceData = await getDatabaseEntry({
tableName,
value
});
const amount = !getNewBalance ? newBalance : safeGetNewBalance({
existingBalanceData,
getNewBalance
});
console.log( `new amount is: ${ amount } BTC` );
const newBalanceData = getBalanceData({
amount,
state
});
/*
{
bitcoinNodeIn: {
abc: <new balance data>,
xyz: <existing balance data>,
},
normalWithdraw: {
abc: <existing balance data>,
xyz: <existing balance data>,
},
}
*/
const newBalanceEntry = Object.assign(
existingBalanceData,
{
[ balanceType ]: Object.assign(
existingBalanceData[ balanceType ],
{
[ balanceId ]: newBalanceData,
}
)
}
);
await updateDatabaseEntry({
tableName,
entry: newBalanceEntry,
});
};
if( shouldDoOperationWithLock ) {
await doOperationInQueue({
queueId: getQueueId({
type: BALANCES,
id: userId
}),
doOperation,
});
}
else {
await doOperation();
}
console.log( 'updateBalance successfully complete😄' );
});<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import { setState } from '../../../../../reduxX';
import makeStyles from '@material-ui/core/styles/makeStyles';
const getStyles = ({
backgroundColor,
}) => {
return {
gameBox: {
width: 250,
// height: 250,
backgroundColor,
marginTop: 25,
marginBottom: 20,
alignSelf: 'center',
borderRadius: 10,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
mainScreenHolder: {
borderRadius: 10,
width: '100%',
height: 214,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
bottomButton: {
width: '100%',
// height
backgroundColor: 'black',
color: 'white',
height: 36,
}
};
};
const useStyles = makeStyles({
root: {
width: '100%',
// height
backgroundColor: 'black',
color: 'white',
height: 36,
},
text: {
fontSize: 10,
}
});
export default ({
mainScreen = e(
Box,
{
style: {
width: '100%',
height: 214,
backgroundColor: 'white',
}
}
),
nameOfTheGame = 'Dino Game',
gameStateName = null,
smallButtonText = false,
backgroundColor = 'beige',
noActionOnClick = false,
}) => {
const styles = getStyles({
backgroundColor,
});
const buttonStyles = useStyles();
const onClick = noActionOnClick ? () => {} : () => {
setState({
keys: [
'notLoggedInMode',
'freeGame'
],
value: gameStateName
});
};
return e(
Paper,
{
style: styles.gameBox,
},
e(
Box,
{
style: styles.mainScreenHolder,
onClick,
},
mainScreen,
),
e(
Button,
{
classes: {
root: buttonStyles.root,
text: smallButtonText ? buttonStyles.text : undefined,
},
// style: styles.bottomButton,
// textStyle: {
// fontSize: 14,
// },
onClick,
},
nameOfTheGame
)
);
};
<file_sep>'use strict';
const {
withdraws: { states }
} = require( '../../constants' );
const stringify = require( '../stringify' );
const { formatting: { getAmountNumber } } = require( '../bitcoin' );
const getMoneyIn = Object.freeze( ({
balanceData
}) => {
// Source: bitcoin node in
const bitcoinNodeInBalanceIdToBalanceData = (
balanceData.bitcoinNodeIn
) || {};
const totalAmountIn = Object.values(
bitcoinNodeInBalanceIdToBalanceData
).map( ({ amount }) => amount ).reduce(
(amountA, amountB) => amountA + amountB, 0
);
return totalAmountIn;
});
const getMoneyOutData = Object.freeze( ({
balanceData
}) => {
// Source: normal withdraw
const bitcoinNormalWithdrawBalanceIdToBalanceData = (
balanceData.normalWithdraw
) || {};
let moneyOutIsInTransformationState = false;
const totalAmountOut = Object.values(
bitcoinNormalWithdrawBalanceIdToBalanceData
).map( ({ amount, state }) => {
if( state === states.complete ) {
return amount;
}
else if(
[
states.pending,
states.verifying
].includes( state )
) {
moneyOutIsInTransformationState = true;
return amount;
}
return 0;
}).reduce(
(amountA, amountB) => amountA + amountB, 0
);
return {
moneyOut: totalAmountOut,
moneyOutIsInTransformationState
};
});
module.exports = Object.freeze( ({
balanceData
}) => {
console.log(
`running getBalance with balance data: ${ stringify( balanceData ) }`
);
const moneyIn = getMoneyIn({ balanceData });
const {
moneyOut,
moneyOutIsInTransformationState
} = getMoneyOutData({ balanceData });
const balance = getAmountNumber( moneyIn - moneyOut );
console.log(
`getBalance executed successfully, here are the results: ` +
`${ stringify({
moneyIn,
moneyOut,
balance,
['🐲']: '🐉',
moneyOutIsInTransformationState
}) }`
);
return {
moneyOutIsInTransformationState,
balance
};
});<file_sep>'use strict';
const {
formatting: { getAmountNumber }
} = require( '../../bitcoin' );
const feeSumReducer = Object.freeze(
( accumulator, currentValue ) => accumulator + currentValue
);
const getBusinessFeeStringComponents = Object.freeze( ({
businessFeeData,
businessKeys,
businessFee,
}) => {
const businessFeeStringPart1 = `${ businessFee } BTC = `;
let businessFeeStringPart2 = '';
if( businessKeys.length === 0 ) {
businessFeeStringPart2 += `no business fee data specified`;
}
else {
for( const businessKey of businessKeys ) {
const businessValue = businessFeeData[ businessKey ];
businessFeeStringPart2 += `${ businessValue.amount } BTC (${ businessKey } fee) + `;
}
businessFeeStringPart2 = businessFeeStringPart2.substring(
0,
businessFeeStringPart2.length - 3
);
}
return {
businessFeeStringPart1,
businessFeeStringPart2,
};
});
module.exports = Object.freeze(
({
feeData: {
amount,
multiplier,
businessFeeData,
},
pleaseDoNotLogAnything = false,
shouldReturnAdvancedResponse = false
}) => {
const baseFee = getAmountNumber( amount * multiplier );
const businessKeys = Object.keys(
businessFeeData
);
const businessFee = getAmountNumber(
businessKeys.map( businessKey => {
const businessValue = businessFeeData[ businessKey ];
return businessValue.amount;
} ).reduce( feeSumReducer, 0 )
);
const feeToPay = getAmountNumber( baseFee + businessFee );
if( !pleaseDoNotLogAnything ) {
console.log( `
Getting Fee to Pay:
A) Base Fee (Blockchain Fee) = amount x multiplier
=> ${ baseFee } BTC = ${ amount } BTC x ${ multiplier }
`);
const {
businessFeeStringPart1,
businessFeeStringPart2,
} = getBusinessFeeStringComponents({
businessFeeData,
businessKeys,
businessFee
});
const fullBusinessFeeString = (
businessFeeStringPart1 + businessFeeStringPart2
);
console.log( `
B) Business Fee = sum of business fee data amounts
=> ${ fullBusinessFeeString }
`);
console.log(`
Fee to Pay = A) Base Fee + B) Business Fee
=> ${ feeToPay } BTC = ${ baseFee } (blockchain fee) BTC + ${ businessFeeStringPart2 } BTC
`);
}
if( shouldReturnAdvancedResponse ) {
return {
baseFee,
businessFee,
feeToPay
};
}
return feeToPay;
}
);<file_sep>'use strict';
const uuidv4 = require( 'uuid' ).v4;
module.exports = Object.freeze( () => {
const transactionId = (
`transaction_${ uuidv4().split( '-' ).join( '' ) }_${ Date.now() }`
);
return transactionId;
});<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser,
}
}
},
constants: {
transactions,
dreams,
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
random,
crypto: { getCryptoAmountNumber },
} = require( '../../../../../exchangeUtils' );
const minSlotNumber = 1;
const maxSlotNumber = 3;
const winMultiplier = 7;
const percentageToWin = 0.95;
const coinNumberMultiplier = 1000000;
const coinNumberThreshold = (1 - percentageToWin) * coinNumberMultiplier;
const flipCoin = Object.freeze( () => {
const coinNumber = random.getRandomIntegerInclusive({
min: 1,
max: coinNumberMultiplier
});
const hasWonThisChallengeOfFate = coinNumber > coinNumberThreshold;
console.log(
`⭑・゚゚・*:༅。.。༅:*゚:*:✼✿ ' +
'👑🐸 Flipping the 🎰Slot Coin ✿✼:*゚:༅。.。༅:*・゚゚・⭑\n` +
' - \n' +
'executed successfully: ' + stringify({
coinNumber,
hasWonThisChallengeOfFate
})
);
return hasWonThisChallengeOfFate;
});
const spinSlot = Object.freeze( ({
amount
}) => {
console.log(
`⭑・゚゚・*:༅。.。༅:*゚:*:✼✿ 🐑☢️ Spinning the Slot ✿✼:*゚:༅。.。༅:*・゚゚・⭑\n ` +
'value: ' + stringify({
amount,
})
);
const slotNumber1 = random.getRandomIntegerInclusive({
min: minSlotNumber,
max: maxSlotNumber
});
const slotNumber2 = random.getRandomIntegerInclusive({
min: minSlotNumber,
max: maxSlotNumber
});
const slotNumber3 = random.getRandomIntegerInclusive({
min: minSlotNumber,
max: maxSlotNumber
});
console.log(
'slotNumbers:',
stringify({
slotNumber1,
slotNumber2,
slotNumber3,
})
);
const results = {};
const hasWon = (
(slotNumber1 === slotNumber2) &&
(slotNumber2 === slotNumber3)
);
if( hasWon ) {
console.log( '🧑🎨has one level one checking if won for real' );
const hasWonForReal = flipCoin();
console.log(
`🧑🎨slot =>>>: ${ stringify({
hasWonForReal
})}`
);
if( hasWonForReal ) {
Object.assign(
results,
{
hasWonGame: true,
transactionAmount: getCryptoAmountNumber(
winMultiplier * amount
),
resultValues: {
slotNumbers: [
slotNumber1,
slotNumber2,
slotNumber3,
]
},
}
);
}
else {
Object.assign(
results,
{
hasWonGame: false,
transactionAmount: getCryptoAmountNumber(
-amount
),
resultValues: {
slotNumbers: [
slotNumber1,
(
(
slotNumber2 -
minSlotNumber +
1 // inc. amount
) % maxSlotNumber
) + minSlotNumber,
slotNumber3,
]
},
}
);
}
}
else if( // has tied
(slotNumber1 !== slotNumber2) &&
(slotNumber2 !== slotNumber3) &&
(slotNumber1 !== slotNumber3)
) {
console.log( `🧑🎨slot -> it's a tie🎀` );
Object.assign(
results,
{
hasWonGame: false,
hasTied: true,
transactionAmount: 0,
resultValues: {
slotNumbers: [
slotNumber1,
slotNumber2,
slotNumber3,
]
},
}
);
}
else { // has lost
console.log(
`🧑🎨slot -> lost😭`
);
Object.assign(
results,
{
hasWonGame: false,
transactionAmount: getCryptoAmountNumber( -amount ),
resultValues: {
slotNumbers: [
slotNumber1,
slotNumber2,
slotNumber3,
]
},
}
);
}
console.log(
`⭑・゚゚・*:༅。.。༅:*゚:*:✼✿ 🐑☢️ Spinning the Slot ✿✼:*゚:༅。.。༅:*・゚゚・⭑\n` +
' - \n' +
'executed successfully: ' + stringify( results )
);
return results;
});
module.exports = Object.freeze( async ({
amount,
exchangeUserId,
}) => {
console.log(
'running doEnchantedLuck ' +
`with the following values: ${ stringify({
amount,
exchangeUserId,
})}`
);
const {
hasWonGame,
transactionAmount,
hasTied = false,
resultValues,
} = spinSlot({
amount
});
const happyDream = hasWonGame;
await addTransactionAndUpdateExchangeUser({
noLocka: true,
exchangeUserId,
type: transactions.types.dream,
data: {
dreamType: dreams.types.slot,
amount: transactionAmount,
happyDream,
resultValues,
hasTied,
},
});
const luckResults = {
happyDream,
hasTied,
resultValues,
};
console.log(
'doEnchantedLuck executed successfully - ' +
`returning luck results: ${ stringify( luckResults ) }`
);
return luckResults;
});<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../reduxX';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import HelpOutlineIcon from '@material-ui/icons/HelpOutline';
import IconButton from '@material-ui/core/IconButton';
import { story } from '../../constants';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
titleTextMetaBox: {
width: '97%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
leftSpacerBox: {
width: 50,
height: 20,
// backgroundColor: 'purple',
},
titleTextBox: {
// backgroundColor: 'pink',
},
titleText: {
paddingTop: 5,
paddingBottom: 5,
color: 'black',
fontSize: 18,
textAlign: 'center',
// padding: 15,
},
iconButton: {
// backgroundColor: 'green',
},
icon: {
color: 'black',
},
};
};
export default () => {
const styles = getStyles();
const isLoading = getState( 'isLoading' );
return e(
Box,
{
style: styles.titleTextMetaBox
},
e(
Box,
{
style: styles.leftSpacerBox
},
),
e(
Box,
{
style: styles.titleTextBox
},
e(
Typography,
{
style: styles.titleText
},
'Referral ID'
)
),
e(
IconButton,
{
disabled: isLoading,
// 'aria-label': '',
style: styles.iconButton,
onClick: () => {
setState(
'dialogMode',
story.dialogModes.referralIdInfo
);
}
},
e(
HelpOutlineIcon,
{
style: styles.icon,
}
)
)
);
};
<file_sep>import { createElement as e } from 'react';
// import { setState } from '../../../../reduxX';
// import { validation } from '../../../../utils';
// import placeBet from './placeBet';
// import cancelBet from './cancelBet';
const getStyles = () => {
return {
polygon: {
width: '100%',
height: 300,
backgroundColor: 'yellow',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
polygonText: {
padding: 10,
color: 'black',
}
};
};
export default ({
currentAmount,
currentChoice
}) => {
const styles = getStyles();
return e(
'div',
{
style: styles.polygon
},
e(
'div',
{
style: styles.polygonText
},
(currentAmount !== 0) ? (
'Voting period has ended, ' +
'Waiting for payout if won - ' +
`current bet is ${ currentAmount } Cryptos ` +
`on ${ currentChoice }.`
) : (
`Voting period has ended, no more votes are allowed.`
)
)
);
};
<file_sep>'use strict';
// can use common-api
module.exports = Object.freeze( ({
time,
}) => {
if(
(typeof time === 'number') &&
Number.isInteger( time ) &&
(time >= 1) &&
(time <= 99678647379534)
) {
return true;
}
return false;
});<file_sep>import { delay } from '../../../../utils';
const win = 'win';
let operationQueue = Promise.resolve({
previousAction: win,
});
const doAction = async ({
action,
previousAction,
}) => {
await delay({ timeout: 50 });
const box = document.querySelector( '.TheDinocoin-Box' );
while( box.classList.length > 1 ) {
box.classList.remove( box.classList[ box.classList.length - 1 ] );
}
if( previousAction !== win ) {
box.classList.add( 'action-reset-back' );
}
else {
box.classList.add( 'action-reset' );
}
await delay({ timeout: 500 });
box.classList.add( `action-${ action }` );
await delay({ timeout: 3100 });
return { previousAction: action };
};
export default ({
action,
}) => {
operationQueue = operationQueue.then( async ({
previousAction,
}) => {
try {
const doActionResults = await doAction({
action,
previousAction,
});
return {
previousAction: doActionResults.previousAction,
};
}
catch( err ) {
console.log( 'error in doing spin action:', err );
return {
previousAction: win,
};
}
});
};<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'pink',
width: '100%',
// display: 'flex',
// justifyContent: 'center',
// flexDirection: 'column',
// alignItems: 'center'
},
explanationText: {
width: '90%',
// color: 'white',
color: 'black',
textAlign: 'left',
fontSize: 16,
marginTop: 10,
marginBottom: 10,
marginLeft: 15,
}
};
};
const aboutWithdrawText = Object.freeze([
`the minimum withdraw amount for standard withdraws is 0.00004 BTC`,
`the minimum withdraw amount for full balance withdraws is 0.00025 BTC`,
`the only fee is the Bitcoin network fee (the blockchain fee)`,
`the withdraw system aims to minimize the actual blockchain fee used`,
`the "Blockchain Fee Estimate" is an estimate of the fee to be used and it's generally an overestimate; while performing a withdraw the withdraw system aims to set the actual fee used to be lower than what's estimated`,
`the actual fee will not be more than the fee estimate`,
`if the actual fee used for a withdraw is less than the fee estimate, whatever amount that's reserved for the fee estimate which is not used to cover the actual fee will automatically be refunded after the withdraw is made`,
`the "Estimated Total Withdraw Amount" is also considered an estimate because it contains the fee estimate`,
`the fee is included in the withdraw amount while withdrawing your full balance amount`,
`full balance amount withdraws also aim to minimize the fee used, if the actual fee used for a full balance amount withdraw is less than the fee estimate, then the unused Bitcoin amount reserved for the fee estimate will be sent along with the withdraw in addition to the withdraw amount`,
`please contact <EMAIL> if you have any difficulties withdrawing your Bitcoin`
]);
export default () => {
const styles = getStyles();
const textElements = aboutWithdrawText.map( text => {
return e(
Typography,
{
style: styles.explanationText,
},
`• ${ text }`
);
});
return e(
Box,
{
style: styles.outerContainer,
},
...textElements
// e(
// Typography,
// {
// style: styles.text,
// },
// 'Our mission at DynastyBitcoin.com is to provide ' +
// 'a high quality crypto game platform with modern crypto games.'
// )
);
};
<file_sep>'use strict';
const queueIdSeparator = '___';
module.exports = Object.freeze(
({ type, id }) => {
if( !id ) {
throw new Error( 'getQueueId error: missing id' );
}
else if( !type ) {
throw new Error( 'getQueueId error: missing type' );
}
return (
`queue${ queueIdSeparator }${ type }${ queueIdSeparator }${ id }`
);
}
);<file_sep>export default ({
text,
maxAmount = 69,
allowedNumberOfDecimals = 8,
})=> {
const textAsNumber = Number( text );
if(
Number.isNaN( textAsNumber ) ||
(textAsNumber > maxAmount) ||
text.startsWith( '00' ) ||
(
(text.length > 1) &&
text.startsWith( '0' ) &&
text[1] !== ( '.' )
)
) {
return false;
}
const periodSplitText = text.split( '.' );
if(
(periodSplitText.length === 2) &&
periodSplitText[1].length > allowedNumberOfDecimals
) {
return false;
}
return true;
};
<file_sep>'use strict';
const {
utils: {
stringify,
business: {
getIsValidWithdrawAmount
},
bitcoin: {
validation: { getIsValidAddress },
formatting: { getAmountNumber }
}
},
constants: {
// environment: {
// isProductionMode
// }
withdraws: {
limits: {
maximumWithdrawAmount,
minimumWithdrawAmount
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
errors: { ValidationError },
business: {
verifyGoogleCode,
},
constants: {
google: {
captcha: {
actions
}
}
}
} = require( '../../../../../utils' );
// const minimumWithdrawAmount = 0.00004;
const validateAndGetEnviroWithdrawAmount = Object.freeze( ({
rawEnviroWithdrawAmount
}) => {
if( !rawEnviroWithdrawAmount ) {
return 0;
}
if( typeof rawEnviroWithdrawAmount !== 'number' ) {
const validationError = new ValidationError(
`invalid enviroWithdrawAmount: ${ rawEnviroWithdrawAmount }`
);
validationError.bulltrue = true;
throw validationError;
}
if(
(rawEnviroWithdrawAmount < 0) ||
(rawEnviroWithdrawAmount > 69)
) {
const validationError = new ValidationError(
`invalid enviroWithdrawAmount: ${ rawEnviroWithdrawAmount }`
);
validationError.bulltrue = true;
throw validationError;
}
return rawEnviroWithdrawAmount;
});
module.exports = Object.freeze( async ({
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount,
rawShouldDoFullWithdraw,
ipAddress,
rawGoogleCode,
}) => {
console.log(
`running validateAndGetValues with values: ${ stringify({
rawAmount,
rawShouldIncludeFeeInAmount,
rawAddress,
rawEnviroWithdrawAmount,
rawShouldDoFullWithdraw,
ipAddress,
rawGoogleCode,
})}`
);
const withdrawAmount = getAmountNumber( rawAmount );
if(
!rawAddress ||
!getIsValidAddress( rawAddress )
) {
const validationError = new ValidationError(
`invalid withdraw address: ${ rawAddress }`
);
validationError.bulltrue = true;
throw validationError;
}
else if( typeof rawShouldIncludeFeeInAmount !== 'boolean' ) {
const validationError = new ValidationError(
`invalid includeFeeInAmount value: ${
rawShouldIncludeFeeInAmount
}`
);
validationError.bulltrue = true;
throw validationError;
}
else if( typeof rawShouldDoFullWithdraw !== 'boolean' ) {
const validationError = new ValidationError(
`invalid fullWithdraw value: ${
rawShouldDoFullWithdraw
}`
);
validationError.bulltrue = true;
throw validationError;
}
const enviroWithdrawAmount = validateAndGetEnviroWithdrawAmount({
rawEnviroWithdrawAmount
});
const results = {
addressToSendTo: rawAddress,
shouldIncludeFeeInAmount: rawShouldIncludeFeeInAmount,
enviroWithdrawAmount,
shouldDoFullWithdraw: rawShouldDoFullWithdraw,
};
if( !rawShouldDoFullWithdraw ) {
const theWithdrawAmountIsInvalid = !getIsValidWithdrawAmount({
withdrawAmount
});
if( theWithdrawAmountIsInvalid ) {
const validationError = new ValidationError(
`invalid withdraw amount: ${ withdrawAmount }`
);
validationError.bulltrue = true;
throw validationError;
}
if(
(withdrawAmount < minimumWithdrawAmount) ||
(withdrawAmount > maximumWithdrawAmount)
) {
const validationError = new ValidationError(
`Invalid withdraw amount: ${ withdrawAmount } BTC.`
);
validationError.bulltrue = true;
throw validationError;
}
results.withdrawAmount = withdrawAmount;
}
await verifyGoogleCode({
rawGoogleCode,
ipAddress,
expectedAction: actions.withdraw,
});
console.log(
'validateAndGetValues executed successfully, ' +
'here are the values: ' +
stringify( results )
);
return results;
});
<file_sep>'use strict';
const getAddressDatum = require( './getAddressDatum' );
const updateAddressAmount = require( './updateAddressAmount' );
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser
}
}
},
constants: {
transactions: {
types
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
mongo,
backgroundExecutor,
} = require( '@bitcoin-api/full-stack-backend-private' );
const getAddressCacheObject = Object.freeze( ({
isLegacy = false,
legacyData = null,
lastUpdateData = null,
}) => ({
isLegacy,
legacyData,
lastUpdateData,
}));
const addCacheValue = Object.freeze( async ({
mongoCollections,
isLegacy,
legacyData,
lastUpdateData,
address
}) => {
const params = {};
if( !!isLegacy ) {
params.isLegacy = isLegacy;
}
if( !!lastUpdateData ) {
params.lastUpdateData = lastUpdateData;
}
if( !!legacyData ) {
params.legacyData = legacyData;
}
await mongo.update({
collection: mongoCollections.address_data,
query: {
address,
},
newValue: {
$set: getAddressCacheObject( params )
},
});
});
const addAddressToLegacyCache = Object.freeze( async ({
address,
amount,
mongoCollections,
}) => {
console.log(
'running addAddressToLegacyCache: ' +
`adding address ${ address } as ` +
'legacy address to cache'
);
await addCacheValue({
address,
mongoCollections,
isLegacy: true,
legacyData: {
amount
}
});
console.log(
'addAddressToLegacyCache: ' +
'💾legacy or unused address with money found in ' +
'bitcoin node, not processing it - ' +
'addAddressToLegacyCache executed successfully'
);
});
const updateAddressDinoAndAddToCache = Object.freeze( async ({
address,
amount,
existingAddressDatum,
mongoCollections,
}) => {
const { userId } = existingAddressDatum;
await updateAddressAmount({
userId,
address,
amount,
});
console.log(
`adding address ${ address } - last update data - to cache`
);
await addCacheValue({
address,
mongoCollections,
lastUpdateData: {
amount,
userId
}
});
const isExchangeUserAddress = (
!!existingAddressDatum.isExchangeAddress &&
!!existingAddressDatum.exchangeUserId
);
if( isExchangeUserAddress ) {
console.log(
`address ${ address } is an exchange user address - ` +
'adding add bitcoin transaction'
);
backgroundExecutor.addOperation({
operation: async () => {
await addTransactionAndUpdateExchangeUser({
exchangeUserId: existingAddressDatum.exchangeUserId,
type: types.addBitcoin,
data: {
address,
amount
}
});
}
});
}
});
const updateUserIdToBitcoinNodeAmountIn = Object.freeze( ({
userId,
amount,
userIdToBitcoinNodeAmountIn
}) => {
userIdToBitcoinNodeAmountIn[ userId ] = (
userIdToBitcoinNodeAmountIn[ userId ] || 0
);
userIdToBitcoinNodeAmountIn[ userId ] += amount;
});
const cachedAddressDatumStatuses = Object.freeze({
storyUntold: 'storyUntold',
unchangedLegacy: 'unchangedLegacy',
improvedLegacy: 'improvedLegacy',
sameFresh: 'sameFresh',
improvedFresh: 'improvedFresh',
});
const getCacheStatus = Object.freeze( ({
canonicalAddressDatum,
cachedAddressDatum
}) => {
const { address } = canonicalAddressDatum;
console.log(
'getting cache status using the following info: ' +
stringify({
['the address']: address,
['cached address datum']: (
cachedAddressDatum || 'no cached address datum'
),
['canonical address datum']: canonicalAddressDatum
})
);
if( !cachedAddressDatum ) {
return cachedAddressDatumStatuses.storyUntold;
}
else if( cachedAddressDatum.isLegacy ) {
if(
cachedAddressDatum.legacyData.amount ===
canonicalAddressDatum.amount
) {
return cachedAddressDatumStatuses.unchangedLegacy;
}
return cachedAddressDatumStatuses.improvedLegacy;
}
else if(
!!cachedAddressDatum.lastUpdateData &&
(
cachedAddressDatum.lastUpdateData.amount ===
canonicalAddressDatum.amount
) &&
!!cachedAddressDatum.lastUpdateData.userId // safeguard
) {
return cachedAddressDatumStatuses.sameFresh;
}
return cachedAddressDatumStatuses.improvedFresh;
});
const getCacheInfo = Object.freeze( async ({
canonicalAddressDatum,
mongoCollections
}) => {
console.log( 'running getCacheInfo' );
const {
address,
// amount
} = canonicalAddressDatum;
const cachedAddressDatum = (
await mongo.search({
collection: mongoCollections.address_data,
query: {
address,
},
queryOptions: {
limit: 1,
}
})
)[0];
const cacheStatus = getCacheStatus({
canonicalAddressDatum,
cachedAddressDatum
});
const cacheInfo = {
cacheStatus,
cachedAddressDatum
};
console.log(
'getCacheInfo executed successfully, got cache info:',
stringify( cacheInfo )
);
return cacheInfo;
});
// NOTE: add helpers and stories for modularization
const updateAddressDatum = Object.freeze( async ({
canonicalAddressDatum,
mongoCollections,
userIdToBitcoinNodeAmountIn
}) => {
console.log(
'running updateAddressDatum ' +
`with the following values: ${ stringify({
canonicalAddressDatum,
}) }`
);
console.log(
'updateAddressDatum: ' +
'if necessary, updating the following address data with ' +
`the following values: ${ stringify( canonicalAddressDatum ) }`
);
const {
address,
amount
} = canonicalAddressDatum;
const {
cacheStatus,
cachedAddressDatum
} = await getCacheInfo({
canonicalAddressDatum,
mongoCollections
});
if( cacheStatus === cachedAddressDatumStatuses.storyUntold ) {
const existingAddressDatum = await getAddressDatum({
address
});
if( !existingAddressDatum ) {
console.log(
'🦉updateAddressDatum: ' +
'🦉legacy address not in cache case - ' +
'adding legacy address to cache'
);
await addAddressToLegacyCache({
address,
mongoCollections,
amount,
});
return console.log(
'updateAddressDatum ' +
`executed successfully - ${ address } - 🦉`
);
}
const { userId } = existingAddressDatum;
// const addressShouldBeReclaimed = getIfAddressShouldBeReclaimed({
// addressDatum: existingAddressDatum
// });
// if( addressShouldBeReclaimed ) {
// console.log(
// `🐞address ${ address } should be reclaimed🐞 - ` +
// 'removing the dino ' +
// 'entry and adding to legacy cache'
// );
// await removeDatabaseEntry({
// tableName: ADDRESSES,
// keyObject: {
// userId,
// address,
// }
// });
// await addAddressToLegacyCache({
// address,
// mongoCollections,
// amount,
// });
// return console.log(
// 'updateAddressDatum ' +
// `executed successfully - ${ address } - 🐞`
// );
// }
console.log(
'🐺updateAddressDatum: ' +
'🐺live address not in cache case - '+
'updating amount and adding to cache'
);
await updateAddressDinoAndAddToCache({
address,
amount,
existingAddressDatum,
mongoCollections,
});
updateUserIdToBitcoinNodeAmountIn({
userId,
amount,
userIdToBitcoinNodeAmountIn
});
return console.log(
'updateAddressDatum ' +
`executed successfully - ${ address } - 🐺`
);
}
else if( cacheStatus === cachedAddressDatumStatuses.unchangedLegacy ) {
console.log(
'📞cache call📞 - ' +
'updateAddressDatum: ' +
'💾legacy or unused address with money found in ' +
'bitcoin node, not processing it - ' +
`address: ${ address }`
);
return console.log(
'updateAddressDatum ' +
`executed successfully - ${ address } - 📞`
);
}
else if( cacheStatus === cachedAddressDatumStatuses.improvedLegacy ) {
// NOTE: case - reclaimed address and next address owner added money
console.log(
'♞♘addAddressToLegacyCache♘♞ ' +
'an improved legacy ♘♞- ' +
'amount in legacy address increased, ' +
'removing cache value and running updateAddressDatum again'
);
await mongo.remove({
collection: mongoCollections.address_data,
query: {
address,
},
});
console.log(
'updateAddressDatum ' +
`executed successfully (running again) - ${ address } - ♘♞`
);
return await updateAddressDatum({
canonicalAddressDatum,
mongoCollections,
userIdToBitcoinNodeAmountIn
});
}
else if( cacheStatus === cachedAddressDatumStatuses.sameFresh ) {
console.log(
'🐲updateAddressDatum: ' +
'🐲live address already in cache with same amount'
);
updateUserIdToBitcoinNodeAmountIn({
userId: cachedAddressDatum.lastUpdateData.userId,
amount,
userIdToBitcoinNodeAmountIn
});
console.log(
'updateAddressDatum: ' +
`address ${ address } is already up-to-date - no-op`
);
return console.log(
'updateAddressDatum ' +
`executed successfully - ${ address } - 🐲`
);
}
else if( cacheStatus === cachedAddressDatumStatuses.improvedFresh ) {
console.log(
'🐸updateAddressData: ' +
`🐸updating live address ${ address } with new amount ` +
amount +
' - the case is updating an address ' +
'that already existed in cache'
);
const existingAddressDatum = await getAddressDatum({
address
});
await updateAddressDinoAndAddToCache({
address,
amount,
existingAddressDatum,
mongoCollections,
});
updateUserIdToBitcoinNodeAmountIn({
userId: existingAddressDatum.userId,
amount,
userIdToBitcoinNodeAmountIn
});
return console.log(
'updateAddressDatum ' +
`executed successfully - ${ address } - 🐸`
);
}
throw new Error(
`weird error, unexpected cache status: ${ cacheStatus }`
);
});
module.exports = updateAddressDatum;<file_sep>'use strict';
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser
}
},
},
constants: {
// aws: {
// database: {
// tableNames: {
// EXCHANGE_USERS
// }
// }
// },
transactions: {
types,
bitcoinWithdrawTypes
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
utils: {
stringify,
// doOperationInQueue,
// javascript: {
// getQueueId
// },
aws: {
dino: {
getDatabaseEntry,
}
},
database:{
metadata: {
metaGetFeeToPayFromFeeData
}
}
},
constants: {
aws: {
database: {
tableNames: {
WITHDRAWS
}
}
},
withdraws: {
states
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const addTransactionAndUpdateExchangeUserDeluxeCore = Object.freeze( async ({
userId,
ultraKey,
}) => {
const {
exchangeUserId,
addressToSendTo,
amount,
shouldIncludeFeeInAmount,
feeData,
withdrawId,
state
} = await getDatabaseEntry({
tableName: WITHDRAWS,
value: userId,
sortValue: ultraKey
});
const metaFeeToPay = metaGetFeeToPayFromFeeData(
{
shouldIncludeFeeInAmount
},
{
feeData,
}
);
const bitcoinWithdrawType = (
state === states.complete
) ? bitcoinWithdrawTypes.success : bitcoinWithdrawTypes.failed;
await addTransactionAndUpdateExchangeUser({
exchangeUserId,
type: types.withdrawBitcoin,
data: {
address: addressToSendTo,
amount,
fee: metaFeeToPay,
withdrawId,
bitcoinWithdrawType,
feeIncludedInAmount: shouldIncludeFeeInAmount,
},
});
});
module.exports = Object.freeze( async ({
exchangeUserId,
userId,
ultraKey
}) => {
console.log(
'running addTransactionAndUpdateExchangeUserDeluxe with ' +
`the following values: ${ stringify({
exchangeUserId,
userId,
ultraKey,
})}`
);
// await doOperationInQueue({
// queueId: getQueueId({ type: EXCHANGE_USERS, id: exchangeUserId }),
// doOperation: async () => {
await addTransactionAndUpdateExchangeUserDeluxeCore({
userId,
ultraKey,
});
// }
// });
console.log(
'addTransactionAndUpdateExchangeUserDeluxe ' +
'executed successfully'
);
});
<file_sep>import { createElement as e } from 'react';
// import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import { moneyActions } from '../../../../constants';
const getStyles = ({
dialogMode
}) => {
const {
color,
} = dialogMode ? {
color: 'white',
} : {
color: 'black',
};
// const mainStyleObject = getState( 'mainStyleObject' );
return {
amountText: {
color,
fontSize: 14,
marginLeft: 5,
marginTop: 3,
},
};
};
export default ({
excitingElements,
moneyAction,
dialogMode,
}) => {
const styles = getStyles({
dialogMode,
});
if(
moneyAction.type ===
moneyActions.types.regal.exchange.btcToCrypto
) {
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
'BTC spent: ' +
`${ moneyAction.amountInBTCNeeded } BTC`
),
e(
Typography,
{
style: styles.amountText
},
'DB acquired: ' +
`${ moneyAction.amountInCryptoWanted } DB`
),
);
}
else if(
moneyAction.type ===
moneyActions.types.regal.exchange.cryptoToBTC
) {
excitingElements.push(
e(
Typography,
{
style: styles.amountText
},
'DB spent: ' +
`${ moneyAction.amountInCryptoNeeded } DB`
),
e(
Typography,
{
style: styles.amountText
},
'BTC acquired: ' +
`${ moneyAction.amountInBitcoinWanted } BTC`
),
);
}
};
<file_sep>'use strict';
const withdrawMoney = require( './withdrawMoney' );
const {
getFormattedEvent,
beginningDragonProtection,
getResponse,
handleError,
stringify
} = require( '../../../utils' );
const fiveMinutes = 5 * 60 * 1000;
exports.handler = Object.freeze( async rawEvent => {
console.log( 'running /withdraws - POST function' );
try {
const event = getFormattedEvent({
rawEvent,
shouldGetBodyFromEvent: true,
});
const { user } = await beginningDragonProtection({
queueName: 'withdrawMoney',
event,
necessaryDragonDirective: 2,
ipAddressMaxRate: 10,
ipAddressTimeRange: fiveMinutes,
advancedCodeMaxRate: 10,
advancedCodeTimeRange: fiveMinutes,
});
const withdrawMoneyResults = await withdrawMoney({
event,
user
});
const response = getResponse({ body: withdrawMoneyResults });
console.log(
'/withdraws - POST function executed successfully ' +
`returning values: ${ stringify( response ) }`
);
return response;
}
catch( err ) {
console.log( 'error in request to /withdraws - POST:', err );
return handleError( err );
}
});
<file_sep>import { createElement as e, useEffect, useState } from 'react';
import {
usefulComponents,
} from '../../TheSource';
import {
getState
} from '../../reduxX';
import { actions } from '../../utils';
import { pages, gameData, games } from '../../constants';
import TitleBox from './TitleBox';
import Box from '@material-ui/core/Box';
import Paper from '@material-ui/core/Paper';
import Divider from '@material-ui/core/Divider';
import ModeSection from './ModeSection';
import TheDinocoin from './TheDinocoin';
import CoinFlipCommandCenter from './CoinFlipCommandCenter';
const gameModes = gameData[ games.theDragonsTalisman ].modes;
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
metaContainer: {
maxWidth: 620,
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
outerContainer: {
// backgroundColor: 'beige',
backgroundColor: 'black',
// maxWidth: 620,
width: '100%',
marginTop: 20,
// height: 300,
// borderRadius: '50%',
// backgroundColor: 'pink',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
dataBar: {
maxWidth: 320,
width: '100%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
divider: {
backgroundColor: 'black',
width: '100%'
}
};
};
export default ({
freeGameMode = false,
// lotusDreamsMode = false,
}) => {
const [ noDinoCoin, setNoDinoCoin ] = useState( false );
useEffect( () => {
actions.scroll();
actions.setLastVisitedPage({
loggedInMode: true,
page: pages.loggedInMode.coinFlip,
});
}, [] );
const styles = getStyles();
// const subtitleText = 'Coin Toss Game';
const coinFlipMode = getState(
'loggedInMode',
'coinFlip',
'mode'
);
const isJackpotMode = coinFlipMode === gameModes.jackpot;
return e(
Box,
{
style: styles.metaContainer,
},
e(
Paper,
{
style: styles.outerContainer,
},
e(
TitleBox,
{
noDinoCoin,
setNoDinoCoin
}
),
e(
Divider,
{
style: styles.divider
}
),
noDinoCoin ? e(
Box,
{
style: {
height: 30,
width: 20,
}
}
) : e( TheDinocoin ),
e(
Box,
{
style: styles.dataBar,
},
e(
ModeSection,
{
freeGameMode,
isJackpotMode,
}
),
e(
usefulComponents.crypto.CurrentAmount,
{
backgroundColor: 'lightGreen',
// color: 'white',
fontWeight: 'normal',
// height: 35,
height: 85,
// width: '40%',
freeGameMode,
borderRadius: 5,
balanceFontSize: 16,
// width: '90%',
maxWidth: 140,
// noTitleText: true,
textVersion: 'c',
}
)
),
e(
CoinFlipCommandCenter,
{
freeGameMode,
isJackpotMode,
}
)
)
);
};
<file_sep>'use strict';
module.exports = Object.freeze({
// lambda: require( './lambda' ),
ses: require( './ses' ),
dino: require( './dino' ),
dinoCombos: require( './dinoCombos' ),
});
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
aws: {
dinoCombos: {
emails: {
ensureEmailIsNotBlocked,
}
}
}
} = require( '../../../../../exchangeUtils' );
const {
constants: {
http: {
headers
},
// google: {
// captcha
// }
}
} = require( '../../../../../utils' );
const validateAndGetValues = require( './validateAndGetValues' );
const ensureVerificationRequestIsValid = require( './ensureVerificationRequestIsValid' );
const verifyUserEmail = require( './verifyUserEmail' );
const doLogin = require( '../../../../../sacredElementals/crypto/doLogin' );
module.exports = Object.freeze( async ({
event,
ipAddress
}) => {
const rawEmail = event.headers.email;
const rawPassword = event.headers.password;
const rawVerifyEmailCode = event.headers[ headers.verifyEmailCode ];
const rawGoogleCode = event.headers[ headers.grecaptchaGoogleCode ];
console.log(
`running verifyUser with the following values - ${ stringify({
rawEmail,
rawPassword,
rawVerifyEmailCode,
rawGoogleCode
}) }`
);
const {
email,
password,
verifyEmailCode
} = await validateAndGetValues({
rawEmail,
rawPassword,
rawVerifyEmailCode,
rawGoogleCode,
ipAddress
});
await ensureEmailIsNotBlocked({
email,
});
const {
exchangeUserId,
} = await ensureVerificationRequestIsValid({
email,
password,
verifyEmailCode
});
await verifyUserEmail({
email,
password,
verifyEmailCode,
ipAddress,
exchangeUserId
});
console.log( '🦩verify user - performing login' );
const doLoginResults = await doLogin({
event,
ipAddress,
});
console.log( '🦩verify user - login performed successfully' );
const verifyUserResponse = Object.assign(
{},
doLoginResults
);
console.log(
'verifyUser executed successfully - ' +
`returning values: ${ stringify( verifyUserResponse ) }`
);
return verifyUserResponse;
});
<file_sep>'use strict';
module.exports = Object.freeze({
createLoginToken: require( './createLoginToken' ),
mongolianBeginningDragonProtection: require( './mongolianBeginningDragonProtection' ),
getSignedOutLoginToken: require( './getSignedOutLoginToken' ),
});
<file_sep>'use strict';
module.exports = Object.freeze({
getBalance: require( './getBalance' ),
getBalanceData: require( './getBalanceData' ),
getIsValidWithdrawAmount: require( './getIsValidWithdrawAmount' ),
});<file_sep># Bitcoin-Api Web App Frontend
-> need to improve frontend appearance (material UI)
-> home page explanation
-> FAQ
-> terms of service
have a vote-bet type event
data ->
put money down
take money off
-> on event date
if money down
if right
payout
if wrong
no-op
---
event:
add bet - amount
remove bet
<file_sep>'use strict';
const uuidv4 = require( 'uuid/v4' );
const getBaseId = Object.freeze( () => uuidv4().split( '-' ).join( '' ) );
module.exports = Object.freeze( ({
baseId = getBaseId(),
} = {
baseId: getBaseId()
}) => {
const exchangeUserId = (
`exchange_user_${ baseId }`
);
const exchangeUserIdData = {
baseId,
exchangeUserId
};
return exchangeUserIdData;
});<file_sep>'use strict';
const {
utils: {
redis: {
rhinoCombos: {
giraffeAndTreeStatusUpdate
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze({
giraffeAndTreeStatusUpdate,
constants: require( './constants' ),
listenForEventsAndExecuteActions: require( './listenForEventsAndExecuteActions' ),
getTimeInfo: require( './getTimeInfo' ),
sendErrorToDeployStreamOnControlC: require( './sendErrorToDeployStreamOnControlC' ),
});<file_sep>'use strict';
const {
utils: {
// stringify,
// },
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
http: {
headers
}
},
throwStandardError,
} = require( '../../../../../../utils' );
const {
aws: {
dinoCombos: {
emails: {
ensureEmailIsNotBlocked
}
}
},
exchangeUsers: {
getExchangeUserByEmail,
}
} = require( '../../../../../../exchangeUtils' );
const validateAndGetValues = require( './validateAndGetValues' );
// const getPasswordResetCode = require( './getPasswordResetCode' );
const updateExchangeUser = require( './updateExchangeUser' );
const sendPasswordResetEmail = require( './sendPasswordResetEmail' );
module.exports = Object.freeze( async ({
event,
email,
ipAddress,
}) => {
const rawGoogleCode = event.headers[ headers.grecaptchaGoogleCode ];
console.log(
'running initiatePasswordReset with the following values:',
stringify({
rawGoogleCode: !!rawGoogleCode,
ipAddress
})
);
await validateAndGetValues({
rawGoogleCode,
ipAddress
});
await ensureEmailIsNotBlocked({
email
});
const exchangeUser = await getExchangeUserByEmail({
email,
});
if( !exchangeUser ) {
return throwStandardError({
logMessage: (
'😲error in initiatePasswordReset ' +
'user with email does not exist: ' +
stringify({
email
})
),
message: `user with email "${ email }" does not exist`,
statusCode: 404,
bulltrue: true,
});
}
const { exchangeUserId, displayEmail } = exchangeUser;
// const passwordResetCode = getPasswordResetCode({
// exchangeUserId,
// });
const {
passwordResetCode
} = await updateExchangeUser({
exchangeUserId,
// passwordResetCode,
});
await sendPasswordResetEmail({
email,
displayEmail,
passwordResetCode,
});
const initiatePasswordResetResults = {
passwordResetHasBeenSuccessfullyInitialized: true,
};
console.log(
'initiatePasswordReset executed successfully: ' +
stringify( initiatePasswordResetResults )
);
return initiatePasswordResetResults;
});<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const getExchangeUser = require( '../getExchangeUser' );
module.exports = Object.freeze( async ({
exchangeUserId,
}) => {
console.log(
'running ensureExchangeUserExistsAndGet with the following values: ' +
stringify({
exchangeUserId,
})
);
const exchangeUser = await getExchangeUser({
exchangeUserId,
});
if( !exchangeUser ) {
throw new Error(
'addTransactionAndUpdateExchangeUser - ' +
'ensureExchangeUserExistsAndGet error: ' +
`exchange user with id "${ exchangeUserId } does not exist!🙀`
);
}
console.log(
'ensureExchangeUserExistsAndGet executed successfully - ' +
'exchange user exists🖖'
);
return exchangeUser;
});
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
random,
} = require( '../../../../../../exchangeUtils' );
const percentageToWin = 0.495;
const coinNumberMultiplier = 1000000;
const coinNumberThreshold = (1 - percentageToWin) * coinNumberMultiplier;
module.exports = Object.freeze( () => {
console.log(
`⭑・゚゚・*:༅。.。༅:*゚:*:✼✿ 🌸🐲 Flipping the 🌸Lotus Coin ✿✼:*゚:༅。.。༅:*・゚゚・⭑\n` +
' - \n' +
`need to get coinNumber higher than or equal to ${ coinNumberThreshold }`
);
const coinNumber = random.getRandomIntegerInclusive({
min: 1,
max: coinNumberMultiplier
});
const hasWonThisChallengeOfFate = coinNumber > coinNumberThreshold;
console.log(
`⭑・゚゚・*:༅。.。༅:*゚:*:✼✿ ' +
'👑🐸 Flipping the 🌸Lotus Coin ✿✼:*゚:༅。.。༅:*・゚゚・⭑\n` +
' - \n' +
'executed successfully: ' + stringify({
coinNumber,
hasWonThisChallengeOfFate
})
);
return hasWonThisChallengeOfFate;
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase,
}
},
stringify,
},
constants: {
aws: {
database: {
tableNames: { ADDRESSES },
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const updateAlienBalanceDatum = require( './updateAlienAddressDatum' );
const searchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
exchangeUserId: '#exchangeUserId',
}),
nameValues: f({
exchangeUserId: 'exchangeUserId',
}),
valueKeys: f({
exchangeUserId: ':exchangeUserId',
}),
});
const alien = 'alien';
module.exports = Object.freeze( async () => {
console.log(
'running updateAlienBalanceData ' +
`with the following values - ${ stringify({}) }`
);
let paginationValueToUse = null;
let iterationCount = 0;
do {
console.log(
'updateAlienBalanceData - ' +
'running address search: ' +
stringify({
paginationValueToUse,
iterationCount,
})
);
const searchParams = {
TableName: ADDRESSES,
// IndexName: addressIndex,
Limit: searchLimit,
// ScanIndexForward: true,
// ProjectionExpression: [
// // attributes
// ].join( ', ' ), // TODO:
KeyConditionExpression: (
`${ attributes.nameKeys.exchangeUserId } = ` +
`${ attributes.valueKeys.exchangeUserId }`
),
// FilterExpression: (),
ExpressionAttributeNames: {
[attributes.nameKeys.exchangeUserId]: attributes.nameValues.exchangeUserId,
},
ExpressionAttributeValues: {
[attributes.valueKeys.exchangeUserId]: alien,
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const alienAddressData = ultimateResults;
for( const alienAddressDatum of alienAddressData ) {
await updateAlienBalanceDatum( alienAddressDatum );
}
if( !!paginationValue ) {
paginationValueToUse = paginationValue;
iterationCount++;
}
else if( !!paginationValueToUse ) {
paginationValueToUse = null;
}
} while( !!paginationValueToUse );
});
<file_sep>import ArgonInformation from './ArgonInformation';
import { createElement as e } from 'react';
export default () => {
return e(
ArgonInformation,
{
title: 'Privacy Policy',
lastUpdatedDate: 'July 1st 2020',
titleContentsAndMore: [
{
title: 'Scope',
contents: (
'This is the Privacy Policy of the technology company DynastyBitcoin.com. DynastyBitcoin.com will be referred to in this document as "DB". "You", "your", the "user", or the "customer" will refer to anyone who uses DB services. This Privacy Policy describes how DB handles your data and personally identifiable information when using DB technology including the DynastyBitcoin.com website, or any other service provided by DB.'
),
},
{
contents: (
`The purpose of this policy is to explain how DB gathers and uses data and how the collected and processed data is secure for DB customers.`
),
},
{
title: 'Acceptance of Privacy Policy',
contents: (
'In using the services provided by DB, you are in agreement with the Privacy Policy. If you do not agree to or are unable to agree to the Privacy Policy, you should cease to use DB and its services immediately.'
),
},
{
title: 'Changes to the Privacy Policy',
contents: (
'The Privacy Policy of DB can be modified at any time. When modified, the "Last Updated" date at the top of this Privacy Policy will be updated. If there are any material changes to the Privacy Policy, you will be notified when required.'
),
},
{
title: 'Data Collection and Usage',
contents: (
`In order for DB to provide its services, data is required to be collected and used in various ways. This includes email, IP address, and any other information required to use DB services. Your usage data of DB services is also collected for improving DB security and quality. Any information volunteered to DB is subject the terms of the Privacy Policy.`
),
},
{
title: 'Data Sharing',
contents: (
`It should be noted that DB being a company that works with Bitcoin, Bitcoin transactions, and the Bitcoin network, some of the data such as Bitcoin addresses and Bitcoin transactions will be publicly viewable through the Bitcoin network. Below is a summary of what data is shared by DB and how it's used:`
),
},
{
contents: (
`• Your data will be shared with third party service providers that are used as a basis for DB, this includes web and cloud technology providers. Any third party service provider used will be properly vetted to ensure any shared data is being handled in an appropriate manner. Your personally identifiable information will not be sold to any third party service providers.`
),
},
{
contents: (
`• Your information in anonymized format may be shared with third party services for analysis in order to improve DB security and services.`
),
},
{
contents: (
`• Any other provided or volunteered information where consent has been given for it to be shared.`
),
},
{
title: 'Data Protection',
contents: (
`DB uses secure digital and procedural methodologies in order to keep your data and your Bitcoin as secure as possible. In addition, DB DOES NOT store large volumes of Bitcoin. The DB services themselves only contain purposefully smaller amounts of Bitcoin that are needed for the business computer operation logic.`
),
},
{
title: 'Data Retention and Access',
contents: (
`DB uses accounts that can store personally identifiable information associated with them. Transactions and other user actions associated with those accounts will be stored indefinitely although the personally identifiable information associated with those accounts and actions are not necessarily stored indefinitely, depending upon user request. `
),
},
{
contents: (
`If you require access to specific data or have a request to delete certain data, you can contact support at <EMAIL>.`
),
},
{
title: 'Third-Party Links',
contents: (
`DB may have links to third-party websites and other internet based services that are not managed or are affiliated with DB. DB is not responsible for any data shared or any other interaction and any resulting consequences of those actions on those third-party entities. Please refer to those companies' own terms and privacy policies in order to understand how those companies deal with your data and your privacy while using their services.`
),
},
{
title: 'Contact',
contents: (
`For any questions, complaints, suggestions, comments about this Privacy Policy or any other aspect of DB services, please don't hesitate to contact us through email at support<EMAIL>.`
),
},
]
}
);
};
<file_sep>import { createElement as e } from 'react';
import Button from '@material-ui/core/Button';
//
const getStyles = ({
marginTop,
marginBottom,
isLoadingMode,
}) => {
return {
backButton: {
backgroundColor: isLoadingMode ? 'grey' : 'beige',
marginTop,
marginBottom,
marginRight: 15,
marginLeft: 15,
borderRadius: 4,
width: '75%',
height: 40,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
// text: {
// textAlign: 'center',
// color: 'black',
// fontSize: 20,
// }
};
};
export default ({
onClick,
text,
isLoadingMode = false,
marginTop = 0,
marginBottom = 0,
}) => {
const styles = getStyles({
marginTop,
marginBottom,
isLoadingMode,
});
return e(
Button,
{
style: styles.backButton,
onClick: isLoadingMode ? () => {} : onClick,
},
text
);
};
<file_sep>'use strict';
module.exports = Object.freeze({
constants: require( './constants' ),
utils: require( './utils' ),
});
<file_sep>'use strict';
const {
constants: {
megaServerIdToMegaServerData
}
} = require( '@bitcoin-api/full-stack-api-private' );
const megaServerId = process.env.ID_OF_CURRENT_MEGA_SERVER;
if( !megaServerIdToMegaServerData[ megaServerId ] ) {
throw new Error( `invalid mega server id: ${ megaServerId }` );
}
module.exports = Object.freeze({
megaServerId,
mongo: {
collectionNames: {
address_data: 'address_data',
user_data: 'user_data',
}
}
});
<file_sep>'use strict';
// NOTE: might not be necessary to be in it's own file
module.exports = Object.freeze( ({
operationExpiry
}) => {
const timeUntilExpiry = operationExpiry - Date.now();
const thereIsTimeBeforeExpiry = (timeUntilExpiry > 0);
return {
timeUntilExpiry,
thereIsTimeBeforeExpiry,
};
});
<file_sep>'use strict';
const fs = require( 'fs' );
const withdrawReportsPath = process.env.WITHDRAW_REPORTS_PATH;
const reportsPath = `${ withdrawReportsPath }/currentWithdrawReports.txt`;
const writeReportToFile = Object.freeze( ({
withdrawReport
}) => {
const stream = fs.createWriteStream(
reportsPath,
{
flags: 'a'
}
);
stream.write(
`==--==--==--==--==--==--==--==--==--==--==--==--==\n` +
`Withdraw Occurred - ${ (new Date()).toLocaleString() }\n` +
`${ JSON.stringify( withdrawReport, null, 4 ) },\n` +
`==--==--==--==--==--==--==--==--==--==--==--==--==\n`
);
stream.end();
});
module.exports = Object.freeze( ({
withdrawReport
}) => {
console.log( 'running safeWriteReportToFile' );
try {
writeReportToFile({ withdrawReport });
console.log( 'safeWriteReportToFile executed successfully' );
}
catch( err ) {
console.log(
'an error occur in writing safeWriteReportToFile:', err
);
}
});
<file_sep>'use strict';
const {
utils: {
doOperationInQueue,
stringify,
javascript: {
getQueueId
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_USERS
}
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
constants: {
http: {
headers
},
// google: {
// captcha
// }
}
} = require( '../../../../../utils' );
const validateAndGetValues = require( './validateAndGetValues' );
const ensureExchangeUserHasEnoughMoney = require( './ensureExchangeUserHasEnoughMoney' );
const doEnchantedLuck = require( './doEnchantedLuck' );
const performEnchantedLuckFunctionCore = Object.freeze( async ({
exchangeUserId,
amount,
}) => {
await ensureExchangeUserHasEnoughMoney({
amount,
exchangeUserId,
});
const doEnchantedLuckResults = await doEnchantedLuck({
amount,
exchangeUserId,
});
return doEnchantedLuckResults;
});
module.exports = Object.freeze( async ({
event,
ipAddress,
exchangeUserId
}) => {
const requestBody = event.body;
// const rawMode = requestBody.mode;
const rawAmount = requestBody.amount;
const rawGoogleCode = event.headers[ headers.grecaptchaGoogleCode ];
console.log(
`running performEnchantedLuckFunction
with the following values - ${
stringify({
exchangeUserId,
ipAddress,
rawAmount,
rawGoogleCode,
})
}`
);
const {
amount,
} = await validateAndGetValues({
rawAmount,
ipAddress,
rawGoogleCode
});
const enchantedLuck = await doOperationInQueue({
queueId: getQueueId({ type: EXCHANGE_USERS, id: exchangeUserId }),
doOperation: async () => {
return await performEnchantedLuckFunctionCore({
exchangeUserId,
amount,
});
}
});
console.log(
`performEnchantedLuckFunction executed successfully
- returning values ${
stringify( enchantedLuck )
}`
);
return enchantedLuck;
});
<file_sep>import { createElement as e } from 'react';
// import { getState } from '../../../../reduxX';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
// import {
// enchanted
// } from '../../../../../../../utils';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import getSortByUserProcessedData from './getSortByUserProcessedData';
// import SortSelector from './SortSelector';
// import Typography from '@material-ui/core/Typography';
// import Button from '@material-ui/core/Button';
const getUserBoxBackgroundColour = ({
alt,
own,
}) => {
if( own ) {
return 'lightgreen';
}
return alt ? '#FDFEF4': '#F4F5DB';
};
const getUserBoxStyle = ({
alt = false,
own = false,
} = { alt: false, own: false }) => {
return {
backgroundColor: getUserBoxBackgroundColour({
alt,
own,
}),
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
minHeight: 45,
};
};
const getStyles = () => {
return {
metaContainer: {
width: '100%',
height: '100%',
// backgroundColor: '#FDFEF4',
// backgroundColor: 'green',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
overflowY: 'scroll',
// marginBottom: 8,
// marginTop: 10,
// marginBottom: 10,
},
ownUserBox: getUserBoxStyle({ own: true }),
userBox: getUserBoxStyle(),
altUserBox: getUserBoxStyle({ alt: true }),
userBoxTicketText: {
width: '90%',
fontWeight: 'bold',
color: 'black',
textAlign: 'left',
},
userBoxDataText: {
width: '90%',
fontSize: 14,
color: 'black',
textAlign: 'left',
}
};
};
const selectUserBoxStyle = ({
styles,
index,
isOwn
}) => {
if( isOwn ) {
return styles.ownUserBox;
}
return (
(index % 2) === 0
) ? styles.userBox : styles.altUserBox;
};
export default ({
data,
ownSpecialId,
}) => {
const styles = getStyles();
const userListItems = getSortByUserProcessedData({
data,
ownSpecialId,
}).map(
( choiceDatum, index ) => {
const isOwn = choiceDatum.own;
// do get box style, consider own too
return e(
Box,
{
style: selectUserBoxStyle({
styles,
index,
isOwn
})
},
e(
Typography,
{
style: styles.userBoxTicketText,
},
isOwn ? `${ choiceDatum.name } (self)` : choiceDatum.name,
),
e(
Typography,
{
style: styles.userBoxDataText,
},
choiceDatum.choices.join( ', ' )
)
);
}
);
return e(
Box,
{
style: styles.metaContainer
},
...userListItems
);
};<file_sep>'use strict';
const handleTransactions = require( './handleTransactions' );
exports.handler = Object.freeze( async event => {
console.log( '💦Running handleTransactionsStream' );
try {
await handleTransactions({
event,
});
console.log(
'💦🐉handleTransactionsStream executed successfully'
);
}
catch( err ) {
console.log( '💦🍣error in handleTransactionsStream:', err );
}
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
getDatabaseEntry,
},
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
aws: {
database: {
tableNameToKey,
tableNameToSortKey
}
},
} = require( '../../../constants' );
module.exports = Object.freeze( async ({
tableName,
value,
}) => {
const key = tableNameToKey[ tableName ];
const params = {
tableName,
value,
key,
};
const sortKey = tableNameToSortKey[ tableName ];
if( !!sortKey ) {
params.sortKey = sortKey;
}
const databaseEntry = await getDatabaseEntry( params );
return databaseEntry;
});<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase
}
},
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
TRANSACTIONS
},
secondaryIndices: {
exchangeUserIdCreationDateIndex,
}
}
},
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const smallBatchSearchLimit = 3;
const searchLimit = 20;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
exchangeUserId: '#exchangeUserId',
}),
nameValues: f({
exchangeUserId: 'exchangeUserId',
}),
valueKeys: f({
exchangeUserId: ':exchangeUserId',
}),
});
module.exports = Object.freeze( async ({
exchangeUserId,
lastTime,
lastTransactionId,
smallBatch,
}) => {
const searchLimitToUse = smallBatch ? smallBatchSearchLimit : searchLimit;
console.log(
'running getData with the following values: ' +
stringify({
exchangeUserId,
lastTime,
lastTransactionId,
smallBatch,
searchLimitToUse
})
);
const transactions = [];
let thereIsMoreDataToGet = true;
let lastTimeToUse = lastTime;
let lastTransactionIdToUse = lastTransactionId;
let iterationCount = 0;
while( thereIsMoreDataToGet ) {
iterationCount++;
console.log(
'getData - running search iteration with values: ' +
stringify({
iterationCount,
lastTimeToUse,
lastTransactionIdToUse,
['number of transactions retrieved']: transactions.length
})
);
const searchParams = {
TableName: TRANSACTIONS,
IndexName: exchangeUserIdCreationDateIndex,
Limit: searchLimitToUse,
ScanIndexForward: false,
// ProjectionExpression: [
// attributes.nameKeys.amount,
// attributes.nameKeys.creationDate,
// attributes.nameKeys.action,
// ].join( ', ' ), // TODO:
KeyConditionExpression: (
`${ attributes.nameKeys.exchangeUserId } = ${ attributes.valueKeys.exchangeUserId }`
),
// FilterExpression: (
// `${ attributes.nameKeys.raffleId } = ${ attributes.valueKeys.raffleId }`// +
// `${ attributes.nameKeys.raffleType } = ${ attributes.valueKeys.raffleType } and ` +
// `${ attributes.nameKeys.choice } = ${ attributes.valueKeys.choice }`
// ),
ExpressionAttributeNames: {
[attributes.nameKeys.exchangeUserId]: attributes.nameValues.exchangeUserId,
},
ExpressionAttributeValues: {
[attributes.valueKeys.exchangeUserId]: exchangeUserId,
},
ExclusiveStartKey: (!!lastTimeToUse && !!lastTransactionIdToUse) ? {
transactionId: lastTransactionIdToUse,
creationDate: lastTimeToUse,
exchangeUserId,
} : undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const batchOfTransactions = ultimateResults;
transactions.push( ...batchOfTransactions );
// IMPLEMENTED_OPTIMIZATION: if small batch and is small batch length
if( smallBatch && (transactions.length === searchLimitToUse) ) {
thereIsMoreDataToGet = false;
const lastIndex = transactions.length - 1;
lastTimeToUse = transactions[ lastIndex ].creationDate;
lastTransactionIdToUse = transactions[ lastIndex ].transactionId;
}
else if( !paginationValue ) {
thereIsMoreDataToGet = false;
if( transactions.length <= searchLimitToUse ) {
lastTimeToUse = null;
lastTransactionIdToUse = null;
}
else {
transactions.length = searchLimitToUse;
const lastIndex = transactions.length - 1;
lastTimeToUse = transactions[ lastIndex ].creationDate;
lastTransactionIdToUse = transactions[ lastIndex ].transactionId;
}
}
else {
if( transactions.length <= searchLimitToUse ) {
lastTimeToUse = paginationValue.creationDate;
lastTransactionIdToUse = paginationValue.transactionId;
}
else {
thereIsMoreDataToGet = false;
transactions.length = searchLimitToUse;
const lastIndex = transactions.length - 1;
lastTimeToUse = transactions[ lastIndex ].creationDate;
lastTransactionIdToUse = transactions[ lastIndex ].transactionId;
}
}
}
const data = {
transactions
};
if( !!lastTimeToUse && !!lastTransactionIdToUse ) {
Object.assign(
data,
{
lastTransactionId: lastTransactionIdToUse,
lastTime: lastTimeToUse,
}
);
}
else {
Object.assign(
data,
{
lastTransactionId: null,
lastTime: null,
}
);
}
console.log(
'getData executed successfully - ' +
`got ${ data.transactions.length } transactions - ` +
`the search limit is: ${ searchLimitToUse }`
);
return data;
});
<file_sep>'use strict';
module.exports = Object.freeze({
javascript: require( './javascript' ),
validation: require( './validation' ),
aws: require( './aws' ),
exchangeUsers: require( './exchangeUsers' ),
loginTokens: require( './loginTokens' ),
constants: require( './constants' ),
random: require( './random' ),
crypto: require( './crypto' ),
});
<file_sep>'use strict';
const { argv: { meta } } = require( 'yargs' );
if( !meta ) {
module.exports = Object.freeze({
core: require( './api' ),
// service: require( './service' ),
// site: require( './site' ),
exchange: require( './exchange' ),
});
}
else {
const jamesBondFunctions = {};
if( meta.includes( 'e' ) ) {
jamesBondFunctions.exchange = require( './exchange' );
}
// if( meta.includes( 's' ) ) {
// jamesBondFunctions.site = require( './site' );
// }
// if( meta.includes( 's' ) ) {
// jamesBondFunctions.service = require( './service' );
// }
if( meta.includes( 'a' ) ) {
jamesBondFunctions.core = require( './api' );
}
module.exports = Object.freeze( jamesBondFunctions );
}
<file_sep>'use strict';
const stringify = m => JSON.stringify( m, null, 4 );
const getAmountNumber = Object.freeze(
amount => Number(
(Math.round( Number(amount) * 100000000 ) / 100000000).toFixed(8)
)
);
const toFixedConstant = 5;
const amountMultiplier = 100000;
const getCryptoAmountNumber = Object.freeze( amount => {
const cryptoAmount = Number(
(
Math.round(
Number(amount) * amountMultiplier
) / amountMultiplier
).toFixed( toFixedConstant )
);
return cryptoAmount;
});
const no_withdraws_are_currently_being_processed = 'no_withdraws_are_currently_being_processed';
const bitcoinSumReducer = Object.freeze(
( accumulator, currentValue ) => accumulator + currentValue.amount
);
const getSumOfBitcoinDeposits = Object.freeze( ({
bitcoinData
}) => {
const sumOfBitcoinDeposits = bitcoinData.reduce( bitcoinSumReducer, 0 );
return sumOfBitcoinDeposits;
});
const addBitcoinBalanceData = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const bitcoinData = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.bitcoin &&
exchangeUser.moneyData.bitcoin
) || [];
if( bitcoinData.length === 0 ) {
const bitcoinBalanceData = {
totalAmount: 0,
depositAddress: null
};
balanceData.bitcoin = bitcoinBalanceData;
return;
}
const totalAmount = getSumOfBitcoinDeposits({
bitcoinData
});
const depositAddress = bitcoinData[
bitcoinData.length - 1
].address;
const bitcoinBalanceData = {
totalAmount: getAmountNumber( totalAmount ),
depositAddress
};
balanceData.bitcoin = bitcoinBalanceData;
});
const addBitcoinWithdrawsBalanceData = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const bitcoinWithdrawsBalanceDataFromExchangeUser = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.bitcoinWithdraws &&
exchangeUser.moneyData.bitcoinWithdraws
) || null;
const bitcoinWithdrawsBalanceData = {};
if( !bitcoinWithdrawsBalanceDataFromExchangeUser ) {
Object.assign(
bitcoinWithdrawsBalanceData,
{
totalAmount: 0,
currentState: no_withdraws_are_currently_being_processed,
}
);
}
else {
Object.assign(
bitcoinWithdrawsBalanceData,
{
totalAmount: getAmountNumber(
bitcoinWithdrawsBalanceDataFromExchangeUser.totalAmount
),
currentState: (
bitcoinWithdrawsBalanceDataFromExchangeUser.currentState
),
}
);
}
balanceData.bitcoinWithdraws = bitcoinWithdrawsBalanceData;
});
const addCryptoBalanceData = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const cryptoBalanceData = {};
const cryptoBalanceDataFromExchangeUser = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.dream &&
!!exchangeUser.moneyData.dream.crypto &&
exchangeUser.moneyData.dream.crypto
) || null;
if( !cryptoBalanceDataFromExchangeUser ) {
Object.assign(
cryptoBalanceData,
{
totalAmount: 0,
}
);
}
else {
Object.assign(
cryptoBalanceData,
{
totalAmount: getCryptoAmountNumber(
cryptoBalanceDataFromExchangeUser.amount
),
}
);
}
balanceData.crypto = cryptoBalanceData;
});
const addExchangeBalanceData = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const exchangeBalanceDataFromExchangeUser = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.exchange &&
exchangeUser.moneyData.exchange
) || null;
const exchangeBalanceData = {};
if( !exchangeBalanceDataFromExchangeUser ) {
Object.assign(
exchangeBalanceData,
{
bitcoin: {
totalAmount: 0,
},
crypto: {
totalAmount: 0,
},
}
);
}
else {
Object.assign(
exchangeBalanceData,
{
bitcoin: {
totalAmount: getAmountNumber(
!!exchangeBalanceDataFromExchangeUser.bitcoin &&
!!exchangeBalanceDataFromExchangeUser.bitcoin.amount &&
exchangeBalanceDataFromExchangeUser.bitcoin.amount
) || 0,
},
crypto: {
totalAmount: getCryptoAmountNumber(
!!exchangeBalanceDataFromExchangeUser.crypto &&
!!exchangeBalanceDataFromExchangeUser.crypto.amount &&
exchangeBalanceDataFromExchangeUser.crypto.amount
) || 0,
},
}
);
}
balanceData.exchange = exchangeBalanceData;
});
const addVoteBalanceData = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const voteBalanceDataFromExchangeUser = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.vote &&
exchangeUser.moneyData.vote
) || null;
const voteBalanceData = {};
if( !voteBalanceDataFromExchangeUser ) {
voteBalanceData.crypto = {
totalAmount: 0,
};
}
else {
voteBalanceData.crypto = {
totalAmount: getCryptoAmountNumber(
voteBalanceDataFromExchangeUser.crypto.amount
) || 0,
};
}
balanceData.vote = voteBalanceData;
});
const addRaffleBalanceData = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const raffleBalanceDataFromExchangeUser = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.raffle &&
exchangeUser.moneyData.raffle
) || null;
const raffleBalanceData = {};
if( !raffleBalanceDataFromExchangeUser ) {
raffleBalanceData.crypto = {
totalAmount: 0,
};
}
else {
raffleBalanceData.crypto = {
totalAmount: getCryptoAmountNumber(
raffleBalanceDataFromExchangeUser.crypto.amount
) || 0,
};
}
balanceData.raffle = raffleBalanceData;
});
const addSummaryBalanceData = Object.freeze( ({
balanceData,
}) => {
const summaryBalanceData = {
bitcoin: {
totalAmount: getAmountNumber(
balanceData.bitcoin.totalAmount +
(-balanceData.bitcoinWithdraws.totalAmount) +
(balanceData.exchange.bitcoin.totalAmount)
)
},
crypto: {
totalAmount: getCryptoAmountNumber(
balanceData.crypto.totalAmount +
(balanceData.exchange.crypto.totalAmount) +
balanceData.vote.crypto.totalAmount +
balanceData.raffle.crypto.totalAmount
)
},
};
balanceData.summary = summaryBalanceData;
});
module.exports = Object.freeze( ({
exchangeUser,
}) => {
console.log( 'running getBalanceData' );
const balanceData = {};
addBitcoinBalanceData({
exchangeUser,
balanceData,
});
addBitcoinWithdrawsBalanceData({
exchangeUser,
balanceData,
});
addCryptoBalanceData({
exchangeUser,
balanceData,
});
addExchangeBalanceData({
exchangeUser,
balanceData,
});
addVoteBalanceData({
exchangeUser,
balanceData,
});
addRaffleBalanceData({
exchangeUser,
balanceData,
});
addSummaryBalanceData({
exchangeUser,
balanceData,
});
console.log(
'getBalanceData executed successfully: ' +
`got balance data ${ stringify( balanceData ) }`
);
return balanceData;
});<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry
}
},
stringify,
},
constants: {
aws: {
database: {
tableNameToKey,
tableNames: { METADATA },
}
},
metadata: {
types: {
raffle
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
raffle: { getRaffleId },
constants: { raffle: { lotteryTypes: { twoNumber } } },
} = require( '../../../../../enchantedUtils' );
/*
{
"creationDate": 1602141854902,
"cryptoPot": -22,
"key": "raffle_1602141854902",
"lotteryType": "twoNumber",
"ticketCryptoPrice": 2,
"type": "raffle"
// "lastUpdated": 1603777527342,
}
*/
const defaultCryptoTicketPrice = 1;
module.exports = Object.freeze( async ({
ticketCryptoPrice = defaultCryptoTicketPrice,
previousRaffleId,
previousRaffleNumber,
previousRaffleEndHour,
houseCut
}) => {
console.log(
'running createNewRaffle ' +
'with the following values: ' +
stringify({
ticketCryptoPrice,
previousRaffleId,
previousRaffleNumber,
previousRaffleEndHour,
houseCut,
})
);
const raffleData = {
[ tableNameToKey[ METADATA] ]: getRaffleId(),
cryptoPot: 0,
lotteryType: twoNumber,
ticketCryptoPrice: ticketCryptoPrice,
type: raffle,
creationDate: Date.now(),
previousRaffleId,
raffleNumber: previousRaffleNumber + 1,
previousRaffleEndHour,
houseCut,
};
await updateDatabaseEntry({
tableName: METADATA,
entry: raffleData,
});
console.log( 'createNewRaffle executed successfully' );
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase
}
},
stringify,
},
constants: {
aws: {
database: {
tableNames: {
METADATA
},
tableNameToKey,
secondaryIndex: {
typeCreationDateIndex
}
}
},
metadata: {
types: {
rafflePutTicketEvent
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const doManagePutTicketEvent = require( './doManagePutTicketEvent' );
const deleteRafflePutTicketEvent = require( './deleteRafflePutTicketEvent' );
const searchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
type: '#type',
}),
nameValues: f({
type: 'type',
}),
valueKeys: f({
type: ':type',
}),
});
module.exports = Object.freeze( async () => {
console.log( 'running managePutTicketEvents, YES🦖👑👑👑' );
let paginationValueToUse = null;
let iterationCount = 0;
do {
console.log(
'managePutTicketEvents - ' +
'running metadata search: ' +
stringify({
paginationValueToUse,
iterationCount,
})
);
const searchParams = {
TableName: METADATA,
IndexName: typeCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: true,
// ProjectionExpression: [
// attributes.nameKeys.amount,
// attributes.nameKeys.creationDate,
// attributes.nameKeys.action,
// ].join( ', ' ), // TODO:
KeyConditionExpression: (
`${ attributes.nameKeys.type } = ${ attributes.valueKeys.type }`
),
// FilterExpression: (
// `${ attributes.nameKeys.raffleId } = ${ attributes.valueKeys.raffleId } and ` +
// `${ attributes.nameKeys.raffleType } = ${ attributes.valueKeys.raffleType } and ` +
// `${ attributes.nameKeys.choice } = ${ attributes.valueKeys.choice }`
// ),
ExpressionAttributeNames: {
[attributes.nameKeys.type]: attributes.nameValues.type,
},
ExpressionAttributeValues: {
[attributes.valueKeys.type]: rafflePutTicketEvent,
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const rafflePutTicketEvents = ultimateResults;
for( const putTicketEvent of rafflePutTicketEvents ) {
await doManagePutTicketEvent({
putTicketEvent,
});
await deleteRafflePutTicketEvent({
rafflePutTicketEventId: putTicketEvent[
tableNameToKey[ METADATA ]
],
});
}
if( !!paginationValue ) {
paginationValueToUse = paginationValue;
iterationCount++;
}
else if( !!paginationValueToUse ) {
paginationValueToUse = null;
}
} while( !!paginationValueToUse );
console.log( 'managePutTicketEvents executed successfully✅✅✅✅✅✅' );
});
<file_sep>import { browser } from '../utils';
import { setState } from '../reduxX';
import { queryStringModes, story } from '../constants';
const { getQueryStringValue } = browser;
export default () => {
const mode = getQueryStringValue( 'mode' );
const verificationCode = getQueryStringValue( 'verification_code' );
const email = getQueryStringValue( 'email' );
if(
(mode === queryStringModes.account_verification) &&
!!verificationCode &&
!!email
) {
window.history.replaceState(
{
key: 'exchange'
},
document.title,
'/'
);
setState(
{
keys: [ 'verifyEmailPolygon', 'emailInput' ],
value: email,
},
{
keys: [ 'verifyEmailPolygon', 'verifyEmailCodeInput' ],
value: verificationCode,
},
{
keys: [ 'notLoggedInMode', 'mainMode' ],
value: story.NotLoggedInMode.mainModes.verifyUserMode
}
);
}
};<file_sep>'use strict';
const {
withdraws: {
limits: {
minimumWithdrawAmount,
maximumWithdrawAmount
}
}
} = require( '../../constants' );
module.exports = Object.freeze( ({
withdrawAmount,
}) => !(
Number.isNaN( withdrawAmount ) ||
(withdrawAmount > maximumWithdrawAmount) ||
(withdrawAmount < minimumWithdrawAmount)
));<file_sep>'use strict';
module.exports = Object.freeze({
getClient: require( './getClient' ),
doRedisRequest: require( './doRedisRequest' ),
streams: require( './streams' ),
rhinoCombos: require( './rhinoCombos' ),
doRedisFunction: require( './doRedisFunction' ),
});
<file_sep>import { createElement as e, useEffect } from 'react';
import { getState } from '../../../../../../reduxX';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
// import Button from '@material-ui/core/Button';
import componentDidMount from './componentDidMount';
import { getViewDrawsContainerId } from '../viewDrawsTools';
const getIfTimeIsSpecial = ({ time }) => {
const date = new Date( time );
const pureTime = date.getTime();
const dayStartDate = new Date(
date.getFullYear(),
date.getMonth(),
date.getDate()
);
const dayStartTime = dayStartDate.getTime();
// const threeTime = (new Date(
// date.getFullYear(),
// date.getMonth(),
// date.getDate(),
// 3
// )).getTime();
// const sixTime = (new Date(
// date.getFullYear(),
// date.getMonth(),
// date.getDate(),
// 6
// )).getTime();
// const nineTime = (new Date(
// date.getFullYear(),
// date.getMonth(),
// date.getDate(),
// 9
// )).getTime();
// const twelveTime = (new Date(
// date.getFullYear(),
// date.getMonth(),
// date.getDate(),
// 12
// )).getTime();
// const fifteenTime = (new Date(
// date.getFullYear(),
// date.getMonth(),
// date.getDate(),
// 15
// )).getTime();
// const eighteenTime = (new Date(
// date.getFullYear(),
// date.getMonth(),
// date.getDate(),
// 18
// )).getTime();
// const twentyOneTime = (new Date(
// date.getFullYear(),
// date.getMonth(),
// date.getDate(),
// 21
// )).getTime();
// const specialTimes = [
// dayStartTime,
// // threeTime,
// // sixTime,
// // nineTime,
// // twelveTime,
// // fifteenTime,
// // eighteenTime,
// // twentyOneTime
// ];
// const timeIsSpecial = specialTimes.includes( pureTime );
const timeIsSpecial = pureTime === dayStartTime;
return timeIsSpecial;
};
const getFullTimeString = ({ time }) => {
const pureTimeString = (new Date( time )).toLocaleString();
const splitTime = pureTimeString.split( ', ' );
const fullTimeString = `${ splitTime[ 1 ] }, ${ splitTime[ 0 ] }`;
return fullTimeString;
};
const getChoiceStyle = ({
alt = false
} = { alt: false }) => {
return {
backgroundColor: alt ? '#F4F5DB' : '#FDFEF4',
// height: 22,
width: '100%',
minHeight: 22,
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
};
};
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
dayBox: {
marginTop: 10,
width: '100%',
// minWidth: 0,
maxWidth: 340,
marginBottom: 10,
backgroundColor: '#D0D2A8',
// backgroundColor: 'beige',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
dayBoxBottomSpacer: {
height: 15,
width: 5,
},
// dayBoxTimeText: {
// marginTop: 10,
// color: 'black',
// },
choiceElementsMetaHolder: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
width: '100%',
height: 200,
},
choiceElementsHolder: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
width: '100%',
// height: '85%',
height: '100%',
overflowY: 'scroll',
WebkitOverflowScrolling: 'touch',
},
choice: getChoiceStyle(),
altChoice: getChoiceStyle({ alt: true }),
choiceTextLeft: {
// width: '75%',
// height: 22,
textAlign: 'left',
color: 'black',
marginLeft: 5,
fontSize: 12,
},
choiceTextRight: {
// height: 22,
// width: '25%',
textAlign: 'right',
color: 'black',
marginRight: 5,
},
};
};
const ChoiceElementsHolder = ({
styles,
choiceElements,
isLocalLoading,
drawData,
raffleId,
}) => {
return e(
Box,
{
id: getViewDrawsContainerId({ raffleId }),
style: styles.choiceElementsHolder,
},
(choiceElements.length > 0) ? choiceElements : e(
Box,
{
style: Object.assign(
{},
styles.choice,
{
marginTop: 30,
width: '90%'
}
),
}//,
// !isLocalLoading && e(
// Typography,
// {
// style: styles.choiceTextLeft,
// },
// (drawData.index === 0) ? (
// 'No draws yet, please check again later, ' +
// 'thank you!'
// ) : '◀️'
// )
),
);
};
export default ({
// startTime,
raffleDatum,
isLocalLoading,
setIsLocalLoading,
}) => {
const { raffleId } = raffleDatum;
useEffect( () => {
Promise.resolve().then( async () => {
setIsLocalLoading( true );
try {
await componentDidMount({
raffleDatum
});
setIsLocalLoading( false );
}
catch( err ) {
setIsLocalLoading( false );
console.log( 'an error occurred:', err );
}
});
}, [ raffleDatum, setIsLocalLoading ] );
const styles = getStyles();
const drawData = getState(
'destinyRaffle',
'raffleIdToDrawData'
)[ raffleId ] || {
allDraws: [ [] ],
lastTime: null,
index: 0,
};
const choiceElements = (
drawData.allDraws[ drawData.index ]
).map( ( choiceDatum, index ) => {
const timeIsSpecial = getIfTimeIsSpecial({
time: choiceDatum.time
});
return e(
Box,
{
style: ( index % 2 === 0 ) ? styles.choice : styles.altChoice,
key: `${ choiceDatum.choice }-${ index }`,
},
e(
Typography,
{
style: styles.choiceTextLeft,
},
timeIsSpecial ? (
getFullTimeString({
time: choiceDatum.time,
})
) : (new Date( choiceDatum.time )).toLocaleTimeString(),
),
e(
Typography,
{
style: styles.choiceTextRight,
},
choiceDatum.choice,
)
);
});
return e(
Box,
{
style: styles.dayBox,
},
e(
Box,
{
style: styles.choiceElementsMetaHolder,
},
e(
ChoiceElementsHolder,
{
styles,
choiceElements,
isLocalLoading,
drawData,
raffleId
}
)
)
);
};
<file_sep>import { createElement as e } from 'react';
import { setState } from '../../../reduxX';
// import { story } from '../../constants';
// import {
// usefulComponents,
// POWBlock,
// } from '../../TheSource';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import getMore from './getMore';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
// backgroundColor: 'beige',
width: '100%',
maxWidth: 620,
// height: 300,
// backgroundColor: 'pink',
marginTop: 20,
marginBottom: 20,
// borderRadius: '50%',
// backgroundColor: 'pink',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
button: {
width: '100%',
backgroundColor: 'black',
color: 'white'
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Button,
{
style: styles.button,
onClick: async () => {
try {
setState( 'isLoading', true );
await getMore();
setState( 'isLoading', false );
}
catch( err ) {
setState( 'isLoading', false );
alert(
`error in getting more Lotus Seasons: ${
(
!!err &&
!!err.response &&
!!err.response.data &&
!!err.response.data.message &&
err.response.data.message
) || 'internal server error'
}`
);
}
},
},
'More Lotus Seasons'
)
);
};
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser,
}
}
},
constants: {
transactions,
dreams,
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
random,
} = require( '../../../../../exchangeUtils' );
const coinNumberMultiplier = 1000000;
const percentageToWin = 0.4999;
const defaultCoinNumberThreshold = (1 - percentageToWin) * coinNumberMultiplier;
const flipCoin = Object.freeze( ({
coinNumberThreshold = defaultCoinNumberThreshold,
exchangeUserId = null,
}) => {
if( !exchangeUserId ) {
throw new Error(
'doEnchantedLuck WEIRD ERROR: ' +
'missing exchangeUserId'
);
}
console.log(
`⭑・゚゚・*:༅。.。༅:*゚:*:✼✿ 🐑☢️ Flipping the Coin ✿✼:*゚:༅。.。༅:*・゚゚・⭑\n` +
' - \n' +
`need to get coinNumber higher than or equal to ${ coinNumberThreshold } - ` +
`exchangeUserId -> ${ exchangeUserId }`
);
const coinNumber = random.getRandomIntegerInclusive({
min: 1,
max: coinNumberMultiplier
});
// TODO: put into function
let shouldHaveOffset = [
process.env.EXCHANGE_WOLF_ON_WALL_STREET_USER_ID || 'NOPE',
].includes( exchangeUserId );
console.log( 'shouldHaveOffset:', shouldHaveOffset );
// const offsetAmountThreshold = (
// shouldHaveOffset ? (0.222 * coinNumberMultiplier) : 0
// );
const offsetAmountThreshold = 0;
console.log( 'offsetAmountThreshold:', offsetAmountThreshold );
const modifiedCoinNumberThreshold = (
coinNumberThreshold +
offsetAmountThreshold
);
console.log( 'modifiedCoinNumberThreshold:', modifiedCoinNumberThreshold );
const hasWonThisChallengeOfFate = (
coinNumber > modifiedCoinNumberThreshold
);
console.log(
`⭑・゚゚・*:༅。.。༅:*゚:*:✼✿ 🐑☢️ Flipping the Coin ✿✼:*゚:༅。.。༅:*・゚゚・⭑\n` +
' - \n' +
'executed successfully: ' + stringify({
coinNumber,
hasWonThisChallengeOfFate
})
);
return hasWonThisChallengeOfFate;
});
module.exports = Object.freeze( async ({
amount,
exchangeUserId,
}) => {
console.log(
'running doEnchantedLuck ' +
`with the following values: ${ stringify({
amount,
exchangeUserId
})}`
);
const hasWonGame = flipCoin({
exchangeUserId
});
const happyDream = hasWonGame;
const transactionAmount = hasWonGame ? amount : -amount;
await addTransactionAndUpdateExchangeUser({
noLocka: true,
exchangeUserId,
type: transactions.types.dream,
data: {
dreamType: dreams.types.coin,
amount: transactionAmount,
happyDream,
},
});
const luckResults = {
happyDream,
};
console.log(
'doEnchantedLuck executed successfully - ' +
`returning luck results: ${ stringify( luckResults ) }`
);
return luckResults;
});<file_sep>import {
createElement as e,
} from 'react';
import { getState } from '../../../reduxX';
import Box from '@material-ui/core/Box';
import VerticalSection from './VerticalSection';
import ButtonSection from './ButtonSection';
export default ({
freeGameMode,
}) => {
const slotNumber1 = getState(
'loggedInMode',
'slot',
'slotNumber1'
);
const slotNumber2 = getState(
'loggedInMode',
'slot',
'slotNumber2'
);
const slotNumber3 = getState(
'loggedInMode',
'slot',
'slotNumber3'
);
return e(
Box,
{
style: {
width: '100%',
// height: 200,
marginTop: 33,
// backgroundColor: 'crimson',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
},
e(
Box,
{
style: {
width: '91%',
// height: '100%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
}
},
e(
VerticalSection,
{
slotNumber: slotNumber1,
}
),
e(
VerticalSection,
{
slotNumber: slotNumber2,
}
),
e(
VerticalSection,
{
slotNumber: slotNumber3,
}
)
),
e(
ButtonSection,
{
freeGameMode,
}
)
);
};
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase
}
},
stringify,
},
constants: {
aws: {
database: {
tableNames: {
METADATA
},
tableNameToKey,
secondaryIndex: {
typeCreationDateIndex
}
}
},
metadata: {
types: {
raffleDraw
}
},
environment: {
isProductionMode
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
timeNumbers: {
minute
}
}
} = require( '../../../../../../utils' );
// const searchLimit = 1;
const searchLimit = isProductionMode ? 100 : 3;
// const searchLimit = 20000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
type: '#type',
creationDate: '#creationDate',
raffleId: '#raffleId',
}),
nameValues: f({
type: 'type',
raffleId: 'raffleId',
creationDate: 'creationDate',
}),
valueKeys: f({
type: ':type',
startTime: ':startTime',
endTime: ':endTime',
raffleId: ':raffleId',
}),
});
// const key = tableNameToKey[ METADATA ];
module.exports = Object.freeze( async ({
raffleId,
startTime,
endTime,
lastTime,
lastKey,
}) => {
console.log(
'running getDrawsData with the following values: ' +
stringify({
raffleId,
startTime,
endTime,
lastTime,
lastKey,
})
);
const collectedDraws = [];
let thereAreMoreDrawsToGet = true;
let lastTimeToUse = lastTime;
let lastKeyToUse = lastKey;
let iterationCount = 0;
while( thereAreMoreDrawsToGet ) {
iterationCount++;
console.log(
'getDrawsData - running search iteration with values: ' +
stringify({
iterationCount,
lastTimeToUse,
lastKeyToUse,
})
);
const searchParams = {
TableName: METADATA,
IndexName: typeCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: false,
// ProjectionExpression: [
// attributes.nameKeys.amount,
// attributes.nameKeys.creationDate,
// attributes.nameKeys.action,
// ].join( ', ' ), // TODO:
KeyConditionExpression: (
`${ attributes.nameKeys.type } = ${ attributes.valueKeys.type } and ` +
`${ attributes.nameKeys.creationDate } between ` +
`${ attributes.valueKeys.startTime } and ` +
`${ attributes.valueKeys.endTime }`
),
FilterExpression: (
`${ attributes.nameKeys.raffleId } = ${ attributes.valueKeys.raffleId }`// +
// `${ attributes.nameKeys.raffleType } = ${ attributes.valueKeys.raffleType } and ` +
// `${ attributes.nameKeys.choice } = ${ attributes.valueKeys.choice }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.type]: attributes.nameValues.type,
[attributes.nameKeys.creationDate]: attributes.nameValues.creationDate,
[attributes.nameKeys.raffleId]: attributes.nameValues.raffleId,
},
ExpressionAttributeValues: {
[attributes.valueKeys.type]: raffleDraw,
[attributes.valueKeys.startTime]: startTime,
[attributes.valueKeys.endTime]: endTime + (10 * minute),
[attributes.valueKeys.raffleId]: raffleId,
},
ExclusiveStartKey: (!!lastTimeToUse && !!lastKeyToUse) ? {
[ tableNameToKey[ METADATA ] ]: lastKeyToUse,
creationDate: lastTimeToUse,
type: raffleDraw,
} : undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const draws = ultimateResults.map( rawDraw => {
const draw = {
time: rawDraw.currentHour,
choice: rawDraw.choice,
win: !!rawDraw.winData,
key: rawDraw.key,
creationDate: rawDraw.creationDate,
};
return draw;
});
collectedDraws.push( ...draws );
if( !paginationValue ) {
thereAreMoreDrawsToGet = false;
if( collectedDraws.length <= searchLimit ) {
lastTimeToUse = null;
lastKeyToUse = null;
}
else {
collectedDraws.length = searchLimit;
lastTimeToUse = collectedDraws[
collectedDraws.length - 1
].creationDate;
lastKeyToUse = collectedDraws[
collectedDraws.length - 1
].key;
}
}
else {
if( collectedDraws.length <= searchLimit ) {
lastTimeToUse = paginationValue.creationDate;
lastKeyToUse = paginationValue.key;
}
else {
thereAreMoreDrawsToGet = false;
collectedDraws.length = searchLimit;
lastTimeToUse = collectedDraws[
collectedDraws.length - 1
].creationDate;
lastKeyToUse = collectedDraws[
collectedDraws.length - 1
].key;
}
}
}
const drawsData = {
draws: collectedDraws.map( rawCollectedDraw => {
const draw = {
time: rawCollectedDraw.time,
choice: rawCollectedDraw.choice,
win: rawCollectedDraw.win,
id: rawCollectedDraw.key,
};
return draw;
}),
pageInfo: (
!!lastTimeToUse &&
!!lastKeyToUse
) ? {
lastKey: lastKeyToUse,
lastTime: lastTimeToUse,
} : null,
};
console.log(
'getDrawsData executed successfully - got ' +
`${ collectedDraws.length } draws - search limit is: ${ searchLimit }`
);
return drawsData;
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase,
},
},
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
raffles: {
actions: {
buy,
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
constants: {
aws: {
database: {
tableNames: {
TRANSACTIONS,
},
secondaryIndices: {
exchangeUserIdCreationDateIndex,
}
}
},
raffles: {
types: {
putTicket,
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const searchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
amount: '#amount',
creationDate: '#creationDate',
exchangeUserId: '#exchangeUserId',
searchId: '#searchId',
raffleType: '#raffleType',
choice: '#choice',
action: '#action',
}),
nameValues: f({
amount: 'amount',
creationDate: 'creationDate',
exchangeUserId: 'exchangeUserId',
searchId: 'searchId',
raffleType: 'raffleType',
choice: 'choice',
action: 'action'
}),
valueKeys: f({
exchangeUserId: ':exchangeUserId',
searchId: ':searchId',
raffleType: ':raffleType',
choice: ':choice',
}),
});
module.exports = Object.freeze( async ({
raffleId,
choice,
exchangeUserId,
}) => {
console.log(
`running getCurrentChoiceData with the following values - ${
stringify({
raffleId,
choice,
exchangeUserId,
})
}`
);
let currentChoiceAmount = 0;
let paginationValueToUse = null;
let iterationCount = 0;
const currentChoiceData = {
currentAmountForChoice: null,
mostRecentBuyTransactionCreationDate: null,
};
do {
console.log(
'getCurrentChoiceData - ' +
'running transactions search: ' +
stringify({
currentChoiceAmount,
paginationValueToUse,
iterationCount,
})
);
const searchParams = {
TableName: TRANSACTIONS,
IndexName: exchangeUserIdCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: true,
ProjectionExpression: [
attributes.nameKeys.amount,
attributes.nameKeys.creationDate,
attributes.nameKeys.action,
].join( ', ' ),
KeyConditionExpression: (
`${ attributes.nameKeys.exchangeUserId } = ${ attributes.valueKeys.exchangeUserId }`
),
FilterExpression: (
`${ attributes.nameKeys.searchId } = ${ attributes.valueKeys.searchId } and ` +
`${ attributes.nameKeys.raffleType } = ${ attributes.valueKeys.raffleType } and ` +
`${ attributes.nameKeys.choice } = ${ attributes.valueKeys.choice }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.creationDate]: attributes.nameValues.creationDate,
[attributes.nameKeys.amount]: attributes.nameValues.amount,
[attributes.nameKeys.exchangeUserId]: attributes.nameValues.exchangeUserId,
[attributes.nameKeys.searchId]: attributes.nameValues.searchId,
[attributes.nameKeys.raffleType]: attributes.nameValues.raffleType,
[attributes.nameKeys.choice]: attributes.nameValues.choice,
[attributes.nameKeys.action]: attributes.nameValues.action,
},
ExpressionAttributeValues: {
[attributes.valueKeys.exchangeUserId]: exchangeUserId,
[attributes.valueKeys.searchId]: raffleId,
[attributes.valueKeys.raffleType]: putTicket,
[attributes.valueKeys.choice]: choice,
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const retrievedTransactions = ultimateResults;
for( const transaction of retrievedTransactions ) {
currentChoiceAmount += transaction.amount;
}
if( !!paginationValue ) {
paginationValueToUse = paginationValue;
iterationCount++;
}
else if( !!paginationValueToUse ) {
paginationValueToUse = null;
}
if(
!paginationValueToUse &&
(retrievedTransactions.length > 0) &&
(
retrievedTransactions[
retrievedTransactions.length - 1
].action === buy
)
) {
currentChoiceData.mostRecentBuyTransactionCreationDate = (
retrievedTransactions[
retrievedTransactions.length - 1
].creationDate
);
}
} while( !!paginationValueToUse );
currentChoiceData.currentAmountForChoice = currentChoiceAmount;
console.log(
`getCurrentChoiceData executed successfully
returning current choice data - ${
stringify( currentChoiceData )
}`
);
return currentChoiceData;
});<file_sep>'use strict';
const {
utils: {
stringify,
redis: {
doRedisRequest,
// getClient,
},
javascript: {
jsonEncoder
}
},
constants: {
redis: {
keys: {
cacheOnAndOffStatus
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const timeUntilRhinoPondBecomesMurky = 5 * 60 * 1000;
const getApiIsOnData = Object.freeze( ({
bitcoinApiIsOn = false,
bitcoinApiIsOffReason = null,
}) => ({
bitcoinApiIsOn,
bitcoinApiIsOffReason,
}));
const getIfBankIsOn = Object.freeze( async ({
redisClient
}) => {
try {
const cacheOnAndOffStatusRhinoPond = await doRedisRequest({
client: redisClient,
command: 'get',
redisArguments: [
cacheOnAndOffStatus,
]
});
if( !cacheOnAndOffStatusRhinoPond ) {
throw new Error( 'no rhino pond for on and off status' );
}
const {
bitcoinApiIsOn,
bitcoinApiIsOffReason,
rhinoTime,
} = jsonEncoder.decodeJson( cacheOnAndOffStatusRhinoPond );
console.log(`
getIfApiIsOnData.getIfBankIsOn gotten values:
${ stringify({
bitcoinApiIsOn,
bitcoinApiIsOffReason,
rhinoTime,
})}
`);
const rhinoPondExpiry = (rhinoTime + timeUntilRhinoPondBecomesMurky);
if( Date.now() > rhinoPondExpiry ) {
throw new Error( 'expired rhino pond for on and off status' );
}
const apiIsOnData = getApiIsOnData({
bitcoinApiIsOn,
bitcoinApiIsOffReason,
});
return apiIsOnData;
}
catch( err ) {
console.log( 'error in getIfBankIsOn:', err, '- ignoring error' );
const apiIsOnData = getApiIsOnData({
bitcoinApiIsOn: false,
});
return apiIsOnData;
}
});
module.exports = Object.freeze( async ({
redisClient
}) => {
console.log( 'running getIfApiIsOnData' );
const apiIsOnData = await getIfBankIsOn({
redisClient
});
console.log(
'getIfApiIsOnData - executed successfully ' +
`Api is on?: ${ stringify({ apiIsOnData }) }`
);
return apiIsOnData;
});
<file_sep>'use strict';
module.exports = Object.freeze( async ({ megaCode }) => {
if(
!megaCode ||
(typeof megaCode !== 'string') ||
(megaCode.length < 420) ||
(megaCode.length > 769)
) {
throw new Error( 'invalid megaCode' );
}
});<file_sep>'use strict';
const constants = require( '../constants' );
const getHashedValue = require( '../../utils/javascript/getHashedValue' );
module.exports = Object.freeze( ({
exchangeUserId,
}) => {
const hiddenGhostId = getHashedValue(
exchangeUserId.substring(
constants.exchangeUsers.exchangeUserId.prefix.length
)
);
return hiddenGhostId;
});
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
google: {
captcha: {
actions
}
}
},
formatting: {
getFormattedEmail
},
validation: {
getIfEmailIsValid
},
business: {
verifyGoogleCode
}
} = require( '../../../utils' );
const {
validation: {
getIfPasswordIsValid
}
} = require( '../../../exchangeUtils' );
module.exports = Object.freeze( async ({
rawEmail,
rawPassword,
needGoogleCode,
rawGoogleCode,
ipAddress,
}) => {
console.log(
`running validateAndGetValues
with the following values - ${ stringify({
email: rawEmail,
password: <PASSWORD>,
needGoogleCode,
googleCode: rawGoogleCode,
ipAddress,
})
}`
);
const emailIsInvalid = !getIfEmailIsValid({
email: rawEmail,
});
if( emailIsInvalid ) {
const err = new Error( 'invalid email provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
const passwordIsInvalid = !getIfPasswordIsValid({
password: <PASSWORD>
});
if( passwordIsInvalid ) {
const err = new Error( 'invalid password provided' );
err.bulltrue = true;
err.statusCode = 400;
throw err;
}
if( needGoogleCode ) {
await verifyGoogleCode({
rawGoogleCode,
ipAddress,
expectedAction: actions.login
});
}
const validValues = {
email: getFormattedEmail({
rawEmail,
}),
password: <PASSWORD>
};
console.log(
'validateAndGetValues executed successfully - got values ' +
stringify( validValues )
);
return validValues;
});
<file_sep>'use strict';
const bluebird = require( 'bluebird' );
const { doBitcoinRequest } = require( '@bitcoin-api/full-stack-backend-private' );
const {
utils: { stringify }
} = require( '@bitcoin-api/full-stack-api-private' );
const maxAllowedTriesToGetTheActualFee = 5;
const getTheActualFee = Object.freeze( async ({
transactionId,
attemptNumber = 1
}) => {
console.log(
`running getTheActualFee with the following values: ${
stringify({
transactionId,
})
}
Attempt number ${ attemptNumber } of ${
maxAllowedTriesToGetTheActualFee
}.
`
);
try {
const getTransactionDataArgs = [
'gettransaction',
transactionId
];
const transactionData = JSON.parse(
await doBitcoinRequest({
args: getTransactionDataArgs
})
);
const theActualRawFee = transactionData.fee;
if(
(
!theActualRawFee &&
(theActualRawFee !== 0)
) ||
(typeof theActualRawFee !== 'number')
) {
// TODO: test error case
throw new Error(
`invalid theActualRawFee value: ${ theActualRawFee }`
);
}
const theActualFee = Math.abs( theActualRawFee );
console.log(
`getTheActualFee
executed successfully with the following values: ${
stringify({
transactionId,
attemptNumber
})
} here is the actual fee: ${ theActualFee }
`
);
return theActualFee;
}
catch( err ) {
if( attemptNumber >= maxAllowedTriesToGetTheActualFee ) {
throw new Error(
'😅unexpected ' +
`error in getTheActualFee: ${ err.message }`
);
}
console.log( 'normal error in getTheActualFee:', err );
await bluebird.delay( 2000 );
console.log( 'getTheActualFee - trying again' );
return await getTheActualFee({
transactionId,
attemptNumber: attemptNumber + 1,
});
}
});
module.exports = getTheActualFee;
<file_sep>import { getState } from '../../../../../../reduxX';
import { actions } from '../../../../../../utils';
export default async ({
raffleId,
}) => {
const ticketData = getState(
'destinyRaffle',
'raffleIdToTicketData'
)[ raffleId ];
if( !ticketData ) {
await actions.refreshes.refreshRaffleTickets({
raffleId,
});
}
};
<file_sep>'use strict';
const getHashedValue = require( '../../utils/javascript/getHashedValue' );
module.exports = Object.freeze( ({
password,
}) => {
const hashedPassword = getHashedValue( password );
return hashedPassword;
});<file_sep>'use strict';
const {
utils: {
stringify,
},
constants: {
withdraws: {
limits: {
maximumWithdrawAmount
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
// const {
// constants: {
// votes
// }
// } = require( '@bitcoin-api/full-stack-exchange-private' );
const {
errors: { ValidationError },
} = require( '../../../../../../utils' );
const {
crypto: { getCryptoAmountNumber },
validation: { getIfVoteIdIsValid },
} = require( '../../../../../../exchangeUtils' );
const minimumVoteAmount = 0;
const maximumVoteAmount = maximumWithdrawAmount;
const getIfAmountIsValid = Object.freeze( ({ amount }) => {
const amountIsValid = (
(typeof amount === 'number') &&
!Number.isNaN( amount ) &&
(amount >= minimumVoteAmount) &&
(amount <= maximumVoteAmount)
);
return amountIsValid;
});
const getIfChoiceIsValid = Object.freeze( ({ choice }) => {
const choiceIsValid = (
!!choice &&
(typeof choice === 'string') &&
(choice.length > 0) &&
(choice.length <= 100)
);
return choiceIsValid;
});
module.exports = Object.freeze( ({
rawAmount,
rawChoice,
rawVoteId,
}) => {
console.log(
`running validateAndGetValues with values: ${ stringify({
rawAmount,
rawChoice,
rawVoteId,
})}`
);
if( !getIfVoteIdIsValid({ voteId: rawVoteId }) ) {
const validationError = new ValidationError(
`invalid voteId value: ${ rawVoteId }`
);
validationError.bulltrue = true;
throw validationError;
}
else if( !getIfAmountIsValid({ amount: rawAmount }) ) {
const validationError = new ValidationError(
`invalid amount value: ${ rawAmount }`
);
validationError.bulltrue = true;
throw validationError;
}
if( rawAmount === 0 ) {
if( rawChoice !== null ) {
const validationError = new ValidationError(
'cannot provide choice if cancelling bet'
);
validationError.bulltrue = true;
throw validationError;
}
}
else if( !getIfChoiceIsValid({ choice: rawChoice }) ) {
const validationError = new ValidationError(
`invalid choice provided: ${ rawChoice }`
);
validationError.bulltrue = true;
throw validationError;
}
const values = {
amount: -getCryptoAmountNumber( rawAmount ),
voteId: rawVoteId,
choice: rawChoice,
};
console.log(
'validateAndGetValues executed successfully, ' +
'here are the values: ' +
stringify( values )
);
return values;
});
<file_sep>import * as refreshes from './refreshes';
import * as passwordReset from './passwordReset';
export { refreshes, passwordReset };
export { default as goToHomePage } from './goToHomePage';
export { default as signOut } from './signOut';
export { default as getIsLoggedIn } from './getIsLoggedIn';
export { default as getIsOnRestPage } from './getIsOnRestPage';
export { default as login } from './login';
export { default as refreshUserData } from './refreshUserData';
export { default as refreshJackpotData } from './refreshJackpotData';
export { default as refreshDensityRaffleData } from './refreshDensityRaffleData';
export { default as scroll } from './scroll';
export { default as setLastVisitedPage } from './setLastVisitedPage';
<file_sep>'use strict';
const coolCoolIdRegex = /^[0-9a-f]{32}$/;
module.exports = Object.freeze( ({
coolCoolId,
}) => {
if(
(typeof coolCoolId === 'string') &&
!!coolCoolId.match( coolCoolIdRegex )
) {
return true;
}
return false;
});<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry,
}
},
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
aws: {
database: {
tableNames: {
TRANSACTIONS
},
}
},
transactions: {
types,
// bitcoinWithdrawTypes,
},
} = require( '../../../../../constants' );
// const getTransactionId = require( './getTransactionId' );
const getNewMoneyData = require( './getNewMoneyData' );
const updateExchangeUser = require( '../../updateExchangeUser' );
module.exports = Object.freeze( async ({
exchangeUser,
transactionToAdd,
hallucinationInsights,
}) => {
console.log(
'running performDatabaseWrites with the following values: ' +
stringify({
exchangeUser,
transactionToAdd,
hallucinationInsights,
})
);
const {
existingAtaueu: {
oracleGhost: {
theOracleOfDelphiDefi
}
},
transactionCount
} = hallucinationInsights;
const databaseWrites = [];
const newMoneyData = getNewMoneyData({
exchangeUser,
theOracleOfDelphiDefi,
});
console.log( '📜performDatabaseWrites - updating user✅' );
const existingAtaueu = {
// 😎swaggy
oracleGhost: hallucinationInsights.existingAtaueu.oracleGhost,
};
const isIdentityTransaction = ( transactionToAdd.type === types.identity );
const transactionCountToUse = isIdentityTransaction ? (
transactionCount - 1
) : transactionCount;
databaseWrites.push(
updateExchangeUser({
newExchangeUser: Object.assign(
{},
exchangeUser,
{
moneyData: newMoneyData,
existingAtaueu,
transactionCount: transactionCountToUse,
}
)
})
);
if( isIdentityTransaction ) {
console.log(
'🌈performDatabaseWrites Special Case: ' +
'⛔️NOT adding transaction, is identity transaction'
);
}
else {
console.log( '📜performDatabaseWrites - adding transaction✅' );
databaseWrites.push(
updateDatabaseEntry({
tableName: TRANSACTIONS,
entry: transactionToAdd,
})
);
}
await Promise.all( databaseWrites );
console.log(
'👑🐸performDatabaseWrites executed successfully'
);
});
<file_sep>'use strict';
module.exports = Object.freeze( ({
amount,
state = null,
}) => ({
amount,
lastUpdated: Date.now(),
state
}));<file_sep>'use strict';
const {
utils: {
stringify,
// aws: {
// dino: {
// getDatabaseEntry,
// },
// },
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: { EXCHANGE_USERS }
}
},
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const verifyEmailMessageIdIsValid = require( './verifyEmailMessageIdIsValid' );
const {
aws: {
dino: {
getExchangeDatabaseEntry
}
},
javascript: {
getHashedPassword,
getExchangeUserIdData,
verificationCodeTools: {
// getVerificationCode,
getVerificationCodeComponents,
}
},
} = require( '../../../../../../exchangeUtils' );
const flamingoCrescentDecrypt = require( '../../../../../../sacredElementals/crypto/flamingoCrescentDecrypt' );
module.exports = Object.freeze( async ({
email,
password,
verifyEmailCode
}) => {
console.log(
'running ensureVerificationRequestIsValid ' +
`with the following values - ${ stringify({
email,
password,
verifyEmailCode
}) }`
);
const {
baseId,
expiryDate
} = getVerificationCodeComponents({
verificationCode: verifyEmailCode
});
if( Date.now() > expiryDate ) {
const error = new Error(
'The provided email verification link has been expired. ' +
'Please try creating your ' +
'account again. Sorry for any inconvenience.'
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
const {
exchangeUserId,
} = getExchangeUserIdData({
baseId
});
const exchangeUser = await getExchangeDatabaseEntry({
value: exchangeUserId,
tableName: EXCHANGE_USERS,
});
if( !exchangeUser ) {
const error = new Error(
'The provided email verification code is invalid.'
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
else if( !exchangeUser.emailToVerify ) {
const error = new Error(
'The provided email has already been verified.'
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
if(
!(
(
exchangeUser.emailToVerify ===
email
) &&
(
flamingoCrescentDecrypt({
text: exchangeUser.hashedPassword
}) === getHashedPassword({ password })
) &&
(
exchangeUser.verifyEmailCode ===
verifyEmailCode
)
)
) {
const error = new Error(
'The provided data for email verification is invalid.'
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
await verifyEmailMessageIdIsValid({
email,
emailMessageId: exchangeUser.emailMessageId,
expiryDate,
});
const responseValues = {
exchangeUserId,
};
console.log(
'ensureVerificationRequestIsValid executed successfully - ' +
`returning values: ${ stringify( responseValues ) }`
);
return responseValues;
});
<file_sep>'use strict';
const {
transactions: {
types,
}
} = require( '../../../../../../constants' );
const getCryptoAmountNumber = require(
'../../../../../crypto/getCryptoAmountNumber'
);
module.exports = Object.freeze( ({
theOracleOfDelphiDefi,
}) => {
const {
[types.dream]: {
totalCryptoAmount,
},
} = theOracleOfDelphiDefi;
const dreamData = {
crypto: {
amount: getCryptoAmountNumber( totalCryptoAmount ),
},
lastUpdated: Date.now(),
};
return dreamData;
});
<file_sep>'use strict';
const updateAlienBalanceData = require( './updateAlienBalanceData' );
exports.handler = Object.freeze( async () => {
console.log( '🆙👾⚖️📀 Running updateAlienBalanceData' );
try {
await updateAlienBalanceData();
// await addCacheOnAndOffStatusToRhino( cacheOnAndOffStatus );
console.log( '🆙👾⚖️📀 updateAlienBalanceData executed successfully' );
}
catch( err ) {
console.log( '🆙👾⚖️📀 error in updateAlienBalanceData:', err );
}
// trigger next lambda function no matter what
});
<file_sep>#!/usr/bin/env node
'use strict';
const argv = require( 'yargs' ).argv;
const isProductionMode = argv.mode === 'production';
if( isProductionMode ) {
require( 'dotenv' ).config({ path: `${ __dirname }/productionCredentials/.env` });
}
else {
require( 'dotenv' ).config({ path: `${ __dirname }/stagingCredentials/.env` });
}
const {
utils: {
bitcoin: {
formatting: {
getAmountNumber
}
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser
}
},
},
constants: {
transactions: {
types: {
bonus
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const exchangeUserId = argv.e;
const searchId = argv.s;
if( !exchangeUserId || !searchId ) {
throw new Error( 'Award Bonus - missing values' );
}
const amount = getAmountNumber( argv.amount || argv.a );
if(
Number.isNaN( amount ) ||
(amount > 0.0001) ||
(amount < 0)
) {
throw new Error( `invalid amount: ${ amount }` );
}
const bonusData = [
{
exchangeUserId,
bitcoinAmount: amount,
cryptoAmount: 0,
// bitcoinAmount: 0.00015,
// searchId: 'First1000DynastySatsBonus',
searchId,
}
];
const awardBonus = Object.freeze( async ({
exchangeUserId,
bitcoinAmount,
cryptoAmount,
searchId,
}) => {
console.log(
'🎁📈📈📈adding bonus with the following values: ',
JSON.stringify({
exchangeUserId,
bitcoinAmount,
cryptoAmount,
searchId,
}, null, 4 )
);
await addTransactionAndUpdateExchangeUser({
exchangeUserId,
type: bonus,
data: {
bitcoinAmount,
cryptoAmount,
searchId,
}
});
console.log( '🎁📈📈📈bonus added successfully' );
});
(async () => {
try {
console.log( `✅Awarding ${ bonusData.length } bonus(es)` );
for( const bonusDatum of bonusData ) {
await awardBonus( bonusDatum );
}
console.log( `💯Awarded ${ bonusData.length } bonus(es)` );
process.exit( 0 );
}
catch( err ) {
console.log( '❌error in awarding bonus(es):', err );
process.exit( 1 );
}
})();
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const destroyLickFile = require( './destroyLickFile' );
const fs = require( 'fs' );
const oneMinute = 60 * 1000;
module.exports = Object.freeze( async ({
pathToLickFile,
}) => {
console.log(
`running getValidLickFileInfo from path: ${ pathToLickFile }`
);
const lickFile = await new Promise( ( resolve, reject ) => {
fs.readFile(
pathToLickFile,
( err, data ) => {
if( !!err ) {
if( err.code === 'ENOENT' ) {
return resolve( null );
}
return reject( err );
}
const lickFile = JSON.parse( data.toString() );
resolve( lickFile );
}
);
});
if( !lickFile ) {
console.log(
'getValidLickFileInfo executed successfully (no-op) - ' +
'no lick file'
);
return null;
}
console.log( `got lickFile ${ stringify( lickFile ) }` );
await destroyLickFile({
pathToLickFile
});
const {
deployId,
operationTime,
operationExpiry,
deployCommand,
forceDeploy,
} = lickFile;
if(
!deployId ||
(typeof deployId !== 'string')
) {
console.log(
'getValidLickFileInfo executed successfully (no-op) - ' +
'lick_file with no deployId'
);
return null;
}
else if(
!operationExpiry ||
(typeof operationExpiry !== 'number')
) {
console.log(
'getValidLickFileInfo executed successfully (no-op) - ' +
'lick_file with no operationExpiry'
);
return null;
}
else if(
!operationTime ||
(typeof operationTime !== 'number') ||
(
(operationTime + oneMinute) <
Date.now()
)
) {
console.log(
'getValidLickFileInfo executed successfully (no-op) - ' +
`lick_file with invalid operationTime: ${ operationTime }`
);
return null;
}
const lickFileInfo = {
deployId,
operationExpiry,
deployCommand,
forceDeploy
};
console.log(
'getValidLickFileInfo executed successfully - ' +
`got lickFileInfo: ${ stringify( lickFileInfo ) }`
);
return lickFileInfo;
});
<file_sep>import { setState } from '../../reduxX';
import { story } from '../../constants';
export default () => {
setState(
// actual page resets
{
keys: 'metaMode',
value: null
},
{
keys: [ 'notLoggedInMode', 'freeGame' ],
value: null,
},
{
keys: [ 'notLoggedInMode', 'mainMode' ],
value: story.NotLoggedInMode.mainModes.initialChoiceMode,
},
{
keys: [ 'loggedInMode', 'mode' ],
value: story.LoggedInMode.modes.base,
},
// other relevant state changes
{
keys: [ 'forgotMyPasswordPolygon', 'successEmail' ],
value: null,
}
);
};<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const validateAndGetValues = require( './validateAndGetValues' );
const getMostRecentVoteTransaction = require( '../../../../../../sacredElementals/probability/votes/getMostRecentVoteTransaction' );
module.exports = Object.freeze( async ({
// event,
exchangeUserId,
rawVoteId,
}) => {
console.log(
'running getVote with the following values: ' +
stringify({
exchangeUserId,
rawVoteId,
})
);
const {
voteId,
} = validateAndGetValues({
rawVoteId,
});
const mostRecentVoteTransaction = await getMostRecentVoteTransaction({
exchangeUserId,
voteId,
});
if( !mostRecentVoteTransaction ) {
const results = {
choice: null,
voteType: null,
amount: 0,
metadata: {}
};
console.log(
'getVote executed successfully - ' +
`no vote info for vote "${ voteId }" - ` +
`returning results ${ stringify( results ) }`
);
return results;
}
const results = {
choice: mostRecentVoteTransaction.choice,
voteType: mostRecentVoteTransaction.voteType,
amount: Math.abs( mostRecentVoteTransaction.amount ),
metadata: Object.assign(
{
time: mostRecentVoteTransaction.creationDate,
},
mostRecentVoteTransaction.metadata || {}
),
};
console.log(
'getVote executed successfully - ' +
`got vote info for vote "${ voteId }" - ` +
`returning results ${ stringify( results ) }`
);
return results;
});
<file_sep>const getBaseResults = ({
isValid = false,
data = null,
} = {
isValid: false,
data: null,
}) => ({
isValid,
data,
});
const getGetResultsOrThrowError = ({
shouldThrowError
}) => ({
message,
}) => {
if( shouldThrowError ) {
throw new Error( message );
}
return getBaseResults();
};
export default ({
passwordResetCode,
shouldThrowError = false,
}) => {
const getResultsOrThrowError = getGetResultsOrThrowError({
shouldThrowError
});
if( !passwordResetCode ) {
return getResultsOrThrowError({
message: 'missing password reset code',
});
}
if( typeof passwordResetCode !== 'string' ) {
return getResultsOrThrowError({
message: 'invalid password reset code - is not string',
});
}
const splitPasswordResetCode = passwordResetCode.split( '-' );
if( splitPasswordResetCode.length !== 4 ) {
return getResultsOrThrowError({
message: 'invalid password reset code',
});
}
const exchangeUserId = splitPasswordResetCode[1];
const coolCoolId = splitPasswordResetCode[2];
const expiryTime = Number( splitPasswordResetCode[3] );
if(
!(
(splitPasswordResetCode[0] === 'prc') &&
exchangeUserId.startsWith( 'exchange_user_' ) &&
(exchangeUserId.length > 5) &&
(exchangeUserId.length < 100) &&
(coolCoolId.length > 5) &&
(coolCoolId.length < 100) &&
Number.isInteger( expiryTime ) &&
(expiryTime > 69420) &&
(expiryTime < 76129040221370)
)
) {
return getResultsOrThrowError({
message: 'invalid password reset code',
});
}
return getBaseResults({
isValid: true,
data: {
exchangeUserId,
expiryTime
}
});
};
<file_sep>'use strict';
// const {
// utils: {
// stringify,
// bitcoin: {
// formatting: { getAmountNumber }
// },
// },
// } = require( '@bitcoin-api/full-stack-api-private' );
const getCryptoAmountNumber = require( '../../crypto/getCryptoAmountNumber' );
module.exports = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const cryptoBalanceData = {};
const cryptoBalanceDataFromExchangeUser = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.dream &&
!!exchangeUser.moneyData.dream.crypto &&
exchangeUser.moneyData.dream.crypto
) || null;
if( !cryptoBalanceDataFromExchangeUser ) {
Object.assign(
cryptoBalanceData,
{
totalAmount: 0,
}
);
}
else {
Object.assign(
cryptoBalanceData,
{
totalAmount: getCryptoAmountNumber(
cryptoBalanceDataFromExchangeUser.amount
),
}
);
}
balanceData.crypto = cryptoBalanceData;
});
<file_sep>import getIsLoggedIn from './getIsLoggedIn';
import { getState } from '../../reduxX';
import { story } from '../../constants';
export default () => {
const metaMode = getState( 'metaMode' );
if(
!!metaMode &&
(metaMode !== story.metaModes.zeroPointEnergy)
) {
return false;
}
const freeGameMode = !!getState( 'notLoggedInMode', 'freeGame' );
if( freeGameMode ) {
return false;
}
const isLoggedIn = getIsLoggedIn();
if( isLoggedIn ) {
const thereIsUserData = !!getState( 'loggedInMode', 'userData' );
if( thereIsUserData ) {
return true;
}
return false;
}
const notLoggedInMode = getState( 'notLoggedInMode', 'mainMode' );
if(
!notLoggedInMode ||
(
notLoggedInMode ===
story.NotLoggedInMode.mainModes.initialChoiceMode
)
) {
return true;
}
return false;
};
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils:{
aws: {
dino: {
getExchangeDatabaseEntry
}
}
},
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_USERS,
}
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
throwStandardError,
} = require( '../../../../../../utils' );
module.exports = Object.freeze( async ({
exchangeUserId,
exchangeUser,
}) => {
console.log(
'running ensureNoExistingAddress ' +
`with the following values: ${ stringify({
exchangeUserId,
'exchangeUser has been provided': !!exchangeUser
}) }`
);
if( !exchangeUser ) {
console.log(
'running ensureNoExistingAddress ' +
`with the following values: ${ stringify({
exchangeUserId,
exchangeUser: !!exchangeUser
}) }`
);
exchangeUser = await getExchangeDatabaseEntry({
tableName: EXCHANGE_USERS,
value: exchangeUserId,
});
if( !exchangeUser ) {
// safeguard
return throwStandardError({
message: (
`exchange user with id ${ exchangeUserId } ` +
'has not been found'
),
statusCode: 500,
});
}
}
if(
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.bitcoin &&
(exchangeUser.moneyData.bitcoin.length >= 1)
) {
return throwStandardError({
message: (
'user already has Bitcoin address'
),
statusCode: 400,
bulltrue: true
});
}
console.log(
'ensureNoExistingAddress executed successfully'
);
});
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const validateAndGetValues = require( './validateAndGetValues' );
const getData = require( './getData' );
const mappyMappyTransactions = require( './mappyMappyTransactions' );
module.exports = Object.freeze( async ({
exchangeUserId,
rawLastTransactionId,
rawLastTime,
smallBatch,
}) => {
console.log(
`running getMoneyActionData with the following values - ${
stringify({
exchangeUserId,
rawLastTransactionId,
rawLastTime,
smallBatch,
})
}`
);
const {
lastTime,
lastTransactionId,
} = validateAndGetValues({
rawLastTransactionId,
rawLastTime,
});
const data = await getData({
exchangeUserId,
lastTime,
lastTransactionId,
smallBatch,
});
const moneyActionData = {
moneyActions: mappyMappyTransactions({
transactions: data.transactions
}),
lastTime: data.lastTime,
lastTransactionId: data.lastTransactionId
};
console.log(
`getMoneyActionData executed successfully -
returning moneyActionData: ${
stringify( Object.keys( moneyActionData ) )
}`
);
return moneyActionData;
});<file_sep>'use strict';
const {
utils: {
redis: {
getClient,
},
stringify
},
constants: {
environment: {
isProductionMode
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const f = Object.freeze;
const {
constants: {
dragonErrorStatusCode
},
} = require( './localTools' );
const runIpAddressDragonInspection = require(
'./runIpAddressDragonInspection'
);
const getDragonsToInspectBankStatus = require(
'./getDragonsToInspectBankStatus'
);
const getDragonsToMakeSureBankIsOn = require(
'./getDragonsToMakeSureBankIsOn'
);
const getDragonsToInspectTheMegaCode = require(
'./getDragonsToInspectTheMegaCode'
);
const runAltruisticCodeDragonInspection = require(
'./runAltruisticCodeDragonInspection'
);
module.exports = f( async ({
queueName,
event,
necessaryDragonDirective = 1,
megaCodeIsRequired = true,
ipAddressMaxRate = 6,
ipAddressTimeRange = 60 * 1000,
advancedCodeMaxRate = 6,
advancedCodeTimeRange = 60 * 1000,
altruisticCode = null,
altruisticCodeIsRequired = false,
altruisticCodeMaxRate = 6,
altruisticCodeTimeRange = 60 * 1000,
customDragonFunction = async () => {},
}) => {
const dragonFindings = {};
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'🐉🐲Dragon Protection Activated🐉🐲\n' +
'☢️🐑Yes, once again, it is time. ' +
'Time to unleash the dragons! 🐉🐉🐉🐲🔥🔥🔥🔥🔥 ' +
`${
stringify({
megaCodeIsRequired,
necessaryDragonDirective,
queueName
})
}`
);
event = event || {};
const maintenanceModeCode = process.env.MAINTENANCE_MODE_CODE || 'off';
if(
(maintenanceModeCode !== 'off') &&
!(
!!event &&
!!event.headers &&
(
event.headers.bulltrueTech7df97Code54f8cWowd8ea897d7b1182 ===
maintenanceModeCode
)
)
) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'The API is in maintenance mode and ' +
'the user is not bulltrueing ⛔️🐄'
);
const standardMessage = (
'This web command is ' +
'unavailable at the moment.'
// 'This Bitcoin-Api.io API endpoint is ' +
// 'unavailable at the moment ' +
// 'due to maintenance. ' +
// 'This endpoint will be active again ' +
// 'as soon as possible. We thank you for your patience and ' +
// 'understanding.'
);
const maintenanceModeMessage = process.env.MAINTENANCE_MODE_MESSAGE;
const message = !maintenanceModeMessage ? standardMessage : (
standardMessage + ` ${ maintenanceModeMessage }`
);
const error = new Error( message );
error.bulltrue = true;
error.statusCode = 503;
throw error;
}
const ipAddress = (
!!event.data &&
!!event.data.ipAddress &&
event.data.ipAddress
);
dragonFindings.ipAddress = ipAddress;
const eventHeader = (
!!event.headers &&
event.headers
) || {};
const megaCode = (
eventHeader.Token ||
eventHeader.token ||
null
);
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
`Given credential info: ${ stringify({
ipAddress,
megaCodeCrazyInfo: (
!!megaCode &&
(typeof megaCode === 'string') &&
(megaCode.length > 0) &&
megaCode.length
) || 'no mega code/invalid mega code'
}) }`
);
if(
!ipAddress ||
(
megaCodeIsRequired &&
!megaCode
)
) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'missing required values, ROOOOOOARRR, ' +
'YOU ARE BANISHED!🐲🔥🔥🔥🔥🔥'
);
const error = new Error( 'invalid credentials' );
error.bulltrue = true;
error.statusCode = dragonErrorStatusCode;
throw error;
}
const redisClient = getClient();
let errorInCustomDragonFunctionInvocation = null;
let errorInIpAddressDragonInspection = null;
let errorInBankStatusDragonInspection = null;
let errorInBankIsOnOrOffDragonInspection = null;
let errorInMegaCodeDragonInspection = null;
let errorInAltruisticCodeDragonInspection = null;
try {
const dragonInspections = [
(async () => {
try {
await customDragonFunction();
}
catch( err ) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'the customDragonFunction has failed! ' +
'Here is the error that has occurred: ' +
`${ err }. ` +
'Yikes, this is 100% not ideal🐲🐉🔥🔥🔥🔥🔥!'
);
errorInCustomDragonFunctionInvocation = err;
}
})(),
(async () => {
try {
await getDragonsToMakeSureBankIsOn({
redisClient
});
}
catch( err ) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'while the dragons inspected if the ' +
'bank is on or off, an error has occurred: ' +
`${ err }. WOW, this is insane🐲🐉🔥🔥🔥🔥🔥`
);
errorInBankIsOnOrOffDragonInspection = err;
}
})(),
(
isProductionMode ||
(
process.env.SHOULD_CONSIDER_BANK_STATUS_IN_STAGING_MODE ===
'yes'
)
) && (async () => {
try {
await getDragonsToInspectBankStatus({
redisClient,
});
}
catch( err ) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'while the dragons inspected the bank status, ' +
'they have determined that an error has occurred: ' +
`${ err }. WOW, careful there buddy🐲🐉🔥🔥🔥🔥🔥`
);
errorInBankStatusDragonInspection = err;
}
})(),
(async () => {
try {
await runIpAddressDragonInspection({
redisClient,
ipAddress,
queueName,
maxRate: ipAddressMaxRate,
timeRange: ipAddressTimeRange,
});
}
catch( err ) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'error occurred in ip address dragon inspection: ' +
err +
' - Waiting for other dragon inspections before ' +
'throwing this error. (they might error first)🤠'
);
errorInIpAddressDragonInspection = err;
}
})()
];
if( megaCodeIsRequired ) {
dragonInspections.push(
(async () => {
try {
await getDragonsToInspectTheMegaCode({
megaCode,
queueName,
redisClient,
dragonFindings,
advancedCodeMaxRate,
advancedCodeTimeRange,
necessaryDragonDirective,
});
}
catch( err ) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'error occurred in mega code dragon inspection: ' +
err +
' - Waiting for other dragon inspections before ' +
'throwing this error. (they might error first)🤠'
);
errorInMegaCodeDragonInspection = err;
}
})()
);
}
if( altruisticCodeIsRequired ) {
dragonInspections.push(
(async () => {
try {
await runAltruisticCodeDragonInspection({
redisClient,
altruisticCode,
queueName,
maxRate: altruisticCodeMaxRate,
timeRange: altruisticCodeTimeRange,
});
}
catch( err ) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'error occurred in altruistic code ' +
'dragon inspection: ' +
err +
' - Waiting for other dragon ' +
'inspections before ' +
'throwing this error. ' +
'😎(they might error first)🤠'
);
errorInAltruisticCodeDragonInspection = err;
}
})()
);
}
await Promise.all( dragonInspections );
[
errorInCustomDragonFunctionInvocation,
errorInBankIsOnOrOffDragonInspection,
errorInBankStatusDragonInspection,
errorInIpAddressDragonInspection,
errorInMegaCodeDragonInspection,
errorInAltruisticCodeDragonInspection
].forEach( possibleError => {
if( !!possibleError ) {
throw possibleError;
}
});
redisClient.quit();
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'The guard dragons have not eaten you🐟🐠🍣🤠🐉🐲(wow, lucky). ' +
'You may enter, for now... ' +
'Beginning dragon protection executed successfully.🦖🍄'
);
return dragonFindings;
}
catch( err ) {
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'error in redis based functions, wow, ' +
'quitting redis.'
);
redisClient.quit();
throw err;
}
});
<file_sep>'use strict';
const {
utils: {
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
// const getTransactionId = require( './getTransactionId' );
const getNewBitcoinData = require( './getNewBitcoinData' );
const getBitcoinWithdrawsData = require( './getBitcoinWithdrawsData' );
const getExchangeData = require( './getExchangeData' );
const getDreamData = require( './getDreamData' );
const getVoteData = require( './getVoteData' );
const getRaffleData = require( './getRaffleData' );
const getBonusData = require( './getBonusData' );
const getAlienBalanceData = require( './getAlienBalanceData' );
module.exports = Object.freeze( ({
exchangeUser,
theOracleOfDelphiDefi,
}) => {
console.log(
'running getNewMoneyData with the following values: ' +
stringify({
exchangeUser,
theOracleOfDelphiDefi,
})
);
const newMoneyData = {
bitcoin: getNewBitcoinData({
exchangeUser,
theOracleOfDelphiDefi,
}),
bitcoinWithdraws: getBitcoinWithdrawsData({
theOracleOfDelphiDefi,
}),
exchange: getExchangeData({
theOracleOfDelphiDefi,
}),
dream: getDreamData({
theOracleOfDelphiDefi,
}),
vote: getVoteData({
theOracleOfDelphiDefi,
}),
raffle: getRaffleData({
theOracleOfDelphiDefi,
}),
bonus: getBonusData({
theOracleOfDelphiDefi,
}),
alienBalance: getAlienBalanceData({
theOracleOfDelphiDefi,
}),
};
console.log(
'getNewMoneyData executed successfully, returning money data:',
newMoneyData
);
return newMoneyData;
});
<file_sep>import BitcoinExchange from './BitcoinExchange';
// const TestBitcoinExchange
// const bitcoinExchange = !!process.env.TEST_MODE ? (
// new BitcoinExchange({})
// ) : ;
const bitcoinExchange = new BitcoinExchange({});
export default bitcoinExchange;<file_sep>'use strict';
const {
aws: { database: { tableNames: { USERS } } }
} = require( '../constants' );
const { Crypto } = require( '../javascript' );
// const { NotAuthorizedError } = require( '../errors' );
const {
getDecodedReturnCode, getTemplarCode
} = require( '../accessCodeTools' );
const validateReturnCode = require( '../validation/validateReturnCode' );
const {
utils: { aws: { dino: { getDatabaseEntry } } }
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( async ({
returnCode
}) => {
console.log( '🛡Running Authorize User🛡' );
await validateReturnCode({ returnCode });
const decodedReturnCode = getDecodedReturnCode({ returnCode });
const userFromDatabase = await getDatabaseEntry({
value: decodedReturnCode.userId,
tableName: USERS,
});
if( !userFromDatabase ) {
const errorMessage = (
'ERROR: utils.auth.authorizeUser error: ' +
'invalid userId found in return code: ' +
returnCode
);
console.log( errorMessage );
const err = new Error( 'unauthorized' );
err.statusCode = 401;
err.bulltrue = true;
throw err;
}
const templarCodeFromRequest = getTemplarCode({
megaCode: decodedReturnCode.megaCode
});
const templarCodeFromDatabase = Crypto.decrypt({
text: userFromDatabase.accessCode,
encryptionId: userFromDatabase.encryptionId
});
const theReturnCodeDoesNotHaveTheCorrectMegaCode = (
templarCodeFromRequest !== templarCodeFromDatabase
);
if( theReturnCodeDoesNotHaveTheCorrectMegaCode ) {
const errorMessage = (
'👁🔻ERROR🚩🚩🔻🐙: WARNING: WOW: ' +
'utils.auth.authorizeUser error: ' +
'invalid mega code found in return code🔻👁: ' +
returnCode
);
console.log( errorMessage );
const err = new Error( 'unauthorized' );
err.statusCode = 401;
err.bulltrue = true;
throw err;
}
console.log( '🦕🛡User is Authorized🛡🦖' );
const returnValues = {
user: userFromDatabase
};
return returnValues;
});
<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../../reduxX';
import { validation, dynastyBitcoin } from '../../../utils';
import { gameData, games } from '../../../constants';
import { withStyles } from '@material-ui/core/styles';
import Box from '@material-ui/core/Box';
import Slider from '@material-ui/core/Slider';
import Input from '@material-ui/core/Input';
// import Typography from '@material-ui/core/Typography';
import InputAdornment from '@material-ui/core/InputAdornment';
const theGameData = gameData[ games.theDragonsTalisman ];
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: 'lightgreen',
// backgroundColor: 'black',
marginTop: 25,
marginBottom: 25,
width: '95%',
maxWidth: 332,
borderRadius: 5,
// height: 300,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
title: {
width: '90%',
marginTop: 5,
// textDecoration: 'underline'
},
theRow: {
// backgroundColor: 'pink',
// backgroundColor: 'black',
width: '100%',
// height: 100,
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
};
};
// const diamondMin = theGameData.diamondMin;
// const diamondMax = theGameData.diamondMax;
const diamondStepCount = theGameData.diamondStepCount;
// const jackpotMin = theGameData.jackpotMin;
// const jackpotMax = 0.00008;
// const jackpotMax = theGameData.jackpotMax;
const jackpotStepCount = theGameData.jackpotStepCount;
const getSliderMarksData = ({
step,
addInitialMark = false,
stepCount,
}) => {
const sliderMarksData = [];
if( addInitialMark ) {
sliderMarksData.push({
value: 0.00001,
});
}
for( let i = 1; i <= stepCount; i++ ) {
sliderMarksData.push({
value: dynastyBitcoin.getDynastyBitcoinAmount(
step * i
)
});
}
return sliderMarksData;
};
const getSliderValue = ({
selectedAmountAsNumber,
min,
max,
}) => {
if(
(typeof selectedAmountAsNumber === 'number') &&
!Number.isNaN(selectedAmountAsNumber)
) {
if( selectedAmountAsNumber > max ) {
return max;
}
else if( selectedAmountAsNumber < min ) {
return min;
}
return selectedAmountAsNumber;
}
return min;
};
const PrettoSlider = withStyles({
root: {
color: '#52af77',
// height: 8,
},
thumb: {
// height: 24,
// width: 24,
backgroundColor: 'green',
// border: '2px solid currentColor',
// marginTop: -8,
// marginLeft: -12,
// '&:focus, &:hover, &$active': {
// boxShadow: 'inherit',
// },
},
// active: {},
// valueLabel: {
// left: 'calc(-50% + 4px)',
// },
// track: {
// height: 8,
// borderRadius: 4,
// },
// rail: {
// height: 8,
// borderRadius: 4,
// },
})( Slider );
export default ({
freeGameMode,
isJackpotMode,
min,
max
}) => {
const styles = getStyles();
const isLoading = getState( 'isLoading' );
const mainStateMode = freeGameMode ? 'notLoggedInMode' : 'loggedInMode';
const selectedAmount = getState(
mainStateMode,
'coinFlip',
'selectedAmount'
);
const selectedAmountAsNumber = Number( selectedAmount );
let addInitialMark;
let stepCount;
if( isJackpotMode ) {
stepCount = jackpotStepCount;
addInitialMark = true;
}
else {
stepCount = diamondStepCount;
addInitialMark = false;
}
const step = dynastyBitcoin.getDynastyBitcoinAmount(
max / stepCount
);
const sliderValue = getSliderValue({
selectedAmountAsNumber,
min,
max,
});
const marks = getSliderMarksData({
step,
addInitialMark,
stepCount
});
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.theRow,
},
e(
PrettoSlider,
{
disabled: isLoading,
marks,
min,
max,
step,
style: {
width: 150,
},
onChange: ( event, newValue ) => {
// get crypto amount
setState(
[
mainStateMode,
'coinFlip',
'selectedAmount'
],
newValue
);
},
// valueLabelDisplay: 'auto',
'aria-labelledby': 'input-slider',
value: sliderValue,
}
),
e(
Input,
{
disabled: isLoading,
endAdornment: e(
InputAdornment,
{
position: 'end'
},
'DB'
),
style: {
width: 93,
marginBottom: 5,
},
onChange: event => {
const newValue = event.target.value;
// get crypto amount
// const newValueAsNumber = Number( newValue );
const amountIsValid = validation.isValidNumberTextInput({
text: newValue,
maxAmount: max,
allowedNumberOfDecimals: 5
});
if( !amountIsValid ) {
return;
}
setState(
[
mainStateMode,
'coinFlip',
'selectedAmount'
],
newValue
);
},
// type: 'number',
// increment: 0.1,
// valueLabelDisplay: 'auto',
'aria-labelledby': 'input-slider',
value: selectedAmount
}
)
)
);
};
<file_sep>export { default as getRandomIntInclusive } from './getRandomIntInclusive';<file_sep>// TODO: extract from constants
const PROD_API_URL = 'https://l485y92hcf.execute-api.ca-central-1.amazonaws.com';
const THE_DYNASTY = 'DynastyBitcoin.com';
export default () => {
if(
(
process.env.REACT_APP_EXCHANGE_API_BASE_URL ===
PROD_API_URL
) &&
(
process.env.REACT_APP_WEBSITE_NAME ===
THE_DYNASTY
) &&
!window.location.hostname.includes( 'dynastybitcoin.com' )
) {
window.location = 'https://www.dynastybitcoin.com';
}
};
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
width: '100%',
// minWidth: '100%',
// height: 100,
// backgroundColor: 'pink',
display: 'flex',
justifyContent: 'flex-start',
flexDirection: 'column',
alignItems: 'center'
},
text: {
width: '100%',
// height: 100,
color: 'black',
marginTop: 15,
marginBottom: 5,
// padding: 5,
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
Typography,
{
style: styles.text,
},
`• Spin slot for 0.0001 DB (10 Satoshi)`
),
e(
Typography,
{
style: styles.text,
},
`• all different -> tie with 0.0001 DB (10 Satoshi)`
),
e(
Typography,
{
style: styles.text,
},
`• 3 same -> win 0.0007 DB (70 Satoshi)!`
),
);
};
<file_sep>'use strict';
module.exports = Object.freeze( ({
voteId,
}) => {
const voteIdIsValid = (
!!voteId &&
(typeof voteId === 'string') &&
(voteId.length >= 2) &&
(voteId.length <= 100) &&
(voteId !== 'undefined') &&
(voteId !== 'null')
);
return voteIdIsValid;
});<file_sep>'use strict';
const pseudoEncrypt = require( './pseudo' );
module.exports = ({
exchangeUserId,
}) => {
const psuedoOmega1 = pseudoEncrypt({
text: exchangeUserId
});
return psuedoOmega1;
};
<file_sep>'use strict';
const bluebird = require( 'bluebird' );
const {
utils: {
aws: {
dinoCombos: {
balances: {
updateBalance
}
}
},
stringify
},
constants: {
users: {
balanceTypes: {
bitcoinNodeIn
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
mongo,
constants: {
megaServerId
},
} = require( '@bitcoin-api/full-stack-backend-private' );
module.exports = Object.freeze( async ({
userIdToBitcoinNodeAmountIn,
mongoCollections
}) => {
const userIds = Object.keys( userIdToBitcoinNodeAmountIn );
console.log(`
running updateUserBalanceData, YES🐺
updating ${ userIds.length } users
`);
await bluebird.map( userIds, async userId => {
const newBalance = userIdToBitcoinNodeAmountIn[ userId ];
const cachedUserData = (
await mongo.search({
collection: mongoCollections.user_data,
query: {
userId,
},
queryOptions: {
limit: 1,
}
})
)[0];
if(
!!cachedUserData &&
(cachedUserData.lastUpdateBalance === newBalance)
) {
return console.log(`
cache value the same for user: ${ userId }
no update required
`);
}
await updateBalance({
userId,
balanceType: bitcoinNodeIn,
balanceId: megaServerId,
newBalance,
});
const userData = {
lastUpdateBalance: newBalance
};
console.log(
`adding user_data to cache: ${ stringify( userData )}`
);
await mongo.update({
collection: mongoCollections.user_data,
query: {
userId,
},
newValue: {
$set: userData
}
});
}, { concurrency: 3 });
console.log(`
updateUserBalanceData exeucted successfully, YES BABY🌹🌹🌹!!
updated ${ userIds.length } users
`);
});
<file_sep>import { createElement as e } from 'react';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
const getStyles = ({
isLoadingMode,
marginTop,
marginBottom,
borderRadius,
backgroundColor,
color,
width,
}) => {
return {
outerContainer: {
width,
marginTop,
marginBottom,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
POW: {
backgroundColor: isLoadingMode ? 'grey' : backgroundColor,
borderRadius,
width: '100%',
// padding: 20,
userSelect: 'none',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
color,
},
};
};
export default ({
onClick,
text,
isLoadingMode,
marginTop = 0,
marginBottom = 0,
borderRadius = 4,
width = 300,
backgroundColor = 'beige',
color = 'black',
form,
}) => {
const styles = getStyles({
isLoadingMode,
marginTop,
marginBottom,
borderRadius,
backgroundColor,
color,
width,
});
return e(
Paper,
{
style: styles.outerContainer,
},
e(
Button,
{
form,
style: styles.POW,
disabled: isLoadingMode,
onClick: isLoadingMode ? () => {} : onClick,
},
text
)
);
};
<file_sep>'use strict';
const MongoClient = require( 'mongodb' ).MongoClient;
module.exports = Object.freeze( ({
collectionNames
}) => new Promise( ( resolve, reject ) => {
console.log( 'connecting to mongodb' );
const url = process.env.MONGO_DB_URL;
if( !url ) {
throw new Error( 'missing required mongo db url' );
}
const client = new MongoClient(
url,
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
client.connect( err => {
if( !!err ) {
console.log( 'an error occurred initializing mongodb' );
if( !!client && !!client.close ) {
client.close();
}
return reject(
new Error( `Error in connecting to mongo: ${ err }` )
);
}
const db = client.db();
const collections = {};
for( const collectionName of collectionNames ) {
collections[ collectionName ] = db.collection( collectionName );
}
console.log( 'successfully initialized mongodb' );
const disconnect = Object.freeze( () => {
console.log( 'disconnecting from mongodb' );
return new Promise( ( resolve, reject ) => {
client.close( err => {
if( !!err ) {
return reject( err );
}
resolve();
});
});
});
resolve({
// client,
// db,
collections,
disconnect
});
});
}));<file_sep>'use strict';
module.exports = require(
'@bitcoin-api/full-stack-exchange-private'
).utils.crypto.getCryptoAmountNumber;<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const validateAndGetValues = require( './validateAndGetValues' );
const getTicketsData = require( './getTicketsData' );
module.exports = Object.freeze( async ({
rawRaffleId,
rawTime,
rawPowerId,
rawSpecialId
}) => {
console.log(
`running getRaffleTicketsData with the following values - ${
stringify({
rawRaffleId,
rawTime,
rawPowerId,
rawSpecialId,
})
}`
);
const {
raffleId,
time,
transactionId,
specialId,
} = validateAndGetValues({
rawRaffleId,
rawTime,
rawPowerId,
rawSpecialId,
});
const ticketsData = await getTicketsData({
raffleId,
time,
transactionId,
specialId,
});
console.log(
`getRaffleTicketsData executed successfully -
returning raffle tickets: ${
stringify({
'number of tickets': ticketsData.tickets.length,
'page info': ticketsData.pageInfo
})
}`
);
return ticketsData;
});<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase
}
},
stringify,
},
constants: {
environment: {
isProductionMode
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
TRANSACTIONS
},
secondaryIndices: {
searchIdCreationDateIndex
}
}
},
// transactions: {
// types: {
// raffle
// }
// },
raffles: {
types: {
putTicket
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const searchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
raffleType: '#raffleType',
searchId: '#searchId',
creationDate: '#creationDate',
amount: '#amount',
}),
nameValues: f({
raffleType: 'raffleType',
searchId: 'searchId',
creationDate: 'creationDate',
amount: 'amount',
}),
valueKeys: f({
raffleType: ':raffleType',
searchId: ':searchId',
currentHour: ':currentHour',
}),
});
// TODO: use sacred elements
module.exports = Object.freeze( async ({
raffleId,
currentHour
}) => {
console.log(
'running getCryptoPotData with the following values: ' +
stringify({
raffleId,
currentHour,
})
);
let cryptoPot = 0;
let paginationValueToUse = null;
let iterationCount = 0;
do {
console.log(
'getCryptoPotData - ' +
'running transactions search: ' +
stringify({
cryptoPot,
paginationValueToUse,
iterationCount,
})
);
const searchParams = {
TableName: TRANSACTIONS,
IndexName: searchIdCreationDateIndex,
Limit: searchLimit,
ScanIndexForward: true,
ProjectionExpression: [
attributes.nameKeys.amount
].join( ', ' ),
KeyConditionExpression: (
`${ attributes.nameKeys.searchId } = ${ attributes.valueKeys.searchId } and ` +
`${ attributes.nameKeys.creationDate } <= ${ attributes.valueKeys.currentHour }`
),
FilterExpression: (
`${ attributes.nameKeys.raffleType } = ${ attributes.valueKeys.raffleType }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.raffleType]: attributes.nameValues.raffleType,
[attributes.nameKeys.searchId]: attributes.nameValues.searchId,
[attributes.nameKeys.creationDate]: attributes.nameValues.creationDate,
[attributes.nameKeys.amount]: attributes.nameValues.amount,
},
ExpressionAttributeValues: {
[attributes.valueKeys.searchId]: raffleId,
[attributes.valueKeys.raffleType]: putTicket,
[attributes.valueKeys.currentHour]: isProductionMode ? currentHour : Date.now(),
// [attributes.valueKeys.currentHour]: Date.now(),
},
ExclusiveStartKey: paginationValueToUse || undefined,
};
const {
ultimateResults,
paginationValue
} = await searchDatabase({
searchParams
});
const transactions = ultimateResults;
for( const transaction of transactions ) {
cryptoPot += transaction.amount;
}
if( !!paginationValue ) {
paginationValueToUse = paginationValue;
iterationCount++;
}
else if( !!paginationValueToUse ) {
paginationValueToUse = null;
}
} while( !!paginationValueToUse );
const cryptoPotData = {
cryptoPot: Math.abs( cryptoPot )
};
console.log(
'getCryptoPotData executed successfully ' +
'returning cryptoPotData: ' +
stringify( cryptoPotData )
);
return cryptoPotData;
});
<file_sep>'use strict';
const {
transactions: {
types,
bitcoinWithdrawTypes,
},
exchanges,
dreams,
votes,
} = require( '../../../../../constants' );
module.exports = Object.freeze( ({
transactions,
theOracleOfDelphiDefi,
withdrawIdToData,
voteIdToData,
}) => {
for( const transaction of transactions ) {
const {
type,
} = transaction;
switch( type ) {
case types.addBitcoin: {
const addressToData = theOracleOfDelphiDefi[
types.addBitcoin
].addressToData;
if( !addressToData[ transaction.address ] ) {
addressToData[ transaction.address ] = {
amount: transaction.amount,
creationDate: transaction.creationDate,
};
}
else if(
transaction.creationDate >
addressToData[ transaction.address ].creationDate
) {
addressToData[ transaction.address ] = {
amount: transaction.amount,
creationDate: transaction.creationDate,
};
}
break;
}
case types.withdrawBitcoin: {
switch( transaction.bitcoinWithdrawType ) {
case bitcoinWithdrawTypes.start:
const startAmount = (
transaction.amount + transaction.fee
);
theOracleOfDelphiDefi[
types.withdrawBitcoin
].totalAmount += startAmount;
withdrawIdToData[ transaction.withdrawId ] = {
startAmount
};
break;
case bitcoinWithdrawTypes.success:
const data2 = withdrawIdToData[
transaction.withdrawId
] || {};
if(
!data2.startAmount &&
(data2.startAmount !== 0)
) {
throw new Error(
'invalid transaction ' +
JSON.stringify( transaction )
);
}
const successAmount = (
transaction.amount + transaction.fee
);
theOracleOfDelphiDefi[
types.withdrawBitcoin
].totalAmount += (
- data2.startAmount + successAmount
);
delete withdrawIdToData[ transaction.withdrawId ];
break;
case bitcoinWithdrawTypes.failed:
const data3 = withdrawIdToData[
transaction.withdrawId
] || {};
if(
!data3.startAmount &&
(data3.startAmount !== 0)
) {
throw new Error(
'invalid transaction ' +
JSON.stringify( transaction )
);
}
theOracleOfDelphiDefi[
types.withdrawBitcoin
].totalAmount += (
- data3.startAmount
);
delete withdrawIdToData[ transaction.withdrawId ];
break;
default:
// safeguard: should not get here in normal operation
throw new Error(
'oracleHallucination error: ' +
'got withdraw transaction with ' +
`invalid withdraw type: ${
transaction.bitcoinWithdrawType
}`
);
}
break;
}
case types.exchange: {
switch( transaction.exchangeType ) {
case exchanges.types.btcToCrypto:
theOracleOfDelphiDefi[
types.exchange
].totalBitcoinAmount -= (
transaction.amountInBTCNeeded
);
theOracleOfDelphiDefi[
types.exchange
].totalCryptoAmount += (
transaction.amountInCryptoWanted
);
break;
case exchanges.types.cryptoToBTC:
theOracleOfDelphiDefi[
types.exchange
].totalBitcoinAmount += (
transaction.amountInBitcoinWanted
);
theOracleOfDelphiDefi[
types.exchange
].totalCryptoAmount -= (
transaction.amountInCryptoNeeded
);
break;
default:
// safeguard: should not get here in normal operation
throw new Error(
'oracleHallucination error: ' +
'got exchange transaction with ' +
`invalid exchange type: ${
transaction.exchangeType
}`
);
}
break;
}
case types.dream: {
switch( transaction.dreamType ) {
case dreams.types.coin:
case dreams.types.lotus:
case dreams.types.slot:
theOracleOfDelphiDefi[
types.dream
].totalCryptoAmount += (
transaction.amount
);
break;
default:
// safeguard: should not get here in normal operation
throw new Error(
'oracleHallucination error: ' +
'got dream transaction with ' +
`invalid dream type: ${
transaction.dreamType
}`
);
}
break;
}
case types.vote: {
const {
voteId,
amount,
voteType
} = transaction;
// console.log(
// 'A ORACLE HALLUCINATION TEMPORARY LOG:',
// JSON.stringify({
// voteId,
// voteIdToData,
// theOracleOfDelphiDefi,
// }, null, 4 )
// );
/* v1 -5
CIA -5 = -v0 + v1 = -0 + -5 = -5, TOTAL -5
v2 -3
CIA = -v1 + v2 = --5 + -3 = +2, TOTAL -3
v3 -6
CIA = -v1 + v2 = --3 + -6 = -3, TOTAL -6
*/
if( !voteIdToData[ voteId ] ) {
voteIdToData[ voteId ] = {
amount: 0,
};
// console.log(
// 'FIRST ORACLE HALLUCINATION TEMPORARY LOG:',
// JSON.stringify({
// voteId,
// voteIdToData,
// theOracleOfDelphiDefi,
// }, null, 4 )
// );
}
// console.log(
// 'ULTRA ORACLE HALLUCINATION TEMPORARY LOG:',
// JSON.stringify({
// voteId,
// amount,
// voteType,
// voteIdToData,
// }, null, 4 )
// );
const changeInAmount = (
-voteIdToData[ voteId ].amount + amount
);
theOracleOfDelphiDefi[
types.vote
].totalCryptoAmount += changeInAmount;
if( voteType !== votes.types.payout ) {
voteIdToData[ voteId ].amount = amount;
// console.log(
// 'C ORACLE HALLUCINATION TEMPORARY LOG:',
// JSON.stringify({
// voteId,
// voteIdToData,
// theOracleOfDelphiDefi,
// }, null, 4 )
// );
}
else {
delete voteIdToData[ voteId ];
// console.log(
// 'E ORACLE HALLUCINATION TEMPORARY LOG:',
// JSON.stringify({
// voteId,
// voteIdToData,
// theOracleOfDelphiDefi,
// }, null, 4 )
// );
}
break;
}
case types.raffle: {
const {
amount,
} = transaction;
theOracleOfDelphiDefi[
types.raffle
].totalCryptoAmount += amount;
break;
}
case types.bonus: {
const {
bitcoinAmount,
cryptoAmount
} = transaction;
theOracleOfDelphiDefi[
types.bonus
].totalBitcoinAmount += bitcoinAmount;
theOracleOfDelphiDefi[
types.bonus
].totalCryptoAmount += cryptoAmount;
break;
}
case types.setAlienBalance: {
theOracleOfDelphiDefi[
types.setAlienBalance
][
transaction.currency
].totalCryptoAmount = transaction.amount;
break;
}
case types.identity: {
break;
}
default:
// safeguard: should not get here in normal operation
throw new Error(
'oracleHallucination error: got transaction with ' +
`invalid type: ${ type }`
);
}
}
});<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import { MoneyActionsPolygon } from '../../TheSource';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'pink',
width: '100%',
// display: 'flex',
// justifyContent: 'center',
// flexDirection: 'column',
// alignItems: 'center'
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e(
MoneyActionsPolygon,
{
dialogMode: true,
}
)
);
};
<file_sep>import { createElement as e } from 'react';
import { setState, getState } from '../../../reduxX';
import { enchanted, grecaptcha } from '../../../utils';
import { google } from '../../../constants';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import putTicket from './putTicket';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: '#D0D2A8',
width: '90%',
minHeight: 75,
borderRadius: 10,
marginTop: 5,
marginBottom: 5,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
titleText: {
width: '90%',
fontSize: 18,
color: 'black',
fontWeight: 'bold',
marginTop: 10,
},
choiceBox: {
width: '90%',
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
marginTop: 4,
marginBottom: 4,
},
text: {
color: 'black',
},
cancelButton: {
marginLeft: 10,
backgroundColor: '#AFB278',
},
noTicketsSection: {
width: '90%',
color: 'black',
textAlign: 'center',
fontSize: 20,
fontWeight: 'bold',
}
};
};
export default ({
raffleDatum
}) => {
const styles = getStyles();
const isLoading = getState( 'isLoading' );
const choiceElements = [];
if(
!raffleDatum.choices ||
(raffleDatum.choices.length === 0)
) {
choiceElements.push(
e(
Typography,
{
style: styles.noTicketsSection,
},
'...'
)
);
}
else {
const choiceElementsToAdd = raffleDatum.choices.map( choiceData => {
const cancelIsAllowed = (
Date.now() <= choiceData.lastCancelTime
);
return e(
Box,
{
style: styles.choiceBox
},
e(
Typography,
{
style: styles.text,
},
choiceData.choice
),
cancelIsAllowed && e(
Button,
{
disabled: isLoading,
style: styles.cancelButton,
onClick: async () => {
setState( 'isLoading', true );
try {
const numbers = (
enchanted
.destinyRaffle
.getNumbersFromChoice({
choice: choiceData.choice,
})
);
const googleCode = (
await grecaptcha.safeGetGoogleCode({
action: (
google
.grecapcha
.actions
.destinyRaffleTicketPut
)
})
);
if( !googleCode ) {
return setState( 'isLoading', false );
}
await putTicket({
raffleId: raffleDatum.raffleId,
numbers,
action: 'cancel',
googleCode
});
setState( 'isLoading', false );
}
catch( err ) {
setState( 'isLoading', false );
alert(
`error in buying ticket: ${
(
!!err &&
!!err.response &&
!!err.response.data &&
!!err.response.data.message &&
err.response.data.message
) || 'internal server error'
}`
);
}
}
},
'Unpick Petal'
)
);
});
choiceElements.push( ...choiceElementsToAdd );
}
// for( const choiceData of raffleDatum.choices ) {
// choiceElements.push(
// e(
// Box,
// {
// style: styles.text,
// },
// choiceData.choice
// )
// );
// }
return e(
Box,
{
style: styles.outerContainer,
},
e(
Typography,
{
style: styles.titleText,
},
'My Petals'
),
...choiceElements
);
};
<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../reduxX';
import { validation } from '../../utils';
import { usefulComponents } from '../../TheSource';
import verifyEmailAndLogin from './verifyEmailAndLogin';
const getStyles = () => {
const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: mainStyleObject.backgroundColor,
width: 300,
display: 'flex',
flexDirection: 'column',
// justifyContent: 'space-between',
// alignItems: 'center',
justifyContent: 'space-around',
alignItems: 'center',
color: 'white',
},
};
};
export default () => {
const styles = getStyles();
const emailInput = getState( 'verifyEmailPolygon', 'emailInput' );
const passwordInput = getState( 'verifyEmailPolygon', 'passwordInput' );
const verifyEmailCodeInput = getState(
'verifyEmailPolygon',
'verifyEmailCodeInput'
);
const isLoading = getState( 'isLoading' );
const powBlockIsActive = (
!isLoading &&
!!emailInput &&
validation.isValidEmail( emailInput ) &&
validation.isValidPassword( passwordInput ) &&
(
!!verifyEmailCodeInput &&
(verifyEmailCodeInput.length > 5) &&
(verifyEmailCodeInput.length < 500)
)
);
return e(
'div',
{
style: styles.outerContainer,
},
e(
'form',
{
id: 'verifyEmailPolygon'
},
e(
usefulComponents.WatermelonInput,
{
value: emailInput,
marginTop: 30,
autoComplete: 'username',
onChange: event => {
const newText = event.target.value;
if( newText.length > 200 ) {
return;
}
setState(
[
'verifyEmailPolygon',
'emailInput'
],
newText.trim()
);
},
title: 'email',
isLoadingMode: isLoading,
}
),
e(
usefulComponents.WatermelonInput,
{
value: passwordInput,
marginTop: 30,
type: 'password',
autoComplete: 'current-password',
onChange: event => {
const newText = event.target.value;
if( newText.length > 200 ) {
return;
}
setState(
[
'verifyEmailPolygon',
'passwordInput'
],
newText.trim()
);
},
title: 'password',
isLoadingMode: isLoading,
}
)
),
e(
usefulComponents.POWBlock,
{
form: 'verifyEmailPolygon',
text: 'Verify User and Login',
isLoadingMode: !powBlockIsActive,
marginTop: 60,
onClick: async () => {
await verifyEmailAndLogin({
emailInput,
passwordInput,
verifyEmailCodeInput,
});
},
},
'Verify User'
)
);
};
<file_sep>'use strict';
module.exports = Object.freeze({
// addTransactionAndUpdateExchangeUser: require( './addTransactionAndUpdateExchangeUserOG' ),
addTransactionAndUpdateExchangeUser: require( './addTransactionAndUpdateExchangeUser' ),
getExchangeUser: require( './getExchangeUser' ),
updateExchangeUser: require( './updateExchangeUser' ),
});
<file_sep>import { createElement as e, useEffect } from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import { getState, setState } from '../../../../reduxX';
import { desireElements } from '../../../../TheEnchantedSource';
import { story } from '../../../../constants';
import { actions } from '../../../../utils';
const getWindowWidthModeVariables = () => {
const windowWidth = getState( 'windowWidth' );
if( windowWidth > 1410 ) {
// return {
// previewVideoWidth: 1080,
// previewVideoHeight: 607.5,
// };
return {
previewVideoWidth: 900,
previewVideoHeight: 488.7931,
};
}
else
if( windowWidth > 580 ) {
return {
previewVideoWidth: 560,
previewVideoHeight: 315,
};
}
return {
previewVideoWidth: 320,
previewVideoHeight: 180,
};
};
const getStyles = ({
previewVideoWidth
}) => {
return {
outerContainer: {
// backgroundColor: 'pink',
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
marginTop: 20,
},
// text: {
// width: '90%',
// color: 'white',
// fontSize: 16,
// marginTop: 30,
// },
previewVideoTitleTextContainer: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
// marginTop: 10,
width: '100%',
},
previewVideoTitleText: {
color: 'white',
width: previewVideoWidth,
fontWeight: 'bold',
fontSize: 18,
},
previewVideoContainer: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
width: '100%',
minHeight: 300,
// backgroundColor: 'brown',
},
temporarySpacer: {
width: '100%',
height: 100,
maxWidth: 500,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
},
temporaryText: {
width: '80%',
textAlign: 'left',
},
buttonPlaceContainer: {
// backgroundColor: 'pink',
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
marginTop: 15,
},
button: {
backgroundColor: 'beige',
},
alreadyHaveAnAccountTextContainer: {
// backgroundColor: 'brown',
width: 320,
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginTop: 20,
marginBottom: 40,
},
alreadyHaveAnAccountText: {
// width: '100%',
color: 'white',
fontSize: 16,
},
alreadyHaveAnAccountLoginNowText: {
// width: '100%',
// textAlign: 'left',
color: '#85f3ff',
fontWeight: 'bold',
marginLeft: 5,
cursor: 'pointer',
fontSize: 16,
},
};
};
export default () => {
useEffect( () => {
actions.scroll();
}, [] );
const {
previewVideoWidth,
previewVideoHeight
} = getWindowWidthModeVariables();
const styles = getStyles({
previewVideoWidth
});
return e(
Box,
{
style: styles.outerContainer
},
e(
desireElements.gameTitles.DestinyRaffleTitle
),
// e(
// Box,
// {
// style: styles.temporarySpacer,
// },
// e(
// Typography,
// {
// style: styles.temporaryText,
// },
// 'Available on Login Only'
// ),
// e(
// Typography,
// {
// style: styles.temporaryText,
// },
// 'Hourly Draw Lottery is Currently Active!'
// )
// ),
e(
Box,
{
style: styles.previewVideoContainer
},
e(
Box,
{
style: styles.previewVideoTitleTextContainer
},
e(
Typography,
{
style: styles.previewVideoTitleText
},
'Gameplay Video'
),
),
e(
'iframe',
{
width: previewVideoWidth,
height: previewVideoHeight,
src: 'https://www.youtube.com/embed/nwxhWTpu5yM',
frameBorder: 0,
allow: 'accelerometer; autoplay;',
clipboardwrite: 'encrypted-media; gyroscope; picture-in-picture',
allowFullScreen: true,
}
)
),
e(
Box,
{
style: styles.buttonPlaceContainer
},
e(
Button,
{
style: styles.button,
size: 'large',
onClick: () => {
setState(
{
keys: [ 'notLoggedInMode', 'freeGame' ],
value: null,
},
{
keys: [ 'notLoggedInMode', 'mainMode' ],
value: (
story
.NotLoggedInMode
.mainModes
.signUpMode
),
}
);
}
},
'Create an Account and Play Now!'
),
e(
Box,
{
style: styles.alreadyHaveAnAccountTextContainer
},
e(
Typography,
{
style: styles.alreadyHaveAnAccountText
},
'Already have an account?'
),
e(
Box,
{
onClick: () => {
setState(
{
keys: [ 'notLoggedInMode', 'freeGame' ],
value: null,
},
{
keys: [ 'notLoggedInMode', 'mainMode' ],
value: (
story
.NotLoggedInMode
.mainModes
.loginMode
),
}
);
}
},
e(
Typography,
{
style: styles.alreadyHaveAnAccountLoginNowText,
},
'Login now!'
)
)
)
)
);
};
<file_sep>'use strict';
// const {
// utils: {
// stringify
// },
// } = require( '@bitcoin-api/full-stack-api-private' );
const updateTokenValue = require( './updateTokenValue' );
const {
getFormattedEvent,
getResponse,
handleError,
beginningDragonProtection,
} = require( '../../../utils' );
exports.handler = Object.freeze( async rawEvent => {
console.log( 'running the /tokens - PUT function' );
try {
const event = getFormattedEvent({
rawEvent,
});
const {
user,
} = await beginningDragonProtection({
queueName: 'putUser',
event,
});
const {
returnCode
} = await updateTokenValue({
user
});
const response = {
token: returnCode
};
console.log(
'/tokens - PUT function executed successfully, ' +
'returning values: ' +
JSON.stringify( Object.keys( response ) )
);
return getResponse({ body: response });
}
catch( err ) {
console.log( `error in /tokens - GET function: ${ err }` );
return handleError( err );
}
});<file_sep>import { createElement as e } from 'react';
const LOADING_FROG_URL = 'https://s3.ca-central-1.amazonaws.com/dynastybitcoin.com/site/images/loading-frog-1.png';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: '',
// backgroundColor: 'pink',
width: 300,
height: 350,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
loadingFrogHolder: {
width: 222,
height: 231,
// backgroundColor: 'pink',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
loadingFrog: {
},
// triangle: {
// width: 0,
// height: 0,
// borderLeft: '90px solid transparent',
// borderRight: '90px solid transparent',
// borderTop: '150px solid green',
// }
};
};
const FullDogeStyle = () => {
return e(
'div',
{},
e(
'h1',
{
style: {
color: 'white',
fontFamily: 'Roboto',
textAlign: 'center',
marginTop: 140,
marginBottom: 70,
}
},
'DynastyBitcoin.com'
)
);
};
export default ({
fullDogeStyle = false
}) => {
const styles = getStyles();
return e(
'div',
{
style: styles.outerContainer,
},
fullDogeStyle && e( FullDogeStyle ),
e(
'div',
{
style: styles.loadingFrogHolder,
},
e(
'img',
{
style: styles.loadingFrog,
src: LOADING_FROG_URL,
}
)
)
);
};
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry,
}
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
aws: {
database: {
tableNames: {
EXCHANGE_USERS,
}
}
}
} = require( '../../../constants' );
module.exports = Object.freeze( async ({
newExchangeUser,
}) => {
console.log( 'running updateExchangeUser' );
await updateDatabaseEntry({
tableName: EXCHANGE_USERS,
entry: newExchangeUser,
});
console.log( 'updateExchangeUser successfully executed' );
});
<file_sep>cd
rm -rf tempTigerScript
mkdir tempTigerScript
mkdir tempTigerScript/feeDataBot
mkdir tempTigerScript/withdrawsBot
mkdir tempTigerScript/depositsBot
<file_sep>'use strict';
module.exports = Object.freeze({
btcToCrypto: require( './btcToCrypto' ),
cryptoToBTC: require( './cryptoToBTC' ),
getCryptoAmountNumber: require( './getCryptoAmountNumber' ),
});
<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const addBitcoin = require( './addBitcoin' );
const addBitcoinWithdraws = require( './addBitcoinWithdraws' );
const addCrypto = require( './addCrypto' );
const addExchange = require( './addExchange' );
const addVote = require( './addVote' );
const addRaffle = require( './addRaffle' );
const addBonus = require( './addBonus' );
const addSummary = require( './addSummary' );
module.exports = Object.freeze( ({
exchangeUser,
}) => {
console.log( 'running getBalanceData' );
const balanceData = {};
addBitcoin({ exchangeUser, balanceData });
addBitcoinWithdraws({ exchangeUser, balanceData });
addCrypto({ exchangeUser, balanceData });
addExchange({ exchangeUser, balanceData });
addVote({ exchangeUser, balanceData });
addRaffle({ exchangeUser, balanceData });
addBonus({ exchangeUser, balanceData });
addSummary({ exchangeUser, balanceData });
console.log(
'getBalanceData executed successfully: ' +
`got balance data ${ stringify( balanceData ) }`
);
return balanceData;
});
<file_sep>import {
createElement as e,
} from 'react';
import Box from '@material-ui/core/Box';
// import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import { getState, setState } from '../../../reduxX';
import { story } from '../../../constants';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
// backgroundColor: 'pink',
width: '100%',
// height: 300,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
container: {
// backgroundColor: mainStyleObject.backgroundColor,
// backgroundColor: 'black',
width: '92%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'left',
borderRadius: 4,
},
// text: {
// // backgroundColor: mainStyleObject.backgroundColor,
// backgroundColor: 'black',
// // width: '100%',
// // height: '20%',
// marginTop: 5,
// marginBottom:3,
// marginLeft: 5,
// marginRight: 5,
// },
innerContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
backgroundColor: 'black',
width: 260,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 4,
},
button: {
// backgroundColor: mainStyleObject.backgroundColor,
backgroundColor: 'beige',
width: 250,
// height: '20%',
marginTop: 5,
marginBottom: 5,
marginLeft: 5,
marginRight: 5,
},
};
};
export default (
// {
// balanceData,
// }
) => {
const styles = getStyles();
const isLoading = getState( 'isLoading' );
return e(
Box,
{
style: styles.outerContainer,
},
e(
Box,
{
style: styles.container
},
// e(
// Typography,
// {
// style: styles.text,
// },
// `Deposit Address:`
// ),
e(
Box,
{
style: styles.innerContainer,
},
e(
Button,
{
disabled: isLoading,
style: styles.button,
onClick: () => {
setState(
'dialogMode',
story.dialogModes.depositsBastion,
);
},
// onClick: async () => {
// try {
// setState( 'isLoading', true );
// await addAddress();
// setState( 'isLoading', false );
// }
// catch( err ) {
// setState( 'isLoading', false );
// alert(
// `error in getting address: ${
// (
// !!err &&
// !!err.response &&
// !!err.response.data &&
// !!err.response.data.message &&
// err.response.data.message
// ) || 'internal server error'
// }`
// );
// }
// },
},
'Deposit Bitcoin'
)
)
)
);
};
<file_sep>'use strict';
require( 'dotenv' ).config();
const yargs = require( 'yargs' );
const isProductionMode = yargs.argv.mode === 'production';
const samanthaDecrypt = require( './samantha' );
const exchangeUserIdData = [
isProductionMode ? {
publicId: yargs.argv.r || process.env.PRODUCTION_PUBLIC_ID,
} : {
publicId: yargs.argv.r || process.env.STAGING_PUBLIC_ID,
},
];
const getExchangeUserIdFromPublicId = ({
publicId
}) => {
const exchangeUserIdRaw1 = Buffer.from(
publicId.substring(
'DynastyBitcoin_Ref_ID_'.length
).replace( /^\_$/g, '=' ),
'base64'
).toString( 'ascii' );
const exchangeUserId = samanthaDecrypt({
text: exchangeUserIdRaw1
});
console.log({
publicId,
modifiedPublicIdLength: `DynastyBitcoin_Ref_ID_${ publicId }`.length,
exchangeUserId
});
};
(() => {
for( const exchangeUserIdDatum of exchangeUserIdData ) {
getExchangeUserIdFromPublicId({
publicId: exchangeUserIdDatum.publicId,
});
}
})();<file_sep>import { createElement as e } from 'react';
import { getState/*, setState*/ } from '../../../reduxX';
import {
usefulComponents,
// POWBlock,
} from '../../../TheSource';
import {
gameData, games
} from '../../../constants';
import {
dynastyBitcoin,
} from '../../../utils';
// import { validation } from '../../utils';
import AmountChooser from './AmountChooser';
import doEnchantedLuck from './doEnchantedLuck';
import Box from '@material-ui/core/Box';
// import Paper from '@material-ui/core/Paper';
// import Typography from '@material-ui/core/Typography';
// import Divider from '@material-ui/core/Divider';
// import TheDinocoin from './TheDinocoin';
// import About from './About';
// import doExchange from './doExchange';
const theGameData = gameData[ games.theDragonsTalisman ];
const diamondMin = theGameData.diamondMin;
const diamondMax = theGameData.diamondMax;
const jackpotMin = theGameData.jackpotMin;
const jackpotMax = theGameData.jackpotMax;
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
// backgroundColor: 'beige',
backgroundColor: 'black',
maxWidth: 620,
width: '100%',
// marginTop: 20,
// height: 300,
// borderRadius: '50%',
// backgroundColor: 'pink',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
};
};
export default ({
freeGameMode = false,
isJackpotMode,
}) => {
const styles = getStyles();
const isLoading = getState( 'isLoading' );
// const amount = getState( 'coinExperiencePolygon', 'amount' );
const selectedAmount = getState(
freeGameMode ? 'notLoggedInMode' : 'loggedInMode',
'coinFlip',
'selectedAmount'
);
const selectedDynastyAmount = dynastyBitcoin.getDynastyBitcoinAmount(
selectedAmount
);
let min;
let max;
if( isJackpotMode ) {
min = jackpotMin;
max = jackpotMax;
}
else {
min = diamondMin;
max = diamondMax;
}
const buttonIsDisabled = !(
!isLoading &&
(
(selectedDynastyAmount >= min) &&
(selectedDynastyAmount <= max)
)
);
return e(
Box,
{
style: styles.outerContainer,
},
e(
AmountChooser,
{
freeGameMode,
isJackpotMode,
min,
max
}
),
e(
usefulComponents.POWBlock,
{
onClick: async () => {
await doEnchantedLuck({
freeGameMode,
min,
max,
});
},
backgroundColor: 'lightgreen',
width: '100%',
text: `Toss Talisman for ${ selectedAmount } DB`,
isLoadingMode: buttonIsDisabled,
// marginTop: 10,
}
)
);
};
<file_sep>'use strict';
const AWS = require( 'aws-sdk' );
const yargs = require( 'yargs' );
const isProductionMode = (yargs.argv.mode === 'production');
if( isProductionMode ) {
console.log( '☢︎🐑 is production mode' );
require( 'dotenv' ).config({
path: `${ __dirname }/productionCredentials/.env`
});
process.env.ENV = 'production';
}
else {
console.log( '🐲🐉 is staging mode' );
require( 'dotenv' ).config({
path: `${ __dirname }/stagingCredentials/.env`
});
process.env.ENV = 'staging';
}
const {
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
AWS_REGION,
AWS_ACCOUNT_NUMBER,
INSTANCE_PREFIX,
} = process.env;
AWS.config.update({
accessKeyId: AWS_ACCESS_KEY_ID,
secretAccessKey: AWS_SECRET_ACCESS_KEY,
region: AWS_REGION,
});
const iam = new AWS.IAM();
const stageSuffix = isProductionMode ? '' : '_staging';
const lambdaAssumeRolePolicyDocument = JSON.stringify({
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"lambda.amazonaws.com"
]
},
"Action": [ "sts:AssumeRole" ]
}
]
});
const roleData = [
// {
// roleName: 'lambda_api_get',
// policyNames: [
// 'role_lambda_api_get'
// ]
// },
// {
// roleName: 'lambda_api_tokens_post',
// policyNames: [
// 'role_lambda_api_tokens_post'
// ]
// },
// {
// roleName: 'lambda_api_tokens_get',
// policyNames: [
// 'role_lambda_api_tokens_get'
// ]
// },
// {
// roleName: 'lambda_api_tokens_put',
// policyNames: [
// 'role_lambda_api_tokens_put'
// ]
// },
// {
// roleName: 'lambda_api_addresses_post',
// policyNames: [
// 'role_lambda_api_addresses_post'
// ]
// },
// {
// roleName: 'lambda_api_feeData_get',
// policyNames: [
// 'role_lambda_api_feeData_get'
// ]
// },
// {
// roleName: 'lambda_service_cacheOnAndOffStatus',
// policyNames: [
// 'role_lambda_service_cacheOnAndOffStatus'
// ]
// },
// {
// roleName: 'lambda_api_withdraws_post',
// policyNames: [
// 'role_lambda_api_withdraws_post'
// ]
// },
// {
// roleName: 'lambda_eApi_eUsers_post',
// policyNames: [
// 'role_lambda_eApi_eUsers_post'
// ]
// },
// {
// roleName: 'lambda_eApi_eUsers_eUserId_get',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_eUsers_eUserId_get'
// ]
// },
// {
// roleName: 'lambda_eApi_eUsers_eUserId_delete',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_eUsers_eUserId_delete'
// ]
// },
// {
// roleName: 'lambda_eApi_verifyUser_post',
// policyNames: [
// 'role_lambda_eApi_login_post',
// 'role_lambda_eApi_verifyUser_post'
// ]
// },
// {
// roleName: 'lambda_eApi_addresses_post',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_addresses_post'
// ]
// },
// {
// roleName: 'lambda_eApi_transactions_get',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_transactions_get'
// ]
// },
// {
// roleName: 'lambda_eApi_login_post',
// policyNames: [
// 'role_lambda_eAPI_login_post'
// ]
// },
// {
// roleName: 'lambda_eApi_login_password_post',
// policyNames: [
// 'role_lambda_eAPI_login_password_post'
// ]
// },
// {
// roleName: 'lambda_eApi_login_password_patch',
// policyNames: [
// 'role_lambda_eAPI_login_password_patch'
// ]
// },
// {
// roleName: 'lambda_eApi_withdraws_post',
// policyNames: [
// 'role_lambda_eApi_withdraws_post',
// 'eFunction_addTransactionAndUpdateExchangeUser',
// 'eFunction_mongolianBeginningDragonProtection',
// ]
// },
// {
// roleName: 'lambda_eApi_logout_post',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_logout_post',
// ]
// },
// {
// roleName: 'lambda_eApi_exchanges_post',
// policyNames: [
// 'eFunction_addTransactionAndUpdateExchangeUser',
// 'eFunction_mongolianBeginningDragonProtection',
// ],
// },
// {
// roleName: 'lambda_eApi_dreams_post',
// policyNames: [
// 'eFunction_addTransactionAndUpdateExchangeUser',
// 'eFunction_mongolianBeginningDragonProtection',
// ],
// },
// {
// roleName: 'lambda_eApi_dreamsLotus_post',
// policyNames: [
// 'eFunction_addTransactionAndUpdateExchangeUser',
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_dreamsLotus_post',
// ],
// },
// {
// roleName: 'lambda_eApi_dreamsLotus_get',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_dreamsLotus_get',
// ],
// },
{
roleName: 'lambda_eApi_dreamsSlot_post',
policyNames: [
'eFunction_addTransactionAndUpdateExchangeUser',
'eFunction_mongolianBeginningDragonProtection',
'role_lambda_eApi_dreamsSlot_post',
],
},
// {
// roleName: 'lambda_eApi_votes_voteId_get',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_votes_voteId_get',
// ],
// },
// {
// roleName: 'lambda_eApi_votes_voteId_post',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'eFunction_addTransactionAndUpdateExchangeUser',
// 'role_lambda_eApi_votes_voteId_post',
// ],
// },
// {
// roleName: 'lambda_eApi_raffles_get',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_raffles_get',
// ],
// },
// {
// roleName: 'lambda_eApi_raffles_raffleId_post',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'eFunction_addTransactionAndUpdateExchangeUser',
// 'role_lambda_eApi_raffles_raffleId_post',
// ],
// },
// {
// roleName: 'lambda_eApi_raffleDraws_raffleId_get',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_raffleDraws_raffleId_get',
// ],
// },
// {
// roleName: 'lambda_eApi_raffleTickets_raffleId_get',
// policyNames: [
// 'eFunction_mongolianBeginningDragonProtection',
// 'role_lambda_eApi_raffleTickets_raffleId_get',
// ],
// },
// {
// roleName: 'lambda_eService_handleEEDRs',
// policyNames: [
// 'role_lambda_eService_handleEEDRs',
// ],
// },
// {
// roleName: 'lambda_eService_handleTransactionsStream',
// policyNames: [
// 'role_lambda_eService_handleTransactionsStream',
// ],
// isDynamoStreamLambda: true,
// },
// {
// roleName: 'lambda_eService_manageRafflePutTicketEvents',
// policyNames: [
// 'role_lambda_eService_manageRafflePutTicketEvents',
// ],
// },
// {
// roleName: 'lambda_eService_doRaffleDraw',
// policyNames: [
// 'role_lambda_eService_doRaffleDraw',
// 'eFunction_addTransactionAndUpdateExchangeUser',
// ],
// },
];
const getFullRoleName = Object.freeze( ({ roleName }) => (
`${ INSTANCE_PREFIX }${ roleName }${ stageSuffix }`
));
const createRole = Object.freeze( ({
roleName,
}) => {
return new Promise( ( resolve, reject ) => {
const params = {
AssumeRolePolicyDocument: lambdaAssumeRolePolicyDocument, /* required */
RoleName: roleName,
};
console.log(
'creating role with params: ' +
JSON.stringify( params, null, 4 )
);
iam.createRole( params, ( err, data ) => {
if( !!err ) {
console.log( 'error in creating role:', err );
return reject( err );
}
console.log(
'successfully created role: ' +
JSON.stringify({
name: roleName,
responseData: data
}, null, 4 )
);
resolve( data );
});
});
});
const attachPolicy = Object.freeze( ({
roleName,
policyName,
overridePolicyArn,
}) => {
return new Promise( ( resolve, reject ) => {
const policyArn = overridePolicyArn || `arn:aws:iam::${ AWS_ACCOUNT_NUMBER }:policy/${ INSTANCE_PREFIX }${ policyName }${ stageSuffix }`;
const params = {
PolicyArn: policyArn, /* required */
RoleName: roleName,
};
console.log(
'attaching policy to role with params: ' +
JSON.stringify( params, null, 4 )
);
iam.attachRolePolicy( params, ( err, data ) => {
if( !!err ) {
console.log( 'error in attaching policy to role:', err );
return reject( err );
}
console.log(
'successfully attached policy to role: ' +
JSON.stringify({
roleName,
policyName,
overridePolicyArn,
responseData: data
}, null, 4 )
);
resolve( data );
});
});
});
(async () => {
try {
console.log( 'setting up roles' );
for( const roleDatum of roleData ) {
const fullRoleName = getFullRoleName({
roleName: roleDatum.roleName
});
try {
await createRole({
roleName: fullRoleName,
});
}
catch( err ) {
console.log(
`error creating role "${ fullRoleName }": ` +
err.message
);
if( err.code !== 'EntityAlreadyExists' ) {
throw err;
}
}
for( const policyName of roleDatum.policyNames ) {
await attachPolicy({
roleName: fullRoleName,
policyName
});
}
await attachPolicy({
roleName: fullRoleName,
overridePolicyArn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
});
if( roleDatum.isDynamoStreamLambda ) {
await attachPolicy({
roleName: fullRoleName,
overridePolicyArn: 'arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole',
});
}
}
console.log( 'set up roles successfully executed' );
}
catch( err ) {
console.log(
'an error occurred in setting up roles:',
err
);
}
})();
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry,
}
},
doOperationInQueue,
stringify,
redis: {
doRedisFunction,
doRedisRequest,
},
javascript: {
getQueueId,
jsonEncoder: {
decodeJson
}
},
},
constants: {
redis: {
listIds,
},
aws: {
database: {
tableNames: {
ADDRESSES,
}
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_USERS,
}
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
aws: {
dino: {
getExchangeDatabaseEntry
}
}
} = require( '../../../../exchangeUtils' );
const {
auth: {
authorizeUser
},
} = require( '../../../../utils' );
module.exports = Object.freeze( async ({
// user
event,
}) => {
const exchangeUserId = event.body.exchangeUserId;
const eventHeaders = (
!!event.headers &&
event.headers
) || {};
const megaCode = (
eventHeaders.Token ||
eventHeaders.token ||
null
);
console.log(
'running 🏛runWalhallaAddressMode🏛 ' +
`with the following values: ${ stringify({
exchangeUserId,
['there is a mega code']: !!megaCode,
}) }`
);
const exchangeTokenUserId = process.env.EXCHANGE_TOKEN_USER_ID;
if( !exchangeTokenUserId ) {
throw new Error(
'🏛runWalhallaAddressMode🏛 error - ' +
'operational error: missing EXCHANGE_TOKEN_USER_ID'
);
}
const { user } = await authorizeUser({
returnCode: megaCode
});
if( exchangeTokenUserId !== user.userId ) {
throw new Error(
'🏛runWalhallaAddressMode🏛 error - ' +
'operational error: invalid mega code provided'
);
}
await doOperationInQueue({
queueId: getQueueId({
type: EXCHANGE_USERS,
id: exchangeUserId
}),
doOperation: async () => {
const exchangeUser = await getExchangeDatabaseEntry({
tableName: EXCHANGE_USERS,
value: exchangeUserId,
});
if( !exchangeUser ) {
throw new Error(
'🏛runWalhallaAddressMode🏛 error - ' +
'exchange user with id ' +
`"${ exchangeUserId }" does not exist`
);
}
const unusedAddressData = await doRedisFunction({
performFunction: async ({
redisClient
}) => {
const rawUnusedAddressData = await doRedisRequest({
client: redisClient,
command: 'rpop',
redisArguments: [
listIds.unusedAddressData
],
});
if( !rawUnusedAddressData ) {
return null;
}
const unusedAddressData = decodeJson(
rawUnusedAddressData
);
return unusedAddressData;
},
functionName: 'getting fresh address',
});
if( !unusedAddressData ) {
return console.log(
'🏛runWalhallaAddressMode🏛 NO-OP - ' +
'no fresh addresses available'
);
}
const newMoneyData = Object.assign(
{},
exchangeUser.moneyData || {}
);
if( !newMoneyData.bitcoin ) {
newMoneyData.bitcoin = [];
}
const newBitcoinMoneyDatum = {
amount: 0,
address: unusedAddressData.address,
creationDate: Date.now(),
};
newMoneyData.bitcoin.push( newBitcoinMoneyDatum );
const newExchangeUser = Object.assign(
{},
exchangeUser,
{
moneyData: newMoneyData
}
);
const updates = [];
const updateExchangeUser = updateDatabaseEntry({
tableName: EXCHANGE_USERS,
entry: newExchangeUser,
});
updates.push( updateExchangeUser );
const newAddressDatum = Object.assign(
{},
unusedAddressData,
{
userId: process.env.EXCHANGE_TOKEN_USER_ID,
conversionDate: Date.now(),
isExchangeAddress: true,
exchangeUserId,
}
);
const createAddressDatabaseEntry = updateDatabaseEntry({
tableName: ADDRESSES,
entry: newAddressDatum,
});
updates.push( createAddressDatabaseEntry );
await Promise.all( updates );
}
});
console.log(
'🏛runWalhallaAddressMode🏛 executed successfully'
);
});
<file_sep>import { createElement as e } from 'react';
// import { getState } from '../../reduxX';
import WithdrawPolygonCore from './WithdrawPolygonCore';
import Box from '@material-ui/core/Box';
// import Paper from '@material-ui/core/Paper';
// import Typography from '@material-ui/core/Typography';
import TitleTextBox from './TitleTextBox';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: 'beige',
width: '100%',
maxWidth: 620,
marginTop: 20,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
};
};
export default () => {
const styles = getStyles();
return e(
Box,
{
style: styles.outerContainer,
},
e( TitleTextBox ),
// e(
// Typography,
// {
// style: {
// paddingTop: 2,
// paddingBottom: 20,
// color: 'black',
// fontSize: 16,
// textAlign: 'left',
// width: '80%',
// maxWidth: 469,
// minWidth: 300
// }
// },
// e(
// 'span',
// {
// style: {
// fontWeight: 'bold',
// }
// },
// 'Important Note: '
// ),
// 'Due to current blockchain updating, withdraws may fail, ' +
// 'if so, please email <EMAIL> ' +
// 'to make a withdraw ASAP (contact via twitter @DynastyBitcoin works too, your info will be confidential). '+
// 'Automated withdraws will be ' +
// 'back to being 100% operational soon.'
// ),
e( WithdrawPolygonCore )
);
};
<file_sep>import { createElement as e } from 'react';
// import { getState } from '../../../../reduxX';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
// import {
// enchanted
// } from '../../../../../../../utils';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import getSortByTicketProcessedData from './getSortByTicketProcessedData';
// import SortSelector from './SortSelector';
// import Typography from '@material-ui/core/Typography';
// import Button from '@material-ui/core/Button';
const getTicketBoxBackgroundColor = ({
alt = false,
own = false,
}) => {
if( own ) {
return alt ? '#BCF8BC' : 'lightgreen';
}
return alt ? '#FDFEF4': '#F4F5DB';
};
const getTicketBoxStyle = ({
alt = false,
own = false,
} = { alt: false, own: false, }) => {
return {
backgroundColor: getTicketBoxBackgroundColor({
alt,
own,
}),
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
minHeight: 42,
};
};
const getStyles = () => {
return {
metaContainer: {
width: '100%',
height: '100%',
// backgroundColor: '#FDFEF4',
// backgroundColor: 'green',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
overflowY: 'scroll',
// marginBottom: 8,
// marginTop: 10,
// marginBottom: 10,
},
ticketBox: getTicketBoxStyle(),
altTicketBox: getTicketBoxStyle({ alt: true }),
ownTicketBox: getTicketBoxStyle({ own: true }),
ownAltTicketBox: getTicketBoxStyle({ own: true, alt: true, }),
ticketBoxTicketText: {
width: '90%',
fontWeight: 'bold',
color: 'black',
textAlign: 'left',
},
ticketBoxDataText: {
width: '90%',
fontSize: 12,
color: 'black',
textAlign: 'left',
}
};
};
const getTicketListItemStyle = ({
choiceDatum,
styles,
index,
}) => {
if( choiceDatum.own ) {
return (
(index % 2) === 0
) ? styles.ownTicketBox : styles.ownAltTicketBox;
}
return (
(index % 2) === 0
) ? styles.ticketBox : styles.altTicketBox;
};
export default ({
data,
ownSpecialId
}) => {
const styles = getStyles();
const ticketListItems = getSortByTicketProcessedData({
data,
ownSpecialId
}).map(
( choiceDatum, index ) => {
return e(
Box,
{
style: getTicketListItemStyle({
choiceDatum,
styles,
index
}),
// style: (
// (index % 2) === 0
// ) ? styles.ticketBox : styles.altTicketBox,
},
e(
Typography,
{
style: styles.ticketBoxTicketText,
},
choiceDatum.choice,
),
e(
Typography,
{
style: styles.ticketBoxDataText,
},
`petal pick count: ${ choiceDatum.numberOfTicketsPurchased }`
)
);
}
);
return e(
Box,
{
style: styles.metaContainer
},
...ticketListItems
);
};<file_sep>import { createElement as e } from 'react';
import { setState } from '../../reduxX';
import { story } from '../../constants';
// import { bitcoinExchange } from '../../utils';
import LuluLemonButton from './LuluLemonButton';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
width: 300,
backgroundColor: 'green',
borderRadius: 25,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
color: 'white',
marginTop: 40,
marginBottom: 30,
},
luluLemonButtons: {
width: '85%',
height: 40,
// margin: 20,
marginTop: 10,
marginBottom: 10,
marginLeft: 10,
marginRight: 10,
// margin: 20,
// margin: 20,
padding: 5,
backgroundColor: 'darkgreen',
// backgroundColor: '#FF9900',
borderRadius: 15,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
theText: {
color: 'beige',
userSelect: 'none',
}
};
};
export default () => {
const styles = getStyles();
return e(
'div',
{
style: styles.outerContainer,
},
e(
LuluLemonButton,
{
text: 'Privacy Policy',
onClick: () => {
setState( 'metaMode', story.metaModes.privacyPolicy );
},
}
),
e(
LuluLemonButton,
{
text: 'Terms Of Service',
onClick: () => {
setState( 'metaMode', story.metaModes.termsOfService );
},
}
)
);
};
<file_sep>import { createElement as e } from 'react';
import { story } from '../../../constants';
import { getState } from '../../../reduxX';
import GameTitle from '../GameTitle';
export default () => {
const windowWidth = getState( 'windowWidth' );
// const {
// type,
// } = (windowWidth > 510) ? {
// type: 'Hourly Draw Probability Function',
// } : {
// type: 'Hourly Draw',
// };
const type = (
windowWidth > 510
) ? 'Hourly Draw Lottery': 'Hourly Draw';
return e(
GameTitle,
{
title: 'Thousand Petal Lotus',
// type: 'Hourly Draw Probability Function',
type,
helpDialogMode: story.dialogModes.games.aboutDestinyRaffle,
marginBottom: 20,
}
);
};
<file_sep>import { createElement as e } from 'react';
import { setState } from '../../../reduxX';
import withStyles from '@material-ui/core/styles/withStyles';
import lightBlue from '@material-ui/core/colors/lightBlue';
// import lightGreen from '@material-ui/core/colors/lightGreen';
import { gameData, games } from '../../../constants';
import Switch from '@material-ui/core/Switch';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
const gameModes = gameData[ games.theDragonsTalisman ].modes;
const getStyles = () => {
return {
formGroup: {
width: '100%',
marginTop: 0,
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
alignItems: 'center'
},
formControlLabel: {
width: '100%',
marginTop: 0,
display: 'flex',
justifyContent: 'center',
flexDirection: 'row',
alignItems: 'center'
}
};
};
const CoolSwitch = withStyles({
switchBase: {
color: lightBlue[300],
'&$track': {
backgroundColor: lightBlue[500],
},
// '&$checked': {
// color: lightGreen[500],
// },
// '&$checked + $track': {
// backgroundColor: lightGreen[500],
// },
},
checked: {
color: lightBlue[300],
'&$track': {
backgroundColor: lightBlue[500],
},
// '&$checked': {
// color: lightGreen[500],
// },
// '&$checked + $track': {
// backgroundColor: lightGreen[500],
// },
},
track: {
color: lightBlue[300],
'&$track': {
backgroundColor: lightBlue[500],
},
},
})(Switch);
export default ({
isJackpotMode
}) => {
const styles = getStyles();
return e(
FormGroup,
{
style: styles.formGroup,
},
e(
FormControlLabel,
{
style: styles.formControlLabel,
control: e(
CoolSwitch,
{
checked: isJackpotMode,
onChange: () => {
if( isJackpotMode ) {
const netAmount = 0.00003;
setState(
[
'loggedInMode',
'coinFlip',
'mode'
],
gameModes.standard,
[
'loggedInMode',
'coinFlip',
'selectedAmount'
],
netAmount,
[
'notLoggedInMode',
'coinFlip',
'selectedAmount'
],
netAmount
);
}
else {
const netAmount = 0.0003;
setState(
[
'loggedInMode',
'coinFlip',
'mode'
],
gameModes.jackpot,
[
'loggedInMode',
'coinFlip',
'selectedAmount'
],
netAmount,
[
'notLoggedInMode',
'coinFlip',
'selectedAmount'
],
netAmount
);
}
},
name: "checkedA",
color: 'primary',
size: 'small'
// inputProps: { 'aria-label': 'secondary checkbox' }
}
),
label: isJackpotMode ? 'Jackpot' : 'Diamond',
},
)
);
};
<file_sep>'use strict';
const crypto = require( 'crypto' );
const algorithm = 'aes-256-cbc';
const IV_LENGTH = 16;
const encryptionId = process.env.EXCHANGE_TESSA_ENCRYPTION_ID;
const encryptionPassword = process.env.EXCHANGE_TESSA_ENCRYPTION_PASSWORD;
const riverEncryptTag = '__river__';
module.exports = Object.freeze( ({
text,
}) => {
const iv = crypto.randomBytes( IV_LENGTH );
const cipher = crypto.createCipheriv(
algorithm,
Buffer.from( encryptionPassword ),
iv
);
const encrypted = cipher.update( text );
const encryptedFinalForm = Buffer.concat( [ encrypted, cipher.final() ] );
const encryptedText = (
`${ iv.toString('hex') }:${ encryptedFinalForm.toString('hex') }`
);
const fullEncryptedText = (
`${ encryptionId }${ riverEncryptTag }${ encryptedText }`
);
return fullEncryptedText;
});
<file_sep>#!/usr/bin/env node
'use strict';
const argv = require( 'yargs' ).argv;
if( argv.mode === 'production' ) {
require( 'dotenv' ).config({
path: `${ __dirname }/../../productionCredentials/tree/.env`
});
}
else {
require( 'dotenv' ).config({
path: `${ __dirname }/../../stagingCredentials/tree/.env`
});
}
const provideWaterToTree = require( './provideWaterToTree' );
provideWaterToTree();
<file_sep>import { delay } from '../../../../utils';
// const win = 'win';
// let operationQueue = Promise.resolve({
// previousAction: win,
// });
let i = 0;
export default async ({
action,
// previousAction,
}) => {
const box = document.querySelector( '.TheDinocoin-Box' );
if( i === 66 ) {
// while( box.classList.length > 1 ) {
// box.classList.remove( box.classList[ box.classList.length - 1 ] );
// }
i++;
return;
}
// await delay({ timeout: 1 });
// await delay({ timeout: 1 });
if( (i > 0) && (i % 2 === 1) ) {
console.log( 'x2' );
await delay({ timeout: 1 });
box.classList.add( 'speed' );
await delay({ timeout: 1 });
while( box.classList.length > 2 ) {
// console.log( 'x:', box.classList[ box.classList.length - 1 ] );
console.log( 'xa:', box.classList[ 1 ] );
if(
box.classList[ 1 ] !== 'speed'
) {
console.log( 'xb:', box.classList[ 1 ] );
box.classList.remove( box.classList[ 1 ] );
}
// box.classList.remove( box.classList[ box.classList.length - 1 ] );
}
await delay({ timeout: 1 });
console.log( 'xend:', box.classList );
// box.classList.remove( box.classList[ 1 ] );
i++;
return;
}
if( (i > 0) && (i % 2 === 0) ) {
console.log( 'x3' );
await delay({ timeout: 1 });
console.log( 'xend2:', box.classList[ 1 ] );
box.classList.remove( box.classList[ 1 ] );
await delay({ timeout: 1 });
box.classList.add( 'action-testomega' );
i++;
return;
}
i++;
// while( box.classList.length > 1 ) {
// console.log( 'x:', box.classList[ box.classList.length - 1 ] );
// box.classList.remove( box.classList[ box.classList.length - 1 ] );
// }
if( i === 2 ) {
}
// await delay({ timeout: 1 });
// box.classList.add( 'action-reset' );
await delay({ timeout: 1 });
// if( previousAction !== win ) {
// box.classList.add( 'action-reset-back' );
// }
// else {
// box.classList.add( 'action-reset' );
// }
// await delay({ timeout: 500 });
// box.classList.add( `action-${ action }` );
box.classList.add( 'action-test1' );
await delay({ timeout: 40 });
// box.classList.remove( 'action-test1' );
// await delay({ timeout: 1 });
box.classList.add( 'action-test2' );
await delay({ timeout: 40 });
box.classList.add( 'action-test3' );
await delay({ timeout: 40 });
box.classList.add( 'action-test4' );
// await delay({ timeout: 1001 });
// box.classList.remove( 'action-test2' );
// await delay({ timeout: 1001 });
// box.classList.add( 'action-test1' );
// box.classList.add( 'action-test3' );
// await delay({ timeout: 3100 });
// return { previousAction: action };
};
// export default ({
// action,
// }) => {
// operationQueue = operationQueue.then( async ({
// previousAction,
// }) => {
// try {
// const doActionResults = await doAction({
// action,
// previousAction,
// });
// return {
// previousAction: doActionResults.previousAction,
// };
// }
// catch( err ) {
// console.log( 'error in doing spin action:', err );
// return {
// previousAction: win,
// };
// }
// });
// };<file_sep>'use strict';
const {
utils: {
stringify,
aws: {
dino: {
conversionTools: {
getDinoClientDino
}
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
transactions: {
types: {
// raffle,
dream
}
},
// raffles: {
// types: {
// putTicket
// }
// },
dreams: {
types: {
lotus
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
// const handleRafflePutTicket = require( './handleRafflePutTicket' );
const handleDreamsLotusLose = require( './handleDreamsLotusLose' );
const INSERT = 'INSERT';
// const getIfIsRafflePutTicket = Object.freeze( ({
// dino
// }) => {
// const isRafflePutTicket = (
// (dino.type === raffle) &&
// (dino.raffleType === putTicket)
// );
// return isRafflePutTicket;
// });
const getIfIsDreamsLotusLose = Object.freeze( ({
dino
}) => {
const isDreamsLotusLose = (
(dino.type === dream) &&
(dino.dreamType === lotus) &&
!dino.happyDream
);
return isDreamsLotusLose;
});
module.exports = Object.freeze( async ({
event,
}) => {
const records = event.Records;
console.log(
'running handleTransactions with ' +
`${ records.length } records`
);
for( const record of records ) {
if( record.eventName === INSERT ) {
const dynamoDino = record.dynamodb.NewImage;
const dino = getDinoClientDino({
dynamoDino,
});
// if( getIfIsRafflePutTicket({ dino }) ) {
// console.log(
// 'handling raffle putTicket record: ' +
// stringify( record )
// );
// await handleRafflePutTicket({
// dino
// });
// }
// else
if( getIfIsDreamsLotusLose({ dino }) ) {
console.log(
'handling dreams lotus lose record: ' +
stringify( record )
);
await handleDreamsLotusLose({
dino
});
}
}
}
console.log( 'handleTransactions executed successfully👩🏿💻👨🏻💻👩🏼💻👨🏾💻👏🏿👏🏽👏' );
});<file_sep>import { createElement as e } from 'react';
import Paper from '@material-ui/core/Paper';
import Box from '@material-ui/core/Box';
import Checkbox from '@material-ui/core/Checkbox';
import Typography from '@material-ui/core/Typography';
const getStyles = ({
marginTop,
marginBottom,
}) => {
return {
metaOuterContainer: {
width: 300,
marginTop,
marginBottom,
borderRadius: 4,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
backgroundColor: 'beige',
},
outerContainer: {
// backgroundColor: mainStyleObject.backgroundColor,
width: '100%',
padding: 10,
// height: 200,
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
// backgroundColor: 'green',
},
checkbox: {
color: 'black',
marginLeft: 20,
height: 20,
width: 20,
},
textAndMore: {
width: '74%',
textAlign: 'left',
color: 'black',
fontSize: 15,
display: 'flex',
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
marginRight: 20,
userSelect: 'none',
},
fakeLinkText: {
textAlign: 'left',
color: 'blue',
textDecoration: 'underline',
fontSize: 15,
marginLeft: 5,
userSelect: 'none',
},
};
};
export default ({
isLoadingMode,
text,
linkText,
marginTop = 0,
marginBottom = 0,
checked,
onLinkClick,
onCheck,
}) => {
const styles = getStyles({
isLoadingMode,
marginTop,
marginBottom,
});
return e(
Paper,
{
style: styles.metaOuterContainer,
},
e(
Box,
{
style: styles.outerContainer,
},
e(
Checkbox,
{
// color: 'black',
disabled: isLoadingMode,
type: 'checkbox',
checked,
style: styles.checkbox,
onChange: onCheck,
}
),
e(
Box,
{
style: styles.textAndMore
},
e(
Typography,
{},
text
),
e(
Typography,
{
style: styles.fakeLinkText,
onClick: onLinkClick,
},
linkText
)
)
),
);
};
<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../../../reduxX';
import { grecaptcha } from '../../../../utils';
import { google } from '../../../../constants';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import NumberBox from './NumberBox';
import putTicket from '../putTicket';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
// backgroundColor: 'green',
marginTop: 30,
width: '100%',
// height: 200,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
titleText: {
fontSize: 18,
width: '90%',
color: 'black',
fontWeight: 'bold'
},
subtitleText: {
fontSize: 18,
width: '90%',
color: 'black',
},
button: {
marginTop: 20,
// marginBottom: 30,
width: '100%',
color: 'black',
},
};
};
export default ({
raffleId,
}) => {
const styles = getStyles();
const isLoading = getState( 'isLoading' );
const selectedNumberOne = Number(
getState( 'destinyRaffle', 'selectedNumberOne' )
) || null;
const selectedNumberTwo = Number(
getState( 'destinyRaffle', 'selectedNumberTwo' )
) || null;
const buttonIsDisabled = (
isLoading ||
!Number.isInteger( selectedNumberOne ) ||
!Number.isInteger( selectedNumberTwo )
);
return e(
Box,
{
style: styles.outerContainer,
},
e(
Typography,
{
style: styles.titleText,
},
'Petal Pick'
),
e(
Typography,
{
style: styles.subtitleText,
},
'Select 2 different numbers between 1 and 36:'
),
e( NumberBox ),
e(
Button,
{
style: styles.button,
disabled: buttonIsDisabled,
onClick: async () => {
setState( 'isLoading', true );
try {
const googleCode = await grecaptcha.safeGetGoogleCode({
action: (
google
.grecapcha
.actions
.destinyRaffleTicketPut
)
});
if( !googleCode ) {
return setState( 'isLoading', false );
}
await putTicket({
raffleId,
numbers: [
selectedNumberOne,
selectedNumberTwo
],
action: 'buy',
googleCode
});
setState( 'isLoading', false );
}
catch( err ) {
setState( 'isLoading', false );
alert(
`error in buying ticket: ${
(
!!err &&
!!err.response &&
!!err.response.data &&
!!err.response.data.message &&
err.response.data.message
) || 'internal server error'
}`
);
}
}
},
'Pick Petal'
)
);
};
<file_sep>import {
createElement as e
} from 'react';
import Box from '@material-ui/core/Box';
import { getState } from '../../../reduxX';
import { gameData, games } from '../../../constants';
// import { javascript } from '../../../utils';
const slotConstants = gameData[ games.slot ];
const baseImageUrl = slotConstants.baseImageUrl;
// const krogUrl = 'https://s3.ca-central-1.amazonaws.com/dynastybitcoin.com/site/images/loading-frog-1.png';
const krogUrl = slotConstants.loadingImageUrl;
// const slotNumberToSymbolImageName = Object.freeze({
// 1: slotConstants.slotImageNames[0],
// 2: slotConstants.slotImageNames[1],
// 3: slotConstants.slotImageNames[2],
// });
// 'doge_logo_1.png',
// 'eth_logo_1.png',
// ];
// const slotNumberToSymbolImageNameSet1 = Object.freeze({
// 1: 'btc_logo_1.png',
// 2: 'doge_logo_1.png',
// 3: 'eth_logo_1.png',
// });
// const slotNumberToSymbolImageNameSet2 = Object.freeze({
// 1: 'btc_logo_1.png',
// 2:
// 3:
// });
// const truthy = javascript.getRandomIntInclusive( 0, 1 );
export default ({
slotNumber
}) => {
const slotNumberImageIndices = getState(
'loggedInMode',
'slot',
'slotNumberImageIndices'
);
const slotNumberToSymbolImageName = Object.freeze({
1: slotConstants.slotImageNames[ slotNumberImageIndices[0] ],
2: slotConstants.slotImageNames[ slotNumberImageIndices[1] ],
3: slotConstants.slotImageNames[ slotNumberImageIndices[2] ],
});
// useEffect( () => {
// setInterval( () => {
// const isLoading = getState( 'isLoading' );
// setState( [ 'isLoading' ], !isLoading );
// }, 2000 );
// }, [] );
// const slotNumberToSymbolImageName = truthy ? (
// slotNumberToSymbolImageNameSet1
// ) : slotNumberToSymbolImageNameSet2;
const symbolImageName = slotNumberToSymbolImageName[ slotNumber ];
const symbolImageUrl = `${ baseImageUrl }/${ symbolImageName }`;
const isLoading = getState( 'isLoading' );
return e(
Box,
{
style: {
// width: 180,
// height: 180,
maxWidth: '30%',
// height: 100,
height: '30vw',
maxHeight: 182,
// maxHeight: '20%',
// height: 100,
// backgroundColor: 'white',
borderStyle: 'solid',
borderWidth: 1,
borderColor: 'white',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 20
},
},
e(
Box,
{
style: {
width: '100%',
// height: '100%',
// color: 'black',
// backgroundColor: 'white',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
fontSize: 40,
borderRadius: 20,
// padding: 10,
},
},
isLoading ? e(
'img',
{
className: 'xx',
style: {
userSelect: 'none',
width: '83%',
pointerEvents: 'none',
borderRadius: 20,
},
src: krogUrl,
}
) : e(
'img',
{
style: {
width: '90%',
userSelect: 'none',
pointerEvents: 'none',
},
src: symbolImageUrl,
}
)
)
);
};
<file_sep>import { createElement as e, useEffect } from 'react';
import { getState, } from '../../../reduxX';
import { actions, grecaptcha } from '../../../utils';
import { LoginPolygon, TitlePolygon } from '../../../TheSource';
// import { story } from '../../../constants';
const getStyles = () => {
const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: mainStyleObject.backgroundColor,
width: 300,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
color: 'white',
},
};
};
export default () => {
useEffect( () => {
actions.scroll();
grecaptcha.showGrecaptcha();
return () => {
Promise.resolve().then( async () => {
try {
await grecaptcha.hideGrecaptcha();
}
catch( err ) {
console.log( 'error in hiding grecaptcha:', err );
}
});
};
}, [] );
const styles = getStyles();
// const isLoading = getState( 'isLoading' );
const createElementArguments = [
'div',
{
style: styles.outerContainer,
},
e(
TitlePolygon,
{
shouldHaveHomeButton: true,
marginBottom: 6,
}
),
e(
LoginPolygon,
{
marginBottom: 25,
}
)
];
return e( ...createElementArguments );
};
<file_sep>#!/usr/bin/env node
'use strict';
console.log( 'not implemented yet' );<file_sep>'use strict';
module.exports = Object.freeze({
getExchangeDatabaseEntry: require( './getExchangeDatabaseEntry' ),
});
<file_sep>cd
touch currentWithdrawReports.txt
touch safeErrors.txt
<file_sep>import { createElement as e, useEffect } from 'react';
import { getState, setState } from '../../../reduxX';
// import { gameData, games } from '../../../constants';
import { actions, delay } from '../../../utils';
import Paper from '@material-ui/core/Paper';
import NintendoSwitch from './NintendoSwitch';
import JackpotAmountDisplay from './JackpotAmountDisplay';
const getStyles = () => {
// const mainStyleObject = getState( 'mainStyleObject' );
return {
outerContainer: {
backgroundColor: 'lightGreen',
// maxWidth: 620,
width: '100%',
maxWidth: 165,
height: 85,
borderRadius: 5,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
},
};
};
export default ({
freeGameMode,
isJackpotMode,
}) => {
useEffect( () => {
const isLoggedIn = actions.getIsLoggedIn();
if( !freeGameMode && isLoggedIn ) {
const startedGettingJackpotDataForFirstTime = getState(
'loggedInMode',
'coinFlip',
'startedGettingJackpotDataForFirstTime'
);
if( !startedGettingJackpotDataForFirstTime ) {
setState(
[
'loggedInMode',
'coinFlip',
'startedGettingJackpotDataForFirstTime'
],
true
);
new Promise( async () => {
try {
await actions.refreshJackpotData();
await delay({ timeout: 3000 });
setState(
[
'loggedInMode',
'coinFlip',
'hasGottenJackpotDataForFirstTime'
],
true
);
}
catch( err ) {
console.log(
'an error occurred in loading jackpot data:',
err
);
}
});
}
}
}, [ freeGameMode ] );
const styles = getStyles();
return e(
Paper,
{
style: styles.outerContainer,
},
e(
NintendoSwitch,
{
isJackpotMode
}
),
e(
JackpotAmountDisplay,
{
isJackpotMode,
freeGameMode,
}
)
);
};
<file_sep>'use strict';
const {
utils: {
// stringify,
bitcoin: {
formatting: { getAmountNumber }
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const bitcoinSumReducer = Object.freeze(
( accumulator, currentValue ) => accumulator + currentValue.amount
);
const getSumOfBitcoinDeposits = Object.freeze( ({
bitcoinData
}) => {
const sumOfBitcoinDeposits = bitcoinData.reduce( bitcoinSumReducer, 0 );
return sumOfBitcoinDeposits;
});
module.exports = Object.freeze( ({
exchangeUser,
balanceData,
}) => {
const bitcoinData = (
!!exchangeUser.moneyData &&
!!exchangeUser.moneyData.bitcoin &&
exchangeUser.moneyData.bitcoin
) || [];
if( bitcoinData.length === 0 ) {
const bitcoinBalanceData = {
totalAmount: 0,
depositAddress: null
};
balanceData.bitcoin = bitcoinBalanceData;
return;
}
const totalAmount = getSumOfBitcoinDeposits({
bitcoinData
});
const depositAddress = bitcoinData[
bitcoinData.length - 1
].address;
const bitcoinBalanceData = {
totalAmount: getAmountNumber( totalAmount ),
depositAddress
};
balanceData.bitcoin = bitcoinBalanceData;
});
<file_sep>'use strict';
const {
utils: {
doOperationInQueue,
stringify,
javascript: {
getQueueId
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser,
getExchangeUser,
}
}
},
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_USERS
}
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
constants: {
http: {
headers
}
}
} = require( '../../../../../utils' );
const validateAndGetValues = require( './validateAndGetValues' );
const getAddTransactionValues = require( './getAddTransactionValues' );
module.exports = Object.freeze( async ({
event,
exchangeUserId,
ipAddress,
}) => {
const rawType = event.body.type;
const rawData = event.body.data;
const rawGoogleCode = event.headers[ headers.grecaptchaGoogleCode ];
console.log(
'running doExchange with the following values:',
stringify({
rawType,
rawData,
rawGoogleCode: !!rawGoogleCode,
ipAddress
})
);
const {
type,
data
} = await validateAndGetValues({
rawType,
rawData,
rawGoogleCode,
ipAddress
});
const doExchangeResponseValues = await doOperationInQueue({
queueId: getQueueId({ type: EXCHANGE_USERS, id: exchangeUserId }),
doOperation: async () => {
const exchangeUser = await getExchangeUser({
exchangeUserId,
});
if( !exchangeUser ) {
// safeguard: should not get here in normal operation
throw new Error(
'cannot find exchange user: ' +
exchangeUserId
);
}
const addTransactionValues = getAddTransactionValues({
exchangeUserId,
exchangeUser,
type,
data
});
await addTransactionAndUpdateExchangeUser( addTransactionValues );
return {};
}
});
console.log(
'doExchange executed successfully: ' +
stringify( doExchangeResponseValues )
);
return doExchangeResponseValues;
});<file_sep>const MetaCoin = artifacts.require("MetaCoin");
contract('MetaCoin', (accounts) => {
it('should put 10000 MetaCoin in the first account', async () => {
const metaCoinInstance = await MetaCoin.deployed();
const balance = await metaCoinInstance.getBalance.call(accounts[0]);
assert.equal(balance.valueOf(), 10000, "10000 wasn't in the first account");
});
it('should call a function that depends on a linked library', async () => {
const metaCoinInstance = await MetaCoin.deployed();
const metaCoinBalance = (await metaCoinInstance.getBalance.call(accounts[0])).toNumber();
const metaCoinEthBalance = (await metaCoinInstance.getBalanceInEth.call(accounts[0])).toNumber();
assert.equal(metaCoinEthBalance, 2 * metaCoinBalance, 'Library function returned unexpected function, linkage may be broken');
});
it('should send coin correctly', async () => {
const metaCoinInstance = await MetaCoin.deployed();
// Setup 2 accounts.
const accountOne = accounts[0];
const accountTwo = accounts[1];
// Get initial balances of first and second account.
const accountOneStartingBalance = (await metaCoinInstance.getBalance.call(accountOne)).toNumber();
const accountTwoStartingBalance = (await metaCoinInstance.getBalance.call(accountTwo)).toNumber();
// Make transaction from first account to second.
const amount = 10;
await metaCoinInstance.sendCoin(accountTwo, amount, { from: accountOne });
// Get balances of first and second account after the transactions.
const accountOneEndingBalance = (await metaCoinInstance.getBalance.call(accountOne)).toNumber();
const accountTwoEndingBalance = (await metaCoinInstance.getBalance.call(accountTwo)).toNumber();
assert.equal(accountOneEndingBalance, accountOneStartingBalance - amount, "Amount wasn't correctly taken from the sender");
assert.equal(accountTwoEndingBalance, accountTwoStartingBalance + amount, "Amount wasn't correctly sent to the receiver");
});
});
<file_sep>'use strict';
const {
utils: {
stringify,
},
// constants: {
// redis: {
// streamIds
// }
// }
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
eventNames
}
} = require( '@bitcoin-api/giraffe-utils' );
const handleLickComplete = require( './handleLickComplete' );
const handleTigerEnlightenment = require( './handleTigerEnlightenment' );
module.exports = Object.freeze( ({
forceDeploy
}) => Object.freeze( async ({
eventName,
information
}) => {
console.log(
'🧞♀️performActionBasedOnDeployEvent - ' +
`🌴tree got ${ eventName } event with information: ` +
stringify( information )
);
switch( eventName ) {
case eventNames.leaf.tongueFeel:
case eventNames.leaf.tigerCommand:
case eventNames.leaf.serviceIsGood:
console.log(
`event ${ eventName } is not relevant ` +
'to the tree🎄🚫📰 - skipping event'
);
break;
case eventNames.giraffe.lickComplete:
await handleLickComplete({
information,
forceDeploy,
});
break;
case eventNames.tiger.tigerEnlightenment:
await handleTigerEnlightenment({
information
});
break;
default:
throw new Error(
'performActionBasedOnDeployEvent error - ' +
`unexpected ${ eventName }`
);
}
console.log(
'🧞♀️performActionBasedOnDeployEvent - ' +
'🦒giraffe executed the function successfully✅✅'
);
}));
<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../../../reduxX';
import Paper from '@material-ui/core/Paper';
const getStyles = ({
choiceInput,
cardIcon,
defaultColor,
isLoading,
}) => {
return {
card: {
height: 200,
width: '45%',
borderRadius: 30,
backgroundColor: isLoading ? (
'darkgrey'
) : (
(choiceInput === cardIcon) ? 'black' : defaultColor
),
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
marginTop: 5,
marginBottom: 5,
// color: 'white',
// marginTop: 10,
},
image: {
width: '100%',
}
};
};
export default ({
choiceInput,
cardIcon = 'trump',
defaultColor = 'blue',
choiceToChoiceData,
}) => {
const isLoading = getState( 'isLoading' );
const styles = getStyles({
choiceInput,
cardIcon,
defaultColor,
isLoading,
});
const { image } = choiceToChoiceData[ cardIcon ];
return e(
Paper,
{
style: styles.card,
elevation: 3,
onClick: () => {
if( isLoading ) {
return;
}
const choiceInput = getState(
[ 'presidentialVote2020', 'choiceInput' ],
cardIcon
);
if( !!choiceInput && (choiceInput === cardIcon) ) {
setState(
[ 'presidentialVote2020', 'choiceInput' ],
null
);
}
else {
setState(
[ 'presidentialVote2020', 'choiceInput' ],
cardIcon
);
}
}
},
e(
'img',
{
style: styles.image,
src: image,
}
)
);
};
<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const { sesv2 } = require( '../aws' );
module.exports = Object.freeze( async ({
subject,
html,
text,
toEmailAddress,
fromEmailAddress = '<EMAIL>',
}) => {
console.log( 'running sendEmail' );
const params = {
Content: {
Simple: {
Body: {
Html: {
Data: html,
Charset: 'UTF-8'
},
Text: {
Data: text,
Charset: 'UTF-8'
}
},
Subject: {
Data: subject,
Charset: 'UTF-8'
}
},
},
Destination: {
// BccAddresses: [
// 'STRING_VALUE',
// /* more items */
// ],
// CcAddresses: [
// 'STRING_VALUE',
// /* more items */
// ],
ToAddresses: [
toEmailAddress,
/* more items */
]
},
FromEmailAddress: fromEmailAddress,
};
const {
emailMessageId,
} = await new Promise( ( resolve, reject ) => {
sesv2.sendEmail(
params,
( err, data ) => {
if( !!err ) {
console.log(
'sendEmail: error in sending email',
err
);
return reject( err );
}
console.log(
'sendEmail - email successfully sent - ' +
`AWS response data: ${ stringify( data ) }`
);
resolve({
emailMessageId: data.MessageId,
});
}
);
});
const sendEmailResults = {
emailMessageId,
};
console.log(
'sendEmail executed successfully - returning results: ' +
stringify( sendEmailResults )
);
return sendEmailResults;
});
<file_sep>export { default as refreshRaffleTickets } from './refreshRaffleTickets';
<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
beginningDragonProtection,
} = require( '../../utils' );
const getIfLoginTokenIsValidData = require( './getIfLoginTokenIsValidData' );
const {
headers
} = require( '../constants' );
module.exports = Object.freeze( async ({
queueName,
event,
ipAddressMaxRate,
ipAddressTimeRange,
altruisticCode,
altruisticCodeIsRequired,
altruisticCodeMaxRate,
altruisticCodeTimeRange,
shouldOnlyGetInitialTokens = true,
shouldGetFullLoginTokenInfo = false,
}) => {
const exchangeUserId = event.headers[ headers.userId ];
if( !exchangeUserId ) {
const validationError = new Error( 'missing userId' );
validationError.statusCode = 400;
validationError.bulltrue = true;
throw validationError;
}
else if(
(typeof exchangeUserId !== 'string') ||
(exchangeUserId.length > 200)
) {
const validationError = new Error(
`invalid userId: ${ exchangeUserId }`
);
validationError.statusCode = 400;
validationError.bulltrue = true;
throw validationError;
}
console.log(
'🔥🔥🔥🔥🐉🐲🐉🐲Running mongolianBeginningDragonProtection ' +
`with the following values: ${
stringify({
queueName,
event,
ipAddressMaxRate,
ipAddressTimeRange,
exchangeUserId,
altruisticCode,
altruisticCodeIsRequired,
altruisticCodeMaxRate,
altruisticCodeTimeRange,
shouldGetFullLoginTokenInfo,
shouldOnlyGetInitialTokens
})
}🐉🐲🐉🐲🔥🔥🔥🔥`
);
const powerDragonCollection = {
exchangeUserId,
};
const mongolianDragonFindings = await beginningDragonProtection({
queueName,
event,
megaCodeIsRequired: false,
altruisticCode,
altruisticCodeIsRequired,
altruisticCodeMaxRate,
altruisticCodeTimeRange,
ipAddressMaxRate,
ipAddressTimeRange,
customDragonFunction: async () => {
const loginTokenId = event.headers[ headers.loginToken ];
if( !loginTokenId ) {
const error = new Error(
'missing "login-token" in header'
);
error.statusCode = 400;
error.bulltrue = true;
throw error;
}
const {
loginTokenIsValid,
loginTokens,
hashedLoginTokenIdFromRequestHeader,
} = await getIfLoginTokenIsValidData({
exchangeUserId,
loginTokenId,
shouldGetFullLoginTokenInfo,
shouldOnlyGetInitialTokens
});
if( !loginTokenIsValid ) {
const error = new Error(
'invalid "login-token" header provided'
);
error.statusCode = 403;
error.bulltrue = true;
throw error;
}
Object.assign(
powerDragonCollection,
{
loginTokenId,
loginTokens,
hashedLoginTokenIdFromRequestHeader,
}
);
},
});
const extensiveMongolDragonFindings = Object.assign(
{},
mongolianDragonFindings,
powerDragonCollection
);
console.log(
'mongolianBeginningDragonProtection executed successfully ' +
`here are the dragon findings: ${
stringify(
Object.keys( extensiveMongolDragonFindings )
)
}`
);
return extensiveMongolDragonFindings;
});<file_sep>'use strict';
const fiveMinutes = 1000 * 60 * 5;
// const deadFunction = Object.freeze(
module.exports = Object.freeze(
({ name }) => new Promise( (/* resolve, reject */) => {
const runFunctionRecursion = async () => {
const date = new Date();
const powerOfNowString = (
`${ date.toDateString() } ${ date.toTimeString() } - ` +
date.getTime().toString()
);
console.log(
`${ name } is dead💀🏴☠️ - ${ powerOfNowString }`
);
await new Promise( resolve => setTimeout( resolve, fiveMinutes ) );
runFunctionRecursion();
};
runFunctionRecursion();
})
);
// (() => {
// console.log( 1 + 4 );
// return deadFunction({
// name: 'bot'
// });
// })();<file_sep>'use strict';
module.exports = Object.freeze( ({
envKey
}) => {
const envValue = process.env[ envKey ];
const envValueIsTruthful = !(
!envValue ||
[
'undefined',
'null',
'""',
'"',
`''`,
`'`,
].includes( envValue )
);
return envValueIsTruthful;
});
<file_sep>'use strict';
/*
[
{
type: 'string',
key: 'MONKEY_VALUE',
}
]
*/
const {
getIfUrlIsValid,
getIfEmailIsValid,
} = require( '../validation' );
const envValidationTypes = Object.freeze({
number: 'number',
string: 'string',
url: 'url',
email: 'email',
});
const getIfEnvValuesAreValid = data => {
console.log( 'running getIfEnvValuesAreValid' );
for( const datum of data ) {
if( !datum.undefinedAllowed ) {
datum.undefinedAllowed = false;
}
if(
!datum.key ||
(typeof datum.key !== 'string') ||
!envValidationTypes[ datum.type ]
) {
throw new Error(
'getIfEnvValuesAreValid error: invalid datum ' +
JSON.stringify( datum )
);
}
else if(
!!datum.extraValidation &&
(typeof datum.extraValidation !== 'function')
) {
throw new Error(
'getIfEnvValuesAreValid error: invalid datum ' +
JSON.stringify( datum )
);
}
const envValue = process.env[ datum.key ];
if(
!datum.undefinedAllowed &&
(
!envValue ||
[
'undefined',
'null',
'""',
'"',
`''`,
`'`,
].includes( envValue )
)
) {
throw new Error(
'getIfEnvValuesAreValid error: invalid datum ' +
JSON.stringify( datum ) +
' - undefined not allowed'
);
}
switch (datum.type ) {
case envValidationTypes.string: {
if( typeof envValue !== 'string' ) {
throw new Error(
'getIfEnvValuesAreValid error: invalid datum ' +
JSON.stringify( datum ) +
' - env value not a string'
);
}
break;
}
case envValidationTypes.number: {
const envValueAsNumber = Number( envValue );
if(
(typeof envValueAsNumber !== 'number') ||
Number.isNaN( envValueAsNumber )
) {
throw new Error(
'getIfEnvValuesAreValid error: invalid datum ' +
JSON.stringify( datum ) +
' - env value not a number'
);
}
break;
}
case envValidationTypes.url: {
if( !getIfUrlIsValid({ url: envValue }) ) {
throw new Error(
'getIfEnvValuesAreValid error: invalid datum ' +
JSON.stringify( datum ) +
' - env value not a url'
);
}
break;
}
case envValidationTypes.email: {
if( !getIfEmailIsValid({ email: envValue }) ) {
throw new Error(
'getIfEnvValuesAreValid error: invalid datum ' +
JSON.stringify( datum ) +
' - env value not an email'
);
}
break;
}
default:
throw new Error(
'getIfEnvValuesAreValid error: ' +
'weird switch case error'
);
}
if( !!datum.extraValidation ) {
try {
datum.extraValidation( envValue );
}
catch( err ) {
throw new Error(
'getIfEnvValuesAreValid error: invalid datum ' +
JSON.stringify( datum ) +
' - did not pass extra validation - ' +
err.message
);
}
}
}
console.log(
'getIfEnvValuesAreValid executed successfully ' +
'env values are valid'
);
};
getIfEnvValuesAreValid.envValidationTypes = envValidationTypes;
module.exports = Object.freeze( getIfEnvValuesAreValid );
<file_sep>import { createElement as e, lazy, Suspense } from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import { getState } from '../../../reduxX';
import { games } from '../../../constants';
import { actions } from '../../../utils';
import { TitlePolygon } from '../../../TheSource';
// const FreeDestinyRaffle = lazy(() => import('./freeGameModes/FreeDestinyRaffle'));
const CoinExperiencePolygon = lazy(() => import('../../../TheEnchantedSource/CoinExperiencePolygon'));
const SlotPolygon = lazy(() => import('../../../TheEnchantedSource/SlotPolygon'));
// import { CoinExperiencePolygon } from '../../../TheEnchantedSource/CoinExperiencePolygon';
// import { FreeDestinyRaffle } from './freeGameModes';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'pink',
width: '100%',
maxWidth: 620,
// height: 300,
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
color: 'white',
},
menuButton: {
marginRight: 10,
}
};
};
const getGameData = () => {
const freeGame = getState( 'notLoggedInMode', 'freeGame' );
switch( freeGame ) {
case games.theDragonsTalisman: {
return {
titleBackgroundColor: 'lightgreen',
game: e(
Suspense,
{
fallback: e( 'div' ),
},
e(
CoinExperiencePolygon,
{
freeGameMode: true,
}
)
)
};
}
case games.slot: {
return {
// titleBackgroundColor: ''
game: e(
Suspense,
{
fallback: e( 'div' ),
},
e(
SlotPolygon,
{
freeGameMode: true,
}
)
),
};
// return e(
// CoinExperiencePolygon,
// {
// freeGameMode: true,
// }
// );
}
// case games.destinyRaffle: {
// return {
// // titleBackgroundColor: ''
// game: e(
// Suspense,
// {
// fallback: e( 'div' ),
// },
// e( FreeDestinyRaffle )
// ),
// };
// // return e(
// // CoinExperiencePolygon,
// // {
// // freeGameMode: true,
// // }
// // );
// }
default: {
return null;
}
}
};
export default () => {
const styles = getStyles();
// const isLoading = getState( 'isLoading' );
const {
titleBackgroundColor,
game,
} = getGameData();
return e(
Box,
{
style: styles.outerContainer,
},
e(
TitlePolygon,
{
backgroundColor: titleBackgroundColor,
customButton: e(
Button,
{
style: styles.menuButton,
onClick: () => {
actions.goToHomePage();
// setState(
// [
// 'notLoggedInMode',
// 'freeGame'
// ],
// null
// );
},
},
e(
Typography,
{
style: styles.menuButtonText,
},
'Home'
)
)
}
),
game
);
};
<file_sep>'use strict';
const doRedisRequest = require( 'do-redis-request' );
const {
getKeyValues,
constants: {
START,
END,
},
getRedisXAddArguments,
obliterateOperationFromQueue,
getOperationTime,
delay,
xRangeWithPagination,
getIncrementedTimeKeyData
} = require( '../tools' );
const waitUntilItIsTime = require( './waitUntilItIsTime' );
const getPreviousOperationStartKeyValuesAndInfo = Object.freeze( ({
// operationStartOrder,
currentOperations
}) => {
for(
let i = (currentOperations.length - 1);
i >= 0;
i--
) {
const {
timeKey,
keyValues
} = currentOperations[i];
if( keyValues.state === START ) {
return {
previousOperationStartTimeKey: timeKey,
previousOperationStartOrder: i,
previousOperationStartKeyValues: keyValues
};
}
}
return {
previousOperationStartTimeKey: null,
previousOperationStartOrder: null,
previousOperationStartKeyValues: null
};
});
const getPreviousOperationEndKeyValuesAndInfo = Object.freeze( ({
// operationStartOrder,
previousOperationStartOrder,
currentOperations,
previousOperationStartKeyValues
}) => {
for(
let i = (currentOperations.length - 1);
i > previousOperationStartOrder;
i--
) {
const {
// timeKey,
keyValues
} = currentOperations[i];
if(
(
keyValues.operationId ===
previousOperationStartKeyValues.operationId
) &&
// ( // implied
// keyValues.queueId ===
// previousOperationStartKeyValues.queueId
// ) &&
(keyValues.state === END)
) {
return {
previousOperationEndKeyValues: keyValues
};
}
}
return {
previousOperationEndKeyValues: null
};
});
module.exports = Object.freeze( async ({
redisClient,
operationId,
queueId,
doOperation,
doOperationArgs,
timeout,
operationTimeout,
}) => {
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`running doOperationInQueueCore for operation: "${ operationId }"`
);
const operationTimeKey = await doRedisRequest({
client: redisClient,
command: 'xadd',
redisArguments: getRedisXAddArguments({
queueId,
operationId,
state: START,
timeout,
operationTimeout,
// magnaQueue
}),
});
const operationTime = getOperationTime({ operationTimeKey });
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`time data: ${ JSON.stringify({
operationTimeKey,
timeout,
operationTimeout,
}, null, 4 )}`
);
const startTime = (
operationTime - (timeout + operationTimeout + 100)
);
/*
OPTIMIZATION:
could optimize by using XREVRANGE without pagination check if previous
operation is there
paginateThroughForPreviousOperationAndWaitIfFound = async () => ...
*/
const currentOperations = (
await xRangeWithPagination({
redisClient,
startTime,
endTime: getIncrementedTimeKeyData({
timeKey: operationTimeKey,
add: false
})
})
).map( rawCurrentOperation => {
const timeKey = rawCurrentOperation[0];
const currentOperation = {
timeKey,
keyValues: getKeyValues({
keyValueList: rawCurrentOperation[1],
})
};
if( currentOperation.keyValues.queueId === queueId ) {
return currentOperation;
}
else {
return null;
}
}).filter( currentOperation => !!currentOperation );
const {
previousOperationStartTimeKey,
previousOperationStartOrder,
previousOperationStartKeyValues
} = getPreviousOperationStartKeyValuesAndInfo({
// operationStartOrder,
currentOperations
});
if( !!previousOperationStartKeyValues ) {
const {
previousOperationEndKeyValues
} = getPreviousOperationEndKeyValuesAndInfo({
// operationStartOrder,
previousOperationStartOrder,
currentOperations,
previousOperationStartKeyValues
});
if( !previousOperationEndKeyValues ) {
const whenThePreviousOperationWillBeFinishedForSure = (
getOperationTime({
operationTimeKey: previousOperationStartTimeKey,
}) +
previousOperationStartKeyValues.timeout +
previousOperationStartKeyValues.operationTimeout +
20
);
if( Date.now() < whenThePreviousOperationWillBeFinishedForSure ) {
await waitUntilItIsTime({
redisClient,
whenThePreviousOperationWillBeFinishedForSure,
queueId,
firstLastTimeKey: operationTimeKey,
operationId,
previousOperationStartKeyValues,
timeout
});
}
}
}
// await paginateThroughForPreviousOperationAndWaitIfFound();
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
'doing operation'
);
const doOperationResults = await new Promise( async (
resolve,
reject
) => {
let operationHasFinished = false;
let operationTimedOut = false;
let errorOccurred = false;
delay( operationTimeout ).then( () => {
if( !errorOccurred && !operationHasFinished ) {
operationTimedOut = true;
const error = new Error(
`timeout error: Operation "${ operationId }" ` +
`on queue with id "${ queueId }" ` +
'did not finish on time⏰. ' +
`The timeout of ${ operationTimeout/1000 } ` +
`seconds was hit WHILE ` +
'this operation was being performed🧐. '
);
return reject( error );
}
});
try {
const doOperationResults = await doOperation( ...doOperationArgs );
if( !errorOccurred && !operationTimedOut ) {
operationHasFinished = true;
return resolve( doOperationResults );
}
}
catch( err ) {
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
`error occured in doing operation: ${ err }`
);
if( !operationTimedOut && !operationHasFinished ) {
errorOccurred = true;
return reject( err );
}
}
});
await obliterateOperationFromQueue({
redisClient,
queueId,
operationId,
});
console.log(
`▼queueId: ${ queueId } - ` +
`👁operation: ${ operationId } - ` +
'doOperationInQueueCore executed successfully, ' +
'here are the doOperationResults: ' +
JSON.stringify( doOperationResults, null, 4 )
);
return doOperationResults;
});<file_sep>'use strict';
const AWS = require( 'aws-sdk' );
const yargs = require( 'yargs' );
const isProductionMode = (yargs.argv.mode === 'production');
if( isProductionMode ) {
console.log( '☢︎🐑 is production mode' );
require( 'dotenv' ).config({
path: `${ __dirname }/productionCredentials/.env`
});
process.env.BITCOIN_API_ENV = 'production';
}
else {
console.log( '🐲🐉 is staging mode' );
require( 'dotenv' ).config({
path: `${ __dirname }/stagingCredentials/.env`
});
process.env.BITCOIN_API_ENV = 'staging';
}
const {
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
AWS_REGION,
AWS_ACCOUNT_NUMBER,
INSTANCE_PREFIX,
} = process.env;
AWS.config.update({
accessKeyId: AWS_ACCESS_KEY_ID,
secretAccessKey: AWS_SECRET_ACCESS_KEY,
region: AWS_REGION,
});
const iam = new AWS.IAM();
const stageSuffix = isProductionMode ? '' : '_staging';
const getPolicyData = require( './getPolicyData' );
const policyData = getPolicyData({
awsAccountNumber: AWS_ACCOUNT_NUMBER,
awsRegion: AWS_REGION,
stageSuffix,
instancePrefix: INSTANCE_PREFIX
});
const createPolicy = Object.freeze( ({
policy,
name,
}) => {
return new Promise( ( resolve, reject ) => {
const awsPolicyName = `${ INSTANCE_PREFIX }${ name }${ stageSuffix }`;
const params = {
PolicyDocument: policy, /* required */
PolicyName: awsPolicyName,
};
console.log(
'create policy with params: ' +
JSON.stringify( params, null, 4 )
);
params.PolicyDocument = JSON.stringify( params.PolicyDocument );
iam.createPolicy( params, ( err, data ) => {
if( !!err ) {
console.log( 'error in creating policy:', err );
return reject( err );
}
console.log(
'successfully created policy: ' +
JSON.stringify({
awsPolicyName,
responseData: data
}, null, 4 )
);
resolve( data );
});
});
});
(async () => {
try {
console.log( 'setting up policies' );
for( const policyDatum of policyData ) {
await createPolicy( policyDatum );
}
console.log( 'set up policies successfully executed' );
}
catch( err ) {
console.log(
'an error occurred in setting up policies:',
err
);
}
})();
<file_sep>'use strict';
module.exports = Object.freeze({
getTheOracleOfDelphiDefi: require( './getTheOracleOfDelphiDefi' ),
});
<file_sep>'use strict';
/*
RUN EVERY 15 minutes, function hasn't been run in past 15 minutes,
then run again
get lastPaginationValue from metadata update alien balance glyph
if last update just happened
or if no lastpagination value and it is still within 20 seconds
get all alien addresses starting with address_bsc_1
for each address
get user balance
if diff -> balanceUpdate ATAEUE
run with next function
*/
module.exports = Object.freeze( async () => {
});
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
// import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'pink',
// width: '100%',
// width: 300,
// height: 230,
display: 'flex',
justifyContent: 'space-around',
flexDirection: 'column',
alignItems: 'center'
},
theQrImage: {
marginTop: 20,
marginBottom: 20,
},
theAddressTextMetaBox: {
// width: 620,
width: 320,
backgroundColor: 'black',
borderRadius: 5,
display: 'flex',
justifyContent: 'center',
flexDirection: 'column',
alignItems: 'center'
},
theAddressTextBox: {
width: 318,
height: '90%',
backgroundColor: 'white',
borderRadius: 4,
marginTop: 2,
marginBottom: 2,
// padding: 15,
},
theAddressText: {
color: 'black',
// wordWrap: 'break-word',
width: '100%',
paddingTop: 20,
paddingBottom: 20,
// paddingLeft: 5,
// paddingRight: 5,
fontSize: 12,
// overflowX: 'scroll',
textAlign: 'center',
}
};
};
const qrCodeBaseUrl = (
process.env.REACT_APP_QR_CODES_BASE_URL ||
'https://s3.ca-central-1.amazonaws.com/dynastybitcoin.com/qr_codes'
);
export default ({
address,
}) => {
const styles = getStyles();
const qrCodeUrl = `${ qrCodeBaseUrl }/${ address }.jpg`;
return e(
Box,
{
style: styles.outerContainer,
},
e(
'img',
{
src: qrCodeUrl,
style: styles.theQrImage,
}
),
e(
Box,
{
style: styles.theAddressTextMetaBox,
},
e(
Box,
{
style: styles.theAddressTextBox,
},
e(
Typography,
{
style: styles.theAddressText,
},
address
)
)
)
);
};
<file_sep>'use strict';
const {
utils: {
stringify,
doOperationInQueue,
javascript: {
getQueueId
}
},
constants: {
aws: {
database: {
tableNames: {
METADATA
}
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser,
}
},
crypto: {
getCryptoAmountNumber
}
},
constants: {
transactions,
dreams,
aws: {
database: {
searchIds: {
dreamLotus
}
}
},
queues: {
queueBaseIds: {
lotusDreamsJackpotWin,
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
maxAmount,
} = require( '../localConstants' );
const flipCoin = require( './flipCoin' );
const flipJackpot = require( './flipJackpot' );
const getWinAmount = require( './getWinAmount' );
const updateJackpotMetadata = require( './updateJackpotMetadata' );
const {
dream: { getJackpotMetadata }
} = require( '../../../../../../enchantedUtils' );
// const minimumJackpotAmount = 0.3;
const minimumJackpotAmount = 0;
const houseCut = 0.05;
module.exports = Object.freeze( async ({
amount,
exchangeUserId,
}) => {
console.log(
'running doEnchantedLuck ' +
`with the following values: ${ stringify({
amount,
exchangeUserId
})}`
);
const hasWonGame = flipCoin();
const happyDream = hasWonGame;
// const transactionAmount = hasWonGame ? amount : -amount;
const transactionData = {
dreamType: dreams.types.lotus,
happyDream,
searchId: dreamLotus,
amount: 0,
};
if( happyDream ) {
transactionData.amount += amount;
const hasWonJackpot = flipJackpot();
if( hasWonJackpot ) {
await doOperationInQueue({
queueId: getQueueId({
type: METADATA,
id: lotusDreamsJackpotWin,
}),
doOperation: async () => {
const {
jackpotAmount,
} = await getJackpotMetadata();
// { jackpotAmount, unhappyDreamCount }
const isTrueJackpotWin = (
jackpotAmount >=
minimumJackpotAmount
);
console.log(
'🦉Jackpot Win Comparison:',
stringify({
jackpotAmount,
minimumJackpotAmount,
isTrueJackpotWin,
})
);
if( isTrueJackpotWin ) {
const winAmount = getWinAmount({
amount,
jackpotAmount,
houseCut,
});
transactionData.jackpotWinData = {
amount,
maxAmount,
minimumJackpotAmount,
jackpotAmount,
houseCut,
winAmount,
time: Date.now(),
};
transactionData.amount = getCryptoAmountNumber(
transactionData.amount + winAmount
);
await updateJackpotMetadata({
jackpotAmount,
winAmount,
});
}
else {
console.log(
'WOW, WOW, WOW, ' +
'JACKPOT WIN BUT NOT HIGH ENOUGH' +
'🐲🐲🐲🐲🐲🐲🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥 - ' +
stringify({
jackpotAmount,
minimumJackpotAmount
}) +
' The Dragon STRIKES in its MIGHT!!!!!!' +
'🐉🐉🐉🐉🐉🐉'
);
}
},
});
}
}
else {
transactionData.amount -= amount;
}
await addTransactionAndUpdateExchangeUser({
noLocka: true,
exchangeUserId,
type: transactions.types.dream,
data: transactionData,
});
const luckResults = {
happyDream,
};
console.log(
'doEnchantedLuck executed successfully - ' +
`returning luck results: ${ stringify( luckResults ) }`
);
return luckResults;
});<file_sep>import {
enchanted
} from '../../../../../../../../utils';
import getNumbersAvsNumbersB from '../getNumbersAvsNumbersB';
const putOwnProcessedDataFirst = ({
sortByTicketProcessedData
}) => {
sortByTicketProcessedData.sort( ( datumA, datumB ) => {
if( datumA.own && !datumB.own ) {
return -1;
}
else if( !datumA.own && datumB.own ) {
return 1;
}
return 0;
});
};
export default ({
data,
ownSpecialId
}) => {
const choiceToData = {};
for( const { time, choice, specialId } of data ) {
if( !choiceToData[ choice ] ) {
choiceToData[ choice ] = {
numberOfTicketsPurchased: 1,
mostRecentPurchaseTime: time,
own: (specialId === ownSpecialId)
};
}
else {
if( time > choiceToData[ choice ].mostRecentPurchaseTime ) {
choiceToData[ choice ].mostRecentPurchaseTime = time;
}
if(
(specialId === ownSpecialId) &&
!choiceToData[ choice ].own
) {
choiceToData[ choice ].own = true;
}
choiceToData[ choice ].numberOfTicketsPurchased++;
}
}
const sortByTicketProcessedData = [];
Object.keys( choiceToData ).forEach( choice => {
const data = Object.assign(
{},
choiceToData[ choice ],
{
choice
}
);
sortByTicketProcessedData.push( data );
});
sortByTicketProcessedData.sort( ( datumA, datumB ) => {
const numbersA = enchanted.destinyRaffle.getNumbersFromChoice({
choice: datumA.choice
});
const numbersB = enchanted.destinyRaffle.getNumbersFromChoice({
choice: datumB.choice
});
return getNumbersAvsNumbersB({
numbersA,
numbersB
});
});
sortByTicketProcessedData.sort( ( datumA, datumB ) => {
return (
datumB.numberOfTicketsPurchased -
datumA.numberOfTicketsPurchased
);
});
putOwnProcessedDataFirst({
sortByTicketProcessedData,
});
return sortByTicketProcessedData;
};<file_sep>'use strict';
module.exports = Object.freeze(
message => JSON.stringify( message, null, 4 )
);
<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../reduxX';
import { validation } from '../../utils';
import { story } from '../../constants';
import { WatermelonInput, POWBlock } from '../usefulComponents';
import LegalCheckbox from './LegalCheckbox';
import signUp from './signUp';
const getStyles = () => {
const mainStyleObject = getState( 'mainStyleObject' );
const isLoading = getState( 'isLoading' );
return {
outerContainer: {
backgroundColor: mainStyleObject.backgroundColor,
width: 300,
// height: 200,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
color: 'white',
},
input: {
width: '90%',
},
loginButton: {
backgroundColor: isLoading ? 'grey' : 'green',
borderRadius: 5,
width: '75%',
padding: 20,
userSelect: 'none',
}
};
};
export default ({
callback,
}) => {
const styles = getStyles();
const emailInput = getState( 'signUpPolygon', 'emailInput' );
const passwordInput = getState( 'signUpPolygon', 'passwordInput' );
const reTypePasswordInput = getState( 'signUpPolygon', 'reTypePasswordInput' );
const isLoading = getState( 'isLoading' );
const agreeToTermsOfService = getState( 'signUpPolygon', 'agreeToTermsOfService' );
const agreeToPrivacyPolicy = getState( 'signUpPolygon', 'agreeToPrivacyPolicy' );
const itIsOkayToMakeASignUpRequestRightNow = (
!isLoading &&
validation.isValidEmail( emailInput ) &&
validation.isValidPassword( passwordInput ) &&
(passwordInput === reTypePasswordInput) &&
agreeToTermsOfService &&
agreeToPrivacyPolicy
);
return e(
'div',
{
style: styles.outerContainer,
},
e(
'form',
{
id: 'signUpPolygonForm',
},
e(
WatermelonInput,
{
isLoadingMode: isLoading,
marginTop: 30,
value: emailInput,
title: 'email',
autoComplete: 'no',
onChange: event => {
const newText = event.target.value;
if( newText.length > 200 ) {
return;
}
setState(
[
'signUpPolygon',
'emailInput'
],
newText.trim()
);
},
}
),
e(
WatermelonInput,
{
marginTop: 30,
isLoadingMode: isLoading,
title: 'password',
value: passwordInput,
autoComplete: 'no',
type: 'password',
onChange: event => {
const newText = event.target.value;
if( newText.length > 200 ) {
return;
}
setState(
[
'signUpPolygon',
'passwordInput'
],
newText.trim()
);
},
}
),
e(
WatermelonInput,
{
marginTop: 30,
isLoadingMode: isLoading,
title: 'retype password',
value: reTypePasswordInput,
type: 'password',
autoComplete: 'no',
onChange: event => {
const newText = event.target.value;
if( newText.length > 200 ) {
return;
}
setState(
[
'signUpPolygon',
'reTypePasswordInput'
],
newText.trim()
);
},
}
),
e(
LegalCheckbox,
{
isLoadingMode: isLoading,
text: 'Agree to the ',
linkText: 'Terms of Service',
marginTop: 60,
checked: agreeToTermsOfService,
onCheck: event => {
setState(
[
'signUpPolygon',
'agreeToTermsOfService'
],
event.target.checked
);
},
onLinkClick: () => {
setState(
'metaMode',
story.metaModes.termsOfService
);
},
},
),
e(
LegalCheckbox,
{
isLoadingMode: isLoading,
text: 'Agree to the ',
linkText: 'Privacy Policy',
marginTop: 20,
checked: agreeToPrivacyPolicy,
onCheck: event => {
setState(
[
'signUpPolygon',
'agreeToPrivacyPolicy'
],
event.target.checked
);
},
onLinkClick: () => {
setState(
'metaMode',
story.metaModes.privacyPolicy
);
},
},
)
),
e(
POWBlock,
{
marginTop: 60,
// style: styles.loginButton,
form: 'signUpPolygonForm',
isLoadingMode: !itIsOkayToMakeASignUpRequestRightNow,
onClick: async () => {
await signUp({
isLoading,
emailInput,
passwordInput,
callback,
});
},
text: 'Sign Up'
}
)
);
};
<file_sep>import { createElement as e, useEffect, lazy, Suspense } from 'react';
import { actions } from '../../../utils';
import Box from '@material-ui/core/Box';
import TopPaper from './TopPaper';
import GamesSection from './GamesSection';
// import TwitterFeedSection from './TwitterFeedSection';
import MoreInfo from './MoreInfo';
import Footer from './Footer';
import Divider from '@material-ui/core/Divider';
import LoadingPage from '../../../TheSource/LoadingPage';
const TwitterFeedSection = lazy(() => import('./TwitterFeedSection'));
const StandardSuspense = ({ children }) => {
return e(
Suspense,
{
fallback: e( LoadingPage ),
},
children
);
};
const getStyles = () => {
return {
outerContainer: {
// backgroundColor: 'beige',
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
marginTop: 20,
},
theBottomLine: {
width: '80%',
marginTop: 12,
maxWidth: 585,
minWidth: 300,
backgroundColor: 'beige',
// marginTop: 20,
// marginBottom: 20,
},
theBottomLine2: {
width: '80%',
// marginTop: 35,
maxWidth: 585,
minWidth: 300,
backgroundColor: 'beige',
// marginTop: 20,
// marginBottom: 20,
}
};
};
export default () => {
useEffect( () => {
actions.scroll();
}, [] );
const styles = getStyles();
// const classes = getClasses();
return e(
Box,
{
style: styles.outerContainer,
// className: classes.root,
},
e( TopPaper ),
e( GamesSection ),
e(
Divider,
{
style: styles.theBottomLine,
}
),
e(
StandardSuspense,
{},
e( TwitterFeedSection )
),
e(
Divider,
{
style: styles.theBottomLine2,
}
),
e( MoreInfo ),
// e(
// Divider,
// {
// style: styles.theBottomLine2,
// }
// ),
e( Footer )
);
};
<file_sep>import { getState, setState, resetReduxX } from '../../../../reduxX';
import { bitcoinExchange, actions } from '../../../../utils';
export default async ({
amount,
choice,
voteId,
}) => {
setState( 'isLoading', true );
try {
const userId = getState( 'auth', 'userId' );
const loginToken = getState( 'auth', 'loginToken' );
await bitcoinExchange.vote({
userId,
loginToken,
amount,
voteId,
choice,
});
resetReduxX({
listOfKeysToInclude: [
[ 'presidentialVote2020', 'choiceInput' ],
[ 'presidentialVote2020', 'amountInput' ],
[ 'presidentialVote2020', 'currentAmount' ],
[ 'presidentialVote2020', 'currentChoice' ],
[ 'presidentialVote2020', 'currentVoteType' ],
[ 'presidentialVote2020', 'currentMetadata' ],
]
});
await actions.refreshUserData({ setToLoading: false });
setState( 'isLoading', false );
}
catch( error ) {
setState( 'isLoading', false );
console.log( 'the error:', error );
alert(
`error in placing bet: ${
(
!!error &&
!!error.response &&
!!error.response.data &&
!!error.response.data.message &&
error.response.data.message
) || 'internal server error'
}`
);
}
};
<file_sep>'use strict';
const { argv } = require( 'yargs' );
const mode = argv.mode || argv.m || 's';
const values = {
apiUrl: null,
exchangeApiUrl: null,
token: null,
withdrawAddress: null,
};
const getEnvKey = Object.freeze( ({
prefix,
key
}) => {
return `${ prefix }${ key }`;
});
const getEnvironmentValues = Object.freeze( ({
prefix,
}) => {
return {
apiUrl: process.env[ getEnvKey({ prefix, key: 'API_URL' }) ],
exchangeApiUrl: process.env[ getEnvKey({ prefix, key: 'EXCHANGE_API_URL' }) ],
token: process.env[ getEnvKey({ prefix, key: 'TOKEN' }) ],
withdrawAddress: process.env[ getEnvKey({ prefix, key: 'WITHDRAW_ADDRESS' }) ],
};
});
switch( mode ) {
case 's':
case 'staging':
case 'i':
case 'ireland': {
Object.assign(
values,
getEnvironmentValues({ prefix: 'IRELAND_' })
);
break;
}
case 'p':
case 'production':
case 'c':
case 'canada': {
Object.assign(
values,
getEnvironmentValues({ prefix: 'CANADA_' })
);
break;
}
default:
throw new Error( `invalid mode: ${ mode }` );
}
module.exports = Object.freeze( values );
<file_sep>'use strict';
const {
constants: {
aws: {
database: {
tableNames: { ADDRESSES },
}
},
redis: {
listIds
}
},
utils: {
aws: {
dino: {
updateDatabaseEntry,
}
},
redis: {
getClient,
doRedisRequest
},
stringify,
javascript: {
jsonEncoder: {
decodeJson
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
// const oneHundredDays = (100 * 24 * 60 * 60 * 1000);
const assignAddressToUser = Object.freeze( async ({
user,
}) => {
console.log( 'running assignAddressToUser' );
const client = getClient();
try {
const rawUnusedAddressData = await doRedisRequest({
client,
command: 'rpop',
redisArguments: [
listIds.unusedAddressData
],
});
client.quit();
if( !rawUnusedAddressData ) {
console.log(
'assignAddressToUser error: ' +
// 'assignAddressToUser executed successfully, ' +
'no fresh addresses found'// +
// 'returning null instead of an address'
);
const error = new Error(
'Bitcoin-API error: no fresh addresses. ' +
'Please try again later, we apologize for any ' +
'inconvenience. ' +
'Contact <EMAIL> for more information.'
);
error.statusCode = 500;
error.bulltrue = true;
throw error;
}
const unusedAddressData = decodeJson( rawUnusedAddressData );
if( unusedAddressData.amount > 0 ) {
// note: safeguard
console.log(
'Weird case: ' +
'assignAddressToUser - ' +
'unusedAddressData is actually used, ' +
'trying again to find another clean address. ' +
`address data ${ stringify( unusedAddressData ) } ` +
'will be disregarded'
);
return await assignAddressToUser({
user
});
}
const newAddressDatum = Object.assign(
{},
unusedAddressData,
{
userId: user.userId,
conversionDate: Date.now(),
// timeUntilReclamationAfterConversionDate: oneHundredDays,
}
);
await updateDatabaseEntry({
tableName: ADDRESSES,
entry: newAddressDatum,
});
console.log(
'assignAddressToUser executed successfully, ' +
`assigned new address: ${ newAddressDatum.address }`
);
return newAddressDatum;
}
catch( err ) {
try {
client.quit();
}
catch( redisQuitErr ) {
console.log(
'an redis quit error occurred in assignAddressToUser:',
redisQuitErr
);
}
console.log( 'an error occurred in assignAddressToUser:', err );
throw err;
}
});
module.exports = assignAddressToUser;<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
raffle: {
getChoiceTimeData,
}
} = require( '../../../../../../enchantedUtils' );
// const oneMinute = 1000 * 60;
// const fiveMinutes = oneMinute * 5;
// const oneHour = fiveMinutes * 12;
// const getNumberWhenRoundedToHourAbove = Object.freeze(({
// timestamp
// }) => {
// const timeFromHourUnder = timestamp % oneHour;
// const theHourAfterPurchase = (
// timestamp +
// (oneHour - timeFromHourUnder)
// );
// return theHourAfterPurchase;
// });
module.exports = Object.freeze( ({
mostRecentBuyTransactionCreationDate,
}) => {
console.log(
'running validateIfCancelTransactionIsAllowed: ' +
stringify({
mostRecentBuyTransactionCreationDate,
})
);
// const raffleDrawTimeAfterPurchase = getNumberWhenRoundedToHourAbove({
// timestamp: mostRecentBuyTransactionCreationDate
// });
const {
lastCancelTime
} = getChoiceTimeData({
timestamp: mostRecentBuyTransactionCreationDate
});
const thePowerOfNow = Date.now();
const itIsAlreadyPastTheLastCancelTime = thePowerOfNow > lastCancelTime;
console.log(
'making sure raffle ticket can still be cancelled: ' +
stringify({
lastCancelTime,
thePowerOfNow,
itIsAlreadyPastTheLastCancelTime,
})
);
if( itIsAlreadyPastTheLastCancelTime ) {
const error = new Error(
`Error in cancelling your lottery ticket. ` +
`It's past five minute before the next lottery draw, ` +
`it's too late to cancel your lottery ticket. ` +
'Thank you for your ticket purchase ' +
'and good luck from DynastyBitcoin.com!'
);
error.bulltrue = true;
error.statusCode = 400;
throw error;
}
console.log(
'validateIfCancelTransactionIsAllowed executed successfully'
);
});
<file_sep>'use strict';
const {
constants: {
redis: {
streamIds: {
bankStatusQueueId
}
}
},
utils: {
redis: {
getClient,
doRedisRequest
},
stringify,
server: {
getServiceNameStreamKey
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const megaServerId = process.env.ID_OF_CURRENT_MEGA_SERVER;
if( !megaServerId ) {
throw new Error(
'signalOnStatusToCommandCenter initialization error: ' +
'missing required megaServerId'
);
}
module.exports = Object.freeze( async ({
serviceName,
}) => {
if( !serviceName ) {
throw new Error( 'expected service name🐒' );
}
console.debug(
'☢️🐑running signalOnStatusToCommandCenter: ' +
stringify({ serviceName })
);
const client = getClient();
const streamKey = getServiceNameStreamKey({
serviceName,
megaServerId,
});
try {
await doRedisRequest({
client,
command: 'xadd',
redisArguments: [
bankStatusQueueId,
'MAXLEN',
'~',
2000,
'*',
'serviceNameStreamKey',
streamKey
]
});
console.debug(
'☢️🐑signalOnStatusToCommandCenter executed successfully'
);
client.quit();
}
catch( err ) {
console.log(
'🧐error in signalOnStatusToCommandCenter:',
err
);
client.quit();
throw err;
}
});
<file_sep>'use strict';
const {
utils: {
aws: {
dinoCombos: {
balances: {
updateBalance,
}
}
},
stringify,
},
constants: {
withdraws: {
states: {
pending,
}
},
users: {
balanceTypes: { normalWithdraw }
},
normalWithdraws: {
normalWithdrawsIds: {
api
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const getGetNewBalance = Object.freeze( ({
totalAmountToDeduct
}) => ({
existingBalanceData,
}) => (
(
(
!!existingBalanceData[ normalWithdraw ][ api ] &&
!!existingBalanceData[ normalWithdraw ][ api ].amount &&
existingBalanceData[ normalWithdraw ][ api ].amount
) || 0
) + totalAmountToDeduct
));
module.exports = Object.freeze( async ({
userId,
totalAmountToDeduct,
}) => {
console.log(
'running updateWithdrawBalance with the following values: ' +
stringify({
userId,
state: pending
})
);
const getNewBalance = getGetNewBalance({
totalAmountToDeduct,
});
await updateBalance({
userId,
getNewBalance,
balanceType: normalWithdraw,
balanceId: api,
state: pending,
shouldDoOperationWithLock: false
});
console.log( 'updateWithdrawBalance executed successfully' );
});<file_sep>import isValidPasswordResetCode from '../../validation/isValidPasswordResetCode';
export default ({
passwordResetCode
}) => {
const {
data
} = isValidPasswordResetCode({
passwordResetCode,
shouldThrowError: true,
});
return data;
};
<file_sep>'use strict';
const {
constants: {
redis: {
keys
}
},
utils: {
// stringify,
redis: {
getClient,
doRedisRequest
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze(async (
cacheOnAndOffStatus
) => {
console.log(
'running addCacheOnAndOffStatusToRhino with rhino pond size: ' +
cacheOnAndOffStatus.length
);
const redisClient = getClient();
try {
await doRedisRequest({
client: redisClient,
command: 'set',
redisArguments: [
keys.cacheOnAndOffStatus,
cacheOnAndOffStatus
]
});
}
catch( err ) {
console.log( 'error in adding addCacheOnAndOffStatusToRhino', err );
}
console.log( 'addCacheOnAndOffStatusToRhino executed successfully' );
redisClient.quit();
});
<file_sep>'use strict';
const crypto = require( 'crypto' );
const algorithm = 'aes-256-cbc';
const yargs = require( 'yargs' );
const isProductionMode = yargs.argv.mode === 'production';
const encryptionId = isProductionMode ? process.env.PRODUCTION_EXCHANGE_SAMANTHA_ENCRYPTION_ID : process.env.STAGING_EXCHANGE_SAMANTHA_ENCRYPTION_ID;
const encryptionPassword = isProductionMode ? process.env.PRODUCTION_EXCHANGE_SAMANTHA_ENCRYPTION_PASSWORD : process.env.STAGING_EXCHANGE_SAMANTHA_ENCRYPTION_PASSWORD;
const brickworksEncryptTag = '__bw__';
const encryptionIdToEncryptionPassword = {
[encryptionId]: encryptionPassword,
};
module.exports = Object.freeze( ({
text,
}) => {
const splitText = text.split( brickworksEncryptTag );
if( splitText.length !== 2 ) {
const errorMessage = `invalid text to decrypt: ${ text }`;
throw new Error( errorMessage );
}
const [ encryptionId, textToDecrypt ] = splitText;
const decryptPassword = encryptionIdToEncryptionPassword[ encryptionId ];
if( !decryptPassword ) {
const errorMessage = `invalid encryptionId: ${ encryptionId }`;
throw new Error( errorMessage );
}
const textParts = textToDecrypt.split(':');
const iv = Buffer.from( textParts.shift(), 'hex' );
const encryptedText = Buffer.from( textParts.join(':'), 'hex' );
const decipher = crypto.createDecipheriv(
algorithm,
Buffer.from( decryptPassword ),
iv
);
const decrypted = decipher.update( encryptedText );
const decryptedFinalForm = Buffer.concat(
[ decrypted, decipher.final() ]
);
const decryptedText = decryptedFinalForm.toString();
return decryptedText;
});
<file_sep>'use strict';
module.exports = Object.freeze({
metadata: require( './metadata' ),
addresses: require( './addresses' ),
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
updateDatabaseEntry,
}
},
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
LOGIN_TOKENS
},
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const {
loginTokens: {
getSignedOutLoginToken
}
} = require( '../../../../../exchangeUtils' );
let xoOvoDecrypt;
module.exports = Object.freeze( async ({
exchangeUserId,
hashedLoginTokenIdFromRequestHeader,
ipAddress,
signedInLoginTokens,
}) => {
console.log(
'running the deleteLogins function with the following values: ' +
stringify({
exchangeUserId,
hashedLoginTokenIdFromRequestHeader,
ipAddress,
['number of login tokens']: signedInLoginTokens.length,
})
);
if( !xoOvoDecrypt ) {
xoOvoDecrypt = require(
// '../../sacredElementals/crypto/xoOvoDecrypt'
'../../../../../sacredElementals/crypto/xoOvoDecrypt'
);
}
const rawLoginTokenToConsider = signedInLoginTokens.filter( ({
loginTokenId,
}) => {
const hashedLoginTokenIdFromDatabase = xoOvoDecrypt({
text: loginTokenId
});
return (
hashedLoginTokenIdFromRequestHeader ===
hashedLoginTokenIdFromDatabase
);
});
if( rawLoginTokenToConsider.length !== 1 ) {
// safeguard: shouldn't get here in normal operation
throw new Error(
'weird error in finding appropriate token'
);
}
const loginToken = rawLoginTokenToConsider[0];
console.log(
'deleteLogouts signing out the following token: ' +
stringify( loginToken )
);
const signedOutLoginToken = getSignedOutLoginToken({
loginToken,
ipAddress,
});
await updateDatabaseEntry({
tableName: LOGIN_TOKENS,
entry: signedOutLoginToken,
});
const deleteLoginResults = {
// loginTokens
};
console.log(
'deleteLogins executed successfully: returning results ' +
stringify( deleteLoginResults )
);
return deleteLoginResults;
});<file_sep># Bitcoin-API
[](https://badge.fury.io/js/bitcoin-api)
<a href="#">
<img
src="https://bitcoin-api.s3.amazonaws.com/images/visual_art/so-splush-bee-and-lamby-build-your-own-world-banner-25.png"
/>
</a>
<br>
## About
* Run your own highly scalable and performant Bitcoin wallet and game platform for as cheap as a few USD per month
* You own the private keys for all the users (you are the custodian🧑🎨)
## Demo Videos
* **[Withdrawing Bitcoin from Bitcoin-Api Instance Using Postman, Demo Video on Twitter](https://twitter.com/Bitcoin_Api_io/status/1294575054479654913/video/1)**
<file_sep>export default () => {
window.scroll( 0, 0 );
};
<file_sep>import * as desireElements from './desireElements';
export { desireElements };
export { default as CoinExperiencePolygon } from './CoinExperiencePolygon';
export { default as DestinyRafflePolygon } from './DestinyRafflePolygon';
export { default as SlotPolygon } from './SlotPolygon';<file_sep>import { createElement as e } from 'react';
import { getState, setState } from '../../../../reduxX';
import { WatermelonInput } from '../../../usefulComponents';
import { validation } from '../../../../utils';
export default () => {
const isLoading = getState( 'isLoading' );
const amount = getState( 'withdrawPolygon', 'amount' );
const fullWithdraw = getState( 'withdrawPolygon', 'fullWithdraw' );
const amountDisplay = String( amount );
return e(
WatermelonInput,
{
// width: '100%',
value: !!fullWithdraw ? '' : amountDisplay,
title: 'Amount to Withdraw in BTC',
borderRadius: 0,
baseComponentName: 'box',
isLoadingMode: (
isLoading ||
fullWithdraw
),
onChange: event => {
const text = event.target.value;
const amountIsValid = validation.isValidNumberTextInput({
text,
});
if( amountIsValid ) {
setState( [ 'withdrawPolygon', 'amount' ], text );
}
},
}
);
};
<file_sep>import { createElement as e } from 'react';
import Paper from '@material-ui/core/Paper';
import makeStyles from '@material-ui/core/styles/makeStyles';
import Typography from '@material-ui/core/Typography';
import Box from '@material-ui/core/Box';
import Heading from './Heading';
import HowItWorks from './HowItWorks';
import ButtonPaper from './ButtonPaper';
const getStyles = () => {
return {
outerContainer: {
backgroundColor: 'beige',
borderRadius: 4,
// backgroundColor,
maxWidth: 600,
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
upperBox: {
width: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
},
titlePaper: {
backgroundColor: 'black',
width: '100%',
paddingTop: 20,
paddingBottom: 20,
display: 'flex',
flexDirection: 'flex-start',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 5,
},
titleText: {
textAlign: 'center',
color: 'white',
fontSize: 30,
},
};
};
const getClasses = makeStyles( theme => ({
root: {
'& > *': {
margin: theme.spacing(3),
},
},
}));
export default () => {
const styles = getStyles();
const classes = getClasses();
return e(
Paper,
{
style: styles.outerContainer,
className: classes.root,
},
e(
Box,
{
style: styles.upperBox,
},
e(
Paper,
{
style: styles.titlePaper,
elevation: 5,
},
e(
Typography,
{
style: styles.titleText,
variant: 'h1'
},
'DynastyBitcoin.com'
)
),
e( Heading ),
),
e( HowItWorks ),
e( ButtonPaper )//,
// e( LegalSelection )
);
};
<file_sep>'use strict';
const stringify = require( '../../stringify' );
const Crypto = require( '../../javascript/Crypto' );
const theKeys = require( '../../theKeys' );
const getMegaCodeV3 = require( './getMegaCodeV3' );
const getTemplarCode = require( '../getTemplarCode' );
module.exports = Object.freeze( ({
encryptionId = theKeys.encryptionIdToUse
} = { encryptionId: theKeys.encryptionIdToUse }) => {
console.log(
'running getETCData with the ' +
`following encryption id: ${ encryptionId }`
);
const megaCode = getMegaCodeV3();
const templarCode = getTemplarCode({
megaCode
});
const encryptedTemplarCode = Crypto.encrypt({
text: templarCode,
encryptionId
});
console.log(
`getETCData executed successfully: ${ stringify({
['Size of Mega Code']: megaCode.length,
encryptedTemplarCode,
}) }`
);
return {
megaCode,
encryptedTemplarCode,
encryptionId
};
});<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase,
}
},
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_USERS
},
secondaryIndices: {
emailIndex
}
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const f = Object.freeze;
const attributes = f({
nameKeys: f({
email: '#email',
}),
nameValues: f({
email: 'email',
}),
valueKeys: f({
email: ':email',
}),
// valueValues: f({
// amount: 0,
// })
});
module.exports = Object.freeze( async ({
email,
}) => {
console.log(
`running getExchangeUserByEmail
with the following values - ${
stringify({
email,
})
}`
);
const {
nameKeys,
nameValues,
valueKeys
} = attributes;
const searchParams = {
TableName: EXCHANGE_USERS,
IndexName: emailIndex,
// ProjectionExpression: [
// nameKeys.email,
// ].join( ', ' ),
Limit: 5,
ScanIndexForward: false,
KeyConditionExpression: (
`${ nameKeys.email } = ${ valueKeys.email }`
),
ExpressionAttributeNames: {
[nameKeys.email]: nameValues.email,
},
ExpressionAttributeValues: {
[valueKeys.email]: email,
},
};
const exchangeUserData = (await searchDatabase({
searchParams,
})).ultimateResults;
console.log(
`getExchangeUserByEmail, got ${ exchangeUserData.length } ` +
'exchange users'
);
if( exchangeUserData.length === 0 ) {
console.log(
'getExchangeUserByEmail executed successfully, ' +
`user with email ${ email } does not exist, returning null🖖🐸`
);
return null;
}
else if( exchangeUserData.length > 1 ) {
// safeguard
throw new Error(
'getExchangeUserByEmail unexpected error - ' +
`more than 1 account has the same email: ${ email }`
);
}
const exchangeUser = exchangeUserData[0];
console.log(
'getExchangeUserByEmail executed successfully, ' +
`returning exchange user ${ stringify( exchangeUser ) }`
);
return exchangeUser;
});
<file_sep>'use strict';
const {
utils: {
aws: {
dino: {
searchDatabase,
}
},
stringify,
javascript: {
getEnvNumberValue
}
},
constants: {
environment: {
isProductionMode,
},
aws: {
database: {
tableNames: {
METADATA
},
secondaryIndex: {
typeCreationDateIndex,
}
}
},
metadata: {
types: {
raffle
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const searchLimit = isProductionMode ? getEnvNumberValue({
key: 'EXCHANGE_ENDPOINT_RAFFLES_GET_GRD_SEARCH_LIMIT',
min: 1,
max: 2000000,
shouldBeInteger: true,
defaultValue: 2
}) : 2;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
type: '#type',
// key: '#key',
// cryptoPot: '#cryptoPot',
// creationDate: '#creationDate',
// lotteryType: '#lotteryType',
// ticketCryptoPrice: '#ticketCryptoPrice',
}),
nameValues: f({
type: 'type',
// key: 'key',
// cryptoPot: 'cryptoPot',
// creationDate: 'creationDate',
// lotteryType: 'lotteryType',
// ticketCryptoPrice: 'ticketCryptoPrice',
}),
valueKeys: f({
type: ':type',
}),
valueValues: f({
type: raffle,
})
});
module.exports = Object.freeze( async ({
lastKey,
lastTime,
}) => {
console.log(
'running getRaffleFullData ' +
`with the following values - ${ stringify({
lastKey,
lastTime,
}) }`
);
// {
// "creationDate": 1602141854902,
// "cryptoPot": 0,
// "key": "raffle_1602141854902",
// "lotteryType": "twoNumber",
// "ticketCryptoPrice": 2,
// "type": "raffle"
// }
let thereAreMoreRafflesToGet = true;
const rawRaffleData = [];
let paginationValueToUse = {
lastKey,
lastTime
};
let iterationCount = 0;
while( thereAreMoreRafflesToGet ) {
iterationCount++;
console.log(
'getRaffleFullData - running search iteration with values: ' +
stringify({
iterationCount,
paginationValueToUse,
})
);
const searchParams = {
TableName: METADATA,
IndexName: typeCreationDateIndex,
ScanIndexForward: false,
// ProjectionExpression: [
// attributes.nameKeys.creationDate,
// attributes.nameKeys.cryptoPot,
// attributes.nameKeys.key,
// attributes.nameKeys.lotteryType,
// attributes.nameKeys.ticketCryptoPrice,
// ].join( ', ' ), // TODO:
Limit: searchLimit,
KeyConditionExpression: (
`${ attributes.nameKeys.type } = ` +
`${ attributes.valueKeys.type }`
),
ExpressionAttributeNames: {
[attributes.nameKeys.type]: attributes.nameValues.type,
// [attributes.nameKeys.key]: attributes.nameValues.key,
// [attributes.nameKeys.cryptoPot]: attributes.nameValues.cryptoPot,
// [attributes.nameKeys.creationDate]: attributes.nameValues.creationDate,
// [attributes.nameKeys.lotteryType]: attributes.nameValues.lotteryType,
// [attributes.nameKeys.ticketCryptoPrice]: attributes.nameValues.ticketCryptoPrice,
},
ExpressionAttributeValues: {
[attributes.valueKeys.type]: attributes.valueValues.type,
},
ExclusiveStartKey: (
!!paginationValueToUse.lastKey &&
!!paginationValueToUse.lastTime
) ? {
key: paginationValueToUse.lastKey,
creationDate: paginationValueToUse.lastTime,
type: attributes.valueValues.type,
} : undefined,
};
const {
ultimateResults,
paginationValue,
} = await searchDatabase({
searchParams,
});
const rawRaffleDataChunk = ultimateResults;
rawRaffleData.push( ...rawRaffleDataChunk );
if( !paginationValue ) {
thereAreMoreRafflesToGet = false;
if( rawRaffleData.length <= searchLimit ) {
paginationValueToUse = {
lastKey: null,
lastTime: null,
};
}
else {
rawRaffleData.length = searchLimit;
const lastRawRaffleDatum = rawRaffleData[
rawRaffleData.length - 1
];
paginationValueToUse = {
lastKey: lastRawRaffleDatum.key,
lastTime: lastRawRaffleDatum.creationDate,
};
}
}
else {
if( rawRaffleData.length <= searchLimit ) {
paginationValueToUse = {
lastKey: paginationValue.key,
lastTime: paginationValue.creationDate,
};
}
else {
thereAreMoreRafflesToGet = false;
rawRaffleData.length = searchLimit;
const lastRawRaffleDatum = rawRaffleData[
rawRaffleData.length - 1
];
paginationValueToUse = {
lastKey: lastRawRaffleDatum.key,
lastTime: lastRawRaffleDatum.creationDate,
};
}
}
}
const raffleFullData = {
rawRaffleData,
lastValues: (
!!paginationValueToUse.lastKey &&
!!paginationValueToUse.lastTime
)? {
lastKey: paginationValueToUse.lastKey,
lastTime: paginationValueToUse.lastTime,
} : {
lastKey: null,
lastTime: null,
},
};
console.log(
`getRaffleFullData, got ${ rawRaffleData.length } ` +
'raffleDatas - ' +
'Last values: ' +
stringify( raffleFullData.lastValues ) +
'getRaffleFullData executed successfully - ' +
'returning raffleFullData'
);
return raffleFullData;
});<file_sep>'use strict';
const {
getFormattedEvent,
getResponse,
handleError,
beginningDragonProtection,
stringify,
constants: {
http: {
headers
},
timeNumbers: {
hour
}
},
} = require( '../../../../../utils' );
const validateAndGetDecodedPasswordResetCode = require( './validateAndGetDecodedPasswordResetCode' );
const resetPasswordDo = require( './resetPasswordDo' );
exports.handler = Object.freeze( async rawEvent => {
try {
console.log(
'running the exchange /login/password - PATCH function'
);
const event = getFormattedEvent({
rawEvent,
});
const passwordResetCode = event.headers[ headers.passwordResetCode ];
const {
exchangeUserId,
} = validateAndGetDecodedPasswordResetCode({
passwordResetCode,
});
const {
ipAddress,
} = await beginningDragonProtection({
queueName: 'exchangeLoginPasswordPatch',
event,
megaCodeIsRequired: false,
ipAddressMaxRate: 10,
ipAddressTimeRange: hour,
altruisticCode: exchangeUserId,
altruisticCodeIsRequired: true,
altruisticCodeMaxRate: 10,
altruisticCodeTimeRange: hour,
});
const rawNewPassword = event.headers[ headers.newPassword ];
const rawGoogleCode = event.headers[ headers.grecaptchaGoogleCode ];
const resetPasswordDoResults = await resetPasswordDo({
ipAddress,
passwordResetCode,
rawNewPassword,
rawGoogleCode,
exchangeUserId,
});
const responseData = Object.assign(
{},
resetPasswordDoResults
);
console.log(
'the exchange /login/password - ' +
'PATCH function executed successfully: ' +
stringify({ responseData })
);
return getResponse({
body: responseData
});
}
catch( err ) {
console.log(
`error in exchange /login/password - PATCH function: ${ err }` );
return handleError( err );
}
});
<file_sep>import { setState, getState } from '../../../reduxX';
import {
bitcoinExchange,
grecaptcha,
actions,
throwApiStyleError,
} from '../../../utils';
import { google } from '../../../constants';
export default async () => {
const googleCode = await grecaptcha.safeGetGoogleCode({
action: google.grecapcha.actions.resetPasswordDo,
});
const passwordResetCode = getState(
'notLoggedInMode', 'passwordReset',
'passwordResetCode'
);
const {
expiryTime
} = actions.passwordReset.getDecodedPasswordResetCode({
passwordResetCode,
});
if( Date.now() > expiryTime ) {
return throwApiStyleError({
message: 'password reset link expired',
});
}
const newPassword = getState(
'notLoggedInMode',
'passwordReset',
'passwordInput'
);
const {
userId,
loginToken
} = await bitcoinExchange.resetPasswordDo({
passwordResetCode,
newPassword,
googleCode,
});
actions.login({
userId,
loginToken,
});
setState(
[
'notLoggedInMode', 'passwordReset',
'email'
],
'',
[
'notLoggedInMode', 'passwordReset',
'passwordInput'
],
'',
[
'notLoggedInMode', 'passwordReset',
'repeatPasswordInput'
],
'',
[
'notLoggedInMode', 'passwordReset',
'passwordResetCode'
],
null
);
};
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
// const {
// raffle: {
// getIfRaffleIdIsValid,
// },
// } = require( '../../../../../../enchantedUtils' );
const validateAndGetValues = require( './validateAndGetValues' );
const getDrawsData = require( './getDrawsData' );
module.exports = Object.freeze( async ({
rawRaffleId,
rawLastTime,
rawLastKey,
rawStartTime = 1,
rawEndTime = 9604340079791,
}) => {
console.log(
`running getRaffleDrawsData with the following values - ${
stringify({
rawRaffleId,
rawStartTime,
rawLastKey,
rawEndTime,
rawLastTime,
})
}`
);
const {
raffleId,
startTime,
endTime,
lastTime,
lastKey,
} = validateAndGetValues({
rawRaffleId,
rawStartTime,
rawLastKey,
rawEndTime,
rawLastTime
});
const drawsData = await getDrawsData({
raffleId,
startTime,
endTime,
lastTime,
lastKey,
});
console.log(
`getRaffleDrawsData executed successfully - returning raffle draws: ${
stringify({
'number of raffle draws': drawsData.draws.length,
'page info': drawsData.pageInfo
})
}`
);
return drawsData;
});<file_sep>'use strict';
const {
utils: {
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
transactions: {
types,
// bitcoinWithdrawTypes,
},
identityTransactions
} = require( '../../../../constants' );
module.exports = Object.freeze( ({
theOracleOfDelphiDefi,
transactionToAdd,
exchangeUser,
}) => {
console.log(
'🐐☢️🤙🧿running oracleFlashback: ' +
stringify({
theOracleOfDelphiDefi,
transactionToAdd,
})
);
if( transactionToAdd.type === types.addBitcoin ) {
const bitcoinData = (
exchangeUser &&
exchangeUser.moneyData &&
exchangeUser.moneyData.bitcoin
);
const currentAddressAmount = bitcoinData.filter(
({ address }) => ( address === transactionToAdd.address )
)[0].amount;
const amountBasedOnAddBitcoinTransaction = theOracleOfDelphiDefi[
types.addBitcoin
].addressToData[
transactionToAdd.address
].amount;
console.log(
'🐐☢️🤙🧿 oracleFlashback: ' +
'type is bitcoin add, inspecting eUser bitcoinData:' +
stringify({
['🐸exchange user Bitcoin data']: bitcoinData,
[`💰current amount for address "${ transactionToAdd.address }"`]: currentAddressAmount,
['📝Amount based on add BTC tx']: amountBasedOnAddBitcoinTransaction,
})
);
if(
currentAddressAmount ===
amountBasedOnAddBitcoinTransaction
) {
console.log(
'🐐☢️🤙🧿oracleFlashback executed successfully: ' +
'the current amount === add BTC transaction amount ' +
'SHOULD NOT perform database writes❌😳'
);
return {
shouldPerformDatabaseWrites: false
};
}
}
else if(
(transactionToAdd.type === types.identity) &&
(
transactionToAdd.identityType !==
identityTransactions.types.refresh
)
) {
console.log(
'🐐☢️🤙🧿oracleFlashback executed successfully: ' +
`should NOT perform database writes, it's an identity tx ` +
`of identity type ${ transactionToAdd.identityType }`
);
return {
shouldPerformDatabaseWrites: false
};
}
console.log(
'🐐☢️🤙🧿oracleFlashback executed successfully: ' +
'should perform database writes✅😎'
);
return {
shouldPerformDatabaseWrites: true
};
});
<file_sep>'use strict';
const {
utils: {
delay,
javascript: {
getIfEnvValuesAreValid
}
},
// constants: {
// redis: {
// streamIds
// }
// }
} = require( '@bitcoin-api/full-stack-api-private' );
const {
listenForEventsAndExecuteActions,
sendErrorToDeployStreamOnControlC
} = require( '@bitcoin-api/giraffe-utils' );
const waitUntilGiraffeLicksLeaf = require( './waitUntilGiraffeLicksLeaf' );
const getDoPostInitializationAction = require( './getDoPostInitializationAction' );
const getPerformActionBasedOnDeployEvent = require( './getPerformActionBasedOnDeployEvent' );
const oneSecond = 1000;
const fiveSeconds = 5 * oneSecond;
getIfEnvValuesAreValid([
{
type: getIfEnvValuesAreValid.envValidationTypes.string,
key: 'TREE_TIGER_HOME'
},
{
type: getIfEnvValuesAreValid.envValidationTypes.string,
key: 'REDIS_URL'
}
]);
const provideWaterToTreeForever = Object.freeze( async () => {
console.log( 'running provideWaterToTreeForever🌲' );
const {
deployId,
operationExpiry,
deployCommand,
forceDeploy
} = await waitUntilGiraffeLicksLeaf();
const doPostInitializationAction = getDoPostInitializationAction({
deployId,
deployCommand
});
const performActionBasedOnDeployEvent = getPerformActionBasedOnDeployEvent({
forceDeploy
});
const {
anErrorOccurred
} = await listenForEventsAndExecuteActions({
deployId,
operationExpiry,
isGiraffe: '🌴',
performActionBasedOnDeployEvent,
doPostInitializationAction,
});
console.log(
'provideWaterToTreeForever executed successfully🎄' +
`running again in ${ fiveSeconds / oneSecond } seconds - ` +
`
💦provide water results🌴:
an error occurred: ${ anErrorOccurred ? 'yes': 'no' }
`
);
await delay( fiveSeconds );
return await provideWaterToTreeForever();
});
module.exports = Object.freeze( async () => {
console.log( '💦running provide water to tree🌲' );
sendErrorToDeployStreamOnControlC({
isGiraffe: '🌴'
});
try {
await provideWaterToTreeForever();
}
catch( err ) {
console.log(
'⛔️💦☹️error in providing water to tree🌲:', err,
`running again in ${ fiveSeconds / oneSecond } seconds`
);
await delay( fiveSeconds );
return await provideWaterToTreeForever();
}
});
<file_sep>'use strict';
const { DO_NOT_SHOW_REAL_ERRORS } = process.env;
// const defaultErrorName = 'InternalServerError';
const defaultErrorMessage = 'Internal Server Error';
const defaultErrorStatusCode = 500;
const getErrorObject = Object.freeze(({
// name,
statusCode,
message,
}) => {
// if( IS_EXCHANGE ) {
return {
statusCode,
body: JSON.stringify({
statusCode,
message,
})
};
// }
// return {
// isError: true,
// // name,
// statusCode,
// message,
// };
});
module.exports = Object.freeze( err => {
err = err || {};
console.log( 'utils.handleError: the following error has occurred:', err );
if( DO_NOT_SHOW_REAL_ERRORS && !err.bulltrue ) {
return getErrorObject({
statusCode: defaultErrorStatusCode,
message: defaultErrorMessage,
});
}
const statusCode = (!!err && err.statusCode) || defaultErrorStatusCode;
const message = (!!err && err.message) || defaultErrorMessage;
return getErrorObject({
// name: err.name || defaultErrorName,
statusCode,
message,
});
});<file_sep>import ReduxX, { v } from 'react-state-management';
import {
mainStyles,
mainStyleToMainStyleObject,
story,
games,
gameData
// story
} from './constants';
const initialMainStyleObject = mainStyleToMainStyleObject[ mainStyles.dark ];
export const {
setUpReduxX,
setState,
getState,
/* Optional Exports: */
resetReduxX,
// getGlobalUseState,
// oldeFashionedStateManagement,
} = ReduxX({
initialState: {
mainStyleObject: v( initialMainStyleObject ),
// metaMode: v( story.metaModes.zeroPointEnergy ),
metaMode: v( null ),
// metaMode: v( 'termsOfService' ),
// metaMode: v( 'verifyUserMode' ),
dialogMode: v( story.dialogModes.none ),
// dialogMode: v( story.dialogModes.faq ),
// dialogMode: v( story.dialogModes.withdraws ),
// dialogMode: v( story.dialogModes.depositsBastion ),
// dialogMode: v( story.dialogModes.games.aboutCoinFlip ),
// dialogMode: v( story.dialogModes.games.aboutDestinyRaffle ),
// dialogMode: v( story.dialogModes.viewTransactions ),
// isLoading: v( false ),
// isLoading: v( false ),
isLoading: v( false ),
windowWidth: v( window.innerWidth ),
auth: {
userId: v( null ),
loginToken: v( null ),
// userId: v( 'exchange_user_8027206ba0724b97a17a8e1870b907b8' ),
// loginToken: v( 'login_token-13fa669da4c0494892d86021f781ed31cdc7d739d975437cac430ee12f6310959e6b8681c62848408413fe72e96229e6' ),
},
signUpPolygon: {
emailInput: v( '' ),
passwordInput: v( '' ),
reTypePasswordInput: v( '' ),
agreeToTermsOfService: v( false ),
agreeToPrivacyPolicy: v( false ),
// emailInput: v( '<EMAIL>' ),
// passwordInput: v( '<PASSWORD>' ),
// reTypePasswordInput: v( '<PASSWORD>' ),
// agreeToTermsOfService: v( true ),
// agreeToPrivacyPolicy: v( true ),
},
verifyEmailPolygon: {
emailInput: v( '' ),
passwordInput: v( '' ),
// passwordInput: v( '<PASSWORD>' ),
verifyEmailCodeInput: v( '' ),
// verifyEmailCodeInput: v( '2321231231232132121' ),
},
loginPolygon: {
// emailInput: v( '' ),
// emailInput: v( '<EMAIL>' ),
emailInput: v( '' ),
passwordInput: v( '' ),
// passwordInput: v( '<PASSWORD>' ),
},
getUserPolygon: {
userIdInput: v( '' ),
loginTokenInput: v( '' ),
},
withdrawPolygon: {
amount: v( '0' ),
address: v( '' ),
fee: v( '0' ),
fullWithdraw: v( false ),
},
exchangePolygon: {
amountWantedInCryptos: v( '' ),
amountWantedInBitcoin: v( '' ),
},
transactionsPolygon: {
moneyActions: v( null ),
lastTransactionId: v( null ),
lastTime: v( null ),
// lastTransactionId: v( 'xyz_abc' ),
// lastTime: v( 34312438726 ),
},
forgotMyPasswordPolygon: {
emailInput: v( '' ),
// emailInput: v( '<EMAIL>' ),
successEmail: v( null ),
// successEmail: v( '<EMAIL>' ),
},
notLoggedInMode: {
// mainMode: v( null ),
mainMode: v( story.NotLoggedInMode.mainModes.initialChoiceMode ),
// mainMode: v( 'afterSignUpMode' )
// mainMode: v( 'signUpMode' ),
// mainMode: v( story.NotLoggedInMode.mainModes.loginMode ),
// mainMode: v( story.NotLoggedInMode.mainModes.forgotMyPasswordMode ),
// mainMode: v( story.NotLoggedInMode.mainModes.passwordResetMode ),
// mainMode: v( story.NotLoggedInMode.mainModes.verifyUserMode ),
freeGame: v( null ),
// freeGame: v( 'theDragonsTalisman' ),
// freeGame: v( 'destinyRaffle' ),
freeGameModeBalance: v( 0.07 ),
// freeGameModeBalance: v( 55555.55555 ),
coinFlip: {
selectedAmount: v( '0.0003' ),
},
passwordReset: {
passwordInput: v( '' ),
repeatPasswordInput: v( '' ),
email: v( '' ),
passwordResetCode: v( null ),
// email: v( '<EMAIL>' ),
// passwordInput: v( '<PASSWORD>' ),
// repeatPasswordInput: v( '<PASSWORD>' ),
// passwordResetCode: v( 'prc-exchange_user_fake_eu90-kdasdhkasj-99999999999999' ),
},
},
loggedInMode: {
userData: v( null ),
mode: v( story.LoggedInMode.modes.base ),
// mode: v( story.LoggedInMode.modes.exchange ),
// mode: v( story.LoggedInMode.modes.vote ),
// mode: v( story.LoggedInMode.modes.withdraw ),
// mode: v( story.LoggedInMode.modes.coinFlip ),
// mode: v( story.LoggedInMode.modes.destinyRaffle ),
drawerIsOpen: v( false ),
coinFlip: {
selectedAmount: v( '0.0003' ),
mode: v(
gameData[ games.theDragonsTalisman ].modes.jackpot
),
jackpotAmount: v( null ),
// jackpotAmount: v( 69123.12345 ),
startedGettingJackpotDataForFirstTime: v( false ),
hasGottenJackpotDataForFirstTime: v( false ),
},
slot: {
slotNumber1: v( 1 ),
slotNumber2: v( 2 ),
slotNumber3: v( 3 ),
slotNumberImageIndices: v([
0,
1,
2,
])
}
},
ultraTools: {
fastMessageData: v( null ),
// fastMessageData: v({
// message: 'this is the mega test message for monkeys and for people but for monkeys.🙊',
// timeout: 20000,
// noX: true
// }),
// fastMessageData: v({
// message: (
// `To login, please check your email: ${ 'test' } ` +
// 'for a verification code link. Thank you!'
// ),
// // timeout: 999999,
// timeout: 5000,
// noX: true
// })
},
// coinExperiencePolygon: {
// amount: v( 0 ),
// },
destinyRaffle: {
loadError: v( null ),
data: v( null ),
selectedNumberOne: v( '' ),
selectedNumberTwo: v( '' ),
raffleIdToDrawData: v( {} ),
raffleIdToTicketData: v( {} ),
lastKey: v( null ),
lastTime: v( null ),
ownSpecialId: v( null ),
},
presidentialVote2020: {
// choice: v( 'trump' ),
localError: v( null ),
choiceInput: v( null ),
amountInput: v( '0' ),
currentAmount: v( null ),
currentChoice: v( null ),
currentVoteType: v( null ),
currentMetadata: v( {} ),
}
}
});<file_sep>'use strict';
const uuidv4 = require( 'uuid/v4' );
module.exports = Object.freeze( () => {
console.log( 'running getUserId' );
const userId = uuidv4().split('-').join('');
console.log( 'getUserId executed successfully, returning id:', userId );
return userId;
});<file_sep>'use strict';
// const argv = require( 'yargs' ).argv;
const fs = require( 'fs' );
const util = require( 'util' );
const writeFile = util.promisify( fs.writeFile );
const {
utils: {
stringify,
},
// constants: {
// aws: { database: { tableNames: { BALANCES, WITHDRAWS } } }
// }
} = require( '@bitcoin-api/full-stack-api-private' );
const getBalanceData = require( process.env.GET_BALANCE_DATA_PATH );
module.exports = Object.freeze( async ({
allItems,
}) => {
console.log(
'running writeStandardReport with the following values:',
stringify({
numberOfItems: allItems.length,
})
);
allItems.sort( ( itemA, itemB ) => {
return itemB.lastUpdated - itemA.lastUpdated;
});
const standardReport = stringify({
standardReport: {
numberOfItems: allItems.length,
itemData: allItems.map( exchangeUser => {
const balanceData = getBalanceData({
exchangeUser
});
return {
email: exchangeUser.email,
exchangeUserId: exchangeUser.exchangeUserId,
transactionCount: exchangeUser.transactionCount,
lastUpdated: exchangeUser.lastUpdated,
lastUpdatedCool: (new Date( exchangeUser.lastUpdated )).toLocaleString(),
'Bitcoin Balance ': balanceData.summary.bitcoin.totalAmount,
'Crypto Balance': balanceData.summary.crypto.totalAmount,
'Total BTC Balance': (
Math.round(
(
balanceData.summary.bitcoin.totalAmount +
(balanceData.summary.crypto.totalAmount/1000)
) * 100000000 ) / 100000000
).toFixed(8),
};
})
}
});
writeFile(
`${ __dirname }/standardReport.json`,
standardReport
);
console.log(
'writeStandardReport executed successfully'
);
});
<file_sep>'use strict';
const crypto = require( 'crypto' );
module.exports = Object.freeze( value => {
const hashedValue = crypto.createHash(
'md5'
).update(
value
).digest( 'hex' );
return hashedValue;
});<file_sep>'use strict';
const {
utils: {
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
exchangeUsers: {
getIfExchangeUserExists
}
} = require( '../../../../../exchangeUtils' );
module.exports = Object.freeze( async ({
email,
}) => {
console.log(
`running ensureUserDoesNotExist
with the following values - ${
stringify({
email,
})
}`
);
const exchangeUserExists = await getIfExchangeUserExists({
email
});
if( exchangeUserExists ) {
const error = new Error(
`user with email ${ email } already exists`
);
error.statusCode = 409;
error.bulltrue = true;
throw error;
}
console.log(
'ensureUserDoesNotExist executed successfully, ' +
`user with email ${ email } does not already exist🖖🐸`
);
});
<file_sep>'use strict';
require( 'dotenv' ).config();
const express = require( 'express' );
const cors = require( 'cors' );
const data = require( './data' );
const app = express();
const port = process.env.PORT;
app.use( cors() );
app.use( express.json() );
const stringify = message => JSON.stringify( message, null, 4 );
const toFixedConstant = 5;
const amountMultiplier = 100000;
const getCryptoAmountNumber = Object.freeze( amount => {
const cryptoAmount = Number(
(
Math.round(
Number(amount) * amountMultiplier
) / amountMultiplier
).toFixed( toFixedConstant )
);
return cryptoAmount;
});
app.get( '/', ( req, res, next ) => {
// const error = new Error( 'testError' );
// error.statusCode = 420;
// next( error );
res.send({ test: '123' });
});
app.post( '/login', ( req, res, next ) => {
console.log(
'request to /login - POST with the following value:',
stringify({
body: req.body,
})
);
res.send({
loginToken: '<PASSWORD>-token',
userId: 'exchange_user_fake_user_id_123'
});
});
app.post( '/login/password', ( req, res, next ) => {
console.log(
'request to /login/password - POST with the following value:',
stringify({
headers: req.headers,
body: req.body,
})
);
res.send({
passwordResetHasBeenSuccessfullyInitialized: true,
});
});
app.patch( '/login/password', ( req, res, next ) => {
console.log(
'request to /login/password - PATCH with the following value:',
stringify({
headers: req.headers,
body: req.body,
})
);
res.send({
loginToken: 'fake-exchange-user-login-token',
userId: 'exchange_user_fake_user_id_123'
});
});
app.post( '/logout', ( req, res, next ) => {
console.log(
'request to /logout - POST with the following value:',
stringify({
body: req.body,
})
);
res.send({});
});
app.post( '/exchange-users', ( req, res, next ) => {
console.log(
'request to /exchange-users - POST with the following value:',
stringify({
body: req.body,
})
);
res.send({});
});
app.get( '/exchange-users/:exchangeUserId', ( req, res, next ) => {
console.log(
'request to /exchange-users/:exchange-user-id - GET with the following value:',
stringify({
param: req.params,
headerUserId: req.headers[ 'user-id' ],
headerLoginToken: req.headers[ 'login-token' ],
})
);
res.send({
userId: 'exchange_user_fake_user_id_123',
email: '<EMAIL>',
balanceData: {
bitcoin: {
totalAmount: 6.9,
depositAddress: null,
// depositAddress: 'bc1qkqjlhde0uhl37wyvmnwwwpkn6eych5xndc7hsh',
},
bitcoinWithdraws: {
totalAmount: 2,
currentState: 'test state',
},
crypto: {
totalAmount: 0,
},
exchange: {
bitcoin: {
totalAmount: 42.0,
},
crypto: {
totalAmount: 420,
},
},
vote: {
crypto: {
totalAmount: 100,
},
},
summary: {
bitcoin: {
totalAmount: 5
},
crypto: {
totalAmount: 3
},
}
},
});
});
app.post( '/verify-user', ( req, res, next ) => {
console.log(
'request to /verify-user - POST with the following value:',
stringify({
body: req.body,
})
);
res.send({
loginToken: '<PASSWORD>',
userId: 'exchange_user_fake_user_id_123'
});
});
app.post( '/addresses', ( req, res, next ) => {
console.log(
'request to /addresses - POST with the following value:',
stringify({
headers: req.headers,
body: req.body,
})
);
res.send({
addressPostOperationSuccessful: true,
});
});
app.post( '/votes/:voteId', ( req, res, next ) => {
console.log(
'request to /votes - POST with the following value:',
stringify({
body: req.body,
voteId: req.params.voteId,
})
);
res.send({});
});
app.get( '/votes/:voteId', ( req, res, next ) => {
console.log(
'request to /votes/:voteId - GET with the following value:',
stringify({
voteId: req.params.voteId,
})
);
// res.send({
// "choice": null,
// "voteType": null,
// "amount": 0,
// "metadata": {
// "time": 1600611813756
// }
// });
res.send({
"choice": 'trump',
"voteType": "doVote",
"amount": 0.2,
"metadata": {
"time": 1600611813756
}
});
// res.send({
// "choice": null,
// "voteType": "payout",
// "amount": 0.5,
// "metadata": {
// "time": 1600611813756,
// "resultAmount": 3.5,
// "resultChoice": 'trump'
// }
// });
// res.send({
// "choice": null,
// "voteType": "payout",
// "amount": 0.5,
// "metadata": {
// "time": 1600611813756,
// "resultAmount": 0,
// "resultChoice": 'biden'
// }
// });
});
let dreamsWin = false;
app.post( '/dreams', ( req, res, next ) => {
dreamsWin = !dreamsWin;
console.log(
'request to /dreams - POST with the following value:',
stringify({
body: req.body,
voteId: req.params.voteId,
}),
'returning win result:',
dreamsWin
);
res.send({
happyDream: dreamsWin,
});
});
app.post( '/dreams-lotus', ( req, res, next ) => {
dreamsWin = !dreamsWin;
console.log(
'request to /dreams-lotus - POST with the following values:',
stringify({
body: req.body,
}),
'returning win result:',
dreamsWin
);
res.send({
happyDream: dreamsWin,
});
});
app.post( '/dreams-slot', ( req, res, next ) => {
dreamsWin = !dreamsWin;
console.log(
'request to /dreams-slot - POST with the following values:',
stringify({
body: req.body,
}),
'returning win result:',
dreamsWin
);
res.send({
happyDream: dreamsWin,
hasTied: false,
resultValues: {
slotNumbers: [
1,
2,
3
]
}
});
});
let lotusDreamsJackpotAmount = 0;
app.get( '/dreams-lotus', ( req, res, next ) => {
lotusDreamsJackpotAmount += 0.00008;
console.log(
'request to /dreams-lotus - GET with the following values:',
stringify({}),
'returning lotus dreams jackpot data:',
lotusDreamsJackpotAmount
);
res.send({
jackpotAmount: getCryptoAmountNumber( lotusDreamsJackpotAmount ),
});
});
app.get( '/raffles', ( req, res, next ) => {
console.log(
'request to /raffles - GET with the following values:',
stringify({
query: req.query,
}),
);
if( !!req.query.lastTime && !!req.query.lastKey ) {
const responseData = {
"raffleData": [
{
"raffleId": "raffle_1602141854902",
"cryptoPot": 28,
"raffleStartTime": 1602141854902,
"raffleType": "twoNumber",
"ticketCryptoPrice": 2,
raffleNumber: 1,
winRaffleDrawId: 'raffle_draw_210dsds-23vdvd222_21039123021',
winHour: 1603857600000,
previousRaffleEndHour: 1603774800000,
'winChoice': '3-36',
numberOfWinners: 2,
houseCut: 0.1,
winCryptoPayout: 11.2,
"choices": [
{
"choice": "1-36",
"amount": -2,
lastCancelTime: Date.now() + (1000 * 60 * 60),
},
{
"choice": "2-36",
"amount": -2,
lastCancelTime: Date.now() + (1000 * 60 * 60),
},
{
"choice": "3-36",
"amount": -2,
lastCancelTime: Date.now() - (1000 * 60 * 60),
},
{
"choice": "4-36",
"amount": -2,
lastCancelTime: Date.now() - (1000 * 60 * 60),
},
{
"choice": "5-36",
"amount": -2,
lastCancelTime: Date.now() - (1000 * 60 * 60),
}
],
"winData": {
"hasWon": true,
"amount": 11.2
},
},
],
lastValues: {
lastKey: null,
lastTime: null,
}
};
console.log(
'request to /raffles - GET with the following value:',
stringify({
query: req.query
}),
'returning raffle data:',
stringify({
responseData
}),
);
res.send( responseData );
return;
}
const responseData = {
"raffleData": [
{
"raffleId": "raffle_c16ffeef-c677-4b0d-b335-bd8960ed1597_1603860480457",
raffleNumber: 2,
"cryptoPot": 0,
"raffleStartTime": 1603860480457,
previousRaffleEndHour: 1603857600000,
houseCut: 0.1,
"raffleType": "twoNumber",
"ticketCryptoPrice": 2,
"choices": [],
"winData": {
"hasWon": false,
"amount": 0
}
},
],
lastValues: {
lastKey: 'raffle_1602141854902',
lastTime: 69696969,
}
};
console.log(
'request to /raffles - GET with the following value:',
stringify({
query: req.query
}),
'returning raffle data:',
stringify({
responseData
}),
);
res.send( responseData );
});
app.get( '/raffle-draws/:raffleId', ( req, res, next ) => {
console.log(
'request to /raffle-draws/:raffleId - GET with the following value:',
stringify({
// body: req.body,
raffleId: req.params.raffleId,
query: req.query,
}),
);
const m = !req.query.lastTime ? 0 : 9;
const results = {
draws: [
{
"time": 1604124000000 - ((1 + m) * 1000 * 60 * 60),
"choice": `${ (1 + m) }-36`,
"win": true
},
{
"time": 1604124000000 - ((2 + m) * 1000 * 60 * 60),
"choice": `${ (2 + m) }-36`,
},
{
"time": 1604124000000 - ((3 + m) * 1000 * 60 * 60),
"choice": `${ (3 + m) }-36`,
},
{
"time": 1604124000000 - ((4 + m) * 1000 * 60 * 60),
"choice": `${ (4 + m) }-36`,
},
{
"time": 1604124000000 - ((5 + m) * 1000 * 60 * 60),
"choice": `${ (5 + m) }-36`,
},
{
"time": 1604124000000 - ((6 + m) * 1000 * 60 * 60),
"choice": `${ (6 + m) }-36`,
},
{
"time": 1604124000000 - ((7 + m) * 1000 * 60 * 60),
"choice": `${ (7 + m) }-36`,
},
{
"time": 1604124000000 - ((8 + m) * 1000 * 60 * 60),
"choice": `${ (8 + m) }-36`,
},
],
"pageInfo": (m === 0) ? {
"lastTime": 1604125263055
} : null
};
if(
(m === 0) // || true
) {
results.draws.push({
"time": 1604124000000 - ((9 + m) * 1000 * 60 * 60),
"choice": `${ (9 + m) }-36`,
});
}
res.send( results );
});
app.get( '/raffle-tickets/:raffleId', ( req, res, next ) => {
console.log(
'request to /raffle-tickets/:raffleId - GET with the following value:',
stringify({
// body: req.body,
raffleId: req.params.raffleId,
query: req.query,
}),
);
const noQsValuesAreProvided = !(
!!req.query.time &&
!!req.query.powerId &&
!!req.query.specialId
);
const results = {
tickets: noQsValuesAreProvided ? [
{
"choice": "1-36",
"time": 1,
"specialId": "exchange_user_abce12",
"action": "buy"
},
{
"choice": "2-36",
"time": 2,
"specialId": "exchange_user_abce12",
"action": "buy"
},
{
"choice": "3-36",
"time": 3,
"specialId": "exchange_user_bf967",
"action": "buy"
}
] : [
{
"choice": "1-36",
"time": 4,
"specialId": "exchange_user_ce420",
"action": "buy"
},
{
"choice": "2-36",
"time": 5,
"specialId": "exchange_user_abce12",
"action": "cancel"
},
{
"choice": "3-36",
"time": 6,
"specialId": "exchange_user_ce420",
"action": "buy"
},
{
"choice": "3-36",
"time": 7,
"specialId": "exchange_user_ce420",
"action": "cancel"
},
{
"choice": "3-36",
"time": 8,
"specialId": "exchange_user_ce420",
"action": "buy"
},
{
"choice": "4-36",
"time": 9,
"specialId": "exchange_user_ce420",
"action": "buy"
}
],
"pageInfo": noQsValuesAreProvided ? {
"time": 3,
"powerId": "2xxx_323322",
"specialId": "exchange_user_6"
} : null
};
res.send( results );
});
app.get( '/fee-data', ( req, res, next ) => {
console.log(
'request to /fee-data - GET with the following value:',
stringify({
// body: req.body,
raffleId: req.params.raffleId,
query: req.query,
}),
);
res.send({
fee: 0.00005
});
});
app.get( '/transactions', ( req, res, next ) => {
console.log(
'request to /transactions - GET with the following value:',
stringify({
// body: req.body,
raffleId: req.params.raffleId,
query: req.query,
}),
);
if( !!req.query.lastTime && !!req.query.lastTransactionId ) {
console.log(
'request to /transactions - GET second POWER-API-Attack!!!'
);
return res.send({
moneyActions: data.moneyActions.secondBatchOfMoneyActions,
lastTransactionId: null,
lastTime: null,
});
}
res.send({
moneyActions: data.moneyActions.firstBatchOfMoneyActions,
lastTransactionId: 'fake_slash_transactions_transactions_id',
lastTime: 123456789,
});
});
app.listen( port, err => {
if( err ) {
console.log( 'an error occurred in listening:', err );
return;
}
console.log( `Example app listening at http://localhost:${port}` );
});
<file_sep>import { createElement as e, useEffect } from 'react';
import { getState, setState } from '../../reduxX';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
//
const getStyles = ({
marginTop,
marginBottom,
}) => {
return {
outerContainer: {
position: 'fixed',
bottom: 0,
backgroundColor: 'beige',
marginTop,
marginBottom,
width: 300,
// height: 100,
borderRadius: 4,
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
topBar: {
// backgroundColor: 'green',
// marginTop: 5,
// marginBottom: 5,
// width: '15%',
height: '100%',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
exitCircle: {
backgroundColor: 'teal',
// marginTop: 5,
// marginBottom: 5,
width: 30,
height: 30,
borderRadius: '50%',
marginRight: 7,
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
},
xText: {
color: 'white',
textAlign: 'center',
},
textBox: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'teal',
borderRadius: 4,
// height: 100,
margin: 5,
wordBreak: 'break-word'
},
text: {
textAlign: 'center',
color: 'white',
fontSize: 20,
margin: 9,
}
};
};
export default ({
marginTop = 0,
marginBottom = 0,
} = {
marginTop: 0,
marginBottom: 0,
}) => {
const fastMessageData = getState( 'ultraTools', 'fastMessageData' );
useEffect( () => {
if( !!fastMessageData && !!fastMessageData.timeout ) {
setTimeout( () => {
setState({
keys: [ 'ultraTools', 'fastMessageData' ],
value: null
});
}, fastMessageData.timeout );
}
}, [ fastMessageData ] );
const styles = getStyles({
marginTop,
marginBottom,
});
// const fastMessageData = getState( 'ultraTools', 'fastMessageData' );
if( !fastMessageData ) {
return null;
}
return e(
Paper,
{
style: styles.outerContainer,
},
e(
Paper,
{
style: styles.textBox,
},
e(
Typography,
{
style: styles.text,
},
fastMessageData.message
)
),
!fastMessageData.noX && e(
'div',
{
style: styles.topBar,
},
e(
'div',
{
style: styles.exitCircle,
onClick: () => {
setState({
keys: [ 'ultraTools', 'fastMessageData' ],
value: null
});
},
},
e(
'div',
{
style: styles.xText,
},
'X'
)
)
)
);
};
<file_sep>'use strict';
const {
utils: {
redis: {
rhinoCombos: {
giraffeAndTreeStatusUpdate
},
doRedisFunction,
getClient,
doRedisRequest,
streams
},
javascript: {
jsonEncoder
},
stringify
},
} = require( '@bitcoin-api/full-stack-api-private' );
const getTimeInfo = require( './getTimeInfo' );
const {
eventNames,
// publishSubscribeChannels,
// errorListenerMessages,
streamIds
} = require( './constants' );
const theNameOfTheFinalEvent = eventNames.leaf.serviceIsGood;
const handleError = Object.freeze( async ({
err,
isGiraffe,
otherData
}) => {
console.log(
'listenForEventsAndExecuteActionsCore.handleError - ' +
'running handleError with the following values: ' +
stringify({
err,
isGiraffe,
otherData
})
);
const redisClient = getClient();
try {
await giraffeAndTreeStatusUpdate({
redisClient,
eventName: eventNames.common.error,
information: {
errorMessage: (
err.message || 'listenForEventsAndExecuteActions error'
),
isGiraffe: (isGiraffe === '🦒'),
otherData
}
});
redisClient.quit();
console.log(
(
'listenForEventsAndExecuteActionsCore.handleError -'
),
err
);
}
catch( innerErr ) {
redisClient.quit();
console.log(
'listenForEventsAndExecuteActionsCore - ' +
'error with the following values: ' +
stringify({
err,
isGiraffe,
otherData
})
);
}
});
const listenForEventsAndExecuteActionsCore = Object.freeze( async ({
operationStartTimeKey = `${ Date.now() }-0`,
deployId,
isGiraffe = '🦒',
redisClient,
operationExpiry,
performActionBasedOnDeployEvent,
doPostInitializationAction = null,
}) => {
const operationExpiryTimeString = (
new Date( operationExpiry )
).toTimeString();
console.log(
'🤠',
'running listenForEventsAndExecuteActions with the following values:',
stringify({
deployId,
isGiraffe,
operationStartTimeKey,
currentTime: ( new Date() ).toTimeString(),
operationExpiry: operationExpiryTimeString,
}),
'🤠'
);
let { timeUntilExpiry, thereIsTimeBeforeExpiry } = getTimeInfo({
operationExpiry
});
let theFinalActionHasNotBeenPerformedYet = true;
let listenStartTimeKey = operationStartTimeKey;
let thePostInitializationActionHasStarted = false;
let currentEventOrderNumber = 0;
while(
thereIsTimeBeforeExpiry &&
theFinalActionHasNotBeenPerformedYet
) {
console.log(
'listenForEventsAndExecuteActions - listening for events:',
stringify({
['seconds until expiry']: timeUntilExpiry/1000,
['listen start time']: (
new Date( streams.getOperationTime({
operationTimeKey: listenStartTimeKey,
}) )
).toTimeString(),
['operation expiry time']: operationExpiryTimeString
})
);
const [ deployEventRawDataResults ] = await Promise.all([
doRedisRequest({
client: redisClient,
command: 'xread',
redisArguments: [
'BLOCK',
timeUntilExpiry,
'STREAMS',
streamIds.zarbonDeploy,
listenStartTimeKey
],
}),
(async () => {
if(
!!doPostInitializationAction &&
!thePostInitializationActionHasStarted
) {
thePostInitializationActionHasStarted = true;
try {
console.log(
'listenForEventsAndExecuteActions - ' +
'running doPostInitializationAction'
);
await doPostInitializationAction();
console.log(
'listenForEventsAndExecuteActions - ' +
'doPostInitializationAction executed ' +
'successfully'
);
}
catch( err ) {
console.log(
'listenForEventsAndExecuteActions -',
'error in doPostInitializationAction:',
err ,
'handling error'
);
await handleError({
err,
isGiraffe,
otherData: {
errorInfo: 'doPostInitializationAction error',
errorMessage: err.message
}
});
return;
}
}
})()
]);
const deployEventRawData = (
!!deployEventRawDataResults &&
!!deployEventRawDataResults[0] &&
!!deployEventRawDataResults[0][1] &&
deployEventRawDataResults[0][1]
) || [];
const deployEventData = deployEventRawData.map( entry => {
return {
timeKey: entry[0],
keyValues: streams.getKeyValues({
keyValueList: entry[1],
}),
};
});
console.log(
'listenForEventsAndExecuteActions - got deploy event data:',
stringify({
deployEventDataLength: deployEventData.length
})
);
for( const deployEventDatum of deployEventData ) {
const {
// timeKey,
keyValues,
} = deployEventDatum;
const eventName = keyValues.eventName;
const information = jsonEncoder.decodeJson(
keyValues.information
);
try {
console.log(
(
'listenForEventsAndExecuteActions - ' +
'performing action based on the following data:'
),
stringify({
isGiraffe,
eventName,
information
})
);
if( eventName === eventNames.common.error ) {
const results = {
anErrorOccurred: true
};
console.log(
'listenForEventsAndExecuteActions - ' +
'executed successfully (not >=100% like 🦍🐒vs🐊) ' +
'is error event - returning results ' +
`${ stringify( results ) }`
);
return results;
}
const eventHasInvalidDeployId = (
information.deployId !== deployId
);
const eventIsNotInTheExpectedOrder =(
information.eventOrder !== (currentEventOrderNumber + 1)
);
if(
eventHasInvalidDeployId ||
eventIsNotInTheExpectedOrder
) {
console.log( `unexpected event: ${
JSON.stringify({
information,
eventHasInvalidDeployId,
eventIsNotInTheExpectedOrder
})
}` );
const results = {
anErrorOccurred: true,
};
console.log(
'🤠listenForEventsAndExecuteActions - ' +
'executed successfully - is error event🐊🤠 - ' +
'returning results - ' +
stringify( results )
);
return results;
}
currentEventOrderNumber++;
await performActionBasedOnDeployEvent({
isGiraffe,
eventName,
information
});
}
catch( err ) {
console.log(
'listenForEventsAndExecuteActions -',
'an error occurred:',
err,
'handling error'
);
await handleError({
err,
isGiraffe,
otherData: {
eventName,
information
},
});
const results = {
anErrorOccurred: true,
};
console.log(
'🤠listenForEventsAndExecuteActions - ' +
'executed successfully ' +
'(an error occurred in processing an event🐊) - ' +
`returning results - ${ stringify( results ) }`
);
return results;
}
if( eventName === theNameOfTheFinalEvent ) {
console.log(
(
'listenForEventsAndExecuteActions - ' +
'the final event has occurred ' +
'breaking the cycle of karma'
),
eventName
);
theFinalActionHasNotBeenPerformedYet = false;
}
}
if( deployEventData.length < 1 ) {
console.log(
'listenForEventsAndExecuteActions - ' +
'hit timeout!⏰'
);
throw new Error(
'listenForEventsAndExecuteActions: operation timed out'
);
}
else if( theFinalActionHasNotBeenPerformedYet ) {
listenStartTimeKey = streams.getIncrementedTimeKeyData({
timeKey: deployEventData[
deployEventData.length - 1
].timeKey
});
const timeInfo = getTimeInfo({
operationExpiry
});
console.log(
'listenForEventsAndExecuteActions - ' +
'processed events - will listen for more - ' +
stringify({
listenStartTimeKey,
timeInfo
})
);
timeUntilExpiry = timeInfo.timeUntilExpiry;
thereIsTimeBeforeExpiry = timeInfo.thereIsTimeBeforeExpiry;
}
else {
console.log(
'listenForEventsAndExecuteActions - ' +
'finished processing events - will not listen for more'
);
}
}
const results = {
anErrorOccurred: false,
};
console.log(
'🤠listenForEventsAndExecuteActions - ' +
'executed successfully🤠 - ' +
'returning results - ' +
stringify( results )
);
return results;
});
module.exports = Object.freeze( async ({
deployId,
isGiraffe,
operationExpiry,
performActionBasedOnDeployEvent,
doPostInitializationAction,
}) => {
const results = await doRedisFunction({
performFunction: async ({
redisClient
}) => {
return await listenForEventsAndExecuteActionsCore({
deployId,
isGiraffe,
redisClient,
operationExpiry,
performActionBasedOnDeployEvent,
doPostInitializationAction,
});
},
functionName: 'listenForEventsAndExecuteActionsCore'
});
return results;
});
<file_sep>'use strict';
module.exports = Object.freeze(({
statusCode = 200,
body,
}) => {
return {
statusCode,
body: JSON.stringify( body ),
};
});<file_sep>'use strict';
const STATUS_CODE_MESSAGE = 'not_authorized_error';
class NotAuthorizedError extends Error {
constructor( message ) {
super( message );
this.statusCode = 401;
this.statusCodeMessage = STATUS_CODE_MESSAGE;
}
}
NotAuthorizedError.statusCodeMessage = STATUS_CODE_MESSAGE;
module.exports = NotAuthorizedError;<file_sep>'use strict';
const {
utils: {
stringify,
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
google: {
captcha: {
actions
}
}
},
business: {
verifyGoogleCode
}
} = require( '../../../../../utils' );
// const {
// crypto: {
// getCryptoAmountNumber
// }
// } = require( '../../../../../exchangeUtils' );
module.exports = Object.freeze( async ({
rawGoogleCode,
ipAddress,
}) => {
console.log(
`running validateAndGetValues with values: ${ stringify({
ipAddress,
rawGoogleCode,
}) }`
);
await verifyGoogleCode({
rawGoogleCode,
ipAddress,
expectedAction: actions.addAddress,
});
const results = {};
console.log(
'validateAndGetValues executed successfully, ' +
'here are the values: ' +
stringify( results )
);
return results;
});
<file_sep>'use strict';
const getCacheOnAndOffStatus = require( './getCacheOnAndOffStatus' );
const addCacheOnAndOffStatusToRhino = require( './addCacheOnAndOffStatusToRhino' );
exports.handler = Object.freeze( async () => {
console.log( '💃🏻Running cacheOnAndOffStatus' );
try {
const cacheOnAndOffStatus = await getCacheOnAndOffStatus();
await addCacheOnAndOffStatusToRhino( cacheOnAndOffStatus );
console.log( '💃🏻🐑cacheOnAndOffStatus executed successfully' );
}
catch( err ) {
console.log( '🦌💃🏻error in cacheOnAndOffStatus:', err );
}
});
<file_sep>'use strict';
const stringify = require( '../stringify' );
const {
utils: {
redis: {
streams: {
// getOperationTime,
xRangeWithPagination,
getKeyValues
}
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
module.exports = Object.freeze( async ({
elementalQueueId,
maxRate = 1,
timeRange = 1000 * 60 * 60 * 24,
redisClient,
powerQueueId,
thePowerOfNow,
veryPreviousOperationTimeKey
}) => {
const searchStart = thePowerOfNow - timeRange;
const searchEnd = veryPreviousOperationTimeKey;
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 - ' +
'running getIfThisElementIsAllowedToPerformThisRequest: ' +
stringify({
elementalQueueId,
maxRate,
timeRange,
searchStart,
searchEnd,
powerQueueId
})
);
// OPTIMIZATION: paginate and count and check as you paginate
const requestsInTimeRangeToConsider = await xRangeWithPagination({
redisClient,
startTime: searchStart,
endTime: searchEnd,
queueName: elementalQueueId,
paginationCount: 100,
});
const data = requestsInTimeRangeToConsider.map( entry => {
return {
// timeKey: entry[0],
keyValues: getKeyValues({
keyValueList: entry[1],
}),
};
});
const numberOfRequestsInTimeFrame = data.filter(
entry => (entry.keyValues.powerQueueId === powerQueueId)
).length + 1;
const hashedElementIsAllowedToPerformRequest = (
numberOfRequestsInTimeFrame <= maxRate
);
console.log(
'🐉🐲Beginning Dragon Protection🐉🐲 -\n' +
'number of requests in the time frame: ' +
`${ numberOfRequestsInTimeFrame }\n` +
`max rate in time frame: ${ maxRate }\n` +
stringify({ hashedElementIsAllowedToPerformRequest }) +
'\ngetIfThisElementIsAllowedToPerformThisRequest ' +
'executed successfully.'
);
return hashedElementIsAllowedToPerformRequest;
});
<file_sep>'use strict';
const jsonEncoder = require( '../../javascript/jsonEncoder' );
const doRedisRequest = require( '../doRedisRequest' );
const getClient = require( '../getClient' );
const {
redis: {
listIds
}
} = require( '../../../constants' );
const stringify = require( '../../stringify' );
module.exports = Object.freeze( async ({
addressDatum
}) => {
const { address } = addressDatum;
console.log(
'running addUnusedAddressDatum ' +
'(to rhino) with the following values: ' +
stringify({
address,
addressDatum
})
);
const encodedAddressDatum = jsonEncoder.encodeJson( addressDatum );
const client = getClient();
try {
await doRedisRequest({
client,
command: 'lpush',
redisArguments: [
listIds.unusedAddressData,
encodedAddressDatum
],
});
client.quit();
console.log(
'addUnusedAddressDatum - ' +
`address ${ address } successfully added to rhino`
);
}
catch( err ) {
client.quit();
console.log(
'addUnusedAddressDatum - ' +
`error in adding ${ address } to rhino`
);
throw err;
}
});
<file_sep>import { getState } from '../../reduxX';
import { actions } from '../../utils';
import { story, gameData, games } from '../../constants';
export default async () => {
if(
actions.getIsLoggedIn() &&
getState(
'loggedInMode',
'coinFlip',
'hasGottenJackpotDataForFirstTime'
) &&
(
getState( 'loggedInMode', 'mode' ) ===
story.LoggedInMode.modes.coinFlip
) &&
(
getState( 'loggedInMode', 'coinFlip', 'mode' ) ===
gameData[ games.theDragonsTalisman ].modes.jackpot
)
) {
await actions.refreshJackpotData();
}
};
<file_sep>'use strict';
const { argv } = require( 'yargs' );
const getRandomIntegerInclusive = ({ min, max }) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1) + min);
};
const stringify = message => JSON.stringify( message, null, 4 );
const minSlotNumber = 1;
const maxSlotNumber = 3;
// const winMultiplier = 7;
const percentageToWin = 0.9 + 0.00;
const coinNumberMultiplier = 1000000;
const coinNumberThreshold = (1 - percentageToWin) * coinNumberMultiplier;
const flipCoin = Object.freeze( () => {
const coinNumber = getRandomIntegerInclusive({
min: 1,
max: coinNumberMultiplier
});
const hasWonThisChallengeOfFate = coinNumber > coinNumberThreshold;
return hasWonThisChallengeOfFate;
});
let theTestAmount = 0;
const spinSlot = Object.freeze( () => {
theTestAmount -= 0.0001;
const slotNumber1 = getRandomIntegerInclusive({
min: minSlotNumber,
max: maxSlotNumber
});
const slotNumber2 = getRandomIntegerInclusive({
min: minSlotNumber,
max: maxSlotNumber
});
const slotNumber3 = getRandomIntegerInclusive({
min: minSlotNumber,
max: maxSlotNumber
});
const hasWon = (
(slotNumber1 === slotNumber2) &&
(slotNumber2 === slotNumber3)
);
if( hasWon ) {
const hasWonForReal = flipCoin();
if( hasWonForReal ) {
// console.log( 'WINWIN' );
theTestAmount += 0.0007;
}
// else {
// // console.log( 'WINLOSE' );
// // theTestAmount -= 0.0001;
// }
}
else if( // has tied
(slotNumber1 !== slotNumber2) &&
(slotNumber2 !== slotNumber3) &&
(slotNumber1 !== slotNumber3)
) {
theTestAmount += 0.0001;
// console.log( 'TIE' );
}
// else { // has lost
// // console.log( 'LOSE' );
// // theTestAmount -= 0.0001;
// }
});
const doSpins = () => {
const max = Number( argv.n ) || 1000;
for( let i = 0; i < max; i++ ) {
spinSlot();
}
// console.log(
// stringify({
// theTestAmount
// })
// );
return theTestAmount;
};
const metaDoSpins = () => {
const max = Number( argv.m ) || 10;
const doSpinsResults = [];
for( let i = 0; i < max; i++ ) {
theTestAmount = 0;
doSpinsResults.push( doSpins() );
}
console.log(
doSpinsResults.reduce( (a, b) => a + b, 0 ) / doSpinsResults.length
);
};
metaDoSpins();
<file_sep>'use strict';
const {
constants: {
computerServerServiceNames: {
refreshingDrank,
monkeyPaw,
juiceCamel
},
redis: {
streamIds: {
zarbonDeploy
}
},
deploy: {
eventNames
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const deployCommands = {
feeDataBot: refreshingDrank,
withdrawsBot: monkeyPaw,
depositsBot: juiceCamel,
};
module.exports = Object.freeze({
streamIds: {
zarbonDeploy,
},
deployCommands,
deployCommandList: Object.values( deployCommands ),
eventNames: {
giraffe: {
lick: 'lick', // (🦒😋🍃)
lickComplete: 'lickComplete',
},
leaf: {
tongueFeel: 'tongueFeel', // (🦒😋🍃)
tigerCommand: eventNames.leaf.tigerCommand,
serviceIsGood: 'serviceIsGood',
},
tiger: {
tigerEnlightenment: eventNames.tiger.tigerEnlightenment
},
common: {
error: 'error'
}
},
errorListenerMessages: {
error: 'error',
done: 'done',
},
});
<file_sep>'use strict';
module.exports = Object.freeze( ({
numbers,
}) => {
const choice = numbers.join( '-' );
return choice;
});
<file_sep>import { createElement as e } from 'react';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
const getStyles = () => {
return {
outerContainer: {
width: '100%',
// height: 100,
// // backgroundColor: 'pink',
// display: 'flex',
// justifyContent: 'center',
// flexDirection: 'column',
// alignItems: 'center'
},
text: {
width: '90%',
// height: 100,
color: 'black',
marginTop: 13,
marginBottom: 9,
marginLeft: 15,
// padding: 5,
},
};
};
const texts = [
`• Thousand Petal Lotus is an hourly draw lottery game`,
`• Users pick lotus petals, each petal has two numbers associated with it`,
`• The numbers range from 1 to 36 and duplicate numbers cannot be chosen`,
`• Picking a petal costs Dynasty Bitcoin (DB), when a user picks a petal the amount they pay goes to the Flower Pot.`,
`• A petal is drawn at the beginning of each hour. Users who've picked the same petal win the Flower Pot!`,
`• Thousand Petal Lotus is segmented overall in time by Lotus Seasons. A Lotus Season is the time period until the hourly draw choses a winning picked petal. After a winning petal is picked, a new Lotus Season starts.`,
`• If multiple users have the same winning petal, then the Flower Pot is split evenly among winners.`,
`• Dynasty Bitcoin takes a percentage of the Flower Pot. This percentage is called the "House Flower Pot" and is specified per Lotus Season.`,
`• Petals can be unpicked (cancelled - and completely refunded) if they have not yet been considered for a petal draw. Petals cannot be unpicked 5 minutes before a draw, or any later. Draws happen at the beginning of each hour. This means if a petal is picked five minutes before the next draw, which happens at the beginning of each hour, that petal cannot be unpicked.`,
`• The petal draw happens on the hour slightly after the start of the hour and it takes a small amount of time to process. If a petal was picked for the draw after the draw's hour and the draw was a winning draw, then any petal picked for that draw after the draw's hour will be unpicked and refunded.`,
`• The petal draw probability can be described using a mathematical function of the following form: for a number of chosen petals x, the probability of winning the Flower Pot (minus the House Flower Pot) per draw is given by the function f( x ) = ( x / 1260 ) * 100%.`
];
export default () => {
const styles = getStyles();
const textElements = texts.map( text => {
return e(
Typography,
{
style: styles.text,
},
text
);
});
return e(
Box,
{
style: styles.outerContainer,
},
...textElements
);
};
<file_sep>'use strict';
module.exports = Object.freeze({
getIfRaffleIdIsValid: require( './getIfRaffleIdIsValid' ),
getIfRaffleDrawIdIsValid: require( './getIfRaffleDrawIdIsValid' ),
getRaffleId: require( './getRaffleId' ),
getRaffleDrawId: require( './getRaffleDrawId' ),
getChoiceFromNumbers: require( './getChoiceFromNumbers' ),
getChoiceTimeData: require( './getChoiceTimeData' ),
});
<file_sep>'use strict';
const {
utils: {
stringify,
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
crypto: { getCryptoAmountNumber },
} = require( '../../../../../../exchangeUtils' );
const {
maxAmount,
} = require( '../localConstants' );
module.exports = Object.freeze( ({
amount,
jackpotAmount,
houseCut,
}) => {
const amountOverMaxAmount = (amount/maxAmount);
console.log(
'running getWinAmount with the following values:',
stringify({
amount,
maxAmount,
amountOverMaxAmount,
houseCut,
jackpotAmount
})
);
const rawWinAmount = amountOverMaxAmount * jackpotAmount;
const oneMinusHouseCut = (1 - houseCut);
const winAmount = getCryptoAmountNumber(
rawWinAmount * oneMinusHouseCut
);
console.log(
'getWinAmount executed successfully, here is the win amount:',
stringify({
rawWinAmount,
'(1 - houseCut)': oneMinusHouseCut,
winAmount,
})
);
return winAmount;
});
<file_sep>import { google } from '../../constants';
export default ({
action,
}) => new Promise( (
resolve
) => {
try {
window.grecaptcha.ready( async () => {
try{
const token = await window.grecaptcha.execute(
google.grecapcha.siteKey,
{ action }
);
resolve( token );
}
catch( err ) {
resolve();
}
});
}
catch( err ) {
resolve();
}
});<file_sep>'use strict';
const {
utils: {
stringify
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
utils: {
aws: {
dinoCombos: {
addTransactionAndUpdateExchangeUser,
}
}
},
constants: {
transactions: {
types,
},
raffles: {
types: {
putTicket,
},
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
// const {
// constants: {
// raffle: {
// lotteryTypes
// }
// }
// } = require( '../../../../../../enchantedUtils' );
module.exports = Object.freeze( async ({
raffleId,
choice,
exchangeUserId,
action,
amount,
}) => {
console.log(
`running addTransaction with the following values - ${
stringify({
exchangeUserId,
raffleId,
action,
choice,
amount,
})
}`
);
await addTransactionAndUpdateExchangeUser({
noLocka: true,
exchangeUserId,
type: types.raffle,
data: {
searchId: raffleId,
amount,
raffleType: putTicket,
choice,
action,
},
});
console.log( 'addTransaction executed successfully' );
});<file_sep>'use strict';
const {
getFormattedEvent,
getResponse,
handleError,
stringify,
constants: {
timeNumbers: {
hour,
},
},
javascript: {
ensureEnvValuesAreTruthful
}
} = require( '../../../../utils' );
const {
loginTokens: {
<PASSWORD>
},
constants: {
headers: {
grecaptchaGoogleCode
}
}
} = require( '../../../../exchangeUtils' );
const addAddress = require( './addAddress' );
ensureEnvValuesAreTruthful({
envKeys: [
'EXCHANGE_TOKEN_USER_ID',
'EXCHANGE_XOOVO_ENCRYPTION_ID',
'EXCHANGE_XOOVO_ENCRYPTION_PASSWORD',
'EXCHANGE_GRECAPTCHA_SECRET_KEY',
// 'EXCHANGE_GRECAPTCHA_BYPASS_HEADER_KEY_VALUE',
]
});
exports.handler = Object.freeze( async rawEvent => {
try {
console.log( 'running the exchange /addresses - POST function' );
const event = getFormattedEvent({
rawEvent,
// shouldGetBodyFromEvent: false,
});
const {
ipAddress,
exchangeUserId,
} = await mongolianBeginningDragonProtection({
queueName: 'exchangeAddressesPost',
event,
megaCodeIsRequired: false,
ipAddressMaxRate: 5,
ipAddressTimeRange: hour,
});
const rawGoogleCode = event.headers[ grecaptchaGoogleCode ];
const addAddressResults = await addAddress({
exchangeUserId,
rawGoogleCode,
ipAddress,
});
const responseData = Object.assign(
{},
addAddressResults
);
console.log(
'the exchange /addresses - ' +
'POST function executed successfully: ' +
stringify({ responseData })
);
return getResponse({
body: responseData
});
}
catch( err ) {
console.log(
'error in exchange /addresses - ' +
`POST function: ${ err }`
);
return handleError( err );
}
});<file_sep>'use strict';
const {
utils: {
stringify,
},
constants: {
environment: {
isProductionMode,
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const execa = require( 'execa' );
const start = 'start';
const getExecaArgs = Object.freeze( ({
mainFileName,
}) => {
const args = [
start,
mainFileName,
];
if( isProductionMode ) {
args.push(
'--',
'--mode=production'
);
}
return args;
});
module.exports = Object.freeze( async ({
log,
trueTigerPath,
mainFileName,
}) => {
log(
'🌠🐈🐈running startPmTiger - ' +
stringify({
trueTigerPath
})
);
await execa(
'pm2',
getExecaArgs({
mainFileName
}),
{
cwd: trueTigerPath
}
);
log( '🌠🐈🐈startPm2 executed successfully' );
});
<file_sep>'use strict';
const BEP20 = artifacts.require( 'BEP20' );
const a2 = '0xb37b05768686220fff33e6be9fd5aed2fd0f19d0';
module.exports = function( callback ) {
console.log( 'running script' );
return (new Promise( async ( resolve, reject ) => {
try {
const instance = await BEP20.deployed();
const balance = await instance.balanceOf( a2 );
console.log( 'here is the balance:', balance.words[0] );
resolve();
}
catch( err ) {
reject( err );
}
})).then( () => {
console.log( 'script executed successfully' );
callback();
}).catch( err => {
console.log( 'error in script:', err );
callback( err );
});
};
<file_sep>'use strict';
module.exports = Object.freeze( ({
exchangeUserId
}) => {
if(
!exchangeUserId ||
(typeof exchangeUserId !== 'string')
) {
throw new Error(
'getExchangeUserIdDataComponents error: invalid exchangeUserId'
);
}
const splitExchangeUserId = exchangeUserId.split( '_' );
if( splitExchangeUserId.length !== 3 ) {
throw new Error(
'getExchangeUserIdDataComponents error: invalid exchangeUserId'
);
}
if(
!(
(
splitExchangeUserId[0] === 'exchange'
) &&
(
splitExchangeUserId[1] === 'user'
) &&
(
!!splitExchangeUserId[2] &&
(splitExchangeUserId[2].length > 5) &&
(splitExchangeUserId[2].length < 100)
)
)
) {
throw new Error(
'getExchangeUserIdDataComponents error: invalid exchangeUserId'
);
}
const exchangeUserIdDataComponents = {
baseId: splitExchangeUserId[2]
};
return exchangeUserIdDataComponents;
});<file_sep>'use strict';
const ultimateEncryptionObjects = Object.freeze([
Object.freeze({
id: process.env.MEGA_CODE_ENCRYPTION_ID_4,
password: process.env.MEGA_CODE_ENCRYPTION_PASSWORD_4,
}),
]);
const { id, password } = ultimateEncryptionObjects[
ultimateEncryptionObjects.length - 1
];
const encryptionIds = [];
const encryptionIdToEncryptionPassword = {};
for( const encryptionObject of ultimateEncryptionObjects ) {
encryptionIds.push( encryptionObject.id );
encryptionIdToEncryptionPassword[
encryptionObject.id
] = encryptionObject.password;
}
Object.freeze( encryptionIds );
Object.freeze( encryptionIdToEncryptionPassword );
module.exports = Object.freeze({
encryptionIdToUse: id,
encryptionPasswordToUse: password,
encryptionIdToEncryptionPassword,
encryptionIds,
});
<file_sep>'use strict';
const {
utils: {
doOperationInQueue,
stringify,
javascript: {
getQueueId
},
}
} = require( '@bitcoin-api/full-stack-api-private' );
const {
constants: {
aws: {
database: {
tableNames: {
EXCHANGE_USERS
}
}
}
}
} = require( '@bitcoin-api/full-stack-exchange-private' );
const validateAndGetExchangeUser = require( './validateAndGetExchangeUser' );
const signOutLoginTokens = require( './signOutLoginTokens' );
const signOutExchangeUser = require( './signOutExchangeUser' );
const deleteUserCore = Object.freeze( async ({
exchangeUserId,
loginTokens,
ipAddress,
}) => {
const exchangeUser = await validateAndGetExchangeUser({
exchangeUserId,
});
await signOutLoginTokens({
loginTokens,
ipAddress,
});
await signOutExchangeUser({
exchangeUser,
ipAddress,
});
});
module.exports = Object.freeze( async ({
ipAddress,
exchangeUserId,
loginTokens,
}) => {
console.log(
'running the deleteUser ' +
`with the following values: ${ stringify({
exchangeUserId,
ipAddress,
})}`
);
await doOperationInQueue({
queueId: getQueueId({ type: EXCHANGE_USERS, id: exchangeUserId }),
doOperation: async () => {
return await deleteUserCore({
exchangeUserId,
loginTokens,
ipAddress,
});
}
});
const responseData = {};
console.log(
'the exchange deleteUser executed successfully: ' +
stringify({ responseData })
);
return responseData;
});<file_sep>#!/bin/sh
pushd ../../../2-api/
npm install
echo \"swaggy swag v3🐺🐺🐺\"
node ./deployFunctions $0 $1 $2 $3 $4 $5 $6 $7 $8 $9
popd
<file_sep>'use strict';
/*
RUN EVERY 15 minutes, function hasn't been run in past 15 minutes,
then run again
get lastPaginationValue from metadata update alien balance glyph
if last update just happened
or if no lastpagination value and it is still within 20 seconds
get all alien addresses starting with address_bsc_1
for each address
get user balance
if diff -> balanceUpdate ATAEUE
run with next function
*/
const {
utils: {
aws: {
dino: {
searchDatabase,
}
},
stringify,
},
constants: {
aws: {
database: {
tableNames: { ADDRESSES },
// addressesTable: {
// secondaryIndexNames: {
// addressIndex
// }
// }
}
}
}
} = require( '@bitcoin-api/full-stack-api-private' );
const getIfThereIsAnAlienBalanceDiff = require( './getIfThereIsAnAlienBalanceDiff' );
// const {
// } = require( '@bitcoin-api/full-stack-exchange-private' );
// const {
// crypto: {
// getCryptoAmountNumber
// }
// } = require( '../../../../../exchangeUtils' );
// const {
// raffle: {
// getChoiceTimeData
// }
// } = require( '../../../../../enchantedUtils' );
const searchLimit = 1000;
const f = Object.freeze;
const attributes = f({
nameKeys: f({
exchangeUserId: '#exchangeUserId',
}),
nameValues: f({
exchangeUserId: 'exchangeUserId',
}),
valueKeys: f({
exchangeUserId: ':exchangeUserId',
}),
// valueValues: f({
// type: raffle,
// })
});
const alien = 'alien';
module.exports = Object.freeze( async alienAddressDatum => {
console.log(
'running updateAlienAddressDatum ' +
`with the following values - ${ stringify( alienAddressDatum ) }`
);
// const getIfThereIsAnAlienBalanceDiff
/*
1. get exchange user see if diff
2. if diff
in lock
get exchange user see if diff
if diff ATAUEU
*/
console.log(
'updateAlienAddressDatum ' +
`executed successfully - ${ stringify({
}) }`
);
});
<file_sep>import * as ArgonRealms from './ArgonRealms';
const { PrivacyPolicyRealm, TermsOfServiceRealm } = ArgonRealms;
export { PrivacyPolicyRealm, TermsOfServiceRealm };<file_sep>import { createElement as e, useEffect } from 'react';
// import { getState } from '../../../../reduxX';
// import {
// usefulComponents,
// // POWBlock,
// } from '../../TheSource';
// import {
// usefulComponents
// } from '../../../../../TheSource';
import Box from '@material-ui/core/Box';
import SortSelector from './SortSelector';
import DisplayBox from './DisplayBox';
import componentDidMount from './componentDidMount';
// import Typography from '@material-ui/core/Typography';
// import Button from '@material-ui/core/Button';
const getStyles = () => {
return {
metaContainer: {
width: '100%',
// height: 69,
backgroundColor: '#FDFEF4',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'center',
marginTop: 10,
marginBottom: 13,
},
};
};
export default ({
raffleDatum,
isLocalLoading,
setIsLocalLoading,
}) => {
// component did mount -> raffleIdToTicketData
// get data, get own special id
const { raffleId } = raffleDatum;
useEffect( () => {
Promise.resolve().then( async () => {
setIsLocalLoading( true );
try {
await componentDidMount({
raffleId,
});
setIsLocalLoading( false );
}
catch( err ) {
setIsLocalLoading( false );
console.log( 'an error occurred:', err );
}
});
}, [ raffleId, setIsLocalLoading ] );
const styles = getStyles();
return e(
Box,
{
style: styles.metaContainer
},
e(
SortSelector,
{
raffleDatum,
isLocalLoading,
}
),
e(
DisplayBox,
{
raffleDatum
}
)
);
};<file_sep>cd
rm -rf treeDeploy
mkdir treeDeploy
mkdir treeDeploy/giraffeDeploy
mkdir treeDeploy/stagingCredentials
mkdir treeDeploy/stagingCredentials/tree
mkdir treeDeploy/productionCredentials
mkdir treeDeploy/productionCredentials/tree
<file_sep>import { createElement as e } from 'react';
import GameTitle from '../desireElements/GameTitle';
import { story } from '../../constants';
export default () => {
return e(
GameTitle,
{
title: 'Satoshi Slot',
type: 'Slot Game',
helpDialogMode: story.dialogModes.games.aboutSlot,
marginTop: 0,
marginBottom: 0,
},
);
};
<file_sep>export default key => {
const url = window.location.href;
key = key.replace(/[[\]]/g, '\\$&');
const regex = new RegExp('[?&]' + key + '(=([^&#]*)|&|#|$)');
const results = regex.exec( url );
if( !results ) {
return null;
}
if( !results[2] ) {
return '';
}
const value = decodeURIComponent( results[2].replace( /\+/g, ' ' ) );
return value;
};<file_sep>'use strict';
const stringify = require( '../../../stringify' );
const MAX_NUMBER_OF_ENTRIES_TO_PUT_AT_ONCE = 2;
module.exports = Object.freeze( ({ entries }) => {
console.log(
'running putMultipleDatabaseEntries.getEntriesToPutNowAndToPutLater ' +
`with the following values: ${ stringify({ entries }) }`
);
const entriesToPutNow = [];
const entriesToPutLater = [];
for( let i = 0; i < entries.length; i++ ) {
if( i < MAX_NUMBER_OF_ENTRIES_TO_PUT_AT_ONCE ) {
entriesToPutNow.push( entries[i] );
}
else {
entriesToPutLater.push( entries[i] );
}
}
console.log(
'putMultipleDatabaseEntries.getEntriesToPutNowAndToPutLater ' +
'executed successfully ' +
`returning values: ${ stringify({
entriesToPutNow,
entriesToPutLater,
})}`
);
return {
entriesToPutNow,
entriesToPutLater,
};
});
<file_sep>'use strict';
const {
utils: {
stringify,
redis: {
doRedisFunction,
},
},
} = require( '@bitcoin-api/full-stack-api-private' );
const {
giraffeAndTreeStatusUpdate,
constants: {
eventNames
}
} = require( '@bitcoin-api/giraffe-utils' );
const log = Object.freeze( ( ...args ) => {
console.log( '👅☑️handleLickComplete - ', ...args );
});
const handleLickCompleteCore = Object.freeze( async ({
deployId,
deployCommand,
forceDeploy
}) => {
log(
'👅👅 next - ' +
'telepathy message to tiger🌊🐅'
);
await doRedisFunction({
performFunction: async ({
redisClient
}) => {
await giraffeAndTreeStatusUpdate({
redisClient,
eventName: eventNames.leaf.tigerCommand,
information: {
deployId,
eventOrder: 3,
deployCommand,
forceDeploy,
}
});
if( !!forceDeploy ) {
console.log(
'tree(🌲) is performing 🐅tigerEnlightenment⏫💁♀️ ' +
'because force deploy was requested'
);
await giraffeAndTreeStatusUpdate({
redisClient,
eventName: eventNames.tiger.tigerEnlightenment,
information: {
deployId,
eventOrder: 4,
deployCommand,
}
});
}
},
functionName: '🌲tree engages with summoned tiger telepathically🐅'
});
log(
'telepathy message to tiger success🐅✅'
);
});
module.exports = Object.freeze( async ({
information: {
deployId,
deployCommand,
},
forceDeploy
}) => {
log( `running handleLickComplete - ${ stringify({
deployCommand,
forceDeploy
})}` );
await handleLickCompleteCore({
deployId,
deployCommand,
forceDeploy
});
log( 'handleLickComplete executed successfully' );
});
<file_sep>import { createElement as e, Suspense, lazy } from 'react';
import ReactDOM from 'react-dom';
import * as serviceWorker from './serviceWorker';
// import 'fontsource-roboto';
// import App from './App';
// import goToRightUrlIfNecessary from './goToRightUrlIfNecessary';
import LoadingPage from './App/TheSource/LoadingPage';
// import 'fontsource-roboto';
const App = lazy(() => import('./App'));
// ReactDOM.render( e('div'), document.getElementById('root'));
const TheMeta = () => {
// useEffect( () => {
// goToRightUrlIfNecessary();
// }, [] );
return e(
Suspense,
{
fallback: e( LoadingPage, { fullDogeStyle: true } ),
},
e(
App,
{
safeMode: true,
}
)
);
};
ReactDOM.render(
e( TheMeta ),
document.getElementById( 'root' )
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();
<file_sep>import { actions } from '../../utils';
export default async () => {
await actions.refreshDensityRaffleData({
setToLoading: false
});
};
<file_sep>'use strict';
const { database } = require( '../aws' );
const stringify = require( '../../stringify' );
const {
aws: { database: { tableNameToKey, tableNameToSortKey } }
} = require( '../../../constants' );
module.exports = Object.freeze( ({
tableName,
value,
sortValue,
key,
sortKey,
}) => {
key = key || tableNameToKey[ tableName ];
const TableName = tableName;
const Key = {
[ key ]: value,
};
if( !!sortValue ) {
sortKey = sortKey || tableNameToSortKey[ tableName ];
Key[ sortKey ] = sortValue;
}
const params = { TableName, Key };
console.log(
'Running database.getDatabaseEntry with the following values:',
stringify( params )
);
return new Promise(
( resolve, reject ) => database.get( params, ( err, data ) => {
if( !!err ) {
console.log(
'Error in database.getDatabaseEntry',
'with the following values:',
stringify( params )
);
return reject( err );
}
const result = (
!!data &&
!!data.Item &&
data.Item
) || null;
console.log(
'database.getDatabaseEntry successfully executed',
`returning data: ${
!!result ? JSON.stringify( Object.keys( result ) ) : result
}`
);
resolve( result );
})
);
});<file_sep>'use strict';
const {
getFormattedEvent,
getResponse,
handleError,
beginningDragonProtection,
stringify,
validation: {
getIfEmailIsValid
},
formatting: {
getFormattedEmail
},
constants: {
timeNumbers: {
hour
}
}
} = require( '../../../../../utils' );
const initiatePasswordReset = require( './initiatePasswordReset' );
exports.handler = Object.freeze( async rawEvent => {
try {
console.log(
'running the exchange /login/password - POST function'
);
const event = getFormattedEvent({
rawEvent,
});
const rawEmail = event.headers.email;
if( !getIfEmailIsValid({ email: rawEmail }) ) {
const invalidEmailError = new Error( 'invalid email provided' );
invalidEmailError.statusCode = 400;
invalidEmailError.bulltrue = true;
throw invalidEmailError;
}
const email = getFormattedEmail({ rawEmail });
const {
ipAddress
} = await beginningDragonProtection({
queueName: 'exchangeLoginPasswordPost',
event,
megaCodeIsRequired: false,
ipAddressMaxRate: 2,
ipAddressTimeRange: hour,
altruisticCode: email,
altruisticCodeIsRequired: true,
altruisticCodeMaxRate: 2,
altruisticCodeTimeRange: hour,
});
const initiatePasswordResetResults = await initiatePasswordReset({
event,
email,
ipAddress,
});
const responseData = Object.assign(
{},
initiatePasswordResetResults
);
console.log(
'the exchange /login/password - ' +
'POST function executed successfully: ' +
stringify({ responseData })
);
return getResponse({
body: responseData
});
}
catch( err ) {
console.log(
`error in exchange /login/password - POST function: ${ err }` );
return handleError( err );
}
});
|
49e5c1a0c5493802530495bbcf090fb534bd23ca
|
[
"JavaScript",
"TypeScript",
"Markdown",
"Shell"
] | 513 |
JavaScript
|
bitcoin-api/bitcoin-api
|
a0b78735183f60606469b298ac6a752b5789fdbb
|
5c6c1694b11dd3edff4c306b74258c4ecbb06c18
|
refs/heads/master
|
<repo_name>awloint/ys-volunteer<file_sep>/scripts/Notify.php
<?php
/**
* This script is the Notify Class
*
* PHP version 7.2
*
* @category Notification_Class
* @package Notification_Class
* @author <NAME>,ST <<EMAIL>>
* @license MIT https://opensource.org/licenses/MIT
* @link https://stbensonimoh.com
*/
require '../PHPMailer/src/PHPMailer.php';
require '../PHPMailer/src/SMTP.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
/**
* This is the Notify Class
*
* @category Notify_Class
* @package Notify_Class
* @author <NAME>,ST <<EMAIL>>
* @license MIT https://opensource.org/licenses/MIT
* @link https://stbensonimoh.com
*/
class Notify
{
/**
* Constructor Function
*
* @param string $smstoken The API token for the SMS
* @param string $emailHost The hostname of the email server
* @param string $emailUsername The email address
* @param string $emailPassword The email <PASSWORD>
* @param integer $SMTPDebug If you'd like to see debug information
* @param boolean $SMTPAuth If you'd like to authenticate via SMTP
* @param string $SMTPSecure Certificate Type
* @param integer $Port Port Number
*/
public function __construct($smstoken, $emailHost, $emailUsername, $emailPassword, $SMTPDebug, $SMTPAuth, $SMTPSecure, $Port)
{
$this->smstoken = $smstoken;
$this->emailHost = $emailHost;
$this->emailUsername = $emailUsername;
$this->emailPassword = $emailPassword;
$this->SMTPDebug = $SMTPDebug;
$this->SMTPAuth = $SMTPAuth;
$this->SMTPSecure = $SMTPSecure;
$this->Port = $Port;
}
/**
* Send notification via SMS
*
* @param string $from the SMS from identify - not more than 11 characters
* @param string $body - The body of the SMS
* @param string $phone - The Phone number enclosed in Strings
*
* @return void
*/
public function viaSMS($from, $body, $phone)
{
// prepare the parameters
$url = 'https://www.bulksmsnigeria.com/api/v1/sms/create';
$token = $this->smstoken;
$myvars = 'api_token=' . $token . '&from=' . $from . '&to='
. $phone . '&body=' . $body;
//start CURL
// create curl resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
}
/**
* Sends Email notification via PHPMailer
*
* @param string $fromEmail The From Email Address
* @param string $fromName The From Name
* @param string $toEmail The To Email Address
* @param string $toName The To Name
* @param string $emailBody The Email Body
* @param string $subject The Email Subject
*
* @return void
*/
public function viaEmail($fromEmail, $fromName, $toEmail, $toName, $emailBody, $subject)
{
$mail = new PHPMailer(true);
// Server settings
$mail->SMTPDebug = $this->SMTPDebug;
$mail->isSMTP();
$mail->Host = $this->emailHost;
$mail->SMTPAuth = $this->SMTPAuth;
$mail->Username = $this->emailUsername;
$mail->Password = $this-><PASSWORD>;
$mail->SMTPSecure = $this->SMTPSecure;
$mail->Port = $this->Port;
// Send the Email
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($toEmail, $toName);
$mail->isHTML(true);
$mail->Subject = $subject;
$mail->Body = $emailBody;
$mail->send();
}
}
<file_sep>/scripts/emails.php
<?php
$emailBodyVolunteer = "<table style='background-color: #d5d5d5;' border='0' width='100%' cellspacing='0'>
<tbody>
<tr>
<td>
<table style='font-family: Helvetica,Arial,sans-serif; background-color: #fff; margin-top: 40px; margin-bottom: 40px;' border='0' width='600' cellspacing='0' cellpadding='0' align='center'>
<tbody>
<tr>
<td style='padding-top: 40px; padding-right: 40px; padding-bottom: 15px;' colspan='2'>
<p style='text-align: right;'><a href='https://awlo.org'><img src='http://awlo.org/email/awlo_lg.png' alt='African Women in Leadership Organisation' width='20%' border='0' /></a></p>
</td>
</tr>
<tr>
<td style='padding-right: 40px; text-align: right;' colspan='2'></td>
</tr>
<tr>
<td style='color: #000; font-size: 12pt; font-family: Helvetica; font-weight: normal; line-height: 15pt; padding: 40px 40px 80px 40px;' colspan='2' valign='top'>Dear {$firstName} {$lastName},
<p>Thank you for choosing to volunteer for the Youth Summit 2019, and sharing your good heart with us. You may not know this but you are real MVP.</p>
<p>The data you submitted has been submitted into our database.</p>
<p>Kindly click <a href='https://join.slack.com/t/awlo/<KEY>k'>HERE</a> to join our slack channel where you can meet with other volunteers and get instructions/information about the next steps on your volunteer journey.</p>
<p>We look forward to working together with you.</p>
<p>Welcome to the AWLO Team,</p>
<p><img src='https://stbensonimoh.com/email/sign_rosette_blue_ink.png' height='50px' /></p>
</td>
</tr>
<tr>
<td style='border-top: 5px solid #940000; height: 10px; font-size: 7pt;' colspan='2' valign='top'><span> </span></td>
</tr>
<tr style='text-align: center;'>
<td id='s1' style='padding-left: 20px;' valign='top'><span style='text-align: center; color: #333; font-size: 12pt;'><strong>Volunteer</strong></span><span style='color: #cccccc; font-size: x-large;'> | </span><span style='text-align: left; color: #333; font-size: 11pt; font-weight: normal;'>Volunteer Desk</span></td>
</tr>
<tr style='text-align: center; padding-left: 40px; padding-right: 40px; padding-bottom: 0;'>
<td colspan='2' valign='top'><span style='color: #333; font-size: 8pt; font-weight: normal; line-height: 17pt; padding-left: 40px; padding-right: 40px;'>African Women in Leadership Organisation<br /><strong>International Headquarters:</strong> 6, Alhaji Bankole Crescent, Ikeja, Lagos - Nigeria<br />tel: +2347066819910 | mobile: +2348066285116 | +2348087719510<br /><strong>USA:</strong> 60 4800 Duval Point Way SW, Snellville, GA 30039, USA.<br />tel: +1 404-518-8194 | <span>+1 505-547-0528</span> <br /><strong>South Africa:</strong> Newlands Shopping Centre CNR. Dely Road/Lois Road, <br />1st Floor, Suite 104, Newlands, Pretoria, South Africa<br />tel: +27-845-105871<br /><strong>email: </strong><EMAIL> | <strong>www.awlo.org</strong></span>
<p><a href='http://twitter.com/awloint'><img src='http://awlo.org/email/social/twitter_circle_color-20.png' width='20px' height='20px' /></a><a href='http://facebook.com/awloint'><img src='http://awlo.org/email/social/facebook_circle_color-20.png' width='20px' height='20px' /></a><a href='https://plus.google.com/103912934440599693779'><img src='http://awlo.org/email/social/google_circle_color-20.png' width='20px' height='20px' /></a><a href='http://linkedin.com/company/awloint'><img src='http://awlo.org/email/social/linkedin_circle_color-20.png' width='20px' height='20px' /></a><a href='http://instagram.com/awloint'><img src='http://awlo.org/email/social/instagram_circle_color-20.png' width='20px' height='20px' /></a><a href='https://www.youtube.com/channel/UCevvBafqeTjY16qd2gbceJw'><img src='http://awlo.org/email/social/youtube_circle_color-20.png' width='20px' height='20px' /></a></p>
</td>
</tr>
<tr>
<td id='s3' style='padding-left: 20px; padding-right: 20px;' colspan='2' valign='bottom'>
<p style='font-family: Helvetica, sans-serif; text-align: center; font-size: 12px; line-height: 21px; color: #333;'><span style='margin-left: 4px;'><span style='opacity: 0.4; color: #333; font-size: 9px;'>Disclaimer: This message and any files transmitted with it are confidential and privileged. If you have received it in error, please notify the sender by return e-mail and delete this message from your system. If you are not the intended recipient you are hereby notified that any dissemination, copy or disclosure of this e-mail is strictly prohibited.</span></span></p>
</td>
</tr>
<tr>
<td style='border-bottom: 5px solid #940000; height: 5px; font-size: 7pt;' colspan='2' valign='top'> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>";
$emailBodyOrganisation = "<table style='background-color: #d5d5d5;' border='0' width='100%' cellspacing='0'>
<tbody>
<tr>
<td>
<table style='font-family: Helvetica,Arial,sans-serif; background-color: #fff; margin-top: 40px; margin-bottom: 40px;' border='0' width='600' cellspacing='0' cellpadding='0' align='center'>
<tbody>
<tr>
<td style='padding-top: 40px; padding-right: 40px; padding-bottom: 15px;' colspan='2'>
<p style='text-align: right;'><a href='https://awlo.org'><img src='http://awlo.org/email/awlo_lg.png' alt='African Women in Leadership Organisation' width='20%' border='0' /></a></p>
</td>
</tr>
<tr>
<td style='padding-right: 40px; text-align: right;' colspan='2'></td>
</tr>
<tr>
<td style='color: #000; font-size: 12pt; font-family: Helvetica; font-weight: normal; line-height: 15pt; padding: 40px 40px 80px 40px;' colspan='2' valign='top'>
<p>Dear Admin,</p>
<p>Someone has Volunteered for the AWLCRwanda2019 as a Social Media Volunteer. Below are the details:</p>
<p>
<strong>First Name: </strong> {$firstName} <br>
<strong>Middle Name: </strong> {$middleName} <br>
<strong>Last Name: </strong> {$lastName} <br>
<strong>Email: </strong> {$email} <br>
<strong>Phone Number: </strong> {$phone} <br>
<strong>Current Location: </strong> {$location} <br>
<strong>LinkedIn Handle: </strong> {$linkedinHandle} <br>
<strong>Twitter Handle: </strong> {$twitterHandle} <br>
<strong>Instagram Handle: </strong> {$instagramHandle} <br>
<strong>Facebook Handle: </strong> {$facebookHandle} <br>
<strong>Which of these social media handles are you most conversant with? : </strong> {$familiarHandles} <br>
<strong>What unit would you like to Volunteer in?: </strong> {$unit} <br>
<strong>Why do you want to volunteer?: </strong> {$reasonForVolunteering} <br>
</p>
<p>Warm Regards,</p>
<p><img src='https://stbensonimoh.com/email/sign_rosette_blue_ink.png' height='50px' /></p>
</td>
</tr>
<tr>
<td style='border-top: 5px solid #940000; height: 10px; font-size: 7pt;' colspan='2' valign='top'><span> </span></td>
</tr>
<tr style='text-align: center;'>
<td id='s1' style='padding-left: 20px;' valign='top'><span style='text-align: center; color: #333; font-size: 12pt;'><strong>Volunteer</strong></span><span style='color: #cccccc; font-size: x-large;'> | </span><span style='text-align: left; color: #333; font-size: 11pt; font-weight: normal;'>Volunteer Desk</span></td>
</tr>
<tr style='text-align: center; padding-left: 40px; padding-right: 40px; padding-bottom: 0;'>
<td colspan='2' valign='top'><span style='color: #333; font-size: 8pt; font-weight: normal; line-height: 17pt; padding-left: 40px; padding-right: 40px;'>African Women in Leadership Organisation<br /><strong>International Headquarters:</strong> 6, Alhaji Bankole Crescent, Ikeja, Lagos - Nigeria<br />tel: +2347066819910 | mobile: +2348066285116 | +2348087719510<br /><strong>USA:</strong> 60 4800 Duval Point Way SW, Snellville, GA 30039, USA.<br />tel: +1 404-518-8194 | <span>+1 505-547-0528</span> <br /><strong>South Africa:</strong> Newlands Shopping Centre CNR. Dely Road/Lois Road, <br />1st Floor, Suite 104, Newlands, Pretoria, South Africa<br />tel: +27-845-105871<br /><strong>email: </strong><EMAIL> | <strong>www.awlo.org</strong></span>
<p><a href='http://twitter.com/awloint'><img src='http://awlo.org/email/social/twitter_circle_color-20.png' width='20px' height='20px' /></a><a href='http://facebook.com/awloint'><img src='http://awlo.org/email/social/facebook_circle_color-20.png' width='20px' height='20px' /></a><a href='https://plus.google.com/103912934440599693779'><img src='http://awlo.org/email/social/google_circle_color-20.png' width='20px' height='20px' /></a><a href='http://linkedin.com/company/awloint'><img src='http://awlo.org/email/social/linkedin_circle_color-20.png' width='20px' height='20px' /></a><a href='http://instagram.com/awloint'><img src='http://awlo.org/email/social/instagram_circle_color-20.png' width='20px' height='20px' /></a><a href='https://www.youtube.com/channel/UCevvBafqeTjY16qd2gbceJw'><img src='http://awlo.org/email/social/youtube_circle_color-20.png' width='20px' height='20px' /></a></p>
</td>
</tr>
<tr>
<td id='s3' style='padding-left: 20px; padding-right: 20px;' colspan='2' valign='bottom'>
<p style='font-family: Helvetica, sans-serif; text-align: center; font-size: 12px; line-height: 21px; color: #333;'><span style='margin-left: 4px;'><span style='opacity: 0.4; color: #333; font-size: 9px;'>Disclaimer: This message and any files transmitted with it are confidential and privileged. If you have received it in error, please notify the sender by return e-mail and delete this message from your system. If you are not the intended recipient you are hereby notified that any dissemination, copy or disclosure of this e-mail is strictly prohibited.</span></span></p>
</td>
</tr>
<tr>
<td style='border-bottom: 5px solid #940000; height: 5px; font-size: 7pt;' colspan='2' valign='top'> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>";<file_sep>/scripts/Newsletter.php
<?php
require '../sendpulse-rest-api-php/ApiInterface.php';
require '../sendpulse-rest-api-php/ApiClient.php';
require '../sendpulse-rest-api-php/Storage/TokenStorageInterface.php';
require '../sendpulse-rest-api-php/Storage/FileStorage.php';
require '../sendpulse-rest-api-php/Storage/SessionStorage.php';
require '../sendpulse-rest-api-php/Storage/MemcachedStorage.php';
require '../sendpulse-rest-api-php/Storage/MemcacheStorage.php';
use Sendpulse\RestApi\ApiClient;
use Sendpulse\RestApi\Storage\FileStorage;
/**
* This script is the Newsletter Class
*
* PHP version 7.2
*
* @category Newsletter_Class
* @package Newsletter_Class
* @author <NAME>,ST <<EMAIL>>
* @license MIT https://opensource.org/licenses/MIT
* @link https://stbensonimoh.com
*/
class Newsletter
{
/**
* Constructor function
*
* @param string $apiUserId The SendPulse UserID
* @param string $apiSecret The SendPUlse ApiSecret
*/
public function __construct($apiUserId, $apiSecret)
{
$this->SPApiClient = new ApiClient($apiUserId, $apiSecret, new FileStorage());
}
/**
* Add User to the SendPule mailing List
*
* @param string $bookID The BookID of the SendPulse mailing list
* @param array $emails The email and other variables to put in the list
*
* @return void
*/
public function insertIntoList($bookID, $emails)
{
$this->SPApiClient->addEmails($bookID, $emails);
}
}
|
9e7992898168c829098acd02fda5acbf60857f79
|
[
"PHP"
] | 3 |
PHP
|
awloint/ys-volunteer
|
86ea0c9a0564410edcb4db96e70aaaa7fb8cdc73
|
01c584a173385c79f923e430e6c03928dcc46dcb
|
refs/heads/master
|
<repo_name>anagrahovac/oisisi_studentskasluzba<file_sep>/StudentskaSluzba/src/view/TablePredmetiProfesora.java
package view;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableCellRenderer;
public class TablePredmetiProfesora extends JTable {
private static final long serialVersionUID = -6464471052766055117L;
public TablePredmetiProfesora(String id) {
this.setRowSelectionAllowed(true);
this.setColumnSelectionAllowed(true);
this.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
this.setModel(new AbstractTableModelPredmetiProfesora(id));
Font f = new Font("Dialog", Font.PLAIN, 14);
Color headerColor = new Color(143, 180, 255); //blue
this.setFont(f);
this.setRowHeight(25);
this.getTableHeader().setBackground(headerColor);
this.getTableHeader().setPreferredSize(new Dimension(0, 25));
}
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
Color color = new Color(245, 245, 245);
if (isRowSelected(row)) {
c.setBackground(color);
} else {
c.setBackground(Color.WHITE);
}
return c;
}
}<file_sep>/StudentskaSluzba/src/listeners/NewActionListener.java
package listeners;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import model.BazaPredmeta;
import view.MainFrame;
import view.NoviPredmetDialog;
import view.NoviProfesorDialog;
import view.NoviStudentDialog;
public class NewActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
int tab = MainFrame.getInstance().getActiveTab();
if (tab == 0) {
NoviStudentDialog nsd = new NoviStudentDialog();
nsd.setVisible(true);
}
if (tab == 1) {
NoviProfesorDialog npd = new NoviProfesorDialog();
npd.setVisible(true);
}
if (tab == 2) {
String staraSifra = BazaPredmeta.getInstance().staraSifra();
NoviPredmetDialog npd = new NoviPredmetDialog(MainFrame.getInstance(),staraSifra);
npd.setVisible(true);
}
}
}
<file_sep>/StudentskaSluzba/src/view/AbstractTableModelPredmeti.java
package view;
import model.*;
import javax.swing.table.AbstractTableModel;
public class AbstractTableModelPredmeti extends AbstractTableModel {
private static final long serialVersionUID = -2177631931847342087L;
public AbstractTableModelPredmeti() {}
@Override
public int getColumnCount() {
return BazaPredmeta.getInstance().getColumnCount();
}
@Override
public int getRowCount() {
return BazaPredmeta.getInstance().getPredmeti().size();
}
@Override
public Object getValueAt(int row, int column) {
return BazaPredmeta.getInstance().getValueAt(row, column);
}
@Override
public String getColumnName(int column) {
return BazaPredmeta.getInstance().getColumnName(column);
}
public Class<?> getColumnClass(int column) {
if(BazaPredmeta.getInstance().getPredmeti().size() == 0)
return Object.class;
return BazaPredmeta.getInstance().getValueAt(0, column).getClass();
}
}<file_sep>/StudentskaSluzba/src/view/IzmenaPredmetaDialog.java
package view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import controller.PredmetController;
import listeners.PredmetIzmenaKeyListener;
import model.BazaPredmeta;
import model.Predmet;
public class IzmenaPredmetaDialog extends JDialog{
private static final long serialVersionUID = 111473971714136217L;
private PredmetController controller;
private RowPanel pSifra;
private RowPanel pNaziv;
private RowPanel pGodinaStudija;
private RowPanel pBrojESPB;
private RowPanel pSemestar;
private JTextField txtProfesor;
private Predmet p;
private JButton btnPotvrdi = new JButton("Potvrdi");
private JButton btnOdbaci = new JButton("Odustani");
private JButton btnPlus;
private JButton btnMinus;
public IzmenaPredmetaDialog(String staraSifra) {
super(MainFrame.getInstance(), "Izmena predmeta", true);
setSize(500, 600);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(MainFrame.getInstance());
setResizable(false);
Color c = new Color(245,245,245);
setBackground(c);
PredmetIzmenaKeyListener keyListener = new PredmetIzmenaKeyListener(this);
controller = new PredmetController(this);
controller.getVal().setAllTrue();
JPanel informacije = new JPanel();
informacije.setBackground(c);
informacije.setLayout(new BoxLayout(informacije, BoxLayout.Y_AXIS));
p = BazaPredmeta.getInstance().predmetDateSifre(staraSifra);
pSifra = new RowPanel("Šifra predmeta*");
pSifra.getTextField().setToolTipText("Format: SBBB, npr: T123");
pSifra.getTextField().setText(p.getSifraPredmeta());
pSifra.getTextField().setName("txtSifra");
pSifra.getTextField().addKeyListener(keyListener);
pNaziv = new RowPanel("Naziv*");
pNaziv.getTextField().setText(p.getNazivPredmeta());
pNaziv.getTextField().setName("txtNaziv");
pNaziv.getTextField().addKeyListener(keyListener);
pGodinaStudija = new RowPanel("Godina studija*");
pGodinaStudija.getTextField().setText(Integer.toString(p.getGodinaStudija()));
pGodinaStudija.getTextField().setName("txtGodinaStudija");
pGodinaStudija.getTextField().addKeyListener(keyListener);
Color gray = new Color(245,245,245);
JPanel pProfesor = new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel lblProfesor = new JLabel("Profesor*");
Dimension lblDim = new Dimension(150, 30);
Font dialog = new Font("Dialog", Font.ITALIC, 14);
lblProfesor.setPreferredSize(lblDim);
lblProfesor.setFont(dialog);
txtProfesor = new JTextField();
txtProfesor.setName("txtProfesor");
txtProfesor.setText(p.getImePrezimeProfesora());
txtProfesor.setEditable(false);
txtProfesor.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
txtProfesor.setBackground(Color.white);
Dimension txtDim = new Dimension(180, 30);
Font dialog1 = new Font("Dialog", Font.PLAIN, 14);
txtProfesor.setPreferredSize(txtDim);
txtProfesor.setFont(dialog1);
btnPlus = new JButton("+");
Dimension btnDim = new Dimension(30,30);
Font dialog2 = new Font("Dialog", Font.BOLD, 14);
btnPlus.setPreferredSize(btnDim);
btnPlus.setFont(dialog2);
btnPlus.setBackground(Color.white);
btnPlus.setToolTipText("Dodaj profesora");
btnPlus.setBorder(BorderFactory.createLineBorder(Color.gray, 1));
if(txtProfesor.getText().isEmpty() || txtProfesor.getText() == null || txtProfesor.getText().equals("")) {
btnPlus.setEnabled(true);
} else {
btnPlus.setEnabled(false);
}
dodajListener(this, staraSifra);
btnMinus = new JButton("-");
btnMinus.setPreferredSize(btnDim);
btnMinus.setFont(dialog2);
btnMinus.setBackground(Color.white);
btnMinus.setToolTipText("Obriši profesora");
btnMinus.setBorder(BorderFactory.createLineBorder(Color.gray,1));
if(txtProfesor.getText().isEmpty() || txtProfesor.getText() == null || txtProfesor.getText().equals("")) {
btnMinus.setEnabled(false);
} else {
btnMinus.setEnabled(true);
}
ukloniProfesoraListener();
pProfesor.add(Box.createHorizontalStrut(20));
pProfesor.add(lblProfesor);
pProfesor.add(txtProfesor);
pProfesor.add(btnPlus);
pProfesor.add(btnMinus);
pProfesor.setBackground(gray);
pBrojESPB = new RowPanel("Broj ESPB bodova*");
pBrojESPB.getTextField().setText(Integer.toString(p.getBrojBodova()));
pBrojESPB.getTextField().setName("txtBrojESPB");
pBrojESPB.getTextField().addKeyListener(keyListener);
String[] semestar = { "letnji", "zimski"};
pSemestar = new RowPanel("Semestar*", semestar);
pSemestar.getComboBox().setSelectedIndex(p.getSemestar().ordinal());
informacije.add(Box.createVerticalStrut(30));
informacije.add(pSifra);
informacije.add(pNaziv);
informacije.add(pGodinaStudija);
informacije.add(pBrojESPB);
informacije.add(pSemestar);
informacije.add(pProfesor);
informacije.add(Box.createVerticalStrut(150));
JPanel buttons = new JPanel();
buttons.setBackground(c);
buttons.setLayout(new FlowLayout(FlowLayout.CENTER));
buttons.setPreferredSize(new Dimension(50, 50));
formatButton(btnPotvrdi, 1);
formatButton(btnOdbaci, 0);
btnPotvrdi.setToolTipText("Izmeni predmet");
btnOdbaci.setToolTipText("Odustani od izmene predmeta");
enablePotvrdi();
btnPotvrdi.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent arg0) {
if(btnPotvrdi.isEnabled()) {
boolean succ = controller.izmeniPredmet(BazaPredmeta.getInstance().pronadjiPredmet1(staraSifra));
if(succ == true) {
JOptionPane.showMessageDialog(null, "Predmet uspešno izmenjen.");
dispose();
}
else {
JOptionPane.showMessageDialog(null, "Šifra predmeta već postoji u bazi!");
}
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
if(btnPotvrdi.isEnabled()) {
btnPotvrdi.setBackground(new Color(228, 244, 255));
btnPotvrdi.setBorder(BorderFactory.createLineBorder(new Color(103, 140, 235), 1));
}
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
if(btnPotvrdi.isEnabled()) {
btnPotvrdi.setBorder(BorderFactory.createLineBorder(new Color(103, 140, 235), 2));
btnPotvrdi.setBackground(new Color(230,230,230));
}
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
btnOdbaci.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent arg0) {
Object[] daNe = {"Da", "Ne"};
int code = JOptionPane.showOptionDialog(null, "Da li ste sigurni da želite da odbacite izmene?", "Message", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, daNe, daNe[0]);
if (code == JOptionPane.YES_OPTION)
dispose();
}
@Override
public void mouseEntered(MouseEvent arg0) {
btnOdbaci.setBackground(new Color(228, 244, 255));
btnOdbaci.setBorder(BorderFactory.createLineBorder(new Color(103, 140, 235), 1));
}
@Override
public void mouseExited(MouseEvent arg0) {
btnOdbaci.setBackground(new Color(230,230,230));
btnOdbaci.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
buttons.add(btnPotvrdi);
buttons.add(Box.createHorizontalStrut(10));
buttons.add(btnOdbaci);
//buttons.add(Box.createHorizontalStrut(10));
informacije.add(buttons, BorderLayout.SOUTH);
this.add(informacije,BorderLayout.CENTER);
validate();
}
public void dodajListener(IzmenaPredmetaDialog i, String staraSifra) {
btnPlus.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
DodajProfesoraDialog dialog = new DodajProfesoraDialog(MainFrame.getInstance(), staraSifra, i);
dialog.setVisible(true);
}
});
}
private void ukloniProfesoraListener() {
btnMinus.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object[] opcije = {"Da", "Ne"};
int opcija = JOptionPane.showOptionDialog(MainFrame.getInstance(), "Da li ste sigurni da želite da uklonite profesora?",
"Uklanjanje profesora", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, opcije, opcije[1]);
if (opcija != JOptionPane.YES_OPTION) {
} else {
txtProfesor.setText("");
btnPlus.setEnabled(true);
btnMinus.setEnabled(false);
controller.ukloniProfesoraSaPredmeta(p.getSifraPredmeta(), p.getPredmetniProfesor().getBrojLicneKarte());
}
}
});
}
private void formatButton(JButton btn, int i) {
Dimension btnDim = new Dimension(100, 30);
Font f = new Font("Dialog", Font.PLAIN, 14);
Color g = new Color(230,230,230);
Color b = new Color(103, 140, 235);
btn.setPreferredSize(btnDim);
btn.setBackground(g);
btn.setFont(f);
if (i == 1) {
btn.setBorder(BorderFactory.createLineBorder(b, 2));
btn.setToolTipText("Sačuvaj unete podatke");
}
if (i == 0) {
btn.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
btn.setToolTipText("Odbaci unete podatke");
}
}
public void disablePotvrdi() {
btnPotvrdi.setEnabled(false);
btnPotvrdi.setForeground(new Color(150, 150, 150));
btnPotvrdi.setBackground(new Color(220, 220, 220));
btnPotvrdi.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
}
public void enablePotvrdi() {
btnPotvrdi.setEnabled(true);
btnPotvrdi.setBorder(BorderFactory.createLineBorder(new Color(103, 140, 235), 2));
btnPotvrdi.setBackground(new Color(230,230,230));
btnPotvrdi.setForeground(Color.BLACK);
}
public void azurirajPredmet(JTextField txt, Predmet p,IzmenaPredmetaDialog i) {
txt.setText(p.getImePrezimeProfesora());
if(txt.getText().isEmpty() || txt.getText() == null || txt.getText().equals("")) {
i.getBtnPlus().setEnabled(true);
} else {
i.getBtnPlus().setEnabled(false);
}
if(txt.getText().isEmpty() || txt.getText() == null || txt.getText().equals("")) {
i.getBtnMinus().setEnabled(false);
} else {
i.getBtnMinus().setEnabled(true);
}
}
public Predmet getP() {
return p;
}
public void setP(Predmet p) {
this.p = p;
}
public JTextField getTxtProfesor() {
return txtProfesor;
}
public void setTxtProfesor(JTextField txtProfesor) {
this.txtProfesor = txtProfesor;
}
public PredmetController getController() {
return controller;
}
public void setController(PredmetController controller) {
this.controller = controller;
}
public RowPanel getpSifra() {
return pSifra;
}
public void setpSifra(RowPanel pSifra) {
this.pSifra = pSifra;
}
public RowPanel getpNaziv() {
return pNaziv;
}
public void setpNaziv(RowPanel pNaziv) {
this.pNaziv = pNaziv;
}
public RowPanel getpGodinaStudija() {
return pGodinaStudija;
}
public void setpGodinaStudija(RowPanel pGodinaStudija) {
this.pGodinaStudija = pGodinaStudija;
}
public RowPanel getpBrojESPB() {
return pBrojESPB;
}
public void setpBrojESPB(RowPanel pBrojESPB) {
this.pBrojESPB = pBrojESPB;
}
public RowPanel getpSemestar() {
return pSemestar;
}
public void setpSemestar(RowPanel pSemestar) {
this.pSemestar = pSemestar;
}
public JButton getBtnPotvrdi() {
return btnPotvrdi;
}
public void setBtnPotvrdi(JButton btnPotvrdi) {
this.btnPotvrdi = btnPotvrdi;
}
public JButton getBtnOdbaci() {
return btnOdbaci;
}
public void setBtnOdbaci(JButton btnOdbaci) {
this.btnOdbaci = btnOdbaci;
}
public JButton getBtnPlus() {
return btnPlus;
}
public void setBtnPlus(JButton btnPlus) {
this.btnPlus = btnPlus;
}
public JButton getBtnMinus() {
return btnMinus;
}
public void setBtnMinus(JButton btnMinus) {
this.btnMinus = btnMinus;
}
}
<file_sep>/README.md
student 1: <NAME> (RA23/2018)
student 2: <NAME> (RA17/2018)
java 11.0.9 2020-10-20 LTS
eclipse 2020-09 (4.17.0)<file_sep>/StudentskaSluzba/src/view/AbstractTableModelListaPredmeta.java
package view;
import javax.swing.table.AbstractTableModel;
import model.BazaPredmeta;
import model.BazaStudenata;
public class AbstractTableModelListaPredmeta extends AbstractTableModel{
private static final long serialVersionUID = 1L;
private String indx;
public AbstractTableModelListaPredmeta(String i) {
// TODO Auto-generated constructor stub
this.indx = i;
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return BazaPredmeta.getInstance().getColumnCountListaPredmeta();
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
if(!(BazaStudenata.getInstance().studentDatogIndeksa(indx).getPredmetiZaDodavanje() == null))
return BazaStudenata.getInstance().studentDatogIndeksa(indx).getPredmetiZaDodavanje().size();
else
return -1;
}
@Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return BazaStudenata.getInstance().studentDatogIndeksa(indx).getValueAtListaPredmeta(arg0, arg1);
}
@Override
public String getColumnName(int column) {
return BazaPredmeta.getInstance().getColumnNameListaPredmeta(column);
}
}
<file_sep>/StudentskaSluzba/src/listeners/PredmetKeyListener.java
package listeners;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BorderFactory;
import javax.swing.JTextField;
import view.NoviPredmetDialog;
public class PredmetKeyListener implements KeyListener{
private NoviPredmetDialog npd;
public PredmetKeyListener(NoviPredmetDialog n) {
// TODO Auto-generated constructor stub
super();
this.npd = n;
}
@Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
JTextField txt = (JTextField) arg0.getComponent();
String val = txt.getText().trim();
boolean validno = false;
switch(txt.getName()) {
case "txtSifra":
validno = npd.getController().getVal().validirajSifru(val);
break;
case "txtNaziv":
validno = npd.getController().getVal().validirajNaziv(val);
break;
case "txtGodinaStudija":
validno = npd.getController().getVal().validirajGodinuStudija(val);
break;
case "txtBrojESPB":
validno = npd.getController().getVal().validirajBrojESPB(val);
break;
}
if (!validno) {
txt.setBorder(null);
txt.setBorder(BorderFactory.createLineBorder(new Color(221,119,119)));
txt.setForeground(new Color(221,119,119));
npd.disablePotvrdi();
} else {
txt.setForeground(Color.black);
txt.setBorder(BorderFactory.createLineBorder(Color.gray));
}
if(npd.getController().getVal().validirajPredmet()) {
npd.enablePotvrdi();
}
else {
npd.disablePotvrdi();
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
<file_sep>/StudentskaSluzba/src/view/AbstractTableModelPolozeniIspiti.java
package view;
import javax.swing.table.AbstractTableModel;
import model.BazaStudenata;
public class AbstractTableModelPolozeniIspiti extends AbstractTableModel{
private static final long serialVersionUID = -2685393268849549750L;
private String indx;
public AbstractTableModelPolozeniIspiti(String i) {
// TODO Auto-generated constructor stub
this.indx = i;
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return BazaStudenata.getInstance().getColumnCountPolozeni();
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
if(!(BazaStudenata.getInstance().studentDatogIndeksa(indx).getSpisakPolozenihIspita() == null))
return BazaStudenata.getInstance().studentDatogIndeksa(indx).getSpisakPolozenihIspita().size();
else
return -1;
}
@Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return BazaStudenata.getInstance().studentDatogIndeksa(indx).getValueAtPolozeni(arg0, arg1);
}
@Override
public String getColumnName(int arg0) {
return BazaStudenata.getInstance().getColumnNamesPolozeni(arg0);
}
}
<file_sep>/StudentskaSluzba/src/view/MyToolbar.java
package view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import listeners.DeleteActionListener;
import listeners.EditActionListener;
import listeners.NewActionListener;
import listeners.SearchActionListener;
import javax.swing.JTextField;
public class MyToolbar extends JToolBar {
private static final long serialVersionUID = -3666207502033139205L;
private JTextField searchBox = new JTextField();
public MyToolbar() {
super(SwingConstants.HORIZONTAL);
Color c = new Color(245, 245, 245); //svetlo siva
//(255, 255, 255); //bela
setBackground(c);
setBorder(BorderFactory.createLineBorder(new Color(255,255,255)));
Dimension btnDim = new Dimension(30, 30);
//panel sa alatima iz toolbara
JPanel panTools = new JPanel(new FlowLayout(FlowLayout.LEFT));
panTools.setBackground(c);
JButton btnNew = new JButton();
btnNew.setToolTipText("New");
btnNew.setIcon(new ImageIcon("toolbar_images" + File.separator + "new.png"));
btnNew.setPreferredSize(btnDim);
btnNew.setBackground(c);
btnNew.setBorderPainted(isDisplayable());
panTools.add(btnNew);
JButton btnEdit = new JButton();
btnEdit.setToolTipText("Edit");
btnEdit.setIcon(new ImageIcon("toolbar_images" + File.separator + "edit.png"));
btnEdit.setPreferredSize(btnDim);
btnEdit.setBackground(c);
btnEdit.setBorderPainted(isDisplayable());
panTools.add(btnEdit);
JButton btnDelete = new JButton();
btnDelete.setToolTipText("Delete");
btnDelete.setIcon(new ImageIcon("toolbar_images" + File.separator + "delete.png"));
btnDelete.setPreferredSize(btnDim);
btnDelete.setBackground(c);
btnDelete.setBorderPainted(isDisplayable());
panTools.add(btnDelete);
//akcije
btnNew.addActionListener(new NewActionListener());
btnDelete.addActionListener(new DeleteActionListener());
btnEdit.addActionListener(new EditActionListener());
add(panTools);
//panel sa komponentama za pretrazivanje
JPanel panSearch = new JPanel(new FlowLayout(FlowLayout.RIGHT));
panSearch.setBackground(c);
//searchBox = new JTextField();
searchBox.setPreferredSize(new Dimension(400, 30));
panSearch.add(searchBox);
JButton btnSearch = new JButton();
btnSearch.setToolTipText("Search");
btnSearch.setIcon(new ImageIcon("toolbar_images" + File.separator + "search.png"));
btnSearch.setPreferredSize(btnDim);
btnSearch.setBackground(c);
btnSearch.setBorderPainted(isDisplayable());
panSearch.add(btnSearch);
SearchActionListener sal = new SearchActionListener(this);
searchBox.addActionListener(sal);
btnSearch.addActionListener(sal);
add(panSearch);
validate();
}
public String getEntry() {
return searchBox.getText();
}
}
<file_sep>/StudentskaSluzba/src/view/IzmenaProfesoraDialog.java
package view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.time.format.DateTimeFormatter;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import controller.ProfesorController;
import listeners.ProfesorIzmenaKeyListener;
import model.BazaPredmeta;
import model.BazaProfesora;
import model.Profesor;
public class IzmenaProfesoraDialog extends JDialog {
private static final long serialVersionUID = 415279348790456678L;
private Profesor profesor;
private ProfesorController controller;
private JTabbedPane tabbedPane = new JTabbedPane();
private RowPanel pIme;
private RowPanel pPrezime;
private RowPanel pDatum;
private RowPanel pAdresaStan;
private RowPanel pTelefon;
private RowPanel pEmail;
private RowPanel pAdresaKancelarija;
private RowPanel pID;
private RowPanel pTitula;
private RowPanel pZvanje;
private JButton btnPotvrdi = new JButton("Potvrdi");
private JButton btnOdbaci = new JButton("Odustani");
JButton btnDodajPredmet = new JButton("Dodaj");
JButton btnUkloniPredmet = new JButton("Ukloni");
private TablePredmetiProfesora predmetiProfesora;
public IzmenaProfesoraDialog(String id) {
super(MainFrame.getInstance(), "Izmena profesora", true);
this.setSize(900, 600);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setLocationRelativeTo(MainFrame.getInstance());
this.setResizable(false);
this.getContentPane().setBackground(Color.WHITE);
controller = new ProfesorController(this);
controller.getValidacija().setAllTrue();
int redniBr = BazaProfesora.getInstance().pronadjiProfesora(id);
profesor = BazaProfesora.getInstance().getProfesori().get(redniBr);
Font f = new Font("Dialog", Font.PLAIN, 14);
this.tabbedPane.setBackground(Color.WHITE);
this.tabbedPane.setFont(f);
JPanel infoTab = new JPanel();
JPanel predmetiTab = new JPanel();
Color gray = new Color(245,245,245);
infoTab.setBackground(gray);
BoxLayout box = new BoxLayout(infoTab, BoxLayout.Y_AXIS);
infoTab.setLayout(box);
this.add(infoTab, BorderLayout.CENTER);
ProfesorIzmenaKeyListener pl = new ProfesorIzmenaKeyListener(this);
pIme = new RowPanel("Ime*");
pIme.getTextField().setName("txtIme");
pIme.getTextField().setText(profesor.getIme());
pIme.getTextField().addKeyListener(pl);
pPrezime = new RowPanel("Prezime*");
pPrezime.getTextField().setName("txtPrezime");
pPrezime.getTextField().setText(profesor.getPrezime());
pPrezime.getTextField().addKeyListener(pl);
pDatum = new RowPanel("Datum rodjenja*");
pDatum.getTextField().setName("txtDatum");
pDatum.getTextField().setText(profesor.getDatumRodjenja().format(DateTimeFormatter.ofPattern("dd.MM.yyyy.")));
pDatum.getTextField().addKeyListener(pl);
pDatum.getTextField().setToolTipText("Format: dd.mm.yyyy.");
pAdresaStan = new RowPanel("Adresa stanovanja*");
pAdresaStan.getTextField().setName("txtAdresaStan");
pAdresaStan.getTextField().setText(profesor.getAdresaStanovanja());
pAdresaStan.getTextField().addKeyListener(pl);
pTelefon = new RowPanel("Kontakt telefon*");
pTelefon.getTextField().setName("txtTelefon");
pTelefon.getTextField().setText(profesor.getKontaktTelefon());
pTelefon.getTextField().addKeyListener(pl);
pEmail = new RowPanel("E-mail adresa*");
pEmail.getTextField().setName("txtEmail");
pEmail.getTextField().setText(profesor.getEmailAdresa());
pEmail.getTextField().addKeyListener(pl);
pAdresaKancelarija = new RowPanel("Adresa kancelarije*");
pAdresaKancelarija.getTextField().setName("txtAdresaKancelarija");
pAdresaKancelarija.getTextField().setText(profesor.getAdresaKancelarije());
pAdresaKancelarija.getTextField().addKeyListener(pl);
pID = new RowPanel("Broj lične karte*");
pID.getTextField().setName("txtID");
pID.getTextField().setText(profesor.getBrojLicneKarte());
pID.getTextField().addKeyListener(pl);
String[] titule = { "Doktor", "Profesor doktor", };
pTitula = new RowPanel("Titula*", titule);
pTitula.getComboBox().setSelectedIndex(profesor.getTitula().ordinal());
String[] zvanja = {"Docent", "Vanredni profesor", "Redovni profesor", };
pZvanje = new RowPanel("Zvanje*", zvanja);
pZvanje.getComboBox().setSelectedIndex(profesor.getZvanje().ordinal());
infoTab.add(Box.createVerticalStrut(30));
infoTab.add(pIme);
infoTab.add(pPrezime);
infoTab.add(pDatum);
infoTab.add(pAdresaStan);
infoTab.add(pTelefon);
infoTab.add(pEmail);
infoTab.add(pAdresaKancelarija);
infoTab.add(pID);
infoTab.add(pTitula);
infoTab.add(pZvanje);
infoTab.add(Box.createVerticalStrut(30));
//panel pBotom za dugmad
JPanel pBottom = new JPanel();
pBottom.setPreferredSize(new Dimension(70, 70));
pBottom.setBackground(gray);
pBottom.setLayout(new FlowLayout(FlowLayout.LEFT));
pBottom.setPreferredSize(new Dimension(50, 50));
infoTab.add(pBottom, BorderLayout.SOUTH);
this.formatButton(btnPotvrdi, 1);
this.enablePotvrdi();
pBottom.add(Box.createHorizontalStrut(190));
pBottom.add(btnPotvrdi);
pBottom.add(Box.createHorizontalStrut(10));
this.dodajListenerPotvrdi();
this.formatButton(btnOdbaci, 0);
pBottom.add(btnOdbaci);
this.dodajListenerOdbaci();
//tab predmeti
predmetiTab.setBackground(Color.WHITE);
//predmetiTab.setBackground(gray);
JPanel pTop = new JPanel();
pTop.setLayout(new BorderLayout());
formatButton(btnDodajPredmet, 3);
dodajListenerDodajPredmet(this);
formatButton(btnUkloniPredmet, 2);
dodajListenerUkloniPredmet(this,id);
pTop.setLayout(new FlowLayout(FlowLayout.CENTER));
pTop.setPreferredSize(new Dimension(850, 50));
pTop.setBackground(Color.WHITE);
//pTop.setBackground(gray);
pTop.add(btnDodajPredmet);
pTop.add(Box.createHorizontalStrut(10));
pTop.add(btnUkloniPredmet);
pTop.add(Box.createHorizontalStrut(10));
predmetiProfesora = new TablePredmetiProfesora(id);
updatePredmetiProfesoraTable();
predmetiTab.add(pTop, BorderLayout.NORTH);
JScrollPane scroll = new JScrollPane(predmetiProfesora);
scroll.setPreferredSize(new Dimension(850, 450));
scroll.getViewport().setBackground(Color.WHITE);
predmetiTab.add(scroll, BorderLayout.CENTER);
tabbedPane.addTab("Info", null, infoTab, "Informacije o profesoru");
tabbedPane.addTab("Predmeti", null, predmetiTab, "Predmeti na kojima je angažovan");
this.add(tabbedPane);
validate();
}
private void dodajListenerPotvrdi() {
btnPotvrdi.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent arg0) {
if(btnPotvrdi.isEnabled()) {
boolean succ = controller.izmeniProfesora(BazaProfesora.getInstance().pronadjiProfesora(profesor.getBrojLicneKarte()));
if(succ == true) {
JOptionPane.showMessageDialog(null, "Profesor uspešno izmenjen u bazi.");
dispose();
}
else {
JOptionPane.showMessageDialog(null, "Broj lične karte već postoji u bazi!");
}
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
if(btnPotvrdi.isEnabled()) {
btnPotvrdi.setBackground(new Color(228, 244, 255));
btnPotvrdi.setBorder(BorderFactory.createLineBorder(new Color(103, 140, 235), 1));
}
}
@Override
public void mouseExited(MouseEvent arg0) {
if(btnPotvrdi.isEnabled()) {
btnPotvrdi.setBorder(BorderFactory.createLineBorder(new Color(103, 140, 235), 2));
btnPotvrdi.setBackground(new Color(230,230,230));
}
}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
});
}
private void dodajListenerOdbaci() {
btnOdbaci.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent arg0) {
dispose();
}
@Override
public void mouseEntered(MouseEvent arg0) {
btnOdbaci.setBackground(new Color(228, 244, 255));
btnOdbaci.setBorder(BorderFactory.createLineBorder(new Color(103, 140, 235), 1));
}
@Override
public void mouseExited(MouseEvent arg0) {
btnOdbaci.setBackground(new Color(230,230,230));
btnOdbaci.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
});
}
private void dodajListenerDodajPredmet(IzmenaProfesoraDialog ipd) {
btnDodajPredmet.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent arg0) {
DodajPredmetProfesoruDialog dp = new DodajPredmetProfesoruDialog(ipd, profesor.getBrojLicneKarte());
dp.setVisible(true);
}
@Override
public void mouseEntered(MouseEvent arg0) {
btnDodajPredmet.setBackground(new Color(228, 244, 255));
btnDodajPredmet.setBorder(BorderFactory.createLineBorder(new Color(103, 140, 235), 1));
}
@Override
public void mouseExited(MouseEvent arg0) {
btnDodajPredmet.setBackground(new Color(230,230,230));
btnDodajPredmet.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
});
}
public void dodajListenerUkloniPredmet(IzmenaProfesoraDialog i, String id) {
btnUkloniPredmet.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int i = predmetiProfesora.getSelectedRow();
if(i == -1) {
JOptionPane.showMessageDialog(null, "Niste selektovali predmet koji želite da uklonite.");
return;
} else {
Object[] daNe = {"Da", "Ne"};
int code = JOptionPane.showOptionDialog(MainFrame.getInstance(), "Da li ste sigurni da želite da uklonite predmet profesoru?",
"Ukloni predmet", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, daNe, daNe[0]);
if (code != JOptionPane.YES_OPTION) {
} else {
BazaPredmeta.getInstance().predmetDateSifre(getSifraListaPredmeta()).ukloniPredmetnogProfesora();
BazaProfesora.getInstance().profesorDateLicneKarte(id).ukloniPredmet(getSifraListaPredmeta());
updatePredmetiProfesoraTable();
JOptionPane.showMessageDialog(null, "Predmet uklonjen profesoru.");
}
}
}
});
}
public void updatePredmetiProfesoraTable() {
AbstractTableModelPredmetiProfesora model = (AbstractTableModelPredmetiProfesora) predmetiProfesora.getModel();
model.fireTableDataChanged();
validate();
}
private void formatButton(JButton btn, int i) {
Dimension btnDim = new Dimension(100, 30);
Font f = new Font("Dialog", Font.PLAIN, 14);
Color g = new Color(230,230,230);
Color b = new Color(103, 140, 235);
btn.setPreferredSize(btnDim);
btn.setBackground(g);
btn.setFont(f);
if (i == 3) {
btn.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
btn.setToolTipText("Dodaj predmet profesoru");
}
if (i == 2) {
btn.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
btn.setToolTipText("Ukloni predmet sa profesora");
}
if (i == 1) {
btn.setBorder(BorderFactory.createLineBorder(b, 2));
btn.setToolTipText("Sačuvaj unete podatke");
}
if (i == 0) {
btn.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
btn.setToolTipText("Odbaci unete podatke");
}
}
public void disablePotvrdi() {
btnPotvrdi.setEnabled(false);
btnPotvrdi.setForeground(new Color(150, 150, 150));
btnPotvrdi.setBackground(new Color(220, 220, 220));
btnPotvrdi.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
}
public void enablePotvrdi() {
btnPotvrdi.setEnabled(true);
btnPotvrdi.setBorder(BorderFactory.createLineBorder(new Color(103, 140, 235), 2));
btnPotvrdi.setBackground(new Color(230,230,230));
btnPotvrdi.setForeground(Color.BLACK);
}
public String getSifraListaPredmeta() {
int i = predmetiProfesora.getSelectedRow();
if(i != -1) {
return (String) predmetiProfesora.getValueAt(i, 0);
} else {
return "";
}
}
public RowPanel getpIme() {
return pIme;
}
public RowPanel getpPrezime() {
return pPrezime;
}
public RowPanel getpDatum() {
return pDatum;
}
public RowPanel getpAdresaStan() {
return pAdresaStan;
}
public RowPanel getpTelefon() {
return pTelefon;
}
public RowPanel getpEmail() {
return pEmail;
}
public RowPanel getpAdresaKancelarija() {
return pAdresaKancelarija;
}
public RowPanel getpID() {
return pID;
}
public RowPanel getpTitula() {
return pTitula;
}
public RowPanel getpZvanje() {
return pZvanje;
}
public JButton getBtnPotvrdi() {
return btnPotvrdi;
}
public JButton getBtnOdbaci() {
return btnOdbaci;
}
public ProfesorController getController() {
return controller;
}
}
<file_sep>/StudentskaSluzba/src/listeners/PredmetIzmenaKeyListener.java
package listeners;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BorderFactory;
import javax.swing.JTextField;
import controller.Validacija;
import view.IzmenaPredmetaDialog;
public class PredmetIzmenaKeyListener implements KeyListener{
private IzmenaPredmetaDialog ipd;
public PredmetIzmenaKeyListener(IzmenaPredmetaDialog i) {
super();
this.ipd = i;
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
JTextField txt = (JTextField) e.getComponent();
String val = txt.getText().trim();
Validacija v = ipd.getController().getVal();
boolean validno = false;
switch(txt.getName()) {
case "txtSifra":
validno = ipd.getController().getVal().validirajSifru(val);
break;
case "txtNaziv":
validno = ipd.getController().getVal().validirajNaziv(val);
break;
case "txtGodinaStudija":
validno = ipd.getController().getVal().validirajGodinuStudija(val);
break;
case "txtBrojESPB":
validno = ipd.getController().getVal().validirajBrojESPB(val);
break;
}
if (!validno) {
ipd.disablePotvrdi();
txt.setBorder(null);
txt.setBorder(BorderFactory.createLineBorder(new Color(221,119,119)));
txt.setForeground(new Color(221,119,119));
} else {
txt.setForeground(Color.black);
txt.setBorder(BorderFactory.createLineBorder(Color.gray));
}
if(v.validirajPredmet() == true) {
ipd.enablePotvrdi();
}
else {
ipd.disablePotvrdi();
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
<file_sep>/StudentskaSluzba/src/view/AboutDialog.java
package view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class AboutDialog extends JDialog{
private static final long serialVersionUID = 8956415914908634115L;
public AboutDialog(JFrame parent, String title) {
super(parent,"About");
setLayout(new BorderLayout());
Font f = new Font("Dialog",Font.ITALIC+Font.BOLD,14);
Font f1 = new Font("Dialog",Font.PLAIN,14);
Color c = Color.white;
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int sizeHeight = (screenSize.height * 3 / 4) * 3/4;
int sizeWidth = (screenSize.width * 3 / 4) / 2;
setSize(sizeWidth, sizeHeight);
setLocationRelativeTo(parent);
setBackground(c);
JPanel header = new JPanel(new FlowLayout(FlowLayout.LEADING,5,10));
header.setBackground(c);
this.add(header,BorderLayout.NORTH);
JPanel background = new JPanel(new FlowLayout(FlowLayout.LEADING,5,10));
background.setBackground(c);
this.add(background, BorderLayout.CENTER);
JLabel lblHeader = new JLabel("Verzija aplikacije: 2020-09 (4.17.0)");
lblHeader.setFont(f);
JTextArea koriscenje = new JTextArea();
koriscenje.setText(" Pred vama se nalazi aplikacija koja predstavlja studentsku službu Fakulteta "
+ "Tehničkih Nauka u Novom Sadu. Studentska služba rukuje bazom studenata, "
+ "profesora i predmeta. \n\n"
+ "Biografija studenta 1:\n"
+ "<NAME> Aleksić rođena je 14. oktobra 1999. godine u Zrenjaninu. Od malena je zainteresovana za muziku i pevanje i do svoje "
+ "četrnaeste godine učestvovala je u raznim priredbama sa svojom osnovnom školom \"<NAME>\". Godine 2014. upisuje Zrenjaninsku "
+ "gimnaziju na prirodno-matematički smer i \"baca\" se na prirodne nauke. Sa odličnim uspehom završava srednju školu i upisuje "
+ "Fakultet tehničkih nauka u Novom Sadu, smer Računarstvo i automatika, gde dalji život staje."
+ "\n\n"
+ "Biografija studenta 2:\n"
+ "<NAME> je rođena 10. septembra 1999. godine u Novom Sadu. Osnovnu školu \"<NAME>\" u Veterniku je završila 2014. "
+ "i iste godine se upisuje na priridno-matematički smer u Gimnaziji \"<NAME>\". Srednju školu završava 2018. i "
+ "upisuje se na Fakultet tehničkih nauka Univerziteta Novi Sad, smer Računarstvo i automatika. Interesuje se za astronomiju i "
+ "fotografiju, a slobodno vreme voli da provodi sa prijateljima, u prirodi ili čitajući knjige. Ima četiri mačke i dva psa, ali "
+ "nije toliko strašno kao što možda zvuči jer ima dvorište."
);
koriscenje.setLineWrap(true);
koriscenje.setFont(f1);
koriscenje.setOpaque(true);
koriscenje.setEditable(false);
header.setBackground(c);
koriscenje.setBackground(c);
header.add(lblHeader);
background.add(koriscenje);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane,BorderLayout.CENTER);
scrollPane.setViewportView(koriscenje);
}
}
<file_sep>/StudentskaSluzba/src/listeners/StudentKeyListener.java
package listeners;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.BorderFactory;
import javax.swing.JTextField;
import view.NoviStudentDialog;
public class StudentKeyListener implements KeyListener{
private NoviStudentDialog nsd;
public StudentKeyListener (NoviStudentDialog n) {
super();
this.nsd = n;
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
JTextField txt = (JTextField) e.getComponent();
String val = txt.getText().trim();
boolean validno = false;
switch(txt.getName()) {
case "txtIme":
validno = nsd.getController().getValidacija().validirajIme(val);
break;
case "txtPrezime":
validno = nsd.getController().getValidacija().validirajPrezime(val);
break;
case "txtDatumRodjenja":
validno = nsd.getController().getValidacija().validirajDatum(val);
break;
case "txtAdresaStanovanja":
validno = nsd.getController().getValidacija().validirajAdresuStanovanja(val);
break;
case "txtBrojTelefona":
validno = nsd.getController().getValidacija().validirajTelefon(val);
break;
case "txtEMailAdresa":
validno = nsd.getController().getValidacija().validirajEmail(val);
break;
case "txtBrojIndexa":
validno = nsd.getController().getValidacija().validirajBrojIndeksa(val);
break;
case "txtGodinaUpisa":
validno = nsd.getController().getValidacija().validirajGodinuUpisa(val);
break;
}
if (!validno) {
txt.setBorder(null);
txt.setBorder(BorderFactory.createLineBorder(new Color(221,119,119)));
txt.setForeground(new Color(221,119,119));
nsd.disablePotvrdi();
} else {
txt.setForeground(Color.black);
txt.setBorder(BorderFactory.createLineBorder(Color.gray));
}
if(nsd.getController().getValidacija().validirajStudenta()) {
nsd.enablePotvrdi();
}
else {
nsd.disablePotvrdi();
}
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
|
d27a4ac1aa0adeb060a083eb61f5ec65cf9b921e
|
[
"Markdown",
"Java"
] | 13 |
Java
|
anagrahovac/oisisi_studentskasluzba
|
45e01fab9b4d7529e887594cbad90ea0b39a74e5
|
13683b100f140a1c3caad65c20bde8071b173732
|
refs/heads/master
|
<file_sep>package com.bl.censusanalyser;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import java.io.IOException;
import java.io.Reader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Iterator;
public class CensusAnalyzer {
public int loadIndiaCensusData(String csvFilePath) {
Reader reader = null;
try {
reader = Files.newBufferedReader(Paths.get(csvFilePath));
CsvToBean<IndiaCensusCSV> csvToBean = new CsvToBeanBuilder<IndiaCensusCSV>(reader)
.withType(IndiaCensusCSV.class)
.withIgnoreLeadingWhiteSpace(true)
.build();
Iterator<IndiaCensusCSV> iterator = csvToBean.iterator();
int numOfEntries = 0;
while (iterator.hasNext()) {
numOfEntries++;
iterator.next();
}
return numOfEntries;
} catch (
IOException e) {
System.out.println(e);
}
return 0;
}
}<file_sep>package com.bl.censusanalyser;
import org.junit.Assert;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.IOException;
public class CensusAnalyserTest {
private String INDIA_CENSUS_CSV_FILE_PATH = "./src/main/resources/IndiaStateCensusData.csv";
private String INDIA_STATE_CSV_FILE_PATH = "./src/main/resources/IndiaStateCode.csv";
private String INIDAN_CENSUS_WrongCSV_FILE_PATH = "./src/main/resources/IndiaStateCensusData.csv";
@Test
public void givenIndianCensusCSVFIle_WhenLoad_ShouldReturnCorrectRecords() throws CensusAnalyserException {
CensusAnalyzer censusAnalyzer = new CensusAnalyzer();
int count = censusAnalyzer.loadIndiaCensusData(INDIA_CENSUS_CSV_FILE_PATH);
Assert.assertEquals(29, count);
}
@Test
public void givenIndianCensusWrongCSVFile_WhenLoad_ShouldReturnException() {
try {
CensusAnalyzer censusAnalyser = new CensusAnalyzer();
ExpectedException exceptionRule = ExpectedException.none();
exceptionRule.expect(CensusAnalyserException.class);
censusAnalyser.loadIndiaCensusData(INIDAN_CENSUS_WrongCSV_FILE_PATH);
} catch (CensusAnalyserException e) {
Assert.assertEquals(e.type, CensusAnalyserException.ExceptionType.CENSUS_FILE_INCORRECT);
e.printStackTrace();
}
}
}
|
bcd8a72f2c68abab6f19a68106a17a019920c80b
|
[
"Java"
] | 2 |
Java
|
kalevishal/IndainCensusAnalyser
|
c55e65df8edc0dce6e678e4be477bc7f039abced
|
10529aeffc6a5b0009ddd9659ad46abaf9e2c4e1
|
refs/heads/master
|
<repo_name>ashokios/TestingRepo<file_sep>/Registration/Modal/ShareMessageHeader.h
//
// ShareMessageHeader.h
// VTLogin
//
// Created by <NAME> on 17/04/14.
// Copyright (c) 2014 valvirt. All rights reserved.
//
#ifndef VTLogin_ShareMessageHeader_h
#define VTLogin_ShareMessageHeader_h
#define SHARE_FB_MESSAGE @"This is my test message to share on facebook."
#define SHARE_FB_URL @"http://www.valvirttechnologies.com"
#define SHARE_FB_IMAGE @""
#define SHARE_TWITTER_MESSAGE @"This is my test message to share on facebook."
#define SHARE_TWITTER_URL @"http://www.valvirttechnologies.com"
#define SHARE_TWITTER_IMAGE @""
#endif
<file_sep>/Registration/Modal/VVTWebServiceURLs.h
//
// VVTWebServiceURLs.h
// Registration
//
// Created by <NAME> on 23/04/14.
// Copyright (c) 2014 ValvirtTechnologies. All rights reserved.
//
#ifndef Registration_VVTWebServiceURLs_h
#define Registration_VVTWebServiceURLs_h
#define USER_LOGIN_WITH_FACEBOOK @"user_facebook_login.php"
#define USER_REGISTRATION_WITH_EMAIL @"user_registration.php"
#define FETCH_ALL_INTERESTS @"registration_interests_list.php"
#endif
|
025ca4f674e883d686736d25ec804c38f451172a
|
[
"C"
] | 2 |
C
|
ashokios/TestingRepo
|
09c369f5155600fa45fa7549896cafbb52b22012
|
ad2a4f7abbba547cfad716ed00617fd2bb5db8da
|
refs/heads/master
|
<file_sep>interface RootState {
inc: IncomeState,
exp: ExpensesState,
}
interface IncomeState {
salary: number,
married: boolean,
taxRate: number,
state: string,
deductions: number,
stdDeduct: boolean,
retireContributions: number,
retireRate: number,
retireRateOf: number,
netIncome: number,
effectiveTaxRate: number,
}
interface ExpensesState {
homeowner: booleanB,
rent: number,
rentInsurance: number,
utilities: number,
groceries: number,
misc: number,
mortgagePay: number,
mortgageRate: number,
propertyValue: number,
hoaFees: number,
hoInsurance: number,
downPayment: number,
mortgageLength: number,
pmiRate: number,
}
interface taxBracket {
maxIncome: number
rate: number
maxInBracket: number
}
interface StateTaxes {
[key: string]: {state: string, rate: number}
}
interface TaxInputs {
income: number,
state: string,
taxRate: number,
deductions: number,
retireContributions: number,
}
interface PropertyInputs {
propertyValue: number,
state: string,
}
interface MortgageInputs {
propertyValue: number,
propertyTax: number,
mortgageRate: number,
downPayment: number,
mortgageLength: number,
pmiRate: number,
hoaFees: number,
}
interface SavingsInputs {
netIncome: number,
homeowner: boolean,
monthlyPropertyTax: number,
mortgagePay: number,
hoaFees: number,
rent: number,
rentInsurance: number,
utilities: number,
groceries: number,
misc: number,
}
|
035b0f4049e9af4f18850eacf5e9644f065d3d2e
|
[
"TypeScript"
] | 1 |
TypeScript
|
Teesh/Personal_Finance_App
|
58f619784a9a7359ebb14b1f20d5f3e48ec8141c
|
acea437f64bb151e5878c9c10c7c659cbf46c56b
|
refs/heads/master
|
<repo_name>katlarusse/KatLivraison<file_sep>/src/main/java/org/formation/jsf/validator/EmailValidator.java
package org.formation.jsf.validator;
import java.util.ResourceBundle;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
@FacesValidator
public class EmailValidator implements Validator {
public String email;
@Override
public void validate(FacesContext facesContext, UIComponent arg1, Object arg2) throws ValidatorException {
}
}
<file_sep>/resources/i18n/labels.properties
appli=Student Tracker App
uni=Licorne Université
action.ajouterEtudiant=Ajouter un étudiant
action.cancel=Annuler
action.update=Mettre à jour
action.delete=Effacer
action.save=Sauvegarder
action.deconnecter=Se déconnecter
action.entrer=Entrer
action.inscrire=S'inscrire
action.save=Enregistrer
action.retour=Retour à la liste principale
accueil.welcome=Bienvenue
accueil.alreadyMembre=Déjà membre ?
accueil.login=Identifiez vous
accueil.createMembre = Créer un compte
accueil.notAlreadyMembre=Sinon rejoignez nous et :
membre.login=Login
membre.logout=Déconnexion
membre.password=<PASSWORD>
membre.nom=Nom
membre.prenom=Prénom
membre.email=Adresse e-mail
membre.action=Action
required.nom=Votre nom est obligatoire
required.prenom=Votre prenom est obligatoire
required.email=Votre adresse mail est obligatoire
required.length=Ce champ doit faire au moins 3 lettres de long
invalid.email=Ceci n'est pas une adresse mail valide
membre.age=Age
membre.genre=Genre
membre.genre.femme=Femme
membre.genre.homme=Homme
message.auteur=Auteur
message.date=Date
message.sujet=Sujet
topic=Thème
topic.description=Description
topic.titre=Titre
topics.titre=Liste des thèmes
error.duplicateLogin=Le login existe déjà
error.prohibitedWords=Ce thème est interdit<file_sep>/resources/i18n/labels_en.properties
appli=Appli suivi étudiants
uni=Unicorn University
action.ajouterEtudiant=Add a new student
action.cancel=Cancel
action.update=Update
action.delete=Delete
action.save=Save
action.deconnecter=Logout
action.entrer=Login
action.inscrire=Register
action.save=Save
action.retour=Return to main list
accueil.welcome=Welcome
accueil.alreadyMembre=Already registered ?
accueil.login=Please fill your login and password
accueil.createMembre = Register
accueil.notAlreadyMembre=Otherwise, just join us and :
membre.login=Login
membre.logout=Logout
membre.password=<PASSWORD>
membre.nom=Last Name
membre.prenom=First Name
membre.email=E-mail address
membre.action=Action
membre.age=Age
membre.genre=Sex
membre.genre.femme=Female
membre.genre.homme=Male
message.auteur=Author
message.date=Date
message.sujet=Subject
required.nom=Your last name is required
required.prenom=Your first name is required
required.email=Your e-mail address is required
required.length=This field must be at least 3 letters long
invalid.email=This is an invalid e-mail format
topic=Topic
topic.description=Description
topic.titre=Title
topics.titre=List of topics
error.duplicateLogin=This login already exists, please choose another one
error.prohibitedWords=This topic is not allowed
|
8108a56bcc82e4ef7983ca692efe6f2408c6aabd
|
[
"Java",
"INI"
] | 3 |
Java
|
katlarusse/KatLivraison
|
d8c7f8382193212b2755df275fa00911d5c41a57
|
f793df3c8b357d5ef0d2d90fd79d7e212f86b4c7
|
refs/heads/master
|
<file_sep>const express = require('express');
const { MongoClient } = require('mongodb');
const secrets = require('./secrets');
const app = express();
const uri = `mongodb+srv://${secrets.username}:${secrets.password}@${secrets.server}/test?retryWrites=true&w=majority`;
const client = MongoClient(uri);
function getRoot(req, res) {
res.end('Hello World!');
}
async function getNumber(req, res) {
const raw = parseInt(req.params.id, 10);
let formatted = raw.toString();
if (raw < 10) {
formatted = `00${formatted}`;
} else if (raw < 100) {
formatted = `0${formatted}`;
}
const query = { number: formatted };
const result = await client.db('monDb').collection('monCollection').findOne(query);
res.end(JSON.stringify(result));
}
async function getSearch(req, res) {
const { term } = req.params;
let query = { name: term };
let result = await client.db('monDb').collection('monCollection').find(query).toArray();
query = { number: term };
result = result.concat(await client.db('monDb').collection('monCollection').find(query).toArray());
res.end(JSON.stringify(result));
}
app.get('/', getRoot);
app.get('/number/:id', getNumber);
app.get('/search/:term', getSearch);
async function serverFunc() {
await client.connect();
}
app.listen(8081, serverFunc);
|
803c1ae5d19561b2ba3d7433d9f3c7b4cab708ac
|
[
"JavaScript"
] | 1 |
JavaScript
|
zclewell/pokeServer
|
3823e83f1ba5afd0198cb5feb33b941708638ef8
|
98aae21f7d404522cbadda1da324216256dce006
|
refs/heads/main
|
<file_sep><?php session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Practising files and forms</title>
</head>
<body>
<center>
<?php
if (isset($_SESSION['msg'])) {
echo "<h3>".$_SESSION['msg']."</h3>";
}?>
<h3>Reset Password</h3>
<form action="processor.php" method="POST">
<input type="text" name="u_name" placeholder="Username">
<input type="<PASSWORD>" name="new_password" placeholder="<PASSWORD>">
<input type="<PASSWORD>" name="confirm_password" placeholder="<PASSWORD>">
<input type="submit" name="reset" value="RESET"></input>
</form>
<?php unset($_SESSION['msg']); ?>
<p>Can't remember your username? <a href="reset.php">CLick here</a> to create a new account</p>
</center>
</body>
</html><file_sep><?php include("auth_session.php"); ?>
<!DOCTYPE html>
<html>
<head>
<title>Practising files and forms</title>
</head>
<body>
<center>
<h2> Welcome, <?php echo $_SESSION['username'] ?></h2><br><br>
<button style="padding: 10px; background: blue;">
<a href="logout.php" style="color: white; text-decoration: none;">LOGOUT</a>
</button>
</center>
</body>
</head>
</html><file_sep><?php
session_start();
unset($_SESSION["just_registered"]);
unset($_SESSION['msg']);
if(isset($_POST['register'])) {
$username = trim($_POST['u_name']);
$data = [$username => [ "f_name" => trim($_POST['f_name']),
"l_name" => trim($_POST['l_name']),
"u_name" => trim($_POST['u_name']),
"password" => trim($_POST['password'])
]];
$my_file = file_get_contents('database.json');
$tmp_arr = json_decode($my_file, $associative = true);
if ($tmp_arr != NULL) {
array_push($tmp_arr, $data);
$data = json_encode($tmp_arr);
file_put_contents('database.json', $data);
} else {
$tmp_arr = [];
array_push($tmp_arr, $data);
$data = json_encode($tmp_arr);
file_put_contents('database.json', $data);
}
$_SESSION['just_registered'] = "yes";
header("Location: login.php");
} elseif (isset($_POST['reset'])) {
$u_name = trim($_POST['u_name']);
$new_password = trim($_POST['new_<PASSWORD>']);
$confirm_password = trim($_POST['<PASSWORD>_password']);
if ($new_password != $confirm_password) {
$_SESSION['msg'] = "The passwords you provided don't match. Please confirm password accurately.";
header("Location: reset.php");
exit();
}
$my_file = file_get_contents('database.json');
$tmp_arr = json_decode($my_file, $associative = true);
if ($tmp_arr != NULL) {
foreach($tmp_arr as $x => &$x_value) {
foreach($x_value as $y => &$y_value) {
if ($y == $u_name) {
$y_value["password"] = $<PASSWORD>;
$_SESSION['msg'] = "Your password has been succesfully reset. Enter your details below to login.";
$data = json_encode($tmp_arr);
file_put_contents('database.json', $data);
header("Location: login.php");
exit();
}
}
unset($y_value);
}
$_SESSION['msg'] = "Oops... Seems like you are not a registered user. If you feel otherwise, try to enter your username again accurately";
header("Location: reset.php");
}
} elseif (isset($_POST['login'])) {
$u_name = trim($_POST['u_name']);
$password = trim($_POST['password']);
$my_file = file_get_contents('database.json');
$tmp_arr = json_decode($my_file, $associative = true);
if ($tmp_arr != NULL) {
foreach($tmp_arr as $x => $x_value) {
foreach($x_value as $y => $y_value) {
if ($y == $u_name && $y_value["password"] == $<PASSWORD>) {
$_SESSION['username'] = $u_name;
header("Location: dashboard.php");
exit();
}
}
}
$_SESSION['msg'] = "The login details you entered are incorrect";
header("Location: login.php");
}
}
?><file_sep><?php session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Practising files and forms</title>
</head>
<body>
<center>
<?php
if (isset($_SESSION['just_registered'])) {
echo '<h3>You have successfully registered your account.</h3>
</p>Enter your details below to login</p>';
}
if (isset($_SESSION['msg'])) {
echo "<h3>".$_SESSION['msg']."</h3>";
}
?>
<h3> LOGIN </h3>
<form action="processor.php" method="POST">
<input type="text" name="u_name" placeholder="Username">
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>">
<input type="submit" name="login" value="LOGIN"></input>
</form>
<?php
if (!isset($_SESSION['just_registered'])) {
?>
<p> Don't have an account yet? CLick <a href="register.php">here</a> to register.</p>
<?php
}
?>
<p>Forgotten your password? CLick <a href="reset.php">here</a> to reset your password</p>
</center>
</body>
</html>
|
1e94e74fa7c1105d2fd5b11836842dbf669a5068
|
[
"PHP"
] | 4 |
PHP
|
Ivumar11/FormsAndFiles
|
e99fbbe049c8238bdbf89687040d0b885fd78513
|
72328d9d4b6ebfbb161bde93b9890f11644d679f
|
refs/heads/master
|
<repo_name>PeterXUYAOHAI/SimPointSite<file_sep>/FastLSH/views.py
import subprocess
from django.http import HttpResponse
from django.shortcuts import render, render_to_response
import time
import os
from django import forms
# Create your views here.
def index(request):
return render(request, 'FastLSH/home.html')
def parameterSet(request):
return render(request, 'FastLSH/parameterSet.html')
def execution(request):
return render(request, 'FastLSH/execution.html')
def contact(request):
return render(request, 'FastLSH/basic.html' , {'content': ['if you would','fsdaf']})
def submit(request):
dir_path = os.path.dirname(os.path.realpath(__file__))
time_stamp = time.strftime("%Y%m%d%H%M%S")
para_set = dict()
para_set["run_name"] = "first run" if request.POST["RunName"]=="" else request.POST["RunName"]
para_set["N"] = 1000 if request.POST["phN"]=="" else request.POST["phN"]
para_set["Q"] = 1000 if request.POST["phQ"]=="" else request.POST["phQ"]
para_set["D"] = 56 if request.POST["phD"]=="" else request.POST["phD"]
para_set["L"] = 200 if request.POST["phL"]=="" else request.POST["phL"]
para_set["K"] = 1 if request.POST["phK"]=="" else request.POST["phK"]
para_set["W"]= 1.2 if request.POST["phW"]=="" else request.POST["phW"]
para_set["T"] = 100 if request.POST["phT"]=="" else request.POST["phT"]
para_set["compute_mode"] = request.POST["computeMode"]
para_set["thread_mode"] = request.POST["threadMode"]
para_set["input_path_N"] = "./dataset1000NoIndex.csv" if request.POST["ipathN"]=="" else request.POST["ipathN"]
para_set["input_path_Q"] = "./dataset1000NoIndex.csv" if request.POST["ipathQ"]=="" else request.POST["ipathQ"]
para_set["output_path"] = "candidate.csv" if request.POST["opath"]=="" else request.POST["opath"]
#
# s = subprocess.check_output(["./FastLSH/core/cExec/FastLSH"])
# s = s.replace("\n","<br>")
return render(request, 'FastLSH/execution.html', {'content': para_set["L"]})
# return HttpResponse(s)
# return HttpResponse('Hello World!')
def download(request):
f = open('/home/peter/FYP/SimPointSite/FastLSH/cExec/output/candidate.csv', 'r')
response = HttpResponse(f, content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="candidate.csv"'
f.close()
return response
# def hello(request):
# return HttpResponse('Hello World!')
#
# def home(request):
# return render_to_response('index.html', {'variable': 'world'})
<file_sep>/FastLSH/core/flExec/lshExecution.py
import FastLSH as lsh
def calCandidate():
l = lsh.LSH(1000, 1000, 57, 200, 1, 1.2, 100)
print l.reportStatus()
l.loadSetN("dataset1000NoIndex.csv",0)
l.loadSetQ("dataset1000NoIndex.csv",0)
l.setThreadMode(1)
l.setComputeMode(1)
print l.reportStatus()
result = l.getCandidateSet()
print l.reportStatus()
print len(result)
<file_sep>/FastLSH/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^parameterSet/$', views.parameterSet, name='parameterSet'),
url(r'^execution/$', views.execution, name='execution'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^submit', views.submit),
url(r'^download', views.download)
# url(r'^hello/', 'FastLSH.views.hello'),
# url(r'^home/', 'FastLSH.views.home'),
]
|
dbb51e1bbd33a8f6b4180ffc73cf426a530f88a4
|
[
"Python"
] | 3 |
Python
|
PeterXUYAOHAI/SimPointSite
|
e9a8fd6b88918560270f3cedd4c7d8984cbd1192
|
fd54a9ff0246c4a2cd77abfc9b06859ab50b4caf
|
refs/heads/master
|
<file_sep>export * from './lib/shared-tmo-styles.module';
<file_sep># TMO Styles - Material Theme
There are 2 variations of this theme - default (light) and dark. To import the theme into your application styles, first import the core styles, then one or both themes.
## Default (light) theme only
```
// Material theme imports
@import 'material-theme/theme-core';
@import 'material-theme/theme-default';
```
## Dark theme only
```
// Material theme imports
@import 'material-theme/theme-core';
@import 'material-theme/theme-dark';
```
## Both themes
```
// Material theme imports
@import 'material-theme/theme-core';
@import 'material-theme/theme-default';
@import 'material-theme/theme-dark';
```
<file_sep># Shared TMO Styles
A Sass library that will eventually be available for use by all of tmo-one-site. It's still in development, so please don't use it yet unless advised.
|
a47c19fa877265ae60fbfae550c8c102e87031eb
|
[
"Markdown",
"TypeScript"
] | 3 |
TypeScript
|
tmalbonph/tmo-styles
|
72c0e3c346925cbeda5cf9114236e236caed8219
|
f29839d1123347e3f11dd885cb62b402dc81cef6
|
refs/heads/master
|
<repo_name>claurent/CharlesPersonalProject<file_sep>/app/app.js
'use strict';
// Declare app level module which depends on views, and components
var myApp = angular.module('myApp', [
'ngRoute',
'myApp.version',
'ngResource'
]);
myApp.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {
templateURL: 'homepage/homepage.html',
controller: 'HomepageCtrl'
})
.when('/weatherApp', {
templateUrl: 'weatherApp/weatherSearch.html',
controller: 'WeatherSearchCtrl'
});
}]);
<file_sep>/app/homepage/homepage.js
'use strict';
myApp.controller('HomepageCtrl', [function() {
}]);<file_sep>/app/weatherApp/weatherSearch.js
'use strict';
myApp.controller('WeatherSearchCtrl', ['$scope', '$location', '$resource', '$log', function($scope, $location, $resource, $log) {
$scope.cityName = '';
$scope.errorMessage = false;
$scope.position = {};
$scope.weatherAPIKey = '<KEY>';
$scope.weatherAPI = $resource('http://api.openweathermap.org/data/2.5/forecast/daily', {
callback: "JSON_CALLBACK"}, {get: { method: "JSONP"}});
$scope.weatherResults = {}
// Search by City Name
$scope.searchWeather = function() {
$log.info('City name: ' + $scope.cityName);
$scope.errorMessage = false;
$scope.callWeatherAPI({cityName: $scope.cityName});
}
// Search by coordinates
$scope.getLocation = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
$log.log(position);
$scope.$apply(function() {
$scope.position = position;
$scope.errorMessage = false;
});
$scope.callWeatherAPI(position);
},
function(err) {
$log.error(err);
$scope.$apply(function() {
$scope.errorMessage = err;
});
})
}
$log.info('location');
}
$scope.callWeatherAPI = function(input) {
var weatherRequestParams = {};
if(input.coords){
weatherRequestParams = {
lat: input.coords.latitude,
lon: input.coords.longitude,
APPID: $scope.weatherAPIKey
}
}
else if (input.cityName) {
weatherRequestParams = {
q: input.cityName,
APPID: $scope.weatherAPIKey
}
}
else {
$log.error('Error');
return;
}
$log.log(weatherRequestParams);
$scope.weatherResults = $scope.weatherAPI.get(weatherRequestParams);
$log.log($scope.weatherResults);
}
}]);
|
9ea5d390040d1d39491f51fe98112add50d84080
|
[
"JavaScript"
] | 3 |
JavaScript
|
claurent/CharlesPersonalProject
|
4e4ae3e63f80c952fe9cd9ae0358be7cb4cd6ac5
|
d403b707c1bfd8a10fa61d124aef6110cb90bdf1
|
refs/heads/master
|
<repo_name>AO15A1LM/laterna-magica<file_sep>/app/Http/Controllers/Admin/StudentController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Yajra\Datatables\Facades\Datatables;
use Illuminate\Http\Request;
use App\Models\Basegroup;
use App\Models\User;
class StudentController extends Controller
{
public function index()
{
return view('admin.student.index');
}
public function create(Request $request)
{
if($request->isMethod('post')){
$this->validate($request, [
'fname' => 'required|alpha|string|min:2|max:35',
'lname' => 'required|alpha|string|min:2|max:35',
'basegroup_id' => 'required|integer|min:1|max:5',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
]);
User::createStudent($request);
return Redirect::back()->withErrors(['Student is aangemaakt']);
}
return view('admin.student.create', ['basegroups' => Basegroup::all()]);
}
public function edit($id, Request $request)
{
if($request->isMethod('post')){
$this->validate($request, [
'uname' => [
"regex:/^[a-z -]+$/i",
'min:2',
'max:75'
],
'fname' => 'alpha|string|min:2|max:35',
'lname' => 'alpha|string|min:2|max:35',
]);
User::editStudent($id, $request);
return Redirect::back()->withErrors(['Student is aangepast']);
}
return view('admin.student.edit', [
'student' => User::find($id),
'basegroups' => Basegroup::all()
]);
}
public function delete($id, Request $request)
{
if($request->isMethod('post') && ctype_digit($id)){
$this->validate($request, [
'verify' => 'required'
]);
$student = User::find($id);
$student->delete();
}
return Redirect::back();
}
public function ajax_read()
{
return Datatables::of(User::students())
->addColumn('action', function($student) {
$id = $student->id;
$name = htmlspecialchars($student->name, ENT_QUOTES, 'UTF-8');
$basegroup = (int)$student->basegroup_id;
$actions = "";
$actions .=
'<a href="/student/'.$id.'/edit" title="Bewerk '.$name.'">
<i class="fa fa-pencil-square-o"></i>
</a>
<a href="#delete"
id="btn_delete_student"
title="Verwijder '.$name.'"
data-name="'.$name.'"
data-id="'.$id.'"
>
<i class="fa fa-trash"></i>
</a>';
return $actions;
})
->addColumn('basegroup', function($student) {
if($student->basegroup_id != null) {
$filter = Basegroup::find($student->basegroup_id)->name;
return htmlspecialchars($filter, ENT_QUOTES, 'UTF-8');
}
})
->make(true);
}
public function ajax_read_basegroup($id)
{
return Datatables::of(User::find($id)->basegroup())
->addColumn('action', function($student) {
return 'TODO';
})
->make(true);
}
public function ajax_read_roles($id)
{
return Datatables::of(User::find($id)->role())
->addColumn('action', function($student) {
return 'TODO';
})
->make(true);
}
}<file_sep>/app/Console/Kernel.php
<?php
namespace App\Console;
use App\Models\User;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\File;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
$basegroups = DB::table('basegroup')->get();
$users = User::all();
if (!is_dir(storage_path('app/basegroups'))) {
Storage::makeDirectory('basegroups');
}
foreach ($basegroups as $basegroup) {
if (!is_dir(storage_path('app/basegroups/' . $basegroup->id))) {
Storage::makeDirectory('basegroups/' . $basegroup->id);
}
}
foreach ($users as $user) {
if ($user->hasRole('student')) {
if (!is_dir(storage_path('app/basegroups/' . $user->basegroup_id . '/' . $user->id))) {
Storage::makeDirectory('basegroups/' . $user->basegroup_id . '/' . $user->id);
}
}
}
});
}
/**
* Register the Closure based commands for the application.
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
<file_sep>/database/seeds/UsersTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
private $table = "users";
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
try{
DB::table($this->table)->delete();
$this->_makeCoaches();
$this->_makeStudents();
} catch(Exception $e) {
print "Message: " .$e->getMessage();
}
}
private function _usersCount($user)
{
try {
$user = File::get("database/data/{$user}.json");
$arr = json_decode($user, true);
return count($arr);
} catch (Exception $e) {
print "Message: {$e->getMessage()}\n";
}
return 0;
}
private function _makeCoaches()
{
$json = File::get("database/data/coaches.json");
$users = json_decode($json);
$id = 1;
foreach($users as $user) {
DB::table($this->table)->insert([
"id" => $id++,
"name" => strtolower($user->fname." ".$user->lname),
"email" => strtolower($user->fname)."@gmail.com",
"first_name" => ucfirst($user->fname),
"last_name" => ucfirst($user->lname),
"password" => Hash::make("<PASSWORD>"),
"basegroup_id" => rand(1, 5),
"created_at" => date("Y-m-d G:i:s")
]);
}
print "Coaches are succesfuly created! \n";
}
private function _makeStudents()
{
$json = File::get("database/data/students.json");
$users = json_decode($json);
$id = $this->_usersCount("coaches") + 1;
foreach($users as $user) {
DB::table($this->table)->insert([
"id" => $id++,
"name" => strtolower($user->fname." ".$user->lname),
"email" => strtolower($user->fname)."@<EMAIL>",
"first_name" => ucfirst($user->fname),
"last_name" => ucfirst($user->lname),
"password" => <PASSWORD>("<PASSWORD>"),
"basegroup_id" => rand(1, 5),
"created_at" => date("Y-m-d G:i:s")
]);
}
print "Users are succesfuly created! \n";
}
}
<file_sep>/app/Http/Controllers/Student/TaskController.php
<?php
namespace App\Http\Controllers\Student;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use Yajra\Datatables\Facades\Datatables;
use Illuminate\Support\Facades\Auth;
use App\Models\Task;
class TaskController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$tasks = Task::getCollectionOfTasks();
return view('student.dashboard', ['tasks' => $tasks]);
}
public function create(Request $request)
{
// Validate user input
if ($request->isMethod('post')) {
$this->validate($request, [
'name' => [
'regex:/[a-zA-Z0-9 -]/',
'required',
'min:2',
'max:35'
],
'start_date' => 'required|date',
'end_date' => 'required|date',
'target' => 'required|string|min:4|max:255',
'todo' => 'required|string|min:4|max:255',
'step1' => 'required|string|min:4|max:255',
'step2' => 'string|min:4|max:255|nullable',
'step3' => 'string|min:4|max:255|nullable',
'step4' => 'string|min:4|max:255|nullable',
'achieved' => 'required',
'reflection' => 'required|string|min:4',
]);
$user = Auth::user();
if ($request->hasFile('evidence')) {
$file = $request->file('evidence');
$fileName = $file->getClientOriginalName();
if ($file->isValid()) {
$this->validate($request, [
'evidence' => 'mimetypes:image/jpeg,image/png,application/doc,text/plain'
]);
$task_id = Task::createTask($request, $fileName);
if (!is_file('basegroups/' . $user->basegroup_id . '/' . $user->id . '/' . $task_id . '/' . $fileName)) {
$file->storeAs('basegroups/' . $user->basegroup_id . '/' . $user->id . '/' . $task_id, $fileName);
} else {
Storage::delete('basegroups/' . $user->basegroup_id . '/' . $user->id . '/' . $task_id, $fileName);
}
} else {
return Redirect::back()->withErrors();
}
}
Task::createTask($request);
return Redirect::back()->withErrors(['Taak is aangemaakt']);
}
return view('student.tasks.create');
}
public function edit($id, Request $request)
{
Task::checkTaskPerm($id);
// Validate user input
if ($request->isMethod('post')) {
$this->validate($request, [
'name' => [
'regex:/[a-zA-Z0-9 -]/',
'required',
'min:2',
'max:35'
],
'start_date' => 'required|date',
'end_date' => 'required|date',
'target' => 'required|string|min:4|max:255',
'todo' => 'required|string|min:4|max:255',
'step1' => 'required|string|min:4|max:255',
'step2' => 'string|min:4|max:255|nullable',
'step3' => 'string|min:4|max:255|nullable',
'step4' => 'string|min:4|max:255|nullable',
'achieved' => 'required',
'reflection' => 'required|string|min:4',
]);
$user = Auth::user();
$task = Task::find($id);
if ($request->hasFile('evidence')) {
$file = $request->file('evidence');
$fileName = $file->getClientOriginalName();
if ($file->isValid()) {
$this->validate($request, [
'evidence' => 'mimetypes:image/jpeg,image/png,application/doc,text/plain'
]);
if (!is_file('basegroups/' . $user->basegroup_id . '/' . $user->id . '/' . $task->id . '/' . $fileName)) {
$file->storeAs('basegroups/' . $user->basegroup_id . '/' . $user->id . '/' . $task->id, $fileName);
} else {
Storage::delete('basegroups/' . $user->basegroup_id . '/' . $user->id . '/' . $task->id, $fileName);
}
} else {
return Redirect::back()->withErrors();
}
}
Task::editTask($id, $request, $fileName);
return Redirect::back()->withErrors(['Taak is aangepast']);
}
$task = Task::find($id);
$taskContent = json_decode($task->content);
$task->target = $taskContent->target;
$task->todo = $taskContent->todo;
$task->step1 = $taskContent->roadmap->step1;
$task->step2 = $taskContent->roadmap->step2;
$task->step3 = $taskContent->roadmap->step3;
$task->step4 = $taskContent->roadmap->step4;
$task->achieved = $taskContent->achieved;
$task->evidence = $taskContent->evidence;
$task->reflection = $taskContent->reflection;
return view('student.tasks.edit', ['task' => $task]);
}
public function delete($id)
{
Task::checkTaskPerm($id);
Task::deleteTask($id);
return view('student.tasks.index');
}
public function read($id)
{
if (ctype_digit ($id) === false) die; // Validate
$task = Task::getSingleTask($id);
return view('student.tasks.read', ['task' => $task, 'content' => $task->content]);
}
public function download($id)
{
$task = Task::find($id);
$user_id = $task->user_id;
$user = User::find($user_id);
$taskContent = json_decode($task->content);
$fileName = $taskContent->evidence;
if (file_exists(storage_path('app/basegroups/' . $user->basegroup_id . '/' . $user->id . '/' . $task->id . '/' . $fileName)))
{
return response()->download(storage_path('app/basegroups/' . $user->basegroup_id . '/' . $user->id . '/' . $task->id . '/' . $fileName));
};
return Redirect::back();
}
public function ajax_read()
{
return Datatables::of(Auth::user()->getTasks())
->addColumn('action', function ($task) {
$id = $task->id;
return '
<a href="/task/' . $id . '" title="Overzicht">
<i class="ion-document"></i>
</a>
<a href="/task/' . $id . '/edit" title="Bewerk">
<i class="ion-compose"></i>
</a>
<a href="/task/' . $id . '/delete" title="Verwijderen">
<i class="ion-ios-trash-outline"></i>
</a>';
})
->make(true);
}
}<file_sep>/dev/install.sh
#!/bin/bash
BANNER="Installation of Laterna Magica App"
# Colors
green=$(tput setaf 2)
yellow=$(tput setaf 3)
normal=$(tput sgr0)
function msg {
printf "${green}$1${normal}\n"
}
function doInstall {
composer install
msg "Composer successfuly installed!"
npm install
msg "Node_modules successfuly installed!"
apt-get -y install `check-language-support -l nl`
msg "Installed dutch language file"
php artisan migrate
msg "Database Migrated!"
php artisan db:seed
msg "Database seeded!"
npm run dev
npm run watch
}
printf "${yellow}$BANNER${normal}\n"
select opt in "Install" "Exit"; do
case $opt in
Install ) doInstall; break;;
Exit ) printf "${green}Bye Bye Amigo!${normal} \n"; exit;;
esac
done
<file_sep>/routes/web.php
<?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('auth.login');
});
Auth::routes();
// Routes for when the user is logged in
Route::group(['middleware' => 'auth'], function () {
// ADMIN GROUP
Route::group(['middleware' => 'role:admin'], function() {
Route::get('basegroup', 'Admin\BasegroupController@index');
$this->group(['prefix' => 'basegroup'], function(){
$this->match(['get', 'post'], 'create', 'Admin\BasegroupController@create');
$this->get('ajax_read', 'Admin\BasegroupController@ajax_read');
$this->get('{id}', 'Admin\BasegroupController@read');
$this->get('{id}/ajax_read_coaches', 'Admin\BasegroupController@ajax_read_coaches');
$this->get('{id}/ajax_read_students', 'Admin\BasegroupController@ajax_read_students');
$this->match(['get', 'post'], '{id}/edit', 'Admin\BasegroupController@edit');
$this->match(['get', 'post'], '{id}/delete', 'Admin\BasegroupController@delete');
});
Route::get('coach', 'Admin\CoachController@index');
$this->group(['prefix' => 'coach'], function(){
$this->match(['get', 'post'], 'create', 'Admin\CoachController@create');
$this->get('ajax_read', 'Admin\CoachController@ajax_read');
$this->get('{id}/ajax_read_basegroup', 'Admin\CoachController@ajax_read_basegroup');
$this->get('{id}/ajax_read_role', 'Admin\CoachController@ajax_read_role');
$this->match(['get', 'post'], '{id}/edit', 'Admin\CoachController@edit');
$this->match(['get', 'post'], '{id}/delete', 'Admin\CoachController@delete');
});
Route::get('student', 'Admin\StudentController@index');
$this->group(['prefix' => 'student'], function(){
$this->match(['get', 'post'], 'create', 'Admin\StudentController@create');
$this->get('ajax_read', 'Admin\StudentController@ajax_read');
$this->get('{id}/ajax_read_basegroup', 'Admin\StudentController@ajax_read_basegroup');
$this->get('{id}/ajax_read_role', 'Admin\StudentController@ajax_read_role');
$this->match(['get', 'post'], '{id}/edit', 'Admin\StudentController@edit');
$this->match(['get', 'post'], '{id}/delete', 'Admin\StudentController@delete');
});
// Profile
Route::get('profile', 'Admin\AdminController@index');
// Update Email
Route::post('update_email', [
'as' => 'admin_update_email',
'uses' => 'Admin\AdminController@createNewEmail'
]);
// Update Password
Route::post('update_password', [
'as' => 'admin_update_password',
'uses' => 'Admin\AdminController@createNewPassword'
]);
});
// COACH GROUP
Route::group(['middleware' => 'role:coach'], function() {
});
// STUDENT GROUP
Route::group(['middleware' => 'role:student'], function() {
// Student routes
$this->get('dashboard', 'Student\TaskController@index');
$this->group(['prefix' => 'task'], function(){
$this->match(['get', 'post'], 'create', 'Student\TaskController@create');
$this->get('ajax_read', 'Student\TaskController@ajax_read');
$this->get('{id}', 'Student\TaskController@read');
$this->match(['get', 'post'], '{id}/edit', 'Student\TaskController@edit');
$this->match(['get', 'post'], '{id}/delete', 'Student\TaskController@delete');
$this->get('{id}/download', 'Student\TaskController@download');
});
});
});
<file_sep>/app/Http/Controllers/Coach/CoachController.php
<?php
namespace App\Http\Controllers\Coach;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CoachController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
}
<file_sep>/database/seeds/DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Hash;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
try {
print File::get("database/data/welcome.txt") . "\n";
$this->call(BasegroupTableSeeder::class);
$this->call(RolesTableSeeder::class);
$this->call(UsersTableSeeder::class);
$this->call(RoleUserTableSeeder::class);
$this->call(TasksTableSeeder::class);
print "Seeding has been succefully completed! \n";
exit;
} catch (Exception $e) {
print "Message: {$e->getMessage()}\n";
}
}
}
<file_sep>/readme.md
## Laterna Magica
See: [Laterna-magica wiki](https://github.com/AO15A1LM/laterna-magica/wiki)<file_sep>/app/Models/Basegroup.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Zizaco\Entrust\EntrustRole;
use App\Models\User;
class Basegroup extends Model
{
protected $table = 'basegroup';
public function users()
{
return $this->hasMany('App\Models\User');
}
/**
* Get users from basegroup with the role coach
* @return role, users.id, users.name, users.first_name, users.last_name
*/
public function coaches()
{
return $this->hasMany('App\Models\User')
->join('role_user', 'role_user.user_id', '=', 'users.id')
->join('roles', 'roles.id', '=', 'role_user.role_id')
->where('roles.name', 'coach')
->select(
'roles.name AS role',
'users.id',
'users.name',
'users.first_name',
'users.last_name'
);
}
/**
* Get users from basegroup with the role
* @return role, users.id, users.name, users.first_name, users.last_name
*/
public function students()
{
return $this->hasMany('App\Models\User')
->join('role_user', 'role_user.user_id', '=', 'users.id')
->join('roles', 'roles.id', '=', 'role_user.role_id')
->where('roles.name', 'student')
->select(
'roles.name AS role',
'users.id',
'users.name',
'users.first_name',
'users.last_name'
);
}
public static function create($request)
{
$basegroup = new Basegroup;
$basegroup->name = htmlspecialchars($request->input('name'), ENT_QUOTES, 'UTF-8');
$basegroup->save();
foreach($request->input('coaches') as $coach_id){
$user = User::find($coach_id);
$user->basegroup_id = (int)$basegroup->id;
$user->save();
}
foreach($request->input('students') as $student_id){
$user = User::find($student_id);
$user->basegroup_id = (int)$basegroup->id;
$user->save();
}
}
public static function edit($request, $id)
{
$users = User::where('basegroup_id', $id)->get();
foreach ($users as $user) {
$user->basegroup_id = NULL;
$user->save();
}
$basegroup = Basegroup::find($id);
$basegroup->name = htmlspecialchars($request->input('name'), ENT_QUOTES, 'UTF-8');
$basegroup->save();
foreach($request->input('coaches') as $coach_id){
$user = User::find($coach_id);
$user->basegroup_id = (int)$id;
$user->save();
}
foreach($request->input('students') as $student_id){
$user = User::find($student_id);
$user->basegroup_id = (int)$id;
$user->save();
}
}
public static function deleteBasegroup($id)
{
$basegroup = Basegroup::find($id);
$users = User::where('basegroup_id', $basegroup->id);
$users->update([
'basegroup_id' => NULL,
'updated_at' => date('Y-m-d G:i:s')
]);
$basegroup->delete();
}
}
<file_sep>/app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Auth\Authenticatable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;
use App\Models\Role as Role;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use EntrustUserTrait;
use Authenticatable, CanResetPassword;
use Notifiable;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'id', 'name', 'first_name', 'last_name', 'email', 'basegroup_id', 'updated_at'
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public static function students()
{
$users = User::all();
$students = [];
foreach($users as $user){
if($user->hasRole('student')){
if ($user->basegroup_id) {
$basegroup = Basegroup::find($user->basegroup_id);
} else {
$basegroup = NULL;
}
$user->basegroup_name = $basegroup ? $basegroup->name : "";
htmlspecialchars($user->basegroup_name, ENT_QUOTES, 'UTF-8');
array_push($students, $user);
}
}
return $students;
}
public static function createStudent($request)
{
$student = new User;
$student->name = strtolower($request->input('fname')." ".$request->input('lname'));
$student->first_name = ucfirst($request->input('fname'));
$student->last_name = ucfirst($request->input('lname'));
$student->basegroup_id = (int)$request->input('basegroup_id');
$student->password = <PASSWORD>::<PASSWORD>($request->input('password'));
$student->created_at = date('Y-m-d G:i:s');
$student->save();
// Give role
$id = User::where('name', $student->name)
->get(['id', 'name'])
->first()
->attributes['id'];
DB::table('role_user')->insert([
'user_id' => $id,
'role_id' => 3
]);
}
public static function editStudent($id, $request)
{
$student = User::find($id);
$student->name = strtolower($request->input('uname'));
$student->first_name = ucfirst($request->input('fname'));
$student->last_name = ucfirst($request->input('lname'));
$student->basegroup_id = (int)$request->input('basegroup_id');
$student->password = <PASSWORD>::make($request->input('password'));
$student->updated_at = date('Y-m-d G:i:s');
$student->save();
}
public static function coaches()
{
$users = User::all();
$coaches = [];
foreach($users as $user){
if($user->hasRole('coach')) {
if($user->basegroup_id) $basegroup = Basegroup::find($user->basegroup_id);
else $basegroup = NULL;
$user->basegroup_name = $basegroup ? $basegroup->name : "";
array_push($coaches, $user);
}
}
return $coaches;
}
public static function createCoach($request)
{
$coach = new User;
$coach->name = strtolower($request->input('fname') . " " . $request->input('lname'));
$coach->first_name = ucfirst($request->input('fname'));
$coach->last_name = ucfirst($request->input('lname'));
$coach->email = $request->input('email');
$coach->basegroup_id = (int)$request->input('basegroup_id');
$coach->password = <PASSWORD>($request->input('password'));
$coach->created_at = date('Y-m-d G:i:s');
$coach->save();
// Give role
$id = User::where('name', $coach->name)
->get(['id', 'name'])
->first()
->attributes['id'];
DB::table('role_user')->insert([
'user_id' => $id,
'role_id' => 2
]);
}
public static function editCoach($id, $request)
{
$coach = User::find($id);
$coach->name = strtolower($request->input('uname'));
$coach->first_name = ucfirst($request->input('fname'));
$coach->last_name = ucfirst($request->input('lname'));
$coach->email = $request->input('email');
$coach->basegroup_id = (int)$request->input('basegroup_id');
$coach->password = <PASSWORD>($request->input('password'));
$coach->updated_at = date('Y-m-d G:i:s');
$coach->save();
}
public static function admins()
{
$users = User::all();
$admins = [];
foreach($users as $user){
if($user->hasRole('admin')) array_push($admins, $user);
}
return $admins;
}
public function roles()
{
return $this->belongsToMany('App\Models\Role');
}
public function basegroup()
{
return $this->belongsTo('App\Models\Basegroup');
}
public function getTasks()
{
if($this->hasRole('student')) return $this->hasMany('App\Models\Task');
else return $this;
}
}
<file_sep>/app/Http/Controllers/Admin/AdminController.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use App\Models\Admin\Profile;
class AdminController extends Controller
{
private $profile;
public function __construct()
{
$this->middleware('auth');
$this->profile = new Profile;
}
/**
* Render user information to the page
*/
public function index()
{
$user = $this->_getProfileInformation();
return view('admin.profile.index')->with('user', $user);
}
/**
* Update current user email
* 1. Validate request
* 2. Update user email
* 3. Redirect back to the page with success message
*/
public function createNewEmail(Request $request)
{
if( $this->_validate($request) ) {
try {
$id = (int)$this->_getProfileInformation()->id;
$new_email = $request->new_email;
$this->profile->updateEmail($id, $new_email);
$msg = ['Email is bijgewerkt'];
return redirect('profile')->with('message', $msg);
} catch(Exception $e) {
return redirect('profile')->withErrors($e->getMessage);
}
}
$errors = [
'Controlleer of het wachtwoord overeen komt',
'Controlleer of het een bestaand email adres is'
];
return redirect('profile')->withErrors($errors);
}
/**
* Update current user password
* 1. Validate request
* 2. Update user password
* 3. Redirect back to the page with success message
*/
public function createNewPassword(Request $request)
{
if( $this->_validate($request) ) {
try {
$id = (int)$this->_getProfileInformation()->id;
$new_password = Hash::make( $request->new_password );
$this->profile->updatePassword($id, $new_password);
$msg = ['Wachtwoord is bijgewerkt!'];
return redirect('profile')->with('message', $msg);
} catch(Exception $e) {
return redirect('profile')->withErrors($e->getMessage());
}
}
$errors = [
'Controlleer of het wachtwoord overeen komt',
'Wachtwoord mag niet hetzelfde zijn als het oude wachtwoord',
'Wachtwoord moet tussen 5 en 50 karakters lang zijn'
];
return redirect('profile')->withErrors($errors);
}
/**
* Get user profile information
* @return Object id, name, email, password
*/
private function _getProfileInformation()
{
$user = ( !is_object($this->profile->get_result() ) )
? (object) $this->profile->get_result()
: $this->profile->get_result();
return $user;
}
/**
* Validate request
* 1. Check request_uri
* 2. Check rules
* 3. Check if password match within the database
* @return boolean;
*/
private function _validate($request)
{
$rules = [];
// Rules Update email
if($_SERVER['REQUEST_URI'] === '/update_email') {
$rules = [
'new_email' => 'required|string|email',
'match_password' => '<PASSWORD>'
];
// Rules Update Password
} elseif ($_SERVER['REQUEST_URI'] === '/update_password') {
$rules = [
'match_password' => '<PASSWORD>',
'new_password' => '<PASSWORD>',
'confirm_password' => '<PASSWORD>'
];
}
$this->validate($request, $rules);
return $this->_checkPassword($request);
}
/**
* Check if password matches
* 1. Check if new password is unique from old password
* 2. Confirm new password
* @return boolean
*/
private function _checkPassword($request)
{
$pwd = $this->_getProfileInformation()->password;
$match_pwd = $request->match_password;
$new_pwd = $request->new_password;
// Check if new password is unique from old password
if ($_SERVER['REQUEST_URI'] === '/update_password') {
if( Hash::check($new_pwd, $pwd)) return false;
}
// Check if password match
return Hash::check($match_pwd, $pwd);
}
}
<file_sep>/app/Http/Controllers/Admin/CoachController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Yajra\Datatables\Facades\Datatables;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Http\Request;
use App\Models\Basegroup;
use App\Models\User;
class CoachController extends Controller
{
public function index()
{
return view('admin.coach.index');
}
public function create(Request $request)
{
if($request->isMethod('post')){
$this->validate($request, [
'fname' => 'required|alpha|min:2|max:35',
'lname' => 'required|alpha|min:2|max:35',
'email' => 'required|email|max:75|unique:users',
'basegroup_id' => 'required|integer|min:1|max:5',
'password' => '<PASSWORD>',
'password_confirmation' => '<PASSWORD>',
]);
User::createCoach($request);
return Redirect::back()->withErrors(['Leraar is aangemaakt']);
}
return view('admin.coach.create', ['basegroups' => Basegroup::all()]);
}
public function edit($id, Request $request)
{
if($request->isMethod('post')){
$this->validate($request, [
'uname' => [
"regex:/^[a-z -]+$/i",
'min:2',
'max:75'
],
'fname' => 'alpha|min:2|max:35',
'lname' => 'alpha|min:2|max:35',
'email' => 'email|max:75',
'basegroup_id' => 'integer|min:1|max:5'
]);
User::editCoach($id, $request);
return Redirect::back()->withErrors(['Leraar is aangepast']);
}
return view('admin.coach.edit', [
'coach' => User::find($id),
'basegroups' => Basegroup::all()
]);
}
public function delete($id, Request $request)
{
if($request->isMethod('post') && ctype_digit($id)){
$this->validate($request, [
'verify' => 'required'
]);
$coach = User::find($id);
$coach->delete();
}
return Redirect::back();
}
public function ajax_read()
{
return Datatables::of(User::coaches())
->addColumn('action', function($coach) {
$id = $coach->id;
$name = $coach->name;
$basegroup = $coach->basegroup_id;
$actions = "";
$actions .=
'<a href="/coach/'.$id.'/edit" title="Bewerk '.$name.'">
<i class="fa fa-pencil-square-o"></i>
</a>
<a href="#delete"
id="btn_delete_coach"
title="Verwijder '.$name.'"
data-name="'.$name.'"
data-id="'.$id.'"
>
<i class="fa fa-trash"></i>
</a>';
return $actions;
})
->addColumn('basegroup', function($coach) {
if($coach->basegroup_id != null) {
return Basegroup::find($coach->basegroup_id)->name;
}
})
->make(true);
}
public function ajax_read_basegroup($id)
{
return Datatables::of(User::find($id)->basegroup())
->addColumn('action', function($coach) {
return 'TODO';
})
->make(true);
}
public function ajax_read_roles($id)
{
return Datatables::of(User::find($id)->roles())
->addColumn('action', function($coach) {
return 'TODO';
})
->make(true);
}
}<file_sep>/app/Http/Helpers/ViewHelper.php
<?php
//namespace App\Http\Helpers;
//use Illuminate\Http\Request;
trait ViewHelper
{
public static function isActive($url)
{
return Request::is($url) ? 'active' : null;
}
}<file_sep>/app/Models/Admin/Profile.php
<?php
namespace App\Models\Admin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class Profile extends Model
{
public function get_result()
{
return (object) [
'id' => Auth::id(),
'name' => Auth::user()->name,
'email' => Auth::user()->email,
'password' => Auth::user()->password
];
}
public function updateEmail($id, $new_email)
{
DB::table('users')
->where('id', $id)
->update(['email' => $new_email]);
}
public function updatePassword($id, $new_password)
{
DB::table('users')
->where('id', $id)
->update(['password' => $new_password]);
}
}
<file_sep>/app/Http/Controllers/Admin/BasegroupController.php
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Yajra\Datatables\Facades\Datatables;
use Illuminate\Http\Request;
use App\Models\Basegroup;
use App\Models\User;
class BasegroupController extends Controller
{
private $_students;
private $_coaches;
public function __construct()
{
$this->_students = User::students();
$this->_coaches = User::coaches();
}
public function index()
{
return view('admin.basegroup.index');
}
public function create(Request $request)
{
if($request->isMethod('post')){
$this->validate($request, [
'name' => 'required|alpha_num|min:2|max:55',
'coaches' => 'required|array:alpha_num',
'students' => 'required|array:alpha_num',
]);
Basegroup::create($request);
return redirect()->back()->withErrors(['Stamgroep is aangemaakt']);
}
return view('admin.basegroup.create', [
'students' => $this->_students,
'coaches' => $this->_coaches
]);
}
public function read($id)
{
$basegroup = Basegroup::find($id);
return view('admin.basegroup.read', ['id' => $id]);
}
public function edit(Request $request, $id)
{
if($request->isMethod('post')){
$this->validate($request, [
'name' => 'alpha_num|min:2|max:55',
'coaches' => 'array:alpha_num',
'students' => 'array:alpha_num',
]);
Basegroup::edit($request, $id);
return redirect()->back();
}
$basegroup = Basegroup::find($id);
$users = User::where('basegroup_id', $id)->get();
return view('admin.basegroup.edit',
['students' => $this->_students, 'coaches' => $this->_coaches],
['basegroup' => $basegroup, 'users' => $users]
);
}
public function delete(Request $request, $id)
{
if($request->isMethod('post') && ctype_digit($id)){
$this->validate($request, [
'verify' => 'required'
]);
Basegroup::deleteBasegroup($id);
}
return redirect()->back();
}
public function ajax_read()
{
return Datatables::of(Basegroup::query())
->addColumn('action', function($basegroup) {
$id = $basegroup->id;
$name = $basegroup->name;
return '
<a href="/basegroup/'.$id.'/edit" title="Bewerk '.$name.'">
<i class="fa fa-pencil-square-o"></i>
</a>
<a href="#delete"
id="btn_delete_basegroup"
title="Verwijder '.$name.'"
data-name="'.$name.'"
data-id="'.$id.'"
>
<i class="fa fa-trash"></i>
</a>'
;
})
->make(true);
}
public function ajax_read_coaches($id)
{
return Datatables::of(Basegroup::find($id)->coaches)
->addColumn('action', function($coach) {
return 'TODO';
})
->make(true);
}
public function ajax_read_students($id)
{
return Datatables::of(Basegroup::find($id)->students)
->addColumn('action', function($student) {
return 'TODO';
})
->make(true);
}
}<file_sep>/app/Http/Controllers/Coach/BasegroupController.php
<?php
namespace App\Http\Controllers\Coach;
use Illuminate\Http\Request;
use App\Http\Controllers\Coach\CoachController;
use App\Models\Coach\Basegroup;
class BasegroupController extends CoachController
{
public function __contruct()
{
parent::construct();
}
public function createBasegroup()
{
dd($_POST);
}
}
<file_sep>/dev/readme.md
#### install
```
chmod +x ./dev/install.sh
cd dev && ./install.sh
```<file_sep>/database/seeds/TasksTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class TasksTableSeeder extends Seeder
{
private $table = "tasks";
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
try{
DB::table($this->table)->delete();
$this->_createTasksForAllStudents();
} catch(Exception $e) {
print "Message: " .$e->getMessage();
}
}
/**
* Create tasks for a single user/student.
*/
private function _createTasks($user_id)
{
$json = File::get("database/data/tasks.json");
$tasks = json_decode($json);
foreach($tasks as $task){
DB::table($this->table)->insert([
"name" => $task->name,
"content" => json_encode($task->content),
"user_id" => $user_id,
"start_date" => $task->start_date,
"end_date" => $task->end_date,
"created_at" => date("Y-m-d G:i:s")
]);
}
}
/**
* Create tasks for all users/students.
*/
private function _createTasksForAllStudents()
{
$users = File::get("database/data/students.json");
$user_count = count(json_decode($users));
for($user_id = 1; $user_id <= $user_count; $user_id++){
$this->_createTasks($user_id);
}
print "Tasks are succesfuly created! \n";
}
}
<file_sep>/app/Models/Task.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Auth;
use stdClass;
use DateHelper;
class Task extends Model
{
use SoftDeletes;
protected $table = 'tasks';
protected $fillable = ['id', 'name', 'content', 'user_id', 'start_date', 'end_date'];
protected $dates = ['deleted_at'];
/*
* Convert dates from tasks attributes to local dates.
* @return: [array] [task attributes with local dates]
*/
private static function _convertTaskDate($attr)
{
$attr['start_date'] = DateHelper::localize($attr['start_date']);
$attr['end_date'] = DateHelper::localize($attr['end_date']);
$attr['created_at'] = DateHelper::localize($attr['created_at']);
$attr['updated_at'] = DateHelper::localize($attr['updated_at']);
return $attr;
}
/**
* Get single task from student
* @param [int] $id [task id]
* @return [object] [task attributes]
*/
public static function getSingleTask($id)
{
Self::checkTaskPerm($id);
$task = Self::find($id);
$task->content = json_decode($task->content);
$task->attributes = Self::_convertTaskDate($task->attributes);
return (Object)$task->attributes;
}
/**
* Get collection of tasks from student
* @return [array] [all tasks from student]
*/
public static function getCollectionOfTasks()
{
$tasks = Auth::user()->getTasks()
->orderBy('created_at', 'desc')
->get();
foreach($tasks as $task) {
$task->attributes = Self::_convertTaskDate($task->attributes);
$task->content = json_decode($task->content);
}
return $tasks;
}
public static function checkTaskPerm($task_id)
{
$user = Auth::user();
if($user->hasRole('admin')){
return;
} else if($user->hasRole('coach')) {
$students = $user->basegroup->students;
foreach($students as $student){
if($student->id === Task::find($task_id)->user_id) return;
abort(401);
}
} else if($user->hasRole('student')){
if($user->id === Task::find($task_id)->user_id) return;
else abort(401);
}
}
public static function createTask($request, $fileName = null)
{
$roadmap = new stdClass;
$roadmap->step1 = $request->input('step1');
$roadmap->step2 = $request->input('step2') ?: NULL;
$roadmap->step3 = $request->input('step3') ?: NULL;
$roadmap->step4 = $request->input('step4') ?: NULL;
$content = new stdClass;
$content->target = $request->input('target');
$content->todo = $request->input('todo');
$content->roadmap = $roadmap;
$content->achieved = $request->input('achieved');
$content->evidence = $fileName;
$content->reflection = $request->input('reflection');
$task = new Task;
$task->name = $request->input('name');
$task->content = json_encode($content);
$task->user_id = Auth::user()->id;
$task->start_date = $request->input('start_date');
$task->end_date = $request->input('end_date');
$task->save();
return $task->id;
}
public static function editTask($id, $request, $fileName = null)
{
$roadmap = new stdClass;
$roadmap->step1 = $request->input('step1');
$roadmap->step2 = $request->input('step2') ?: NULL;
$roadmap->step3 = $request->input('step3') ?: NULL;
$roadmap->step4 = $request->input('step4') ?: NULL;
$content = new stdClass;
$content->target = $request->input('target');
$content->todo = $request->input('todo');
$content->roadmap = $roadmap;
$content->achieved = $request->input('achieved');
$content->evidence = $fileName;
$content->reflection = $request->input('reflection');
$task = Task::find($id);
$task->name = $request->input('name');
$task->content = json_encode($content);
$task->user_id = Auth::user()->id;
$task->start_date = $request->input('start_date');
$task->end_date = $request->input('end_date');
$task->save();
}
public static function deleteTask($id)
{
$task = Task::find($id);
$task->delete();
}
public function user()
{
$this->belongsTo('App\Models\User');
}
}<file_sep>/database/seeds/BasegroupTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class BasegroupTableSeeder extends Seeder
{
private $table = "basegroup";
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$basegroups = [];
$id = 1;
for($i = 1; $i <= 5; $i++) {
array_push($basegroups, 'Groep ' . $i);
}
DB::table('basegroup')->delete();
foreach ($basegroups as $basegroup) {
DB::table($this->table)->insert([
'id' => $id++,
'name' => $basegroup,
'created_at' => date('Y-m-d G:i:s')
]);
}
print "Basegroups are succesfuly created! \n";
}
}
<file_sep>/app/Http/Helpers/DateHelper.php
<?php
use \Carbon\Carbon;
trait DateHelper
{
/*
* Parse date format to local time
* See: http://carbon.nesbot.com/docs/
* @return dutch date form i.e. dinsdag 07 november 2017
*/
public static function localize($date)
{
setlocale(LC_TIME, 'nl_NL.utf8');
$parsed = Carbon::parse($date);
$nl_format = $parsed->formatLocalized('%A %d %B %Y');
return $nl_format;
}
}<file_sep>/database/seeds/RoleUserTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class RoleUserTableSeeder extends Seeder
{
private $table = "role_user";
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$total_users = $this->_usersCount('coaches') + $this->_usersCount('students');
DB::table($this->table)->delete();
for($i = 1; $i < $total_users; $i++) {
if($i == 1) {
$id = 1;
} elseif ($i > 1 && $i <= 10) {
$id = 2;
} elseif( $i > 10) {
$id = 3;
} else {
$id = 1;
}
DB::table($this->table)->insert([
'user_id' => $i,
'role_id' => $id
]);
}
print "Users are assigned to role! \n";
}
private function _usersCount($user)
{
try {
$user = File::get("database/data/{$user}.json");
$arr = json_decode($user, true);
return count($arr);
} catch (Exception $e) {
print "Message: {$e->message}\n";
}
return 0;
}
}
|
ea43c66ce435f59c2de513cfb9bea3f3782ca0e7
|
[
"Markdown",
"PHP",
"Shell"
] | 23 |
PHP
|
AO15A1LM/laterna-magica
|
26062f30cd166ff9679d1e769a6212e4b9773c3d
|
4fb6d2af20557f77316a6d2047f035bb4880ca69
|
refs/heads/master
|
<repo_name>AFMS-Rowan-Software-Projects/Microservice-Project-Spring2020<file_sep>/ui/pages/_App.js
// import App from 'next/app'
import "../css/theme.scss"
import React from "react";
import fetch from "node-fetch";
const PROD_URL = "http://example"; // TODO: implement
const WEB_URL = process.env.NODE_ENV !== "production" ? "http://localhost:3000" : PROD_URL;
// this is the url of the webpage which is localhost unless this is running in production
export const API_URL = `${WEB_URL}/api`;
// TODO: use this instead of exporting the url
export async function api_fetch(req) {
let res;
await fetch(`${API_URL}/${req}`)
.then(res => res.json())
.then((data => {res = data}));
return res;
}
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
// Only uncomment this method if you have blocking data requirements for
// every single page in your application. This disables the ability to
// perform automatic static optimization, causing every page in your app to
// be server-side rendered.
//
// MyApp.getInitialProps = async (appContext) => {
// // calls page's `getInitialProps` and fills `appProps.pageProps`
// const appProps = await App.getInitialProps(appContext);
//
// return { ...appProps }
// }
export default MyApp<file_sep>/ui/pages/courses/[...id].js
import React from "react";
import {useRouter} from "next/router";
import Page from "../../components/Page";
import fetch from "node-fetch";
import {Button} from "react-bootstrap";
import {API_URL} from "../_App";
import Error500 from "../../components/error/Error500";
const Course = props => {
const router = useRouter();
// if there's an error, display an error page instead of the course info
// TODO: display the actual error instead of just a 500
if (props.err) {
return (
<div>
<Error500/>
</div>
)
}
return (
<div>
<Page>
<div>
<h1>{props.course.CourseName}</h1>
<p>{props.course.CourseDesc}</p>
<p>Fees: {props.course.Fees}</p>
<p>Tuition: {props.course.Tuition}</p>
<Button variant={"primary"}>Register</Button>
</div>
</Page>
</div>
)
};
Course.getInitialProps = async context => {
const query = context.query.id[0]; // this is the part of the url after the /courses/
const props = {};
try {
// get the specified course
await fetch(`${API_URL}/courses/${query}`)
.then(res => res.json())
.then((data => {props.course = data}));
} catch (e) {
props.err = e; // store any potential error
}
return props;
};
export default Course;<file_sep>/course-management/index.js
const PORT = 3001;
const API_URL = "http://pinizz68.somee.com/"
const express = require("express");
const app = express();
const proxy = require("express-http-proxy");
// forward everything through the proxy
app.use("/", proxy(API_URL));
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`);
})<file_sep>/ui/components/error/Error500.js
import React from "react";
import Page from "../Page";
// TODO: create actual error page system
export default class Error500 extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Page>
<h1>Error 500</h1>
<h4>Gadzooks!</h4>
<p>Something went wrong</p>
</Page>
</div>
);
}
}
<file_sep>/ui/pages/api/[...args].js
import { createProxyMiddleware } from "http-proxy-middleware";
export const config = {
api: {
bodyParser: false
}
};
export default createProxyMiddleware({
target: "http://localhost:3001/",
changeOrigin: true,
api: {
bodyParser: false
}
});
<file_sep>/ui/components/Page.js
import React from "react";
import Header from "./Header";
import Container from "react-bootstrap/Container";
import {Collapse, Nav, Navbar, NavLink, Row} from "react-bootstrap";
import CoursePreview from "./CoursePreview";
import Head from "next/head";
export default class Page extends React.Component {
render() {
return (
<div className={"wrapper"}>
<Head>
<title>ABC Training</title>
</Head>
<Header/>
<Container fluid={true} className={"content"}>
<Row className={"h-100"}>
<div className={"sidebar pt-3 col-12 col-sm-7 col-md-4 col-lg-3 d-none d-md-block"}>
<div>
<Navbar variant={"dark"}>
<Nav className={"flex-column"}>
<NavLink>Registration</NavLink>
<div className={"ml-5"}>
<NavLink active={false}>New students</NavLink>
<NavLink active={false}>Current students</NavLink>
</div>
<NavLink active={false}>Tuition</NavLink>
<div className={"ml-5"}>
<NavLink active={false}>Payment options</NavLink>
<NavLink active={false}>Reduced rates</NavLink>
</div>
<NavLink active={false} href={"/admin"}>Admin</NavLink>
<div className={"ml-5"}>
<NavLink active={false} href={"/admin/create"}>Create course</NavLink>
</div>
<NavLink active={false}>Information sessions</NavLink>
<NavLink active={false}>Contact</NavLink>
</Nav>
</Navbar>
</div>
</div>
<div className={"col px-4 pt-3"}>
{this.props.children}
</div>
</Row>
</Container>
</div>
);
}
}<file_sep>/README.md
# Microservice-Project-Spring2020
ASRC Federal Mission Solutions is in the process of evaluating some of our larger programs for decomposition into microservices. The team will start with a single, monolithic application of their choosing and decompose it into a group of microservices that provide the same functionality. The solution will leverage Docker Containers for the runtime environment. The team’s experience and recommendations will provide valuable insights for AFMS into software decomposition process.
## How to use this repository
First, clone this project with `git clone https://github.com/AFMS-Rowan-Software-Projects/Microservice-Project-Spring2020.git`
and navigate into the created directory.
At the root of the project, there are several directories, each corresponding to a specific microservice. All code
should be inside one of those directories.
Before making changes, make sure you are not on the master branch. Use `git checkout <branch>` to change branches. You
should also make sure everything is up-to-date by running `git pull`.
To upload your work, commit all of your changes using `git commit <path> -m "<message>"` and push them up by using
`git push origin <branch>`. **DO NOT PUSH TO MASTER UNLESS YOU'RE ABSOLUTELY SURE OF WHAT YOU'RE DOING.**
|
eac786bbc3b657e3b194fa9ad48fc85b9e4e80a1
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
AFMS-Rowan-Software-Projects/Microservice-Project-Spring2020
|
a87fa18930a1cda24ece4fd7ded2a3ef58c32628
|
c73609854feead57f32a25e3d9c3b9e2e00de1ec
|
refs/heads/master
|
<file_sep>//
// Created by JerryZhu on 2018/6/5.
//
#include "include/v8.h"
#ifndef V8DEMO_CONTEXTWRAPPER_H
#define V8DEMO_CONTEXTWRAPPER_H
#define OBJ_TEMPLATE(obj,isolate) Local<ObjectTemplate> obj = ObjectTemplate::New(isolate)
#define EXPOSE(obj,isolate, jsname, func) obj->Set(String::NewFromUtf8(isolate, jsname, NewStringType::kNormal).ToLocalChecked(),FunctionTemplate::New(isolate, func));
using namespace v8;
class ContextWrapper {
public:
static Local<Context> createContext1(Isolate *isolate);
static Local<Context> createContext2(Isolate *isolate);
static Local<Context> createContext3(Isolate *isolate);
};
#endif //V8DEMO_CONTEXTWRAPPER_H
<file_sep>
# v8demo
基于chromeV8引擎展示C++与js互调逻辑的android项目
### js调用C++的方法:
```c++
v8Helper::Initialize();
Isolate::Scope isolate_scope(v8Helper::GetIsolate());
// Create a stack-allocated handle scope.
HandleScope handle_scope(v8Helper::GetIsolate());
// Create a new context.
Local<Context> context =creatContext(v8Helper::GetIsolate());
context_.Reset(v8Helper::GetIsolate(),context);
if (context.IsEmpty())
{
LOGI("Error creating context\n");
}
// Enter the context for compiling and running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
bool result = v8Helper::ExecuteString(context->GetIsolate(),
String::NewFromUtf8(context->GetIsolate(), jsSource,NewStringType::kNormal).ToLocalChecked(),true, true);
LOGI("JS Script Execute Result :%d", result);
```
```c++
// Creates a new execution environment containing the built-in functions.
v8::Local<v8::Context> CreateContext(v8::Isolate* isolate) {
// Create a template for the global object.
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
// Bind the global 'print' function to the C++ Print callback.
global->Set(v8::String::NewFromUtf8(isolate, "print", v8::NewStringType::kNormal)
v8::FunctionTemplate::New(isolate, print))
// Bind the global 'read' function to the C++ Read callback.
global->Set(v8::String::NewFromUtf8(isolate, "add", v8::NewStringType::kNormal).ToLocalChecked(),v8::FunctionTemplate::New(isolate, add));
return Context::New(isolate,0,global);
}
```
```c++
void LocalCFunction::add(const FunctionCallbackInfo <Value> &args)
{
int a = args[0]->Uint32Value();
int b = args[1]->Uint32Value();
args.GetReturnValue().Set(
Integer::New(args.GetIsolate(), a+b));
LOGI("add is called");
}
```
```c++
void LocalCFunction::print(const FunctionCallbackInfo <Value> &args)
{
callbackInfo ="";
bool first = true;
for (int i = 0; i < args.Length(); i++) {
HandleScope handle_scope(args.GetIsolate());
if (first) {
first = false;
} else {
printf(" 1111");
}
String::Utf8Value str(args.GetIsolate(),args[i]);
LOGI("print is called : %s",*str);
std::string result(*str);
callbackInfo += (result + ", ");
}
fflush(stdout);
}
```
```JavaScript
var y = add(20, 30);
print(y);
```
不管是js调用C++的方法,还是C++调用js的方法,对这些方法的包装都应该是v8初始化完成后最先操作的。在 ``Local<Context> context =creatContext(v8Helper::GetIsolate());`` 之前的操作都是v8初始化常规代码我做了一些简单的封装,首先创建一个全局对象的模板然后绑定C++的方法到字符串上,js就可以用此字符串来调用绑定的方法。应该注意到这些绑定在执行js字符串之前就已经进行了。
### C++调用js方法:
```c++
v8Helper::Initialize();
Isolate::Scope isolate_scope(v8Helper::GetIsolate());
// Create a stack-allocated handle scope.
HandleScope handle_scope(v8Helper::GetIsolate());
// Create a new context.
Local<Context> context =creatContext(v8Helper::GetIsolate());
context_.Reset(v8Helper::GetIsolate(),context);
if (context.IsEmpty())
{
LOGI("Error creating context\n");
}
// Enter the context for compiling and running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
bool result = v8Helper::ExecuteString(context->GetIsolate(),
String::NewFromUtf8(context->GetIsolate(), jsSource,
NewStringType::kNormal).ToLocalChecked(),true, true);
LOGI("JS Script Execute Result :%d", result);
//调用js方法
Local<String> process_name =String::NewFromUtf8(v8Helper::GetIsolate(), "jsFunction", NewStringType::kNormal)
.ToLocalChecked();
Local<Value> process_val;
// If there is no Process function, or if it is not a function,
if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||!process_val->IsFunction()) {
LOGI("initView is not a function\n");
}
// It is a function; cast it to a Function
Local<Function> process_fun = Local<Function>::Cast(process_val);
process_.Reset(v8Helper::GetIsolate(),process_fun);
```
```JavaScript
var x = [7, 8, 'jsarray', 7 * 8];
print(x);
function jsFunction(){
var y = add(20, 30);
print(y)
}
```
注意 ``context_.Reset(GetIsolate(), context);`` 这一句是用来保存当前上下文句柄的, ``process_.Reset(GetIsolate(), process_fun);`` 是用来保存在js找出来的方法的句柄的,这两句是我们在以后的任何时候都可以调用js方法的关键。中间的一些代码都很常规,就是找出js中的方法名然后转成方法。应该注意到找出js方法的操作是在脚本加载并且执行完之后进行的,这是因为如果在加载js脚本之前找js的方法是肯定找不到的。context_是Global<Context>类型,process_是Global<Function>类型,这两个全局类型的对象其实是用来保存当前的上下文环境和需要以后来执行的方法的句柄的。以后我们我们可以通过这两个句柄,进入到相应上下文环境中执行相应的方法。接下来看一下,我们是怎么在C++中调用在js中找出来的这个方法的:
```c++
// Create a handle scope to keep the temporary object references.
HandleScope handle_scope(v8Helper::GetIsolate());
v8::Local<v8::Context> context = v8::Local<v8::Context>::New(v8Helper::GetIsolate(), context_);
// Enter this processor's context so all the remaining operations
// take place there
Context::Scope context_scope(context);
// Set up an exception handler before calling the Process function
TryCatch try_catch(v8Helper::GetIsolate());
const int argc = 0;
Local<Value> argv[argc] = {};
v8::Local<v8::Function> process =v8::Local<v8::Function>::New(v8Helper::GetIsolate(), process_);
Local<Value> result;
if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
String::Utf8Value error(v8Helper::GetIsolate(), try_catch.Exception());
LOGI("call js function error:%s",*error);
}
```
首先是创建一栈区域来保存当前临时对象引用。红框内的方法就是把之前保存``context_`` ,和 ``process_`` 对象中的句柄拿出来,先进入相应的上下文,然后在对应的上下文环境中拿到对应的方法来执行。基本C++调用js方法都是这个套路,这里argc为0是调用无参的js方法,调用有参的js方法,我还没试不过按照process.cc中的套路也应该没什么问题。
## js调C++类:
这里有两种情况:
* 在C++中创建类的对象,然后把对象作为参数传递给js,在js中访问对象的属性和方法。
* 在js中创建对象,在JS中访问对象的属性和方法。
第一种情况:
这种情况下与调用C++普通方法的区别是js在调用C++方法的时候多了一个对象参数,由于这个参数是个C++类的对象,所以我们需要把这个C++对象封装成js对象。
```c++
// Create a handle scope to keep the temporary object references.
HandleScope handle_scope(v8Helper::GetIsolate());
v8::Local<v8::Context> context =v8::Local<v8::Context>::New(v8Helper::GetIsolate(), context_);
// Enter this processor's context so all the remaining operations
// take place there
Context::Scope context_scope(context);
Person person("SexMonkey",18);
Local<Object> person_object = WrapPerson(&person);
// Set up an exception handler before calling the Process function
TryCatch try_catch(v8Helper::GetIsolate());
const int argc = 1;
Local<Value> argv[argc] = {person_object};
v8::Local<v8::Function> process = v8::Local<v8::Function>::New(v8Helper::GetIsolate(), process_);
Local<Value> result;
if (!process->Call(context, context->Global(), argc, argv).ToLocal(&result)) {
String::Utf8Value error(v8Helper::GetIsolate(), try_catch.Exception());
LOGI("call js function error:%s",*error);
}
```
```c++
Local<Object> WrapPerson(Person *person) {
//Local scope for temporary handles.
EscapableHandleScope handle_scope(v8Helper::GetIsolate());
// Fetch the template for creating JavaScript person wrappers.
// It only has to be created once, which we do on demand.
if (person_template_.IsEmpty()) {
Local<ObjectTemplate> raw_template = MakePersonTemplate(v8Helper::GetIsolate());
person_template_.Reset(v8Helper::GetIsolate(), raw_template);
}
Local<ObjectTemplate> temp = Local<ObjectTemplate>::New(v8Helper::GetIsolate(),person_template_);
// Create an empty person wrapper.
Local<Object> result = temp -> NewInstance(v8Helper::GetIsolate() -> GetCurrentContext()).ToLocalChecked();
// Wrap the raw C++ pointer in an External so it can be referenced
// from within JavaScript.
Local<External> person_ptr = External::New(v8Helper::GetIsolate(),person);
// Store the person pointer in the JavaScript wrapper.
result->SetInternalField(0, person_ptr);
// Return the result through the current handle scope. Since each
// of these handles will go away when the handle scope is deleted
// we need to call Close to let one, the result, escape into the
// outer handle scope.
return handle_scope.Escape(result);
}
```
```c++
Local<ObjectTemplate> MakePersonTemplate(Isolate *isolate) {
EscapableHandleScope handle_scope(isolate);
Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
result->SetInternalFieldCount(1);
// Add accessors for each of the fields of the request.
result->SetAccessor(
String::NewFromUtf8(isolate, "name", NewStringType::kInternalized)
.ToLocalChecked(),
GetName);
result->SetAccessor(
String::NewFromUtf8(isolate, "age", NewStringType::kInternalized)
.ToLocalChecked(),
GetAge);
result->Set(String::NewFromUtf8(isolate, "setName", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, SetName));
result->Set(String::NewFromUtf8(isolate, "setAge", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, SetAge));
// Again, return the result through the current handle scope.
return handle_scope.Escape(result);
}
```
```c++
void GetName(Local<String> name, const PropertyCallbackInfo<Value>& info) {
// Extract the C++ request object from the JavaScript wrapper.
Person* person = UnwrapPerson(info.Holder());
// Fetch the path.
const std::string& cName = person -> getName();
// Wrap the result in a JavaScript string and return it.
info.GetReturnValue().Set(
String::NewFromUtf8(info.GetIsolate(), cName.c_str(),
NewStringType::kNormal,
static_cast<int>(cName.length())).ToLocalChecked());
}
```
```c++
void SetAge(const FunctionCallbackInfo <Value> &args)
{
LOGI("setAge is called");
Person* person = UnwrapPerson(args.Holder());
person -> setAge(args[0]->Uint32Value());
}
```
```c++
Person* UnwrapPerson(Local<Object> obj) {
Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
void* ptr = field->Value();
return static_cast<Person*>(ptr);
}
```
```JavaScript
function jsFunction(person){
print(person.name,person.age);
person.setName("test");
person.setAge(18);
print(person.name,person.age);
}
```
仔细看一下其实套路都是一样的,只不过是多了几步针对C++对象封装的专有步骤而已。主要的步骤就是先创建一个对象模板为这个对象模板绑定暴露给js访问C++对象的属性和方法的接口,注意对访问属性和访问方法的封装是不一样的,虽然这些套路都是固定的但也要注意其中的区别。
以我传递的person对象为例,当我在js中用person.name来访问person的name属性的时候,v8实际上就会调用 ``GetName(Local<String> name, const PropertyCallbackInfo<Value>& info)`` 方法,通过回调的info参数来解包装,转成你传递的对像类型的指针后,再用这个指针来访问对象的成员方法getName()来获取name的值,然后再设置成返回值其实也就是 ``person.name`` 的值。访问方法也一样,比如在js中访问 ``person.setName("123")`` ,v8会调用 ``SetName(const FunctionCallbackInfo <Value> &args)`` ;也是先解包装转换成你传递的对像类型的指针后再用对象的成员方法 ``setName(*str(args.GetIsolate(),args[0]));`` 通过v8回调给C++的参数来改变对象的属性值。注意以上 ``person.name`` , ``person.setName("123")`` ,name和setName都是你绑定对象模板时暴露给js接口的字符串,person也是你自己在js中使用的一个字符而已,你也可以用teacher,teacher.name。在模板创建完成后又经过了几个步骤主要是对刚才创建的模板与C++对象的关联。这些步骤完成后,一个C++对象就封装成为js对象了,然后把这个对象当做参数传给js,js就可以访问之前创建的模板上绑定的方法了。
第二种情况:
在js中创建C++的对象去访问对象的属性和方法,重点是对构造函数的绑定,绑定的时机与一般函数即全局函数一样,在js文件加载之前就可绑定,注意是在``creatContext(Isolate *isolate)`` 这个方法中进行绑定。
```c++
Local<Context> creatContext(Isolate *isolate) {
Local<ObjectTemplate> global = ObjectTemplate::New(isolate);
//Create the function template for the constructor, and point it to our constructor,
Handle<FunctionTemplate> person_template = FunctionTemplate::New(v8Helper::GetIsolate(),PersonConstructor);
//We can tell the scripts what type to report. In this case, just Person will do.
person_template->SetClassName(String::NewFromUtf8(v8Helper::GetIsolate(), "Person", NewStringType::kNormal)
.ToLocalChecked());
//This template is the unique properties of this type, we can set
//functions, getters, setters, and values directly on each new Person() object.
Handle<ObjectTemplate> person = person_template -> InstanceTemplate();
//Again, this is to store the c++ object for use in callbacks.
person -> SetInternalFieldCount(1);
person -> SetAccessor(
String::NewFromUtf8(isolate, "name", NewStringType::kInternalized)
.ToLocalChecked(),
GetName);
person -> SetAccessor(
String::NewFromUtf8(isolate, "age", NewStringType::kInternalized)
.ToLocalChecked(),
GetAge);
person -> Set(String::NewFromUtf8(isolate, "setName", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, SetName));
person -> Set(String::NewFromUtf8(isolate, "setAge", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, SetAge));
//Finally, we can tell the global scope that it now has a 'function' called Person,
//and that this function returns the template object above.
global -> Set(String::NewFromUtf8(isolate, "Person", NewStringType::kNormal)
.ToLocalChecked(),person_template);
return Context::New(isolate,0,global);
}
```
```c++
void PersonConstructor(const FunctionCallbackInfo <Value>& args)
{
LOGI("PersonConstructor is called");
if (!args.IsConstructCall())
{
LOGI("args is not PersonConstructor call");
}
Handle<Object> object = args.This();
HandleScope handle_scope(v8Helper::GetIsolate());
String::Utf8Value str(args.GetIsolate(),args[0]);
std::string name = *str;
int age = args[1] -> Uint32Value();
Person *person = new Person(name,age);
//Note that this index 0 is the internal field we created in the template!
object -> SetInternalField(0,v8::External::New (v8Helper::GetIsolate(),person));
}
```
```JavaScript
var per = new Person("JIMI",20);
print(per.name,per.age);
per.setName("test");
per.setAge(18);
print(per.name,per.age);
```
在 ``creatContext(Isolate *isolate)`` 中先是为构造函数创建函数模板,并将其指向我们的构造函数,SetClassName是告诉js脚本C++对象的类型,就是来区分普通字符串和C++类的,InstanceTemplate()是获取C++实例模板,接下来就是为js中创建C++对象访问其属性和方法绑定的C++接口,与我们传递C++对象给js函数然后用对象访问属性和方法的绑定过程是一样的,最后一步是设置person(name,age)这个全局函数给js调用;
构造函数的绑定需要注意一下,回调参数args数组索引对应着是初始化对象时的属性顺序,拿到属性值后,用这些属性值在C++中创建一个类的对象,然后再把对象指针设置到索引为0的地方,v8会在js中C++对象调用其属性和方法时从这个地方查询到真正的C++对象。
### C++调js类:
C++调用调用js的类与C++调用js方法有些许类似,都是在脚本加载并运行之后进行的。看一下代码会发现调用过程有点复杂,但基本套路都是一样的。
```c++
v8Helper::Initialize();
Isolate::Scope isolate_scope(v8Helper::GetIsolate());
// Create a stack-allocated handle scope.
HandleScope handle_scope(v8Helper::GetIsolate());
// Create a new context.
Local<Context> context =creatTestContext(v8Helper::GetIsolate());
context_.Reset(v8Helper::GetIsolate(),context);
if (context.IsEmpty())
{
LOGI("Error creating context\n");
}
// Enter the context for compiling and running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
bool result = v8Helper::ExecuteString(context->GetIsolate(),
String::NewFromUtf8(context->GetIsolate(), jsSource,NewStringType::kNormal).ToLocalChecked(),true, true);
LOGI("JS Script Execute Result :%d", result);
/*C++调用js类 start..*/
Local<String> js_data = String::NewFromUtf8(v8Helper::GetIsolate(), "Point", NewStringType::kInternalized)
.ToLocalChecked();
Local<Value> js_data_value = context -> Global() -> Get(js_data);
String::Utf8Value str(js_data_value);
LOGI("Point = %s \n",*str);
bool isFunction = js_data_value -> IsFunction();
LOGI("Point is function %d",isFunction);
bool isObject = js_data_value -> IsObject();
LOGI("Point is object %d",isObject);
Local<Object> js_data_object = Local<Object>::Cast(js_data_value);
// var newObj = new Point(1,2);
const int argc = 2;
Local<Value> argv[argc] = {};
argv[0] = Int32::New(v8Helper::GetIsolate(),7);
argv[1] = Int32::New(v8Helper::GetIsolate(),8);
Local<Value> newObject = js_data_object -> CallAsConstructor(context, argc, argv).ToLocalChecked();
LOGI("Point is function %d \n",newObject -> IsFunction());
LOGI("Point is object %d",newObject -> IsObject());
// newObj.show();
Local<Object> obj = Local<Object>::Cast(newObject);
Local<String> js_func_name = String::NewFromUtf8(v8Helper::GetIsolate(), "show", NewStringType::kInternalized).ToLocalChecked();
Local<Value> js_func_ref = obj->Get(js_func_name);
Local<Function> js_func = Local<Function>::Cast(js_func_ref);
js_data_value = js_func->Call(obj, 0, NULL) ;
String::Utf8Value str2(js_data_value);
LOGI("Point = %s \n",*str2);
//object.z;
Local<String> js_pro_name = String::NewFromUtf8(v8Helper::GetIsolate(), "z", NewStringType::kInternalized).ToLocalChecked();
Local<Value> js_pro_ref = obj->Get(js_pro_name);
String::Utf8Value pro(js_pro_ref);
LOGI("js object prototype :%s",*pro);
/*C++调用js类 end..*/
//调用js方法
Local<String> process_name =
String::NewFromUtf8(v8Helper::GetIsolate(), "initView", NewStringType::kNormal)
.ToLocalChecked();
Local<Value> process_val;
// If there is no Process function, or if it is not a function,
if (!context->Global()->Get(context, process_name).ToLocal(&process_val) ||
!process_val->IsFunction()) {
LOGI("initView is not a function\n");
}
// It is a function; cast it to a Function
Local<Function> process_fun = Local<Function>::Cast(process_val);
process_.Reset(v8Helper::GetIsolate(),process_fun);
```
```JavaScript
function Point(x,y){
this.x=x;
this.y=y;
}
Point.prototype.show=function(){
return '(x,y) = '+this.x+','+this.y;
}
Point.prototype.z = 1000;
```
首先将想要调用的js类的类名以字符串的形式转成v8能识别的字符串,然后``context -> Global() -> Get(js_data)`` , v8开始通过这个类名在js中找到相应的值,然后转通过相应的方法来先看看这个找出来的值是方法还是类,我们可以在脚本中看到这个值既是类又是方法,这其实是个构造方法,然后``Local<Object>::Cast(js_data_value);`` 将这个值转化成了js的类,接着``js_data_object -> CallAsConstructor(context, argc, argv).ToLocalChecked();`` ,是调用js类的构造方法并做一些属性的初始化操作,返回的就是js类的对象了,接下来就是用这个对象来调用js类的方法了,与之前C++调用js全局方法的方法是一样的。注意prototype是JavaScript类的一个关键字它可以指定类的属性,脚本中是把show()方法当做类的方法。可以用类的对象调用这个方法。
<file_sep>//
// Created by JerryZhu on 2018/5/28.
//
#include <string>
#include "LocalCFunction.h"
#include "v8Helper.h"
#include "Person.h"
Person* UnwrapPerson(Local<Object> obj);
void LocalCFunction::add(const FunctionCallbackInfo <Value> &args)
{
int a = args[0]->Uint32Value();
int b = args[1]->Uint32Value();
args.GetReturnValue().Set(
Integer::New(args.GetIsolate(), a+b));
LOGI("add is called");
}
std::string callbackInfo;
void LocalCFunction::print(const FunctionCallbackInfo <Value> &args)
{
callbackInfo ="";
bool first = true;
for (int i = 0; i < args.Length(); i++) {
HandleScope handle_scope(args.GetIsolate());
if (first) {
first = false;
} else {
printf(" 1111");
}
String::Utf8Value str(args.GetIsolate(),args[i]);
LOGI("print is called : %s",*str);
std::string result(*str);
callbackInfo += (result + ", ");
}
fflush(stdout);
}
void LocalCFunction::PersonConstructor(const FunctionCallbackInfo<Value> &args)
{
LOGI("PersonConstructor is called");
if (!args.IsConstructCall())
{
LOGI("args is not PersonConstructor call");
}
Handle<Object> object = args.This();
HandleScope handle_scope(v8Helper::GetIsolate());
String::Utf8Value str(args.GetIsolate(),args[0]);
std::string name = *str;
int age = args[1] -> Uint32Value();
Person *person = new Person(name,age);
//Note that this index 0 is the internal field we created in the template!
object -> SetInternalField(0,v8::External::New(v8Helper::GetIsolate(),person));
}
Person* UnwrapPerson(Local<Object> obj) {
Local<External> field = Local<External>::Cast(obj->GetInternalField(0));
void* ptr = field->Value();
return static_cast<Person*>(ptr);
}
void LocalCFunction::getName(Local<String> name, const PropertyCallbackInfo<Value> &info)
{
LOGI("getName is called ...");
// Extract the C++ request object from the JavaScript wrapper.
Person* person = UnwrapPerson(info.Holder());
// Fetch the path.
const std::string& cName = person -> getName();
// Wrap the result in a JavaScript string and return it.
info.GetReturnValue().Set(
String::NewFromUtf8(info.GetIsolate(), cName.c_str(),
NewStringType::kNormal,
static_cast<int>(cName.length())).ToLocalChecked());
}
void LocalCFunction::setName(const FunctionCallbackInfo<Value> &args)
{
LOGI("setName is called ...");
Person* person = UnwrapPerson(args.Holder());
String::Utf8Value str(args.GetIsolate(),args[0]);
// Fetch the path.
person ->setName(*str);
}
void LocalCFunction::getAge(Local<String> name, const PropertyCallbackInfo<Value> &info)
{
LOGI("getAge is called ...");
// Extract the C++ request object from the JavaScript wrapper.
Person* person = UnwrapPerson(info.Holder());
// Fetch the path.
const int cAge = person -> getAge();
// Wrap the result in a JavaScript int and return it.
info.GetReturnValue().Set(
Integer::New(info.GetIsolate(), cAge));
}
void LocalCFunction::setAge(const FunctionCallbackInfo<Value> &args)
{
LOGI("setAge is called");
Person* person = UnwrapPerson(args.Holder());
person -> setAge(args[0]->Uint32Value());
}
std::string LocalCFunction::getCallbackInfo()
{
return callbackInfo;
}
<file_sep>#include <jni.h>
#include <string>
#include "log.h"
#include "v8Helper.h"
#include "LocalCFunction.h"
jobject assetManager;
const char* js_call_c_method_soure;
const char* js_create_c_object_soure;
const char* c_call_js_method_soure;
const char* c_pass_object_toJs_soure;
const char* c_call_js_object_soure;
extern "C"
JNIEXPORT jstring
JNICALL
Java_com_boyaa_v8demo_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
static void _nativeInit(JNIEnv *env, jclass clazz,jobject assets)
{
assetManager = assets;
LOGI("native method _nativeInit ...");
js_call_c_method_soure = v8Helper::loadScriptSource(env, assets, "script/js_call_c_method.js");
js_create_c_object_soure = v8Helper::loadScriptSource(env, assets, "script/js_create_c_object.js");
c_call_js_method_soure = v8Helper::loadScriptSource(env, assets, "script/c_call_js_method.js");
c_pass_object_toJs_soure = v8Helper::loadScriptSource(env, assets, "script/c_pass_object_toJs.js");
c_call_js_object_soure = v8Helper::loadScriptSource(env, assets, "script/c_call_js_object.js");
v8Helper::Initialize();
}
static jstring _native_js_call_c_method(JNIEnv *env, jclass clazz)
{
LOGI("native method _native_js_call_c_method ...");
bool scriptExectueResult = v8Helper::js_call_c_method(js_call_c_method_soure);
std::string result ;
if(scriptExectueResult){
result = "script exectue ... \nresult : success\ncallbackinfo :";
}else{
result = "script exectue failed:";
}
return env->NewStringUTF((result +LocalCFunction::getCallbackInfo()).c_str());
}
static jstring _native_js_create_c_object(JNIEnv *env, jclass clazz)
{
LOGI("native method _native_js_create_c_object ...");
bool scriptExectueResult = v8Helper::js_create_c_object(js_create_c_object_soure);
std::string result ;
if(scriptExectueResult){
result = "script exectue ... \nresult : success\ncallbackinfo :";
}else{
result = "script exectue failed:";
}
return env->NewStringUTF((result +LocalCFunction::getCallbackInfo()).c_str());
}
static jstring _native_c_call_js_method(JNIEnv *env, jclass clazz)
{
LOGI("native method _native_c_call_js_method ...");
bool scriptExectueResult = v8Helper::c_call_js_method(c_call_js_method_soure);
std::string result ;
if(scriptExectueResult){
result = "script exectue ... \nresult : success\ncallbackinfo :";
}else{
result = "script exectue failed:";
}
return env->NewStringUTF((result +LocalCFunction::getCallbackInfo()).c_str());
}
static jstring _native_c_pass_object_toJs(JNIEnv *env, jclass clazz)
{
LOGI("native method _native_c_pass_object_toJs ...");
bool scriptExectueResult = v8Helper::c_pass_object_toJs(c_pass_object_toJs_soure);
std::string result ;
if(scriptExectueResult){
result = "script exectue ... \nresult : success\ncallbackinfo :";
}else{
result = "script exectue failed:";
}
return env->NewStringUTF((result +LocalCFunction::getCallbackInfo()).c_str());
}
static jstring _native_c_call_js_object(JNIEnv *env, jclass clazz)
{
LOGI("native method _native_c_call_js_object ...");
bool scriptExectueResult = v8Helper::c_call_js_object(c_call_js_object_soure);
std::string result ;
if(scriptExectueResult){
result = "script exectue ... \nresult : success\ncallbackinfo :";
}else{
result = "script exectue failed:";
}
return env->NewStringUTF((result +LocalCFunction::getCallbackInfo()).c_str());
}
static void _nativeDestory(JNIEnv *env, jclass clazz)
{
LOGI("native method _nativeDestory ...");
v8Helper::ShutDown();
}
static JNINativeMethod _methodTable[] = {
{ "native_js_call_c_method", "()Ljava/lang/String;", (void*)_native_js_call_c_method },
{ "native_js_create_c_object", "()Ljava/lang/String;", (void*)_native_js_create_c_object },
{ "native_c_call_js_method", "()Ljava/lang/String;", (void*)_native_c_call_js_method},
{ "native_c_pass_object_toJs", "()Ljava/lang/String;", (void*)_native_c_pass_object_toJs },
{ "native_c_call_js_object", "()Ljava/lang/String;", (void*)_native_c_call_js_object },
{ "nativeInit", "(Landroid/content/res/AssetManager;)V", (void*)_nativeInit },
{ "nativeDestory", "()V", (void*)_nativeDestory },
};
int JNI_OnLoad(JavaVM* vm, void* reserved)
{
LOGI("JNI_OnLoad ...");
JNIEnv* env = 0;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
{
return JNI_ERR;
}
jclass cls = env -> FindClass("com/boyaa/v8demo/MainActivity");
if (cls == 0)
{
LOGI("JNI_OnLoad cls null");
return JNI_ERR;
}
int len = sizeof(_methodTable) / sizeof(_methodTable[0]);
if (JNI_OK != env->RegisterNatives(cls, _methodTable, len))
{
LOGE( "_registerNativeMethods: failed");
if (env->ExceptionCheck())
{
env->ExceptionClear();
}
}
return JNI_VERSION_1_4;
}<file_sep>//
// Created by JerryZhu on 2018/5/25.
//
#include <sys/types.h>
#include <stdlib.h>
#include <android/asset_manager_jni.h>
#include <android/asset_manager.h>
#include <assert.h>
#include "include/libplatform/libplatform.h"
#include "v8Helper.h"
#include "log.h"
#include "ContextWrapper.h"
#include "LocalCFunction.h"
#include "Person.h"
Local<v8::Context> context;
Global<Context> context_;
Global<Function> function_;
static Global<ObjectTemplate> person_template_;
Global<Context>* v8Helper::getGlobalContext()
{
return &context_;
}
Global<Function>* v8Helper::getGlobalFunction()
{
return &function_;
}
bool v8Helper::ExecuteString(Isolate *isolate, Local<String> source, bool print_result,
bool report_exceptions)
{
LOGI("execute js source ....");
HandleScope handle_scope(isolate);
TryCatch try_catch(isolate);
Local<Context> context(isolate->GetCurrentContext());
Local<Script> script;
if (!Script::Compile(context, source).ToLocal(&script)) {
// Print errors that happened during compilation.
if (report_exceptions)
v8Helper::ReportException(isolate, &try_catch);
return false;
} else {
Local<Value> result;
if (!script->Run(context).ToLocal(&result)) {
assert(try_catch.HasCaught());
// Print errors that happened during execution.
if (report_exceptions)
v8Helper::ReportException(isolate, &try_catch);
return false;
} else {
assert(!try_catch.HasCaught());
if (print_result && !result->IsUndefined()) {
// If all went well and the result wasn't undefined then print
// the returned value.
String::Utf8Value str(isolate, result);
LOGI("execute js source result %s\n", *str);
}
return true;
}
}
}
void v8Helper::ReportException(Isolate *isolate, TryCatch *try_catch)
{
HandleScope handle_scope(isolate);
String::Utf8Value exception(isolate, try_catch->Exception());
// const char *exception_string = ToCString(exception);
Local<Message> message = try_catch->Message();
if (message.IsEmpty()) {
// V8 didn't provide any extra information about this error; just
// print the exception.
LOGI("exception_string ; %s\n", *exception);
} else {
// Print (filename):(line number): (message).
String::Utf8Value filename(isolate,
message->GetScriptOrigin().ResourceName());
Local<Context> context(isolate->GetCurrentContext());
int linenum = message->GetLineNumber(context).FromJust();
LOGI("exception_string : %s:%i: %s\n", *filename, linenum, *exception);
// Print line of source code.
String::Utf8Value sourceline(
isolate, message->GetSourceLine(context).ToLocalChecked());
LOGI("stderr :%s\n",*sourceline);
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn(context).FromJust();
for (int i = 0; i < start; i++) {
fprintf(stderr, " ");
}
int end = message->GetEndColumn(context).FromJust();
for (int i = start; i < end; i++) {
fprintf(stderr, "^");
}
fprintf(stderr, "\n");
Local<Value> stack_trace_string;
if (try_catch->StackTrace(context).ToLocal(&stack_trace_string) &&
stack_trace_string->IsString() &&
Local<v8::String>::Cast(stack_trace_string)->Length() > 0) {
String::Utf8Value stack_trace(isolate, stack_trace_string);
LOGI("exception_string : %s\n\n",*stack_trace);
}
}
}
Isolate::CreateParams create_params;
Isolate *isolate;
namespace v8::internal
{
void ReadNatives(){}
void DisposeNatives(){}
void SetNativesFromFile(v8::StartupData *s){}
void SetSnapshotFromFile(v8::StartupData *s){}
}
void v8Helper::Initialize()
{
LOGI("Initialize ...");
Platform *platform = platform::CreateDefaultPlatform();
V8::InitializePlatform(platform);
V8::Initialize();
create_params.array_buffer_allocator =
ArrayBuffer::Allocator::NewDefaultAllocator();
isolate =Isolate::New(create_params);
}
Isolate* v8Helper::GetIsolate()
{
return isolate;
}
void v8Helper::ShutDown()
{
GetIsolate()->Dispose();
V8::Dispose();
V8::ShutdownPlatform();
delete create_params.array_buffer_allocator;
}
//JS调用C++全局方法
bool v8Helper::js_call_c_method(const char *jsSource) {
Isolate::Scope isolate_scope(GetIsolate());
// Create a stack-allocated handle scope.
HandleScope handle_scope(GetIsolate());
// Create a new context.
Local<Context> context =ContextWrapper::createContext1(GetIsolate());
if (context.IsEmpty())
{
LOGI("Error creating context\n");
}
// Enter the context for compiling and running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
bool result = ExecuteString(context->GetIsolate(),
String::NewFromUtf8(context->GetIsolate(), jsSource,
NewStringType::kNormal).ToLocalChecked(),true, true);
LOGI("JS Script Execute Result :%d", result);
return result;
}
//在JS中创建C++对象,访问对象属性和方法
bool v8Helper::js_create_c_object(const char *jsSource) {
Isolate::Scope isolate_scope(GetIsolate());
// Create a stack-allocated handle scope.
HandleScope handle_scope(GetIsolate());
// Create a new context.
Local<Context> context =ContextWrapper::createContext2(GetIsolate());
if (context.IsEmpty())
{
LOGI("Error creating context\n");
}
// Enter the context for compiling and running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
bool result = ExecuteString(context->GetIsolate(),
String::NewFromUtf8(context->GetIsolate(), jsSource,
NewStringType::kNormal).ToLocalChecked(),true, true);
LOGI("JS Script Execute Result :%d", result);
return result;
}
//C++调用JS方法
bool v8Helper::c_call_js_method(const char *jsSource) {
Isolate::Scope isolate_scope(GetIsolate());
// Create a stack-allocated handle scope.
HandleScope handle_scope(GetIsolate());
// Create a new context.
Local<Context> context =ContextWrapper::createContext3(GetIsolate());
//store context
context_.Reset(v8Helper::GetIsolate(),context);
if (context.IsEmpty())
{
LOGI("Error creating context\n");
}
// Enter the context for compiling and running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
bool result = ExecuteString(context->GetIsolate(),
String::NewFromUtf8(context->GetIsolate(), jsSource,
NewStringType::kNormal).ToLocalChecked(),true, true);
LOGI("JS Script Execute Result :%d", result);
//调用js方法
Local<String> function_name =
String::NewFromUtf8(v8Helper::GetIsolate(), "jsFunction", NewStringType::kNormal)
.ToLocalChecked();
Local<Value> jsFunction_val;
// If there is no Process function, or if it is not a function,
if (!context->Global()->Get(context, function_name).ToLocal(&jsFunction_val) ||
!jsFunction_val->IsFunction()) {
LOGI("jsFunction is not a function\n");
}
// It is a function; cast it to a Function
Local<Function> jsFunction_fun = Local<Function>::Cast(jsFunction_val);
function_.Reset(v8Helper::GetIsolate(),jsFunction_fun);
//可以用context_和function_在以后的任何时候调用js方法,这里就直接调用了
// Create a handle scope to keep the temporary object references.
// HandleScope handle_scope(v8Helper::GetIsolate());
// v8::Local<v8::Context> context =
// v8::Local<v8::Context>::New(v8Helper::GetIsolate(), context_);
TryCatch try_catch(v8Helper::GetIsolate());
const int argc = 0;
Local<Value> argv[argc] = {};
// v8::Local<v8::Function> process =
// v8::Local<v8::Function>::New(v8Helper::GetIsolate(), process_);
Local<Value> call_result;
if (!jsFunction_fun -> Call(context, context->Global(), argc, argv).ToLocal(&call_result)) {
String::Utf8Value error(v8Helper::GetIsolate(), try_catch.Exception());
LOGI("call js function error:%s",*error);
}
return result;
}
Local<ObjectTemplate> MakePersonTemplate(Isolate *isolate) {
EscapableHandleScope handle_scope(isolate);
Local<ObjectTemplate> result = ObjectTemplate::New(isolate);
result->SetInternalFieldCount(1);
// Add accessors for each of the fields of the request.
result->SetAccessor(
String::NewFromUtf8(isolate, "name", NewStringType::kInternalized)
.ToLocalChecked(),
LocalCFunction::getName);
result->SetAccessor(
String::NewFromUtf8(isolate, "age", NewStringType::kInternalized)
.ToLocalChecked(),
LocalCFunction::getAge);
result->Set(String::NewFromUtf8(isolate, "setName", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, LocalCFunction::setName));
result->Set(String::NewFromUtf8(isolate, "setAge", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, LocalCFunction::setAge));
// Again, return the result through the current handle scope.
return handle_scope.Escape(result);
}
/**
* Utility function that wraps a C++ http person object in a
* JavaScript object.
*/
Local<Object> WrapPerson(Person *person) {
// Local scope for temporary handles.
EscapableHandleScope handle_scope(v8Helper::GetIsolate());
// Fetch the template for creating JavaScript person wrappers.
// It only has to be created once, which we do on demand.
if (person_template_.IsEmpty()) {
Local<ObjectTemplate> raw_template = MakePersonTemplate(v8Helper::GetIsolate());
person_template_.Reset(v8Helper::GetIsolate(), raw_template);
}
Local<ObjectTemplate> temp = Local<ObjectTemplate>::New(v8Helper::GetIsolate(),person_template_);
// Create an empty person wrapper.
Local<Object> result = temp -> NewInstance(v8Helper::GetIsolate() -> GetCurrentContext()).ToLocalChecked();
// Wrap the raw C++ pointer in an External so it can be referenced
// from within JavaScript.
Local<External> person_ptr = External::New(v8Helper::GetIsolate(),person);
// Store the person pointer in the JavaScript wrapper.
result->SetInternalField(0, person_ptr);
// Return the result through the current handle scope. Since each
// of these handles will go away when the handle scope is deleted
// we need to call Close to let one, the result, escape into the
// outer handle scope.
return handle_scope.Escape(result);
}
//C++传递对象给JS调用
bool v8Helper::c_pass_object_toJs(const char *jsSource) {
Isolate::Scope isolate_scope(GetIsolate());
// Create a stack-allocated handle scope.
HandleScope handle_scope(GetIsolate());
// Create a new context.
Local<Context> context =ContextWrapper::createContext3(GetIsolate());
//store context
context_.Reset(v8Helper::GetIsolate(),context);
if (context.IsEmpty())
{
LOGI("Error creating context\n");
}
// Enter the context for compiling and running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
bool result = ExecuteString(context->GetIsolate(),
String::NewFromUtf8(context->GetIsolate(), jsSource,
NewStringType::kNormal).ToLocalChecked(),true, true);
LOGI("JS Script Execute Result :%d", result);
//调用js方法
Local<String> function_name =
String::NewFromUtf8(v8Helper::GetIsolate(), "jsFunction", NewStringType::kNormal)
.ToLocalChecked();
Local<Value> jsFunction_val;
// If there is no Process function, or if it is not a function,
if (!context->Global()->Get(context, function_name).ToLocal(&jsFunction_val) ||
!jsFunction_val->IsFunction()) {
LOGI("jsFunction is not a function\n");
}
// It is a function; cast it to a Function
Local<Function> jsFunction_fun = Local<Function>::Cast(jsFunction_val);
function_.Reset(v8Helper::GetIsolate(),jsFunction_fun);
//可以用context_和function_在以后的任何时候调用js方法,这里就直接调用了
// Create a handle scope to keep the temporary object references.
// HandleScope handle_scope(v8Helper::GetIsolate());
// v8::Local<v8::Context> context =
// v8::Local<v8::Context>::New(v8Helper::GetIsolate(), context_);
Person person("<NAME>",20);
Local<Object> person_object = WrapPerson(&person);
TryCatch try_catch(v8Helper::GetIsolate());
const int argc = 1;
Local<Value> argv[argc] = {person_object};
// v8::Local<v8::Function> function =
// v8::Local<v8::Function>::New(v8Helper::GetIsolate(), function_);
Local<Value> call_result;
if (!jsFunction_fun -> Call(context, context->Global(), argc, argv).ToLocal(&call_result)) {
String::Utf8Value error(v8Helper::GetIsolate(), try_catch.Exception());
LOGI("call js function error:%s",*error);
}
return result;
}
//C++调用JS类
bool v8Helper::c_call_js_object(const char *jsSource) {
Isolate::Scope isolate_scope(GetIsolate());
// Create a stack-allocated handle scope.
HandleScope handle_scope(GetIsolate());
// Create a new context.
Local<Context> context =ContextWrapper::createContext3(GetIsolate());
if (context.IsEmpty())
{
LOGI("Error creating context\n");
}
// Enter the context for compiling and running the hello world script.
Context::Scope context_scope(context);
// Create a string containing the JavaScript source code.
bool result = ExecuteString(context->GetIsolate(),
String::NewFromUtf8(context->GetIsolate(), jsSource,
NewStringType::kNormal).ToLocalChecked(),true, true);
LOGI("JS Script Execute Result :%d", result);
//C++调用js类start
Local<String> js_data = String::NewFromUtf8(v8Helper::GetIsolate(), "Point", NewStringType::kInternalized)
.ToLocalChecked();
// PersistentBase::
Local<Value> js_data_value = context -> Global() -> Get(js_data);
String::Utf8Value str(js_data_value);
LOGI("Point = %s \n",*str);
bool isFunction = js_data_value -> IsFunction();
LOGI("Point is function %d",isFunction);
bool isObject = js_data_value -> IsObject();
LOGI("Point is object %d",isObject);
Local<Object> js_data_object = Local<Object>::Cast(js_data_value);
// var object = new Point(1,2);
const int argc = 2;
Local<Value> argv[argc] = {};
argv[0] = Int32::New(v8Helper::GetIsolate(),8);
argv[1] = Int32::New(v8Helper::GetIsolate(),9);
Local<Value> newObject = js_data_object -> CallAsConstructor(context, argc, argv).ToLocalChecked();
LOGI("Point is function %d \n",newObject -> IsFunction());
LOGI("Point is object %d",newObject -> IsObject());
// object.show();
Local<Object> obj = Local<Object>::Cast(newObject);
Local<String> js_func_name = String::NewFromUtf8(v8Helper::GetIsolate(), "show", NewStringType::kInternalized).ToLocalChecked();
Local<Value> js_func_ref = obj->Get(js_func_name);
Local<Function> js_func = Local<Function>::Cast(js_func_ref);
js_func->Call(obj, 0, NULL) ;
//object.z
Local<String> js_pro_name = String::NewFromUtf8(v8Helper::GetIsolate(), "z", NewStringType::kInternalized).ToLocalChecked();
Local<Value> js_pro_ref = obj->Get(js_pro_name);
String::Utf8Value pro(js_pro_ref);
LOGI("js object prototype :%s",*pro);
return result;
}
const char* v8Helper::loadScriptSource(JNIEnv *env, jobject assetManager, const char *name)
{
LOGI("loadScriptSource.................");
AAssetManager* mgr = AAssetManager_fromJava(env, assetManager);
if(mgr==NULL)
{
LOGI(" %s","AAssetManager==NULL");
return 0;
}
AAsset* asset = AAssetManager_open(mgr, name,AASSET_MODE_UNKNOWN);
if(asset==NULL)
{
return 0;
}
off_t bufferSize = AAsset_getLength(asset);
char *buffer=(char *)malloc(bufferSize+1);
buffer[bufferSize]=0;
int numBytesRead = AAsset_read(asset, buffer, bufferSize);
// free(buffer);
AAsset_close(asset);
return buffer;
}
<file_sep>var per = new Person("JIMI",20);
print(per.name,per.age);
per.setName("test");
per.setAge(18);
print(per.name,per.age);
<file_sep>//
// Created by JerryZhu on 2018/5/28.
//
#include "v8.h"
#include "log.h"
#ifndef V8DEMO_LOCALCFUNCTION_H
#define V8DEMO_LOCALCFUNCTION_H
using namespace v8;
class LocalCFunction {
public:
static void add(const FunctionCallbackInfo<Value>& args);
static void print(const FunctionCallbackInfo<Value>& args);
static void PersonConstructor(const FunctionCallbackInfo<Value>& args);
static void getName(Local<String> name, const PropertyCallbackInfo<Value>& info);
static void getAge(Local<String> name, const PropertyCallbackInfo<Value>& info);
static void setName(const FunctionCallbackInfo <Value> &args);
static void setAge(const FunctionCallbackInfo <Value> &args);
static std::string getCallbackInfo();
};
#endif //V8DEMO_LOCALCFUNCTION_H
<file_sep>function Point(x,y){
this.x=x;
this.y=y;
}
Point.prototype.show=function(){
print('(x,y) = '+this.x+','+this.y);
}
Point.prototype.z = 1000;<file_sep>//
// Created by JerryZhu on 2018/6/5.
//
#include "ContextWrapper.h"
#include "LocalCFunction.h"
Local<Context> ContextWrapper::createContext1(Isolate *isolate)
{
// Create a template for the global object.
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
// Bind the global 'print' function to the C++ Print callback.
global->Set(
v8::String::NewFromUtf8(isolate, "print", v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::FunctionTemplate::New(isolate, LocalCFunction::print));
global->Set(
v8::String::NewFromUtf8(isolate, "add", v8::NewStringType::kNormal)
.ToLocalChecked(),
v8::FunctionTemplate::New(isolate, LocalCFunction::add));
return Context::New(isolate,0,global);
}
Local<Context> ContextWrapper::createContext2(Isolate *isolate)
{
// Create a template for the global object.
OBJ_TEMPLATE(global,isolate);
// Bind the global 'print' function to the C++ Print callback.
EXPOSE(global,isolate,"print",LocalCFunction::print);
EXPOSE(global,isolate,"add",LocalCFunction::add);
//Create the function template for the constructor, and point it to our constructor,
Local<FunctionTemplate> person_template = FunctionTemplate::New(isolate,LocalCFunction::PersonConstructor);
//We can tell the scripts what type to report. In this case, just Person will do.
person_template->SetClassName(String::NewFromUtf8(isolate, "Person", NewStringType::kNormal)
.ToLocalChecked());
//This template is the unique properties of this type, we can set
//functions, getters, setters, and values directly on each new Person() object.
Local<ObjectTemplate> person = person_template -> InstanceTemplate();
//Again, this is to store the c++ object for use in callbacks.
person -> SetInternalFieldCount(1);
person -> SetAccessor(
String::NewFromUtf8(isolate, "name", NewStringType::kInternalized)
.ToLocalChecked(),
LocalCFunction::getName);
person -> SetAccessor(
String::NewFromUtf8(isolate, "age", NewStringType::kInternalized)
.ToLocalChecked(),
LocalCFunction::getAge);
person -> Set(String::NewFromUtf8(isolate, "setName", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, LocalCFunction::setName));
person -> Set(String::NewFromUtf8(isolate, "setAge", NewStringType::kNormal)
.ToLocalChecked(),
FunctionTemplate::New(isolate, LocalCFunction::setAge));
//Finally, we can tell the global scope that it now has a 'function' called Person,
//and that this function returns the template object above.
global -> Set(String::NewFromUtf8(isolate, "Person", NewStringType::kNormal)
.ToLocalChecked(),person_template);
return Context::New(isolate,0,global);
}
Local<Context> ContextWrapper::createContext3(Isolate *isolate)
{
// Create a template for the global object.
OBJ_TEMPLATE(global,isolate);
// Bind the global 'print' function to the C++ Print callback.
EXPOSE(global,isolate,"print",LocalCFunction::print);
EXPOSE(global,isolate,"add",LocalCFunction::add);
return Context::New(isolate,0,global);
}<file_sep>//
// Created by JerryZhu on 2018/5/18.
//
#include <android/log.h>
#ifndef V8DEMO_LOG_H
#define V8DEMO_LOG_H
#define LOG_TAG "v8demojni"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)
#endif //V8DEMO_LOG_H
<file_sep>//
// Created by JerryZhu on 2018/5/25.
//
#ifndef V8DEMO_V8HELPER_H
#define V8DEMO_V8HELPER_H
#define OBJ_TEMPLATE(obj,isolate) Local<ObjectTemplate> obj = ObjectTemplate::New(isolate)
#define EXPOSE(obj,isolate, jsname, func) obj->Set(String::NewFromUtf8(isolate, jsname, NewStringType::kNormal).ToLocalChecked(),FunctionTemplate::New(isolate, func));
#include <string>
#include <jni.h>
#include "include/v8.h"
using namespace v8;
class v8Helper {
public:
static void ReportException(Isolate* isolate, TryCatch* try_catch);
static bool ExecuteString(Isolate* isolate, Local<String> source,
bool print_result,
bool report_exceptions);
static void Initialize();
static Isolate* GetIsolate();
static void ShutDown();
static const char *loadScriptSource(JNIEnv *env, jobject assetManager, const char* name);
static Global<Function>* getGlobalFunction();
static Global<Context>* getGlobalContext();
static bool js_call_c_method(const char *soure);
static bool js_create_c_object(const char *soure);
static bool c_call_js_method(const char *soure);
static bool c_pass_object_toJs(const char *soure);
static bool c_call_js_object(const char *soure);
};
#endif //V8DEMO_V8HELPER_H
|
363c96ce0af9ea74cf99ec0fcac88fbcdfa87fa7
|
[
"Markdown",
"C",
"JavaScript",
"C++"
] | 11 |
C++
|
monkey-jz/v8demo
|
b5af6ac268639b7e16a631b007bac2c3f6ac1d21
|
ef4ff1453763bc701242ee3d60b0a61b56b48371
|
refs/heads/master
|
<repo_name>saurabhgupta050890/react-calculator<file_sep>/src/App.js
import React, { useState, useEffect } from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
let [expression, setExpression] = useState(0);
const clickHandler = (e, key) => {
let ex = expression;
console.log(key);
switch (key) {
case "AC":
setExpression(0);
break;
case "=":
if (/[+\-\/X]/gi.test(ex)) {
ex = evaluateExp();
setExpression(ex);
}
break;
case "+":
case "-":
case "X":
case "/":
if (/[+\-\/X]/gi.test(ex) && !endsWithExp(ex)) {
ex = evaluateExp();
ex = ex + key;
setExpression(ex);
} else if (!endsWithExp(ex)) {
ex = ex + key;
setExpression(ex);
}
break;
default:
ex = ex + key;
setExpression(ex);
}
}
const evaluateExp = () => {
console.log("evaluate");
let parts = expression.split(/[+\-\/X]/gi);
let operator = expression.match(/[+\-\/X]/gi)[0];
let left = Number(parts[0]);
let right = Number(parts[1]);
let result;
console.log(operator);
switch (operator) {
case "+":
result = left + right;
break;
case "-":
result = left - right;
break;
case "X":
result = left * right;
break;
case "/":
result = (left / right).toFixed(2);
break;
default:
result = 0;
}
console.log(result);
return result.toString();
}
const endsWithExp = (str) => {
console.log(str);
return str.endsWith("+") || str.endsWith("-") || str.endsWith("/") || str.endsWith("X");
}
let buttons = ["7", "8", "9", "+", "6", "5", "4", "-", "3", "2", "1", "X", "0", "AC", "=", "/"];
return (
<div className="App">
<div className="container">
<div className="display">{expression}</div>
<div className="buttons">
{buttons.map(x => {
return (<div className="button" key={x} onClick={(e) => clickHandler(e, x)}> {x} </div>)
})}
</div>
</div>
</div>
);
}
export default App;
|
81c53829469d9ab1f5db40a1535b73afa780c820
|
[
"JavaScript"
] | 1 |
JavaScript
|
saurabhgupta050890/react-calculator
|
a15ab5284485fa75cbbf320a0bd070fef2d54be3
|
617c8d9df79c36022e8fc2266a4f109357abdfe4
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormProcessing extends Controller
{
/**
*Find the specific Ajax call
*
*@param Request $request
*@return Response
*/
public function process(Request $request)
{
$task = $request->task;
if ("subscribe" === $task ) {
$response = $this->subscribe($request);
}
if ( "leadform" === $task) {
$response = $this->submitLeadForm($request);
}
return $response;
}
/**
*Check if user is subscribed and subscribes to mailing
*
*@param Request $request
*@return Response
*/
public function subscribe($request)
{
$this->validate($request, [
'email' => 'required|email'
]);
return ['test' => $request->input('email')];
}
/**
*Submits lead form, and validates it
*
*@param Request $request
*@return Response
*/
public function submitLeadForm($request)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'phoneNumber' => 'required|numeric|recurring|digits_between:10,15|contains:1234567890,0987654321,9876543210,0123456789,0101010101,1010101010'
]);
return ['test' => $request->input('phoneNumber')];
}
}
<file_sep><?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
class ValidatorServiceProvider extends ServiceProvider{
public function boot()
{
Validator::extend('contains', function ($attribute, $value, $parameters, $validator) {
foreach($parameters as $v) {
if(strpos($value, $v) !== false) {
return false;
}
}
return true;
});
Validator::extend('recurring', function ($attribute, $value, $parameters, $validator) {
if ($value[0] === $value[1] && $value[1] === $value[2]){
return false;
} else {
return true;
}
});
}
public function register()
{
}
}
?>
<file_sep>$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="_token"]').attr('content')
}
});
});
function validateEmail(email){
var patt = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
if(patt.test(email)){
return true;
}
return false;
}
function validatePhoneNumber(phoneNumber){
newPhoneNumber = phoneNumber.replace(/\D/g,'');
phoneNumberLength = newPhoneNumber.length;
if(phoneNumberLength >= 10 && phoneNumberLength <= 15) {
numberArray = newPhoneNumber.split('');
if(numberArray[0] === numberArray[1] && numberArray[1] === numberArray[2]) {
return false;
}
if(checkPattern(newPhoneNumber) === true) {
return false;
}
return true;
}
return false;
}
function checkPattern(phoneNumber){
patternArray = ["1234567890","0987654321","9876543210","0123456789",
"0101010101","1010101010"];
x = 0;
patternArray.forEach(function(pattern) {
if(phoneNumber.indexOf(pattern) !== -1) {
x = 1;
}
});
if(x == 1) {
return true;
} else {
return false;
}
}
$('#formSubmit').click( function( event ) {
event.preventDefault();
var Name = $("#Name").val();
var Email = $("#Email").val();
var Phone = $("#Phone").val();
if(validateEmail(Email) == false) {
alert("Please enter a valid email");
return;
}
if(validatePhoneNumber(Phone) == false){
alert("Please enter a valid Phone Number");
return;
} else {
$.ajax({
url : '/ajax/leadform',
type : 'POST',
dataType : "json",
data : {
"email" : Email,
"name" : Name,
"phoneNumber" : Phone },
success : function(data) {
alert("You have submitted the form!");
},
error : function(data) {
if(data['phoneNumber'] !== ''){
alert("Enter a valid phone number");
} else if(data['email'] !== '') {
alert("Enter a valid email");
}
}
});
}
});
$('#Email').blur(function(){
var Email = $("#Email").val();
if(validateEmail(Email) == false){
$('#Email').removeClass('is-valid');
$('#Email').addClass('is-invalid');
} else {
$('#Email').removeClass('is-invalid');
$('#Email').addClass('is-valid');
}
});
$('#Phone').blur(function(){
var Phone = $("#Phone").val();
if(validatePhoneNumber(Phone) == false){
$('#Phone').removeClass('is-valid');
$('#Phone').addClass('is-invalid');
} else {
$('#Phone').removeClass('is-invalid');
$('#Phone').addClass('is-valid');
}
});
|
2c99cfe891f7bad07b42f4229324fc63efd38ce4
|
[
"JavaScript",
"PHP"
] | 3 |
PHP
|
erik-montee/Developer-Challange
|
73c8c3df12e69d7885b2dd70bb86a3779c37bc72
|
3545b293225998562ad9a31b8912ec6e32678dea
|
refs/heads/master
|
<repo_name>svvay/KinoCMS<file_sep>/KinoCMS/migrations/0003_auto_20200417_1835.py
# Generated by Django 3.0.5 on 2020-04-17 15:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('KinoCMS', '0002_auto_20200417_1758'),
]
operations = [
migrations.AddField(
model_name='news',
name='cinema',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='KinoCMS.Cinema', verbose_name='Кинотеатр'),
),
migrations.AlterField(
model_name='news',
name='publication',
field=models.PositiveIntegerField(default=2020, help_text='Публикация'),
),
]
<file_sep>/KinoCMS/models.py
from django.db import models
from django.urls import reverse
from datetime import date
class Category(models.Model):
name = models.CharField(max_length=160)
description = models.TextField()
url = models.SlugField(max_length=100, unique=True)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
class Movie(models.Model):
title = models.CharField('Название фильма', max_length=160)
description = models.TextField('описание')
short_description = models.TextField('Краткое описание', blank=True, null=True, default=None)
poster = models.ImageField('Постер', upload_to='movies/')
category = models.ForeignKey(Category, verbose_name='Категория', on_delete=models.SET_NULL, null=True)
url = models.SlugField(max_length=100, unique=True)
is_active = models.BooleanField(default=False)
price_per_film = models.PositiveIntegerField(default=0, help_text='указываем цену')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('movie', kwargs={'slug': self.url})
class Meta:
verbose_name = 'Фильм'
verbose_name_plural = 'Фильмы'
class MoviShots(models.Model):
title = models.CharField(max_length=160)
description = models.TextField()
image = models.ImageField(upload_to='movies_shots/')
movie = models.ForeignKey(Movie, verbose_name='Фильмы', on_delete=models.CASCADE)
def __str__(self):
return self.title
class Meta:
verbose_name = 'Кадры из фильма'
verbose_name_plural = 'Кадры из фильмов'
class RatingStar(models.Model):
value = models.PositiveSmallIntegerField(default=0)
def __str__(self):
return self.value
class Meta:
verbose_name = 'Звезда рейтинга'
verbose_name_plural = 'Звезды рейтинга'
class Rating(models.Model):
ip = models.CharField(max_length=15)
star = models.ForeignKey(RatingStar, on_delete=models.CASCADE, verbose_name='звезда')
movie = models.ForeignKey(Movie, on_delete=models.CASCADE, verbose_name='фильм')
def __str__(self):
return f'{self.star} - {self.movie}'
class Meta:
verbose_name = 'Рейтинг'
verbose_name_plural = 'Рейтинги'
class Reviews(models.Model):
email = models.EmailField()
name = models.CharField(max_length=100)
text = models.TextField(max_length=5000)
parent = models.ForeignKey('self', verbose_name='Родитель', on_delete=models.SET_NULL, blank=True, null=True)
movie = models.ForeignKey(Movie, verbose_name='фильм', on_delete=models.CASCADE)
def __str__(self):
return f'{self.name} - {self.movie}'
class Meta:
verbose_name = 'Отзыв'
verbose_name_plural = 'Отзывы'
class Cinema(models.Model):
customer_name = models.CharField(max_length=64, blank=True, null=True, default=None)
description = models.TextField(blank=True, null=True, default=None)
address = models.TextField(blank=True, null=True, default=None)
contact_phone = models.CharField(max_length=48, blank=True, null=True, default=None)
def __str__(self):
return self.customer_name
class Meta:
verbose_name = 'Кинотеатр'
verbose_name_plural = 'Кинотеатры'
class News(models.Model):
name = models.CharField(max_length=100)
text = models.TextField(max_length=5000)
publication = models.PositiveIntegerField(default=2020, help_text='Публикация')
date_info = models.DateField('Акция стартует', default=date.today)
cinema = models.ForeignKey(Cinema, verbose_name='Кинотеатр', on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class Meta:
verbose_name = 'Новость'
verbose_name_plural = 'Новости'
<file_sep>/MainAPP/admin.py
from django.contrib import admin
class LocationUsersInLine(admin.TabularInline):
extra = 0
class StatusAdmin(admin.ModelAdmin):
list_display = ['name', 'is_active']
class UserAdmin(admin.ModelAdmin):
list_display = ['customer_name', 'customer_phone', 'customer_email', 'customer_address', 'comments', 'status']
<file_sep>/KinoCMS/urls.py
from django.urls import path
from .views import Movie, MoviesDetailViews, ActiveMovies, MoviesViews, CinemaViews, NewsDetail
urlpatterns = [
path('', MoviesViews.as_view(), name='movies'),
path('<slug:slug>/', MoviesDetailViews.as_view(), name='movie'),
path('placard', ActiveMovies.as_view(), name='placard'),
path('cinema', CinemaViews.as_view(), name='cinema'),
path('#', NewsDetail.as_view(), name='news'),
]
<file_sep>/KinoCMS/apps.py
from django.apps import AppConfig
class KinocmsConfig(AppConfig):
name = 'KinoCMS'
<file_sep>/MainAPP/views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.contrib.auth import login, authenticate
from .forms import RegistrationForm, LoginForm
def registration_view(request):
form = RegistrationForm(request.POST or None)
if form.is_valid():
new_user = form.save(commit=False)
username = form.cleaned_data['username']
password = form.cleaned_data['<PASSWORD>']
email = form.cleaned_data['email']
first_name = form.cleaned_data['first_name']
last_name = form.cleaned_data['last_name']
new_user.username = username
new_user.set_password(<PASSWORD>)
new_user.first_name = first_name
new_user.last_name = last_name
new_user.email = email
new_user.save()
login_user = authenticate(username=username, password=<PASSWORD>)
if login_user:
login(request, login_user)
return HttpResponseRedirect(reverse('placard'))
context = {
'form': form
}
return render(request, 'mainAPP/registration.html', context)
def login_view(request):
form = LoginForm(request.POST or None)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['<PASSWORD>']
login_user = authenticate(username=username, password=<PASSWORD>)
if login_user:
login(request, login_user)
return HttpResponseRedirect(reverse('placard'))
context = {
'form': form
}
return render(request, 'mainAPP/login.html', context)<file_sep>/KinoCMS/views.py
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.base import View
from .models import Movie, MoviShots, Cinema, News
class MoviesViews(ListView):
""" Вывод всех фильмов """
model = Movie
queryset = Movie.objects.all()
template_name = 'movie/movies.html'
class ActiveMovies(View):
"""Вывод фильмов в прокате"""
def get(self, request):
placard = Movie.objects.filter(is_active=True)
return render(request, 'movie/active_movies.html', {'placard_list': placard})
class MoviesDetailViews(DetailView):
""" Описание фильма"""
model = Movie
slug_field = 'url'
template_name = 'movie/movie_detail.html'
class CinemaViews(View):
"""Вывод кинотеатров"""
def get(self, request):
cinemas = Cinema.objects.all()
return render(request, 'cinema/cinema.html', {'cinemas_list': cinemas})
class NewsDetail(View):
""" Вывод новостей в кинотеатре"""
def get(self, request, pk):
news = Cinema.objects.get(id=pk)
return render(request, 'cinema/news.html', {'news_list': news})
<file_sep>/MainAPP/forms.py
from django.contrib.auth.models import User
from django import forms
class LoginForm(forms.Form):
username = forms.CharField()
passwords = forms.CharField(widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.fields['username'].label = 'Логин'
self.fields['passwords'].label = 'Пароль'
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['passwords']
if not User.objects.filter(username=username).exists():
raise forms.ValidationError(
'Пользователь с таким логином не зареган в системе')
user = User.objects.get(username=username)
if user and not user.check_password(password):
raise forms.ValidationError('Неверный пароль')
class RegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
password_check = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = [
'username',
'password',
'password_check',
'first_name',
'last_name',
'email',
]
def __init__(self, *args, **kwargs):
super(RegistrationForm, self).__init__(*args, **kwargs)
self.fields['username'].label = 'Логин'
self.fields['password'].label = '<PASSWORD>'
self.fields['password'].help_text = '<PASSWORD>'
self.fields['password_check'].label = 'Повторите пароль'
self.fields['first_name'].label = 'Введите имя'
self.fields['last_name'].label = 'Введите фамилию'
self.fields['email'].label = 'Ваша почта'
self.fields['email'].help_text = 'Указывайте реальный адрес'
def clean(self):
username = self.cleaned_data['username']
password = self.cleaned_data['password']
password_check = self.cleaned_data['<PASSWORD>']
email = self.cleaned_data['email']
if User.objects.filter(username=username).exists():
raise forms.ValidationError(
'Пользователь с таким логином уже зареган')
if User.objects.filter(email=email).exists():
raise forms.ValidationError(
'Пользователь с таким email уже зарегестрирован')
if password != password_check:
raise forms.ValidationError(
'Ваши пароли не совпдают, попробуйте снова')
<file_sep>/KinoCMS/migrations/0001_initial.py
# Generated by Django 3.0.5 on 2020-04-17 13:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=160)),
('description', models.TextField()),
('url', models.SlugField(max_length=100, unique=True)),
],
options={
'verbose_name': 'Категория',
'verbose_name_plural': 'Категории',
},
),
migrations.CreateModel(
name='Cinema',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('customer_name', models.CharField(blank=True, default=None, max_length=64, null=True)),
('description', models.TextField(blank=True, default=None, null=True)),
('address', models.TextField(blank=True, default=None, null=True)),
('contact_phone', models.CharField(blank=True, default=None, max_length=48, null=True)),
],
options={
'verbose_name': 'Кинотеатр',
'verbose_name_plural': 'Кинотеатры',
},
),
migrations.CreateModel(
name='Movie',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=160, verbose_name='Название фильма')),
('description', models.TextField(verbose_name='описание')),
('short_description', models.TextField(blank=True, default=None, null=True, verbose_name='Краткое описание')),
('poster', models.ImageField(upload_to='movies/', verbose_name='Постер')),
('url', models.SlugField(max_length=100, unique=True)),
('is_active', models.BooleanField(default=False)),
('price_per_film', models.PositiveIntegerField(default=0, help_text='указываем цену')),
('category', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='KinoCMS.Category', verbose_name='Категория')),
],
options={
'verbose_name': 'Фильм',
'verbose_name_plural': 'Фильмы',
},
),
migrations.CreateModel(
name='News',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('text', models.TextField(max_length=5000)),
('date_film', models.PositiveIntegerField(default=0, help_text='указываем дату')),
],
options={
'verbose_name': 'Новость',
'verbose_name_plural': 'Новости',
},
),
migrations.CreateModel(
name='RatingStar',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('value', models.PositiveSmallIntegerField(default=0)),
],
options={
'verbose_name': 'Звезда рейтинга',
'verbose_name_plural': 'Звезды рейтинга',
},
),
migrations.CreateModel(
name='Reviews',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('email', models.EmailField(max_length=254)),
('name', models.CharField(max_length=100)),
('text', models.TextField(max_length=5000)),
('movie', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='KinoCMS.Movie', verbose_name='фильм')),
('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='KinoCMS.Reviews', verbose_name='Родитель')),
],
options={
'verbose_name': 'Отзыв',
'verbose_name_plural': 'Отзывы',
},
),
migrations.CreateModel(
name='Rating',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('ip', models.CharField(max_length=15)),
('movie', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='KinoCMS.Movie', verbose_name='фильм')),
('star', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='KinoCMS.RatingStar', verbose_name='звезда')),
],
options={
'verbose_name': 'Рейтинг',
'verbose_name_plural': 'Рейтинги',
},
),
migrations.CreateModel(
name='MoviShots',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=160)),
('description', models.TextField()),
('image', models.ImageField(upload_to='movies_shots/')),
('movie', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='KinoCMS.Movie', verbose_name='Фильмы')),
],
options={
'verbose_name': 'Кадры из фильма',
'verbose_name_plural': 'Кадры из фильмов',
},
),
]
<file_sep>/MainAPP/urls.py
from django.contrib.auth.views import LogoutView
from django.urls import path, reverse_lazy
from .views import registration_view, login_view
urlpatterns = [
path('registration/', registration_view, name='registration'),
path('login/', login_view, name='login'),
path('logout/', LogoutView.as_view(next_page=reverse_lazy('placard')), name='logout'),
]
<file_sep>/MainAPP/models.py
from django.db import models
class User(models.Model):
customer_name = models.CharField(max_length=64, blank=True, null=True, default=None)
customer_phone = models.CharField(max_length=48, blank=True, null=True, default=None)
customer_email = models.EmailField(blank=True, null=True, default=None)
customer_address = models.CharField(max_length=100, blank=True, null=True, default=None)
comments = models.TextField(blank=True, null=True, default=None)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
# class<file_sep>/KinoCMS/admin.py
from django.contrib import admin
from .models import Category, Movie, MoviShots, RatingStar, Rating, Reviews, Cinema, News
class CinemaAdmin(admin.ModelAdmin):
list_display = ['id', 'customer_name', 'description', 'address', 'contact_phone']
admin.site.register(News)
admin.site.register(Cinema, CinemaAdmin)
admin.site.register(Category)
admin.site.register(Movie)
admin.site.register(MoviShots)
admin.site.register(RatingStar)
admin.site.register(Rating)
admin.site.register(Reviews)
<file_sep>/KinoCMS/migrations/0002_auto_20200417_1758.py
# Generated by Django 3.0.5 on 2020-04-17 14:58
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('KinoCMS', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='news',
name='date_film',
),
migrations.AddField(
model_name='news',
name='date_info',
field=models.DateField(default=datetime.date.today, verbose_name='Акция стартует'),
),
migrations.AddField(
model_name='news',
name='publication',
field=models.PositiveIntegerField(default=2019, help_text='Публикация'),
),
]
|
8610184b3fbae30cbb25cd7eba3bf1ef5085d069
|
[
"Python"
] | 13 |
Python
|
svvay/KinoCMS
|
36da3f3cf1b91d7cd9340a7cbb72b6277e5b76a7
|
fc034c5cfae89f527799352a73d81d8af0c50cf2
|
refs/heads/master
|
<repo_name>naudys15/place2Pay<file_sep>/tests/Feature/ExampleTest.php
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*
* @return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
$data = array(
'_token' => csrf_token(),
'name' => 'Test',
'email' => '<EMAIL>',
'reference' => 'test123456',
'description' => '123456',
'total' => 123456,
'currency' => 'COP'
);
$response = $this->from('/')->post('/sendRequest', $data);
$response->assertStatus(302);
$response = $this->get('/responseRequest');
$response->assertStatus(302);
}
}
<file_sep>/README.md
# Test for PlaceToPay
En el siguiente repositorio se encuentra la resolución de la prueba planteada por ustedes.
Fue realizada por parte de <NAME>, con el objeto de optar al cargo de desarrollador.
Fue realizada el 30/03/19.
Contiene dos ramas, la master contiene el paso 1 del proyecto desarrollado.
La estructura de código fue desarrollada de acuerdo a los estándares PSR-1, PSR-2 y PSR-4.
# Funcionamiento de la aplicación
De acuerdo a las especificaciones dadas por ustedes, se desarrolló la aplicación de la siguiente manera:
- Se tiene un formulario que recolecta los datos que son recomendados y necesarios de la api de ustedes, tales como:
- Nombre
- Correo electrónico
- Referencia
- Descripción
- Monto
- Moneda
- Una vez ingresados los mismos, se ejecuta la función sendRequest del controlador RequestToPay, que se encarga de recolectar los datos ingresados y los datos de autenticación, acto seguido se realiza una petición a la api, la cual retorna la respuesta satisfactoria, con el requestId y el processUrl.
- Se redirecciona al sitio de PlacetoPay usando la dirección processUrl, donde se ingresan los datos de pago correspondientes. Una vez realizado este proceso el sistema genera una respuesta del pago y permite volver al sitio.
- El sistema devuelve la respuesta y es capturada en la función receiveRequest del controlador
ResponseToPay, esta respuesta es almacenada en base de datos y en cache; en base de datos para obtener el histórico y en cache para mantener el registro de la última transacción realizada, y que sea visible para el usuario por un lapso de 60 minutos en la página principal.
# Estructura
El proyecto consta de dos controladores, llamados RequestToPay y ResponseToPay, uno está encargado de procesar la solicitud, y el otro la respuesta respectivamente. Estos controladores se encuentran ubicados en la ruta app\Http\Controllers\Request y app\Http\Controllers\Response respectivamente.
Consta de un modelo llamado Responses, el cual permite alojar las respuestas de la api en la base de datos. Este modelo se encuentra ubicado en la ruta app\Http\Models.
La libreria de Dnetix fue usada para simplificar el proceso de conexión y consumo de la api. Esta librería está ubicada en la ruta app\Libraries.
# Pruebas
Se realizaron pruebas unitarias para verificar la carga de las diferentes vistas y métodos del proyecto.
Para ejecutar las pruebas se debe ejecutar el comando vendor/bin/phpunit
Las pruebas realizadas fueron:
- Verificar que el home carga correctamente.
- Verificar que se envíe un formulario con datos al método sendRequest correctamente.
- Verificar que el método responseRequest cargue correctamente.
# Paso 2
Con respecto a realizar y usar un patron de diseño que permitar dar con una solución al problema desarrollado en el Paso 1, una sugerencia para ello es un patron estilo Composite, que permita reunir objetos sencillos en un objeto más complejo.
En este caso, tenemos tres clases sencillas llamadas Auth, Client y Payment, cada una por separado tiene su información propia, son independientes, y pueden existir sin la intervención de las otras. Pero en conjunto pueden formar una más compleja, que permite cumplir con el requerimiento de funcionalidad del proyecto.
Además existen los métodos llamados getAuth, getClient y getPayment. Todos ellos retornan información de sus respectivas clases. En la clase compleja se pudiera crear este método que sería implementado en las clases hijas.
Con la jerarquización se permite reutilizar código y se tendría una estructura de arbol, la cual es eficiente en búsquedas.
Por lo tanto, dado mi análisis al respecto, puedo afirmar que un patron similar al Composite, puede ser útil en este proyecto.
<file_sep>/app/Objects/Client.php
<?php
namespace App\Objects;
class Client
{
var $name;
var $surName;
var $email;
var $address;
public function __construct($name, $email, $surName = null, $address = null)
{
$this->name = $name;
$this->surName = $surName;
$this->email = $email;
$this->address = $address;
}
public function getClient()
{
if ($this->surName != null && $this->address != null) {
$client = array(
'name' => $this->name,
'surName' => $this->surName,
'email' => $this->email,
'address' => $this->address
);
return $client;
}
$client = array(
'name' => $this->name,
'email' => $this->email
);
return $client;
}
public function getName()
{
return $this->name;
}
public function getSurName()
{
return $this->surName;
}
public function getEmail()
{
return $this->email;
}
public function getAddress()
{
return $this->address;
}
}
|
0c8939a7c91855becd3184e3aa49c60220b6f043
|
[
"Markdown",
"PHP"
] | 3 |
PHP
|
naudys15/place2Pay
|
b21d93225007f3113f663b8577f80ffe5a332b51
|
4675654b041d4c517714d41b61ef1a4e1b7c6328
|
refs/heads/master
|
<file_sep>using System;
namespace pp_laba5
{
class IndexValue
{
public int index;
public int value;
}
class Program
{
/*Составить программу, содержащую процедуру вычисления
значений выражений по заданным формулам (из 1 л.р.)*/
static double T1ask(float x, float y)
{
try
{
double a = ((Math.Sqrt(Math.Abs(x - 1)) - Math.Sqrt(Math.Abs(y))) /
((1 + Math.Pow(x, 2) / 2) + (Math.Pow(y, 2) / 4)));
Console.WriteLine(a);
return a;
}
catch (Exception) { Console.WriteLine("ошибка ввода"); return 0; }
}
static int[] arrbuilder(int count, int from )
{
Random rnd = new Random(15);
int result = 0;
System.Collections.Generic.List<int> autocad = new System.Collections.Generic.List<int>();
for (int i = from; Math.Abs(i) < count; i--)
{
autocad.Add(i - rnd.Next());
if (i < 0) result++;
}
return autocad.ToArray();
}
static int T2ask(int[] arra)
/*Написать программу, в которой будет реализована процедура
вычисления кол-ва строк двумерного массива, в которых
присутствуют отрицательные элементы*/
{
int count = 0;
foreach (int i in arra)
count += (i < 0 ? 1: 0);
return count;
}
static IndexValue T3ask(int[] arr, Boolean amelia)
// если Амелия, то выдаст последний отрицательный элемент,
// если не Амелия, то выдаст последний элемент любого знака
/*Составить программу, содержащую функцию для нахождения
номера последнего отрицательного элемента одномерного
массива*/
{
int count = 0;
System.Collections.Generic.Stack<int> sanek = new System.Collections.Generic.Stack<int>();
System.Collections.Generic.Stack<IndexValue> anka = new System.Collections.Generic.Stack<IndexValue>();
foreach (int i in arr)
{
IndexValue semen = new IndexValue() {index = count, value = i};
anka.Push(semen); // и тут Семён вошёл в Анку
if(i < 0) sanek.Push(i);
count++;
}
IndexValue vasyan = new IndexValue() { index = count, value = sanek.Peek()};
return amelia ? vasyan: anka.Peek();// если Амелия, то выдаст последний отрицательный элемент,
// если не Амелия, то выдаст последний элемент любого знака
}
static IndexValue T3ask(int[] arr)
{
return T3ask(arr, true);
}
static void Main(string[] args)
{
int[] testArr = new int[9] { 1, 2, 3, 5, -3, 3, -23, -365, 4 };
int[] test1 = arrbuilder(23, 11);
Console.WriteLine("task 1 : "+T1ask(5,10));
Console.WriteLine("task 2 : " + T2ask(test1));
Console.WriteLine("task 3 : index-value{" + T3ask(testArr).index +" : "+ T3ask(testArr).value + "}");
Console.WriteLine("task 3* : index-value{" + T3ask(testArr, false).index + " : " + T3ask(testArr, false).value + "}");
}
}
}
|
b24b7db69d0dfd31ca807ffefb7a9f14fc7d0ec6
|
[
"C#"
] | 1 |
C#
|
SkSkreb/univer_pp_3-1
|
072a952cd67135a0981d7376c376eaefa51d99fb
|
67db3c5762c0b1fac0d510116c5de32524a5d678
|
refs/heads/main
|
<repo_name>shka2001/shka2001.github.io<file_sep>/app/js/index.js
const hamburger = document.querySelector(
".header .nav-bar .nav-list .hamburger"
);
const mobile_menu = document.querySelector(".header .nav-bar .nav-list ul");
const menu_item = document.querySelectorAll(
".header .nav-bar .nav-list ul li a"
);
const header = document.querySelector(".header.container");
hamburger.addEventListener("click", () => {
hamburger.classList.toggle("active");
mobile_menu.classList.toggle("active");
});
document.addEventListener("scroll", () => {
var scroll_position = window.scrollY;
if (scroll_position > 250) {
header.style.backgroundColor = "#26302E";
} else {
header.style.backgroundColor = "#77898C";
}
});
menu_item.forEach((item) => {
item.addEventListener("click", () => {
hamburger.classList.toggle("active");
mobile_menu.classList.toggle("active");
});
});
let inputName = document.getElementById("input-name");
let inputeEmail = document.getElementById("input-email");
let inputTextarea = document.getElementById("input-textarea");
let inputSubmit = document.getElementById("input-submit");
console.log(inputSubmit.value);
inputSubmit.addEventListener("click", function (e) {
let is_empty = false;
if (inputName.value == "") {
inputName.style.border = "thick solid #17c3b2";
is_empty = true;
console.log("Name is empty");
} else {
inputName.style.border = "thin solid black";
}
if (inputeEmail.value == "") {
inputeEmail.style.border = "thick solid #17c3b2";
is_empty = true;
console.log("Email is empty");
} else {
inputeEmail.style.border = "thin solid black";
}
if (inputTextarea.value == "") {
inputTextarea.style.border = "thick solid #17c3b2";
is_empty = true;
console.log("Textarea is empty");
} else {
inputTextarea.style.borderColor = "thin solid black";
}
if (!is_empty) {
window.location.assign("/sent.html");
}
});
let HangingCats = document.getElementById("HangingCats");
HangingCats.addEventListener("mousemove", function (event) {
let bcr = this.getBoundingClientRect();
let percentage = (event.clientX - bcr.left) / bcr.width;
let Blackcat = document.getElementById("Blackcat");
Blackcat.style.width = Math.round(percentage * 100.0) + "%";
});
|
38e9183d7c2e123cbd75b1e80f52c6f1bce66ebe
|
[
"JavaScript"
] | 1 |
JavaScript
|
shka2001/shka2001.github.io
|
71ae56a90a63c856322228e8d3e7046941ce4cf8
|
ff2d440e368fc0b122718dc241874136d55500ca
|
refs/heads/master
|
<repo_name>VinayagamD/hibernatetut<file_sep>/src/main/java/com/vinay/hibernatetut/PrimaryKeyDemo.java
/**
*
*/
package com.vinay.hibernatetut;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import model.Student;
/**
* @author Dell
*
*/
public class PrimaryKeyDemo {
/**
* @param args
*/
public static void main(String[] args) {
// create session factory
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
// create session
Session session = factory.getCurrentSession();
try {
// Create the student object
System.out.println("Creating new studnet object.... ");
Student student = new Student("Vinay","Ganesh","<EMAIL>");
// start a transaction
session.beginTransaction();
// save the student object
System.out.println("Saving the student... ");
session.save(student);
// commit the transaction
session.getTransaction().commit();
System.out.println("Done !");
}finally {
factory.close();
}
}
}
|
8939bdbc85ab61d0a5d79ce7c2e25054ffc27a1b
|
[
"Java"
] | 1 |
Java
|
VinayagamD/hibernatetut
|
b7939470fd87069443d72b7d90cbdb2b34077977
|
dea9f0bbb680147993dcf513c74962d05a8ebe36
|
refs/heads/master
|
<file_sep><?php
/**
* Description of Booking
*
* @author richard_lovell
*/
class Booking {
private $id;
private $flightName;
private $flightDate;
private $dateCreated;
private $status;
private $userId;
function getId() {
return $this->id;
}
function getFlightName() {
return $this->flightName;
}
function getFlightDate() {
return $this->flightDate;
}
function getDateCreated() {
return $this->dateCreated;
}
function getStatus() {
return $this->status;
}
function getUserId() {
return $this->userId;
}
function setId($id) {
$this->id = $id;
}
function setFlightName($flightName) {
$this->flightName = $flightName;
}
function setFlightDate($flightDate) {
$this->flightDate = $flightDate;
}
function setDateCreated($dateCreated) {
$this->dateCreated = $dateCreated;
}
function setStatus($status) {
$this->status = $status;
}
function setUserId($user_id) {
$this->userId = $user_id;
}
}
<file_sep><?php
/**
* Description of BookingMapper
*/
class BookingMapper {
private function __construct() {
}
/**
* Maps an array to a booking object.
* @param Booking $booking
* @param array $properties
*/
public static function map(Booking $booking, array $properties) {
if (array_key_exists('id', $properties)) {
$booking->setId($properties['id']);
}
if (array_key_exists('flight_name', $properties)) {
$booking->setFlightName($properties['flight_name']);
}
if (array_key_exists('flight_date', $properties)) {
$flightDate = self::createDateTime($properties['flight_date']);
if ($flightDate) {
$booking->setFlightDate($flightDate);
}
}
if (array_key_exists('date_created', $properties)) {
$dateCreated = self::createDateTime($properties['date_created']);
if ($dateCreated) {
$booking->setDateCreated($dateCreated);
}
}
if (array_key_exists('status', $properties)) {
$booking->setStatus($properties['status']);
}
if (array_key_exists('user_id', $properties)) {
$booking->setUserId($properties['user_id']);
}
}
private static function createDateTime($input) {
return DateTime::createFromFormat('Y-n-j H:i:s', $input);
}
}
|
50d3e4adb530171038a5479ed50547484d843c95
|
[
"PHP"
] | 2 |
PHP
|
hana-wawatai/fttl-crud-master
|
dc8d1562eaa156bae02d3ab53064b44c9c845d31
|
2cdc27bea31aafb30ac2b16782c244925fe97538
|
refs/heads/master
|
<repo_name>projet-drone/test-web-socket<file_sep>/src/WebAppsManager.js
var WebApp = require('./model/WebApp')
var {ClientHandler, clientTypes} = require('./ClientHandler')
class WebAppManager {
webApps = []
init(){
let webAppClients = ClientHandler.getinstance().findClientByType(clientTypes.DISPLAY)
webAppClients.forEach(webApp => {
console.log("this is an app", webApp.name)
let newWebApp = new WebApp(
webApp.name,
webApp.client
)
this.webApps.push(newWebApp)
});
}
findWebAppByName(name){
let webappToReturn = null
this.webApps.forEach(webApp => {
if(webApp.name == name){
webappToReturn = webApp
}
});
return webappToReturn
}
}
module.exports = WebAppManager;<file_sep>/src/XpManager.js
var {Observable } = require('rxjs')
var {ClientHandler,clientTypes} = require('./ClientHandler')
var RoomManager = require('./RoomManager')
var SpheroManager = require('./SpheroManager')
var ActivityManager = require('./activityManager')
var WebAppsManager = require('./WebAppsManager')
var MapSystemManager = require('./MapSystemManager')
var {Sphero, SpheroMods} = require('./model/Sphero')
var Activity = require('./model/Activity')
var WebApp = require('./model/WebApp')
var Pupitre = require('./model/Pupitre')
var XpTracker = require('./XpTracker')
class XpManager{
roomManager;
spheroManager;
mapManager;
activityManager;
webAppsManager;
mapSystemManager;
pupitre;
master;
xpTracker = new XpTracker
experienceHasBegun = false
nbInventorSpheros = 0
nbWebApps = 0
nbMapSystems = 0
expectedInventorSpheroNumber = 3
excpectedWebApps = 2
excpectedMapSystems = 5
activityDone = []
unlockedInventors = []
pendingActivity = false
init(){
const connectionObserver = ClientHandler.getinstance().observeConnections.subscribe(newClientConnected => {
if (newClientConnected.type == clientTypes.SPHERO) {
this.nbInventorSpheros += 1
console.log('nbInventorSpheros',this.nbInventorSpheros)
}
if (newClientConnected.type == clientTypes.DISPLAY) {
this.nbWebApps += 1
console.log('nbWebApps',this.nbWebApps)
}
if (newClientConnected.type == clientTypes.MAP) {
this.nbMapSystems += 1
console.log('nbMapSystems',this.nbMapSystems)
}
if (newClientConnected.name == "Pupitre") {
this.pupitre = new Pupitre("theOnlyPupitre",newClientConnected.client)
}
if (newClientConnected.name == "Master") {
this.master = newClientConnected
this.launchExperience()
}
console.log("///////////////////////////////////////")
console.log("///////////////////////////////////////")
console.log("inventors : " + this.nbInventorSpheros + "/" + this.expectedInventorSpheroNumber )
console.log("webapps : " + this.nbWebApps + "/" + this.excpectedWebApps )
console.log("mapSystems : " + this.nbMapSystems + "/" + this.excpectedMapSystems )
console.log("///////////////////////////////////////")
console.log("///////////////////////////////////////")
newClientConnected.client.on('disconnect', () => {
//console.log("clientToDisconnect",newClientConnected);
let clientToDelete = newClientConnected
console.log("switchType",clientToDelete.type)
clientToDelete.client.removeAllListeners()
switch (clientToDelete.type) {
case clientTypes.SPHERO:
this.nbInventorSpheros -= 1
let spheroTODelete = this.spheroManager.findSpheroByName(clientToDelete.name)
if (spheroTODelete) {
for (let i = 0; i < this.spheroManager.spheros.length; i++) {
const element = this.spheroManager.spheros[i];
if (element == spheroTODelete) {
this.spheroManager.spheros.splice(i,1)
}
}
}
break;
case clientTypes.DISPLAY:
this.nbWebApps -= 1
break;
case clientTypes.MAP:
this.nbMapSystems -= 1
break;
default:
break;
}
ClientHandler.getinstance().clients.splice(clientToDelete.index,1)
console.log("disconnected")
//console.log("test")
})
})
this.spheroManager = new SpheroManager()
this.webAppsManager = new WebAppsManager()
this.activityManager = new ActivityManager()
this.mapSystemManager = new MapSystemManager()
this.roomManager = new RoomManager()
}
launchExperience(){
if (this.master){
this.master.client.on("startExperience",() => {
//initialisation des différents managers
this.spheroManager.init()
this.webAppsManager.init()
this.mapSystemManager.init()
this.roomManager.master = this.master
this.roomManager.init()
//déclarations des différentes activités de l'experience
this.declareExperienceActivities()
//écoute la connexion éventuelle d'un sphéro en mode Joystick ==> correspond a une volonté de se déplacer de bubulle en bubulle
this.pupitre.listenForJoystickConnection((spheroName) => {
let sphero = this.spheroManager.findSpheroByName(spheroName)
if(this.unlockedInventors.includes(spheroName)){
console.log("===================================")
console.log("sphero " + sphero.name + " connected as Joystick")
console.log("===================================")
//active le sphéro en question
this.spheroManager.activate(sphero)
//sphero.client.emit('waitingForJoystickData')
this.spheroManager.switchSpheroMod(sphero,SpheroMods.JOYSTICK)
let skillTreeWebApp = this.webAppsManager.findWebAppByName("SkillTreeWebApp")
ClientHandler.getinstance().collapseSocketTunnel("sendJoystickDatas")
//appeler la fonction de transfere des données du sphéro au client web
ClientHandler.getinstance().createSocketTunnel(sphero,skillTreeWebApp,"sendJoystickDatas")
}
})
this.spheroManager.switchJoystickDataSource(this.roomManager)
this.pupitre.listenForJoystickDisconnection((spheroName) => {
console.log("disconnectedJoystick")
let sphero = this.spheroManager.findSpheroByName(spheroName)
if (this.unlockedInventors.includes(spheroName) && !this.pendingActivity) {
this.spheroManager.switchSpheroMod(sphero,SpheroMods.IDLE)
}
ClientHandler.getinstance().collapseSocketTunnelBySphero(sphero,"sendJoystickDatas")
})
let skillTreeWebApp = this.webAppsManager.findWebAppByName("SkillTreeWebApp")
//écouter l'appweb si une activité dois commencer ==> l'utlisateur a clické sur une bubulle d'experience
if (skillTreeWebApp) {
skillTreeWebApp.client.on("launchActivity",(activityName) => {
ClientHandler.getinstance().collapseSocketTunnel("sendJoystickDatas")
let activity = this.activityManager.findActivityByName(activityName)
this.pendingActivity = true
console.log("===================================")
console.log(activityName + " launched")
console.log("===================================")
console.log(activity)
const waitForValidation = new Observable((subscriber) => {
if (this.pupitre) {
this.pupitre.client.on("spheroLifted",data => {
console.log("do you even lift ?")
subscriber.next("lifted")
})
}else{
console.log("ERROR", "skillTreeWebApp undefined")
}
// activity.actorSphero.client.on("spheroShaked",data => {
// console.log("drop da bass")
// subscriber.next("shaked")
// })
})
let completedTasks = []
const validationObserver = waitForValidation.subscribe((observer) =>{
completedTasks.push(observer)
if (completedTasks.includes("lifted") /*&& completedTasks.includes("shaked")*/){
console.log("===================================")
console.log(activityName + " launched")
console.log("===================================")
console.log("test")
activity.activityCore().then((result) => {
//code a executer quand l'activité est finie
this.activityDone.push(activityName)
this.pendingActivity = false
console.log(this.activityDone)
console.log("testsetset")
console.log("===================================")
console.log(activityName + " finished")
console.log("===================================")
validationObserver.unsubscribe()
//reswitch les sphero dans le bon mode
this.spheroManager.switchSpheroMod(activity.actorSphero,SpheroMods.IDLE)
})
}
})
})
}else{
console.log("ERROR", "skillTreeWebApp undefined")
}
//a changer
if (this.pupitre) {
this.pupitre.client.on("spheroLifted",(spheroName) => {
if (!this.unlockedInventors.includes(spheroName)) {
let spheroToUnlock = this.spheroManager.findSpheroByName(spheroName)
console.log(spheroToUnlock)
if (1){
this.spheroManager.unlock(spheroToUnlock)
this.spheroManager.activate(spheroToUnlock)
this.spheroManager.switchSpheroMod(spheroToUnlock,SpheroMods.PROXIMITY_DETECTOR, () => {
spheroToUnlock.client.on("gotCloseToEmitter",() => {
this.spheroManager.disable(spheroToUnlock)
this.unlockedInventors.push(spheroName)
console.log("===================================")
console.log(spheroName + " captured !!")
console.log("===================================")
//TODO: emit un event pour allumer les lumières
//TODO: jouer un son
})
})
}else{
console.log("ERROR", "sphero to unlock undefined")
}
}
})
}else{
console.log("ERROR", "pupitre undefined")
}
//experience start
console.log("===================================")
console.log("experience started")
console.log("===================================")
})
}else{
console.log("ERROR", "master client undefined")
}
}
declareExperienceActivities(){
/**
* déclaration de l'activité de la machine a courant continu
*/
let DCGeneratorActivity = new Activity()
DCGeneratorActivity.name = "ContinuousGeneratorActivity"
let actorSphero = this.spheroManager.findSpheroByName("Edison")
DCGeneratorActivity.actorSphero = actorSphero
//definition de ce qu'il se passe pendant l'activité
DCGeneratorActivity.activityCore = () => {
let skillTreeWebApp = this.webAppsManager.findWebAppByName("SkillTreeWebApp")
//mettre les sphero et tout et tout dans le bon mode
//this.spheroManager.activate(actorSphero)
this.spheroManager.switchSpheroMod(DCGeneratorActivity.actorSphero,SpheroMods.DC_GENERATOR,() => {
this.spheroManager.activate(DCGeneratorActivity.actorSphero)
//écoute les datas envoyés par le bon sphero et les retransmet a la bonne webApp
ClientHandler.getinstance().createSocketTunnel(DCGeneratorActivity.actorSphero,skillTreeWebApp,"sendContinuousData")
})
//écouter la fin de l'activitée
const endedActivityPromise = new Promise((resolve,reject) => {
//eventuellent l'écran qui envoie cet event
if (skillTreeWebApp) {
skillTreeWebApp.client.on('DCgeneratorActivityCompleted',() => {
console.log("activity finie")
this.mapSystemManager.mapSystems.forEach(mapSystem => {
mapSystem.client.emit("edisonCompleted")
})
//ClientHandler.getinstance().collapseSocketTunnel("sendContinuousData")
resolve('finished')
})
}else{
console.log("ERROR", "skillTreeMap missing")
}
})
return endedActivityPromise
}
/**
* déclaration de l'activité du générateur alternatif
*/
let ACGeneratorActivity = new Activity()
ACGeneratorActivity.name = "AlternativeGeneratorActivity"
actorSphero = this.spheroManager.findSpheroByName("Westinghouse")
ACGeneratorActivity.actorSphero = actorSphero
//definition de ce qu'il se passe pendant l'activité
ACGeneratorActivity.activityCore = () => {
let skillTreeWebApp = this.webAppsManager.findWebAppByName("SkillTreeWebApp")
//mettre les sphero et tout et tout dans le bon mode
this.spheroManager.switchSpheroMod(ACGeneratorActivity.actorSphero,SpheroMods.AC_GENERATOR,() => {
this.spheroManager.activate(ACGeneratorActivity.actorSphero)
//écoute les datas envoyés par le bon sphero et les retransmet a la bonne webApp
ClientHandler.getinstance().createSocketTunnel(ACGeneratorActivity.actorSphero,skillTreeWebApp,"sendAlternativeData")
})
//écouter la fin de l'activitée
const endedActivityPromise = new Promise((resolve,reject) => {
//eventuellent l'écran qui envoie cet event
if (skillTreeWebApp) {
skillTreeWebApp.client.on('ACgeneratorActivityCompleted',() => {
this.mapSystemManager.mapSystems.forEach(mapSystem => {
mapSystem.client.emit("westinghouseCompleted")
})
ClientHandler.getinstance().collapseSocketTunnel("sendAlternativeData")
resolve('finished')
})
}else{
console.log("ERROR", "skillTreeWebApp missing")
}
})
return endedActivityPromise
}
/**
* déclaration de l'activité du Moteur te Tesla
*/
let motorActivity = new Activity()
motorActivity.name = "MotorActivity"
actorSphero = this.spheroManager.findSpheroByName("Tesla")
motorActivity.actorSphero = actorSphero
//definition de ce qu'il se passe pendant l'activité
motorActivity.activityCore = () => {
let motorWebApp = this.webAppsManager.findWebAppByName("MotorWebApp")
//mettre les sphero et tout et tout dans le bon mode
this.spheroManager.switchSpheroMod(motorActivity.actorSphero,SpheroMods.MOTOR,() => {
this.spheroManager.activate(motorActivity.actorSphero)
//tunnel entre le sphéro et l'app web
ClientHandler.getinstance().createSocketTunnel(motorActivity.actorSphero,motorWebApp,"sendMotorData")
})
//écouter la fin de l'activitée
const endedActivityPromise = new Promise((resolve,reject) => {
//eventuellent l'écran qui envoie cet event
if (motorWebApp) {
motorWebApp.client.on('MotorActivityCompleted',() => {
this.mapSystemManager.mapSystems.forEach(mapSystem => {
mapSystem.client.emit("teslaCompleted")
})
ClientHandler.getinstance().collapseSocketTunnel("sendAlternativeData")
resolve('finished')
})
}else{
console.log("ERROR","motorWebApp is not Definied")
}
})
return endedActivityPromise
}
this.activityManager.activities.push(DCGeneratorActivity)
this.activityManager.activities.push(ACGeneratorActivity)
this.activityManager.activities.push(motorActivity)
}
}
module.exports = XpManager<file_sep>/src/model/MapSystem.js
class MapSystem {
name
client
constructor(name, client){
this.name = name
this.client = client
}
}
module.exports = MapSystem;<file_sep>/esp8266scripts/map/motorController/motorController.ino
/*
* WebSocketClientSocketIO.ino
*
* Created on: 06.06.2016
*
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <Adafruit_NeoPixel.h>
#include <Stepper.h>
#include <ArduinoJson.h>
#include <SocketIoClient.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
SocketIoClient webSocket;
#define LED_PIN 14
#define LED_PIN2 12
#define USE_SERIAL Serial1
#define LED_COUNT 60
#define PATAPON "patapatapon"
#define PATAPON_PASS "<PASSWORD>"
#define PATAPON_SERVER_IP "192.168.43.81"
#define HOME "Livebox-FA80"
#define HOME_PASS "<PASSWORD>"
#define HOME_SERVER_IP "192.168.1.10"
int inPin = 4;
int val = HIGH;
int timer = 0;
boolean canRotateMotors = true;
const int stepsPerRevolution = 2048;
Stepper myStepper = Stepper(stepsPerRevolution, 14, 13, 12, 15);
void identify(const char * payload, size_t length) {
Serial.println("refreshing \n");
webSocket.emit("HandShakeAnswered","\"motor:map\"");
//rainbow(10);
}
void activateNearMotors(const char * payload, size_t length) {
Serial.println("refreshing \n");
canRotateMotors = true;
//rainbow(10);
}
void disableMotors(const char * payload, size_t length) {
canRotateMotors = false;
Serial.println("refreshing \n");
//rainbow(10);
}
void activateAllMotors(const char * payload, size_t length) {
Serial.println("refreshing \n");
canRotateMotors = true;
//rainbow(10);
}
void setup() {
Serial.begin(115200);
USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
pinMode(inPin, INPUT);
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFi.getMode();
//WiFi.mode(WIFI_AP);
WiFiMulti.addAP(PATAPON, PATAPON_PASS);
while(WiFiMulti.run() != WL_CONNECTED) {
delay(100);
}
webSocket.on("edisonCompleted", activateNearMotors);
webSocket.on("westinghouseCompleted", disableMotors);
webSocket.on("teslaCompleted", activateAllMotors);
webSocket.on("startHandShake", identify);
webSocket.begin(PATAPON_SERVER_IP,3000);
webSocket.emit("hello","\"je suis le centre de la map o/\"");
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.
myStepper.setSpeed(16);
}
// use HTTP Basic Authorization this is optional remove if not needed
//webSocket.setAuthorization("username", "password");
void loop() {
webSocket.loop();
int newVal = digitalRead(inPin);
// read input value
if (newVal == LOW && canRotateMotors) { // check if the input is HIGH (button released)
myStepper.step(100);// Blue
}
if (timer == 500){
stats("test");
webSocket.emit("hello","\"this is a reponse ws\"");
timer = 0;
}
timer ++;
}
void stats(const char* what) {
// we could use getFreeHeap() getMaxFreeBlockSize() and getHeapFragmentation()
// or all at once:
uint32_t free;
uint16_t max;
uint8_t frag;
ESP.getHeapStats(&free, &max, &frag);
Serial.printf("free: %5d - max: %5d - frag: %3d%% <- ", free, max, frag);
// %s requires a malloc that could fail, using println instead:
Serial.println(what);
}
<file_sep>/src/XpTracker.js
class XpTracker{
trackedClients = {
spheros:[],
webApps:[],
mapSystems:[],
systems:[]
}
doneActivities = []
unlockedNodes = []
trackSphero(name){
let newTrackedSphero = {
name,
currentMode:"locked",
hasAlreadyConnected:false,
}
}
}
module.exports = XpTracker<file_sep>/server.js
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io');
var ExperienceManager = require('./src/XpManager')
var {ClientHandler} = require('./src/ClientHandler')
const port = 3000
server.listen(process.env.PORT || 3000, function () {
console.log('Express server listening on %d', port);
});
let xpManager = new ExperienceManager()
let clientHandler = ClientHandler.getinstance()
clientHandler.server = server;
clientHandler.ioObject = io;
try {
xpManager.init()
} catch (error) {
console.log(error)
}
console.log(clientHandler.clients)
const events = [
{event:"scoreSended",hint:"score to send to rotate the motor in the motor experience",expectedType:"Int"},
{event:"joystickMoved",hint:"sphero joystick data to send to move in the skill tree",expectedType:"Array of coordinates [x,y]"},
{event:"generatorRotated",hint:"number of circle per second",expectedType:"number"},
{event:"hello",hint:"debug",expectedType:"Any"},
{event:"hello",hint:"debug",expectedType:"nothing"},
]
// app.get('/', (req, res) => {
// res.sendFile(__dirname + '/index.html');
// });
let sockets = {}
let countUsers = 0
let shouldFarLightTurnOn = false
/*io.on('connection', (socket) => {
countUsers ++
console.log('a user connected');
console.log(countUsers);
socket.emit("startHandShake")
socket.on("HandShakeAnswered",(data) => {
let explodedData = data.split(":")
console.log("explodedData", explodedData)
sockets[explodedData[0]] = {socket: socket, name:explodedData[0]}
console.log("sockets",sockets)
})*/
//socket.emit("startHandShake",{responseEvent: "HandShakeAnswered", responseForm:'name/type'})
/*socket.on("HandShakeAnswered",data => {
console.log("***********************************")
console.log("connection",data)
console.log("***********************************")
//client.emit("connectionState","connected")
//console.log("new client",newClient.name + " : " + newClient.type)
})*/
//socket.emit("event","events")
/*socket.on("pizza-cordon-bleu", data => {
socket.emit("miam",events)
})*/
/*socket.on('edisonCompleted', data => {
console.log(data)
shouldFarLightTurnOn = false
//sockets["exterieur"].socket.emit("edisonCompleted",data)
sockets["led"].socket.emit("edisonCompleted",data)
sockets["motor"].socket.emit("edisonCompleted",data)
sockets["farMotor"].socket.emit("edisonCompleted",data)
})
socket.on('westinghouseCompleted', data => {
console.log(data)
shouldFarLightTurnOn = true
//sockets["exterieur"].socket.emit("westinghouseCompleted",data)
sockets["led"].socket.emit("westinghouseCompleted",data)
sockets["motor"].socket.emit("westinghouseCompleted",data)
sockets["farMotor"].socket.emit("westinghouseCompleted",data)
})
socket.on('teslaCompleted', data => {
shouldFarLightTurnOn = true
console.log(data)
//sockets["exterieur"].socket.emit("teslaCompleted",data)
sockets["led"].socket.emit("teslaCompleted",data)
sockets["motor"].socket.emit("teslaCompleted",data)
sockets["farMotor"].socket.emit("teslaCompleted",data)
})*/
/*socket.on('lightUp', data => {
console.log(data)
if (//sockets["exterieur"]) {
//sockets["exterieur"].socket.emit("lightUp",data)
}
})*/
/*socket.on('turnOff', data => {
console.log(data)
if (//sockets["exterieur"]) {
//sockets["exterieur"].socket.emit("turnOff",data)
}
})*/
/*socket.on('scoreSended', data => {
console.log(data)
socket.broadcast.emit("scoreSended",data)
})
socket.on("joystickMoved", data => {
console.log(data)
data = data+ ''
console.log(typeof(data))
let coords = data.split(":")
socket.broadcast.emit("joystickMoved",coords)
})
socket.on("generatorRotated", data => {
console.log(data)
socket.broadcast.emit("generatorRotated",coords)
})
*/
/*socket.on("hello",data => {
//socket.emit("hello","yo");
console.log(data)
})
socket.on('disconnect', () => {
let name = "interieur"
if (sockets[name] && sockets[name].socket == socket ) {
console.log( name + ' disconnected');
}
})
});*/<file_sep>/src/model/Client.js
class Client {
name
type
client
}
module.exports = Client;<file_sep>/src/MapSystemManager.js
var MapSystem = require('./model/MapSystem')
var {ClientHandler, clientTypes} = require('./ClientHandler')
class MapSystemManager {
mapSystems = []
init(){
let mapSystemClients = ClientHandler.getinstance().findClientByType(clientTypes.MAP)
mapSystemClients.forEach(mapSystem => {
console.log("this is an app", mapSystem.name)
let newmapSystem = new MapSystem(
mapSystem.name,
mapSystem.client
)
this.mapSystems.push(newmapSystem)
});
}
findMapSystemByName(name){
let mapSystemToReturn = null
console.log("/*/*//**//*/*/*/* */")
console.log(this.mapSystems)
console.log("/*/*//**//*/*/*/* */")
this.mapSystems.forEach(mapSystem => {
console.log("/*/*/*/*/*/*/*/*/*/*/*/")
console.log(mapSystem.name)
console.log(name)
console.log("/*/*/*/*/*/*/*/*/*/*/*/")
if(mapSystem.name == name){
mapSystemToReturn = mapSystem
console.log("/*/*/*/*/*/*/*/*/*/*/*/")
console.log(mapSystemToReturn.name)
console.log("/*/*/*/*/*/*/*/*/*/*/*/")
}
});
return mapSystemToReturn
}
findallSystemsByNameAndType(name,type){
let mapSystemToReturn = []
this.mapSystems.forEach(mapSystem => {
if(mapSystem.name.includes(name) && mapSystem.name.includes(type)){
mapSystemToReturn.push(mapSystem);
}
});
return mapSystemToReturn
}
findallSystemsByName(name){
let mapSystemToReturn = []
this.mapSystems.forEach(mapSystem => {
if(mapSystem.name.includes(name)){
mapSystemToReturn.push(mapSystem);
}
});
return mapSystemToReturn
}
}
module.exports = MapSystemManager;<file_sep>/src/RoomManager.js
var Light = require('./model/Light')
const axios = require('axios');
var {ClientHandler, clientTypes} = require('./ClientHandler')
class RoomManager {
lights = []
master;
init(){
let lightClients = ClientHandler.getinstance().findClientByType(clientTypes.LIGHT)
console.log("lightClients", lightClients)
lightClients.forEach(client => {
//console.log("this is a sphero", sphero.name)
let newLight = new Light(
client.name,
client.type,
client.client
)
this.lights.push(newLight)
console.log("newLight", newLight)
});
}
changeAmbiantColor(inventorName){
let hueValue = 0;
console.log("inAmbiantColor", inventorName)
this.lights.forEach((light) => {
console.log("light","****************************************")
switch (inventorName) {
case "Edison":
light.client.emit("edisonCompleted");
hueValue = 100
console.log("HUE value :", hueValue)
this.master.client.emit("lightPhilipsHue",hueValue)
break;
case "Westinghouse":
light.client.emit("westinghouseCompleted");
hueValue = 50000
console.log("HUE value :", hueValue)
this.master.client.emit("lightPhilipsHue",hueValue)
break;
case "Tesla":
light.client.emit("teslaCompleted");
hueValue = 40000
console.log("HUE value :", hueValue)
this.master.client.emit("lightPhilipsHue",hueValue)
break;
default:
break;
}
})
switch (inventorName) {
case "Edison":
hueValue = 100
console.log("HUE value :", hueValue)
this.master.client.emit("lightPhilipsHue",hueValue)
break;
case "Westinghouse":
hueValue = 50000
console.log("HUE value :", hueValue)
this.master.client.emit("lightPhilipsHue",hueValue)
break;
case "Tesla":
hueValue = 40000
console.log("HUE value :", hueValue)
this.master.client.emit("lightPhilipsHue",hueValue)
break;
default:
break;
}
/*axios.put('https://192.168.1.30/api/Ynfv-hJ0vh0LZCTevecUMGvhcv6DJmyNW9K68Inv/lights/1/state',
{"on":true, "sat":254, "bri":254,"hue":10000})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});*/
}
}
module.exports = RoomManager;<file_sep>/esp8266scripts/pupitre/joystickController/joystickController.ino
/*
* WebSocketClientSocketIO.ino
*
* Created on: 06.06.2016
*
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <Adafruit_NeoPixel.h>
#include <ArduinoJson.h>
#include <SocketIoClient.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
SocketIoClient webSocket;
#define USE_SERIAL Serial1
#define PATAPON "patapatapon"
#define PATAPON_PASS "<PASSWORD>"
#define PATAPON_SERVER_IP "192.168.43.81"
#define HOME "Livebox-FA80"
#define HOME_PASS "<PASSWORD>"
#define HOME_SERVER_IP "192.168.1.10"
int inPin = 14;
int inPin2 = 12;
int inPin3 = 13;
int val = 0;
int val2 = 0;
int val3 = 0;
int timer = 0;
void refresh(const char * payload, size_t length) {
Serial.println("refreshing \n");
//rainbow(10);
}
void identify(const char * payload, size_t length) {
Serial.println("refreshing \n");
webSocket.emit("HandShakeAnswered","\"Pupitre:installation\"");
//rainbow(10);
}
void setup() {
Serial.begin(115200);
USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
pinMode(inPin, INPUT);
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFi.getMode();
//WiFi.mode(WIFI_AP);
WiFiMulti.addAP(PATAPON, PATAPON_PASS);
while(WiFiMulti.run() != WL_CONNECTED) {
delay(100);
}
webSocket.on("startHandShake",identify);
webSocket.begin(PATAPON_SERVER_IP,3000);
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.
}
// use HTTP Basic Authorization this is optional remove if not needed
//webSocket.setAuthorization("username", "password");
void loop() {
webSocket.loop();
int newVal = digitalRead(inPin);
int newVal2 = digitalRead(inPin2);
int newVal3 = digitalRead(inPin3);// read input value
if (newVal != val) {
if(newVal == HIGH){
webSocket.emit("spheroLifted","\"Edison\""); // Blue
USE_SERIAL.printf("EDISON lifted");
}else{
webSocket.emit("spheroDropped","\"Edison\"");
}
//webSocket.emit("hello","\"btn 1 puhed\""); // Blue
}
if (newVal2 != val2) { // check if the input is HIGH (button released)
if(newVal == HIGH){
webSocket.emit("spheroLifted","\"Westinghouse\""); // Blue
}else{
webSocket.emit("spheroDropped","\"Westinghouse\"");
}
}
if (newVal3 != val3) { // check if the input is HIGH (button released)
if(newVal == HIGH){
webSocket.emit("spheroLifted","\"Tesla\""); // Blue
}else{
webSocket.emit("spheroDropped","\"Tesla\"");
}
}
val = newVal;
val2 = newVal2;
val3 = newVal3;
USE_SERIAL.printf("%d",val);
}
void stats(const char* what) {
// we could use getFreeHeap() getMaxFreeBlockSize() and getHeapFragmentation()
// or all at once:
uint32_t free;
uint16_t max;
uint8_t frag;
ESP.getHeapStats(&free, &max, &frag);
Serial.printf("free: %5d - max: %5d - frag: %3d%% <- ", free, max, frag);
// %s requires a malloc that could fail, using println instead:
Serial.println(what);
}
<file_sep>/src/ClientHandler.js
var io = require('socket.io')
var Client = require('./model/Client')
var {Observable, Subscriber } = require('rxjs')
/**
* types of clients that can conenct to the server
*/
const clientTypes = {
SPHERO : "sphero",
LIGHT : "lighting",
MAP : "map",
DISPLAY : "display",
INSTALL : "installation",
ADMIN : "admin"
}
/**
* Singleton in charge of handeling clients, from connection to disconnetion
*/
class ClientHandler{
static instance = null
server
socketTunnels = {}
clients = [];
static getinstance() {
if (this.instance == null){
this.instance = new ClientHandler()
}
return this.instance
}
/**
* listen for new connection and trigger its identification
* @param {*} connectionCallBack
* @param {*} disconnectionCallBack
*/
listenForConnections(connectionCallBack,disconnectionCallBack){
io(this.server).on('connection',client => {
console.log('a user connected');
this.identifyClient(client,(newClient) =>{
connectionCallBack(newClient)
console.log(newClient.name)
})
//listening to disconnection
client.on('disconnect', () => {
//console.log("clientToDisconnect",client);
let clientToDelete = this.findClientFromSocket(client)
disconnectionCallBack(clientToDelete)
this.clients.splice(clientToDelete.index,1)
console.log("disconnected")
//console.log("test")
})
})
}
observeConnections = new Observable(subscriber => {
io(this.server).on('connection',client => {
console.log('a user connected');
this.identifyClient(client,(newClient) =>{
subscriber.next(newClient)
console.log(newClient.name)
})
//listening to disconnection
})
})
findClientFromSocket(client){
let foundClient = null
for (let i = 0; i < this.clients.length; i++) {
const element = this.clients[i];
if (client == element.client) {
//this.clients.splice(i,1)
foundClient = element
return {client :foundClient, index:i}
}
}
}
findClientByType(type){
let foundClients = []
for (let i = 0; i < this.clients.length; i++) {
const element = this.clients[i];
console.log("found element", element.name)
if (type == element.type) {
//this.clients.splice(i,1)
foundClients.push(element)
}
}
return foundClients
}
identifyClient(client, identificationCallback){
let newClient = new Client();
client.on("hello",(data) =>{
//console.log("helloed")
})
console.log("client oui")
newClient.client = client;
client.emit("startHandShake")
client.on("HandShakeAnswered",data => {
let explodedData = data.split(":")
console.log("explodedData", explodedData)
newClient.name = explodedData[0]
newClient.type = explodedData[1]
this.clients.push(newClient)
identificationCallback(newClient)
//this.sortInRightChannel(newClient)
console.log("***********************************")
console.log("connection",newClient.name)
console.log("***********************************")
console.log(this.clients.length)
//client.emit("connectionState","connected")
//console.log("new client",newClient.name + " : " + newClient.type)
})
}
/*
sortInRightChannel(newClient){
switch (newClient.type) {
case clientTypes.SPHERO:
newClient.client.join(clientTypes.SPHERO)
console.log("new Sphero detected")
break;
case clientTypes.LIGHT:
newClient.client.join(clientTypes.LIGHT)
console.log("new LIGHT detected")
break;
case clientTypes.MAP:
newClient.client.join(clientTypes.MAP)
console.log("new MAP detected")
break;
case clientTypes.DISPLAY:
newClient.client.join(clientTypes.DISPLAY)
console.log("new DISPLAY detected")
break;
case clientTypes.Map:
newClient.client.join(clientTypes.MAP)
console.log("new MAP detected")
break;
default:
console.log("Unknown device")
newClient.client.emit("error","wrong client type")
break;
}
}
*/
disconnectAll(){
this.clients.forEach(client => {
client.client.disconnect(true);
});
}
createSocketTunnel(emitter,receiver,eventName){
this.socketTunnels[eventName] = {emitter:emitter.client,receiver:receiver.client}
emitter.client.on(eventName,(datas) =>{
console.log("received " + datas + "on event : " + eventName)
receiver.client.emit(eventName,datas)
})
}
collapseSocketTunnel(eventName){
if (this.socketTunnels.hasOwnProperty(eventName)){
console.log(this.socketTunnels)
this.socketTunnels[eventName].emitter.off(eventName,() => {})
delete this.socketTunnels[eventName]
}
}
collapseSocketTunnelBySphero(sphero,eventName){
for (const property in this.socketTunnels) {
if (property == eventName && sphero.client == this.socketTunnels[property].emitter) {
this.socketTunnels[property].receiver.off(property,() => {})
delete this.socketTunnels[property]
}
}
}
}
module.exports = {ClientHandler, clientTypes, io};<file_sep>/src/SpheroManager.js
var io = require('socket.io')
var {ClientHandler, clientTypes} = require('./ClientHandler')
var {Sphero, SpheroMods} = require('./model/Sphero')
class SpheroManager {
spheros = []
init(){
let spherosClients = ClientHandler.getinstance().findClientByType(clientTypes.SPHERO)
spherosClients.forEach(client => {
//console.log("this is a sphero", sphero.name)
let newSphero = new Sphero(
client.name,
client.type,
SpheroMods.PROXIMITY_DETECTOR,
client.client,
"locked",
)
this.spheros.push(newSphero)
});
this.pingAllSpheros()
}
listenForProximityDetection(){
}
activateAllInventorSpheros(){
this.spheros.forEach(sphero => {
sphero.activate()
})
}
unlock(sphero){
sphero.state = "idle"
sphero.disable()
}
lock(sphero){
sphero.state = "locked"
}
activate(spheroToActivate){
this.spheros.forEach(sphero => {
if (spheroToActivate == sphero && spheroToActivate.state != "locked") {
sphero.activate()
}else if(spheroToActivate.state != "locked"){
sphero.disable()
}
})
}
disable(spheroToDisable){
if(spheroToDisable.state != "locked"){
spheroToDisable.disable()
}
}
findSpheroByName(name){
let spheroToRetrun = null
this.spheros.forEach(sphero => {
if(sphero.name == name){
spheroToRetrun = sphero
}
})
return spheroToRetrun
}
switchSpheroMod(sphero,mod,modSwitched){
sphero.switchMode(mod,modSwitched)
sphero.client.emit("switchMode",mod)
}
listenForJoystickConnection(spheroConnected){
this.spheros.forEach((sphero) =>{
sphero.client.on('connectedAsJoystick',() =>{
spheroConnected(sphero)
})
})
}
pingAllSpheros(){
this.spheros.forEach(sphero => {
//console.log("this is a sphero", sphero.name)
//io.sockets.emit("checkAllSpheroClients",{response:"pingServer"})
sphero.client.emit("checkAllSpheroClients",{response:"pingServer"})
sphero.client.on("pingServer",data => {
console.log(data)
})
});
}
switchJoystickDataSource(roomManager){
this.spheros.forEach((sphero) => {
sphero.client.on('silenceWenches',data =>{
this.spheros.forEach((spheroThatNeedToShutUp) =>{
if (spheroThatNeedToShutUp != sphero && spheroThatNeedToShutUp) {
console.log("spheroThatNeedToShutUp", spheroThatNeedToShutUp.name)
spheroThatNeedToShutUp.client.emit("shutUp","shutUp")
}else{
console.log("spheroThatSpeaks", spheroThatNeedToShutUp.name)
roomManager.changeAmbiantColor(spheroThatNeedToShutUp.name)
}
})
})
})
}
}
module.exports = SpheroManager;
<file_sep>/src/model/Activity.js
class Activity {
name
actorSphero
activityCore
state
}
module.exports = Activity;<file_sep>/src/model/Sphero.js
const SpheroMods = {
JOYSTICK : "joystick",
DC_GENERATOR : "dcGenerator",
AC_GENERATOR : "acGenerator",
PROXIMITY_DETECTOR : "memoryVacuum",
MOTOR : "motor",
IDLE : "idle"
}
class Sphero {
name
type
mode
client
state
constructor(name, type, mode, client, state){
this.name = name
this.type = type
this.mode = mode
this.client = client
this.state = state
}
activate(){
this.state = "active"
this.client.emit("activate")
//TODO: changer l'éclairage de la pièce
}
disable(){
this.state = "idle"
this.client.emit("disable")
}
switchMode(mod,modSwitched){
this.mode = mod
console.log("///////////////////////")
console.log("switched " + this.name + "to " + mod)
console.log("///////////////////////")
if(modSwitched){
modSwitched()
}
}
}
module.exports = {Sphero,SpheroMods};<file_sep>/src/model/Pupitre.js
class Pupitre {
name
client
constructor(name, client){
this.name = name
this.client = client
}
listenForJoystickConnection(spheroConnected){
this.client.on("spheroDropped",name => {
console.log("dropped",name )
spheroConnected(name)
})
}
listenForJoystickDisconnection(spheroConnected){
this.client.on("spheroLifted",name => {
console.log("lifted",name )
spheroConnected(name)
})
}
}
module.exports = Pupitre;<file_sep>/esp8266scripts/map/ledController/ledController.ino
/*
* WebSocketClientSocketIO.ino
*
* Created on: 06.06.2016
*
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <Adafruit_NeoPixel.h>
#include <ArduinoJson.h>
#include <SocketIoClient.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
SocketIoClient webSocket;
#define LED_PIN 14
#define LED_PIN2 12
#define USE_SERIAL Serial1
#define LED_COUNT 60
#define PATAPON "patapatapon"
#define PATAPON_PASS "<PASSWORD>"
#define PATAPON_SERVER_IP "192.168.43.81"
#define HOME "Livebox-FA80"
#define HOME_PASS "<PASSWORD>"
#define HOME_SERVER_IP "192.168.1.10"
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2(LED_COUNT, LED_PIN2, NEO_GRB + NEO_KHZ800);
int inPin = 13;
int val = HIGH;
uint32_t testColor = strip.Color(100,20,200);
int timer = 0;
bool canShowSecondLedStrip = false;
void colorStripRed(const char * payload, size_t length) {
canShowSecondLedStrip = false;
Serial.println("event received");
testColor = strip.Color(255,10,0);
webSocket.emit("hello","\"this is a putain de reponse ws\"");
//rainbow(10);
}
void colorStripBlue(const char * payload, size_t length) {
canShowSecondLedStrip = true;
Serial.println("event received");
testColor = strip.Color(0,130,255);
webSocket.emit("hello","\"this is a putain de reponse ws\"");
//rainbow(10);
}
void colorStripPurple(const char * payload, size_t length) {
Serial.println("event received");
canShowSecondLedStrip = true;
testColor = strip.Color(105,10,180);
webSocket.emit("hello","\"this is a putain de reponse ws\"");
//rainbow(10);
}
void identify(const char * payload, size_t length) {
Serial.println("refreshing \n");
webSocket.emit("HandShakeAnswered","\"led:map\"");
//rainbow(10);
}
void refresh(const char * payload, size_t length) {
Serial.println("refreshing \n");
//rainbow(10);
}
void setup() {
Serial.begin(115200);
USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
pinMode(inPin, INPUT);
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFi.getMode();
//WiFi.mode(WIFI_AP);
WiFiMulti.addAP(PATAPON, PATAPON_PASS);
while(WiFiMulti.run() != WL_CONNECTED) {
delay(100);
}
webSocket.on("edisonCompleted", colorStripRed);
webSocket.on("teslaCompleted", colorStripBlue);
webSocket.on("westinghouseCompleted", colorStripPurple);
webSocket.on("startHandShake", identify);
webSocket.begin(PATAPON_SERVER_IP,3000);
webSocket.emit("hello","\"je suis le centre de la map o/\"");
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
clock_prescale_set(clock_div_1);
#endif
// END of Trinket-specific code.
strip.begin();
strip2.begin();// INITIALIZE NeoPixel strip object (REQUIRED)
strip.show();
strip2.show();// Turn OFF all pixels ASAP
strip.setBrightness(200);
strip2.setBrightness(200); // Set BRIGHTNESS to about 1/5 (max = 255)
}
// use HTTP Basic Authorization this is optional remove if not needed
//webSocket.setAuthorization("username", "password");
void loop() {
webSocket.loop();
int newVal = digitalRead(inPin);
// read input value
if (newVal == LOW && newVal != val) { // check if the input is HIGH (button released)
colorWipe(testColor, 5);// Blue
}
if (newVal == HIGH && newVal != val) { // check if the input is HIGH (button released)
turnStripOff();
}
val = newVal;
if (timer == 500){
stats("test");
webSocket.emit("hello","\"this is a reponse ws\"");
timer = 0;
}
timer ++;
}
void turnStripOff(){
for(int i=0; i<strip.numPixels(); i++){
strip.setPixelColor(i, strip.Color(0, 0, 0));
strip.show();
}
for(int i=0; i<strip2.numPixels(); i++){
strip2.setPixelColor(i, strip.Color(0, 0, 0));
strip2.show();
}
}
void colorWipe(uint32_t color, int wait) {
for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
strip.setPixelColor(i, color); // Set pixel's color (in RAM)
strip.show(); // Update strip to match
delay(wait); // Pause for a moment
}
if(canShowSecondLedStrip){
for(int i=0; i<strip2.numPixels(); i++) { // For each pixel in strip...
strip2.setPixelColor(i, color); // Set pixel's color (in RAM)
strip2.show(); // Update strip to match
delay(wait);
}
// Pause for a moment
}
}
void stats(const char* what) {
// we could use getFreeHeap() getMaxFreeBlockSize() and getHeapFragmentation()
// or all at once:
uint32_t free;
uint16_t max;
uint8_t frag;
ESP.getHeapStats(&free, &max, &frag);
Serial.printf("free: %5d - max: %5d - frag: %3d%% <- ", free, max, frag);
// %s requires a malloc that could fail, using println instead:
Serial.println(what);
}
|
8beda56c326971c8b4371401bb7cc5ab5397c6a6
|
[
"JavaScript",
"C++"
] | 16 |
JavaScript
|
projet-drone/test-web-socket
|
d1be03ca6502b0132f423be6bdaa897b1c752035
|
1970c93b60fb5211937a94a929603ed6c5767728
|
refs/heads/master
|
<file_sep>#!/bin/bash
rustc lib.rs
rustc example.rs -L .
rustc channelbench.rs -L .
rustc syncchannelbench.rs -L .
rustc serverexample.rs -L .<file_sep>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cast;
use std::libc;
use std::io;
use std::mem;
use std::os;
use std::io::IoError;
use std::io::net::ip;
use std::io::net::ip::{IpAddr,SocketAddr};
use std::cell::RefCell;
use std::rc::Rc;
use std::unstable::intrinsics;
use super::IoResult;
use super::events;
use super::eventqueue::EventQueue;
use super::eventqueue::IEventQueue;
use super::eventqueueimpl::EventQueueImpl;
use super::syscalls;
use super::helpers;
fn htons(u: u16) -> u16 {
mem::to_be16(u as i16) as u16
}
// fn ntohs(u: u16) -> u16 {
// mem::from_be16(u as i16) as u16
// }
enum InAddr {
InAddr(libc::in_addr),
In6Addr(libc::in6_addr),
}
fn ip_to_inaddr(ip: ip::IpAddr) -> InAddr {
match ip {
ip::Ipv4Addr(a, b, c, d) => {
InAddr(libc::in_addr {
s_addr: (d as u32 << 24) |
(c as u32 << 16) |
(b as u32 << 8) |
(a as u32 << 0)
})
}
ip::Ipv6Addr(a, b, c, d, e, f, g, h) => {
In6Addr(libc::in6_addr {
s6_addr: [
htons(a),
htons(b),
htons(c),
htons(d),
htons(e),
htons(f),
htons(g),
htons(h),
]
})
}
}
}
fn create_socket(addr: ip::SocketAddr, blocking: bool) -> IoResult<i32> {
unsafe {
let fam = match addr.ip {
ip::Ipv4Addr(..) => libc::AF_INET,
ip::Ipv6Addr(..) => libc::AF_INET6,
};
let mut ty: libc::c_int = libc::SOCK_STREAM | syscalls::SOCK_CLOEXEC;
if !blocking {
ty |= syscalls::SOCK_NONBLOCK;
};
match libc::socket(fam, ty, 0) {
-1 => Err(helpers::last_error()),
fd => Ok(fd),
}
}
}
fn addr_to_sockaddr(addr: ip::SocketAddr) -> (libc::sockaddr_storage, uint) {
unsafe {
let storage: libc::sockaddr_storage = intrinsics::init();
let len = match ip_to_inaddr(addr.ip) {
InAddr(inaddr) => {
let storage: *mut libc::sockaddr_in = cast::transmute(&storage);
(*storage).sin_family = libc::AF_INET as libc::sa_family_t;
(*storage).sin_port = htons(addr.port);
(*storage).sin_addr = inaddr;
mem::size_of::<libc::sockaddr_in>()
}
In6Addr(inaddr) => {
let storage: *mut libc::sockaddr_in6 = cast::transmute(&storage);
(*storage).sin6_family = libc::AF_INET6 as libc::sa_family_t;
(*storage).sin6_port = htons(addr.port);
(*storage).sin6_addr = inaddr;
mem::size_of::<libc::sockaddr_in6>()
}
};
return (storage, len);
}
}
#[deriving(Eq)]
pub enum ConnectionState {
Created = 0,
Connecting = 1,
Connected = 2,
Closed = 3
}
pub struct RawTcpSocket {
priv fd: i32,
priv blocking: bool,
priv connection_state: ConnectionState
}
impl RawTcpSocket {
pub fn connect(addr: ip::SocketAddr) -> IoResult<RawTcpSocket> {
unsafe {
create_socket(addr, true).and_then(|fd| {
let (addr, len) = addr_to_sockaddr(addr);
let addrp = &addr as *libc::sockaddr_storage;
let ret = RawTcpSocket::from_fd(fd);
match helpers::retry(|| {
libc::connect(fd, addrp as *libc::sockaddr,
len as libc::socklen_t)
}) {
-1 => Err(helpers::last_error()),
_ => Ok(ret),
}
})
}
}
fn from_fd(fd: i32) -> RawTcpSocket {
RawTcpSocket {
fd: fd,
blocking: true,
connection_state: Connected
}
}
fn set_blocking(&mut self, blocking: bool) {
if self.connection_state == Closed { return; }
if self.blocking == blocking { return; }
syscalls::set_fd_blocking(self.fd, blocking);
self.blocking = blocking;
}
fn close_socket(&mut self) {
if self.connection_state == Closed { return; }
self.connection_state = Closed;
unsafe { libc::close(self.fd); }
}
pub fn close(&mut self) {
self.close_socket();
}
pub fn write(&mut self, buf: &[u8]) -> IoResult<(uint)> {
if self.connection_state != Connected {
return Err(IoError{
kind: io::Closed,
desc: "Connection is closed",
detail: None
});
}
let len = buf.len();
let data = buf.as_ptr();
if len == 0 {
return Ok(0);
}
let ret:libc::c_int = helpers::retry(|| {
unsafe {
libc::send(self.fd,
data as *mut libc::c_void,
len as libc::size_t,
0) as libc::c_int
}
});
if ret < 0 {
let errno = os::errno() as int;
if errno != libc::EWOULDBLOCK as int && errno != libc:: EAGAIN as int {
self.close_socket();
}
Err(helpers::last_error())
} else {
Ok(ret as uint)
}
}
pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
if self.connection_state != Connected {
return Err(IoError{
kind: io::Closed,
desc: "Connection is closed",
detail: None
});
}
if buf.len() == 0 {
return Ok(0);
}
let ret = helpers::retry(|| {
unsafe {
libc::recv(self.fd,
buf.as_ptr() as *mut libc::c_void,
buf.len() as libc::size_t,
0) as libc::c_int
}
});
if ret == 0 { // TODO: Check if that's correct for nonblocking IO
self.close_socket();
Err(io::standard_error(io::EndOfFile))
}
else if ret < 0 {
let errno = os::errno() as int;
if errno != libc::EWOULDBLOCK as int && errno != libc:: EAGAIN as int {
self.close_socket();
}
Err(helpers::last_error())
} else {
Ok(ret as uint)
}
}
}
impl Drop for RawTcpSocket {
fn drop(&mut self) {
self.close_socket();
}
}
pub struct TcpSocket {
priv process_func: fn(func_ptr: *libc::c_void, event_queue: &mut EventQueueImpl, epoll_events: u32),
priv socket: RawTcpSocket,
priv event_queue: Rc<RefCell<EventQueueImpl>>,
priv event_source_info: Rc<events::EventSourceInfo>,
priv epoll_events: u32,
priv available_bytes: uint
}
impl events::EventSource for TcpSocket {
fn get_event_source_info<'a>(&'a self) -> &'a Rc<events::EventSourceInfo> {
&self.event_source_info
}
}
impl TcpSocket {
pub fn from_raw_tcp_socket(raw_tcp_socket: RawTcpSocket, event_queue: &EventQueue) -> ~TcpSocket {
let mut socket = ~TcpSocket {
socket: raw_tcp_socket,
event_queue: event_queue._get_impl(),
process_func: TcpSocket::process_epoll_events,
event_source_info: Rc::new(events::EventSourceInfo::new()),
epoll_events: 0,
available_bytes: 0
};
if socket.socket.connection_state != Closed {
socket.register_fd();
}
socket
}
pub fn connect(addr: ip::SocketAddr, event_queue: &EventQueue) -> IoResult<~TcpSocket> {
unsafe {
create_socket(addr, false).and_then(|fd| {
let (addr, len) = addr_to_sockaddr(addr);
let addrp = &addr as *libc::sockaddr_storage;
let mut rawsock = RawTcpSocket {
fd: fd,
blocking: false,
connection_state: Created };
match helpers::retry(|| {
libc::connect(fd, addrp as *libc::sockaddr,
len as libc::socklen_t)
}) {
-1 => {
let errno = os::errno() as i32;
if errno != libc::EINPROGRESS {
println!("Failed on connect");
Err(helpers::last_error())
}
else {
rawsock.connection_state = Connecting;
let ret = TcpSocket::from_raw_tcp_socket(rawsock, event_queue);
Ok(ret)
}
},
_ => { // Strangely we were connected synchronously
rawsock.connection_state = Connected;
rawsock.set_blocking(true);
let ret = TcpSocket::from_raw_tcp_socket(rawsock, event_queue);
ret.event_queue.borrow().with_mut(|eq| {
let evt = events::Event {
event_type: events::ConnectedEvent,
is_valid: true,
source_info: ret.event_source_info.clone()
};
eq.push_back_event(evt);
});
Ok(ret)
}
}
})
}
}
pub fn close(&mut self) {
self.remove_pending_events();
self.socket.close_socket();
}
pub fn write(&mut self, buf: &[u8]) -> IoResult<(uint)> {
let state = self.socket.connection_state;
let ret = self.socket.write(buf);
// Check if the the write caused an error/close
if state != self.socket.connection_state
&& self.socket.connection_state == Closed {
self.remove_pending_events();
// TODO: Should an unsuccessful write queue an error event?
// And should it really kill possible data to read?
}
ret
}
pub fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
let state = self.socket.connection_state;
if self.socket.connection_state == Connected
&& self.available_bytes == 0 {
Ok(0)
}
else {
let ret = self.socket.read(buf);
match ret {
Ok(read_bytes) => { // Downcount available bytes
self.available_bytes -= read_bytes;
Ok(read_bytes)
}
Err(err) => {
if state != self.socket.connection_state
&& self.socket.connection_state == Closed {
self.remove_pending_events();
}
Err(err)
}
}
}
}
/*fn set_blocking(&mut self, blocking: bool) {
// TODO: Allow during active operation?
self.socket.set_blocking(blocking)
}*/
fn read_available_bytes(&mut self) -> IoResult<uint> {
let bytes_available:i32 = 0;
let ret = helpers::retry(|| unsafe {
syscalls::ioctl(self.socket.fd, syscalls::FIONREAD, &bytes_available)
});
if ret < 0 {
self.available_bytes = 0;
Err(helpers::last_error())
} else {
self.available_bytes = bytes_available as uint;
Ok(bytes_available as uint)
}
}
/**
* Registers the fd for reading if it's connected or for writing on connects
*/
fn register_fd(&mut self) {
let callback: *libc::c_void = unsafe { cast::transmute(&self.process_func) };
self.event_queue.borrow().with_mut(|q| {
if self.socket.connection_state == Connected {
q.register_fd(self.socket.fd, syscalls::EPOLLIN, callback)
}
else {
q.register_fd(self.socket.fd, syscalls::EPOLLOUT, callback)
}
});
}
fn remove_pending_events(&mut self) {
self.event_queue.borrow().with_mut(|q|
q.remove_pending_events(
|ev|ev.originates_from(self))
);
}
fn process_epoll_events(func_ptr: *libc::c_void, event_queue: &mut EventQueueImpl, epoll_events: u32) {
unsafe {
let sock: *mut TcpSocket = func_ptr as *mut TcpSocket;
if epoll_events & syscalls::EPOLLERR != 0 { // Read the error
let errno: libc::c_int = 0;
let outlen: libc::socklen_t = mem::size_of::<libc::c_int>() as libc::socklen_t;
let ret = syscalls::getsockopt(
(*sock).socket.fd, libc::SOL_SOCKET, syscalls::SO_ERROR,
&errno as *libc::c_int as *libc::c_void,
&outlen as *libc::socklen_t);
// Read and evaluate the error
if ret != -1 {
let err = helpers::translate_error(errno, false);
let e = events::Event {
event_type: events::IoErrorEvent(err),
is_valid: true,
source_info: (*sock).event_source_info.clone()
};
(*sock).socket.close_socket();
// There is no need to remove pending events
// because if there would be any this function
// wouldn't have been called
event_queue.push_back_event(e);
}
else {
fail!("Could not retrieve error");
}
}
else {
if (*sock).socket.connection_state == Connected {
if (epoll_events & syscalls::EPOLLIN != 0) || (epoll_events & syscalls::EPOLLERR != 0) {
if epoll_events & syscalls::EPOLLHUP == 0 {
let _ = (*sock).read_available_bytes();
} else {
(*sock).available_bytes = 0;
}
if (*sock).available_bytes > 0 {
let e = events::Event {
event_type: events::DataAvailableEvent((*sock).available_bytes),
is_valid: true,
source_info: (*sock).event_source_info.clone()
};
event_queue.push_back_event(e);
} else {
let e = events::Event {
event_type: events::StreamClosedEvent,
is_valid: true,
source_info: (*sock).event_source_info.clone()
};
(*sock).socket.close_socket();
event_queue.push_back_event(e);
}
}
// Currently not used
/*if (epoll_events & syscalls::EPOLLOUT != 0) {
}*/
}
else { // Connecting
if epoll_events & syscalls::EPOLLOUT != 0 {
let out: libc::c_int = 0;
let outlen: libc::socklen_t = mem::size_of::<libc::c_int>() as libc::socklen_t;
let ret = syscalls::getsockopt(
(*sock).socket.fd, libc::SOL_SOCKET, syscalls::SO_ERROR,
&out as *libc::c_int as *libc::c_void,
&outlen as *libc::socklen_t);
// Read and evaluate if connect was successful
let mut success = ret != -1;
let mut errno;
if success {
success = out == 0;
errno = out;
}
else {
errno = os::errno() as libc::c_int;
}
if !success {
let err = helpers::translate_error(errno, false);
let e = events::Event {
event_type: events::IoErrorEvent(err),
is_valid: true,
source_info: (*sock).event_source_info.clone()
};
(*sock).socket.close_socket();
event_queue.push_back_event(e);
}
else { // Connect was successful
(*sock).socket.set_blocking(true);
(*sock).socket.connection_state = Connected;
let e = events::Event {
event_type: events::ConnectedEvent,
is_valid: true,
source_info: (*sock).event_source_info.clone()
};
let callback: *libc::c_void = cast::transmute(&(*sock).process_func);
// Switch interest to EPOLLIN
event_queue.modify_fd((*sock).socket.fd, syscalls::EPOLLIN, callback);
event_queue.push_back_event(e);
}
}
}
}
}
}
}
#[unsafe_destructor]
impl Drop for TcpSocket {
fn drop(&mut self) {
self.remove_pending_events();
}
}
pub struct RawTcpServerSocket {
priv fd: i32,
priv connection_state: ConnectionState,
}
impl RawTcpServerSocket {
// TODO: Ipv6-only parameter
pub fn bind(addr: ip::SocketAddr, backlog: i32) -> IoResult<RawTcpServerSocket> {
unsafe {
create_socket(addr, true).and_then(|fd| {
let (addr, len) = addr_to_sockaddr(addr);
let addrp = &addr as *libc::sockaddr_storage;
let ret = RawTcpServerSocket {
fd: fd,
connection_state: Connected,
};
let reuse: libc::c_int = 1;
// Set SO_REUSEADDR
let opt = libc::setsockopt(fd, libc::SOL_SOCKET,
syscalls::SO_REUSEADDR,
&reuse as *libc::c_int as *libc::c_void,
mem::size_of::<libc::c_int>() as libc::socklen_t);
if opt == -1 {
return Err(helpers::last_error());
}
// Bind the socket
match libc::bind(fd, addrp as *libc::sockaddr,
len as libc::socklen_t) {
-1 => Err(helpers::last_error()),
_ => {
match libc::listen(fd, backlog) {
-1 => Err(helpers::last_error()),
_ => Ok(ret)
}
}
}
})
}
}
pub fn accept(&mut self) -> IoResult<RawTcpSocket> {
if self.connection_state != Connected {
return Err(IoError{
kind: io::Closed,
desc: "Socket is closed",
detail: None
});
}
unsafe {
let mut storage: libc::sockaddr_storage = intrinsics::init();
let storagep = &mut storage as *mut libc::sockaddr_storage;
let size = mem::size_of::<libc::sockaddr_storage>();
let mut size = size as libc::socklen_t;
match helpers::retry(|| {
libc::accept(self.fd,
storagep as *mut libc::sockaddr,
&mut size as *mut libc::socklen_t) as libc::c_int
}) {
-1 => {
let errno = os::errno() as int;
if errno != libc::EWOULDBLOCK as int && errno != libc::EAGAIN as int {
self.close_socket();
}
Err(helpers::last_error())
},
fd => Ok(RawTcpSocket::from_fd(fd))
}
}
}
fn close_socket(&mut self) {
if self.connection_state == Closed { return; }
self.connection_state = Closed;
unsafe { libc::close(self.fd); }
}
pub fn close(&mut self) {
self.close_socket();
}
}
impl Drop for RawTcpServerSocket {
fn drop(&mut self) {
self.close_socket();
}
}
pub struct TcpServerSocket {
priv process_func: fn(func_ptr: *libc::c_void, event_queue: &mut EventQueueImpl, epoll_events: u32),
priv socket: RawTcpServerSocket,
priv event_queue: Rc<RefCell<EventQueueImpl>>,
priv event_source_info: Rc<events::EventSourceInfo>,
priv epoll_events: u32,
priv client_available: bool
}
impl events::EventSource for TcpServerSocket {
fn get_event_source_info<'a>(&'a self) -> &'a Rc<events::EventSourceInfo> {
&self.event_source_info
}
}
impl TcpServerSocket {
pub fn from_raw_server_socket(raw_server_socket: RawTcpServerSocket, event_queue: &EventQueue) -> ~TcpServerSocket {
let mut socket = ~TcpServerSocket {
socket: raw_server_socket,
event_queue: event_queue._get_impl(),
process_func: TcpServerSocket::process_epoll_events,
event_source_info: Rc::new(events::EventSourceInfo::new()),
epoll_events: 0,
client_available: false
};
if socket.socket.connection_state != Closed {
socket.register_fd();
}
socket
}
pub fn bind(addr: ip::SocketAddr, backlog: i32, event_queue: &EventQueue) -> IoResult<~TcpServerSocket> {
let sock = RawTcpServerSocket::bind(addr, backlog);
match sock {
Ok(sock) => {
Ok(TcpServerSocket::from_raw_server_socket(sock, event_queue))
},
Err(err) => Err(err)
}
}
pub fn close(&mut self) {
self.socket.close_socket();
self.remove_pending_events();
}
pub fn accept(&mut self) -> IoResult<RawTcpSocket> {
let state = self.socket.connection_state;
if self.socket.connection_state == Connected
&& !self.client_available { // Currently no client available
Err(IoError{
kind: io::ResourceUnavailable,
desc: "No client available",
detail: None
})
}
else {
let ret = self.socket.accept();
match ret {
Ok(socket) => {
self.client_available = false;
Ok(socket)
}
Err(err) => {
if state != self.socket.connection_state
&& self.socket.connection_state == Closed {
self.remove_pending_events();
}
Err(err)
}
}
}
}
/**
* Registers the fd for reading if it's connected or for writing on connects
*/
fn register_fd(&mut self) {
let callback: *libc::c_void = unsafe { cast::transmute(&self.process_func) };
self.event_queue.borrow().with_mut(|q| {
q.register_fd(self.socket.fd, syscalls::EPOLLIN, callback)
});
}
fn remove_pending_events(&mut self) {
self.event_queue.borrow().with_mut(|q|
q.remove_pending_events(
|ev|ev.originates_from(self))
);
}
fn process_epoll_events(func_ptr: *libc::c_void, event_queue: &mut EventQueueImpl, epoll_events: u32) {
unsafe {
let sock: *mut TcpServerSocket = func_ptr as *mut TcpServerSocket;
if epoll_events & syscalls::EPOLLERR != 0 { // Read the error
let errno: libc::c_int = 0;
let outlen: libc::socklen_t = mem::size_of::<libc::c_int>() as libc::socklen_t;
let ret = syscalls::getsockopt(
(*sock).socket.fd, libc::SOL_SOCKET, syscalls::SO_ERROR,
&errno as *libc::c_int as *libc::c_void,
&outlen as *libc::socklen_t);
// Read and evaluate the error
if ret != -1 {
let err = helpers::translate_error(errno, false);
let e = events::Event {
event_type: events::IoErrorEvent(err),
is_valid: true,
source_info: (*sock).event_source_info.clone()
};
(*sock).socket.close_socket();
// There is no need to remove pending events
// because if there would be any this function
// wouldn't have been called
event_queue.push_back_event(e);
}
else {
fail!("Could not retrieve error");
}
}
else {
if epoll_events & syscalls::EPOLLIN != 0 {
(*sock).client_available = true;
let e = events::Event {
event_type: events::ClientConnectedEvent,
is_valid: true,
source_info: (*sock).event_source_info.clone()
};
event_queue.push_back_event(e);
}
}
}
}
}
#[unsafe_destructor]
impl Drop for TcpServerSocket {
fn drop(&mut self) {
self.remove_pending_events();
}
}
<file_sep>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#[crate_id = "revbio#0.1"];
#[comment = "Rust evented based I/O"];
#[license = "MIT/ASL2"];
#[crate_type = "lib"];
#[no_uv];
extern mod native;
extern mod collections;
use std::io::IoError;
pub use eventqueue::EventQueue;
pub mod events;
mod eventqueue;
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[path="linux/eventqueueimpl.rs"]
mod eventqueueimpl;
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[path="linux/timer.rs"]
pub mod timer;
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[path="linux/syscalls.rs"]
#[allow(dead_code)]
mod syscalls;
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[path="linux/helpers.rs"]
mod helpers;
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[path="linux/tcp.rs"]
pub mod tcp;
#[cfg(target_os = "linux")]
#[cfg(target_os = "android")]
#[path="linux/channel.rs"]
pub mod channel;
/// Holds either the success value of an IO operation or an error
pub type IoResult<T> = Result<T, IoError>;<file_sep>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cast;
use std::libc;
use std::cell::RefCell;
use std::rc::Rc;
use super::events;
use super::IoResult;
use super::eventqueue;
use super::eventqueue::IEventQueue;
use super::eventqueueimpl::EventQueueImpl;
use super::syscalls;
use super::helpers;
pub struct Timer {
priv process_func: fn(func_ptr: *libc::c_void, event_queue: &mut EventQueueImpl, epoll_events: u32),
priv fd: i32,
priv is_active: bool,
priv interval: u32,
priv singleshot: bool,
priv epoll_registered: bool,
priv event_queue: Rc<RefCell<EventQueueImpl>>,
priv event_source_info: Rc<events::EventSourceInfo>
}
impl Timer {
pub fn create(event_queue: &eventqueue::EventQueue) -> IoResult<~Timer> {
let tfd = unsafe {
syscalls::timerfd_create(libc::CLOCK_MONOTONIC, 0)
};
if tfd == -1 {
Err(helpers::last_error())
}
else {
Ok(~Timer{
fd: tfd,
interval: 0,
is_active: false,
singleshot: false,
epoll_registered: false,
event_queue: event_queue._get_impl(),
process_func: Timer::process_epoll_events,
event_source_info: Rc::new(events::EventSourceInfo::new())
})
}
}
pub fn set_interval(&mut self, interval: u32) {
self.interval = interval;
}
pub fn get_interal(&self) -> u32 {
self.interval
}
pub fn set_singleshot(&mut self, singleshot: bool) {
self.singleshot = singleshot;
}
pub fn is_singleshot(&self) -> bool {
self.singleshot
}
pub fn is_active(&self) -> bool {
self.is_active
}
pub fn stop(&mut self) {
if !self.is_active { return; }
let new_value = syscalls::itimerspec::new(); // init to 0
let ret = unsafe {
syscalls::timerfd_settime(self.fd, 0, &new_value, 0 as *syscalls::itimerspec)
};
if ret != 0 {
fail!("Error on stopping timer {0}", helpers::last_error().desc);
}
self.event_queue.borrow().with_mut(
|q|q.unregister_fd(self.fd)
);
self.epoll_registered = false;
self.is_active = false;
self.remove_pending_events();
}
pub fn start(&mut self) {
if self.is_active || self.interval == 0 { return; }
let mut new_value = syscalls::itimerspec::new();
new_value.it_value.tv_sec = (self.interval / 1000u32) as libc::time_t;
new_value.it_value.tv_nsec = (self.interval % 1000u32) as libc::c_long;
new_value.it_value.tv_nsec *= 1000000;
if !self.singleshot {
new_value.it_interval.tv_sec = new_value.it_value.tv_sec;
new_value.it_interval.tv_nsec = new_value.it_value.tv_nsec;
}
let ret = unsafe {
syscalls::timerfd_settime(self.fd, 0, &new_value, 0 as *syscalls::itimerspec)
};
if ret != 0 {
fail!("Error on starting timer {0}", helpers::last_error().desc);
}
self.is_active = true;
// Register fd
let epoll_flags = if self.singleshot {
syscalls::EPOLLIN | syscalls::EPOLLONESHOT
} else { syscalls::EPOLLIN };
let callback: *libc::c_void = unsafe { cast::transmute(&self.process_func) };
if !self.epoll_registered {
self.event_queue.borrow().with_mut(|q|
q.register_fd(self.fd, epoll_flags, callback)
);
self.epoll_registered = true;
} else {
self.event_queue.borrow().with_mut(|q|
q.modify_fd(self.fd, epoll_flags, callback)
);
}
}
fn process_epoll_events(func_ptr: *libc::c_void, event_queue: &mut EventQueueImpl, epoll_events: u32) {
unsafe {
let timer: *mut Timer = func_ptr as *mut Timer;
if epoll_events & syscalls::EPOLLIN != 0 {
let buffer = [0, ..8];
let ret = helpers::retry(||
libc::read((*timer).fd,
buffer.as_ptr() as *mut libc::c_void,
buffer.len() as libc::size_t) as i32
);
if ret == 8 { // Must be 8 bytes
let expirations: *u64 = cast::transmute(&buffer);
for _ in range(0, *expirations) {
let e = events::Event {
event_type: events::TimerEvent,
is_valid: true,
source_info: (*timer).event_source_info.clone()
};
event_queue.push_back_event(e);
// Set timer to inactive when it was a singleshot
if (*timer).singleshot {
(*timer).is_active = false;
}
}
}
}
}
}
fn remove_pending_events(&mut self) {
self.event_queue.borrow().with_mut(|q|
q.remove_pending_events(
|ev|ev.originates_from(self))
);
}
}
#[unsafe_destructor]
impl Drop for Timer {
fn drop(&mut self) {
// Don't call close because this won't deque already
// queued events if the timer is inactive
self.remove_pending_events();
if self.fd != 0 {
unsafe { libc::close(self.fd); }
}
}
}
impl events::EventSource for Timer {
fn get_event_source_info<'a>(&'a self) -> &'a Rc<events::EventSourceInfo> {
&self.event_source_info
}
}<file_sep>#[no_uv];
extern mod native;
extern mod revbio;
extern mod extra;
use extra::time;
use revbio::events;
use revbio::channel::{Channel,Transmitter,BlockingReceiver,Receiver};
use revbio::{EventQueue};
#[start]
fn start(argc: int, argv: **u8) -> int {
native::start(argc, argv, proc() {
bench_conditions_main();
})
}
fn timediff(start: time::Timespec, end: time::Timespec) -> f64 {
let mut diff:f64;
if start.sec == end.sec {
diff = ((end.nsec - start.nsec) as f64) / 1000000000f64;
}
else {
diff = ((1000000000i32 - start.nsec) as f64) / 1000000000f64;
let startsec = start.sec + 1;
diff += ((end.sec - startsec) as f64);
diff += ((end.nsec) as f64) / 1000000000f64;
}
diff
}
fn bench_conditions_main() {
let ITERATIONS = 100000u32;
let (port,chan): (Port<i32>, Chan<i32>) = Chan::new();
let (rport,rchan): (Port<i32>, Chan<i32>) = Chan::new();
let start_time = time::get_time();
native::task::spawn(proc() {
for _ in range(0,ITERATIONS) {
rport.recv();
chan.send(0);
}
});
for _ in range(0,ITERATIONS) {
rchan.send(0);
port.recv();
}
let end_time = time::get_time();
let diff = timediff(start_time, end_time);
println!("Native channels: Diff: {:?}", diff);
let (rx,tx): (BlockingReceiver<i32>, Transmitter<i32>) = Channel::create_blocking();
let (rrx,rtx): (BlockingReceiver<i32>, Transmitter<i32>) = Channel::create_blocking();
let start_time = time::get_time();
native::task::spawn(proc() {
for _ in range(0,ITERATIONS) {
rrx.recv();
tx.send(0);
}
});
for _ in range(0,ITERATIONS) {
rtx.send(0);
rx.recv();
}
let end_time = time::get_time();
let diff = timediff(start_time, end_time);
println!("Revio blocking channels: Diff: {:?}", diff);
let mut ev_queue = EventQueue::new();
let (mut rx,tx): (~Receiver<i32>, Transmitter<i32>) = Channel::create(&ev_queue);
let (rrx,rtx): (BlockingReceiver<i32>, Transmitter<i32>) = Channel::create_blocking();
let mut nr_received = 0u32;
let start_time = time::get_time();
native::task::spawn(proc() {
let mut rev = EventQueue::new();
let mut rselport = Receiver::from_blocking_receiver(rrx, &rev);
for _ in range(0,ITERATIONS) {
rev.next_event().unwrap();
rselport.recv();
tx.send(0);
}
});
loop {
rtx.send(0);
let event = ev_queue.next_event().unwrap();
if event.originates_from(rx) {
match event.event_type {
events::ChannelMessageEvent => {
rx.recv();
nr_received += 1;
if nr_received == ITERATIONS {
break;
}
},
_ => ()
}
}
}
let end_time = time::get_time();
let diff = timediff(start_time, end_time);
println!("Revio event based channels: Diff: {:?}", diff);
}<file_sep>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cast;
use std::libc;
use collections::ringbuf::RingBuf;
use collections::deque::Deque;
use super::eventqueue::IEventQueue;
use super::events;
use super::IoResult;
use super::syscalls;
use super::helpers;
pub struct EventQueueImpl {
priv fd: i32, // epoll fd,
priv ready_events: RingBuf<events::Event>
}
impl IEventQueue for EventQueueImpl {
#[inline]
fn push_back_event(&mut self, event: events::Event) {
self.ready_events.push_back(event);
}
#[inline]
fn push_front_event(&mut self, event: events::Event) {
self.ready_events.push_front(event);
}
}
impl EventQueueImpl {
pub fn new() -> EventQueueImpl {
let fd = unsafe { syscalls::epoll_create(64) }; // Parameter is ignored
if fd == 1 {
fail!(helpers::last_error());
}
EventQueueImpl{
fd: fd,
ready_events: RingBuf::new()
}
}
pub fn next_event(&mut self) -> IoResult<events::Event> {
if self.ready_events.len() > 0 {
Ok(self.ready_events.pop_front().unwrap())
}
else {
// No handles ready. Must poll
loop { // loop until poll returns sth. useful
let result = self.poll_events();
match result {
Err(err) => { return Err(err); },
Ok(()) => {
if self.ready_events.len() > 0 {
let first = self.ready_events.pop_front().unwrap();
if first.is_valid {
return Ok(first);
}
}
}
}
}
}
}
pub fn poll_events(&mut self) -> IoResult<()> {
let evs = syscalls::epoll_event::new();
let ready_fds = helpers::retry(|| unsafe {
syscalls::epoll_wait(self.fd, &evs, 1, -1)
});
if ready_fds == -1 {
return Err(helpers::last_error());
}
else if ready_fds == 1 {
let ptr = evs.data.get_data_as_ptr();
let cb: *fn(*libc::c_void, &mut EventQueueImpl, u32)
= unsafe { cast::transmute(ptr) };
unsafe { (*cb)(ptr, self, evs.events) };
}
Ok(())
}
pub fn remove_pending_events(&mut self, condition: |event: &events::Event|-> bool) {//event_source: &event::EventSource) {
for ev in self.ready_events.mut_iter() {
if condition(ev) {
ev.is_valid = false;
}
}
}
pub fn register_fd(&mut self, fd: i32, flags: u32, callback: *libc::c_void) {
// Initialize epoll data
let mut data = syscalls::epoll_data::new();
data.set_data_as_ptr(callback);
let event = syscalls::epoll_event {
events: flags, /* Epoll events */
data: data /* User data variable */
};
// Register at epoll
let s = unsafe {
syscalls::epoll_ctl(self.fd, syscalls::EPOLL_CTL_ADD, fd, &event)
};
if s != 0 {
fail!("Could not register fd for epoll");
}
}
pub fn modify_fd(&mut self, fd: i32, flags: u32, callback: *libc::c_void) {
// Initialize epoll data
let mut data = syscalls::epoll_data::new();
data.set_data_as_ptr(callback);
let event = syscalls::epoll_event {
events: flags, /* Epoll events */
data: data /* User data variable */
};
// Register at epoll
let s = unsafe {
syscalls::epoll_ctl(self.fd, syscalls::EPOLL_CTL_MOD, fd, &event)
};
if s != 0 {
fail!("Could not modify epoll interest");
}
}
pub fn unregister_fd(&mut self, fd: i32) {
let event = syscalls::epoll_event {
events: 0,
data: syscalls::epoll_data::new()
};
// Unregister from epoll
let s = unsafe {
syscalls::epoll_ctl(self.fd, syscalls::EPOLL_CTL_DEL, fd, &event)
};
if s != 0 {
fail!("Could not remove epoll interest");
}
}
}
#[unsafe_destructor]
impl Drop for EventQueueImpl {
fn drop(&mut self) {
unsafe { libc::close(self.fd); }
}
}<file_sep>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cell::RefCell;
use std::rc::Rc;
use super::events;
use super::eventqueueimpl;
use super::IoResult;
pub struct EventQueue {
priv queue: Rc<RefCell<eventqueueimpl::EventQueueImpl>>
}
impl EventQueue {
pub fn new() -> EventQueue {
EventQueue{
queue: Rc::new(RefCell::new(eventqueueimpl::EventQueueImpl::new()))
}
}
pub fn _get_impl(&self) -> Rc<RefCell<eventqueueimpl::EventQueueImpl>> {
self.queue.clone()
}
pub fn next_event(&mut self) -> IoResult<events::Event> {
self.queue.borrow().with_mut(|ev_queue|ev_queue.next_event())
}
}
pub trait IEventQueue {
fn push_back_event(&mut self, event: events::Event);
fn push_front_event(&mut self, event: events::Event);
}
impl IEventQueue for EventQueue {
#[inline]
fn push_back_event(&mut self, event: events::Event) {
self.queue.borrow().borrow_mut().get().push_back_event(event);
}
#[inline]
fn push_front_event(&mut self, event: events::Event) {
let mut refmut = self.queue.borrow().borrow_mut();
refmut.get().push_front_event(event);
}
}<file_sep>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::libc;
use std::io;
use std::os;
use std::io::IoError;
#[cfg(unix)]
#[inline]
pub fn retry(f: || -> libc::c_int) -> libc::c_int {
loop {
match f() {
-1 if os::errno() as int == libc::EINTR as int => {}
n => return n,
}
}
}
pub fn translate_error(errno: i32, detail: bool) -> IoError {
#[cfg(not(windows))]
fn get_err(errno: i32) -> (io::IoErrorKind, &'static str) {
// XXX: this should probably be a bit more descriptive...
match errno {
libc::EOF => (io::EndOfFile, "end of file"),
libc::ECONNREFUSED => (io::ConnectionRefused, "connection refused"),
libc::ECONNRESET => (io::ConnectionReset, "connection reset"),
libc::EPERM | libc::EACCES =>
(io::PermissionDenied, "permission denied"),
libc::EPIPE => (io::BrokenPipe, "broken pipe"),
libc::ENOTCONN => (io::NotConnected, "not connected"),
libc::ECONNABORTED => (io::ConnectionAborted, "connection aborted"),
libc::EADDRNOTAVAIL => (io::ConnectionRefused, "address not available"),
libc::EADDRINUSE => (io::ConnectionRefused, "address in use"),
// These two constants can have the same value on some systems, but
// different values on others, so we can't use a match clause
x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
(io::ResourceUnavailable, "resource temporarily unavailable"),
x => {
println!("errno = {0}", errno);
debug!("ignoring {}: {}", x, os::last_os_error());
(io::OtherIoError, "unknown error")
}
}
}
let (kind, desc) = get_err(errno);
IoError {
kind: kind,
desc: desc,
detail: if detail {Some(os::last_os_error())} else {None},
}
}
pub fn last_error() -> IoError { translate_error(os::errno() as i32, true) }<file_sep>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::io::IoError;
use std::rc::{Rc, Weak};
pub enum EventKind
{
StreamClosedEvent,
IoErrorEvent(IoError),
DataAvailableEvent(uint),
TimerEvent,
ChannelClosedEvent,
ChannelMessageEvent,
ConnectedEvent,
ClientConnectedEvent
}
pub struct Event
{
event_type: EventKind,
is_valid: bool,
source_info: Rc<EventSourceInfo>
}
impl Event {
pub fn originates_from<T:EventSource>(&self, source: &T) -> bool{
if self.source_info.borrow() as *EventSourceInfo
== source.get_event_source_info().borrow() as *EventSourceInfo {
true
}
else {false}
}
}
/**
* A structure that stores information that belongs to the source of
* an event
*/
pub struct EventSourceInfo {
priv id: bool,
priv processor: Option<Weak<~EventProcessor>>
// More to come
}
impl EventSourceInfo {
pub fn new() -> EventSourceInfo {
EventSourceInfo {
id: true,
processor: None
}
}
}
impl Clone for EventSourceInfo {
fn clone(&self) -> EventSourceInfo {
EventSourceInfo {
id: self.id,
processor: self.processor.clone()
}
}
}
/**
* A trait that is implemented by possible sources of events
*/
pub trait EventSource
{
fn get_event_source_info<'a>(&'a self) -> &'a Rc<EventSourceInfo>;
}
pub trait EventProcessor
{
fn process_event(event: &Event);
}<file_sep>#[no_uv];
extern mod native;
extern mod revbio;
extern mod extra;
use std::io::net::ip::{IpAddr,SocketAddr};
use revbio::events;
use revbio::channel::{Transmitter,BlockingReceiver,Channel};
use revbio::{EventQueue};
use revbio::tcp::{TcpSocket,RawTcpSocket,TcpServerSocket};
#[start]
fn start(argc: int, argv: **u8) -> int {
native::start(argc, argv, proc() {
main();
})
}
fn main() {
let mut ev_queue = EventQueue::new();
let (rx,tx): (BlockingReceiver<bool>,Transmitter<bool>) = Channel::create_blocking();
native::task::spawn(proc() {
servertask(tx);
});
// Wait for the server to start up
rx.recv();
let opt_ipaddr:Option<IpAddr> = FromStr::from_str("127.0.0.1");
let socketaddr = SocketAddr {ip: opt_ipaddr.unwrap(), port: 7000};
let mut socket = TcpSocket::connect(socketaddr, &ev_queue).unwrap();
let mut received_data = false;
loop {
let event = ev_queue.next_event().unwrap();
if event.originates_from(socket) {
match event.event_type {
events::ConnectedEvent => {
println!("TCP stream got connected");
},
events::IoErrorEvent(err) => {
println!("IoError: {}", err.desc.to_owned());
if received_data { // Reconnect
socket = TcpSocket::connect(socketaddr, &ev_queue).unwrap();
received_data = false;
}
else {
break;
}
},
events::StreamClosedEvent => {
println!("TCP connection closed");
if received_data { // Reconnect
socket = TcpSocket::connect(socketaddr, &ev_queue).unwrap();
received_data = false;
}
else {
break;
}
},
events::DataAvailableEvent(nr_bytes) => {
let mut buffer: ~[u8] = std::vec::from_elem::<u8>(nr_bytes, 0);
let read_res = socket.read(buffer);
match read_res {
Err(err) => {
println!("{}", err.desc.to_owned());
}
Ok(nr_read) => {
received_data = true;
let txt = std::str::from_utf8(buffer.slice(0, nr_read));
println!("{}", txt);
}
}
},
_ => ()
}
}
}
}
fn servertask(start_tx: Transmitter<bool>) {
let mut client_count = 5; // Nr of clients to accept
let mut ev_queue = EventQueue::new();
let host = ~"0.0.0.0";
let opt_ipaddr:Option<IpAddr> = FromStr::from_str(host);
let socketaddr = SocketAddr{ip: opt_ipaddr.unwrap(), port: 7000};
let opt_socket = TcpServerSocket::bind(socketaddr, 0, &ev_queue);
if opt_socket.is_err() {
println!("Error: {:?}", opt_socket.unwrap_err());
fail!();
}
let mut server_socket = opt_socket.unwrap();
start_tx.send(true);
loop {
let event = ev_queue.next_event().unwrap();
if event.originates_from(server_socket) {
match event.event_type {
events::ClientConnectedEvent => {
println!("Client available");
let acceptres = server_socket.accept();
let socket = acceptres.unwrap();
println!("Accepted a client");
native::task::spawn(proc() {
clienttask(socket);
});
client_count -= 1;
if client_count == 0 {
server_socket.close();
break;
}
},
events::IoErrorEvent(err) => {
println!("IoError: {}", err.desc.to_owned());
break;
},
_ => ()
}
}
}
}
fn clienttask(mut socket: RawTcpSocket) {
let response = "HTTP 400 bad request";
let _ = socket.write(response.as_bytes());
}<file_sep>#[no_uv];
extern mod native;
extern mod revbio;
extern mod extra;
use std::io::net::ip::{IpAddr,SocketAddr};
use revbio::events;
use revbio::channel::{Transmitter,Receiver,Channel};
use revbio::{EventQueue};
use revbio::timer::Timer;
use revbio::tcp::{TcpSocket};
#[start]
fn start(argc: int, argv: **u8) -> int {
native::start(argc, argv, proc() {
main();
})
}
fn main() {
let mut ev_queue = EventQueue::new();
let (mut rx,tx): (~Receiver<~str>, Transmitter<~str>) = Channel::create(&ev_queue);
let mut main_timer = Timer::create(&ev_queue).unwrap();
main_timer.set_interval(2000);
main_timer.start();
native::task::spawn(proc() {
subtask(tx);
});
loop {
let event = ev_queue.next_event().unwrap();
if event.originates_from(rx) {
match event.event_type {
events::ChannelMessageEvent => {
let msg = rx.recv().unwrap();
println!("Message from subtask: {}", msg);
},
events::ChannelClosedEvent => {
println!("Subtask closed");
return;
},
_ => ()
}
}
else if event.originates_from(main_timer) {
println!("main_timer::tick()");
}
}
}
fn subtask(tx: Transmitter<~str>) {
let mut ev_queue = EventQueue::new();
let mut sub_timer = Timer::create(&ev_queue).unwrap();
let mut iterations = 3;
let mut stream_alive;
let host = ~"192.168.1.99";
let opt_ipaddr:Option<IpAddr> = FromStr::from_str(host);
let socketaddr = SocketAddr {ip: opt_ipaddr.unwrap(), port: 80};
let mut socket = TcpSocket::connect(socketaddr, &ev_queue).unwrap();
stream_alive = true;
sub_timer.set_interval(3000);
sub_timer.start();
let mut request = ~"GET / HTTP/1.1\r\nHost: ";
request = request + "host";
request = request + "\r\n\r\n";
loop {
let event = ev_queue.next_event().unwrap();
if event.originates_from(sub_timer) {
tx.send(~"subtimer::tick()");
if !stream_alive {
if iterations > 0 {
socket = TcpSocket::connect(socketaddr, &ev_queue).unwrap();
stream_alive = true;
}
else {
sub_timer.stop();
socket.close();
return;
}
}
}
else if event.originates_from(socket) {
match event.event_type {
events::ConnectedEvent => {
tx.send(~"TCP stream got connected");
stream_alive = true;
let _ = socket.write(request.as_bytes());
iterations -= 1;
},
events::IoErrorEvent(err) => {
tx.send(~"IoError");
tx.send(err.desc.to_owned());
stream_alive = false;
iterations -= 1;
},
events::StreamClosedEvent => {
tx.send(~"TCP connection closed");
stream_alive = false;
iterations -= 1;
},
events::DataAvailableEvent(nr_bytes) => {
let mut buffer: ~[u8] = std::vec::from_elem::<u8>(nr_bytes, 0);
let read_res = socket.read(buffer);
match read_res {
Err(err) => {
tx.send(err.desc.to_owned());
}
Ok(nr_read) => {
let txt = std::str::from_utf8(buffer.slice(0, nr_read));
if txt.is_some() {
tx.send(txt.unwrap().to_owned());
}
}
}
},
_ => ()
}
}
}
}<file_sep>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::cast;
use std::libc;
use std::cell::RefCell;
use std::rc::Rc;
use std::unstable::mutex::Mutex;
use std::sync::arc::UnsafeArc;
use collections::ringbuf::RingBuf;
use collections::deque::Deque;
use super::events;
use super::eventqueue::EventQueue;
use super::eventqueue::IEventQueue;
use super::eventqueueimpl::EventQueueImpl;
use super::syscalls;
use super::helpers;
pub struct BlockingReceiver<T> {
priv data: UnsafeArc<SharedChannelData<T>>
}
pub struct Transmitter<T> {
priv data: UnsafeArc<SharedChannelData<T>>
}
struct SharedChannelData<T> {
queue: RingBuf<T>,
mutex: Mutex,
port_alive: bool,
nr_senders: uint,
receiver_notified: bool,
epoll_fd: i32
}
pub struct Channel<T>;
impl <T:Send> Channel<T> {
pub fn create_blocking() -> (BlockingReceiver<T>, Transmitter<T>) {
let shared_data: UnsafeArc<SharedChannelData<T>>
= UnsafeArc::new(SharedChannelData {
queue: RingBuf::new(),
mutex: unsafe { Mutex::new() },
port_alive: true,
receiver_notified: false,
nr_senders: 1,
epoll_fd: -1
});
(BlockingReceiver{data: shared_data.clone()}, Transmitter{data: shared_data})
}
pub fn create(event_queue: &EventQueue) -> (~Receiver<T>, Transmitter<T>) {
let (rx,tx) = Channel::<T>::create_blocking();
(Receiver::from_blocking_receiver(rx, event_queue), tx)
}
}
impl<T:Send> BlockingReceiver<T> {
pub fn recv(&self) -> T {
let data = self.data.get();
unsafe {
(*data).mutex.lock();
while ((*data).queue.len() < 1) && ((*data).nr_senders != 0) {
(*data).mutex.wait();
}
if (*data).queue.len() > 0 {
let ret = (*data).queue.pop_front().unwrap();
(*data).receiver_notified = false;
(*data).mutex.unlock();
ret
}
else { // Sender(s) dead
(*data).mutex.unlock();
fail!("Remote channels are dead");
}
}
}
pub fn recv_opt(&self) -> Option<T> {
let data = self.data.get();
let mut ret = None;
unsafe {
(*data).mutex.lock();
while ((*data).queue.len() < 1) && ((*data).nr_senders != 0) {
(*data).mutex.wait();
}
if (*data).queue.len() > 0 {
ret = Some((*data).queue.pop_front().unwrap());
}
(*data).receiver_notified = false;
(*data).mutex.unlock();
ret
}
}
pub fn try_recv(&self) -> TryRecvResult<T> {
let data = self.data.get();
let mut ret = Empty;
unsafe {
(*data).mutex.lock();
if (*data).queue.len() >= 1 {
ret = Data((*data).queue.pop_front().unwrap());
}
else if (*data).nr_senders == 0 {
ret = Disconnected;
}
(*data).receiver_notified = false;
(*data).mutex.unlock();
ret
}
}
}
#[unsafe_destructor]
impl<T:Send> Drop for BlockingReceiver<T> {
fn drop(&mut self) {
let data = self.data.get();
unsafe {
(*data).mutex.lock();
(*data).port_alive = false;
(*data).queue.clear();
(*data).mutex.unlock();
}
}
}
pub enum TryRecvResult<T> {
Empty,
Disconnected,
Data(T),
}
pub struct Receiver<T> {
priv process_func: fn(func_ptr: *libc::c_void, event_queue: &mut EventQueueImpl, epoll_events: u32),
priv receiver: BlockingReceiver<T>,
priv event_queue: Rc<RefCell<EventQueueImpl>>,
priv event_source_info: Rc<events::EventSourceInfo>,
priv epoll_events: u32,
priv available_messages: uint
}
impl<T> events::EventSource for Receiver<T> {
fn get_event_source_info<'a>(&'a self) -> &'a Rc<events::EventSourceInfo> {
&self.event_source_info
}
}
impl<T:Send> Receiver<T> {
pub fn from_blocking_receiver(blocking_receiver: BlockingReceiver<T>, event_queue: &EventQueue) -> ~Receiver<T> {
let receiver = ~Receiver{
receiver: blocking_receiver,
event_queue: event_queue._get_impl(),
process_func: Receiver::<T>::process_epoll_events,
event_source_info: Rc::new(events::EventSourceInfo::new()),
epoll_events: 0,
available_messages: 0
};
let data = receiver.receiver.data.get();
unsafe {
(*data).mutex.lock();
if (*data).nr_senders != 0 { // Don't need to do anything when there are 0 senders
let fd = syscalls::eventfd(0, 0);
if fd == -1 {
(*data).mutex.unlock();
fail!("Creating eventfd for port failed: {}", helpers::last_error().desc);
}
(*data).epoll_fd = fd;
let callback: *libc::c_void = cast::transmute(&receiver.process_func);
receiver.event_queue.borrow().with_mut(|q|
q.register_fd(fd, syscalls::EPOLLIN, callback)
);
// Check if there are messages available and if yes queue them
if (*data).queue.len() > 0 {
let bytes = [0,..8];
let content: *mut u64 = cast::transmute(&bytes);
*content = 1;
let ret = helpers::retry(||
libc::write(fd, bytes.as_ptr() as *libc::c_void, 8) as libc::c_int
);
if ret == -1 {
(*data).mutex.unlock();
fail!("Error on writing to eventfd: {}", helpers::last_error().desc);
}
(*data).receiver_notified = true;
}
}
else {
receiver.event_queue.borrow().with_mut(|q|
q.push_back_event(events::Event{
event_type: events::ChannelClosedEvent,
is_valid: true,
source_info: receiver.event_source_info.clone()
})
);
}
(*data).mutex.unlock();
}
receiver
}
pub fn recv(&mut self) -> Option<T> {
if self.available_messages > 0 {
let ret = self.receiver.recv();
self.available_messages -= 1;
Some(ret)
}
else {
None
}
}
fn process_epoll_events(func_ptr: *libc::c_void, event_queue: &mut EventQueueImpl, epoll_events: u32) {
unsafe {
let receiver: *mut Receiver<T> = func_ptr as *mut Receiver<T>;
let data = (*receiver).receiver.data.get();
if epoll_events & syscalls::EPOLLIN != 0 {
let buffer = [0, ..8];
let ret = helpers::retry(||
libc::read((*data).epoll_fd,
buffer.as_ptr() as *mut libc::c_void,
buffer.len() as libc::size_t) as i32
);
if ret == 8 { // Must be 8 bytes
let value: *u64 = cast::transmute(&buffer);
if *value == 1 {
(*data).mutex.lock();
let new_messages = (*data).queue.len() - (*receiver).available_messages;
(*receiver).available_messages += (*data).queue.len();
for _ in range(0, new_messages) {
let e = events::Event {
event_type: events::ChannelMessageEvent,
is_valid: true,
source_info: (*receiver).event_source_info.clone()
};
event_queue.push_back_event(e);
}
if (*data).nr_senders == 0 {
let e = events::Event {
event_type: events::ChannelClosedEvent,
is_valid: true,
source_info: (*receiver).event_source_info.clone()
};
event_queue.push_back_event(e);
}
(*data).receiver_notified = false;
(*data).mutex.unlock();
}
}
}
}
}
fn remove_pending_events(&mut self) {
self.event_queue.borrow().with_mut(|q|
q.remove_pending_events(
|ev|ev.originates_from(self))
);
}
}
#[unsafe_destructor]
impl<T:Send> Drop for Receiver<T> {
fn drop(&mut self) {
let data = self.receiver.data.get();
unsafe {
(*data).mutex.lock();
if (*data).epoll_fd != -1 {
libc::close((*data).epoll_fd);
(*data).epoll_fd = -1; // Disable further events from clients
}
(*data).mutex.unlock();
}
self.remove_pending_events();
}
}
impl<T:Send> Transmitter<T> {
pub fn send(&self, t: T) {
self.try_send(t);
}
pub fn try_send(&self, t: T) -> bool {
let data = self.data.get();
unsafe {
(*data).mutex.lock();
if !(*data).port_alive {
(*data).mutex.unlock();
return false;
}
(*data).queue.push_back(t);
if (*data).queue.len() == 1 && !(*data).receiver_notified { // Signal to receiver
// Decide depending on port state what to do
if (*data).epoll_fd == -1 {
(*data).mutex.signal();
}
else {
let bytes = [0,..8];
let content: *mut u64 = cast::transmute(&bytes);
*content = 1;
let ret = helpers::retry(||
libc::write((*data).epoll_fd, bytes.as_ptr() as *libc::c_void, 8) as libc::c_int
);
if ret == -1 {
(*data).mutex.unlock();
fail!("Error on writing to eventfd: {}", helpers::last_error().desc);
}
}
(*data).receiver_notified = true;
}
(*data).mutex.unlock();
}
true
}
}
#[unsafe_destructor]
impl<T:Send> Drop for Transmitter<T> {
fn drop(&mut self) {
// Decrease refcount
let data = self.data.get();
unsafe {
(*data).mutex.lock();
(*data).nr_senders -= 1;
if (*data).nr_senders == 0 && !(*data).receiver_notified {
if (*data).epoll_fd == -1 {
(*data).mutex.signal();
}
else {
let bytes = [0,..8];
let content: *mut u64 = cast::transmute(&bytes);
*content = 1;
let ret = helpers::retry(||
libc::write((*data).epoll_fd, bytes.as_ptr() as *libc::c_void, 8) as libc::c_int
);
if ret == -1 {
(*data).mutex.unlock();
fail!("Error on writing to eventfd: {}", helpers::last_error().desc);
}
}
(*data).receiver_notified = true;
}
(*data).mutex.unlock();
}
}
}
impl<T:Send> Clone for Transmitter<T> {
fn clone(&self) -> Transmitter<T> {
let new = Transmitter{data: self.data.clone()};
// Increase refcount
let data = self.data.get();
unsafe {
(*data).mutex.lock();
(*data).nr_senders += 1;
(*data).mutex.unlock();
}
new
}
}<file_sep>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::libc;
/// Epoll typess
pub static EPOLLIN: u32 = 0x001;
pub static EPOLLPRI: u32 = 0x002;
pub static EPOLLOUT: u32 = 0x004;
pub static EPOLLRDNORM: u32 = 0x040;
pub static EPOLLRDBAND: u32 = 0x080;
pub static EPOLLWRNORM: u32 = 0x100;
pub static EPOLLWRBAND : u32 = 0x200;
pub static EPOLLMSG: u32 = 0x400;
pub static EPOLLERR: u32 = 0x008;
pub static EPOLLHUP: u32 = 0x010;
pub static EPOLLONESHOT: u32 = (1 << 30);
pub static EPOLLET: u32 = (1 << 31);
pub static EPOLL_CTL_ADD: i32 = 1; /* Add a file decriptor to the interface. */
pub static EPOLL_CTL_DEL: i32 = 2; /* Remove a file decriptor from the interface. */
pub static EPOLL_CTL_MOD: i32 = 3; /* Change file decriptor epoll_event structure. */
/// Structure that allows to store user data during an epoll operation
pub struct epoll_data {
data: [u8, ..8]
}
impl epoll_data {
pub fn new() -> epoll_data {
epoll_data {data: [0, ..8]}
}
pub fn set_data_as_u64(&mut self, data:u64) {
let start: *mut epoll_data = self;
unsafe { *(start as *mut u64) = data; }
}
pub fn as_u64(&self) -> u64 {
let start: *epoll_data = self;
unsafe { *(start as *u64) }
}
pub fn set_data_as_u32(&mut self, data: u32) {
self.data = [0, ..8];
let start: *mut epoll_data = self;
unsafe { *(start as *mut u32) = data; }
}
pub fn get_data_as_u32(&self) -> u32 {
let start: *epoll_data = self;
unsafe { *(start as *u32) }
}
pub fn set_data_as_fd(&mut self, fd: i32) {
self.data = [0, ..8];
let start: *mut epoll_data = self;
unsafe { *(start as *mut i32) = fd; }
}
pub fn get_data_as_fd(&self) -> i32 {
let start: *epoll_data = self;
unsafe { *(start as *i32) }
}
pub fn set_data_as_ptr(&mut self, ptr: *libc::c_void) {
self.data = [0, ..8];
let start: *mut epoll_data = self;
unsafe { *(start as *mut* libc::c_void) = ptr; }
}
pub fn get_data_as_ptr(&self) -> *libc::c_void {
let start: *epoll_data = self;
unsafe { *(start as **libc::c_void) }
}
}
pub struct epoll_event {
/// Epoll events
events: u32,
/// Epoll user data
data: epoll_data
}
impl epoll_event {
pub fn new() -> epoll_event {
epoll_event{
events: 0,
data: epoll_data::new()
}
}
}
extern {
pub fn epoll_create(size: i32) -> i32;
pub fn epoll_ctl(epfd: i32, op: i32, fd: i32, event: *epoll_event) -> i32;
pub fn epoll_wait(epfd: i32, events: *epoll_event,
maxevents: i32, timeout: i32) -> i32;
}
/// Timerfd calls
extern {
pub fn timerfd_create(clockid: i32, flags: i32) -> i32;
pub fn timerfd_settime(fd: i32, flags: i32,
new_value: *itimerspec,
old_value: *itimerspec) -> i32;
pub fn timerfd_gettime(fd: i32, curr_value: *itimerspec) -> i32;
}
pub struct itimerspec {
it_interval: libc::timespec, /* Interval for periodic timer */
it_value: libc::timespec /* Initial expiration */
}
impl itimerspec {
pub fn new() -> itimerspec {
itimerspec {
it_interval: libc::timespec {
tv_sec: 0,
tv_nsec: 0
},
it_value: libc::timespec {
tv_sec: 0,
tv_nsec: 0
}
}
}
}
extern {
pub fn eventfd(initval: u32, flags: i32) -> i32;
pub fn ioctl(fd: i32, req: i32, ...) -> i32;
pub fn fcntl(fd: i32, cmd:i32, ...) -> i32;
pub fn getsockopt(socket: libc::c_int, level: libc::c_int, name: libc::c_int,
value: *libc::c_void, option_len: *libc::socklen_t) -> libc::c_int;
}
pub fn set_fd_blocking(fd: i32, blocking: bool) {
unsafe {
let mut flags = fcntl(fd, F_GETFL, 0);
if blocking {
flags = flags & !O_NONBLOCK;
}
else {
flags = flags |O_NONBLOCK;
}
fcntl(fd, F_SETFL, flags);
}
}
pub static FIONREAD: i32 = 0x541B;
pub static O_NONBLOCK: i32 = 0x800;
pub static F_GETFL: i32 = 3; /* Get file status flags. */
pub static F_SETFL: i32 = 4; /* Set file status flags. */
pub static SOCK_CLOEXEC: i32 = 0x80000; /* Atomically set close-on-exec flag for the new descriptor(s). */
pub static SOCK_NONBLOCK: i32 = 0x800; /* Atomically mark descriptor(s) as non-blocking. */
// Socket options
pub static SO_DEBUG: i32 = 1;
pub static SO_REUSEADDR: i32 = 2;
pub static SO_TYPE: i32 = 3;
pub static SO_ERROR : i32 = 4;
pub static SO_DONTROUTE: i32 = 5;
pub static SO_BROADCAST: i32 = 6;
pub static SO_SNDBUF: i32 = 7;
pub static SO_RCVBUF: i32 = 8;
pub static SO_SNDBUFFORCE: i32 = 32;
pub static SO_RCVBUFFORCE: i32 = 33;
pub static SO_KEEPALIVE: i32 = 9;
pub static SO_OOBINLINE: i32 = 10;
pub static SO_NO_CHECK: i32 = 11;
pub static SO_PRIORITY: i32 = 12;
pub static SO_LINGER: i32 = 13;
pub static SO_BSDCOMPAT: i32 = 14;
pub static SO_REUSEPORT: i32 = 15;<file_sep>revbio
======
revbio is a Rust library which provides event based I/O.
It provides the ability to use multiple I/O objects like Sockets, Signals, Timers or Channels in a single task parallel.
`revbio` is based on `Events` that signal the new status of these objects.
revbio is currently an experiment. Use it at your own risk. All APIs may heavily change.
Supported platforms
-------------------
revio works only inside Rusts native tasks.
In addition to that currently linux is the only supported platform.
Building revbio
---------------
Simply execute `rustc lib.rs`
Example
-------
For an example see example.rs in the repository
|
d5f46f80581cb638a762b1c8af38970d8470c6c1
|
[
"Markdown",
"Rust",
"Shell"
] | 14 |
Shell
|
cambricorp/revbio
|
8b8e27a1eb8e40c13cb7c158b40a0bde60c6f0a2
|
198e20eac9e8e74ca9047c67eb5e0e0949380e32
|
refs/heads/master
|
<file_sep>#!/bin/bash
git_mode=$1
echo ""
echo "setup the development environment"
set -e
repos=$(curl https://api.github.com/orgs/aztfmod/repos)
setup_folder () {
folder=$1
if [ -d ${folder} ]; then
echo "${folder} folder exists"
else
mkdir ${folder}
echo "${folder} folder created"
fi
}
clone () {
name=$1
ssh_url=$2
clone_url=$3
folder=$4
git_clone_mode=$5
echo ""
echo "-----------------------------------------------"
echo "name: '${name}'"
echo "ssh_url: '${ssh_url}'"
echo "clone_url: '${clone_url}'"
echo "folder: '${folder}'"
echo "git_clone_mode: '${git_clone_mode}'"
if [ ! -z $name ]; then
echo "cloning $name"
# Check if the folder already exist
if [ ! -d "${folder}${name}" ]; then
echo "cloning with ${git_clone_mode} - ${name} into ${folder}${name}"
if [ ${git_clone_mode} == "gitssh" ]; then
git clone $ssh_url ${folder}${name}
else
git clone $clone_url ${folder}${name}
fi
else
echo "already cloned with ${git_clone_mode}"
fi
fi
}
# Cloning modules
repos_to_clone=$(echo $repos | jq '.[] | select(.full_name | contains("aztfmod/terraform-azurerm-caf-")) | "\(.name) \(.ssh_url) \(.clone_url)"')
setup_folder "../modules"
echo ${repos_to_clone} | while read -d '" "' line; do
if [ ! -z "${line}" ]; then
clone ${line} "../modules/" ${git_mode}
fi
done
# Cloning landingzone_template
repos_to_clone=$(echo $repos | jq '.[] | select(.full_name | contains("aztfmod/landingzone_template")) | "\(.name) \(.ssh_url) \(.clone_url)"')
echo ${repos_to_clone} | while read -d '" "' line; do
if [ ! -z "${line}" ]; then
clone ${line} "../" ${git_mode}
fi
done
# Cloning landingzones
repos_to_clone=$(echo $repos | jq '.[] | select(.full_name | contains("aztfmod/landingzones")) | "\(.name) \(.ssh_url) \(.clone_url)"')
echo ${repos_to_clone} | while read -d '" "' line; do
if [ ! -z "${line}" ]; then
clone ${line} "../" ${git_mode}
fi
done
# Cloning level0
repos_to_clone=$(echo $repos | jq '.[] | select(.full_name | contains("aztfmod/level0")) | "\(.name) \(.ssh_url) \(.clone_url)"')
echo ${repos_to_clone} | while read -d '" "' line; do
if [ ! -z "${line}" ]; then
clone ${line} "../" ${git_mode}
fi
done
<file_sep>ARG versionAzureCli
FROM mcr.microsoft.com/azure-cli:${versionAzureCli}
ARG versionTerraform
RUN apk update \
&& apk add bash jq unzip git
RUN echo "Installing terraform ${versionTerraform}..." \
&& curl -LO https://releases.hashicorp.com/terraform/${versionTerraform}/terraform_${versionTerraform}_linux_amd64.zip \
&& unzip -d /usr/local/bin terraform_${versionTerraform}_linux_amd64.zip \
&& rm terraform_${versionTerraform}_linux_amd64.zip
WORKDIR /tf
COPY rover/scripts/launchpad.sh .
COPY rover/scripts/functions.sh .
RUN git clone https://github.com/aztfmod/landingzones.git /tf/landingzones
RUN git clone https://github.com/aztfmod/level0.git /tf/level0
ENTRYPOINT [ "./launchpad.sh" ]
|
98ec5ac18aa134af0507281e0ad622748341f7d8
|
[
"Dockerfile",
"Shell"
] | 2 |
Shell
|
theG1/rover
|
962aedaa5bcc05376e529a7ba0b910c375077807
|
5ff18df3c685c35ebf0713ba6c2fd343eb316817
|
refs/heads/master
|
<repo_name>mikelietz/tag_url_cleaner<file_sep>/tag_url_cleaner.plugin.php
<?php
class TagURLCleaner extends Plugin
{
public function filter_rewrite_rules( $rules )
{
foreach( $rules as $rule ) {
if( $rule->name == 'display_entries_by_tag' ) {
$rule->parse_regex = '#^(?P<tag>[^/]+)(?:/page/(?P<page>\d+))?/?$#i';
$rule->build_str = '{$tag}(/page/{$page})';
return $rules;
}
}
return $rules;
}
}
?>
|
a99a628f937132f90bf650965aa8dbc61435cd87
|
[
"PHP"
] | 1 |
PHP
|
mikelietz/tag_url_cleaner
|
278ce3e4f20f51f0f0610283dc83b60727772d41
|
674405fbb8aef9ba27ecb240dc3bf30997415681
|
refs/heads/master
|
<repo_name>emanuelemazza/cloudily<file_sep>/README.rst
Cloudily - automatically visualize your EC2 infrastructure
==========================================================
.. image:: http://loads.pickle.me.uk/static/images/cloudily.png
Getting Started
---------------
You'll need `graphviz <http://www.graphviz.org/>`_ installed, and optionally
`imagemagick <http://www.imagemagick.org/>`_ to use the ``--preview`` functionality.
On Ubuntu::
$ sudo apt-get install graphviz imagemagick
Install cloudily from `PyPI <http://pypi.python.org/pypi/graphops>`_ like so::
$ sudo pip install cloudily
Run cloudily::
$ cloudily --ec2 instances,elb --conns --preview
Open montage.png in your favourite image viewer::
$ qiv montage.png
The ``--preview`` makes a montage of the various graphviz layouts available.
Depending on your network usually 'dot' produces the cleaner layouts, but others
may work better / look cooler.
Visualizing EC2 hosts
---------------------
Use the ``--ec2`` option to visualize your EC2 instances and ELBs. Run::
$ cloudily --ec2 instances,elb --conns --png myarch.png
You need to set your Amazon credentials as environment variables: AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY or configure them in ~/.boto. For more information see:
http://code.google.com/p/boto/wiki/BotoConfig
``--ec2groups`` may be used to filter by security group. This accepts a comma-
separated list of multiple groups. eg. ``--ec2groups group1,group2``
Discovery
---------
There are various ways Cloudily can discover the connections between your
hosts.
``--arp``: Looks at the IP addresses in the arp cache. This has limited use inside
EC2, since hosts are usually on different subnets, but maybe useful for other
setups.
``--conns``: Looks at the currently open UDP and TCP connections for each host. If
the system is active or there is connection pooling (eg. most database
libraries) you should see everything, otherwise there's a chance you'll
not see connections through inactivity.
``--logins``: Includes logins by username in the diagram so you can see who logs
in to which hosts.
Other options
-------------
With ``--conns`` you can also limit to a selection of ports using ``--connsports
80,3306``. This is handy if you're only interested in specific services.
Changelog
---------
0.1.4
- Robustify code to missing values. Fixes #3
- Add --ec2groups option. Fixes #1
- Fix for internal ELBs. Fixes #2
0.1.3
- .ssh/config optional
0.1.2
- Fix defaults
0.1.1
- First release
<file_sep>/scripts/cloudily
#!/usr/bin/env python
import boto.ec2
import boto.ec2.elb
import paramiko
import os
import re
import socket
import sys
from optparse import OptionParser
import logging
import subprocess
from multiprocessing.pool import ThreadPool
logger = logging.getLogger('cloudily')
def abort(message):
raise SystemExit(message)
class Node(object):
"""Base class for a graph node"""
def __init__(self, id, name, aliases=[]):
self.id = id
self.name = name
self.aliases = ['id:%s' % id] + aliases
def __hash__(self):
return hash(self.id)
def __eq__(self, a):
return self.id == a.id
def __str__(self):
return self.id
class Elb(Node):
"""An ELB node"""
pass
class Host(Node):
"""A physical host node"""
def __init__(self, id, hostname, aliases, name):
self.id = id
self.hostname = hostname
self.aliases = aliases
self.name = name
self.ssh = None
def __str__(self):
return self.name
def connect(self):
# ssh config file
config = paramiko.SSHConfig()
# usage ssh config for username, keys, etc.
configfile = os.path.expanduser('~/.ssh/config')
if os.path.exists(configfile):
config.parse(open(configfile))
o = config.lookup(self.hostname)
# ssh client
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
username = o.get('user', os.getlogin())
self.ssh.connect(o['hostname'], username=username, timeout=10)
@property
def connection(self):
if not self.ssh:
self.connect()
return self.ssh
class HostScanner(object):
"""Base class for a host scanner"""
def get_output(self, host, cmd):
logger.debug('Executing: %s on %s' % (cmd, host))
stdin, stdout, stderr = host.connection.exec_command(cmd)
return stdout.read()
@property
def types(self):
return (Host,)
class ArpScanner(HostScanner):
"""Get host-host connections by entries in the arp cache"""
re_arp_ip = re.compile(r'\(([^)]+)\)')
def list(self, host):
output = self.get_output(host, 'arp -an')
for line in output.split('\n'):
m = self.re_arp_ip.search(line)
if m:
yield host, 'ip:%s' % m.group(1), True, None
class LoginScanner(HostScanner):
"""Get user-host connections by user logins"""
def __init__(self, mode):
self.mode = mode
def list(self, host):
output = self.get_output(host, 'last -w')
for line in output.split('\n'):
if not line or line.startswith('wtmp begins') or line.startswith('reboot'):
continue
username = line.split(' ')[0]
yield host, 'user:%s' % username, False, None
class NetstatScanner(HostScanner):
"""Get host-host connections by open connections"""
def __init__(self, ports):
if ports:
self.ports = set(ports.split(','))
else:
self.ports = None
# some additional services along with /etc/services
known_services = {
'9200/tcp': 'elasticsearch',
'9300/tcp': 'elasticsearch node',
'9500/tcp': 'elasticsearch thrift',
'6379/tcp': 'redis',
'26379/tcp': 'redis sentinel',
'8649/tcp': 'ganglia gmetad',
'8649/udp': 'ganglia gmetad',
'27017/tcp': 'mongo',
'27018/tcp': 'mongo slave',
}
def getservbyport(self, port, proto):
key = '%s/%s' % (port, proto)
# lookup in known_services
if key in self.known_services:
return self.known_services[key]
try:
# lookup in /etc/services
v = socket.getservbyport(int(port))
self.known_services[key] = v
return v
except:
pass
return None
re_ws = re.compile('\s+')
def list(self, host):
output = self.get_output(host, 'netstat -nut')
for line in output.split('\n'):
if not line or not (line.startswith('tcp') or line.startswith('udp')):
continue
try:
parts = self.re_ws.split(line)
proto, recvq, sendq, local, remote, state = parts[:6]
if proto == 'tcp6':
proto = 'tcp'
lip, lport = local.split(':', 1)
rip, rport = remote.split(':', 1)
if lip == '127.0.0.1':
continue
if self.ports and not(rport in self.ports or lport in self.ports):
continue
label = self.getservbyport(rport, proto)
if label:
yield host, 'ip:%s' % rip, True, label
continue
label = self.getservbyport(lport, proto)
if label:
yield host, 'ip:%s' % rip, False, label
continue
# unknown protocol on either end - warn?
logging.warn('Unknown source/dest port on connection: %s (%r)' % (line, parts))
except ValueError:
continue
class NodeScanner(object):
"""Base class for a node scanner"""
@property
def types(self):
return None
def __str__(self):
return self.__class__.__name__
class EC2NodeScanner(NodeScanner):
"""Scanner for EC2 resources.
Supports:
- instances
- ELBs
"""
def __init__(self, key, secret, options, groups):
self.key = key
self.secret = secret
self.options = options
self.groups = groups
def get_instances(self, filters={}):
conn = self.get_connection()
filters = {'instance-state-name': 'running'}
instances = (inst for r in conn.get_all_instances(filters=filters) for inst in r.instances)
# post filters
if self.groups:
def contains_group(inst):
groupnames = set(g.name for g in inst.groups)
return groupnames & set(self.groups)
instances = (inst for inst in instances if contains_group(inst))
return instances
def get_elbs(self):
conn = boto.ec2.elb.connect_to_region(os.getenv('EC2_REGION', 'us-east-1'))
return conn.get_all_load_balancers()
def get_connection(self):
ec2_region = os.getenv('EC2_REGION', 'us-east-1')
return boto.ec2.connect_to_region(ec2_region)
def list(self):
if 'instances' in self.options:
for inst in self.get_instances():
name = inst.tags.get('Name') or inst.public_dns_name
aliases = ['id:%s' % inst.id, 'host:%s' % inst.public_dns_name, 'ip:%s' % inst.ip_address, 'ip:%s' % inst.private_ip_address]
yield Host(inst.id, inst.public_dns_name, aliases, name)
if 'elb' in self.options:
for lb in self.get_elbs():
aliases = []
try:
logger.debug("Looking up %s" % lb.dns_name)
hostname, aliaslist, ipaddrlist = socket.gethostbyname_ex(lb.dns_name)
aliases = ['host:%s' % hostname] + ['host:%s' % h for h in aliaslist] + ['ip:%s' % ip for ip in ipaddrlist]
except socket.error:
logger.debug("Could not resolve %s (possibly an internal ELB)" % lb.dns_name)
elb = Elb('elb:%s' % lb.name, '%s ELB' % lb.name, aliases)
yield elb
for inst in lb.instances:
yield elb, 'id:%s' % inst.id, True, None
class FileNodeScanner(NodeScanner):
"""Scanner using static host list"""
def __init__(self, filename):
self.filename = filename
def list(self):
with file(self.filename) as fin:
for line in fin:
hostname = line.strip()
ip = socket.gethostbyname(hostname)
aliases = ['host:%s' % hostname, 'ip:%s' % ip]
yield Host(hostname, hostname, aliases, hostname)
class Edge(object):
"""Represents an edge in the graph"""
def __init__(self, frm, to, label):
self.frm = frm
self.to = to
self.label = label
def __hash__(self):
return hash(self.frm) ^ hash(self.to) ^ hash(self.label)
def __eq__(self, a):
return self.frm == a.frm and self.to == a.to and self.label == a.label
def __str__(self):
return '%s -> %s' % (self.frm, self.to)
def unique(seq):
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)]
class Cloudily(object):
"""Main class"""
def run(self):
self.parse_args()
self.configure()
self.scan()
self.save(self.opts.out)
if self.opts.png:
self.render(self.opts.out, self.opts.png, self.opts.layout)
if self.opts.preview:
self.preview(self.opts.out)
def parse_args(self):
parser = OptionParser()
parser.add_option('--unknown', action='store_true', help='Include unknown nodes')
parser.add_option('--out', default='output.dot', help='Dot output filename')
parser.add_option('--hosts', help='A static host list: file.txt')
parser.add_option('--ec2', help='Scan EC2 for instances, elb,etc.')
parser.add_option('--ec2creds', default='env', help='Use EC2 for host list')
parser.add_option('--ec2groups', help='Filter by ec2 security groups (comma-separate multiple groups)')
parser.add_option('--arp', action='store_true', help='Scan arp cache')
parser.add_option('--logins', help='Scan user logins. Value currently unused.')
parser.add_option('--conns', action='store_true', help='Scan open connections (netstat)')
parser.add_option('--connsports', help='Port list to include')
parser.add_option('--labels', action='store_true', help='Add edge labels (if available)')
parser.add_option('--preview', action='store_true', help='Generate a preview montage of graphviz layouts')
parser.add_option('--png', help='Generate a png image using graphviz')
parser.add_option('--layout', default='dot', help='Select a layout to use for the png image')
self.opts, self.args = parser.parse_args()
if not self.opts.arp and not self.opts.logins and not self.opts.conns:
self.opts.conns = True
if not self.opts.hosts and not self.opts.ec2:
self.opts.ec2 = 'instances,elb'
def configure(self):
self.scanners = s = []
self.parse_args()
if self.opts.hosts:
s.append(FileNodeScanner(self.opts.hosts))
elif self.opts.ec2:
if self.opts.ec2creds == 'env':
key = os.getenv('AWS_ACCESS_KEY_ID')
if not key:
abort('AWS_ACCESS_KEY_ID not set')
secret = os.getenv('AWS_SECRET_ACCESS_KEY')
if not secret:
abort('AWS_SECRET_ACCESS_KEY not set')
options = self.opts.ec2.split(',')
groups = None
if self.opts.ec2groups:
groups = self.opts.ec2groups.split(',')
s.append(EC2NodeScanner(key, secret, options, groups))
if self.opts.arp:
s.append(ArpScanner())
if self.opts.logins:
s.append(LoginScanner(self.opts.logins))
if self.opts.conns:
s.append(NetstatScanner(self.opts.connsports))
logging.basicConfig(level=logging.WARN, format='%(levelname)-8s %(message)s')
logger.setLevel(logging.DEBUG)
def scan(self):
pool = ThreadPool(8)
nodes = []
edges = set()
lookup = {}
for scanner in self.scanners:
if scanner.types is None:
logger.info('Scanning using %s' % scanner)
results = scanner.list()
else:
def scan_node(node):
logger.info('Scanning node %s' % node)
try:
results = list(scanner.list(node))
logger.debug('Finished node %s' % node)
return results
except:
logger.exception('Exception scanning node: %s' % node)
return []
matches = [node for node in nodes if isinstance(node, scanner.types)]
results = [r for rs in pool.map(scan_node, matches) for r in rs]
for result in results:
if isinstance(result, Node):
logger.debug('Discovered node: %s' % result)
nodes.append(result)
for a in result.aliases:
lookup[a] = result
else:
node, id, forward, label = result
target = lookup.get(id)
if not target and self.opts.unknown:
target = Node(id, id)
nodes.append(target)
lookup[node] = target
if not self.opts.labels:
label = None
if target:
if forward:
edge = Edge(node, target, label)
else:
edge = Edge(target, node, label)
if edge not in edges:
logger.debug('Discovered edge: %s' % edge)
edges.add(edge)
self.nodes = nodes
self.edges = edges
logger.info('Done')
def save(self, filename):
if filename == '-':
self.to_dot(sys.stdout)
else:
with file(filename, 'w') as fout:
self.to_dot(fout)
def render(self, dot, png, prog):
try:
ps = subprocess.Popen([prog, '-Tpng', dot], stdout=subprocess.PIPE)
output = ps.communicate()[0]
with file(png, 'w') as fout:
fout.write(output)
logger.info("Generated: %s (layout: %s)" % (png, prog))
except Exception as ex:
logger.error("Problem running graphviz '%s' command.\n\n"
"Please ensure imagemagick is installed:\n"
" %s" % (prog, str(ex)))
def preview(self, filename):
files = []
for prog in ('dot', 'neato', 'circo', 'fdp', 'sfdp', 'twopi'):
self.render(filename, '%s.png' % prog, prog)
files.append('%s.png' % prog)
montage = 'montage.png'
args = ['montage', '-label', "'%f'"]
args.extend(files)
args.extend(['-geometry', '800x800', montage])
try:
subprocess.call(args)
logger.info("Generated: %s (from: %s)" % (montage, ', '.join(files)))
except Exception as ex:
logger.error("Problem running imagemagick 'montage' command.\n\n"
"Please ensure imagemagick is installed:\n"
" %s" % str(ex))
shapes = {
Host: 'box',
Elb: 'trapezium',
}
def to_dot(self, fout):
print >>fout, 'digraph network {'
print >>fout, ' graph [overlap=false];'
for node in self.nodes:
shape = self.shapes.get(type(node), 'ellipse')
print >>fout, ' "%s" [label="%s", shape=%s];' % (node.id, node.name, shape)
print >>fout
for edge in self.edges:
if edge.label:
print >>fout, ' "%(from)s" -> "%(to)s" [label="%(label)s"];' % {'from': edge.frm.id, 'label': edge.label, 'to': edge.to.id}
else:
print >>fout, ' "%s" -> "%s";' % (edge.frm.id, edge.to.id)
print >>fout, '}'
def main():
Cloudily().run()
if __name__ == '__main__':
main()
<file_sep>/release.sh
#!/bin/bash -e
sublime -w setup.py:4
VERSION=$(python setup.py --version)
# make changelog
echo -e "$VERSION\n" > changelog
git log --format='- %s%n' $(git describe --abbrev=0).. >> changelog
sublime -w README.rst:56 changelog
rm changelog
git add README.rst setup.py
git commit -m $VERSION
git push
python setup.py release
echo "$VERSION released"
|
f738290bb735469790145ccf73fcb526408d1df7
|
[
"Python",
"reStructuredText",
"Shell"
] | 3 |
reStructuredText
|
emanuelemazza/cloudily
|
8f6c7cca4e4d7b16d17a1fdf2a8b6a644dd4cfb9
|
64667cbde3287d46e8681dbf04cb6577514b9204
|
refs/heads/master
|
<file_sep>//! Room buffer module.
//!
//! This module implements creates buffers that processes and prints out all the
//! user visible events
//!
//! Care should be taken when handling events. Events can be state events or
//! timeline events and they can come from a sync response or from a room
//! messages response.
//!
//! Events coming from a sync response and are part of the timeline need to be
//! printed out and they need to change the buffer state (e.g. when someone
//! joins, they need to be added to the nicklist).
//!
//! Events coming from a sync response and are part of the room state only need
//! to change the buffer state.
//!
//! Events coming from a room messages response, meaning they are old events,
//! should never change the room state. They only should be printed out.
//!
//! Care should be taken to model this in a way that event formatting methods
//! are pure functions so they can be reused e.g. if we print messages that
//! we're sending ourselves before we receive them in a sync response, or if we
//! decrypt a previously undecryptable event.
use matrix_sdk::events::collections::all::{RoomEvent, StateEvent};
use matrix_sdk::events::room::encrypted::EncryptedEvent;
use matrix_sdk::events::room::member::{MemberEvent, MembershipState};
use matrix_sdk::events::room::message::{
MessageEvent, MessageEventContent, TextMessageEventContent,
};
use matrix_sdk::Room;
use url::Url;
use crate::server::Connection;
use crate::Config;
use std::cell::RefCell;
use std::rc::Rc;
use weechat::buffer::{Buffer, BufferHandle, BufferSettings, NickSettings};
use weechat::Weechat;
pub(crate) struct RoomMember {
nick: String,
user_id: String,
prefix: String,
color: String,
}
pub(crate) struct RoomBuffer {
server_name: String,
homeserver: Url,
buffer_handle: BufferHandle,
room_id: String,
prev_batch: Option<String>,
typing_notice_time: Option<u64>,
room: Room,
printed_before_ack_queue: Vec<String>,
}
impl RoomBuffer {
pub fn new(
server_name: &str,
connected_state: &Rc<RefCell<Option<Connection>>>,
homeserver: &Url,
config: &Config,
room_id: String,
own_user_id: &str,
) -> Self {
let state = Rc::downgrade(connected_state);
let buffer_settings = BufferSettings::new(&room_id.to_string())
.input_data((state, room_id.to_owned()))
.input_callback(async move |data, buffer, input| {
{
let (client_rc, room_id) = data.unwrap();
let client_rc = client_rc.upgrade().expect(
"Can't upgrade server, server has been deleted?",
);
let client = client_rc.borrow();
let buffer = buffer
.upgrade()
.expect("Running input cb but buffer is closed");
if client.is_none() {
buffer.print("Error not connected");
return;
}
if let Some(s) = client.as_ref() {
// TODO check for errors and print them out.
s.send_message(&room_id, &input).await;
}
}
})
.close_callback(|weechat, buffer| {
// TODO remove the roombuffer from the server here.
// TODO leave the room if the plugin isn't unloading.
Ok(())
});
let buffer_handle = Weechat::buffer_new(buffer_settings)
.expect("Can't create new room buffer");
let buffer = buffer_handle
.upgrade()
.expect("Can't upgrade newly created buffer");
buffer.enable_nicklist();
RoomBuffer {
server_name: server_name.to_owned(),
homeserver: homeserver.clone(),
room_id: room_id.clone(),
buffer_handle,
prev_batch: None,
typing_notice_time: None,
room: Room::new(&room_id, &own_user_id.to_string()),
printed_before_ack_queue: Vec::new(),
}
}
pub fn weechat_buffer(&mut self) -> Buffer {
self.buffer_handle
.upgrade()
.expect("Buffer got closed but Room is still lingering around")
}
pub fn handle_membership_event(
&mut self,
event: &MemberEvent,
print_message: bool,
) {
let mut buffer = self.weechat_buffer();
let content = &event.content;
match content.membership {
MembershipState::Join => {
let settings = NickSettings::new(&event.state_key);
let _ = buffer.add_nick(settings);
}
MembershipState::Leave => {
buffer.remove_nick(&event.state_key);
}
MembershipState::Ban => {
buffer.remove_nick(&event.state_key);
}
_ => (),
}
// The state event should not be printed out, return early here.
if !print_message {
return;
}
let message = match content.membership {
MembershipState::Join => "joined",
MembershipState::Leave => "left",
_ => return,
};
let message = format!(
"{} ({}) has {} the room",
content.displayname.as_ref().unwrap_or(&"".to_string()),
event.state_key,
message
);
let timestamp: u64 = event.origin_server_ts.into();
let timestamp = timestamp / 1000;
buffer.print_date_tags(timestamp as i64, &[], &message);
self.room.handle_membership(&event);
}
pub fn handle_text_message(
&mut self,
sender: &str,
timestamp: u64,
content: &TextMessageEventContent,
) {
let buffer = self.weechat_buffer();
let timestamp = timestamp / 1000;
let message = format!("{}\t{}", sender, content.body);
buffer.print_date_tags(timestamp as i64, &[], &message);
}
pub fn handle_room_message(&mut self, event: &MessageEvent) {
let sender = &event.sender;
let timestamp: u64 = event.origin_server_ts.into();
match &event.content {
MessageEventContent::Text(t) => {
self.handle_text_message(&sender.to_string(), timestamp, t)
}
_ => (),
}
}
pub fn handle_encrypted_message(&mut self, event: &EncryptedEvent) {
let buffer = self.weechat_buffer();
let sender = &event.sender;
let timestamp: u64 = event.origin_server_ts.into();
let timestamp = timestamp / 1000;
let message = format!("{}\t{}", sender, "Unable to decrypt message");
buffer.print_date_tags(timestamp as i64, &[], &message);
}
pub fn handle_room_event(&mut self, event: RoomEvent) {
match &event {
RoomEvent::RoomMember(e) => self.handle_membership_event(e, true),
RoomEvent::RoomMessage(m) => self.handle_room_message(m),
RoomEvent::RoomEncrypted(m) => self.handle_encrypted_message(m),
event => {
self.room.receive_timeline_event(event);
}
}
}
pub fn handle_state_event(&mut self, event: StateEvent) {
match &event {
StateEvent::RoomMember(e) => self.handle_membership_event(e, false),
_ => (),
}
self.room.receive_state_event(&event);
}
}
<file_sep>//! Configuration module
//!
//! This is the global plugin configuration.
//!
//! Configuration options should be split out into different sections:
//!
//! * network
//! * look
//! * color
//! * server
//!
//! The server config options are added in the server.rs file.
//!
//! The config options created here will be alive as long as the plugin is
//! loaded so they don't need to be freed manually. The drop implementation of
//! the section will do so.
use crate::{MatrixServer, Servers};
use weechat::config::{
Conf, ConfigSection, ConfigSectionSettings, OptionChanged,
};
use weechat::Weechat;
use std::cell::{Ref, RefCell, RefMut};
use std::rc::{Rc, Weak};
#[derive(Clone)]
pub struct Config(Rc<RefCell<weechat::config::Config>>);
#[derive(Clone, Default)]
pub struct ConfigHandle(Weak<RefCell<weechat::config::Config>>);
impl ConfigHandle {
pub fn upgrade(&self) -> Config {
Config(
self.0
.upgrade()
.expect("Config got deleted before plugin unload"),
)
}
}
fn server_write_cb(
_weechat: &Weechat,
config: &Conf,
section: &mut ConfigSection,
) {
config.write_section(section.name());
for option in section.options() {
config.write_option(option);
}
}
impl Config {
pub fn new(weechat: &Weechat, servers: &Servers) -> Config {
let config = Weechat::config_new("matrix-rust")
.expect("Can't create new config");
let servers = servers.clone_weak();
let config = Config(Rc::new(RefCell::new(config)));
let weak_config = config.clone_weak();
let server_section_options = ConfigSectionSettings::new("server")
.set_write_callback(server_write_cb)
.set_read_callback(
move |_, _config, section, option_name, value| {
let config = weak_config.clone();
let servers = servers.clone();
if option_name.is_empty() {
return OptionChanged::Error;
}
let option_args: Vec<&str> =
option_name.splitn(2, '.').collect();
if option_args.len() != 2 {
return OptionChanged::Error;
}
let server_name = option_args[0];
{
let servers = servers.upgrade();
let mut servers_borrow = servers.borrow_mut();
// We are reading the config, if the server doesn't yet exists
// we need to create it before setting the option and running
// the option change callback.
if !servers_borrow.contains_key(server_name) {
let config = config.upgrade();
let server = MatrixServer::new(
server_name,
&config,
section,
);
servers_borrow
.insert(server_name.to_owned(), server);
}
}
let option = section.search_option(option_name);
if let Some(o) = option {
o.set(value, true)
} else {
OptionChanged::NotFound
}
},
);
{
let mut config_borrow = config.borrow_mut();
config_borrow
.new_section(server_section_options)
.expect("Can't create server section");
}
config
}
pub fn borrow(&self) -> Ref<'_, weechat::config::Config> {
self.0.borrow()
}
pub fn borrow_mut(&self) -> RefMut<'_, weechat::config::Config> {
self.0.borrow_mut()
}
pub fn clone_weak(&self) -> ConfigHandle {
ConfigHandle(Rc::downgrade(&self.0))
}
}
|
4a94e0b0a8e67a44df8301d96436ea07e12995ac
|
[
"Rust"
] | 2 |
Rust
|
goulov/weechat-matrix-rs
|
4baa1e6134da3f965350e3f980056c038dfce04b
|
bd717aa5feaeed9f8bf1a6d8e1365e2ba70ae24d
|
refs/heads/main
|
<file_sep>"""
This file contains example output as displayed by running
'numerical_examples_code.py' with gpu_installed = True
and complete_version = True.
"""
# Table: Simulation CPU times
# \begin{tabular}{lrrrrr}
# \hline
# & exact & ea & ma & gwa & gpu \\
# \hline
# Compute time (secs) & 73.7610 & 3.8110 & 7.1890 & 13.7780 & 0.1090 \\
# \hline
# \end{tabular}
# C:\Users\brend\anaconda3\envs\test7\lib\site-packages\birdepy\probability_gwasa.py:338: RuntimeWarning: Probability not in [0, 1] computed, some output has been replaced by a default value. Results may be unreliable.
# warnings.warn("Probability not in [0, 1] computed, "
# Table: Small population Verhulst CPU times
# \begin{tabular}{lrrrrrrrrr}
# \hline
# & sim & expm & uniform & Erlang & ilt & da & oua & gwa & gwasa \\
# \hline
# Compute time (secs) & 0.5840 & 0.0070 & 0.7700 & 0.0030 & 2.0500 & 0.0050 & 0.0040 & 0.0250 & 0.0030 \\
# \hline
# \end{tabular}
# Basic ABC estimate is [0.7468397861173611], with standard error [0.1033682469591971]computed in 74.70699763298035 seconds.
# Dynamic ABC estimate is [0.7620827322497084], with standard error [0.05331307382209087]computed in 1853.4449698925018 seconds.
# C:\Users\brend\anaconda3\envs\test7\lib\site-packages\scipy\optimize\optimize.py:282: RuntimeWarning: Values in x were outside bounds during a minimize step, clipping to bounds
# warnings.warn("Values in x were outside bounds during a "
# C:\Users\brend\anaconda3\envs\test7\lib\site-packages\birdepy\interface_estimate.py:530: RuntimeWarning: invalid value encountered in sqrt
# se = list(np.sqrt(np.diag(cov)))
# Table: DNM Estimates
# \begin{tabular}{lrrr}
# \hline
# & gamma & nu & alpha \\
# \hline
# da & 0.7817 & 0.3906 & 0.0252 \\
# Erlang & 0.7824 & 0.3873 & 0.0250 \\
# expm & 0.7810 & 0.3867 & 0.0250 \\
# gwa & 0.4111 & 0.3414 & 0.0076 \\
# gwasa & 0.4198 & 0.3494 & 0.0075 \\
# ilt & 0.7782 & 0.3852 & 0.0251 \\
# oua & 0.6528 & 0.3716 & 0.0229 \\
# uniform & 0.7811 & 0.3867 & 0.0250 \\
# \hline
# \end{tabular}
# Table: DNM Standard Errors
# \begin{tabular}{lrrr}
# \hline
# & gamma & nu & alpha \\
# \hline
# da & 0.0612 & 0.0292 & 0.0013 \\
# Erlang & 0.0653 & 0.0294 & 0.0013 \\
# expm & 0.0650 & 0.0292 & 0.0013 \\
# gwa & 0.0432 & 0.0228 & 0.0041 \\
# gwasa & 0.0438 & 0.0239 & 0.0040 \\
# ilt & 0.0047 & 0.0052 & nan \\
# oua & 0.0570 & 0.0298 & 0.0016 \\
# uniform & 0.0650 & 0.0292 & 0.0013 \\
# \hline
# \end{tabular}
# Table: DNM Compute Times
# \begin{tabular}{lr}
# \hline
# Method & Compute time (secs) \\
# \hline
# da & 89.8750 \\
# Erlang & 0.8610 \\
# expm & 1.0960 \\
# gwa & 88.9520 \\
# gwasa & 7.3920 \\
# ilt & 4738.9250 \\
# oua & 15.7860 \\
# uniform & 2.8480 \\
# \hline
# \end{tabular}
# Table: EM Estimates
# \begin{tabular}{llrrr}
# \hline
# & & gamma & nu & alpha \\
# \hline
# expm & cg & 0.7796 & 0.3865 & 0.0250 \\
# expm & none & 0.8175 & 0.4079 & 0.0248 \\
# expm & Lange & 0.8031 & 0.4039 & 0.0246 \\
# expm & qn1 & 0.7810 & 0.3867 & 0.0250 \\
# expm & qn2 & 0.7526 & 0.4068 & 0.0231 \\
# ilt & cg & 0.7815 & 0.3862 & 0.0250 \\
# ilt & none & 0.8171 & 0.4078 & 0.0248 \\
# ilt & Lange & 0.8060 & 0.4025 & 0.0248 \\
# ilt & qn1 & 0.7802 & 0.3864 & 0.0250 \\
# ilt & qn2 & 0.7535 & 0.4073 & 0.0238 \\
# num & cg & 0.8626 & 0.4296 & 0.0249 \\
# num & none & 0.6153 & 0.4414 & 0.0172 \\
# num & Lange & 0.7859 & 0.3895 & 0.0250 \\
# num & qn1 & 0.5046 & 0.5039 & 0.0161 \\
# num & qn2 & 0.6609 & 0.4275 & 0.0184 \\
# \hline
# \end{tabular}
# Table: EM Standard Errors
# \begin{tabular}{llrrr}
# \hline
# & & gamma & nu & alpha \\
# \hline
# expm & cg & 0.0649 & 0.0292 & 0.0013 \\
# expm & none & 0.0712 & 0.0325 & 0.0013 \\
# expm & Lange & 0.0700 & 0.0318 & 0.0013 \\
# expm & qn1 & 0.0650 & 0.0292 & 0.0013 \\
# expm & qn2 & 0.0655 & 0.0322 & 0.0015 \\
# ilt & cg & 0.0649 & 0.0289 & 0.0012 \\
# ilt & none & 0.0139 & 0.0138 & 0.0012 \\
# ilt & Lange & 0.0378 & 0.0305 & nan \\
# ilt & qn1 & 0.0649 & 0.0290 & 0.0013 \\
# ilt & qn2 & 0.0592 & 0.0326 & 0.0013 \\
# num & cg & 0.0778 & 0.0363 & 0.0012 \\
# num & none & 0.0490 & 0.0423 & 0.0018 \\
# num & Lange & 0.0656 & 0.0296 & 0.0013 \\
# num & qn1 & nan & nan & nan \\
# num & qn2 & 0.0625 & 0.0352 & 0.0020 \\
# \hline
# \end{tabular}
# Table: EM Compute Times
# \begin{tabular}{llr}
# \hline
# & Method & Compute time (secs) \\
# \hline
# expm & cg & 4.6590 \\
# expm & none & 4.3630 \\
# expm & Lange & 4.4360 \\
# expm & qn1 & 11.0230 \\
# expm & qn2 & 3.5980 \\
# ilt & cg & 9409.6620 \\
# ilt & none & 8338.6820 \\
# ilt & Lange & 9518.8610 \\
# ilt & qn1 & 19994.9424 \\
# ilt & qn2 & 6198.4972 \\
# num & cg & 12.3250 \\
# num & none & 87.9390 \\
# num & Lange & 27.1730 \\
# num & qn1 & 46.6500 \\
# num & qn2 & 9.8320 \\
# \hline
# \end{tabular}
# Table: LSE Estimates
# \begin{tabular}{lrrr}
# \hline
# & gamma & nu & alpha \\
# \hline
# expm & 0.7078 & 0.2988 & 0.0288 \\
# fm & 0.7109 & 0.2955 & 0.0279 \\
# gwa & 0.6792 & 0.3278 & 0.0244 \\
# \hline
# \end{tabular}
# Table: LSE Standard Errors
# \begin{tabular}{lrrr}
# \hline
# & gamma & nu & alpha \\
# \hline
# expm & 0.0383 & 0.0241 & 0.0021 \\
# fm & 0.0367 & 0.0257 & 0.0025 \\
# gwa & 0.0480 & 0.0354 & 0.0024 \\
# \hline
# \end{tabular}
# Table: LSE Compute Times
# \begin{tabular}{lr}
# \hline
# Method & Compute time (secs) \\
# \hline
# expm & 21.4170 \\
# fm & 484.6330 \\
# gwa & 15.9930 \\
# \hline
# \end{tabular}
# Overall script compute time: 61270.87859225273
<file_sep>"""
This file contains the code used in the numerical examples in Section 6
of the paper. The accompanying file 'numerical_examples_output.py'
contains the output from running this script.
"""
# Indicate whether a Nvidia graphics card is available and
# the cudatoolkit package installed:
gpu_installed = True
# Indicate whether to execute all of the code, otherwise parts
# of the code that take an excessive amount of time to execute
# will be skipped:
complete_version = True
import birdepy as bd
if gpu_installed:
import birdepy.gpu_functions as bdg
import numpy as np
import matplotlib.pyplot as plt
import time
from tabulate import tabulate
import seaborn as sns
import tikzplotlib
# Begin a timer to see how long the entire script takes to run
overall_tic = time.time()
### SIMULATION EXPERIMENT ###
gamma = 0.75
nu = 0.25
alpha = 0.01
c = 1
param=[gamma, nu, alpha, c]
times = np.arange(0,101,1)
model = 'Hassell'
z0 = 10
K = 10**3
p_data_exact = bd.simulate.discrete(param, model, z0, times, k=K, seed=2021)
p_data_ea = bd.simulate.discrete(param, model, z0, times, k=K, method='ea', seed=2021)
p_data_ma = bd.simulate.discrete(param, model, z0, times, k=K, method='ma', seed=2021)
p_data_gwa = bd.simulate.discrete(param, model, z0, times, k=K, method='gwa', seed=2021)
if gpu_installed:
p_data_gpu = bdg.discrete(param, model, z0, times[-1], k=K, seed=2021)
fig, axs = plt.subplots(1,1, figsize=(5,3))
axs.plot(times, p_data_exact[0:3, :].T, color='tab:blue')
axs.plot(times, np.mean(p_data_exact, axis=0), color='k')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
axs.set_title('exact')
tikzplotlib.save("exact_sim.tex")
fig, axs = plt.subplots(1,1, figsize=(5,3))
axs.plot(times, p_data_ea[0:3, :].T, color='tab:red')
axs.plot(times, np.mean(p_data_ea, axis=0), color='k')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
axs.set_title('ea')
tikzplotlib.save("ea_sim.tex")
fig, axs = plt.subplots(1,1, figsize=(5,3))
axs.plot(times, p_data_ma[0:3, :].T, color='tab:green')
axs.plot(times, np.mean(p_data_ma, axis=0), color='k')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
axs.set_title('ma')
tikzplotlib.save("ma_sim.tex")
fig, axs = plt.subplots(1,1, figsize=(5,3))
axs.plot(times, p_data_gwa[0:3, :].T, color='tab:cyan')
axs.plot(times, np.mean(p_data_gwa, axis=0), color='k')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
axs.set_title('gwa')
tikzplotlib.save("gwa_sim.tex")
times = [0, times[-1]]
tic = time.time()
p_data_exact = bd.simulate.discrete(param, model, z0, times, k=K, seed=2021)
toc_exact = time.time()-tic
tic = time.time()
p_data_ea = bd.simulate.discrete(param, model, z0, times, k=K, method='ea', seed=2021)
toc_ea = time.time()-tic
tic = time.time()
p_data_ma = bd.simulate.discrete(param, model, z0, times, k=K, method='ma', seed=2021)
toc_ma = time.time()-tic
tic = time.time()
p_data_gwa = bd.simulate.discrete(param, model, z0, times, k=K, method='gwa', seed=2021)
toc_gwa = time.time()-tic
if gpu_installed:
tic = time.time()
p_data_gpu = bdg.discrete(param, model, z0, times[-1], k=K, seed=2021)
toc_gpu = time.time()-tic
fig, ax = plt.subplots(figsize=(5,2))
sns.kdeplot(p_data_exact[:, -1], color='tab:blue', label='exact')
sns.kdeplot(p_data_ea[:, -1], color='tab:red', label='ea', linestyle=(0, (3, 5, 1, 5, 1, 5)))
sns.kdeplot(p_data_ma[:, -1], color='tab:green', label='ma', linestyle='-.')
sns.kdeplot(p_data_gwa[:, -1], color='tab:cyan', label='gwa',linestyle=':')
if gpu_installed:
sns.kdeplot(p_data_gpu, color='tab:purple', label='gpu', linestyle=(0, (5,1)))
plt.legend(loc='upper right')
plt.xlim([125, 275])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
tikzplotlib.save("sim_kdes.tex")
print("Table: Simulation CPU times")
if gpu_installed:
print(tabulate([["exact", "ea", "ma", "gwa", "gpu"],
["Compute time (secs)", toc_exact, toc_ea, toc_ma, toc_gwa, toc_gpu]],
headers="firstrow", floatfmt=".4f", tablefmt='latex'))
else:
print(tabulate([["exact", "ea", "ma", "gwa"],
["Compute time (secs)", toc_exact, toc_ea, toc_ma, toc_gwa]],
headers="firstrow", floatfmt=".4f", tablefmt='latex'))
### CONTINUOUS SIMULATION EXPERIMENT ###
gamma = 0.5
nu = 0.45
times = np.arange(0,3,0.1)
dsc_sample_path = bd.simulate.discrete([gamma, nu], 'linear', 10, times, seed=2021)
cts_times, cts_sample_path = bd.simulate.continuous([gamma, nu], 'linear', 10, 3, seed=2021)
fig, ax = plt.subplots(1,1, sharex=True, sharey=True, figsize=(10,2.5))
fig.suptitle("Linear simulated sample paths")
ax.plot(times, dsc_sample_path, '+', label='discrete')
ax.step(cts_times, cts_sample_path, label='continuous', where='post')
ax.legend(loc='upper left')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
tikzplotlib.save("cts_dsc_sim.tex")
### VERHULST MODEL PROBABILITY EXPERIMENT 1 ###
alpha = 0.025
beta = 0
gamma = 0.8
nu = 0.4
param = [gamma, nu, alpha, beta]
t = 1
zz = np.arange(0, 40, 1)
model = 'Verhulst'
z0 = 15
fig.suptitle("Small population Verhulst density approximations")
tic = time.time()
if gpu_installed:
pp_sim = bdg.probability(z0, zz, t, param, model=model, k=10**6, seed=2021)
else:
pp_sim = bd.probability(z0, zz, [t], param, model=model, method='sim', k=10**4, seed=2021)
toc_sim = time.time() - tic
tic = time.time()
pp_expm = bd.probability(z0, zz, t, param, model=model, method='expm')
toc_expm = time.time() - tic
fig, axs = plt.subplots(figsize=(5,2))
axs.plot(zz, pp_sim[0], 'tab:gray',alpha=0.5)
axs.plot(zz, pp_expm[0], '+')
axs.plot(zz, np.where((pp_expm[0]>=0)*(pp_expm[0]<=1), 1, 0.01), 'rx')
axs.set_ylim([0,0.15])
axs.set_title('expm')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
tikzplotlib.save("prob_expm.tex")
tic = time.time()
pp_uni = bd.probability(z0, zz, t, param, model=model, method='uniform', k=10**4)
toc_uni = time.time() - tic
fig, axs = plt.subplots(figsize=(5,2))
axs.plot(zz, pp_sim[0], 'tab:gray',alpha=0.5)
axs.plot(zz, pp_uni[0], '+')
axs.plot(zz, np.where((pp_uni[0]>=0)*(pp_uni[0]<=1), 1, 0.01), 'rx')
axs.set_ylim([0,0.15])
axs.set_title('uniform')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
tikzplotlib.save("prob_uniform.tex")
tic = time.time()
pp_erl = bd.probability(z0, zz, t, param, model=model, method='Erlang', k=10**3)
toc_erl = time.time() - tic
fig, axs = plt.subplots(figsize=(5,2))
axs.plot(zz, pp_sim[0], 'tab:gray',alpha=0.5)
axs.plot(zz, pp_erl[0], '+')
axs.plot(zz, np.where((pp_erl[0]>=0)*(pp_erl[0]<=1), 1, 0.01), 'rx')
axs.set_ylim([0,0.15])
axs.set_title('Erlang')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
tikzplotlib.save("prob_erlang.tex")
tic = time.time()
pp_ilt = bd.probability(z0, zz, t, param, model=model, method='ilt')
toc_ilt = time.time() - tic
fig, axs = plt.subplots(figsize=(5,2))
axs.plot(zz, pp_sim[0], 'tab:gray',alpha=0.5)
axs.plot(zz, pp_ilt[0], '+')
axs.plot(zz, np.where((pp_ilt[0]>=0)*(pp_ilt[0]<=1), 1, 0.01), 'rx')
axs.set_ylim([0,0.15])
axs.set_title('ilt')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
tikzplotlib.save("prob_ilt.tex")
tic = time.time()
pp_da = bd.probability(z0, zz, t, param, model=model, method='da')
toc_da = time.time() - tic
fig, axs = plt.subplots(figsize=(5,2))
axs.plot(zz, pp_sim[0], 'tab:gray',alpha=0.5)
axs.plot(zz, pp_da[0], '+')
axs.plot(zz, np.where((pp_da[0]>=0)*(pp_da[0]<=1), 1, 0.01), 'rx')
axs.set_ylim([0,0.15])
axs.set_title('da')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
tikzplotlib.save("prob_da.tex")
tic = time.time()
pp_oua = bd.probability(z0, zz, t, param, model=model, method='oua')
toc_oua = time.time() - tic
fig, axs = plt.subplots(figsize=(5,2))
axs.plot(zz, pp_sim[0], 'tab:gray',alpha=0.5)
axs.plot(zz, pp_oua[0], '+')
axs.plot(zz, np.where((pp_oua[0]>=0)*(pp_oua[0]<=1), 1, 0.01), 'rx')
axs.set_ylim([0,0.15])
axs.set_title('oua')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
tikzplotlib.save("prob_oua.tex")
tic = time.time()
pp_gwa = bd.probability(z0, zz, t, param, model=model, method='gwa')
toc_gwa = time.time() - tic
fig, axs = plt.subplots(figsize=(5,2))
axs.plot(zz, pp_sim[0], 'tab:gray',alpha=0.5)
axs.plot(zz, pp_gwa[0], '+')
axs.plot(zz, np.where((pp_gwa[0]>=0)*(pp_gwa[0]<=1), 1, 0.01), 'rx')
axs.set_ylim([0,0.15])
axs.set_title('gwa')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
tikzplotlib.save("prob_gwa.tex")
tic = time.time()
pp_gwasa = bd.probability(z0, zz, t, param, model=model, method='gwasa')
toc_gwasa = time.time() - tic
fig, axs = plt.subplots(figsize=(5,2))
axs.plot(zz, pp_sim[0], 'tab:gray',alpha=0.5)
axs.plot(zz, pp_gwasa[0], '+')
axs.plot(zz, np.where((pp_gwasa[0]>=0)*(pp_gwasa[0]<=1), 1, 0.14), 'rx')
axs.set_ylim([0,0.15])
axs.set_title('gwasa')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
tikzplotlib.save("prob_gwasa.tex")
print("Table: Small population Verhulst CPU times")
print(tabulate([["sim", "expm", "uniform", "Erlang", "ilt", "da", "oua", "gwa", "gwasa"],
["Compute time (secs)", toc_sim, toc_expm, toc_uni, toc_erl, toc_ilt, toc_da, toc_oua, toc_gwa, toc_gwasa]],
headers="firstrow", floatfmt=".4f", tablefmt='latex'))
### ESTIMATION EXPERIMENT 1 SETUP ###
gamma = 0.8
nu = 0.4
alpha = 0.025
beta = 0
param = [gamma, nu, alpha, beta]
num_sample_paths = 5
obs_times = list(range(100))
p_data = bd.simulate.discrete(param, 'Verhulst', 5, obs_times, seed=2021, k=num_sample_paths)
t_data = [obs_times for _ in range(num_sample_paths)]
con = {'type': 'ineq', 'fun': lambda p: p[0]-p[1]}
alpha_max = 1/np.amax(np.array(p_data))
alpha_mid = 0.5*alpha_max
### ABC ESTIMATION EXPERIMENT ###
est = bd.estimate(t_data, p_data, [0.5], [[0,1]], framework='abc', model='Verhulst',
known_p=[nu, alpha, beta], idx_known_p=[1, 2, 3], max_its=1,
seed=2021)
print(f'Basic ABC estimate is {est.p}, with standard error {est.se}'
f'computed in {est.compute_time} seconds.')
if complete_version:
est = bd.estimate(t_data, p_data, [0.5], [[0,1]], framework='abc', model='Verhulst',
known_p=[nu, alpha, beta], idx_known_p=[1, 2, 3],
seed=2021)
print(f'Dynamic ABC estimate is {est.p}, with standard error {est.se}'
f'computed in {est.compute_time} seconds.')
# ### DNM ESTIMATION EXPERIMENT ###
dnm_estimates = []
dnm_se = []
dnm_times = []
dnm_estimates.append(['gamma', 'nu', 'alpha'])
dnm_se.append(['gamma', 'nu', 'alpha'])
dnm_times.append(["Method", "Compute time (secs)"])
if complete_version:
for likelihood in ['da', 'Erlang', 'expm', 'gwa', 'gwasa', 'ilt', 'oua', 'uniform']:
tic = time.time()
est = bd.estimate(t_data, p_data, [0.51, 0.5, alpha_mid], [[1e-6,5], [1e-6,5], [1e-6, alpha_max]],
model='Verhulst', framework='dnm', known_p=[0], idx_known_p=[3],
con=con, likelihood=likelihood, opt_method='differential-evolution')
toc = time.time()-tic
(est.p).insert(0, likelihood)
(est.se).insert(0, likelihood)
dnm_estimates.append(est.p)
dnm_se.append(est.se)
dnm_times.append([likelihood, toc])
else:
for likelihood in ['da', 'Erlang', 'expm', 'gwa', 'gwasa', 'oua', 'uniform']:
tic = time.time()
est = bd.estimate(t_data, p_data, [0.51, 0.5, alpha_mid], [[1e-6,5], [1e-6,5], [1e-6, alpha_max]],
model='Verhulst', framework='dnm', known_p=[0], idx_known_p=[3],
con=con, likelihood=likelihood, opt_method='differential-evolution')
toc = time.time()-tic
(est.p).insert(0, likelihood)
(est.se).insert(0, likelihood)
dnm_estimates.append(est.p)
dnm_se.append(est.se)
dnm_times.append([likelihood, toc])
print("Table: DNM Estimates")
print(tabulate(dnm_estimates, headers="firstrow", floatfmt=".4f", tablefmt='latex'))
print("Table: DNM Standard Errors")
print(tabulate(dnm_se, headers="firstrow", floatfmt=".4f", tablefmt='latex'))
print("Table: DNM Compute Times")
print(tabulate(dnm_times, headers="firstrow", floatfmt=".4f", tablefmt='latex'))
### EM ESTIMATION EXPERIMENT ###
em_estimates = []
em_se = []
em_times = []
em_estimates.append(['gamma', 'nu', 'alpha'])
em_se.append(['gamma', 'nu', 'alpha'])
em_times.append(["Method", "Compute time (secs)"])
if complete_version:
for technique in ['expm', 'ilt', 'num']:
for accelerator in ['cg', 'none', 'Lange', 'qn1', 'qn2']:
tic = time.time()
est = bd.estimate(t_data, p_data, [0.51, 0.5, alpha_mid], [[1e-6,5], [1e-6,5], [1e-6, alpha_max]],
framework='em', technique=technique, accelerator=accelerator,
model='Verhulst', known_p=[0], idx_known_p=[3], con=con, display=False)
toc = time.time() - tic
(est.p).insert(0, accelerator)
(est.p).insert(0, technique)
(est.se).insert(0, accelerator)
(est.se).insert(0, technique)
em_estimates.append(est.p)
em_se.append(est.se)
em_times.append([technique, accelerator, toc])
else:
for technique in ['expm', 'num']:
for accelerator in ['cg', 'none', 'Lange', 'qn1', 'qn2']:
tic = time.time()
est = bd.estimate(t_data, p_data, [0.51, 0.5, alpha_mid], [[1e-6,5], [1e-6,5], [1e-6, alpha_max]],
framework='em', technique=technique, accelerator=accelerator,
model='Verhulst', known_p=[0], idx_known_p=[3], con=con, display=False)
toc = time.time() - tic
(est.p).insert(0, accelerator)
(est.p).insert(0, technique)
(est.se).insert(0, accelerator)
(est.se).insert(0, technique)
em_estimates.append(est.p)
em_se.append(est.se)
em_times.append([technique, accelerator, toc])
print("Table: EM Estimates")
print(tabulate(em_estimates, headers="firstrow", floatfmt=".4f", tablefmt='latex'))
print("Table: EM Standard Errors")
print(tabulate(em_se, headers="firstrow", floatfmt=".4f", tablefmt='latex'))
print("Table: EM Compute Times")
print(tabulate(em_times, headers="firstrow", floatfmt=".4f", tablefmt='latex'))
### LSE ESTIMATION EXPERIMENT ###
lse_estimates = []
lse_se = []
lse_times = []
lse_estimates.append(['gamma', 'nu', 'alpha'])
lse_se.append(['gamma', 'nu', 'alpha'])
lse_times.append(["Method", "Compute time (secs)"])
if complete_version:
for squares in ['expm', 'fm', 'gwa']:
tic = time.time()
est = bd.estimate(t_data, p_data, [0.51, 0.5, alpha_mid], [[1e-6,1], [1e-6,1], [1e-6, alpha_max]],
framework='lse', model='Verhulst', idx_known_p=[3], known_p=[0], con=con,
squares=squares, se_type='simulated')
toc = time.time() - tic
(est.p).insert(0, squares)
(est.se).insert(0, squares)
lse_estimates.append(est.p)
lse_se.append(est.se)
lse_times.append([squares, toc])
else:
for squares in ['expm', 'gwa']:
tic = time.time()
est = bd.estimate(t_data, p_data, [0.51, 0.5, alpha_mid], [[1e-6,1], [1e-6,1], [1e-6, alpha_max]],
framework='lse', model='Verhulst', idx_known_p=[3], known_p=[0], con=con,
squares=squares, se_type='simulated')
toc = time.time() - tic
(est.p).insert(0, squares)
(est.se).insert(0, squares)
lse_estimates.append(est.p)
lse_se.append(est.se)
lse_times.append([squares, toc])
print("Table: LSE Estimates")
print(tabulate(lse_estimates, headers="firstrow", floatfmt=".4f", tablefmt='latex'))
print("Table: LSE Standard Errors")
print(tabulate(lse_se, headers="firstrow", floatfmt=".4f", tablefmt='latex'))
print("Table: LSE Compute Times")
print(tabulate(lse_times, headers="firstrow", floatfmt=".4f", tablefmt='latex'))
overall_time = time.time() - overall_tic
print('Overall script compute time:', overall_time)
<file_sep># birdepy_examples
Contains scripts for obtaining the numerical results in our BirDePy paper.
For more information on BirDePy visit https://birdepy.github.io/
<file_sep>"""
This file contains the code used in the black robin and whooping crane case
studies in Section 5 of the paper. The accompanying file
'case_studies_output.py' contains the output from running this script.
"""
import birdepy as bd
import numpy as np
from tabulate import tabulate
import matplotlib.pyplot as plt
import tikzplotlib
### BLACK ROBIN DATASET 1 CASE STUDY ###
t_data_b = [1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 2010,
2011, 2012, 2013, 2014, 2015]
p_data_b = [30, 37, 35, 35, 42, 39, 50, 50, 57, 61, 86, 98, 94, 108, 117, 118]
###############
est_v1 = bd.estimate(t_data_b, p_data_b, [2, 2, 0.05], [[0,10], [0,10], [0, 1]],
model='Verhulst', known_p=[0], idx_known_p=[3],
opt_method='differential-evolution', seed=2021)
(est_v1.p).insert(0, 'Verhulst 1')
(est_v1.se).insert(0, 'Verhulst 1')
extra_v1 = ['Verhulst 1', est_v1.capacity[1], np.exp(est_v1.val)]
###############
est_v2 = bd.estimate(t_data_b, p_data_b, [2, 2, 0.05], [[0,10], [0,10], [0, 1]],
model='Verhulst', known_p=[0], idx_known_p=[2], se_type='asymptotic',
opt_method='differential-evolution', seed=2021)
(est_v2.p).insert(0, 'Verhulst 2')
(est_v2.se).insert(0, 'Verhulst 2')
extra_v2 = ['Verhulst 2', est_v2.capacity[1], np.exp(est_v2.val)]
###############
est_r = bd.estimate(t_data_b, p_data_b, [2, 2, 0.05], [[0,10], [0,10], [0,1]],
model='Ricker', known_p=[1], idx_known_p=[3], se_type='asymptotic',
opt_method='differential-evolution', seed=2021)
(est_r.p).insert(0, 'Ricker')
(est_r.se).insert(0, 'Ricker')
extra_r = ['Ricker', est_r.capacity[1], np.exp(est_r.val)]
###############
est_b = bd.estimate(t_data_b, p_data_b, [2, 2, 2], [[0,10], [0,10], [0,1]],
model='Hassell', known_p=[1], idx_known_p=[3],
se_type='asymptotic', opt_method='differential-evolution',
seed=2021)
(est_b.p).insert(0, 'Beverton-Holt')
(est_b.se).insert(0, 'Beverton-Holt')
extra_b = ['Beverton-Holt', est_b.capacity[1], np.exp(est_b.val)]
###############
est_h = bd.estimate(t_data_b, p_data_b, [2, 2, 2], [[0,10], [0,10], [0, 1]],
model='Hassell', known_p=[2], idx_known_p=[3],
se_type='asymptotic', opt_method='differential-evolution',
seed=2021)
(est_h.p).insert(0, 'Hassell')
(est_h.se).insert(0, 'Hassell')
extra_h = ['Hassell', est_h.capacity[1], np.exp(est_h.val)]
###############
est_mss = bd.estimate(t_data_b, p_data_b, [2, 2, 2], [[0,10], [0,10], [0, 1]],
model='MS-S', known_p=[2], idx_known_p=[3],
se_type='asymptotic', opt_method='differential-evolution',
seed=2021)
(est_mss.p).insert(0, 'MS-S')
(est_mss.se).insert(0, 'MS-S')
extra_mss = ['MS-S', est_mss.capacity[1], np.exp(est_mss.val)]
###############
est_l = bd.estimate(t_data_b, p_data_b, [2]*2, [[0,10]]*2, model='linear',
se_type='asymptotic', opt_method='differential-evolution',
seed=2021)
(est_l.p).insert(0, 'linear')
(est_l.se).insert(0, 'linear')
extra_l = ['linear', 'n/a', np.exp(est_l.val)]
###############
###############
###############
print("\n Table: BLACK ROBIN DATASET PARAMETER ESTIMATES")
print(tabulate([["Model", "gamma", "nu", "alpha/beta"],
est_v1.p, est_v2.p, est_r.p, est_b.p, est_h.p, est_mss.p, est_l.p],
headers="firstrow", floatfmt=".4f", tablefmt='latex'))
###############
print("Table: BLACK ROBIN DATASET STANDARD ERRORS")
print(tabulate([["Model", "gamma", "nu", "alpha", "beta/c"],
est_v1.se, est_v2.se, est_r.se, est_b.se, est_h.se, est_mss.se, est_l.se],
headers="firstrow", floatfmt=".4f", tablefmt='latex'))
###############
print("Table: BLACK ROBIN DATASET CARRYING CAPACITY AND LIKELIHOOD")
print(tabulate([["Model", "Capacity", "Likelihood"],
extra_v1, extra_v2, extra_r, extra_b, extra_h, extra_mss, extra_l],
headers="firstrow", tablefmt='latex'))
###############
###############
bd.forecast('Hassell', p_data_b[-1], np.arange(2015, 2051, 1), est_b.p[1:], cov=est_b.cov, p_bounds=[[0,10], [0,10], [0, 1]],
known_p=[1], idx_known_p=[3], export='hassell_robins')
bd.estimate(t_data_b, p_data_b, [0.36, 0.0017], [[0,1], [0, 1]],
model='Hassell', known_p=[0.2373, 1], idx_known_p=[1, 3],
se_type='asymptotic', ci_plot=True, seed=2021, export='hassell_robins_ci_asy',
xlabel='$\gamma$', ylabel='$\\alpha$')
bd.estimate(t_data_b, p_data_b, [0.36, 0.0017], [[0,10], [0, 1]],
model='Hassell', known_p=[0.2373, 1], idx_known_p=[1, 3],
se_type='simulated', ci_plot=True, seed=2021, export='hassell_robins_ci_sim',
xlabel='$\gamma$', ylabel='$\\alpha$')
# ### WHOOPING CRANE DATASET CASE STUDY ###
t_data_w = [t for t in range(1938, 2010, 1)]
p_data_w = [9, 11, 13, 8, 10, 10, 9, 11, 13, 15, 15, 17, 15, 12, 10, 12, 11, 14, 12, 13, 16,
17, 18, 19, 16, 16, 21, 22, 22, 24, 25, 28, 28, 30, 25, 25, 24, 29, 34, 36, 37,
38, 39, 37, 36, 38, 43, 48, 55, 67, 69, 73, 73, 66, 68, 71, 66, 79, 80, 91,
91, 94, 90, 88, 93, 97, 109, 110, 118, 133, 135, 132]
fig, axs = plt.subplots(1,1, figsize=(5,3))
axs.plot(t_data_b, p_data_b, 'k+')
axs.set(xlabel='Year')
axs.set(ylabel='Population')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
axs.set_title('Black Robins')
tikzplotlib.save("robin_data.tex")
fig, axs = plt.subplots(1,1, figsize=(5,3))
axs.plot(t_data_w, p_data_w, 'k+')
axs.set(xlabel='Year')
axs.set(ylabel='Population')
axs.spines['right'].set_visible(False)
axs.spines['top'].set_visible(False)
axs.set_title('Whooping Cranes')
tikzplotlib.save("crane_data.tex")
###############
est_v1 = bd.estimate(t_data_w, p_data_w, [2, 2, 0.05], [[0,10], [0,10], [0, 1]],
model='Verhulst', known_p=[0], idx_known_p=[3], se_type='asymptotic',
opt_method='differential-evolution', seed=2021)
(est_v1.p).insert(0, 'Verhulst 1')
(est_v1.se).insert(0, 'Verhulst 1')
extra_v1 = ['Verhulst 1', est_v1.capacity[1], np.exp(est_v1.val)]
###############
est_v2 = bd.estimate(t_data_w, p_data_w, [2, 2, 0.05], [[0,10], [0,10], [0, 1]],
model='Verhulst', known_p=[0], idx_known_p=[2], se_type='asymptotic',
opt_method='differential-evolution', seed=2021)
(est_v2.p).insert(0, 'Verhulst 2')
(est_v2.se).insert(0, 'Verhulst 2')
extra_v2 = ['Verhulst 2', est_v2.capacity[1], np.exp(est_v2.val)]
###############
est_r = bd.estimate(t_data_w, p_data_w, [2, 2, 0.05], [[0,10], [0,10], [0,1]],
model='Ricker', known_p=[1], idx_known_p=[3], se_type='asymptotic',
opt_method='differential-evolution', seed=2021)
(est_r.p).insert(0, 'Ricker')
(est_r.se).insert(0, 'Ricker')
extra_r = ['Ricker', est_r.capacity[1], np.exp(est_r.val)]
###############
est_b = bd.estimate(t_data_w, p_data_w, [2, 2, 2], [[0,10], [0,10], [0, 1]],
model='Hassell', known_p=[1], idx_known_p=[3],
se_type='asymptotic', opt_method='differential-evolution',
seed=2021)
(est_b.p).insert(0, 'Beverton-Holt')
(est_b.se).insert(0, 'Beverton-Holt')
extra_b = ['Beverton-Holt', est_b.capacity[1], np.exp(est_b.val)]
###############
est_h = bd.estimate(t_data_w, p_data_w, [2, 2, 2], [[0,10], [0,10], [0, 1]],
model='Hassell', known_p=[2], idx_known_p=[3],
se_type='asymptotic', opt_method='differential-evolution',
seed=2021)
(est_h.p).insert(0, 'Hassell')
(est_h.se).insert(0, 'Hassell')
extra_h = ['Hassell', est_h.capacity[1], np.exp(est_h.val)]
###############
est_mss = bd.estimate(t_data_w, p_data_w, [2, 2, 2], [[0,10], [0,10], [0, 1]],
model='MS-S', known_p=[2], idx_known_p=[3],
se_type='asymptotic', opt_method='differential-evolution',
seed=2021)
(est_mss.p).insert(0, 'MS-S')
(est_mss.se).insert(0, 'MS-S')
extra_mss = ['MS-S', est_mss.capacity[1], np.exp(est_mss.val)]
###############
est_l = bd.estimate(t_data_w, p_data_w, [2]*2, [[0,10]]*2, model='linear',
se_type='asymptotic', opt_method='differential-evolution',
seed=2021)
(est_l.p).insert(0, 'linear')
(est_l.se).insert(0, 'linear')
extra_l = ['linear', 'n/a', np.exp(est_l.val)]
###############
est_lm = bd.estimate(t_data_w, p_data_w, [2]*3, [[0,10]]*3, model='linear-migration',
se_type='asymptotic', opt_method='differential-evolution',
seed=2021)
(est_lm.p).insert(0, 'linear-migration')
(est_lm.se).insert(0, 'linear-migration')
extra_lm = ['linear-migration', 'n/a', np.exp(est_lm.val)]
###############
###############
###############
print("\n Table: WHOOPING CRANE PARAMETER ESTIMATES")
print(tabulate([["Model", "gamma", "nu", "alpha/beta"],
est_v1.p, est_v2.p, est_r.p, est_b.p, est_h.p, est_mss.p, est_l.p, est_lm.p],
headers="firstrow", floatfmt=".4f", tablefmt='latex'))
###############
print("Table: WHOOPING CRANE STANDARD ERRORS")
print(tabulate([["Model", "gamma", "nu", "alpha", "beta/c"],
est_v1.se, est_v2.se, est_r.se, est_b.se, est_h.se, est_mss.se, est_l.se, est_lm.se],
headers="firstrow", floatfmt=".4f", tablefmt='latex'))
###############
print("Table: WHOOPING CRANE CARRYING CAPACITY AND LIKELIHOOD")
print(tabulate([["Model", "Capacity", "Likelihood"],
extra_v1, extra_v2, extra_r, extra_b, extra_h, extra_mss, extra_l, extra_lm],
headers="firstrow", tablefmt='latex'))
##############
bd.estimate(t_data_w, p_data_w, [0.1812, 0.1489], [[0,1], [0, 1]],
model='linear-migration', known_p=[0.3157], idx_known_p=[2],
se_type='asymptotic', ci_plot=True, seed=2021, export='lm_cranes_ci_asy',
xlabel='$\gamma$', ylabel='$\\nu$')
bd.estimate(t_data_w, p_data_w, [0.1812, 0.1489], [[0,1], [0, 1]],
model='linear-migration', known_p=[0.3157], idx_known_p=[2],
se_type='simulated', ci_plot=True, seed=2021, export='lm_cranes_ci_sim',
xlabel='$\gamma$', ylabel='$\\nu$')
bd.forecast('linear-migration', p_data_w[-1], np.arange(2009, 2051, 1), est_lm.p[1:],
cov=est_lm.cov, p_bounds=[[0,10]]*3, export="lm_cranes")
bd.forecast('MS-S', p_data_w[-1], np.arange(2009, 2051, 1), est_mss.p[1:],
cov=est_mss.cov, p_bounds=[[0,10]]*3, known_p=[2], idx_known_p=[3], export="mss_cranes")
<file_sep>
# Table: BLACK ROBIN DATASET PARAMETER ESTIMATES
# \begin{tabular}{lrrr}
# \hline
# Model & gamma & nu & alpha/beta \\
# \hline
# Verhulst 1 & 0.3505 & 0.2382 & 0.0023 \\
# Verhulst 2 & 0.3018 & 0.1860 & 0.0046 \\
# Ricker & 0.3587 & 0.2380 & 0.0029 \\
# Beverton-Holt & 0.3690 & 0.2367 & 0.0038 \\
# Hassell & 0.3687 & 0.2418 & 0.0016 \\
# MS-S & 0.3283 & 0.2413 & 0.0045 \\
# linear & 0.2845 & 0.2350 & \\
# \hline
# \end{tabular}
# Table: BLACK ROBIN DATASET STANDARD ERRORS
# \begin{tabular}{lrrr}
# \hline
# Model & gamma & nu & alpha \\
# \hline
# Verhulst 1 & 0.1299 & 0.1000 & 0.0018 \\
# Verhulst 2 & 0.1051 & 0.1036 & 0.0059 \\
# Ricker & 0.1365 & 0.1002 & 0.0027 \\
# Beverton-Holt & 0.1475 & 0.0998 & 0.0045 \\
# Hassell & 0.1446 & 0.1034 & 0.0017 \\
# MS-S & 0.1190 & 0.1019 & 0.0026 \\
# linear & 0.0957 & 0.0956 & \\
# \hline
# \end{tabular}
# Table: BLACK ROBIN DATASET CARRYING CAPACITY AND LIKELIHOOD
# \begin{tabular}{llr}
# \hline
# Model & Capacity & Likelihood \\
# \hline
# Verhulst 1 & 137.68861627644102 & 9.84099e-22 \\
# Verhulst 2 & 134.6832698816235 & 9.5712e-22 \\
# Ricker & 141.18736501019416 & 9.99087e-22 \\
# Beverton-Holt & 145.55564274595758 & 1.01644e-21 \\
# Hassell & 142.30094491528058 & 1.00645e-21 \\
# MS-S & 132.15007378321272 & 9.27018e-22 \\
# linear & n/a & 5.58725e-22 \\
# \hline
# \end{tabular}
# Table: WHOOPING CRANE PARAMETER ESTIMATES
# \begin{tabular}{lrrr}
# \hline
# Model & gamma & nu & alpha/beta \\
# \hline
# Verhulst 1 & 0.1998 & 0.1492 & 0.0008 \\
# Verhulst 2 & 0.1931 & 0.1423 & 0.0011 \\
# Ricker & 0.1999 & 0.1493 & 0.0008 \\
# Beverton-Holt & 0.1999 & 0.1493 & 0.0008 \\
# Hassell & 0.1999 & 0.1493 & 0.0004 \\
# MS-S & 0.1966 & 0.1493 & 0.0025 \\
# linear & 0.1902 & 0.1506 & \\
# linear-migration & 0.1812 & 0.1489 & 0.3157 \\
# \hline
# \end{tabular}
# Table: WHOOPING CRANE STANDARD ERRORS
# \begin{tabular}{lrrr}
# \hline
# Model & gamma & nu & alpha \\
# \hline
# Verhulst 1 & 0.0351 & 0.0293 & 0.0013 \\
# Verhulst 2 & 0.0303 & 0.0321 & 0.0021 \\
# Ricker & 0.0354 & 0.0293 & 0.0015 \\
# Beverton-Holt & 0.0357 & 0.0293 & 0.0016 \\
# Hassell & 0.0356 & 0.0293 & 0.0008 \\
# MS-S & 0.0320 & 0.0293 & 0.0022 \\
# linear & 0.0295 & 0.0293 & \\
# linear-migration & 0.0317 & 0.0294 & 0.4768 \\
# \hline
# \end{tabular}
# Table: WHOOPING CRANE CARRYING CAPACITY AND LIKELIHOOD
# \begin{tabular}{llr}
# \hline
# Model & Capacity & Likelihood \\
# \hline
# Verhulst 1 & 329.93373684069326 & 1.50976e-81 \\
# Verhulst 2 & 324.93396426855503 & 1.52411e-81 \\
# Ricker & 366.79768175130005 & 1.5053e-81 \\
# Beverton-Holt & 410.22714018143967 & 1.50121e-81 \\
# Hassell & 387.63262258205435 & 1.50321e-81 \\
# MS-S & 223.122891645555 & 1.56307e-81 \\
# linear & n/a & 1.29697e-81 \\
# linear-migration & n/a & 1.62844e-81 \\
# \hline
|
f161beabc740cc15643ed931b1ea3fe0f158bfa2
|
[
"Markdown",
"Python"
] | 5 |
Python
|
bpatch/birdepy_examples
|
09736f72574ed802a101b3dd062acd5dc24ada52
|
ee5570e24b84bc45b8d1a32337b8b6312974ec24
|
refs/heads/master
|
<repo_name>vladvventura/MultiPoly<file_sep>/MultiPoly.cpp
//<NAME>-- I didn't put this section in until part 2
//Part 3: Multiply and Power
//Date Last Modified: 12/10/2013
//Class: CS435
//Notes: The fact that I wasn't deleting nodes in insertwAdd when two terms were opposites
//e.g. -10xy +10xy needs to cancel out was fixed.
//
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <algorithm>//used for Step 2, max
using namespace std;
int polyNum;
bool doesRowExist[100]; //I don't think we will have more than a 10th order poly
bool doesColExist[100];//if we do, then I need to make this more dynamic.
struct node
{
node *rowLink;//same row, different columns.
node *colLink;//same column, different rows.
int coefficient;
int row, col;
~node()
{
delete rowLink; delete colLink;
}
};
struct Polynomial
{
node **rowHeader, **colHeader;//array of nodes (head)
int maxRow, maxCol;//rowHeader[maxRow] does not exist; maxRow-1 is actually
//the highest x-order value. same for maxCol-1 being the highest y-order value
/*~Polynomial()//destructor
{
/* delete all the stoofs!
int count=0;
while (count<maxRow)
{
delete rowHeader[count];
}
count=0;
while(count<maxCol)
{
delete colHeader[count];
}
delete rowHeader; delete colHeader;
}*/
};
//////////////////////////
// prototypes //
//////////////////////////
void initialize(Polynomial &p, int m, int n);
void input(Polynomial &p);
void insertTerm(Polynomial &p, int coeff, int rowIndex, int colIndex);
void output(Polynomial p);
void resetBoolExists(int m, int n);
void Part1(Polynomial &P, Polynomial &Q, Polynomial &R, Polynomial &S, Polynomial &T);
void evaluate(Polynomial p);
void evaluates(Polynomial p, int x, int y);
void Part2and3(Polynomial P, Polynomial Q, Polynomial R, Polynomial S, Polynomial T);
void inputwAdd(Polynomial &A, Polynomial toAdd);
void insertAdd(Polynomial &p, int coeff, int rowIndex, int colIndex);
void inputwSub(Polynomial &A, Polynomial toSub);
void insertSub(Polynomial &P, int coeff, int rowIndex, int colIndex);
void part3(Polynomial A, Polynomial B, Polynomial C, Polynomial D, Polynomial E, Polynomial F, Polynomial P, Polynomial Q, Polynomial R, Polynomial S);
Polynomial multiply(Polynomial P, Polynomial Q);
Polynomial power(Polynomial P, int k);
//end prototypes
int main()
{
Polynomial A,B,D,E,F,P,Q,R,S,T;
Part1(P,Q,R,S,T);
cout<<"Step 1 is complete; the following is Step2:\n";//just to divide it up.
Part2and3(P,Q,R,S,T);//combined into the same step because I need to use A,B,D,E,F.
cout<<"program is done!\n";
return 0;
}
////////////////////
// Part 1 Methods //
////////////////////
void Part1(Polynomial &P, Polynomial &Q, Polynomial &R, Polynomial &S, Polynomial &T)
{
int m=5, n=5;//values 0-4 is 5 rows and columns
resetBoolExists(m+1,n+1);
polyNum=1;
initialize(P,m,n);
input(P);
cout<<"P = ";
output(P);
evaluate(P);
resetBoolExists(m, n+2);
polyNum=2;
initialize(Q,m-1,n+1);//maxrow here is 4 (0-3, 3 is the highest order X)
input(Q);
cout<<"Q = ";
output(Q);
evaluate(Q);
resetBoolExists(5,3);
polyNum=3;
initialize(R,4,2);
input(R);
cout<<"R = ";
output(R);
evaluate(R);
resetBoolExists(3,7);
polyNum=4;
initialize(S,2,6);
input(S);
cout<<"S = ";
output(S);
evaluate(S);
resetBoolExists(10,10);//the max it can hold.
polyNum=5;
initialize(T,m,n);
input(T);
cout<<"Your own polynomial, \"T\" = ";
output(T);
evaluate(T);
}
void resetBoolExists(int row, int col)
{
//code lifted
}
void initialize(Polynomial &p, int m, int n)
{
p.rowHeader= new node*[m];//m is rows
p.colHeader= new node*[n];//n is columns
int a=0;
while(a<m)
{
p.rowHeader[a]=NULL;//need to initialize these values, as they have been causing a sigsegv
a++;
}
a=0;
while(a<n)
{
p.colHeader[a]=NULL;
a++;
}
p.maxRow=m;
p.maxCol=n;
// p.rowHeader[0].coefficient=1;//used for debugging purposes.
}
void input(Polynomial &p)
{
//code lifted
}
void insertTerm(Polynomial &p, int coeff, int rowIndex, int colIndex)
{
//cout<<rowIndex<<" inside insertTerm\n";//for debugging
if (coeff==0)
{
cout<<"coefficient was zero, triple not added\n";//debugging
return;
}
if (rowIndex>(p.maxRow) || colIndex>(p.maxCol) || rowIndex<0 || colIndex<0)
{
//cout<<"out of bounds\n";//debugging
return;
}
node *colPtr = p.colHeader[colIndex];
node *rowPtr = p.rowHeader[rowIndex];
//cout<<"ptrs initialized and maxCol is: "<<p.maxCol<<"\n";//so far maxCol works as suspected
////////////////////////////////////////////
// //
// Header Link Creation //
// //
////////////////////////////////////////////
////////////////////
// colPtrs //
////////////////////
//code lifted
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//For each individual insertTerm, their perspective headers have been created and attached to their respective col/row indeces.//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//traverse into the linked list ("outside" of headers) if it exists
//cout<<"headers initialized for input\n";
colPtr=colPtr->colLink;
rowPtr=rowPtr->rowLink;//move to the first node (first case, it will be the header)
while(colPtr->colLink->row > rowIndex && colPtr->colLink != p.colHeader[colIndex])
{//we are on the column array; move along the cols (up the rows.. rows decrement) until we reach the intended row number, hence row>rowIndex,
//and as long as the next node isn't equal to the header... which it will in the first instance.
colPtr=colPtr->colLink;//since we check for colPtr->colLink->row,
}//we end up on the spot right BEFORE the intended value, perfect for inserting a node
while(rowPtr->rowLink->col > colIndex && rowPtr->rowLink != p.rowHeader[rowIndex])
{//similar deal to the colptr; you travel along the rows (down the columns, columns decrement)
rowPtr=rowPtr->rowLink;
}
//insert the node into the linked list
// node *newnode=new node();
// newnode->coefficient=coeff;
// newnode->row=rowIndex;
// newnode->col=colIndex;
//cout<<"for the triple: ("<<coeff<< ", "<<rowIndex<<", "<<colIndex<<") we are at: ("<<colPtr->coefficient<<", "<<colPtr->row<< ", "<<rowPtr->col<<")\n";
if(rowPtr->rowLink->col==colIndex)//taken from Part 2
{//we were to travel right before the intended node. What if the node with the value right row exists?
rowPtr->rowLink->coefficient=coeff;
cout<<"a node has been replaced\n"; //we replace in insertTerm, not add or subtract like Part 2.
}
else if(colPtr->colLink->row==rowIndex)
{
colPtr->colLink->coefficient=coeff;
cout<<"node has been replaced\n";
}
else
{
//code lifted
}
//the below I used as an alternative [to see if it worked better]...
/*node *tempPtr=colPtr->colLink;
colPtr->colLink=new node();//colPtr->colLink is pointing to newnode.
colPtr->colLink->colLink=tempPtr; // (newnode)->colLink=tempPtr [remember newnode is now instead colPtr->colLink) because
//we were behind, and new node is inserted between colPtr and colPtr->colLink
colPtr->colLink->rowLink=rowPtr->rowLink;//newnode->rowLink points to the rowPtr->rowLink, so as to be inserted between rowPtr and rowPtr->rowLink
rowPtr->rowLink=colPtr->colLink;//now rowPtr will point to the (newnode), known as colPtr->colLink.
colPtr->colLink->coefficient=coeff;
colPtr->colLink->row=rowIndex;
colPtr->colLink->col=colIndex;*/
//cout<<"node inserted\n";
// if(rowPtr == p.rowHeader[rowIndex])//so it wass coming back that it's not... because I malloc'ed rowPtr and colPtr instead of polynomial's header explicitly.
// cout<<p.rowHeader[rowIndex]->rowLink->row<<" row\n"<<colPtr->colLink->col<<" col\n"<<rowPtr->rowLink->coefficient<<" coefficient\n"<<rowIndex<<" rowIndex\n";
// return;
}
void output(Polynomial p)
{
/*cout<<"Outputting...";
node *rowPtr=p.rowHeader[p.maxRow-1]; //4 does not seem to work. hrm.
rowPtr=rowPtr->rowLink;
cout<<rowPtr->coefficient<<"\n";
rowPtr=p.rowHeader[3];
rowPtr=rowPtr->rowLink;
cout<<rowPtr->coefficient<<"\n";
rowPtr=p.rowHeader[1];
rowPtr=rowPtr->rowLink;
cout<<rowPtr->coefficient<<"\n";
rowPtr=p.rowHeader[0];
rowPtr=rowPtr->rowLink;
cout<<rowPtr->coefficient<<"\n";*/
int temprow=p.maxRow-1;
while(doesRowExist[temprow]==false)//look for the highest order X poly
{
temprow--;
if(temprow<0)
{
cout<<"there are no terms to output\n"; return;
}
}
int minrow=0;
while(doesRowExist[minrow]==false)
{
minrow++;//this won'tt run if there are 0 terms, because of return above
}
//cout<<"highest Order X is: "<<temprow<<" and lowest is: "<<minrow<<"\n";
node *rowPtr=p.rowHeader[temprow]; //start with highest x
rowPtr=rowPtr->rowLink;//get out of header, theoretically this is the highest y value
while(rowPtr->row>minrow)//if it's equal to minrow, we need to evaluate it.
{//>minrow-1 doesn't work because if minrow is zero, after zero is p.maxCol, causing an endless loop.
while(rowPtr->col!=-1)//made changes for readability's sake. changed in Part 2.
{
if(rowPtr->coefficient==1)
{
if(rowPtr->col==0)//its not at minrow, row can't be zero, but col can
cout<<"x"<<rowPtr->row<<" + ";
else
cout<<"x"<<rowPtr->row<<"y"<<rowPtr->col<<" + ";
}
else if(rowPtr->coefficient==-1)
{
if(rowPtr->col==0)//its not at minrow, row can't be zero, but col can
cout<<" -x"<<rowPtr->row<<" + ";
else
cout<<" -x"<<rowPtr->row<<"y"<<rowPtr->col<<" + ";
}
else
{
if(rowPtr->col==0)//its not at minrow, row can't be zero, but col can
cout<<rowPtr->coefficient<<"x"<<rowPtr->row<<" + ";
else
cout<<rowPtr->coefficient<<"x"<<rowPtr->row<<"y"<<rowPtr->col<<" + ";
}
rowPtr=rowPtr->rowLink;
}
//cout<<"Row done";
rowPtr=rowPtr->colLink;
rowPtr=rowPtr->rowLink;
}
//cout<<"all rows but minrow are done";
while(rowPtr->col!=-1)//evaluate at minrow.
{
//minrow is either 0, or above 0, so here is where we use if statement.
if(rowPtr->coefficient!=1 && rowPtr->coefficient!=-1)
{
if(rowPtr->row==0 && rowPtr->col==0)
cout<<rowPtr->coefficient;
else if(rowPtr->row==0)//implies col failed
cout<<rowPtr->coefficient<<"y"<<rowPtr->col;
else if(rowPtr->col==0) //implies row isn't zero
cout<<rowPtr->coefficient<<"x"<<rowPtr->row;
else
cout<<rowPtr->coefficient<<"x"<<rowPtr->row<<"y"<<rowPtr->col;
}
else if(rowPtr->coefficient ==-1)
{
if(rowPtr->row==0 && rowPtr->col==0) //no choice
cout<<rowPtr->coefficient;
else if(rowPtr->row==0)//implies col failed
cout<<" -y"<<rowPtr->col;
else if(rowPtr->col==0) //implies row isn't zero
cout<<" -x"<<rowPtr->row;
else
cout<<" -x"<<rowPtr->row<<"y"<<rowPtr->col;
}
else//it is 1
{
if(rowPtr->row==0 && rowPtr->col==0)
cout<<rowPtr->coefficient;
else if(rowPtr->row==0)//implies col failed
cout<<"y"<<rowPtr->col;
else if(rowPtr->col==0) //implies row isn't zero
cout<<"x"<<rowPtr->row;
else
cout<<"x"<<rowPtr->row<<"y"<<rowPtr->col;
}
rowPtr=rowPtr->rowLink;
if(rowPtr->col!=-1)
cout<<" + ";//if it's the last term, we dont want a + at the end
}
cout<<"\n"; //the poly is done, next one!
}
void evaluate(Polynomial p)//general case, gives allll the values
{
evaluates(p,3,8); evaluates(p,3,0); evaluates(p,0,2); evaluates(p,2,2);
evaluates(p,10,6);
}
void evaluates(Polynomial p, int x, int y)
{
int result=0;
cout<<"Given values: ("<<x<<","<<y<<") this polynomial's value is: ";
//same type of algorithm as the output, except we don't need to worry about
//maxrow, just minrow. evaluate minrow and circle around until u reach it again.
int minrow=0;
while(doesRowExist[minrow]==false)
{
minrow++;
if(minrow>p.maxRow)
{
cout<<"woops, no terms to evaluate\n"; return;
}
}
node *rowPtr=p.rowHeader[minrow]; //start with lowest x
//code lifted
cout<<result<<"\n";
}
/////////////////////////////////////
//end Part 1, start Part 2 (and 3) //
/////////////////////////////////////
void Part2and3(Polynomial P, Polynomial Q, Polynomial R, Polynomial S, Polynomial T)
{
Polynomial A,B,C,D,E,F;//A=P+Q, B=P-Q, C=R+S, D=P-S, E=S-P, F=Q+R
A.maxRow= max(P.maxRow, Q.maxRow);//set max or maxRow and maxCol into
A.maxCol= max(P.maxCol, Q.maxCol);//A
resetBoolExists(A.maxRow+1,A.maxCol+1);
initialize(A,A.maxRow, A.maxCol);
//cout<<"init\n";
inputwAdd(A,P);//put P into A, if any col/rows exist, instead of replacing it, add them together.
//cout<<"P added\n";
inputwAdd(A,Q); //this way, when we put Q into A, the common terms' coefficients are added!
cout<<"A = ";
output(A);
//B=P-Q
B.maxRow=max(P.maxRow, Q.maxRow);
B.maxCol=max(P.maxCol, Q.maxCol);
resetBoolExists(B.maxRow+1, B.maxCol+1);
initialize(B, B.maxRow, B.maxCol);
inputwAdd(B,P);//we "add" P to B first.
inputwSub(B,Q);//then we sub Q FROM B (B=P, so B-Q =same-as= P-Q)
cout<<"B = ";
output(B);
//C=R+S
C.maxRow=max(R.maxRow, S.maxRow);
C.maxCol=max(R.maxCol, S.maxCol);
resetBoolExists(C.maxRow+1, C.maxCol+1);
initialize(C, C.maxRow, C.maxCol);
inputwAdd(C,R);
inputwAdd(C,S);
cout<<"C = ";
output(C);
//D=P-S
D.maxRow=max(P.maxRow,S.maxRow);
D.maxCol=max(P.maxCol,S.maxCol);
resetBoolExists(D.maxRow+1, D.maxCol+1);
initialize(D, D.maxRow, D.maxCol);
inputwAdd(D,P);
inputwSub(D,S);
cout<<"D = ";
output(D);
//E=S-P
E.maxRow=max(P.maxRow,S.maxRow);
E.maxCol=max(P.maxCol,S.maxCol);
resetBoolExists(E.maxRow+1, E.maxCol+1);
initialize(E, E.maxRow, E.maxCol);
inputwAdd(E,S);//we "add" S to E first.
inputwSub(E,P);//we subtract P from E, which is the same as S; S-P.
cout<<"E = ";
output(E);
//F=Q+R, phew last one of part2!
F.maxRow=max(Q.maxRow,R.maxRow);
F.maxCol=max(Q.maxCol,R.maxCol);
resetBoolExists(F.maxRow+1, F.maxCol+1);
initialize(F, F.maxRow, F.maxCol);
inputwAdd(F,Q);
inputwAdd(F,R);
cout<<"F = ";
output(F);
cout<<"end of part 2, starting Part 3\n";
part3(A,B,C,D,E,F,P,Q,R,S);
delete A.rowHeader; delete A.colHeader; //delete components here (except C, which is no longer used).
delete B.rowHeader; delete B.colHeader;
delete C.rowHeader; delete C.colHeader;
delete D.rowHeader; delete D.colHeader;
delete E.rowHeader; delete E.colHeader;
delete F.rowHeader; delete F.colHeader;
}
void inputwAdd(Polynomial &A, Polynomial toAdd)//similar algorithm to input(poly p) except here, we traverse the entire poly toAdd
{//and add everything in term by term.
//It's worth noting, that although it says &A up there, the Part2()'s Polynomial A is NOT necessarily this one.
//A here is a local variable that I'm deciding to keep after testing with the first case.
//if(polyNum==1)//A = P+Q//polyNum not needed, as this applies to every inputwAdd
//{
//code lifted
}
//}
}
void insertAdd(Polynomial &p, int coeff, int rowIndex, int colIndex)//here is where we insert each term, and if we find common terms, add coefficients
{//instead of replacing the previous one.
//cout<<"inserting triple: " <<coeff<< " "<< rowIndex<< " "<< colIndex<< "\n";
if (coeff==0)//shouldn't happen, but eh.
return;
if (rowIndex>(p.maxRow) || colIndex>(p.maxCol) || rowIndex<0 || colIndex<0)//again shouldn't happen considering the polynomials have already been made.
return;
node *colPtr = p.colHeader[colIndex];
node *rowPtr = p.rowHeader[rowIndex];
////////////////////////////////////////////
// Header Link Creation //
////////////////////////////////////////////
//code lifted
//////////////////////////////////////////////////////////////////
//For each individual insertAdd, their perspective headers have //
//been created and attached to their respective col/row indeces.//
//////////////////////////////////////////////////////////////////
//traverse into the linked list ("outside" of headers) if it exists
//cout<<"headers initialized for input\n";
colPtr=colPtr->colLink;
rowPtr=rowPtr->rowLink;//move to the first node (first case, it will be the header)
while(colPtr->colLink->row > rowIndex && colPtr->colLink != p.colHeader[colIndex])
{
colPtr=colPtr->colLink;//change rows, goingdown 1,
}//we end up on the spot right BEFORE the intended value, perfect for inserting a node, or adding coefficients
while(rowPtr->rowLink->col > colIndex && rowPtr->rowLink != p.rowHeader[rowIndex])
{//similar deal to the colptr; you travel along the rows (down the columns, columns decrement)
rowPtr=rowPtr->rowLink;
}
//the first 4 of these if's/else if's are to add the terms if we are either on or right "behind" the term we're looking for
if(rowPtr->rowLink->col==colIndex && colPtr->colLink->row==rowIndex)//both must be true. we are right before the term.
{//we were to travel right before the intended node. What if the node with the value right row exists?
rowPtr->rowLink->coefficient+=coeff;
if (rowPtr->rowLink->coefficient==0) //oh boy, this number is zero, so it needs to be deleted. colPtr and rowPtr alike.
{
node *tempPtr=rowPtr->rowLink;
rowPtr->rowLink=rowPtr->rowLink->rowLink;//delete this node if it's zero.
colPtr->colLink=colPtr->colLink->colLink;
tempPtr->rowLink=NULL;
tempPtr->colLink=NULL;
delete(tempPtr);
//cout<<"Row deleted, coeff =0\n";//yay it works in each of the 4 conditions.
}
// cout<<"a node has been added\n"; //add.
}
else if(colPtr->row==rowIndex && rowPtr->col==colIndex)//we are at the term instead
{
colPtr->coefficient+=coeff;
if (colPtr->coefficient==0)
{
node *tempColPtr=p.colHeader[colIndex];
while(tempColPtr->colLink!=colPtr)//we want the node before rowPtr
tempColPtr=tempColPtr->colLink;
//assume tempColPtr is before colPtr.
tempColPtr->colLink=colPtr->colLink;//colPtr has no colLinks pointing to it.
node *tempRowPtr=p.rowHeader[rowIndex];
while(tempRowPtr->rowLink!=rowPtr)//we want the node before rowPtr
tempRowPtr=tempRowPtr->rowLink;
//assume tempRowPtr is before rowPtr.
tempRowPtr->rowLink=rowPtr->rowLink;//newnode is inserted between rowPtr and its prev node.
rowPtr->rowLink=NULL; rowPtr->colLink=NULL; colPtr->colLink=NULL; colPtr->rowLink=NULL;
delete(rowPtr);
//delete(colPtr);
}
}
else if(colPtr->row==rowIndex)//yes one, not the other, will happen in the first and maximum poly secnarios.
{
colPtr->coefficient+=coeff;
if(colPtr->coefficient==0)
{
node *tempColPtr=p.colHeader[colIndex];
while(tempColPtr->colLink!=colPtr)//we want the node before colPtr
tempColPtr=tempColPtr->colLink;
tempColPtr->colLink=colPtr->colLink; //colPtr has no colLinks pointint to it.
//however, it has a rowPtr pointing to it....
node *tempRowPtr=p.rowHeader[rowIndex]; //the colPtr is at said row.
while(tempRowPtr->rowLink!=colPtr)
tempRowPtr=tempRowPtr->rowLink;
tempRowPtr->rowLink=colPtr->rowLink;
//now colPtr has nothing pointing to it.
colPtr->colLink=NULL;
colPtr->rowLink=NULL;
delete(colPtr);
}
}
else if(rowPtr->col==colIndex)
{
rowPtr->coefficient+=coeff;
if(rowPtr->coefficient==0)
{
node *tempRowPtr=p.rowHeader[rowIndex];
while(tempRowPtr->rowLink!=rowPtr)
tempRowPtr=tempRowPtr->rowLink;
tempRowPtr->rowLink = rowPtr->rowLink;
//rowPtr has no rowLink pointing to it. it has a colLink pointing to it though.
node *tempColPtr=p.colHeader[colIndex]; //if col is equal to colIndex, then we are at said column.
while(tempColPtr->colLink!=rowPtr)
tempColPtr=tempColPtr->colLink;
tempColPtr->colLink=rowPtr->colLink;
//now rowPtr has nothing pointing to it.
rowPtr->colLink=NULL; rowPtr->rowLink=NULL;
delete(rowPtr);
}
}//*/
else
{
if(colPtr->row<rowIndex && rowPtr->col<colIndex)
{
node *newnode = new node();
newnode->colLink= colPtr;
//what was before colPtr? let's find out
node *tempColPtr=p.colHeader[colIndex];
while(tempColPtr->colLink!=colPtr)//we want the node before rowPtr
tempColPtr=tempColPtr->colLink;
//assume tempColPtr is before colPtr.
tempColPtr->colLink=newnode;//newnode is inserted between rowPtr and its prev node.
//now rowPtr
newnode->rowLink= rowPtr;
//what was before rowPtr? let's find out
node *tempRowPtr=p.rowHeader[rowIndex];
while(tempRowPtr->rowLink!=rowPtr)//we want the node before rowPtr
tempRowPtr=tempRowPtr->rowLink;
//assume tempRowPtr is before rowPtr.
tempRowPtr->rowLink=newnode;//newnode is inserted between rowPtr and its prev node.
newnode->row=rowIndex;
newnode->col=colIndex;
newnode->coefficient=coeff;
}
else if(colPtr->row <rowIndex)//just one, not the other.
{
node *newnode = new node();
newnode->rowLink= rowPtr->rowLink;
rowPtr->rowLink=newnode;
//now to pt to colPtr
newnode->colLink= colPtr;
//what was before colPtr? let's find out
node *tempColPtr=p.colHeader[colIndex];
while(tempColPtr->colLink!=colPtr)//we want the node before rowPtr
tempColPtr=tempColPtr->colLink;
//assume tempColPtr is before colPtr.
tempColPtr->colLink=newnode;//newnode is inserted between rowPtr and its prev node.
newnode->row=rowIndex;
newnode->col=colIndex;
newnode->coefficient=coeff;
}
else if(rowPtr->col < colIndex)//I updated this for Part1 as well
{//we want to insert before our current rowPtr.
node *newnode = new node();
newnode->colLink= colPtr->colLink;
colPtr->colLink=newnode;
//now to pt to rowPTr
newnode->rowLink= rowPtr;
//what was before rowPtr? let's find out
node *tempRowPtr=p.rowHeader[rowIndex];
while(tempRowPtr->rowLink!=rowPtr)//we want the node before rowPtr
tempRowPtr=tempRowPtr->rowLink;
//assume tempRowPtr is before rowPtr.
tempRowPtr->rowLink=newnode;//newnode is inserted between rowPtr and its prev node.
newnode->row=rowIndex;
newnode->col=colIndex;
newnode->coefficient=coeff;
}
else
{
node *newnode = new node();
newnode->colLink= colPtr->colLink;
colPtr->colLink=newnode;
newnode->rowLink= rowPtr->rowLink;
rowPtr->rowLink=newnode;
newnode->row=rowIndex;
newnode->col=colIndex;
newnode->coefficient=coeff;
}
}
}
void inputwSub(Polynomial &B, Polynomial toSub)//similar algorithm to inputwAdd..
{//except we call insertSub.
//It's worth noting, that although it says &B up there, the Part2()'s Polynomial B is NOT necessarily this one.
//(view same note as A in inputwAdd).
node *rowPtr=toSub.rowHeader[toSub.maxRow-1];
rowPtr=rowPtr->rowLink; //outside of header;
//cout<<"row is: "<<rowPtr->row<<"\n";
while (rowPtr->col!=-1)//compute at maxRow
{
insertSub(B, rowPtr->coefficient, rowPtr->row, rowPtr->col);
rowPtr=rowPtr->rowLink;
}
rowPtr=rowPtr->colLink;
rowPtr=rowPtr->rowLink;//get out of header.
while(rowPtr->row!=toSub.maxRow-1)//compute all aside from maxRow
{
while(rowPtr->col!=-1)//col shouldnt be -1 because we just got outside of the header
{
insertSub(B, rowPtr->coefficient, rowPtr->row, rowPtr->col);
rowPtr=rowPtr->rowLink;
}
rowPtr=rowPtr->colLink;//switch rows.
rowPtr=rowPtr->rowLink;//get out of header;
}
}
void insertSub(Polynomial &p, int coeff, int rowIndex, int colIndex)
{//similar to insertAdd or insert -- we subtract common col/row's, and insert
//negative terms.
//cout<<"inserting triple: " <<coeff<< " "<< rowIndex<< " "<< colIndex<< "\n";
if (coeff==0)//shouldn't happen, but eh.
return;
if (rowIndex>(p.maxRow) || colIndex>(p.maxCol) || rowIndex<0 || colIndex<0)//again shouldn't happen considering the polynomials have already been made.
return;
node *colPtr = p.colHeader[colIndex];
node *rowPtr = p.rowHeader[rowIndex];
////////////////////////////////////////////
// Header Link Creation //
////////////////////////////////////////////
//////////////////////
// colPtrs //
//////////////////////
if(colPtr == NULL || doesColExist[colIndex]!=true)
{
p.colHeader[colIndex]=new node();//somehow maxCol is set to zero when the new node is malloced..
if(p.colHeader[colIndex]==NULL)
cout<<"malloc failed at colIndex: "<<colIndex<<"\n";
colPtr=p.colHeader[colIndex];
colPtr->col=colIndex;
colPtr->row=-1;
colPtr->colLink=p.colHeader[colIndex];//circular linked list
doesColExist[colIndex]=true;//added this because the NULL wasn't always coming through.
int tempcol=colIndex-1;//we want to point to the nearest previous colLink.
if(tempcol<0)
{
tempcol=p.maxCol-1;
}
while(doesColExist[tempcol]==false)//
{
tempcol--;
if(tempcol<0)
tempcol=p.maxCol-1;
}
colPtr->rowLink=p.colHeader[tempcol];
//we know this vallue of tempcol is true, so go backwards
tempcol=colIndex+1; //now to find the nearest "next" colLink which is to point to colIndex.
if(tempcol>p.maxCol-1)
tempcol=0;
//now work backwards to find the rowPtr who needs to pt to this one.
while(doesColExist[tempcol]==false)
{
tempcol++;
if(tempcol>p.maxCol-1)
tempcol=0;
}
p.colHeader[tempcol]->rowLink=colPtr;
//cout<<colPtr->col<<"colIndex col added\n";
tempcol=0;
}
////////////////////
// rowPtrs //
////////////////////
if(rowPtr == NULL || doesRowExist[rowIndex]!=true)
{//if the node hasn't been started..
p.rowHeader[rowIndex]=new node();//allocate memory to this not-started node
rowPtr=p.rowHeader[rowIndex];
rowPtr->row=rowIndex;
rowPtr->col=-1;
rowPtr->rowLink=p.rowHeader[rowIndex];//circular linked list
doesRowExist[rowIndex]=true; //useful for colLink purposes, below.
//this is in order to insert a valid colLink.
int temprow=rowIndex-1;//if we use rowIndex, it will of course be made/true, we just did it..
if(temprow<0)
temprow=p.maxRow-1;//so we go finding the first one for colLink to point to
while(doesRowExist[temprow]==false)
{
temprow--;
if(temprow<0)
temprow=p.maxRow-1;
}
rowPtr->colLink=p.rowHeader[temprow];
temprow=rowIndex+1; //now for the position that will POINT to rowIndex
if(temprow>p.maxRow-1)
temprow=0;
//working backwards to find the rowPtr who needs to pt to this rowIndex...
while(doesRowExist[temprow]==false)
{
temprow++;
if(temprow>p.maxRow-1)
temprow=0;
}
p.rowHeader[temprow]->colLink=rowPtr;
//cout<<rowPtr->row<<"RowIndex row added\n";
temprow=0;
}
//traverse into the linked list ("outside" of headers) if it exists
//cout<<"headers initialized for input\n";
colPtr=colPtr->colLink;
rowPtr=rowPtr->rowLink;//move to the first node (first case, it will be the header)
while(colPtr->colLink->row > rowIndex && colPtr->colLink != p.colHeader[colIndex])
{
colPtr=colPtr->colLink;//change rows, goingdown 1,
}//we end up on the spot right BEFORE the intended value, perfect for inserting a node, or adding coefficients
while(rowPtr->rowLink->col > colIndex && rowPtr->rowLink != p.rowHeader[rowIndex])
{//similar deal to the colptr; you travel along the rows (down the columns, columns decrement)
rowPtr=rowPtr->rowLink;
}
//cout<<"for the triple: ("<<coeff<< ", "<<rowIndex<<", "<<colIndex<<") we are at: ("<<colPtr->coefficient<<", "<<colPtr->row<< ", "<<rowPtr->col<<")\n";
if(rowPtr->col < colIndex)//I updated this for Part1 as well
{//we want to insert before our current rowPtr.
node *newnode = new node();
newnode->colLink= colPtr->colLink;
colPtr->colLink=newnode;
//now to pt to rowPTr
newnode->rowLink= rowPtr;
//what was before rowPtr? let's find out
node *tempRowPtr=p.rowHeader[rowIndex];
while(tempRowPtr->rowLink!=rowPtr)//we want the node before rowPtr
tempRowPtr=tempRowPtr->rowLink;
//assume tempRowPtr is before rowPtr.
tempRowPtr->rowLink=newnode;//newnode is inserted between rowPtr and its prev node.
newnode->row=rowIndex;
newnode->col=colIndex;
newnode->coefficient=-1*coeff;
}
else if(colPtr->colLink->row==rowIndex)
{
colPtr->colLink->coefficient-=coeff;
if (colPtr->colLink->coefficient==0)
{
node *tempPtr=colPtr->colLink;
colPtr->colLink=colPtr->colLink->colLink;//delete this node if it's zero.
rowPtr->rowLink=rowPtr->rowLink->rowLink;
tempPtr->rowLink=NULL;
tempPtr->colLink=NULL;
delete(tempPtr);
}
}
else if(rowPtr->rowLink->col==colIndex)
{//we were to travel right before the intended node. What if the node with the value right row exists?
rowPtr->rowLink->coefficient-=coeff;
if (rowPtr->rowLink->coefficient==0)
{
node *tempPtr=rowPtr->rowLink;
rowPtr->rowLink=rowPtr->rowLink->rowLink;//delete this node if it's zero.
colPtr->colLink=colPtr->colLink->colLink;
tempPtr->rowLink=NULL;
tempPtr->colLink=NULL;
delete(tempPtr);
}
//cout<<"a node has been subtracted\n"; //coefficient = coefficient-coeff.
}/*
else if(colPtr->row==rowIndex && colPtr->colLink ==colPtr )
{//what if, when we went to the first link off header, it was automatically
//lower than row (while loop immediately ends)?
colPtr->coefficient+=coeff;
cout<<"current colNode added";
}
else if(rowPtr->col==colIndex && rowPtr->rowLink==rowPtr)
{
rowPtr->coefficient+=coeff;
cout<<"current rowNode added";
}*/ //not sure if the above is needed anymore
else
{
node *newnode = new node();
newnode->colLink= colPtr->colLink;
colPtr->colLink=newnode;
newnode->rowLink= rowPtr->rowLink;
rowPtr->rowLink=newnode;
newnode->row=rowIndex;
newnode->col=colIndex;
newnode->coefficient=-1*coeff;
}
}
///////////////////////////////////////////
// END //
// PART //
// TWO //
///////////////////////////////////////////
void part3(Polynomial A, Polynomial B, Polynomial C, Polynomial D, Polynomial E,
Polynomial F, Polynomial P, Polynomial Q, Polynomial R, Polynomial S)
{
Polynomial G,H,I,J,K,L;
cout<<endl<<endl;
//G=P*Q, so the maxCol is 1 higher than the sum of the two highest cols (P.maxCol-1 + Q.maxCol-1)
G=multiply(P,Q);
cout<<"G = ";
output(G); cout<<endl;
H=multiply(R,S); cout<<"H = "; output(H); cout<<endl;
I=multiply(A,B); cout<<"I = "; output(I); cout<<endl;
J=multiply(E,F); cout<<"J = "; output(J); cout<<endl;
K=multiply(D,E); cout<<"K = "; output(K); cout<<endl;
L=multiply(I,K); cout<<"L = "; output(L); cout<<endl;
//delete(A.rowHeader); delete(A.colHeader);
//delete(B.rowHeader); delete(B.colHeader);
A=power(P,5);
cout<<"A = ";
output(A); cout<<endl;
B=power(Q,3); cout<<"B = "; output(B); cout<<endl;
C=power(R,7); cout<<"C = "; output(C); cout<<endl;
D=power(S,2); cout<<"D = "; output(D); cout<<endl;
E=power(P,2); cout<<"E = "; output(E); cout<<endl;
F=power(Q,5); cout<<"F = "; output(F); cout<<endl;
}
Polynomial multiply(Polynomial P, Polynomial Q)
{
Polynomial product;
product.maxCol=P.maxCol+Q.maxCol-1;//as explained before, it's minus 1 because -2+1=-1.
product.maxRow=P.maxRow+Q.maxRow-1;
resetBoolExists(product.maxRow+1, product.maxCol+1);
initialize(product, product.maxRow, product.maxCol);
node *pRowPtr=P.rowHeader[P.maxRow-1]; pRowPtr=pRowPtr->rowLink;
node *qRowPtr=Q.rowHeader[Q.maxRow-1]; qRowPtr=qRowPtr->rowLink;
while(pRowPtr->col!=-1)
{
while(qRowPtr->col!=-1)//do the max row of Q
{
insertAdd(product, pRowPtr->coefficient*qRowPtr->coefficient, pRowPtr->row + qRowPtr->row, pRowPtr->col + qRowPtr->col);
qRowPtr= qRowPtr->rowLink;
}
qRowPtr=qRowPtr->colLink;
qRowPtr=qRowPtr->rowLink;
while(qRowPtr->row!=Q.maxRow-1)//now the rest of Q.
{
while(qRowPtr->col!=-1)
{
insertAdd(product, pRowPtr->coefficient*qRowPtr->coefficient, pRowPtr->row + qRowPtr->row, pRowPtr->col + qRowPtr->col);//any common terms should be added together.
qRowPtr=qRowPtr->rowLink;
}
qRowPtr=qRowPtr->colLink;
qRowPtr=qRowPtr->rowLink;
}
pRowPtr=pRowPtr->rowLink;//no change in columns because we are only doing the max row of P.
}
//here we do the rest of P.
pRowPtr=pRowPtr->colLink;
pRowPtr=pRowPtr->rowLink;
while(pRowPtr->row!=P.maxRow-1)
{
while(pRowPtr->col!=-1)
{
while(qRowPtr->col!=-1)//do the max row of Q again, for each term of P
{
insertAdd(product, pRowPtr->coefficient*qRowPtr->coefficient, pRowPtr->row + qRowPtr->row, pRowPtr->col + qRowPtr->col);
qRowPtr= qRowPtr->rowLink;
}
qRowPtr=qRowPtr->colLink;
qRowPtr=qRowPtr->rowLink;
while(qRowPtr->row!=Q.maxRow-1)//now the rest of Q.
{
while(qRowPtr->col!=-1)
{
insertAdd(product, pRowPtr->coefficient*qRowPtr->coefficient, pRowPtr->row + qRowPtr->row, pRowPtr->col + qRowPtr->col);
qRowPtr=qRowPtr->rowLink;
}
qRowPtr=qRowPtr->colLink;
qRowPtr=qRowPtr->rowLink;
}
pRowPtr=pRowPtr->rowLink;
}
pRowPtr=pRowPtr->colLink;
pRowPtr=pRowPtr->rowLink;
}
return product;
}
Polynomial power(Polynomial A, int k)
{
//To explain the logic below, and how it gives at MOST 2log(n) multiplications:
//I turn the exponent, k, into a binary representation. e.g. A^7 = A^4*A^2*A^1, or 111.
//I get A, requires zero multiplications
//A^2, requires one multiplication.
//A^4, requires one multiplication (A^2^2).
//A*A^2*A^4 are two more multiplications. A total of 4 multiplications.
//by turning an exponent into a multiplication of binary numbers,
//I reduce the number of multiplications between A*A^2*A^4*A^8 etc.. to log(n).
//I also reduce the multiplications of each A to logn (to get A, 0 mult, to get A^2m 1 mult, A^4 requires 2 mult total, etc..).
//this makes for log(n)+log(n)= 2log(n). yay, at most 2log(n).
Polynomial product;
product.maxCol=(A.maxCol-1)*k+1;//as explained before, maxCol is the number of columns, so the highest value is maxCol-1
product.maxRow=(A.maxRow-1)*k+1;//times k because it is an exponent raised to a power
//see log rules: (A^(maxCol-1))^k --> log((maxCol-1)^k) = k*log(maxCol-1). add 1 because we want the number of rows/cols
resetBoolExists(product.maxRow+1, product.maxCol+1);
initialize(product, product.maxRow, product.maxCol);
//cout<<"maxRow is: "<< product.maxRow<<" and maxCol is: "<<product.maxCol<<endl;
if(k==0)//A^0 =1. that's it.
{
insertTerm(product,1,0,0);
return product;
}
if(k<0) //not part of the requirements, but always good to include an if for this.
{
//not sure what to do with this. I'll leave it blank for now.. or rather I'll just return
cout<<"I am incapable of doing this with my current skillset. Please try again in a few years...\n";
//a tad bit of a lie, but I don't think factoring denominators is what we're supposed to do here. =/
return product;
}
int arraysize=0, ktemp=k;
while(ktemp!=0)
{
arraysize++;
ktemp=ktemp/2;
}
int *binaryArray= new int[arraysize];
Polynomial arrayP[arraysize];
for(int i=0; i<arraysize; i++)
{
binaryArray[i]=0;//initialize all values.
arrayP[i]=A;
}
ktemp=k; int index=0;//time to fill in the binaryArray values now.
while(ktemp!=0)//I don't need an additional index<arraysize, because ktemp will stop when index reaches arraysize simply by the fact
{//that arraysize was defined that way.
binaryArray[index]=ktemp%2;
ktemp=ktemp/2;
index++;
}
index=0;
while(index<arraysize)
{
if(index==0)
arrayP[index]=A;//0th term is always the array itself (A^(2^0)) = A
else
arrayP[index]=multiply(arrayP[index-1],arrayP[index-1]); //here I find A^2, or A^2^2 aka A^4, and A^8, etc..
index++;
}
//cout<<"A = "; output(arrayP[1]);//0th and 1st term both work. the problem isn't arrayP.
index=0;
bool isEmpty = 1;//product is empty.
//cout<<"arrayP filled\n"; //it's after here that something goes wrong.
while(index<arraysize)
{
//cout<<"inside while loop\t";
if(binaryArray[index]==1)
{
if(isEmpty==1)//1 is true 0 is false :o..
{
//cout<<"first term was input";
//inputwAdd(product, arrayP[index]); //for some reason, I cannot use an element of the array?
//this is something that gave me so much trouble for the past week
//this is the workaround I've decided on. eh. meh.
product=arrayP[index];
isEmpty=0;
}
else
{
product=multiply(product, arrayP[index]); //now, multiply the first poly to the second
//cout<<"a term was multiplied";
}
}
//do nothing if binaryArray[index] is 0.
index++;
}
//cout<<"product done\n";
//output(product);
return product;
}
<file_sep>/README.md
# MultiPoly
Representing polynomials using data structures for an advanced data structures & algorithms course.
#Because of the nature of coursework, a lot of code has been lifted in order to prevent plagierism for such courses. If you would like a copy of the original code, please contact me directly for a copy. VV
|
b464733e0c86d40181f90df0003f0950ed14f764
|
[
"Markdown",
"C++"
] | 2 |
C++
|
vladvventura/MultiPoly
|
f12d44648354c34e29a7037a5410b18b1ad47c8a
|
f9aff32fdbb8df20eea0b66f3efe0a37d99a1aa7
|
refs/heads/master
|
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NotificationsService } from 'angular2-notifications';
import { Idea, IdeaService } from '../shared';
@Component({
selector: 'app-ideas',
templateUrl: './ideas.component.html',
styleUrls: ['./ideas.component.css']
})
export class IdeasComponent implements OnInit {
ideas: Idea[];
ideaCount: number = 0;
constructor(
private router: Router,
private ideaService: IdeaService,
private notificationsService: NotificationsService
) { }
goto(idea: Idea) {
this.router.navigate(['/ideas/edit', idea.id]);
}
ngOnInit() {
this.ideaService.get()
.subscribe(
data => {
this.ideas = data;
this.ideaCount = data.length;
console.log(this.ideas);
},
err => {
this.notificationsService.error('Oops', `There was problem retrieving your ideas. ${err.message}`);
}
);
}
}
<file_sep>/* tslint:disable:no-unused-variable */
import { TestBed, async, inject } from '@angular/core/testing';
import { AuthResolverService } from './auth-resolver.service';
describe('Service: AuthResolver', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [AuthResolverService]
});
});
it('should ...', inject([AuthResolverService], (service: AuthResolverService) => {
expect(service).toBeTruthy();
}));
});
<file_sep>export class SnippetMenuConfig {
top: number;
left: number;
display: boolean;
}
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ApiService } from './api.service';
import { Snippet } from '../models';
@Injectable()
export class SnippetService {
private apiPath = '/snippets/';
constructor(
private apiService: ApiService
) {}
get(): Observable<Snippet[]> {
return this.apiService.get(`${this.apiPath}`)
.map(response => {
let result = <Snippet[]>this.apiService.extractDatas(response);
return result; });
}
find(id: number): Observable<Snippet> {
return this.apiService.get(`${this.apiPath}${id}`)
.map(response => {
let result = <Snippet>this.apiService.extractData(response);
return result; });
}
put(snippet: Snippet): Observable<any> {
let update = {
snippet_id: snippet.id,
text: snippet.text,
interview_id: snippet.interview_id,
update_user: snippet.updated_by
};
return this.apiService.put(`${this.apiPath}${snippet.id}`, update)
.map(data => data);
}
post(snippet: Snippet): Observable<any> {
return this.apiService.post(`${this.apiPath}`, snippet)
.map(data => data);
}
delete(id: number): Observable<any> {
return this.apiService.delete(`${this.apiPath}${id}`)
.map(data => data);
}
}
<file_sep>export * from './idea-preview.component';<file_sep>import { ModuleWithProviders, NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { IdeasComponent } from './ideas.component';
import { EditorComponent } from './editor/editor.component';
import { EditableIdeaResolver } from './editor/editable-idea-resolver.service';
import { SharedModule, AuthGuardService } from '../shared';
const ideasRoutes: Routes = [
{
path: 'ideas',
component: IdeasComponent,
canActivate: [AuthGuardService]
},
{
path: 'ideas/edit/:id',
component: EditorComponent,
canActivate: [AuthGuardService],
resolve: {
idea: EditableIdeaResolver
}
},
{
path: 'ideas/add',
component: EditorComponent,
canActivate: [AuthGuardService]
}
];
const ideasRouting: ModuleWithProviders = RouterModule.forChild(ideasRoutes);
@NgModule({
imports: [
ideasRouting,
SharedModule,
NgbModule
],
declarations: [
IdeasComponent,
EditorComponent
],
providers: [
AuthGuardService,
EditableIdeaResolver
]
})
export class IdeasModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { NotificationsService } from 'angular2-notifications';
import { Idea, IdeaService, UserService } from '../../shared';
import { Snippet } from '../../shared/models';
// todo: implement CanDeactivate https://angular.io/docs/ts/latest/guide/router.html#!#can-deactivate-guard
@Component({
selector: 'app-editor',
templateUrl: './editor.component.html',
styleUrls: ['./editor.component.css']
})
export class EditorComponent implements OnInit {
search: string;
idea: Idea = new Idea();
snippets: Snippet[];
isSubmitting: boolean = false;
userId: any;
constructor(
private modalService: NgbModal,
private ideaService: IdeaService,
private userService: UserService,
private route: ActivatedRoute,
private router: Router,
private notificationsService: NotificationsService
) { }
ngOnInit() {
// load prefetched interview
this.route.data.subscribe(
(data: {idea: Idea}) => {
if (data.idea) {
this.idea = data.idea;
}
}
);
this.userService.currentUser.subscribe(
user => {
if (this.idea && this.idea.id) {
this.idea.updated_by = user.username;
} else {
this.idea.created_by = user.username;
this.idea.status = 'UNTESTED';
}
}
);
this.ideaService.snippets(this.idea.id)
.subscribe(data => { this.snippets = data; });
}
save() {
// check if interview is new or exists.
let serviceCall: Observable<any>;
let insert: boolean;
if (this.idea && this.idea.id) {
serviceCall = this.ideaService.put(this.idea);
insert = false;
} else {
serviceCall = this.ideaService.post(this.idea);
insert = true;
}
serviceCall.subscribe(
data => {
console.log('idea saved.');
this.idea.id = data.idea_id;
if (insert) {
this.notificationsService.success('Saved', 'Idea saved successfully!');
}
else {
this.notificationsService.success('Updated', 'Idea updated successfully!');
}
},
err => {
this.notificationsService.error('Oops', `There was problem saving your idea. ${err.message}`);
}
);
}
}
<file_sep>export * from './customer.model';
export * from './dashboard.model';
export * from './idea.model';
export * from './interview.model';
export * from './snippet.model';
export * from './user.model';
<file_sep>import { ModuleWithProviders, NgModule } from '@angular/core';
import { Routes, RouterModule, CanActivate } from '@angular/router';
import { DashboardComponent } from './dashboard.component';
import { SharedModule, AuthGuardService } from '../shared';
const dashboardRoutes: Routes = [
{
path: 'dashboard',
component: DashboardComponent,
canActivate: [AuthGuardService]
}
];
const dashboardRouting: ModuleWithProviders = RouterModule.forChild(dashboardRoutes);
@NgModule({
imports: [
dashboardRouting,
SharedModule
],
declarations: [DashboardComponent],
providers: [
AuthGuardService
]
})
export class DashboardModule { }
<file_sep>import { Directive, ElementRef, EventEmitter, HostListener, OnInit, Output } from '@angular/core';
@Directive({ selector: '[appSnippet]' })
export class SnippetDirective implements OnInit {
@Output()
onSnippetSelection = new EventEmitter<any>();
@Output()
onSnippetDeselection = new EventEmitter<boolean>();
@HostListener('mouseup') onMouseUp() {
let selectedText = this.getSelection();
let position = this.getSelectedPosition();
if (selectedText && selectedText !== '') {
let result = { text: selectedText, position: position };
this.onSnippetSelection.emit( result );
} else {
this.onSnippetDeselection.emit(true);
}
}
constructor(public element: ElementRef) {}
ngOnInit() { }
getSelection() {
let doc = (<any>document);
let text: string;
if (window.getSelection) {
text = window.getSelection().toString();
} else if (doc.selection && doc.selection.type !== 'Control') {
text = doc.selection.createRange().htmlText;
}
return text;
}
getSelectedPosition() {
let doc = (<any>document);
let element = this.element.nativeElement;
let start = 0, end = 0;
let sel, range, priorRange, rect;
if (typeof window.getSelection !== 'undefined') {
range = window.getSelection().getRangeAt(0);
rect = range.getClientRects()[0];
priorRange = range.cloneRange();
priorRange.selectNodeContents(element);
priorRange.setEnd(range.startContainer, range.startOffset);
start = priorRange.toString().length;
end = start + range.toString().length;
} else if (typeof doc.selection !== 'undefined' &&
(sel = doc.selection).type !== 'Control') {
range = sel.createRange();
rect = range.getClientRects()[0];
priorRange = doc.body.createTextRange();
priorRange.moveToElementText(element);
priorRange.setEndPoint('EndToStart', range);
start = priorRange.text.length;
end = start + range.text.length;
}
return {
start: start,
end: end,
rect: rect
};
}
getSelectionCoords() {
let win = window;
let doc = (<any>win.document);
let sel = doc.selection, range, rects, rect;
let x = 0, y = 0;
if (sel) {
if (sel.type !== 'Control') {
range = sel.createRange();
range.collapse(true);
x = range.boundingLeft;
y = range.boundingTop;
}
} else if (win.getSelection) {
sel = win.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0).cloneRange();
if (range.getClientRects) {
range.collapse(true);
rects = range.getClientRects();
if (rects.length > 0) {
rect = rects[0];
}
x = rect.left;
y = rect.top;
}
// Fall back to inserting a temporary element
if (x === 0 && y === 0) {
let span = doc.createElement('span');
if (span.getClientRects) {
// Ensure span has dimensions and position by
// adding a zero-width space character
span.appendChild( doc.createTextNode('\u200b') );
range.insertNode(span);
rect = span.getClientRects()[0];
x = rect.left;
y = rect.top;
let spanParent = span.parentNode;
spanParent.removeChild(span);
// Glue any broken text nodes back together
spanParent.normalize();
}
}
}
}
return { leftx: x, top: y };
}
}
<file_sep>/* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { SnippetPreviewComponent } from './snippet-preview.component';
describe('Component: SnippetPreview', () => {
it('should create an instance', () => {
let component = new SnippetPreviewComponent();
expect(component).toBeTruthy();
});
});
<file_sep>/* tslint:disable:no-unused-variable */
import { TestBed, async } from '@angular/core/testing';
import { ContenteditableModelDirective } from './contenteditable-model.directive';
describe('Directive: ContenteditableModel', () => {
it('should create an instance', () => {
let directive = new ContenteditableModelDirective();
expect(directive).toBeTruthy();
});
});
<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { NotificationsService } from 'angular2-notifications';
import { InterviewService, Interview, Customer } from '../../shared';
@Component({
selector: 'app-interview-full',
templateUrl: './interview-full.component.html',
styleUrls: ['./interview-full.component.css']
})
export class InterviewFullComponent implements OnInit {
@Input() interview: Interview;
customer: Customer;
constructor(
private interviewService: InterviewService,
private notificationsService: NotificationsService
) { }
ngOnInit() {
this.getMetaData();
}
getMetaData() {
this.interviewService.customer(this.interview.id)
.subscribe(
data => {
this.customer = data;
},
err => {
this.notificationsService
.error('Oops', `There was problem retrieving your "${this.interview.title}" interview. ${err.message}`);
}
);
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NotificationsService } from 'angular2-notifications';
import { Interview, InterviewService } from '../shared';
@Component({
selector: 'app-interviews',
templateUrl: './interviews.component.html',
styleUrls: ['./interviews.component.css']
})
export class InterviewsComponent implements OnInit {
interviews: Interview[];
interviewCount: number = 0;
constructor(
private router: Router,
private interviewService: InterviewService,
private notificationsService: NotificationsService
) { }
goto(interview: Interview) {
this.router.navigate(['/interviews/edit', interview.id]);
}
ngOnInit() {
this.interviewService.get()
.subscribe(
data => {
this.interviews = data;
this.interviewCount = data.length;
console.log(this.interviews);
},
err => {
this.notificationsService
.error('Oops', `There was problem retrieving your interviews. ${err.message}`);
}
);
}
}
<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Idea } from '../models';
@Component({
selector: 'app-idea-preview',
templateUrl: './idea-preview.component.html',
styleUrls: ['./idea-preview.component.css']
})
export class IdeaPreviewComponent implements OnInit {
@Input() idea: Idea;
constructor(private router: Router) { }
ngOnInit() {
}
goto() {
this.router.navigate(['/ideas', this.idea.id]);
}
}
<file_sep>import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChange } from '@angular/core';
import { NotificationsService } from 'angular2-notifications';
import { Customer } from '../models';
import { CustomerService } from '../services';
@Component({
selector: '[app-customer-lookup]',
templateUrl: './customer-lookup.component.html',
styleUrls: ['./customer-lookup.component.css']
})
export class CustomerLookupComponent implements OnInit, OnChanges {
private customerFound: boolean = false;
private searching: boolean = false;
private initialized: boolean = false;
@Input() customer: Customer;
@Input() search: string;
@Output() customerChange = new EventEmitter();
constructor(
private customerService: CustomerService,
private notificationsService: NotificationsService
) { }
ngOnInit() {
this.customerFound = this.customerIsValid();
if (!this.customerFound && this.isValidEmail(this.search)) {
this.lookupCustomer();
}
this.initialized = true;
}
ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
if (this.initialized) {
for (let propName in changes) {
if (changes.hasOwnProperty(propName)) {
let changedProp = changes[propName];
console.log(`${propName} changed: ${changedProp.currentValue}`);
switch (propName) {
case 'customer':
if (changedProp.currentValue && changedProp.currentValue.id) {
this.customerFound = true;
}
break;
case 'search':
let isValidCustomer = this.customerIsValid();
if (this.isValidEmail(changedProp.currentValue) && (!isValidCustomer || changedProp.currentValue !== this.customer.email)) {
this.lookupCustomer();
} else {
this.customerFound = (isValidCustomer &&
(!this.isValidEmail(changedProp.currentValue) || (changedProp.currentValue === this.customer.email)));
}
break;
}
}
}
}
}
isUndefined(obj) {
return obj === void 0;
}
customerIsValid() {
return (!this.isUndefined(this.customer) && ((this.customer.id && this.customer.id > 0) || this.customer.success));
}
cleanString(value: string) {
return value.replace(/\s/g, '');
}
isValidEmail(value: string) {
if (this.isUndefined(value) && value !== '') {
return false;
}
let EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
return (value.length > 5 && EMAIL_REGEXP.test(this.cleanString(value)));
}
lookupCustomer() {
this.search = this.cleanString(this.search);
if (this.isValidEmail(this.search)) {
console.log(`Looking up customer ${this.search}`);
this.searching = true;
this.customerService.lookup(this.search)
.subscribe(
data => {
this.customer = data;
this.searching = false;
this.customerFound = this.customerIsValid();
this.customerChange.emit(data);
},
err => {
this.notificationsService
.error('Oops', `There was problem finding a customer for ${this.search}. ${err.message}`);
this.customer.email = this.search;
this.customer.found = false;
this.customerFound = false;
this.searching = false;
}
);
}
}
}
<file_sep>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import {MomentModule} from 'angular2-moment';
import { CardFooterCreatedComponent } from './card-helpers';
import { CustomerLookupComponent } from './customer-lookup';
import { ShowAuthedDirective, ContenteditableModelDirective } from './directives';
import { IdeaPreviewComponent } from './idea-helpers';
import { InterviewPreviewComponent } from './interview-helpers';
import { SnippetPreviewComponent, SnippetPreviewListComponent, SnippetIdeaListComponent } from './snippet-helpers/';
//import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
@NgModule({
imports: [
CommonModule,
FormsModule,
HttpModule,
MomentModule,
RouterModule
],
declarations: [
CardFooterCreatedComponent,
ContenteditableModelDirective,
CustomerLookupComponent,
IdeaPreviewComponent,
InterviewPreviewComponent,
ShowAuthedDirective,
SnippetPreviewComponent,
SnippetPreviewListComponent,
SnippetIdeaListComponent
],
exports: [
CommonModule,
FormsModule,
HttpModule,
MomentModule,
RouterModule,
CardFooterCreatedComponent,
ContenteditableModelDirective,
CustomerLookupComponent,
IdeaPreviewComponent,
InterviewPreviewComponent,
ShowAuthedDirective,
SnippetPreviewComponent,
SnippetPreviewListComponent,
SnippetIdeaListComponent
]
})
export class SharedModule { }
<file_sep>import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { NotificationsService } from 'angular2-notifications';
import { IdeaService, SnippetService } from '../services';
import { Snippet } from '../models';
@Component({
selector: 'app-snippet-idea-list',
templateUrl: './snippet-idea-list.component.html',
styleUrls: ['./snippet-idea-list.component.css'],
encapsulation: ViewEncapsulation.None
})
export class SnippetIdeaListComponent implements OnInit {
@Input() ideaId: number;
@Input() limit: number;
snippets: Snippet[];
constructor(
private ideaService: IdeaService,
private notificationsService: NotificationsService
) { }
ngOnInit() {
this.ideaService.snippets(this.ideaId)
.subscribe(data => { this.snippets = data; });
}
snippetRemoved(index: number) {
this.snippets.splice(index, 1);
this.notificationsService.success('Removed', 'Snippet removed successfully!');
}
}
<file_sep>import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'ellipsis'
})
export class EllipsisPipe implements PipeTransform {
transform(value: string,
args: string[]): any {
if (!value) return value;
// return value.replace(/\w\S*/g, function(txt) {
// return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
// });
//let p = value.length;
//var divh=$('.notes').height();
//alert(divh);
//while ( p > 500) {
return value.replace(/\W*\s(\S)*$/, '...');
//}
}
}
<file_sep>import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, Router, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { InterviewService } from '../../shared';
@Injectable()
export class EditableInterviewResolver implements Resolve<any> {
constructor(private interviewService: InterviewService, private router: Router) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> {
return this.interviewService.find(route.params['id'])
.map(
data => {
return data;
}
)
.catch((err) => this.router.navigateByUrl('/interviews'));
}
}
<file_sep>import { ICreated } from './created.interface';
export class Interview implements ICreated {
id: number;
title: string;
notes: string;
created_by: string;
created_datetime: Date;
created_image_link: string;
updated_by: string;
updated_datetime: Date;
updated_image_link: string;
}
<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { IdeaService } from '../services';
import { Snippet } from '../models';
@Component({
selector: 'app-snippet-preview-list',
templateUrl: './snippet-preview-list.component.html',
styleUrls: ['./snippet-preview-list.component.css']
})
export class SnippetPreviewListComponent implements OnInit {
@Input() ideaId: number;
@Input() limit: number;
snippets: Snippet[];
constructor(private ideaService: IdeaService) { }
ngOnInit() {
this.ideaService.snippets(this.ideaId)
.subscribe(data => { this.snippets = data; });
}
showLimit() {
return this.limit || (this.snippets ? this.snippets.length : 3);
}
}
<file_sep>export const environment = {
production: true,
server: '',
api_url : 'https://coppia-api.herokuapp.com/api/v1'
};
<file_sep>import { Component, EventEmitter, Input, OnInit, Output, ViewEncapsulation } from '@angular/core';
import { NotificationsService } from 'angular2-notifications';
import { InterviewService, SnippetService } from '../services';
import { Snippet, Customer } from '../models';
@Component({
selector: 'app-snippet-preview',
templateUrl: './snippet-preview.component.html',
styleUrls: ['./snippet-preview.component.css'],
encapsulation: ViewEncapsulation.None
})
export class SnippetPreviewComponent implements OnInit {
@Input() snippet: Snippet;
@Input() index: number;
@Input() editable: boolean = false;
@Output() onRemoved = new EventEmitter<number>();
loading: boolean = true;
customer: Customer;
constructor(
private interviewService: InterviewService,
private snippetService: SnippetService,
private notificationsService: NotificationsService
) { }
ngOnInit() {
this.getMetaData();
}
getMetaData() {
this.interviewService.customer(this.snippet.interview_id)
.subscribe(
data => {
this.customer = data;
console.log(this.customer);
},
err => {
this.notificationsService
.error('Oops', `There was problem retrieving the customer for this snippet. ${err.message}`);
}
);
}
remove(snippet: Snippet, index: number) {
debugger;
this.snippetService.delete(snippet.id)
.subscribe(
data => {
this.onRemoved.emit(index);
},
err => {
this.notificationsService
.error('Oops', `There was problem removing the snippet. ${err.message}`);
}
);
}
}
<file_sep>export * from './api.service';
export * from './auth-guard.service';
export * from './auth-resolver.service';
export * from './customer.service';
export * from './idea.service';
export * from './interview.service';
export * from './jwt.service';
export * from './snippet.service';
export * from './user.service';
<file_sep>export * from './snippet-preview.component';
export * from './snippet-preview-list.component';
export * from './snippet-idea-list.component';
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NotificationsService } from 'angular2-notifications';
import { UserService } from '../shared';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
user: Object = { username: '', password: '' };
errors: Object = {};
isSubmitting: boolean = false;
constructor(
private router: Router,
private userService: UserService,
private notificationsService: NotificationsService
) { }
ngOnInit() {
this.userService.isAuthenticated.subscribe(authenticated => {
if (authenticated) {
this.router.navigate(['dashboard']);
}
});
}
login() {
this.userService.attempAuth(this.user)
.subscribe(
data => { console.log(data); },
err => {
this.errors = err;
this.isSubmitting = false;
this.notificationsService.error('Sign in failed', `There was problem signing in. ${err.message}`);
}
);
}
}
<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';
import { NotificationsService } from 'angular2-notifications';
import { Idea, IdeaService, Snippet, SnippetService, UserService } from '../../shared';
@Component({
selector: 'app-snippet-modal',
templateUrl: './snippet-modal.component.html',
styleUrls: ['./snippet-modal.component.css']
})
export class SnippetModalComponent implements OnInit {
@Input()
snippet: Snippet;
ideas: Idea[];
saving: boolean;
constructor(
public activeModal: NgbActiveModal,
private ideaService: IdeaService,
private snippetService: SnippetService,
private userService: UserService,
private notificationsService: NotificationsService
) {}
ngOnInit() {
this.ideaService.get()
.subscribe(
data => {
this.ideas = data;
},
err => {
this.notificationsService
.error('Oops', `There was problem retrieving your ideas. ${err.message}`);
});
}
choose(idea: Idea) {
this.saveSnippet(idea);
}
private saveSnippet(idea: Idea) {
this.saving = true;
this.snippetService.post(this.snippet)
.subscribe(data => {
console.log('Snippet saved.');
this.snippet.id = data.snippet_id;
this.assignSnippet(idea.id);
},
err => {
this.notificationsService
.error('Oops', `There was problem saving your snippet. ${err.message}`);
this.saving = false;
});
}
private assignSnippet(idea_id: number) {
this.ideaService.assignSnippet(idea_id, this.snippet.id)
.subscribe(data => {
this.saving = false;
console.log('Snippet assigned to idea: ' + data.idea_snippet_id);
this.activeModal.close('Snippet saved.');
},
err => {
this.notificationsService
.error('Oops', `There was problem saving your snippet. ${err.message}`);
this.saving = false;
});
}
}
<file_sep>import { AfterViewInit, Component, ElementRef, EventEmitter, Input, Output } from '@angular/core';
import { SnippetMenuConfig } from './snippet-menu-config.model';
@Component({
selector: 'app-snippet-menu',
templateUrl: './snippet-menu.component.html',
styleUrls: ['./snippet-menu.component.css']
})
export class SnippetMenuComponent implements AfterViewInit {
private topOffset: number = 40;
private leftOffset: number = 175; //This is the offset of the column width.
@Input()
config: SnippetMenuConfig;
@Output()
onMakeSnippet = new EventEmitter<any>();
constructor(private element: ElementRef) {}
getTop(): string {
return `${this.config.top - this.topOffset}px`;
}
getLeft(): string {
return `${this.config.left}px`;
}
makeSnippet() {
this.onMakeSnippet.emit(true);
}
ngAfterViewInit() {
this.topOffset = (this.element.nativeElement.children.length > 0
&& this.element.nativeElement.children[0].clientHeight || this.topOffset);
}
}
<file_sep>export * from './card-footer-created.component';<file_sep>import { ModuleWithProviders, NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { InterviewsComponent } from './interviews.component';
import { InterviewFullComponent } from './interview-full/interview-full.component';
import { InterviewSlimComponent } from './interview-slim/interview-slim.component';
import { EditorComponent } from './editor/editor.component';
import { EditableInterviewResolver } from './editor/editable-interview-resolver.service';
import { SnippetDirective } from './snippets/snippet.directive';
import { SnippetMenuComponent } from './snippets/snippet-menu.component';
import { SnippetModalComponent } from './snippets/snippet-modal.component';
import { SharedModule, AuthGuardService } from '../shared';
const interviewsRoutes: Routes = [
{
path: 'interviews',
component: InterviewsComponent,
canActivate: [AuthGuardService]
},
{
path: 'interviews/edit/:id',
component: EditorComponent,
canActivate: [AuthGuardService],
resolve: {
interview: EditableInterviewResolver
}
},
{
path: 'interviews/add',
component: EditorComponent,
canActivate: [AuthGuardService]
}
];
const interviewsRouting: ModuleWithProviders = RouterModule.forChild(interviewsRoutes);
@NgModule({
imports: [
interviewsRouting,
SharedModule,
NgbModule
],
declarations: [
InterviewsComponent,
InterviewFullComponent,
InterviewSlimComponent,
EditorComponent,
SnippetDirective,
SnippetMenuComponent,
SnippetModalComponent
],
entryComponents: [ SnippetModalComponent ],
providers: [
AuthGuardService,
EditableInterviewResolver
]
})
export class InterviewsModule { }
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ApiService } from './api.service';
import { Interview, Customer } from '../models';
@Injectable()
export class InterviewService {
private apiPath = '/interviews/';
constructor(
private apiService: ApiService
) {}
get(): Observable<Interview[]> {
return this.apiService.get(`${this.apiPath}`)
.map(response => {
let result = <Interview[]>this.apiService.extractDatas(response);
return result; });
}
find(id: number): Observable<Interview> {
return this.apiService.get(`${this.apiPath}${id}`)
.map(response => {
let result = <Interview>this.apiService.extractData(response);
return result; });
}
put(interview: Interview): Observable<any> {
return this.apiService.put(`${this.apiPath}${interview.id}`, interview)
.map(data => data);
}
post(interview: Interview): Observable<any> {
return this.apiService.post(`${this.apiPath}`, interview)
.map(data => data);
}
delete(id: number): Observable<any> {
return this.apiService.delete(`${this.apiPath}${id}`)
.map(data => data);
}
customer(id: number): Observable<Customer> {
return this.apiService.get(`${this.apiPath}interview_customer/${id}`)
.map(data => {
data.assigned = true;
return data;
});
}
assign(id: number, customer_id: number): Observable<any> {
let postData: any = { 'interview_id': id, 'customer_id': customer_id };
return this.apiService.post(`${this.apiPath}interview_customer/`, postData)
.map(data => data);
}
}
<file_sep>import { BrowserModule } from '@angular/platform-browser';
import { ModuleWithProviders, NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
import {SimpleNotificationsModule, NotificationsService} from 'angular2-notifications';
import { AppComponent } from './app.component';
/* Import App Modules */
import { LoginModule } from './login/login.module';
import { DashboardModule } from './dashboard/dashboard.module';
import { IdeasModule } from './ideas/ideas.module';
import { InterviewsModule } from './interviews/interviews.module';
import {
ApiService,
AuthGuardService,
AuthResolverService,
CustomerService,
IdeaService,
InterviewService,
JwtService,
SharedModule,
SnippetService,
SideBarComponent,
UserService
} from './shared';
const rootRoutes: Routes = [
{
path: '', redirectTo: 'dashboard', pathMatch: 'full'
}
];
const rootRouting: ModuleWithProviders = RouterModule.forRoot(rootRoutes, { useHash: true });
@NgModule({
declarations: [
AppComponent,
SideBarComponent
],
imports: [
BrowserModule,
NgbModule.forRoot(),
SimpleNotificationsModule,
DashboardModule,
IdeasModule,
InterviewsModule,
LoginModule,
rootRouting,
SharedModule
],
providers: [
NotificationsService,
ApiService,
AuthGuardService,
AuthResolverService,
CustomerService,
IdeaService,
InterviewService,
JwtService,
SnippetService,
UserService
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>export class Dashboard {
idea_id: number;
idea_title: string;
idea_goal: string;
idea_status: string;
idea_create_user: number;
idea_create_datetime: string;
snippet_text: string;
snippet_create_datetime: string;
customer_first_name: string;
customer_last_name: string;
}
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ApiService } from './api.service';
import { Idea, Snippet } from '../models';
@Injectable()
export class IdeaService {
private apiPath = '/ideas/';
constructor(
private apiService: ApiService
) {}
get(): Observable<Idea[]> {
return this.apiService.get(`${this.apiPath}`)
.map(response => {
let result = <Idea[]>this.apiService.extractDatas(response);
return result; });
}
find(id: number): Observable<Idea> {
return this.apiService.get(`${this.apiPath}${id}`)
.map(response => {
let result = <Idea>this.apiService.extractData(response);
return result; });
}
put(idea: Idea): Observable<any> {
let update = {idea_id: idea.id, title: idea.title, goal: idea.goal, status: idea.status, update_user: idea.updated_by};
return this.apiService.put(`${this.apiPath}${idea.id}`, update)
.map(data => data);
}
post(idea: Idea): Observable<any> {
return this.apiService.post(`${this.apiPath}`, idea)
.map(data => data);
}
delete(id: number): Observable<any> {
return this.apiService.delete(`${this.apiPath}${id}`)
.map(data => data);
}
snippets(id: number): Observable<Snippet[]> {
return this.apiService.get(`${this.apiPath}idea_snippet/${id}`)
.map(response => {
let result = <Snippet[]>this.apiService.extractDatas(response);
return result; });
}
assignSnippet(idea_id: number, snippet_id: number): Observable<any> {
return this.apiService.post(`${this.apiPath}idea_snippet/`, {idea_id, snippet_id});
}
}
<file_sep>export class CustomerLookup {
person: {
id: string;
name: {
fullName: string;
givenName: string;
familyName: string;
};
email: string;
gender: string;
location: string;
timeZone: string;
utcOffset: number;
geo: {
city: string;
state: string;
stateCode: string;
country: string;
countryCode: string;
lat: number;
lng: number;
};
bio: string;
site: string;
avatar: string;
employment: {
domain: string;
name: string;
title: string;
role: string;
seniority: string;
};
facebook: {
handle: string;
};
github: {
handle: string;
id: string;
avatar: string;
company: string;
blog: string;
followers: string;
following: string;
};
twitter: {
handle: string;
id: number;
bio: string;
followers: number;
following: number;
statuses: number;
favorites: number;
location: string;
site: string;
avatar: string;
};
linkedin: {
handle: string;
};
googleplus: {
handle: string;
};
aboutme: {
handle: string;
bio: string;
avatar: string;
};
gravatar: {
handle: string;
urls: string[];
avatar: string;
avatars: string[];
};
fuzzy: boolean;
emailProvider: boolean;
};
company: {
id: string;
name: string;
legalName: string;
domain: string;
domainAliases: string[];
url: string;
site: {
url: string;
title: string;
h1: string;
metaDescription: string;
metaAuthor: string;
phoneNumbers: string[];
emailAddresses: string[];
};
category: {
sector: string;
industryGroup: string;
industry: string;
subIndustry: string;
};
tags: string[];
description: string;
foundedYear: number;
location: string;
timeZone: string;
utcOffset: number;
geo: {
streetNumber: string;
streetName: string;
subPremise: string;
city: string;
postalCode: string;
state: string;
stateCode: string;
country: string;
countryCode: string;
lat: number;
lng: number;
};
logo: string;
facebook: {
handle: string;
};
inkedin: {
handle: string;
};
twitter: {
handle: string;
id: string;
bio: string;
followers: number;
following: number;
location: string;
site: string;
avatar: string;
};
crunchbase: {
handle: string;
};
emailProvider: boolean;
type: string;
ticker: any;
phone: string;
metrics: {
alexaUsRank: number;
alexaGlobalRank: number;
googleRank: number;
employees: number;
employeesRange: string;
marketCap: any;
raised: number;
annualRevenue: any;
};
tech: string[];
};
}
<file_sep>import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NotificationsService } from 'angular2-notifications';
import { InterviewService } from '../services';
import { Interview, Customer } from '../models';
@Component({
selector: 'app-interview-preview',
templateUrl: './interview-preview.component.html',
styleUrls: ['./interview-preview.component.css']
})
export class InterviewPreviewComponent implements OnInit {
@Input() interview: Interview;
customer: Customer;
constructor(
private router: Router,
private interviewService: InterviewService,
private notificationsService: NotificationsService
) { }
ngOnInit() {
this.getMetaData();
}
getMetaData() {
this.interviewService.customer(this.interview.id)
.subscribe(
data => {
this.customer = data;
console.log(this.customer);
},
err => {
this.notificationsService
.error('Oops', `There was problem retrieving the customer for your "${this.interview.title}" interview. ${err.message}`);
}
);
}
goto() {
this.router.navigate(['/ideas', this.interview.id]);
};
}
<file_sep>export * from './interview-preview.component';<file_sep>import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { Headers, Http, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { JwtService } from './jwt.service';
import { User } from '../models/user.model';
import { ICreated } from '../models/created.interface';
@Injectable()
export class ApiService {
user: User;
constructor(
private http: Http,
private jwtService: JwtService
) {}
private setHeaders(): Headers {
let headersConfig = {
'Content-Type': 'application/json',
'Accept': 'application/json'
};
if (this.jwtService.getToken()) {
headersConfig['x-access-token'] = `${this.jwtService.getToken()}`;
}
return new Headers(headersConfig);
}
private formatErrors(error: any) {
return Observable.throw(error.json());
}
private setCreateUser(data: any): void {
if (this.user && this.user.id) {
data.create_user = this.user.id;
}
}
private setUpdateUser(data: any): void {
if (this.user && this.user.id) {
data.update_user = this.user.id;
}
}
extractDatas<t>(data: ICreated[]) {
data.forEach((d) => {
d.created_datetime = new Date(d.created_datetime);
});
return data;
}
extractData(data: ICreated) {
data.created_datetime = new Date(data.created_datetime);
return data;
}
getWithHeaders(path: string, headers: any): Observable<any> {
return this.http.get(`${environment.api_url}${path}`, { headers: new Headers(headers) })
.catch(this.formatErrors)
.map((res: Response) => res.json());
};
get(path: string, params: URLSearchParams = new URLSearchParams()): Observable<any> {
return this.http.get(`${environment.api_url}${path}`, { headers: this.setHeaders(), search: params })
.catch(this.formatErrors)
.map((res:Response) => res.json());
}
put(path: string, body: Object = {}): Observable<any> {
this.setUpdateUser(body);
return this.http.put(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res:Response) => res.json());
}
post(path: string, body: Object = {}): Observable<any> {
this.setCreateUser(body);
return this.http.post(
`${environment.api_url}${path}`,
JSON.stringify(body),
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res:Response) => res.json());
}
delete(path): Observable<any> {
return this.http.delete(
`${environment.api_url}${path}`,
{ headers: this.setHeaders() }
)
.catch(this.formatErrors)
.map((res:Response) => res.json());
}
}
<file_sep>export * from './customer-lookup.component';
<file_sep>export * from './card-helpers';
export * from './customer-lookup';
export * from './directives';
export * from './idea-helpers';
export * from './interview-helpers';
export * from './layout';
export * from './models';
export * from './services';
export * from './shared.module';
export * from './snippet-helpers';
<file_sep>export interface ICreated {
created_by: string;
created_datetime: Date;
created_image_link: string;
updated_by: string;
updated_datetime: Date;
updated_image_link: string;
}
<file_sep>import { ICreated } from './created.interface';
export class Customer implements ICreated {
id: number;
first_name: string;
last_name: string;
email: string;
image_link: string;
title: string;
company_name: string;
created_by: string;
created_datetime: Date;
created_image_link: string;
updated_by: string;
updated_datetime: Date;
updated_image_link: string;
success: boolean;
assigned: boolean;
found: boolean;
}
<file_sep>import { ICreated } from './created.interface';
export class Idea implements ICreated {
id: number;
title: string;
goal: string;
status: string;
created_by: string;
created_datetime: Date;
created_image_link: string;
updated_by: string;
updated_datetime: Date;
updated_image_link: string;
}
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { ApiService } from './api.service';
import { Customer } from '../models';
@Injectable()
export class CustomerService {
private apiPath = '/customers/';
constructor(
private apiService: ApiService
) {}
get(): Observable<Customer[]> {
return this.apiService.get(`${this.apiPath}`)
.map(response => {
let result = <Customer[]>this.apiService.extractDatas(response);
return result; });
}
find(id: number): Observable<Customer> {
return this.apiService.get(`${this.apiPath}${id}`)
.map(response => {
let result = <Customer>this.apiService.extractData(response);
return result; });
}
lookup(email: string): Observable<Customer> {
return this.apiService.get(`${this.apiPath}lookup/${email}`)
.map(data => {
if (data.success) {
return data;
} else {
throw data;
}
});
}
put(customer: Customer): Observable<any> {
let update = {
customer_id: customer.id,
first_name: customer.first_name,
last_name: customer.last_name,
email: customer.email,
image_link: customer.image_link,
updated_by: customer.updated_by
};
return this.apiService.put(`${this.apiPath}${customer.id}`, update)
.map(data => data);
}
post(customer: Customer): Observable<any> {
return this.apiService.post(`${this.apiPath}`, customer)
.map(data => data);
}
delete(id: number): Observable<any> {
return this.apiService.delete(`${this.apiPath}${id}`)
.map(data => data);
}
}
<file_sep>export * from './contenteditable-model.directive';
export * from './show-authed.directive';
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { NotificationsService } from 'angular2-notifications';
import { Customer, CustomerService, Interview, InterviewService, Snippet, UserService } from '../../shared';
import { SnippetMenuConfig } from '../snippets/snippet-menu-config.model';
import { SnippetModalComponent } from '../snippets/snippet-modal.component';
// todo: implement CanDeactivate https://angular.io/docs/ts/latest/guide/router.html#!#can-deactivate-guard
@Component({
selector: 'app-interview-editor',
templateUrl: './editor.component.html',
styleUrls: ['./editor.component.css']
})
export class EditorComponent implements OnInit {
search: string;
interview: Interview = new Interview();
customer: Customer = new Customer();
isSubmitting: boolean = false;
userId: any;
snippetMenuConfig: SnippetMenuConfig = new SnippetMenuConfig();
snippet: Snippet;
constructor(
private modalService: NgbModal,
private customerService: CustomerService,
private interviewService: InterviewService,
private userService: UserService,
private route: ActivatedRoute,
private router: Router,
private notificationsService: NotificationsService
) { }
ngOnInit() {
// load prefetched interview
this.route.data.subscribe(
(data: {interview: Interview}) => {
if (data.interview) {
this.interview = data.interview;
this.getMetaData();
}
}
);
this.userService.currentUser.subscribe(
user => {
if (this.interview && this.interview.id) {
this.interview.updated_by = user.username;
} else {
this.interview.created_by = user.username;
}
}
);
}
getMetaData() {
this.interviewService.customer(this.interview.id)
.subscribe(
data => {
this.customer = data;
this.search = data.email;
},
err => {
this.notificationsService
.error('Oops', `There was problem retrieving your "${this.interview.title}" interview. ${err.message}`);
}
);
}
save() {
// check if interview is new or exists.
let serviceCall: Observable<any>;
let insert: boolean;
if (this.interview && this.interview.id) {
serviceCall = this.interviewService.put(this.interview);
insert = false;
} else {
serviceCall = this.interviewService.post(this.interview);
insert = true;
}
serviceCall.subscribe(
data => {
console.log('interview saved.' + data);
this.interview.id = this.interview.id || data.interview_id;
if (insert) {
this.notificationsService.success('Saved', 'Interview saved successfully!');
} else {
this.notificationsService.success('Updated', 'Interview updated successfully!');
}
this.saveMetaData();
},
err => {
this.notificationsService
.error('Oops', `There was problem saving your "${this.interview.title}" interview. ${err.message}`);
}
);
}
saveMetaData() {
// check if customer is new.
if (this.customer && (!this.customer.hasOwnProperty('id') || this.customer.id === 0)) {
this.customerService.post(this.customer).subscribe(
data => {
console.log('customer saved.');
this.customer.id = data.customer_id;
this.assignCustomer(this.interview.id, this.customer.id);
},
err => {
this.notificationsService
.error('Oops', `There was problem saving your "${this.interview.title}" interview's customer. ${err.message}`);
}
);
} else if (this.customer && !this.customer.assigned) {
this.assignCustomer(this.interview.id, this.customer.id);
}
}
assignCustomer(interview_id: number, customer_id: number) {
this.interviewService.assign(interview_id, customer_id).subscribe(
data => {
console.log('customer assigned.');
this.customer.assigned = true;
},
err => {
this.notificationsService
.error('Oops', `There was problem saving your "${this.interview.title}" interview's customer. ${err.message}`);
}
);
}
snippetSelected(data: any) {
this.snippetMenuConfig.top = data.position.rect.top;
this.snippetMenuConfig.left = data.position.rect.left;
this.snippetMenuConfig.display = true;
this.snippet = new Snippet();
this.snippet.interview_id = this.interview.id;
this.snippet.text = data.text;
}
snippetDeselected() {
this.snippetMenuConfig.display = false;
}
makeSnippet(data: any) {
this.snippetMenuConfig.display = false;
const modalRef = this.modalService.open(SnippetModalComponent);
modalRef.componentInstance.snippet = this.snippet;
}
}
<file_sep>import { Directive, ElementRef, EventEmitter, HostBinding, HostListener, Input, OnChanges, OnInit, Output, SimpleChange } from '@angular/core';
//TODO: Rewrite this component. It is too buggy for input/outputs.
@Directive({
selector: '[contenteditableModel]'
})
export class ContenteditableModelDirective implements OnChanges, OnInit {
private valueSet: boolean = false;
private updatingModel = false;
@Input() contenteditableModel: string;
@Input() defaultValue: any;
@Output() contenteditableModelChange = new EventEmitter();
@HostBinding('attr.contenteditable') contenteditable = 'true';
@HostListener('focus') onFocus() {
if(this.defaultValue === this.getValue()) {
this.setValue('');
}
}
@HostListener('blur') onBlur() {
let value = this.getValue();
if (value) {
this.updatingModel = true;
this.contenteditableModel = value;
this.contenteditableModelChange.emit(value);
} else {
this.setValue(this.defaultValue);
}
}
constructor(private element: ElementRef) { console.log(`new ContenteditableModelDirective()`); }
ngOnInit() {
if (!this.valueSet) {
this.defaultValue = this.defaultValue || this.element.nativeElement.innerText || 'Just start typing...';
this.setValue(this.defaultValue);
}
}
ngOnChanges(changes: {[propKey: string]: SimpleChange}) {
if (!this.updatingModel) {
for (let propName in changes) {
if (changes.hasOwnProperty(propName) && propName === 'contenteditableModel') {
let changedProp = changes[propName];
this.setValue(changedProp.currentValue);
}
}
} else {
this.updatingModel = false;
}
}
private setValue(value: any) {
if (typeof value !== 'undefined' && this.getValue() !== value) {
this.element.nativeElement.innerText = value;
this.valueSet = true;
}
}
private getValue() {
return this.element.nativeElement.innerText;
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NotificationsService } from 'angular2-notifications';
import { Idea, IdeaService, Interview, InterviewService } from '../shared';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
ideas: Idea[];
interviews: Interview[];
constructor(
private router: Router,
private ideaService: IdeaService,
private interviewService: InterviewService,
private notificationsService: NotificationsService
) { }
gotoidea(idea: Idea) {
this.router.navigate(['/ideas/edit', idea.id]);
}
gotointerview(interview: Interview) {
this.router.navigate(['/interviews/edit', interview.id]);
}
ngOnInit() {
this.ideaService.get()
.subscribe(
data => {
this.ideas = data;
},
err => {
this.notificationsService.error('Oops', `There was problem retrieving your ideas. ${err.message}`);
}
);
this.interviewService.get()
.subscribe(
data => {
this.interviews = data;
console.log(this.interviews);
},
err => {
this.notificationsService.error('Oops', `There was problem retrieving your interviews. ${err.message}`);
}
);
}
}
<file_sep>import { Component, Input } from '@angular/core';
import { ICreated } from '../../shared/models/created.interface';
@Component({
selector: 'app-card-footer-created',
templateUrl: './card-footer-created.component.html',
styleUrls: ['./card-footer-created.component.css']
})
export class CardFooterCreatedComponent {
@Input() created: ICreated;
constructor() { }
}
<file_sep>import { CoppiaPage } from './app.po';
describe('coppia App', function() {
let page: CoppiaPage;
beforeEach(() => {
page = new CoppiaPage();
});
it('should display message saying coppia works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('Coppia works!');
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
import { UserService } from './shared';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
isAuthenticated: boolean = false;
notificationOptions = {
timeOut: 0,
lastOnBottom: true,
clickToClose: true,
maxLength: 0,
maxStack: 7,
showProgressBar: true,
pauseOnHover: true,
preventDuplicates: false,
preventLastDuplicates: 'visible',
rtl: false,
animate: 'scale',
position: ['top', 'right']
};
constructor (
private userService: UserService
) {}
ngOnInit() {
this.userService.isAuthenticated.subscribe(authenticated => { this.isAuthenticated = authenticated; });
this.userService.populate();
}
}
|
e095671f3f4371fc3692bbb8e699028cd5000c3a
|
[
"TypeScript"
] | 52 |
TypeScript
|
Coppia/saas-web
|
d2dec7b0690ec62f920152c658bb23310753aa8c
|
d74533239c49de14e8d1cb031e274c8cbe157444
|
refs/heads/master
|
<file_sep>package games.keno;
import java.util.ArrayList;
import java.util.Scanner;
public class KenoCLI
{
private final static int MAX_CARDS = 20;
static Keno keno;
public static void main(String[] args)
{
keno = new Keno(1000);
Scanner kb = new Scanner(System.in);
getCards(kb);
getBets(kb);
kb.close();
}
//get all bets from command line
private static void getBets(Scanner kb)
{
while(true)
{
boolean exited = getBet(kb);
if(exited) { break;}
}
}
//get single bet from command line
private static boolean getBet(Scanner kb)
{
//TODO handle invalid data
System.out.println("Enter bet or e to exit: ");
String input = kb.nextLine();
if(input.equalsIgnoreCase("e"))
{
return true;
}
else
{
try
{
int bet = Integer.parseInt(input);
System.out.println("Amount won: " + keno.play(bet));
}
catch(NumberFormatException e)
{
System.out.println("Invalid input");
}
}
System.out.println("Credits: " + keno.getCredits());
return false;
}
// adds multiple cards to keno game
private static void getCards(Scanner kb)
{
while(keno.getNumOfCards() < MAX_CARDS)
{
boolean exited = getCard(kb);
if(exited) {break;}
}
}
// gets user input to add a card to the game of keno
private static boolean getCard(Scanner kb)
{
System.out.println("Enter numbers on card " + (keno.getNumOfCards() + 1) + " separated by a space");
System.out.println("Enter e to exit");
String input = kb.nextLine();
Scanner parser = new Scanner(input);
ArrayList<Integer> shots = new ArrayList<Integer>();
boolean invalid = false;
while(parser.hasNext())
{
String str = parser.next();
// handle numbers
try
{
Integer num = Integer.parseInt(str);
if(num < 1 || num >= Keno.SIZE || shots.size() > Odds.MAX_SHOTS)
{
throw new NumberFormatException();
}
shots.add(num);
}
catch( NumberFormatException e)
{
//handle invalid input
if(str.equalsIgnoreCase("e"))
{
System.out.println("Exiting");
parser.close();
return true;
}
else
{
System.out.println("Invalid Input");
invalid = true;
}
break;
}
}
if(!invalid)
{
Card card = new Card(shots);
keno.addCard(card);
System.out.println(card);
}
parser.close();
return false;
}
}
<file_sep>package games.keno;
public class KenoTester
{
public static void main(String[] args)
{
Keno k = new Keno(4000000);
int[][] arr =
{
{34, 35, 36, 44, 45, 46},
{34, 35, 44, 45, 54, 55},
{35, 36, 45, 46, 55, 56},
{44, 45, 46, 54, 55, 56}
};
k.addCard(new Card(arr[0]));
k.addCard(new Card(arr[1]));
k.addCard(new Card(arr[2]));
k.addCard(new Card(arr[3]));
for(int i = 0; i < 1000000; i++)
{
k.play(2);
System.out.println(k.getCredits());
}
System.out.println(k.getCredits());
}
}
|
a6145ef995ab1dae7b71a71d9bca2d5f6a7feae7
|
[
"Java"
] | 2 |
Java
|
KevinYoung18/Keno
|
f7c750772f1ffbe0127949912cf826a2a8fd40ed
|
7eb3f4cc0fa2d64f72770957a8b73c3a968799ad
|
refs/heads/master
|
<repo_name>medstudioinc/Android-PathShapeView<file_sep>/app/src/main/java/demo/shape/path/view/samples/ShapeManager.kt
package demo.shape.path.view.samples
import android.graphics.Color
import android.graphics.PointF
import demo.shape.path.view.R
import shape.path.view.*
import shape.path.view.fill.provider.*
import shape.path.view.graph.function.CustomLinesBuilder
import shape.path.view.graph.function.WaveFunction
import shape.path.view.mark.Mark
import shape.path.view.point.converter.CoordinateConverter
import shape.path.view.point.converter.PercentagePointConverter
import kotlin.collections.ArrayList
/**
* Created by Gleb on 1/29/18.
*/
class ShapeManager {
fun getShapes(sample: Sample): List<PathShape> {
when (sample) {
Sample.SIMPLE_SHAPES -> return getSampleShapes()
Sample.CONTOUR_SAMPLE -> return getContourSamples()
Sample.GRADIENT_AND_TEXTURE_SAMPLE -> return getGradientSamples()
Sample.SHAPE_SET_SAMPLE -> return getSetOfShapeSamples()
Sample.POINT_CONVERTER_SAMPLE -> return getPointConverterSamples()
Sample.MARKS_SAMPLE -> return getMarksSamples()
Sample.TEXT_SAMPLE -> return getTextPathSamples()
Sample.FILL_WITH_EFFECTS_SAMPLE -> return getSampleEffects()
else -> {
return arrayListOf()
}
}
}
private fun getSampleShapes(): List<PathShape> {
//1st
var list = arrayListOf<PathShape>()
var pathProvider = PathProvider()
var points = ArrayList<PointF>()
points.add(PointF(0.1f, 0.9f))
points.add(PointF(0.5f, 0.1f))
points.add(PointF(0.9f, 0.9f))
pathProvider.putLines(points, true, PathProvider.PathOperation.ADD)
var body = BodyFillProvider()
body.setColor(Color.GRAY)
body.setRoundedCorners(30f)
var contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(10f)
contour.setRoundedCorners(30f)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
//2nd
pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(10f)
list.add(PathShape.create()
.setPath(pathProvider)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
//3rd
pathProvider = PathProvider()
pathProvider.putStar(PointF(0.5f, 0.5f), 0.4f, 0.3f, 0f,10, PathProvider.PathOperation.ADD)
body = BodyFillProvider()
body.setColor(Color.DKGRAY)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.setPointConverter(PercentagePointConverter()))
//4th
pathProvider = PathProvider()
pathProvider.putArc(PointF(0.5f, 0.5f), 0.9f, 0.7f, 30f, 230f, PathProvider.PathOperation.ADD)
contour = ContourFillProvider()
contour.setColor(Color.LTGRAY)
contour.setWidth(10f)
body = BodyFillProvider()
body.setColor(Color.BLUE)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
return list
}
private fun getContourSamples(): List<PathShape> {
var list = arrayListOf<PathShape>()
//1st
var pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
var body = BodyFillProvider()
body.setColor(Color.GRAY)
var contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
contour.addDotParams(20f, 20f)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
//2nd
pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
contour.addDotParams(20f, 40f)
contour.addDotParams(40f, 40f)
contour.addDotParams(40f, 40f)
contour.setIsDotRounded(true)
list.add(PathShape.create()
.setPath(pathProvider)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
//3rd
pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
body = BodyFillProvider()
body.setColor(Color.DKGRAY)
body.setRoundedCorners(50f)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
contour.addDotParams(40f, 20f)
contour.setRoundedCorners(50f)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
return list
}
private fun getGradientSamples(): List<PathShape> {
var list = arrayListOf<PathShape>()
//1st
var pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
var body = BodyFillProvider()
var gradient = GradientProvider()
gradient.addColor(Color.BLACK)
.addColor(Color.WHITE)
.addColor(Color.BLACK)
.setAngle(90f)
.setType(GradientProvider.Type.LINEAR)
body.setGradient(gradient)
var contour = ContourFillProvider()
contour.setWidth(20f)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.setPointConverter(PercentagePointConverter()))
//2nd
pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
contour = ContourFillProvider()
gradient = GradientProvider()
gradient.addColor(Color.BLACK)
.addColor(Color.WHITE)
.addColor(Color.BLACK)
.setType(GradientProvider.Type.RADIAL)
contour.setColor(Color.BLACK)
contour.setWidth(20f)
body = BodyFillProvider()
body.setGradient(gradient)
list.add(PathShape.create()
.setPath(pathProvider)
.fillContour(contour)
.fillBody(body)
.setPointConverter(PercentagePointConverter()))
//3rd
pathProvider = PathProvider()
pathProvider.putRoundRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, 0.2f, PathProvider.PathOperation.ADD)
gradient = GradientProvider()
gradient.addColor(Color.BLUE)
.addColor(Color.WHITE)
.addColor(Color.BLUE)
.setType(GradientProvider.Type.SWEEP)
body = BodyFillProvider()
body.setGradient(gradient)
gradient = GradientProvider()
gradient.addColor(Color.BLACK, 0f)
.addColor(Color.RED,0.1f)
.addColor(Color.WHITE,0.5f)
.addColor(Color.RED,0.9f)
.addColor(Color.BLACK,1f)
.setType(GradientProvider.Type.LINEAR)
contour = ContourFillProvider()
contour.setGradient(gradient)
contour.setWidth(100f)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
//4th
pathProvider = PathProvider()
pathProvider.putCircle(PointF(0.5f, 0.5f), 0.4f, PathProvider.PathOperation.ADD)
body = BodyFillProvider()
body.setColor(Color.CYAN)
body.setTexture(R.drawable.bridge)
body.setFillType(FillProvider.FillType.CLAMP)
body.fitTextureToSize(0.8f, 0.8f, true)
contour = ContourFillProvider()
contour.setWidth(100f)
contour.setTexture(R.mipmap.ic_launcher)
contour.fitTextureToSize(60f, 60f)
contour.setFillType(FillProvider.FillType.REPEAT)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
return list
}
private fun getPointConverterSamples(): List<PathShape> {
var list = arrayListOf<PathShape>()
//1st
var pathProvider = PathProvider()
pathProvider.putRect(PointF(200f, 200f), 100f, 100f, PathProvider.PathOperation.ADD)
var body = BodyFillProvider()
body.setColor(Color.LTGRAY)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body))
//2nd
pathProvider = PathProvider()
pathProvider.putRect(PointF(200f, 200f), 100f, 100f, PathProvider.PathOperation.ADD)
body = BodyFillProvider()
body.setColor(Color.LTGRAY)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.setPointConverter(CoordinateConverter(400f, 500f)))
//3rd
pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
body = BodyFillProvider()
body.setColor(Color.LTGRAY)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.setPointConverter(PercentagePointConverter()))
return list
}
private fun getSetOfShapeSamples(): List<PathShape> {
var list = arrayListOf<PathShape>()
//1st
var pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.6f, 1f, PathProvider.PathOperation.JOIN)
pathProvider.putOval(PointF(0.5f, 0.5f), 1f, 0.6f, PathProvider.PathOperation.JOIN)
var contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
var body = BodyFillProvider()
body.setColor(Color.LTGRAY)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
//2nd
pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.6f, 1f, PathProvider.PathOperation.INTERSECT)
pathProvider.putOval(PointF(0.5f, 0.5f), 1f, 0.6f, PathProvider.PathOperation.INTERSECT)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
body = BodyFillProvider()
body.setColor(Color.LTGRAY)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter())
)
//3rd
pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.6f, 1f, PathProvider.PathOperation.SUB)
pathProvider.putOval(PointF(0.5f, 0.5f), 1f, 0.6f, PathProvider.PathOperation.SUB)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
body = BodyFillProvider()
body.setColor(Color.LTGRAY)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter())
)
//4th
pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.6f, 0.9f, PathProvider.PathOperation.SUB_REVERSE)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.9f, 0.6f, PathProvider.PathOperation.SUB_REVERSE)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
body = BodyFillProvider()
body.setColor(Color.LTGRAY)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter())
)
return list
}
private fun getMarksSamples(): List<PathShape> {
var list = arrayListOf<PathShape>()
var points = ArrayList<PointF>()
points.add(PointF(0.1f, 0.9f))
points.add(PointF(0.5f, 0.1f))
points.add(PointF(0.9f, 0.9f))
//1st
var pathProvider = PathProvider()
pathProvider.putLines(points, true, PathProvider.PathOperation.ADD)
var contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
var mark = Mark()
mark.setDrawable(R.drawable.mark)
mark.setSelectedDrawable(R.drawable.mark_selected)
mark.fitDrawableToSize(50f,50f)
mark.setTouchBounds(100f, 100f)
mark.setCheckable(true)
mark.addPositions(points)
list.add(PathShape.create()
.setPath(pathProvider)
.fillContour(contour)
.addMark(mark)
.setPointConverter(PercentagePointConverter())
)
//2nd
points = ArrayList()
points.add(PointF(0.1f, 0.1f))
points.add(PointF(0.5f, 0.3f))
points.add(PointF(0.6f, 0.4f))
points.add(PointF(0.7f, 0.6f))
points.add(PointF(0.9f, 0.8f))
pathProvider = PathProvider()
pathProvider.putLines(points, false, PathProvider.PathOperation.ADD)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
mark = Mark()
mark.setDrawable(R.mipmap.ic_launcher)
mark.fitDrawableToSize(50f,50f)
mark.setTouchBounds(100f, 100f)
var tc = TextConfigurator()
tc.setTextColor(Color.BLUE)
tc.setStyle(TextConfigurator.Style.BOLD, TextConfigurator.Style.UNDERLINE)
tc.setTextSize(20f)
tc.setTextOffset(PointF(0f, -30f))
mark.setTextConfigurator(tc)
points.forEach { mark.addPosition(it, it.toString()) }
list.add(PathShape.create()
.setPath(pathProvider)
.fillContour(contour)
.addMark(mark)
.setPointConverter(PercentagePointConverter())
)
//3rd
points = ArrayList()
points.add(PointF(0.1f, 0.1f))
points.add(PointF(0.5f, 0.3f))
points.add(PointF(0.6f, 0.4f))
points.add(PointF(0.7f, 0.6f))
points.add(PointF(0.9f, 0.8f))
points.add(PointF(0.1f, 0.9f))
points.add(PointF(0.5f, 0.1f))
points.add(PointF(0.9f, 0.9f))
mark = Mark()
mark.setDrawable(R.mipmap.ic_launcher)
mark.fitDrawableToSize(50f,50f)
mark.setTouchBounds(100f, 100f)
mark.addPositions(points.subList(0,5))
mark.setId(1)
var mark2 = Mark()
mark2.setDrawable(R.drawable.mark)
mark2.fitDrawableToSize(50f,50f)
mark2.setTouchBounds(100f, 100f)
mark2.addPositions(points.subList(5,8))
mark2.setId(2)
pathProvider = PathProvider()
pathProvider.putLines(points, false, PathProvider.PathOperation.ADD)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
list.add(PathShape.create()
.setPath(pathProvider)
.fillContour(contour)
.addMark(mark)
.addMark(mark2)
.setPointConverter(PercentagePointConverter())
)
return list
}
private fun getTextPathSamples(): List<PathShape> {
var list = arrayListOf<PathShape>()
//1st
var pathProvider = PathProvider()
var tc = TextConfigurator()
tc.setStyle(TextConfigurator.Style.BOLD, TextConfigurator.Style.ITALIC)
pathProvider.putText(PointF(0.5f, 0.5f), 0.5f, 0.2f,"Hello!", tc, PathProvider.PathOperation.ADD)
var body = BodyFillProvider()
body.setColor(Color.LTGRAY)
var contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(5f)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
//2nd
pathProvider = PathProvider()
tc = TextConfigurator()
tc.setStyle(TextConfigurator.Style.UNDERLINE)
tc.setTextSize(50f)
pathProvider.putText(PointF(0.5f, 0.5f), 0.8f, 0.5f,"Hello!", tc, PathProvider.PathOperation.ADD)
var gradient = GradientProvider()
gradient.setLength(50f)
gradient.addColor(Color.BLUE)
.addColor(Color.WHITE)
.addColor(Color.BLUE)
.setType(GradientProvider.Type.RADIAL)
body = BodyFillProvider()
body.setGradient(gradient)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.setPointConverter(PercentagePointConverter())
)
//3rd
pathProvider = PathProvider()
tc = TextConfigurator()
tc.setStyle(TextConfigurator.Style.STRIKE)
tc.setTextSize(50f)
pathProvider.putText(PointF(0.5f, 0.5f), 0.8f, 0.5f,"Hello!", tc, PathProvider.PathOperation.ADD)
gradient = GradientProvider()
gradient.setLength(50f)
gradient.addColor(Color.RED)
.addColor(Color.WHITE)
.setType(GradientProvider.Type.LINEAR)
body = BodyFillProvider()
body.setGradient(gradient)
body.setRoundedCorners(30f)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(10f)
contour.addDotParams(15f, 15f)
contour.setIsDotRounded(true)
contour.setRoundedCorners(30f)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
return list
}
private fun getSampleEffects(): List<PathShape> {
//1st
var list = arrayListOf<PathShape>()
var pathProvider = PathProvider()
var points = ArrayList<PointF>()
points.add(PointF(0.1f, 0.9f))
points.add(PointF(0.5f, 0.1f))
points.add(PointF(0.9f, 0.9f))
pathProvider.putLines(points, true, PathProvider.PathOperation.ADD)
var body = BodyFillProvider()
body.setTexture(R.drawable.bridge)
body.fitTextureToSize(1f, 1f, true)
body.setFillType(FillProvider.FillType.CLAMP)
body.setRoundedCorners(30f)
var contour = ContourFillProvider()
contour.setColor(Color.BLUE)
contour.setWidth(10f)
contour.setRoundedCorners(30f)
contour.setGlowEffect(30f, FillProvider.GlowType.SOLID)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
//2nd
pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
body = BodyFillProvider()
body.setTexture(R.drawable.bridge)
body.fitTextureToSize(1f, 1f, true)
body.setFillType(FillProvider.FillType.CLAMP)
contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(30f)
contour.setGlowEffect(30f, FillProvider.GlowType.INNER)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
//3rd
pathProvider = PathProvider()
pathProvider.putOval(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
body = BodyFillProvider()
body.setTexture(R.drawable.bridge)
body.fitTextureToSize(1f, 1f, true)
body.setFillType(FillProvider.FillType.CLAMP)
body.setEmbossEffect(45f, FillProvider.EmbossType.NORMAL)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.setPointConverter(PercentagePointConverter()))
//4th
pathProvider = PathProvider()
pathProvider.putText(PointF(0.5f, 0.5f), 0.9f, 0.5f, "Hello!", TextConfigurator(), PathProvider.PathOperation.ADD)
contour = ContourFillProvider()
contour.setColor(Color.DKGRAY)
contour.setWidth(10f)
contour.setShadow(15f, 10f, 10f, Color.BLACK)
body = BodyFillProvider()
body.setTexture(R.drawable.bridge)
body.fitTextureToSize(1f, 1f, true)
body.setFillType(FillProvider.FillType.CLAMP)
list.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
return list
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/fill/provider/GradientProvider.kt
package shape.path.view.fill.provider
import android.graphics.*
import org.json.JSONObject
import shape.path.view.point.converter.PointConverter
import shape.path.view.utils.JSONUtils
import shape.path.view.utils.MathUtils
/**
* Created by root on 1/10/18.
*/
class GradientProvider {
private var type: Type = Type.LINEAR
private var angle: Float = 0f
private var colorList: ArrayList<Int> = arrayListOf()
private var percentageColorPositions: ArrayList<Float> = arrayListOf()
private var startPoint: PointF = PointF(0f, 0f)
private var isStartPointSet: Boolean = false
private var endPoint: PointF = PointF(0f, 0f)
internal var length: Float = 0f
companion object {
internal fun fromJson(json: JSONObject?): GradientProvider? {
if (json == null) return null
val gradient = GradientProvider()
val type = Type.fromString(json.optString("type"))
type?.let { gradient.setType(it) }
val angle = json.optDouble("angle", 0.0).toFloat()
gradient.setAngle(angle)
val length = json.optDouble("length", 0.0).toFloat()
gradient.setLength(length)
val startPoint = JSONUtils.jsonToPoint(json.optJSONObject("startPoint"), PointF(0f, 0f))
gradient.setStartPoint(startPoint!!)
val colors = json.optJSONArray("colors")
colors?.let {
for (i in 0 until it.length()) {
val item = it.optJSONObject(i)
if (item == null) continue
val color = Color.parseColor(item.optString("color"))
val percentage = item.optDouble("position")
if (percentage == Double.NaN) {
gradient.addColor(color)
}
else {
gradient.addColor(color, percentage.toFloat())
}
}
}
return gradient
}
}
enum class Type {
LINEAR,
RADIAL,
SWEEP;
companion object {
fun fromString(type: String?): Type? {
if (type.isNullOrEmpty()) return null
Type.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
fun setType(type: Type): GradientProvider {
this.type = type
return this
}
fun setAngle(angle: Float): GradientProvider {
this.angle = angle
return this
}
fun setLength(length: Float): GradientProvider {
this.length = length
return this
}
fun setStartPoint(startPoint: PointF): GradientProvider {
this.startPoint = startPoint
isStartPointSet = true
return this
}
fun addColor(color: Int): GradientProvider {
colorList.add(color)
return this
}
fun addColor(color: Int, colorPosition: Float): GradientProvider {
colorList.add(color)
percentageColorPositions.add(colorPosition)
return this
}
internal fun build(converter: PointConverter, tileMode: Shader.TileMode): Shader {
convertAllParams(converter)
val percentage: FloatArray? = if (percentageColorPositions.size < colorList.size) null else percentageColorPositions.toFloatArray()
return when(type) {
Type.LINEAR -> {
updateLinearValues(converter.screenWidth , converter.screenHeight)
LinearGradient(startPoint.x, startPoint.y, endPoint.x, endPoint.y, colorList.toIntArray(), percentage, tileMode)
}
Type.RADIAL -> {
updateRadialValues(converter.screenWidth, converter.screenHeight)
RadialGradient(startPoint.x, startPoint.y, length, colorList.toIntArray(), percentage, tileMode)
}
Type.SWEEP -> {
updateRadialValues(converter.screenWidth, converter.screenHeight)
SweepGradient(startPoint.x, startPoint.y, colorList.toIntArray(), percentage)
}
}
}
private fun updateRadialValues(width: Float, height: Float) {
if (!isStartPointSet) {
startPoint.x = width / 2
startPoint.y = height / 2
}
if (length == 0f) {
length = MathUtils.getLength(startPoint.x, startPoint.y, width, height)
}
}
private fun updateLinearValues(width: Float, height: Float) {
if (length == 0f) {
val p = MathUtils.getVectorEndPoint(angle, width, height)
length = MathUtils.getLength(0f, 0f, p.x, p.y)
}
endPoint = MathUtils.getVectorEndPoint(angle, length)
}
private fun convertAllParams(converter: PointConverter) {
if (isStartPointSet) {
startPoint = converter.convertPoint(startPoint)
}
}
}<file_sep>/app/src/main/java/demo/shape/path/view/MainActivity.kt
package demo.shape.path.view
import android.app.Fragment
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import demo.shape.path.view.fragment.JsonParserFragment
import demo.shape.path.view.fragment.custom.CustomShapeListFragment
import demo.shape.path.view.fragment.ShapeFragment
import demo.shape.path.view.samples.Sample
import demo.shape.path.view.samples.SampleAdapter
import demo.shape.path.view.samples.SampleItemHolder
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(), SampleItemHolder.OnItemClickListener {
var fragment: Fragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
sample_list.layoutManager = LinearLayoutManager(this)
sample_list.adapter = SampleAdapter(this)
}
override fun onItemClick(sample: Sample) {
var tag: String
when (sample) {
Sample.CUSTOM_SHAPE_LIST_SAMPLE -> {
fragment = CustomShapeListFragment.newInstance()
tag = CustomShapeListFragment::javaClass.name
}
Sample.JSON_PARSER_SAMPLE -> {
fragment = JsonParserFragment.newInstance()
tag = JsonParserFragment::javaClass.name
}
else -> {
fragment = ShapeFragment.newInstance(sample)
tag = ShapeFragment::javaClass.name
}
}
val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.add(R.id.container, fragment)
fragmentTransaction.addToBackStack(tag)
fragmentTransaction.commit()
}
override fun onBackPressed() {
if (fragmentManager.backStackEntryCount > 0) {
fragmentManager.popBackStack()
}
else {
super.onBackPressed()
}
}
}
<file_sep>/pathshapeview/src/main/java/shape/path/view/graph/function/WaveFunction.kt
package shape.path.view.graph.function
/**
* Created by root on 2/15/18.
*/
class WaveFunction(var waveWidth: Float, var waveHeight: Float, var waveType: WaveType): GraphFunction() {
enum class WaveType {
SINE {
override fun getFunction(waveWidth: Float, waveHeight: Float, xValue: Float, stepValue: Float): Float {
val k = 2.0f * Math.PI / waveWidth
return (waveHeight * Math.sin(k * xValue)).toFloat()
}
},
SINE_ARC {
override fun getFunction(waveWidth: Float, waveHeight: Float, xValue: Float, stepValue: Float): Float {
val k = Math.PI / waveWidth
return Math.abs(waveHeight * Math.sin(k * xValue)).toFloat()
}
},
SINE_ARC_REVERSE {
override fun getFunction(waveWidth: Float, waveHeight: Float, xValue: Float, stepValue: Float): Float {
val k = Math.PI / waveWidth
return -Math.abs(waveHeight * Math.cos(k * xValue)).toFloat()
}
},
SQUARE {
override fun getFunction(waveWidth: Float, waveHeight: Float, xValue: Float, stepValue: Float): Float {
val k = 2.0f * Math.PI / waveWidth
val f = Math.sin(k * xValue).toFloat()
return waveHeight * Math.signum(f)
}
},
TRIANGLE {
override fun getFunction(waveWidth: Float, waveHeight: Float, xValue: Float, stepValue: Float): Float {
val h = 2 * waveHeight
val k = h / waveWidth
return Math.abs((xValue * k) % (h) - waveHeight)
}
},
SAWTOOTH {
override fun getFunction(waveWidth: Float, waveHeight: Float, xValue: Float, stepValue: Float): Float {
val k = waveHeight / waveWidth
return (xValue * k) % waveHeight - waveHeight
}
};
internal abstract fun getFunction(waveWidth: Float, waveHeight: Float, xValue: Float, stepValue: Float): Float
companion object {
fun fromString(type: String?): WaveType? {
if (type.isNullOrEmpty()) return null
WaveType.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
init {
}
override fun onFunctionGetValue(xValue: Float, stepValue: Float, maxStepCount: Int): Float {
return waveType.getFunction(waveWidth, waveHeight, xValue, stepValue)
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/mark/MarkItem.kt
package shape.path.view.mark
import android.graphics.PointF
import android.graphics.RectF
import shape.path.view.point.converter.PointConverter
/**
* Created by root on 2/1/18.
*/
class MarkItem {
var index: Int = 0
var position: PointF = PointF(0f, 0f)
var label: String? = null
var bounds = RectF()
var isSelected = false
internal fun build(pointConverter: PointConverter, touchWidth: Float,touchHeight: Float) {
position = pointConverter.convertPoint(position)
setBounds(touchWidth, touchHeight)
}
private fun setBounds(width: Float, height: Float) {
if (width > 0f && height > 0f) {
bounds.left = position.x - width / 2
bounds.right = position.x + width / 2
bounds.top = position.y - height / 2
bounds.bottom = position.y + height / 2
}
}
internal fun isInBounds(x: Float, y: Float): Boolean {
return bounds.contains(x, y)
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/parser/PathParser.kt
package shape.path.view.parser
import android.content.Context
import android.graphics.PointF
import org.json.JSONObject
import shape.path.view.PathProvider
import shape.path.view.TextConfigurator
import shape.path.view.graph.function.CustomLinesBuilder
import shape.path.view.utils.JSONUtils
/**
* Created by root on 3/15/18.
*/
class PathParser {
enum class ShapeType {
LINES,
ARC,
OVAL,
CIRCLE,
POLY,
STAR,
TEXT,
RECT,
ROUND_RECT,
CUSTOM_SHAPE;
companion object {
fun fromString(type: String?): ShapeType? {
if (type.isNullOrEmpty()) return null
ShapeType.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
companion object {
internal fun fromJson(context: Context, json: JSONObject?): PathProvider? {
if (json == null) return null
val parser = PathParser()
return parser.toPathProvider(context, json)
}
}
internal fun toPathProvider(context: Context, json: JSONObject): PathProvider {
val result = PathProvider()
val shapes = json.optJSONArray("shapes")
shapes?.let {
for (i in 0 until shapes.length()) {
putShape(context, result, shapes.optJSONObject(i))
}
}
return result
}
private fun putShape(context: Context, pathProvider: PathProvider, json: JSONObject?) {
if (json == null) return
val type = ShapeType.fromString(json.optString("shapeType"))
val operation = PathProvider.PathOperation.fromString(json.optString("pathOperation"))
operation?.let {
when (type) {
ShapeType.LINES -> {
val array = json.optJSONArray("lines") ?: return
val lines = arrayListOf<PointF>()
for (i in 0 until array.length()) {
val point = JSONUtils.jsonToPoint(array.optJSONObject(i))
point?.let { lines.add(point) }
}
val isClosed = json.optBoolean("isClosed", false)
pathProvider.putLines(lines, isClosed, operation)
}
ShapeType.ARC -> {
val centerPoint = JSONUtils.jsonToPoint(json.optJSONObject("centerPoint")) ?: return
val w = json.optDouble("width", 0.0).toFloat()
val h = json.optDouble("height", 0.0).toFloat()
val startAngle = json.optDouble("startAngle", 0.0).toFloat()
val sweepAngle = json.optDouble("sweepAngle", 0.0).toFloat()
pathProvider.putArc(centerPoint, w, h, startAngle, sweepAngle, operation)
}
ShapeType.OVAL -> {
val centerPoint = JSONUtils.jsonToPoint(json.optJSONObject("centerPoint")) ?: return
val w = json.optDouble("width", 0.0).toFloat()
val h = json.optDouble("height", 0.0).toFloat()
pathProvider.putOval(centerPoint, w, h, operation)
}
ShapeType.CIRCLE -> {
val centerPoint = JSONUtils.jsonToPoint(json.optJSONObject("centerPoint")) ?: return
val r = json.optDouble("radius", 0.0).toFloat()
pathProvider.putCircle(centerPoint, r, operation)
}
ShapeType.POLY -> {
val centerPoint = JSONUtils.jsonToPoint(json.optJSONObject("centerPoint")) ?: return
val r = json.optDouble("radius", 0.0).toFloat()
val a = json.optDouble("angleRotation", 0.0).toFloat()
val c = json.optInt("sidesCount", 0)
pathProvider.putPoly(centerPoint, r, a, c, operation)
}
ShapeType.STAR -> {
val centerPoint = JSONUtils.jsonToPoint(json.optJSONObject("centerPoint")) ?: return
val innerR = json.optDouble("innerRadius", 0.0).toFloat()
val outerR = json.optDouble("outerRadius", 0.0).toFloat()
val a = json.optDouble("angleRotation", 0.0).toFloat()
val c = json.optInt("sidesCount", 0)
pathProvider.putStar(centerPoint, outerR, innerR, a, c, operation)
}
ShapeType.RECT -> {
val centerPoint = JSONUtils.jsonToPoint(json.optJSONObject("centerPoint")) ?: return
val w = json.optDouble("width", 0.0).toFloat()
val h = json.optDouble("height", 0.0).toFloat()
pathProvider.putRect(centerPoint, w, h, operation)
}
ShapeType.ROUND_RECT -> {
val centerPoint = JSONUtils.jsonToPoint(json.optJSONObject("centerPoint")) ?: return
val w = json.optDouble("width", 0.0).toFloat()
val h = json.optDouble("height", 0.0).toFloat()
val r = json.optDouble("cornerRadius", 0.0).toFloat()
pathProvider.putRoundRect(centerPoint, w, h, r, operation)
}
ShapeType.TEXT -> {
val centerPoint = JSONUtils.jsonToPoint(json.optJSONObject("centerPoint")) ?: return
val w = json.optDouble("width", 0.0).toFloat()
val h = json.optDouble("height", 0.0).toFloat()
val text = json.optString("text")
val tc = TextConfigurator.fromJson(context, json.optJSONObject("textConfigurator"))
if (tc == null || text.isNullOrEmpty()) return
pathProvider.putText(centerPoint, w, h, text, tc, operation)
}
ShapeType.CUSTOM_SHAPE -> {
val linesBuilder = CustomLinesBuilder.fromJson(json)
if (linesBuilder == null) return
pathProvider.putCustomShape(linesBuilder, operation)
}
}
}
}
}
<file_sep>/app/src/main/java/demo/shape/path/view/fragment/custom/CustomShapeAdapter.kt
package demo.shape.path.view.fragment.custom
import android.content.Context
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import demo.shape.path.view.R
import shape.path.view.PathProvider
import shape.path.view.PathShape
import shape.path.view.fill.provider.BodyFillProvider
import shape.path.view.fill.provider.GradientProvider
import shape.path.view.graph.function.CustomLinesBuilder
import shape.path.view.graph.function.WaveFunction
import shape.path.view.point.converter.PercentagePointConverter
/**
* Created by Gleb on 1/26/18.
*/
class CustomShapeAdapter(var context: Context): RecyclerView.Adapter<CustomShapeItemHolder>() {
val items: ArrayList<PathShape> = arrayListOf()
init {
WaveFunction.WaveType.values().forEach {
val pathProvider = PathProvider()
val f = WaveFunction(0.2f, 0.1f, it)
f.offset(0f, 0.85f)
val shape = CustomLinesBuilder()
shape.addGraphPoints( 0f, 1f, -1f, 1f, f)
shape.addPoint(1f, 0f)
shape.addPoint(0f, 0f)
shape.setClosed(true)
pathProvider.putCustomShape(shape, PathProvider.PathOperation.ADD)
val body = BodyFillProvider()
val gradient = GradientProvider()
gradient.addColor(Color.LTGRAY)
gradient.addColor(ContextCompat.getColor(context, R.color.colorAccent))
gradient.setAngle(90f)
body.setGradient(gradient)
body.setRoundedCorners(30f)
items.add(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.setPointConverter(PercentagePointConverter()))
}
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: CustomShapeItemHolder, position: Int) {
holder.bind(items[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomShapeItemHolder {
return CustomShapeItemHolder.newInstance(parent)
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/fill/provider/ContourFillProvider.kt
package shape.path.view.fill.provider
import android.content.Context
import android.graphics.*
import org.json.JSONObject
/**
* Created by root on 1/10/18.
*/
class ContourFillProvider: FillProvider() {
private var dotParams: ArrayList<Float> = arrayListOf()
companion object {
internal fun fromJson(context: Context, json: JSONObject?): ContourFillProvider? {
if (json == null) return null
val provider = ContourFillProvider()
provider.fromJson(context, json)
return provider
}
}
init {
paint.style = Paint.Style.STROKE
}
fun setWidth(width: Float) {
paint.strokeWidth = width
}
fun setIsDotRounded(isDotRounded: Boolean) {
if (isDotRounded) {
paint.strokeCap = Paint.Cap.ROUND
}
else {
paint.strokeCap = Paint.Cap.BUTT
}
}
fun addDotParams(dotLength: Float, dotDistance: Float) {
dotParams.add(dotLength)
dotParams.add(dotDistance)
pathEffectChanged = true
}
override fun buildEffect(): PathEffect? {
if (dotParams.isEmpty()) {
return super.buildEffect()
}
else {
val dashPathEffect = DashPathEffect(getDots(), 0f)
val effect = super.buildEffect()
if (effect == null) {
return dashPathEffect
}
else {
return ComposePathEffect(dashPathEffect, effect)
}
}
}
private fun getDots(): FloatArray {
if (paint.strokeCap == Paint.Cap.ROUND) {
val array = FloatArray(dotParams.size)
for (i in 0 until dotParams.size) {
if ((i + 1) % 2 == 1) {
array[i] = getDotLength(dotParams[i])
}
else {
array[i] = dotParams[i]
}
}
return array
}
return dotParams.toFloatArray()
}
private fun getDotLength(length: Float): Float {
var l = length - paint.strokeWidth
if (l < 0f) {
l = 0f
}
return l
}
override fun fromJson(context: Context, json: JSONObject) {
super.fromJson(context, json)
setWidth(json.optDouble("width", 0.0).toFloat())
setIsDotRounded(json.optBoolean("isDotRounded", false))
val params = json.optJSONArray("dotParams")
if (params != null) {
for (i in 0 until params.length()) {
val item = params.optJSONObject(i)
if (item == null) continue
val length = item.optDouble("length", 0.0).toFloat()
val distance = item.optDouble("distance", 0.0).toFloat()
addDotParams(length, distance)
}
}
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/point/converter/CoordinateConverter.kt
package shape.path.view.point.converter
import android.graphics.Matrix
/**
* Created by root on 1/9/18.
*/
class CoordinateConverter(var originScreenW: Float, var originScreenH: Float) : PointConverter() {
private var screenScaleFactorX = 1f
private var screenScaleFactorY = 1f
override fun setScreenSize(screenWidth: Float, screenHeight: Float) {
super.setScreenSize(screenWidth, screenHeight)
screenScaleFactorX = screenWidth / originScreenW
screenScaleFactorY = screenHeight / originScreenH
matrix.setScale(screenScaleFactorX, screenScaleFactorY)
}
override fun getMatrix(): Matrix {
return matrix
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/PathProvider.kt
package shape.path.view
import android.annotation.TargetApi
import android.graphics.Matrix
import android.graphics.Path
import android.graphics.PointF
import android.graphics.RectF
import android.os.Build
import shape.path.view.graph.function.CustomLinesBuilder
import shape.path.view.point.converter.PointConverter
/**
* Created by root on 1/9/18.
*/
class PathProvider {
private val path: Path = Path()
internal var shapePath: Path? = null
enum class PathOperation {
ADD,
SUB,
SUB_REVERSE,
JOIN,
INTERSECT,
XOR;
companion object {
fun fromString(type: String?): PathOperation? {
if (type.isNullOrEmpty()) return null
PathOperation.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
fun putLines(list: List<PointF>, isClosed:Boolean, operation: PathOperation) {
if (list.isNotEmpty()) {
val p = Path()
p.moveTo(list[0].x, list[0].y)
for (i in 1 until list.size) {
p.lineTo(list[i].x, list[i].y)
}
if (isClosed) {
p.close()
}
putPath(p, operation)
}
}
fun putCustomShape(customLinesBuilder: CustomLinesBuilder, operation: PathOperation) {
putPath(customLinesBuilder.getPath(), operation)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun putArc(centerPoint: PointF, width:Float, height:Float, startAngle: Float, sweepAngle: Float, operation: PathOperation) {
val p = Path()
val left = centerPoint.x - width / 2
val top = centerPoint.y - height / 2
val right = centerPoint.x + width / 2
val bottom = centerPoint.y + height / 2
val start = PointF(left, top)
val end = PointF(right, bottom)
p.addArc(start.x, start.y, end.x, end.y, startAngle, sweepAngle)
putPath(p, operation)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun putOval(centerPoint: PointF, width:Float, height:Float, operation: PathOperation) {
val p = Path()
val left = centerPoint.x - width / 2
val top = centerPoint.y - height / 2
val right = centerPoint.x + width / 2
val bottom = centerPoint.y + height / 2
val start = PointF(left, top)
val end = PointF(right, bottom)
p.addOval(start.x, start.y, end.x, end.y, Path.Direction.CCW)
putPath(p, operation)
}
fun putCircle(centerPoint: PointF, radius:Float, operation: PathOperation) {
val p = Path()
p.addCircle(centerPoint.x, centerPoint.y, radius, Path.Direction.CCW)
putPath(p, operation)
}
fun putPoly(centerPoint: PointF, radius:Float, angleRotation: Float, sidesCount:Int, operation: PathOperation) {
if (sidesCount < 3) {
return
}
val p = Path()
val a = Math.toRadians(angleRotation.toDouble())
for (i in 0 until sidesCount) {
val x = (Math.sin( i.toDouble() / sidesCount * 2 * Math.PI + a) * radius).toFloat() + centerPoint.x
val y = (Math.cos( i.toDouble() / sidesCount * 2 * Math.PI + a) * radius).toFloat() + centerPoint.y
if (i == 0) {
p.moveTo(x, y)
}
else {
p.lineTo(x, y)
}
}
p.close()
putPath(p, operation)
}
fun putStar(centerPoint: PointF, outerRadius:Float, innerRadius: Float, angleRotation: Float, sidesCount:Int, operation: PathOperation) {
if (sidesCount < 3) {
return
}
val p = Path()
val rotation = Math.toRadians(angleRotation.toDouble())
val angle = (2 * Math.PI) / sidesCount
val n = 2 * sidesCount
var innerStep = 0
var outerStep = 0
for(i in 0 until n) {
val k = i % 2
var omega: Double
var r: Float
if (k == 0) {
omega = angle * outerStep + rotation
r = outerRadius
outerStep++
}
else {
omega = angle * innerStep + angle / 2 + rotation
r = innerRadius
innerStep++
}
val x = r * Math.sin(omega).toFloat() + centerPoint.x
val y = r * Math.cos(omega).toFloat() + centerPoint.y
if (i == 0) {
p.moveTo(x, y)
}
else {
p.lineTo(x, y)
}
}
p.close()
putPath(p, operation)
}
fun putText(centerPoint: PointF, width: Float, height: Float, text: String, textConfigurator: TextConfigurator, operation: PathOperation) {
val p = textConfigurator.getPath(text, centerPoint, width, height)
putPath(p, operation)
}
fun putRect(centerPoint: PointF, width:Float, height:Float, operation: PathOperation) {
val p = Path()
val left = centerPoint.x - width / 2
val top = centerPoint.y - height / 2
val right = centerPoint.x + width / 2
val bottom = centerPoint.y + height / 2
val start = PointF(left, top)
val end = PointF(right, bottom)
p.addRect(start.x, start.y, end.x, end.y, Path.Direction.CCW)
putPath(p, operation)
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun putRoundRect(centerPoint: PointF, width:Float, height:Float, cornerRadius: Float, operation: PathOperation) {
val p = Path()
val left = centerPoint.x - width / 2
val top = centerPoint.y - height / 2
val right = centerPoint.x + width / 2
val bottom = centerPoint.y + height / 2
val start = PointF(left, top)
val end = PointF(right, bottom)
p.addRoundRect(start.x, start.y, end.x, end.y, cornerRadius * 1.5f, cornerRadius, Path.Direction.CCW)
putPath(p, operation)
}
fun reset() {
path.reset()
shapePath = null
}
private fun putPath(p: Path, operation: PathOperation) {
when (operation) {
PathOperation.ADD -> path.addPath(p)
PathOperation.INTERSECT -> path.op(p, Path.Op.INTERSECT)
PathOperation.SUB -> path.op(p, Path.Op.DIFFERENCE)
PathOperation.SUB_REVERSE -> path.op(p, Path.Op.REVERSE_DIFFERENCE)
PathOperation.JOIN -> path.op(p, Path.Op.UNION)
PathOperation.XOR -> path.op(p, Path.Op.XOR)
}
}
internal fun build(converter: PointConverter) {
this.build(converter, 0f)
}
internal fun build(converter: PointConverter, contourWidth: Float) {
val m = converter.getMatrix()
shapePath = Path(path)
if (!m.isIdentity) {
shapePath!!.transform(m)
}
fitContourPath(converter.screenWidth, converter.screenHeight, contourWidth)
}
private fun fitContourPath(screenWidth: Float, screenHeight: Float, contourWidth: Float) {
if (contourWidth >= 0f) {
val d = contourWidth / 2
val r1 = RectF(0f, 0f, screenWidth, screenHeight)
val r2 = RectF(d, d, screenWidth - d, screenHeight - d)
val matrix = Matrix()
matrix.setRectToRect(r1, r2, Matrix.ScaleToFit.FILL)
shapePath?.transform(matrix)
}
}
internal fun hasPath(): Boolean {
return shapePath != null
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/TextConfigurator.kt
package shape.path.view
import android.content.Context
import android.graphics.*
import android.text.TextPaint
import org.json.JSONObject
import shape.path.view.utils.JSONUtils
/**
* Created by root on 1/25/18.
*/
class TextConfigurator {
internal val paint: TextPaint = TextPaint(Paint.ANTI_ALIAS_FLAG)
internal var textOffset: PointF = PointF(0f, 0f)
enum class Style {
BOLD,
UNDERLINE,
STRIKE,
SUB_PIXEL,
ITALIC;
companion object {
fun fromString(type: String?): Style? {
if (type.isNullOrEmpty()) return null
Style.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
companion object {
internal fun fromJson(context:Context, json: JSONObject?):TextConfigurator? {
if (json == null) return null
val tc = TextConfigurator()
val stylesArr = json.optJSONArray("styles")
stylesArr?.let {
val styles: Array<Style?> = arrayOfNulls(stylesArr.length())
for (i in 0 until stylesArr.length()) {
styles[i] = Style.fromString(stylesArr.optString(i))
}
tc.setStyle(*styles)
}
val offset = JSONUtils.jsonToPoint(json.optJSONObject("textOffset")) ?: PointF(0f, 0f)
val size = json.optDouble("size", 0.0).toFloat()
val color = json.optInt("color", 0)
val typeface = JSONUtils.jsonToTypeface(context, json)
tc.setTextOffset(offset)
tc.setTextSize(size)
tc.setTextColor(color)
tc.setTypeface(typeface)
return tc
}
}
init {
paint.style = Paint.Style.FILL_AND_STROKE
paint.textAlign = Paint.Align.CENTER
paint.typeface = Typeface.DEFAULT
//paint.strokeWidth = 30f
}
fun setTextSize(size: Float) {
paint.textSize = size
}
fun setTextColor(color: Int) {
paint.color = color
}
fun setTypeface(typeface: Typeface) {
paint.typeface = typeface
}
fun setTextOffset(offset: PointF) {
textOffset = offset
}
fun setStyle(vararg style: Style?) {
paint.isFakeBoldText = false
paint.isUnderlineText = false
paint.isStrikeThruText = false
paint.isSubpixelText = false
paint.textSkewX = 0f
style.forEach {
if (it == null) return@forEach
when(it) {
Style.BOLD -> paint.isFakeBoldText = true
Style.UNDERLINE -> paint.isUnderlineText = true
Style.STRIKE -> paint.isStrikeThruText = true
Style.SUB_PIXEL -> paint.isSubpixelText = true
Style.ITALIC -> paint.textSkewX = -0.2f
}
}
}
internal fun getPath(text: String, position: PointF, textWidth: Float, textHeight: Float): Path {
val path = Path()
if (text.isNotEmpty()) {
val x = position.x
val y = position.y
paint.getTextPath(text, 0, text.length, 0f, 0f, path)
val bounds = Rect()
paint.getTextBounds(text, 0, text.length, bounds)
bounds.offsetTo(0, 0)
val currentBounds = RectF(bounds)
val matrix = Matrix()
val newBounds = RectF(x, y, textWidth + x, textHeight + y)
matrix.setRectToRect(currentBounds, newBounds, Matrix.ScaleToFit.CENTER)
path.transform(matrix)
}
return path
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/point/converter/PercentagePointConverter.kt
package shape.path.view.point.converter
import android.graphics.Matrix
/**
* Created by root on 1/9/18.
*/
class PercentagePointConverter: PointConverter() {
override fun setScreenSize(screenWidth: Float, screenHeight: Float) {
super.setScreenSize(screenWidth, screenHeight)
matrix.setScale(screenWidth, screenHeight)
}
override fun getMatrix(): Matrix {
return matrix
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/utils/BitmapUtils.kt
package shape.path.view.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.support.v4.content.res.ResourcesCompat
/**
* Created by root on 2/13/18.
*/
class BitmapUtils {
companion object {
internal fun loadBitmap(context: Context, bitmap: Bitmap?, resId: Int, reqWidth: Float, reqHeight: Float): Bitmap? {
if (bitmap == null && resId == -1) {
return null
}
var result = bitmap
try {
if (result == null) {
val drawable = ResourcesCompat.getDrawable(context.resources, resId, null)
if (drawable != null) {
result = drawableToBitmap(drawable, reqWidth, reqHeight)
}
}
else {
val w = reqWidth.toInt()
val h = reqHeight.toInt()
if (reqWidth > 0 && reqHeight > 0 && (result.width != w || result.height != h)) {
result = scaleBitmap(result, w, h, false)
}
}
}
catch (e: OutOfMemoryError) {
e.printStackTrace()
}
catch (e: Error) {
e.printStackTrace()
}
return result
}
private fun drawableToBitmap(drawable: Drawable, width: Float, height: Float): Bitmap? {
val w = if (width > 0) width.toInt() else drawable.intrinsicWidth
val h = if (height > 0) height.toInt() else drawable.intrinsicHeight
if (w <= 0 || h <= 0) {
return null
}
if (drawable is BitmapDrawable) {
if (w == drawable.intrinsicWidth && h == drawable.intrinsicHeight) {
return drawable.bitmap
}
return scaleBitmap(drawable.bitmap, w, h, true)
}
val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
private fun scaleBitmap(bm: Bitmap, newWidth: Int, newHeight: Int, keepOrigin: Boolean): Bitmap {
val width = bm.width
val height = bm.height
val scaleWidth = newWidth.toFloat() / width.toFloat()
val scaleHeight = newHeight.toFloat() / height.toFloat()
val matrix = Matrix()
matrix.postScale(scaleWidth, scaleHeight)
val resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false)
if (!keepOrigin) {
bm.recycle()
}
return resizedBitmap
}
}
}
<file_sep>/README.md
# Android-PathShapeView
[](https://jitpack.io/#gleb8k/Android-PathShapeView)
[](https://github.com/gleb8k/Android-PathShapeView/blob/master/LICENSE)
This library allows to draw different shapes, lines, marks easily. It's customizable and provides posibility to fill your custom shapes by color, gradient or texture. Also you can fill just by stroke with color, gradient or texture. If you want to add some labels or marks on your shapes or lines it's not difficult with this toolbox.
## Table of Contents:
* **[Setup](#setup)**
* **[Usage](#usage)**
* **[Samples](#samples)**
* **[License](#license)**
## Setup
Add it in your root `build.gradle` at the end of repositories:
```gradle
allprojects {
repositories {
// ... other repositories
maven { url "https://jitpack.io" }
}
}
```
Then add the dependencies that you need in your project.
```gradle
dependencies {
compile 'com.github.gleb8k:Android-PathShapeView:1.3.2'
}
```
## Usage
The main class to show your graphic items is **PathShapeView**
You can create it and attach to your root view:
```kotlin
val pathShapeView = PathShapeView(context: Context)
...
```
Or inflate from xml:
```xml
<shape.path.view.PathShapeView
android:id="@+id/path"
android:layout_width="match_parent"
android:layout_height="match_parent">
...
```
Use *PathShape* class to config graphic items
```kotlin
val pathShape = PathShape.create()
...
//or load from .json
val pathShape = PathShape.fromAsset(context, fileName)
...
pathShapeView.setPath(pathShape)
...
```
Or add *assetShapeResource* attribute to PathShapeView in xml
```xml
...
xmlns:app="http://schemas.android.com/apk/res-auto"
...
<shape.path.view.PathShapeView
android:id="@+id/path"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:assetShapeResource="pathShape.json">
...
```
Here is a [sample of file format in json](https://github.com/gleb8k/Android-PathShapeView/blob/master/app/src/main/assets/pathShape.json)
* **PathProvider** - is the main class which allow to create different graphic items. Each item can be added with the logical operation (**PathOperation**: ADD, SUB, SUB_REVERSE, JOIN, INTERSECT, XOR)
Just to simple add item use **ADD** operation.
There are several items which you can create:
- **putLines(list: List<PointF>, isClosed:Boolean, operation: PathOperation)** - add lines by list of points,
**isClosed** - allows to close the current contour.
- **putArc(centerPoint: PointF, width:Float, height:Float, startAngle: Float, sweepAngle: Float, operation: PathOperation)** - add arc to the path as a new contour
- **putOval(centerPoint: PointF, width:Float, height:Float, operation: PathOperation)** - add a closed oval contour
- **putCircle(centerPoint: PointF, radius:Float, operation: PathOperation)** - add a closed circle contour
- **putPoly(centerPoint: PointF, radius:Float, angleRotation: Float, sidesCount:Int, operation: PathOperation)** -
add equilateral polygon
- **putStar(centerPoint: PointF, outerRadius:Float, innerRadius: Float, angleRotation: Float, sidesCount:Int, operation: PathOperation)** - add star shape
- **putRect(centerPoint: PointF, width:Float, height:Float, operation: PathOperation)** - add a closed rectangle contour
- **putRoundRect(centerPoint: PointF, width:Float, height:Float, cornerRadius: Float, operation: PathOperation)** - add a closed round-rectangle contour
- **putText(centerPoint: PointF, width: Float, height: Float, text: String, textConfigurator: TextConfigurator, operation: PathOperation)** - add text
- **putCustomShape(customLinesBuilder: CustomLinesBuilder, operation: PathOperation)** - add **customLinesBuilder** object
* **CustomLinesBuilder** - class which helps to create custom lines by points or by function
- **addPoint(x: Float, y: Float)** - add new point
- **addGraphPoints(minX: Float, maxX: Float, minY: Float, maxY: Float, function: GraphFunction)** - add points created by function and limited by bounds: minX, maxX, minY, maxY.
- **setClosed(isClosed: Boolean)** - close the current contour
* **GraphFunction** - abstract class which provide function
- **onFunctionGetValue(xValue: Float, stepValue: Float, maxStepCount: Int): Float** - return function value
- **offset(dx: Float, dy: Float)** - offset current point by distance
- **rotate(angle: Float)** - rotate current point by angle
- **skew(kx: Float, ky: Float)** - skew current point by coefficients
* **WaveFunction(var waveWidth: Float, var waveHeight: Float, var waveType: WaveType)** - class allows to create wave function
by waveType(SINE, SINE_ARC, SINE_ARC_REVERSE, SQUARE, TRIANGLE, SAWTOOTH)
* **BodyFillProvider** - class which allows to fill your graphic items. There are methods of **BodyFillProvider**:
- **setColor(color: Int)** - set the fill color
- **setGradient(gradient: GradientProvider)** - set the fill gradient. There are methods of **GradientProvider**:
- **gradient.setType(type: Type)** - gradient can be(*LINEAR*, *RADIAL* or *SWEEP*)
- **gradient.setAngle(angle: Float)** - set the angle of gradient direction
- **gradient.setLength(length: Float)** - set the length of gradient, by default it fills fit view size
- **gradient.setStartPoint(startPoint: PointF)** - set the start position of gradient
- **gradient.addColor(color: Int)** - add new color to gradient
- **gradient.addColor(color: Int, colorPosition: Float)** - add new color to gradient with color position, colorPosition can be in [0..1]
- **setTexture(resId: Int)** - set the fill texture by resource id
- **setTexture(bitmap: Bitmap)** - set the fill texture by bitmap
- **fitTextureToSize(width: Float, height: Float)** - fit texture to current size
- **fitTextureToSize(width: Float, height: Float, convertWithPointConverter: Boolean)** - fit texture to current size
with possibility to convert setted size
- **setFillType(fillType: FillType)** - set fill type for gradient or texture (REPEAT, MIRROR, CLAMP)
- **setRoundedCorners(radius: Float)** - set all corners rounded with radius
- **setGlowEffect(radius: Float, glowType: GlowType)** - set the glow effect with radius and type (NORMAL, SOLID, OUTER, INNER)
- **setEmbossEffect(angle: Float, embossType: EmbossType)** - set the emboss effect with angle of direction and type
(EMBOSS, EXTRUDE)
- **setShadow(radius: Float, dx: Float, dy: Float, color: Int)** - draws a shadow, with the specified offset and color, and blur radius.
* **ContourFillProvider** - class which allows to draw the contour of your graphic items. Has the same methods with the **BodyFillProvider** class and several specified methods:
- **setWidth(width: Float)** - set the width of contour
- **setIsDotRounded(isDotRounded: Boolean)** - if your contour is dashed it allows to round your dots
- **addDotParams(dotLength: Float, dotDistance: Float)** - set your contour is dashed and add dot params. You can add params more than one time. Each new params will configure the next dot.
* list of **Mark** items - marks which show labels and icons on the graphic items. Each mark can be configured by the following methods:
- **addPosition(point: PointF)** - add new position to current mark
- **addPosition(point: PointF, label: String?)** - add new position with label to current mark
- **addPositions(points: List<PointF>)** - add list of positions to current mark
- **addPositions(points: List<PointF>, labels: List<String>)** - add list of positions and list of labels to current mark
- **setDrawable(resId: Int)** - set image resource to current mark
- **setDrawable(drawable: Drawable)** - set image drawable to current mark
- **fitDrawableToSize(width: Float, height: Float)** - scale mark icon to current size
- **setTextConfigurator(configurator: TextConfigurator)** - set text configuration to mark. It does effect when mark contains text labels.
* **TextConfigurator** - main class to configure text params. There are following methods:
- **setStyle(vararg style: Style)** - set text style(BOLD, UNDERLINE, STRIKE, SUB_PIXEL, ITALIC)
- **setTextSize(size: Float)** - set text size
- **setTextColor(color: Int)** - set text color
- **setTypeface(typeface: Typeface)** set text font
- **setTextOffset(offset: PointF)** set text offset position
* **PointConverter** - main class which allows convert positions of graphic items. There are 3 types of **PointConverter**:
- **DefaultPointConverter** - doesn't convert any positions
- **PercentagePointConverter** - convert all points with percantage aspect ratio to view size. Positions can be in [0..1]. If position is out of range converted position will be out of view size.
- **CoordinateConverter** - convert all positions from old view bounds(width and height) with aspect ratio to current view size
Set *OnMarkClickListener* to view
*PathShape* contains of:
```kotlin
pathShapeView.setOnMarkClickListener(object : PathShapeView.OnMarkClickListener {
override fun onMarkClick(markId: Int, markItem: MarkItem) {
//To change body of created functions use File | Settings | File Templates.
}
})
```
## Samples
* Sample for drawing shapes

Draw triangle with rounded corners:
```kotlin
var list = arrayListOf<PathShape>()
var pathProvider = PathProvider()
var points = ArrayList<PointF>()
points.add(PointF(0.1f, 0.9f))
points.add(PointF(0.5f, 0.1f))
points.add(PointF(0.9f, 0.9f))
pathProvider.putLines(points, true, PathProvider.PathOperation.ADD)
var body = BodyFillProvider()
body.setColor(Color.GRAY)
body.setRoundedCorners(30f)
var contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(10f)
contour.setRoundedCorners(30f)
var pathShape = PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter())
```
Draw rect
```kotlin
...
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
...
```
Draw oval
```kotlin
...
pathProvider.putOval(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
...
```
Draw arc
```kotlin
...
pathProvider.putArc(PointF(0.5f, 0.5f), 0.9f, 0.7f, 30f, 230f, PathProvider.PathOperation.ADD)
...
```
* Dashed contour sample

```kotlin
val pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
val contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
contour.addDotParams(20f, 40f)
contour.addDotParams(40f, 40f)
contour.addDotParams(40f, 40f)
contour.setIsDotRounded(true)
...
```
* Shape with gradient sample

```kotlin
var pathProvider = PathProvider()
pathProvider.putRoundRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, 0.2f, PathProvider.PathOperation.ADD)
var gradient = GradientProvider()
gradient.addColor(Color.BLUE)
.addColor(Color.WHITE)
.addColor(Color.BLUE)
.setType(GradientProvider.Type.SWEEP)
var body = BodyFillProvider()
body.setGradient(gradient)
gradient = GradientProvider()
gradient.addColor(Color.BLACK, 0f)
.addColor(Color.RED,0.1f)
.addColor(Color.WHITE,0.5f)
.addColor(Color.RED,0.9f)
.addColor(Color.BLACK,1f)
.setType(GradientProvider.Type.LINEAR)
var contour = ContourFillProvider()
contour.setGradient(gradient)
contour.setWidth(100f)
...
```
* Logical operations with shapes

```kotlin
var pathProvider = PathProvider()
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.6f, 1f, PathProvider.PathOperation.JOIN)
pathProvider.putOval(PointF(0.5f, 0.5f), 1f, 0.6f, PathProvider.PathOperation.JOIN)
var contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
var body = BodyFillProvider()
body.setColor(Color.LTGRAY)
...
```
```kotlin
...
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.6f, 1f, PathProvider.PathOperation.INTERSECT)
pathProvider.putOval(PointF(0.5f, 0.5f), 1f, 0.6f, PathProvider.PathOperation.INTERSECT)
...
```
```kotlin
...
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.6f, 1f, PathProvider.PathOperation.SUB)
pathProvider.putOval(PointF(0.5f, 0.5f), 1f, 0.6f, PathProvider.PathOperation.SUB)
...
```
```kotlin
...
pathProvider.putRect(PointF(0.5f, 0.5f), 0.9f, 0.9f, PathProvider.PathOperation.ADD)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.6f, 0.9f, PathProvider.PathOperation.SUB_REVERSE)
pathProvider.putOval(PointF(0.5f, 0.5f), 0.9f, 0.6f, PathProvider.PathOperation.SUB_REVERSE)
...
```
* Sample with marks

```kotlin
var points = ArrayList()
points.add(PointF(0.1f, 0.1f))
points.add(PointF(0.5f, 0.3f))
points.add(PointF(0.6f, 0.4f))
points.add(PointF(0.7f, 0.6f))
points.add(PointF(0.9f, 0.8f))
var pathProvider = PathProvider()
pathProvider.putLines(points, false, PathProvider.PathOperation.ADD)
var contour = ContourFillProvider()
contour.setColor(Color.BLACK)
contour.setWidth(20f)
var mark = Mark()
mark.setDrawable(R.mipmap.ic_launcher)
mark.fitDrawableToSize(50f,50f)
var tc = TextConfigurator()
tc.setTextColor(Color.BLUE)
tc.setStyle(TextConfigurator.Style.BOLD, TextConfigurator.Style.UNDERLINE)
tc.setTextSize(20f)
tc.setTextOffset(PointF(0f, -30f))
mark.setTextConfigurator(tc)
points.forEach { mark.addPosition(it, it.toString()) }
var pathShape = PathShape.create()
.setPath(pathProvider)
.fillContour(contour)
.addMark(mark)
.setPointConverter(PercentagePointConverter()
```
* Text sample

```kotlin
var pathProvider = PathProvider()
var tc = TextConfigurator()
tc.setStyle(TextConfigurator.Style.BOLD, TextConfigurator.Style.ITALIC)
pathProvider.putText(PointF(0.5f, 0.5f), 0.5f, 0.2f,"Hello!", tc, PathProvider.PathOperation.ADD)
...
```
* Sample with effects

Glow effect
```kotlin
...
contour.setGlowEffect(30f, FillProvider.GlowType.SOLID)
...
```
Emboss effect
```kotlin
body.setEmbossEffect(45f, FillProvider.EmbossType.NORMAL)
```
Shadow
```kotlin
contour.setShadow(15f, 10f, 10f, Color.BLACK)
```
* Sample with list of custom wave shapes

```kotlin
val pathProvider = PathProvider()
val f = WaveFunction(0.2f, 0.1f, WaveType.SINE)
f.offset(0f, 0.85f)
val shape = CustomLinesBuilder()
shape.addGraphPoints( 0f, 1f, -1f, 1f, f)
shape.addPoint(1f, 0f)
shape.addPoint(0f, 0f)
shape.setClosed(true)
pathProvider.putCustomShape(shape, PathProvider.PathOperation.ADD)
...
```
## License
Copyright (c) 2018 gleb8k
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.
<file_sep>/pathshapeview/src/main/java/shape/path/view/utils/MathUtils.kt
package shape.path.view.utils
import android.graphics.PointF
import android.graphics.RectF
/**
* Created by Gleb on 1/3/18.
*/
class MathUtils {
companion object {
//get distance between 2 points
fun getLength(x1: Float, y1: Float, x2: Float, y2: Float): Float {
return Math.sqrt(((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1)).toDouble()).toFloat()
}
/*
Get end point for vector by it angle and length;
By default the start point is (0;0)
*/
fun getVectorEndPoint(angle: Float, length: Float): PointF {
val angleInRadians = Math.toRadians(angle.toDouble())
val endX = Math.round(Math.cos(angleInRadians) * length)
val endY = Math.round(Math.sin(angleInRadians) * length)
return PointF(endX.toFloat(), endY.toFloat())
}
/*
Get end point for vector by it angle and bounds size;
By default the start point is (0;0)
*/
fun getVectorEndPoint(angle: Float, boundsWidth: Float, boundsHeight: Float): PointF {
val angleInRadians = Math.toRadians(angle.toDouble())
val k = Math.abs(angleInRadians % (Math.PI / 2))
if (k > Math.PI / 4) {
val x = boundsWidth
val y = Math.round(Math.tan(angleInRadians) * boundsWidth).toFloat()
return PointF(x, y)
}
else {
val y = boundsHeight
var x = 0f
if (angleInRadians != 0.0) {
x = Math.round(boundsHeight / Math.tan(angleInRadians)).toFloat()
}
return PointF(x, y)
}
}
/*
Return lines intersection point
If no intersections return null
*/
fun getLinesIntersection(lineA_P1: PointF, lineA_P2: PointF, lineB_P1:PointF, lineB_P2:PointF): PointF? {
val sAx = lineA_P2.x - lineA_P1.x
val sAy = lineA_P2.y - lineA_P1.y
val sBx = lineB_P2.x - lineB_P1.x
val sBy = lineB_P2.y - lineB_P1.y
val k = sAx * sBy - sBx * sAy
val s = (sAx * (lineA_P1.y - lineB_P1.y) - sAy * (lineA_P1.x - lineB_P1.x)) / k
val t = (sBx * (lineA_P1.y - lineB_P1.y) - sBy * (lineA_P1.x - lineB_P1.x)) / k
if (s in 0f..1f && t in 0f..1f) {
val x = lineA_P1.x + (t * sAx)
val y = lineA_P1.y + (t * sAy)
return PointF(x, y)
}
return null
}
/*
return intersection point with one of rect border(top or bottom)
*/
fun getBoundsIntersection(bounds: RectF, p1: PointF, p2: PointF) : PointF? {
var result = getLinesIntersection(PointF(bounds.top, bounds.left), PointF(bounds.top, bounds.right), p1, p2)
if (result == null) {
result = getLinesIntersection(PointF(bounds.bottom, bounds.left), PointF(bounds.bottom, bounds.right), p1, p2)
}
return result
}
}
}
<file_sep>/pathshapeview/src/main/java/shape/path/view/utils/JSONUtils.kt
package shape.path.view.utils
import android.content.Context
import android.graphics.Color
import android.graphics.PointF
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import org.json.JSONObject
import java.io.IOException
import java.nio.charset.Charset
/**
* Created by root on 3/20/18.
*/
class JSONUtils {
companion object {
internal fun jsonToPoint(json: JSONObject?): PointF? {
return jsonToPoint(json, null)
}
internal fun jsonToPoint(json: JSONObject?, default: PointF?): PointF? {
if (json == null) return default
val x = json.optDouble("x")
val y = json.optDouble("y")
if (x == Double.NaN || y == Double.NaN) return default
return PointF(x.toFloat(), y.toFloat())
}
internal fun jsonToTypeface(context: Context, json: JSONObject?): Typeface {
if (json == null) return Typeface.DEFAULT
val asset = json.optString("typefaceAsset")
if (asset.isNullOrEmpty()) return Typeface.DEFAULT
return Typeface.createFromAsset(context.assets, asset)
}
internal fun loadJsonFromAsset(context: Context, filename: String): JSONObject? {
var json: JSONObject? = null
try {
val stream = context.assets.open(filename)
val size = stream.available()
val buffer = ByteArray(size)
stream.read(buffer)
stream.close()
val string = String(buffer, Charset.forName("UTF-8"))
json = JSONObject(string)
} catch (ex: IOException) {
ex.printStackTrace()
}
return json
}
internal fun stringToDrawableResId(context: Context, resName: String?): Int {
if (resName.isNullOrEmpty()) return -1
val resID = context.resources.getIdentifier(resName,
"drawable", context.packageName)
return if (resID == 0) -1 else resID
}
}
}
<file_sep>/app/src/main/java/demo/shape/path/view/samples/SampleAdapter.kt
package demo.shape.path.view.samples
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
/**
* Created by Gleb on 1/26/18.
*/
class SampleAdapter(val itemClickListener: SampleItemHolder.OnItemClickListener): RecyclerView.Adapter<SampleItemHolder>() {
val items: Array<Sample> = Sample.values()
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: SampleItemHolder, position: Int) {
holder.bind(items[position])
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SampleItemHolder {
return SampleItemHolder.newInstance(parent, itemClickListener)
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/mark/Mark.kt
package shape.path.view.mark
import android.content.Context
import android.graphics.Canvas
import android.graphics.PointF
import android.graphics.drawable.Drawable
import org.json.JSONObject
import shape.path.view.TextConfigurator
import shape.path.view.point.converter.PointConverter
import shape.path.view.utils.DrawableUtils
import shape.path.view.utils.JSONUtils
/**
* Created by root on 1/25/18.
*/
class Mark {
private var id: Int = 0
private var touchWidth = 0f
private var touchHeight = 0f
private var items: ArrayList<MarkItem> = arrayListOf()
private var width: Float = 0f
private var height: Float = 0f
private var textConfigurator: TextConfigurator? = null
private var drawable: Drawable? = null
private var drawableResId: Int = -1
private var selectedDrawable: Drawable? = null
private var selectedDrawableResId: Int = -1
private var multiSelectionModeEnabled = false
private var isCheckable = false
private var itemsChanged = false
private var drawableChanged = false
companion object {
internal fun fromJson(context: Context, json: JSONObject?): Mark? {
if (json == null) return null
val mark = Mark()
mark.setId(json.optInt("id", 0))
val drawable = json.optJSONObject("drawable")
drawable?.let {
val w = drawable.optDouble("width", 0.0).toFloat()
val h = drawable.optDouble("height", 0.0).toFloat()
mark.setDrawable(JSONUtils.stringToDrawableResId(context, drawable.optString("resource")))
mark.setSelectedDrawable(JSONUtils.stringToDrawableResId(context, drawable.optString("selectedResource")))
mark.fitDrawableToSize(w, h)
}
val touchBounds = json.optJSONObject("touchBounds")
touchBounds?.let {
val w = touchBounds.optDouble("width", 0.0).toFloat()
val h = touchBounds.optDouble("height", 0.0).toFloat()
mark.setTouchBounds(w, h)
}
mark.setCheckable(json.optBoolean("checkable", false))
mark.setMultiSelectionModeEnabled(json.optBoolean("multiSelectionMode", false))
mark.setTextConfigurator(TextConfigurator.fromJson(context, json.optJSONObject("textConfigurator")))
val items = json.optJSONArray("items")
items?.let {
for(i in 0 until it.length()) {
val item = it.optJSONObject(i)
item?.let {
val p = JSONUtils.jsonToPoint(item, PointF(0f, 0f))
val label = item.optString("label")
mark.addPosition(p!!, label)
}
}
}
return mark
}
}
fun addPosition(point: PointF) {
this.addPosition(point, null)
}
fun addPosition(point: PointF, label: String?) {
val item = MarkItem()
item.position = point
item.label = label
item.index = items.size
items.add(item)
itemsChanged = true
}
fun addPositions(points: List<PointF>) {
this.addPositions(points, arrayListOf())
}
fun addPositions(points: List<PointF>, labels: List<String>) {
for (i in 0 until points.size) {
if (i < labels.size) {
addPosition(points[i], labels[i])
}
else {
addPosition(points[i])
}
}
}
fun resetItems() {
items.clear()
itemsChanged = true
}
fun setTextConfigurator(configurator: TextConfigurator?) {
this.textConfigurator = configurator
}
fun setDrawable(resId: Int) {
drawableResId = resId
drawable = null
drawableChanged = true
}
fun setSelectedDrawable(drawable: Drawable) {
this.selectedDrawable = drawable
drawableChanged = true
}
fun setSelectedDrawable(resId: Int) {
selectedDrawableResId = resId
selectedDrawable = null
drawableChanged = true
}
fun setDrawable(drawable: Drawable) {
this.drawable = drawable
drawableChanged = true
}
fun setMultiSelectionModeEnabled(enabled: Boolean){
multiSelectionModeEnabled = enabled
}
fun setCheckable(isCheckable: Boolean) {
this.isCheckable = isCheckable
}
fun fitDrawableToSize(width: Float, height: Float) {
this.width = width
this.height = height
drawableChanged = true
}
fun setId(id: Int) {
this.id = id
}
fun getId(): Int {
return id
}
fun setTouchBounds(width: Float, height: Float) {
this.touchWidth = width
this.touchHeight = height
}
internal fun build(context: Context, pointConverter: PointConverter) {
if (itemsChanged) {
items.forEach { it.build(pointConverter, touchWidth, touchHeight) }
itemsChanged = false
}
if (drawableChanged) {
drawable = DrawableUtils.getScaledDrawable(context, drawable, drawableResId, width, height)
selectedDrawable = DrawableUtils.getScaledDrawable(context, selectedDrawable, selectedDrawableResId, width, height)
drawableChanged = false
}
}
internal fun draw(canvas: Canvas) {
items.forEach {
updatePositionDrawableAndDraw(it, canvas)
updateLableAndDraw(it, canvas)
}
}
private fun updatePositionDrawableAndDraw(markItem: MarkItem, canvas: Canvas) {
drawable?.let {
val w = it.bounds.width()
val h = it.bounds.height()
val left = (markItem.position.x - w / 2).toInt()
val top = (markItem.position.y - h / 2).toInt()
val right = (markItem.position.x + w / 2).toInt()
val bottom = (markItem.position.y + h / 2).toInt()
if (markItem.isSelected && selectedDrawable != null) {
selectedDrawable!!.setBounds(left, top, right, bottom)
selectedDrawable!!.draw(canvas)
}
else {
it.setBounds(left, top, right, bottom)
it.draw(canvas)
}
}
}
private fun updateLableAndDraw(markItem: MarkItem, canvas: Canvas) {
if (markItem.label != null) {
textConfigurator?.let {
val x = markItem.position.x + it.textOffset.x
val y = markItem.position.y + it.textOffset.y
canvas.drawText(markItem.label, x, y, it.paint)
}
}
}
internal fun onItemClick(x: Float, y: Float): MarkItem? {
if (touchWidth > 0f && touchHeight > 0f) {
for(i in 0 until items.size) {
val it = items[i]
if (it.isInBounds(x, y)) {
if (!multiSelectionModeEnabled) {
unselectAllExceptItem(i)
}
if (isCheckable) {
it.isSelected = !it.isSelected
}
else {
it.isSelected = true
}
return it
}
}
}
return null
}
private fun unselectAllExceptItem(itemIndex: Int) {
for(i in 0 until items.size) {
if (i != itemIndex) {
items[i].isSelected = false
}
}
}
internal fun hasSelectedDrawable(): Boolean {
return selectedDrawable != null
}
}<file_sep>/app/src/main/java/demo/shape/path/view/fragment/ShapeFragment.kt
package demo.shape.path.view.fragment
import android.app.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import demo.shape.path.view.R
import demo.shape.path.view.samples.Sample
import demo.shape.path.view.samples.ShapeManager
import kotlinx.android.synthetic.main.fragment_shape.*
import shape.path.view.PathShapeView
import shape.path.view.mark.MarkItem
/**
* Created by Gleb on 1/26/18.
*/
class ShapeFragment : Fragment(), PathShapeView.OnMarkClickListener, View.OnClickListener {
private var sample: Sample = Sample.SIMPLE_SHAPES
companion object {
private val SAMPLE_TYPE_KEY: String = "sample_type_key"
fun newInstance(sample: Sample): ShapeFragment {
val f = ShapeFragment()
val b = Bundle()
b.putInt(SAMPLE_TYPE_KEY, sample.ordinal)
f.arguments = b
return f
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sample = Sample.values()[arguments!!.getInt(SAMPLE_TYPE_KEY, 0)]
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_shape, null)
return v
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val sm = ShapeManager()
val views = arrayListOf(path1, path2, path3, path4)
val shapes = sm.getShapes(sample)
for (i in 0 until shapes.size) {
views[i].setPath(shapes[i])
}
if (sample == Sample.MARKS_SAMPLE) {
for (i in 0 until shapes.size) {
views[i].setOnMarkClickListener(this)
views[i].id = i
views[i].setOnClickListener(this)
}
}
}
override fun onMarkClick(markId: Int, markItem: MarkItem) {
Toast.makeText(activity, "mark Id: " + markId + ", item index: " + markItem.index +
", item label: " + markItem.label, Toast.LENGTH_SHORT).show()
}
override fun onClick(v: View?) {
Toast.makeText(activity, "view Id: " + v!!.id, Toast.LENGTH_SHORT).show() //To change body of created functions use File | Settings | File Templates.
}
}<file_sep>/pathshapeview/src/androidTest/java/shape/path/view/MathTest.kt
package shape.path.view
import android.graphics.PointF
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
import shape.path.view.utils.MathUtils
/**
* Instrumented test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class MathTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
// test distance between points
var p = MathUtils.getLinesIntersection(PointF(-1f, 0f), PointF(1f, 0f), PointF(0f, -1f), PointF(0f, 1f))
assertEquals(PointF(0f,0f), p)
}
}
<file_sep>/app/src/main/java/demo/shape/path/view/samples/Sample.kt
package demo.shape.path.view.samples
import android.content.Context
import demo.shape.path.view.R
/**
* Created by Gleb on 1/26/18.
*/
enum class Sample private constructor(private var stringResId: Int) {
SIMPLE_SHAPES(R.string.sample_simple_shapes),
CONTOUR_SAMPLE(R.string.sample_shape_contour),
GRADIENT_AND_TEXTURE_SAMPLE(R.string.sample_fill_shape),
SHAPE_SET_SAMPLE(R.string.sample_shape_set),
POINT_CONVERTER_SAMPLE(R.string.sample_point_converter),
MARKS_SAMPLE(R.string.sample_marks),
TEXT_SAMPLE(R.string.sample_text),
FILL_WITH_EFFECTS_SAMPLE(R.string.sample_fill_with_effects),
CUSTOM_SHAPE_LIST_SAMPLE(R.string.sample_custom_shape_list),
JSON_PARSER_SAMPLE(R.string.sample_json_parser);
fun getName(context: Context): String {
return context.getString(stringResId)
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/point/converter/PointConverter.kt
package shape.path.view.point.converter
import android.graphics.Matrix
import android.graphics.PointF
/**
* Created by root on 1/9/18.
*/
abstract class PointConverter {
internal var screenWidth: Float = 0f
internal var screenHeight: Float = 0f
protected var matrix: Matrix = Matrix()
open fun setScreenSize(screenWidth: Float, screenHeight: Float) {
this.screenWidth = screenWidth
this.screenHeight = screenHeight
}
open fun convertPoint(originPoint: PointF): PointF {
val src = floatArrayOf(originPoint.x, originPoint.y)
val dst = floatArrayOf(0f, 0f)
matrix.mapPoints(dst, src)
return PointF(dst[0], dst[1])
}
abstract internal fun getMatrix(): Matrix
}<file_sep>/pathshapeview/src/main/java/shape/path/view/fill/provider/BodyFillProvider.kt
package shape.path.view.fill.provider
import android.content.Context
import android.graphics.Paint
import org.json.JSONObject
/**
* Created by root on 1/10/18.
*/
class BodyFillProvider : FillProvider() {
init {
paint.style = Paint.Style.FILL
}
companion object {
internal fun fromJson(context: Context, json: JSONObject?): BodyFillProvider? {
if (json == null) return null
val provider = BodyFillProvider()
provider.fromJson(context, json)
return provider
}
}
}<file_sep>/app/src/main/java/demo/shape/path/view/fragment/custom/CustomShapeItemHolder.kt
package demo.shape.path.view.fragment.custom
import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import demo.shape.path.view.R
import kotlinx.android.synthetic.main.view_item_custom_shape.view.*
import shape.path.view.PathShape
import shape.path.view.PathShapeView
/**
* Created by Gleb on 1/26/18.
*/
class CustomShapeItemHolder private constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var title: AppCompatTextView? = null
private var shapeView: PathShapeView? = null
companion object {
fun newInstance(parent: ViewGroup): CustomShapeItemHolder {
return CustomShapeItemHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_item_custom_shape, parent, false))
}
}
init {
title = itemView.title
shapeView = itemView.custom_shape_view
}
fun bind(shape: PathShape) {
this.shapeView!!.setPath(shape)
title!!.text = itemView.context.getString(R.string.custom_shape_item_title, adapterPosition)
}
}<file_sep>/settings.gradle
include ':app', ':pathshapeview'
<file_sep>/app/src/main/java/demo/shape/path/view/fragment/custom/CustomShapeListFragment.kt
package demo.shape.path.view.fragment.custom
import android.app.Fragment
import android.graphics.Color
import android.graphics.PointF
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import demo.shape.path.view.MainActivity
import demo.shape.path.view.R
import kotlinx.android.synthetic.main.fragment_custom_shape_list.*
import shape.path.view.PathProvider
import shape.path.view.fill.provider.*
import shape.path.view.graph.function.CustomLinesBuilder
import shape.path.view.graph.function.WaveFunction
import shape.path.view.point.converter.PercentagePointConverter
import shape.path.view.PathShape
import shape.path.view.fill.provider.ContourFillProvider
/**
* Created by Gleb on 1/26/18.
*/
class CustomShapeListFragment : Fragment() {
companion object {
fun newInstance(): CustomShapeListFragment {
val f = CustomShapeListFragment()
return f
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_custom_shape_list, null)
return v
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(activity as MainActivity).setSupportActionBar(toolBar)
recyclerView.layoutManager = LinearLayoutManager(activity)
recyclerView.adapter = CustomShapeAdapter(activity)
initHeader()
initAvatarBehavior()
}
private fun initHeader() {
val pathProvider = PathProvider()
val f = WaveFunction(0.05f, 0.05f, WaveFunction.WaveType.SINE_ARC)
f.offset(0f, 0.94f)
val shape = CustomLinesBuilder()
shape.addGraphPoints( 0f, 1f, -1f, 1f, f)
shape.addPoint(1f, 0.4f)
shape.addPoint(0.4f, 0f)
shape.addPoint(0f, 0f)
shape.setClosed(true)
pathProvider.putCustomShape(shape, PathProvider.PathOperation.ADD)
val body = BodyFillProvider()
body.setColor(ContextCompat.getColor(activity, R.color.colorPrimary))
header.setPath(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.setPointConverter(PercentagePointConverter()))
}
private fun initAvatarBehavior() {
val pathProvider = PathProvider()
pathProvider.putCircle(PointF(0.5f, 0.5f), 0.5f, PathProvider.PathOperation.ADD)
val body = BodyFillProvider()
body.setTexture(R.drawable.bridge)
body.fitTextureToSize(1f, 1f, true)
val contour = ContourFillProvider()
contour.setColor(Color.WHITE)
contour.setWidth(8f)
ava.setPath(PathShape.create()
.setPath(pathProvider)
.fillBody(body)
.fillContour(contour)
.setPointConverter(PercentagePointConverter()))
appbar.addOnOffsetChangedListener { _, verticalOffset ->
val kx = 1f + (verticalOffset.toFloat() / appbar.totalScrollRange.toFloat())
Log.d("scale factor","kx = " + kx)
ava.scaleX = kx
ava.scaleY = kx
}
}
}<file_sep>/app/src/main/java/demo/shape/path/view/fragment/JsonParserFragment.kt
package demo.shape.path.view.fragment
import android.app.Fragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import demo.shape.path.view.R
import demo.shape.path.view.samples.Sample
import demo.shape.path.view.samples.ShapeManager
import kotlinx.android.synthetic.main.fragment_json_parser.*
import kotlinx.android.synthetic.main.fragment_shape.*
import shape.path.view.PathShape
import shape.path.view.PathShapeView
import shape.path.view.mark.MarkItem
/**
* Created by Gleb on 1/26/18.
*/
class JsonParserFragment : Fragment(), PathShapeView.OnMarkClickListener, View.OnClickListener {
companion object {
fun newInstance(): JsonParserFragment {
val f = JsonParserFragment()
return f
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = inflater.inflate(R.layout.fragment_json_parser, null)
return v
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
path_shape.setOnMarkClickListener(this)
path_shape.setOnClickListener(this)
}
override fun onMarkClick(markId: Int, markItem: MarkItem) {
Toast.makeText(activity, "mark Id: " + markId + ", item index: " + markItem.index +
", item label: " + markItem.label, Toast.LENGTH_SHORT).show()
}
override fun onClick(v: View?) {
Toast.makeText(activity, "view Id: " + v!!.id, Toast.LENGTH_SHORT).show() //To change body of created functions use File | Settings | File Templates.
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/utils/DrawableUtils.kt
package shape.path.view.utils
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v4.content.res.ResourcesCompat
/**
* Created by root on 2/12/18.
*/
class DrawableUtils {
companion object {
internal fun getScaledDrawable(context: Context, drawable: Drawable?, drawableResId: Int, width: Float, height: Float): Drawable? {
var result: Drawable? = drawable
try {
if (result == null && drawableResId != -1) {
result = ResourcesCompat.getDrawable(context.resources, drawableResId, null)
}
if (result != null) {
scaleDrawable(result, width, height)
}
}
catch (e: Exception) {
e.printStackTrace()
}
return result
}
private fun scaleDrawable(drawable: Drawable, width: Float, height: Float) {
var w = drawable.bounds.width()
var h = drawable.bounds.height()
if (w == 0 && h == 0 && width == 0f && height == 0f) {
w = drawable.intrinsicWidth
h = drawable.intrinsicHeight
drawable.setBounds(0, 0, w, h)
}
else if (width > 0 && width.toInt() != w && height > 0 && height.toInt() != h) {
drawable.setBounds(0, 0, width.toInt(), height.toInt())
}
}
}
}
<file_sep>/pathshapeview/src/main/java/shape/path/view/graph/function/CustomLinesBuilder.kt
package shape.path.view.graph.function
import android.content.Context
import android.graphics.Path
import android.graphics.PointF
import android.graphics.RectF
import org.json.JSONObject
import shape.path.view.utils.JSONUtils
import shape.path.view.utils.MathUtils
/**
* Created by root on 2/19/18.
*/
class CustomLinesBuilder {
private var points = arrayListOf<PointF>()
private var isClosed = false
companion object {
val DEFAULT_STEP_COUNT = 200
internal fun fromJson(json: JSONObject?): CustomLinesBuilder? {
if (json == null) return null
val array = json.optJSONArray("lines") ?: return null
val result = CustomLinesBuilder()
for (i in 0 until array.length()) {
val item = array.optJSONObject(i)
if (item == null) continue
val type = WaveFunction.WaveType.fromString(item.optString("type"))
if (type == null) {
val point = JSONUtils.jsonToPoint(item)
if (point == null) continue
result.addPoint(point)
}
else {
val waveWidth = item.optDouble("waveWidth", 0.0).toFloat()
val waveHeight = item.optDouble("waveHeight", 0.0).toFloat()
val offset = JSONUtils.jsonToPoint(item.optJSONObject("offset"))
val skew = JSONUtils.jsonToPoint(item.optJSONObject("skew"))
val rotate = item.optDouble("rotate", 0.0).toFloat()
val f = WaveFunction(waveWidth, waveHeight, type)
offset?.let { f.offset(offset.x, offset.y) }
skew?.let { f.skew(skew.x, skew.y) }
if (rotate != 0f) f.rotate(rotate)
val minPoint = JSONUtils.jsonToPoint(item.optJSONObject("minPoint")) ?: PointF(0f,0f)
val maxPoint = JSONUtils.jsonToPoint(item.optJSONObject("maxPoint")) ?: PointF(0f,0f)
val stepCount = item.optInt("stepCount", DEFAULT_STEP_COUNT)
result.addGraphPoints(minPoint.x, maxPoint.x, minPoint.y, maxPoint.y, stepCount, f)
}
}
val isClosed = json.optBoolean("isClosed", false)
result.setClosed(isClosed)
return result
}
}
fun addPoint(x: Float, y: Float) {
points.add(PointF(x, y))
}
fun addPoint(p: PointF) {
points.add(p)
}
fun addGraphPoints(minX: Float, maxX: Float, minY: Float, maxY: Float, function: GraphFunction) {
this.addGraphPoints(minX, maxX, minY, maxY, DEFAULT_STEP_COUNT, function)
}
fun addGraphPoints(minX: Float, maxX: Float, minY: Float, maxY: Float, stepCount: Int, function: GraphFunction) {
val stepValue = (maxX - minX) / stepCount
var x = minX
while (x < maxX) {
var p = function.getTransformFunctionPoint(x, stepValue, stepCount)
if (function.originY in minY..maxY) {
addPoint(p)
}
else {
if (function.originY > maxY || function.originY < minY) {
val cur = PointF(function.originX, function.originY)
val f = function.onFunctionGetValue(x - stepValue, stepValue, stepCount)
val prev = PointF(x - stepValue, f)
val res = MathUtils.getBoundsIntersection(RectF(minX, minY, maxX, maxY), prev, cur)
if (res != null) {
p = function.getTransformPoint(res.x, res.y)
}
}
addPoint(p)
break
}
x += stepValue
}
}
fun setClosed(isClosed: Boolean) {
this.isClosed = isClosed
}
internal fun getPath() : Path {
val p = Path()
if (points.isNotEmpty()) {
p.moveTo(points[0].x, points[0].y)
for (i in 1 until points.size) {
p.lineTo(points[i].x, points[i].y)
}
if (isClosed) {
p.close()
}
}
return p
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/fill/provider/FillProvider.kt
package shape.path.view.fill.provider
import android.content.Context
import android.graphics.*
import org.json.JSONObject
import shape.path.view.point.converter.PointConverter
import shape.path.view.utils.BitmapUtils
import shape.path.view.utils.JSONUtils
import shape.path.view.utils.MathUtils
/**
* Created by root on 1/10/18.
*/
abstract class FillProvider {
internal val paint: Paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.DITHER_FLAG)
private var gradient: GradientProvider? = null
private var roundedCornerRadius: Float = 0f
private var fillType: FillType = FillType.MIRROR
private var imageResId: Int = -1
private var bitmap: Bitmap? = null
private var imageWidth: Float = 0f
private var imageHeight: Float = 0f
private var convertImageSize: Boolean = false
private var hasShadowLayer: Boolean = false
internal open var shaderChanged = false
internal open var pathEffectChanged = false
enum class FillType private constructor(internal var mode: Shader.TileMode) {
REPEAT(Shader.TileMode.REPEAT),
MIRROR(Shader.TileMode.MIRROR),
CLAMP(Shader.TileMode.CLAMP);
companion object {
fun fromString(type: String?): FillType? {
if (type.isNullOrEmpty()) return null
FillType.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
enum class GlowType private constructor(internal var type: BlurMaskFilter.Blur){
NORMAL(BlurMaskFilter.Blur.NORMAL),
SOLID(BlurMaskFilter.Blur.SOLID),
OUTER(BlurMaskFilter.Blur.OUTER),
INNER(BlurMaskFilter.Blur.INNER);
companion object {
fun fromString(type: String?): GlowType? {
if (type.isNullOrEmpty()) return null
GlowType.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
enum class EmbossType private constructor(internal var z: Float, internal var ambient: Float,
internal var specular: Float, internal var radius: Float) {
NORMAL(1f, 0.3f, 10f, 10f),
EXTRUDE(0.5f, 0.8f, 13f, 7f);
companion object {
fun fromString(type: String?): EmbossType? {
if (type.isNullOrEmpty()) return null
EmbossType.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
fun setColor(color: Int) {
paint.color = color
}
fun setGradient(gradient: GradientProvider) {
this.gradient = gradient
shaderChanged = true
}
fun setFillType(fillType: FillType) {
this.fillType = fillType
shaderChanged = true
}
fun setTexture(resId: Int) {
clearBitmap()
this.imageResId = resId
shaderChanged = true
}
fun setTexture(bitmap: Bitmap) {
clearBitmap()
this.bitmap = bitmap
shaderChanged = true
}
fun fitTextureToSize(width: Float, height: Float) {
this.fitTextureToSize(width, height, false)
shaderChanged = true
}
fun fitTextureToSize(width: Float, height: Float, convertWithPointConverter: Boolean) {
this.imageWidth = width
this.imageHeight = height
this.convertImageSize = convertWithPointConverter
shaderChanged = true
}
fun setRoundedCorners(radius: Float) {
roundedCornerRadius = radius
pathEffectChanged = true
}
fun setGlowEffect(radius: Float, glowType: GlowType) {
clearShadow()
paint.maskFilter = BlurMaskFilter(radius, glowType.type)
}
fun setEmbossEffect(angle: Float, embossType: EmbossType) {
clearShadow()
val p = MathUtils.getVectorEndPoint(angle, 1f)
paint.maskFilter = EmbossMaskFilter(floatArrayOf(p.x, p.y, embossType.z), embossType.ambient,
embossType.specular, embossType.radius)
}
fun setShadow(radius: Float, dx: Float, dy: Float, color: Int) {
paint.maskFilter = null
paint.setShadowLayer(radius, dx, dy, color)
hasShadowLayer = true
}
fun clearAllEffects() {
clearShadow()
paint.maskFilter = null
}
private fun clearShadow() {
if (hasShadowLayer) {
paint.clearShadowLayer()
hasShadowLayer = false
}
}
internal fun hasEffects(): Boolean {
return paint.maskFilter != null || hasShadowLayer
}
private fun clearBitmap() {
if (bitmap != null) {
bitmap!!.recycle()
bitmap = null
}
}
protected open fun buildEffect(): PathEffect? {
if (roundedCornerRadius != 0f) {
return CornerPathEffect(roundedCornerRadius)
}
return null
}
internal fun build(context: Context, converter: PointConverter) {
if (pathEffectChanged) {
paint.pathEffect = buildEffect()
pathEffectChanged = false
}
if (shaderChanged) {
paint.shader = buildShader(context, converter)
shaderChanged = false
}
}
private fun buildShader(context: Context, converter: PointConverter): Shader? {
var imageSize = PointF(imageWidth, imageHeight)
if (convertImageSize) {
imageSize = converter.convertPoint(imageSize)
}
bitmap = BitmapUtils.loadBitmap(context, bitmap, imageResId, imageSize.x, imageSize.y)
var bitmapShader: Shader? = null
bitmap?.let {
bitmapShader = BitmapShader(it, fillType.mode, fillType.mode)
}
val gradientShader = gradient?.build(converter, fillType.mode)
if (bitmapShader == null) {
return gradientShader
}
if (gradientShader == null) {
return bitmapShader
}
return ComposeShader(bitmapShader, gradientShader, PorterDuff.Mode.MULTIPLY)
}
protected open fun fromJson(context: Context, json: JSONObject) {
val c = json.optString("color", null)
c?.let { paint.color = Color.parseColor(it) }
gradient = GradientProvider.fromJson(json.optJSONObject("gradient"))
val texture = json.optJSONObject("texture")
texture?.let {
val w = it.optDouble("width")
val h = it.optDouble("height")
setTexture(JSONUtils.stringToDrawableResId(context, it.optString("resource")))
if (w != Double.NaN && h != Double.NaN) {
fitTextureToSize(w.toFloat(), h.toFloat())
}
}
fillType = FillType.fromString(json.optString("fillType")) ?: FillType.MIRROR
roundedCornerRadius = json.optDouble("roundedCorners", 0.0).toFloat()
val glow = json.optJSONObject("glow")
glow?.let {
val type = GlowType.fromString(it.optString("type"))
val radius = it.optDouble("radius", 0.0).toFloat()
if (type != null && radius > 0) {
setGlowEffect(radius, type)
}
}
val emboss = json.optJSONObject("emboss")
emboss?.let {
val type = EmbossType.fromString(it.optString("type"))
val angle = it.optDouble("angle", 0.0).toFloat()
type?.let { setEmbossEffect(angle, it) }
}
val shadow = json.optJSONObject("shadow")
shadow?.let {
val color = Color.parseColor(it.optString("color"))
val radius = it.optDouble("radius", 0.0).toFloat()
val offset = JSONUtils.jsonToPoint(it.optJSONObject("offset"), PointF(0f,0f))!!
setShadow(radius, offset.x, offset.y, color)
}
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/PathShape.kt
package shape.path.view
import android.content.Context
import android.graphics.*
import shape.path.view.fill.provider.BodyFillProvider
import shape.path.view.fill.provider.ContourFillProvider
import shape.path.view.mark.Mark
import shape.path.view.parser.*
import shape.path.view.point.converter.DefaultPointConverter
import shape.path.view.point.converter.PointConverter
import shape.path.view.utils.JSONUtils
/**
* Created by Gleb on 1/3/18.
*/
class PathShape private constructor() {
internal var body: BodyFillProvider? = null
internal var contour: ContourFillProvider? = null
internal var pathProvider: PathProvider? = null
internal var marks: ArrayList<Mark> = arrayListOf()
private var pointConverter: PointConverter = DefaultPointConverter()
fun setPath(provider: PathProvider?): PathShape {
this.pathProvider = provider
return this
}
fun fillBody(provider: BodyFillProvider?): PathShape {
this.body = provider
return this
}
fun fillContour(provider: ContourFillProvider?): PathShape {
this.contour = provider
return this
}
fun setPointConverter(pointConverter: PointConverter): PathShape {
this.pointConverter = pointConverter
return this
}
fun addMark(mark: Mark): PathShape {
marks.add(mark)
return this
}
internal fun hasEffects(): Boolean {
return contour?.hasEffects() ?: false || body?.hasEffects() ?: false
}
internal fun build(context: Context, screenWidth: Float, screenHeight: Float) {
pointConverter.setScreenSize(screenWidth, screenHeight)
var strokeWidth = 0f
contour?.let {
it.build(context, pointConverter)
strokeWidth = it.paint.strokeWidth
}
body?.let {
it.build(context, pointConverter)
}
pathProvider?.build(pointConverter, strokeWidth)
marks.forEach { it.build(context, pointConverter) }
}
internal fun draw(canvas: Canvas) {
if (pathProvider != null && pathProvider!!.hasPath()) {
if (body != null) {
canvas.drawPath(pathProvider!!.shapePath, body!!.paint)
}
if (contour != null) {
canvas.drawPath(pathProvider!!.shapePath, contour!!.paint)
}
}
marks.forEach { it.draw(canvas) }
}
companion object {
fun create(): PathShape {
return PathShape()
}
fun fromAsset(context: Context, fileName: String): PathShape {
val shape = PathShape()
val json = JSONUtils.loadJsonFromAsset(context, fileName)
json?.let {
val path = it.optJSONObject("pathProvider")
shape.setPath(PathParser.fromJson(context, path))
val body = it.optJSONObject("fillBody")
shape.fillBody(BodyFillProvider.fromJson(context, body))
val contour = it.optJSONObject("fillContour")
shape.fillContour(ContourFillProvider.fromJson(context, contour))
val marks = json.optJSONArray("marks")
marks?.let {
for(i in 0 until marks.length()) {
val mark = Mark.fromJson(context, marks.optJSONObject(i))
mark?.let {
shape.addMark(mark)
}
}
}
val converter = it.optJSONObject("pointConverter")
shape.setPointConverter(PointConverterParser.fromJson(converter))
}
return shape
}
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/parser/PointConverterParser.kt
package shape.path.view.parser
import org.json.JSONObject
import shape.path.view.point.converter.CoordinateConverter
import shape.path.view.point.converter.DefaultPointConverter
import shape.path.view.point.converter.PercentagePointConverter
import shape.path.view.point.converter.PointConverter
/**
* Created by root on 3/27/18.
*/
class PointConverterParser {
enum class ConverterType {
PERCENTAGE,
COORDINATE;
companion object {
fun fromString(type: String?): ConverterType? {
if (type.isNullOrEmpty()) return null
ConverterType.values().forEach {
if (it.toString() == type) {
return it
}
}
return null
}
}
}
companion object {
internal fun fromJson(json: JSONObject?): PointConverter {
json?.let {
val sType = json.optString("type")
if (!sType.isNullOrEmpty()) {
when(ConverterType.fromString(sType)) {
ConverterType.PERCENTAGE -> return PercentagePointConverter()
ConverterType.COORDINATE -> {
val width = json.optDouble("originWidth", 0.0).toFloat()
val height = json.optDouble("originHeight", 0.0).toFloat()
return CoordinateConverter(width, height)
}
}
}
}
return DefaultPointConverter()
}
}
}
<file_sep>/app/src/main/java/demo/shape/path/view/samples/SampleItemHolder.kt
package demo.shape.path.view.samples
import android.support.v7.widget.AppCompatTextView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import demo.shape.path.view.R
import kotlinx.android.synthetic.main.view_item_sample.view.*
/**
* Created by Gleb on 1/26/18.
*/
class SampleItemHolder private constructor(val itemClickListener: OnItemClickListener, itemView: View) : RecyclerView.ViewHolder(itemView) {
private var title: AppCompatTextView? = null
private var sample: Sample = Sample.SIMPLE_SHAPES
companion object {
fun newInstance(parent: ViewGroup, itemClickListener: OnItemClickListener): SampleItemHolder {
return SampleItemHolder(itemClickListener, LayoutInflater.from(parent.context).inflate(R.layout.view_item_sample, parent, false))
}
}
interface OnItemClickListener {
fun onItemClick(sample: Sample)
}
init {
title = itemView.sample_name
itemView.setOnClickListener { itemClickListener.onItemClick(sample) }
}
fun bind(sample: Sample) {
this.sample = sample
title!!.text = sample.getName(itemView.context)
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/point/converter/DefaultPointConverter.kt
package shape.path.view.point.converter
import android.graphics.Matrix
import android.graphics.PointF
/**
* Created by Gleb on 1/22/18.
*/
class DefaultPointConverter : PointConverter() {
override fun getMatrix(): Matrix {
return matrix
}
override fun convertPoint(originPoint: PointF): PointF {
return originPoint
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/PathShapeView.kt
package shape.path.view
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import shape.path.view.mark.MarkItem
/**
* Created by root on 12/19/17.
*/
class PathShapeView : View {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
initFromAttrs(context, attrs)
}
private var pathShape: PathShape? = null
private var onMarkClickListener: OnMarkClickListener? = null
interface OnMarkClickListener {
fun onMarkClick(markId: Int, markItem: MarkItem)
}
private fun initFromAttrs(context: Context?, attrs: AttributeSet?) {
val a = context?.theme?.obtainStyledAttributes(attrs, R.styleable.PathShapeView, 0, 0)
a?.let {
try {
val fileName = it.getString(R.styleable.PathShapeView_assetShapeResource)
if (!fileName.isNullOrEmpty()) {
pathShape = PathShape.fromAsset(context, fileName)
}
}
finally {
it.recycle()
}
}
}
fun setPath(pathShape: PathShape) {
this.pathShape = pathShape
updateView()
}
private fun updateView() {
if (width != 0 && height != 0) {
update()
}
else {
post {
update()
}
}
}
private fun update() {
pathShape?.let {
it.build(context, width.toFloat(), height.toFloat())
if (it.hasEffects() && layerType != View.LAYER_TYPE_SOFTWARE) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null)
}
else {
invalidate()
}
}
}
fun setOnMarkClickListener(onMarkClickListener: OnMarkClickListener) {
this.onMarkClickListener = onMarkClickListener
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
pathShape?.let {
it.build(context, w.toFloat(), h.toFloat())
if (it.hasEffects() && layerType != View.LAYER_TYPE_SOFTWARE) {
setLayerType(View.LAYER_TYPE_SOFTWARE, null)
}
}
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
pathShape?.draw(canvas!!)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (onMarkClickListener != null && pathShape != null) {
when(event!!.action) {
MotionEvent.ACTION_UP -> {
pathShape!!.marks.forEach {
val markItem = it.onItemClick(event.x, event.y)
if (markItem != null) {
if (it.hasSelectedDrawable()) {
invalidate()
}
onMarkClickListener!!.onMarkClick(it.getId(), markItem)
return true
}
}
}
}
super.onTouchEvent(event)
return true
}
return super.onTouchEvent(event)
}
}<file_sep>/pathshapeview/src/main/java/shape/path/view/graph/function/GraphFunction.kt
package shape.path.view.graph.function
import android.graphics.Matrix
import android.graphics.PointF
/**
* Created by root on 2/15/18.
*/
abstract class GraphFunction {
open val matrix = Matrix()
var originX = 0f
var originY = 0f
abstract fun onFunctionGetValue(xValue: Float, stepValue: Float, maxStepCount: Int): Float
fun offset(dx: Float, dy: Float) {
matrix.postTranslate(dx, dy)
}
fun rotate(angle: Float) {
matrix.postRotate(angle)
}
fun skew(kx: Float, ky: Float) {
matrix.postSkew(kx, ky)
}
open fun getTransformFunctionPoint(xValue: Float, stepValue: Float, maxStepCount: Int): PointF {
originX = xValue
originY = onFunctionGetValue(xValue, stepValue, maxStepCount)
return getTransformPoint(originX, originY)
}
fun getTransformPoint(x: Float, y: Float): PointF {
if (matrix.isIdentity) {
return PointF(x, y)
}
val array = FloatArray(2)
matrix.mapPoints(array, floatArrayOf(x, y))
return PointF(array[0], array[1])
}
}<file_sep>/pathshapeview/src/androidTest/java/shape/path/view/GradientProviderTest.kt
package shape.path.view
import android.graphics.PointF
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
import shape.path.view.fill.provider.GradientProvider
import shape.path.view.utils.MathUtils
/**
* Instrumented test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class GradientProviderTest {
private var gradient: GradientProvider = GradientProvider()
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
// test distance between points
assertEquals(5f, MathUtils.getLength(0f, 3f, 4f, 0f))
assertEquals(5f, MathUtils.getLength(0f, -3f, -4f, 0f))
//
var expectedP = PointF(500f, 500f)
var actualP = MathUtils.getVectorEndPoint(45f, 500f, 500f)
assertEquals(expectedP, actualP)
expectedP = PointF(500f, 0f)
actualP = MathUtils.getVectorEndPoint(0f, 500f, 500f)
assertEquals(expectedP, actualP)
expectedP = PointF(0f, 500f)
actualP = MathUtils.getVectorEndPoint(90f, 500f, 500f)
assertEquals(expectedP, actualP)
expectedP = PointF(500f, 0f)
actualP = MathUtils.getVectorEndPoint(180f, 500f, 500f)
assertEquals(expectedP, actualP)
expectedP = PointF(0f, 500f)
actualP = MathUtils.getVectorEndPoint(-90f, 500f, 500f)
assertEquals(expectedP, actualP)
//3,4,5 (53.13, 36.87, 90)
expectedP = PointF(3f, 4f)
actualP = MathUtils.getVectorEndPoint(53.13f, 5f)
assertEquals(expectedP, actualP)
expectedP = PointF(4f, 3f)
actualP = MathUtils.getVectorEndPoint(36.87f, 5f)
assertEquals(expectedP, actualP)
}
}
|
bfd537cf307b8e2c79d95c6275b4fa29b6ee8e1d
|
[
"Markdown",
"Kotlin",
"Gradle"
] | 37 |
Kotlin
|
medstudioinc/Android-PathShapeView
|
54433597c277191df263586884242140a5e665cd
|
478603f11b29e8ff111cec4b61bd4f0e9d7b5f93
|
refs/heads/master
|
<file_sep># Codemod for removing `debugger;`
[![NPM version][npm-image]][npm-url] [![Build Status][travis-image]][travis-url]
Simplest [`codemod`](https://github.com/facebook/jscodeshift) you can think of,
but is still handy: Remove all `debugger;` statements from your code.
You could also do a regex replace for this, but it wouldn't be as stable
and predictable and is much likely to miss something, all though removing
`debugger;` seems pretty straight forward.
## Usage from terminal
Install using
```
npm install -g rm-debugger
```
Run:
```
rm-debugger ./my/src
```
Usage
```shell
Usage: rm-debugger <path>... [options]
path Files or directory to transform
Options:
-c, --cpus (all by default) Determines the number of processes started.
-v, --verbose Show more information about the transform process [0]
-d, --dry Dry run (no changes are made to files)
-p, --print Print output, useful for development
--babel Apply Babel to transform files [true]
--extensions File extensions the transform file should be applied to [js]
```
Options same as running [`jscodeshift`](https://github.com/facebook/jscodeshift) directly,
but with a predefined codemod.
## License
[MIT License](http://en.wikipedia.org/wiki/MIT_License)
[npm-url]: https://npmjs.org/package/rm-debugger
[npm-image]: http://img.shields.io/npm/v/rm-debugger.svg?style=flat
[travis-url]: http://travis-ci.org/mikaelbr/rm-debugger
[travis-image]: http://img.shields.io/travis/mikaelbr/rm-debugger.svg?style=flat
<file_sep>'use strict';
debugger;
function foo () {
debugger;
setTimeout(() => { debugger; console.log('foo') });debugger;
}
<file_sep>{
"name": "rm-debugger",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "node tests/test.js | tap-spec",
"foo": "rm-debugger tests/fixture -d"
},
"bin": {
"rm-debugger": "./bin/rm-debugger.js"
},
"keywords": ["codemod", "jscodeshift", "remove debugger"],
"author": "<NAME> <<EMAIL>>",
"license": "MIT",
"devDependencies": {
"tap-spec": "^4.1.0",
"tape": "^4.2.2"
},
"dependencies": {
"jscodeshift": "^0.3.8",
"nomnom": "^1.8.1"
}
}
<file_sep>'use strict';
// codemod for removing debugger statements
module.exports = function(fileInfo, api) {
const j = api.jscodeshift;
return j(fileInfo.source)
.find(j.DebuggerStatement)
.forEach(function (path) {
j(path).remove()
})
.toSource();
}
|
fe9d8e235009f0cf9725f7a6b4f2b5308aaef9b5
|
[
"Markdown",
"JSON",
"JavaScript"
] | 4 |
Markdown
|
mikaelbr/rm-debugger
|
89a29be7db68c9fef0123184ae79aaef1af16ab1
|
9e6e6c2542ff62105b9ac23b3b8e17c6e51edda1
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import {
View, StyleSheet, Text, Image,
TouchableOpacity, TextInput, Alert, Modal,
ScrollView, KeyboardAvoidingView} from 'react-native';
import {Avatar, Icon} from 'react-native-elements';
import * as ImagePicker from 'expo-image-picker';
import { RFValue } from "react-native-responsive-fontsize";
import db from '../config';
import firebase from 'firebase';
import { DrawerItems } from "react-navigation-drawer";
export default class CustomSideBarMenu extends React.Component {
render() {
return (
<View style={styles.container}>
<View>
</View>
<Text></Text>
<View style={{ flex: 0.6 }}>
<DrawerItems {...this.props} />
</View>
<View style={styles.logOutContainer}>
<TouchableOpacity
style={styles.logOutButton}
onPress={() => {
this.props.navigation.navigate('WelcomeScreen');
firebase.auth().signOut();
}}
>
<Text>
Log Out
</Text>
</TouchableOpacity>
<Icon
name = 'logout'
type = 'antdesign'
size = {RFValue(20)}
iconStyle = {{paddingLeft: RFValue(10)}}
/>
</View>
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1
},
drawerItemsContainer: {
flex: 0.88
},
logOutContainer: {
flex: 0.2,
justifyContent: 'flex-end',
paddingBottom: 30
},
logOutButton: {
height: 30,
width: '100%',
justifyContent: 'center',
padding: 10
},
logOutText: {
fontSize: 30,
fontWeight: 'bold'
},
imageContainer: {
flex: 0.75,
width: "40%",
height: "20%",
marginLeft: 20,
marginTop: 30,
borderRadius: 40,
},
})
|
b0b53c5ab01f83d089b5ccd72f8f7d5ada6fe358
|
[
"JavaScript"
] | 1 |
JavaScript
|
advaitsharma223/curiQlem-Part1
|
403a6f5ca8fa2185dfdf9655ca242ed1e0dae3ff
|
19bf6d3360591e7df3e12d2d84ed66b0ad83a33b
|
refs/heads/master
|
<file_sep>#include "stdafx.h"
#include "Random.hpp"
#include "VectorWriter.hpp"
LPCTSTR destPath = LR"(C:\Temp\2remove\simd)";
// Make them 1GB files
constexpr size_t scalarsPerTest = 1024 * 1024 * 256;
template<class TFunc, class TVec = __m256>
static inline void generate( LPCTSTR name )
{
CPath path;
path.m_strPath = destPath;
const CString fileName = CString{ name } + L".bin";
path.Append( fileName );
CAtlFile file;
HRESULT hr = file.Create( path.m_strPath, GENERIC_WRITE, 0, CREATE_ALWAYS );
if( FAILED( hr ) )
__debugbreak();
VectorWriter<TVec> writer{ file };
printf( "Generating \"%S\"\n", path.m_strPath.operator LPCWSTR() );
constexpr size_t vectorSize = sizeof( TVec ) / 4;
const size_t countVectors = scalarsPerTest / vectorSize;
TFunc func;
for( size_t i = 0; i < countVectors; i++ )
{
const TVec val = func.next();
writer.write( val );
}
}
struct GeneratorBase
{
RandomNumbers lhs, rhs;
GeneratorBase() : lhs( 0xC4000C40u ), rhs( 0x946E36B2u ) { }
};
struct TestSum : GeneratorBase
{
__forceinline __m256 next()
{
__m256 a, b;
lhs.next( a );
rhs.next( b );
return _mm256_add_ps( a, b );
}
};
struct TestMul : GeneratorBase
{
__forceinline __m256 next()
{
__m256 a, b;
lhs.next( a );
rhs.next( b );
return _mm256_mul_ps( a, b );
}
};
struct TestFma : GeneratorBase
{
RandomNumbers acc;
TestFma() : acc( 0xFFEE0033 ) { }
__forceinline __m256 next()
{
__m256 a, b, c;
lhs.next( a );
rhs.next( b );
acc.next( c );
return _mm256_fmadd_ps( c, a, b );
}
};
struct TestConvert : GeneratorBase
{
__forceinline __m256 next()
{
__m256 a;
lhs.next( a );
__m256i ints = _mm256_cvtps_epi32( a );
return _mm256_castsi256_ps( ints );
}
};
void saveExactMathBinaries()
{
CreateDirectory( destPath, nullptr );
generate<TestSum>( L"vaddps" );
generate<TestMul>( L"vmulps" );
generate<TestFma>( L"vfmadd" );
generate<TestConvert>( L"vcvtps2dq" );
}
#include "rcppsErrorSummary.h"
int main()
{
// saveExactMathBinaries();
rcppsErrorSummary();
return 0;
}<file_sep>#include "stdafx.h"
#include "Random.hpp"
#include <random>
RandomNumbers::RandomNumbers( uint32_t seed )
{
std::mt19937 engine{ seed };
alignas( 16 ) std::array<uint32_t, 4> _state, _key;
for( int i = 0; i < 4; i++ )
_state[ i ] = engine();
for( int i = 0; i < 4; i++ )
_key[ i ] = engine();
state = _mm_load_si128( ( __m128i* )_state.data() );
key = _mm_load_si128( ( __m128i* )_key.data() );
}<file_sep>#pragma once
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <windows.h>
#include <stdio.h>
#include <array>
#include <vector>
#include <algorithm>
#include <atltypes.h>
#include <atlstr.h>
#include <atlpath.h>
#include <atlfile.h><file_sep>#include "stdafx.h"
#include "rcppsErrorSummary.h"
#include <omp.h>
#include <assert.h>
// How many floats are processed by each iteration. The iterations are running in parallel, of course.
constexpr uint32_t floatsPerChunk = 1024 * 1024;
// We use AVX, have 8 lanes in a vector
constexpr uint32_t vectorsPerChunk = floatsPerChunk / 8;
// Store 3 integer lanes out of 4, with 2 instructions
__forceinline void store3( uint32_t* dest, const __m128i v )
{
_mm_storeu_si64( dest, v );
// Extract can store directly to memory, so this compiles into a single instruction like `vpextrd dword ptr [rcx-4], xmm2, 2`
dest[ 2 ] = _mm_extract_epi32( v, 2 );
}
// A single bucket of the output
struct Bucket
{
// Meaning of indices in both arrays: 0 = equal, 1 = the approximate was less than the precise, 2 = the approximate was greater than precise
// Total count of values in the bucket
std::array<uint32_t, 3> counts;
// Maximum absolute difference in the bucket. Because index 0 means "they are equal", the first element is always 0.
std::array<uint32_t, 3> maxDiff;
// Helper methods to load and store. Store only does 3 out of 4 lanes of the argument.
__forceinline __m128i loadCount() const
{
return _mm_loadu_si128( ( const __m128i* )counts.data() );
}
__forceinline __m128i loadMaxDiff() const
{
return _mm_loadu_si128( ( const __m128i* )maxDiff.data() );
}
__forceinline void storeCount( const __m128i v )
{
store3( counts.data(), v );
}
__forceinline void storeMaxDiff( const __m128i v )
{
store3( maxDiff.data(), v );
}
};
// A collection of all 0x200 buckets of the output. The index in the array is the high 9 bits of the precise float value, containing sign and exponent.
struct ThreadContext
{
std::array<Bucket, 0x200> buckets;
ThreadContext()
{
ZeroMemory( this, sizeof( ThreadContext ) );
}
inline void mergeFrom( const ThreadContext& other )
{
// This code runs rarely, not too much point in using SIMD for this, but scalar instructions can't natively compute max, std::max compiles into compare + conditional move
const Bucket* src = other.buckets.data();
const Bucket* const srcEnd = src + 0x200;
Bucket* dest = buckets.data();
for( ; src < srcEnd; src++, dest++ )
{
// Load them into SIMD registers
const __m128i c1 = src->loadCount();
const __m128i ax1 = src->loadMaxDiff();
const __m128i c2 = dest->loadCount();
const __m128i ax2 = dest->loadMaxDiff();
// Merge and store: adding counts, computing maximum of the differences
dest->storeCount( _mm_add_epi32( c1, c2 ) );
dest->storeMaxDiff( _mm_max_epu32( ax1, ax2 ) );
}
}
};
// Get low half of AVX register; compiles into no instructions
__forceinline __m128i vget_low( __m256i x )
{
return _mm256_castsi256_si128( x );
}
// Get high half of AVX register; AMD64 doesn't have register names for higher halves, this compiles into an extract instruction.
__forceinline __m128i vget_high( __m256i x )
{
return _mm256_extracti128_si256( x, 1 );
}
template<int lane16, int lane32>
__forceinline void accumulateLane( Bucket* const buckets, const int comparisons, const __m128i preciseExpVec, const __m128i absDiffVec )
{
// Extract scalar lanes from input vectors
const uint16_t exponent = _mm_extract_epi16( preciseExpVec, lane16 );
assert( exponent < 0x200 );
const uint32_t absDiff = (uint32_t)_mm_extract_epi32( absDiffVec, lane32 );
// Extract 2 bits from the comparisons which is index of the value within the bucket
const int cmpMask = ( comparisons >> ( lane16 * 2 ) ) & 3;
assert( 3 != cmpMask );
// Update the destination bucket
Bucket& bucket = buckets[ exponent ];
bucket.counts[ cmpMask ]++;
bucket.maxDiff[ cmpMask ] = std::max( bucket.maxDiff[ cmpMask ], absDiff );
}
template<bool isNegative>
static void computeChunk( int index, ThreadContext& dest )
{
// We don't want cache line sharing, that's why using local context to compute stuff, merging in the end
// Unlike std::vector elements, thread stacks are very far away from each other in memory
ThreadContext context;
// Initialize the source vector, it's incremented on each iteration
const uint32_t firstFloat = (uint32_t)index * floatsPerChunk;
__m256i integers = _mm256_set1_epi32( (int)firstFloat );
integers = _mm256_add_epi32( integers, _mm256_setr_epi32( 0, 1, 2, 3, 4, 5, 6, 7 ) );
// Prepare a couple of constants
const __m256 one = _mm256_set1_ps( 1.0f );
Bucket* const buckets = context.buckets.data();
const __m256i advanceOffsets = _mm256_set1_epi32( 8 );
// The main loop of the chunk
for( uint32_t i = 0; i < vectorsPerChunk; i++ )
{
// Compute these floats
const __m256 floats = _mm256_castsi256_ps( integers );
const __m256 preciseFloats = _mm256_div_ps( one, floats );
const __m256 approxFloats = _mm256_rcp_ps( floats );
// Cast to integers and extract exponent + sign portions. Sign is 1 bit, exponent is 8.
const __m256i precise = _mm256_castps_si256( preciseFloats );
const __m256i approx = _mm256_castps_si256( approxFloats );
const __m256i expValues = _mm256_srli_epi32( precise, 32 - 9 );
// The exponent+sign only takes 9 bits, packing all 8 values into SSE register.
// Despite there're AVX2 extract intrinsics defined, there're no AVX2 extract instructions apart from vextracti128 and similar, compilers are emulating with 1-2 instructions based on immediate argument.
const __m128i preciseExp = _mm_packus_epi32( vget_low( expValues ), vget_high( expValues ) );
// Subtract and compute absolute difference of integer representations
const __m256i absDiff = _mm256_abs_epi32( _mm256_sub_epi32( approx, precise ) );
// Compare both ( approx > precise ) and ( approx < precise ), move all 16 results into scalar register
// Negative floats have their sort order flipped relative to integers.
// The condition is true or false for complete chunks, only testing that once per chunk outside the loop
// Passing that value as a template argument for optimal performance, unlike regular branches `if constexpr` has no runtime overhead.
__m256i greater, less;
if constexpr( isNegative )
{
greater = _mm256_cmpgt_epi32( precise, approx );
less = _mm256_cmpgt_epi32( approx, precise );
}
else
{
greater = _mm256_cmpgt_epi32( approx, precise );
less = _mm256_cmpgt_epi32( precise, approx );
}
const __m256i comparisonsAvx = _mm256_blend_epi16( less, greater, 0b10101010 ); // Now we have 16-bit lanes set to either -1 or 0, based on these comparisons
const __m128i comparisonsSse = _mm_packs_epi16( vget_low( comparisonsAvx ), vget_high( comparisonsAvx ) ); // Pack them into bytes
const int comparisons = _mm_movemask_epi8( comparisonsSse ); // Move all 16 values into bits of the scalar register
assert( comparisons >= 0 && comparisons < 0x10000 );
// The scalar portion of the function.
// Can't use scatter/gather instructions because lanes of the same vector may update same bucket of the result.
__m128i tmp = vget_low( absDiff );
accumulateLane<0, 0>( buckets, comparisons, preciseExp, tmp );
accumulateLane<1, 1>( buckets, comparisons, preciseExp, tmp );
accumulateLane<2, 2>( buckets, comparisons, preciseExp, tmp );
accumulateLane<3, 3>( buckets, comparisons, preciseExp, tmp );
tmp = vget_high( absDiff );
accumulateLane<4, 0>( buckets, comparisons, preciseExp, tmp );
accumulateLane<5, 1>( buckets, comparisons, preciseExp, tmp );
accumulateLane<6, 2>( buckets, comparisons, preciseExp, tmp );
accumulateLane<7, 3>( buckets, comparisons, preciseExp, tmp );
// Advance to the next 8 values
integers = _mm256_add_epi32( integers, advanceOffsets );
}
// Merge the result into the destination.
// No locking is needed because the calling code has a context for each native thread, uses omp_get_thread_num() to index
dest.mergeFrom( context );
}
// Print a row of the table
static void print( int index, const Bucket& b )
{
// Sign & exponent
const char sign = ( index & 0x100 ) ? '-' : '+';
printf( "%c\t", sign );
const int exponent = index & 0xFF;
if( 0 == exponent )
printf( "DEN" );
else if( 0xFF == exponent )
printf( "NAN" );
else
printf( "2^%i", exponent - 127 );
// Counters
const uint32_t total = b.counts[ 0 ] + b.counts[ 1 ] + b.counts[ 2 ];
printf( "\t%i\t", total );
for( int i = 0; i < 3; i++ )
printf( "%i\t", b.counts[ i ] );
// Differences
printf( "%i\t%i\t%i\n", b.maxDiff[ 1 ], b.maxDiff[ 2 ], std::max( b.maxDiff[ 1 ], b.maxDiff[ 2 ] ) );
}
void rcppsErrorSummary()
{
std::vector<ThreadContext> threads;
threads.resize( (size_t)omp_get_max_threads() );
constexpr int chunksCount = ( (size_t)1 << 32 ) / floatsPerChunk;
// Run the main loop with OpenMP
#ifdef NDEBUG
#pragma omp parallel for schedule( static, 1 )
#endif
for( int i = 0; i < chunksCount; i++ )
{
ThreadContext& ctx = threads[ omp_get_thread_num() ];
if( i < ( chunksCount / 2 ) )
computeChunk<false>( i, ctx );
else
computeChunk<true>( i, ctx );
}
// Merge per-thread results into the final one
ThreadContext result;
for( const auto& c : threads )
result.mergeFrom( c );
// Print it as tab-separated values, with a header
printf( "sign\texp\ttotal\texact\tless\tgreater\tmaxLess\tmaxGreater\tmaxAbs\n" );
for( int i = 0; i < 0x100; i++ )
{
const int neg = i | 0x100;
print( neg, result.buckets[ neg ] );
print( i, result.buckets[ i ] );
}
}<file_sep>#pragma once
// Utility class to write SIMD vectors into a file, fast.
template<class TVec>
class VectorWriter
{
CAtlFile& file;
static constexpr size_t capacity = ( 1024 * 8 ) / sizeof( TVec );
std::array<TVec, capacity> buffer;
size_t count = 0;
void flush()
{
const DWORD cb = (DWORD)( count * sizeof( TVec ) );
HRESULT hr = file.Write( buffer.data(), cb );
if( SUCCEEDED( hr ) )
{
count = 0;
return;
}
__debugbreak();
}
public:
VectorWriter( CAtlFile& f ) : file( f ) { }
~VectorWriter()
{
if( count > 0 )
flush();
}
__forceinline void write( TVec v )
{
if( count < capacity )
{
buffer[ count++ ] = v;
return;
}
flush();
buffer[ 0 ] = v;
count = 1;
}
};<file_sep>#pragma once
void rcppsErrorSummary();<file_sep>#pragma once
// Utility class to generate pseudo-random values, fast.
class RandomNumbers
{
__m128i key;
__m128i state;
public:
RandomNumbers( uint32_t seed );
__forceinline void next( __m128& result )
{
state = _mm_aesenc_si128( state, key );
result = _mm_castsi128_ps( state );
}
__forceinline void next( __m256& result )
{
__m128 low, high;
next( low );
next( high );
result = _mm256_insertf128_ps( _mm256_castps128_ps256( low ), high, 1 );
}
};
|
1b7dcbf50da96d58e9e13bd5eb9dac2b9113d364
|
[
"C",
"C++"
] | 7 |
C++
|
Const-me/SimdPrecisionTest
|
7b009df3061e78781e9860dbf48a8cb20d7ec609
|
4119097663a7e840e1c5fa4b452d109b43a9ca43
|
refs/heads/master
|
<repo_name>inmagination/buscaminas<file_sep>/Buscaminas/js/cronometro.js
// variable global que almacena el tiempo transcurrido
var time;
// función llamada cuando se cree el span del encabezado que contendrá el cronómetro
function cronometro(){
// inicializamos los minutos y segundos
var minutos = 0;
var segundos = 0;
// usamos setInterval para cambiar el tiempo cada segundo
setInterval(
function(){
// para que cambien los minutos en función de los segundos..
if(segundos == 59){
minutos++;
segundos = 0;
}else{ // o siga contando segundos
segundos++;
}
// para que nos ponga un '0' cuando los segundos son solo una unidad
if(segundos < 10) {
segundos = '0' + segundos;
}
// damos valor al span contenido en nuestro encabezado para visualizar el tiempo
that.campo.celdaEncabezado.childNodes[0].innerHTML = minutos + ':' + segundos;
// almacenamos en un array los minutos y segundos
time = [minutos, segundos];
}, 1000); // 1000 -> es un segundo en milisegundos, es cada cuanto tiempo se ejecuta la fn del tiempo
}<file_sep>/Buscaminas/js/contarMinasAlrededor.js
function contarMinasAlrededor(){
var contador = 0;
var valorCelda;
// recorremos el array de celdas vecinas
for(var i=0; i< that.celdasVecinas.length; i++){
// nos aseguramos que exista la celda
if(that.celdasVecinas[i] != undefined){
// sacamos el valor de la celda
valorCelda = parseInt(that.celdasVecinas[i].getAttribute('data-campominado-valor'));
// si el valor de la celda es 1 es una mina por lo que el contador aumenta
if(valorCelda == 1){
contador++;
}
}
}
// devolvemos el contador
return contador;
}<file_sep>/Buscaminas/js/clickSobreCelda.js
function clickSobreCelda(miEvento){
// recogemos la celda (elemento td) que ha lanzado el evento
var celda = miEvento.target;
// invocamos el método ocuparCelda de CampoMinado
that.ocuparCelda(celda);
}<file_sep>/Buscaminas/js/mostrarResultados.js
// mostrar los resultados del ranking al usuario
function mostrarResultados(partidas){
// creamos la ventana nueva donde irán los resultados
var popUp = window.open("", "RANKING", "width=500,height=650,Scrollbars=YES");
// estructura html + link al css del popup (popup.css)
popUp.document.write('<html><head><link rel="stylesheet" type="text/css" href="./estilos/popup.css" media="screen" /></head>');
// div que contiene el titulo del popup y las tablas de los rankings por dificultad
popUp.document.write('<body><div class=ranking><h2 class=title>RANKING</h2>');
// invocamos los resultados en función de su dificultad
resultadosDificultad(popUp, 'Muy Fácil', partidas);
resultadosDificultad(popUp, 'Fácil', partidas);
resultadosDificultad(popUp, 'Normal', partidas);
resultadosDificultad(popUp, 'Difícil', partidas);
resultadosDificultad(popUp, 'Muy Difícil', partidas);
// cierre estructura html
popUp.document.write('</div></body></html>');
}
///////////////////////////////////////////////////////////////
// para agrupar los resultados en función de su dificultad
function resultadosDificultad(popUp, dificultad, partidas){
// nos servirá para contar las partidas en esa dificultad
var contadorPartidas = 0;
// variable que indica la posición del jugador en el ranking
var posicion = 0;
// tabla con cabeceras que indica la dificultad y la info de la tabla
popUp.document.write('<table align=center>' +
'<th colspan=5>' + dificultad + '</th>' +
'<tr class=infoTabla>' +
'<td>Posición</td>' +
'<td>Partida</td>' +
'<td>Nombre</td>' +
'<td>Dificultad</td>' +
'<td>Tiempo</td>' +
'</tr>');
// recorremos el array de partidas buscando aquellas que sean de la dificultad que queremos
for(var i=0; i<partidas.length; i++){
// si la dificultad es la que queremos..
if(partidas[i][2] == dificultad){
// calculamos la posicion de la partida dentrod e la tabla de la dificultad elegida
posicion = contadorPartidas + 1;
// construimos una fila con los datos de la partida en la tabla
popUp.document.write('<tr>' +
'<td>' + posicion + '</td>' +
'<td>' + partidas[i][0] + '</td>' +
'<td>' + partidas[i][1] + '</td>' +
'<td>' + partidas[i][2] + '</td>' +
'<td>' + partidas[i][3] + ':' + partidas[i][4] + '</td>' +
'</tr>');
// aumentamos el contador de partidas
contadorPartidas++;
}
}
// fila que enseña la cantidad de partidas de la dificultad
popUp.document.write('<tr class=infoContador><td colspan=5>Total Partidas en ' + dificultad +': ' + contadorPartidas + '</td></tr>');
// cierre de tabla
popUp.document.write('</table>');
}<file_sep>/Buscaminas/js/mostrarCampo.js
function mostrarCampo(){
// ocultamos el formulario inicial
that.divPadre.childNodes[1].style.display = "none";
// agregamos el tablero a divPadre
that.divPadre.appendChild(that.campo.tablero);
}<file_sep>/Buscaminas/js/ordenarResultados.js
// pasar tiempo a segundos para poder ordenarlo más fácilmente
function todoSegundos(partidas){
for(var i=0; i<partidas.length; i++){
// si los minutos son mayores que 0 los convertimos a segundos
if(parseInt(partidas[i][3]) > 0){
partidas[i][4] = (parseInt(partidas[i][3]) * 60) + parseInt(partidas[i][4]);
partidas[i][3] = 0;
}
}
// retornamos el array de partidas modificado
return partidas;
}
///////////////////////////////////////////////////////////////
// ordenar las partidas de menor a mayor cantidad de segundos
function ordenar(partidas){
var menor;
// recorremos el array siempre comparando dos tiempos consecutivos
for (var i=0; i<(partidas.length-1); i++){
for(var j=(i+1); j<partidas.length; j++){
// si la partida posterior es menor en tiempo que la anterior alteramos su orden
if(partidas[j][4] < partidas[i][4]){
menor = partidas[j];
partidas[j] = partidas[i];
partidas[i] = menor;
}
}
}
// retornamos el array de partidas modificado
return partidas;
}
///////////////////////////////////////////////////////////////
// una vez ordenado cronológicamente las partidas devolvemos al formato minutos + segundos
function minutosSegundos(partidas){
var minutos;
for(var i=0; i<partidas.length; i++){
minutos = parseInt(partidas[i][4]);
// hallamos los minutos y segundos correspondientes
// se usa Math.floor para evitar minutos decimales
if(minutos > 60){
partidas[i][3] = Math.floor(minutos / 60);
partidas[i][4] = minutos % 60;
}
// para agregar el 0 si los segundos tienen solo un dígito
if(partidas[i][4] < 10){
partidas[i][4] = '0' + parseInt(partidas[i][4]);
}
}
// retornamos el array de partidas modificado
return partidas;
}<file_sep>/Buscaminas/js/elegirRutaSegura.js
function elegirRutaSegura(){
var movimientos = new Array(); // array para guardar los movimientos a la derecha y abajo
var asignar; // para cuando se van obteniendo las casillas seguras
var fila, columna;
// calcula el máximo número de movimientos hacia abajo
for(var i = 0; i < that.filas -1; i++){
movimientos.push('x');
}
// calcula el número máximo de movimientos hacia la derecha
for(var j = 0; j < that.columnas - 1; j++){
movimientos.push('y');
}
// hacemos que la primera casilla sea siempre segura
fila = 0;
columna = 0;
that.campo.celda[fila][columna].setAttribute("data-campominado-valor", '2');
// mientras tengamos casillas disponible asignamos casillas seguras de forma aleatoria
while(movimientos.length > 0){
asignar = Math.floor(Math.random() * movimientos.length);
if (movimientos.splice(asignar,1)[0] == 'x') {
fila++;
} else{
columna++;
};
//asignamos a la celda segura su valor
that.campo.celda[fila][columna].setAttribute("data-campominado-valor", '2');
that.campo.celda[fila][columna].setAttribute("class", 'safe');
}
}<file_sep>/Buscaminas/js/mostrarMinas.js
function mostrarMinas(tablero){
var filas = tablero.childNodes;
var celda, valor;
for(var i=1; i<filas.length; i++){
for(var j=0; j<filas[i].childNodes.length; j++){
celda = filas[i].childNodes[j];
valor = celda.getAttribute('data-campominado-valor');
if(valor == 1){
celda.setAttribute("class", "mina");
}
else if(valor == 2){
celda.setAttribute("class","safe");
}
}
}
}<file_sep>/Buscaminas/js/ocuparCelda.js
function ocuparCelda(celda){
console.log("ocuparceldas");
var valorCelda, filaCelda, columnaCelda;
var ultimaFila, ultimaColumna;
var encabezado, textoNuevo;
var minas, celdaRellena;
var jugador;
// ver si la celda es accesible, si no el click no hará nada
if(celda == that.celdasAccesibles[0] || celda == that.celdasAccesibles[1] || celda == that.celdasAccesibles[2] || celda == that.celdasAccesibles[3]){
// valor, fila y columna de la celda activa
valorCelda = parseInt(celda.getAttribute('data-campominado-valor'));
filaCelda = parseInt(celda.getAttribute('data-campominado-fila'));
columnaCelda = parseInt(celda.getAttribute('data-campominado-columna'));
// valores de la última fila y columna del tablero
ultimaFila = that.filas - 1;
ultimaColumna = that.columnas - 1;
// quitamos el borde a la anterior celda activa para ver la que se activa cada vez que ocupamos la celda con un borde gris oscuro
that.anteriorCeldaActiva.style.borderColor = "yellow";
// si es una mina o la celda inferior derecha se acaba el juego
if(valorCelda == 1 || (filaCelda == ultimaFila && columnaCelda == ultimaColumna)){
// si has ganado el juego el cronómetro se para para saber cuanto tiempo has empleado
if(filaCelda == ultimaFila && columnaCelda == ultimaColumna){
// paramos el cronómetro con clearInterval
clearInterval();
// pedimos al jugador su nombre para el ranking
jugador = prompt('Introduce tu nombre: ');
// creamos la cookie con el nombre del jugador, dificultad y tiempo
creaCookie(jugador, dificultad, time);
// obtenemos las cookies para que se visualice el ranking
obtenCookie();
}
// guardamos la celda en anteriorCeldaActiva para poder acceder a ella en gestionarTeclado
that.anteriorCeldaActiva = celda;
// vamos a la celda encabezado y eliminamos el texto nodo (jugando...)
encabezado = that.campo.celdaEncabezado;
encabezado.removeChild(encabezado.childNodes[0]);
// creamos nuevo nodo texto y lo agregamos a la celda encabezado
textoNuevo = document.createTextNode('FIN DE PARTIDA');
encabezado.appendChild(textoNuevo);
// mostrar las minas al finalizar el juego
mostrarMinas(that.campo.tablero);
// evento click del encabezado que nos llevara a la página inicial del formulario
that.campo.celdaEncabezado.addEventListener('click', function(){
location.assign('buscaminas.html');
}, false);
}else{ // sigue el juego
// referenciar la celda anterior activa y cambiar el color para poder seguir la ruta realizada
that.anteriorCeldaActiva = celda;
that.anteriorCeldaActiva.setAttribute("class", "anteriorActiva");
// ponemos el borde de otro color para ver la celda actualmente activa
celda.style.borderColor = "black";
// actualizar celdas vecinas y accesibles
that.actualizarCeldasVecinas();
that.actualizarCeldasAccesibles();
// contar minas para poner en la celda activa cuantas hay alrededor
minas = that.contarMinasAlrededor();
// para que no nos pinte de nuevo el número de minas si volvemos atrás en la ruta realizada
if(!that.anteriorCeldaActiva.childNodes[0]){
celdaRellena = document.createTextNode(minas);
celda.appendChild(celdaRellena);
}
console.log(that.celdasVecinas);
console.log(that.celdasAccesibles);
}
}
}<file_sep>/Buscaminas/js/establecerDificultad.js
function establecerDificultad(){
var meterValue, spanValue;
// coger el valor del elemento range
var range = document.getElementById('range').value;
// según el valor de range establecemos el valor del meter y del span
switch(range){
case "1": meterValue = 0.0;
spanValue = " Muy fácil";
break;
case "2": meterValue = 0.25;
spanValue = " Fácil";
break;
case "3": meterValue = 0.50;
spanValue = " Normal";
break;
case "4": meterValue = 0.75;
spanValue = " Difícil";
break;
case "5": meterValue = 1;
spanValue = " Muy Difícil";
break;
}
// a través del DOM cogemos el meter y el span y les asignamos los valores correspondientes
var meterElement = document.getElementById('meter');
meterElement.setAttribute("value",meterValue);
var spanElement = document.getElementById('span');
spanElement.innerHTML = spanValue;
} <file_sep>/Buscaminas/js/ubicarMinas.js
function ubicarMinas(){
var fila, columna, valorCelda;
// obtenemos el número de minas a insertar dependiendo de la dificultad asignada
var numMinas = Math.round(that.filas * that.columnas * (that.dificultad * 0.1));
// mientras dispongamos de minas las iremos insertando en posiciones aleatorias
while (numMinas > 0){
fila = Math.floor(Math.random() * that.filas);
columna = Math.floor(Math.random() * that.columnas);
valorCelda = that.campo.celda[fila][columna].getAttribute("data-campominado-valor");
// debemos asegurarnos que el valor sea 0 ya que si es el 2 pondremos minas en la ruta segura
if (valorCelda == '0'){
that.campo.celda[fila][columna].setAttribute("data-campominado-valor", '1');
numMinas--;
}
}
}<file_sep>/Buscaminas/js/CampoMinado.js
// guardamos en una variable global el valor de this para asegurarnos que siempre apunte a donde nos interese
var that = this;
function CampoMinado(filas, columnas, dificultad, divPadre){
// propiedades
that.filas = filas;
that.columnas = columnas;
that.dificultad = dificultad;
that.divPadre = divPadre;
that.celdasVecinas = [];
that.celdasAccesibles = [];
that.anteriorCeldaActiva = null;
// métodos
that.construirCampo = construirCampo;
that.mostrarCampo = mostrarCampo;
that.elegirRutaSegura = elegirRutaSegura;
that.ubicarMinas = ubicarMinas;
that.actualizarCeldasVecinas = actualizarCeldasVecinas;
that.actualizarCeldasAccesibles = actualizarCeldasAccesibles;
that.contarMinasAlrededor = contarMinasAlrededor;
that.clickSobreCelda = clickSobreCelda;
that.ocuparCelda = ocuparCelda;
that.mostrarMinas = mostrarMinas;
that.inicializar = inicializar;
// método para poder usar el teclado
that.gestionarTecla = function gestionarTecla(miEvento){
// guardamos el código de la tecla en una variable
var tecla = miEvento.keyCode;
// celda que usaremos como referencia para movernos por teclado
var celda = that.anteriorCeldaActiva;
// fila , columna y valor de la celda
var fila = parseInt(celda.getAttribute('data-campominado-fila'));
var columna = parseInt(celda.getAttribute('data-campominado-columna'));
var valor = parseInt(celda.getAttribute('data-campominado-valor'));
// límite de filas y columnas
var ultimaFila = that.filas - 1;
var ultimaColumna = that.columnas - 1;
// nos aseguramos que sean las flechas de dirección del teclado lo que pulsamos
if(tecla == 37 || tecla == 38 || tecla == 39 || tecla == 40){
// dependiendo de la tecla que pulsemos fila o columna varían de valor
switch(tecla){
case 37: columna--; // izquierda
break;
case 38: fila--; // arriba
break;
case 39: columna++; // derecha
break;
case 40: fila++; // abajo
break;
}
// si la fila y columna no son negativos y no superan los límites del tablero...
if((fila >= 0 && columna >=0) && (fila <= ultimaFila && columna <= ultimaColumna)){
// hacemos que la celda apunte bien al elemento deseado del tablero
// sin esta linea aunque celda tenga los atributos de fila y columna bien señala a la anteriorCeldaActiva
celda = that.campo.celda[fila][columna];
// cambiamos los atributos fila y columna de la celda
celda.setAttribute('data-campominado-fila', fila);
celda.setAttribute('data-campominado-columna', columna);
// llamamos a ocuparCelda con la celda obtenida asociada a la propiedad celda del objeto campo
// si pasamos solo el parámetro celda no entiende que ese elemento es una celda del tablero
that.ocuparCelda(that.campo.celda[fila][columna]);
}
// si lo que pulsamos es el enter y es una mina o la última casilla...
}else if((tecla == 13 && valor == 1) || (tecla == 13 && (fila == ultimaFila && columna == ultimaColumna))){
// redirigimos al formulario inicial
location.assign('buscaminas.html');
}
}
}
// En el caso de poner la función en un archivo js externo en vez de incluído en el archivo CampoMinado.js se comporta exactamente igual.
// Esto es debido a que el código de la función es exactamente el mismo y aunque esté en un sitio o en otro está relacionado con el mismo método del objeto CampoMinado.<file_sep>/Buscaminas/js/jugar.js
// wrapper de la aplicación
function jugar(){
// coger variables formulario
var filas = parseInt(document.getElementById('filas').value);
var columnas = parseInt(document.getElementById('columnas').value);
var dificultad = document.getElementById('range').value;
var divPadre = document.getElementById('divPadre');
// crear objeto CampoMinado e inicializarlo
var tablero = new CampoMinado(filas,columnas,dificultad,divPadre);
inicializar.call(tablero);
}
<file_sep>/README.md
buscaminas
==========
<file_sep>/Buscaminas/js/actualizarCeldasAccesibles.js
function actualizarCeldasAccesibles(){
// vaciamos el array para actualizarlo cada vez que usemos el método
that.celdasAccesibles = [];
// introducimos en el array las celdas de arriba, izquierda, derecha y abajo de la celda activa
that.celdasAccesibles.push(that.celdasVecinas[1], that.celdasVecinas[3], that.celdasVecinas[4], that.celdasVecinas[6]);
}<file_sep>/Buscaminas/js/construirCampo.js
function construirCampo(){
// definimos objeto campo
that.campo = {
tablero : document.createElement("table"),
celdaEncabezado : document.createElement("td"),
celda : new Array()
};
// atributos de la celda encabezado
that.campo.celdaEncabezado.setAttribute("colspan", that.columnas);
that.campo.celdaEncabezado.setAttribute("class","encabezado");
// texto del encabezado, creamos span y lo agregamos al encabezado
var texto = document.createElement('span');
that.campo.celdaEncabezado.appendChild(texto);
// llamamos a cronometro que es el encargado de crear el tiempo y visualizarlo
that.cronometro();
// creamos el elemento tr a partir del cual agregaremos las filas de nuestra tabla
var tr = document.createElement("tr");
tr.appendChild(that.campo.celdaEncabezado);
that.campo.tablero.appendChild(tr);
// bucle dentro de otro para construir el tablero de juego
for (var i = 0; i < that.filas; i++) {
that.campo.celda[i] = [];
var fila = document.createElement("tr");
// celdas de cada fila con sus respectivos atributos
for (var j = 0; j < that.columnas; j++) {
that.campo.celda[i][j] = document.createElement("td");
that.campo.celda[i][j].setAttribute("data-campominado-valor",'0');
that.campo.celda[i][j].setAttribute("data-campominado-fila", i);
that.campo.celda[i][j].setAttribute("data-campominado-columna", j);
that.campo.celda[i][j].setAttribute("class","celdas");
fila.appendChild(that.campo.celda[i][j]);
}
// agregamos cada fila creada al tablero
that.campo.tablero.appendChild(fila);
}
}<file_sep>/Buscaminas/js/inicializar.js
function inicializar(){
that.construirCampo();
that.elegirRutaSegura();
that.ubicarMinas();
// la primera celda es accesible ya que si no ignora el click en ocupar celda
that.celdasAccesibles = new Array(that.campo.celda[0][0]);
// primera celda como anterior activa
that.anteriorCeldaActiva = that.campo.celda[0][0];
// para que el juego funcione con el teclado...
// con esto la primera celda aparecerá como activa al iniciar el juego
that.ocuparCelda(that.anteriorCeldaActiva);
that.mostrarCampo();
// asignar evento click al tablero
that.campo.tablero.addEventListener('click', clickSobreCelda, false);
// asignar evento keydown a todo el documento no al tablero ya que no podemos
// como la fn oyente está en inicializar no se lanzarán eventos de teclado en el formulario inicial
document.getElementById('divPadre').parentNode.addEventListener('keydown', gestionarTecla, false);
}
|
5306475dcf955f02242b0a03867c3318ca459b8d
|
[
"JavaScript",
"Markdown"
] | 17 |
JavaScript
|
inmagination/buscaminas
|
69aff2ccd15ea0cd0d661442283a5030acd7f88c
|
79f176634504e964ed4d65a6274968d22fd44978
|
refs/heads/master
|
<file_sep>class AddColumnManageTableGames < ActiveRecord::Migration
def up
add_column :games, :manager, :string
end
def down
end
end
<file_sep>class Player < ActiveRecord::Base
resourcify
belongs_to :game
belongs_to :user
PLAYER_ROLE = ['don','mafia','sheriff','citizen'].freeze
PLAYER_TEAM = ['red', 'black'].freeze
attr_accessible :user_id, :game_id, :id, :role, :team, :player_number, :remark, :kill, :nominate
validates :user_id, presence: true
validates :role, :inclusion => { :in => PLAYER_ROLE }, on: :update
validates :team, :inclusion => { :in => PLAYER_TEAM }, on: :update
delegate :result_black?, :result_red?, to: :game
#def methods is_don? is_mafia? is_sheriff? is_citizen?
PLAYER_ROLE.each do |type|
define_method("is_#{type}?") {role.to_s == type}
end
#def methods team_red? team_black?
PLAYER_TEAM.each do |type|
define_method("team_#{type}?") {team.to_s == type}
end
def set_team!
if is_don? || is_mafia?
update_attribute(:team, 'black')
else
update_attribute(:team, 'red')
end
end
def opts
if is_mafia?
{ system_email: '<EMAIL>',
system_support_email: '<EMAIL>',
system_host: 'onapp.com'
}.any? { |opt, val| OnApp.configuration.send(opt) == val }
end
end
def set_score!
if game.result_red?
if team_red? && is_sheriff?
update_attribute(:score, 4 )
elsif team_red?
update_attribute(:score, 3 )
elsif team_black? && is_don?
update_attribute(:score, -1)
elsif team_black?
update_attribute(:score, 0 )
end
elsif game.result_black?
if team_black? && is_don?
update_attribute(:score, 5)
elsif team_black?
update_attribute(:score, 4)
elsif team_red? && is_sheriff? && !game.first_killed_sheriff
update_attribute(:score, -1)
elsif team_red?
update_attribute(:score, 0)
end
else
update_attribute(:score, 0 )
end
end
def won!
if game.result_red?
red_winner
elsif game.result_black?
black_winner
end
end
private
def red_winner
if team_red?
update_attribute(:won, true)
elsif team_black?
update_attribute(:won, false)
end
end
def black_winner
if team_red?
update_attribute(:won, false)
elsif team_black?
update_attribute(:won, true)
end
end
end
<file_sep>class BestPlayerType < ActiveRecord::Migration
def up
change_column :games, :best_player, :string
end
def down
end
end
<file_sep>#require 'services/reference'
class Game < ActiveRecord::Base
resourcify
extend FriendlyId
friendly_id :game_ref
attr_accessible :game_status, :result, :description, :game_manager, :players_attributes, :best_player, :game_ref, :first_killed_sheriff
attr_accessor :game_manager
has_many :players, dependent: :destroy
has_many :users, :through => :players
has_one :manager, dependent: :destroy
accepts_nested_attributes_for :players
before_create :generate_game_ref
after_create :create_manager
validates :description, presence: true
GAME_RESULT = ['red', 'black'].freeze
#def methods result_black? result_red?
GAME_RESULT.each do |type|
define_method("result_#{type}?") {result.to_s == type}
end
def create_manager
if game_manager
Manager.create(user_id: self.game_manager, game_id: self.id)
end
end
def status_open?
game_status == 'open'
end
def game_result
result
end
def generate_game_ref
::ReferenceService.new(self).create_reference!
end
class << self
def search(search)
if search
where('result LIKE ? OR best_player LIKE ? ', "%#{search}%", "%#{search}%")
else
scoped
end
end
end
end
<file_sep>class BestPlayer < ActiveRecord::Migration
def up
change_column :games, :best_player, :integer
end
def down
end
end
<file_sep>class WonLost < ActiveRecord::Migration
def up
add_column :appointments, :won, :boolean
end
def down
end
end
<file_sep>class UsersController < ApplicationController
load_and_authorize_resource
helper_method :sort_column, :sort_direction
before_filter :user_scoped
respond_to :html
def index
@users = User.order(sort_column + ' ' + sort_direction).paginate(page: params[:page], per_page: 10).search(params[:search])
respond_with do |format|
format.html {
render :partial => 'users/table' if request.xhr?
}
end
end
def show
end
def edit
end
def update
@user.update_attributes(params[:user])
redirect_to users_path
end
def new
end
def create
@user = User.create(params[:user])
binding.pry
redirect_to users_path
end
def destroy
@user.destroy
redirect_to users_path
end
private
def user_scoped
@users = User.scoped
end
def sort_column
User.column_names.include?(params[:sort_column]) ? params[:sort_column] : 'created_at'
end
def sort_direction
%w[asc desc].include?(params[:sort_direction]) ? params[:sort_direction] : 'asc'
end
end
<file_sep>class RenameAppointmentToPlayer < ActiveRecord::Migration
def up
rename_table :appointments, :players
end
def down
rename_table :players, :appointments
end
end
<file_sep>class ScoresController < ApplicationController
helper_method :sort_column, :sort_direction
respond_to :html
def index
@users = User.order(sort_column + ' ' + sort_direction).paginate(page: params[:page], per_page: 5).search(params[:search])
respond_with do |format|
format.html {
render :partial => 'scores/scores_table' if request.xhr?
}
end
end
def show
@user = User.find(params[:id])
@score = Player.where(user_id: @user.id).count()
end
private
def sort_column
User.column_names.include?(params[:sort_column]) ? params[:sort_column] : 'created_at'
end
def sort_direction
%w[asc desc].include?(params[:sort_direction]) ? params[:sort_direction] : 'asc'
end
def pagination_items
binding.pry
%w[10 20].include? params[:per_page] ? params[:per_page] : 5
end
end
<file_sep>class PlayersController < ApplicationController
before_filter :find_game
respond_to :html, :js
def create
Rails.logger.info params
@player = @game.players.build(params[:player])
@player.save
respond_with @game, @player, :location => game_path(@game)
end
def create_bunch
@game.update_attributes(players_attributes: params.fetch(:player_data, []))
render nothing: true
end
def show
end
def destroy
@player = @game.players.find(params[:id])
@player.destroy
respond_with @game, @player, :location => game_path(@game)
end
def destroy_all
@players = @game.players.all.map(&:destroy)
respond_with @game, @player, :location => game_path(@game)
end
def set_role
Rails.logger.info params
@player = @game.players(params[:player])
#render 'players/role', layout: false
end
def put_roles
@game.update_attributes(params.fetch(:game, {}))
@game.players.each do |player|
player.set_team!
end
respond_with(@game, @player) do |format|
format.html { render partial: 'games/drop_zone' if request.xhr? }
end
end
def get_remarks
@player = @game.players(params[:player])
end
def put_remarks
@game.update_attributes(params.fetch(:game, {}))
respond_with(@game, @player) do |format|
format.html { render partial: 'games/display_remarks' if request.xhr? }
format.json
end
end
private
def find_game
@game = Game.find(params[:game_id])
end
end
<file_sep>Mafia::Application.routes.draw do
devise_for :users, :path_prefix => 'my'
resources :users do
resources :player_roles
end
resources :games do
get :best_player
resources :rounds
resources :players do
collection do
post :create_bunch
put :put_roles
put :put_remarks
end
member do
#get :score
get :set_role
delete :destroy_all
get :get_remarks
end
end
end
resources :scores
root :to => 'games#index'
end
<file_sep>module ScoresHelper
def red_score(user)
Player.where(user_id: user.id, team: 'red', won: '1').count()
end
def black_score(user)
Player.where(user_id: user.id, team: 'black', won: '1').count()
end
def won(user)
black_score(user) + red_score(user)
end
def overall_games(user)
Player.where(user_id: user.id).count()
end
def points(user)
Player.where(user_id: user.id).sum(:score)
end
def ratio(user)
if overall_games(user) != 0
points(user)/overall_games(user).to_f
end
end
end
<file_sep>class RenameCoulmnUserName < ActiveRecord::Migration
def up
rename_column :users, :user_name, :name
end
def down
end
end
<file_sep>class DefatulForRemarks < ActiveRecord::Migration
def up
change_column :appointments, :remark, :integer, :default => 0
end
end
<file_sep>class User < ActiveRecord::Base
rolify
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :alias, :role_ids
# attr_accessible :title, :body
has_many :players
has_many :games, :through => :players
has_many :managers
validates :name, exclusion: {in: %w(admin superuser moderator),
message: "%{value} is reserved.'"}
after_create :set_permission!
def self.search(search)
if search
where('alias LIKE ? OR name LIKE ?',"%#{search}%", "%#{search}%")
else
scoped
end
end
def set_permission!
self.add_role 'player'
end
end
<file_sep>task :create_admin => :environment do
if User.exists?(name: "admin", email: "<EMAIL>", :alias => "manager")
false
else
admin = User.new(name: "admin", email: "<EMAIL>", :alias => "manager", password:"<PASSWORD>")
admin.add_role "admin"
admin.save(validate: false)
end
end
<file_sep>mafia
=====
mafiaapp
Rounds Does not Works at all for this moment !
MODELS:
<b>player_role.rb</b></br>
<b>game_role.rb</b></br>
DOES NOT WORK AS WELL, TRYING TO EXTRACT ROLIFY PROCESS OUT FROM APPOINTMENTS MODEL
</br>
APPOINTMENTS CAN BE CONSIDERED AS PLAYERS INSIDE OF GAME
Before start you need run in concole <br> <b> rake create_admin</b>
If you want have admin permissoins you must log in with credentials <br>
email :<b> <EMAIL></b> <br>
pw: <b> m<PASSWORD> </b> <br>
Another way: <br>
1. Create user <br>
2. After set admin role for your user via rails c using next command <br>
<b>user.add_role('admin')<b>
test
TODO : kill/nominate feature<file_sep># ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "$debian_chroot" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
xterm-color) color_prompt=yes;;
esac
# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi
# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
# Add an "alert" alias for long running commands. Use like so:
# sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if [ -f /etc/bash_completion ] && ! shopt -oq posix; then
. /etc/bash_completion
fi
PATH=$PATH:$HOME/.rvm/bin # Add RVM to PATH for scripting
[[ -s "/home/andre/.rvm/scripts/rvm" ]] && source "/home/andre/.rvm/scripts/rvm"
[[ -s "/home/andre/.rvm/scripts/rvm" ]] && source "/home/yvodol/.rvm/scripts/rvm"
### Added by the Heroku Toolbelt
export PATH="/usr/local/heroku/bin:$PATH"
#============================================================
#
# ALIASES AND FUNCTIONS
#
# Arguably, some functions defined here are quite big.
# If you want to make this file smaller, these functions can
#+ be converted into scripts and removed from here.
#
#============================================================
#-------------------
# Personnal Aliases
#-------------------
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# -> Prevents accidentally clobbering files.
alias mkdir='mkdir -p'
alias h='history'
alias j='jobs -l'
alias which='type -a'
alias ..='cd ..'
# Pretty-print of some PATH variables:
alias path='echo -e ${PATH//:/\\n}'
alias libpath='echo -e ${LD_LIBRARY_PATH//:/\\n}'
alias du='du -kh' # Makes a more readable output.
alias df='df -kTh'
#-------------------------------------------------------------
# The 'ls' family (this assumes you use a recent GNU ls).
#-------------------------------------------------------------
# Add colors for filetype and human-readable sizes by default on 'ls':
alias ls='ls -h --color'
alias lx='ls -lXB' # Sort by extension.
alias lk='ls -lSr' # Sort by size, biggest last.
alias lt='ls -ltr' # Sort by date, most recent last.
alias lc='ls -ltcr' # Sort by/show change time,most recent last.
alias lu='ls -ltur' # Sort by/show access time,most recent last.
# The ubiquitous 'll': directories first, with alphanumeric sorting:
alias ll="ls -lv --group-directories-first"
alias lm='ll |more' # Pipe through 'more'
alias lr='ll -R' # Recursive ls.
alias la='ll -A' # Show hidden files.
alias tree='tree -Csuh' # Nice alternative to 'recursive ls' ...
#-------------------------------------------------------------
# Tailoring 'less'
#-------------------------------------------------------------
alias more='less'
export PAGER=less
export LESSCHARSET='latin1'
export LESSOPEN='|/usr/bin/lesspipe.sh %s 2>&-'
# Use this if lesspipe.sh exists.
export LESS='-i -N -w -z-4 -g -e -M -X -F -R -P%t?f%f \
:stdin .?pb%pb\%:?lbLine %lb:?bbByte %bb:-...'
# LESS man page colors (makes Man pages more readable).
export LESS_TERMCAP_mb=$'\E[01;31m'
export LESS_TERMCAP_md=$'\E[01;31m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;44;33m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;32m'
###############################
### dev 5 #####################
alias dev5='ssh [email protected]' # dev5 ssh
########### UMLET #################
alias umlet='java -jar ~/Umlet/umlet.jar'
############# #rails env ?<./.,m
############################
export RUBY_GC_MALLOC_LIMIT=90000000
export RUBY_FREE_MIN=200000
############################# GIT
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\W\[\033[00m\]$(__git_ps1 " [%s] ")\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\W$(__git_ps1 " [%s] ")\$ '
fi
<file_sep>class ReferenceService
attr_reader :game
def initialize(game)
@game = game
end
def create_reference!
game_ref = reference
loop do
unless Game.where(game_ref: game_ref).exists?
game.game_ref = game_ref
break
end
end
end
private
def reference(separator = '-')
number = rand(000..999)
ref = ("A".."Z").to_a.shuffle().first(3).join('')
"#{ref}#{separator}#{number}"
end
end<file_sep>class ChangeManagerType < ActiveRecord::Migration
def up
change_column :games, :manager, :integer
end
def down
end
end
<file_sep>class GamesController < ApplicationController
load_and_authorize_resource
helper_method :sort_column, :sort_direction
before_filter :game_find, except: [:create, :new, :index, :best_player]
before_filter :user_scoped, except: [:index]
before_filter :appointment_scoped, only: [:best_player, :show]
respond_to :html
def index
@games = Game.order(sort_column + ' ' + sort_direction).paginate(page: params[:page], per_page: 5).search(params[:search])
respond_with do |format|
format.html {
render :partial => 'games/games_table' if request.xhr?
}
end
end
def show
@used_ids = (@game.players.pluck(:user_id)) + [@game.manager.user_id]
end
def new
render "games/new", layout: false
end
def create
@game = Game.create(params[:game])
respond_with @game
end
def edit
end
def best_player
@game = Game.find(params[:game_id])
@best_player = @game.players.pluck(:user_id)
render 'games/best_player', layout: false
end
def update
@game.update_attributes(params[:game])
@game.players.each do |a|
a.set_score!
a.won!
end
respond_with @game
end
def destroy
@game.destroy
redirect_to games_path
end
private
def game_find
@game = Game.find(params[:id])
end
def user_scoped
@users = User.scoped
end
def appointment_scoped
@players = Player.scoped
end
def sort_column
Game.column_names.include?(params[:sort_column]) ? params[:sort_column] : 'created_at'
end
def sort_direction
%w[asc desc].include?(params[:sort_direction]) ? params[:sort_direction] : 'asc'
end
end
<file_sep>class Team < ActiveRecord::Migration
def up
add_column :appointments, :team, :string
end
def down
end
end
<file_sep>class RemoveManagerFieldFromGameTable < ActiveRecord::Migration
def up
remove_column :games, :manager
end
def down
end
end
<file_sep>module GamesHelper
def games_action(g)
actions = {}
actions[:show] = link_to 'Show', game_path(g), class:'btn'
actions[:edit] = link_to 'Edit', edit_game_path(g), class:'btn'
actions[:destroy] = link_to 'Destroy', game_path(g), method: :delete,class:'btn btn-danger'
render "shared/actions", :object => g, :actions => actions
end
def user_alias_by_player(player)
user = User.find(player.user_id)
if player.player_number
"##{player.player_number}. #{user.alias} "
else
"#{user.alias}"
end
end
def player_name_or_alias(player)
if player.user.alias
"#{player.user.alias},"
else
"#{player.user.name}"
end
end
end
<file_sep>class DefaultGameStatus < ActiveRecord::Migration
def up
change_column :games, :game_status, :string, default: 'open'
end
def down
end
end
<file_sep>class Manager < ActiveRecord::Base
attr_accessible :user_id, :game_id
belongs_to :user
belongs_to :game
end
<file_sep>class KillNominate < ActiveRecord::Migration
def up
add_column :players, :kill, :boolean, default: false
add_column :players, :nominate, :boolean, default: false
end
end
<file_sep>class RoundService
attr_reader :game, :round
def initialize(game, round)
@game = game
@round = round
end
def create_round!
game_round = 1
loop do
unless @game.rounds.where(round_number: game_round).exists?
round.round_number = game_round + 1
end
end
end
end<file_sep>task :create_users => :environment do
User.create(name: "user1", email: "<EMAIL>", :alias => "alias1", password:"<PASSWORD>")
User.create(name: "user2", email: "<EMAIL>", :alias => "alias2", password:"<PASSWORD>")
User.create(name: "user3", email: "<EMAIL>", :alias => "alias3", password:"<PASSWORD>")
User.create(name: "user4", email: "<EMAIL>", :alias => "alias4", password:"<PASSWORD>")
User.create(name: "user5", email: "<EMAIL>", :alias => "alias5", password:"<PASSWORD>")
User.create(name: "user6", email: "<EMAIL>", :alias => "alias6", password:"<PASSWORD>")
User.create(name: "user7", email: "<EMAIL>", :alias => "alias7", password:"<PASSWORD>")
User.create(name: "user8", email: "<EMAIL>", :alias => "alias8", password:"<PASSWORD>")
User.create(name: "user9", email: "<EMAIL>", :alias => "alias9", password:"<PASSWORD>")
User.create(name: "user10", email: "<EMAIL>", :alias => "alias10", password:"<PASSWORD>")
User.create(name: "user11", email: "<EMAIL>", :alias => "alias11", password:"<PASSWORD>")
User.create(name: "user12", email: "<EMAIL>", :alias => "alias12", password:"<PASSWORD>")
end
|
0576a4d2b36d60ce90ba348643d03417a22fc8ca
|
[
"Markdown",
"Ruby",
"Shell"
] | 29 |
Ruby
|
yurakuzh/mafia
|
9ab037d1ac8184d698f0b5d7f1437f6e70e0799f
|
faf3e02afd8b790ebb3a96925a1b51b07409ea3f
|
refs/heads/main
|
<file_sep>function rollDice() {
var p1 = document.querySelector(".p-1 i")
var p2 = document.querySelector(".p-2 i")
var btn = document.querySelector(".btn")
var randomP1 = Math.floor((Math.random() * 6)) + 1
if (randomP1 === 1) {
p1.removeAttribute("class", "fas fa-dice-one")
p1.setAttribute("class", "fas fa-dice-one")
} else if (randomP1 === 2) {
p1.removeAttribute("class", "fas fa-dice-one")
p1.setAttribute("class", "fas fa-dice-two")
} else if (randomP1 === 3) {
p1.removeAttribute("class", "fas fa-dice-one")
p1.setAttribute("class", "fas fa-dice-three")
} else if (randomP1 === 4) {
p1.removeAttribute("class", "fas fa-dice-one")
p1.setAttribute("class", "fas fa-dice-four")
} else if (randomP1 === 5) {
p1.removeAttribute("class", "fas fa-dice-one")
p1.setAttribute("class", "fas fa-dice-five")
} else if (randomP1 === 6) {
p1.removeAttribute("class", "fas fa-dice-one")
p1.setAttribute("class", "fas fa-dice-six")
}
var randomP2 = Math.floor((Math.random() * 6)) + 1
if (randomP2 === 1) {
p2.removeAttribute("class", "fas fa-dice-six")
p2.setAttribute("class", "fas fa-dice-one")
} else if (randomP2 === 2) {
p2.removeAttribute("class", "fas fa-dice-six")
p2.setAttribute("class", "fas fa-dice-two")
} else if (randomP2 === 3) {
p2.removeAttribute("class", "fas fa-dice-six")
p2.setAttribute("class", "fas fa-dice-three")
} else if (randomP2 === 4) {
p2.removeAttribute("class", "fas fa-dice-six")
p2.setAttribute("class", "fas fa-dice-four")
} else if (randomP2 === 5) {
p2.removeAttribute("class", "fas fa-dice-six")
p2.setAttribute("class", "fas fa-dice-five")
} else if (randomP2 === 6) {
p2.removeAttribute("class", "fas fa-dice-six")
p2.setAttribute("class", "fas fa-dice-six")
}
if (randomP1 > randomP2) {
btn.innerHTML = "<h1><i class='fas fa-flag'></i> Player 1 Won!</h1>"
} else if (randomP1 < randomP2) {
btn.innerHTML = "<h1><i class='fas fa-flag'></i> Player 2 Won!</h1>"
} else if (randomP1 === randomP2) {
btn.innerHTML = "<h1>You both Lost!</h1>"
}
}
|
a583217a0d188a4d8a2e70316691f55ee212acb2
|
[
"JavaScript"
] | 1 |
JavaScript
|
mgajdo/dice-game
|
57360f62107f516d27e0b0683498b9b43ca6828f
|
4e01d74aed26f2bb9ce161de166479fe39d4b23f
|
refs/heads/main
|
<repo_name>tfrc19/Laravel_Sintaxis<file_sep>/app/Models/Cliente.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Cliente extends Model
{
use HasFactory;
protected $fillable=
(
["nombre",
"apellido"
]
);
//protected $primaryKey = 'cliente_id';
public function articulo () {
return $this->hasOne("App\Models\Articulo");
}
public function articulos(){
return $this->hasMany("App\Models\Articulo");
}
public function perfils(){
return $this->belongsToMany("App\Models\Perfil");
}
//Relacion Polimorfica
public function calificaciones(){
return $this->morphMany("App\Models\Calificacion","calificacion");
}
/* protected $fillable=([
'nombre',
'apellido'
]);
*/
}
<file_sep>/app/Models/Articulo.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Articulo extends Model
{
use HasFactory;
use SoftDeletes;
protected $fillable=([
'producto',
'precio',
'observacion',
'codigo',
'pais'
]);
public function cliente(){
//return $this->hasOne("App\Models\Cliente");
return $this->belongsTo("App\Models\Cliente");
}
//Relacion Polimorfica
public function calificaciones(){
return $this->morphMany("App\Models\Calificacion","calificacion");
}
}
<file_sep>/public/js/prueba.js
$(document).ready(function(){
//var tamanoventana = $(window).innerHeight;
$('#boton').on('click',function(e){
alert("Hola, estas aqui desde js");
});
alert($(window).width());
});<file_sep>/routes/web.php
<?php
use App\Models\Articulo;
use App\Models\Cliente;
use App\Models\Perfil;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/home', function () {
return view('welcome');
});
Route::get('/',function(){
return view('welcome');
});
Route::get('/blog','paginasController@create');
Route::get('/contacto','paginasController@contacto');
Route::get('/usuarios','paginasController@usuarios');
/*
Route::get('/insertar',function(){
DB::insert('insert into articulos (producto,precio,observacion,recomendaciones,codigo) values(?,?,?,?,?)',[
'Chocolate',20,'chocolate de Ecuador','se debe beber con leche','abc123'
]);
});
Route::get('/seleccionar',function(){
$articulos = DB::select('select * from articulos');
//print_r($articulos);
foreach($articulos as $articulo){
return $articulo->producto;
}
});
Route::get('/actualizar/{producto}', function ($producto) {
DB::update('update articulos set producto=? where producto="perro"', [$producto]);
});
Route::get('eliminar/{id}', function ($id) {
$eliminar= DB::delete('delete from articulos where id = ?', [$id]);
if($eliminar==0){
return "No Existe registro para eliminar";
}
else
if($eliminar==1){
return "Registro elimino";
}
//return $eliminar;
});
*/
/*Route::get('/insertar',function(){
DB::insert('insert into articulos(producto,precio,observacion,recomendaciones,codigo)values(?,?,?,?,?)',
['Queso',1.50,'Queso de mesa','Este queso se come sin pan','abc123']);
});*/
//Leer sql con Eloquent
Route::get('/leer',function(){
//$articulos = Articulo::where('producto','Chocolate')->first();
//$articulos = Articulo::all();
//$articulos = Articulo::where('producto','Queso')->orderby('precio','desc')->get();
$articulos = Articulo::all()->max("precio");
$articulosPorPrecio = Articulo::where("precio",$articulos)->take(10)->get();
return $articulosPorPrecio;
/*foreach($articulos as $articulo){
echo "Nombre".": ".$articulo->producto;
}*/
});
//Controlador y modelo del cliente
Route::get('/insertarClientes/{nombre}/{apellido}', function($nombre,$apellido) {
$cliente = new Cliente();
$cliente->nombre=$nombre;
$cliente->apellido=$apellido;
$cliente = $cliente->save();
return $cliente;
});
//Insertar sql con Eloquent
Route::get('/insertar',function(){
$articulo = new Articulo();
$articulo->producto = "Pan de molde";
$articulo->precio=1.80;
$articulo->observacion="Pan artesanal";
$articulo->recomendaciones="en cualquier instancia";
$articulo->codigo="001B";
$articulo = $articulo->save();
return $articulo;
});
//Actualizar sql con Eloquent
Route::get('/actualizar',function(){
$articulo =Articulo::find(7);
$articulo->producto = "Pan";
$articulo->precio=1.80;
$articulo->observacion="Pan artesanal";
$articulo->recomendaciones="en cualquier instancia";
$articulo->codigo="001B";
$articulo = $articulo->save();
return $articulo;
});
//Actualizar mas de 1 elemento sql con Eloquent
Route::get('/update',function(){
//Articulo::where("producto","Queso")->update(["pais"=>"Ecuador"]);
//Sentencia con like
//Articulo::where("producto","like","%"."Chocolate"."%")->update(["pais"=>"Africa"]);
Articulo::where("pais","Ecuador")->update(["precio"=>"2.00"]);
});
Route::get('/eliminar',function(){
//Eliminación con un solo criterio
/*$articulo = Articulo::find(8);
$articulo->delete();*/
//Eliminacion con mas de un criterio
$articulo = Articulo::where("producto","Queso")->where("pais","Ecuador");
$articulo->delete();
});
Route::get('/insertarMultiple',function(){
$articulo = Articulo::create(["producto"=>"Yogurt","precio"=>1.10,"observacion"=>"Yogurt de Frutilla","codigo"=>"001ab","pais"=>"Ecuador"])->
create(["producto"=>"Queso","precio"=>1.10,"observacion"=>"Queso de Cuajada","codigo"=>"001ab","pais"=>"España"]);
});
Route::get('/seleccionarProducto/{nombre}',function($nombre){
$articulo = Articulo::where("producto",$nombre)->get();
/*$valor = sizeof($articulo);
echo $valor;*/
if(sizeof($articulo)>0){
return $articulo;
}
else{
return "No existen registros";
}
/* if(!empty($articulo)){
return $articulo;
}
else{
if(empty($articulo)){
return "no existe registro";
}
}*/
});
Route::get('/softDelete',function(){
Articulo::where('id',17)->delete();
});
Route::get('/listarSoftDelete',function(){
$articulos = Articulo::withTrashed()
->where('deleted_at','!=','NULL')->get();
//$articulos = Articulo::where('id',19)->get();
return $articulos;
});
Route::get('/listarOnlyDelete',function(){
$articulos = Articulo::onlyTrashed()->get();
return $articulos;
});
Route::get('/restauraDelete',function(){
$articulos = Articulo::where('id',17)->restore();
});
Route::get('/foreceDelete',function(){
$articulos = Articulo::where('id',19)->forceDelete();
});
//Modelo Cliente
Route::get('/insertarClientes/{nombre}/{apellido}', function($nombre,$apellido) {
$cliente = new Cliente();
$cliente->nombre=$nombre;
$cliente->apellido=$apellido;
$cliente = $cliente->save();
return $cliente;
});
Route::get('/cliente/{id}', function ($id) {
$articulo = Cliente::find($id)->articulo;
return $articulo;
});
Route::get('/clientes/{id}',function($id){
$articulos = Cliente::find($id)->articulos->where('precio','<=',10);;
return $articulos;
});
Route::get('/articulo/{id}',function($id){
$cliente = Articulo::find($id)->cliente->where('pais','España');
return $cliente;
});
Route::get('/perfilInsert/{nombre}',function($nombre){
$perfil = new Perfil();
$perfil->nombre=$nombre;
$perfil->save();
});
Route::get('/leerPerfil',function(){
return Perfil::where("id",1)->get();
});
Route::get('/leerPerfilCliente/{id}',function($id){
$cliente =Cliente::find($id);
if(isset($cliente)>0){
foreach($cliente->perfils as $perfil){
echo "Perfil: ".'<b>'.$perfil->nombre.'</b>'.'<br>';
}
}
else{
echo "No existe Cliente";
}
/*foreach($cliente->perfils as $perfil){
echo "Perfil: ".'<b>'.$perfil->nombre.'</b>'.'<br>';
}*/
//return Cliente::find($id)->perfils()->orderBy("nombre","desc")->get();
});
//Relacion Polimorfica
Route::get('/calificacionCliente/{id}', function ($id)
{
$cliente = Cliente::find($id);
if(isset($cliente))
{
foreach($cliente->calificaciones as $calificacion)
{
return $calificacion->calificacion;
}
}
else
{
return "No Existe Clientes";
}
});
Route::get('/calificacionArticulo/{id}', function ($id)
{
$articulo = Articulo::find($id);
if(isset($articulo))
{
foreach($articulo->calificaciones as $calificacion)
{
return $calificacion->calificacion;
}
}
else
{
return "No Existe Clientes";
}
});
|
2071b70f8ae6966ccbc5473f3c96b7ac3a329a15
|
[
"JavaScript",
"PHP"
] | 4 |
PHP
|
tfrc19/Laravel_Sintaxis
|
83eb2f1444f7af21c27bef99470a1bc086da49d6
|
3f9fa571ff5707e41b5383994712ea6240842daf
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace TestRelay
{
public class Program
{
//this would go in a config somewhere
private const string ConnectionString = "[replace with full connection string]";
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.UseAzureRelay(options =>
{
options.UrlPrefixes.Add(ConnectionString);
});
webBuilder.UseContentRoot(Path.GetFullPath(@"."));
webBuilder.UseWebRoot(Path.GetFullPath(@".\wwwroot"));
});
}
}
<file_sep>using Microsoft.Azure.Relay;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace ClientWrapper.cs
{
public sealed class TheClient
{
private const string RelayNamespaceFormat = "{0}.servicebus.windows.net";
private readonly string _RelayNamespace;
private readonly string _ConnectionName;
private readonly string _KeyName;
private readonly string _Key;
private readonly HttpClientHandler _Handler;
public TheClient(string relayNamespace, string connectionName, string keyName, string key)
{
_RelayNamespace = string.Format(RelayNamespaceFormat, relayNamespace);
_ConnectionName = connectionName;
_KeyName = keyName;
_Key = key;
_Handler = new HttpClientHandler();
}
public async Task DoQueryForThings()
{
using (HttpClient client = new HttpClient(_Handler, false))
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format("https://{0}/{1}/test/queryforthings", _RelayNamespace, _ConnectionName)),
Method = HttpMethod.Get
};
request.Headers.Add("ServiceBusAuthorization", await GetTokenAsync());
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
}
}
public async Task<string> PerformSignificantWork(string message)
{
//i a real world we would stream this to avoid memory pressure
SomeUnitOfWork work = new SomeUnitOfWork { ImportantMessage = message };
var messagePayload = JsonConvert.SerializeObject(work);
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(messagePayload)))
{
using (HttpClient client = new HttpClient(_Handler, false))
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(string.Format("https://{0}/{1}/test/DoSignificantWork", _RelayNamespace, _ConnectionName)),
Method = HttpMethod.Post,
Content = new StreamContent(stream),
};
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
request.Headers.Add("ServiceBusAuthorization", await GetTokenAsync());
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
//again we would stream this to the object in real world
var content = await response.Content.ReadAsStringAsync();
return (JsonConvert.DeserializeObject<SomeUnitOfWorkResponse>(content)).Response;
}
}
}
private async Task<string> GetTokenAsync()
{
var uri = new Uri(string.Format("https://{0}/{1}", _RelayNamespace, _ConnectionName));
var tokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(_KeyName, _Key);
var token = await tokenProvider.GetTokenAsync(uri.AbsoluteUri, TimeSpan.FromHours(1));
return token.TokenString;
}
}
}
<file_sep>using ClientWrapper.cs;
using System;
using System.Threading.Tasks;
namespace TestDriver
{
class Program
{
static async Task Main(string[] args)
{
TheClient client = new TheClient("[replace with namespace]", "[replace with connection name]", "[replace with key name]", "[replace with key]");
await client.DoQueryForThings();
Console.WriteLine(await client.PerformSignificantWork("hello world"));
Console.ReadLine();
}
}
}
<file_sep>using Microsoft.AspNetCore.Mvc;
using TestRelay.Models;
namespace TestRelay.Controllers
{
[Route("[controller]/[action]")]
public sealed class TestController : Controller
{
public TestController() { }
[HttpGet]
public IActionResult QueryForThings()
{
return Ok();
}
[HttpPost]
public IActionResult DoSignificantWork([FromBody] SomeUnitOfWork body)
{
return Ok(new SomeUnitOfWorkResponse { Response = $"Hello {body.ImportantMessage}" });
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ClientWrapper
{
public sealed class SomeUnitOfWork
{
public string ImportantMessage { get; set; }
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ClientWrapper
{
public class SomeUnitOfWorkResponse
{
public string Response { get; set; }
}
}
|
d2edcb4efb9608d69f792de6f3c42c1d25d54332
|
[
"C#"
] | 6 |
C#
|
jmblakl/Test-Relay-AspNet
|
f6abf2fa2d01cad0bbf751c9038a22fe990d2b58
|
8d4173ba79243d215fc0d223abf81d7a7356e674
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import matplotlib.pyplot as plt
import math
import time
import numpy
import sys
import os
def fix_lat_long(lat,long,latdir,longdir):
#reformat latitude
print 'old lat ', lat
lat = ''.join(lat.split('.'))
if latdir == 'S':
lat = float('-'+lat[:2]+'.'+lat[2:])
else:
lat = float(lat[:2] + '.' + lat[2:])
print 'new lat ',lat
print 'new lat type ',type(lat)
#reformat longitude
print 'old long ', long
long = ''.join(long.split('.'))
if longdir == 'W':
long = float('-'+long[:3]+'.'+long[3:])
else:
long = float(long[:2] + '.' + long[2:])
print 'new long ',long
print 'new long type ',type(long)
return [lat,long]
def reformat(msg):
splitline= msg.split(',')#splits the line when a comma is read
if splitline[4] == '$GPGGA':#if line begins with $GPGGA
node_time = splitline[0]
angle = splitline[1]
node_num = splitline[2]
test_name = splitline[3]
time = splitline[5]#information we we wish to extract
latitude= splitline[6]#line number is the order the data is written in the GPGGA line
latDir=splitline[7]
longitude=splitline[8]
longDir=splitline[9]
#print 'total msg: ',msg#prints the entire line
print 'node time: ', node_time
print 'angle: ',angle
node_num = int(node_num)
print 'node number: ',node_num
print 'test name: ',test_name
print 'time: ',time
print 'lat: %s latDir: %s' % (latitude, latDir)
print 'long: %s longDir: %s' % (longitude, longDir)
new_info = fix_lat_long(latitude,longitude,latDir,longDir)
print 'new info: ',new_info
#get ip addr and port #
ip_addr = '0.0.0.0'
msg_num = 1
if len(sys.argv) == 1:
print 'you didnt type a port number argument when you ran the script'
port = int(raw_input("what port# would you like to listen to?"))
elif int(sys.argv[1]) > 999:
port = int(sys.argv[1])
else:
print 'you entered a port number less than 1000'
port = int(raw_input("what port# would you like to listen to? "))
print "listening on IP address: ", ip_addr
print "listening on port: ", port
#build socket using above user input
serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serversocket.bind((ip_addr, port))
#serversocket.listen(5) # become a server socket, maximum 5 connections
while 1:
msg = serversocket.recv(128)
print '\nmsg #: %d' % msg_num
msg_num += 1
reformat(msg)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import time
import serial
import sys
def socksend(msg):
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((ip_addr, port))
clientsocket.send(msg)
if len(sys.argv) < 2:
port = int(raw_input('port number = '))
ip_addr = raw_input('ip address = ')
real_or_fake = int(raw_input('do you want real data or fake data?\n press 1 for real, press 2 for fake'))
else:
port = int(sys.argv[1])
ip_addr = str(sys.argv[2])
real_or_fake = int(sys.argv[3])
n = 1
while 1:
if real_or_fake == 1:
ser=serial.Serial( '/dev/ttyUSB0', 4800, timeout = 5)
msg = ser.readline()
filename = "/home/ben/Desktop/senior_design/python/gps.txt"
f = open(filename, 'w')
f.write(msg)
f.close()
splitline = msg.split(',')
if splitline[0] == '$GPGGA':#if line begins with $GPGGA
#print 'splitline[0]: ',splitline[0]
gps_time = splitline[1]#information we we wish to extract
latitude= splitline[2]#line number is the order the data is written in the GPGGA line
latDir=splitline[3]
longitude=splitline[4]
longDir=splitline[5]
print 'time: ',gps_time
print 'lat: %s latDir: %s' % latitude,latDir
print 'long: ', longitude
print 'message being sent to server'
socksend(msg)
print 'MESSAGE #: '+str(n)+'\nthis is the GPS data from the puck: \n'+msg
n+=1
else:
print 'sending fake GPS data to the server'
msg = '$GPGGA,205704.000,3849.3529,N,07701.5355,W,1,08,1.2,10.0,M,-33.5,M,,0000*54 MESSAGE #: '+str(n)+'\n'
time.sleep(1)
print port
print ip_addr
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print 'works 1'
#clientsocket.connect((ip_addr, port))
print 'works 2'
clientsocket.sendto(msg,(ip_addr, port))
#socksend(msg)
n+=1
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016 <+YOU OR YOUR COMPANY+>.
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
import csv
import numpy
from gnuradio import gr
import time
import math
import socket
import serial
import sys
import matplotlib.pyplot as plt
class xcorr_ts_ff(gr.sync_block):
"""
docstring for block xcorr_ts_ff
"""
def __init__(self,samp_window,samp_rate,node_number,ip_addr,port_num,center_mic_offset,mic_distance,test_number):
gr.sync_block.__init__(self,
name="xcorr_ts_ff",
in_sig=[numpy.float32,numpy.float32,numpy.float32,numpy.float32,numpy.float32],
out_sig=[numpy.float32])
self.samp_window = samp_window
self.samp_rate = samp_rate
self.trig_in_tracker = []
self.in1_tracker = []
self.in2_tracker = []
self.in3_tracker = []
self.in4_tracker = []
self.fixed_dly = 10
self.limiter = 1
self.total_capture_len = samp_window
self.captured_samp_count = 0
self.captured_samps1 = []
self.captured_samps2 = []
self.captured_samps3 = []
self.captured_samps4 = []
self.capturing = 0
self.out_msg = [0,0,node_number,test_number] # [timestamp,angle]
self.ip_address = ip_addr
self.port_num = port_num
self.center_mic_offset = center_mic_offset
self.mic_distance = mic_distance
self.test_number = test_number
# def tracker(self, trig_in,in1,in2,in3,in4):
# if len(self.trig_in_tracker) == 0:
# self.trig_in_tracker[:] = trig_in
# else:
# self.trig_in_tracker[len(self.trig_in_tracker):] = trig_in
# print "trig_in_tracker: ", self.trig_in_tracker
# print "length of trig_in_tracker: ",len(self.trig_in_tracker)
# if len(self.in1_tracker) == 0:
# self.in1_tracker[:] = in1
# else:
# self.in1_tracker[len(self.in1_tracker):] = in1
# print "in1_tracker: ", self.in1_tracker
# print "length of in1_tracker: ", len(self.in1_tracker)
# if len(self.in2_tracker) == 0:
# self.in2_tracker[:] = in2
# else:
# self.in2_tracker[len(self.in2_tracker):] = in2
# print "in2_tracker: ", self.in2_tracker
# print "length of in2_tracker: ", len(self.in2_tracker)
# if len(self.in3_tracker) == 0:
# self.in3_tracker[:] = in3
# else:
# self.in3_tracker[len(self.in3_tracker):] = in3
# print "in3_tracker: ", self.in3_tracker
# print "length of in3_tracker: ", len(self.in3_tracker)
# if len(self.in4_tracker) == 0:
# self.in4_tracker[:] = in4
# else:
# self.in4_tracker[len(self.in4_tracker):] = in4
# print "in4_tracker: ", self.in4_tracker
# print "length of in4_tracker: ", len(self.in4_tracker)
def angler(self,lags):
print 'lags in angler', lags
# speed of sound
c = 343 # m/s
elem_dist = self.mic_distance # meters
# sampling rate
fs = 44100.0 # samps/sec
third_mic = lags.index([max(lags)]), int(max(lags))
print "third mic w/o abs val: ",third_mic
lags[third_mic[0]] = -99999
second_mic = lags.index([max(lags)]), int(max(lags))
print "second mic w/o abs val: ",second_mic
lags[second_mic[0]] = -99999
first_mic = lags.index([max(lags)]), int(max(lags))
print "first mic w/o abs val: ",first_mic
lags[first_mic[0]] = -99999
print 'first mic to receive hit is: ', first_mic[0] + 2
print 'second mic to receive hit is: ', second_mic[0] + 2
print 'third mic to receive hit is: ', third_mic[0] + 2
t_delay = math.fabs(first_mic[1]) / fs
print "t_delay is: ", t_delay
print "distance (x = c*t_delay) is: ", c * t_delay
theta = math.degrees(math.acos((c * t_delay) / elem_dist))
print 'angle between detector and first mic (theta = invcos(c*t_delay)/elem_dist): ', theta
print "determining which side its on using which mics came after"
if first_mic[0] + 2 == 2 and second_mic[0] + 2 == 4:
theta = theta
elif first_mic[0] + 2 == 2 and second_mic[0] + 2 == 3:
theta = -theta
elif first_mic[0] + 2 == 3 and second_mic[0] + 2 == 2:
theta = theta + 240
elif first_mic[0] + 2 == 3 and second_mic[0] + 2 == 4:
theta = 240 - theta
elif first_mic[0] + 2 == 4 and second_mic[0] + 2 == 3:
theta = 120 + theta
elif first_mic[0] + 2 == 4 and second_mic[0] + 2 == 2:
theta = 120 - theta
else:
print "missed a case here"
print "theta after looking at other mics: ", theta
first_mic_and_angle = [first_mic[0] + 2, theta]
self.out_msg[1] = theta
print "final message: 'node number %d, saw a shot at time: %f, at angle: %f" % (self.out_msg[2],self.out_msg[0],self.out_msg[1])
return first_mic_and_angle
def xcorr(self, mic1_detector, mic2_locator, mic3_locator, mic4_locator):
autocorr = numpy.correlate(mic1_detector, mic1_detector, "same")
mxind0 = numpy.where(autocorr == max(autocorr))
mxind0 = mxind0[0][0]
middle = mxind0
print "ch-ch-ch-ch-ch-changes"
print 'location of initial detection is: ', mxind0
print "len autocorr: ", len(autocorr)
#cross correlate detector with element 2
xcorr1 = numpy.correlate(mic1_detector, mic2_locator, "same")
mxind1 = numpy.where(xcorr1 == max(xcorr1))
mxind1 = mxind1[0][0]
print 'mxind1 is: ', mxind1
print 'middle', middle
lag1 = middle - mxind1
print "len xcorr1: ", len(xcorr1)
print "lag1: ",lag1
#lag1 = self.center_mic_offset - lag1
print 'lag1 after delay compensation: ',lag1
# cross correlate detector with element 3
xcorr2 = numpy.correlate(mic1_detector, mic3_locator, "same")
mxind2 = numpy.where(xcorr2 == max(xcorr2))
mxind2 = mxind2[0][0]
print 'mxind2 is: ', mxind2
lag2 = middle - mxind2
print "len xcorr2: ", len(xcorr2)
print "lag2: ", lag2
#lag2 = self.center_mic_offset - lag2
print 'lag1 after delay compensation: ',lag2
# cross correlate detector with element 4
xcorr3 = numpy.correlate(mic1_detector, mic4_locator, "same")
mxind3 = numpy.where(xcorr3 == max(xcorr3))
mxind3 = mxind3[0][0]
print 'mxind3 is: ', mxind3
lag3 = middle - mxind3
print "len xcorr3: ", len(xcorr3)
print "lag3: ", lag3
#lag3 = self.center_mic_offset - lag3
print 'lag1 after delay compensation: ',lag3
lags = [lag1,lag2,lag3]
self.angler(lags)
def capture(self, in1, in2, in3, in4):
in1 = in1.tolist()
in2 = in2.tolist()
in3 = in3.tolist()
in4 = in4.tolist()
if self.total_capture_len > 0 and len(self.captured_samps1) == 0:
print "lengths of in1-4 in 1st stage of capture: ", len(in1), len(in2), len(in3), len(in4)
print "first if statement satisfied, total_captured_len = ", self.total_capture_len
self.captured_samps1 = in1
self.captured_samps2 = in2
self.captured_samps3 = in3
self.captured_samps4 = in4
self.total_capture_len = self.total_capture_len - len(in1)
print 'len of captured samps1: ', len(self.captured_samps1)
elif self.total_capture_len > 0 and len(in1) <= self.total_capture_len:
print "second if statement satisfied, total_captured_len = ", self.total_capture_len
self.captured_samps1[len(self.captured_samps1):] = in1
self.captured_samps2[len(self.captured_samps2):] = in2
self.captured_samps3[len(self.captured_samps3):] = in3
self.captured_samps4[len(self.captured_samps4):] = in4
self.total_capture_len = self.total_capture_len - len(in1)
print 'len of captured samps1: ',len(self.captured_samps1)
elif self.total_capture_len > 0 and len(in1) > self.total_capture_len:
print "third if statement satisfied, total_captured_len = ", self.total_capture_len
self.captured_samps1[len(self.captured_samps1):] = in1[:self.total_capture_len]
self.captured_samps2[len(self.captured_samps2):] = in2[:self.total_capture_len]
self.captured_samps3[len(self.captured_samps3):] = in3[:self.total_capture_len]
self.captured_samps4[len(self.captured_samps4):] = in4[:self.total_capture_len]
self.total_capture_len = self.total_capture_len - len(in1[:self.total_capture_len])
print 'len of captured samps1: ', len(self.captured_samps1)
elif self.total_capture_len == 0:
print "************************************"
print "fourth if statement satisfied, total_captured_len = ", self.total_capture_len
print 'start writing data'
data1 = self.captured_samps1
data2 = self.captured_samps2
data3 = self.captured_samps3
data4 = self.captured_samps4
with open('/home/ben/Desktop/senior_design/gnuradio/data_files/in1file%s.csv' % self.test_number,'wb') as f1:
writer = csv.writer(f1)
writer.writerow(data1)
with open('/home/ben/Desktop/senior_design/gnuradio/data_files/in2file%s.csv' % self.test_number,'wb') as f2:
writer = csv.writer(f2)
writer.writerow(data2)
with open('/home/ben/Desktop/senior_design/gnuradio/data_files/in3file%s.csv' % self.test_number,'wb') as f3:
writer = csv.writer(f3)
writer.writerow(data3)
with open('/home/ben/Desktop/senior_design/gnuradio/data_files/in4file%s.csv' % self.test_number,'wb') as f4:
writer = csv.writer(f4)
writer.writerow(data4)
self.capturing = 0
print "data written"
print "len of captured samps1: ", len(self.captured_samps1)
print "calling xcorr on captured samples"
print "************************************"
self.xcorr(self.captured_samps1,self.captured_samps2,self.captured_samps3,self.captured_samps4)
else:
"something i didn't think of in capture function"
def message_write(self,msg):
filename = "/home/ben/Desktop/senior_design/python/gps.txt"
f = open(filename, 'r')
gps = f.read()
f.close()
msg.append(gps)
msg = str(msg[0]),str(msg[1]),str(msg[2]),str(msg[3]),str(msg[4])
msg = ','.join(msg)
detection_file = '/home/ben/Desktop/senior_design/python/detection.txt'
d = open(detection_file,'w')
d.write(msg)
print 'this message was just written to a file', msg
d.close()
# clientsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# clientsocket.connect((self.ip_address, self.port_num))
# clientsocket.send(msg+'n')
#clientsocket.close()
def work(self, input_items, output_items):
trig_in = input_items[0]
in1 = input_items[1] #in1 is the whole list, in1[h] is the single element of the list
in2 = input_items[2]
in3 = input_items[3]
in4 = input_items[4]
out = output_items[0]
h = 0
trig_index = 0
# print "len in1: ",len(in1)
# print "len in2: ",len(in2)
# print "len in3: ",len(in3)
# print "len in4: ",len(in4)
while h < len(output_items[0]):
val = trig_in[h]
if val == 1 and self.limiter ==1:
print "************************************"
print "triggering value is: ", val
print "at index: ",h
self.out_msg[0] = time.time()
print "timestamp is: ", self.out_msg[0]
print "setting enable to 'on'"
print "capturing %d samples (%0.3f sec) of signal in scheduler dependent chunks." % (self.samp_window,float(self.samp_window)/self.samp_rate)
print "************************************"
self.limiter = 0
self.capturing = 1
trig_index = h
output_items[0][h] = input_items[0][h]
h = len(output_items[0])
else:
output_items[0][h] = input_items[0][h]
h = h+1
if self.capturing ==1 and len(self.captured_samps1) == 0:
print "************************************"
print "starting sample capture, because capture flag is high and captured samps == 0"
print "will only grab samples from trigger index on"
print "capturing %d samples now" % len(in1[trig_index:])
print "************************************"
self.capture(in1[trig_index:], in2[trig_index:], in3[trig_index:], in4[trig_index:])
elif self.capturing == 1 and self.total_capture_len > 0:
print "************************************"
print "continuing to capture samples"
print "capturing %d samples now" % len(in1)
print "************************************"
self.capture(in1,in2,in3,in4)
elif self.capturing == 1 and self.total_capture_len == 0:
print 'capturing flag still high, but total capture length == 0'
self.capture(in1,in2,in3,in4)
print 'writing message to file'
self.message_write(self.out_msg)
h = 0
trig_index = 0
out[:] = trig_in
return len(output_items[0])
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import matplotlib.pyplot as plt
import math
import time
import numpy
import sys
import os
#function to plot based on received information
def plot_more_stuff(theta,node_num):
theta = math.radians(theta)
# # Polar plotting
fig = plt.figure(node_num) # Size
ax = plt.subplot(111, polar=True) # Create subplot
plt.grid(color='#888888') # Color the grid
ax.set_theta_zero_location('N') # Set zero to North
mic1 = math.radians(0)
mic2 = math.radians(0)
mic3 = math.radians(-120)
mic4 = math.radians(120)
ax = plt.subplot(111,polar=True)
ycoords = [0,100,100,100]
xcoords = [mic1,mic2,mic3,mic4]
ax.plot((0,theta),(0,200) , c = 'r', linewidth = 3)
ax.plot((0,mic2),(0,100) , c = 'b', linewidth = 3)
ax.plot((0,mic3),(0,100) , c = 'b', linewidth = 3)
ax.plot((0,mic4),(0,100) , c = 'b', linewidth = 3)
ax.scatter(xcoords,ycoords, c = 'b', linewidth = 7)
ax.annotate('detector mic', xy=(0, 0), xytext=(24,19))
ax.annotate('mic2(North)', xy=(0, 0), xytext=(mic2, 115))
ax.annotate('mic3', xy=(0, 0), xytext=(mic3, 125))
ax.annotate('mic4', xy=(0, 0), xytext=(mic4, 150))
ax.annotate(('vector to source:\n %f degrees' % math.degrees(theta)),xy = (0,0),xytext=(theta-25,300))
ax.annotate('plot for node number: %d' % node_num, xy=(0, 0), xytext=(100,300))
def reformat(msgs):
node_count = 0
# re-format data
for msg in msgs:
word = []
message_lst = []
count = len(msg)
for char in msg:
if char != ',' and count > 0:
word.append(char)
count -= 1
# print 'count: ', count
elif char == ',' and count > 0:
word = ''.join(word)
message_lst.append(word[:])
word = []
count -= 1
word = ''.join(word)
message_lst.append(word[:])
message_lst = [float(message_lst[0]), float(message_lst[1]), int(message_lst[2]),float(message_lst[3])]
# print 'converted message_lst: ',message_lst
test_num = message_lst[3]
node_num = message_lst[2]
shot_time = message_lst[0]
theta = message_lst[1]
# show user the metrics received from a node (timestamp, node number, shot direction
print "time of shot: ", shot_time
print 'test number: ', test_num
print "node number: ", node_num
node_count += 1
print "direction of shot: %f degrees counterclockwise from north" % theta
print 'node count: ', node_count
# send data received from node
plot_more_stuff(theta, node_num)
node_count = 0
#get ip addr and port #
ip_addr = '0.0.0.0'
print int(sys.argv[1])
if int(sys.argv[1]) > 999:
port = int(sys.argv[1])
else:
port = int(raw_input("what port# would you like to listen to? "))
print "listening on IP address: ", ip_addr
print "listening on port: ", port
#build socket using above user input
serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serversocket.bind((ip_addr, port))
#serversocket.listen(5) # become a server socket, maximum 5 connections
shutdown = 0
timeout = None
quick_list = []
#wait for connection
while node_count < 3 and shutdown == 0:
try:
print "number of nodes that have reported in so far: ",node_count
serversocket.settimeout(timeout)
print 'waiting for data from node(s)'
#connection, address = serversocket.accept()
data = serversocket.recv(128)
quick_list.append(data)
node_count +=1
print timeout
if timeout == None:
timeout = 5
except socket.timeout:
print "no other nodes reported gunshots in a logical amount of time"
break
reformat(quick_list)
print "plotting data"
plt.savefig('foo.png')
plt.show()
<file_sep># CMake generated Testfile for
# Source directory: /home/ben/Desktop/senior_design/gnuradio/gr-astra/python
# Build directory: /home/ben/Desktop/senior_design/gnuradio/gr-astra/build/python
#
# This file includes the relevant testing commands required for
# testing this directory and lists subdirectories to be tested as well.
ADD_TEST(qa_timestamper_ff "/bin/sh" "/home/ben/Desktop/senior_design/gnuradio/gr-astra/build/python/qa_timestamper_ff_test.sh")
ADD_TEST(qa_xcorr_ts_ff "/bin/sh" "/home/ben/Desktop/senior_design/gnuradio/gr-astra/build/python/qa_xcorr_ts_ff_test.sh")
ADD_TEST(qa_peak_detect_ff "/bin/sh" "/home/ben/Desktop/senior_design/gnuradio/gr-astra/build/python/qa_peak_detect_ff_test.sh")
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import matplotlib.pyplot as plt
import math
import time
import numpy
import sys
import os
def reformat(msg):
splitline= msg.split(',')#splits the line when a comma is read
GPS_type = splitline[4]# begins with $GPGGA
time = splitline[5]#information we we wish to extract
latitude= splitline[6]#line number is the order the data is written in the GPGGA line
latDir=splitline[7]
longitude=splitline[8]
longDir=splitline[9]
print 'total msg: ',msg#prints the entire line
print 'time: ',time
print 'lat: ', latitude
print 'long: ', longitude
#get ip addr and port #
ip_addr = '0.0.0.0'
msg_num = 1
if len(sys.argv) == 1:
print 'you didnt type a port number argument when you ran the script'
port = int(raw_input("what port# would you like to listen to?"))
elif int(sys.argv[1]) > 999:
port = int(sys.argv[1])
else:
print 'you entered a port number less than 1000'
port = int(raw_input("what port# would you like to listen to? "))
print "listening on IP address: ", ip_addr
print "listening on port: ", port
#build socket using above user input
serversocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serversocket.bind((ip_addr, port))
#serversocket.listen(5) # become a server socket, maximum 5 connections
while 1:
msg = serversocket.recv(128)
print 'msg #: %d' % msg_num
msg_num += 1
reformat(msg)
<file_sep>__author__ = 'kellen'
import math
ONE_RADIAN_IN_DEGREES = 180.0
def degrees_to_radians(degrees):
print degrees
print math.pi
print ONE_RADIAN_IN_DEGREES
return degrees * math.pi / ONE_RADIAN_IN_DEGREES
def radians_to_degrees(radians):
return radians * (ONE_RADIAN_IN_DEGREES / math.pi)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
filename = "/home/ben/Desktop/gps.txt"
f = open(filename,'r')
print f.read()
print type (f.read())
<file_sep>FILE(REMOVE_RECURSE
"CMakeFiles/pygen_python_b9106"
"__init__.pyc"
"timestamper_ff.pyc"
"xcorr_ts_ff.pyc"
"peak_detect_ff.pyc"
"__init__.pyo"
"timestamper_ff.pyo"
"xcorr_ts_ff.pyo"
"peak_detect_ff.pyo"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang)
INCLUDE(CMakeFiles/pygen_python_b9106.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
<file_sep>INCLUDE(FindPkgConfig)
PKG_CHECK_MODULES(PC_ASTRA astra)
FIND_PATH(
ASTRA_INCLUDE_DIRS
NAMES astra/api.h
HINTS $ENV{ASTRA_DIR}/include
${PC_ASTRA_INCLUDEDIR}
PATHS ${CMAKE_INSTALL_PREFIX}/include
/usr/local/include
/usr/include
)
FIND_LIBRARY(
ASTRA_LIBRARIES
NAMES gnuradio-astra
HINTS $ENV{ASTRA_DIR}/lib
${PC_ASTRA_LIBDIR}
PATHS ${CMAKE_INSTALL_PREFIX}/lib
${CMAKE_INSTALL_PREFIX}/lib64
/usr/local/lib
/usr/local/lib64
/usr/lib
/usr/lib64
)
INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(ASTRA DEFAULT_MSG ASTRA_LIBRARIES ASTRA_INCLUDE_DIRS)
MARK_AS_ADVANCED(ASTRA_LIBRARIES ASTRA_INCLUDE_DIRS)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import math
import time
import numpy
import sys
import os
import matplotlib.pyplot as plt
def get_streams_from_files(test_number):
#for gnuradio output file
with open('/home/ben/Desktop/senior_design/gnuradio/data_files/in1file%s.csv' % test_number, 'rb') as f1:
#for matlab output file
#with open("/home/ben/Desktop/senior_design/gnuradio/data_files/stream1.csv",'rb') as f1:
reader = csv.reader(f1)
in1 = []
for row in reader:
print len(row)
for num in row:
num = float(num)
in1.append(num)
print len(in1)
# for gnuradio output file
with open('/home/ben/Desktop/senior_design/gnuradio/data_files/in2file%s.csv' % test_number, 'rb') as f2:
# for matlab output file
#with open("/home/ben/Desktop/senior_design/gnuradio/data_files/stream2.csv", 'rb') as f2:
reader = csv.reader(f2)
in2 = []
for row in reader:
print len(row)
for num in row:
num = float(num)
in2.append(num)
print len(in2)
# for gnuradio output file
with open('/home/ben/Desktop/senior_design/gnuradio/data_files/in3file%s.csv' % test_number, 'rb') as f3:
# for matlab output file
#with open("/home/ben/Desktop/senior_design/gnuradio/data_files/stream3.csv", 'rb') as f3:
reader = csv.reader(f3)
in3 = []
for row in reader:
print len(row)
for num in row:
num = float(num)
in3.append(num)
print len(in3)
# for gnuradio output file
with open('/home/ben/Desktop/senior_design/gnuradio/data_files/in4file%s.csv' % test_number, 'rb') as f4:
# for matlab output file
#with open("/home/ben/Desktop/senior_design/gnuradio/data_files/stream4.csv", 'rb') as f4:
reader = csv.reader(f4)
in4 = []
for row in reader:
print len(row)
for num in row:
num = float(num)
in4.append(num)
print len(in4)
ins = [in1, in2, in3, in4]
return ins
def xcorr(mic1_detector, mic2_locator, mic3_locator, mic4_locator,test_num):
# cross correlate detector with element 2
autocorr = numpy.correlate(mic1_detector, mic1_detector, "same")
mxind0 = numpy.where(autocorr == max(autocorr))
mxind0 = mxind0[0][0]
middle = mxind0
print 'location of initial detection is: ', middle
print "len autocorr: ", len(autocorr)
plt.figure(5)
plt.plot(autocorr)
#plt.show()
xcorr1 = numpy.correlate(mic1_detector, mic2_locator, "same")
mxind1 = numpy.where(xcorr1 == max(xcorr1))
mxind1 = mxind1[0][0]
print 'mxind1 is: ',mxind1
print 'middle', middle
lag1 = middle - mxind1
print "len xcorr1: ", len(xcorr1)
print "lag1: ", lag1
# cross correlate detector with element 3
xcorr2 = numpy.correlate(mic1_detector, mic3_locator, "same")
mxind2 = numpy.where(xcorr2 == max(xcorr2))
mxind2 = mxind2[0][0]
print 'mxind2 is: ', mxind2
lag2 = middle - mxind2
print "len xcorr2: ", len(xcorr2)
print "lag2: ", lag2
# cross correlate detector with element 4
xcorr3 = numpy.correlate(mic1_detector, mic4_locator, "same")
mxind3 = numpy.where(xcorr3 == max(xcorr3))
mxind3 = mxind3[0][0]
print 'mxind3 is: ', mxind3
lag3 = middle - mxind3
print "len xcorr3: ", len(xcorr3)
print "lag3: ", lag3
plt.figure(2)
plt.subplot(411)
plt.plot(autocorr)
plt.plot(numpy.argmax(autocorr), max(autocorr), '-rD')
plt.ylabel('autocorr')
plt.subplot(412)
plt.plot(xcorr1)
plt.plot(numpy.argmax(xcorr1), max(xcorr1), '-bD')
plt.ylabel('xcorr1')
plt.subplot(413)
plt.plot(xcorr2)
plt.plot(numpy.argmax(xcorr2), max(xcorr2), '-gD')
plt.ylabel('xcorr2')
plt.subplot(414)
plt.plot(xcorr3)
plt.plot(numpy.argmax(xcorr3), max(xcorr3), '-yD')
plt.ylabel('xcorr3')
plt.savefig('/home/ben/Desktop/senior_design/field_test/plots/%s.cross_corr.png' % test_num)
# if (lag1 or lag2 or lag3) > 100:
center_mic_offset = 0
lag1 = lag1-center_mic_offset
lag2 = lag2-center_mic_offset
lag3 = lag3-center_mic_offset
lags = [lag1,lag2,lag3]
return lags
def angler(lags,mic_dist):
print 'lags in angler', lags
#speed of sound
c = 343 #m/s
elem_dist = mic_dist #meters
#sampling rate
fs = 44100.0 #samps/sec
third_mic = lags.index([max(lags)]), int(max(lags))
print "third mic w/o abs val: ", third_mic
lags[third_mic[0]] = -99999
second_mic = lags.index([max(lags)]), int(max(lags))
print "second mic w/o abs val: ", second_mic
lags[second_mic[0]] = -99999
first_mic = lags.index([max(lags)]), int(max(lags))
print "first mic w/o abs val: ", first_mic
lags[first_mic[0]] = -99999
print 'first mic to receive hit is: ',first_mic[0]+2
print 'second mic to receive hit is: ',second_mic[0]+2
print 'third mic to receive hit is: ',third_mic[0]+2
print "first_mic[1]: ",first_mic[1]
print "taking abs val of first mic for calculation purposes"
print 'first mic abs val: ',math.fabs(first_mic[1])
t_delay = math.fabs(first_mic[1])/fs
print "t_delay is: ",t_delay
print "distance (x = c*t_delay) is: ",c*t_delay
theta = math.degrees(math.acos((c*t_delay)/elem_dist))
print 'angle between detector and first mic (theta = invcos(c*t_delay)/elem_dist): ',theta
print "determining which side its on using which mics came after"
if first_mic[0]+2 == 2 and second_mic[0]+2 == 4:
theta = theta
elif first_mic[0]+2 == 2 and second_mic[0]+2 == 3:
theta = -theta
elif first_mic[0]+2 == 3 and second_mic[0]+2 == 2:
theta = theta+240
elif first_mic[0]+2 == 3 and second_mic[0]+2 == 4:
theta = 240-theta
elif first_mic[0]+2 == 4 and second_mic[0]+2 == 3:
theta = 120+theta
elif first_mic[0]+2 == 4 and second_mic[0]+2 == 2:
theta = 120-theta
else:
print "missed a case here"
print "theta after looking at other mics: ",theta
first_mic_and_angle = [first_mic[0]+2,theta]
return first_mic_and_angle
def plot_stuff(in1,in2,in3,in4,test_num):
x1 = in1.index(max(in1))
y1 = max(in1)
x2 = in2.index(max(in2))
y2 = max(in2)
x3 = in3.index(max(in3))
y3 = max(in3)
x4 = in4.index(max(in4))
y4 = max(in4)
plt.figure(1)
plt.subplot(411)
plt.plot(in1)
plt.plot(in1.index(max(in1)), max(in1),'-rD')
#plt.annotate(str(x1), xy=(x1,y1), xytext=(x1,y1))
plt.ylabel('in1')
plt.subplot(412)
plt.plot(in2)
plt.plot(in2.index(max(in2)), max(in2),'-bD')
plt.ylabel('in2')
plt.subplot(413)
plt.plot(in3)
plt.plot(in3.index(max(in3)), max(in3),'-gD')
plt.ylabel('in3')
plt.subplot(414)
plt.plot(in4)
plt.plot(in4.index(max(in4)), max(in4),'-yD')
plt.ylabel('in4')
plt.savefig('/home/ben/Desktop/senior_design/field_test/plots/%s.streams.png' % test_num)
#plt.figure(4)
#plt.plot(in1,'r',in2,'b',in3,'g',in4,'y')
def plot_more_stuff(theta):
theta = math.radians(theta)
first_mic = elem_num_and_theta[0]
# # Polar plotting
fig = plt.figure(5) # Size
ax = plt.subplot(111, polar=True) # Create subplot
plt.grid(color='#888888') # Color the grid
ax.set_theta_zero_location('N') # Set zero to North
mic1 = math.radians(0)
mic2 = math.radians(0)
mic3 = math.radians(-120)
mic4 = math.radians(120)
ax = plt.subplot(111,polar=True)
ycoords = [0,100,100,100]
xcoords = [mic1,mic2,mic3,mic4]
ax.plot((0,theta),(0,200) , c = 'r', linewidth = 3)
ax.plot((0,mic2),(0,100) , c = 'b', linewidth = 3)
ax.plot((0,mic3),(0,100) , c = 'b', linewidth = 3)
ax.plot((0,mic4),(0,100) , c = 'b', linewidth = 3)
ax.scatter(xcoords,ycoords, c = 'b', linewidth = 7)
ax.annotate('detector mic', xy=(0, 0), xytext=(24,19))
ax.annotate('mic2(North)', xy=(0, 0), xytext=(mic2, 115))
ax.annotate('mic3', xy=(0, 0), xytext=(mic3, 125))
ax.annotate('mic4', xy=(0, 0), xytext=(mic4, 150))
ax.annotate(('vector to source:\n %f degrees' % math.degrees(theta)),xy = (0,0),xytext=(theta-25,300))
##################################################
#--------------------MAIN------------------------#
##################################################
if len(sys.argv[1]) > 1:
test_number = sys.argv[1]
else:
print ('test number example is: AR15.50m.120deg.shot1')
test_number = raw_input('enter test number to analyze: ')
mic_dist = float(raw_input('enter mic_dist: '))
ins = get_streams_from_files(test_number)
#cross_correlate all inputs with in1 and get back lags
result = xcorr(ins[0],ins[1],ins[2],ins[3],test_number)
#calculate angle of arrival and first_element to receive signal
elem_num_and_theta = angler(result,mic_dist) #result = lags
plot_stuff(ins[0],ins[1],ins[2],ins[3],test_number)
theta = elem_num_and_theta[1]
plot_more_stuff(theta)
plt.show()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
kml_file = open('/home/ben/Desktop/python_kml_writer_output.kml','w+')
line1 = '<?xml version="1.0" encoding="UTF-8"?>\n'
line2 = '<kml xmlns="http://www.opengis.net/kml/2.2">\n'
line3 = '\t<Document>\n'
line5 = '\t\t<name>Paths</name>\n'
line6 = '\t\t<description>Examples of paths. Note that the tessellate tag is by default\n'
line7 = '\t\tset to 0. If you want to create tessellated lines, they must be authored\n'
line8 = '\t\t(or edited) directly in KML.</description>\n'
line9 = '\t\t<Style id="yellowLineGreenPoly">\n'
line10 ='\t\t\t<LineStyle>\n'
line11 ='\t\t\t\t<color>7f00ffff</color>\n'
line12 ='\t\t\t\t<width>2</width>\n'
line13 ='\t\t\t</LineStyle>\n'
line14 ='\t\t\t<PolyStyle>\n'
line15 ='\t\t\t\t<color>7f00ff00</color>\n'
line16 ='\t\t\t</PolyStyle>\n'
line17 ='\t\t</Style>\n'
line18 ='\t\t<Placemark>\n'
line19 ='\t\t\t<name>Absolute Extruded</name>\n'
line20 ='\t\t\t<description>Transparent green wall with yellow outlines</description>\n'
line21 ="\t\t\t<styleUrl>#yellowLineGreenPoly</styleUrl>'\n"
line22 ='\t\t\t<LineString>\n'
line23 ='\t\t\t\t<extrude>1</extrude>\n'
line24 ='\t\t\t\t<tessellate>1</tessellate>\n'
line25 ='\t\t\t\t<altitudeMode>absolute</altitudeMode>\n'
line26 ='\t\t\t\t<coordinates> -112.2550785337791,36.07954952145647,2357\n'
line27 ='\t\t\t\t-112.2549277039738,36.08117083492122,2357\n'
line28 ='\t\t\t\t-112.2552505069063,36.08260761307279,2357\n'
line29 ='\t\t\t\t</coordinates>\n'
line30 ='\t\t\t</LineString>\n'
line31 ='\t\t</Placemark>\n'
line32 ='\t</Document>\n'
line33 ='</kml>\n'
kml_file.writelines([line1,line2,line3,line5,line6,line7,line8,line9,
line10,line11,line12,line13,line14,line15,line16,line17,line18,line19,line20,
line21,line22,line23,line24,line25,line26,line27,line28,line29,line30,line31,line32,line33])
<file_sep>#!/usr/bin/env python2
# -*- coding: utf-8 -*-
##################################################
# GNU Radio Python Flow Graph
# Title: Top Block
# Generated: Sat Oct 8 17:09:26 2016
##################################################
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.startswith('linux'):
try:
x11 = ctypes.cdll.LoadLibrary('libX11.so')
x11.XInitThreads()
except:
print "Warning: failed to XInitThreads()"
from PyQt4 import Qt
from gnuradio import audio
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio import qtgui
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from optparse import OptionParser
import sip
import sys
class top_block(gr.top_block, Qt.QWidget):
def __init__(self):
gr.top_block.__init__(self, "Top Block")
Qt.QWidget.__init__(self)
self.setWindowTitle("Top Block")
try:
self.setWindowIcon(Qt.QIcon.fromTheme('gnuradio-grc'))
except:
pass
self.top_scroll_layout = Qt.QVBoxLayout()
self.setLayout(self.top_scroll_layout)
self.top_scroll = Qt.QScrollArea()
self.top_scroll.setFrameStyle(Qt.QFrame.NoFrame)
self.top_scroll_layout.addWidget(self.top_scroll)
self.top_scroll.setWidgetResizable(True)
self.top_widget = Qt.QWidget()
self.top_scroll.setWidget(self.top_widget)
self.top_layout = Qt.QVBoxLayout(self.top_widget)
self.top_grid_layout = Qt.QGridLayout()
self.top_layout.addLayout(self.top_grid_layout)
self.settings = Qt.QSettings("GNU Radio", "top_block")
self.restoreGeometry(self.settings.value("geometry").toByteArray())
##################################################
# Variables
##################################################
self.samp_rate = samp_rate = 44100
##################################################
# Blocks
##################################################
self.qtgui_time_sink_x_0_0_0 = qtgui.time_sink_f(
1024*200, #size
samp_rate, #samp_rate
"threshold", #name
1 #number of inputs
)
self.qtgui_time_sink_x_0_0_0.set_update_time(0.10)
self.qtgui_time_sink_x_0_0_0.set_y_axis(-1, 1)
self.qtgui_time_sink_x_0_0_0.set_y_label("Amplitude", "")
self.qtgui_time_sink_x_0_0_0.enable_tags(-1, True)
self.qtgui_time_sink_x_0_0_0.set_trigger_mode(qtgui.TRIG_MODE_FREE, qtgui.TRIG_SLOPE_POS, 0.0, 0, 0, "")
self.qtgui_time_sink_x_0_0_0.enable_autoscale(False)
self.qtgui_time_sink_x_0_0_0.enable_grid(False)
self.qtgui_time_sink_x_0_0_0.enable_control_panel(True)
if not True:
self.qtgui_time_sink_x_0_0_0.disable_legend()
labels = ["", "", "", "", "",
"", "", "", "", ""]
widths = [1, 1, 1, 1, 1,
1, 1, 1, 1, 1]
colors = ["blue", "red", "green", "black", "cyan",
"magenta", "yellow", "dark red", "dark green", "blue"]
styles = [1, 1, 1, 1, 1,
1, 1, 1, 1, 1]
markers = [-1, -1, -1, -1, -1,
-1, -1, -1, -1, -1]
alphas = [1.0, 1.0, 1.0, 1.0, 1.0,
1.0, 1.0, 1.0, 1.0, 1.0]
for i in xrange(1):
if len(labels[i]) == 0:
self.qtgui_time_sink_x_0_0_0.set_line_label(i, "Data {0}".format(i))
else:
self.qtgui_time_sink_x_0_0_0.set_line_label(i, labels[i])
self.qtgui_time_sink_x_0_0_0.set_line_width(i, widths[i])
self.qtgui_time_sink_x_0_0_0.set_line_color(i, colors[i])
self.qtgui_time_sink_x_0_0_0.set_line_style(i, styles[i])
self.qtgui_time_sink_x_0_0_0.set_line_marker(i, markers[i])
self.qtgui_time_sink_x_0_0_0.set_line_alpha(i, alphas[i])
self._qtgui_time_sink_x_0_0_0_win = sip.wrapinstance(self.qtgui_time_sink_x_0_0_0.pyqwidget(), Qt.QWidget)
self.top_grid_layout.addWidget(self._qtgui_time_sink_x_0_0_0_win, 1,0,1,2)
self.blocks_file_source_0 = blocks.file_source(gr.sizeof_float*1, "/home/ben/Desktop/senior_design/field_test/audio_recordings/AR.50m", False)
self.audio_sink_0 = audio.sink(samp_rate, "", True)
##################################################
# Connections
##################################################
self.connect((self.blocks_file_source_0, 0), (self.audio_sink_0, 0))
self.connect((self.blocks_file_source_0, 0), (self.qtgui_time_sink_x_0_0_0, 0))
def closeEvent(self, event):
self.settings = Qt.QSettings("GNU Radio", "top_block")
self.settings.setValue("geometry", self.saveGeometry())
event.accept()
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.qtgui_time_sink_x_0_0_0.set_samp_rate(self.samp_rate)
def main(top_block_cls=top_block, options=None):
from distutils.version import StrictVersion
if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"):
style = gr.prefs().get_string('qtgui', 'style', 'raster')
Qt.QApplication.setGraphicsSystem(style)
qapp = Qt.QApplication(sys.argv)
tb = top_block_cls()
tb.start()
tb.show()
def quitting():
tb.stop()
tb.wait()
qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting)
qapp.exec_()
if __name__ == '__main__':
main()
<file_sep>#!/usr/bin/env python
import socket
import serial #python package for reading serial ports
ser=serial.Serial( '/dev/ttyUSB0', 4800, timeout = 5)#creates serial vairable and sets port to read from and speed to read from port. Timeout prevents program from waiting more than X seconds in case of infinite loop
ip_addr = '0.0.0.0'
port = 5557
while 1:
line = ser.readline()#reads a line of data from port
splitline= line.split(',')#splits the line when a comma is read
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientsocket.connect((ip_addr,port))
msg = line
print "running on ip: %s \nrunning on port: %s" % (ip_addr,port)
filename = "/home/ben/Desktop/senior_design/python/gps.txt"
if splitline[0] == '$GPGGA':#if line begins with $GPGGA
print 'in if statement'
print 'splitline[0]: ',splitline[0]
f = open(filename,'w')
f.write(line)
f.close()
time = splitline[1]#information we we wish to extract
latitude= splitline[2]#line number is the order the data is written in the GPGGA line
latDir=splitline[3]
longitude=splitline[4]
longDir=splitline[5]
print 'time: ',time
print 'lat: ', latitude
print 'long: ', longitude
print 'message being sent to server',msg
clientsocket.send(msg)
clientsocket.close()
else:
clientsocket.close()
#break
<file_sep>__author__ = 'kellen'
class CartesianPoint(object):
def __init__(self, x, y, z):
self._x = x
self._y = y
self._z = z
@property
def x(self):
return self._x
@property
def y(self):
return self._y
@property
def z(self):
return self._z
<file_sep>class GeographicPoint(object):
def __init__(self, lat, lon, alt):
self._latitude = lat
self._longitude = lon
self._altitude = alt
@property
def latitude(self):
return self._latitude
@property
def longitude(self):
return self._longitude
@property
def altitude(self):
return self._altitude
def equals(self, pt):
return self._latitude == pt.latitude and self._longitude == pt.longitude
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
UDP_IP = "0.0.0.0"
UDP_PORT = 5555
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
short_list = []
node_count = 0
while node_count < 2:
try:
sock.settimeout(10)
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
short_list.append(data)
node_count =+1
except socket.timeout:
print 'socket timed out'
break
index = 0
for msg in short_list:
print 'msg #%d: %s' % (index +1,msg)
index +=1
<file_sep>import math
from cartesian_point import CartesianPoint
import conversions
from geographic_point import GeographicPoint
EARTH_RADIUS_IN_METERS = 6371137.0
def compute_endpoint(origin, bearing, distance):
angular_distance = distance / EARTH_RADIUS_IN_METERS
bearing_radians = conversions.degrees_to_radians(bearing)
lat1 = conversions.degrees_to_radians(origin.latitude)
lon1 = conversions.degrees_to_radians(origin.longitude)
radianLat2 = math.asin(math.sin(lat1) * math.cos(angular_distance) +
math.cos(lat1) * math.sin(angular_distance) * math.cos(bearing_radians))
radianLon2 = lon1 + math.atan2(math.sin(bearing_radians) * math.sin(angular_distance) * math.cos(lat1),
math.cos(angular_distance) - math.sin(lat1) * math.sin(radianLat2))
lat2 = conversions.radians_to_degrees(radianLat2)
lon2 = conversions.radians_to_degrees(radianLon2)
return GeographicPoint(lat2, lon2, origin.altitude)
def compute_bearing(start, end):
if start.equals(end):
return -1
lat1 = conversions.degrees_to_radians(start.latitude)
lat2 = conversions.degrees_to_radians(end.latitude)
dlon = conversions.degrees_to_radians(end.longitude - start.longitude)
y = math.sin(dlon) * math.cos(lat2)
x = math.cos(lat1) * math.sin(lat2) - math.sin(lat1) * math.cos(lat2) * math.cos(dlon)
theta = math.atan2(y, x)
theta = conversions.radians_to_degrees(theta)
theta += 360.0
while theta > 360.0:
theta -= 360.0
return theta
def compute_distance(start, end):
if start.equals(end):
return 0
lat1 = conversions.degrees_to_radians(start.latitude)
lat2 = conversions.degrees_to_radians(end.latitude)
lon1 = conversions.degrees_to_radians(start.longitude)
lon2 = conversions.degrees_to_radians(end.longitude)
x = math.acos(math.sin(lat1) * math.sin(lat2) +
math.cos(lat1) * math.cos(lat2) *
math.cos(lon2 - lon1)) * EARTH_RADIUS_IN_METERS
y = math.fabs(start.altitude - end.altitude)
result = math.sqrt(x * x + y * y)
return result
def compute_2d_distance(start, end):
if start.equals(end):
return 0
lat1 = conversions.degrees_to_radians(start.latitude)
lat2 = conversions.degrees_to_radians(end.latitude)
lon1 = conversions.degrees_to_radians(start.longitude)
lon2 = conversions.degrees_to_radians(end.longitude)
return math.acos(math.sin(lat1) * math.sin(lat2) +
math.cos(lat1) * math.cos(lat2) *
math.cos(lon2 - lon1)) * EARTH_RADIUS_IN_METERS
def compute_midpoint(start, end):
lat1 = conversions.degrees_to_radians(start.latitude)
lon1 = conversions.degrees_to_radians(start.longitude)
lat2 = conversions.degrees_to_radians(end.latitude)
lon2 = conversions.degrees_to_radians(end.longitude)
bx = math.cos(lat2) * math.cos(lon2 - lon1)
by = math.cos(lat2) * math.sin(lon2 - lon1)
latm = math.atan2(math.sin(lat1) + math.sin(lat2),
math.sqrt(math.pow(math.cos(lat1) + bx, 2) + math.pow(by, 2)))
lonm = lon1 + math.atan2(by, math.cos(lat1) + bx)
return GeographicPoint(conversions.radians_to_degrees(latm),
conversions.radians_to_degrees(lonm),
(max(start.altitude, end.altitude) - min(start.altitude, end.altitude)) / 2.0)
def cartesian_coordinate_to_geographic(cartesian_point, origin, rotation=0):
rotated_cartesian_coordinates = rotate_cartesian_coordinates(cartesian_point.x, cartesian_point.y,
cartesian_point.z, rotation)
phi_angle = conversions.radians_to_degrees(math.atan2(rotated_cartesian_coordinates.x,
rotated_cartesian_coordinates.y))
length = math.sqrt(math.pow(cartesian_point.x, 2) + math.pow(cartesian_point.y, 2))
result = compute_endpoint(origin, phi_angle, length)
return GeographicPoint(result.latitude, result.longitude, cartesian_point.z)
def geographic_coordinate_to_cartesian(origin, point, rotation):
length = compute_2d_distance(origin, point)
heading = compute_bearing(origin, point)
cartesian_angle = geographic_heading_to_cartesian_angle(heading)
x = length * math.cos(conversions.degrees_to_radians(cartesian_angle));
y = length * math.sin(conversions.degrees_to_radians(cartesian_angle));
rotated_cartesian_coordinates = rotate_cartesian_coordinates(x, y, point.altitude, rotation)
# print "length@geographicHeading: {0}@{1}, {2}".format(length, heading, cartesian_angle)
# print "x,y: {0},{1}".format(x, y)
# print "rotated x,y: {0},{1}".format(rotated_cartesian_coordinates.x, rotated_cartesian_coordinates.y)
return rotated_cartesian_coordinates
def geographic_heading_to_cartesian_angle(geographic_heading):
if 0 < geographic_heading < 180:
geographic_heading = 0 - geographic_heading
else:
geographic_heading = 360 - geographic_heading
if geographic_heading < 0:
geographic_heading += 360.0
geographic_heading += 90
return geographic_heading % 360
def geographic_heading_wrap_angle(geographic_heading):
if geographic_heading >= 360.0:
temp = int(geographic_heading / 360)
geographic_heading -= temp * 360
elif geographic_heading < 0:
temp = int(geographic_heading / 360)
geographic_heading += temp * 360
geographic_heading += 360
return geographic_heading % 360
def rotate_cartesian_coordinates(x, y, z, rotation_degrees):
# http://www.mathematics-online.org/inhalt/aussage/aussage444/
cartesian_rotate_radians = conversions.degrees_to_radians(rotation_degrees)
xhat = x * math.cos(cartesian_rotate_radians) + y * math.sin(cartesian_rotate_radians)
yhat = -x * math.sin(cartesian_rotate_radians) + y * math.cos(cartesian_rotate_radians)
return CartesianPoint(xhat, yhat, z)
<file_sep>var api_8h =
[
[ "ASTRA_API", "api_8h.html#a92d0a0e290468c38d80b0a14f40ac7ad", null ]
];<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import time
import serial
import sys
import os
import errno
from socket import error as socket_error
def socksend(msg):
try:
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#clientsocket.connect((ip_addr, port))
clientsocket.sendto(msg,(ip_addr, port))
return 1
except socket_error as serr:
if serr.errno != errno.ECONNREFUSED:
raise serr
print '***NO CONNECTION***'
return 0
if len(sys.argv) < 5:
port = int(raw_input('port number = '))
ip_addr = raw_input('ip address = ')
node_number = int(raw_input('node # = '))
real_or_fake = int(raw_input('do you want real data or fake data?\n press 1 for real, press 2 for fake'))
else:
port = int(sys.argv[1])
ip_addr = sys.argv[2]
node_number = int(sys.argv[3])
real_or_fake = int(sys.argv[4])
print '\n\n*************************'
print "port: ",port
print "ip address: ",ip_addr
print "node number: ",node_number
if real_or_fake ==1:
print "real data (option 1)"
else:
print "fake data (option 2)"
print '*************************\n'
n = 1
detect_filename = '/home/ben/Desktop/senior_design/python/detection.txt'
try:
os.remove(detect_filename)
except OSError:
pass
if real_or_fake == 1: #real
while os.path.isfile(detect_filename) == False:
ser = serial.Serial('/dev/ttyUSB0', 4800, timeout=5)
msg = ser.readline()
splitline = msg.split(',')
if splitline[0] == '$GPGGA': # if line begins with $GPGGA
filename = "/home/ben/Desktop/senior_design/python/gps.txt"
f = open(filename, 'w')
f.write(msg)
f.close()
# print 'splitline[0]: ',splitline[0]
gps_time = splitline[1] # information we we wish to extract
latitude = splitline[2] # line number is the order the data is written in the GPGGA line
latDir = splitline[3]
longitude = splitline[4]
longDir = splitline[5]
print 'time: ', gps_time
print 'lat: ', latitude
print 'long: ', longitude
print 'sending real heartbeat info to server'
msg = str(time.time())+',,'+str(node_number)+',no test number,'+str(msg)
socksend(msg)
print 'MESSAGE #: ' + str(n) + '\nthis is the non-detect message with GPS from the puck: \n' + msg
n += 1
data = open(detect_filename, 'r')
msg = data.readline()
socksend(msg)
data.close()
print 'sending real detection data to server: \n'
print str(msg)
else: # 2 -->fake
m = 1
while m < 10:
msg = str(time.time())+',,1,school.testing.10.08.16,$GPGGA,205704.000,3849.3529,N,07701.5355,W,1,08,1.2,10.0,M,-33.5,M,,0000*54'
time.sleep(1)
x = socksend(msg)
if x == 1:
print 'sending fake GPS data to the server'
n += 1
m += 1
else:
print 'not sending data'
print 'sending fake DETECTION data to the server'
msg = str(time.time())+',5.40390060322,1,school.testing.10.08.16,$GPGGA,205704.000,3849.3529,N,07701.5355,W,1,08,1.2,10.0,M,-33.5,M,,0000*54'
socksend(msg)
<file_sep><?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
<link rel="icon" href="/FS/orbweaver/static/hgicon.png" type="image/png" />
<meta name="robots" content="index, nofollow"/>
<link rel="stylesheet" href="/FS/orbweaver/static/style-gitweb.css" type="text/css" />
<script type="text/javascript" src="/FS/orbweaver/static/mercurial.js"></script>
<title>FS/orbweaver: orbweaver-signal_distance_map_generator/src/sdm_simulator/kml_utilities.py@07f9e9bfecab</title>
<link rel="alternate" type="application/atom+xml"
href="/FS/orbweaver/atom-log" title="Atom feed for FS/orbweaver"/>
<link rel="alternate" type="application/rss+xml"
href="/FS/orbweaver/rss-log" title="RSS feed for FS/orbweaver"/>
</head>
<body>
<div class="page_header">
<a href="http://mercurial.selenic.com/" title="Mercurial" style="float: right;">Mercurial</a><a href="/FS/orbweaver/summary">FS/orbweaver</a> / file revision
</div>
<div class="page_nav">
<a href="/FS/orbweaver/summary">summary</a> |
<a href="/FS/orbweaver/shortlog">shortlog</a> |
<a href="/FS/orbweaver/log">changelog</a> |
<a href="/FS/orbweaver/graph">graph</a> |
<a href="/FS/orbweaver/tags">tags</a> |
<a href="/FS/orbweaver/bookmarks">bookmarks</a> |
<a href="/FS/orbweaver/branches">branches</a> |
<a href="/FS/orbweaver/file/07f9e9bfecab/orbweaver-signal_distance_map_generator/src/sdm_simulator/">files</a> |
<a href="/FS/orbweaver/rev/07f9e9bfecab">changeset</a> |
file |
<a href="/FS/orbweaver/file/tip/orbweaver-signal_distance_map_generator/src/sdm_simulator/kml_utilities.py">latest</a> |
<a href="/FS/orbweaver/log/07f9e9bfecab/orbweaver-signal_distance_map_generator/src/sdm_simulator/kml_utilities.py">revisions</a> |
<a href="/FS/orbweaver/annotate/07f9e9bfecab/orbweaver-signal_distance_map_generator/src/sdm_simulator/kml_utilities.py">annotate</a> |
<a href="/FS/orbweaver/diff/07f9e9bfecab/orbweaver-signal_distance_map_generator/src/sdm_simulator/kml_utilities.py">diff</a> |
<a href="/FS/orbweaver/raw-file/07f9e9bfecab/orbweaver-signal_distance_map_generator/src/sdm_simulator/kml_utilities.py">raw</a> |
<a href="/FS/orbweaver/help">help</a>
<br/>
</div>
<div class="title">orbweaver-signal_distance_map_generator/src/sdm_simulator/kml_utilities.py</div>
<div class="title_text">
<table cellspacing="0">
<tr>
<td>author</td>
<td>Brandon P. Enochs <brandon.enochs@nrl.navy.mil></td></tr>
<tr>
<td></td>
<td class="date age">Fri, 14 Oct 2016 09:40:31 -0400</td></tr>
<tr>
<td>changeset 681</td>
<td style="font-family:monospace"><a class="list" href="/FS/orbweaver/rev/07f9e9bfecab">07f9e9bfecab</a></td></tr>
<tr>
<td>parent 529</td>
<td style="font-family:monospace">
<a class="list" href="/FS/orbweaver/file/09cf38de2f73/orbweaver-signal_distance_map_generator/src/sdm_simulator/kml_utilities.py">
09cf38de2f73
</a>
</td>
</tr>
<tr>
<td>permissions</td>
<td style="font-family:monospace">-rw-r--r--</td></tr>
</table>
</div>
<div class="page_path">
FLYINGSQUIRREL-1738: fixed an ArrayIndexOutOfBoundsException in SdmGeolocationStrategyImplementation. It assumed that it was always using 3D geolocation.<br/>
<br/>
+review FLYINGSQUIRREL-400
</div>
<div class="page_body">
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l1" id="l1"> 1</a> import math
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l2" id="l2"> 2</a> import jet_color_map
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l3" id="l3"> 3</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l4" id="l4"> 4</a> ALTITUDE = 400
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l5" id="l5"> 5</a> RANGE = 400
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l6" id="l6"> 6</a> DRIVE_PATH_WIDTH = 3
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l7" id="l7"> 7</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l8" id="l8"> 8</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l9" id="l9"> 9</a> def create_tour_open(foldername):
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l10" id="l10"> 10</a> XMLVERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l11" id="l11"> 11</a> KMLXMLNS = "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" " \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l12" id="l12"> 12</a> "xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l13" id="l13"> 13</a> DOCUMENT_NAME = "\t<Document>\n" + \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l14" id="l14"> 14</a> "\t\t<name>{}</name>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l15" id="l15"> 15</a> "\t\t<open>1</open>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l16" id="l16"> 16</a> "\t\t<visibility>1</visibility>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l17" id="l17"> 17</a> return XMLVERSION + KMLXMLNS + DOCUMENT_NAME.format(foldername)
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l18" id="l18"> 18</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l19" id="l19"> 19</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l20" id="l20"> 20</a> def create_tour_close():
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l21" id="l21"> 21</a> return "\t</Document>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l22" id="l22"> 22</a> "</kml>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l23" id="l23"> 23</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l24" id="l24"> 24</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l25" id="l25"> 25</a> def create_icon(icon, icon_name, scale=1, heading=None):
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l26" id="l26"> 26</a> output = "\t\t<Style id=\"" + icon_name + "\">\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l27" id="l27"> 27</a> "\t\t\t<IconStyle>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l28" id="l28"> 28</a> "\t\t\t\t<scale>" + repr(scale) + "</scale>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l29" id="l29"> 29</a> if heading is not None:
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l30" id="l30"> 30</a> output += "\t\t\t\t<heading>" + repr(heading) + "</heading>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l31" id="l31"> 31</a> output += "\t \t\t\t<Icon><href>" + icon + "</href></Icon>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l32" id="l32"> 32</a> "\t\t\t</IconStyle>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l33" id="l33"> 33</a> "\t\t</Style>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l34" id="l34"> 34</a> return output
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l35" id="l35"> 35</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l36" id="l36"> 36</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l37" id="l37"> 37</a> def create_initial_view(point):
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l38" id="l38"> 38</a> return "\t\t<LookAt>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l39" id="l39"> 39</a> "\t\t\t<longitude>" + repr(point.longitude) + "</longitude>" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l40" id="l40"> 40</a> "<latitude>" + repr(point.latitude) + "</latitude>" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l41" id="l41"> 41</a> "<altitude>" + repr(
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l42" id="l42"> 42</a> ALTITUDE) + "</altitude><tilt>0</tilt>" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l43" id="l43"> 43</a> "<range>" + repr(RANGE) + "</range><heading>0</heading>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l44" id="l44"> 44</a> "\t\t</LookAt>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l45" id="l45"> 45</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l46" id="l46"> 46</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l47" id="l47"> 47</a> def create_initial_view(point, heading, tilt=0):
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l48" id="l48"> 48</a> return "\t\t<LookAt>\n\
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l49" id="l49"> 49</a> \t\t\t<longitude>{0}</longitude>\n\
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l50" id="l50"> 50</a> \t\t\t<latitude>{1}</latitude>\n\
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l51" id="l51"> 51</a> \t\t\t<altitude>{2}</altitude><tilt>0</tilt>\n\
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l52" id="l52"> 52</a> \t\t\t<range>{3}</range> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l53" id="l53"> 53</a> \t\t\t<heading>{4}</heading> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l54" id="l54"> 54</a> \t\t\t<tilt>{5}</tilt> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l55" id="l55"> 55</a> \t\t</LookAt>\n".format(point.longitude,
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l56" id="l56"> 56</a> point.latitude,
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l57" id="l57"> 57</a> point.altitude,
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l58" id="l58"> 58</a> RANGE,
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l59" id="l59"> 59</a> heading,
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l60" id="l60"> 60</a> tilt)
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l61" id="l61"> 61</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l62" id="l62"> 62</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l63" id="l63"> 63</a> def create_screen_overlay(icon, iconName, x_position, y_position):
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l64" id="l64"> 64</a> return "\t\t<ScreenOverlay id=\"aplegend\">\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l65" id="l65"> 65</a> "\t\t\t<name></name>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l66" id="l66"> 66</a> "\t\t\t<Icon><href>" + icon + "</href></Icon>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l67" id="l67"> 67</a> "\t\t\t<overlayXY x=\"" + repr(x_position) + "\" y=\"" + repr(y_position) + \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l68" id="l68"> 68</a> "\" xunits=\"fraction\" yunits=\"fraction\"/>" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l69" id="l69"> 69</a> "\t\t\t<screenXY x=\"" + repr(x_position) + "\" y=\"" + repr(y_position) + \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l70" id="l70"> 70</a> "\" xunits=\"fraction\" yunits=\"fraction\"/>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l71" id="l71"> 71</a> "\t\t</ScreenOverlay>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l72" id="l72"> 72</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l73" id="l73"> 73</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l74" id="l74"> 74</a> def create_folder_open(folder_name):
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l75" id="l75"> 75</a> return "\t\t<Folder id='PlotView'>\n \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l76" id="l76"> 76</a> \t\t\t<name>{0}</name>\n \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l77" id="l77"> 77</a> \t\t\t<open>0</open><visibility>0</visibility>\n".format(folder_name)
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l78" id="l78"> 78</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l79" id="l79"> 79</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l80" id="l80"> 80</a> def create_folder_close():
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l81" id="l81"> 81</a> return "\t\t</Folder>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l82" id="l82"> 82</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l83" id="l83"> 83</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l84" id="l84"> 84</a> def plot_icon(icon, location, name):
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l85" id="l85"> 85</a> result = "\t\t<Placemark>\n \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l86" id="l86"> 86</a> \t\t\t<name>{0}</name>\n \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l87" id="l87"> 87</a> \t\t\t<styleUrl>#{1}</styleUrl>\n \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l88" id="l88"> 88</a> \t\t\t<open>0</open><visibility>0</visibility>\n \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l89" id="l89"> 89</a> \t\t\t<Point>".format(name, icon)
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l90" id="l90"> 90</a> if location.altitude != 0:
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l91" id="l91"> 91</a> result += "<altitudeMode>absolute</altitudeMode>"
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l92" id="l92"> 92</a> result += "<coordinates>{0},{1},{2}</coordinates></Point>\n \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l93" id="l93"> 93</a> \t\t</Placemark>\n".format(location.longitude, location.latitude, location.altitude)
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l94" id="l94"> 94</a> return result
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l95" id="l95"> 95</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l96" id="l96"> 96</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l97" id="l97"> 97</a> def plot_line(name, line_color, line_width, start_point, end_point):
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l98" id="l98"> 98</a> return "\t\t\t<Placemark> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l99" id="l99"> 99</a> \t\t\t\t<name>{0}</name> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l100" id="l100"> 100</a> \t\t\t\t<visibility>0</visibility> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l101" id="l101"> 101</a> \t\t\t\t<Style id=\"linestyleExample\"> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l102" id="l102"> 102</a> \t\t\t\t<LineStyle> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l103" id="l103"> 103</a> \t\t\t\t\t<color>{1}</color> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l104" id="l104"> 104</a> \t\t\t\t\t<width>{2}</width> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l105" id="l105"> 105</a> \t\t\t\t</LineStyle> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l106" id="l106"> 106</a> \t\t\t\t</Style> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l107" id="l107"> 107</a> \t\t\t\t<LineString><altitudeMode>absolute</altitudeMode><coordinates>{3},{4},{5},{6},{7},{8}</coordinates></LineString> \n\
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l108" id="l108"> 108</a> \t\t\t</Placemark>\n".format(name, line_color, line_width, start_point.longitude, start_point.latitude,
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l109" id="l109"> 109</a> start_point.altitude, end_point.longitude, end_point.latitude,
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l110" id="l110"> 110</a> end_point.altitude)
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l111" id="l111"> 111</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l112" id="l112"> 112</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l113" id="l113"> 113</a> def plot_linear_ring(border_color, polygon_color, folder_name, points):
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l114" id="l114"> 114</a> result = "\t\t\t<Placemark>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l115" id="l115"> 115</a> "\t\t\t\t<name>" + folder_name + "</name>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l116" id="l116"> 116</a> "\t\t\t\t<open>0</open><visibility>0</visibility>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l117" id="l117"> 117</a> "\t\t\t\t<Style><LineStyle><color>" + border_color + "</color>" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l118" id="l118"> 118</a> "<width>2</width></LineStyle>" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l119" id="l119"> 119</a> "<PolyStyle><color>" + polygon_color + "</color>" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l120" id="l120"> 120</a> "</PolyStyle>" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l121" id="l121"> 121</a> "</Style>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l122" id="l122"> 122</a> "\t\t\t\t\t<Polygon>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l123" id="l123"> 123</a> "\t\t\t\t\t\t<altitudeMode>relativeToGround</altitudeMode>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l124" id="l124"> 124</a> "\t\t\t\t\t\t<outerBoundaryIs>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l125" id="l125"> 125</a> "\t\t\t\t\t\t\t<LinearRing>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l126" id="l126"> 126</a> "\t\t\t\t\t\t\t\t<coordinates>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l127" id="l127"> 127</a> for value in points:
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l128" id="l128"> 128</a> result += "\t\t\t\t\t\t\t\t" + repr(value.longitude) + "," + \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l129" id="l129"> 129</a> repr(value.latitude) + "," + \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l130" id="l130"> 130</a> repr(value.altitude) + "\n"
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l131" id="l131"> 131</a> result += "\t\t\t\t\t\t\t\t</coordinates>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l132" id="l132"> 132</a> "\t\t\t\t\t\t\t</LinearRing>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l133" id="l133"> 133</a> "\t\t\t\t\t\t</outerBoundaryIs>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l134" id="l134"> 134</a> "\t\t\t\t\t</Polygon>\n" \
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l135" id="l135"> 135</a> "\t\t\t</Placemark>\n"
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l136" id="l136"> 136</a> return result
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l137" id="l137"> 137</a>
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l138" id="l138"> 138</a>
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l139" id="l139"> 139</a> def create_color_from_extrema(opacity, value, extrema):
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l140" id="l140"> 140</a> difference = math.fabs(extrema.max - extrema.min)
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l141" id="l141"> 141</a> if difference == 0.0:
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l142" id="l142"> 142</a> return jet_color_map.create_color_string(opacity, 1.0)
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l143" id="l143"> 143</a> else:
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l144" id="l144"> 144</a> stepSize = .95 / difference
</pre>
</div>
<div style="font-family:monospace" class="parity0">
<pre><a class="linenr" href="#l145" id="l145"> 145</a> normalized_signal = 1.0 - (stepSize * math.fabs(extrema.max - value))
</pre>
</div>
<div style="font-family:monospace" class="parity1">
<pre><a class="linenr" href="#l146" id="l146"> 146</a> return jet_color_map.create_color_string(opacity, normalized_signal)
</pre>
</div>
</div>
<script type="text/javascript">process_dates()</script>
<div class="page_footer">
<div class="page_footer_text">FS/orbweaver</div>
<div class="rss_logo">
<a href="/FS/orbweaver/rss-log">RSS</a>
<a href="/FS/orbweaver/atom-log">Atom</a>
</div>
<br />
</div>
</body>
</html>
<file_sep>#!/usr/bin/env python
import socket
import serial #python package for reading serial ports
import time
port = int(raw_input('enter UDP port # (generally use 5557): '))
ip_addr = (raw_input('enter ip address (ex. 10.0.0.2): '))
type_of_test = int(raw_input('run for real, press 1, run dummy press 2: '))
print type(type_of_test)
#if type_of_test ==1:
# ser=serial.Serial( '/dev/ttyUSB0', 4800, timeout = 5)#creates serial vairable and sets port to read from and speed to read from port. Timeout prevents program from waiting more than X seconds in case of infinite loop
#else:
# print "running dummy GPS value of: '$GPGGA,205704.000,3849.3529,N,07701.5355,W,1,08,1.2,10.0,M,-33.5,M,,0000*54'"
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
clientsocket.connect((ip_addr,port))
msg_num = 1
while 1:
# if type_of_test == 1:
# line = ser.readline()#reads a line of data from port
# else:
line = '$GPGGA,205704.000,3849.3529,N,07701.5355,W,1,08,1.2,10.0,M,-33.5,M,,0000*54\n'
splitline= line.split(',')#splits the line when a comma is read
msg = line
print "running on ip: %s \nrunning on port: %s" % (ip_addr,port)
filename = "gps.txt"
if splitline[0] == '$GPGGA':#if line begins with $GPGGA
#print 'splitline[0]: ',splitline[0]
f = open(filename,'w')
f.write(line)
f.close()
gps_time = splitline[1]#information we we wish to extract
latitude= splitline[2]#line number is the order the data is written in the GPGGA line
latDir=splitline[3]
longitude=splitline[4]
longDir=splitline[5]
print 'time: ',gps_time
print 'lat: ', latitude
print 'long: ', longitude
print 'message being sent to server',msg
if type_of_test == 2:
print 'this is a fake message # %d' % msg_num
time.sleep(1)
msg_num+=1
else:
print 'this is a real message # %d' % msg_num
msg_num+=1
clientsocket.send(msg)
#clientsocket.close()
else:
'not a $GPGGA message'
#break
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016 <+YOU OR YOUR COMPANY+>.
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
import numpy
from gnuradio import gr
class peak_detect_ff(gr.sync_block):
"""
docstring for block peak_detect_ff
"""
def __init__(self, percent,window_size):
self.percent = .01*percent
self.window_size = window_size
self.window = []
self.limiter = 1
self.init_avg = 1
self.avg_compare = []
self.potential_max = 0
gr.sync_block.__init__(self,
name="peak_detect_ff",
in_sig=[numpy.float32],
out_sig=[numpy.float32])
def averager(self, window):
avg_val = (sum(window)/len(window))
if avg_val > 0:
avg_val +=1
else:
avg_val = avg_val
return avg_val
def work(self, input_items, output_items):
in0 = input_items[0]
out = output_items[0]
h = 0
for val in in0:
if len(self.window) < self.window_size-1:
self.window.append(val)
else:
self.window.append(val)
avg = self.averager(self.window)
#print 'average', avg
if len(self.avg_compare) < 2:
self.avg_compare.insert(0,avg)
else:
self.avg_compare.pop(1)
self.avg_compare.insert(0,avg)
print self.avg_compare
delta = abs(self.avg_compare[0]-self.avg_compare[1])
#print "avg_compare delta: ",delta
#if self.init_avg == 0:
if self.avg_compare[0] > self.avg_compare[1]*self.percent:# and self.limiter ==1:
self.potential_max = self.avg_compare[0]
print "thresh potentially exceeded with potential max: ",self.potential_max
print "thresh is avg_compare[1] * self.percent = ",(self.avg_compare[1]*self.percent)
output_items[0][h] = 1
self.window = []
self.init_avg = 0
#self.limiter = 0
#else:
# output_items[0][h] = 0
h +=1
#out[:] = in0
#print output_items
return len(output_items[0])
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import time
import serial
import sys
import os.path
def socksend(msg):
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((ip_addr, port))
clientsocket.send(msg)
filename = '/home/ben/Desktop/senior_design/python/detection.txt'
try:
os.remove(filename)
except OSError:
pass
if len(sys.argv) < 2:
port = int(raw_input('port number = '))
ip_addr = raw_input('ip address = ')
real_or_fake = int(raw_input('do you want real data or fake data?\n press 1 for real, press 2 for fake'))
else:
port = int(sys.argv[1])
ip_addr = sys.argv[2]
real_or_fake = int(sys.argv[3])
n = 1
if real_or_fake == 1:#real
while os.path.isfile(filename) == False:
print 'waiting for detection ...'
time.sleep(1)
data = open(filename, 'r')
msg = data.readline()
socksend(msg)
data.close()
print 'sending real detection data to server: \n'
print str(msg)
else:#fake
print 'sending fake detection data to the server'
msg = '1475978415.01,5.40390060322,1,school.testing.10.08.16,$GPGGA,205704.000,3849.3529,N,07701.5355,W,1,08,1.2,10.0,M,-33.5,M,,0000*54'
#time
#angle
#node number
#test name
#gps string
time.sleep(1)
socksend(msg)
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import conversions
import math
from geographic_point import GeographicPoint
class location:
def __init__(self,latitude,longitude,altitude):
self.latitude = latitude
self.longitude = longitude
self.altitude = altitude
def compute_endpoint(origin, bearing, distance):
EARTH_RADIUS_IN_METERS = 6371137.0
angular_distance = float(distance) / EARTH_RADIUS_IN_METERS
bearing_radians = conversions.degrees_to_radians(bearing)
lat1 = conversions.degrees_to_radians(origin.latitude)
lon1 = conversions.degrees_to_radians(origin.longitude)
radianLat2 = math.asin(math.sin(lat1) * math.cos(angular_distance) +
math.cos(lat1) * math.sin(angular_distance) * math.cos(bearing_radians))
radianLon2 = lon1 + math.atan2(math.sin(bearing_radians) * math.sin(angular_distance) * math.cos(lat1),
math.cos(angular_distance) - math.sin(lat1) * math.sin(radianLat2))
lat2 = conversions.radians_to_degrees(radianLat2)
lon2 = conversions.radians_to_degrees(radianLon2)
return GeographicPoint(lat2, lon2, origin.altitude)
def create_tour_open(foldername):
XMLVERSION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
KMLXMLNS = "<kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" " \
"xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n"
DOCUMENT_NAME = "\t<Document>\n" + \
"\t\t<name>{}</name>\n" \
"\t\t<open>1</open>\n" \
"\t\t<visibility>1</visibility>\n"
return XMLVERSION + KMLXMLNS + DOCUMENT_NAME.format(foldername)
def create_tour_close():
return "\t</Document>\n" \
"</kml>\n"
def create_icon(icon, icon_name, scale=1, heading=None):
output = "\t\t<Style id=\"" + icon_name + "\">\n" \
"\t\t\t<IconStyle>\n" \
"\t\t\t\t<scale>" + repr(scale) + "</scale>\n"
if heading is not None:
output += "\t\t\t\t<heading>" + repr(heading) + "</heading>\n"
output += "\t \t\t\t<Icon><href>" + icon + "</href></Icon>\n" \
"\t\t\t</IconStyle>\n" \
"\t\t</Style>\n"
return output
def create_folder_open(folder_name):
return "\t\t<Folder id='PlotView'>\n \
\t\t\t<name>{0}</name>\n \
\t\t\t<open>0</open><visibility>0</visibility>\n".format(folder_name)
def create_folder_close():
return "\t\t</Folder>\n"
def plot_icon(icon, location, name):
result = "\t\t<Placemark>\n \
\t\t\t<name>{0}</name>\n \
\t\t\t<styleUrl>#{1}</styleUrl>\n \
\t\t\t<open>0</open><visibility>0</visibility>\n \
\t\t\t<Point>".format(name, icon)
if location.altitude != 0:
result += "<altitudeMode>absolute</altitudeMode>"
result += "<coordinates>{0},{1},{2}</coordinates></Point>\n \
\t\t</Placemark>\n".format(location.longitude, location.latitude, location.altitude)
return result
def plot_line(name, line_color, line_width, start_point, end_point):
return "\t\t\t<Placemark> \n\
\t\t\t\t<name>{0}</name> \n\
\t\t\t\t<visibility>0</visibility> \n\
\t\t\t\t<Style id=\"linestyleExample\"> \n\
\t\t\t\t<LineStyle> \n\
\t\t\t\t\t<color>{1}</color> \n\
\t\t\t\t\t<width>{2}</width> \n\
\t\t\t\t</LineStyle> \n\
\t\t\t\t</Style> \n\
\t\t\t\t<LineString><altitudeMode>absolute</altitudeMode><coordinates>{3},{4},{5},{6},{7},{8}</coordinates></LineString> \n\
\t\t\t</Placemark>\n".format(name, line_color, line_width, start_point.longitude, start_point.latitude,
start_point.altitude, end_point.longitude, end_point.latitude,
end_point.altitude)
node1_loc = location(38.88541097824265,-77.10719816506928,0)
node2_loc = location(38.88453630832175,-77.10772528265257,0)
node3_loc = location(38.8845691509614,-77.10638801565288,0)
start1 = node1_loc
end1 = compute_endpoint(node1_loc,3,'1000000')
foldername = 'KmlFile'
file_start = create_tour_open(foldername)
node1_icon = create_icon('http://maps.google.com/mapfiles/kml/shapes/target.png','s_ylw-pushpin_hl0')
node2_icon = create_icon('http://maps.google.com/mapfiles/kml/shapes/target.png','s_ylw-pushpin_hl0')
node3_icon = create_icon('http://maps.google.com/mapfiles/kml/shapes/target.png','s_ylw-pushpin_hl0')
folder = create_folder_open("automate_test")
node1 = plot_icon('m_ylw-pushpin0',node1_loc,'node 1')
node2 = plot_icon('m_ylw-pushpin0',node2_loc,'node 2')
node3 = plot_icon('m_ylw-pushpin0',node3_loc,'node 3')
line1 = plot_line('line 1','ff0000aa',5,start1,end1)
folder_close = create_folder_close()
file_end = create_tour_close()
filename = open('/home/ben/Desktop/KML/automated.kml','w')
filename.write(file_start)
filename.write(node1_icon)
filename.write(node2_icon)
filename.write(node3_icon)
filename.write(folder)
filename.write(node1)
filename.write(node2)
filename.write(node3)
filename.write(line1)
filename.write(line2)
filename.write(line3)
filename.write(folder_close)
filename.write(file_end)
filename.close()
<file_sep>#!/bin/sh
export VOLK_GENERIC=1
export GR_DONT_LOAD_PREFS=1
export srcdir=/home/ben/Desktop/senior_design/gnuradio/gr-astra/python
export GR_CONF_CONTROLPORT_ON=False
export PATH=/home/ben/Desktop/senior_design/gnuradio/gr-astra/build/python:$PATH
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH
export PYTHONPATH=/home/ben/Desktop/senior_design/gnuradio/gr-astra/build/swig:$PYTHONPATH
/usr/bin/python2 /home/ben/Desktop/senior_design/gnuradio/gr-astra/python/qa_timestamper_ff.py
|
4f4387b98130d85d621c8e264cd6744a71c3eb78
|
[
"JavaScript",
"Python",
"CMake",
"Shell"
] | 26 |
Python
|
bengineer1981/ASTRA
|
aad9d97d09cb2797e8030edf65dc39939780df40
|
ec3525e28cccc19055bad3f64840aa060db49145
|
refs/heads/master
|
<file_sep>
/*
* Test vector generator for SCP03 KDF
*
* Source code:
* Derived from GlobalPlatformPro by <NAME>, <EMAIL>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3.0 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.engines.AESEngine;
import org.bouncycastle.crypto.generators.KDFCounterBytesGenerator;
import org.bouncycastle.crypto.macs.CMac;
import org.bouncycastle.crypto.params.KDFCounterParameters;
public class SCP03KDFTestVectorsGenerator {
private static byte[] scp03_kdf(byte[] key, byte constant, byte[] context, int blocklen_bits) {
// 11 bytes
byte[] label = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
ByteArrayOutputStream bo = new ByteArrayOutputStream();
try {
bo.write(label); // 11 bytes of label
bo.write(constant); // constant for the last byte
bo.write(0x00); // separator
bo.write((blocklen_bits >> 8) & 0xFF); // block size in two bytes
bo.write(blocklen_bits & 0xFF);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
byte[] blocka = bo.toByteArray();
byte[] blockb = context;
return scp03_kdf(key, blocka, blockb, blocklen_bits / 8);
}
// Generic KDF in counter mode with one byte counter.
public static byte[] scp03_kdf(byte[] key, byte[] a, byte[] b, int bytes) {
BlockCipher cipher = new AESEngine();
CMac cmac = new CMac(cipher);
KDFCounterBytesGenerator kdf = new KDFCounterBytesGenerator(cmac);
kdf.init(new KDFCounterParameters(key, a, b, 8)); // counter size is in bits
byte[] cgram = new byte[bytes];
kdf.generateBytes(cgram, 0, cgram.length);
return cgram;
}
private static String byteArrayToHex(byte[] array) {
StringBuilder sb = new StringBuilder(2 * array.length);
for (byte b : array)
sb.append(String.format("%02X", b));
return sb.toString();
}
public static void main(String argv[]) {
byte[] KI = new byte[16];
byte[] KO;
byte[] context = new byte[16];
byte constant = 0;
for (int i = 0; i < 40; i++) {
int bytes = ((i % 5) > 2) ? 16 : 32;
constant++;
KO = scp03_kdf(KI, constant, context, bytes * 8);
System.out.printf("%s %x %s %s\n", byteArrayToHex(KI), constant, byteArrayToHex(context),
byteArrayToHex(KO));
KI = context;
context = KO;
}
}
}
|
86f51baa51747f76fe2169f4bf289299b325e93b
|
[
"Java"
] | 1 |
Java
|
blaufish/scp03_kdf_testvectors
|
e6c5b93fc403bce69dff1743a5237eadbe4e6d7b
|
1f70ada36a7986a4eda8e135e30215bf989eb78a
|
refs/heads/master
|
<file_sep># Bijhouden van bezoekersaantallen in een array
De bezoekersaantallen worden per dag van de week bijgehouden.
De gebruiker geeft een datum en een bezoekersaantal in. Dit wordt dan opgeteld bij de cijfers tot dan toe.

## Bijhouden gegevens
### Gegevens per dag
De gegevens per dag worden bijgehouden in een array.
- Op index 0 worden de gegevens bijgehouden van de zondag.
- Op index 1 worden de gegevens bijgehouden van de maandag.
- Op index 2 worden de gegevens bijgehouden van de dinsdag.
### Algemeen totaal
Het totale bezoekersaantal wordt ook bijgehouden.
## Beginsituatie
Bij het opstarten
- worden de dagen van de week in de linker stack panel toegevoegd. Hiervoor is de code reeds aanwezig.
- worden de bezoekersaantallen van de dagen getoond in de rechter stack panel.
- wordt het totaal aantal bezoekers weergegeven in de titelbalk
- wordt de cursor in txtVisitors geplaatst.
- wordt de systeemdatum getoond in dtpDate en lblToday.
## Check van de input
- De methode IsValidInteger gaat na of een doorgegeven tekst zonder problemen kan omgezet worden in een geheel getal
- De methode IsValidInput gaat na of de input voldoet aan de volgende voorwaarden:
- er is een datum die niet in de toekomst ligt geselecteerd.
- er is een bezoekersaantal ingevuld dat minstens 1 is.
De check van de input gebeurt bij elke wijziging in txtVisitors en dtpDate.
Als de input geldig is, kan de btnAddVisitors gebruikt worden. Anders wordt die uitgeschakeld.
## Bezoekersaantallen ingeven
Bij een klik op de knop btnAddVisitors worden de gegeven datum en bezoekersaantal uitgelezen.
Via de methode IncreaseVisitors wordt het aantal bezoekers voor de weekdag van de doorgegeven datum verhoogd. Er wordt dus eerst nagegaan op welke dag van de week de doorgegeven datum valt. Daarna wordt aan de hand van de index de array met de bezoekersaantallen aangepast.
De bezoekersaantallen worden weergegeven in stpVisitors.
De cursor wordt in txtVisitors geplaatst en de input volledig geselecteerd.
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Prb.VisitorsCount.Wpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
int[] vistorsDaily = new int[7];
int visitorsTotal;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
AddDayNameLabels();
ShowNumberOfVisitors();
txtVisitors.Focus();
dtpDate.SelectedDate = DateTime.Now;
lblToday.Content = $"Today: + {DateTime.Now.ToShortDateString()}";
}
private void AddDayNameLabels()
{
AddDayNameLabel(1);
AddDayNameLabel(2);
AddDayNameLabel(3);
AddDayNameLabel(4);
AddDayNameLabel(5);
AddDayNameLabel(6);
AddDayNameLabel(0);
}
void AddDayNameLabel(int dayNumber)
{
Label lblDayLabel = new Label();
lblDayLabel.Content = (DayOfWeek)dayNumber;
stpNamesOfDays.Children.Add(lblDayLabel);
}
void ShowNumberOfVisitors()
{
stpVisitors.Children.Clear();
AddNumberOfVisitors(1);
AddNumberOfVisitors(2);
AddNumberOfVisitors(3);
AddNumberOfVisitors(4);
AddNumberOfVisitors(5);
AddNumberOfVisitors(6);
AddNumberOfVisitors(0);
}
void AddNumberOfVisitors(int dayNumber)
{
Label lblVisitors = new Label();
int numberOfVisitors = vistorsDaily[dayNumber];
lblVisitors.Content = numberOfVisitors;
visitorsTotal += numberOfVisitors;
stpVisitors.Children.Add(lblVisitors);
}
}
}
|
9e07b08f213b4e3725625047465b76ff398b0f65
|
[
"Markdown",
"C#"
] | 2 |
Markdown
|
KoenDJ/ST-2021-1-S1-A-H06-bezoekersaantallen-KoenDeJans-main
|
507be74132e4d1c000e1cd400708057581fb0644
|
445feb10029a2ff73ecdd425c3737cfdda71e7b6
|
refs/heads/master
|
<file_sep>import React from "react";
import styled from "styled-components";
import Lottie from "react-lottie";
import animationData from "../assets/sat.json";
import { Button, DisplayText } from "@shopify/polaris";
import { Link } from "react-router-dom";
const Home = () => {
const defaultOptions = {
loop: true,
autoplay: true,
animationData: animationData,
rendererSettings: {
preserveAspectRatio: "xMidYMid slice",
},
};
return (
<Wrapper>
<DisplayText size="extraLarge">Welcome to Spacetagram</DisplayText>
<br />
<DisplayText size="small">
View the Astronomy Picture of the Day, brought to you by NASA.
</DisplayText>
<Lottie options={defaultOptions} height={400} width={400} />
<br />
<SpaceLink to={"/space"}>
<Button primary>Explore Space</Button>
</SpaceLink>
</Wrapper>
);
};
const Wrapper = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 100vh;
position: relative;
font-size: 1.8em;
padding: 5%;
`;
const SpaceLink = styled(Link)`
text-decoration: none;
`;
export default Home;
<file_sep>import React, { useState } from "react";
import Heart from "react-animated-heart";
import styled from "styled-components";
import { TextStyle } from "@shopify/polaris";
const HeartButton = () => {
const [isPostLiked, setIsPostLiked] = useState();
const [numberOfLikes, setNumberOfLikes] = useState(99);
const handleLike = () => {
setIsPostLiked(!isPostLiked);
!isPostLiked
? setNumberOfLikes(numberOfLikes + 1)
: setNumberOfLikes(numberOfLikes - 1);
};
return (
<Wrapper>
<Heart
isClick={isPostLiked}
onClick={(() => setIsPostLiked(!isPostLiked), handleLike)}
/>
<TextStyle variation="subdued">{numberOfLikes} Likes</TextStyle>
</Wrapper>
);
};
const Wrapper = styled.div`
display: flex;
flex-direction: row;
align-items: center;
`;
export default HeartButton;
|
52fdffcc8306cbff358a87696c2f252e59c13221
|
[
"JavaScript"
] | 2 |
JavaScript
|
preetecool/spacetagram
|
8c5676adc7f385ad19c52aa2157576805abc7dab
|
950179339433e27423f93cdd064b9096aa04092b
|
refs/heads/master
|
<file_sep>from random import uniform
from time import sleep
import sys
def kms():
typing("You continue walking and out of nowhere, a bobcat jumps out at you and kills you as you have no weapon to defend yourself\n")
typing("GAME OVER\n")
startover()
def go_to_woods():
typing("You yell but nobody hears you\n")
typing("You walk outside and find you are in the middle of the woods, and there is another shack in the distance\n")
typing("Do you investigate?\n")
def typing(string, time=0.01):
for char in string:
sleep(time)
sys.stdout.write(char)
sys.stdout.flush()
def drink_water():
typing("You drink form the creek and your stomach begins to hurt, you hope it's just the lack of food\n")
typing("You continue walking and you find a water proof box on bridge that goes over the creek. In it, you find a lighter and a few granola bars\n")
typing("You eat a few granola bars and hope your stomach feels better. You are also still cold. Do you start a fire with the lighter you found?\n")
def rest_death():
typing("You start to get very cold\n")
typing("After another thirty minutes of walking, you start to get very tired so you lay down to rest for a little while\n")
typing("Because you are freezing already, the only thing that kept you alive was your body movement. You die\n")
typing("GAME OVER\n")
def find_knife():
typing("You find a bowie knife and banages\n")
typing("You begin to feel a little cold, do you cut the seats to make a makeshift coat?\n")
def walk_right():
typing("You continue walking right\n")
typing("You fall into a shallow hole and sprain your ankle\n")
typing("You can no longer continue and you freeze to death\n")
typing("GAME OVER\n")
def start():
typing("Welcome to Nathan's (probably) failed attempt at making a game\n")
typing("You awake in a room, and there's nobody around you. Do you investigate the room?\n")
def make_coat():
if (uniform(1,10)) >7.5:
typing("You have cut your hand while you were trying to cut the seat\n")
typing("You hurridly use some of the bandages that you luckily found while searching the car\n")
typing("You start to warm up\n")
typing("After an hour of walking, you begin to feel thirsty. Luckily, you see a creek up ahead.\n")
typing("Do you drink from the creek?\n")
def start_fire():
typing("You start a fire and warm up, but you notice the fire is getting too big and you try to put it out, but fail\n")
typing("You start running in order to escape the massive blaze you've started and you make it to a safe spot\n")
typing("You see a truck going down the road you are near. You walk near the edge of the road\n")
typing("Do you jump into the road so you know he'll see you, or do you yell for him to come help you?\n")
typing("Please type jump or yell\n")
def man_shoot():
typing("The man shoots you in the chest, then stabs you until you die\n")
typing("GAME OVER\n")
def refuse_ride():
typing("You refuse to get into his truck, but you head towards the town\n")
typing("You see the man drive away and you think nothing more of him\n")
typing("As you are walking towards the town, the man comes out of nowhere and stabs you. You bleed out and die\n")
typing("GAME OVER\n")
def man_see_false():
typing("The man in the truck doesn't see you in time and he hits you. You die\n")
typing("GAME OVER\n")
def die_hypo():
typing("You die from hypothermia\n")
typing("GAME OVER\n")
def no_drink():
typing("You don't drink from the creek to avoid sickness, but you pass out from dehydration and die\n")
typing("GAME OVER\n")
<file_sep>
class Heal():
def __init__(self,name,points):
self.name = name
self.points = points
Granolabar = Heal("Granola Bar", 20)
Bandages = Heal("Bandages", 10, )
Bowie = Heal("Bowie Knife", None)
<file_sep># -*- coding: utf-8 -*-
from random import uniform
import os
from combat import combat
from classes import Granolabar
from classes import Bandages
from BuffCreekcalllist import go_to_woods
from BuffCreekcalllist import drink_water
from BuffCreekcalllist import rest_death
from BuffCreekcalllist import find_knife
from BuffCreekcalllist import walk_right
from BuffCreekcalllist import make_coat
from BuffCreekcalllist import start_fire
from BuffCreekcalllist import man_shoot
from BuffCreekcalllist import refuse_ride
from BuffCreekcalllist import man_see_false
from BuffCreekcalllist import die_hypo
from BuffCreekcalllist import no_drink
from BuffCreekcalllist import typing
from BuffCreekcalllist import kms
def startover():
typing("Do you wish to retry?\n(yes/no)")
cont = input()
if cont.lower() == "yes":
game()
elif cont.lower() == "no":
exit()
else:
typing("Please enter a valid command")
input()
startover()
def game():
typing("Welcome to Buffalo Creek! A game designed by <NAME> and <NAME>\n")
typing("You awake in a room, and there's nobody around you. Do you investigate the room?\n")
answer1=input()
if answer1.lower() == "no":
go_to_woods()
answer3=input()
if answer3.lower()== "yes":
typing("You find a bottle of high proof moonshine, which can be used as an antispetic if needed and you put it in your backpack\n")
kms()
startover()
elif answer3.lower()== "no":
kms()
elif answer1.lower() == "yes":
typing("You find a beer bottle and you break it to make a shank\n")
typing("You have cut your hand and are bleeding everywhere\n")
typing("Do you sacrifice a bit of your pant leg to stop the bleeding?\n")
answer2=input()
if answer2.lower()== "yes":
typing("The bleeding has stopped and you are ok\n")
typing("You walk outside and find you are in the middle of the woods, and there is another shack in the distance\n")
typing("Do you investigate?\n")
answer3=input()
if answer3.lower()== "yes":
typing("You find a bottle of high proof moonshine, which can be used as an antispetic if needed and you put it in your backpack\n")
typing("You keep walking and out of nowhere, a bobcat jumps out at you and you manage to kill it with your makeshift beer bottle weapon\n")
typing("You eventually find a path, but it goes in two directions, do you go to the left or right?\n")
answer4=input()
if answer4.lower()== "left":
typing("You continue walking left\n")
typing("You eventually see an abandoned car\n")
typing("Do you investigate?\n")
answer5=input()
if answer5.lower()== "yes":
find_knife()
answer6=input()
if answer6.lower()== "yes":
make_coat()
answer7=input()
if answer7.lower()== "yes":
drink_water()
if (uniform(1,10)) >7.5:
typing("The water you drank was infected and you have finally succombed to dysentary\n")
typing("You die\n")
typing("GAME OVER\n")
startover()
exit()
answer8=input()
if answer8.lower()== "yes":
start_fire()
answer9=input()
if answer9.lower()== "yell":
typing("The man in the truck hears you and he stops. He then tells you of a town not too far up the road he can take you to\n")
typing("Do you enter his truck?\n")
answer10=input()
if answer10.lower()== "no":
refuse_ride()
startover()
if answer10.lower()== "yes":
typing("You get in his truck and you see him reach beside his seat\n")
typing("Do you attack him?\n")
answer11=input()
if answer11.lower()== "yes":
combat()
typing("Congratulations, YOU WIN\n")
exit()
elif answer11.lower()== "no":
man_shoot()
startover()
elif answer9.lower()== "jump":
man_see_false()
startover()
elif answer8.lower()== "no":
die_hypo()
startover()
elif answer7.lower()== "no":
no_drink()
startover()
elif answer6.lower()== "no":
rest_death()
startover()
elif answer5.lower()== "no":
typing("You continue walking\n")
typing("The bandage you made from your pant leg is getting very bloody. Do you make another?\n")
answer6=input()
if answer6.lower()== "yes":
typing("You make another bandage and your wound feels better\n")
elif answer6.lower()== "no":
typing("You keep the same bandage on and you continue\n")
elif answer4.lower()== "right":
walk_right()
startover()
elif answer3.lower()== "no":
typing("You keep walking and out of nowhere, a bobcat jumps out at you and you manage to kill it with your makeshift beer bottle weapon\n")
typing("You eventually find a path, but it goes in two directions, do you go to the left or right?\n")
answer4=input()
if answer4.lower()== "left":
typing("You continue walking left\n")
typing("You eventually see an abandoned car\n")
typing("Do you investigate?\n")
answer5=input()
if answer5.lower()== "yes":
find_knife()
answer6=input()
if answer6.lower()== "yes":
make_coat()
answer7=input()
if answer7.lower()== "yes":
drink_water()
if (uniform(1,10)) >7.5:
typing("The water you drank was infected and you have caught dysentary\n")
typing("You die\n")
typing("GAME OVER\n")
startover()
exit()
answer8=input()
if answer8.lower()== "yes":
start_fire()
answer9=input()
if answer9.lower()== "yell":
typing("The man in the truck hears you and he stops. He then tells you of a town not too far up the road he can take you to\n")
typing("Do you enter his truck?\n")
answer10=input()
if answer10.lower()== "yes":
typing("You get in his truck and you see him reach beside his seat\n")
typing("Do you attack him?\n")
answer11=input()
if answer11.lower()== "yes":
combat()
typing("Congratulations, YOU WIN\n")
exit()
elif answer11.lower()== "no":
man_shoot()
startover()
elif answer10.lower()== "no":
refuse_ride()
startover()
elif answer9.lower()== "jump":
man_see_false()
startover()
elif answer8.lower()== "no":
die_hypo()
startover()
elif answer7.lower()== "no":
no_drink()
startover()
elif answer6.lower()== "no":
rest_death()
startover()
elif answer5.lower()== "no":
typing("You continue walking\n")
typing("The bandage you made from your pant leg is getting very bloody. Do you make another?\n")
answer6=input()
if answer6.lower()== "yes":
typing("You make another bandage and your wound feels better\n")
elif answer6.lower()== "no":
typing("You keep the same bandage on and you continue\n")
elif answer4.lower()== "right":
walk_right()
startover()
elif answer2.lower()== "no":
typing("You get an infection and need to find an antiseptic quickly\n")
typing("You walk outside and find you are in the middle of the woods, and there is another shack in the distance\n")
typing("Do you investigate?\n")
answer3=input()
if answer3.lower()== "yes":
typing("You find a bottle of high proof moonshine, and use it as an antiseptic, saving your life\n")
typing("You keep walking and out of nowhere, a bobcat jumps out at you and you manage to kill it with your makeshift beer bottle weapon\n")
typing("You eventually find a path, but it goes in two directions, do you go to the left or right?\n")
answer4=input()
if answer4.lower()== "left":
typing("You continue walking left\n")
typing("You eventually see an abandoned car\n")
typing("Do you investigate?\n")
answer5=input()
if answer5.lower()== "yes":
find_knife()
answer6=input()
if answer6.lower()== "yes":
make_coat()
answer7=input()
if answer7.lower()== "yes":
drink_water()
if (uniform(1,10)) >7.5:
typing("The water you drank was infected and you have caught dysentary\n")
typing("You die\n")
typing("GAME OVER\n")
startover()
exit()
answer8=input()
if answer8.lower()== "yes":
start_fire()
answer9=input()
if answer9.lower()== "yell":
typing("The man in the truck hears you and he stops. He then tells you of a town not too far up the road he can take you to\n")
typing("Do you enter his truck?\n")
answer10=input()
if answer10.lower()== "yes":
typing("You get in his truck and you see him reach beside his seat\n")
typing("Do you attack him?\n")
answer11=input()
if answer11.lower()== "yes":
combat()
typing("Congratulations, YOU WIN\n")
exit()
elif answer11.lower()== "no":
man_shoot()
startover()
elif answer10.lower() == "no":
refuse_ride()
startover()
elif answer9.lower()== "jump":
man_see_false()
startover()
elif answer8.lower()== "no":
die_hypo()
startover()
elif answer7.lower()== "no":
no_drink()
startover()
elif answer6.lower()== "no":
rest_death()
startover()
elif answer5.lower()== "no":
typing("You continue walking\n")
typing("The bandage you made from your pant leg is getting very bloody. Do you make another?\n")
answer6=input()
if answer6.lower()== "yes":
typing("You make another bandage and your wound feels better\n")
elif answer6.lower()== "no":
typing("You keep the same bandage on and you continue\n")
elif answer4.lower()== "right":
walk_right()
startover()
elif answer3.lower()== "no":
typing("you feel terrible as the infection begins to take over your body\n")
typing("You keep walking and out of nowhere, a bobcat jumps out at you and you manage to kill it with your makeshift beer bottle weapon\n")
typing("You eventually find a path, but it goes in two directions, do you go to the left or right?\n")
answer4=input()
if answer4.lower()== "left":
typing("You continue walking left\n")
typing("You eventually see an abandoned car\n")
typing("Do you investigate?\n")
answer5=input()
if answer5.lower()== "yes":
find_knife()
answer6=input()
if answer6.lower()== "yes":
make_coat()
answer7=input()
if answer7.lower()== "yes":
typing("You drink form the creek and your stomach begins to hurt, you hope it's just the lack of food\n")
typing("You continue walking and you find a water proof box on bridge that goes over the creek. In it, you find a lighter and a few granola bars\n")
typing("You eat the granola bars and your stomach feels worse. You then succomb to influenza and you die\n")
typing("GAME OVER\n")
startover()
elif answer7.lower()== "no":
no_drink()
startover()
elif answer6.lower()== "no":
rest_death()
startover()
elif answer5.lower()== "no":
typing("You continue walking\n")
typing("The bandage you made from your pant leg is getting very bloody. Do you make another?\n")
answer6=input()
if answer6.lower()== "yes":
typing("You make another bandage and your wound feels better\n")
elif answer6.lower()== "no":
typing("You keep the same bandage on and you continue\n")
elif answer4.lower()== "right":
walk_right()
startover()
game()
<file_sep># -*- coding: utf-8 -*-
import random
import os
import time
from classes import Granolabar
from classes import Bandages
from BuffCreekcalllist import typing
count = None
granola_count = 3
bandages_count = 2
health = 100
enemyh = 100
first = True
food = None
def Ted():
global health #declaring health as a global variable so I can use it in this function
os.system("clear\n")
typing("Ted lunges himself at you ▼\n")
input()
os.system("clear\n")
thit = random.randint(1,100) #generating a random number and assigning it to a variable
if (thit < 30): #30% chance to trigger a miss
typing("Ted stumbles over and misses you ▼\n")
input()
os.system('clear') #clear terminal screen
combat()
elif (30 <= thit < 50): #20% change to trigger a critical hit
health -= 25
typing("Ted got a critical hit on you and you lost 25hp! ▼\n")
input()
combat()
elif (50 <= thit <= 100): #50% for a normal hit
health -= 15
typing("Ted hit you and you lost 15hp! ▼\n")
input()
combat()
def combat(): #main game
os.system('clear')
global first
global health
global enemyh
global food
if first == True: #detects whether the user is going through the game for the first time since running application
first = False
typing("Ted approaches you with " + str(enemyh) +"hp!\nFight, Run, Items, or Leave? ▼\n")
elif first == False:
if (health > 0) & (enemyh > 0):
typing("You have " + str(health) + "hp left!\n") #reminds user how much hp they have
typing("Ted has " + str(enemyh) + "hp left!\n") #reminds user how much hp Ted has
typing("Fight, Run, Items, or Quit ▼\n")
elif (health > 0) & (enemyh <= 0):
typing("You have successfully killed Ted!\n")
return
elif health <= 0: #detects if user has died
typing("You died!\nTry again?\n(yes/no) ▼\n\n")
answer = input()
if answer.lower() == "yes":
health = 100
enemyh = 100
food = 3
first = True
os.system("clear\n")
combat()
response = input()
if response.lower() == "fight":
hit = random.randint(1,100) #selecting a random integer between 1 and 100
os.system("clear\n")
typing("You swing your knife ▼\n")
input()
os.system("clear\n")
if (hit < 60): #60% chance for a standard hit
enemyh -= 20
typing("Ted lost 20hp! ▼\n")
input()
os.system("clear\n")
Ted()
elif (60 <= hit < 85): #25% chance for a critical hit
enemyh -= 40
typing("Critical hit! Ted lost 30hp! ▼\n")
input()
os.system("clear\n")
Ted()
elif (85 <= hit <= 100): #15% chance to miss
typing("You swing, but unfortunately Ted jumped out the the way ▼\n")
input()
os.system("clear\n")
Ted()
elif response.lower() == "run":
os.system("clear\n")
typing("You ran away ▼\n")
input()
first = True
enemyh = 100 #restarts enemy hp
os.system("clear\n")
combat()
elif response.lower() == "items": #item menu-ish
def healing(count, food):
global health
if (health == 100) & (food.name == "Granola Bar\n"): #if user has full hp, prevent user from wasting food
os.system('clear')
typing("You are not hungry ▼\n")
input()
os.system("clear\n")
items()
elif (health == 100) & (food.name == "Bandages\n"): #if user has full hp, prevent user from wasting food
os.system('clear')
typing("Your hp is full! ▼\n")
input()
os.system("clear\n")
items()
else:
count -= 1
health += food.points
if health > 100: #if user eats an apple and hp goes over 100, limit hp to 100
health = 100
os.system('clear')
typing("You now have " + str(health) + "hp! ▼\n")
input()
os.system("clear\n")
items()
elif food.name == "Granola Bar":
os.system('clear')
typing("You eat a granola bar and gained 20hp! ▼\n")
input()
os.system("clear\n")
items()
elif food.name == "Bandages":
os.system('clear')
typing("You applied a bandage and gained 10hp! ▼\n")
input()
os.system("clear\n")
items()
def items():
global food
global health
global count
os.system("clear\n")
typing("Type exit to go back into the fight! ▼\nYou have " + str(granola_count) + " granola bars and " + str(bandages_count) + " bandages! Please type heal to use items\n")
itemrsp = input()
if itemrsp.lower() == "heal":
need = input("1.Granola Bar\n2.Bandages\n(1 or 2)\n")
if need == "1":
food = Granolabar
count = granola_count
count -= 1
healing(count, food)
elif need == "2":
food = Bandages
count = bandages_count
count -= 1
healing(count, food)
else:
None
elif itemrsp.lower() == "exit": #exiting item menu
combat()
else: #if user gives invalid command
os.system("clear\n")
typing("Please enter a valid command ▼\n")
input()
items()
items()
elif response.lower() == "leave": #quit game
exit()
else:
os.system("clear\n")
typing("Please enter a valid command! ▼\n")
input()
combat()
|
a69bc14c2777d2aa053881a11b0b1cb5fcb4ecff
|
[
"Python"
] | 4 |
Python
|
warhawk7927/Buffalo_Creek
|
b7505c0c0c936ff88c14d8e9384b275dabdf757b
|
7d6bba30d75a43cf7df6494f7f8260a108804911
|
refs/heads/master
|
<repo_name>CaryAndo/CS380Project5<file_sep>/src/UdpClient.java
import java.io.*;
import java.net.Socket;
/**
* @author <NAME>
*/
public class UdpClient {
public static void main(String[] args) {
class Listener implements Runnable {
Socket socket;
public Listener(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader in = new BufferedReader(isr);
String readstring;
while (true) {
readstring = in.readLine();
if (readstring == null)
break;
System.out.println("Received: " + readstring);
}
} catch (IOException ioe) {
//ioe.printStackTrace();
}
}
}
try {
Socket socket = new Socket("172.16.31.10", 38005);
InputStream is = socket.getInputStream();
Listener listener = new Listener(socket);
Thread t = new Thread(listener);
//t.start();
// Thread.sleep(500);
sendLength(socket, 2);
int a = is.read();
int b = is.read();
int c = is.read();
int d = is.read();
System.out.println("0x" + Integer.toString(a, 16) + Integer.toString(b, 16) + Integer.toString(c, 16) + Integer.toString(d, 16));
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception e) {
// nom
}
}
/**
* Send a packet with data length
* The data is 125
*
* @param sock The socket to send the data
* @param len The number of bytes to send as data
* */
private static void sendLength(Socket sock, int len) {
byte[] send = new byte[20+len];
byte b = 4;
b = (byte) (b << 4);
b += 5;
send[0] = b; // Version 4 and 5 words
send[1] = 0; // TOS (Don't implement)
send[2] = 0; // Total length
send[3] = 22; // Total length
send[4] = 0; // Identification (Don't implement)
send[5] = 0; // Identification (Don't implement)
send[6] = (byte) 0b01000000; // Flags and first part of Fragment offset
send[7] = (byte) 0b00000000; // Fragment offset
send[8] = 50; // TTL = 50
send[9] = 0x6; // Protocol (TCP = 6)
send[10] = 0; // CHECKSUM
send[11] = 0; // CHECKSUM
send[12] = (byte) 127; // 127.0.0.1 (source address)
send[13] = (byte) 0; // 127.0.0.1 (source address)
send[14] = (byte) 0; // 127.0.0.1 (source address)
send[15] = (byte) 1; // 127.0.0.1 (source address)
send[16] = (byte) 0x2d; // 127.0.0.1 (destination address)
send[17] = (byte) 0x32; // 127.0.0.1 (destination address)
send[18] = (byte) 0x5; // 127.0.0.1 (destination address)
send[19] = (byte) 0xee; // 127.0.0.1 (destination address)
short length = (short) (22 + len - 2); // Quackulate the total length
byte right = (byte) (length & 0xff);
byte left = (byte) ((length >> 8) & 0xff);
send[2] = left;
send[3] = right;
short checksum = calculateChecksum(send); // Quackulate the checksum
byte second = (byte) (checksum & 0xff);
byte first = (byte) ((checksum >> 8) & 0xff);
send[10] = first;
send[11] = second;
for (int i = 0; i < len; i++) {
send[i+20] = (byte) 125;
}
for (byte be : send) {
System.out.println(be);
}
try {
OutputStream os = sock.getOutputStream();
os.write(send);
os.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
private static void sendHandShake(Socket sock) {
byte[] send = new byte[20+4];
byte b = 4;
b = (byte) (b << 4);
b += 5;
send[0] = b; // Version 4 and 5 words
send[1] = 0; // TOS (Don't implement)
send[2] = 0; // Total length
send[3] = 22; // Total length
send[4] = 0; // Identification (Don't implement)
send[5] = 0; // Identification (Don't implement)
send[6] = (byte) 0b01000000; // Flags and first part of Fragment offset
send[7] = (byte) 0b00000000; // Fragment offset
send[8] = 50; // TTL = 50
send[9] = 0x11; // Protocol (TCP = 6)
send[10] = 0; // CHECKSUM
send[11] = 0; // CHECKSUM
send[12] = (byte) 127; // 127.0.0.1 (source address)
send[13] = (byte) 0; // 127.0.0.1 (source address)
send[14] = (byte) 0; // 127.0.0.1 (source address)
send[15] = (byte) 1; // 127.0.0.1 (source address)
send[16] = (byte) 0x2d; // 127.0.0.1 (destination address)
send[17] = (byte) 0x32; // 127.0.0.1 (destination address)
send[18] = (byte) 0x5; // 127.0.0.1 (destination address)
send[19] = (byte) 0xee; // 127.0.0.1 (destination address)
short length = (short) (22 + 4 - 2); // Quackulate the total length
byte right = (byte) (length & 0xff);
byte left = (byte) ((length >> 8) & 0xff);
send[2] = left;
send[3] = right;
short checksum = calculateChecksum(send); // Quackulate the checksum
byte second = (byte) (checksum & 0xff);
byte first = (byte) ((checksum >> 8) & 0xff);
send[10] = first;
send[11] = second;
send[20] = (byte) 0xDE;
send[21] = (byte) 0xAD;
send[22] = (byte) 0xBE;
send[23] = (byte) 0xEF;
for (byte be : send) {
System.out.println(be);
}
try {
OutputStream os = sock.getOutputStream();
os.write(send);
os.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* Concatenate one array with another
*
* @param first First array
* @param second Second array
* */
private static byte[] concatenateByteArrays(byte[] first, byte[] second) {
int firstLength = first.length;
int secondLength = second.length;
byte[] ret = new byte[first.length + second.length];
System.arraycopy(first, 0, ret, 0, first.length);
System.arraycopy(second, 0, ret, first.length, second.length);
return ret;
}
/**
* Calculate internet checksum
*
* @param array Packet to compute the checksum
* @return The checksum
* */
public static short calculateChecksum(byte[] array) {
int length = array.length;
int i = 0;
int sum = 0;
int data;
// Count down
while (length > 1) {
data = (((array[i] << 8) & 0xFF00) | ((array[i + 1]) & 0xFF));
sum += data;
if ((sum & 0xFFFF0000) > 0) {
sum = sum & 0xFFFF;
sum += 1;
}
i = i + 2;
length = length - 2;
}
if (length > 0) {
sum += (array[i] << 8 & 0xFF00);
if ((sum & 0xFFFF0000) > 0) {
sum = sum & 0x0000FFFF;
sum += 1;
}
}
sum = ~sum;
sum = sum & 0xFFFF;
return (short) sum;
}
}
|
a4fdb01b4b83aa2f9ec56cf27264ffc0caecfc43
|
[
"Java"
] | 1 |
Java
|
CaryAndo/CS380Project5
|
0b7b421f5e83d0eec7251a6fd68736a1bd2ea5d7
|
eb95ede81deeabb6027496bf421ebc268a48925d
|
refs/heads/master
|
<repo_name>cgomes97/iframesStuff<file_sep>/script_eTransfer.js
window.onload = function (e) {
var pageTitle = document.querySelector("#PageTitle").textContent;
//Show Print Button on conclusion screen
function showPrintButton() {
var print = document.querySelectorAll(".topic");
for (var i = 0; i < print.length; i++) {
print[i].classList.add("show-topic");
}
}
//Show Success Image on Conclusion screen
function showSucessImageAndTextReceipN() {
var successImageNode = document.createElement('div');
successImageNode.setAttribute("class", "success-image");
var imageNode = document.createElement('img');
successImageNode.appendChild(imageNode);
imageNode.setAttribute("src", "/DynamicContent/Resources/Images/warning_success.png");
var successImageReferenceNode = document.querySelector('.receiptN');
successImageReferenceNode.parentNode.insertBefore(successImageNode, successImageReferenceNode);
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.receiptN');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
}
//Show Alert Image on Confirmation screen w/ Confirmation DIV
function showAlertImageWithConfirmationDiv() {
var confirmationDiv = document.querySelector('.confirmation').classList.add('transfer-confirmation');
var alertImageNode = document.createElement('div');
alertImageNode.setAttribute("class", "alert-image");
var imageNode = document.createElement('img');
alertImageNode.appendChild(imageNode);
imageNode.setAttribute("src", "/DynamicContent/Resources/Images/warning_alert.png");
var alertImageReferenceNode = document.querySelector('.confirmation');
alertImageReferenceNode.parentNode.insertBefore(alertImageNode, alertImageReferenceNode);
}
//Show Alert Image on Confirmation screen w/ Confirmation DIV
function showAlertImageWithConfirmationDivOnReceiveAndDeclineScreens() {
var confirmationDiv = document.querySelector('.instructions').classList.add('transfer-confirmation');
var alertImageNode = document.createElement('div');
alertImageNode.setAttribute("class", "alert-image");
var imageNode = document.createElement('img');
alertImageNode.appendChild(imageNode);
imageNode.setAttribute("src", "/DynamicContent/Resources/Images/warning_alert.png");
var alertImageReferenceNode = document.querySelector('.instructions');
alertImageReferenceNode.parentNode.insertBefore(alertImageNode, alertImageReferenceNode);
}
//Show Alert Image on Confirmation screen w/ Show Form DIV
function showAlertImageWithShowFormDiv() {
var confirmationDiv = document.querySelector('.showForm').classList.add('transfer-confirmation');
var alertImageNode = document.createElement('div');
alertImageNode.setAttribute("class", "alert-image");
var imageNode = document.createElement('img');
alertImageNode.appendChild(imageNode);
imageNode.setAttribute("src", "/DynamicContent/Resources/Images/warning_alert.png");
var alertImageReferenceNode = document.querySelector('.showForm');
alertImageReferenceNode.parentNode.insertBefore(alertImageNode, alertImageReferenceNode);
}
//Show Alert Image on Fullfil Confirmation screen
function showAlertImageOnFullfilConfirmationScreen() {
var confirmationDiv = document.querySelector('.rfmConfirm').classList.add('transfer-confirmation');
var alertImageNode = document.createElement('div');
alertImageNode.setAttribute("class", "alert-image");
var imageNode = document.createElement('img');
alertImageNode.appendChild(imageNode);
imageNode.setAttribute("src", "/DynamicContent/Resources/Images/warning_alert.png");
var alertImageReferenceNode = document.querySelector('.rfmConfirm');
alertImageReferenceNode.parentNode.insertBefore(alertImageNode, alertImageReferenceNode);
}
//Show Error Image on Conclusion screen
function showErrorImageOnConclusionScreen() {
var errorsImageNode = document.createElement('div');
errorsImageNode.setAttribute("class", "errors-image");
var imageNode = document.createElement('img');
errorsImageNode.appendChild(imageNode);
imageNode.setAttribute("src", "/DynamicContent/Resources/Images/warning_error.png");
var errorsImageReferenceNode = document.querySelector('.receiptN');
errorsImageReferenceNode.parentNode.insertBefore(errorsImageNode, errorsImageReferenceNode);
}
//Show Error Image
function showErrorImage() {
var errorsImageNode = document.createElement('div');
errorsImageNode.setAttribute("class", "errors-image");
var imageNode = document.createElement('img');
errorsImageNode.appendChild(imageNode);
imageNode.setAttribute("src", "/DynamicContent/Resources/Images/warning_error.png");
var errorsImageReferenceNode = document.querySelector('.errors');
errorsImageReferenceNode.parentNode.insertBefore(errorsImageNode, errorsImageReferenceNode);
}
// bottom disclaimer
if (document.querySelector('.formActions') != null && pageTitle == "Send Interac e-Transfer®") {
var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
if (screenWidth > 767) {
var bottomDisclaimerNode = document.createElement('div');
bottomDisclaimerNode.setAttribute("class", "bottom-disclaimer");
var textInsideDiv = document.createElement('div');
textInsideDiv.setAttribute("class", "disclaimer-text");
textInsideDiv.innerHTML = "<div class='title'>Things to know about INTERAC® e-Transfers:</div><ul class='disclaimer-hine-height'><li>INTERAC® e-Transfers can only be sent and received via Canadian financial institutions</li><li>INTERAC® e-Transfers sent via mobile phone can only be sent to Canadian phone numbers.</li><li>The amount and a $1.50 Service Charge will be withdrawn from your account.</br>You may cancel the transfer before the recipient accepts it; however, the service charge will not be refunded.</br>The fee will apply even if you're over the daily eTransfer limit.</li><li>INTERAC® e-Transfers can only be sent from chequing or savings accounts. In order to send an INTERAC® e-Transfer from a different product type, transfer the funds to a chequing or savings account first.</li></ul>";
bottomDisclaimerNode.appendChild(textInsideDiv);
var bottomDisclaimerReferenceNode = document.querySelector('.conclusion');
bottomDisclaimerReferenceNode.parentNode.insertBefore(bottomDisclaimerNode, bottomDisclaimerReferenceNode);
} else {
var bottomDisclaimerNode = document.createElement('div');
bottomDisclaimerNode.setAttribute("class", "bottom-disclaimer");
var textInsideDiv = document.createElement('div');
textInsideDiv.setAttribute("class", "disclaimer-text");
textInsideDiv.innerHTML = "<div class='title'>Things to know about INTERAC® e-Transfers:</div><p>INTERAC® e-Transfers can only be sent and received via Canadian financial institutions. INTERAC® e-Transfers sent via mobile phone can only be sent to Canadian phone numbers.</p><p>The amount and a $1.50 Service Charge will be withdrawn from your account. You may cancel the transfer before the recipient accepts it; however, the service charge will not be refunded. The fee will apply even if you're over the daily eTransfer limit.</p><p>INTERAC® e-Transfers can only be sent from chequing or savings accounts. In order to send an INTERAC® e-Transfer from a different product type, transfer the funds to a chequing or savings account first.</p>";
bottomDisclaimerNode.appendChild(textInsideDiv);
var bottomDisclaimerReferenceNode = document.querySelector('.conclusion');
bottomDisclaimerReferenceNode.parentNode.insertBefore(bottomDisclaimerNode, bottomDisclaimerReferenceNode);
}
}
//Add error image to input
if (document.querySelector('.errors p') != null && (document.querySelector('.errors p').textContent == "There appears to be an error! All errors must be corrected before continuing." ||
document.querySelector('.errors p').textContent == "There appears to be an error! All errors must be corrected before continuing." || document.querySelector('.errors p').textContent == "You have exceeded the maximum number of attempts to authenticate." || document.querySelector('.errors p').textContent == "Incorrect Answer. Please try again. If you enter the incorrect answer too many times you will not be able to receive this transfer.")) {
showErrorImage();
//Add class to Request money form
if (document.querySelector('.requestMoneyForm') != null) {
document.querySelector('.requestMoneyForm').classList.add('money-form-errors');
}
if (document.querySelector('.requirederror') != null && pageTitle != "CRA Account History" && pageTitle != "Search Interac e-Transfer® History") {
var requiredErrors = document.querySelectorAll('.requirederror');
for (var i = 0; i < requiredErrors.length; i++) {
var inputErrorImageNodeIDD = document.createElement('div');
inputErrorImageNodeIDD.setAttribute("class", "error-image");
requiredErrors[i].parentNode.insertBefore(inputErrorImageNodeIDD, requiredErrors[i]);
}
} else if (document.querySelector('.requirederror') != null && pageTitle == "Search Interac e-Transfer® History") {
var requiredErrors = document.querySelectorAll('.requirederror');
for (var i = 0; i < requiredErrors.length; i++) {
var inputErrorImageNodeIDD = document.createElement('div');
inputErrorImageNodeIDD.setAttribute("class", "error-image-history");
requiredErrors[i].parentNode.insertBefore(inputErrorImageNodeIDD, requiredErrors[i]);
}
}
}
//Fulfill Request screen
if (pageTitle == "Fulfill Request") {
var inputValues = document.querySelectorAll(".input");
inputValues[0].classList.add("input-in-line");
var requiredAttr = document.querySelectorAll(".required");
requiredAttr[3].classList.add("add-padd-top");
document.querySelector(".requiredTCs").classList.add("consent-in-line");
}
//Fulfill Request - Confirm screen
if (pageTitle == "Fulfill Request - Confirm") {
showAlertImageOnFullfilConfirmationScreen();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.rfmConfirm');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm the fullfil request details";
}
//Fulfill Request - Receipt screen
if (pageTitle == "Fulfill Request - Receipt") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Fullfil request completed";
showPrintButton();
var dls = document.querySelectorAll("dl");
dls[1].classList.add("no-pad-bottom");
document.querySelector(".linkN").classList.add("request-button");
}
//Receive Interac e-Transfer® screen
/*if(pageTitle == "Receive Interac e-Transfer®")
{
var requiredAttr = document.querySelectorAll(".required");
requiredAttr[0].classList.add("remove-padd-top");
requiredAttr[0].textContent = "You have answered the security question correctly, please indicate whether you would like to accept or decline this transfer";
}*/
//Receive Interac e-Transfer® - Confirm screen
if (pageTitle == "Receive Interac e-Transfer® - Confirm") {
showAlertImageWithConfirmationDivOnReceiveAndDeclineScreens();
document.querySelector('.instructions').classList.add("success-text");
document.querySelector('.instructions').classList.add("show-div");
}
//Decline Interac e-Transfer® - Receipt screen
if (pageTitle == "Decline Interac e-Transfer® - Receipt") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Transfer successfully declined";
showPrintButton();
var dls = document.querySelectorAll("dl");
dls[1].classList.add("no-pad-bottom");
document.querySelector(".linkN").classList.add("request-button");
}
//Add Recipient screen
if (pageTitle == "Add Recipient") {
if (document.querySelector("#id7") != null) {
document.querySelector("#id7").classList.add("recipient-last-field");
}
document.querySelector(".instructions").classList.add("show-instructions");
document.querySelector(".hint").classList.add("display-hint");
}
//Add Recipient - Confirm screen
if (pageTitle == "Add Recipient - Confirm") {
showAlertImageWithConfirmationDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.confirmation');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm recipient details";
}
//Add Recipient - Receipt screen
if (pageTitle == "Add Recipient - Receipt") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Recipient added successfully";
showPrintButton();
var dls = document.querySelectorAll("dl");
dls[0].classList.add("hide-dl");
dls[1].classList.add("no-pad-bottom");
document.querySelector(".linkN").classList.add("d-none");
}
//Request Money via INTERAC e-Transfer® screen
/*if(pageTitle == "Request Money via INTERAC e-Transfer®")
{
var topDisclaimerNode = document.createElement('div');
topDisclaimerNode.setAttribute("class", "top-disclaimer");
topDisclaimerNode.innerHTML ='Choose a recipient to request money from using Interac e-Transfer or go to Manage Recipients to add a new one';
var bottomDisclaimerReferenceNode = document.querySelector('.showForm');
bottomDisclaimerReferenceNode.parentNode.insertBefore(topDisclaimerNode, bottomDisclaimerReferenceNode);
}*/
//Request Money - Confirm screen
/*if(pageTitle == "Request Money - Confirm")
{
showAlertImageWithShowFormDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.showForm');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm money request details";
}*/
//Request Money - Receipt screen
/*if(pageTitle == "Request Money - Receipt")
{
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Request Status Completed";
//showPrintButton();
var link1 = document.querySelector(".link1").classList.add("show-link1");
}*/
//Resend Money Request Notice - Confirm screen
if (pageTitle == "Resend Money Request Notice - Confirm") {
showAlertImageWithShowFormDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.showForm');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm request notice details";
}
//Resend Money Request Notice - Receipt screen
if (pageTitle == "Resend Money Request Notice - Receipt") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Request resent successfully";
//showPrintButton();
}
//Resend Interac e-Transfer® Notice - Confirm screen
if (pageTitle == "Resend Interac e-Transfer® Notice - Confirm") {
showAlertImageWithConfirmationDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.confirmation');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm sent notice details";
}
//Resend Interac e-Transfer® Notice - Receipt screen
if (pageTitle == "Resend Interac e-Transfer® Notice - Receipt") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Notice resent successfully";
//showPrintButton();
}
//Cancel Money Request screen
if (pageTitle == "Cancel Money Request") {
showAlertImageWithShowFormDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.showForm');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm money request cancellation details";
document.querySelectorAll('.required')[4].classList.add('last-required');
var topDisclaimerNode = document.createElement('div');
topDisclaimerNode.setAttribute("class", "cancel-transfer-disclaimer");
topDisclaimerNode.innerHTML = 'This message will appear in the cancellation notice sent to the recipient';
var bottomDisclaimerReferenceNode = document.querySelector('.formActions');
bottomDisclaimerReferenceNode.parentNode.insertBefore(topDisclaimerNode, bottomDisclaimerReferenceNode);
}
//Cancel Money Request - Receipt screen
if (pageTitle == "Cancel Money Request - Receipt") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Transfer Status Deleted";
//showPrintButton();
}
//Edit Money Request - Receipt screen
if (pageTitle == "Edit Money Request - Receipt") {
document.querySelector(".link1").classList.add("back-to-pending-transfers");
var topics = document.querySelectorAll(".topic");
topics[0].classList.add("formActions");
for (var i = 0; i < topics.length; i++) {
topics[i].classList.add("money-request-topic");
}
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Request Status Completed";
showPrintButton();
}
//Cancel Interac e-Transfer® - Confirm screen
if (pageTitle == "Cancel Interac e-Transfer® - Confirm") {
document.querySelector("textarea").classList.add("cancel-transfer-textarea")
document.querySelector(".hint").classList.add("display-hint");
document.querySelector(".hint").classList.add("cancel-hint-padding");
showAlertImageWithConfirmationDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.confirmation');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm money sent cancellation details";
var topDisclaimerNode = document.createElement('div');
topDisclaimerNode.setAttribute("class", "cancel-transfer-disclaimer");
topDisclaimerNode.innerHTML = '<b>Note:</b> Service charge will not be refunded.';
var bottomDisclaimerReferenceNode = document.querySelector('.confirmation');
bottomDisclaimerReferenceNode.parentNode.insertBefore(topDisclaimerNode, bottomDisclaimerReferenceNode);
}
//Cancel Interac e-Transfer® - Receipt screen
if (pageTitle == "Cancel Interac e-Transfer® - Receipt") {
document.querySelector(".receipts").classList.add("cancel-transfer-conclusion");
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Transfer Status Deleted";
showPrintButton();
}
//Add success image to Success Transfer
if (pageTitle == "Send Interac e-Transfer®") {
if (document.querySelector('.errors p') == null) {
var topDisclaimerNode = document.createElement('div');
topDisclaimerNode.setAttribute("class", "top-disclaimer");
topDisclaimerNode.innerHTML = 'Choose a recipient to send money with Interac e-Transfer or go to Manage Recipients to add a new one.';
var bottomDisclaimerReferenceNode = document.querySelector('.certapaySendTransfer');
bottomDisclaimerReferenceNode.parentNode.insertBefore(topDisclaimerNode, bottomDisclaimerReferenceNode);
} else {
var firstRequired = document.querySelectorAll(".required");
var topDisclaimerNode = document.createElement('div');
topDisclaimerNode.setAttribute("class", "top-disclaimer--errors");
topDisclaimerNode.innerHTML = 'Choose a recipient to send money with Interac e-Transfer or go to Manage Recipients to add a new one.';
var bottomDisclaimerReferenceNode = firstRequired[0];
bottomDisclaimerReferenceNode.parentNode.insertBefore(topDisclaimerNode, bottomDisclaimerReferenceNode);
}
}
//Hide cancel button on mobile
if (pageTitle == "Send Interac e-Transfer®" || pageTitle == "Request Money via INTERAC e-Transfer®" || pageTitle == "Autodeposit Registration" || pageTitle == "Edit Sender Profile") {
document.querySelector('.formCancel').classList.add("hide-cancel-button");
}
//Add placeholder to date input
if (pageTitle == "Search Interac e-Transfer® History") {
var topDisclaimerNode = document.createElement('div');
topDisclaimerNode.setAttribute("class", "top-disclaimer--search-transfers");
topDisclaimerNode.innerHTML = 'Enter a date range to display you transfer history';
var bottomDisclaimerReferenceNode = document.querySelector('.instructions');
bottomDisclaimerReferenceNode.parentNode.insertBefore(topDisclaimerNode, bottomDisclaimerReferenceNode);
var selects = document.querySelectorAll('.hasDatepicker');
for (var i = 0; i < selects.length; i++) {
selects[i].placeholder = "dd/mm/yyyy";
}
}
//Add class to control on Pending Interac e-Transfer®s screen
if (pageTitle == "Pending Interac e-Transfer®s") {
var hrefs = document.querySelectorAll('a');
for (var i = 0; i < hrefs.length; i++) {
if (hrefs[hrefs.length - 1] == hrefs[i]) {
hrefs[i].innerHTML = 'Send Interac e-Transfer®';
} else {
hrefs[i].innerHTML = '';
}
}
var table = document.querySelector('.summarygroup');
table.classList.add('pending-transfers-table');
var topDisclaimerNode = document.createElement('div');
topDisclaimerNode.setAttribute("class", "top-disclaimer");
topDisclaimerNode.innerHTML = 'To remind an Interac e-Transfer® Recipient to accept the funds, click on <b>Resend Notice</b> beside the transfer. To edit a request, click on <b>Edit</b>. To cancel an Interac e-Transfer®, or receive a refund for a declined e-Transfer click on <b>Cancel</b>.';
var bottomDisclaimerReferenceNode = document.querySelector('.summarygroup');
bottomDisclaimerReferenceNode.parentNode.insertBefore(topDisclaimerNode, bottomDisclaimerReferenceNode);
}
//add class to formCancel on Edit Money Request screen
/*if(pageTitle == "Edit Money Request")
{
var formCancel = document.querySelectorAll('.formCancel');
formCancel[1].classList.add('hide-clear-button');
}*/
//Remove Delete and Edit text on Recipients screen
if (pageTitle == "Recipients") {
document.querySelector(".link1").classList.add("hiden-recipients");
document.querySelector(".link2").classList.add("hiden-recipients");
document.querySelector(".link4").classList.add("hiden-recipients");
var topic = document.querySelector('.topic');
var nav = document.querySelector('.nav');
var hrefs = document.querySelectorAll('a');
var tables = document.querySelectorAll('.summarydata');
var tdControl = document.querySelectorAll('.control');
topic.classList.add('recipient-topic');
nav.classList.add('recipient-topic');
for (var i = 0; i < tables.length; i++) {
tables[i].classList.add('recipients-table')
}
}
//Add class to Autodeposit settings screen tables
/*if(pageTitle == "Autodeposit Settings")
{
var tables = document.querySelectorAll('.registeredMembers');
tables[0].classList.add("auto-deposit-settings--first-table");
for (var i = 1; i < tables.length; i++) {
tables[i].classList.add('autodeposit-settings-table');
}
var successImageNode = document.createElement('div');
successImageNode.setAttribute("class", "success-image");
var imageNode = document.createElement('img');
successImageNode.appendChild(imageNode);
imageNode.setAttribute("src", "/DynamicContent/Resources/Images/warning_alert.png");
var successImageReferenceNode = document.querySelector('.deleteModalText');
successImageReferenceNode.parentNode.insertBefore(successImageNode, successImageReferenceNode);
}*/
//Add class to eTransfer History screen table
if (pageTitle == "Interac e-Transfer® History") {
if (document.querySelector("span") != null) {
if (document.querySelectorAll("span")[0].textContent == "You do not have any Interac e-Transfer® within this date range.") {
document.querySelector('.summarydata').classList.add('etransfer-history-table-withoutResults');
document.querySelector(".prose").classList.add("prose-w-100");
} else {
document.querySelector('.summarydata').classList.add('etransfer-history-table');
}
} else {
document.querySelector('.summarydata').classList.add('etransfer-history-table');
var showButton = document.querySelectorAll('.topic');
showButton[2].classList.add("d-block");
showButton[3].classList.add("d-block");
document.querySelector(".conclusion").classList.add("conclusion-pad-top");
}
}
//Add class to eTransfer History screen table
if (pageTitle == "Interac e-Transfer® History - Details") {
document.querySelector('.summarydata').classList.add('etransfer-history-table-details');
var showButton = document.querySelectorAll('.control');
showButton[0].classList.add("history-details-button");
document.querySelector(".conclusion").classList.add("conclusion-pad-top-details");
}
//Add class to Delete Recipient error page
if (pageTitle == "Delete Recipient - Confirm") {
if (document.querySelector('.errors p') != null) {
document.querySelector('.errors').classList.add('delete-recipient-error');
showErrorImage();
}
if (document.querySelector('#Continue') != null) {
showAlertImageWithConfirmationDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.confirmation');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm recipient details";
}
}
//Add warning image to Edit Recipient - Confirm screen
if (pageTitle == "Edit Recipient - Confirm") {
if (document.querySelector('#Continue') != null) {
showAlertImageWithConfirmationDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.confirmation');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm recipient details";
}
}
//Show security information disclaimer on Edit Recipient screen
if (pageTitle == "Edit Recipient") {
document.querySelector(".instructions").classList.add("show-instructions");
}
//Add success image to Edit Recipient - Receipt screen
if (pageTitle == "Edit Recipient - Receipt") {
//Status Completed
if (document.querySelector(".status").textContent == "Completed") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Recipient Updated Successfully";
showPrintButton();
var dls = document.querySelectorAll("dl");
dls[0].classList.add("hide-dl");
}
//Status Not Completed
if (document.querySelector(".status").textContent == "Not Completed" || document.querySelector(".status").textContent == "Not Created") {
showErrorImageOnConclusionScreen()
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.receiptN');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Recipient Not Updated";
}
}
//Add success image to Delete Recipient - Receipt screen
if (pageTitle == "Delete Recipient - Receipt") {
if (document.querySelector('.status').textContent == "Completed") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Recipient Deleted Successfully";
showPrintButton();
var dls = document.querySelectorAll("dl");
dls[0].classList.add("hide-dl");
dls[1].classList.add("no-pad-bottom");
}
}
//Add success image to Success Transfer
if (pageTitle == "Send Interac e-Transfer® - Receipt" || pageTitle == "Approve Send Interac e-Transfer® - Receipt") {
if (document.querySelector('.status').textContent == "Completed") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Transfer Status Complete";
var lastdl = document.querySelectorAll("dl");
lastdl[9].classList.add("last-dl-break");
var receipts = document.querySelector(".receipts").classList.add("edit-send-profile-receipt");
showPrintButton();
}
}
//Add confirm image to confirm transfers screen
if (pageTitle == "Send Interac e-Transfer® - Confirm") {
if (document.querySelector('.formEdit') != null) {
showAlertImageWithConfirmationDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.confirmation');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm sending money request details";
var lastValue = document.querySelectorAll(".oneColRow");
lastValue[8].classList.add("last-value-break");
}
if (document.querySelector('.errors p') != null) {
showErrorImage();
}
if (document.querySelector('.formActions') != null) {
var bottomDisclaimerNode = document.createElement('div');
bottomDisclaimerNode.setAttribute("class", "bottom-disclaimer--confirm-screen");
var textInsideDiv = document.createTextNode("Note: The amount and a $1.50 Service Charge will be withdrawn from your account. You may cancel the transfer before the recipient accepts it; however, the service charge will not be refunded. The fee will apply even if you're over the daily eTransfer limit.");
bottomDisclaimerNode.appendChild(textInsideDiv);
var bottomDisclaimerReferenceNode = document.querySelector('.conclusion');
bottomDisclaimerReferenceNode.parentNode.insertBefore(bottomDisclaimerNode, bottomDisclaimerReferenceNode);
}
}
//Add confirm image to confirm approve transfers screen
if (pageTitle == "Approve Send Interac e-Transfer® - Confirm") {
showAlertImageWithConfirmationDiv();
var inputSuccessImageNode = document.createElement('div');
inputSuccessImageNode.setAttribute("class", "success-text");
var inputErrorImageReferenceNode = document.querySelector('.confirmation');
inputErrorImageReferenceNode.parentNode.insertBefore(inputSuccessImageNode, inputErrorImageReferenceNode);
document.querySelector('.success-text').textContent = "Please confirm sending money request details";
var lastValue = document.querySelectorAll(".oneColRow");
lastValue[8].classList.add("last-value-break");
if (document.querySelector('.errors p') != null) {
showErrorImage();
}
if (document.querySelector('.formActions') != null) {
var bottomDisclaimerNode = document.createElement('div');
bottomDisclaimerNode.setAttribute("class", "bottom-disclaimer--confirm-screen");
var textInsideDiv = document.createTextNode("Note: The amount and a $1.50 Service Charge will be withdrawn from your account. You may cancel the transfer before the recipient accepts it; however, the service charge will not be refunded. The fee will apply even if you're over the daily eTransfer limit.");
bottomDisclaimerNode.appendChild(textInsideDiv);
var bottomDisclaimerReferenceNode = document.querySelector('.conclusion');
bottomDisclaimerReferenceNode.parentNode.insertBefore(bottomDisclaimerNode, bottomDisclaimerReferenceNode);
}
}
//add class to conclusion class on Create Your Sender Profile screen
if (pageTitle == "Create Your Sender Profile") {
document.querySelector(".hint").classList.add("display-hint");
document.querySelector(".conclusion").classList.add("create-profile-conclusion");
}
//add class to conclusion class on Create Your Sender Profile screen
if (pageTitle == "Create Sender Profile - Receipt") {
if (document.querySelector('.status').textContent == "Completed") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Profile Status Completed";
showPrintButton();
}
}
//display hint on Edit Sender Profile screen
if (pageTitle == "Edit Sender Profile") {
document.querySelector(".hint").classList.add("display-hint");
}
//Add success image to Edit Profile
if (pageTitle == "Edit Sender Profile - Receipt") {
if (document.querySelector('.status').textContent == "Completed") {
showSucessImageAndTextReceipN();
document.querySelector('.success-text').textContent = "Profile Status Completed";
var receipts = document.querySelector(".receipts").classList.add("edit-send-profile-receipt");
showPrintButton();
}
}
};
|
dae08f89ab04b52dbe6478f584e410241bd7f813
|
[
"JavaScript"
] | 1 |
JavaScript
|
cgomes97/iframesStuff
|
9d215fbaaf9bac9e3a6c4851506aa1bd5c6833e5
|
b4bbf05b7f398ca53302674be5b0affb9b32bebd
|
refs/heads/main
|
<repo_name>albertico/hub-profile<file_sep>/lib/hub/profile.rb
# frozen_string_literal: true
require "hub/profile/version"
require "hub/profile/cli"
<file_sep>/lib/hub/profile/util.rb
# frozen_string_literal: true
require "hub/profile/credentials"
require "hub/profile/host"
require "toml-rb"
require "safe_yaml"
module Hub
module Profile
# Class with utility/helper methods.
module Util
# Constants.
HUB_CONFIG_FILENAME = "hub"
HUB_CREDENTIALS_FILENAME = ".hub_credentials"
HUB_CMD = "hub"
HUB_VERSION_CMD = "hub version"
# Configure SafeYAML.
SafeYAML::OPTIONS[:default_mode] = :safe
# As per hub's documentation, the configuration file path is first determined by
# the HUB_CONFIG environment variable. Else, if $XDG_CONFIG_HOME is present, the
# default is $XDG_CONFIG_HOME/hub; otherwise it's $HOME/.config/hub.
def hub_config_file
if ENV["HUB_CONFIG"]
File.expand_path(ENV["HUB_CONFIG"])
elsif ENV["XDG_CONFIG_HOME"]
File.expand_path(HUB_CONFIG_FILENAME, ENV["XDG_CONFIG_HOME"])
elsif ENV["HOME"]
File.expand_path(HUB_CONFIG_FILENAME, "#{ENV['HOME']}/.config")
else
File.expand_path(HUB_CONFIG_FILENAME, "~/.config")
end
end
def parse_hub_config(hub_config)
hosts = {}
hub_config.each do |d, h|
hosts[d] = Hub::Profile::Host.new(h[0])
end
hosts
end
def load_hub_config_file(file)
# Load file.
data = YAML.load_file(file)
Hub::Profile::Util.parse_hub_config(data)
end
def dump_hub_config(hub_config)
# TODO: Validate schema.
hosts = {}
hub_config.each do |d, h|
hosts[d] = [h]
end
YAML.dump(hosts)
end
def dump_hub_config_to_file(hub_config, file)
data_yaml = Hub::Profile::Util.dump_hub_config(hub_config)
TTY::File.create_file(file, data_yaml, force: true, verbose: false)
end
# Keeping the .hub_credentials file in the same path as hub's config.
def hub_credentials_file
if ENV["HUB_CONFIG"]
hub_config_dir = File.dirname(File.expand_path(ENV["HUB_CONFIG"]))
File.expand_path(HUB_CREDENTIALS_FILENAME, hub_config_dir)
elsif ENV["XDG_CONFIG_HOME"]
File.expand_path(HUB_CREDENTIALS_FILENAME, ENV["XDG_CONFIG_HOME"])
elsif ENV["HOME"]
File.expand_path(HUB_CREDENTIALS_FILENAME, "#{ENV['HOME']}/.config")
else
File.expand_path(HUB_CREDENTIALS_FILENAME, "~/.config")
end
end
def parse_hub_credentials(hub_credentials)
profiles = {}
hub_credentials.each do |p, c|
profiles[p] = Hub::Profile::Credentials.new(c)
end
profiles
end
def load_hub_credentials_file(file)
# Load file.
data = TomlRB.load_file(file)
Hub::Profile::Util.parse_hub_credentials(data)
end
def dump_hub_credentials(hub_credentials)
# TODO: Validate schema.
profiles = {}
hub_credentials.each do |p, c|
profiles[p] = c.to_hash
end
TomlRB.dump(profiles)
end
def dump_hub_credentials_to_file(hub_credentials, file)
data_toml = Hub::Profile::Util.dump_hub_credentials(hub_credentials)
TTY::File.create_file(file, data_toml, force: true, verbose: false)
end
def host_is_contained_in_hub_credentials?(domain, host, hub_credentials)
profile = hub_credentials.select do |_, c|
c.host == domain && c.user == host.user && c.oauth_token == host.oauth_token && c.protocol == host.protocol
end
!profile.empty?
end
module_function :hub_config_file, :parse_hub_config, :load_hub_config_file,
:dump_hub_config, :dump_hub_config_to_file,
:hub_credentials_file, :parse_hub_credentials, :load_hub_credentials_file,
:dump_hub_credentials, :dump_hub_credentials_to_file,
:host_is_contained_in_hub_credentials?
end
end
end
<file_sep>/lib/hub/profile/cli.rb
# frozen_string_literal: true
require "hub/profile/cli/command"
require "dry/cli"
module Hub
module Profile
# Main module containing CLI commands.
module CLI
extend Dry::CLI::Registry
# List command.
class List < Dry::CLI::Command
include Hub::Profile::CLI::Command
desc "List profiles"
def call(*)
prompt = TTY::Prompt.new
# Load '.hub_credentials' file.
hub_credentials_file = Hub::Profile::Util.hub_credentials_file
hub_credentials = Hub::Profile::Util.load_hub_credentials_file(hub_credentials_file)
# Print profiles found in '.hub_credentials'.
print_profiles_in_hub_credentials(prompt, hub_credentials)
rescue TomlRB::ParseError, Dry::Struct::Error => e
# TomlRB::ParseError - Expected if an error occurs when parsing '.hub_credentials'.
# Dry::Struct::Error - Expected if attributes from a profile don't match the credentials schema.
print_hub_credentials_parse_error_and_exit(prompt, e)
rescue SystemCallError, IOError, TomlRB::ParseError => e
# Errno::ENOENT - Not such file or directory.
# Errno::EACCES - Permission denied.
print_error_and_exit(prompt, e)
end
end
# Version command.
class Version < Dry::CLI::Command
include Hub::Profile::CLI::Command
desc "Print version"
def call(*)
prompt = TTY::Prompt.new
print_hub_version(prompt)
print_hub_profile_version(prompt)
end
end
end
end
end
<file_sep>/lib/hub/profile/cli/command.rb
# frozen_string_literal: true
require "hub/profile/version"
require "hub/profile/util"
require "tty/file"
require "tty/which"
require "tty/command"
require "tty/prompt"
module Hub
module Profile
module CLI
# Module that contains methods to include and reuse across command instances.
module Command
def print_hub_version(prompt)
if TTY::Which.exist?(Hub::Profile::Util::HUB_CMD)
cmd = TTY::Command.new(:printer => :quiet)
cmd.run(Hub::Profile::Util::HUB_VERSION_CMD)
else
prompt.say "Error: hub command not found"
end
end
def print_hub_profile_version(prompt)
prompt.say "hub-profile version #{Hub::Profile::VERSION}"
end
def print_profiles_in_hub_credentials(prompt, hub_credentials)
hub_credentials.each_key do |p|
prompt.say p.to_s
end
end
def print_error_and_exit(prompt, exception)
prompt.say "Error: #{exception.message}"
exit 1
end
def print_hub_credentials_parse_error_and_exit(prompt, exception)
prompt.say "Error: Unable to parse hub credentials\n#{exception.message}"
exit 1
end
end
end
end
end
<file_sep>/Gemfile
# frozen_string_literal: true
source "https://rubygems.org"
# Specify your gem's dependencies in hub-profile.gemspec
gemspec
gem "rake", "~> 12.0"
gem "tty-command", github: "albertico/tty-command", branch: "release-0.10.0"
group :test do
gem "rspec", "~> 3.0"
end
<file_sep>/lib/hub/profile/credentials.rb
# frozen_string_literal: true
require "dry-struct"
module Hub
module Profile
# Credentials: Represents the credentials associated with a profile.
class Credentials < Dry::Struct
# Throw an error when unknown keys provided.
schema schema.strict
# Convert string keys to symbols.
transform_keys(&:to_sym)
# Attributes.
attribute :host, Dry.Types::String.default("github.com")
attribute :user, Dry.Types::String
attribute :oauth_token, Dry.Types::String
attribute :protocol, Dry.Types::String.default("https")
end
end
end
<file_sep>/lib/hub/profile/version.rb
# frozen_string_literal: true
module Hub
module Profile
VERSION = "0.1.0"
end
end
<file_sep>/exe/hub-profile
#!/usr/bin/env ruby
# frozen_string_literal: true
begin
require "bundler/setup"
require "hub/profile"
require "warning"
# Ignore all warnings in gem dependencies.
Gem.path.each do |path|
Warning.ignore(//, path)
end
# Register CLI commands.
Hub::Profile::CLI.register "version", Hub::Profile::CLI::Version, aliases: ["v", "-v", "--version"]
Hub::Profile::CLI.register "list", Hub::Profile::CLI::List, aliases: ["l", "-l", "--list"]
Dry::CLI.new(Hub::Profile::CLI).call
rescue SignalException
exit 1
end
|
aab15734a3caf739ba8e3cfce012232bad6453b8
|
[
"Ruby"
] | 8 |
Ruby
|
albertico/hub-profile
|
0a712e66e44826ec4f80e12fbfa8dce82451b9c0
|
7ee9e520e1ea53ea56d703b994ed5b13bc51a28c
|
refs/heads/master
|
<repo_name>PofyTeam/PofyTools<file_sep>/Data/Proficiency.cs
using System.Collections.Generic;
using UnityEngine;
namespace PofyTools
{
[System.Serializable]
public class ProficiencyDefinition : Definition
{
public ProficiencyDefinition(string id)
{
this.id = id;
}
/// <summary>
/// Level represents key-value pair collection where key is current level (index + 1) and the value is required points for next level
/// </summary>
public int[] levels = new int[0];
}
[System.Serializable]
public class ProficiencyData : DefinableData<ProficiencyDefinition>
{
#region Constructors
public ProficiencyData() { }
public ProficiencyData(ProficiencyDefinition definition) : base(definition)
{
}
#endregion
#region Serializable Data
[SerializeField] private int _currentLevelIndex;
public int CurrentLevelIndex { get { return this._currentLevelIndex; } }
[SerializeField] public int _currentPointCount;
public int CurrentPointCount => this._currentPointCount;
#endregion
#region API
/// <summary>
/// Formatted string for displaying current level (index + 1).
/// </summary>
public string DisplayLevel => (this.HasNextLevel) ? (this._currentLevelIndex + 1).ToString() : (this._currentLevelIndex + 1).ToString() + "(MAX)";
/// <summary>
/// Is next level of proficiency available
/// </summary>
public bool HasNextLevel => this.Definition.levels.Length - 1 > this._currentLevelIndex;
/// <summary>
/// Required points for next level of proficiency.
/// </summary>
public int NextLevelRequirements => this.HasNextLevel ? this.Definition.levels[this._currentLevelIndex + 1] : int.MaxValue;
public bool AddPoints(int amount = 1)
{
this._currentPointCount += amount;
Debug.Log(this.id + " current point count: " + this._currentPointCount + " current level: " + this.DisplayLevel);
return false;
}
#endregion
public void LevelUp()
{
this._currentLevelIndex++;
//this.buff += this.CurrentLevel.value;
Debug.Log("Level Up! " + this.id);
}
public void ApplyPoints()
{
while (this.HasNextLevel && this._currentPointCount >= this.NextLevelRequirements)
{
this._currentPointCount -= this.NextLevelRequirements;
LevelUp();
}
}
}
[System.Serializable]
public class ProficiencyDataSet : DefinableDataSet<ProficiencyData, ProficiencyDefinition>
{
#region Constructors
public ProficiencyDataSet() { }
public ProficiencyDataSet(DefinitionSet<ProficiencyDefinition> definitionSet) : base(definitionSet) { }
public ProficiencyDataSet(List<ProficiencyDefinition> _content) : base(_content) { }
#endregion
#region API
public void AddPoints(CategoryData.Descriptor descriptor, int amount = 1)
{
foreach (var superactegory in descriptor.supercategoryIds)
{
GetValue(superactegory).AddPoints(amount);
}
var data = GetValue(descriptor.id);
if (data != null)
{
data.AddPoints(amount);
return;
}
Debug.LogErrorFormat("Id \"{0}\" not found!", descriptor.id);
}
public void ApplyPoints()
{
foreach (var data in this._content)
{
data.ApplyPoints();
}
}
//public void CalculateBuffs(CategoryDataSet categoryDataSet)
//{
// //Calculate self buff for each data
// foreach (var data in this._content)
// {
// data.buff = 0f;
// data._inheritedBuff = 0f;
// for (int i = data.CurrentLevelIndex; i >= 0; --i)
// {
// data.buff += data.Definition.levels[i].value;
// }
// }
// //add buffs to subcategories
// foreach (var data in this._content)
// {
// foreach (var subId in categoryDataSet.GetValue(data.id).descriptor.subcategoryIds)
// {
// GetValue(subId)._inheritedBuff += data.buff;
// }
// }
//}
#endregion
}
/// <summary>
/// Generic proficiency reward solver.
/// </summary>
/// <typeparam name="TKey"></typeparam>
/// <typeparam name="TValue"></typeparam>
public class ProficiencyRewardSolver<TKey, TValue>
{
//category id
public string id;
//reward key
public TKey key;
//reward for each proficiency level
public TValue[] values;
}
}<file_sep>/UI/WorldSpaceUI/WSUIPopup.cs
using UnityEngine;
using UnityEngine.UI;
namespace PofyTools
{
public class WSUIPopup : WSUIBase//StateableActor, IPoolable<ScreenInfo>
{
public Text message;
public AnimationCurve alphaCurve;
public float speed = 1;
private float _timer = 0;
private Data _data;
#region Managable Element
public override bool UpdateElement(WSUIManager.UpdateData data)
{
this._timer -= data.deltaTime;
if (this._timer < 0)
this._timer = 0;
//float normalizedTime = this.alphaCurve.Evaluate(1 - this._timer / this.duration);
//this._canvasGroup.alpha = normalizedTime;
//this._rectTransform.localScale = normalizedTime * this._startScale;
//move up
this._rectTransform.Translate(this.speed * data.deltaTime * this._rectTransform.up, Space.Self);
base.UpdateElement(data);
if (this._timer <= 0)
return true;
return false;
}
#endregion
#region IPoolable
/// <summary>
/// Active instances are visible in the scene and updated by the manager
/// </summary>
public override void Activate()
{
if (!this.IsActive)
{
//custom
this._timer = this._data.duration;
base.Activate();
}
}
public void SetMessageData(Data data)
{
this._data = data;
this.message.text = data.message;
this.message.color = data.color;
this._data.duration = data.duration;
this._rectTransform.position = data.position;
}
#endregion
public struct Data
{
public string message;
public Vector3 position;
public float duration;
public Color color;
public Data(string message, Vector3 position, float duration, int size, Color color)
{
this.message = message;
this.position = position;
this.duration = duration;
this.color = color;
}
public void SetData(string message, Vector3 position, float duration, int size, Color color)
{
this.message = message;
this.position = position;
this.duration = duration;
this.color = color;
}
}
}
}<file_sep>/README.md
# PofyTools
Complete collection.
<file_sep>/Core/StateComponent.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
namespace PofyTools
{
public abstract class StateComponent : MonoBehaviour, IState
{
#region Stateable Actor
[SerializeField]
protected StateableActor _controlledObject;
public StateableActor ControlledObject { get { return this._controlledObject; } }
public StateableActor this[int arg]
{
get
{
return this._controlledObject;
}
}
#endregion
#region IState
[SerializeField] protected bool _hasUpdate;
public bool HasUpdate { get { return this._hasUpdate; } }
[SerializeField] protected bool _isPermanent;
public bool IsPermanent { get { return this._isPermanent; } }
[SerializeField] protected int _priority;
public int Priority { get { return this._priority; } }
[SerializeField] protected bool _ignoreStacking;
public bool RequiresReactivation { get { return this._ignoreStacking; } }
[SerializeField] protected bool _isActive;
public bool IsActive { get { return this._isActive; } }
[SerializeField] protected bool _isInitialized;
public bool IsInitialized { get { return this._isInitialized; } }
public void InitializeState(StateableActor actor)
{
this._controlledObject = actor;
InitializeState();
}
public void InitializeState()
{
this._isInitialized = true;
if (this[0] == null)
Debug.LogError(this.ToString() + " has no controlled object");
}
public void EnterState()
{
this._isActive = true;
}
public virtual bool UpdateState() { return false; }
public virtual bool FixedUpdateState() { return false; }
public virtual bool LateUpdateState() { return false; }
public virtual void Deactivate() { this._isActive = false; }
public virtual void ExitState() { this._isActive = false; }
#endregion
}
}<file_sep>/AdProviderManager/AdProviderManager.cs
#if ADS
using Extensions;
using GoogleMobileAds.Api;
using System;
using UnityEngine;
using UnityEngine.Advertisements;
namespace PofyTools
{
public delegate void AdResultDelegate(ShowResult result);
public sealed class AdProviderManager : IInitializable
{
public const string TAG = "<b>AdProviderManager: </b>";
public static AdResultDelegate onAdResult;
public enum AdProvider : int
{
Google = 1 << 0,
Unity = 1 << 1,
}
//Singleton
private static AdProviderManager _instance;
public AdProviderManager(AdProviderData data)
{
this._data = data;
if (_instance == null)
{
_instance = this;
Initialize();
}
}
public static AdProviderManager Instance
{
get
{
if (_instance == null)
{
//_instance = new AdProviderManager();
//_instance.Initialize();
Debug.LogError(TAG + "Instance not initialized!");
}
return _instance;
}
}
#region IInitializable implementation
private bool _isInitialized = false;
private AdProviderData _data;
public bool Initialize()
{
if (!this.IsInitialized)
{
//GOOGLE
if(!string.IsNullOrEmpty(this._data.googleAppId))
InitializeGoogleAds();
//UNITY ADS
if(!string.IsNullOrEmpty(this._data.unityAdsId))
Advertisement.Initialize(this._data.unityAdsId, this._data.testMode);
this._isInitialized = true;
return true;
}
return false;
}
public bool IsInitialized => this._isInitialized;
#endregion
#region Common
private AdProvider _readyRewardProviders;
private AdProvider _readyInterstitialProviders;
//private AdProvider _initializedProviders;
private bool _hasCachedResult = false;
ShowResult _cachedResult = ShowResult.Failed;
public void Check()
{
//HACK: Check Cache from main thread
if (this._hasCachedResult)
{
onAdResult?.Invoke(this._cachedResult);
this._hasCachedResult = false;
}
}
public static void AddRewardAdStartListener(VoidDelegate listenerToAdd)
{
Instance._rewardAdStarted += listenerToAdd;
}
public static void RemoveRewardAdStartListener(VoidDelegate listenerToRemove)
{
Instance._rewardAdStarted -= listenerToRemove;
}
public static void RemoveAllRewardAdStartListeners()
{
Instance._rewardAdStarted = null;
}
private VoidDelegate _rewardAdStarted = null;
public static void ShowRewardAd()
{
Instance._rewardAdStarted?.Invoke();
if (Instance._readyRewardProviders.HasFlag(AdProvider.Google) && Instance._readyRewardProviders.HasFlag(AdProvider.Unity))
{
if (Chance.FiftyFifty)
RewardBasedVideoAd.Instance.Show();
else
Advertisement.Show("rewardedVideo", Instance._rewardOptions);
}
else if (Instance._readyRewardProviders.HasFlag(AdProvider.Google))
RewardBasedVideoAd.Instance.Show();
else if (Instance._readyRewardProviders.HasFlag(AdProvider.Unity))
Advertisement.Show("rewardedVideo", Instance._rewardOptions);
}
public static void ShowInterstitial()
{
if (Instance._readyInterstitialProviders.HasFlag(AdProvider.Google))
Instance._interstitialGoogle.Show();
else if (Instance._readyInterstitialProviders.HasFlag(AdProvider.Unity))
Advertisement.Show("video", Instance._defaultOptions);
}
public static bool HasRewardVideo
{
get
{
////Unity
if (Advertisement.IsReady())
Instance._readyRewardProviders = Instance._readyRewardProviders.Add(AdProvider.Unity);
else
Instance._readyRewardProviders = Instance._readyRewardProviders.Remove(AdProvider.Unity);
//Google
if (RewardBasedVideoAd.Instance.IsLoaded())
Instance._readyRewardProviders = Instance._readyRewardProviders.Add(AdProvider.Google);
else
Instance._readyRewardProviders = Instance._readyRewardProviders.Remove(AdProvider.Google);
return Instance._readyRewardProviders != 0;
}
}
public static bool HasInterstitial
{
get
{
if (Instance._interstitialGoogle.IsLoaded())
Instance._readyInterstitialProviders = Instance._readyInterstitialProviders.Add(AdProvider.Google);
else
Instance._readyInterstitialProviders = Instance._readyInterstitialProviders.Remove(AdProvider.Google);
if (Advertisement.IsReady())
Instance._readyInterstitialProviders = Instance._readyInterstitialProviders.Add(AdProvider.Unity);
else
Instance._readyInterstitialProviders = Instance._readyInterstitialProviders.Remove(AdProvider.Unity);
return Instance._readyInterstitialProviders != 0;
}
}
private static void OnAdResult(ShowResult result)
{
Instance._cachedResult = result;
Instance._hasCachedResult = true;
}
public void Destroy()
{
this._interstitialGoogle.Destroy();
this._bannerGoogle.Destroy();
}
#endregion
#region Unity
private ShowOptions _rewardOptions = new ShowOptions
{
resultCallback = OnAdResult
};
private ShowOptions _defaultOptions = new ShowOptions();
#endregion
#region Google AdMob
public const string GOOGLE_TEST_INTERSTITIAL = "ca-app-pub-3940256099942544/1033173712";
public const string GOOGLE_TEST_BANNER = "ca-app-pub-3940256099942544/6300978111";
public const string GOOGLE_TEST_REWARD_AD = "ca-app-pub-3940256099942544/5224354917";
private void InitializeGoogleAds()
{
//GOOGLE AD SDK
#if UNITY_ANDROID
string appId = this._data.googleAppId;
#else
string appId = "unexpected_platform";
#endif
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(appId);
//REWARD AD
RewardBasedVideoAd.Instance.OnAdLoaded += HandleRewardBasedVideoLoaded;
RewardBasedVideoAd.Instance.OnAdFailedToLoad += HandleRewardBasedVideoFailedToLoad;
RewardBasedVideoAd.Instance.OnAdOpening += HandleRewardBasedVideoOpened;
RewardBasedVideoAd.Instance.OnAdStarted += HandleRewardBasedVideoStarted;
RewardBasedVideoAd.Instance.OnAdRewarded += HandleRewardBasedVideoRewarded;
RewardBasedVideoAd.Instance.OnAdClosed += HandleRewardBasedVideoClosed;
RewardBasedVideoAd.Instance.OnAdLeavingApplication += HandleRewardBasedVideoLeftApplication;
RequestGoogleRewardAd();
//Interstitial
#if UNITY_ANDROID
string interstitialAdUnitId = (this._data.testMode) ? GOOGLE_TEST_INTERSTITIAL : this._data.googleInterstitialId;
#else
string interstitialAdUnitId = "unexpected_platform";
#endif
// Initialize an InterstitialAd.
this._interstitialGoogle = new InterstitialAd(interstitialAdUnitId);
this._interstitialGoogle.OnAdLoaded += HandleOnInterstitialAdLoaded;
this._interstitialGoogle.OnAdFailedToLoad += HandleOnInterstitialAdFailedToLoad;
this._interstitialGoogle.OnAdOpening += HandleInterstitialOnAdOpened;
this._interstitialGoogle.OnAdClosed += HandleOnInterstitialAdClosed;
this._interstitialGoogle.OnAdLeavingApplication += HandleOnInterstitialAdLeavingApplication;
RequestInterstitial();
#if UNITY_ANDROID
string bannerAdUnitId = (this._data.testMode) ? GOOGLE_TEST_BANNER : this._data.googleBannerId;
#else
string bannerAdUnitId = "unexpected_platform";
#endif
this._bannerGoogle = new BannerView(bannerAdUnitId, AdSize.SmartBanner, AdPosition.Top);
this._bannerGoogle.OnAdLoaded += HandleOnBannerAdLoaded;
this._bannerGoogle.OnAdFailedToLoad += HandleOnBannerAdFailedToLoad;
this._bannerGoogle.OnAdOpening += HandleOnBannerAdOpened;
this._bannerGoogle.OnAdClosed += HandleOnBannerAdClosed;
this._bannerGoogle.OnAdLeavingApplication += HandleOnBannerAdLeavingApplication;
RequestBanner();
}
#endregion
private AdRequest BuildRequest()
{
var builder = new AdRequest.Builder();
foreach(var testDevice in this._data.googleTestDeviceIds)
{
builder.AddTestDevice(testDevice);
}
return builder.Build();
}
#region Google Reward Ad
private void RequestGoogleRewardAd()
{
#if UNITY_ANDROID
string rewardAdUnitId = (this._data.testMode) ? GOOGLE_TEST_REWARD_AD : this._data.googleRewardAdId;
#else
string rewardAdUnitId = "unexpected_platform";
#endif
RewardBasedVideoAd.Instance.LoadAd(BuildRequest(), rewardAdUnitId);
}
//LISTENERS
private ShowResult _googleAdResult;
public void HandleRewardBasedVideoLoaded(object sender, EventArgs args)
{
Debug.LogError(">>>>>>>>>> GOOGLE LOADED! <<<<<<<<<<<<<<<");
}
public void HandleRewardBasedVideoFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
Debug.LogWarning(
"HandleRewardBasedVideoFailedToLoad event received with message: "
+ args.Message);
this._googleAdResult = ShowResult.Failed;
}
public void HandleRewardBasedVideoOpened(object sender, EventArgs args)
{
Debug.LogError(">>>>>>>>>> GOOGLE OPENED! <<<<<<<<<<<<<<<");
this._googleAdResult = ShowResult.Failed;
}
public void HandleRewardBasedVideoStarted(object sender, EventArgs args)
{
Debug.LogError(">>>>>>>>>> GOOGLE STARTED! <<<<<<<<<<<<<<<");
this._googleAdResult = ShowResult.Skipped;
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
Debug.LogError(">>>>>>>>>> GOOGLE CLOSED! <<<<<<<<<<<<<<<");
//Reload Ad
RequestGoogleRewardAd();
OnAdResult(this._googleAdResult);
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
Debug.LogError(">>>>>>>>>> GOOGLE REWARDED! <<<<<<<<<<<<<<<");
this._googleAdResult = ShowResult.Finished;
}
public void HandleRewardBasedVideoLeftApplication(object sender, EventArgs args)
{
Debug.LogError(">>>>>>>>>> GOOGLE LEFT! <<<<<<<<<<<<<<<");
}
#endregion
#region Google Interstitial
InterstitialAd _interstitialGoogle = null;
private void RequestInterstitial()
{
//AdRequest request = new AdRequest.Builder()
// .AddTestDevice(GOOGLE_TEST_DEVICE_ID_0)
// .Build();
this._interstitialGoogle.LoadAd(BuildRequest());
}
public void HandleOnInterstitialAdLoaded(object sender, EventArgs args)
{
}
public void HandleOnInterstitialAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
Debug.LogWarning("HandleFailedToReceiveAd event received with message: "
+ args.Message);
}
public void HandleInterstitialOnAdOpened(object sender, EventArgs args)
{
//MonoBehaviour.print("HandleAdOpened event received");
}
public void HandleOnInterstitialAdClosed(object sender, EventArgs args)
{
//MonoBehaviour.print("HandleAdClosed event received");
RequestInterstitial();
}
public void HandleOnInterstitialAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
#endregion
#region Google Banner
private BannerView _bannerGoogle;
private void RequestBanner()
{
// Create an empty ad request.
//AdRequest request = new AdRequest.Builder()
// .AddTestDevice(GOOGLE_TEST_DEVICE_ID_0)
// .Build();
// Load the banner with the request.
this._bannerGoogle.LoadAd(BuildRequest());
}
public void HandleOnBannerAdLoaded(object sender, EventArgs args)
{
//PofyTools.UI.NotificationView.Show("Banner Loaded!", null, -1f);
}
public void HandleOnBannerAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
Debug.LogWarning("HandleFailedToReceiveAd event received with message: "
+ args.Message);
}
public void HandleOnBannerAdOpened(object sender, EventArgs args)
{
//MonoBehaviour.print("HandleAdOpened event received");
}
public void HandleOnBannerAdClosed(object sender, EventArgs args)
{
//MonoBehaviour.print("HandleAdClosed event received");
RequestBanner();
}
public void HandleOnBannerAdLeavingApplication(object sender, EventArgs args)
{
//MonoBehaviour.print("HandleAdLeavingApplication event received");
}
public static void ShowBanner()
{
if (Instance._bannerGoogle != null)
Instance._bannerGoogle.Show();
}
public static void HideBanner()
{
if (Instance._bannerGoogle != null)
Instance._bannerGoogle.Hide();
}
#endregion
}
//[System.Serializable]
//public struct AdProviderManagetData
//{
// public bool useUnityAds;
// public string unityAdsId;// = "1083748"; //FATSPACE
// public bool useGoogleAds;
// public string googleAppId;
// public string[] googleTestDeviceIds;
// public string googleInterstitialId;
// public string googleBannerId;
// public string googleRewardAdId;
// public bool testMode;
// public AdProviderManagetData(
// string UnityAdsId,
// string googleAppId = "",
// string googleBannerId = "",
// string googleInterstitialId = "",
// string googleRewardAdId = "",
// bool testMode = true,
// params string[] googleTestDeviceIds
// )
// {
// this.unityAdsId = UnityAdsId;
// this.googleAppId = googleAppId;
// this.googleBannerId = googleBannerId;
// this.googleInterstitialId = googleInterstitialId;
// this.googleRewardAdId = googleRewardAdId;
// this.testMode = testMode;
// this.googleTestDeviceIds = googleTestDeviceIds;
// this.useUnityAds = true;
// this.useGoogleAds = true;
// }
//}
}
#endif<file_sep>/UniverseGraph/Nodes/WorldNode.cs
using System;
using UnityEngine;
using XNode;
namespace Guvernal
{
[Serializable, NodeTint(0.6f, 0.8f, 0.3f)]
public class WorldNode : Node
{
public float size = 1;
public ulong endYear;
public OriginEvent originEvent;
}
[Flags]
public enum OriginEvent
{
Civilization = 1 << 0,
Magic = 1 << 1,
Technology = 1 << 2,
}
public class Faction
{
public Vector2 ethicals;
public ulong yearOfOrigin;
}
}<file_sep>/UniverseGraph/Nodes/Editor/WorldNodeEditor.cs
using XNodeEditor;
namespace Guvernal
{
[CustomNodeEditor(typeof(WorldNode))]
public class WorldNodeEditor : NodeEditor
{
public override void OnHeaderGUI()
{
base.OnHeaderGUI();
}
public override void OnBodyGUI()
{
base.OnBodyGUI();
}
}
}<file_sep>/Data/Category.cs
using Extensions;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
namespace PofyTools
{
[System.Serializable]
public class CategoryDefinition : Definition
{
public CategoryDefinition(string key)
{
this.id = key;
}
[Header("Base Categories")]
[FormerlySerializedAs("baseCategories")]
public List<string> baseIds = new List<string>();
}
[System.Obsolete ("No real extension only utility stuff. Should be removed.")]
public class CategoryDefinitionSet : DefinitionSet<CategoryDefinition>
{
public CategoryDefinitionSet(string fullPath, string filename, bool scramble = false, bool encode = false, string extension = "") : base(fullPath, filename, scramble, encode, extension)
{
}
public void Optimize()
{
for (int i = this._content.Count - 1; i >= 0; i--)
{
var element = this._content[i];
if (string.IsNullOrEmpty(element.id))
{
this._content.RemoveAt(i);
continue;
}
element.baseIds.RemoveAll(x => string.IsNullOrEmpty(x));
element.baseIds.Remove(element.id);
}
DataUtility.OptimizeDefinitions(this._content);
}
public override void Save()
{
Optimize();
base.Save();
}
}
public class CategoryData : DefinableData<CategoryDefinition>
{
public CategoryData(CategoryDefinition definition) : base(definition) { }
#region API
public void AddSubcategory(CategoryData data)
{
this._subcategories.AddOnce(data);
foreach (var cat in this._supercategories)
{
cat.AddSubcategory(data);
}
}
public void AddSupercategory(CategoryData data)
{
this._supercategories.AddOnce(data);
foreach (var cat in this._subcategories)
{
cat.AddSupercategory(data);
}
}
public bool IsCategoryOf(string category)
{
if (this.id == category)
return true;
foreach (var cat in this.descriptor.supercategoryIds)
{
if (category == cat)
{
return true;
}
}
return false;
}
#endregion
#region Runtime Data
public List<CategoryData> _subcategories = new List<CategoryData>();
public List<CategoryData> _supercategories = new List<CategoryData>();
#endregion
public Descriptor descriptor = new Descriptor();
[System.Serializable]
public class Descriptor
{
public string id;
public List<string> subcategoryIds = new List<string>();
public List<string> supercategoryIds = new List<string>();
}
}
public class CategoryDataSet : DataSet<string, CategoryData>
{
public CategoryDataSet(DefinitionSet<CategoryDefinition> categoryDefinitionSet)
{
Initialize(categoryDefinitionSet.GetContent());
}
public CategoryDataSet(List<CategoryDefinition> _content)
{
Initialize(_content);
}
/// <summary>
/// Topmost categories.
/// </summary>
public List<CategoryData> rootCategories = new List<CategoryData>();
/// <summary>
/// Bottommost categories.
/// </summary>
public List<CategoryData> leafCategory = new List<CategoryData>();
public bool Initialize(List<CategoryDefinition> categoryDefs)
{
if (!this.IsInitialized)
{
this.content = new Dictionary<string, CategoryData>(categoryDefs.Count);
foreach (var category in categoryDefs)
{
CategoryData data = new CategoryData(category);
//list
this._content.Add(data);
//dictionary
this.content[data.id] = data;
if (category.baseIds.Count == 0)
{
this.rootCategories.Add(data);
}
}
Initialize();
return true;
}
return false;
}
public override bool Initialize()
{
if (!this.IsInitialized)
{
//find subcategories
foreach (var data in this._content)
{
foreach (var baseCategory in data.Definition.baseIds)
{
CategoryData baseData;
if (this.content.TryGetValue(baseCategory, out baseData))
{
baseData.AddSubcategory(data);
}
data.AddSupercategory(baseData);
}
}
//find leafs
foreach (var data in this._content)
{
if (data._subcategories.Count == 0)
this.leafCategory.Add(data);
}
//Propagate rootcategories
foreach (var data in this.rootCategories)
{
foreach (var sub in data._subcategories)
{
sub.AddSupercategory(data);
}
}
//Propagate leafs
foreach (var data in this.leafCategory)
{
foreach (var super in data._supercategories)
{
super.AddSubcategory(data);
}
}
foreach (var data in this._content)
{
data.descriptor.id = data.id;
foreach (var sub in data._subcategories)
{
data.descriptor.subcategoryIds.Add(sub.id);
}
foreach (var sup in data._supercategories)
{
data.descriptor.supercategoryIds.Add(sup.id);
}
}
this.IsInitialized = true;
return true;
}
return false;
}
public List<CategoryData.Descriptor> GetDescriptors()
{
List<CategoryData.Descriptor> result = new List<CategoryData.Descriptor>(this._content.Count);
foreach (var data in this._content)
{
result.Add(data.descriptor);
}
return result;
}
}
public interface ICategorizable
{
CategoryData CategoryData { get; }
void Categorize(CategoryData data);
}
}<file_sep>/Data/Data.cs
namespace PofyTools
{
using Extensions;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;
[System.Serializable]
public abstract class CollectionPair<TKey, TValue> : IContentProvider<List<TValue>>, IInitializable
{
[SerializeField]
protected List<TValue> _content = new List<TValue>();
public Dictionary<TKey, TValue> content = new Dictionary<TKey, TValue>();
#region Constructors
public CollectionPair()
{
this._content = new List<TValue>();
this.content = new Dictionary<TKey, TValue>();
}
public CollectionPair(int capacity)
{
this._content = new List<TValue>(capacity: capacity);
this.content = new Dictionary<TKey, TValue>(capacity: capacity);
}
public CollectionPair(IList<TValue> values)
{
this._content = new List<TValue>(collection: values);
this.content = new Dictionary<TKey, TValue>(capacity: values.Count);
}
public CollectionPair(params TValue[] values)
{
this._content = new List<TValue>(collection: values);
this.content = new Dictionary<TKey, TValue>(capacity: values.Length);
}
public CollectionPair(IDictionary<TKey, TValue> values)
{
this._content = new List<TValue>(collection: values.Values);
this.content = new Dictionary<TKey, TValue>(values);
}
public CollectionPair(params KeyValuePair<TKey, TValue>[] values) : this(values.Length)
{
foreach (var pair in values)
{
this._content.Add(pair.Value);
this.content.Add(pair.Key, pair.Value);
}
}
#endregion
#region IInitializable
public virtual bool IsInitialized { get; protected set; }
public virtual bool Initialize()
{
if (!this.IsInitialized)
{
if (this._content.Count != 0)
{
if (BuildDictionary())
{
this.IsInitialized = true;
return true;
}
Debug.LogWarning("Failed to buid a dictionary. Aborting Collection Pair Initialization... " + typeof(TValue).ToString());
return false;
}
Debug.LogWarning("Content not available. Aborting Collection Pair Initialization... " + typeof(TValue).ToString());
return false;
}
return false;
}
#endregion
protected abstract bool BuildDictionary();
#region IContentProvider
public virtual void SetContent(List<TValue> content)
{
this._content = content;
}
public virtual List<TValue> GetContent()
{
return this._content;
}
public virtual void AddContent(TKey key, TValue value)
{
if (!this._content.Contains(value))
{
this._content.Add(value);
if (!this.content.ContainsKey(key))
this.content[key] = value;
else
{
Debug.LogWarning(ToString() + ": Duplicate key! Aborting... " + key.ToString());
}
}
else
{
Debug.LogWarning(ToString() + ": Duplicate value! Aborting... " + value.ToString());
}
}
public virtual bool RemoveContent(TKey key)
{
TValue outValue = default(TValue);
if (this.content.TryGetValue(key, out outValue))
{
this.content.Remove(key);
this._content.Remove(outValue);
return true;
}
return false;
}
public virtual bool RemoveContent(TValue value)
{
if (this._content.Remove(value))
{
TKey key = default(TKey);
bool keyFound = false;
foreach (var pair in this.content)
{
if (pair.Value.Equals(value))
{
key = pair.Key;
keyFound = true;
break;
}
}
if (keyFound)
{
this.content.Remove(key);
}
return true;
}
return false;
}
public void ClearContent()
{
this._content.Clear();
this.content.Clear();
this.IsInitialized = false;
}
#endregion
#region API
/// <summary>
/// Gets content's element via key.
/// </summary>
/// <param name="key">Element's key.</param>
/// <param name="runtime">Requires initialized set.</param>
/// <returns>Content's element.</returns>
public TValue GetValue(TKey key, bool runtime = true)
{
TValue result = default(TValue);
if (!this.IsInitialized && runtime)
{
Debug.LogWarning("Data Set Not Initialized! " + typeof(TValue).ToString());
return result;
}
if (!this.content.TryGetValue(key, out result))
Debug.LogWarning("Value Not Found For Key: " + key);
return result;
}
/// <summary>
/// Gets random element from content.
/// </summary>
/// <returns>Random element</returns>
public TValue GetRandom()
{
return this._content.GetRandom();
}
/// <summary>
/// Gets random element from content or type's default value.
/// </summary>
/// <returns>Random element</returns>
public TValue TryGetRandom()
{
return this._content.TryGetRandom();
}
/// <summary>
/// Gets random element different from the last random pick.
/// </summary>
/// <param name="lastRandomIndex">Index of previously randomly obtained element.</param>
/// <returns>Random element different from last random.</returns>
public TValue GetNextRandom(ref int lastIndex)
{
return this._content.GetNextRandom(ref lastIndex);
}
#endregion
#region IList
/// <summary>
/// Content's element count.
/// </summary>
public int Count
{
get { return this._content.Count; }
}
/// <summary>
/// Get content from List via index.
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public TValue this[int arg]
{
get
{
return this._content[arg];
}
}
public void RemoveAt(int index)
{
var element = this._content[index];
this._content.RemoveAt(index);
foreach (var pair in this.content)
{
if (pair.Value.Equals(element))
{
//TODO: Check if breaks iterator
this.content.Remove(pair.Key);
break;
}
}
}
public IEnumerator<TValue> GetEnumerator()
{
return this._content.GetEnumerator();
}
#endregion
#region IDicitionary
public List<TKey> GetKeys()
{
return new List<TKey>(this.content.Keys);
}
public void GetKeys(List<TKey> list)
{
list.Clear();
list.AddRange(this.content.Keys);
}
public virtual bool ContainsKey(TKey key)
{
if (this.IsInitialized) return this.content.ContainsKey(key);
return false;
}
public bool ContainsValue(TValue value)
{
return this.content.ContainsValue(value);
}
public bool TryGetValue(TKey key, out TValue outValue)
{
if (this.IsInitialized)return this.content.TryGetValue(key, out outValue);
outValue = default;
return default;
}
//public TValue this[TKey arg]
//{
// get
// {
// return this.content[arg];
// }
//}
#endregion
public override string ToString()
{
string result = "";
foreach (var id in this._content)
{
result += id.ToString() + "\n";
}
return result;
}
}
/// <summary>
/// Collection of keyable values obtainable via key or index.
/// </summary>
/// <typeparam name="TKey"> Key Type.</typeparam>
/// <typeparam name="TValue">Value Type.</typeparam>
[System.Serializable]
public abstract class DataSet<TKey, TValue> : CollectionPair<TKey, TValue> where TValue : IData<TKey>
{
#region CollectionPair
protected override bool BuildDictionary()
{
if (this.content == null)
this.content = new Dictionary<TKey, TValue>(this._content.Count);
else
this.content.Clear();
//Add content from list to dictionary
foreach (var element in this._content)
{
if (this.content.ContainsKey(element.Id))
Debug.LogWarning("Id \"" + element.Id + "\" present in the set. Overwriting...");
this.content[element.Id] = element;
}
return true;
}
public virtual bool AddContent(TValue data)
{
if (this._content.AddOnce(data))
{
if (this.IsInitialized)
this.content[data.Id] = data;
return true;
}
return false;
}
public override bool RemoveContent(TValue data)
{
if (this._content.Remove(data))
{
if (this.IsInitialized)
this.content[data.Id] = data;
return true;
}
return false;
}
public override bool ContainsKey(TKey key)
{
return (this.IsInitialized) ? this.content.ContainsKey(key) : this._content.Exists(x => x.Id.Equals(key));
}
#endregion
}
public interface IData<T>
{
T Id { get; }
}
public abstract class Data<T> : IData<T>
{
public T id = default(T);
public T Id => this.id;
public static implicit operator T(Data<T> data)
{
return data.id;
}
}
#region JSON Approach
public abstract class Definition : Data<string>
{
//TODO: Implement fast hash search
[System.NonSerialized]
public int hash;
public override string ToString()
{
return this.id;
}
}
public class DefinableData<T> : Data<string>, IDefinable<T> where T : Definition
{
public DefinableData() { }
public DefinableData(T definition)
{
Define(definition);
}
#region IDefinable
public T Definition
{
get;
protected set;
}
public bool IsDefined { get { return this.Definition != null; } }
public void Define(T definition)
{
this.Definition = definition;
this.id = this.Definition.id;
}
public void Undefine()
{
this.Definition = null;
this.id = string.Empty;
}
#endregion
}
/// <summary>
/// Collection of definitions obtainable via key or index
/// </summary>
/// <typeparam name="T">Definition Type</typeparam>
[System.Serializable]
public class DefinitionSet<T> : DataSet<string, T> where T : Definition
{
/// <summary>
/// Definition set file path.
/// </summary>
protected string _path;
protected string _filename;
protected string _extension;
protected bool _scrable;
protected bool _encode;
public string FullPath
{
get
{
return this._path + "/" + this._filename + "." + this._extension;
}
}
public string ResourcePath
{
get
{
return this._path + "/" + this._filename;
}
}
/// <summary>
/// Definition Set via file path
/// </summary>
/// <param name="path">Definition set file path.</param>
public DefinitionSet(string fullPath, string filename, bool scramble = false, bool encode = false, string extension = "")
{
this._path = fullPath;
this._filename = filename;
this._extension = extension;
this._encode = encode;
this._scrable = scramble;
}
#region IInitializable implementation
public override bool Initialize()
{
Load();
return base.Initialize();
}
#endregion
#region Instance Methods
public virtual void Save()
{
SaveDefinitionSet(this);
}
public virtual void Load()
{
LoadDefinitionSet(this);
this.IsInitialized = false;
}
#endregion
#region IO
public static void LoadDefinitionSet(DefinitionSet<T> definitionSet)
{
//DataUtility.LoadOverwrite(definitionSet.FullPath, definitionSet, definitionSet._scrable, definitionSet._encode);
DataUtility.ResourceLoad(definitionSet.ResourcePath, definitionSet, definitionSet._scrable, definitionSet._encode);
}
public static void SaveDefinitionSet(DefinitionSet<T> definitionSet)
{
//DataUtility.Save(definitionSet._path, definitionSet._filename, definitionSet, definitionSet._scrable, definitionSet._encode, definitionSet._extension);
DataUtility.ResourceSave(definitionSet._path, definitionSet._filename, definitionSet, definitionSet._scrable, definitionSet._encode, definitionSet._extension);
}
#endregion
}
/// <summary>
/// Collection of loaded data.
/// </summary>
/// <typeparam name="TData">Data Type</typeparam>
/// <typeparam name="TDefinition">Definition Type</typeparam>
[System.Serializable]
public class DefinableDataSet<TData, TDefinition> : DataSet<string, TData> where TDefinition : Definition where TData : DefinableData<TDefinition>, new()
{
public DefinableDataSet() { }
public DefinableDataSet(DefinitionSet<TDefinition> definitionSet)
{
Initialize(definitionSet.GetContent());
}
public DefinableDataSet(List<TDefinition> _content)
{
Initialize(_content);
}
public bool Initialize(List<TDefinition> _content)
{
foreach (var element in _content)
{
TData data = new TData();
data.Define(element);
this._content.Add(data);
}
return Initialize();
}
public void DefineSet(DefinitionSet<TDefinition> definitionSet)
{
foreach (var data in this._content)
{
data.Define(definitionSet.GetValue(data.id));
}
}
}
public interface IDefinable<T> where T : Definition
{
T Definition
{
get;
}
bool IsDefined { get; }
void Define(T definition);
void Undefine();
}
#endregion JSON Approach
#region ScriptableObject Approach
public abstract class Config : ScriptableObject, IData<string>
{
[System.NonSerialized]
public int hash;
//public string id;
public string Id => this.name;
public override string ToString()
{
return this.name;
}
}
public class ConfigSet<T> : DataSet<string, T> where T : Config
{
public ConfigSet(T[] content)
{
this._content = new List<T>(content);
}
}
public class ConfigurableData<T> : Data<string>, IConfigurable<T> where T : Config
{
public ConfigurableData() { }
public ConfigurableData(T config)
{
Configure(config);
}
#region IConfigurable
public T Config
{
get;
protected set;
}
public bool IsConfigured { get { return this.Config != null; } }
public void Configure(T definition)
{
this.Config = definition;
this.id = this.Config.Id;
}
public void Unconfigure()
{
this.Config = null;
this.id = string.Empty;
}
#endregion
}
/// <summary>
/// Collection of loaded data.
/// </summary>
/// <typeparam name="TData">Data Type</typeparam>
/// <typeparam name="TConfig">Definition Type</typeparam>
[System.Serializable]
public class ConfigurableDataSet<TData, TConfig> : DataSet<string, TData> where TConfig : Config where TData : ConfigurableData<TConfig>, new()
{
public ConfigurableDataSet() { }
public ConfigurableDataSet(ConfigSet<TConfig> configSet)
{
Initialize(configSet.GetContent());
}
public ConfigurableDataSet(List<TConfig> _content)
{
Initialize(_content);
}
public bool Initialize(List<TConfig> _content)
{
foreach (var element in _content)
{
AddData(element);
}
return Initialize();
}
public void ConfigureSet(ConfigSet<TConfig> configSet, bool extend = false)
{
//foreach (var data in this._content)
//{
// data.Configure(configSet.GetValue(data.id));
//}
TData data = null;
foreach (var config in configSet)
{
if (this.TryGetValue(config.Id, out data))
{
data.Configure(config);
}
else
{
AddData(config);
}
}
}
public bool AddData(TConfig config)
{
TData data = new TData();
data.Configure(config);
AddContent(data);
return true;
}
}
public interface IConfigurable<T> where T : Config
{
T Config { get; }
bool IsConfigured { get; }
void Configure(T config);
void Unconfigure();
}
#endregion ScriptableObject Approach
public interface IDatable<TKey, TValue> where TValue : Data<TKey>
{
TValue Data { get; }
void AppendData(TValue data);
void ReleaseData();
}
public interface IContentProvider<T>
{
void SetContent(T content);
T GetContent();
}
public static class DataUtility
{
public const string TAG = "<color=yellow><b>DataUtility: </b></color>";
#region LOAD
public enum LoadResult : int
{
NullObject = -3,
NullPath = -2,
FileNotFound = -1,
Done = 0
}
public static LoadResult LoadOverwrite(string fullPath, object objectToOverwrite, bool unscramble = false, bool decode = false)
{
if (objectToOverwrite == null)
{
Debug.LogWarningFormat("{0}Object to overwrite is NULL! Aborting... (\"{1}\")", TAG, fullPath);
return LoadResult.NullObject;
}
if (string.IsNullOrEmpty(fullPath))
{
Debug.LogWarningFormat("{0}Invalid path! Aborting...", TAG);
return LoadResult.NullPath;
}
if (!File.Exists(fullPath))
{
Debug.LogWarningFormat("{0}File \"{1}\" not found! Aborting...", TAG, fullPath);
return LoadResult.FileNotFound;
}
var json = File.ReadAllText(fullPath);
json = (unscramble) ? DataUtility.UnScramble(json) : json;
json = (decode) ? DataUtility.DecodeFrom64(json) : json;
JsonUtility.FromJsonOverwrite(json, objectToOverwrite);
Debug.LogFormat("{0}File \"{1}\" loaded successfully!", TAG, fullPath);
return LoadResult.Done;
}
public static LoadResult ResourceLoad(string relativePath, object objectToOverwrite, bool unscramble = false, bool decode = false)
{
if (objectToOverwrite == null)
{
Debug.LogWarningFormat("{0}Object to overwrite is NULL! Aborting... (\"{1}\")", TAG, relativePath);
return LoadResult.NullObject;
}
var textAsset = Resources.Load<TextAsset>(relativePath);
if (textAsset == null)
{
Debug.LogWarningFormat("{0}File \"{1}\" not found! Aborting...", TAG, relativePath);
return LoadResult.FileNotFound;
}
string json = textAsset.text;
json = (unscramble) ? DataUtility.UnScramble(json) : json;
json = (decode) ? DataUtility.DecodeFrom64(json) : json;
JsonUtility.FromJsonOverwrite(json, objectToOverwrite);
Debug.LogFormat("{0}File \"{1}\" loaded successfully!", TAG, relativePath);
return LoadResult.Done;
}
//TODO: T Load
#endregion
#region SAVE
[System.Flags]
public enum SaveResult : int
{
Done = 1 << 0,
NullObject = 1 << 1,
NullPath = 1 << 2,
DirectoryCreated = 1 << 3,
}
public static SaveResult Save(string fullPath, string filename, object objectToSave, bool scramble = false, bool encode = false, string extension = "")
{
SaveResult result = 0;
//Check input
if (objectToSave == null)
{
Debug.LogWarningFormat("{0}Object you are trying to save is NULL! Aborting... (\"{1}\")", TAG, fullPath);
result = result.Add(SaveResult.NullObject);
return result;
}
//Check Path
if (string.IsNullOrEmpty(fullPath))
{
Debug.LogWarningFormat("{0}Invalid path! Aborting...", TAG);
result = result.Add(SaveResult.NullPath);
return result;
}
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(fullPath);
result = result.Add(SaveResult.DirectoryCreated);
}
var json = JsonUtility.ToJson(objectToSave);
json = (encode) ? DataUtility.EncodeTo64(json) : json;
json = (scramble) ? DataUtility.Scramble(json) : json;
File.WriteAllText(fullPath + "/" + filename + ((string.IsNullOrEmpty(extension)) ? "" : ("." + extension)), json);
result = result.Add(SaveResult.Done);
Debug.LogFormat("{0}File \"{1}\" saved successfully!", TAG, fullPath + "/" + filename + "." + extension);
return result;
}
public static SaveResult ResourceSave(string relativePath, string filename, object objectToSave, bool scramble = false, bool encode = false, string extension = "")
{
string fullPath = Application.dataPath + "/Resources/" + relativePath;
return Save(fullPath, filename, objectToSave, scramble, encode, extension);
}
public static SaveResult PanelSave(string fullPathNameExtension, object objectToSave)
{
var json = JsonUtility.ToJson(objectToSave);
//json = (encode) ? DataUtility.EncodeTo64(json) : json;
//json = (scramble) ? DataUtility.Scramble(json) : json;
File.WriteAllText(fullPathNameExtension, json);
var result = SaveResult.Done;
Debug.LogFormat("{0}File \"{1}\" saved successfully!", TAG, fullPathNameExtension);
return result;
}
#endregion
#region SCRAMBLE
static string Scramble(string toScramble)
{
StringBuilder toScrambleSB = new StringBuilder(toScramble);
StringBuilder scrambleAddition = new StringBuilder(toScramble.Substring(0, toScramble.Length / 2 + 1));
for (int i = 0, j = 0; i < toScrambleSB.Length; i = i + 2, ++j)
{
scrambleAddition[j] = toScrambleSB[i];
toScrambleSB[i] = 'c';
}
StringBuilder finalString = new StringBuilder();
int totalLength = toScrambleSB.Length;
string length = totalLength.ToString();
finalString.Append(length);
finalString.Append("!");
finalString.Append(toScrambleSB.ToString());
finalString.Append(scrambleAddition.ToString());
return finalString.ToString();
}
static string UnScramble(string scrambled)
{
int indexOfLenghtMarker = scrambled.IndexOf("!");
string strLength = scrambled.Substring(0, indexOfLenghtMarker);
int lengthOfRealData = int.Parse(strLength);
StringBuilder toUnscramble = new StringBuilder(scrambled.Substring(indexOfLenghtMarker + 1, lengthOfRealData));
string substitution = scrambled.Substring(indexOfLenghtMarker + 1 + lengthOfRealData);
for (int i = 0, j = 0; i < toUnscramble.Length; i = i + 2, ++j)
toUnscramble[i] = substitution[j];
return toUnscramble.ToString();
}
#endregion
#region ENCODE
public static string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes = System.Text.Encoding.Unicode.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
public static string DecodeFrom64(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.Encoding.Unicode.GetString(encodedDataAsBytes);
return returnValue;
}
#endregion
#region Textures
public static void IncrementSaveToPNG(string filePath, string fileName, Texture2D texture)
{
int count = 0;
if (texture == null)
{
Debug.LogWarningFormat("{0}Texture you are trying to save is NULL! Aborting... (\"{1}\")", TAG, fileName);
return;
}
if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(fileName))
{
Debug.LogWarningFormat("{0}Invalid path! Aborting...", TAG);
return;
}
if (filePath[filePath.Length - 1] != '/' && fileName[0] != '/')
{
filePath += "/";
}
while (File.Exists(filePath + fileName + count + ".png"))
{
count++;
}
SaveToPNG(filePath + fileName + count + ".png", texture);
}
public static void SaveToPNG(string fullPath, Texture2D texture)
{
if (texture == null)
{
Debug.LogWarningFormat("{0}Texture you are trying to save is NULL! Aborting... (\"{1}\")", TAG, fullPath);
return;
}
if (string.IsNullOrEmpty(fullPath))
{
Debug.LogWarningFormat("{0}Invalid path! Aborting...", TAG);
return;
}
File.WriteAllBytes(fullPath, texture.EncodeToPNG());
}
#endregion
#region Utilities
public static List<string> OptimizeStringList(List<string> toOptimize)
{
toOptimize.Sort();
for (int i = toOptimize.Count - 1; i >= 0; --i)
{
toOptimize[i] = toOptimize[i].Trim().ToLower();
if (i < toOptimize.Count - 1)
{
var left = toOptimize[i];
var right = toOptimize[i + 1];
if (left == right)
{
toOptimize.RemoveAt(i);
}
}
}
return toOptimize;
}
public static string OptimizeString(string toOptimize)
{
return toOptimize.Trim().ToLower();
}
public static void OptimizeDefinitions<T>(List<T> definitions) where T : Definition
{
foreach (var definition in definitions)
{
definition.id = OptimizeString(definition.id);
}
definitions.Sort((x, y) => x.id.CompareTo(y.id));
}
#endregion
}
/// <summary>
/// String Float Pair.
/// </summary>
[System.Serializable]
public struct StringValue
{
[SerializeField]
private string _key;
public string Key
{
get { return this._key; }
}
public float value;
public StringValue(string key, float value)
{
this._key = key;
this.value = value;
}
public StringValue(string key)
{
this._key = key;
this.value = 0f;
}
#region Implicit Casts
public static implicit operator float(StringValue stringValue)
{
return stringValue.value;
}
public static implicit operator string(StringValue stringValue)
{
return stringValue._key;
}
#endregion
}
/// <summary>
/// String Int Pair.
/// </summary>
[System.Serializable]
public struct StringAmount
{
[SerializeField]
private string _key;
public string Key
{
get { return this._key; }
}
public int amount;
public StringAmount(string key, int amount)
{
this._key = key;
this.amount = amount;
}
public StringAmount(string key)
{
this._key = key;
this.amount = 0;
}
#region Implicit Casts
public static implicit operator int(StringAmount stringAmount)
{
return stringAmount.amount;
}
public static implicit operator string(StringAmount stringAmount)
{
return stringAmount._key;
}
#endregion
}
}<file_sep>/Core/Mono/StateableActor.cs
using System.Collections.Generic;
using UnityEngine;
namespace PofyTools
{
public abstract class StateableActor : MonoBehaviour, IStateable, ISubscribable, IInitializable, ITransformable
{
#region Variables
#if UNITY_EDITOR
private List<string> _stateList = new List<string>();
#endif
private List<IState> _stateStack;
#endregion
#region IInitializable
protected bool _isInitialized = false;
public virtual bool Initialize()
{
if (!this.IsInitialized)
{
ConstructAvailableStates();
this._stateStack = new List<IState>();
this._isInitialized = !this._hasLateInitialize;
return true;
}
return false;
}
public virtual bool IsInitialized
{
get
{
return this._isInitialized;
}
}
protected bool _hasLateInitialize = false;
public virtual bool LateInitialize()
{
if (!this.IsInitialized)
{
this._isInitialized = true;
return true;
}
return false;
}
#endregion
#region ISubscribable
protected bool _isSubscribed = false;
public virtual bool Subscribe()
{
if (!this.IsSubscribed)
{
this._isSubscribed = true;
return true;
}
return false;
}
public virtual bool Unsubscribe()
{
if (this.IsSubscribed)
{
this._isSubscribed = false;
return true;
}
return false;
}
public bool IsSubscribed
{
get
{
return this._isSubscribed;
}
}
#endregion
#region IStateable
private bool _sort = false;
public void AddState(IState state)
{
bool resetDone = false;
if (state == null)
{
if (this._stateStack.Count == 0)
{
//this.enabled = false;
Debug.LogError("<size=24> " + this.name + ": Trying to add a NULL State Object!</size>");
}
return;
}
if (this._stateStack.Contains(state))
{
//Debug.LogWarning(this.name + ": State already active! Ignoring...");
if (state.RequiresReactivation)
{
RemoveState(state);
resetDone = true;
}
else if (state.IsActive)
{
return;
}
}
state.EnterState();
if (state.HasUpdate)
{
if (!resetDone)
{
this._stateStack.Add(state);
this._sort = true;
}
}
else
state.ExitState();
}
public void RemoveState(IState state)
{
if (state == null)
{
Debug.LogError("<size=24> " + this.name + ": Trying to add a NULL State Object!</size>");
return;
}
if (!state.IsActive)
{
//Debug.LogWarningFormat("{0}: State {1} inactive!", this.name, state.GetType().ToString());
return;
}
state.Deactivate();
if (this._stateStack.Contains(state))
{
state.ExitState();
}
}
public void RemoveAllStates(bool endPermanent = false, int priority = 0)
{
int count = this._stateStack.Count;
IState state = null;
for (int i = count - 1; i >= 0; --i)
{
state = this._stateStack[i];
if (state.IsActive && (!state.IsPermanent || endPermanent))
{
if (state.Priority >= priority)
{
//this._stateStack.RemoveAt(i);
state.ExitState();
}
}
}
}
public void PurgeStateStack()
{
foreach (var state in this._stateStack)
{
state.Deactivate();
}
this._stateStack.Clear();
}
//public void SetToState(IState state)
//{
// RemoveAllStates();
// if (state != null)
// AddState(state);
//}
#endregion
#region Mono
protected virtual void Awake()
{
Initialize();
}
// Use this for initialization
protected virtual void Start()
{
LateInitialize();
Subscribe();
}
// Update is called once per frame
protected virtual void Update()
{
#if UNITY_EDITOR
this._stateList.Clear();
foreach (var logstate in this._stateStack)
{
this._stateList.Add(logstate.ToString() + ":" + logstate.IsActive);
}
#endif
IState state = null;
for (int i = this._stateStack.Count - 1; i >= 0 && i < this._stateStack.Count; --i)
{
state = this._stateStack[i];
if (state.IsActive && state.UpdateState())
{
state.ExitState();
}
}
}
protected virtual void FixedUpdate()
{
IState state = null;
for (int i = this._stateStack.Count - 1; i >= 0 && i < this._stateStack.Count; --i)
{
state = this._stateStack[i];
if (state.IsActive && state.FixedUpdateState())
{
//this._stateStack.RemoveAt(i);
state.ExitState();
}
}
}
protected virtual void LateUpdate()
{
IState state = null;
for (int i = this._stateStack.Count - 1; i >= 0 && i < this._stateStack.Count; --i)
{
state = this._stateStack[i];
if (state.IsActive && state.LateUpdateState())
{
//this._stateStack.RemoveAt(i);
state.ExitState();
}
}
RemoveInactiveStates();
}
private void RemoveInactiveStates()
{
var removal = this._stateStack.RemoveAll(x => !x.IsActive) > 0;
if (this._sort)
{
this._stateStack.Sort((x, y) => x.Priority.CompareTo(y.Priority));
this._sort = false;
}
}
protected virtual void OnDestroy()
{
PurgeStateStack();
Unsubscribe();
}
#endregion
#region States
public abstract void ConstructAvailableStates();
#endregion
#region IList
public int IndexOf(IState state)
{
return this._stateStack.IndexOf(state);
}
public IState this[int index]
{
get { return this._stateStack[index]; }
set { this._stateStack[index] = value; }
}
//public bool Contains(IState item) { return this._stateStack.Contains(item); }
//public int Count { get { return this._stateStack.Count; } }
//public IEnumerator<IState> GetEnumerator() { return this._stateStack.GetEnumerator(); }
#endregion
}
public class StateObject<T> : IState where T : IStateable
{
public T ControlledObject
{
get;
protected set;
}
public bool HasUpdate
{
get;
protected set;
}
public bool IsInitialized
{
get;
protected set;
}
public bool IsActive
{
get;
protected set;
}
public void Deactivate()
{
this.IsActive = false;
}
public bool RequiresReactivation
{
get;
protected set;
}
public bool IsPermanent
{
get;
protected set;
}
public int Priority
{
get; set;
}
#region Constructor
public StateObject()
{
}
public StateObject(T controlledObject)
{
this.ControlledObject = controlledObject;
InitializeState();
}
#endregion
#region IState implementation
public virtual void InitializeState()
{
this.IsInitialized = true;
if (this[0] == null)
{
Debug.LogError(ToString() + " has no controlled object");
}
}
public virtual void EnterState()
{
this.IsActive = true;
//this.onEnter (this);
}
public virtual bool UpdateState()
{
//return true on exit condition
return false;
}
public virtual bool FixedUpdateState()
{
//do fixed stuff
return false;
}
public virtual bool LateUpdateState()
{
//do late state
return false;
}
public virtual void ExitState()
{
this.IsActive = false;
//this.onExit (this);
}
#endregion
public T this[int arg]
{
get
{
return this.ControlledObject;
}
}
}
public class TimedStateObject<T> : StateObject<T> where T : IStateable
{
protected Range _timeRange;
protected AnimationCurve _curve;
public TimedStateObject(T controlledObject, Range timeRange, AnimationCurve curve)
{
this.ControlledObject = controlledObject;
this._timeRange = timeRange;
this._curve = curve;
InitializeState();
}
public TimedStateObject(T controlledObject, float duration, AnimationCurve curve)
: this(controlledObject, new Range(duration), curve)
{
}
public TimedStateObject(T controlledObject, float duration)
: this(controlledObject, new Range(duration), null)
{
}
public TimedStateObject(T controlledObject)
: this(controlledObject, new Range(1), null)
{
}
public virtual void InitializeState(float duration, AnimationCurve curve)
{
this.HasUpdate = true;
base.InitializeState();
}
public override void InitializeState()
{
this.HasUpdate = true;
base.InitializeState();
}
}
public class TimerStateObject<T> : StateObject<T> where T : IStateable
{
public Timer timer = null;
public TimerStateObject(T controlledObject, float timerDuration) : this(controlledObject, new Timer("timer", timerDuration))
{
}
public TimerStateObject(T controlledObject, Timer timer) : base(controlledObject)
{
this.timer = timer;
}
public override void InitializeState()
{
this.HasUpdate = true;
base.InitializeState();
}
}
#region Utility States
public class BackButtonListenerState : StateObject<IStateable>
{
public UpdateDelegate onBackButton;
public BackButtonListenerState(IStateable controlledObject)
: base(controlledObject)
{
}
public void VoidIdle()
{
}
public override void InitializeState()
{
this.onBackButton = VoidIdle;
this.HasUpdate = true;
base.InitializeState();
}
public override bool LateUpdateState()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
this.onBackButton.Invoke();
}
return false;
}
}
public class DelegateStack : StateObject<IStateable>
{
public UpdateDelegate updater;
void VoidIdle()
{
}
public DelegateStack(IStateable controlledObject)
: base(controlledObject)
{
}
public override void InitializeState()
{
this.HasUpdate = true;
this.updater = VoidIdle;
}
public override bool UpdateState()
{
this.updater();
return false;
}
}
#endregion
public interface IState
{
void InitializeState();
void EnterState();
bool UpdateState();
bool FixedUpdateState();
bool LateUpdateState();
void ExitState();
bool HasUpdate { get; }
bool IsPermanent { get; }
int Priority { get; }
bool RequiresReactivation { get; }
bool IsActive
{
get;
}
void Deactivate();
}
public interface IStateable
{
void ConstructAvailableStates();
void AddState(IState state);
void RemoveState(IState state);
void RemoveAllStates(bool endPermanent = false, int priority = 0);
void PurgeStateStack();
}
public delegate void IStateDelegate(IState state);
public abstract class BaseStateable : IStateable
{
private List<IState> _stateStack = new List<IState>();
public abstract void ConstructAvailableStates();
#region IStateable
public void AddState(IState state)
{
if (state == null)
return;
if (!this._stateStack.Contains(state))
{
state.EnterState();
if (state.HasUpdate)
{
this._stateStack.Add(state);
this._stateStack.Sort((x, y) => x.Priority.CompareTo(y.Priority));
return;
}
state.ExitState();
}
}
public void RemoveState(IState state)
{
if (this._stateStack.Remove(state))
{
state.ExitState();
}
}
public void RemoveAllStates(bool endPermanent = false, int priority = 0)
{
if (this._stateStack != null)
{
int count = this._stateStack.Count;
IState state = null;
for (int i = count - 1; i >= 0; --i)
{
state = this._stateStack[i];
if (!state.IsPermanent || endPermanent)
{
if (state.Priority >= priority)
{
this._stateStack.RemoveAt(i);
state.ExitState();
}
}
}
}
}
public void PurgeStateStack()
{
if (this._stateStack != null)
{
foreach (var state in this._stateStack)
{
state.Deactivate();
}
this._stateStack.Clear();
}
}
public void SetToState(IState state)
{
RemoveAllStates();
if (state != null)
AddState(state);
}
#endregion
#region Mono
// Update is called once per frame
public virtual void Update()
{
IState state = null;
for (int i = this._stateStack.Count - 1; i >= 0 && i < this._stateStack.Count; --i)
{
state = this._stateStack[i];
if (state.UpdateState())
{
this._stateStack.RemoveAt(i);
state.ExitState();
}
}
}
public virtual void FixedUpdate()
{
IState state = null;
for (int i = this._stateStack.Count - 1; i >= 0 && i < this._stateStack.Count; --i)
{
state = this._stateStack[i];
if (state.FixedUpdateState())
{
this._stateStack.RemoveAt(i);
state.ExitState();
}
}
}
public virtual void LateUpdate()
{
IState state = null;
for (int i = this._stateStack.Count - 1; i >= 0 && i < this._stateStack.Count; --i)
{
state = this._stateStack[i];
if (state.LateUpdateState())
{
this._stateStack.RemoveAt(i);
state.ExitState();
}
}
}
#endregion
}
}<file_sep>/Core/Cone.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace PofyTools
{
//[System.Serializable]
public struct Cone
{
//X is cone angle Y is cone height
public Vector2 Data
{
get; private set;
}
//from tip to base center
public Vector3 Direction
{
get; private set;
}
//tip world position
public Vector3 TipPosition
{
get; private set;
}
#region Constructors
public Cone(Vector3 tipPosition, Vector3 direction, Vector2 data)
{
this.TipPosition = tipPosition;
this.Direction = direction;
this.Data = data;
}
public Cone(float tipAngle = 1f, float coneHeight = 1f, Vector3 tipPosition = default(Vector3), Vector3 direction = default(Vector3))
{
this.TipPosition = tipPosition;
this.Direction = direction;
this.Data = new Vector2(tipAngle, coneHeight);
}
#endregion
#region API
/// <summary>
/// Check if the cone contains world space point.
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public bool Contains(Vector3 point)
{
if ((this.TipPosition - point).magnitude < Data.y)
{
return InfinityContains(point);
}
return false;
}
/// <summary>
/// Checks if infinity cone contains world space point. (Does not check against distance)
/// </summary>
/// <param name="point"></param>
/// <returns></returns>
public bool InfinityContains(Vector3 point)
{
Vector3 directionToPoint = point - this.TipPosition;
if (Vector3.Angle(directionToPoint, this.Direction) < this.Data.x)
{
return true;
}
return false;
}
/// <summary>
/// Set direction to the point
/// </summary>
/// <param name="point"></param>
public void LookAt(Vector3 point)
{
this.Direction = (point - this.TipPosition).normalized;
}
/// <summary>
/// Sets new direction.
/// </summary>
/// <param name="direction"></param>
public void SetDirection(Vector3 direction)
{
this.Direction = direction.normalized;
}
public void SetTipPosition(Vector3 worldPosition)
{
this.TipPosition = worldPosition;
}
public void SetAtTransform(Transform transform)
{
SetDirection(transform.forward);
SetTipPosition(transform.position);
}
public void SetHeight(float height)
{
Vector2 newData = this.Data;
newData.y = height;
this.Data = newData;
}
public void SetAngle(float angleInDegrees)
{
Vector2 newData = this.Data;
newData.x = angleInDegrees;
this.Data = newData;
}
public void SetData(float angleInDegrees, float height)
{
Vector2 newData = new Vector2(angleInDegrees, height);
this.Data = newData;
}
public void Draw(Color color)
{
Color tempColor = Gizmos.color;
Gizmos.color = color;
Gizmos.DrawWireSphere(this.TipPosition, 0.05f);
float rad = this.Data.y * Mathf.Tan(this.Data.x * Mathf.Deg2Rad);
Vector3 endPoint = this.TipPosition + (this.Direction * this.Data.y);
Gizmos.DrawLine(this.TipPosition, endPoint);
Gizmos.DrawWireSphere(endPoint, rad);
//Gizmos.DrawFrustum (this.tipPosition, this.data.x, this.data.y, 0.1f, 1f);
Gizmos.color = tempColor;
}
public Vector3 GetRandomPointInisde()
{
// Vector3 result = default (Vector3);
// float height = (Random.Range (0, this.Data.y));
// Vector3 distance = this.TipPosition + Direction * height;
// float radius = GetRadiusAtDistanceFromTip (height);
// radius = Random.Range (0, radius);
// return result;
//get base circle radius & center point
float baseCircleRadius = Mathf.Tan(this.Data.x) * this.Data.y;
Vector3 baseCircleCenter = this.TipPosition + this.Direction;
//find up & right axis, normal to a Direction (from tip to base circle center)
Vector3 baseCircleUpNormalized = Vector3.Cross(this.Direction, Vector3.up).normalized;
Vector3 baseCircleRightNormalized = Vector3.Cross(this.Direction.normalized, baseCircleUpNormalized).normalized;
//get random point inside base cirle (local pos)
Vector2 randomPointOnBaseCircleLocal = Random.insideUnitCircle * baseCircleRadius;
//find points on up & right axis, defined by local random point pos
Vector3 pointOnBaseCircleRightAxis = baseCircleRightNormalized * randomPointOnBaseCircleLocal.x;
Vector3 pointOnBaseCircleUpAxis = baseCircleUpNormalized * randomPointOnBaseCircleLocal.y;
Vector3 directionBetweenAxisPonts = pointOnBaseCircleRightAxis - pointOnBaseCircleUpAxis;
Vector3 halfPointBetweenAxisPonts = pointOnBaseCircleRightAxis + directionBetweenAxisPonts / 2f;
//get random point on base circle (global pos) & direction from tip
Vector3 randomPointOnBaseCircleGlobal = baseCircleCenter + (halfPointBetweenAxisPonts - baseCircleCenter) * 2f;
Vector3 directionToRandomPointOnBaseCircle = randomPointOnBaseCircleGlobal - this.TipPosition;
//get final random point inside cone
return this.TipPosition + directionToRandomPointOnBaseCircle * Random.Range(0f, 1f);
}
public float GetRadiusAtDistanceFromTip(float distance)
{
return distance * Mathf.Tan(this.Data.x * Mathf.Deg2Rad);
}
#endregion
}
}
<file_sep>/CategoryGraph/Nodes/Editor/CategoryNodeEditor.cs
using UnityEditor;
using XNodeEditor;
namespace PofyTools
{
[CustomNodeEditor(typeof(CategoryNode))]
public class CategoryNodeEditor : NodeEditor
{
//CategoryNode _categoryNode;
public override void OnHeaderGUI()
{
//this.target.name = ObjectNames.NicifyVariableName(this.target.GetValue(this.target.GetOutputPort("id")).ToString());
//InitiateRename();
base.OnHeaderGUI();
}
/// <summary> Called whenever the xNode editor window is updated </summary>
public override void OnBodyGUI()
{
var _categoryNode = this.target as CategoryNode;
base.OnBodyGUI();
var baseCats = _categoryNode.GetInputValues<string>("baseCategories");
foreach (string baseCat in baseCats)
{
EditorGUILayout.LabelField(baseCat);
}
//if (baseCats.Length == 0)
// EditorGUILayout.LabelField("[ROOT]");
//if (!this._categoryNode.GetOutputPort("id").IsConnected)
// EditorGUILayout.LabelField("[LEAF]");
}
//TODO 20181216: find a place to subscribe to node update delegate
void OnNodeUpdate()
{
//this.target.name = ObjectNames.NicifyVariableName(this.target.GetValue(this.target.GetOutputPort("id")).ToString());
}
}
}
<file_sep>/UI/WorldSpaceUI/WSUIFollowImage.cs
using UnityEngine;
using UnityEngine.UI;
namespace PofyTools
{
public class WSUIFollowImage : WSUIFollow
{
public Image image;
public void SetData(Sprite sprite, Transform followTarget, float size = 1f, Vector3 followOffset = default)
{
this.followTarget = followTarget;
this.followOffset = followOffset;
this.image.sprite = sprite;
this.image.rectTransform.sizeDelta = Vector2.one * size;
}
}
}<file_sep>/Sound/SoundManager.cs
namespace PofyTools
{
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// [RequireComponent(typeof(AudioListener))]
public class SoundManager : MonoBehaviour, IDictionary<string, AudioClip>
{
public const string TAG = "<color=red><b><i>SoundManager: </i></b></color>";
private static SoundManager _instance;
public static SoundManager Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<SoundManager>();
if (_instance == null)
Debug.LogError(TAG + "No instance in the scene!");
else
_instance.Initialize();
}
return _instance;
}
private set { _instance = value; }
}
[Header("Sounds")]
public AudioClip[] clips;
public int voices = 1;
private int _head = 0;
public Range volumeVariationRange = new Range(0.9f, 1), pitchVariationRange = new Range(0.95f, 1.05f);
public AudioListener audioListener { get; private set; }
private List<AudioSource> _sources;
[Header("Music")]
public AudioClip music;
public bool crossMixMusic;
public float crossMixDuration = 0.2f;
public bool duckMusicOnSound;
public float duckOnSoundTransitionDuration = 0.1f, duckOnSoundVolume = 0.2f;
private AudioSource _musicSource
{
get
{
return this._musicSources[this._musicHead];
}
}
private AudioSource[] _musicSources;
private int _musicHead = -1;
[Range(0, 1)] public float musicVolume = 1;
[Header("Master")]
[Range(0, 1)]
public float masterVolume = 1;
[Header("Resources")]
public string resourcePath = "Sound";
public bool loadFromResources = true;
private Dictionary<string, AudioClip> _dictionary;
[Header("AudioListener")]
public bool attachAudioListener;
void Awake()
{
if (_instance == null)
{
_instance = this;
Initialize();
}
else if (Instance != this)
{
Destroy(this.gameObject);
}
}
void OnDestroy()
{
StopAllCoroutines();
}
void Initialize()
{
if (this.attachAudioListener)
this.audioListener = this.gameObject.AddComponent<AudioListener>();
this._musicSources = new AudioSource[2];
this._musicSources[0] = this.gameObject.AddComponent<AudioSource>();
this._musicSources[1] = this.gameObject.AddComponent<AudioSource>();
this._musicHead = 0;
if (this.loadFromResources)
LoadResourceSounds();
LoadPrefabSounds();
DontDestroyOnLoad(this.gameObject);
}
void LoadResourceSounds()
{
AudioClip[] resourceClips = Resources.LoadAll<AudioClip>(this.resourcePath);
this._dictionary = new Dictionary<string, AudioClip>(resourceClips.Length + this.clips.Length);
foreach (var clip in resourceClips)
{
this[clip.name] = clip;
}
}
void LoadPrefabSounds()
{
if (this.music != null)
{
this._musicSource.clip = this.music;
this._musicSource.loop = true;
this._musicSource.volume = this.musicVolume * this.masterVolume;
}
if (this._dictionary == null)
this._dictionary = new Dictionary<string, AudioClip>(this.clips.Length);
this._sources = new List<AudioSource>(voices);
for (int i = 0; i < this.voices; ++i)
{
this._sources.Add(this.gameObject.AddComponent<AudioSource>());
}
for (int i = this.clips.Length - 1; i >= 0; --i)
{
this._dictionary[this.clips[i].name] = this.clips[i];
}
}
void OnApplicationFocus(bool focus)
{
if (focus)
{
ResumeAll();
}
else
{
PauseAll();
}
}
#region Play
public static AudioSource Play(string clip, float volume = 1f, float pitch = 1f, bool loop = false, bool lowPriority = false)
{
AudioClip audioClip = null;
if (Instance.TryGetValue(clip, out audioClip))
{
return PlayOnAvailableSource(audioClip, volume, pitch, loop, lowPriority);
}
Debug.LogWarning(TAG + "Sound not found - " + clip);
return null;
}
public static AudioSource Play(AudioClip clip, float volume = 1f, float pitch = 1f, bool loop = false, bool lowPriority = false)
{
return PlayOnAvailableSource(clip, volume, pitch, loop, lowPriority);
}
//plays a clip with pitch/volume variation
public static AudioSource PlayVariation(string clip, bool loop = false, bool lowPriority = true)
{
return Play(clip, Instance.volumeVariationRange.Random, Instance.pitchVariationRange.Random, loop, lowPriority);
}
//plays a clip with pitch/volume variation
public static AudioSource PlayVariation(AudioClip clip, bool loop = false, bool lowPriority = false)
{
return Play(clip, Instance.volumeVariationRange.Random, Instance.pitchVariationRange.Random, loop, lowPriority);
}
public static AudioSource PlayRandomFrom(params string[] clips)
{
return PlayVariation(clips[Random.Range(0, clips.Length)]);
}
public static AudioSource PlayRandomFrom(List<string> list)
{
return PlayVariation(list[Random.Range(0, list.Count)]);
}
public static AudioSource PlayRandomCustom(params AudioClip[] clips)
{
return PlayVariation(clips[Random.Range(0, clips.Length)]);
}
public static void PlayMusic()
{
Instance._musicSource.Play();
}
public static bool IsMusicPlaying()
{
return Instance._musicSource.isPlaying;
}
public static void PlayCustomMusic(AudioClip newMusic)
{
//set up the other music source
var source = Instance._musicSources[1 - Instance._musicHead];
source.clip = newMusic;
source.loop = true;
if (Instance.crossMixMusic)
{
source.volume = 0;
source.Play();
Instance.CrossMix(Instance.crossMixDuration);
}
else
{
if (Instance._musicSource.isPlaying)
Instance._musicSource.Stop();
source.volume = Instance.masterVolume * Instance.musicVolume;
Instance._musicHead = 1 - Instance._musicHead;
Instance._musicSource.Play();
}
}
//Plays clip that is not in manager's dictionary
private static AudioSource PlayOnAvailableSource(AudioClip clip, float volume = 1, float pitch = 1, bool loop = false, bool lowPriority = false)
{
AudioSource source = Instance._sources[Instance._head];
int startHeadPosition = Instance._head;
while (source.isPlaying)
{
Instance._head++;
if (Instance._head == Instance._sources.Count)
{
Instance._head = 0;
}
source = Instance._sources[Instance._head];
if (Instance._head == startHeadPosition)
{
if (lowPriority)
{
return null;
}
while (source.loop)
{
Instance._head++;
if (Instance._head == Instance._sources.Count)
{
Instance._head = 0;
}
source = Instance._sources[Instance._head];
Debug.Log(Instance._head);
if (Instance._head == startHeadPosition)
{
break;
}
}
break;
}
}
source.clip = clip;
source.volume = volume * Instance.masterVolume;
source.pitch = pitch;
source.loop = loop;
source.Play();
if (Instance.duckMusicOnSound)
DuckMusicOnSound(clip);
return source;
}
#endregion
#region Mute
public static void MuteAll()
{
MuteSound(true);
MuteMusic(true);
}
public static void UnMuteAll()
{
MuteSound(false);
MuteMusic(false);
}
public static void MuteSound(bool mute = true)
{
for (int i = 0, Controller_sourcesCount = Instance._sources.Count; i < Controller_sourcesCount; i++)
{
var source = Instance._sources[i];
source.mute = mute;
}
}
public static void MuteMusic(bool mute = true)
{
Instance._musicSource.mute = mute;
}
public static void PauseAll()
{
PauseMusic();
PauseSound();
}
public static void PauseMusic()
{
Instance._musicSource.Pause();
}
public static void PauseSound()
{
for (int i = 0, Controller_sourcesCount = Instance._sources.Count; i < Controller_sourcesCount; i++)
{
var source = Instance._sources[i];
source.Pause();
}
}
public static void ResumeAll()
{
ResumeMusic();
ResumeSound();
}
public static void ResumeMusic()
{
Instance._musicSource.UnPause();
}
public static void ResumeSound()
{
for (int i = 0, Controller_sourcesCount = Instance._sources.Count; i < Controller_sourcesCount; i++)
{
var source = Instance._sources[i];
source.UnPause();
}
}
public static void StopAll()
{
Instance._musicSource.Stop();
for (int i = 0, Controller_sourcesCount = Instance._sources.Count; i < Controller_sourcesCount; i++)
{
var source = Instance._sources[i];
source.Stop();
source.loop = false;
}
}
#endregion
#region Ducking
//Music Ducking
private float _musicDuckingVolume;
private float _musicDuckingTimer;
private float _musicDuckingDuration;
//Sound Ducking
private float _soundDuckingVolume;
private float _soundDuckingTimer;
private float _soundDuckingDuration;
public static bool IsMusicDucked
{
get { return !(Instance._musicSource.volume > Instance._musicDuckingVolume); }
}
public static void FadeIn(float duration)
{
DuckAll(1, duration);
}
public static void FadeOut(float duration)
{
DuckAll(0, duration);
}
public static void DuckAll(float duckToVolume = 1f, float duckingDuration = 0.5f)
{
DuckMusic(duckToVolume, duckingDuration);
DuckSound(duckToVolume, duckingDuration);
}
public static void DuckMusic(float duckToVolume = 0f, float duckingDuration = 0.5f, bool onSound = false)
{
Instance.StopCoroutine(Instance.DuckMusicState());
Instance._musicDuckingVolume = duckToVolume * Instance.musicVolume * Instance.masterVolume;
Instance._musicDuckingDuration = duckingDuration;
Instance._musicDuckingTimer = duckingDuration;
if (!onSound)
Instance.StartCoroutine(Instance.DuckMusicState());
else
Instance.StartCoroutine(Instance.DuckMusicOnSound());
}
public static void DuckSound(float duckToVolume = 0f, float duckingDuration = 0.5f)
{
Instance.StopCoroutine(Instance.DuckSoundState());
Instance._soundDuckingVolume = duckToVolume * Instance.masterVolume;
Instance._soundDuckingDuration = duckingDuration;
Instance._soundDuckingTimer = duckingDuration;
Instance.StartCoroutine(Instance.DuckSoundState());
}
IEnumerator DuckMusicOnSound()
{
yield return DuckMusicState();
yield return new WaitForSeconds(Mathf.Max(this._duckOnSoundDuration - this.duckOnSoundTransitionDuration, 0));
DuckMusic(1);
}
IEnumerator DuckMusicState()
{
while (this._musicDuckingTimer > 0)
{
this._musicDuckingTimer -= Time.unscaledDeltaTime;
if (this._musicDuckingTimer < 0)
this._musicDuckingTimer = 0;
float normalizedTime = 1 - this._musicDuckingTimer / this._musicDuckingDuration;
this._musicSource.volume = Mathf.Lerp(this._musicSource.volume, this._musicDuckingVolume, normalizedTime);
yield return null;
}
// SoundManager.IsMusicDucked = this._musicSource.volume
//Restore on sound end
}
private float _duckOnSoundDuration = 0;
private static void DuckMusicOnSound(AudioClip sound)
{
Instance.StopCoroutine(Instance.DuckMusicState());
//Debug.Log(sound.length);
Instance._duckOnSoundDuration = sound.length;
DuckMusic(Instance.duckOnSoundVolume, Instance.duckOnSoundTransitionDuration, true);
}
IEnumerator DuckSoundState()
{
while (this._soundDuckingTimer > 0)
{
this._soundDuckingTimer -= Time.unscaledDeltaTime;
if (this._soundDuckingTimer < 0)
this._soundDuckingTimer = 0;
float normalizedTime = 1 - this._soundDuckingTimer / this._soundDuckingDuration;
foreach (var source in this._sources)
{
source.volume = Mathf.Lerp(source.volume, this._soundDuckingVolume, normalizedTime);
}
yield return null;
}
}
#endregion
#region Cross-Mixing
private float _crossMixDuration, _crossMixTimer;
private AudioSource _currentMusicSource, _targetMusicSource;
private void CrossMix(float duration)
{
StopCoroutine(this.CrossMix());
this._crossMixDuration = duration;
this._crossMixTimer = duration;
this._currentMusicSource = this._musicSources[this._musicHead];
this._targetMusicSource = this._musicSources[1 - this._musicHead];
this._musicHead = 1 - this._musicHead;
StartCoroutine(this.CrossMix());
}
private IEnumerator CrossMix()
{
while (this._crossMixTimer > 0)
{
this._crossMixTimer -= Time.unscaledDeltaTime;
if (this._crossMixTimer < 0)
this._crossMixTimer = 0;
float normalizedTime = 1 - this._crossMixTimer / this._crossMixDuration;
this._currentMusicSource.volume = (1 - normalizedTime) * this.masterVolume * this.musicVolume;
this._targetMusicSource.volume = normalizedTime * this.masterVolume * this.musicVolume;
yield return null;
}
}
#endregion
#region IDictionary implementation
public bool ContainsKey(string key)
{
return this._dictionary.ContainsKey(key);
}
public void Add(string key, AudioClip value)
{
this._dictionary.Add(key, value);
}
public bool Remove(string key)
{
return this._dictionary.Remove(key);
}
public bool TryGetValue(string key, out AudioClip value)
{
return this._dictionary.TryGetValue(key, out value);
}
public AudioClip this[string index]
{
get
{
return this._dictionary[index];
}
set
{
this._dictionary[index] = value;
}
}
public ICollection<string> Keys
{
get
{
return this._dictionary.Keys;
}
}
public ICollection<AudioClip> Values
{
get
{
return this._dictionary.Values;
}
}
#endregion
#region ICollection implementation
public void Add(KeyValuePair<string, AudioClip> item)
{
throw new System.NotImplementedException();
}
public void Clear()
{
this._dictionary.Clear();
}
public bool Contains(KeyValuePair<string, AudioClip> item)
{
throw new System.NotImplementedException();
}
public void CopyTo(KeyValuePair<string, AudioClip>[] array, int arrayIndex)
{
throw new System.NotImplementedException();
}
public bool Remove(KeyValuePair<string, AudioClip> item)
{
throw new System.NotImplementedException();
}
public int Count
{
get
{
return this._dictionary.Count;
}
}
public bool IsReadOnly
{
get
{
return true;
}
}
#endregion
#region IEnumerable implementation
public IEnumerator<KeyValuePair<string, AudioClip>> GetEnumerator()
{
return this._dictionary.GetEnumerator();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator()
{
return this._dictionary.GetEnumerator();
}
#endregion
}
}<file_sep>/Data/Localization.cs
namespace PofyTools
{
using System.Collections.Generic;
using System.IO;
//using Excel;
using UnityEngine;
public static class Localization
{
#region Nested Classes
/// <summary>
/// Container class for data I/O. Contains data for all languages.
/// </summary>
[System.Serializable]
public class LocalizationData
{
public List<LanguageData> data = new List<LanguageData>();
}
/// <summary>
/// Container class for Language data serialization. It is required to use ALPHA2 language abbreviation for language key.
/// </summary>
[System.Serializable]
public class LanguageData
{
public string languageKey = "";
public List<string> keys = new List<string>();
public List<string> values = new List<string>();
}
#endregion
#region Variables
public const string TAG = "<b>Localization: </b>";
private static LocalizationData _Loaded = null;
private static Dictionary<string, LanguageData> _Languages = null;
private static Dictionary<string, string> _Strings = null;
public static Dictionary<string, string> Strings
{
get { return _Strings; }
}
private static bool _Initialized = false;
#endregion
#region API
/// <summary>
/// Initialize the static class and loads Localization Data
/// </summary>
public static void Initialize()
{
Clear();
LoadData();
_Initialized = true;
}
/// <summary>
/// Clears static variables replacing them with new objects.
/// </summary>
public static void Clear()
{
_Loaded = new LocalizationData();
_Languages = new Dictionary<string, LanguageData>();
_Strings = new Dictionary<string, string>();
_Initialized = false;
Debug.Log(TAG + "Data Cleared!");
}
/// <summary>
/// Loads the localization data and populates the _Languages dictionary.
/// </summary>
private static void LoadData()
{
var _data = Resources.Load<TextAsset>("Definitions/localization_data");
if (_data != null)
{
JsonUtility.FromJsonOverwrite(_data.text, _Loaded);
_Languages.Clear();
foreach (var langData in _Loaded.data)
{
_Languages[langData.languageKey] = langData;
}
Debug.Log(TAG + "Data Loaded!");
}
else
{
Debug.LogError(TAG + "Data File Not Found!");
}
}
/// <summary>
/// Saves the data to JSON.
/// </summary>
public static void SaveData()
{
if (_Loaded != null)
{
var json = JsonUtility.ToJson(_Loaded, false);
File.WriteAllText("Assets/Resources/Definitions/localization_data.json", json);//C:\svn\
}
else
{
Debug.LogError(TAG + "Saving Localization Data to json failed!");
}
Debug.Log(TAG + "Data Saved!");
}
/// <summary>
/// Sets the language. Populates the _Strings dictionary.
/// </summary>
/// <param name="languageKey">Language key - MUST be ALPHA2 language abbreviation.</param>
public static LanguageData SetLanguage(string languageKey)
{
languageKey = languageKey.ToUpper();
LanguageData data = null;
if (string.IsNullOrEmpty(languageKey) || languageKey.Length != 2)
{
Debug.LogError(TAG + "Language key - " + languageKey + " not valid. Language not set!");
return data;
}
if (_Languages != null)
{
if (_Languages.TryGetValue(languageKey, out data))
{
_Strings.Clear();
for (int i = 0; i < data.keys.Count; i++)
{
var key = data.keys[i];
if (!_Strings.ContainsKey(key))
_Strings[key] = data.values[i];
else
Debug.LogError(TAG + "Key already added - " + key);
}
if (LanguageChanged != null)
LanguageChanged();
}
else
{
Debug.LogError(TAG + "No Language " + languageKey + " found.");
}
}
else
{
Debug.LogError(TAG + "LocalizationData not loaded");
}
return data;
}
/// <summary>
/// Returns localized string if available or just returns the key.
/// </summary>
/// <param name="key">Key.</param>
public static string Get(string key)
{
string cache = key;
_Strings.TryGetValue(key, out cache);
return cache;
}
/// <summary>
/// Returns localized string and replaces numeric string codes with provided arguments.
/// Numeric string codes start with [1].
/// </summary>
/// <param name="key">Key.</param>
/// <param name="args">Arguments to replace numeric string code with.</param>
public static string Get(string key, params string[] args)
{
string value = Get(key);
if (args != null && args.Length != 0)
{
for (int i = 0; i < args.Length; ++i)
{
value = value.Replace("[" + (i + 1).ToString() + "]", args[i]);
}
}
return value;
}
/// <summary>
/// Gets the Array of all defined Language Data.
/// </summary>
/// <returns> Array of ALPHA2 languages.</returns>
public static string[] GetLanguages()
{
return new List<string>(_Languages.Keys).ToArray();
}
public static LanguageData AddLanguage(string languageKey)
{
LanguageData data = null;
if (_Languages.TryGetValue(languageKey, out data))
{
Debug.LogWarning(TAG + "Language \"" + languageKey + "\" already defined.");
return data;
}
data = new LanguageData();
data.languageKey = languageKey;
if (_Loaded.data.Count > 0)
{
data.keys = new List<string>(_Loaded.data[0].keys);
data.values.Clear();
foreach (var key in data.keys)
{
data.values.Add("");
}
}
_Loaded.data.Add(data);
return data;
}
/// <summary>
/// Gets the List of language data.
/// </summary>
/// <returns>The data.</returns>
public static List<LanguageData> GetData()
{
if (_Loaded == null)
LoadData();
return _Loaded.data;
}
/// <summary>
/// Adds the key/value pair to all language data.
/// </summary>
/// <param name="key">Key.</param>
public static void AddPair(string key)
{
var allData = GetData();
foreach (var _data in allData)
{
_data.keys.Add(key);
_data.values.Add("");
}
}
/// <summary>
/// Removes the pair at index from all languages.
/// </summary>
/// <param name="index">Index.</param>
public static void RemovePairAt(int index)
{
var data = Localization.GetData();
if (data.Count != 0 && data[0].keys.Count > index)
{
foreach (var _data in data)
{
_data.keys.RemoveAt(index);
_data.values.RemoveAt(index);
}
}
}
/// <summary>
/// Removes the pair.
/// </summary>
/// <returns><c>true</c>, if pair was removed, <c>false</c> otherwise.</returns>
/// <param name="key">Key.</param>
public static bool RemovePair(string key)
{
var data = Localization.GetData();
int index = -1;
index = data[0].keys.IndexOf(key);
if (index != -1)
{
RemovePairAt(index);
return true;
}
return false;
}
/// <summary>
/// Removes the language data with provided Language Key.
/// </summary>
/// <returns><c>true</c>, if language data was removed, <c>false</c> otherwise.</returns>
/// <param name="languageKey">Language Key (ALPHA2).</param>
public static bool RemoveLanguageData(string languageKey)
{
LanguageData data = null;
if (_Languages.TryGetValue(languageKey, out data))
{
_Languages.Remove(languageKey);
return RemoveLanguageData(data);
}
return false;
}
/// <summary>
/// Removes the language data.
/// </summary>
/// <returns><c>true</c>, if language data was removed, <c>false</c> otherwise.</returns>
/// <param name="data">Data.</param>
public static bool RemoveLanguageData(LanguageData data)
{
if (_Loaded.data.Remove(data))
{
if (_Languages != null)
_Languages.Remove(data.languageKey);
return true;
}
return false;
}
/// <summary>
/// Determines if has key the specified key.
/// </summary>
/// <returns><c>true</c> if has key the specified key; otherwise, <c>false</c>.</returns>
/// <param name="key">Key.</param>
public static bool HasKey(string key)
{
var allData = GetData();
if (allData.Count > 0)
return allData[0].keys.Contains(key);
return false;
}
/// <summary>
/// Checks if Language Data is define for provided Languge Key (ALPHA2)
/// </summary>
/// <returns><c>true</c> if has language the specified languageKey; otherwise, <c>false</c>.</returns>
/// <param name="languageKey">Language key.</param>
public static bool HasLanguage(string languageKey)
{
var allData = GetData();
foreach (var data in allData)
{
if (data.languageKey == languageKey)
return true;
}
return false;
}
//TODO
public static void ExcelToJson()
{
// FileStream streamer = File.Open("Assets\\Resources\\Definitions\\localization_data.xlsx", FileMode.Open, FileAccess.Read);
//
// IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(streamer);
//
// DataSet result = excelReader.AsDataSet();
// while (excelReader.Read())
//// {
// Debug.Log(excelReader.GetString(0));
//// }
//
// excelReader.Close();
}
/// <summary>
/// Gets a value indicating is initialized.
/// </summary>
/// <value><c>true</c> if is initialized; otherwise, <c>false</c>.</value>
public static bool IsInitialized
{
get { return _Initialized; }
}
#endregion
#region Events
public static UpdateDelegate LanguageChanged;
#endregion
}
public interface ILocalizable
{
void OnLanguageChange();
}
}<file_sep>/Core/ElapsedTimeHandler.cs
using UnityEngine;
using System.Collections;
namespace PofyTools
{
[System.Serializable]
public class ElapsedTimeHandler : Timer
{
[Header("Initial Cooldown")]
public Range initialCooldownRange;
[Header("Cooldown")]
[SerializeField]
protected Range _cooldownRange;
#region Constructors
public ElapsedTimeHandler(string id)
: base(id, 0f)
{
}
public ElapsedTimeHandler(string id, float fixedDuration)
: base(id, fixedDuration)
{
this.initialCooldownRange = new Range(fixedDuration);
this._cooldownRange = new Range(fixedDuration);
}
public ElapsedTimeHandler(string id, float min, float max)
: this(id, min, max, min, max)
{
}
public ElapsedTimeHandler(string id, float initMin, float initMax, float min, float max) : base(id, initMax)
{
this.initialCooldownRange.min = initMin;
this.initialCooldownRange.max = initMax;
this._cooldownRange.min = min;
this._cooldownRange.max = max;
}
public ElapsedTimeHandler(string id, Range cooldown)
: this(id, cooldown, cooldown)
{
}
public ElapsedTimeHandler(string id, float initCooldown, Range cooldown)
: this(id, new Range(initCooldown, initCooldown), cooldown)
{
}
public ElapsedTimeHandler(string id, Range initCooldown, Range cooldown) : base(id)
{
this.initialCooldownRange = initCooldown;
this._cooldownRange = cooldown;
Initialize();
}
public ElapsedTimeHandler(string id, ElapsedTimeHandler source) : base(id)
{
this.initialCooldownRange = source.initialCooldownRange;
this._cooldownRange = source._cooldownRange;
Initialize();
}
#endregion
#region API
/// <summary>
/// Resets the Timer.
/// </summary>
public override void ResetTimer()
{
SetTimer(this._cooldownRange.Random);
}
/// <summary>
/// Sets Timer to Initial value
/// </summary>
public void InitializeTimer()
{
SetTimer(this.initialCooldownRange.Random);
}
public void SetRange(Range newRange)
{
this._cooldownRange = newRange;
}
#endregion
#region Initialize
public override bool Initialize()
{
if (base.Initialize())
{
InitializeTimer();
return true;
}
return false;
}
#endregion
}
}<file_sep>/CategoryGraph/CategoryGraph.cs
using System;
using UnityEditor;
using UnityEngine;
using XNode;
namespace PofyTools
{
/// <summary> Defines an example nodegraph that can be created as an asset in the Project window. </summary>
[Serializable, CreateAssetMenu(fileName = "New Category Graph", menuName = "PofyTools/Category Graph")]
public class CategoryGraph : NodeGraph
{
[SerializeField]
private Node _setNode = null;
public Node SetNode { get { return this._setNode; } }
public bool HasSetNode { get { return this._setNode != null; } }
[ContextMenu("Save Category Definition Set")]
public void SaveDefinitions()
{
if(this._setNode!=null)
(this._setNode as CategorySetNode).Save();
#if UNITY_EDITOR
AssetDatabase.SaveAssets();
#endif
}
/// <summary> Add a node to the graph by type </summary>
public override Node AddNode(Type type)
{
if (type == typeof(CategorySetNode))
{
if (this._setNode != null)
{
//destroy?
return null;
}
this._setNode = base.AddNode(type) as CategorySetNode;
return this._setNode;
}
else
return base.AddNode(type);
}
public override void RemoveNode(Node node)
{
if (node != this._setNode)
base.RemoveNode(node);
}
public void ResetGraph()
{
if (Application.isPlaying)
{
for (int i = this.nodes.Count - 1; i >= 0; i--)
{
if (this.nodes[i] != this._setNode)
Destroy(this.nodes[i]);
}
}
this.nodes.Clear();
this.nodes.Add(this._setNode);
}
//private void OnEnable()
//{
// if (this._setNode == null)
// {
// this._setNode = AddNode<CategorySetNode>();
// this._setNode.name = ObjectNames.NicifyVariableName(typeof(CategorySetNode).Name);
// }
//}
}
}<file_sep>/UI/WorldSpaceUI/WSUIFollow.cs
using UnityEngine;
namespace PofyTools
{
public class WSUIFollow : WSUIBase
{
public Transform followTarget;
public Vector3 followOffset;
public override bool UpdateElement(WSUIManager.UpdateData data)
{
//follow
this._rectTransform.position = this.followTarget.position + this.followOffset;
return base.UpdateElement(data);
}
}
}<file_sep>/Distribution/Timeline.cs
namespace PofyTools
{
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Timeline<TEventContent, TEventKey>
{
protected List<TimeEvent> _events = null;
public Dictionary<TEventKey, TimeEvent> _lastEventOfType = null;
public TimeEvent NullVar { get { return null; } }
protected Range _eventSpan = new Range ();
#region Constructors
private Timeline ()
{
}
public Timeline (int initialCapacity)
{
this._events = new List<TimeEvent> (initialCapacity);
this._lastEventOfType = new Dictionary<TEventKey, TimeEvent> (10);
this._filteredEvents = new List<TimeEvent> (initialCapacity / 2 + 1);
}
public Timeline(int initialCapacity, IEqualityComparer<TEventKey> equalityComparer)
{
this._events = new List<TimeEvent>(initialCapacity);
this._lastEventOfType = new Dictionary<TEventKey, TimeEvent>(10, equalityComparer);
this._filteredEvents = new List<TimeEvent>(initialCapacity / 2 + 1);
}
#endregion
#region Add/Remove Events
public TimeEvent AddEvent (TEventContent content, TEventKey type)
{
TimeEvent tEvent = new TimeEvent (content, type, Time.time);
this._events.Add (tEvent);
this._lastEventOfType[type] = tEvent;
this._eventSpan.max = Time.time;
if (this._events.Count == 1)
this._eventSpan.min = Time.time;
return tEvent;
}
public void Purge ()
{
this._events.Clear ();
this._filteredEvents.Clear ();
this._lastEventOfType.Clear ();
this._eventSpan = new Range ();
}
#endregion
#region Type Compare
public List<TimeEvent> GetAllEvents () { return this._events; }
public void GetEvents (List<TimeEvent> events, float period, bool chronologicalOrder = false, params TEventKey[] types)
{
events.Clear ();
for (int i = this._events.Count - 1; i >= 0; --i)
{
var tEvent = this._events[i];
if (tEvent.ElapsedTime <= period)
{
if (types.Length == 0)
{
events.Add (tEvent);
continue;
}
foreach (var type in types)
{
if (tEvent.type.Equals (type))
{
events.Add (tEvent);
break;
}
}
}
else break;
}
if (chronologicalOrder)
events.Reverse ();
}
public List<TimeEvent> GetEvents (float period, bool chronologicalOrder = false, params TEventKey[] types)
{
List<TimeEvent> events = new List<TimeEvent> ();
GetEvents (events, period, chronologicalOrder, types);
return events;
}
protected List<TimeEvent> _filteredEvents = null;
public List<TimeEvent> GetEventsNonAlloc (float period, bool chronologicalOrder = false, params TEventKey[] types)
{
// this._filteredEvents.Clear ();
GetEvents (this._filteredEvents, period, chronologicalOrder, types);
return this._filteredEvents;
}
#endregion
#region Range Compare
public void GetEventsInTimeRange (List<TimeEvent> events, float fromTimestamp, float toTimestamp, bool chronologicalOrder = false, params TEventKey[] types)
{
//Clear provided list
events.Clear ();
//Cache everything!
int count = this._events.Count;
//No events - no service
if (count == 0)
return;
//No Scope - no service
if (fromTimestamp >= toTimestamp)
return;
//Clamp time range to event span
fromTimestamp = (fromTimestamp < this._eventSpan.min) ? this._eventSpan.min : fromTimestamp;
toTimestamp = (toTimestamp > this._eventSpan.max) ? this._eventSpan.max : toTimestamp;
//Out of bounds
if (!this._eventSpan.Contains (fromTimestamp) || !this._eventSpan.Contains (fromTimestamp))
return;
//Index to start the search from
int partitionIndex = 0;
//Element at partition index
TimeEvent partition = null;
//search direction
int sign = 0;
//is partition element inside search scope
bool inRange = false;
float diffLeft, diffRight;
diffLeft = fromTimestamp - _eventSpan.min;
diffRight = _eventSpan.max - toTimestamp;
//If we assume somewhat uniform event distribution over event span
partitionIndex = (diffLeft > diffRight) ? this._events.Count - 1 : 0;
do
{
partitionIndex += sign;
partition = this._events[partitionIndex];
if (partition.timestamp < fromTimestamp) { if (sign != -1) sign = 1; else return; }
else if (partition.timestamp > toTimestamp) { if (sign != 1) sign = -1; else return; }
else
{
inRange = true;
}
}
while (!inRange);
while (inRange)
{
if (types.Length == 0)
{
events.Add (partition);
}
else
{
foreach (var type in types)
{
if (partition.type.Equals (type))
{
events.Add (partition);
break;
}
}
}
partitionIndex += sign;
partition = this._events[partitionIndex];
inRange = (partition.timestamp >= fromTimestamp) && (partition.timestamp <= toTimestamp);
}
if (chronologicalOrder && sign == -1)
{
events.Reverse ();
}
}
public List<TimeEvent> GetEventsInTimeRangeNonAlloc (float fromTimestamp, float toTimestamp, bool chronologicalOrder = false, params TEventKey[] types)
{
GetEventsInTimeRange (this._filteredEvents, fromTimestamp, toTimestamp, chronologicalOrder, types);
return this._filteredEvents;
}
public List<TimeEvent> GetEventsInTimeRange (float fromTimestamp, float toTimestamp, bool chronologicalOrder = false, params TEventKey[] types)
{
List<TimeEvent> events = new List<TimeEvent> ();
GetEventsInTimeRange (events, fromTimestamp, toTimestamp, chronologicalOrder, types);
return events;
}
#endregion
#region Until Compare
public void GetEventsUntilInstance (List<TimeEvent> events, TimeEvent instance, bool chronologicalOrder = false, params TEventKey[] types)
{
events.Clear ();
if (instance == null || !this._lastEventOfType.ContainsKey (instance.type))
{
//The whole thing!
events.AddRange (this._events);
return;
}
for (int i = this._events.Count - 1; i >= 0; --i)
{
var tEvent = this._events[i];
if (tEvent == instance)
{
break;
}
if (types.Length == 0)
{
events.Add (tEvent);
continue;
}
foreach (var type in types)
{
if (tEvent.type.Equals (type))
{
events.Add (tEvent);
break;
}
}
}
if (chronologicalOrder)
events.Reverse ();
}
public List<TimeEvent> GetEventsUntilInstance (TimeEvent instance, bool chronologicalOrder = false, params TEventKey[] types)
{
List<TimeEvent> events = new List<TimeEvent> ();
GetEventsUntilInstance (events, instance, chronologicalOrder, types);
return events;
}
public List<TimeEvent> GetEventsUntilInstanceNonAlloc (TimeEvent instance, bool chronologicalOrder = false, params TEventKey[] types)
{
GetEventsUntilInstance (this._filteredEvents, instance, chronologicalOrder, types);
return this._filteredEvents;
}
#endregion
public class TimeEvent
{
public TEventContent content = default;
public float timestamp = 0f;
public TEventKey type = default;
public float ElapsedTime
{
get { return Time.time - timestamp; }
}
public TimeEvent () { }
public TimeEvent (TEventContent content, TEventKey type, float timestamp)
{
this.content = content;
this.type = type;
this.timestamp = timestamp;
}
}
}
}<file_sep>/Distribution/Deck.cs
using System.Collections.Generic;
using UnityEngine;
namespace PofyTools.Distribution
{
public interface IShufflable
{
bool IsShuffled
{
get;
}
void Shuffle();
}
/// <summary>
/// Generic Deck. Deck contains cards that contain references to the instances of the teplated type.
/// </summary>
[System.Serializable]
public class Deck<T> : IShufflable
{
[System.Serializable]
public class Card
{
[SerializeField] protected T _element = default(T);
public T Element
{
get { return this._element; }
}
[SerializeField] protected int _weight = 0;
public int Weight
{
get { return this._weight; }
set { this._weight = Mathf.Max(1, value); }
}
public override string ToString()
{
return string.Format("[Card: instance={0}, weight={1}]", this._element, this._weight);
}
public Card(T element, int weight = 1)
{
this._element = element;
this._weight = weight;
}
public Card(Card card)
{
this._element = card.Element;
this._weight = card.Weight;
}
}
#region State
public enum State : int
{
Empty = 0,
Initialized = 1,
Populated = 2,
Shuffled = 3,
Distributed = 4,
}
[SerializeField] protected State _state = State.Empty;
public State CurrentState { get { return this._state; } }
#endregion
#region IShufflable
//protected bool _isShuffled = false;
/// <summary>
/// Gets a value indicating whether this <see cref="PofyTools.Deck`1"/> is shuffled.
/// </summary>
/// <value><c>true</c> if is shuffled; otherwise, <c>false</c>.</value>
public bool IsShuffled
{
get { return this._state == State.Shuffled; }
}
/// <summary>
/// Shuffles this Deck.
/// </summary>
public void Shuffle()
{
this._head = 0;
while (this._head < this.Count)
{
int randomIndex = Random.Range(this._head, this.Count);
Card randomCard = this._cards[randomIndex];
this._cards.RemoveAt(randomIndex);
this._cards.Insert(this._head, randomCard);
++this._head;
}
this._state = State.Shuffled;
this._head = 0;
}
#endregion
[SerializeField] protected List<Card> _cards = new List<Card>();
public List<Card> Cards
{
get { return this._cards; }
}
[SerializeField] protected bool _autoShuffle = true;
public bool AutoShuffle => this._autoShuffle;
public bool IsDepleted => this._head == this._cards.Count;
[SerializeField] protected int _head;
/// <summary>
/// Gets the currenct position in the deck or -1 if the Deck is empty.
/// </summary>
/// <value>The head.</value>
public int Head
{
get
{
if (this.Count > 0)
return this._head;
else
return -1;
}
}
/// <summary>
/// Gets the total count of<see cref="PofyTools.Deck.Card"/>in the Deck.
/// </summary>
/// <value>The count.</value>
public int Count
{
get { return this._cards.Count; }
}
[SerializeField] protected int _maxWeight = int.MinValue;
/// <summary>
/// Returns cached max weight or gets the max weight present in the Deck or <c>int.MinValue</c> if empty.
/// </summary>
/// <value>The max weight.</value>
public int MaxWeight
{
get
{
if (this._maxWeight == int.MinValue)
{
this._maxWeight = GetMaxWeight();
}
return this._maxWeight;
}
}
protected int GetMaxWeight()
{
int result = int.MinValue;
for (int i = 0, max_cardsCount = this._cards.Count; i < max_cardsCount; i++)
{
var card = this._cards[i];
result = Mathf.Max(result, card.Weight);
}
return result;
}
[SerializeField] protected int _minWeight = int.MaxValue;
/// <summary>
/// Returns cached min weight or gets the min weight present in the Deck or <c>int.MaxValue</c> if empty.
/// </summary>
/// <value>The min weight.</value>
public int MinWeight
{
get
{
if (this._minWeight == int.MaxValue)
{
this._minWeight = GetMinWeight();
}
return this._minWeight;
}
}
protected int GetMinWeight()
{
int result = int.MaxValue;
for (int i = 0, max_cardsCount = this._cards.Count; i < max_cardsCount; i++)
{
var card = this._cards[i];
result = Mathf.Min(result, card.Weight);
}
return result;
}
/// <summary>
/// Returns whether the <see cref="PofyTools.Deck.Card"/>instance is present in the Deck.
/// </summary>
/// <returns><c>true</c>, if the Card instance is present in the Deck, <c>false</c> otherwise.</returns>
/// <param name="card">Card.</param>
public bool ContainsCard(Card card)
{
return this._cards.Contains(card);
}
/// <summary>
/// Adds the card to the Deck. Sets the Deck's Max Weight to the Card's weight if greater than current Max Weight.
/// </summary>
/// <param name="card">Card.</param>
public void AddCard(Card card)
{
this._cards.Add(card);
if (card.Weight > this.MaxWeight)
{
this._maxWeight = card.Weight;
}
else if (card.Weight < this.MinWeight)
{
this._minWeight = card.Weight;
}
}
/// <summary>
/// Creates and adds the card for the element provided with the weight provided (default 1).
/// </summary>
/// <param name="element">Instance.</param>
/// <param name="weight">Weight.</param>
public Card AddElement(T element, int weight = 1)
{
Card card = new Card(element, weight);
AddCard(card);
return card;
}
public void AddIdentityElement(T element, int weight = 1)
{
Card identityCard = AddElement(element, weight);
SetIdentityCard(identityCard);
}
public void RemoveCard(Card card)
{
this._cards.RemoveAll(c => c == card);
this._maxWeight = GetMaxWeight();
this._minWeight = GetMinWeight();
//TODO: collect extremes in one iteration
}
public void RemoveElementCard(T element)
{
this._cards.RemoveAll(c => (object)c.Element == (object)element);
this._maxWeight = GetMaxWeight();
this._minWeight = GetMinWeight();
//TODO: collect extremes in one iteration
}
/// <summary>
/// Returns whether the Deck contains the Card with the provided elemenet.
/// </summary>
/// <returns><c>true</c>, if instance was containsed, <c>false</c> otherwise.</returns>
/// <param name="element">Instance.</param>
public bool ContainsElement(T element)
{
for (int i = 0, max_cardsCount = this._cards.Count; i < max_cardsCount; i++)
{
var card = this._cards[i];
if ((object)card.Element == (object)element)
return true;
}
return false;
}
public bool ContainsElement(T element, out Card elementCard)
{
for (int i = 0, max_cardsCount = this._cards.Count; i < max_cardsCount; i++)
{
var card = this._cards[i];
if ((object)card.Element == (object)element)
{
elementCard = card;
return true;
}
}
elementCard = null;
return false;
}
public Card FindElementCard(T element)
{
Card card = null;
if (ContainsElement(element, out card))
{
Debug.Log("Instance card found!");
return card;
}
Debug.Log("Instance card not found!");
return card;
}
public Card PickElementCard(T element)
{
Card instanceCard = null;
for (int i = this._head, max_cardsCount = this._cards.Count; i < max_cardsCount; i++)
{
var card = this._cards[i];
if ((object)card.Element == (object)element)
{
instanceCard = PickCardAt(i);
break;
}
}
return instanceCard;
}
protected Card PickCardAt(int index, bool reorder = true)
{
if (!this.IsDepleted)
{
Card resultCard = this._cards[index];
if (index != 0 && reorder)
{
this._cards.RemoveAt(index);
this._cards.Insert(0, resultCard);
}
++this._head;
if (this.IsDepleted && this._autoShuffle)
{
Shuffle();
}
return resultCard;
}
Debug.LogWarning("Deck is depleted. Returning null...");
return null;
}
/// <summary>
/// Picks the Card on the Head position and moves the Head to next position.
/// If Head gets to the end of the Deck, the Deck gets reshuffled.
/// </summary>
/// <returns>The next card.</returns>
public Card PickNextCard()
{
return PickCardAt(this._head, false);
}
/// <summary>
/// Picks the first card with minWeight or higher and removes it from the
/// </summary>
/// <returns>The bias card.</returns>
/// <param name="minWeight">Minimum weight.</param>
public Card PickBiasCard(int minWeight = 0)
{
minWeight = Mathf.Min(minWeight, this.MaxWeight);
Card biasCard = null;
for (int i = this._head, max_cardsCount = this._cards.Count; i < max_cardsCount; ++i)
{
var card = this._cards[i];
if (card.Weight >= minWeight)
{
biasCard = PickCardAt(i);
break;
}
}
return biasCard;
}
//TODO: different distribution types
public Deck<T> CreateDistributionDeck()
{
Deck<T> distributionDeck = null;
if (this._state != State.Distributed)
{
distributionDeck = new Deck<T>();
foreach (var card in this._cards)
{
card.Weight = Mathf.Max(1, card.Weight);
// int totalNumberOfCopies = Mathf.RoundToInt ((float)this.MaxWeight / (float)card.weight);
int count = card.Weight;
// AlertCanvas.Instance.alert (string.Format ("{0} : {1}", card.instance, totalNumberOfCopies), AlertPanel.Type.INFO);
while (count > 0)
{
Card copy = new Card(card);
distributionDeck._cards.Add(copy);
--count;
}
}
}
else
{
Debug.LogWarning("Source deck is already distributed. Returning the shallow copy of the source...");
distributionDeck = new Deck<T>(this);
}
distributionDeck.Shuffle();
distributionDeck._state = State.Distributed;
return distributionDeck;
}
#region Identity
protected Card _identityCard = null;
public Card IdentityCard
{
get { return this._identityCard; }
}
public bool HasIdentityCard
{
get { return this._identityCard != null; }
}
public bool IsIdentityCard(Card card)
{
return card == this._identityCard;
}
public void SetIdentityCard(Card card)
{
if (!this.HasIdentityCard)
this._identityCard = card;
else if (IsIdentityCard(card))
Debug.LogWarningFormat("Deck: Card {0} is already identity card!", card);
else
Debug.LogWarningFormat("Deck: Identity card already set!");
}
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PofyTools.Deck`1"/> class.
/// </summary>
public Deck(bool autoShuffle = true)
{
this._cards = new List<Card>();
this._autoShuffle = autoShuffle;
}
/// <summary>
/// Initializes a new instance of the <see cref="PofyTools.Deck`1"/> class.
/// </summary>
/// <param name="capacity">Capacity of the card list.</param>
public Deck(int capacity, bool autoShuffle = true)
{
this._cards = new List<Card>(capacity);
this._autoShuffle = autoShuffle;
}
public Deck(bool autoShuffle = true, params T[] elements)
{
this._cards = new List<Card>(elements.Length);
for (int i = 0, instancesLength = elements.Length; i < instancesLength; i++)
{
var instance = elements[i];
AddElement(instance);
}
this._autoShuffle = autoShuffle;
}
public Deck(List<Card> cards, bool autoShuffle = true)
{
this._cards = new List<Card>(cards);
this._autoShuffle = autoShuffle;
}
public Deck(Deck<T> source)
{
this._cards = new List<Card>(source._cards);
this._head = source._head;
//this._isShuffled = source._isShuffled;
this._state = source._state;
this._maxWeight = source._maxWeight;
this._minWeight = source._minWeight;
if (source.HasIdentityCard)
this._identityCard = FindElementCard(source._identityCard.Element);
this._autoShuffle = source._autoShuffle;
}
public Deck(bool autoShuffle = true, params Card[] cards)
{
this._cards = new List<Card>(cards);
this._autoShuffle = autoShuffle;
}
#endregion
}
}
<file_sep>/UI/WorldSpaceUI/WSUIFollowText.cs
namespace PofyTools
{
public class WSUIFollowText : WSUIFollow
{
public TMPro.TextMeshProUGUI text;
}
}<file_sep>/Editor/PofyToolsEditorUtility.cs
namespace PofyTools
{
using UnityEditor;
using UnityEngine;
public static class PofyToolsEditorUtility
{
public static T[] LoadAllAssetsAtPath<T>(params string[] paths) where T : Object
{
var guids = AssetDatabase.FindAssets("", paths);
Debug.Log(guids.Length);
T[] result = new T[guids.Length];
for (int i = 0; i < guids.Length; i++)
{
var h = guids[i];
var asset = AssetDatabase.LoadAssetAtPath<T>(AssetDatabase.GUIDToAssetPath(h));
result[i] = asset;
}
return result;
}
}
}<file_sep>/Distribution/NameGenerator/Demo/Dialog.cs
using PofyTools;
using UnityEngine.Events;
using UnityEngine.UI;
public class Dialog : Panel
{
public Text title, message;
public Button confirm, cancel;
public void ShowDialog (string title, string message, UnityAction onConfirm)
{
this.confirm.onClick.RemoveAllListeners ();
this.confirm.onClick.AddListener (onConfirm);
this.confirm.onClick.AddListener (this.Close);
this.cancel.onClick.RemoveAllListeners ();
this.cancel.onClick.AddListener (this.Close);
this.title.text = title;
this.message.text = message;
this.Open ();
}
}
<file_sep>/Distribution/Chance.cs
namespace PofyTools.Distribution
{
using UnityEngine;
using System.Collections;
/// <summary>
/// Distribution based on chance with optional Auto Deck Size
/// </summary>
public class Chance
{
private bool _autoDeckSize = true;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="PofyTools.Distribution.Chance"/> auto deck size.
/// </summary>
/// <value><c>true</c> if auto deck size; otherwise, <c>false</c>.</value>
public bool autoDeckSize {
get { return this._autoDeckSize; }
set {
if (value != this._autoDeckSize)
this._autoDeckSize = value;
else
Debug.LogWarning ("Chance: Auto Deck size is already " + value + ".");
}
}
[Range (0f, 1f)] private float _chance = 0;
/// <summary>
/// Gets or sets the chance (0 - 1).
/// </summary>
/// <value>The chance.</value>
public float chance {
get { return this._chance; }
set {
if (value != this._chance) {
this._chance = value;
BuildDeck ();
}
}
}
public float percent {
get { return this._chance * 100; }
}
private Deck<bool> _deck;
/// <summary>
/// Gets total card count in distribution deck.
/// </summary>
/// <value>The count.</value>
public int Count {
get { return this._deck.Count; }
}
public bool Value {
get { return this._deck.PickNextCard ().Element; }
}
public bool RandomValue {
get {
return Random.Range (0f, 1f) < this._chance;
}
}
void Initialize ()
{
BuildDeck ();
}
void BuildDeck ()
{
int deckSize = 0;
float percent = this._chance * 100;
if (this._autoDeckSize) {
if (percent % 100 == 0) {
deckSize = 1;
} else if (percent % 50 == 0) {
deckSize = 2;
} else if (percent % 25 == 0) {
deckSize = 4;
} else if (percent % 20 == 0) {
deckSize = 5;
} else if (percent % 10 == 0) {
deckSize = 10;
} else if (percent % 5 == 0) {
deckSize = 20;
} else if (percent % 4 == 0) {
deckSize = 25;
} else if (percent % 2 == 0) {
deckSize = 50;
} else if (percent % 1 == 0) {
deckSize = 100;
} else {
deckSize = 1000;
}
} else {
deckSize = 1000;
}
this._deck = new Deck<bool> (deckSize);
int trueCount = (int)(this._chance * deckSize);
int falseCount = deckSize - trueCount;
if (trueCount > 0)
this._deck.AddCard (new Deck<bool>.Card (true, trueCount));
if (falseCount > 0)
this._deck.AddCard (new Deck<bool>.Card (false, falseCount));
this._deck = this._deck.CreateDistributionDeck ();
}
public Chance () : this (1f)
{
}
public Chance (float chance) : this (chance, true)
{
}
public Chance (float chance, bool autoDeckSize)
{
this._chance = chance;
this._autoDeckSize = autoDeckSize;
Initialize ();
}
#region Static Methods
public static bool FiftyFifty {
get { return Random.Range (0, 2) > 0; }
}
public static bool TryWithChance (float chance)
{
chance = Mathf.Clamp01 (chance);
return Random.Range (0f, 1f) < chance;
}
public static int GenerateDigits (int digits)
{
int total = 0;
for (int i = 0; i < digits; ++i)
{
int value = (int)Mathf.Pow (10, i);
int result = 0;
int count = 0;
while (Chance.FiftyFifty && count < 10)
{
count++;
result += value;
}
total += result;
}
return total;
}
public static int GenerateDigits (int digits, int min, int max)
{
return Mathf.Clamp (GenerateDigits (digits), min, max);
}
#endregion
}
}<file_sep>/AdProviderManager/AdProviderData.cs
namespace PofyTools
{
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Ad Provider Data", menuName = "PofyTools/Ad Provider Data")]
public class AdProviderData : ScriptableObject
{
public bool useUnityAds;
public string unityAdsId;
public bool useGoogleAds;
public string googleAppId;
public string[] googleTestDeviceIds;
public string googleInterstitialId;
public string googleBannerId;
public string googleRewardAdId;
public bool testMode;
}
}<file_sep>/Data/Editor/LocalizationDataEditor.cs
namespace PofyTools
{
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class LocalizationDataEditor : EditorWindow
{
private string[] _languages = null;
private string _selectedLanguage = "";
private int _selectedLanguageIndex = -1;
private Localization.LanguageData _data;
[MenuItem("PofyTools/Localization Data Editor")]
static void Init()
{
// Get existing open window or if none, make a new one
LocalizationDataEditor window = (LocalizationDataEditor)EditorWindow.GetWindow(typeof(LocalizationDataEditor));
window.ReadData();
window.Show();
}
public void ReadData()
{
Localization.Initialize();
this._languages = Localization.GetLanguages();
//Select first language (EN)
if (this._languages.Length > 0)
{
this._selectedLanguage = this._languages[Mathf.Max(this._selectedLanguageIndex, 0)];
this._data = Localization.SetLanguage(this._selectedLanguage);
}
}
void OnGUI()
{
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Load Data"))
{
if (this._dirty)
{
if (EditorUtility.DisplayDialog("Changes not saved", "Discard changes?", "Discard", "Cancel"))
{
ReadData();
this._dirty = false;
}
}
else
{
ReadData();
this._dirty = false;
}
}
if (GUILayout.Button("Save Data"))
{
Localization.SaveData();
AssetDatabase.Refresh();
this._dirty = false;
}
if (GUILayout.Button("Import Excel File"))
{
//File browser / other stuff
}
EditorGUILayout.EndHorizontal();
if (this._data == null)
{
return;
}
EditorGUILayout.BeginHorizontal();
int lastIndex = this._selectedLanguageIndex;
EditorGUILayout.LabelField("Select language:");
this._selectedLanguageIndex = EditorGUILayout.Popup(this._selectedLanguageIndex, this._languages);
if (GUILayout.Button("Add Language"))
{
AddLanguage();
}
EditorGUILayout.EndHorizontal();
if (this._selectedLanguageIndex >= 0)
{
if (lastIndex != this._selectedLanguageIndex)
{
this._selectedLanguage = this._languages[this._selectedLanguageIndex];
this._data = Localization.SetLanguage(this._selectedLanguage);
}
DrawPairs();
if (GUILayout.Button("Add Entry"))
{
AddPair();
}
}
}
private Vector2 _scrollPosition;
void DrawPairs()
{
int indexToRemove = -1;
this._scrollPosition = EditorGUILayout.BeginScrollView(this._scrollPosition);
for (int i = 0; i < this._data.keys.Count; i++)
{
var lastKey = this._data.keys[i];
var lastValue = this._data.values[i];
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Remove"/*, GUILayout.Width(25)*/))
{
indexToRemove = i;
}
this._data.keys[i] = EditorGUILayout.TextField(this._data.keys[i]);
this._data.values[i] = EditorGUILayout.TextField(this._data.values[i]);
if (lastKey != this._data.keys[i] || lastValue != this._data.values[i])
{
EditorUtility.SetDirty(this);
this._dirty = true;
}
EditorGUILayout.EndHorizontal();
}
if (indexToRemove != -1)
{
RemovePairAt(indexToRemove);
}
EditorGUILayout.EndScrollView();
}
private Rect _popupRect;
void AddPair()
{
var popup = new LocalizationDataAddEntryPopup();
//popup.editorWindow = this;
PopupWindow.Show(this._popupRect, popup);
if (Event.current.type == EventType.Repaint)
this._popupRect = GUILayoutUtility.GetLastRect();
this._dirty = true;
}
void AddLanguage()
{
if (this._dirty)
{
if (EditorUtility.DisplayDialog("Add New Language", "You must save changes before adding a new language?", "Save and Continue", "Cancel"))
{
Localization.SaveData();
AssetDatabase.Refresh();
this._dirty = false;
var popup = new LocalizationDataAddLanguagePopup();
//popup.editorWindow = this;
PopupWindow.Show(this._popupRect, popup);
if (Event.current.type == EventType.Repaint)
this._popupRect = GUILayoutUtility.GetLastRect();
}
}
else
{
var popup = new LocalizationDataAddLanguagePopup();
//popup.editorWindow = this;
PopupWindow.Show(this._popupRect, popup);
if (Event.current.type == EventType.Repaint)
this._popupRect = GUILayoutUtility.GetLastRect();
}
}
void RemovePairAt(int index)
{
if (EditorUtility.DisplayDialog("Remove Entry", "Are you sure?", "Remove", "Cancel"))
{
Localization.RemovePairAt(index);
this._dirty = true;
}
}
private bool _dirty = false;
void OnDestroy()
{
if (this._dirty)
{
if (EditorUtility.DisplayDialog("Changes not saved", "Save changes?", "Save", "Discard"))
{
Localization.SaveData();
AssetDatabase.Refresh();
this._dirty = false;
}
}
Localization.Clear();
}
}
}<file_sep>/Distribution/NameGenerator/SemanticData.cs
using Extensions;
using System.Collections.Generic;
using UnityEngine;
namespace PofyTools
{
[System.Serializable]
public class SemanticData : IInitializable
{
public const string TAG = "<color=green><b>SemanticData: </b></color>";
#region Constructors
public SemanticData() { }
public SemanticData(string path, string filename, bool scramble = false, bool encode = false, string extension = "")
{
this._path = path;
this._filename = filename;
this._scrable = scramble;
this._encode = encode;
this._extension = extension;
}
#endregion
#region Serializable Data
[Header("Database Version")]
public string dataVersion = "0.0";
[Header("Name Sets")]
public List<Lexicon> setNames = new List<Lexicon>();
//[Header ("Title Sets")]
//public List<TitleSet> setTitles = new List<TitleSet> ();
[Header("Grammar Sets")]
public List<GrammarSet> setGrammars = new List<GrammarSet>();
[Header("Syllable Generator")]
public List<string> vowels = new List<string>();
public List<string> vowelPairs = new List<string>();
public List<string> consonantStart = new List<string>();
public List<string> consonantOpen = new List<string>();
public List<string> consonantClose = new List<string>();
public List<string> maleEndSyllablesOpen = new List<string>();
public List<string> maleEndSyllablesClose = new List<string>();
public List<string> femaleEndSyllablesOpen = new List<string>();
public List<string> femaleEndSyllablesClose = new List<string>();
[Header("Numbers")]
public List<string> numberOrdinals = new List<string>();
public List<string> numberCardinals = new List<string>();
#endregion
#region Runtimes
[System.NonSerialized]
protected string _path;
protected string _filename;
protected string _extension;
protected bool _scrable;
protected bool _encode;
public string ResourcePath
{
get
{
return this._path + "/" + this._filename;
}
}
public string FullPath
{
get
{
return this._path + "/" + this._filename + "." + this._extension;
}
}
[System.NonSerialized]
protected Dictionary<string, Lexicon> _setNames = new Dictionary<string, Lexicon>();
[System.NonSerialized]
protected List<string> _setNameIds = new List<string>();
[System.NonSerialized]
protected Dictionary<string, GrammarSet> _setGrammars = new Dictionary<string, GrammarSet>();
[System.NonSerialized]
protected List<string> _setGrammarIds = new List<string>();
public List<string> GetAllGrammarIds() { return this._setGrammarIds; }
[System.NonSerialized]
protected List<string> _allAdjectives = new List<string>();
[System.NonSerialized]
protected List<string> _allNouns = new List<string>();
protected void CreateRuntimeCollections()
{
this._allNouns.Clear();
this._allAdjectives.Clear();
this._setNames.Clear();
this._setNameIds.Clear();
//this._setTitles.Clear ();
//this._setTitleIds.Clear ();
this._setGrammars.Clear();
this._setGrammarIds.Clear();
foreach (var nameSet in this.setNames)
{
if (this._setNames.ContainsKey(nameSet.id))
Debug.LogWarning(TAG + "Id " + nameSet.id + " already present Name Sets. Owerwritting...");
this._setNames[nameSet.id] = nameSet;
this._setNameIds.Add(nameSet.id);
}
//foreach (var titleSet in this.setTitles)
//{
// if (this._setTitles.ContainsKey (titleSet.id))
// Debug.LogWarning (TAG + "Id " + titleSet.id + " already present in Title Sets. Owerwritting...");
// this._setTitles[titleSet.id] = titleSet;
// this._setTitleIds.Add (titleSet.id);
// foreach (var adjective in titleSet.adjectives)
// {
// this._allAdjectives.Add (adjective);
// }
// foreach (var subjective in titleSet.subjectivesCons)
// {
// this._allNouns.Add (subjective);
// }
// foreach (var subjective in titleSet.subjectivesPros)
// {
// this._allNouns.Add (subjective);
// }
// foreach (var subjective in titleSet.subjectivesNeutral)
// {
// this._allNouns.Add (subjective);
// }
// foreach (var genetive in titleSet.genetives)
// {
// this._allNouns.Add (genetive);
// }
//}
foreach (var grammarset in this.setGrammars)
{
if (this._setGrammars.ContainsKey(grammarset.nounSingular))
Debug.LogWarning(TAG + "Id " + grammarset.nounSingular + " already present in Grammer Sets. Owerwritting...");
this._setGrammars[grammarset.nounSingular] = grammarset;
this._setGrammarIds.Add(grammarset.nounSingular);
}
}
#endregion
#region API
//FIXME
// public string GenerateName(string nameSetId = "", string titleSetId = "", bool useAdjective = true, bool useSubjective = true, bool useGenetive = true, bool male = true)
// {
//
// NameSet nameSet = null;
// TitleSet titleSet = null;
// string final = string.Empty;
// CultureInfo cultureInfo = new CultureInfo("en-US", false);
// TextInfo textInfo = cultureInfo.TextInfo;
//
// if (string.IsNullOrEmpty(nameSetId))
// {
// nameSetId = this._setNameIds[Random.Range(0, this._setNameIds.Count - 1)];
// }
//
// if (this._setNames.TryGetValue(nameSetId, out nameSet))
// {
// final = textInfo.ToTitleCase(nameSet.prefixes[Random.Range(0, nameSet.prefixes.Count - 1)].ToLower(cultureInfo));
// final += nameSet.sufixes[Random.Range(0, nameSet.sufixes.Count - 1)];
// }
//
// if (this._setTitles.TryGetValue(titleSetId, out titleSet))
// {
// if (useAdjective || useSubjective)
// {
// final += " the ";
//
// if (useAdjective)
// {
// final += textInfo.ToTitleCase(titleSet.adjectives[Random.Range(0, titleSet.adjectives.Count - 1)].ToLower(cultureInfo));
// final += " ";
// }
//
// if (useSubjective)
// {
// TitleSet opposingSet = null;
//
// bool opposing = Random.Range(0f, 1f) > 0.5f && this._setTitles.TryGetValue(titleSet.opposingId, out opposingSet);
// if (opposing)
// {
// final += textInfo.ToTitleCase(opposingSet.objectivesNeutral[Random.Range(0, opposingSet.objectivesNeutral.Count - 1)].ToLower(cultureInfo));
// final += textInfo.ToTitleCase(this.subjectiveCons[Random.Range(0, this.subjectiveCons.Count - 1)].ToLower(cultureInfo));
// }
// else
// {
// final += textInfo.ToTitleCase(titleSet.objectivesNeutral[Random.Range(0, titleSet.objectivesNeutral.Count - 1)].ToLower(cultureInfo));
// final += textInfo.ToTitleCase(this.subjectivePros[Random.Range(0, this.subjectivePros.Count - 1)].ToLower(cultureInfo));
// }
// }
// }
//
// if (useGenetive)
// final += " of " + textInfo.ToTitleCase(titleSet.genetives[Random.Range(0, titleSet.genetives.Count - 1)].ToLower(cultureInfo));
// }
//
//
// //final = textInfo.ToTitleCase(final);
//
// return final;
// }
//TODO
//
public Lexicon GetNameSet(string id)
{
Lexicon nameset = null;
this._setNames.TryGetValue(id, out nameset);
return nameset;
}
//public TitleSet GetTitleSet (string id)
//{
// TitleSet titleset = null;
// this._setTitles.TryGetValue (id, out titleset);
// return titleset;
//}
//public string GenerateStoryName (bool useAdjective = true, bool useSubjective = true, bool useGenetive = true)
//{
// string result = string.Empty;
// if (useSubjective)
// {
// result = "the ";
// if (useAdjective)
// {
// result += GetAdjective () + " ";
// }
// result += this.subjectiveStory.GetRandom ();
// }
// if (useGenetive)
// {
// //TODO: pick genetive from other titlesets
// // result += " of the ";
// // result += this._allNouns.GetRandom();
// result += " " + GetGenetive ();
// }
// result = result.Trim ();
// if (string.IsNullOrEmpty (result))
// result = "NULL(story)";
// return result;
//}
//public string GenerateGeolocationName (bool usePrefix = true, bool useSubjective = true, bool useGenetive = true)
//{
// string result = string.Empty;
// if (Chance.FiftyFifty)
// {
// return this.GetNameSet ("town").GetRandomName ();
// }
// if (useSubjective)
// {
// //Prefix
// if (usePrefix)
// result += GetPrefix ();
// //Subjective
// result += this.subjectiveGeolocation.GetRandom ();
// }
// //Genetive
// if (useGenetive && !usePrefix)
// {
// //TODO: pick genetive from other titlesets
// // result += " of the ";
// // result += this._allNouns.GetRandom();
// result += " " + GetGenetive (forceSingular: true, useOrdinals: false, nameSet: "");
// }
// result = result.Trim ();
// if (string.IsNullOrEmpty (result))
// result = "NULL(story)";
// return result;
//}
public string GetRandomOrdinalNumber(int max = 1000)
{
return (Chance.TryWithChance(0.3f)) ? GetOrdinalNumber(Random.Range(4, max + 1)) : this.numberOrdinals.TryGetRandom();
}
public string GetAdjective(bool plural = false, bool useNumbers = true, bool usePossessiveApostrophe = true, string nameSet = "")
{
string result = string.Empty;
//Numbers
if (useNumbers && Chance.TryWithChance(0.3f))
{
if (plural)
result += this.numberCardinals.TryGetRandom();
else
result += this.numberOrdinals.TryGetRandom();
return result;
}
//Name
if (Chance.FiftyFifty)
{
string name = (nameSet == "") ? GetAnyName(Chance.FiftyFifty) : GetNameSet(nameSet).GetRandomName();
if (!string.IsNullOrEmpty(name))
result += (usePossessiveApostrophe) ? NameToAdjective(name) : name;
else
{
Debug.LogError(TAG + "Empty name from GetAnyName!");
result += this._allAdjectives.TryGetRandom();
}
}
else
{
if (Chance.FiftyFifty)
result += this._allAdjectives.TryGetRandom();
else
result += this.setGrammars.TryGetRandom().adjectives.TryGetRandom();
}
return result;
}
public string GetAdjective(string key)
{
GrammarSet set = null;
if (this._setGrammars.TryGetValue(key, out set))
return set.adjectives.TryGetRandom();
return key;
}
public string GetPrefix(string key = "")
{
if (key == "")
return this.setGrammars.TryGetRandom().nounSingular;
return key;
}
public string GetGenetive(bool forceSingular = false, bool useOrdinals = true, string nameSet = "")
{
GrammarSet grammarset = null;
string result = "of ";
string genetive = string.Empty;
bool plural = !forceSingular && Chance.FiftyFifty;
bool useAdjective = Chance.TryWithChance(0.3f);
if (!plural)
{
grammarset = this.setGrammars.TryGetRandom();
if (grammarset.useDeterminer || useAdjective)
{
result += "the ";
genetive = grammarset.nounSingular;
}
grammarset = this.setGrammars.TryGetRandom();
result += (useOrdinals && Chance.FiftyFifty) ? this.numberOrdinals.TryGetRandom() + " " : "";
if (useAdjective)
result += grammarset.adjectives.TryGetRandom() + " ";
result += genetive;
}
else
{
result += (Chance.FiftyFifty) ? this.numberCardinals.TryGetRandom() + " " : "";
grammarset = this.setGrammars.TryGetRandom();
while (grammarset.nounPlurals.Count == 0)
{
grammarset = this.setGrammars.TryGetRandom();
}
genetive = grammarset.nounPlurals.TryGetRandom();
if (useAdjective)
{
grammarset = this.setGrammars.TryGetRandom();
result += grammarset.adjectives.TryGetRandom() + " ";
}
result += genetive;
}
return result;
}
public string GetGenetive(string key)
{
GrammarSet set = null;
if (this._setGrammars.TryGetValue(key, out set))
{
return (Chance.FiftyFifty) ? (set.useDeterminer) ? "the " + set.nounSingular : set.nounSingular : set.nounPlurals.TryGetRandom();
}
return key;
}
public string GetAnyName(bool isMale = true)
{
if (Chance.FiftyFifty)
{
Debug.LogError(TAG + "Getting Name from name data...");
return this.setNames.TryGetRandom().GetRandomName(isMale);
}
Debug.LogError(TAG + "Generating true random name...");
return GenerateTrueRandomName(3, isMale);
}
public static string NameToAdjective(string name)
{
return name + "\'s";
}
#region Syllable Generator
public string GenerateTrueRandomName(int maxSyllables = 3, bool isMale = true)
{
if (maxSyllables == 0)
return "[zero syllables]";
int syllableCount = Random.Range(1, maxSyllables + 1);
Debug.LogError(TAG + syllableCount + " syllables.");
int[] syllableLengths = GetSyllableLenghts(syllableCount);
bool[] syllablesTypes = GetSyllableTypes(syllableLengths);
string[] syllablesStrings = GetSyllableStrings(syllablesTypes, syllableLengths, isMale);
string name = ConcatanateSyllables(syllablesStrings);
return name;
}
public int[] GetSyllableLenghts(int syllableCount = 1)
{
int[] lenghts = new int[syllableCount];
for (int i = 0; i < lenghts.Length; i++)
{
lenghts[i] = Random.Range(2, 4);
Debug.LogError(lenghts[i].ToString());
}
return lenghts;
}
public bool[] GetSyllableTypes(int[] syllableLengths)
{
bool[] syllableTypes = new bool[syllableLengths.Length];
for (var i = 0; i < syllableLengths.Length; i++)
{
if (syllableLengths[i] < 3 || Chance.FiftyFifty)
{
syllableTypes[i] = true;
}
else
{
syllableTypes[i] = false;
}
Debug.LogError(syllableTypes[i].ToString());
}
return syllableTypes;
}
public string[] GetSyllableStrings(bool[] types, int[] lengths, bool isMale = true)
{
string[] syllableStrings = new string[types.Length];
for (var i = 0; i < types.Length; i++)
{
string result = string.Empty;
//if it's a first syllable
if (i == 0)
{
//Try for vowel on start
if (types[i])
{
if (types.Length > 1 && Chance.TryWithChance(0.3f))
{
result = this.vowels.TryGetRandom();
syllableStrings[i] = result;
continue;
}
result = this.consonantStart.TryGetRandom();
result += this.vowels.TryGetRandom();
syllableStrings[i] = result;
continue;
}
if (lengths[i] > 2)
{
result = this.consonantOpen.TryGetRandom();
result += this.vowels.TryGetRandom();
result += this.consonantClose.TryGetRandom();
syllableStrings[i] = result;
continue;
}
result = this.vowels.TryGetRandom();
result += this.consonantClose.TryGetRandom();
syllableStrings[i] = result;
continue;
}
//if it's last
else if (i == (types.Length - 1))
{
if (isMale)
result = (types[i - 1]) ? this.maleEndSyllablesOpen.TryGetRandom() : this.maleEndSyllablesClose.TryGetRandom();
else
result = (types[i - 1]) ? this.femaleEndSyllablesOpen.TryGetRandom() : this.femaleEndSyllablesClose.TryGetRandom();
syllableStrings[i] = result;
continue;
}
//middle syllables
if (types[i])
{
result = this.consonantOpen.TryGetRandom();
result += this.vowels.TryGetRandom();
syllableStrings[i] = result;
continue;
}
if (lengths[i] > 2)
{
result = this.consonantOpen.TryGetRandom();
result += this.vowels.TryGetRandom();
result += this.consonantClose.TryGetRandom();
syllableStrings[i] = result;
continue;
}
result = this.vowels.TryGetRandom();
result += this.consonantClose.TryGetRandom();
syllableStrings[i] = result;
continue;
}
foreach (var value in syllableStrings)
{
Debug.LogError(value);
}
return syllableStrings;
}
protected string ConcatanateSyllables(string[] syllables)
{
string result = string.Empty;
string left, right;
for (int i = 0; i < syllables.Length; ++i)
{
if (i > 0)
{
left = syllables[i - 1];
right = syllables[i];
if (left[left.Length - 1] == right[0])
{
right.PadRight(1);
}
}
result += syllables[i];
}
return result;
}
#endregion
public static string GetOrdinalNumber(int number)
{
int remainder = number % 10;
if (number < 10 || number > 20)
{
if (remainder == 1)
{
return number + "st";
}
else if (remainder == 2)
{
return number + "nd";
}
else if (remainder == 3)
{
return number + "rd";
}
else
{
return number + "th";
}
}
return number + "th";
}
#endregion
#region IInitializable
public bool Initialize()
{
if (!this.IsInitialized)
{
CreateRuntimeCollections();
this.IsInitialized = true;
return true;
}
return false;
}
public bool IsInitialized
{
get;
protected set;
}
#endregion
#region IO
public void Load()
{
LoadData(this);
this.IsInitialized = false;
}
public void Save()
{
SaveData(this);
}
public void Save(string path, string filename, bool scramble = false, bool encode = false, string extension = "")
{
this._path = path;
this._filename = filename;
this._scrable = scramble;
this._encode = encode;
this._extension = extension;
SaveData(this);
}
public void PostLoad()
{
foreach (var nameset in this.setNames)
{
for (int i = 0; i < nameset.prefixes.Count; i++)
{
nameset.prefixes[i] = nameset.prefixes[i].ToLower();
}
nameset.prefixes.Sort();
for (int i = 0; i < nameset.sufixes.Count; i++)
{
nameset.sufixes[i] = nameset.sufixes[i].ToLower();
}
nameset.sufixes.Sort();
}
//foreach (var titleset in this.setTitles)
//{
// for (int i = 0; i < titleset.adjectives.Count; i++)
// {
// titleset.adjectives[i] = titleset.adjectives[i].ToLower ();
// }
// titleset.adjectives.Sort ();
// for (int i = 0; i < titleset.genetives.Count; i++)
// {
// titleset.genetives[i] = titleset.genetives[i].ToLower ();
// }
// titleset.genetives.Sort ();
// for (int i = 0; i < titleset.objectivesNeutral.Count; i++)
// {
// titleset.objectivesNeutral[i] = titleset.objectivesNeutral[i].ToLower ();
// }
// titleset.objectivesNeutral.Sort ();
// for (int i = 0; i < titleset.objectivesNeutral.Count; i++)
// {
// titleset.objectivesNeutral[i] = titleset.objectivesNeutral[i].ToLower ();
// }
// titleset.objectivesNeutral.Sort ();
//}
// this.subjectiveCons.Sort();
// this.subjectivePros.Sort();
//this.subjectiveStory.Sort ();
//this.subjectiveGeolocation.Sort ();
}
public static void LoadData(SemanticData data)
{
DataUtility.ResourceLoad(data.ResourcePath, data, data._scrable, data._encode);
#if UNITY_EDITOR
data.PostLoad();
#endif
}
public static void SaveData(SemanticData data)
{
data.PreSave();
DataUtility.ResourceSave(data._path, data._filename, data, data._scrable, data._encode, data._extension);
}
public void PreSave()
{
DataUtility.OptimizeStringList(this.vowels);
DataUtility.OptimizeStringList(this.vowelPairs);
DataUtility.OptimizeStringList(this.consonantStart);
DataUtility.OptimizeStringList(this.consonantOpen);
DataUtility.OptimizeStringList(this.consonantClose);
DataUtility.OptimizeStringList(this.maleEndSyllablesOpen);
DataUtility.OptimizeStringList(this.maleEndSyllablesClose);
DataUtility.OptimizeStringList(this.femaleEndSyllablesOpen);
DataUtility.OptimizeStringList(this.femaleEndSyllablesClose);
this.setNames.Sort((x, y) => x.id.CompareTo(y.id));
foreach (var nameset in this.setNames)
{
DataUtility.OptimizeStringList(nameset.prefixes);
DataUtility.OptimizeStringList(nameset.sufixes);
DataUtility.OptimizeStringList(nameset.adjectiveKeys);
DataUtility.OptimizeStringList(nameset.presets);
DataUtility.OptimizeStringList(nameset.synonyms);
nameset.concatenationRules.Sort((x, y) => x.replace.CompareTo(y.replace));
}
this.setGrammars.Sort((x, y) => x.nounSingular.CompareTo(y.nounSingular));
foreach (var grammarset in this.setGrammars)
{
DataUtility.OptimizeString(grammarset.nounSingular);
DataUtility.OptimizeStringList(grammarset.nounPlurals);
DataUtility.OptimizeStringList(grammarset.adjectives);
}
}
#endregion
}
[System.Serializable]
public class Lexicon
{
#region DATA
//subjective
public string id;
/// <summary>
/// Synonyms for the subjective.
/// </summary>
public List<string> synonyms = new List<string>();
/// <summary>
/// Prefixes for concatenation with subjective (or synonym)
/// </summary>
public List<string> adjectiveKeys = new List<string>();
/// <summary>
/// The prefixes for pseudo names.
/// </summary>
public List<string> prefixes = new List<string>();
/// <summary>
/// The sufixes for pseudo names.
/// </summary>
public List<string> sufixes = new List<string>();
/// <summary>
/// The real name database.
/// </summary>
public List<string> names = new List<string>();
public List<string> presets = new List<string>();
/// <summary>
/// The concatenation rules for generating pseudo names.
/// </summary>
public List<GrammarRule> concatenationRules = new List<GrammarRule>();
/// <summary>
/// The gender conversion rules for generating pseudo names.
/// </summary>
public List<GrammarRule> genderConversionRules = new List<GrammarRule>();
/// <summary>
/// List of instruction sequences used for generating a title.
/// </summary>
public List<ConstructionSequence> titleConstructionRules = new List<ConstructionSequence>();
#endregion
#region API
/// <summary>
/// Gets eather a random real or pseudo name.
/// </summary>
/// <returns>The random real or pseudo name.</returns>
/// <param name="male">Should random name be male or female name.</param>
public string GetRandomName(bool male = true)
{
if (this.prefixes.Count + this.sufixes.Count == 0)
{
Debug.LogError("No prefixes or sufixes in name set " + this.id);
return GetName();
}
return GetName();
}
/// <summary>
/// Gets the real name from name set database.
/// </summary>
/// <returns>A real name from the database.</returns>
/// <param name="male">Should real name be male or female name.</param>
public string GetName()
{
if (this.names.Count != 0)
return this.names.TryGetRandom();
return "NULL(" + id + ")";
}
public string GenerateTitle(SemanticData data = null, InfluenceSet influenceSet = null)
{
return Lexicon.Construct(this, this.titleConstructionRules.TryGetRandom(), data, influenceSet);
}
#endregion
#region STATIC API
public static string Construct(Lexicon set, ConstructionSequence rule, SemanticData data = null, InfluenceSet influenceSet = null)
{
string result = string.Empty;
bool hasData = data != null;
bool hasInfluenceSet = influenceSet != null;
foreach (var instruction in rule.instructions)
{
switch (instruction)
{
case ConstructionInstruction.DETERMINER:
result += "the ";
break;
case ConstructionInstruction.SEPARATOR:
result += " ";
break;
case ConstructionInstruction.NAME_FULL:
result += (hasInfluenceSet && Chance.FiftyFifty && influenceSet.HasName) ? influenceSet.Name : set.names.TryGetRandom();
break;
case ConstructionInstruction.NAME_PARTIAL_PREFIX:
result += hasInfluenceSet && Chance.FiftyFifty && influenceSet.HasPrefix ? influenceSet.Prefix : set.prefixes.TryGetRandom();
break;
case ConstructionInstruction.NEME_PARTIAL_SUFIX:
result += hasInfluenceSet && Chance.FiftyFifty && influenceSet.HasSufix ? influenceSet.Sufix : set.sufixes.TryGetRandom();
break;
case ConstructionInstruction.SUBJECTIVE_ORIGINAL_OR_SYNONYM:
result += hasInfluenceSet && Chance.FiftyFifty && influenceSet.HasSynonym ? influenceSet.Synonym : set.synonyms.TryGetRandom();
break;
case ConstructionInstruction.ADJECTIVE:
//Consturcts adjective or fallsback to singular noun
result += (hasData) ?
data.GetAdjective(hasInfluenceSet && Chance.FiftyFifty && influenceSet.HasAdjectiveKey ?
influenceSet.AdjectiveKey : set.adjectiveKeys.TryGetRandom())
: set.adjectiveKeys.TryGetRandom();
break;
case ConstructionInstruction.GENETIVE:
//Using only singular noun
result += (hasInfluenceSet && Chance.FiftyFifty && influenceSet.HasAdjectiveKey) ? influenceSet.AdjectiveKey : set.adjectiveKeys.TryGetRandom();
break;
case ConstructionInstruction.PRESET:
result += hasInfluenceSet && Chance.FiftyFifty && influenceSet.HasPreset ? influenceSet.Preset : set.presets.TryGetRandom();
break;
case ConstructionInstruction.PREPOSITION_OF:
result += "of ";
break;
case ConstructionInstruction.POSSESSIVE_APOSTROPHE:
result += "\'s";
break;
}
}
foreach (var concatenationRule in set.concatenationRules)
{
result = result.Replace(concatenationRule.replace, concatenationRule.with);
}
return result;
}
#endregion
}
/// <summary>
/// Sum of all influences.
/// TODO 20180829: Use other lexicons directly as influence sets.
/// </summary>
public class InfluenceSet
{
public InfluenceSet() { this._nameSets = new List<Lexicon>(); }
public InfluenceSet(params Lexicon[] args) { this._nameSets = new List<Lexicon>(args); }
public InfluenceSet(List<Lexicon> namesets) { this._nameSets = new List<Lexicon>(namesets); }
protected List<Lexicon> _nameSets;
#region API
public void AddNameSet(Lexicon nameset)
{
if (!this._nameSets.Contains(nameset))
{
this._nameSets.Add(nameset);
}
}
public bool RemoveNameSet(Lexicon nameset)
{
return this._nameSets.Remove(nameset);
}
public string Synonym
{
get
{
Lexicon set = null;
do
{
set = this._nameSets.TryGetRandom();
}
while (set.synonyms.Count == 0);
return set.synonyms.TryGetRandom();
}
}
public bool HasSynonym
{
get
{
foreach (var nameset in this._nameSets)
{
if (nameset.synonyms.Count > 0)
return true;
}
return false;
}
}
public string AdjectiveKey
{
get
{
Lexicon set = null;
do
{
set = this._nameSets.TryGetRandom();
}
while (set.adjectiveKeys.Count == 0);
return set.adjectiveKeys.TryGetRandom();
}
}
public bool HasAdjectiveKey
{
get
{
foreach (var nameset in this._nameSets)
{
if (nameset.adjectiveKeys.Count > 0)
return true;
}
return false;
}
}
public string Prefix
{
get
{
Lexicon set = null;
do
{
set = this._nameSets.TryGetRandom();
}
while (set.prefixes.Count == 0);
return set.prefixes.TryGetRandom();
}
}
public bool HasPrefix
{
get
{
foreach (var nameset in this._nameSets)
{
if (nameset.prefixes.Count > 0)
return true;
}
return false;
}
}
public string Sufix
{
get
{
Lexicon set = null;
do
{
set = this._nameSets.TryGetRandom();
}
while (set.sufixes.Count == 0);
return set.sufixes.TryGetRandom();
}
}
public bool HasSufix
{
get
{
foreach (var nameset in this._nameSets)
{
if (nameset.sufixes.Count > 0)
return true;
}
return false;
}
}
public string Name
{
get
{
Lexicon set = null;
do
{
set = this._nameSets.TryGetRandom();
}
while (set.names.Count == 0);
return set.names.TryGetRandom();
}
}
public bool HasName
{
get
{
foreach (var nameset in this._nameSets)
{
if (nameset.names.Count > 0)
return true;
}
return false;
}
}
public string Preset
{
get
{
Lexicon set = null;
do
{
set = this._nameSets.TryGetRandom();
}
while (set.presets.Count == 0);
return set.presets.TryGetRandom();
}
}
public bool HasPreset
{
get
{
foreach (var nameset in this._nameSets)
{
if (nameset.presets.Count > 0)
return true;
}
return false;
}
}
#endregion
}
//[System.Serializable]
//public class TitleSet
//{
// public string id;
// public string opposingId;
// public List<string> adjectives = new List<string> ();
// public List<string> objectivePros = new List<string> ();
// public List<string> objectivesNeutral = new List<string> ();
// public List<string> subjectivesPros = new List<string> ();
// public List<string> subjectivesCons = new List<string> ();
// public List<string> subjectivesNeutral = new List<string> ();
// public List<string> genetives = new List<string> ();
//}
[System.Serializable]
public class GrammarSet
{
//also used as id
public string nounSingular;
public bool useDeterminer = true;
public List<string> nounPlurals;
public List<string> adjectives;
}
[System.Serializable]
public class GrammarRule
{
//public enum Type : int
//{
// RemoveLeft,
// RemoveRight,
// ReplaceLeft,
// ReplaceRight,
// Insert,
// Append,
// MergeInto,
//}
//public char left;
//public char right;
//public string affix;
//public Type type;
public string replace, with;
}
public enum ConstructionInstruction
{
POSSESSIVE_APOSTROPHE = -3,
PREPOSITION_OF = -2,
DETERMINER = -1,
SEPARATOR = 0,
NAME_FULL = 1,
//NAME_FULL_FEMALE,
NAME_PARTIAL_PREFIX = 3,
NEME_PARTIAL_SUFIX = 4,
//ADJECTIVE_PREFIX = 5,
//SUBJECTIVE_ORIGINAL = 6,
SUBJECTIVE_ORIGINAL_OR_SYNONYM = 7,
ADJECTIVE = 8,
GENETIVE = 9,
PRESET = 10,
}
[System.Serializable]
public class ConstructionSequence
{
public string name;
public ConstructionInstruction[] instructions;
#region TEMPLATES
public static ConstructionSequence PresetRule
{
get
{
return new ConstructionSequence
{
name = "Preset",
instructions = new ConstructionInstruction[] { ConstructionInstruction.PRESET }
};
}
}
public static ConstructionSequence AdjectivePrefixSynonymRule
{
get
{
return new ConstructionSequence
{
name = "AdjectivePrefix-Synonym",
instructions = new ConstructionInstruction[] { ConstructionInstruction.ADJECTIVE, ConstructionInstruction.SUBJECTIVE_ORIGINAL_OR_SYNONYM }
};
}
}
public static ConstructionSequence AdjectiveSynonymRule
{
get
{
return new ConstructionSequence
{
name = "Adjective-Synonym",
instructions = new ConstructionInstruction[] { ConstructionInstruction.ADJECTIVE, ConstructionInstruction.SEPARATOR, ConstructionInstruction.SUBJECTIVE_ORIGINAL_OR_SYNONYM }
};
}
}
public static ConstructionSequence SynonymGenetiveRule
{
get
{
return new ConstructionSequence
{
name = "Synonym-Genetive",
instructions = new ConstructionInstruction[] {
ConstructionInstruction.SUBJECTIVE_ORIGINAL_OR_SYNONYM,
ConstructionInstruction.SEPARATOR,
ConstructionInstruction.PREPOSITION_OF,
ConstructionInstruction.DETERMINER,
ConstructionInstruction.GENETIVE
}
};
}
}
public static ConstructionSequence SynonymAdjectiveRule
{
get
{
return new ConstructionSequence
{
name = "Synonym-Adjective",
instructions = new ConstructionInstruction[] {
ConstructionInstruction.SUBJECTIVE_ORIGINAL_OR_SYNONYM,
ConstructionInstruction.SEPARATOR,
ConstructionInstruction.PREPOSITION_OF,
ConstructionInstruction.DETERMINER,
ConstructionInstruction.ADJECTIVE
}
};
}
}
public static ConstructionSequence GenetiveSynonymRule
{
get
{
return new ConstructionSequence
{
name = "Synonym-Adjective",
instructions = new ConstructionInstruction[] {
ConstructionInstruction.GENETIVE,
ConstructionInstruction.POSSESSIVE_APOSTROPHE,
ConstructionInstruction.SEPARATOR,
ConstructionInstruction.SUBJECTIVE_ORIGINAL_OR_SYNONYM,
}
};
}
}
#endregion
}
[System.Serializable]
public class SemanticConnection
{
public string noun;
public List<string> adjectives;
}
}<file_sep>/UI/WorldSpaceUI/WSUIBar.cs
namespace PofyTools
{
public class WSUIBar : WSUIFollow
{
}
}<file_sep>/Core/Mono/Socketables/Socket.cs
namespace PofyTools
{
using Extensions;
using System.Collections.Generic;
using UnityEngine;
public class Socket : MonoBehaviour, ITransformable, IInitializable
{
public enum Action : int
{
// default
None = 0,
// equip item to owner
Equip = 1,
// unequip item from owner
Unequip = 2,
// unequip all items
Empty = 3,
//TODO: Add socket to owner
Add = 4,
//TODO Remove socket from owner
Remove = 5,
}
[Tooltip("Must be unique for every socket on a ISocketable")]
public string id;
public int IdHash { get; protected set; }
public ISocketed owner;
public int itemLimit = 1;
//public bool initializeOnStart = false;
[Header("Offsets")]
public Vector3 socketPositionOffset = Vector3.zero;
public Vector3 socketRotationOffset = Vector3.zero;
public Vector3 socketScaleOffset = Vector3.one;
protected List<ISocketable> _items = new List<ISocketable>();
public List<ISocketable> Items { get { return this._items; } }
public bool IsEmpty { get { return this._items.Count == 0; } }
public int ItemCount { get { return this._items.Count; } }
/// <summary>
/// Removes all items from socket with provided approval
/// </summary>
/// <param name="approvedBy"></param>
/// <returns></returns>
public bool Empty(SocketActionRequest.SocketingParty approvedBy = SocketActionRequest.SocketingParty.None)
{
for (int i = this._items.Count - 1;i >= 0;--i)
{
var item = this._items[i];
SocketActionRequest.TryUnequipItemFromOwner(this.owner, item, this.id, approvedBy);
}
return this._items.Count < 0;
}
/// <summary>
/// Add socketable to this socket and call equip callbacks on item and owner.
/// </summary>
/// <param name="request"></param>
/// <param name="inPlace"></param>
public void AddItem(SocketActionRequest request, bool inPlace = false)
{
this._items.Add(request.Item);
request.Item.Equip(request, inPlace);
request.Owner.OnItemEquip(request);
}
/// <summary>
/// Removes item provided in request struct.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public bool RemoveItem(SocketActionRequest request)
{
if (this._items.Remove(request.Item))
{
request.Item.Unequip(request);
request.Owner.OnItemUnequip(request);
return true;
}
return false;
}
#region IInitializable implementation
public bool Initialize()
{
if (!this._isInitialized)
{
if (string.IsNullOrEmpty(this.id))
{
Debug.LogError(ToString() + " ERROR: NO ID!", this);
return false;
}
this.IdHash = Animator.StringToHash(this.id);
if (this.owner == null)
{
//this.owner = GetComponentInParent<ISocketed>();
Debug.LogError(ToString() + " ERROR: OWNER CAN'T BE NULL!", this);
return false;
}
if (this.owner.AddSocket(this))
{
ISocketable item = null;
SocketActionRequest request = default(SocketActionRequest);
foreach (Transform child in this.transform)
{
item = child.GetComponent<ISocketable>();
if (item != null)
{
item.Initialize();
request = new SocketActionRequest(action: Socket.Action.Equip, owner: this.owner, item: item, socket: this);
AddItem(request, true);
}
}
}
else
{
Debug.LogError(ToString() + " ERROR: ID MUST BE UNIQUE", this);
}
this._isInitialized = true;
return true;
}
return false;
}
protected bool _isInitialized = false;
public bool IsInitialized { get { return this._isInitialized; } }
#endregion
//No whitespaces
private void OnValidate()
{
this.id = (string.IsNullOrEmpty(this.id)) ? this.id : this.id.Trim();
}
}
public struct SocketActionRequest
{
public const string TAG = "<color=green><b>SocketActionRequest:</b></color> ";
public enum SocketingParty : int
{
None = 0,
SocketOwner = 1 << 0,
Item = 1 << 1
}
#region Properties
public SocketActionRequest.SocketingParty ApprovedBy { get; private set; }
public Socket.Action Action { get; private set; }
public ISocketable Item { get; private set; }
public ISocketed Owner { get; private set; }
public string Id { get; private set; }
private Socket _socket;
public Socket Socket
{
get
{
if (this._socket == null)
{
if ((int)this.Action <= 2)
this._socket = this.Owner.GetSocket(this.Id);
if (this._socket == null)
Debug.LogWarning(TAG + "No socket found for the id: " + this.Id);
}
return this._socket;
}
}
#endregion
#region Instance Methods
public bool AprovedByAll
{
get
{
return this.ApprovedBy.HasFlag(SocketingParty.SocketOwner) && this.ApprovedBy.HasFlag(SocketingParty.Item);
}
}
public void ApproveByOwner(ISocketed owner)
{
if (owner == this.Owner)
this.ApprovedBy = this.ApprovedBy.Add(SocketingParty.SocketOwner);
}
public void ApproveByItem(ISocketable item)
{
if (item == this.Item)
this.ApprovedBy = this.ApprovedBy.Add(SocketingParty.Item);
}
public void RevokeApproval()
{
this.ApprovedBy = SocketingParty.None;
}
public void ForceApproval()
{
this.ApprovedBy = SocketActionRequest.All;
}
#endregion
#region Constructor
public SocketActionRequest(Socket.Action action = Socket.Action.None, ISocketed owner = null, ISocketable item = null, string id = "", SocketingParty approvedBy = SocketingParty.None, Socket socket = null)
{
this.Action = action;
this.Owner = owner;
this.Item = item;
this.Id = id;
this.ApprovedBy = approvedBy;
this._socket = socket;
}
// public SocketActionRequest(Socket socket) : this(Socket.Action.None,socket.owner,null,socket.id,ApprovedBy.None)
#endregion
#region Object
public override string ToString()
{
return string.Format("[SocketActionRequest: approvedBy={0}, action={1}, item={2}, owner={3}, id={4}, socket={5}, isAprovedByAll={6}]", this.ApprovedBy, this.Action, this.Item, this.Owner, this.Id, this.Socket, this.AprovedByAll);
}
#endregion
#region API Methods
public static SocketActionRequest TryEquipItemToOwner(ISocketed owner, ISocketable item, string id = "", SocketingParty approvedBy = SocketingParty.None)
{
SocketActionRequest request = new SocketActionRequest(action: Socket.Action.Equip, owner: owner, item: item, id: id, approvedBy: approvedBy);
return ResolveRequest(request);
}
public static SocketActionRequest TryUnequipItemFromOwner(ISocketed owner, ISocketable item, string id = "", SocketingParty approvedBy = SocketingParty.None)
{
SocketActionRequest request = new SocketActionRequest(action: Socket.Action.Unequip, owner: owner, item: item, id: id, approvedBy: approvedBy);
return ResolveRequest(request);
}
public static SocketActionRequest TryEmptySocket(Socket socket, SocketingParty approvedBy = SocketingParty.None)
{
SocketActionRequest request = new SocketActionRequest(action: Socket.Action.Empty, owner: socket.owner, item: null, id: socket.id, approvedBy: approvedBy);
return ResolveRequest(request);
}
/// <summary>
/// Gets the approval from socket owner first and socketable item second. Returns request with resolved approvedBy field.
/// </summary>
/// <returns>Resolved request.</returns>
/// <param name="request">Request.</param>
public static SocketActionRequest GetApproval(SocketActionRequest request)
{
if (!request.AprovedByAll)
{
if (!request.ApprovedBy.HasFlag(SocketingParty.SocketOwner))
request = request.Owner.ResolveRequest(request);
if (!request.ApprovedBy.HasFlag(SocketingParty.Item))
request = request.Item.ResolveRequest(request);
}
return request;
}
/// <summary>
/// Resolves the request. Resulting in socketing an item to it's owner's socket or ignoring the action.
/// </summary>
/// <returns>The request.</returns>
/// <param name="request">Request.</param>
public static SocketActionRequest ResolveRequest(SocketActionRequest request)
{
Socket socket = null;
if (request.Action == Socket.Action.None)
{
return request;
}
if (request.Action == Socket.Action.Empty)
{
request.Socket.Empty(request.ApprovedBy);
return request;
}
if (request.Action == Socket.Action.Add || request.Action == Socket.Action.Remove)
{
if (!request.ApprovedBy.HasFlag(SocketActionRequest.SocketingParty.SocketOwner))
request = request.Owner.ResolveRequest(request);
if (request.ApprovedBy.HasFlag(SocketActionRequest.SocketingParty.SocketOwner))
{
if (request.Action == Socket.Action.Add)
request.Owner.AddSocket(request.Socket);
else
request.Owner.RemoveSocket(request.Socket);
}
return request;
}
request = SocketActionRequest.GetApproval(request);
if (request.AprovedByAll)
{
if (request.Action == Socket.Action.Equip)
{
socket = request.Socket;
socket.AddItem(request, false);
return request;
}
if (request.Action == Socket.Action.Unequip)
{
socket = request.Item.Socket;
socket.RemoveItem(request);
return request;
}
}
Debug.LogWarning(TAG + request.ToString() + "was rejected!");
return request;
}
public static SocketingParty All { get { return SocketingParty.SocketOwner | SocketingParty.Item; } }
#endregion
}
public interface ISocketed : ITransformable, IInitializable, ISocketActionRequestResolver // Character
{
bool AddSocket(Socket socket);
bool RemoveSocket(Socket socket);
Socket GetSocket(string id);
Socket GetSocket(int hash);
bool UnequipAll(SocketActionRequest.SocketingParty approvedBy = SocketActionRequest.SocketingParty.None);
void OnItemEquip(SocketActionRequest request);
void OnItemUnequip(SocketActionRequest request);
}
public interface ISocketable : ITransformable, IInitializable, ISocketActionRequestResolver// Item
{
Socket Socket
{
get;
set;
}
bool IsEquipped
{
get;
}
void Equip(SocketActionRequest request, bool inPlace = false);
void Unequip(SocketActionRequest request);
}
public interface ISocketActionRequestResolver
{
SocketActionRequest ResolveRequest(SocketActionRequest request);
}
public delegate void SocketActionRequestDelegate(SocketActionRequest request);
public delegate void SocketableDelegate(ISocketable socketable);
public delegate void SocketedDelegate(ISocketed socketed);
}<file_sep>/UI/WorldSpaceUI/WSUIBase.cs
using UnityEngine;
namespace PofyTools
{
/// <summary>
/// Base World Space UI Behaviour:
/// Distance Fade From PlayerCharacter
/// Look at Character Camera
/// </summary>
[RequireComponent(typeof(Canvas)), RequireComponent(typeof(CanvasGroup))]
public class WSUIBase : MonoBehaviour
{
[SerializeField] protected CanvasGroup _canvasGroup;
[SerializeField] protected RectTransform _rectTransform;
#region Managable Element
public virtual bool UpdateElement(WSUIManager.UpdateData data)
{
//billboard
this._rectTransform.rotation = Quaternion.LookRotation(this._rectTransform.position - data.cameraPosition, data.cameraUp);
//fade
float playerDistanceSqr = (this._rectTransform.position - data.playerPosition).sqrMagnitude;
float cameraDistanceSqr = (this._rectTransform.position - data.cameraPosition).sqrMagnitude;
this._canvasGroup.alpha = (1 - WSUIManager.Instance.Data.fadeDistanceSqrRange.Percentage(playerDistanceSqr)) * WSUIManager.Instance.Data.fadeNearClipRange.Percentage(cameraDistanceSqr);
return false;
}
#endregion
#region IPoolable
protected WSUIManager.PoolData _poolData;
public bool IsActive { get; protected set; }
/// <summary>
/// Sets element's pool data. Elements without stack reference will be destoryed when Free is called.
/// </summary>
/// <param name="data"></param>
public void SetPoolData(WSUIManager.PoolData data)
{
this._poolData = data;
}
/// <summary>
/// Active instances are visible in the scene and updated by the manager
/// </summary>
public virtual void Activate()
{
if (!this.IsActive)
{
this.gameObject.SetActive(true);
this.IsActive = true;
//Add to manager's update stack
if (this._poolData.manager != null)
this._poolData.manager.AddElement(this);
else
Debug.LogError("Element has no manager!");
}
}
/// <summary>
/// Deactivated instances are removed from the manager
/// </summary>
public virtual void Deactivate()
{
if (this.IsActive)
{
this.gameObject.SetActive(false);
this.IsActive = false;
}
}
/// <summary>
/// Frees or destorys element. Needs to be inactive to be freed.
/// </summary>
public virtual void Free()
{
if (this.IsActive)
{
Debug.LogError("Can not free active UI element!");
return;
}
this.gameObject.SetActive(false);
WSUIManager.PushOrDestroy(this, this._poolData.stack, !this._poolData.poolable ? WSUIManager.PushResult.Destroyed : WSUIManager.PushResult.None); //this._data.stack.Push(this);
}
#endregion
}
}<file_sep>/UI/PopUp.cs
using UnityEngine;
using System.Collections;
namespace PofyTools
{
public class PopUp : GameActor
{
public bool onStart = false;
public AnimationCurve curve;
public float duration;
private float _timer;
public bool repeat;
// Use this for initialization
protected override void Start()
{
base.Start();
if (this.onStart)
{
EnterPopUpState();
}
}
public void EnterPopUpState()
{
this._timer = this.duration;
AddState(this.PopUpState);
}
void PopUpState()
{
this._timer -= Time.unscaledDeltaTime;
if (this._timer <= 0)
this._timer = 0;
float normalizedTime = 1 - (this._timer / this.duration);
float scaleFactor = curve.Evaluate(normalizedTime);
this.transform.localScale = new Vector3(scaleFactor, scaleFactor, scaleFactor);
if (this._timer <= 0)
ExitPopUpState();
}
void ExitPopUpState()
{
if (repeat)
{
EnterPopUpState();
}
else
{
RemoveAllStates();
}
}
}
}<file_sep>/UI/WorldSpaceUI/WSUIPositionText.cs
using TMPro;
namespace PofyTools
{
public class WSUIPositionText : WSUIBase
{
public TextMeshProUGUI text;
}
}
<file_sep>/CategoryGraph/Editor/CategoryGraphEditor.cs
using UnityEngine;
using XNodeEditor;
namespace PofyTools
{
[CustomNodeGraphEditor(typeof(CategoryGraph))]
public class CategoryGraphEditor : NodeGraphEditor
{
private CategoryGraph _catGraph;
/// <summary>
/// Overriding GetNodeMenuName lets you control if and how nodes are categorized.
/// In this example we are sorting out all node types that are not in the XNode.Examples namespace.
/// </summary>
public override string GetNodeMenuName(System.Type type)
{
if (this._catGraph == null)
this._catGraph = this.target as CategoryGraph;
if (type.Namespace == "PofyTools")
{
//if (type == typeof(CategorySetNode) && this._catGraph.HasSetNode)
// return null;
return base.GetNodeMenuName(type).Replace("Pofy Tools/", "");
}
else
return null;
}
public override void OnGUI()
{
if (this._catGraph == null)
this._catGraph = this.target as CategoryGraph;
//if (this._catGraph.HasSetNode)
//{
// this._catGraph.SetNode.position = NodeEditorWindow.current.WindowToGridPosition(Vector2.zero);
//}
base.OnGUI();
}
}
}<file_sep>/Core/DelayManager.cs
namespace PofyTools
{
public class DelayManager
{
public const int ELEMENT_LIMIT = 128;
private static DelayManager _instance = null;
public static DelayManager Instance
{
get
{
if (_instance == null)
_instance = new DelayManager();
return _instance;
}
}
#region Static API
public static void Purge()
{
_instance = null;
}
public static int DelayAction(VoidDelegate method, float delay, object instance)
{
return Instance.AddElement(method, delay, instance);
}
public static void StopAt(int index)
{
if (index >= 0)
_instance._elements[index] = default;
}
public static void Tick(float deltaTime)
{
Instance.Update(deltaTime);
}
#endregion
public struct Description
{
public object instance;
public float duration;
public VoidDelegate callback;
public bool IsActive { get; set; }
public bool Update(float deltaTime)
{
this.duration -= deltaTime;
return this.duration <= 0f;
}
}
private Description[] _elements = new Description[ELEMENT_LIMIT];
private int AddElement(VoidDelegate method, float delay, object instance)
{
for (int i = 0; i < this._elements.Length; ++i)
{
if (this._elements[i].callback == null)
{
var desc = new Description()
{
instance = instance,
duration = delay,
callback = method
};
desc.IsActive = true;
this._elements[i] = desc;
return i;
}
}
return -1;
}
private void Update(float deltaTime)
{
for (int i = 0; i < this._elements.Length; ++i)
{
if (this._elements[i].callback != null)
{
if (this._elements[i].Update(deltaTime))
{
if (this._elements[i].instance != null)
this._elements[i].callback.Invoke();
this._elements[i] = default;
}
}
}
}
}
}<file_sep>/Distribution/NameGenerator/Demo/NameGeneratorTest.cs
using Extensions;
using PofyTools;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class NameGeneratorTest : MonoBehaviour
{
[Header("Resources")]
public Button buttonPrefab;
[Header("Dialog")]
public Dialog dialog;
[Header("UI")]
public RectTransform availableSets, selectedSets;
public Dropdown dropdownNamesets;
public Text label;
public Text input;
[Header("Data")]
public SemanticData data;
[Header("Influncer")]
public Lexicon influencerOne;
public Lexicon influencerTwo;
private InfluenceSet _influenceSet;
void Awake()
{
Load();
this.data.Initialize();
this._influenceSet = new InfluenceSet(this.influencerOne, influencerTwo);
this.dropdownNamesets.onValueChanged.AddListener(this.OnDropdownValueChanged);
OnDropdownValueChanged(0);
//RefeshAll ();
}
public void AddNamset()
{
if (!string.IsNullOrEmpty(this.input.text) && this.data.GetNameSet(this.input.text) == null)
{
var ns = new Lexicon();
ns.id = this.input.text;
this.data.setNames.Add(ns);
ns.titleConstructionRules.Add(ConstructionSequence.PresetRule);
ns.titleConstructionRules.Add(ConstructionSequence.AdjectivePrefixSynonymRule);
ns.titleConstructionRules.Add(ConstructionSequence.AdjectiveSynonymRule);
ns.titleConstructionRules.Add(ConstructionSequence.SynonymAdjectiveRule);
ns.titleConstructionRules.Add(ConstructionSequence.SynonymGenetiveRule);
//TODO: Add name instrucitons
this._currentNameSet = ns;
Save();
RefeshAll();
}
}
#region Synonyms
[Header("Synonym Editor")]
public RectTransform synonyms;
public Text synonymInput;
public void AddSynonym()
{
if (!string.IsNullOrEmpty(this.synonymInput.text) && !this._currentNameSet.synonyms.Contains(this.synonymInput.text))
{
this._currentNameSet.synonyms.Add(this.synonymInput.text);
Save();
RefeshAll();
}
}
#endregion
#region Presets
[Header("Presets Editor")]
public RectTransform presets;
public Text presetsInput;
public void AddPreset()
{
if (!string.IsNullOrEmpty(this.presetsInput.text) && !this._currentNameSet.presets.Contains(this.presetsInput.text))
{
this._currentNameSet.presets.Add(this.presetsInput.text);
Save();
RefeshAll();
}
}
#endregion
#region Names
public RectTransform namePrefix, nameSufix, nameFull;
#endregion
void OnDropdownValueChanged(int index)
{
this._currentNameSet = this.data.setNames[index];
RefeshAll();
}
private Lexicon _currentNameSet;
#region API
void RefeshAll()
{
ClearAll();
PopulateAll();
}
void ClearAll()
{
this.availableSets.ClearChildren();
this.selectedSets.ClearChildren();
this.synonyms.ClearChildren();
this.presets.ClearChildren();
this.nameFull.ClearChildren();
this.namePrefix.ClearChildren();
this.nameSufix.ClearChildren();
this.dropdownNamesets.ClearOptions();
}
void PopulateAll()
{
List<Dropdown.OptionData> options = new List<Dropdown.OptionData>();
foreach (var nameset in this.data.setNames)
{
options.Add(new Dropdown.OptionData(nameset.id));
}
this.dropdownNamesets.AddOptions(options);
this.dropdownNamesets.value = (this._currentNameSet != null) ? this.data.setNames.IndexOf(this._currentNameSet) : 0;
this.dropdownNamesets.RefreshShownValue();
List<string> notUsing = new List<string>(this.data.GetAllGrammarIds());
foreach (var term in this._currentNameSet.adjectiveKeys)
{
notUsing.Remove(term);
}
foreach (var term in notUsing)
{
Button button = Instantiate<Button>(this.buttonPrefab);
button.image.rectTransform.SetParent(this.availableSets, false);
button.GetComponentInChildren<Text>().text = term;
button.onClick.AddListener(delegate () { this._currentNameSet.adjectiveKeys.Add(term); Save(); RefeshAll(); });
}
//Adjective Keys (Grammer Set)
foreach (var term in this._currentNameSet.adjectiveKeys)
{
Button button = Instantiate<Button>(this.buttonPrefab);
button.image.rectTransform.SetParent(this.selectedSets, false);
button.GetComponentInChildren<Text>().text = term;
button.onClick.AddListener(delegate () { this._currentNameSet.adjectiveKeys.Remove(term); Save(); RefeshAll(); });
}
//Synonyms
foreach (var synonym in this._currentNameSet.synonyms)
{
Button button = Instantiate<Button>(this.buttonPrefab);
button.image.rectTransform.SetParent(this.synonyms, false);
button.GetComponentInChildren<Text>().text = synonym;
button.onClick.AddListener(delegate () { AskRemove(synonym, this._currentNameSet.synonyms); });
}
//Title Presets
foreach (var preset in this._currentNameSet.presets)
{
Button button = Instantiate<Button>(this.buttonPrefab);
button.image.rectTransform.SetParent(this.presets, false);
button.GetComponentInChildren<Text>().text = preset;
button.onClick.AddListener(delegate () { AskRemove(preset, this._currentNameSet.presets); });
}
//Name Prefix
foreach (var namePrefix in this._currentNameSet.prefixes)
{
Button button = Instantiate<Button>(this.buttonPrefab);
button.image.rectTransform.SetParent(this.namePrefix, false);
button.GetComponentInChildren<Text>().text = namePrefix;
button.onClick.AddListener(delegate () { AskRemove(namePrefix, this._currentNameSet.prefixes); });
}
//Name Sufix
foreach (var nameSufix in this._currentNameSet.sufixes)
{
Button button = Instantiate<Button>(this.buttonPrefab);
button.image.rectTransform.SetParent(this.nameSufix, false);
button.GetComponentInChildren<Text>().text = nameSufix;
button.onClick.AddListener(delegate () { AskRemove(nameSufix, this._currentNameSet.sufixes); });
}
//Full Names
foreach (var nameFull in this._currentNameSet.names)
{
Button button = Instantiate<Button>(this.buttonPrefab);
button.image.rectTransform.SetParent(this.nameFull, false);
button.GetComponentInChildren<Text>().text = nameFull;
button.onClick.AddListener(delegate () { AskRemove(nameFull, this._currentNameSet.names); });
}
}
public void AskRemove(string key, List<string> list)
{
this._cacheString = key;
this._cacheList = list;
this.dialog.ShowDialog("Remove", "Are you sure you want to delete \"" + key + "\"?", this.RemoveChached);
}
private string _cacheString;
private List<string> _cacheList;
public void RemoveChached()
{
RemoveFrom(this._cacheString, this._cacheList);
}
public void RemoveFrom(string toRemove, List<string> from)
{
from.Remove(toRemove);
Save();
RefeshAll();
}
#endregion
public void GenerateTitle()
{
if (this._currentNameSet != null)
{
this.label.text = this._currentNameSet.GenerateTitle(this.data);
}
}
public void SavePreset()
{
if (this._currentNameSet != null)
{
this._currentNameSet.presets.Add(this.label.text);
Save();
RefeshAll();
}
}
#region Name
public void GenerateTrueRandom()
{
this.label.text = this.data.GenerateTrueRandomName().ToTitle();
}
public void GetAnyName()
{
this.label.text = this.data.GetAnyName(Chance.FiftyFifty).ToTitle();
}
#endregion
#region IO
[ContextMenu("Save")]
public void Save()
{
//GameDefinitions.Semantics = this.data;
//GameDefinitions.BuildAll();
}
[ContextMenu("Load")]
public void Load()
{
//GameDefinitions.Init();
//this.data = GameDefinitions.Semantics;
}
#endregion
}
<file_sep>/Data/Editor/LocalizationDataAddLanguagePopup.cs
namespace PofyTools
{
#pragma warning disable 219
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class LocalizationDataAddLanguagePopup : PopupWindowContent
{
private string _newLanguage = "XX";
private string _info = "New language ALPHA2 kek has to unique and two characters long.";
private MessageType _infoType = MessageType.Info;
private EditorWindow _target;
// public static void Init()
// {
// LocalizationDataAddEntryPopup window = ScriptableObject.CreateInstance<LocalizationDataAddEntryPopup>();
// //window.position = new Rect(Screen.width / 2, Screen.height / 2, 250, 150);
// window.position = new Rect(EditorWindow.focusedWindow.position.x, EditorWindow.focusedWindow.position.y, 250, 150);
//
// window._target = EditorWindow.focusedWindow;
// if (!(window._target is LocalizationDataEditor))
// window._target = null;
//
// window.ShowPopup();
// }
public override Vector2 GetWindowSize()
{
return new Vector2(500, 700);
}
private Localization.LanguageData _dataToDelete = null;
private Vector2 _scrollPos;
public override void OnGUI(Rect rect)
{
EditorGUILayout.LabelField("Add New Language", EditorStyles.wordWrappedLabel);
EditorGUILayout.Separator();
EditorGUILayout.LabelField("Enter new language ALPHA2 key:");
this._newLanguage = EditorGUILayout.TextField(this._newLanguage);
this._newLanguage.ToUpper();
if (this._newLanguage.Length > 2)
{
this._newLanguage = this._newLanguage.Substring(0, 2);
}
EditorGUILayout.Separator();
EditorGUILayout.HelpBox(this._info, this._infoType);
EditorGUILayout.BeginHorizontal();
this._scrollPos = EditorGUILayout.BeginScrollView(this._scrollPos);
foreach (var data in Localization.GetData())
{
if (GUILayout.Button("x " + data.languageKey))
{
this._dataToDelete = data;
}
}
EditorGUILayout.EndScrollView();
if (this._dataToDelete != null)
{
if (EditorUtility.DisplayDialog("Delete Language Data", "Ae you sure you want to delete data for \"" + this._dataToDelete + "\". This action can not be undone?", "Delete", "Cancel"))
{
Localization.RemoveLanguageData(this._dataToDelete.languageKey);
Localization.SaveData();
AssetDatabase.Refresh();
}
}
if (GUILayout.Button("Add"))
{
this.AddLanguage();
}
EditorGUILayout.EndHorizontal();
}
void AddLanguage()
{
var allData = Localization.GetData();
var upper = this._newLanguage.ToUpper();
if (Localization.HasLanguage(upper))
{
this._info = "The language key \"" + upper + "\" already present in localization data. Choose different language key.";
this._infoType = MessageType.Error;
}
else
{
Localization.AddLanguage(upper);
this._info = "The language key \"" + upper + "\" successfully added!";
this._infoType = MessageType.Info;
Localization.SaveData();
AssetDatabase.Refresh();
}
}
}
}<file_sep>/UI/WorldSpaceUI/WSUIManager.cs
using System.Collections.Generic;
using UnityEngine;
namespace PofyTools
{
public sealed class WSUIManager : IInitializable
{
public const string TAG = "<b>WorldSpaceUIManager :</b>";
public static WSUIManager Instance;
public WSUIData Data { get; private set; }
#region IInitializable implementation
private bool _isInitialized = false;
public bool IsInitialized => this._isInitialized;
private Transform _character, _camera;
public bool Initialize(Transform character, Transform camera, WSUIData data)
{
this._character = character;
this._camera = camera;
this.Data = data;
return Initialize();
}
public bool Initialize()
{
if (!this.IsInitialized)
{
Instance = this;
//Initialize Pool
this._pools = new Dictionary<System.Type, Stack<WSUIBase>>();
this._activeElements = new List<WSUIBase>();
this._isInitialized = true;
return true;
}
return false;
}
#endregion
#region Pool
private Dictionary<System.Type, Stack<WSUIBase>> _pools = null;
public Stack<WSUIBase> GetStack(System.Type type)
{
Stack<WSUIBase> stack = null;
if (!this._pools.TryGetValue(type, out stack))
{
stack = new Stack<WSUIBase>();
this._pools[type] = stack;
}
return stack;
}
#endregion
[SerializeField] public List<WSUIBase> _activeElements;
public void AddElement(WSUIBase element)
{
this._activeElements.Add(element);
}
public struct UpdateData
{
public float deltaTime;
public Vector3 playerPosition;
public Vector3 cameraPosition;
public Vector3 cameraUp;
}
public void Update(float delatTime)
{
var data = new UpdateData()
{
deltaTime = delatTime,
playerPosition = this._character.position,
cameraPosition = this._camera.position,
cameraUp = this._camera.up,
};
#if UNITY_EDITOR
if (Input.GetKeyDown(KeyCode.P))
{
var newElement = ObtainPositionImage() as WSUIPositionImage;
newElement.transform.position = data.playerPosition;
newElement.image.rectTransform.sizeDelta = Vector2.one * Random.Range(1f, 5f);
newElement.Activate();
//Debug.LogError("[P]LACED!");
}
if (Input.GetKeyDown(KeyCode.I))
{
var newElement = ObtainFollowImage() as WSUIFollow;
newElement.followTarget = this._character;
newElement.followOffset = new Vector3(0f, 2.5f, 0f);
newElement.Activate();
//Debug.LogError("[P]LACED!");
}
if (Input.GetKeyDown(KeyCode.O))
{
foreach (var e in this._activeElements)
{
e.Deactivate();
}
//Debug.LogError("[O]LL IS DEACTIVATED!");
}
#endif
for (int i = this._activeElements.Count - 1; i >= 0; i--)
{
var element = this._activeElements[i];
//update only active elements
if (element.IsActive && element.UpdateElement(data))
{
element.Deactivate();
}
}
}
//Calls on LateUpdate
public void FreeInactiveElements()
{
for (int i = this._activeElements.Count - 1; i >= 0; i--)
{
var element = this._activeElements[i];
if (!element.IsActive)
{
this._activeElements.RemoveAt(i);
element.Free();
}
}
}
public void Purge()
{
this._pools = null;
}
#region Static API
public struct PoolData
{
public WSUIManager manager;
public Stack<WSUIBase> stack;
public bool poolable;
}
public static WSUIBase PopOrRegister(System.Type type, WSUIBase prefab)
{
var stack = Instance.GetStack(type);
WSUIBase instance = null;
if (stack.Count > 0)
instance = stack.Pop();
else
instance = GameObject.Instantiate<WSUIBase>(prefab);
var data = new PoolData()
{
manager = Instance,
stack = stack,
poolable = true
};
instance.SetPoolData(data);
return instance;
}
/// <summary>
/// Register outside instance with manager.
/// </summary>
/// <param name="instance">Instance to register with manager.</param>
/// <param name="poolTrack">Should instance be returned to manager's pool.</param>
public static void RegisterWithManager(WSUIBase instance, bool poolTrack = false)
{
Stack<WSUIBase> stack = (poolTrack) ? Instance.GetStack(instance.GetType()) : null;
var poolData = new PoolData()
{
manager = Instance,
stack = stack,
poolable = poolTrack
};
instance.SetPoolData(poolData);
}
public enum PushResult
{
Destroyed = -1,
None = 0,
Success = 1,
}
public static PushResult PushOrDestroy(WSUIBase instance, Stack<WSUIBase> stack, PushResult forcedResult = PushResult.None)
{
if (stack == null) forcedResult = PushResult.Destroyed;
if (forcedResult == PushResult.Destroyed || (forcedResult != PushResult.Success && stack.Count >= WSUIManager.Instance.Data.stackLimit))
{
GameObject.Destroy(instance.gameObject);
return PushResult.Destroyed;
}
stack.Push(instance);
return PushResult.Success;
}
/// <summary>
/// Obtained Instance is not automatically added to active elements.
/// Use instance.Activate to activate it.
/// </summary>
/// <returns></returns>
public static WSUIBase ObtainPositionText() => PopOrRegister(typeof(WSUIPositionText), Instance.Data.positionTextPrefab);
/// <summary>
/// Obtained Instance is not automatically added to active elements.
/// Use instance.Activate to activate it.
/// </summary>
/// <returns></returns>
public static WSUIBase ObtainFollowText() => PopOrRegister(typeof(WSUIFollowText), Instance.Data.followTextPrefab);
/// <summary>
/// Obtained Instance is not automatically added to active elements.
/// Use instance.Activate to activate it.
/// </summary>
/// <returns></returns>
public static WSUIBase ObtainPositionImage() => PopOrRegister(typeof(WSUIPositionImage), Instance.Data.positionImagePrefab);
/// <summary>
/// Obtained Instance is not automatically added to active elements.
/// Use instance.Activate to activate it.
/// </summary>
/// <returns></returns>
public static WSUIBase ObtainFollowImage() => PopOrRegister(typeof(WSUIFollowImage), Instance.Data.followImagePrefab);
/// <summary>
/// Obtained Instance is not automatically added to active elements.
/// Use instance.Activate to activate it.
/// </summary>
/// <returns></returns>
public static WSUIBase ObtainPopup() => PopOrRegister(typeof(WSUIPopup), Instance.Data.popupPrefab);
/// <summary>
/// Obtained Instance is not automatically added to active elements.
/// Use instance.Activate to activate it.
/// </summary>
/// <returns></returns>
public static WSUIBase ObtainBar() => PopOrRegister(typeof(WSUIBar), Instance.Data.barPrefab);
#endregion
[System.Serializable]
public class WSUIData
{
[Header("Distance Fade")]
public Range fadeDistanceSqrRange = new Range(100f, 600f);
public Range fadeNearClipRange = new Range(1f, 4f);
[Space]
[Header("Pool")]
//Pool stack
public int stackLimit = 20;
public int stackPrewarmSize = 5;
[Space]
//Pool prefabs
[Header("Text")]
public WSUIPositionText positionTextPrefab;
public WSUIFollowText followTextPrefab;
public WSUIPopup popupPrefab;
[Header("Image")]
public WSUIPositionImage positionImagePrefab;
public WSUIFollowImage followImagePrefab;
[Header("Bar")]
public WSUIBar barPrefab;
}
}
}<file_sep>/UniverseGraph/UniverseGraph.cs
using System;
using UnityEditor;
using UnityEngine;
using XNode;
namespace Guvernal
{
/// <summary> Defines an example nodegraph that can be created as an asset in the Project window. </summary>
[Serializable, CreateAssetMenu(fileName = "New Universe Graph", menuName = "PofyTools/Universe Graph")]
public class UniverseGraph : NodeGraph
{
public void ResetGraph()
{
this.nodes.Clear();
}
}
}<file_sep>/CategoryGraph/Nodes/CategorySetNode.cs
using UnityEditor;
using UnityEngine;
using XNode;
namespace PofyTools
{
[System.Serializable]
[NodeTint(0.6f, 0.5f, 0.3f)]
[NodeWidth(400)]
public class CategorySetNode : Node
{
public string DEFINITIONS_PATH = "Definitions";
public string FILE_NAME = "categories";
public string FILE_EXTENSION = "json";
public bool PROTECT_DATA = false;
protected void SingletonCheck()
{
Node other = null;
foreach (var node in this.graph.nodes)
{
if (node != this)
{
if (node is CategorySetNode)
{
other = node;
break;
}
}
}
if (other != null)
{
this.graph.RemoveNode(this);
}
}
[HideInInspector]
public string _lastPath;
[ContextMenu("Save")]
public void Save()
{
CategoryDefinitionSet set = new CategoryDefinitionSet(this.DEFINITIONS_PATH, this.FILE_NAME, this.PROTECT_DATA, this.PROTECT_DATA, this.FILE_EXTENSION);
var content = set.GetContent();
foreach (var node in this.graph.nodes)
{
if (node is CategoryNode)
{
var catNode = node as CategoryNode;
catNode.VerifyConnections();
CategoryDefinition newDefinition = new CategoryDefinition(catNode.categoryId);
newDefinition.baseIds.AddRange(catNode.GetInputValues<string>("baseCategories"));
content.Add(newDefinition);
}
}
set.SetContent(content);
//set.Save();
//var fullPath = EditorUtility.SaveFilePanel("Save Category Definition Set", Application.dataPath, this.FILE_NAME, this.FILE_EXTENSION);
DataUtility.PanelSave(this._lastPath, set);
#if UNITY_EDITOR
AssetDatabase.SaveAssets();
#endif
}
[ContextMenu("Save as...")]
public void SaveAs()
{
#if UNITY_EDITOR
this._lastPath = EditorUtility.SaveFilePanel("Save Category Definition Set", Application.dataPath, this.FILE_NAME, this.FILE_EXTENSION);
Save();
#endif
}
}
}<file_sep>/CategoryGraph/Nodes/CategoryNode.cs
using UnityEngine;
using XNode;
namespace PofyTools
{
[System.Serializable]
[NodeTint(0.6f, 0.8f, 0.3f)]
public class CategoryNode : Node
{
[Input(ShowBackingValue.Never, ConnectionType.Multiple)] public string baseCategories;
[Output(ShowBackingValue.Never, ConnectionType.Multiple)] public string categoryId = "new_definition";
// GetValue should be overridden to return a value for any specified output port
public override object GetValue(NodePort port)
{
if (port.fieldName == "categoryId")
return this.name;
else
return null;
}
protected override void Init()
{
this.categoryId = this.name;
}
}
}<file_sep>/Data/Editor/LocalizationDataAddEntryPopup.cs
namespace PofyTools
{
#pragma warning disable 219
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class LocalizationDataAddEntryPopup : PopupWindowContent
{
private string _newKey = "NEW_ENTRY";
private string _info = "New key has to unique.";
private MessageType _infoType = MessageType.Info;
private EditorWindow _target;
// public static void Init()
// {
// LocalizationDataAddEntryPopup window = ScriptableObject.CreateInstance<LocalizationDataAddEntryPopup>();
// //window.position = new Rect(Screen.width / 2, Screen.height / 2, 250, 150);
// window.position = new Rect(EditorWindow.focusedWindow.position.x, EditorWindow.focusedWindow.position.y, 250, 150);
//
// window._target = EditorWindow.focusedWindow;
// if (!(window._target is LocalizationDataEditor))
// window._target = null;
//
// window.ShowPopup();
// }
public override Vector2 GetWindowSize()
{
return new Vector2(200, 150);
}
public override void OnGUI(Rect rect)
{
EditorGUILayout.LabelField("Add New Entry", EditorStyles.wordWrappedLabel);
EditorGUILayout.Separator();
EditorGUILayout.LabelField("Enter new key:");
this._newKey = EditorGUILayout.TextField(this._newKey);
EditorGUILayout.Separator();
EditorGUILayout.HelpBox(this._info, this._infoType);
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Add"))
this.AddPair();
EditorGUILayout.EndHorizontal();
}
void AddPair()
{
var allData = Localization.GetData();
if (Localization.HasKey(this._newKey))
{
this._info = "The key \"" + this._newKey + "\" already present in language data. Choose different key.";
this._infoType = MessageType.Error;
}
else
{
Localization.AddPair(this._newKey);
this._info = "The key \"" + this._newKey + "\" successfully added!";
this._infoType = MessageType.Info;
}
}
}
}<file_sep>/Core/Milestone.cs
using UnityEngine;
namespace PofyTools
{
public delegate void MilestoneDelegate(Milestone milestone);
public class Milestone
{
private Range _currentRange;
private Range _initialDistanceRange;
private Range _distanceRange;
//private float _initialDistance;
#region Constructors
/// <summary>
/// Distance less than 0 is set to 0.
/// </summary>
/// <param name="distance"></param>
/// <param name="startPoint"></param>
public Milestone(Range distanceRange, float startPoint = 0f)
{
distanceRange.max = Mathf.Max(0, distanceRange.max);
distanceRange.min = Mathf.Max(0, distanceRange.min);
this._initialDistanceRange = this._distanceRange = distanceRange;
this._currentRange = new Range(min: startPoint, max: this._initialDistanceRange.max + startPoint);
//this._initialDistance = distance;
}
#endregion
#region API
public float CurrentMilestone => this._currentRange.max;
public Range CurrentRange => this._currentRange;
public bool MilestoneReached(float point)
{
bool result = point >= this._currentRange.max;
return result;
}
public float DistanceFromMilestone(float point)
{
return this._currentRange.max - point;
}
public void ResetMilestone(float startPoint)
{
SetMilestone(this._distanceRange, startPoint);
}
public void SetMilestone(Range distanceRange, float startPoint)
{
distanceRange.max = Mathf.Max(0, distanceRange.max);
distanceRange.min = Mathf.Max(0, distanceRange.min);
this._distanceRange = distanceRange;
this._currentRange = new Range(min: startPoint, max: startPoint + distanceRange.Random);
}
#endregion
#region Event
protected MilestoneDelegate _onEvent = null;
protected void IdleEventListener(Milestone milestone)
{
}
/// <summary>
/// Adds the event listener.
/// </summary>
/// <param name="listener">Listener.</param>
public void AddEventListener(MilestoneDelegate listener)
{
this._onEvent += listener;
}
/// <summary>
/// Removes the event listener.
/// </summary>
/// <param name="listener">Listener.</param>
public void RemoveEventListener(MilestoneDelegate listener)
{
this._onEvent -= listener;
}
/// <summary>
/// Removes all event listeners.
/// </summary>
public void RemoveAllEventListeners()
{
this._onEvent = IdleEventListener;
}
/// <summary>
/// Tries the execute, firing event and reseting the cooldown.
/// </summary>
/// <returns><c>true</c>, if execution was successful, <c>false</c> otherwise.</returns>
/// <param name="force">If set to <c>true</c> force execution.</param>
public bool TryExecute(float point, bool force = false, bool autoReset = true)
{
if (MilestoneReached(point) || force)
{
FireEvent(point, autoReset);
return true;
}
return false;
}
protected void FireEvent(float point, bool autoResetOnEvent = true)
{
this._onEvent?.Invoke(this);
if (autoResetOnEvent)
ResetMilestone(point);
else
{
SetMilestone(new Range(float.PositiveInfinity, float.PositiveInfinity), point);
}
}
#endregion
}
}
<file_sep>/CategoryGraph/Nodes/Editor/CategorySetNodeEditor.cs
using UnityEngine;
using XNodeEditor;
namespace PofyTools
{
[CustomNodeEditor(typeof(CategorySetNode))]
public class CategorySetNodeEditor : NodeEditor
{
public override void OnHeaderGUI()
{
//this.target.name = ObjectNames.NicifyVariableName(this.target.GetValue(this.target.GetOutputPort("id")).ToString());
//InitiateRename();
base.OnHeaderGUI();
}
/// <summary> Called whenever the xNode editor window is updated </summary>
public override void OnBodyGUI()
{
var _categorySetNode = this.target as CategorySetNode;
base.OnBodyGUI();
if (string.IsNullOrEmpty(_categorySetNode._lastPath))
{
if (GUILayout.Button("Save"))
{
_categorySetNode.SaveAs();
}
}
else
{
if (GUILayout.Button("Save"))
{
_categorySetNode.Save();
}
if (GUILayout.Button("Save as.."))
{
_categorySetNode.SaveAs();
}
}
//if(GUILayout.Button("Clear All"))
//{
// (_categorySetNode.graph as CategoryGraph).ResetGraph();
//}
}
void OnNodeUpdate()
{
//this.target.name = ObjectNames.NicifyVariableName(this.target.GetValue(this.target.GetOutputPort("id")).ToString());
}
}
}
<file_sep>/Core/IPredictor.cs
using System.Collections.Generic;
using UnityEngine;
namespace PofyTools
{
public interface IPredictor
{
Vector3 GetPredictedOffset(float inTime);
void Stamp();
Transform Target { get; }
}
public struct SimplePredictionData : IPredictor
{
public Transform Target { get; private set; }
private Vector3 _cachedPosition;
private float _timestamp;
public SimplePredictionData(Transform target)
{
this.Target = target;
this._cachedPosition = target.position;
this._timestamp = Time.time;
}
/// <summary>
/// Predicts target offset for given time based on state's snapshots.
/// </summary>
/// <param name="inTime"> Time offset for predition.</param>
/// <returns> Target offset prediction for Time.time + inTime.</returns>
public Vector3 GetPredictedOffset(float inTime = 0)
{
if (!this.Target || inTime <= 0)
return default;
Vector3 result;
Vector3 velocity;
Vector3 deltaPosition = this.Target.position - this._cachedPosition;
float elapsedTime = Time.time - this._timestamp;
if (elapsedTime > 0f)
velocity = deltaPosition / elapsedTime;
else
velocity = deltaPosition;
result = (velocity * inTime);
return result;
}
public void Stamp()
{
if (this.Target)
{
this._cachedPosition = this.Target.position;
this._timestamp = Time.time;
}
}
}
public class MultiPointPositionPredictor : IPredictor
{
public struct StampData
{
public Vector3 position;
public float timestamp;
public StampData(Vector3 position, float timestamp)
{
this.position = position;
this.timestamp = timestamp;
}
}
private Transform _target;
public Transform Target => this._target;
public void SetTarget(Transform target)
{
if (this._target != target)
this._target = target;
{
this._stamps.Clear();
Stamp();
}
}
public int pointLimit;
private List<StampData> _stamps;
private Vector3 _lastResult;
public MultiPointPositionPredictor(Transform target, int pointLimit = 1)
{
this.pointLimit = pointLimit + 1;
this._stamps = new List<StampData>();
SetTarget(target);
}
/// <summary>
/// Predicts target offset for given time based on state's snapshots.
/// </summary>
/// <param name="inTime"> Time offset for predition.</param>
/// <returns> Target offset prediction for Time.time + inTime.</returns>
public Vector3 GetPredictedOffset(float inTime = 0)
{
int count = this._stamps.Count;
if (!this.Target || inTime <= 0 || count < 1)
return default;
Stamp();
Vector3 final = Vector3.zero;
Vector3 velocity;
Vector3 deltaPosition;
float elapsedTime;
int elements = 0;
for (int i = 1; i < count; i++)
{
for (int j = i - 1; j >= 0; --j)
{
deltaPosition = this._stamps[i].position - this._stamps[j].position;
elapsedTime = this._stamps[i].timestamp - this._stamps[j].timestamp;
if (elapsedTime > 0f)
velocity = deltaPosition / elapsedTime;
else
velocity = deltaPosition;
final += (velocity * inTime);
elements++;
}
}
return this._lastResult = final / elements;
}
public void Stamp()
{
if (this.Target)
{
if (this._stamps.Count >= this.pointLimit)
this._stamps.RemoveAt(0);
this._stamps.Add(new StampData(this.Target.position, Time.time));
}
}
public void Draw()
{
#if UNITY_EDITOR
if (this.Target)
{
Gizmos.color = new Color(1, 0.5f, 1, 1);
foreach (var stamp in this._stamps)
{
Gizmos.DrawWireSphere(stamp.position, 0.1f);
}
Gizmos.color = new Color(0.5f, 1f, 0.5f, 1f);
Gizmos.DrawWireSphere(this.Target.position + this._lastResult, 0.1f);
}
#endif
}
}
}
<file_sep>/UI/WorldSpaceUI/WSUIPositionImage.cs
using UnityEngine.UI;
namespace PofyTools
{
public class WSUIPositionImage : WSUIBase
{
public Image image;
}
}<file_sep>/Distribution/ComponentDeck.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace PofyTools
{
public interface IClonable
{
IClonable Clone (IClonable source);
}
/// <summary>
/// Component deck. Support deep copying of cards for populating.
/// </summary>
[System.Serializable]
public class ComponentDeck<T> where T : Component
{
[System.Serializable]
public class Card
{
protected T _instance = null;
public T instance {
get{ return this._instance; }
}
protected int _weight = 0;
public int weight {
get{ return this._weight; }
}
public override string ToString ()
{
return string.Format ("[Card: instance={0}, weight={1}]", instance, weight);
}
#region IClonable implementation
public IClonable Clone (IClonable source)
{
Card clone = new Card (source as Card);
return clone as IClonable;
}
#endregion
public Card ()
{
}
public Card (T instance, int weight)
{
this._instance = instance;
this._weight = weight;
}
public Card (Card card)
{
this._instance = GameObject.Instantiate<T> (card.instance);
this._weight = card.weight;
}
}
protected bool _isShuffled = false;
public bool isShuffled {
get{ return this._isShuffled; }
}
protected List<Card> _cards = new List<Card> ();
protected int _head;
public int Head {
get {
if (this.Count > 0)
return this._head;
else
return -1;
}
}
public int Count {
get{ return this._cards.Count; }
}
protected int _maxWeight = -1;
public int MaxWeight {
get {
if (this._maxWeight == -1) {
this._maxWeight = GetMaxWeight ();
}
return this._maxWeight;
}
}
protected int GetMaxWeight ()
{
int result = -1;
foreach (var card in this._cards) {
result = Mathf.Max (result, card.weight);
}
return result;
}
public ComponentDeck<T> ShuffleDeck ()
{
this._head = 0;
while (this._head < this.Count) {
int randomIndex = Random.Range (this._head, this.Count);
Card randomCard = this._cards [randomIndex];
this._cards.RemoveAt (randomIndex);
this._cards.Insert (this._head, randomCard);
++this._head;
}
this._isShuffled = true;
this._head = 0;
return this;
}
public bool ContainsCard (Card card)
{
return this._cards.Contains (card);
}
public void AddCard (Card card)
{
this._cards.Add (card);
if (card.weight > this.MaxWeight) {
this._maxWeight = card.weight;
}
}
public bool ContainsInstance (T instance)
{
foreach (var card in this._cards) {
if (card.instance == instance)
return true;
}
return false;
}
public Card PickNextCard ()
{
Card card = this._cards [this.Head];
++this._head;
if (this.Head == this.Count) {
ShuffleDeck ();
}
return card;
}
public Card PickBiasCard (int minWeight = 0)
{
minWeight = Mathf.Min (minWeight, this.MaxWeight);
Card biasCard = null; //TODO: Continue from here...
while (biasCard == null) {
foreach (var card in this._cards)
if (card.weight >= minWeight)
biasCard = card;
}
return biasCard;
}
public ComponentDeck<T> CreateDistributionDeck (int weightMultiplier = 1)
{
int allocatedCount = Math.ArithmeticSequenceSum (this.Count);
Debug.LogWarningFormat ("allocatedCount: {0}", allocatedCount);
ComponentDeck<T> distributionDeck = new ComponentDeck<T> (allocatedCount);
foreach (var card in this._cards) {
int totalNumberOfCopies = (this.MaxWeight - card.weight + 1) * weightMultiplier;
while (totalNumberOfCopies > 0) {
Card copy = new Card (card);
distributionDeck._cards.Add (copy);
--totalNumberOfCopies;
}
}
distributionDeck.ShuffleDeck ();
return distributionDeck;
}
public ComponentDeck ()
{
}
public ComponentDeck (int size)
{
this._cards = new List<Card> (size);
}
}
}<file_sep>/Data/DataEditor.cs
namespace PofyTools.Data
{
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
[ExecuteInEditMode]
public abstract class DataEditor : MonoBehaviour
{
public abstract void SaveData();
public abstract void LoadData();
public abstract void Refresh();
#if UNITY_EDITOR
[ContextMenu("Load")]
void CommandLoad()
{
LoadData();
}
[ContextMenu("Save")]
void CommandSave()
{
SaveData();
}
[ContextMenu("Refresh")]
void CommandRefresh()
{
Refresh();
}
void OnPrefabUpdated(GameObject prefab)
{
if (this != null)
{
if (prefab == this.gameObject)
{
SaveData();
//AssetDatabase.Refresh(ImportAssetOptions.Default);
Refresh();
}
}
else
{
//Debug.LogError("THIS is NULL! Data NOT Saved!");
}
}
protected virtual void OnValidate()
{
PrefabUtility.prefabInstanceUpdated -= OnPrefabUpdated;
PrefabUtility.prefabInstanceUpdated += OnPrefabUpdated;
}
#endif
}
}
|
b27c0a12a729060b2289bd91db55f13e0cb9e99e
|
[
"Markdown",
"C#"
] | 47 |
C#
|
PofyTeam/PofyTools
|
c1fdd59ab8766eed34b8adbe0c709148afd6a3b9
|
115d5ddf7204a900547b9b067f8fbbec3cd0e6d9
|
refs/heads/master
|
<file_sep>package com.example.user.acmebots_alfa;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class curso extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_curso);
Button b = findViewById(R.id.button5);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent cursitos=new Intent(curso.this,Main2Activity.class);
startActivity(cursitos);
}
});
}
}
<file_sep>package com.example.user.acmebots_alfa;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class contactos extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contactos);
}
//metodo para regresar
public void Regresar(View view){
Intent regresar=new Intent(this,MainAcme.class);
startActivity(regresar);
}
}
<file_sep>package com.example.user.acmebots_alfa;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainAcme extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_acme);
}
//metodo de boton curso
public void Curso(View view){
Intent curso=new Intent(this,com.example.user.acmebots_alfa.curso.class);
startActivity(curso);
}
public void Contacto(View view){
Intent contacto=new Intent(this, contactos.class);
startActivity(contacto);
}
public void Administrar(View view){
Intent administrar=new Intent(this,Admi.class);
startActivity(administrar);
}
}
|
d2907a0b7c2fa16a6f662a7b3448a2061082ee6b
|
[
"Java"
] | 3 |
Java
|
edwinsaavedra99/B2
|
3187bf18e6ce8727b79416c780f82a334ea59e7a
|
7128c606db13931d03d547df5e946b89f16fee42
|
refs/heads/master
|
<file_sep>package com.sc.feign.controller;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Map;
import java.util.zip.GZIPOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.feign.encoding.HttpEncoding;
import feign.RequestInterceptor;
import feign.RequestTemplate;
public class GzipRequestInterceptor implements RequestInterceptor {
private final Logger logger = LoggerFactory.getLogger(GzipRequestInterceptor.class);
@Override
public void apply(RequestTemplate template) {
Map<String, Collection<String>> headers = template.headers();
if (headers.containsKey(HttpEncoding.CONTENT_ENCODING_HEADER)) {
Collection<String> values = headers.get(HttpEncoding.CONTENT_ENCODING_HEADER);
if(values.contains(HttpEncoding.GZIP_ENCODING)) {
logger.info("request gzip wrapper.");
ByteArrayOutputStream gzipedBody = new ByteArrayOutputStream();
try {
GZIPOutputStream gzip = new GZIPOutputStream(gzipedBody);
gzip.write(template.body());
gzip.flush();
gzip.close();
template.body(gzipedBody.toByteArray(), Charset.defaultCharset());
}catch(Exception ex) {
throw new RuntimeException(ex);
}
}
}
}
}
<file_sep>spring.application.name=sc-seata-mstest3
server.port=8103
spring.datasource.url=jdbc:mysql://192.168.5.78:3306/seata3?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.show-sql=true
eureka.client.service-url.defaultZone=http://sc-eureka:[email protected]:8070/eureka/,http://sc-eureka:[email protected]:8071/eureka/
eureka.instance.prefer-ip-address=true
eureka.healthcheck.enabled=true<file_sep>package com.sc.seata.bztest1.service;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sc.seata.bztest1.domain.User;
import com.sc.seata.bztest1.feign.Mstest1FeignClient;
import com.sc.seata.bztest1.feign.Mstest2FeignClient;
import io.seata.spring.annotation.GlobalTransactional;
@Service
public class BusinessService {
@Autowired
private Mstest1FeignClient mstest1FeignClient;
@Autowired
private Mstest2FeignClient mstest2FeignClient;
@GlobalTransactional(name="addUser")
public Collection<User> addUser(Long userId, String name) {
User user1 = mstest1FeignClient.addUser(userId, name);
User user2 = mstest2FeignClient.addUser(userId, name);
Collection<User> users = new ArrayList<User>();
users.add(user1);
users.add(user2);
return users;
}
}
<file_sep># 密码模式(password authorization)客户端
## 1.理论
**如果你高度信任某个应用,RFC 6749 也允许用户把用户名和密码,直接告诉该应用。该应用就使用你的密码,申请令牌,这种方式称为"密码式"(password)。**
第一步,A 网站要求用户提供 B 网站的用户名和密码。拿到以后,A 就直接向 B 请求令牌。
> ```javascript
> https://oauth.b.com/token?
> grant_type=password&
> username=USERNAME&
> password=<PASSWORD>&
> client_id=CLIENT_ID
> ```
上面 URL 中,`grant_type`参数是授权方式,这里的`password`表示"密码式",`username`和`password`是 B 的用户名和密码。
第二步,B 网站验证身份通过后,直接给出令牌。注意,这时不需要跳转,而是把令牌放在 JSON 数据里面,作为 HTTP 回应,A 因此拿到令牌。
这种方式需要用户给出自己的用户名/密码,显然风险很大,因此只适用于其他授权方式都无法采用的情况,而且必须是用户高度信任的应用。
## 2.配置
### 2.1 pom.xml
```xml
<!-- spring cloud security oauth2 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
```
### 2.2 PasswordAuthorizationApplication
```java
@SpringBootApplication
public class PasswordAuthorizationApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest httpRequest = requestAttributes.getRequest();
request.getHeaders().add("Authorization", httpRequest.getHeader("Authorization"));
return execution.execute(request, body);
}});
return restTemplate;
}
public static void main(String[] args) {
SpringApplication.run(PasswordAuthorizationApplication.class, args);
}
}
```
这里唯一需要注意的就是RestTemplate的spring bean,其内部添加了一个ClientHttpRequestInterceptor,目的是把请求的Authorization头,在服务请求之间传递。目前看在Password认证模式下,这个一个好的解决方案了,因为OAuth2RestTemplate只支持authorization_code和client_credentials模式,不支持password和implicit。
### 2.3 application.yml
```yaml
# oauth2 security
security:
oauth2:
resource:
#userInfoUri: http://localhost:6001/auth/user
loadBalanced: true
userInfoUri: http://SC-OAUTH2/auth/user
```
### 2.4 oauth2 server配置
#### 2.4.1 代码认证模式下的client_details
oauth2 服务器端,要配置允许这个第三方应用访问oauth2服务器。
| 字段名 | 数据(样例) |
| -------------------------- | ------------------------------------------------------------ |
| CLIENT_ID | test_client |
| RESOURCE_IDS | |
| CLIENT_SECRET | {<KEY> |
| SCOPE | service,web |
| **AUTHORIZED_GRANT_TYPES** | refresh_token,password,authorization_code |
| WEB_SERVER_REDIRECT_URI | |
| AUTHORITIES | |
| ACCESS_TOKEN_VALIDITY | |
| REFRESH_TOKEN_VALIDITY | |
| ADDITIONAL_INFORMATION | |
| AUTOAPPROVE | |
code_authorization模型下,有三个字段会被使用:
**AUTHORIZED_GRANT_TYPES**,必须含有password字样。
#### 2.4.2 oauth_user
oauth2_user表加入允许登录的用户。
### 2.5 ResourceServerConfiguration
注意:类头源注释@EnableResourceServer,其会创建spring security相关bean。
configure(HttpSecurity http)方法内部配置的规则,是/pw/**的请求必须是已经认证(已经登录)。
```java
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
/**
* 自定义安全配置
* 注意:一定要以http.antMatcher(...)方法开头匹配,否则会覆盖SecurityConfiguration类的相关配置.
* 这里定义的配置有两个作用:
* 1.安全限制,定义外界请求访问系统的安全策略。
* 2.根据规则生成过滤链(FilterChainProxy,过滤器的排列组合),不同的规则生成的过滤链不同的。
* 系统默认的/oauth/xxx相关请求也是基于ResourceServerConfiguration实现的,只不过系统默认已经配置完了。
*/
@Override
public void configure(HttpSecurity http) throws Exception {
// 提供给client端用于认证
http.antMatcher("/pw/**").authorizeRequests().anyRequest().authenticated();
}
}
```
###
## 3.测试
### 3.1 启动相关项目
sc-oauth2 oauth2 服务器,端6001
sc-oauth2-pw-serviceclient 密码模式测试客户端1,端口6005
sc-oauth2-pw-serviceclient1 密码模式测试客户端2,端口6006
### 3.2 发送请求到oauth2 server
**发送请求到oauth2 server获取access_token**
curl -X POST -H 'Content-Type: application/x-www-form-urlencoded' -H 'Authorization: Basic dGVzdF9jbGllbnQ6MTIzNDU2' -i http://localhost:6001/oauth/token --data 'grant_type=password&username=test_user&password=<PASSWORD>&scope=service'
这里的Authorization: Basic dGVzdF9jbGllbnQ6MTIzNDU2的Basic 值是client_id:client_sercret base64后的值。
```json
{
"access_token": "<PASSWORD>",
"token_type": "bearer",
"refresh_token": "<PASSWORD>",
"expires_in": 43199,
"scope": "service"
}
```
### 3.3 发送请求到sc-oauth2-pw-serviceclient
携带access_token,发送请求到sc-oauth2-pw-serviceclient,其内部会调用sc-oauth2-pw-serviceclient1,用于测试认证请求传递。
请求URL:
curl -X GET -H 'Authorization: Bearer <PASSWORD>' -i http://localhost:6005/pw/test/1
```
success, success_pw1_test1
```
其中第一个success为sc-oauth2-pw-serviceclient的结果。
success_pw1_test1为sc-oauth2-pw-serviceclient1返回的结果(认证请求服务间传递)。
传递代码:
```java
@Autowired
private RestTemplate oauth2RestTemplate;
@GetMapping("/pw/test/1")
public String test1() {
OAuth2Authentication oauth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
System.out.println(oauth2Authentication);
String pw1TestResult = this.oauth2RestTemplate.getForObject("http://SC-OAUTH2-PW-SERVICECLIENT1//pw1/test/1", String.class);
return "success, "+pw1TestResult;
}
```
这里的oauth2RestTemplate比较是经过处理的,如下:
```java
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest httpRequest = requestAttributes.getRequest();
request.getHeaders().add("Authorization", httpRequest.getHeader("Authorization"));
return execution.execute(request, body);
}});
return restTemplate;
}
```
<file_sep>package com.sc.zuul.swagger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwapperConfiguration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Zuul构建Swagger2 RESTful APIs入口")
.description("更多Spring Cloud相关文章请关注:https://github.com/zhangdberic/springcloud/")
.termsOfServiceUrl("https://github.com/zhangdberic/")
.contact(new Contact("zhangdberic","https://github.com/zhangdberic","<EMAIL>"))
.version("1.0")
.build();
}
}
<file_sep># spring cloud config 配置客户端
本项目就是为了演示如果基于spring cloud config来配置应用和服务,具体的文档参见:
[](https://github.com/zhangdberic/springcloud/tree/master/sc-config)
<file_sep>package com.sc.seata.mstest2.service;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sc.seata.mstest2.domain.User;
import com.sc.seata.mstest2.feign.Mstest3FeignClient;
import com.sc.seata.mstest2.respository.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private Mstest3FeignClient mstest3FeignClient;
@Transactional
public User addUser(User user) {
User user2 = this.userRepository.saveAndFlush(user);
User user3 = this.mstest3FeignClient.addUser(user.getId(),user.getName());
user3.setName(user2.getName()+"_"+user3.getName());
return user3;
}
}
<file_sep>package com.sc.ribbon.controller;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.sc.ribbon.domain.User;
/**
* 测试ribbon的loadbalancer
* 其会对sc-sampleservice发起服务请求,如果sc-sampleservice部署了两个(集群),则会测试负载均衡请求分发情况.
*
* @author zhangdb
*
*/
@RestController
public class RibbonLoadBalancedTestController {
private static final Logger logger = LoggerFactory.getLogger(RibbonLoadBalancedTestController.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject("http://sc-sampleservice/{id}", User.class, id);
}
@GetMapping(value = "/user/{id}", params = "sleep")
public User findByIdWithSleep(@PathVariable Long id, @RequestParam(value = "sleep", required = false, defaultValue = "0") Long sleep) throws IOException {
long beginTime = System.currentTimeMillis();
try {
User user = this.restTemplate.getForObject("http://sc-sampleservice/{id}?sleep={sleep}", User.class, id, sleep);
return user;
} finally {
logger.info("findByIdWithSleep spend[{}]mills.", System.currentTimeMillis() - beginTime);
}
}
@PostMapping(value = "/", produces = "application/json;charset=UTF-8")
public User addUser(@RequestBody User user) {
User savedUser = this.restTemplate.postForObject("http://sc-sampleservice/", user, User.class);
return savedUser;
}
@GetMapping(value = "/log-user-instance", produces = "text/plant;charset=utf-8")
public String logUserInstance() {
ServiceInstance serviceInstance = this.loadBalancerClient.choose("sc-sampleservice");
String balancerInfo = "serviceId:" + serviceInstance.getServiceId() + ", target " + serviceInstance.getHost() + ":" + serviceInstance.getPort();
logger.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
return balancerInfo;
}
}
<file_sep><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sc</groupId>
<artifactId>sc-seata-mstest1</artifactId>
<version>1.0.1</version>
<name>sc-seata-mstest1</name>
<!-- 引入spring boot依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<!-- 配置属性 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<java.version>1.8</java.version>
</properties>
<!--引入spring cloud 依赖 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- spring boot web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring boot test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- spring boot actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- spring cloud eureka client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- alibaba seata -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
<version>2.1.0.RELEASE</version>
<exclusions>
<exclusion>
<artifactId>seata-all</artifactId>
<groupId>io.seata</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-all</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<!-- 引入spring-boot的maven插件 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- 引入docker打包maven插件 -->
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.4.13</version>
<configuration>
<!-- 访问 docker api 端口 -->
<dockerHost>http://dyit.com:2375</dockerHost>
<!-- dyit.com:5000为仓库地址 -->
<imageName>dyit.com:5000/sc/${project.name}:${project.version}</imageName>
<!-- 使用的基础镜像,生成Dockerfile的FROM指令 -->
<baseImage>base/java:1.8</baseImage>
<!-- docker启动后执行的命令,生成Dockerfile的ENTRYPOINT指令 -->
<entryPoint>["sh","-c","exec java $JAVA_OPTS -jar
/${project.build.finalName}.jar $APP_ENV"]</entryPoint>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<!--添加到镜像的文件,生成Dockerfile的ADD指令 -->
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
<!-- 覆盖相同tag的镜像(支持重复发布) -->
<forceTags>true</forceTags>
<!-- Basic auth 的配置,见settings.xml配置 -->
<serverId>dyit.com:5000</serverId>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep># swagger2 RESTful API文档
它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能来调试每个RESTful API。
# 查看swagger生成的API文档
http://localhost:8080/swagger-ui.htm

# swagger2的api介绍
### 1.建议使用独立swaggerConfiguration配置类
```java
@Configuration
@EnableSwagger2
public class SwapperConfiguration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.sc.swagger"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("更多Spring Cloud相关文章请关注:https://github.com/zhangdberic/springcloud/")
.termsOfServiceUrl("https://github.com/zhangdberic/")
.contact(new Contact("zhangdberic","https://github.com/zhangdberic","90993<EMAIL>"))
.version("1.0")
.build();
}
}
```
**apis(RequestHandlerSelectors.basePackage("com.sc.swagger"))**,指定扫描指定包(包含子包)路径下的swapper注释类来生成api文档。
### 2.@Api
```java
@Api(tags = "用户相关接口", description = "提供用户相关的 Rest API")
@RestController
@RequestMapping("/users")
public class UserController {}
```
@Api源注释标注一个RestController,对整个RestController进行说明,例如:UserController,标注为用户相关接口。如果不使用@Api标注,则swagger-ui是显示UserController字样。
### 3.@ApiOperation
```java
@ApiOperation(value = "获取用户列表", notes = "获取所有的用户信息")
@RequestMapping(method = RequestMethod.GET)
public Collection<User> getUsers() {
logger.info("获取[{}]条用户信息", users.values().size());
return users.values();
}
```
@ApiOperation标注一个Controller内的方法,也就是一个操作。
### 4.@ApiImplicitParam
```java
@ApiOperation(value = "更新用户详细信息", notes = "根据url的id来指定更新对象,并根据传过来的user信息来更新用户详细信息")
@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", example = "1"),
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User") })
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public RetVal<Long> putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
logger.info("修改user.id[{}],用户[{}]", id, user);
return new RetVal<Long>("200", "修改成功", id);
}
```
@ApiImplicitParam标注一个参数
name 参数名
value 描述
required 是否必填,对应swagger ui上是一个红色的星号
**dataType** 指定了参数类型,注意:这里只能两种类型。
1、java基本类型,例如:string、long、int等
2、@ApiModel标注类名,例如:这里dataType="User",User是一个domain类,其已经使用@ApiModel标注,例如dataType="User",对应的User类@ApiModel声明:
```java
@ApiModel(description = "用户信息")
public class User {
@ApiModelProperty(value = "用户id", required = true, example = "1")
private Long id;
@ApiModelProperty(value = "登录用户名", required = true, example = "heige")
private String username;
@ApiModelProperty(value = "用户名称", required = true, example = "黑哥")
private String name;
@ApiModelProperty(value = "年龄", example = "10", allowableValues = "range[1, 150]")
private Integer age;
@ApiModelProperty(value = "结余", example = "423.05", allowableValues = "range[0.00, 99999999.99]")
private BigDecimal balance;
}
```
**example** 参数示例值,如果参数是一个java基本类型,则需要指定值,否则会抛出异常。如果是一个类似于上面的dataType="User"的@ApiModel声明类型,则无需声明example,因为@ApiModel标注的类,本身就会提供example。
根据上面的@ApiOperation和@ApiImplicitParam的配置,生成的swagger ui截图:
**参数部分**
注意观察,界面上的Example Value,就是User类上标注的@ApiModelProperty的example。

**响应部分**
注意观察,界面上的Example Value,对应RetVal<Long>,包括RetVal内的泛型都可以正确识别(根据方法声明的返回值来生成的)。

```java
@ApiModel(description = "响应信息")
public class RetVal<T> {
@ApiModelProperty(value = "代码", required = true, example = "200")
private String code;
@ApiModelProperty(value = "信息", required = true, example = "成功")
private String message;
@ApiModelProperty
private T body;
}
```
### @ApiModel
@ApiModel标注的类,用于支撑@ApiImplicitParam或@ApiModelProperty上的dataType指定的值(参数类型或属性类型)的描述。例如:
@ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User"),这里dataType = "User",指定了User类型,User对应@ApiModel标注的类。其实@ApiModel有一个属性value,其指定了名称,默认不指定就是className,如果按照这个例子,如果我设置@ApiModel(value="user1"),那么@ApiImplicitParam的dataType 属性也要修改为dataType = "user1",也就是说@ApiImplicitParam.dataType和@ApiModel.value是一一对应的。
```java
@ApiModel(description = "用户信息")
public class User {
@ApiModelProperty(value = "用户id", required = true, example = "1")
private Long id;
@ApiModelProperty(value = "登录用户名", required = true, example = "heige")
private String username;
@ApiModelProperty(value = "用户名称", required = true, example = "黑哥")
private String name;
@ApiModelProperty(value = "年龄", example = "10", allowableValues = "range[1, 150]")
private Integer age;
@ApiModelProperty(value = "结余", example = "423.05", allowableValues = "range[0.00, 99999999.99]")
private BigDecimal balance;
}
```
根据上面声明例子,Model界面如下:

### @ApiModelProperty
allowableValues(允许的值范围)属性,这个值不能随便设置,需要查看源码说明,例如:
```java
/**
* Limits the acceptable values for this parameter.
* <p>
* There are three ways to describe the allowable values:
* <ol>
* <li>To set a list of values, provide a comma-separated list.
* For example: {@code first, second, third}.</li>
* <li>To set a range of values, start the value with "range", and surrounding by square
* brackets include the minimum and maximum values, or round brackets for exclusive minimum and maximum values.
* For example: {@code range[1, 5]}, {@code range(1, 5)}, {@code range[1, 5)}.</li>
* <li>To set a minimum/maximum value, use the same format for range but use "infinity"
* or "-infinity" as the second value. For example, {@code range[1, infinity]} means the
* minimum allowable value of this parameter is 1.</li>
* </ol>
*/
String allowableValues() default "";
```
三种值:
1.允许的列表,用逗号分隔,例如:allowableValues="汽车,火车,飞机"
2.最小值,最大值,range[x , x],例如:range[1 , 10]
3.只限制最小值或只限制最大值,例如:range[1 , infinity],只限制了最小值为1,最大值为无穷大(也就是不限制)。
<file_sep>package com.sc.oauth2;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
@Configuration
@EnableOAuth2Client
public class OAuthClientConfiguration {
@Bean
@Primary
public OAuth2ProtectedResourceDetails oauth2RemoteResource() {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
List<String> scopes = new ArrayList<String>(2);
scopes.add(OauthClientTestConfig.OAUTH_CLIENT_SERVICE_SCOPE);
scopes.add("web");
resource.setAccessTokenUri(OauthClientTestConfig.OAUTH_GET_TOKEN_URL);
resource.setClientId(OauthClientTestConfig.OAUTH_CLIENT_ID);
resource.setClientSecret(OauthClientTestConfig.OAUTH_CLIENT_SECRET);
resource.setGrantType("password");
resource.setScope(scopes);
resource.setUsername(OauthClientTestConfig.OAUTH_USERNAME);
resource.setPassword(OauthClientTestConfig.OAUTH_PASSWORD);
return resource;
}
@Bean
public OAuth2ClientContext oauth2ClientContext() {
return new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest());
}
@Bean
@Primary
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,
OAuth2ProtectedResourceDetails details) {
OAuth2RestTemplate template = new OAuth2RestTemplate(details, oauth2ClientContext);
return template;
}
}
<file_sep>package com.sc.feign.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.sc.feign.domain.UploadInfo;
import com.sc.feign.domain.User;
import com.sc.feign.serviceclient.SampleServiceFeignClient;
@RestController
public class FeignTestController {
private static final Logger logger = LoggerFactory.getLogger(FeignTestController.class);
@Autowired
private SampleServiceFeignClient sampleServiceFeignClient;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.sampleServiceFeignClient.findById(id);
}
@GetMapping(value="/user/{id}",params = "sleep")
public User findByIdWithSleep(@PathVariable("id") Long id, @RequestParam(value = "sleep", required = false, defaultValue = "0") Long sleep) {
return this.sampleServiceFeignClient.findByIdWithSleep(id, sleep);
}
@GetMapping(value = "/users")
public List<User> findUsers(@RequestParam(value="num",required=false,defaultValue="10") int num) {
return this.sampleServiceFeignClient.findUsers(num);
}
@RequestMapping(value = "/add_users", method = RequestMethod.POST, consumes="application/json;charset=UTF-8",produces = "application/json;charset=UTF-8")
public List<User> addUsers(@RequestBody List<User> users){
logger.info("param users row num:"+(users==null?0:users.size()));
return this.sampleServiceFeignClient.addUsers(users);
}
@RequestMapping(value = "/", method = RequestMethod.POST, consumes="application/json;charset=UTF-8",produces = "application/json;charset=UTF-8")
public User addUser(@RequestBody User user) {
return this.sampleServiceFeignClient.addUser(user);
}
@PostMapping(value="/uploadFile", produces = "application/json;charset=UTF-8")
public UploadInfo uploadLargeFile(@RequestPart(value="file") MultipartFile file) {
return this.sampleServiceFeignClient.handleFileUpload(file);
}
}
<file_sep>package com.sc.zipkin.test2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
/**
* zipkin服务器端
* @author zhangdb
*
*/
@SpringBootApplication
public class ZipkinService2Application {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ZipkinService2Application.class, args);
}
}
<file_sep>spring.application.name=sc-seata-mstest1
server.port=8101
spring.datasource.url=jdbc:mysql://192.168.5.78:3306/seata1?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.show-sql=true
eureka.client.service-url.defaultZone=http://sc-eureka:[email protected]:8070/eureka/,http://sc-eureka:[email protected]:8071/eureka/
eureka.instance.prefer-ip-address=true
eureka.healthcheck.enabled=true<file_sep>package com.sc.swagger.domain;
import java.math.BigDecimal;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(description = "用户信息")
public class User {
public User() {
super();
}
public User(Long id, String username, String name, Integer age, BigDecimal balance) {
super();
this.id = id;
this.username = username;
this.name = name;
this.age = age;
this.balance = balance;
}
@ApiModelProperty(value = "用户id", required = true, example = "1")
private Long id;
@ApiModelProperty(value = "登录用户名", required = true, example = "heige")
private String username;
@ApiModelProperty(value = "用户名称", required = true, example = "黑哥")
private String name;
@ApiModelProperty(value = "年龄", example = "10", allowableValues = "range[1, 150]")
private Integer age;
@ApiModelProperty(value = "结余", example = "423.05", allowableValues = "range[0.00, 99999999.99]")
private BigDecimal balance;
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", name=" + name + ", age=" + age + ", balance=" + balance + "]";
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public BigDecimal getBalance() {
return balance;
}
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
<file_sep># 集中API(swagger2+zuul整合)
如果部署几百个服务实例(jvm),那么需要一个可以集中展现API的方式。
就像zuul在服务网关中的作用一样(前置接入和路由转发),这里也使用zuul来前置swagger2_ui的访问,对不同服务的API文档访问,路由到不同的服务实例上。
理解为:每个服务实例上的/v2/api-docs(swagger2)也是一个服务,服务启动时把ip:port注册到eureka上,其提供的/v1/api-docs也可以通过服务客户端访问,也是通过zuul前置和转发。
当访问zuul的swagger_ui.html,会出现下拉框选择要查看服务实例。

我们已经有一个swagger2声明的服务(sc-swagger-test),这里我们重点介绍sc-zuul-swagger-test。
因为要转发**/{服务名}/v2/api-docs**到不同的服务实例上,因此我们要重新实现接口:SwaggerResourcesProvider
```java
@Component
@Primary
public class DocumentationConfig implements SwaggerResourcesProvider {
/** 日志 */
private static final Logger logger = LoggerFactory.getLogger(DocumentationConfig.class);
/** zuul 路由定位器 */
private final RouteLocator routeLocator;
/**
* spring context 自动注射 RouteLocator
* @param routeLocator
*/
public DocumentationConfig(RouteLocator routeLocator) {
this.routeLocator = routeLocator;
}
@Override
public List<SwaggerResource> get() {
List<SwaggerResource> resources = new ArrayList<>();
// zuul从eureka中获取服务位置,并注册到resources中
List<Route> routes = this.routeLocator.getRoutes();
logger.info(Arrays.toString(routes.toArray()));
routes.forEach(route -> {
resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs"),"1.0"));
});
return resources;
}
private SwaggerResource swaggerResource(String name, String location, String version) {
SwaggerResource swaggerResource = new SwaggerResource();
swaggerResource.setName(name);
swaggerResource.setLocation(location);
swaggerResource.setSwaggerVersion(version);
return swaggerResource;
}
}
```
核心是RouteLocator routeLocator对象,其是zuul提供的对象,作用:**服务定位器**,List<Route> routes = this.routeLocator.getRoutes();可以获取到服务的位置,其内部是基于ribbon实现,定时从eureka上拉取路由表。
# 安全问题
应单点部署一套测试环境(spring cloud),并提供zuul swagger访问,不应在生产环境上直接提供zuul swagger的访问。
## 公司内部访问
可以基于security basic认证,只有正确的输入用户和密码就可以访问。
```yml
# 开启安全认证(访问swagger需要basic认证)
security:
basic:
enabled: true
user:
name: sc-zuul-swagger
password: <PASSWORD>
```
## 公司外部访问
可以基于spring oauth2安全体系,使用角色和登录用户来限制,每个服务实例内部基于api角色来限制访问,例如:role_api,role_view_api,role_api可以执行try it out,而role_view_api只能查看。
<file_sep># 使用hystrix实现微服务的容错处理
当依赖的服务不可用时,服务自身会不会被拖垮?这是我们要考虑的问题。
## 理论基础
断路器可理解为对容易导致错误的操作的代理。这种代理能够统计一段时间内调用失败的次数,并决定是正常请求依赖的服务还是直接返回。
断路器可以实现快速失败,如果它在一段时间内检测到许多类似的错误(例如超时),就会在之后的一段时间内,强迫对该服务的调用快速失败,既不再请求所依赖的服务。
断路器也可自动诊断依赖的服务是否已经恢复正常。如果发现依赖的服务已经恢复正常,那么就会恢复请求该服务。使用这种方式,就可以实现微服务”自我修复“,当依赖的服务不正常时,打开断路器的快速失败,从而防止雪崩效应;当发现依赖的服务恢复正常时,又会恢复请求。
## 断路器状态转换逻辑
正常情况下,断路器关闭,可以正常请求依赖的服务。
当一段时间内,请求失败率达到一定阀值(错误率达到50%,请求数大于20),断路器就会打开(跳闸)。此时,不会再去请求依赖的服务。
断路器打开一段时间后,会自动进入“半开”状态。此时,断路器可允许一个请求通过访问依赖的服务。如果请求能够调用成功,则关闭断路器;否则继续保持打开状态。
## hystrix提供了
1. 包裹请求:使用HystrixCommand,包裹服务的调用逻辑,每个命令在独立线程中执行。命令模式。
2. 跳闸机制:当前某个服务的错误率超出一定阀值时,Hystrix可以自动跳闸,停止请求该服务一段时间。
3. **资源隔离**:Hystrix为每个依赖都维护一个小型的线程池。如果该线程池已满,发往该依赖的请求就立即被拒绝,而不是排队等候,从而快速失败。
4. 监控:Hystrix提供实时的监控运行指标。
5. 回退机制:当前请求失败、超时、被拒绝或者短路器已经打开(跳闸),直接调用“回退方法”返回数据。
6. 自我修复:断路器打开一段时间后,会自动进入“半开”状态,允许一个请求通过,要验证服务是否可用,可用则关闭断路器,不可以用继续打开断路器。
### hystrix线程(Thread)隔离
#### 在那个线程池中运行?
基于thread模式,可以做到线程隔离,被hystrix保护的方法(@HystrixCommand),运行在一个单独的线程池内,与调用线程分离。默认情况下根据**类名**来创建线程池,例如:UserController内部有两个方法,addUser(User)和ModifyUser(Long,User)方法,这个两个方法都使用@HystrixCommand修饰(被Hystrix保护),那么Hystrix会根据类名UserController来创建一个线程池,这两个方法的调用运行在在UserController线程池中。默认:池的大小为10个,队列大小为5。这就有个问题,如果一个jvm上跑100个Controller,那么就会创建100个线程池,每个10个线程,那就是1000个线程,这显然不能接受。因此我们要定制那些服务接口(Hystrix保护的方法),放在同一个线程池上,并合理的设置线程池和线程内线程的个数。
通过使用@HystrixCommand源注释内的threadPoolKey属性,设置当前方法运行在那个线程池上。例如:不同Controller的内的方法,运行在一个线程池上,或者同一个Controller内的两个方法运行在不同的线程池上。
```java
@HystrixCommand(groupKey = "heigeGroup", threadPoolKey = "heigeThreadPoolKey", fallbackMethod = "findUser5ByIdFallback", threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "1"),
@HystrixProperty(name = "maxQueueSize", value = "10")
}
)
@GetMapping(value = "/user5/{id}")
public User findUser1ById(@PathVariable Long id, @RequestParam int sleep) {
logger.info("request param sleep[{}].", sleep);
try {
Thread.sleep(sleep);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
return this.restTemplate.getForObject("http://sc-sampleservice/{id}", User.class, id);
}
@HystrixCommand(groupKey = "heigeGroup", threadPoolKey = "jiaojieThreadPoolKey", fallbackMethod = "findUser5ByIdFallback", threadPoolProperties = {
@HystrixProperty(name = "coreSize", value = "2"),
@HystrixProperty(name = "maxQueueSize", value = "10")
}
)
@GetMapping(value = "/user5a/{id}")
public User findUser2ById(@PathVariable Long id, @RequestParam int sleep) {
logger.info("request param sleep[{}].", sleep);
try {
Thread.sleep(sleep);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
return this.restTemplate.getForObject("http://sc-sampleservice/{id}", User.class, id);
}
```
#### hystrix线程池运行是否会阻塞调用的线程?
目前测试结果是,即使是使用线程池隔离策略(也就说hystrix保护的方法在独立的线程池上运行),调用这个hystrix保护方法的线程任会被阻塞,等待hystrix保护方法在其线程上运行后返回。
测试方法,tomcat设置1个线程,使用hystrix保护方法(method),默认池大小为10个。
如果发送请求,则controller代码运行在tomcat的线程池上,hystrix保护的方法运行在hystrix线程池上。
在浏览器上发送请求,代码执行进入到hystrix保护的方法后休眠(sleep),这时如果再使用另一个浏览器发送同样的请求,无法进入到controller,说明tomcat的这个线程已经被占用,tomcat执行线程在等待这个hystrix保护的方法线程执行完返回。
设置tomcat只最大运行的最大线程数为1:
```yaml
server:
tomcat:
max-threads: 1
min-spare-threads: 1
```
加大读取超时时间配置60000:
```yaml
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 60000
ribbon:
ReadTimeout: 60000
```
具体的代码,参见HystrixTest6Controller类。
总结:经过上面的测试,得到结论,调用线程和hystrix保护方法运行线程是1对1的,也就是说执行一个操作需要阻塞两个线程。那你可能要有疑问,hystrix是为了保护程序而使用线程隔离,而现在却多了1倍的线程,这样有什么意义?意义就在于即使多使用了1倍的线程,而对整个系统进行了保护。例如:默认hystrix保护的方法运行在线程大小为10的线程池中,如果被保护的方法出现慢处理,则10个线程都在运行中,这时如果第11个请求调用hystrix保护方法,由于线程池已满则直接回退。如果没有hystrix线程隔离,则所有tomcat线程都会被占满,知道最后超出max-threads限制。我们尽管使用了20个线程来处理,总比出现问题后整个系统所有的服务调用雪崩强呀。
# 使用hystrix实现微服务的容错处理
**pom.xml**
```xml
<!-- spring cloud hystrix -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- spring cloud feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- feign use apache httpclient -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
```
上面的spring cloud feign和feign-httpclient不是必须的,如果要结合feign+hystrix,则需要加入,否则如果你只使用ribbon则无必要加入。如果需要feign支持文件上传,则还有加入feign-form相关,具体见"feign文档"。
**启动application加入@EnableHystrix源注释**
```java
@SpringBootApplication
@EnableHystrix
@EnableFeignClients
public class HystrixTestApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(HystrixTestApplication.class, args);
}
}
```
如果要结合feign+hystrix,则需要加入@EnableFeignClients
**hystrix保护方法**
```java
@HystrixCommand(fallbackMethod = "findUser1ByIdFallback")
@GetMapping(value = "/user1/{id}")
public User findUser1ById(@PathVariable Long id, @RequestParam int sleep) {
logger.info("request param sleep[{}].", sleep);
try {
Thread.sleep(sleep);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
return this.restTemplate.getForObject("http://sc-sampleservice/{id}", User.class, id);
}
```
在需要hystrix保护的方法上,加上@HystrixCommand源注释,HystrixCommand的源注释参数比较多,具体见:com.netflix.hystrix.HystrixCommandProperties。
# 测试hystrix
## ~~测试超时~~
根据hystrix的默认配置,来测试超时。
**控制器代码**
为了方便测试,我们加入了sleep参数,可以控制方法的休眠时间,好方便测试延时。
```java
/**
* 测试超时
* @param id
* @param sleep 休眠时间
* @return
*/
@HystrixCommand(fallbackMethod = "findUser1ByIdFallback")
// @HystrixCommand(fallbackMethod = "findUser1ByIdFallback",commandProperties= {@HystrixProperty(name="execution.isolation.strategy",value="SEMAPHORE")})
@GetMapping(value = "/user1/{id}")
public User findUser1ById(@PathVariable Long id, @RequestParam int sleep) {
logger.info("request param sleep[{}].", sleep);
try {
Thread.sleep(sleep);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
return this.restTemplate.getForObject("http://sc-sampleservice/{id}", User.class, id);
}
/**
* 回退方法(降级方法)
* @param id
* @param sleep
* @return
*/
public User findUser1ByIdFallback(Long id, int sleep) {
logger.info("into fallback[{}].");
User user = new User();
user.setId(-1l);
user.setName("默认用户");
return user;
}
```
**测试用例**
```java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HystrixTest1 extends HystrixTestBase {
@Value("${local.server.port}")
private int port;
/**
* 测试方法:发送一个正确请求,休眠1100ms。
*
* @throws InterruptedException
*/
@Test
public void test() throws InterruptedException {
// 发送一个正常请求,休眠500ms
int sleep = 500;
User user = this.sendSpeelRequest(sleep);
logger.info("[{}]延时,返回正常User{}].",sleep,user);
// 发送一个超时请求,休眠1001ms
sleep = 1001;
user = this.sendSpeelRequest(sleep);
logger.info("[{}]延时,返回回退User{}].",sleep,user);
}
@Override
int getPort() {
return this.port;
}
}
```
本测试关系到配置属性:
execution.isolation.thread.timeoutInMilliseconds=1000(默认值)
本测试还可以验证,在SEMAPHORE模式也支持超时判断。
## 测试hystrix的断路器打开(跳闸)、保护机制、回退机制、自我修复
根据hystrix的默认配置,来测试hystrix的断路器打开(跳闸)、保护机制、回退机制、自我修复。
这里只是对关键的代码说明,具体还有参照本项目的代码。
**控制器代码**
为了方便测试,我们加入了status参数,status=true视为成功请求,status=false视为失败请求(抛出异常),方便测试错误率等。
```java
@HystrixCommand(fallbackMethod = "findUser2ByIdFallback")
@GetMapping(value = "/user2/{id}")
public User findUser2ById(@PathVariable Long id, @RequestParam Boolean status) {
if (status) {
logger.info("request param status[{}].", status);
return this.restTemplate.getForObject("http://sc-sampleservice/{id}", User.class, id);
} else {
int fc = this.failureCount.incrementAndGet();
logger.info("request param status[{}], failure count[{}].", status, fc);
throw new RuntimeException("test request failure.");
}
}
/**
* 回退方法(降级方法)
* @param id
* @return
*/
public User findUser2ByIdFallback(Long id, Boolean status) {
logger.info("into fallback[{}].",this.failureCount.get());
User user = new User();
user.setId(-1l);
user.setName("默认用户");
return user;
}
```
**验证测试用例**
```java
/**
* hystrix 测试用例2
* 用于验证:进入短路器打开(跳闸)状态后,5s内正确的请求也会被回退, 超出5s后正确的请求会关闭短路器。
* @author zhangdb
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HystrixTest2 extends HystrixTestBase {
@Value("${local.server.port}")
private int port;
@Autowired
private HystrixHealthIndicator hystrixHealthIndicator;
@Test
public void test() throws InterruptedException {
logger.info("init hystrix status[{}].", this.hystrixHealthIndicator.health().getStatus());
// 记录错误窗口期开始时间
long failureBeginTime = System.currentTimeMillis();
// 发送一个失败请求,激活错误窗口期
this.sendFailureRequest();
// 触发短路器跳闸
this.sendFailureRequest(20, 230);
logger.info("[{}]毫秒内执行了21个失败请求,短路器状态[{}].", System.currentTimeMillis() - failureBeginTime, this.hystrixHealthIndicator.health().getStatus());
// 5s内的正确请求,都会被回退
for (int i = 0; i < 4; i++) {
User user = this.sendSuccessRequest();
this.logger.info("5s内的正确请求都会被回退,User:{},短路器状态[{}].", user, this.hystrixHealthIndicator.health().getStatus());
Thread.sleep(1000);
}
// 5s后的正确的请求,会正确返回,断路器关闭
Thread.sleep(1000);
User user = this.sendSuccessRequest();
this.logger.info("超出5s后正确的请求正常执行,User:{},短路器状态[{}].", user, this.hystrixHealthIndicator.health().getStatus());
}
```
运行这个测试用例,查看日志输出,并且参照上面的理论文档介绍。
本测试关系到的配置属性:
metrics.rollingStats.timeInMilliseconds=10000 ,错误窗口时间,第一个错误请求开始。
circuitBreaker.requestVolumeThreshold=20,打开跳闸的最低请求数。错误时间窗内,只有大于这个值才能跳闸。
circuitBreaker.errorThresholdPercentage=50,失败请求的数大于这个百分比,才能跳闸。
例如:this.sendFailureRequest(20, 230);,发送20个错误请求,每个间隔230ms,这样5000-6000ms内就会打开断路器,正好满足上面三项配置要求。
circuitBreaker.sleepWindowInMilliseconds=5000,跳闸后这个配置时间内,任何请求(正确或者失败请求)都会被回退,这是一种保护。超出这个值,则允许一个请求通过,如果正确返回则关闭断路器,如果失败则保持跳闸状态,并且还是本配置时间内,都会被回退。
## 测试Hystrix的线程上下文变量(ThreadLocal)传递
如果hystrix基于的THREAD模式,则ThreadLocal中的值使用无法传递到@HystrixCommand声明的方法,因为隶属两个不同的线程。
有兴趣大家可以看:SleuthHystrixConcurrencyStrategy的实现代码。
如下代码,是一个很平常的代码,User对象被存放到UserContext中(基于ThreadLocal存放User),但在其无法传递到hystrix保护的方法内,因为hystrix的保护方法执行在另一个线程内,和调用线程不是同一个线程,因此ThreadLocal无法传递。
```java
@GetMapping(value = "/user3/{id}")
public User findUser3ById(@PathVariable Long id) {
User user = this.restTemplate.getForObject("http://sc-sampleservice/{id}", User.class, id);
UserContext.setUser(user); // UserContext内部基于ThreadLocal实现
user = this.hystrixConcurrentStrategyTestBean.findUser3Hystrix(); // 被hystrix保护
UserContext.remove();
return user;
}
```
```java
public class UserContext {
private static final ThreadLocal<User> userThreadLocal = new ThreadLocal<User>();
public static User getUser() {
return userThreadLocal.get();
}
public static void setUser(User user) {
userThreadLocal.set(user);
}
public static void remove() {
userThreadLocal.remove();
}
}
```
```java
@Component
public class HystrixConcurrentStrategyTestBean {
/** 日志 */
private static final Logger logger = LoggerFactory.getLogger(HystrixConcurrentStrategyTestBean.class);
@HystrixCommand(fallbackMethod = "findUser3HystrixFallback")
public User findUser3Hystrix() {
User user = UserContext.getUser(); // UserContext内部基于ThreadLocal实现
logger.info("user value[{}].",user);
return user;
}
public User findUser3HystrixFallback() {
logger.info("into fallback.");
User user = new User();
user.setId(-1l);
user.setName("默认用户");
return user;
}
}
```
为了解决上面的问题,我们要自定义hystrix的并发策略类(HystrixConcurrencyStrategy),继承这个类,并重新实现wrapCallable(Callable<T> callable)方法,对callback参数进行包装,并返回给hystrix线程。在call()方法调用前,把User对象传递到hystrix线程的线程变量(ThreadLocal)中。代码如下:
```java
public class UserContextCallable<V> implements Callable<V> {
private final User user;
private final Callable<V> callable;
/**
* 外围线程初始化(例如:tomcat请求线程)
* @param callable
* @param user
*/
public UserContextCallable(Callable<V> callable,User user) {
super();
this.user = user;
this.callable = callable;
}
/**
* Hystrix隔离仓线程调用(hystrix执行线程)
*/
@Override
public V call() throws Exception {
UserContext.setUser(this.user); // 调用前把User对象绑定到hystrix的线程变量
try {
V v = this.callable.call();
return v;
} finally {
UserContext.remove(); // 清理线程变量的User对象
}
}
}
```
```java
@Configuration
public class UserContextCallbackConfiguration {
@Bean
public Collection<HystrixCallableWrapper> hystrixCallableWrappers() {
Collection<HystrixCallableWrapper> wrappers = new ArrayList<>();
wrappers.add(new HystrixCallableWrapper() {
@Override
public <V> Callable<V> wrap(Callable<V> callable) {
return new UserContextCallable<V>(callable, UserContext.getUser());
}
});
return wrappers;
}
}
```
我参照网上的例子,已经实现了一个公共的HystrixConcurrencyStrategyCustom实现类,大家有兴趣可以查看sc.com.hystrix.concurrentstrategy包内的代码。
测试用例代码:
```java
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HystrixTest3 {
@Value("${local.server.port}")
private int port;
@Test
public void test() {
RestTemplate rest = new RestTemplate();
User user = rest.getForObject("http://localhost:{port}/user3/1", User.class, this.getPort());
System.out.println(user);
Assert.assertNotNull(user);
}
public int getPort() {
return port;
}
}
```
## 测试hystrix+ribbon
可以参考zuul文档的 2.8.1 计算ribbonTimeout 和 2.8.2 计算hystrixTimeout 章节。
## 测试hystrix+feign
如果feign要使用hystrix保护,则需要加入配置(默认feign不受hystrix保护):
```yaml
feign:
httpclient:
# 使用apache httpclient
enabled: true
hystrix:
# 开启hystrix+feign
enabled: true
```
**读取超时时间(readTimeout)**
默认为1000ms,如果要定制feign+hystrix的超时时间,则由feign.client.config.default.readTimeout和hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds两者中最小值来决定。
```yaml
# hystrix
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 2000
# feign
feign:
httpclient:
# 使用apache httpclient
enabled: true
client:
config:
# 定义全局的feign设置
default:
connectTimeout: 1000
readTimeout: 3000
hystrix:
# 开启hystrix+feign
enabled: true
```
如果上面的配置,则调用feign方法的超时时间为2000毫秒,如果你把hystrix的timeoutInMilliseconds修改为4000,则调用feign方法的超时时间为3000毫秒。
你可以通过发送请求:http://localhost:8300/user4/1?sleep=2800,调整sleep参数,来验证上面的配置。
**定制某个feign方法的超时时间**
例如某个方法处理时间比较长,需要大于默认值1000ms的超时处理时间,例如:文件上传处理。
因为默认情况下,ribbon、feign、hystrix的超时时间都是1000ms,因此我们只有调整配置,能让某个单独的feign方法调用(服务),能稳定运行在xxxx ms就可以了,例如:uploadFile方法超时时间设置5000ms。
定制某个feign方法的hystrix参数比较费劲,需要先根据这个feign方法计算出对应的HystrixCommandKey,计算公式为:feign接口名#方法名(参数1类型,参数2类型,参数x类型),只要一个字符不对也不行,因此最好的方法是调试调试feign.Feign类的configKey的方法,获取准确的HystrixCommandKey。
```java
public static String configKey(Class targetType, Method method) {
StringBuilder builder = new StringBuilder();
builder.append(targetType.getSimpleName());
builder.append('#').append(method.getName()).append('(');
for (Type param : method.getGenericParameterTypes()) {
param = Types.resolve(targetType, targetType, param);
builder.append(Types.getRawType(param).getSimpleName()).append(',');
}
if (method.getParameterTypes().length > 0) {
builder.deleteCharAt(builder.length() - 1);
}
return builder.append(')').toString();
}
```
例如:一个声明@FeignClient类的方法,如下,通过调试上面的configKey方法计算后的HystrixCommandKey为SampleServiceFeignClient#findByIdWithSleep(Long,Long):
```java
@FeignClient(name = "sc-sampleservice")
public interface SampleServiceFeignClient {
@RequestMapping(value = "/{id}", params = "sleep", method = RequestMethod.GET)
User findByIdWithSleep(@PathVariable("id") Long id, @RequestParam(value = "sleep", required = false, defaultValue = "0") Long sleep);
}
```
获取到这个feign方法对应的HystrixCommandKey后,我们就可以为这个feign方法单独设置hystrix参数了,例如:读取超时时间。
```yaml
# hystrix 启动并发策略(自定义属性)
hystrix:
concurrent_strategy:
enabled: true
command:
SampleServiceFeignClient#findByIdWithSleep(Long,Long):
execution:
isolation:
thread:
timeoutInMilliseconds: 2000
feign:
httpclient:
# 使用apache httpclient
enabled: true
client:
config:
# 定义sc-sampleservice服务的feign设置
sc-sampleservice:
connectTimeout: 1000
readTimeout: 2000
hystrix:
# 开启hystrix+feign
enabled: true
```
因此遵照feign+hystrix组合使用最小配置值为超时时间的规则,因此我们要同时调整两个参数:hystrix的timeoutInMilliseconds和feign的readTimeout参数(参照上面的yml配置),否则无效。
参照上面yml,如果要调整feign方法SampleServiceFeignClient#findByIdWithSleep(Long,Long)的读取超时时间为2000ms,需要分别设置timeoutInMilliseconds: 2000 ,readTimeout: 2000(@FeignClient(name = "sc-sampleservice")声明服务;),否则无效。
验证测试:
URL请求http://localhost:8300/user4/1?sleep=xxx,会触发HystrixTest4Controller调用hystrix保护的feign方法SampleServiceFeignClient#findByIdWithSleep(Long,Long)。
URL请求http://localhost:8300/user1/1?sleep=xxx,会触发HystrixTest1Controller调用hystrix保护的ribbon方法User findUser1ById(@PathVariable Long id, @RequestParam int sleep)。
发送请求,http://localhost:8300/user4/1?sleep=1800,返回正确的User信息。 证明单独的hystrix+feign某个方法调用超时配置有效。
发送请求,http://localhost:8300/user4/1?sleep=2100,报错或返回回退的User信息。证明单独的hystrix+feign某个方法调用超时配置有效。
发送请求,http://localhost:8300/user1/1?sleep=1800,报错或返回回退的User信息。证明单独的hystrix+feign某个方法调用超时配置有效,但系统的默认超时时间还是1000ms,也就是没有单独配置的方法受到默认值的控制。
## Hystrix监控
如果项目加入spring-boot-starter-actuator,就可以监控hystrix的运行情况,使用如下的URL持续监控(默认每隔500ms刷新一次)。
http://localhost:8300/hystrix.stream
关于Hystrix Dashboard可视化数据监控,可以查看sc-hystrix-turbine目录文档。
<file_sep># spring cloud zuul
微服务网关:介于客户端和服务器端之间的中间层,所有的外部请求都会先经过微服务网关。微服务网关经过过滤出来和路由查询,转发请求到对应的服务器。
默认请求下zuul服务器,使用ribbon来定位eureka server中的微服务;同时,还整合了hystrix实现容错,所有经过zuul的请求都会在Hystrix命令中执行。
注意:尽管zuul起到了服务网关的作用,但还是强烈建议在生产环境中**zuul一定要前置nginx**。

## 1. zuul服务器配置
### 1.1 pom.xml
```xml
<!-- spring cloud zuul -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
```
### 1.2 application.yml
```yaml
# 配置zuul->ribbon->使用APACHE HTTP Client
ribbon:
restclient:
enabled: true
# 配置zuul
zuul:
ignored-services: '*'
routes:
sc-sampleservice: /sampleservice/**
```
配置zuul转发请求使用Apache HttpClient。
配置zuul忽略所有eureka上获取的服务,并指定某些服务对外开放。
这样是做的好处:
1. 解决安全问题,不能所有在eureka上的服务都暴露出去。
2. 通过routes配置可以指定服务的请求路径前缀和服务ID之间的映射(类似于DNS),这样即使服务ID修改了,对外提供的URL不变。
3. 动态刷新路由配置(routes),通过测试Edgware.SR6版本可以做到,git修改配置后,/bus刷新马上生效,无须重新启动zuul。
POST请求,发送:http://config-ip:config-port/bus/refresh?destination=sc-zuul:**
### 1.3 ZuulApplication.java
```java
@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
```
### 1.4 验证zuul启动是否成功
浏览器请求:http://zuul-ip:zuul-port/routes,查看返回的服务路由信息。
查看路由详细信息:http://192.168.5.31:8090/routes?format=details
查看应用的过滤器信息:http://192.168.5.31:8090/filters
## 2. zuul配置
### 2.1 配置使用路由前缀
```yaml
# 配置zuul
zuul:
# 忽略所有的服务
ignored-services: '*'
# 指定请求前缀
prefix: /api
# 转发请求到服务时,是否去掉prefix前缀字符
strip-prefix: true
# 开放服务
routes:
sc-sampleservice: /sampleservice/**
```
关注:zuul.prefix=/api 和 zuul.strip-prefix=true 两处配置。
测试:http://192.168.5.31:8090/api/sampleservice/1,请求前缀加入了/api。
这样做还有一个好处,就是可以在zuul的前端加入nginx,nginx把所有的/api请求转发到zuul上。
**注意:zuul.routes的配置,支持/bus在线属性配置。**
### 2.2 敏感的Header设置
设置哪些Header可以穿透zuul传递到服务。
例如,设置zuul的sc-sampleservice服务路由,允许三个header请求头达到sc-sampleservice服务。
```yaml
# 配置zuul
zuul:
# 忽略所有的服务
ignored-services: '*'
# 指定请求前缀
prefix: /api
# 转发请求到服务时,是否去掉prefix前缀字符
strip-prefix: true
# 配置路由
routes:
# 配置sc-sampleservice服务路由
sc-sampleservice:
path: /sampleservice/**
sensitive-headers: Cookie,Set-Cookie,Authorization
```
关注:sensitive-headers: Cookie,Set-Cookie,Authorization
验证:查看zuul路由配置信息,http://192.168.5.31:8090/routes?format=details,返回:

你也可以通过设置,zuul.ignoredHeaders 来忽略一些Header。
以上的配置支持/bus动态刷新配置。
### 2.3 Zuul上传文件
对于小于1M上传,无须任何任何处理,可以正常上传。大于1M,则需要特殊设置,配置允许最大请求字节数和单个上传的字节数。不支持/bus动态刷新配置。
```yaml
spring:
http:
multipart:
# 整个请求大小限制(1个请求可能包括多个上传文件)
max-request-size: 20Mb
# 单个文件大小限制
max-file-size: 10Mb
```
测试:postman发送post请求,http://192.168.5.31:8090/api/sampleservice/uploadFile
注意:mulitpart的设置,在zuul和upload服务都要设置。
如果是在互联网上传文件,则要考虑到网络带宽和延时等问题,因此要加大超时时间,例如:
```yaml
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 10000
ribbon:
ReadTimeout: 10000
ConnectTimeout: 2000
```
同上面mulitpart的设置,zuul和upload服务都要设置这个超时时间。
**考虑到上面的配置为了上传,加大了请求大小字节数和超时时间,这在上传操作很有用,但如果是普通的服务调用,则会有安全问题,因此强烈建议为upload单独设置一个zuul服务器,只有这台zuul服务器才需要调大这些配置。**例如:/api/dfss/upload的请求,nginx会根据url来转发到这台占用于上传处理的zuul上。
### 2.4 zuul过滤器
Zuul大部分功能都是通过过滤器来实现的。Zuul中定义了4中标准过滤器类型,这些过滤器类型对应请求的典型生命周期。
PRE:这种过滤器在请求被路由之前调用。可利用这种过滤器实现身份认证、获取请求的微服务、记录调试等。
POUTING:这种过滤器将请求路由到微服务,用于构建发送给微服务的请求。
POST:这种过滤器在路由到微服务以后执行,用于为响应添加Http Header、收集统计信息、将响应发送给客户端等。
ERROR:发送错误是执行该过滤器。
STATIC:不常用,直接在Zuul中生成响应,不将请求转发到后端微服务。
#### 2.4.1 内置过滤器
Zuul了一些过滤器,谁zuul启动。
**@EnableZuulServer所启动的过滤器**
PRE 类型过滤器:
ServletDetectionFilter:检查请求是否通过了Spring Dispatcher。
FormBodyWrapperFilter:解析表单数据,并为请求重新编码。目前效率低,如果基于json传递请求体,则可禁止该过滤器。
DebugFilter:调试过滤器,当设置zuul.debug.request=true,并且请求加上debug=true参数,就会开启调试过滤器。
ROUTE 类型过滤器:
SendForwardFilter:使用Servlet RequestDispathcer转发请求,转发位置存在在RequestContext的属性FilterConstant.FORWARD_TO_KEY中。用于zuul自身转发(forward)。
```yaml
zuul:
routes:
path: /path-a/**
url: forward:/path-b
```
POST 类型过滤器:
SendResponseFilter:代理请求响应写入响应。
ERROR 类型过滤器:
SendErrorFilter:若RequestContext.getThrowable()不为null,则默认转发到/error,也可以使用error.path属性来修改。
**@EnableZuulProxy所启动过滤器**
@EnableZuulProxy启动的过滤包含上面@EnableZuulServer启动的过滤器。
PRE 类型过滤器:
PreDecorationFilter:根据RouteLocator对象确定要路由到的地址(微服务位置),以及怎样去路由。
查看sc-zuul-swagger-test项目的DocumentationConfig类,了解RouteLocator对象如果被使用。
ROUTE 类型过滤器:
RibbonRouteFilter:使用Ribbon、Hystrix、HTTP客户端发送请求。servletId在RequestContext的属性FilterConstants.SERVICE_ID_KEY中。
SimpleHostRoutingFilter:如果路由配置直接指定了服务的url,而不能从eureka中获取位置,则使用这个过滤器。
**禁止某个过滤器**
zuul.<SimpleClassName>.<filterType>.disable=true
例如:zuul.FormBodyWrapperFilter.pre.disable=true
#### 2.4.2 自定义过滤器
因为声明了@Component定义为SpringBean,zuul会自动识别并应用这个过滤器。
```java
@Component
public class PreRequestLogFilter extends ZuulFilter {
/** 日志 */
private final Logger logger = LoggerFactory.getLogger(PreRequestLogFilter.class);
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
logger.info("send [{}] request to [{}].", request.getMethod(), request.getRequestURL().toString());
return null;
}
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;
}
}
```
#### 2.4.3 伟大的RequestContext
zuul过滤器中最关键的技术就是RequestContext,其实一个上下文对象,包含zuul使用的几乎所有技术。下面说几个重点的:
1.其继承了ConcurrentHashMap对象,实现了Map所有的接口。
2.基于线程变量ThreadLocal来存储当前实例。
3.request和response都被存放到当前的map中,因此你可以在代码的任何位置来操作request和response。
4.setThrowable(Throwable th)代表zuul执行的过程中出现了异常,如果你的ZuulFilter在执行的过程中抛出了异常,zuul会自动调用这个方法添加异常对象到上下文中,你可以手工赋值(表示出现了异常)。你可以编写一个ErrorFilter来处理异常,这需要使用getThrowable()的方法来获取异常,如果异常处理完了,则一定要调用remove("throwable")来删除这个异常,表示已经没有异常了,否则异常会被传递下去。
5.任何响应的输出,不要直接使用response提供的方法来操作(RequestContext.currentContext().getResponse().xxx()),应该使用RequestContext提供的方法来设置response相关数据,例如:添加响应头RequestContext.currentContext().addZuulRequestHeader("code","ok");你调用任何RequestContext上的操作response的相关方法,SendResponseFilter过滤器(zuul原生)都会帮你输出。例如:setResponseBody(String)、setResponseDataStream(InputStream)、addZuulResponseHeader(String, String)、setOriginContentLength(Long)等。
6.setRouteHost(new URL("http:/xxx")),这个类似于nginx的proxyPass ip地址,请求会被zuul转发到这个地址。
7.SERVICE_ID_KEY,zuul提供了一个关键字就是SERVICE_ID_KEY,设置这个值会改变请求的服务,例如:RequestContext.getCurrentContext().put(FilterConstants.SERVICE_ID_KEY, "myservices");,这里的服务可以是eureka上的服务、在配置文件zuul.route声明的手工服务等,你可以通过编程的方式来改变请求的服务。例如:手工指定服务,
```yaml
zuul:
routes:
tgms-service:
path: /services
serviceId: myservices
myservices:
ribbon:
NIWSServerListClassName: com.netflix.loadbalancer.ConfigurationBasedServerList
listOfServers: 172.16.58.3:80,172.16.58.3:81
```
8.REQUEST_URI_KEY,改变转发请求的uri,例如:RequestContext.getCurrentContext().put(FilterConstants.REQUEST_URI_KEY,"/tgms-services"),例如:你浏览器的请求地址为http://localhost:5000/services,则经过本代码转发到upstream的请求url已经是/tgms-services,不再是/services了。
#### 2.4.4 FilterConstants
zuul的关键字和内置过滤器执行顺序都在这个常量类中定义。看这个常量,你能有收获。
#### 2.4.5 ZuulFilter.filterOrder()
```java
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
@Override
public int filterOrder() {
return 1;
}
```
zuul根据这个值来决定过滤器执行的先后顺序,同一种filterType类型的两个ZuulFilter的filterOrder()不能相同,但不同种类filterType的filterOrder()可以相同,因为zuul是逐个类型(filterType)执行的。
技巧:因为PRE类型,可用的filterOrder()不多,一般情况下应使用2、3、4,这个可以通过查看FilterConstants常量来理解。如果你需要定义4个PRE类型的过滤器,filterOrder不够用了,这里有个技巧,你可以把两个没有相互依赖关系的ZuulFilter都定义为同一个filterOrder(),例如都定义为3。
### 2.4 Zuul容错和回退
#### 2.4.1 hystrix监控
http://zuul-ip:zuul-port/hystrix.stream,查看会查看到hystrix监控数据,也就是说默认情况下zuul的请求是收到zuul保护的,而且还能看出Thread Pools无相关数据,也证明了默认使用的hystrix隔离策略时SEMAPHORE。
#### 2.4.2 自定义回退类
因为声明了@Component定义为SpringBean,zuul会自动识别并应用这个回退提供者实现。
```java
@Component
public class MyFallbackProvider implements FallbackProvider {
@Override
public String getRoute() {
// 表明为哪个微服务提供回退,* 表示所有微服务提供
return "*";
}
@Override
public ClientHttpResponse fallbackResponse(Throwable cause) {
// 注意,只有hystrix异常才会好触发这个接口
if (cause instanceof HystrixTimeoutException) {
return response(HttpStatus.GATEWAY_TIMEOUT);
} else {
return this.fallbackResponse();
}
}
@Override
public ClientHttpResponse fallbackResponse() {
return this.response(HttpStatus.INTERNAL_SERVER_ERROR);
}
private ClientHttpResponse response(final HttpStatus status) {
return new ClientHttpResponse() {
@Override
public InputStream getBody() throws IOException {
return new ByteArrayInputStream(("{\"code\":\""+ status.value()+"\",\"message\":\"服务不可用,请求稍后重试。\"}").getBytes());
}
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
MediaType mt = new MediaType("application", "json", Charset.forName("UTF-8"));
headers.setContentType(mt);
return headers;
}
@Override
public HttpStatus getStatusCode() throws IOException {
return status;
}
@Override
public int getRawStatusCode() throws IOException {
return status.value();
}
@Override
public String getStatusText() throws IOException {
return status.getReasonPhrase();
}
@Override
public void close() {
}
};
}
}
```
测试验证:http://192.168.5.31:8090/api/sampleservice/1?sleep=2000,触发hystrix超时抛出,进而触发回退操作。
### 2.5 饥饿加载
zuul整合ribbon实现负载均衡,而ribbon默认是懒加载,可能会导致首次请求较慢。如果配置则修改为启动加载。
```yaml
zuul:
ribbon:
# 修改为启动加载(默认为懒加载)
eager-load:
enabled: true
```
验证:启动时,查看log信息,会发现有DynamicServerListLoadBalancer字样。
### 2.6 QueryString 编码
如果要强制让query string与HttpServletRequest.getQueryString()保持一致,可使用如下配置:
```yaml
zuul:
# queryString保持一致
forceOriginalQueryStringEncoding: true
```
注意:只对SimpleHostRoutingFilter有效。
### ~~2.7 Hystrix隔离策略和线程池~~
修改为线程隔离后,服务运行的线程池位置,两种模式只能选择一种:
1. 在同一个线程池RibbonCommand下运行,所有的服务都在这个RibbonCommand线程池要运行。
2. 每个服务都有一个独立的线程。
以上两个都有问题,第1种,如果所有的服务都在一个线程池下运行,那就失去了线程隔离的意义,一个服务出现阻塞,则整个RibbonCommand线程池瘫痪。第2种,如果调用100个服务,就分配100个线程池吗,这也有问题。
最理想,默认都使用RibbonCommand线程池调用服务,但可以为某个服务单独设置一个线程池。
#### 2.7.1 配置zuul使用thread隔离策略
默认情况下,Zuul的Hystrix隔离策略时**SEMAPHORE**。
可以使用zuul.ribbon-isolation-strategy=thread修改为THREAD隔离策略,修改后HystrixThreadPoolKey默认为RibbonCommand,这意味着,所有的路由HystrixCommand都会在相同的Hystrix线程池上执行。
修改后可以通过hystrix的dashborad观察,可以看到ThreadPools栏有数据了。

也可以为每个服务(路由),使用独立的线程池,并使用hystrix.threadpool.服务名,来定制线程池大写:
```yaml
zuul:
threadpool:
useSeparateThreadPools: true
hystrix:
threadpool:
sc-sampleservice:
coreSize: 3
```

### 2.8 设置超时时间
在基于zuul+hystrix+ribbon组合情况下设置读取超时时间(ReadTimeout)相对复杂一些,其需要先预估一个服务调用允许的超时时间,然后根据这个预估的参考值来计算相关属性值。
~~默认配置如下(配置文件中无超时相关配置):~~
```properties
ribbon.restclient.enabled=false
hystrix.command.<ServiceId>.execution.isolation.thread.timeoutInMilliseconds=4000
<ServiceId>.ribbon.ConnectTimeout=1000
<ServiceId>.ribbon.ReadTimeout=1000
```
设置全局的超时时间,要同时设置如下几个值:
```properties
ribbon.restclient.enabled=true
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds=xxxxx
ribbon.ConnectTimeout=xxxxx
ribbon.ReadTimeout=xxxxx
```
设置某个服务的超时时间,要同时设置如下几个值:
```properties
ribbon.restclient.enabled=true
hystrix.command.<ServiceId>.execution.isolation.thread.timeoutInMilliseconds=xxxxx
<ServiceId>.ribbon.ConnectTimeout=xxxxx
<ServiceId>.ribbon.ReadTimeout=xxxxx
```
#### 2.8.1 计算ribbonTimeout
**公式如下:**
```java
ribbonTimeout = (ribbonReadTimeout + ribbonConnectTimeout) * (maxAutoRetries + 1) * (maxAutoRetriesNextServer + 1);
```
**来源于:**org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand.getRibbonTimeout()
例如:如下是你的配置;
```properties
ribbon.ConnectTimeout=1000
ribbon.ReadTimeout=10000
```
套用上面的公式计算(默认值:maxAutoRetries = 0,maxAutoRetriesNextServer = 1):
(10000 + 1000) * (0 + 1) * (1 + 1) = 22000;
也就说,你配置的ReadTimeout为10000,而实际上系统计算出的ribbonTimeout为22000;因此应根据公式,反推算出一个ribbon.ReadTimeout;
计算ribbonTimeout的java代码:
```java
protected static int getRibbonTimeout(IClientConfig config, String commandKey) {
int ribbonTimeout;
if (config == null) {
ribbonTimeout = RibbonClientConfiguration.DEFAULT_READ_TIMEOUT + RibbonClientConfiguration.DEFAULT_CONNECT_TIMEOUT;
} else {
int ribbonReadTimeout = getTimeout(config, commandKey, "ReadTimeout",
IClientConfigKey.Keys.ReadTimeout, RibbonClientConfiguration.DEFAULT_READ_TIMEOUT);
int ribbonConnectTimeout = getTimeout(config, commandKey, "ConnectTimeout",
IClientConfigKey.Keys.ConnectTimeout, RibbonClientConfiguration.DEFAULT_CONNECT_TIMEOUT);
int maxAutoRetries = getTimeout(config, commandKey, "MaxAutoRetries",
IClientConfigKey.Keys.MaxAutoRetries, DefaultClientConfigImpl.DEFAULT_MAX_AUTO_RETRIES);
int maxAutoRetriesNextServer = getTimeout(config, commandKey, "MaxAutoRetriesNextServer",
IClientConfigKey.Keys.MaxAutoRetriesNextServer, DefaultClientConfigImpl.DEFAULT_MAX_AUTO_RETRIES_NEXT_SERVER);
ribbonTimeout = (ribbonReadTimeout + ribbonConnectTimeout) * (maxAutoRetries + 1) * (maxAutoRetriesNextServer + 1);
}
return ribbonTimeout;
}
```
#### 2.8.2 计算hystrixTimeout
如果没有在配置文件中设置timeoutInMilliseconds,则使用ribbonTimeout作为hystrixTimeout,否则使用配置文件中的timeoutInMilliseconds作为hystrixTimeout。
**来源于:**
org.springframework.cloud.netflix.zuul.filters.route.support.AbstractRibbonCommand.getHystrixTimeout()
例如:如下是你的配置;
```yaml
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 22000
```
计算hystrixTimeout的java代码:
```java
protected static int getHystrixTimeout(IClientConfig config, String commandKey) {
int ribbonTimeout = getRibbonTimeout(config, commandKey);
DynamicPropertyFactory dynamicPropertyFactory = DynamicPropertyFactory.getInstance();
int defaultHystrixTimeout = dynamicPropertyFactory.getIntProperty("hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds",
0).get();
int commandHystrixTimeout = dynamicPropertyFactory.getIntProperty("hystrix.command." + commandKey + ".execution.isolation.thread.timeoutInMilliseconds",
0).get();
int hystrixTimeout;
if(commandHystrixTimeout > 0) {
hystrixTimeout = commandHystrixTimeout;
}
else if(defaultHystrixTimeout > 0) {
hystrixTimeout = defaultHystrixTimeout;
} else {
hystrixTimeout = ribbonTimeout;
}
if(hystrixTimeout < ribbonTimeout) {
LOGGER.warn("The Hystrix timeout of " + hystrixTimeout + "ms for the command " + commandKey +
" is set lower than the combination of the Ribbon read and connect timeout, " + ribbonTimeout + "ms.");
}
return hystrixTimeout;
}
```
#### 2.8.3 ribbonTimeout和hystrixTimeout的关系
ribbonTImeout用于ribbon底层http client的socket的timeout,也就说用于网络的读取超时。
hystrixTimeout用于方法执行时间超时,理解为:future.get(hystrixTimeout)。
两者之间是在功能上是有区别。
例如:
ribbonTimeout超时报错:Caused by: java.net.SocketTimeoutException: Read timed out
hystrixTimeout超时报错:Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: dfss-upload timed-out and no fallback available.
### 2.9 zuul使用ribbon重试
测试重试,后台开启两个sc-sampleservice的docker,使用zuul做为服务网关,接收请求,正常情况下是负载均衡分发,当停止一个sc-sampleservice的docker,再发送请求到zuul看能否正常返回结果,并通过日志查看是否有重试操作。
默认情况:就已经开启了重试,重试的默认值:maxAutoRetries = 0,maxAutoRetriesNextServer = 1,测试通过。
maxAutoRetries 同一实例重试次数,默认为0。
maxAutoRetriesNextServer 重试其它实例的最大次数,如果有3个实例,应该设置2,默认值1。
### 2.10 设置信号量
在默认的SEMAPHORE隔离策略下,信号量可以控制服务允许的并发访问量。
```yaml
zuul:
# 设置默认最大信号量
semaphore:
max-semaphores: 100
# 设置某个服务的最大信号量
eureka:
sc-sampleservice:
semaphore:
max-semaphores: 50
```
### 2.11 tomcat参数设置
通过设置tomcat参数来调整zuul对外服务能力
```yaml
server:
tomcat:
max-connections: 1000
max-threads: 200
min-spare-threads: 10
accept-count: 50
```
### 3. Zuul高可用
Zuul可以像其它的spring cloud组件一样,把其注册到eureka上来实现zuul的高可用。但有些情况下,需要浏览器和app直接访问zuul,这种情况下可以使用nginx、HAProxy、F5等实现HA,并后接多个ZUUL来实现负载均衡和高可用。最佳实践是两种都用,两个zuul都注册到eureka上,供内网eureka客户端调用,并前置nginx(HA)供外网用户访问。
### 4.zuul整合其他非eureka上的服务
#### 4.1 配置routes路由请求到指定的URL
```yaml
zuul:
# 开放服务
routes:
# 测试整合其它非eureka上的服务
dongyuit:
path: /dongyuit/**
url: http://www.dongyuit.cn/
```
自定义了一个路由dongyuit,所有对/dongyuit/**前置的请求都会转发到http://www.dongyuit.cn/ ,例如:
http://192.168.5.31:8090/api/dongyuit/index.html
但要注意:上面的整合方法,请求不支持ribbon和hystrix,也就是说不支持负载均衡和hystrix容错。待以后解决。
#### 4.2 sidecar
需要被整合的服务端实现/health,这在整合一些第三方服务的情况下不可能,第三方法不可能给你实现一个/health功能。待以后解决。
## FAQ
### 1.安全问题
actutor安全问题?,待以后oauth2解决。
<file_sep>package sc.com.hystrix;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import sc.com.hystrix.domain.User;
public abstract class HystrixTestBase {
final Logger logger = LoggerFactory.getLogger(this.getClass());
User successUser() {
User user = new User();
user.setId(1l);
user.setName("黑哥");
return user;
}
User fallbackUser() {
User user = new User();
user.setId(-1l);
user.setName("默认用户");
return user;
}
User sendFailureRequest() {
RestTemplate rest = new RestTemplate();
User user = rest.getForObject("http://localhost:{port}/user2/1?status=false", User.class, this.getPort());
return user;
}
User sendSuccessRequest() {
RestTemplate rest = new RestTemplate();
User user = rest.getForObject("http://localhost:{port}/user2/1?status=true", User.class, this.getPort());
return user;
}
void sendSuccessRequest(int num,int sleep) throws InterruptedException {
for(int i=0;i<num;i++) {
this.sendSuccessRequest();
Thread.sleep(sleep);
}
}
void sendFailureRequest(int num,int sleep) throws InterruptedException {
for(int i=0;i<num;i++) {
this.sendFailureRequest();
Thread.sleep(sleep);
}
}
User sendSpeelRequest(int sleep) {
RestTemplate rest = new RestTemplate();
User user = rest.getForObject("http://localhost:{port}/user1/1?sleep={sleep}", User.class, this.getPort(),sleep);
return user;
}
abstract int getPort() ;
}
<file_sep># 链路跟踪 sleuth
微服务跟踪(sleuth)其实是一个工具,它在整个分布式系统中能跟踪一个用户请求的过程(包括数据采集,数据传输,数据存储,数据分析,数据可视化),捕获这些跟踪数据,就能构建微服务的整个调用链的视图,这是调试和监控微服务的关键工具。
## 1.sleuth原理
sleuth会在起点服务处,产生一个唯一序号作为整个请求的序号(TraceId),然后在每个经过的服务生产一个唯一序号(SpanId)代表请求的服务序号,然后通过日志把TraceId和SpanId串起来,形成请求日志序号,这样你就可以根据日志的TraceId部分来识别整个请求都经过了那些服务SpanId。
如果服务请求使用了spring cloud提供的ribbon和feign,则会在请求中自动把sleuth相关信息带进去,传递到下一个服务请求。
## 2. sleuth配置
sleuth配置相对简单,只需要在pom.xml中加入启动依赖配置就可以了,Spring Boot启动会自动加载和配置sleuth。
### 2.1 pom.xml
```xml
<!-- spring cloud sleuth -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>
```
### 2.2 application.yml
sleuth对配置无要求。
### 2.3 Application.java
sleuth无须配置任何源注释
## 3.sleuth 测试
发送请求:http://192.168.5.31:8085/user/1,并观察sc-sleuth-test和sc-sampleservice的日志输出,其中sc-sleuth-test会使用ribbon调用sc-sampleservice服务,例如:
sc-sleuth-test的日志输出如下:
```
2019-12-17 09:19:56.855[sc-sleuth-test,a5fa777ee2316237,a5fa777ee2316237,false][http-nio-8085-exec-5] INFO com.sc.sleuth.controller.TestSleuth1Controller - find user[User [id=1, username=account1, name=张三, age=20, balance=100.00]] by id[1].
```
这里的TraceId=a5fa777ee2316237,SpanId=a5fa777ee2316237,如果TraceId等于SpanId,则说明为起点服务。
sc-sampleservice的日志输出如下:
```
2019-12-17 09:19:59.912 INFO [sc-sampleservice,a5fa777ee2316237,7e39ccc4e161e7a1,false] 1 --- [nio-8000-exec-6] c.s.s.controller.UserController : finded User:User [id=1, username=account1, name=张三, age=20, balance=100.00]
```
这里的TraceId=a5fa777ee2316237,SpanId=7e39ccc4e161e7a1,很明显TraceId和上面的sc-sleuth-test的日志中TraceId相同,说明是同一请求相关,而SpanId不同说明同一个请求调用链中不同的服务。
## 4.日志格式
sleuth起步依赖和自动配置会自动修改logback的日志,使其满足基于sleuth个输出,但有时你要了解对于logback格式,因为可能要基于rabbitmq输出到ELK中。如下例子定义了两种输出,1.控制台输出、2.Rabbimtq AMQP输出。
```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<springProperty scope="context" name="APP_NAME" source="spring.application.name"/>
<!-- 控制台输出 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符 -->
<!-- 非sleuth环境日志格式: %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n -->
<!-- sleuth环境日志格式: %d{yyyy-MM-dd HH:mm:ss.SSS}[${APP_NAME},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}][%thread] %-5level %logger{50} - %msg%n -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}[${APP_NAME},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}][%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- Rabbitmq AMQP 输出 -->
<appender name="AMQP"
class="org.springframework.amqp.rabbit.logback.AmqpAppender">
<layout>
<pattern>{"time":"%d{yyyy-MM-dd HH:mm:ss.SSS}","application":"${APP_NAME}","TraceId":"%X{X-B3-TraceId:-}","SpanId":"%X{X-B3-SpanId:-}","Span":"%X{X-Span-Export:-}","thread": "%thread","level": "%level","class": "%logger{50}","message": "%msg"}</pattern>
</layout>
<host>192.168.5.29</host>
<port>5672</port>
<username>admin</username>
<password><PASSWORD></password>
<applicationId>sc-sleuth-test</applicationId>
<routingKeyPattern>logstash</routingKeyPattern>
<declareExchange>true</declareExchange>
<exchangeType>direct</exchangeType>
<exchangeName>ex_logstash</exchangeName>
<generateId>true</generateId>
<charset>UTF-8</charset>
<durable>true</durable>
<deliveryMode>PERSISTENT</deliveryMode>
</appender>
<root level="INFO">
<appender-ref ref="AMQP" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
```
## 5.Sleuth与ELK配合使用
上面的日志格式例子,已经定义了基于Rabbitmq AMQP的日志输出,服务产生的日志会按照sleuth的日志格式输出到Rabbitmq的队列中。而ELK会订阅Rabbitmq队列的日志数据。
### 5.1 ELK概念
ELK时一个简称,其包括:Elasticsearch、Logstash、Kibana
Elasticsearch是实时全文搜索和分析引擎,提供搜集、分析、存储数据三大功能;是一套开放REST和JAVA API等结构提供高效搜索功能,可扩展的分布式系统。它构建于Apache Lucene搜索引擎库之上。
Logstash是一个用来搜集、分析、过滤日志的工具。它支持几乎任何类型的日志,包括系统日志、错误日志和自定义应用程序日志。它可以从许多来源接收日志,这些来源包括 syslog、消息传递(例如 RabbitMQ)和JMX,它能够以多种方式输出数据,包括电子邮件、websockets和Elasticsearch。
Kibana是一个基于Web的图形界面,用于搜索、分析和可视化存储在 Elasticsearch指标中的日志数据。它利用Elasticsearch的REST接口来检索数据,不仅允许用户创建他们自己的数据的定制仪表板视图,还允许他们以特殊的方式查询和过滤数据。
### 5.2 在Rabbitmq上定义相关队列
创建ex_logstash的exchange
创建q_logstash的queue
绑定ex_logstash到q_logstash,routingkey=logstash
### 5.3 基于docker简单安装ELK
#### start es port 9200 9300
docker run -d -it --name es -p 9200:9200 -p 9300:9300 elasticsearch
#### start kibana 5601
docker run -d -it --name kibana --link es:elasticsearch -p 5601:5601 kibana
#### start logstash
docker run -d -it logstash -e 'input { rabbitmq {host => "192.168.5.29" port => 5672 user => "admin" password => "<PASSWORD>" exchange => "ex_logstash" queue => "q_logstash" durable => true } } output { elasticsearch { hosts => ["192.168.5.78"] } }'
### 5.4 客户端配置(spring cloud logback)
参照 **4.日志格式** 中的appender name="AMQP",配置服务发生日志到Rabbitmq上。
### 5.5 测试验证ELK是否成功
发送请求:http://192.168.5.31:8085/user/1,其中sc-sleuth-test会使用ribbon调用sc-sampleservice服务。
访问kibana界面,第一步kibana会提示你创建索引,你可以创建基于@timestamp的索引,然后点击查询,就可以看到发生过来的日志数据了,例如:

## FAQ
### sleuth日志存放到es的那个索引中
因为是基于logstash来获取数据,因此存放到es中的索引就是logstash-yyyy.MM.dd,例如:logstash-2019.12.16,因此只要配置kibana显示logstash-*的index patterns就可以显示sleuth的日志了。
### 查看es中的索引
http://192.168.5.78:9200/_cat/indices
例如:
```
yellow open logstash-2019.12.15 9OONnJ4mR5OIt5tqB2KxOA 5 1 24 0 185.9kb 185.9kb
yellow open .kibana 7m-SoUdZRJabs_8QLxyI1Q 1 1 3 0 15kb 15kb
yellow open logstash-2019.12.16 rIX4uuhlQiqr5T0d-1F5ng 5 1 2028 0 1mb 1mb
yellow open logstash-2019.12.14 3Ky3YFDYRCmE3njeEzzn8A 5 1 812 0 578.3kb 578.3kb
yellow open zipkin:span-2019-12-17 AQviXr49RCKqrawsKf9f5g 5 1 344 0 249.8kb 249.8kb
yellow open logstash-2019.12.17 hXQ42waGRH2ZoL-xTXAsgQ 5 1 539 0 548.2kb 548.2kb
```
### 配置kibana中查看数据
kibana主界面中菜单Management->Index Patterns->Create Index Pattern
Index pattern输入框中输入要查看的索引,例如:上面的索引zipkin:span-2019-12-17,如果你想查看索引的zipkin数据,则可以输入:zipkin*,则将匹配索引**zipkin:span-yyyy-MM-dd**的数据。
Time Filter file name输入框中,kibana会自动根据数据获取到时间相关的字段,然后提示你创建基于时间戳的索引,例如:@timestamp。

点击Create按钮,配置要查看的索引数据。
然后回到主界面上,选择zipkin*(Index Pattern),显示zipkin相关的数据。注意:kibana默认只显示15分钟内的数据,如果要显示一天的数据可以选择Today,如下图:

<file_sep># dashboard hystrix可视化监控界面
使用dashboard可视化来监控某个服务jvm产生的hystrix数据,界面如下:
URL:为监控服务jvm的hystrx路径,
普通的服务hystrix监控路径:http://ip:port/hystrix.stream
turbine监控路径:http://ip:port/turbine.stream
Delay:为刷新的频率。
Title:为这次监控命名。

点击Monitor Stream按钮后,开始监控,如果没有数据界面为空,如果有监控数据了,则界面如下:

## 1.1 pom.xml
```xml
<!-- spring cloud hystrix Dashboard -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>
```
## 1.2 application.yml
没有什么特殊的配置
## 1.3 HystrixDashboardApplication
```java
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixDashboardApplication.class, args);
}
}
```
### 1.4 docker 启动脚本
docker run -itd --cap-add=SYS_PTRACE --name sc-hystrix-dashboard --net host -e JAVA_OPTS="-Xms100m -Xmx100m -Xmn60m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC" -e APP_ENV="--spring.profiles.active=dev --server.port=8030" dyit.com:5000/sc/sc-hystrix-dashboard:1.0.1 <file_sep>package com.sc.oauth2.password_authorization.controller;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/pw1/test/1")
public String test1() {
OAuth2Authentication oauth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
System.out.println(oauth2Authentication);
return "success_pw1_test1";
}
}
<file_sep># oauth2 代码认证模式(code_authorization)
## 1.理论
**授权码(authorization code)方式,指的是第三方应用先申请一个授权码,然后再用该码获取令牌。**
这种方式是最常用的流程,安全性也最高,它适用于那些有后端的 Web 应用。授权码通过前端传送,令牌则是储存在后端,而且所有与资源服务器的通信都在后端完成。这样的前后端分离,可以避免令牌泄漏。
第一步,A 网站提供一个链接,用户点击后就会跳转到 B 网站,授权用户数据给 A 网站使用。下面就是 A 网站跳转 B 网站的一个示意链接。
> ```javascript
> https://b.com/oauth/authorize?
> response_type=code&
> client_id=CLIENT_ID&
> redirect_uri=CALLBACK_URL&
> scope=read
> ```
上面 URL 中,`response_type`参数表示要求返回授权码(`code`),`client_id`参数让 B 知道是谁在请求,`redirect_uri`参数是 B 接受或拒绝请求后的跳转网址,`scope`参数表示要求的授权范围(这里是只读)。

第二步,用户跳转后,B 网站会要求用户登录(输入用户名和密码),然后询问是否同意给予 A 网站授权。用户表示同意,这时 B 网站就会跳回`redirect_uri`参数指定的网址。跳转时,会传回一个授权码,就像下面这样。
> ```javascript
> https://a.com/callback?code=AUTHORIZATION_CODE
> ```
上面 URL 中,`code`参数就是授权码。

第三步,A 网站拿到授权码以后,就可以在后端,向 B 网站请求令牌。
> ```javascript
> https://b.com/oauth/token?
> client_id=CLIENT_ID&
> client_secret=CLIENT_SECRET&
> grant_type=authorization_code&
> code=AUTHORIZATION_CODE&
> redirect_uri=CALLBACK_URL
> ```
上面 URL 中,`client_id`参数和`client_secret`参数用来让 B 确认 A 的身份(`client_secret`参数是保密的,因此只能在后端发请求),`grant_type`参数的值是`AUTHORIZATION_CODE`,表示采用的授权方式是授权码,`code`参数是上一步拿到的授权码,`redirect_uri`参数是令牌颁发后的回调网址。

第四步,B 网站收到请求以后,就会颁发令牌。具体做法是向`redirect_uri`指定的网址,发送一段 JSON 数据。
> ```javascript
> {
> "access_token":"ACCESS_TOKEN",
> "token_type":"bearer",
> "expires_in":2592000,
> "refresh_token":"REFRESH_TOKEN",
> "scope":"read",
> "uid":100101,
> "info":{...}
> }
> ```
上面 JSON 数据中,`access_token`字段就是令牌,A 网站在后端拿到了。

## 2.配置
### 2.1 pom.xml
```xml
<!-- spring cloud security oauth2 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
```
### 2.2 CodeAuthorizationApplication
```java
@SpringBootApplication
public class CodeAuthorizationApplication {
public static void main(String[] args) {
SpringApplication.run(CodeAuthorizationApplication.class, args);
}
}
```
没有什么特殊的源注释(配置),特殊的源注释在其它security相关类上声明。
### 2.3 application.yml
```yaml
server:
session:
cookie:
# 重命名session.cookie名称,防止覆盖oauth server的JSESSIONID
name: testclient
# oauth2 代码模式(code_authorization)客户端配置
oauth2-server: http://localhost:6001
security:
oauth2:
client:
grant-type: code_credentials # 代码授权模式
client-id: test_client # 在oauth 服务端注册的client-id
client-secret: 123456 # 在oauth 服务端注册的secret
access-token-uri: ${oauth2-server}/oauth/token #获取token 地址
user-authorization-uri: ${oauth2-server}/oauth/authorize # 认证地址
scope: web
resource:
token-info-uri: ${oauth2-server}/oauth/check_token # 检查token
user-info-uri: ${oauth2-server}/auth/user # 用户信息
sso:
login-path: /login # 回调登录页
```
server.session.cookie.name=testclient
oauth2的客户端,必须重新设置session的cookie名称,否则在同一域名内会相互覆盖。因为默认spring boot的默认session cookie名称为JSESSIONID,而你为了完成单点登录需要三个项目,oauth2服务器,oauth2客户端1,oauth2客户端2,如果三个项目都使用JSESSION的cookie名称,并且在同一关域内(例如:测试为location),那么三个项目的session cookie会相互覆盖,因此必须为两个测试oauth2客户端重命名session的cookie名称。
问题:目前基于code_authorization模式下,还不能实现基于eureka方式来发现oauth server服务(/oauth2/*),只能使用oauth2-server: http://localhost:6001,方式来声明一个配置文件变量的方式,尽量来减少将来的oauth2 server服务位置修改带来的影响。这个问题待以后解决。
### 2.4 oauth2 server配置
#### 2.4.1 代码认证模式下的client_details
oauth2 服务器端,要配置允许这个第三方应用访问oauth2服务器。
| 字段名 | 数据(样例) |
| --------------------------- | ------------------------------------------------------------ |
| CLIENT_ID | test_client |
| RESOURCE_IDS | |
| CLIENT_SECRET | {bcrypt}$2a$10$uT<KEY>.<KEY> |
| SCOPE | service,web |
| **AUTHORIZED_GRANT_TYPES** | refresh_token,password,authorization_code |
| **WEB_SERVER_REDIRECT_URI** | http://localhost:6002/login |
| AUTHORITIES | |
| ACCESS_TOKEN_VALIDITY | |
| REFRESH_TOKEN_VALIDITY | |
| ADDITIONAL_INFORMATION | |
| **AUTOAPPROVE** | |
code_authorization模型下,有三个字段会被使用:
**AUTHORIZED_GRANT_TYPES**,必须含有authorization_code字样。
**WEB_SERVER_REDIRECT_URI**,认证成功后重定向到应用的URL,必须和/oauth/authorize请求的请求参数redirect_uri相同,一般为http://应用ip:应用port/login,例如:http://192.168.5.32:6002/login,客户端可以通过修改security.oauth2.login-path=/login来配置回调URL。
**AUTOAPPROVE**,是否自动授权(是否需要用户手工点击授权),字段值为true或者与请求参数scope值相同时,则不需要用户手工授权,变为自动授权。默认为NULL的时候,需要用户手工授权。
#### 2.4.2 oauth_user
oauth2_user表加入允许登录的用户。
### 2.5 SecurityConfiguration类
@EnableWebSecurity 开启web安全,自动创建和配置spring security的bean;
@EnableOAuth2Sso 开启单点登录的sso模式,自动和配置spring security的bean的cient;
```java
@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().
and().authorizeRequests().antMatchers("/**").authenticated();
}
@Override
public void configure(WebSecurity web) throws Exception {
}
}
```
上面的configure(HttpSecurity http)方法内配置规则:
1. /login无须授权就可以访问。
2. 其他的url必须认证通过后才可以方法。
## 3.测试
### 3.1 页面测试
启动三个项目:
sc-oauth2(认证服务器),端口6001
sc-oauth2-codeauthorization(第三方应用1),端口6002
sc-oauth2-codeauthorization1(第三方应用2),端口6003
发送请求:http://localhost:6002/
发现还没登录,则会自动重定向到http://localhost:6001/login,正确输入User和Password,点击登录;
登录成功后,重定向回http://localhost:6002/,显示 ”客户端主页(6002)-测试成功“。
再发送请求:http://localhost:6003/,则无需登录(因为上面已经登录),直接显示 ”客户端主页(6003)-测试成功“。
### 3.2 /oauth2/*
结合3.1 的页面测试,把这个认证请求的全过程说明一下,重点说明请求的URL:
发送请求http://localhost:6002/到sc-oauth2-codeauthorization服务器,
sc-oauth2-codeauthorization验证还没登录,则生成URL:/oauth/authorize?**(例如:http://localhost:6001/oauth/authorize?client_id=test_client&redirect_uri=http://localhost:6002/login&response_type=code&scope=web&state=dj43AZ),并重定向到sc-oauth2。
sc-oauth2收到/oauth/authorize?**请求,会进入登录页(http://localhost:6001/login),提示最终用户输入用户名和密码。
最终用户输入用户名和密码提交到http://localhost:6001/login,其验证成功后,会重定向会sc-oauth2-codeauthorization的/login?**,并带上code和state两个参数(例如:http://localhost:6002/login?code=NNYMgO&state=dj43AZ)。
sc-oauth2-codeauthorization根据code生成URL:/oauth2/token(例如:http://localhost:6001/oauth/token,/oauth2/token的请求介绍见:sc-auth2文档),并使用RestTemplate发送这个请求到sc-oauth2来获取access_token。
sc-oauth2-codeauthorization获取access_token成功后,会重定向回最初发送请求的url(例如:http://localhost:6002/),因为已经登录了,就可以顺利的进入sc-oauth2-codeauthorization的"/",页面了。
#### /oauth2/authorize
作用:客户端认证,客户端认证成功后,其会跳转到oauth server的登录页(/login)。
例如:
http://localhost:6001/oauth/authorize?client_id=test_client&redirect_uri=http://localhost:6002/login&response_type=code&scope=web&state=dj43AZ
client_id 请求客户端id
redirect_url 回调应用的url
response_type 响应类型,固定为code
scope 客户端范围
state 状态码,请求时自定义一个随机码,用户登录成功后,重定向回到redirect_uri时,会带上这个参数,为了安全。例如:登录成功后(用户名和密码输入正确后),回调的URL如下:http://localhost:6002/login?code=NNYMgO&state=dj43AZ
### 3.3 cookie
按照上面的页面测试,开启了三个项目,如果按照上面的步骤,会生成三个cookie,oauth2 server的JSESSIONID的cookie(会话)、sc-oauth2-codeauthorization的testclient的cookie(会话)、sc-oauth2-codeauthorization1的testclient1的cookie(会话)。其中testclient和testclient1,是两个sc-oauth2-codeauthorization项目在配置server.session.cookie.name中指定的。同时,这三个cookie也是维系整个oauth2登录体系的令牌。
## 4.logout登出
### 4.1 单点登出
**第三方应用配置登出**
在第三方应用(例如:sc-oauth2-codeauthorization)的SecurityConfiguration类配置,配置登出成功url,其在调用本应用成功后会调用oauth2服务器端url,完成oauth server的登出。
```java
@Value("${security.oauth2.client.client-id}")
private String clientId;
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().
and().logout().logoutSuccessUrl("http://localhost:6001/auth/exit?clientId="+this.clientId).
and().authorizeRequests().antMatchers("/**").authenticated();
// @formatter:on
}
```
这里的URL:http://localhost:6001/auth/exit?clientId="+this.clientId,会发送登出请求到oauth2 server。
**oauth server 登出处理**
```java
@Autowired
private ClientDetailsService clientDetailsService;
@RequestMapping(value="/auth/exit",params="clientId")
public void exit(HttpServletRequest request, HttpServletResponse response,@RequestParam String clientId) {
ClientDetails clientDetails = this.clientDetailsService.loadClientByClientId(clientId);
if(clientDetails!=null && !CollectionUtils.isEmpty(clientDetails.getRegisteredRedirectUri())) {
// oauth server 登出
new SecurityContextLogoutHandler().logout(request, null, null);
// 使用在client_details注册回调uri中最后一个作为退出回调uri
String[] clientRedirectUris = clientDetails.getRegisteredRedirectUri().toArray(new String[0]);
String appRedirectUrl = clientRedirectUris[clientRedirectUris.length-1];
try {
response.sendRedirect(appRedirectUrl);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
```
通过执行spring security的new SecurityContextLogoutHandler().logout(request, null, null),完成服务器端登出(session invalid)。通过clientId请求参数获取client_detials的回调url,重定向到发起请求的client端。
<file_sep>package com.sc.oauth2.password_authorization.domain;
import org.springframework.security.core.GrantedAuthority;
/**
* 角色实体
* @author Administrator
*
*/
@SuppressWarnings("serial")
public class Authority implements GrantedAuthority {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getAuthority() {
return name;
}
@Override
public String toString() {
return "Authority{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}
<file_sep>package com.sc.oauth2.password_authorization;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PasswordAuthorizationApplication {
public static void main(String[] args) {
SpringApplication.run(PasswordAuthorizationApplication.class, args);
}
}
<file_sep>package com.sc.oauth2.authorization;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.sc.oauth2.domain.User;
/**
* 根据用户名获取用户信息
* @author Administrator
*
*/
@Repository
public interface UserDao extends JpaRepository<User, Long> {
User findByUsername(String username);
}
<file_sep># feign测试服务
其提供了一个用于测试feign的服务,其会调用sc-sampleservice服务来测试feign的配置的正确性。
feign的理解是把服务的调用RPC化,在feign没出来之前只能通过RestTemplate基于http协议来调用,而feign的出现则可以基于接口(java)代码的方式来远程调用服务。基于代码的feign(java接口)提供了比服务调用协议(文档)更好的可理解性。服务提供者可以编写基于feigh的服务调用客户端,供服务调用者使用。
feign是在ribbon上面应用,其底层实现还是ribbon。理解为ribbon的java接口化。
## 使用Feign实现声明式Rest调用
pom.xml
```xml
<!-- spring cloud feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- feign use apache httpclient -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<!-- feign from upload file -->
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>io.github.openfeign.form</groupId>
<artifactId>feign-form-spring</artifactId>
<version>3.0.3</version>
</dependency>
```
只有spring-cloud-starter-openfeign是必须的。
feign-httpclient可选,但建议使用,同feign.httpclient.enabled: true配合使用则使用apache http客户端。
feign-form和feign-form-spring可选,如果需要上传文件,则需要开启。
根据要调用的服务,创建一个Feign接口
```java
@FeignClient(name = "sc-sampleservice")
public interface SampleServiceFeignClient {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
User findById(@PathVariable("id") Long id);
}
```
调用这个feigh声明的接口
原理:spring会bean后置处理会增强(Proxy)这个接口,包装为一个TraceLoadBalancerFeignClient代理来调用服务。
```java
@RestController
public class FeignTestController {
@Autowired
private SampleServiceFeignClient sampleServiceFeignClient;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.sampleServiceFeignClient.findById(id);
}
}
```
启动application加入@EnableFeignClient源注释
```java
@SpringBootApplication
@EnableFeignClients
public class FeignTestApplication {
public static void main(String[] args) {
SpringApplication.run(FeignTestApplication.class, args);
}
}
```
## 测试feign的url
浏览器发送GET请求http://192.168.5.78:8005/user/1,来验证是否能正确的调用sc-sampleservice服务。
浏览器发送GET请求http://192.168.5.78:8005/user/1?sleep=xxx,来验证是否能正确的调用sc-sampleservice的延时服务,一般应用测试读超时等。
浏览器发送GET请求http://192.168.5.78:8005/users?num=xxx,来验证大批量返回数据,例如:验证响应压缩配置等。
PostMan发送POST请求http://192.168.5.78:8005/add_users,来验证大批量请求数据,例如:验证请求压缩配置。
请求数据格式为json如下:
```json
[
{
"id": 19,
"username": "account1",
"name": "张三",
"age": 20,
"balance": 100
},
{
"id": 19,
"username": "account1",
"name": "张三",
"age": 20,
"balance": 100
}
]
```
PostMan发送POST请求http://192.168.5.78:8005/,增加一个User请求,验证feign的post请求处理。
请求数据格式为json如下:
```json
{
"id": 19,
"username": "account1",
"name": "张三",
"age": 20,
"balance": 100
}
```
PostMan发送Post请求 http://192.168.5.78:8005/uploadFile ,上传一个文件,来验证feign上下文件。
基于PostMan的form-data格式来发送请求,参数的名字为file,选择file(文件)格式参数,value选择一个文件来上传。
如果需要测试大文件上传则要修改sc-feign-test和sc-sampleservice的配置,例如:
```yml
spring:
multipart:
# 整个请求大小限制(1个请求可能包括多个上传文件)
max-request-size: 20MB
# 单个文件大小限制
file-size-threshold: 10MB
```
## feign自定义配置
例如:
```yml
feign:
client:
config:
# 定义全局的feign设置
default:
connectTimeout: 1000
# 定义调用某个服务的feign设置,
sc-sampleservice:
# 配置连接超时时间(毫秒)
connectTimeout: 5000
# 读取超时时间(毫秒)
readTimeout: 5000
```
feign.client.config.**default**.x,定义的全局feign配置。
feign.client.config.**sc-sampleservice**.x 定义的某个服务的feign配置。
### 测试feign的某个服务配置覆盖全局配置
```yml
feign:
client:
config:
# 全局配置
default:
readTimeout: 4000
# 定义调用某个服务的feign设置,
sc-sampleservice:
# 读取超时时间(毫秒)
readTimeout: 5000
```
浏览器发送http://192.168.5.78:8005/user/1?sleep=5001则抛出java.net.SocketTimeoutException: Read timed out异常,发送http://192.168.5.78:8005/user/1?sleep=4001不抛出异常,证明sc-sampleservice定制readTimeout配置覆盖了default的readTimeout配置。
如果去掉sc-sampleservice的readTImeout配置则http://192.168.5.78:8005/user/1?sleep=4001会抛出java.net.SocketTimeoutException: Read timed out异常,证明全局配置生效。
如果去掉整个feign配置,发送http://192.168.5.78:8005/user/1?sleep=1001抛出java.net.SocketTimeoutException: Read timed out异常,发送http://192.168.5.78:8005/user/1?sleep=900,正常返回。可以证明readTimeout默认值为1000。
### 设置feign使用apache httpclient
#### 开启feign客户端对响应内容解压缩
pom.xml加入如下配置,使用apache的http的client的依赖。
```xml
<!-- feign use apache httpclient -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
```
sc-ribbon-test-dev.yml中加入,使用httpclient的配置。
```yml
# feign自定义配置
feign:
httpclient:
# 使用apache httpclient
enabled: true
```
默认请求下,feign的http客户端使用的jdk自带的,其有很多问题,例如:不能正确的对gzip处理,建议使用上面的配置,修改为使用Apache的httpclient。
如果需要监控apache httpclient的请求和响应日志输出,则可添加:
```yml
logging:
level:
root: INFO
# 日志输出apache httpclient的请求和响应日志
org.apache.http.wire: DEBUG
```
### 测试feign的requestInterceptors配置
```yml
# feign自定义配置
feign:
client:
config:
# 定义调用某个服务的feign设置,
sc-sampleservice:
# 请求拦截器
requestInterceptors:
- com.sc.feign.controller.FeignBasicAuthRequestInterceptor
```
```java
package com.sc.feign.controller;
import java.nio.charset.Charset;
import feign.auth.BasicAuthRequestInterceptor;
public class FeignBasicAuthRequestInterceptor extends BasicAuthRequestInterceptor {
public FeignBasicAuthRequestInterceptor() {
super("黑哥", "密码", Charset.forName("UTF-8"));
}
}
```
测试feign调用sc-sampleservice服务时,是否调用了FeignBasicAuthRequestInterceptor过滤器,发送请求:http://192.168.5.31:8005/user/1,观察调试日志(可以把logging.level.root: DEBUG),会看到调试日志字样:
The modified request equals GET http://192.168.5.78:8001/1?sleep=900 HTTP/1.1
Authorization: Basic 6buR5ZOlOuWvhueggQ==
这里的Authorization: Basic 6buR5ZOlOuWvhueggQ==,就是上面FeignBasicAuthRequestInterceptor添加到请求头中的。证明requestInterceptors配置起作用。
### 测试feign重试和ribbon重试的关系
feign使用ribbon的重试配置,如果关闭了ribbon的重试,则feign的重试也关闭了。
测试方法:配置关闭调用sc-sampleservice的ribbon重试(见下面的yml),部署两个sc-sampleservice服务实例,然后基于浏览器发送请求http://192.168.5.31:8005/user/1到sc-feign-test服务,sc-feign-test服务负载均衡调用sc-sampleservice服务,突然关闭一个sc-sampleservice服务实例,请求如果落到关闭的服务实例上,则抛出异常java.net.ConnectException: Connection refused: connect,证明:feign的重试依赖于ribbon的重试,如果ribbon关闭了重试,feign重试也无效。
### 测试feign的readTimeout和ribbon的ReadTimeout的关系
feign的readTimeout的配置优先级大于ribbon的ReadTimeout配置,feign的readTimeout配置或覆盖ribbon的ReadTimeout配置。feign的readTimeout默认值为1000。
测试方法1(feign.readTime < ribbon.ReadTimeout):
feign的readTimeout=4000,ribbon的ReadTimeout设置为5000,具体yml设置如下:
发送请求http://192.168.5.31:8005/user/1?sleep=4500,报错read time out异常。
发送请求http://192.168.5.31:8005/user/1?sleep=3500,正确返回结果。
证明:使用了feign的readTimeout设置。
```yml
# feign自定义配置
feign:
client:
config:
# 定义全局的feign设置
default:
connectTimeout: 1000
readTimeout: 3000
# 定义调用某个服务的feign设置,
sc-sampleservice:
# 配置连接超时时间(毫秒)
connectTimeout: 5000
# 读取超时时间(毫秒)
readTimeout: 4000
# 配置ribbon属性
# 1.配置某个服务的ribbon属性
sc-sampleservice:
ribbon:
restclient:
enabled: true
ReadTimeout: 5000
```
测试方法2(feign.readTime > ribbon.ReadTimeout):
feign的readTimeout=5000,ribbon的ReadTimeout设置为4000,具体yml设置如下:
发送请求http://192.168.5.31:8005/user/1?sleep=4500,正确返回结果。
发送请求http://192.168.5.31:8005/user/1?sleep=5001,报错read time out异常。
```yml
# feign自定义配置
feign:
client:
config:
# 定义全局的feign设置
default:
connectTimeout: 1000
readTimeout: 3000
# 定义调用某个服务的feign设置,
sc-sampleservice:
# 配置连接超时时间(毫秒)
connectTimeout: 5000
# 读取超时时间(毫秒)
readTimeout: 5000
# 配置ribbon属性
# 1.配置某个服务的ribbon属性
sc-sampleservice:
ribbon:
restclient:
enabled: true
ReadTimeout: 4000
```
### 测试feign的压缩(compression)配置
feign压缩配置是客户端(服务调用者)压缩配置,其必须有服务器端(服务提供者)的压缩支持,如果服务器端不支持压缩是没有任何意义,默认情况下,服务器端和客户端压缩都是关闭的。
**压缩本身就是一个双刃剑,其需要在CPU和网络带宽之间做出抉择。带宽充足的情况下建议关闭压缩(默认),带宽不足的情况下建议开启压缩。**
#### 开启服务器端响应输出压缩
尽管服务器端的压缩配置和feign没关系,但要是想正确的说明feign压缩,则需要先开启服务器端压缩。
服务器端(服务提供者)要求开启需要如下操作:
##### 修改配置:
```yml
server:
port: 8000
# 支持压缩
compression:
enabled: true
mime-types:
- text/xml
- text/plain
- application/xml
- application/json
min-response-size: 1024
```
server.compression.enabled=true,用来开启服务器端压缩,例如:tomcat的响应输出压缩。server.compression.mime-types,那些输出内容类型可以被压缩,因为只有文字内容压缩才有意义。
server.compression.min-response-size,只有这个响应长度(Content-Length)才能被压缩,因为小字节流压缩没有任何意义。
##### 加入基于Content-Length响应头输出的过滤器:
举例子说明:
```java
@GetMapping(value = "/users", produces = "application/json;charset=UTF-8")
List<User> findUsers(@RequestParam(value="num",required=false,defaultValue="10") int num)
```
这是一个列出User对象的RestController方法,其参数num指定了要列出的记录数。返回值类型List<User>因为是RestController,其**返回值会被序列化为json输出**。json内容是可以被正常序列化输出,**但其基于Transfer-Encoding: chunked方式输出,无Content-Length响应头。**无Content-Length响应头的支持,servlet容器(tomcat)无法判断输出字节数(min-response-size配置项是根据Content-Length来判断的),因此不管输出字节数多少,即使输出1个字节,也就执行压缩输出(Content-Encoding: gzip)。这显然不合理,我们还需要加入一个自定义的过滤器来正确的输出Content-Length响应头。
```java
package com.sc.sampleservice.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.util.ContentCachingResponseWrapper;
/**
* 如需要测试响应压缩则可以开启本类
* @author zhangdb
*
*/
@Configuration
public class UserControllerJavaConfig {
@Bean
@ConditionalOnProperty(value="server.response.content-length",matchIfMissing=false)
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new Filter() {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, responseWrapper);
responseWrapper.copyBodyToResponse();
}
@Override
public void destroy() {
}
});
List<String> urls = new ArrayList<String>();
urls.add("/*");
filterRegistrationBean.setUrlPatterns(urls);
return filterRegistrationBean;
}
}
```
```yml
server:
port: 8000
# 支持压缩
compression:
enabled: true
mime-types:
- text/xml
- text/plain
- application/xml
- application/json
min-response-size: 1024
response:
content-length: true
```
这里重点说明一下ContentCachingResponseWrapper响应对象包装类,其继承了HttpServletResponseWrapper对象,对HttpServletResponse对象进行包装,RestController响应输出数据先暂存到这个包装器的content属性内(FastByteArrayOutputStream content),在最终输出的时候计算content字节数输出Content-Length响应头。
题外话:**FastByteArrayOutputStream**这里类实现的非常好,其基于LinkedList<byte[]> buffers来实现字节流缓冲,OutputStream.write(bytes[])每一次输出对应一条LinkedList<byte[]>的Node。
**测试服务器端压缩配置是否正确**
http://192.168.5.78:8000/users?num=13,输出的字节为963,小于min-response-size的1024配置,则直接输出不压缩,如下响应头:
HTTP/1.1 200
X-Application-Context: sc-sampleservice:dev:8000
Content-Type: application/json;charset=UTF-8
**Content-Length: 963**
Date: Mon, 18 Nov 2019 07:38:46 GMT
http://192.168.5.78:8000/users?num=15,输出字节数1.08K,大于min-response-size的1024配置,则基于压缩输出,如下响应头:
HTTP/1.1 200
X-Application-Context: sc-sampleservice:dev:8000
Content-Type: application/json;charset=UTF-8
**Transfer-Encoding: chunked**
**Content-Encoding: gzip**
Vary: Accept-Encoding
Date: Mon, 18 Nov 2019 07:40:37 GMT
#### 开启feign客户端对响应内容解压缩
前提:必须使用feign.httplcient.enabled=true或者开启okhttp3,否则服务响应内容无法解压缩。feign请求的响应处理会抛出无法解析json的异常。见上面的feign的httpclient客户端配置文档。
配置如下,其只支持全局配置,不支持某个服务的压缩配置。
```yml
feign:
httpclient:
# 使用apache httpclient
enabled: true
# 压缩
compression:
response:
enabled: true
```
前提服务器端已经开启了压缩,浏览器发送请求:http://192.168.5.31:8005/users?num=15,到sc-feign-test服务,sc-feign-test调用sc-sampleservice服务,观察sc-feign-test的输出日志输出有,Transfer-Encoding: chunked和Content-Encoding: gzip字样,说明服务器端是基于gzip响应输出,如果浏览器可以正确的显示内容,则说明解压缩正确。
浏览器再发送请求:http://192.168.5.31:8005/users?num=10,到sc-feign-test服务,sc-feign-test调用sc-sampleservice服务,观察sc-feign-test的输出日志输出有,Content-Length: 731字样,因为服务器端响应的内容长度小于服务器端server.compression.min-response-size=1024的配置,因此不压缩,原文返回。
注意:必须使用feign.httplcient.enabled=true或者开启okhttp3,否则服务响应内容无法解压缩。feign请求的响应处理会抛出无法解析json的异常。
#### 开启feign客户端请求压缩
**feign的请求压缩就是一个鸡肋,bug多而且太费事了,并且很多服务器端不支持请求的解压缩(建议不用)。**
配置如下,其只支持全局配置,不支持某个服务的压缩配置。
```yml
feign:
httpclient:
# 使用apache httpclient
enabled: true
# 压缩
compression:
request:
enalbed: true
mime-types:
- text/xml
- text/plain
- application/xml
- application/json;charset=UTF-8
min-request-size: 1024
client:
config:
default:
# 请求拦截器
requestInterceptors:
- com.sc.feign.controller.GzipRequestInterceptor
```
feign.httpclient.enabled=true,设置使用apache http client,这个是必须的,否则无法正确的解压缩服务端返回的gzip响应流。
因为feign就是客户端,因此feign的压缩配置主要集中在request的压缩。
feign.compression.request.enabled=true,开启请求压缩。
feign.compression.request.mime-types,指定了开启压缩的请求内容类型。
feign.compression.request.min-request-size=1024,指定了大于1024个字节才开启压缩。
feign不会对请求内容进行压缩处理,只是增加了请求头**Transfer-Encoding: chunked**、**Content-Encoding: gzip**,没有对请求内容进行gzip处理,需要自己实现RequestInterceptor对象内容进行gzip压缩处理,如下代码:
```java
public class GzipRequestInterceptor implements RequestInterceptor {
private final Logger logger = LoggerFactory.getLogger(GzipRequestInterceptor.class);
@Override
public void apply(RequestTemplate template) {
Map<String, Collection<String>> headers = template.headers();
if (headers.containsKey(HttpEncoding.CONTENT_ENCODING_HEADER)) {
Collection<String> values = headers.get(HttpEncoding.CONTENT_ENCODING_HEADER);
if(values.contains(HttpEncoding.GZIP_ENCODING)) {
logger.info("request gzip wrapper.");
ByteArrayOutputStream gzipedBody = new ByteArrayOutputStream();
try {
GZIPOutputStream gzip = new GZIPOutputStream(gzipedBody);
gzip.write(template.body());
gzip.flush();
gzip.close();
template.body(gzipedBody.toByteArray(), Charset.defaultCharset());
}catch(Exception ex) {
throw new RuntimeException(ex);
}
}
}
}
}
```
上面的配置能保证,feign客户端请求的压缩发送到服务器端,但服务器端还要能正确的先解压缩请求。目前测试tomcat原生是不支持,nginx网上有插件可以支持,但没有测试过。
有人在github上写一个解压缩请求的代码,可以参照:
https://github.com/ohmage/server/blob/master/src/org/ohmage/jee/filter/GzipFilter.java
<file_sep># ribbon测试服务
其提供了一个用于测试ribbon的服务,其会调用sc-sampleservice服务来测试ribbon的配置的正确性。
## 使用LoadBalanced实现ribbon
ribbon支持很简单,就是在RestTemplate加上@LoadBalanced源注释。然后改变restTemplate的调用uri参数,这个uri参数在ribbon支持下意义已经变了,其uri的主机和端口部分对应的请求的服务名,例如:
this.restTemplate.getForObject("http://SC-SAMPLESERVICE/{id}", User.class, id),这里的SC-SAMPLESERVICE就要调用的服务名,这个服务已经在eureka上注册。ribbon默认是延时初始化的,其会在首次调用服务时,从eureka上加载服务路由表,并会定时刷新服务路由表,ribbon只会从本地的服务路由表中(ribbon会定时从eureka上拉取服务路由表)查找服务位置,然后调用,不会每次调用都从eureka上获取某个服务位置,然后在调用。这样的好处是即使eureka宕机,ribbon缓存的本地路由也可以提供服务位置。
使用ribbon支持的RestTemplate
```java
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
```
看这个@LoadBalanced的声明。
spring引用这个RestTemplate实例
```java
@RestController
public class RibbonLoadBalancedTestController {
private static final Logger logger = LoggerFactory.getLogger(RibbonLoadBalancedTestController.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/user/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject("http://sc-sampleservice/{id}", User.class, id);
}
}
```
这里的restTemplate实例已经是ribbon修饰过期的RestTemplate对象了。
this.restTemplate.getForObject("http://sc-sampleservice/{id}", User.class, id);,注意这里的host部分已经被调用的服务名(**sc-sampleservice**)替换了。
### 测试ribbon的url
http://192.168.5.78:8003/user/1,其会基于@LoadBalanced修饰的RestTemplate来调用sc-sampleservice服务,获取一个User信息。
http://192.168.5.78:8003/log-user-instance,查看负载均衡请求分发到的主机。
http://192.168.5.78:8003/,其会基于@LoadBalanced修饰的RestTemplate来调用sc-sampleservice服务,基于post提交,增加一个User,并返回新增加的这个用户信息。
提交的Json如下:
{"username":"heige","name":"黑哥","age":39,"balance":10000000}
http://192.168.5.78:8003/user/1?sleep=xxxx,其会基于@LoadBalanced修饰的RestTemplate来调用sc-sampleservice服务,获取一个User信息,其sc-sampleservice执行的方法会延时参数sleep的毫秒,多用于测试延时,例如:readTimeout等。
# ribbon配置
在application.yml中加入
<clientName>.ribbon.x,用来配置某个对服务请求的ribbon配置。
ribbon.x,如果省略了前面的<clientName>则为全局配置。
具体配置可以看下面的**测试ribbon章节**。
## 测试ribbon
### 设置ribbon使用apache http客户端
```yml
ribbon:
restclient:
enabled: true
```
ribbon默认的情况下使用的jdk自带的http客户端,其有很多问题,例如:ribbon.ReadTimeout设置无效,建议使用上面的配置,修改为使用apache http客户端。
### 测试ribbon默认配置
启动一个sc-sampleservice服务(其会注册到eureka上),浏览器发送请求到sc-ribbon-test服务(http://192.168.5.78:8003/user/1),@LoadBalanced修饰的RestTemplate来调用sc-sampleservice服务。
### 测试ribbon的默认负载均衡(轮询)
启动两个sc-sampleservice服务(其会注册到eureka上),浏览器发送请求到sc-ribbon-test服务(http://192.168.5.78:8003/user/1),@LoadBalanced修饰的RestTemplate来调用sc-sampleservice服务。观察这两个sc-sampleservice产生的日志信息,两个服务会交替输出日志。并逐次调用http://192.168.5.78:8003/log-user-instance来观察ribbon选择发送请求的目标。
浏览器发出请求:http://192.168.5.31:8003/log-user-instance,观察rc-ribbon-test的日志输出,如下:
sc-sampleservice:192.168.5.78:8000
sc-sampleservice:192.168.5.78:8001
sc-sampleservice:192.168.5.78:8000
sc-sampleservice:192.168.5.78:8001
sc-sampleservice:192.168.5.78:8000
sc-sampleservice:192.168.5.78:8001
sc-sampleservice:192.168.5.78:8000
sc-sampleservice:192.168.5.78:8001
sc-sampleservice:192.168.5.78:8000
sc-sampleservice:192.168.5.78:8001
### 测试ribbon随机负载均衡
修改: https://github.com/zhangdberic/config-repo/blob/master/sc-ribbon-test/sc-ribbon-test-dev.yml ,加入如下配置,指定为随机负载均衡策略。
sc-sampleservice:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
浏览器发出请求:http://192.168.5.31:8003/log-user-instance,观察rc-ribbon-test的日志输出,如下:
sc-sampleservice:192.168.5.78:8001
sc-sampleservice:192.168.5.78:8000
sc-sampleservice:192.168.5.78:8001
**sc-sampleservice:192.168.5.78:8000**
**sc-sampleservice:192.168.5.78:8000**
sc-sampleservice:192.168.5.78:8001
sc-sampleservice:192.168.5.78:8000
**sc-sampleservice:192.168.5.78:8001**
**sc-sampleservice:192.168.5.78:8001**
**sc-sampleservice:192.168.5.78:8000**
**sc-sampleservice:192.168.5.78:8000**
**sc-sampleservice:192.168.5.78:8000**
### 测试饥饿(延时)加载
ribbon默认对服务请求都是延时加载处理的,调用那个服务才初始化这个服务调用的ribbon上下文(慢),这对于某些访问量大的请求是无法容忍。因此需要在服务启动的时候,对于重要的服务初始化ribbon上下文对象。
修改: https://github.com/zhangdberic/config-repo/blob/master/sc-ribbon-test/sc-ribbon-test-dev.yml ,加入如下配置,指定sc-sampleservice服务调用ribbon上下文启动就加载。
ribbon:
eager-load:
enabled: true
clients: sc-sampleservice
观察日志输出,如果在启动时能看到如下字样说明启动加载,如果只有在发送请求http://192.168.5.78:8003/user/1,后才能看到如下字样为延时加载。
NFLoadBalancer:name=sc-sampleservice,current list of Servers=[192.168.5.78:8001, 192.168.5.78:8000]
如果有多个服务需要启动加载,则使用:service1, service2, serivce3。如果你想启动加载所有的服务ribbon上下文,只能一个一个的服务名加上,不支持*。
### 测试ribbon的重试配置
#### 测试默认情况下(无ribbon配置)的重试
ribbon默认是支持重试的,测试方法:开启两个sc-sampleservice服务实例,浏览器发送请求http://192.168.5.31:8003/user/1到sc-ribbon-test,sc-ribbon-test再负载均衡调用sc-sampleservice,如果突然关闭了一个sc-sampleservice服务实例,并且浏览器再次发送两个请求http://192.168.5.31:8003/user/1到sc-ribbon-test,你会发现一个请求明显有卡顿,但任何可以正确的返回结果。
#### 测试禁用全局ribbon重试
```yml
spring:
cloud:
# 关闭除zuul所有的请求重试
loadbalancer:
retry:
enabled: false
```
这个配置是全局配置,其将关闭除了zuul外其他所有组件的重试,测试方法:开启两个sc-sampleservice服务实例,浏览器发送请求http://192.168.5.31:8003/user/1到sc-ribbon-test,sc-ribbon-test再负载均衡调用sc-sampleservice,如果突然关闭了一个sc-sampleservice服务实例,并且浏览器再次发送两个请求http://192.168.5.31:8003/user/1到sc-ribbon-test,其中的一个请求抛出 ConnectException 异常。经过一段时间,eureka 90秒后踢掉没续租的服务+ribbon从eureka刷新服务路由表的到本地间隔时间,ribbon本地新的路由表中只有一个sc-sampleservice服务地址信息,然后再发送http://192.168.5.31:8003/user/1到sc-ribbon-test每次都是正确的了。
#### 测试MaxAutoRetries和MaxAutoRetriesNextServer设置
```yml
# 1.配置某个服务的ribbon属性
sc-sampleservice:
ribbon:
# 同一个实例最大重试测试,不包括首次调用
MaxAutoRetries: 1
# 重试其它实例的最大次数(例如:部署了同一个服务3个实例,此处应该设置为2),不包括首次调用所选的实例
MaxAutoRetriesNextServer: 1
restclient:
enabled: true
# 读取超时时间设置(毫秒)
ReadTimeout: 3000
ConnectTimeout: 1000
```
测试方法,部署两个sc-sampleservice实例,浏览器发送请求:http://192.168.5.31:8003/user/1?sleep=3001到sc-ribbon-test服务,sc-ribbon-test负载均衡调用sc-sampleservice实例,因为ReadTimeout设置为3000,而请求的延时设置为3001一定会报错,从而测试请求重试。观察sc-sampleservice的日志输出,明显看到一个实例执行了两次,两个实例都执行到了,也就是说sc-samplservice一共接收到了4个请求。
流程:http://192.168.5.31:8003/user/1?sleep=3001请求发送到实例1,实例1超时报错,再重试实例1,实例1再超时报错。然后自动重试实例2,超时报错,自动再重试实例2。日志输出http://192.168.5.31:8003/user/1?sleep=3001请求耗时是12488 mills,正好是4个请求(1个正常请求,3个重试)的执行耗时。
测试方法:去掉MaxAutoRetries或MaxAutoRetriesNextServer配置(**默认配置**),或配置MaxAutoRetries: 0,MaxAutoRetriesNextServer: 1,两者都是一样的。
测试方法,部署两个sc-sampleservice实例,浏览器发送请求:http://192.168.5.31:8003/user/1?sleep=3001到sc-ribbon-test服务,sc-ribbon-test负载均衡调用sc-sampleservice实例,因为ReadTimeout设置为3000,而请求的延时设置为3001一定会报错,从而测试请求重试。观察sc-sampleservice的日志输出,明显看到一个实例执行了1次,两个实例都执行到了,也就是说sc-samplservice一共接收到了2个请求。
```yml
# 1.配置某个服务的ribbon属性
sc-sampleservice:
ribbon:
# 同一个实例最大重试测试,不包括首次调用
MaxAutoRetries: 0
# 重试其它实例的最大次数(例如:部署了同一个服务3个实例,此处应该设置为2),不包括首次调用所选的实例
MaxAutoRetriesNextServer: 1
restclient:
enabled: true
# 读取超时时间设置(毫秒)
ReadTimeout: 3000
ConnectTimeout: 1000
```
流程:http://192.168.5.31:8003/user/1?sleep=3001请求发送到实例1,实例1超时报错,因为MaxAutoRetries=0实例1不再重试。然后自动重试实例2,因为MaxAutoRetriesNextServer=1,超时报错。日志输出http://192.168.5.31:8003/user/1?sleep=3001请求耗时是6312 mills,正好是2个请求(1个正常请求,1个重试)的执行耗时。
#### 测试禁用某个服务的ribbon重试
```yml
# 1.配置某个服务的ribbon属性
sc-sampleservice:
ribbon:
# 同一个实例最大重试测试,不包括首次调用
MaxAutoRetries: 0
# 重试其它实例的最大次数(例如:部署了同一个服务3个实例,此处应该设置为2),不包括首次调用所选的实例
MaxAutoRetriesNextServer: 0
```
服务的ribbon属性MaxAutoRetries和MaxAutoRetriesNextServer都设置为0,则禁用了这个服务的重试。
生产环境建议这两个值都设置为1。
测试方法:开启两个sc-sampleservice服务实例,浏览器发送请求http://192.168.5.31:8003/user/1到sc-ribbon-test,sc-ribbon-test再负载均衡调用sc-sampleservice,如果突然关闭了一个sc-sampleservice服务实例,并且浏览器再次发送两个请求http://192.168.5.31:8003/user/1到sc-ribbon-test,其中的一个请求抛出 ConnectException 异常,没有启动重试。
#### 测试ribbon请求失败多少次从ribbon路由表剔除服务
测试方法,禁用sc-ribbon-test服务访问sc-sampleservice的重试,并开启两个sc-sampleservice服务实例,浏览器发送请求http://192.168.5.31:8003/user/1到sc-ribbon-test,sc-ribbon-test再负载均衡调用sc-sampleservice,如果突然关闭了一个sc-sampleservice服务实例,并且浏览器再次发送几次请求http://192.168.5.31:8003/user/1到sc-ribbon-test,如果其中的两次请求落到已经关闭的sc-sampleservice实例上(抛出 ConnectException 异常),则从ribbon路由表中剔除这个sc-sampleservice实例,后续的请求http://192.168.5.31:8003/user/1请求都会正常。
#### 测试OkToRetryOnAllOperations设置
测试方法:开启两个sc-sampleservice服务实例,postman发送请求http://192.168.5.31:8003/到sc-ribbon-test,sc-ribbon-test再负载均衡调用sc-sampleservice,如果突然关闭了一个sc-sampleservice服务实例,并且postman再次发送两个请求http://192.168.5.31:8003/到sc-ribbon-test,其中的一个请求抛出 ConnectException 异常,证明OkToRetryOnAllOperations默认值(false)的情况下,post请求不支持重试。
设置OkToRetryOnAllOperations=true,还是使用上面的测试,测试结果不会抛出ConnectException 异常,在关闭一个sc-sampleservice服务实例的情况下,仍然可以正确的发送请求和返回结果。但要注意,post支持重试是一个非常危险配置,如果post处理的方法不支持幂等性,可以出现重复提交和重复数据的情况。
```yml
sc-sampleservice:
ribbon:
# 是否所有的操作都进行重试(默认只有GET请求开启重试,POST请求关闭重试),默认为false
OkToRetryOnAllOperations: true
```
#### 测试ribbon.restclient.enabled=true设置
默认情况下ribbon的http客户端使用的jdk自带的httpconneciton,如果设置为ribbon.restclient.enabled=true其使用的apache http客户端,如果设置为ribbon.okhttp.enabled=true使用的okhttp客户端。
目前建议设置ribbon.restclient.enabled=true使用apache http客户端,因为只有在这个配置下,与http client的配置才能生效,例如:ribbon.ReadTimeout和ribbon.ConnectTimeout属性设置才能有效,具体原因见: https://blog.csdn.net/hsz2568952354/article/details/89466511 。已经做过实验来证明了。
#### 测试ReadTimeout设置
设置ReadTimeout值的前提是ribbon.restclient.enabled=true,否则ReadTimeout设置无效。ribbon的readTimeout的默认值为1000。
测试方法:设置sc-sampleservice的ribbon的调用ReadTimeout=3000,发送请求http://192.168.5.31:8003/user/1,如果关闭重试的请求下,查看sc-ribbon-test.findByIdWithSleep方法的请求耗时为3473mills,如果开启重试MaxAutoRetries: 1和MaxAutoRetriesNextServer: 1 的情况下sc-ribbon-test.findByIdWithSleep方法的请求耗时为12488mills(4个请求,1个正常请求,3个重试请求)。
**开启重试**抛出异常:
com.netflix.client.ClientException: Number of retries on next server exceeded max 1 retries, while making a call for: 192.168.5.78:8001
对应的最底层异常,java.net.SocketTimeoutException: Read timed out
```yml
sc-sampleservice:
ribbon:
restclient:
enabled: true
# 测试随机负载均衡
#NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
# 同一个实例最大重试测试,不包括首次调用
MaxAutoRetries: 1
# 重试其它实例的最大次数(例如:部署了同一个服务3个实例,此处应该设置为2),不包括首次调用所选的实例
MaxAutoRetriesNextServer: 1
# 是否所有的操作都进行重试(默认只有GET请求开启重试,POST请求关闭重试),默认为false
#OkToRetryOnAllOperations: true
# 读取超时时间设置(毫秒)
ReadTimeout: 3000
ConnectTimeout: 1000
```
**这个的ReadTimeout设置为3000,时间的ribbonTimeout经过系统计算后是8000,你可以通过查看,zuul的文档,2.8.1 计算ribbonTimeout 章节,来能明白这个8000是如果计算来的额。**
**重试关闭**的情况下:
com.netflix.client.ClientException; nested exception is java.io.IOException: com.netflix.client.ClientException
java.net.SocketTimeoutException: Read timed out
```yml
sc-sampleservice:
ribbon:
restclient:
enabled: true
# 测试随机负载均衡
#NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
# 同一个实例最大重试测试,不包括首次调用
MaxAutoRetries: 0
# 重试其它实例的最大次数(例如:部署了同一个服务3个实例,此处应该设置为2),不包括首次调用所选的实例
MaxAutoRetriesNextServer: 0
# 是否所有的操作都进行重试(默认只有GET请求开启重试,POST请求关闭重试),默认为false
#OkToRetryOnAllOperations: true
# 读取超时时间设置(毫秒)
ReadTimeout: 3000
ConnectTimeout: 1000
```
#### 测试ConnectTimeout设置
设置ConnectTimeout值的前提是ribbon.restclient.enabled=true,否则ConnectTimeout设置无效。
ConnectTimeout对应socket建立连接的时间,如果在ConnectTimeout指定的时间内没能建立连接,则抛出Connection Time out异常。
如果ConnectTimeout设置的值小,底层网络情况不好,那么可以频繁的报出异常。如果ConnectTimeout设置的值大,并且不能正确的建立连接,那么客户端阻塞的时候会很长。如果开启重试,则(MaxAutoRetriesNextServer+1)*ConnectTimeout才是最终的连接超时时间,需要等待这么久才能抛出连接超时异常。
一般在内网情况下,默认值1000ms已经足够了。如果连接的服务在互联网,则要设置为2000 ms.
<file_sep>package sc.com.hystrix.controller;
import java.util.concurrent.Callable;
import sc.com.hystrix.domain.User;
public class UserContextCallable<V> implements Callable<V> {
private final User user;
private final Callable<V> callable;
/**
* 外围线程初始化(例如:tomcat请求线程)
* @param callable
* @param user
*/
public UserContextCallable(Callable<V> callable,User user) {
super();
this.user = user;
this.callable = callable;
}
/**
* Hystrix隔离仓线程调用(hystrix执行线程)
*/
@Override
public V call() throws Exception {
UserContext.setUser(this.user);
try {
V v = this.callable.call();
return v;
} finally {
UserContext.remove();
}
}
}
<file_sep>package com.sc.seata.mstest2.feign;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.sc.seata.mstest2.domain.User;
@FeignClient(name = "mstest1", url = "127.0.0.1:8103")
public interface Mstest3FeignClient {
@GetMapping("/addUser")
User addUser(@RequestParam("userId") Long userId,
@RequestParam("name") String name);
}
<file_sep># Zipkin
收集系统的时序数据,从而追踪微服务架构的系统延时。
## 1.服务器端配置(基于队列)
基于队列模式的zipkin服务端,将订阅rabbitmq上的zipkin队列(queue),队列上有数据将异步存放到es上。
存放到es上的索引格式:zipkin:span-yyyy-MM-dd,例如:zipkin:span-2019-12-17,你可以通过kibana来查看zipkin索引上的相关sleuth和zipkin数据。rabbitmq上创建zipkin队列都是zipkin-server自动完成的无须手工创建。
kibana查看zipkin的相关数据,可以查看"sleuth配置文档的FAQ部分"。
### 1.1 pom.xml
```xml
<!-- spring cloud zipkin server -->
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-ui</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-server</artifactId>
</dependency>
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-collector-rabbitmq</artifactId>
<version>2.3.1</version>
</dependency>
<!-- 支持Elasticsearch 2.x 存储zipkin数据 -->
<dependency>
<groupId>io.zipkin.java</groupId>
<artifactId>zipkin-autoconfigure-storage-elasticsearch-http</artifactId>
<version>2.3.1</version>
</dependency>
```
### 1.2 application.yml
```yaml
# zipkin server
zipkin:
# zipkin数据收集
collector:
rabbitmq:
addresses: 192.168.5.29:5672
username: admin
password: <PASSWORD>
queue: zipkin
# zipkin数据存储
storage:
type: elasticsearch
elasticsearch:
hosts: http://192.168.5.78:9200
```
可以通过查看ZipkinElasticsearchHttpStorageProperties类代码来分析,zipkin.storage.elasticsearch相关的配置属性,简单的只需要配置hosts属性指定es位置。
### 1.3 ZipkinServerApplication
```java
@SpringBootApplication
@EnableZipkinServer
public class ZipkinServerApplication {
public static void main(String[] args) {
SpringApplication.run(ZipkinServerApplication.class, args);
}
}
```
## 2.服务客户端zipkin配置
### 2.1 pom.xml
```xml
<!-- zipkin -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zipkin</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
</dependency>
```
### 2.3 application.yml
```yaml
spring:
# sleuth和zipkin发送数据到rabbitmq配置
rabbitmq:
host: 192.168.5.29
port: 5672
username: admin
password: <PASSWORD>
# sleuth
sleuth:
sampler:
# 采样数据1.0为100%,默认为0.1(10%),采样越高越准确,但对服务器要求越高(性能和存储)
percentage: 1.0
# zipkin client
zipkin:
rabbitmq:
# 发生数据到rabbitmq的队列名(同zipkin服务端配置队列名)
queue: zipkin
```
## 3. 测试验证
### 3.1 客户端发送测试数据
请求调用链:浏览器->http://192.168.5.31:8681/user/1->sc-zipkin-test1->sc-zipkin-test2-sc-sampleservice
发送请求:http://192.168.5.31:8681/user/1,产生sleuth日志数据发送到Rabbitmq,zipkin server获取rabbitmq上的数据,存放到es上。zipkin界面上可以查看sc-zipkin-test1->sc-zipkin-test2-sc-sampleservice调用链的延时数据。
### 3.2 通过zipkin服务端界面查看zipkin数据


### 3.3 通过kibana查看zipkin数据
zipkin服务器端启动的时候,已经在es上创建了 zipkin:span-yyyy-MM-dd的相关索引了,例如: zipkin:span-2019-12-17,相关的sleuth和zipkin的数据也是存放到对于的索引上,你可以使用kibana的Management-Index Patterns->Create Index Pattern来创建**zipkin***显示模式,基于时间戳来索引。
注意:kibana默认只显示15分钟内的数据,你要切换为显示today的数据。

<file_sep># 配置spring cloud config 配置中心
## 1. config 服务器端配置
### 1.1 pom.xml
```xml
<dependencies>
<!-- spring cloud config server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!-- spring security 安全认证 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- spring cloud bus -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
</dependencies>
```
spring-boot-starter-security和spring-cloud-starter-bus-amqp不是必须的,spring-boot-starter-security是为保护config,客户端需要basic认证方式才能访问config,而spring-cloud-starter-bus-amqp是为了支持属性在线刷新。
### 1.2 bootstrap.yml
```yaml
spring:
application:
name: sc-config # 应用名称
cloud:
config:
server:
encrypt:
enabled: false # 直接返回密文,而并非解密后的原文(需要客户端解密)
encrypt:
key: xxx # 配置文件加密秘钥
```
### 1.3 application.yml
```yaml
# 公有属性
# 指定默认的环境(默认开发环境)
spring:
profiles:
active: dev
# 开启安全认证
security:
basic:
enabled: true
user:
name: sc-config
password: <PASSWORD>
# 开发环境
---
server:
port: 8080
spring:
profiles: dev
cloud:
config:
server:
git:
# Spring Cloud Config配置中心使用gitlab的话,要在仓库后面加后缀.git,而GitHub不需要
uri: https://github.com/zhangdberic/config-repo.git
search-paths: /**
# 因为github的账户和密码不能泄露,因此需要在启动脚本中加入--spring.cloud.config.server.git.username=xxxx --spring.cloud.config.server.git.password=xxxx
username: zhangdb
password: <PASSWORD>
# 和spring-cloud-starter-bus-amqp配合,用于/bus/refresh分布式服务属性刷新.
# 调用/bus/refresh,则刷新所有监听到本队列上的服务属性配置.
# 调用/bus/refresh?destination={application}:**,则刷新监听到本队列上的某个服务(应用)属性配置.
# 调用/bus/refresh?destination={application}:{instanceid},则只刷新监听到本队列上的某个服务(应用)的某个实例属性配置(用集群环境下的灰度发布).
# 客户端为了支持/bus/refresh也需要在pom.xml中引入spring-cloud-starter-bus-amqp,并且在应用的git中(service-dev.yml)加上如下的队列配置.
rabbitmq:
host: 192.168.5.29
port: 5672
username: admin
password: <PASSWORD>
```
### 1.4 ConfigServerApplication
```java
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
```
## 2.config客户端配置
### 2.1 pom.xml
```xml
<!-- spring cloud config client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- spring cloud bus -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
```
spring-cloud-starter-bus-amqp不是必须的,是为了支持属性在线刷新。
### 2.2 bootstrap.yml
```yaml
spring:
application:
name: sc-eureka
profiles:
active: dev
encrypt:
key: xxxxxx # 解密配置属性的秘钥(同配置服务器端秘钥)
# 开发环境
---
spring:
profiles: dev
cloud:
config:
uri: http://192.168.5.78:8080
profile: dev # 指定从config server配置的git上拉取的文件(例如:sc-sample1service-dev.yml)
username: sc-config # config server的basic认证的user
password: <PASSWORD> # config server的basic认证的password
```
注意:如果基于spring cloud config模式来定义服务的配置,那么就应该只创建bootstrap.yml,而application.yml应该放在config上,例如方在git上。而bootstrap.yml文件只应该包含上面例子中的内容:应用名、profile、config客户端配置等,不应在包含过多的配置,其它的配置都应该放在config的application.yml上。
依赖于spring boot的启动依赖和自动配置,spring boot项目启动后会自动在classpath上查找到config依赖包,然后根据bootstrap.yml上的config配置来,创建config相关的bean。
## 2. spring cloud config操作
### 2.1 获取某个服务的配置
**获取default属性:**
格式:http://config-ip:config-port/应用名.yml
例如:http://192.168.5.78:8080/sc-eureka.yml
**获取dev环境属性**
格式:http://config-ip:config-port/应用名-dev.yml
例如:http://192.168.5.78:8080/sc-eureka-dev.yml
### 2.2 bus属性刷新(/bus/refresh)
#### 2.2.1 pom.xml中加入spring-cloud-starter-bus-amqp
spring cloud config 服务器和客户端的pom.xml都要加入这个起步依赖,服务器端config运行时会在rabbitmq上创建springCloudBus的exchanged。客户端config运行会创建一个queue,基于这个springCloudBus的exchanged路由绑定。这样就形成了客户端订阅,服务器端发布的模式,只有你修改git上的属性,并发送请求 /bus/refresh?destination=服务名:** 到config服务器,config服务验证属性确实改变了,就会put修改属性通知到对列,config客户端马上就会接受到属性改变的通知,并重新配置。
#### 2.2.2 刷新属性所在类上加入@RefreshScope源注释
```java
@Component
@RefreshScope
public class ConfigProperties {
@Value("${config.property.refreshProperty1}")
private String refreshProperty1;
public String getRefreshProperty1() {
return refreshProperty1;
}
public void setRefreshProperty1(String refreshProperty1) {
this.refreshProperty1 = refreshProperty1;
}
}
```
强烈建立把属性都放到一个或多个配置类中,这样既方便管理,又方便刷新。
引用这个ConfigProperties的controller代码。
```java
@RestController
public class TestConfigController {
@Autowired
private ConfigProperties configProperties;
@GetMapping("/getConfigProperties")
public ConfigProperties getConfigProperties() {
ConfigProperties configProperties = new ConfigProperties();
configProperties.setRefreshProperty1(this.configProperties.getRefreshProperty1());
return configProperties;
}
}
```
#### 2.2.3 发送属性刷新请求
发送POST请求到,config服务器,请求URL:http://config-ip:config-port/bus/refresh?destination=服务名:**
测试URL:http://192.168.5.78:8080/bus/refresh?destination=sc-config-test:** ,POST请求,Basic认证的用户名和密码为: sc-config: veDSJeUX-JSxkWrk 。
可以是postMan来测试,也可以使用firefox的 RESTClient插件来测试。
#### 2.2.4 测试属性刷新
1.测试发送请求获取属性信息:http://192.168.5.31:8500/getConfigProperties,查看刷新前的属性值。
2.修改github上的config-repo/sc-hystrix-test/sc-hystrix-test-dev.yml配置文件内的属性:
```yaml
# 测试属性在线刷新
config:
property:
refreshProperty1: 马应龙唇膏
```
3.发送POST请求,http://192.168.5.78:8080/bus/refresh?destination=sc-config-test:** ,Basic认证的用户名和密码为: sc-config: veDSJeUX-JSxkWrk ,触发属性刷新。
4.再发送请求获取属性信息:http://192.168.5.31:8500/getConfigProperties,查看刷新后的属性值。
### 2.3 属性加密
#### 2.3.1 配置对称加密KEY
config服务器端和config客户端的bootstrap.yml的配置文中都要加入,如下配置:
```yaml
encrypt:
key: xxxxU # 解密配置属性的秘钥(同配置服务器端秘钥)
```
#### 2.3.2 使用config服务器提供的/encypt加密值
使用curl来发送加密请求,格式:
curl --user basic-username:basic-password http://config-ip:config-port/encrypt -d 加密属性值
例如:curl --user sc-config:veDSJeUX-JSxkWrk http://192.168.5.78:8080/encrypt -d 123
返回:ab1582e88160b08500ed785b666cd274d3343ecb60288b92c061dd049bc5e2a1
#### 2.3.3 修改application.yml属性为加密值
注意:加密的属性值和普通的属性值是有区别的,加密属性值格式:
'{cipher}加密后的属性值',单引号是必须的,前缀字符串{cipher}也是必须的。
```yaml
config:
property:
encryptedProperty2: '{cipher}2e2674efca5bf456f034872fe890686814e0979474781fc2cee9054d305ca067'
```
## 2. 集群
spring cloud 配置集群,最头疼的就是,是把spring cloud config以服务的方式注册的eureka上来保证可靠性,还是把spring cloud config做成vip的HA。就好比是一个先有鸡还是先有蛋的问题。
### 第1种:
好处:简单,可靠性也能保证,config服务也注册到eureka上,由eureka统一管理。
缺点:eureka无法使用spring cloud config,application.yml要放在eureka项目本地文件系统上,如果配置改变需要到本地修改,然后重启eureka。
每个服务,需要写死eureka.client.service-url.defaultZone的地址,因为要先到eureka注册中心获取springcloudconfig服务的地址,然后才能调用config来获取服务配置。
整个spring cloud系统需要先启动eureka集群。
### 第2种:
好处:eureka项目的应用配置也可以加入到spring cloud config中,可以直接在git上查看和修改(配置统一管理)。
坏处:需要配置VIP,加入了复杂性。
整个spring cloud系统需要先启动spring clolud config集群。
但不管是第1种,还是第2种,gitlabs不能是单点,rabbitmq也不能但单点,也应该是双机(VIP)。
**目前我的选择是使用第2种:config vip方式。**
基于VIP的方案来构建集群,VIP后接两个spring cloud config的docker,VIP可以使用keepalived来实现,但这需要两台宿主机上安装和配置keeaplived。
服务配置客户端spring.cloud.config.uri: http://vip:port配置为vip地址。
gitlabs也基于HA方式,也可以安装到spring cloud config docker的宿主机上(这个具体没安装过,但应该没问题),gitlabs的数据基于drbd来保证可靠性。
## docker启动脚本
docker run -itd --cap-add=SYS_PTRACE --name sc-config1 --net host -e JAVA_OPTS="-Xms100m -Xmx100m -Xmn30m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC" -e APP_ENV="--spring.profiles.active=dev --spring.cloud.config.server.git.username=xxxx--spring.cloud.config.server.git.password=<PASSWORD>" dyit.com:5000/sc/sc-config:1.0.1
##
<file_sep># oauth2服务器端
## 1.oauth2的基本理论
oauth2的理论网上很多,你可以baidu一下。这里不多说了。
https://www.cnblogs.com/sky-chen/archive/2019/03/13/10523882.html
## 2.oauth2 server 配置
当前的代码例子,实现了基于jdbc存储client_details、user、authority等静态数据,基于redis存放token。
一般情况下,当前的示例代码基本就够用了。
### 2.1 pom.xml
```xml
<!-- spring cloud security oauth2 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
</dependency>
<!-- oauth2 jdbc redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>172.16.17.32.181016</version>
</dependency>
```
<!-- spring cloud security oauth2 -->注释的依赖包是spring cloud oauth2必须的依赖包,而下面的<!-- oauth2 jdbc redis -->注释的依赖包是基于jdbc存储client_details、user、authority静态数据,基于redis存放token的依赖包。
### 2.2 OauthServerApplication
```java
@SpringBootApplication
public class OauthServerApplication {
public static void main(String[] args) {
SpringApplication.run(OauthServerApplication.class, args);
}
}
```
OauthServerApplication没有什么特殊的源注释(配置),特殊的源注释在其它security相关类上声明。
### 2.3 AuthorizationServerConfiguration
spring cloud oauth2的服务器端bean配置,注意:类上的@EnableAuthorizationServer源注释,开启oauth2 server端的bean自动配置。
```java
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
/** 属性配置 */
@Autowired
private PropertiesConfiguration propertiesConfiguration;
/** 认证管理器 */
@Autowired
private AuthenticationManager authenticationManager;
/** 用户信息服务 */
@Autowired
private UserServiceDetail userServiceDetail;
/** redis连接池工厂 */
@Autowired
private RedisConnectionFactory redisConnectionFactory;
/** 数据库连接池 */
@Autowired
private DataSource dataSource;
/**
* token存储
* @return
*/
@Bean
public TokenStore tokenStore() {
return new RedisTokenStore(this.redisConnectionFactory);
}
/**
* 客户端信息服务
* @return
*/
@Bean
public ClientDetailsService clientDetailsService() {
JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(this.dataSource);
return jdbcClientDetailsService;
}
/**
* token服务(操作)
* @return
*/
@Bean
@Primary
public AuthorizationServerTokenServices tokenService() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setTokenStore(tokenStore());
tokenServices.setSupportRefreshToken(this.propertiesConfiguration.isSupportRefreshToken());
tokenServices.setReuseRefreshToken(this.propertiesConfiguration.isReuseRefreshToken());
tokenServices.setAccessTokenValiditySeconds(this.propertiesConfiguration.getAccessTokenValiditySeconds());
tokenServices.setRefreshTokenValiditySeconds(this.propertiesConfiguration.getRefreshTokenValiditySeconds());
tokenServices.setClientDetailsService(clientDetailsService());
return tokenServices;
}
/**
* 密码编码器
* @return
*/
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(this.clientDetailsService());
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(this.tokenStore());
endpoints.authenticationManager(this.authenticationManager);
endpoints.userDetailsService(this.userServiceDetail);
endpoints.tokenServices(this.tokenService());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// 允许表单认证
security.allowFormAuthenticationForClients();
// 设置请求URL:/oauth/tokey_key和/oauth/check_token的安全规则
security.tokenKeyAccess("denyAll()").checkTokenAccess("isAuthenticated()");
// 设置client_secret的密码编码器,如果你的数据库中对client_secret加密了则要设置相同的加密器
security.passwordEncoder(this.passwordEncoder());
}
}
```
### 2.4 ResourceServerConfiguration
服务资源授权配置,理解为:对外提供服务的URI授权,例如:oauth2服务器对外提供的/auth/user服务
(用于获取已登录用户的基本信息和权限),这个URI需要授权才可以访问到。
注意:在ResourceServerConfiguration和WebSecurityConfiguration两个类同时存在的时候,ResourceServerConfiguration的HttpSecurity配置一定要以http.antMatcher("xxx")开头来定义资源授权,否则配置无效。
oauth2 server原生提供的/oauth2/* 相关URI(服务)不需要在这里配置授权,oauth2 server默认已经为/oauth2/*相关的URL定义了授权规则,一般情况下无须修改,例如:/oauth2/token授权为permitAll()、/oauth/tokey_key授权为denyAll(),但可以通过security.tokenKeyAccess("denyAll()")来重新设置、/oauth/check_token为denyAll(),但可以通过security.checkTokenAccess("isAuthenticated()")来重新设置。
```java
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
/**
* 自定义安全配置
* 注意:一定要以http.antMatcher(...)方法开头匹配,否则会覆盖SecurityConfiguration类的相关配置.
* 这里定义的配置有两个作用:
* 1.安全限制,定义外界请求访问系统的安全策略。
* 2.根据规则生成过滤链(FilterChainProxy,过滤器的排列组合),不同的规则生成的过滤链不同的。
* 系统默认的/oauth/xxx相关请求也是基于ResourceServerConfiguration实现的,只不过系统默认已经配置完了。
*/
@Override
public void configure(HttpSecurity http) throws Exception {
// 提供给client端用于认证
http.antMatcher("/auth/user").authorizeRequests().anyRequest().authenticated();
}
}
```
### 2.5 WebSecurityConfiguration
web资源授权配置,用于配置oauth2 server的web授权,这里配置的授权的都是oauth2 server对外提供的web请求,例如:登录(/login),登录(/logout),js,css等。并且,这个配置器还可以配置安全信息,例如,配置安全登录页,登录处理URL,登出页等。
注意:在ResourceServerConfiguration和WebSecurityConfiguration两个类同时存在的时候,WebSecurityConfiguration的HttpSecurity配置一定要以http.**authorizeRequests()**.antMatchers("xxx")开头来定义web授权,否则配置无效。
```java
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
AuthenticationManager manager = super.authenticationManagerBean();
return manager;
}
/**
* 自定义安全配置
* 注意:不应以http.antMatcher(...)方法开头匹配,否则会和ResourceServerConfiguration安全规则配置冲突,应以authorizeRequests()开头.
* 这里定义的配置有两个作用:
* 1.安全限制,定义外界请求访问系统的安全策略。
* 2.根据规则生成过滤链(FilterChainProxy,过滤器的排列组合),不同的规则生成的过滤链不同的。
*/
@Override
public void configure(HttpSecurity http) throws Exception {
// 授权码模式(authorization_code)配置
// 授权码模式下,会用到/oauth/authorize(授权URL)、/login(登录页)、/oauth/confirm_access(用户授权确认),
// 但由于/oauth/**相关的请求安全规则配置由系统默认生成,则无需再配置。
//
// @formatter:off
http.authorizeRequests().antMatchers("/login").permitAll().and().formLogin().permitAll().
and().authorizeRequests().anyRequest().authenticated();
// @formatter:on
}
/**
* 除了http,其它css、js和图片等静态文件访问控制
*/
@Override
public void configure(WebSecurity web) throws Exception {
}
}
```
### 2.6 application.yml
```yaml
# oauth2 Edgware 版本有bug,因此需要下面的配置把认证过滤器提前
security:
oauth2:
resource:
filter-order: 3
```
## 3.表结构
### oracle
#### OAUTH_CLIENT_DETAILS(客户端信息表)
```sql
create table OAUTH_CLIENT_DETAILS
(
client_id VARCHAR2(256) not null,
resource_ids VARCHAR2(256),
client_secret VARCHAR2(256),
scope VARCHAR2(256),
authorized_grant_types VARCHAR2(256),
web_server_redirect_uri VARCHAR2(256),
authorities VARCHAR2(256),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additional_information VARCHAR2(3072),
autoapprove VARCHAR2(256)
);
alter table OAUTH_CLIENT_DETAILS
add constraint PK_OAUTH_CLIENT_DETAILS primary key (CLIENT_ID);
```
字段说明:
**client_id** 客户端ID
**resource_ids** 允许访问的资源服务器ID(多个用逗号分隔),资源服务器上可以通过,如下设置:
```java
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("oauth-server");
}
```
如果资源服务器(ResourceServerConfiguration)上配置了resourceId,而你的客户端OAUTH_CLIENT_DETAILS.resource_ids字段没有设置相关的值,则无权访问这个资源服务器。
**client_secret** 客户端秘钥,为了安全起见,应该是一个加密值。其对应如下配置的加密器:
这是类AuthorizationServerConfiguration内的一个方法,其设置了client的加密器,其会对http请求的client_secret加密,然后和数据库上的这个字段进行比较。
```java
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.passwordEncoder(this.passwordEncoder());
}
```
**scope** 范围(多个用逗号分隔,例如:web,service,mobile),自定义字符串,定义允许的范围。
**authorized_grant_types** 允许的授权模式(例如:password,authorization_code,implicit,client_credentials,refresh_token),除了refresh_token是特殊模式外,其它的是oauth2常用的四种模式。
**web_server_redirect_uri** 在code_authorization模式下的登录成功后,应用回调url,必须和/oauth/authorize请求的请求参数redirect_uri相同,一般为http://应用ip:应用port/login,例如:http://192.168.5.32:6002/login,客户端可以通过修改security.oauth2.login-path=/login来配置回调URL。
**authorities** 客户端授权,只要在implicit,client_credentials模式下才有意义,因为在password和authorization_code模式下使用的user的授权。
**access_token_validity** 设定客户端的access_token的有效时间值(单位:秒),可选, 若不设定值则使用默认的有效时间值(60 * 60 * 12, 12小时)。
**refresh_token_validity** 设定客户端的refresh_token的有效时间值(单位:秒),可选, 若不设定值则使用默认的有效时间值(60 * 60 * 24 * 30, 30天)。
**additional_information** 这是一个预留的字段,在Oauth的流程中没有实际的使用,可选,但若设置值,必须是JSON格式的数据,例如:
```json
{"country":"CN","country_code":"086"}
```
**autoapprove** 设置用户是否自动Approval操作, 默认值为 'false', 可选值包括 'true','false', 'read','write'.
该字段只适用于grant_type="authorization_code"的情况,当用户登录成功后,若该值为'true'或支持的scope值,则会跳过用户Approve的页面, 直接授权。
#### OAUTH_USER(用户信息表)
```sql
-- Create table
create table OAUTH_USER
(
user_id NUMBER not null,
username VARCHAR2(45) not null,
password VARCHAR2(256) not null,
enabled CHAR(1) default '1'
);
alter table OAUTH_USER
add constraint PK_OAUTH_USER primary key (USER_ID);
```
user_id 用户id
username 用户名
password 密码
enabled 是否允许,1允许,0不允许
#### OAUTH_AUTHORITY(授权表)
```sql
create table OAUTH_AUTHORITY
(
authority_id NUMBER not null,
name VARCHAR2(100)
);
alter table OAUTH_AUTHORITY
add constraint PK_OAUTH_ROLE_ID primary key (AUTHORITY_ID);
```
authority_id 授权id
name 授权名
#### OAUTH_USER_AUTHORITY(用户授权表)
OAUTH_USER和OAUTH_AUTHORITY的多对多中间表
```sql
create table OAUTH_USER_AUTHORITY
(
user_id NUMBER not null,
authority_id NUMBER not null
);
alter table OAUTH_USER_AUTHORITY
add constraint PK_OAUTH_USER_ROLE primary key (USER_ID, AUTHORITY_ID);
```
user_id 用户id
authority_id 授权id
#### 其它表
http://www.andaily.com/spring-oauth-server/db_table_description.html
## 4./oauth2/* 相关URL介绍
### /oauth2/token
作用:获取访问令牌。
#### 密码模式授权(password model)
请求URL:/oauth2/token
请求方法:POST
请求Content:application/x-www-form-urlencoded
请求参数:
grant_type = password
username = 用户名(对应OAUTH_USER.USERNAME)
password = 密码(对应OAUTH_USER.PASSWORD)
scope = 范围(对应OAUTH_CLIENT_DETAILS.SCOPE)
请求头:
Authorization Basic client_id:client_secret
这里的 client_id:client_secret 需要使用base64编码
返回值:
```json
{"access_token":"<PASSWORD>","token_type":"bearer","refresh_token":"<PASSWORD>","expires_in":43199,"scope":"service"}
```
access_token 返回的访问令牌。
token_type 令牌类型 bearer。
refresh_token 刷新令牌,允许在access_token在快要到期的时候,使用refresh_token来刷新access_token。
expires_in 过期时间。
scope 范围,一般对于请求范围,例如:请求scope=service,返回的也是service。
#### 令牌刷新(refresh token)
用于access_token快要到期,不需要重新认证,使用refresh_token就可以获取新的令牌。有时候会为了安全考虑禁用令牌刷新,因为黑客一旦获取到了refresh_token就可以无限刷新access_token,而且默认refresh_token的有效期为30天。
请求URL:/oauth2/token?grant_type=refresh_token&refresh_token=${refresh_token}&client_id=${client_id}&client_secret=${client_secret}
请求方法:GET
返回值:
```json
{"access_token":"<PASSWORD>","token_type":"bearer","refresh_token":"f<PASSWORD>9-<PASSWORD>","expires_in":43199,"scope":"service"}
```
注意:AuthorizationServerConfiguration类的tokenServices.setSupportRefreshToken(true或false),可以设置是否支持令牌刷新。
### /oauth2/check_token
作用:检查token是否合法。
请求URL:/oauth2/check_token?token={access_token}
请求方法:GET
请求头:
Authorization Basic client_id:client_secret
这里的 client_id:client_secret 需要使用base64编码
返回值:
```json
{"exp":1579201673,"user_name":"test_user","authorities":["test_admin","test_user"],"client_id":"test_client","scope":["service"]}
```
exp 过期时间(毫秒)
user_name 用户名
authorities 授权列表
client_id 客户端id
scope 返回列表
注意:AuthorizationServerConfiguration类security.checkTokenAccess("isAuthenticated()");可以设置/oauth2/check_token的访问授权,默认是denyAll(),也就是不允许访问。
### /oauth2/token_key
用于JWT,目前没有用到。
### /oauth/authorize
code_authorization认证模式,使用的URL,客户端认证URL。
参见:”sc-oauth2-codeauthorization“项目的README.md说明。
### /oauth/confirm_access
code_authorization认证模式,使用的URL,用户确认URL。
参见:”sc-oauth2-codeauthorization“项目的README.md说明。
### /oauth/error
作用:oauth2的错误处理URL。
## 5.oauth2 HttpSecurity规则
待以后说明...<file_sep>package com.sc.feign.serviceclient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
@Configuration
public class MultipartSupportConfig {
@Bean
public Encoder feignFormEncoder() {
return new SpringFormEncoder();
}
}
<file_sep>package com.sc.hystrix.turbine;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.turbine.stream.EnableTurbineStream;
/**
* Hystrix Dashboard监控的turbine地址:http://192.168.5.78:28031/turbine.stream
* @author zhangdb
*
*/
@SpringBootApplication
@EnableTurbineStream
public class TurbineServerApplication {
public static void main(String[] args) {
SpringApplication.run(TurbineServerApplication.class, args);
}
}
<file_sep># 服务提供者测试例子
其会在启动的时候通过config来获取git上的配置 [sc-sampleservice-dev.yml]( https://github.com/zhangdberic/config-repo/blob/master/sc-sampleservice/sc-sampleservice-dev.yml ),并注册sc-sampleservcie服务到eureka上。
提供了如下URL:
http://192.168.5.78:8000/1,GET请求,查看用户id为1的用户信息。
http://192.168.5.78:8005/user/1?sleep=5001,GET请求,提供了延时执行(服务方法内sleep),例如:5001则延时5001秒,多用于测试超时。
http://192.168.5.78:8000/ ,POST请求,增加用户,请求的体json,{"username":"heige","name":"黑哥","age":39,"balance":10000000},用postman提交比较好。
http://192.168.5.78:8000/uploadFile ,POST请求(form-data格式),请求参数名file,参数值为上传文件。
http://192.168.5.78:8000/health,监控检查可以查看到:db、rabbitmq、config、eureka、hystrix等状态,比较全。
在测试环境上,可以部署两个sc-sampleservice服务。用于测试如下:
1.eureka上是否可以正确的识别两个服务实例。可以通过eureka主页面来验证,http://192.168.5.78:8070/
2.sc-sampleservice服务提供者角色,供ribbon测试负载均衡请求,sc-ribbon-test服务对sc-sampleservice服务发起请求,两个sc-sampleservice服务实例轮番被请求到。
## docker启动脚本
docker run -itd --cap-add=SYS_PTRACE --name sc-microservice-sample1 --net host -e JAVA_OPTS="-Xms100m -Xmx100m -Xmn60m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC" -e APP_ENV="--spring.profiles.active=dev --server.port=8000" dyit.com:5000/sc/sc-microservice-sample:1.0.1
docker run -itd --cap-add=SYS_PTRACE --name sc-microservice-sample2 --net host -e JAVA_OPTS="-Xms100m -Xmx100m -Xmn60m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC" -e APP_ENV="--spring.profiles.active=dev --server.port=8001" dyit.com:5000/sc/sc-microservice-sample:1.0.1
<file_sep># eureka集群配置
eureka单机没有任何意义,服务注册和发现中心必须部署两个以上。
基于docker部署,测试环境基于单宿主机部署两个eureka docker来模拟eureka集群。
具体的代码,参见当前目录下github代码。
这里重点对配置进行说明:
[bootstrap.yml](https://github.com/zhangdberic/springcloud/blob/master/sc-eureka/src/main/resources/bootstrap.yml)
bootstrap.yml应该只放在当前profile、应用名称,基本的远程配置信息,eureka应用信息应放到application.yml中。
application.yml应配置到config git上,其应该由sc-eureka-default.yml和sc-eureka-{profile}.yml两个文件组成,例如开发环境:config-repo/sc-eureka/sc-eureka.yml和config-repo/sc-eureka/sc-eureka-dev.yml
[sc-eureka-dev.yml]( https://github.com/zhangdberic/config-repo/blob/master/sc-eureka/sc-eureka-dev.yml )
```yml
server:
port: 8070
spring:
cloud:
config:
# 允许使用java -Dxxx=yyy,来覆盖远程属性,例如:java -Dserver.port=8071
overrideSystemProperties: false
# 和spring-cloud-starter-bus-amqp配合,用于/bus/refresh分布式服务属性刷新
rabbitmq:
host: 192.168.5.29
port: 5672
username: admin
password: <PASSWORD>
eureka:
instance:
# 当建立eureka集群时必须使用基于主机名方式(不能直接使用ip地址),相应的要修改linux的/etc/hosts文件
hostname: eureka1
client:
service-url:
# 两个eureka组成集群
defaultZone: http://sc-eureka:veDSJeUX-JSxkWrk@eureka1:8070/eureka/,http://sc-eureka:veDSJeUX-JSxkWrk@eureka2:8071/eureka/
```
这里重点说一下,如果是基于集群配置,应基于**主机名**方式来配置eureka,而不是ip方式,仔细看defaultZone的地址都是主机名,其在eureka.instance.hostname中声明了。在hostname中声明的主机名必须在linux的/etc/hosts中同步设置,例如:192.168.5.78 dyit.com eureka1 eureka2。
## DOCKER RUN脚本
docker run -itd --cap-add=SYS_PTRACE --name sc-eureka1 --net host -e JAVA_OPTS="-Xms200m -Xmx200m -Xmn80m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC" -e APP_ENV="--spring.profiles.active=dev --server.port=8070 --eureka.instance.hostname=eureka1" dyit.com:5000/sc/sc-eureka:1.0.1
docker run -itd --cap-add=SYS_PTRACE --name sc-eureka2 --net host -e JAVA_OPTS="-Xms200m -Xmx200m -Xmn80m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC" -e APP_ENV="--spring.profiles.active=dev --server.port=8071 --eureka.instance.hostname=eureka2" dyit.com:5000/sc/sc-eureka:1.0.1
注意:
1.基于--net host网络模式启动,见FAQ。
2.--server.port指定了端口,两个eureka对应两个不同的端口。
3.--eureka.instance.hostname指定了主机名,两个eureka对应两个不同的主机名,这里的主机名必须在/etc/hosts中配置。
## 运行成功截图


**注意:DS Replicas是对方主机名(对应eureka.instance.hostname),registered-replicas和availabel-replicas都是对方主机的eureka注册链接。**
## FAQ
1、建议基于docker host网络模式来部署eureka,不应使用birdge模式,防止eureka注册的ip为172.17.0.x、防止docker主机名重启变动(这些都是birdge模式的特殊性造成的)。
2、默认情况下eureka开启了自我保护模式下,如果多个服务同时快速下线,则出现DOWN状态,处理:

使用eureka提供的restful的api来处理,使用curl或postman发送**DELETE**请求:
URL格式:
http://eurekaip:port/eureka/apps/{application}/{instance}
例如:
http://192.168.5.78:8070/eureka/apps/SC-SEATA-MSTEST1/heige-PC:sc-seata-mstest1:8101<file_sep># hystrix+rabbitmq+turbine+dashboard
# 构建可视化监控
hystrix数据监控,需要三部分:
1.turbine(mq模式),其负责数据收集,其订阅了springCloudHystrixStream(exchanged)队列数据。
2.服务,把产生的hystrix监控数据发送给springCloudHystrixStream(exchanged)队列。
3.dashboard,负责可视化展示turbine收集的数据。
流程:
各个微服务发送hystrix的数据到rabbitmq(数据生产者),turbine订阅rabbitmq上的hystrix数据(数据消费者),然后通过Dashboard展示。
## 1.创建turbine(rabbitmq模式)
### 1.1 pom.xml
```xml
<!-- spring cloud hystrix stream -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-turbine-stream</artifactId>
</dependency>
<!-- spring cloud stream rabbitmq -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
```
### 1.2 bootstrap.yml
```yaml
spring:
application:
name: sc-hystrix-turbine
profiles:
active: dev
```
### 1.3 application-dev.yml
```yaml
# 开发环境
server:
port: 28031
spring:
# java -D属性可以覆盖本远程参数
cloud:
config:
overrideSystemProperties: false
rabbitmq:
host: 192.168.5.29
port: 5672
username: admin
password: <PASSWORD>
eureka:
client:
service-url:
defaultZone: http://sc-eureka:[email protected]:8070/eureka/,http://sc-eureka:[email protected]:8071/eureka/
# 客户端监控检查(定时检查并发送健康状态到eureka服务器)
healthcheck:
enabled: true
instance:
prefer-ip-address: true
non-secure-port: 28031
management:
port: 20011
security:
enabled: false
```
**在application.yml中加入rabbitmq的连接信息**
注意:这里区别于其他spring cloud项目,其配置没有放到git上,不使用spring cloud config,那是因为Edgware的turbine(mq模式)存在bug,其在基于spring cloud config配置启动的时候报错:java.net.BindException: Address already in use: bind,因此使用本地application-dev.yml来存储配置信息。
而且还有注意:server.port一定要一个大的端口号,否则还报错,eureka.instance.non-secure-port配置要同server.port,而且management.port也要独立设置。
观察turbine的启动日志和eureka注册的turbine服务,会发现其端口是-1,这是正常,具体原因见下面:
```
在搭建springcloud微服务时,可以使用Turbine进行监控多个微服务,用dashboard展示数据。
不过在springboot1.5.x+springcloudEdgware版,使用消息中间间收集数据时会出现一个错误,导致Turbine整合rabbitmq项目无法运行。
错误信息:org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.cloud.netflix.turbine.stream.TurbineStreamConfiguration'; nested exception is java.net.BindException: Address already in use: bind
导致原因:Turbine整合rabbitmq时会启动一个Netty容器,并将server.port 设为-1 ,从而关闭Servlet容器,就会导致yml文件中server.port无法正常工作。
解决办法:修改yml文件
server:
port: 28031
spring:
application:
name: turbinservice
rabbitmq:
host: localhost
port: 5672
username: guest
password: <PASSWORD>
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
instance-id: ${spring.cloud.client.ipAddress}:28031
non-secure-port: 28031
management:
port: 20011
1.server.port尽量设置大一点,不然可能还是会报错
2.添加“non-secure-port:”该值与server.port的值一样
3.添加“management.port”该值设置一个随机数,尽量大一些,要与server.port的值不一样
该方法可能只对springboot1.5.x+springcloud Edgware版有效,可能其他版本不会有这个整合的问题。
在贴出我turbine+rabbitmq的pom文件
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-turbine-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
```
### 1.4 TurbineServerApplication.java
```java
@SpringBootApplication
@EnableTurbineStream
public class TurbineServerApplication {
public static void main(String[] args) {
SpringApplication.run(TurbineServerApplication.class, args);
}
}
```
### 1.5 验证是否正常启动
监控jvm的日志输出,例如:docker logs -f {id},查看使用正常连接到rabbitmq,tomcat启动是否正常等。
通过健康监控检查URL: http://192.168.5.78:20011/health ,来确定启动是否成功。
通过rabbitmq的控制台,查看是否已经创建了springCloudHystrixStream的exchange。
### 1.6 Docker 启动脚本
docker run -itd --cap-add=SYS_PTRACE --name sc-hystrix-turbine --net host -e JAVA_OPTS="-Xms100m -Xmx100m -Xmn60m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC" -e APP_ENV="--spring.profiles.active=dev" dyit.com:5000/sc/sc-hystrix-turbine:1.0.1
## 2. 服务改造发送hystrix监控数据到rabbitmq
### 2.1 pom.xml
```xml
<!-- spring cloud hystrix turbine client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-hystrix-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-rabbit</artifactId>
</dependency>
```
### 2.2 application.yml
```yaml
spring:
rabbitmq:
host: 192.168.5.29
port: 5672
username: admin
password: <PASSWORD>
```
**在application.yml中加入rabbitmq的连接信息**
## 3. dashboard可视化监控
具体可见:sc-hystrix-dashboard项目的README.md介绍。
监控turbine收集hystrix数据的URL:http://turbineip:port/turbine.stream<file_sep>-- Create table
-- 客户端信息表
create table OAUTH_CLIENT_DETAILS
(
client_id VARCHAR2(256) not null,
resource_ids VARCHAR2(256),
client_secret VARCHAR2(256),
scope VARCHAR2(256),
authorized_grant_types VARCHAR2(256),
web_server_redirect_uri VARCHAR2(256),
authorities VARCHAR2(256),
access_token_validity INTEGER,
refresh_token_validity INTEGER,
additional_information VARCHAR2(3072),
autoapprove VARCHAR2(256)
);
alter table OAUTH_CLIENT_DETAILS
add constraint PK_OAUTH_CLIENT_DETAILS primary key (CLIENT_ID);
-- Create table
-- 自定义的用户表
create table OAUTH_USER
(
user_id NUMBER not null,
username VARCHAR2(45) not null,
password VARCHAR2(256) not null,
enabled CHAR(1) default '1'
)
alter table OAUTH_USER
add constraint PK_OAUTH_USER primary key (USER_ID);
-- Create table
-- 自定义的权限表
create table OAUTH_AUTHORITY
(
authority_id NUMBER not null,
name VARCHAR2(100)
);
-- Create/Recreate primary, unique and foreign key constraints
alter table OAUTH_AUTHORITY
add constraint PK_OAUTH_AUTHORITY_ID primary key (AUTHORITY_ID);
-- Create table
-- 自定义的用户权限表
create table OAUTH_USER_AUTHORITY
(
user_id NUMBER not null,
authority_id NUMBER not null
);
alter table OAUTH_USER_AUTHORITY
add constraint PK_OAUTH_USER_ROLE primary key (USER_ID, AUTHORITY_ID);
-- 下面的所有表只要在JdbcTokenStore的情况下有意义,如果使用RedisTokenStore则不需要创建。
-- Create table
create table OAUTH_CLIENT_TOKEN
(
authentication_id VARCHAR2(256) not null,
token_id VARCHAR2(256),
token BLOB,
user_name VARCHAR2(256),
client_id VARCHAR2(256)
);
alter table OAUTH_CLIENT_TOKEN
add constraint PK_OAUTH_CLIENT_TOKEN primary key (AUTHENTICATION_ID);
-- Create table
create table OAUTH_ACCESS_TOKEN
(
authentication_id VARCHAR2(256) not null,
token_id VARCHAR2(256),
token BLOB,
user_name VARCHAR2(256),
client_id VARCHAR2(256),
authentication BLOB,
refresh_token VARCHAR2(256)
);
-- Create/Recreate primary, unique and foreign key constraints
alter table OAUTH_ACCESS_TOKEN
add constraint PK_OAUTH_ACCESS_TOKEN primary key (AUTHENTICATION_ID);
create table oauth_refresh_token (
token_id VARCHAR(256),
token BLOB,
authentication BLOB
);
create table oauth_code (
code VARCHAR(256),
authentication BLOB
);
create table oauth_approvals (
userId VARCHAR(256),
clientId VARCHAR(256),
scope VARCHAR(256),
status VARCHAR(10),
expiresAt TIMESTAMP,
lastModifiedAt TIMESTAMP
);
<file_sep>package sc.com.hystrix.concurrentstrategy;
import java.util.concurrent.Callable;
/**
* hystrix Callback包装器
* 使用装饰器模式,对参数callable进行包装.
* @author zhangdb
*
*/
public interface HystrixCallableWrapper {
<T> Callable<T> wrap(Callable<T> callable);
}
<file_sep>spring.application.name=sc-seata-bztest1
server.port=8100
logging.level.root=INFO
logging.level.io.seata=DEBUG
eureka.client.service-url.defaultZone=http://sc-eureka:[email protected]:8070/eureka/,http://sc-eureka:[email protected]:8071/eureka/
eureka.instance.prefer-ip-address=true
eureka.healthcheck.enabled=true<file_sep>seata分布式事务介绍
==========
1.官网地址
------------
https://github.com/seata
https://github.com/seata/seata-samples
https://github.com/seata/seata-samples/blob/master/springcloud-jpa-seata
https://github.com/seata/seata-samples/tree/master/springcloud-eureka-seata
seata的意义比较大,其实现了分布式事物,其目前的版本没实现XA那么严格的二阶段提交,但在良好的业务设计下,90%可以满足分布式事物处理,其最大的优点是性能,但牺牲了事物的特性,隔离新、完整性、一致性等都会影响。
应用场景:微服务分布式事物、分库分表、跨数据库(一个全局事物内包括mysql和oracle),因为在互联网模式下基于微服务的应用是不可避免的,因此对分布式事物的需求就非常迫切。其提供了AT和MT模式,AT可以实现非侵入代码模式,只需要在TM的方法上面声明@GlobalTransactional,在RM上加入DataSourceProxy类就就可以实现了分布式事物了。
需要注意:分布式环境不可能做到完美,只能力争完美,就想CAP理论一样。因此seata也是如此,其问题如下:
1.隔离性脏读,其RM(例如:RM1)在两阶段提交的第1阶段就已经执行了commit了,数据已经被写到数据库上,能被其它事物访问到。而这时如果整个全局事物中的某个RM(例如:RM2)出错需要回滚,但上面RM1提交的数据已经被人使用了,而这时TC通知RM1回滚,则要把这个数据恢复回去。这个需要有时间研究一下: @GlobalLock 和Select xxx for update了。
2.并发操作同一个数据回滚问题,因为其RM使用undo_log来保持sql操作前后的镜像,因此一旦某个局部事物代码抛出异常,需要回滚执行的时候,但需要回滚对应的行数据已经修改了(RM提交后,TC通知回滚前),那么将造成无法回滚,只能进行人工干预,因此一定要在设计的时候,就考虑这个问题。具体原理,见下面的"seata分析理解"。
3.seata的两阶段提交,注意:所有的RM第1阶段已经提交了(commit),数据已经写到数据库中,其它的事物也可以查看到数据。RM的第2阶段,其实是在需要rollback的时候才执行的(如果全局事物提交成功则第2阶段对于各RM无意义),rollback时其获取undo_log的前镜像,翻译成sql,然后执行并提交(反向执行操作)。因此,这里就有问题了,如果第1阶段部分RM提交成功,某个RM需要回退,而这些RM中的某个需要反向操作的时候,连接的mysql数据库挂了,部分RM无法回退,则会破坏整个全局事物的完整性。
4.seata在RM是执行,如果使用update sql语句会使用select from update来生成前镜像,因此要注意性能问题,而且由于seata的undo机制,批量操作的sql语言可能不支持,即使支持了如果需要回退,那么效率也非常低,因此seata适合在操作单条数据或者是小范围操作数据的业务上。
如果应用在生产环境下,一定要严格的测试以上问题,特别是能否正常回滚(因为其回滚机制和数据库的回滚还是有区别的),并且设计的时候要避免上面的问题。认证考虑全局事物的完整性和一致性。可以参照,这个事物补偿文档来建表设计: https://www.cnblogs.com/lijingshanxi/p/9943836.html
有些问题的处理可以参见seata的FAQ: http://seata.io/zh-cn/docs/faq/faq.html
## 2.约束
参照官网的例子:seata 0.9需要在spring boot 2.1+spring cloud Finchley的环境下运行。
目前测试,spring 1.5+spring Edawage不支持seata0.9。
3.TC 服务器端安装和配置
----------
下载地址:https://github.com/seata/seata/releases
tar xvf seata-server-0.9.0.tar.gz
cd seata
### 3.1 初始化TC表结构
**mysql**
创建一个seata的库,并执行seata/config/db_store.sql文件内的sql,创建成功后会生成3个表。
branch_table、global_table、lock_table
但注意:global_table表的transaction_service_group字段,应修改为varchar(128),否则可能出现"数据截断异常"。
### 3.2 编辑注册文件
**vi conf/registry.conf**
```json
registry {
# file 、nacos 、eureka、redis、zk、consul、etcd3、sofa
type = "eureka"
eureka {
serviceUrl = "http://sc-eureka:[email protected]:8070/eureka/,http://sc-eureka:[email protected]:8071/eureka/"
application = "seata-server"
weight = "1"
}
}
config {
# file、nacos 、apollo、zk、consul、etcd3
type = "file"
file {
name = "file.conf"
}
}
```
seata-server(tc)这样重要的应用,必须是高可用的。因为使用spring cloud全家桶,因此注册到eureka中。
eureka.serviceUrl,同spring cloud eureka client的eureka.client.service-url.defaultZone配置。
eureka.application,同spring cloud eureka client的spring.application.name的配置。
weight.weight,没研究。
当前的配置,把seata-server应用注册到eureka中,注册的应用名为seata-server。
config {
type = "file"
}
指定了使用本地的file.conf配置,从目前支持的远程配置类型(nacos 、apollo、zk、consul、etcd3)看,不支持spring cloud config的远程配置,等待阿里后期版本吧。
### 3.3 编辑配置文件
**vi conf/file.conf**
修改对外提供的访问地址:
```json
service {
#vgroup->rgroup
vgroup_mapping.my_test_tx_group = "default"
#only support single node
default.grouplist = "192.168.5.254:8091"
#degrade current not support
enableDegrade = false
#disable
disable = false
#unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
max.commit.retry.timeout = "-1"
max.rollback.retry.timeout = "-1"
}
```
目前,只有default.grouplist = "192.168.5.254:8091"配置项需要修改。TC对外提供全局事物操作的ip:port。
注意:后期版本的file.conf配置项的内容可能支持spring cloud config,也就说这些配置会被放到git上。
修改基于数据库来存储事物信息:
```json
store {
## store mode: file、db
mode = "db" # 修改为基于db来存储事物信息
## database store
db {
## the implement of javax.sql.DataSource, such as DruidDataSource(druid)/BasicDataSource(dbcp) etc.
datasource = "dbcp"
## mysql/oracle/h2/oceanbase etc.
db-type = "mysql"
driver-class-name = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://192.168.5.78:3306/seata?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai"
user = "root"
password = "<PASSWORD>"
min-conn = 1
max-conn = 3
global.table = "global_table"
branch.table = "branch_table"
lock-table = "lock_table"
query-limit = 100
}
}
```
这里需要修改一下连接mysql的配置项。
### 3.4 启动TC服务器
调试启动
./bin/seata-server.sh
生产启动
nohup ./bin/seata-server.sh > /var/log/seata-server.log 2>&1 &
因为seata-server(TC),也是基于java开发的,因此可以基于修改/bin/seata-server.sh的jvm启动项,来优化seata-server。
## 4.RM客户端配置
RM是集成到spring cloud的服务上,seata对数据(DataSource)对象进行拦截,模拟实现两阶段提交。
### 4.1 初始化RM表结构
**mysql**
执行seata-server服务器上conf/db_undo_log.sql脚本,创建回滚表(undo_log),用于在二阶段,RM回滚数据(补偿)使用。注意:db_undo_log.sql只需要在RM上执行。为什么RM需要使用undo_log表,可以见:"seata理解分析章节"。
### 4.2 pom.xml加入eureka客户端
因为使用eureka来发现TC服务位置,因此pom.xml中需要加入eureka-client配置。
```xml
<!-- spring cloud eureka client-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
```
### 4.3 spring boot文件加入eureka客户端配置
```properties
spring.application.name=sc-seata-mstest1
server.port=8101
spring.datasource.url=jdbc:mysql://192.168.5.78:3306/seata1?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=<PASSWORD>
spring.jpa.show-sql=true
eureka.client.service-url.defaultZone=http://sc-eureka:[email protected]:8070/eureka/,http://sc-eureka:[email protected]:8071/eureka/
eureka.instance.prefer-ip-address=true
eureka.healthcheck.enabled=true
```
### 4.4 编辑注册文件
**vi src/main/resources/registry.conf**
```json
registry {
type = "eureka"
eureka {
serviceUrl = "http://sc-eureka:[email protected]:8070/eureka/,http://sc-eureka:[email protected]:8071/eureka/"
application = "seata-server"
weight = "1"
}
}
config {
# file、nacos 、apollo、zk
type = "file"
file {
name = "file.conf"
}
}
```
使用了eureka注册中心,从eureka上获取TC服务器的位置,从而实现TC服务器位置发现和高可用。
具体配置介绍:可以看上面的TC服务器配置文档。
注意:这里的serviceUrl和application配置项和TC服务器registry.conf上的serviceUrl和application配置项相同。也就是TC服务器把自己的位置注册到eureka上,RM客户端从eureka上发现TC服务器位置。
### 4.5 编辑配置文件
**vi src/main/resources/file.conf**
```json
service {
#vgroup->rgroup
vgroup_mapping.sc-seata-bztest1-fescar-service-group="seata-server"
#vgroup_mapping.sc-seata-bztest1-fescar-service-group="default"
#only support single node
#default.grouplist = "192.168.5.254:8091"
#degrade current not support
enableDegrade = false
#disable
disable = false
#unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent
max.commit.retry.timeout = "-1"
max.rollback.retry.timeout = "-1"
disableGlobalTransaction = false
}
```
配置解释:
service.vgroup_mapping.**sc-seata-bztest1**-fescar-service-group="seata-server" # 指定了sc-seata-bztest1事物组(transactional group)使用的TC服务器,因为使用的eureka服务发现TC位置,因此这里要配置为注册到eureka上的TC应用名。sc-seata-bztest1对应于spring.application.name(应用名)的配置项,如果没有手工配置RM事物组名,则seata RM会使用当前应用名作为事物组名。这个配置项的格式为:
service.vgroup_mapping.**事物组名**-fescar-service-group="**TC注册到eureka的应用名**"
**spring boot启动->读取事物组名(没有指定,则默认为应用名)->根据事物组名获取对应TC位置。**
这样做的好处是,可以配置不同的RM使用不同的TC服务器,可以分类管理并减轻TC服务器压力。例如:XXX服务(RM)连接到TC1服务器上,YYY服务(RM)连接到TC2服务器上。
注释掉:#default.grouplist配置项,因为使用了eureka来发现TC位置,因此无需再使用本配置来直接访问TC服务器了。如果不使用"服务发现",使用本地直连TC,则需要这个配置项指定TC位置。
### 4.6 包装(拦截)Datasource内方法,实现二阶段操作
如果本地事物要加入到全局事物中,则要加入这个DataSourceConfig类来实现本地事物提交和回滚(TC会通知相关的操作)。正常情况下只有RM需要添加这个类,如果只是TM,则没有比较加入这个类。
```java
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druidDataSource() {
return new DruidDataSource();
}
/**
* 需要将 DataSourceProxy 设置为主数据源,否则事务无法回滚
*
* @param druidDataSource The DruidDataSource
* @return The default datasource
*/
@Primary
@Bean("dataSource")
public DataSource dataSource(DruidDataSource druidDataSource) {
return new DataSourceProxy(druidDataSource);
}
}
```
目前,只测试了alibaba的druid数据源,dbcp2还没有验证。
## 5.测试例子说明
seata目录下已经创建了4个项目:
sc-seata-bztest1 主入口,全局事物起点,模拟TM。
sc-seata-mstest1 参与到sc-seata-bztest1发起的全局事物中。
sc-seata-mstest2 参与到sc-seata-bztest1发起的全局事物中。
sc-seata-mstest3 参与到sc-seata-bztest1发起的全局事物中。
例如:对sc-seata-bztest1项目发起请求,http://192.168.5.31:8100/adduser?userId=10&name=mdmd,开启全局事物,调用链如下:
sc-seata-bztest1 ->
sc-seata-mstest1
sc-seata-mstest2 ->
sc-seata-mstest3
sc-seata-mstest1、sc-seata-mstest2、sc-seata-mstest3,分别往自己的mysql数据中增加一条用户数据,如果任何一个位置抛出异常则整个全局事物回滚。
### 5.1.创建测试用表结构
分别创建三个mysql数据库:seata1、seata2、seata3,然后在每个mysql数据库下创建两个表undo_log表和tuser表,建表sql如下:
undo_log表是seata RM的回滚表,用于二阶段回滚数据(如果任何一个RM提交失败,TC通知回滚)。这个表结构,最好使用seata-server的conf/db_undo_log.sql来创建,因为不同的seata版本可能表结构还不一样。
```sql
drop table `undo_log`;
CREATE TABLE `undo_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(20) NOT NULL,
`xid` varchar(100) NOT NULL,
`context` varchar(128) NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(11) NOT NULL,
`log_created` datetime NOT NULL,
`log_modified` datetime NOT NULL,
`ext` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ux_undo_log` (`xid`,`branch_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
```
tuser表,用于测试
```sql
DROP TABLE IF EXISTS `tuser`;
CREATE TABLE `tuser` (
`id` int(255) NOT NULL,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
```
# seata理解分析
## seata的基本原理
### seata的三部分

**Transaction Coordinator(TC):** Maintain status of global and branch transactions, drive the global commit or rollback.
**Transaction Manager(TM):** Define the scope of global transaction: begin a global transaction, commit or rollback a global transaction.
**Resource Manager(RM):** Manage resources that branch transactions working on, talk to TC for registering branch transactions and reporting status of branch transactions, and drive the branch transaction commit or rollback.
关于TC、TM、RM的定义,可以参照官网文档介绍,我们这里将结合测试用例:seata-server、sc-seata-bztest1、 sc-seata-mstest1、 sc-seata-mstest2、sc-seata-mstest3解析seata。
seata-server 相当于TC,已经被安装部署到了测试服务器192.168.5.254上。其会连接mysql,并创建三个表来维护全局事物的状态。
sc-seata-bztest1 相当于TM,其是全局事物(Global Transaction)的起点,其发起全局事物,从TC上获取xid,并发起feign和ribbon请求时附带xid进行传播。
sc-seata-mstest1、sc-seata-mstest2、sc-seata-mstest3 相当于RM,其是全局事物的一部分(Branch Transaction),参与到全局事物中,其通过获取请求的xid来识别全局事物。
上面的sc-seata-bztest1、sc-seata-mstest1、sc-seata-mstest2、sc-seata-mstest3,整个调用链中任何一个位置,出现错误或异常,都将回滚整个事物。
### seata的两阶段提交
我们还是通过测试用例的sc-seata-bztest1、sc-seata-bztest1、sc-seata-bztest2、sc-seata-mstest3四个项目来分析两阶段提交。
例如:对sc-seata-bztest1项目发起请求,http://19192.168.3.11:8100/adduser?userId=10&name=mdmd,开启全局事物,调用链如下:
sc-seata-bztest1 ->
sc-seata-mstest1
sc-seata-mstest2 ->
sc-seata-mstest3
sc-seata-mstest1、sc-seata-mstest2、sc-seata-mstest3,分别往自己的mysql数据中增加一条用户(User)数据,如果任何一个位置抛出异常则整个全局事物回滚。
sc-seata-bztest1调用代码:
```java
@GlobalTransactional(name="addUser")
public Collection<User> addUser(Long userId, String name) {
User user1 = mstest1FeignClient.addUser(userId, name);
User user2 = mstest2FeignClient.addUser(userId, name);
Collection<User> users = new ArrayList<User>();
users.add(user1);
users.add(user2);
return users;
}
```
sc-seata-mstest1调用代码:
```java
@RestController
public class SeataMicroserviceTest1Controller {
@Autowired
private UserService userService;
@GetMapping("/addUser")
public User addUser(@RequestParam("userId") Long userId,
@RequestParam("name") String name) {
User user = new User(userId,name);
user = this.userService.addUser(user);
return user;
}
}
```
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public User addUser(User user) {
return this.userRepository.saveAndFlush(user);
}
}
```
User user1 = mstest1FeignClient.addUser(userId, name);
User user2 = mstest2FeignClient.addUser(userId, name);
sc-seata-bztest1(TM)分布调用了sc-seata-mstest1(RM)和sc-seata-mstest2(RM)服务来增加用户,sc-seata-mstest1调用成功后sc-seata-mstest1的本地事物提交(spring transaction commit),新增的用户写到seata1数据库tuser表中,但sc-seata-mstest2调用失败,则sc-seata-bztest1会收到调用失败的异常返回,其也会抛出异常,其通知TC全局事物失败,TC则通知sc-seata-mstest1(RM)回退,sc-seata-mstest1接收到TC回退请求后,根据TC发送过来的xid获取undo_log的镜像前数据,翻译成sql,反向执行并提交。
## seata如何实现的undo
我们就拿最复杂的update来解析seata如果生成undo的前后镜像:
前镜像(beforeImage)生成:
```java
protected TableRecords beforeImage() throws SQLException {
...
StringBuffer selectSQLAppender = new StringBuffer("SELECT ");
if (!tmeta.containsPK(updateColumns)) {
selectSQLAppender.append(this.getColumnNameInSQL(tmeta.getPkName()) + ", ");
}
...
selectSQLAppender.append(" FROM " + this.getFromTableInSQL());
if (StringUtils.isNotBlank(whereCondition)) {
selectSQLAppender.append(" WHERE " + whereCondition);
}
selectSQLAppender.append(" FOR UPDATE");
String selectSQL = selectSQLAppender.toString();
...
return beforeImage;
}
```
前镜像生成,其根据update语句,反向解析成select语句,并使用for upldate关键字,这里的重点就是for update语句,其特点是在本地事物的范围内select涉及到行数据全部加共享锁,也就是说其它事物无法修改。这样就保证这个update语句执行前,获取到前镜像数据正确性。
后镜像生成,由于oracle和mysql这种数据库本地事物的特性(隔离性),当前事物修改后的数据,如果未提交,只有当前事物能看到,其它事物看不到,因此也保证了后镜像数据的正确性。
<file_sep>package sc.com.hystrix.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sc.com.hystrix.domain.User;
@RestController
public class HystrixTest4Controller {
/** 日志 */
private static final Logger logger = LoggerFactory.getLogger(HystrixTest1Controller.class);
@Autowired
private SampleServiceFeignClient sampleServiceFeignClient;
/**
* 测试feign和hystrix组合
* @param id
* @return
*/
@GetMapping(value = "/user4/{id}")
public User findUser1ById(@PathVariable Long id, @RequestParam long sleep) {
logger.info("request param sleep[{}].", sleep);
return this.sampleServiceFeignClient.findByIdWithSleep(id, sleep);
}
}
<file_sep> --客户端数据:明码密码,<PASSWORD>
insert into OAUTH_CLIENT_DETAILS (CLIENT_ID, RESOURCE_IDS, CLIENT_SECRET, SCOPE, AUTHORIZED_GRANT_TYPES, WEB_SERVER_REDIRECT_URI, AUTHORITIES, ACCESS_TOKEN_VALIDITY, REFRESH_TOKEN_VALIDITY, ADDITIONAL_INFORMATION, AUTOAPPROVE)
values ('test_client', null, '{bcrypt}$2a$10$uT8xtlOWnIiS9Es1QVN9LeKcWpoeuk.bZqgFpNVsCFWacuXn/Moei', 'service,web', 'refresh_token,password,authorization_code', 'http://localhost:6002/login', null, null, null, null, null);
--用户表数据:明码密码,<PASSWORD>
insert into OAUTH_USER (USER_ID,USERNAME, PASSWORD, ENABLED )
values (999, 'test_user', '{bcrypt}$2a$10$uT8xtlOWnIiS9Es1QVN9LeKcWpoeuk.bZqgFpNVsCFWacuXn/Moei', '1');
--授权表数据:
insert into OAUTH_AUTHORITY (AUTHORITY_ID, NAME) values (1001, 'test_admin');
insert into OAUTH_AUTHORITY (AUTHORITY_ID, NAME) values (1002, 'test_user');
--用户授权表数据:
insert into OAUTH_USER_AUTHORITY (USER_ID, AUTHORITY_ID) values (999, 1001);
insert into OAUTH_USER_AUTHORITY (USER_ID, AUTHORITY_ID) values (999, 1002);
-- 如果为了测试单点登录,可以再增加一个客户端
insert into OAUTH_CLIENT_DETAILS (CLIENT_ID, RESOURCE_IDS, CLIENT_SECRET, SCOPE, AUTHORIZED_GRANT_TYPES, WEB_SERVER_REDIRECT_URI, AUTHORITIES, ACCESS_TOKEN_VALIDITY, REFRESH_TOKEN_VALIDITY, ADDITIONAL_INFORMATION, AUTOAPPROVE)
values ('test_client1', null, '{bcrypt}$2a$10$uT8xtlOWnIiS9Es1QVN9LeKcWpoeuk.bZqgFpNVsCFWacuXn/Moei', 'service,web', 'refresh_token,password,authorization_code', 'http://localhost:6003/login', null, null, null, null, null);
<file_sep>package com.sc.oauth2.codeauthorization;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* web相关安全配置类
* 用于服务(web)的安全配置,区别于ResourceServerConfiguration用于服务(service)的安全配置。
* 主要用于授权码模式(authorization_code)的安全规则配置。
* @author Administrator
*
*/
@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Value("${security.oauth2.client.client-id}")
private String clientId;
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().
and().logout().logoutSuccessUrl("http://localhost:6001/auth/exit?clientId="+this.clientId).
and().authorizeRequests().antMatchers("/**").authenticated();
// @formatter:on
}
@Override
public void configure(WebSecurity web) throws Exception {
}
}
|
e72a46f1e8507bde694cb7c3cd8e656ef0c0e73c
|
[
"SQL",
"Markdown",
"Maven POM",
"INI",
"Java"
] | 45 |
Java
|
zhangdberic/springcloud-old
|
678407deeaf9af122c8544b4299f3d2754efe6e9
|
13e3b1958b88bcbfeee801c813d442ae39893842
|
refs/heads/main
|
<file_sep>source 'https://rubygems.org'
gem 'vertebrae', '> 0.5'
# Add dependencies to develop your gem here.
# Include everything needed to run rake, tests, features, etc.
group :development do
gem 'pry', '~> 0.10'
gem 'pry-byebug', '~> 3.4'
gem 'webmock', '~> 3.0', '>= 3.0.1'
gem 'rspec', '~> 3.6'
gem 'rdoc', ">= 6.3.1"
gem 'bundler'
gem 'juwelier'
gem 'simplecov', ">= 0"
gem 'rubocop'
end
<file_sep>require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe IdentityApiClient::Client do
let(:options) { { :host => 'foo.bar.com', :api_token => 'abc123' }}
subject { described_class.new(options) }
it 'should respond to member' do
expect(subject).to respond_to(:member)
end
context 'setup options ' do
let(:config) { subject.connection.configuration }
it 'should initialize the options' do
expect(config.host).to eq 'foo.bar.com'
expect(config.options[:api_token]).to eq 'abc123'
end
end
end
<file_sep>$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'rspec'
require 'identity-api-client'
require 'webmock/rspec'
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].sort.each {|f| require f}
RSpec.configure do |config|
config.color = true
config.include WebMock::API
config.before(:each) do
WebMock.reset!
end
config.after(:each) do
WebMock.reset!
end
end
def stub_get(path)
stub_identity_request(:get, path)
end
def stub_post(path)
stub_identity_request(:post, path)
end
def stub_identity_request(method, path)
stub_request(method, "https://test.com" + path)
end
def fixture_path
File.expand_path("../fixtures", __FILE__)
end
def fixture(file)
File.new(File.join(fixture_path, '/', file)).read
end
<file_sep>module IdentityApiClient
class Member < Base
def details(guid: nil, email: nil, load_current_consents: false)
if guid.present?
params = {'guid' => guid, 'api_token' => client.connection.configuration.options[:api_token]}
elsif email.present?
params = {'email' => email, 'api_token' => client.connection.configuration.options[:api_token]}
else
raise "Must have one of guid or email"
end
if load_current_consents
params['load_current_consents'] = true
end
resp = client.post_request('/api/member/details', params)
resp.body
end
end
end
<file_sep># Generated by juwelier
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Juwelier::Tasks in Rakefile, and run 'rake gemspec'
# -*- encoding: utf-8 -*-
# stub: identity-api-client 0.1.4 ruby lib
Gem::Specification.new do |s|
s.name = "identity-api-client".freeze
s.version = "0.1.4"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib".freeze]
s.authors = ["<NAME>".freeze]
s.date = "2021-12-14"
s.description = "Provides a simple ruby binding to 38dgs identity API".freeze
s.email = "<EMAIL>".freeze
s.extra_rdoc_files = [
"LICENSE",
"README.md"
]
s.files = [
".document",
".github/workflows/ci.yml",
".rspec",
".rubocop.yml",
".ruby-gemset",
".ruby-version",
"Gemfile",
"LICENSE",
"README.md",
"Rakefile",
"VERSION",
"identity-api-client.gemspec",
"lib/identity-api-client.rb",
"lib/identity-api-client/base.rb",
"lib/identity-api-client/client.rb",
"lib/identity-api-client/member.rb",
"spec/client_spec.rb",
"spec/fixtures/details.json",
"spec/fixtures/details_with_consents.json",
"spec/member_spec.rb",
"spec/spec_helper.rb"
]
s.homepage = "http://github.com/controlshift/identity-api-client".freeze
s.licenses = ["MIT".freeze]
s.rubygems_version = "3.1.6".freeze
s.summary = "API Client for 38 Degree's Identity API".freeze
if s.respond_to? :specification_version then
s.specification_version = 4
end
if s.respond_to? :add_runtime_dependency then
s.add_runtime_dependency(%q<vertebrae>.freeze, ["> 0.5"])
s.add_development_dependency(%q<pry>.freeze, ["~> 0.10"])
s.add_development_dependency(%q<pry-byebug>.freeze, ["~> 3.4"])
s.add_development_dependency(%q<webmock>.freeze, ["~> 3.0", ">= 3.0.1"])
s.add_development_dependency(%q<rspec>.freeze, ["~> 3.6"])
s.add_development_dependency(%q<rdoc>.freeze, [">= 6.3.1"])
s.add_development_dependency(%q<bundler>.freeze, [">= 0"])
s.add_development_dependency(%q<juwelier>.freeze, [">= 0"])
s.add_development_dependency(%q<simplecov>.freeze, [">= 0"])
s.add_development_dependency(%q<rubocop>.freeze, [">= 0"])
else
s.add_dependency(%q<vertebrae>.freeze, ["> 0.5"])
s.add_dependency(%q<pry>.freeze, ["~> 0.10"])
s.add_dependency(%q<pry-byebug>.freeze, ["~> 3.4"])
s.add_dependency(%q<webmock>.freeze, ["~> 3.0", ">= 3.0.1"])
s.add_dependency(%q<rspec>.freeze, ["~> 3.6"])
s.add_dependency(%q<rdoc>.freeze, [">= 6.3.1"])
s.add_dependency(%q<bundler>.freeze, [">= 0"])
s.add_dependency(%q<juwelier>.freeze, [">= 0"])
s.add_dependency(%q<simplecov>.freeze, [">= 0"])
s.add_dependency(%q<rubocop>.freeze, [">= 0"])
end
end
<file_sep>require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe IdentityApiClient::Member do
subject { IdentityApiClient.new(host: 'test.com', api_token: '<KEY>') }
let(:request_path) { '/api/member/details' }
describe 'failure' do
context "with no email or guid passed" do
it "should raise error" do
expect { subject.member.details() }.to raise_error "Must have one of guid or email"
end
end
end
describe 'success' do
let(:status) { 200 }
before(:each) do
stub_post(request_path).with(body: expected_request).to_return(:body => body, :status => status,
:headers => {:content_type => "application/json; charset=utf-8"})
end
context 'without load_current_consents' do
let(:expected_request) { {'guid' => 'abcdef1234567890', 'api_token' => '<KEY>'}.to_json }
let(:body) { fixture('details.json') }
it 'should get member details back from the API' do
resp = subject.member.details(guid: 'abcdef1234567890')
expect(resp.first_name).to eq('Joe')
expect(resp.last_name).to eq('Bloggs')
expect(resp.email).to eq('<EMAIL>')
end
end
context 'with load_current_consents' do
let(:expected_request) { {'guid' => 'abcdef1234567890', 'api_token' => '<KEY>', 'load_current_consents' => true}.to_json }
let(:body) { fixture('details_with_consents.json') }
it 'should get member details with consents back from the API' do
resp = subject.member.details(guid: 'abcdef1234567890', load_current_consents: true)
expect(resp.first_name).to eq('Joe')
expect(resp.last_name).to eq('Bloggs')
expect(resp.email).to eq('<EMAIL>')
expect(resp.consents.count).to eq 2
expect(resp.consents[0].public_id).to eq 'terms_of_service_1.0'
end
end
context 'with email passed' do
let(:expected_request) { {'email' => '<EMAIL>', 'api_token' => '<KEY>'}.to_json }
let(:body) { fixture('details.json') }
it 'should get member details back from the API' do
resp = subject.member.details(email: '<EMAIL>')
expect(resp.first_name).to eq('Joe')
expect(resp.last_name).to eq('Bloggs')
expect(resp.email).to eq('<EMAIL>')
end
end
end
end
<file_sep>require 'vertebrae'
require 'identity-api-client/client'
require 'identity-api-client/base'
require 'identity-api-client/member'
module IdentityApiClient
extend Vertebrae::Base
class << self
def new(options = {}, &block)
IdentityApiClient::Client.new(options, &block)
end
end
end
<file_sep># identity-api-client
[](https://github.com/controlshift/identity-api-client/actions/workflows/ci.yml)
API Client for 38 Degree's Identity API
## Install
This api client is distributed as a ruby gem.
`gem install identity-api-client`
## Usage
```ruby
identity = IdentityApiClient.new(host: 'id.test.com', api_token: '<PASSWORD>')
person = identity.member.details('abc123', load_current_consents: true)
person.first_name
=> 'Jane'
person.last_name
=> 'Smith'
person.consents.first.public_id
=> 'terms_of_service_1.0'
```
<file_sep>module IdentityApiClient
class Client < Vertebrae::API
def member
@member ||= IdentityApiClient::Member.new(client: self)
end
private
def extract_data_from_params(params)
params.to_json
end
def default_options
{
user_agent: 'IdentityApiClient'
}
end
end
end
<file_sep>module IdentityApiClient
class Base < Vertebrae::Model
end
end
|
d1a40061e2144f87d23278a7c9ef13d1b48a1973
|
[
"Markdown",
"Ruby"
] | 10 |
Ruby
|
controlshift/identity-api-client
|
91c3a212e09a9b0ca0d90a483795d30bed0ad853
|
3d2986ffe4591ab6be707ab3928b51edcf26bd64
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/tablas.css">
<script src="js/Validar.js"></script>
<script src="js/jquery.validate.min.js"></script>
</head>
<body>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function(event){
$("#cboRegion").change(function(){
var id_region=$("#cboRegion").val();
$.ajax({
url:"llenar_ciudad.php",
type:'POST',
data:{idregiones:id_region},
success: function(data){
$("#cboCiudad").html(data);
}
});
});
});
</script>
<?php
include_once './menu.php';
?>
<?php
$cone= mysqli_connect("localhost", "root", "oracle", "mis_perris");
$reg= mysqli_query($cone, "select * from regiones");
$regis= mysqli_query($cone, "select * from tipo_vivienda");
?>
<center>
<form method="POST" action="grabar_formulario.php" id="formularioperro">
<table border="1">
<thead>
<tr>
<th>Formulario de ingreso de Caninos</th>
</tr>
</thead>
<tbody>
<tr>
<td>Rut:</td>
<td><input type="text" name="txtRut" value="" />
</td>
</tr>
<tr>
<td>Nombre:</td>
<td><input type="text" name="txtNombre" value="" /></td>
</tr>
<tr>
<td>Telefono:</td>
<td><input type="number" name="txtTelefono" value="" min="9"/></td>
</tr>
<tr>
<td>Correo:</td>
<td><input type="email" name="txtCorreo" value="" /></td>
</tr>
<tr>
<td>Fecha de Nacimiento:</td>
<td><input type="text" name="txtFecha" value="" /></td>
</tr>
<tr>
<td>Region</td>
<td><select name="cboRegion" id="cboRegion" >
<?php
while ($row = mysqli_fetch_array($reg)){
echo'<option value="'.$row[0].'">'.$row[1].'</option>';
}
?>
</select></td>
</tr>
<tr>
<td>Ciudad:</td>
<td><select name="cboCiudad" id="cboCiudad" ></select></td>
</tr>
<tr>
<td>Tipo de Vivienda:</td>
<td><select name="cboTipo" id="cboTipo">
<?php
while ($row = mysqli_fetch_array($regis)){
echo'<option value="'.$row[0].'">'.$row[1].'</option>';
}
?>
</select></td>
</tr>
<tr>
<td><input type="submit" value="Enviar" />
<input type="reset" value="Limpiar" />
</td>
</tr>
</tbody>
</table>
</form>
</center>
</body>
</html>
<file_sep>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/tablas.css">
</head>
<body>
<?php include_once './menu.php'; ?>
<?php
$cone= mysqli_connect("localhost", "root", "oracle", "mis_perris");
$reg= mysqli_query($cone, "select * from formulario");
?>
<form method="POST" action="modificar_perro.php">
<table border="1">
<thead>
<tr>
<th>Formulario de ingreso de Caninos</th>
</tr>
</thead>
<tbody>
<tr>
<td>Rut:</td>
<td><select name="cboRut" id="cboRut">
<?php
while ($row = mysqli_fetch_array($reg)){
echo'<option value="'.$row[0].'">'.$row[0].'</option>';
}
?>
</select></td>
</tr>
<tr>
<td>Nombre:</td>
<td><input type="text" name="txtNombre" value="" /></td>
</tr>
<tr>
<td>Telefono:</td>
<td><input type="number" name="txtTelefono" value="" /></td>
</tr>
<tr>
<td>Correo:</td>
<td><input type="text" name="txtCorreo" value="" /></td>
</tr>
<tr>
<td>Fecha de Nacimiento:</td>
<td><input type="text" name="txtFecha" value="" /></td>
</tr>
<tr>
<td><input type="submit" value="Modificar" />
<input type="reset" value="Limpiar" />
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
<file_sep><?php
class perro{
private $rut;
private $nombre;
private $telefono;
private $correo;
private $ciudad;
private $fecha_nacimiento;
private $tipo_vivienda;
function __construct() {
}
function getRut() {
return $this->rut;
}
function getNombre() {
return $this->nombre;
}
function getTelefono() {
return $this->telefono;
}
function getCorreo() {
return $this->correo;
}
function getCiudad() {
return $this->ciudad;
}
function getFecha_nacimiento() {
return $this->fecha_nacimiento;
}
function getTipo_vivienda() {
return $this->tipo_vivienda;
}
function setRut($rut) {
$this->rut = $rut;
}
function setNombre($nombre) {
$this->nombre = $nombre;
}
function setTelefono($telefono) {
$this->telefono = $telefono;
}
function setCorreo($correo) {
$this->correo = $correo;
}
function setCiudad($ciudad) {
$this->ciudad = $ciudad;
}
function setFecha_nacimiento($fecha_nacimiento) {
$this->fecha_nacimiento = $fecha_nacimiento;
}
function setTipo_vivienda($tipo_vivienda) {
$this->tipo_vivienda = $tipo_vivienda;
}
}
<file_sep>$(document).ready(function(){
$("#formularioperro").validate({
rules:{
txtRut:{
required:true,
minlenght:10
},
},
messages:{
required:"Campo Requerido",
minlenght: "Debe ser formato chileno"
}
})
})
<file_sep><?php
$id=$_POST["txtId"];
$titulo=$_POST["txtTitulo"];
$desc=$_POST["txtDesc"];
$imagen=$_POST["imagen"];
//conexion
$cone= mysqli_connect("localhost", "root", "oracle", "mis_perris");
$nombre_imagen="imagen".$id."-".$titulo;
$sql="insert into galeria values ($id, '$titulo', '$desc', '$nombre_imagen')";
$reg= mysqli_query($cone, $sql);
if ($_FILES["imagen"]['type']=="image/jpg"){
copy($_FILES["imagen"]["tpm_name"], "../img/".$nombre_imagen.".jpg");
}<file_sep><?php
session_start();
if (!isset($_SESSION["sesion"])){
header("location:login.php");
}else{
$usuario=$_SESSION["sesion"];
}
?>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/hoja.css">
<title>Mis perris</title>
</head>
<body bgcolor="FCFCFC">
<center>
<?php
include_once 'menu.php';
?>
<div class="casilla">
<div class="contenidoi">
<h2 class="titulo" style="text-align: right; position: relative; right: 10px;">Rescate</h2>
<h4 class="tit" style="text-align: right; position: relative; top: -5px; right: 10px;">ESTAPA UNO</h4>
<hr size= "4" align= "right" style="top: -1px; right: 10px; width: 70px" >
<h5 class="tit" style="text-align: right; position: relative; top: -0.1px; right: 10px;">Rescatamos perros en situacion de peligro y/o abandono. Los rehabilitamos y los preparamos para buscarle un hogar</h5>
<img style="position: relative; left: 115px; top: -0.1px" src="img/perros/rescate.jpg" alt="">
</div>
<div class="contenidod" >
<img style="width: 200px; height: 200px; position: relative; top: 20px; right: 190px;" src="img/perros/crowfunding.jpg" alt="">
<h2 class="titulo" style="position: relative; top: 10px; right: 195px;">CROWFUNDING</h2>
<h4 class="tit" style="position: relative; top: -0.01px; right: 215px;">FINANCIAMENTO</h4>
<hr size= "4" aling="left" style="position: relative; left: 12px; top: -1px; width: 70px;">
<h5>Sigue nuestras redes sociales para informarte acerca de las diversas campañas y actividades que realizamos para obtener financiamiento para seguir ayudando</h5>
<a href=""><input class="fuente" type="button" style="position: relative; right: 248px;" value="campañas"></a>
</div>
</div>
<?php
include_once './galeria.php';
?>
</center>
</body>
</html>
<file_sep><?php
session_start();
//eliminar variable de session
unset($_SESSION["session"]);
header("location:login.php");
<file_sep><?php
session_start();
$usuario=$_POST["txtUsuario"];
$pass=$_POST["txtPass"];
$cone= mysqli_connect("localhost", "root", "oracle", "mis_perris");
$sql="select * from login where usuario='$usuario' and pass='$pass'";
$reg= mysqli_query($cone, $sql);
while ($row = mysqli_fetch_array($reg)) {
$_SESSION["sesion"]=$usuario;
echo'OK';
return;
}
echo 'No Existe Usuario o Password';
<file_sep><?php
include_once '../controlador/Daoperris.php';
include_once '../modelo/perro.php';
$rut=$_POST["cboRut"];
$nombre=$_POST["txtNombre"];
$telefono=$_POST["txtTelefono"];
$correo=$_POST["txtCorreo"];
$fecha_nacimiento=$_POST["txtFecha"];
$formulario=new perro();
$formulario->setRut($rut);
$formulario->setNombre($nombre);
$formulario->setTelefono($telefono);
$formulario->setCorreo($correo);
$formulario->setFecha_nacimiento($fecha_nacimiento);
$dao=new Daoperris();
$filas_afectadas=$dao->Modificar($formulario, $rut);
if ($filas_afectadas>0) {
echo 'Modifico';
} else {
echo 'No Modifico';
}
<file_sep><?php
$id_region=$_POST["idregiones"];
$cone= mysqli_connect("localhost", "root", "oracle", "mis_perris");
$reg= mysqli_query($cone, "select * from ciudades "
. "where regiones_idregiones=$id_region");
?>
<option value="0">Seleccione</option>
<?php
while ($row = mysqli_fetch_array($reg)) {
echo '<option value="'.$row[0].'">'.$row[1].'</option>';
}
?>
<file_sep><?php
include_once '../controlador/Daoperris.php';
$dao=new Daoperris();
$rut=$_GET["rut"];
$resp=$dao->Eliminar($rut);
//redireccionar
header("location:listar.php");
<file_sep><?php
include_once 'conexion.php';
include_once '../modelo/perro.php';
class Daoperris {
private $cone;
private $rut;
function __construct() {
try {
$this->cone = new conexion();
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function Grabar($x) {
try {
$sql = "insert into formulario "
. "values('@ru','@nom',@te,'@co', '@fe','@ci', '@vi')";
$sql = str_replace("@ru", $x->getRut(), $sql);
$sql = str_replace("@nom", $x->getNombre(), $sql);
$sql = str_replace("@te", $x->getTelefono(), $sql);
$sql = str_replace("@co", $x->getCorreo(), $sql);
$sql = str_replace("@fe", $x->getFecha_nacimiento(), $sql);
$sql = str_replace("@ci", $x->getCiudad(), $sql);
$sql = str_replace("@vi", $x->getTipo_vivienda(), $sql);
return $this->cone->SqlOperacion($sql);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function Modificar($perro, $filtro) {
try {
$sql = "update formulario set nombre='@nom',telefono= @te, correo='@co', fecha_nacimiento='@fe' "
. " where rut=".$filtro;
$sql = str_replace("@nom", $perro->getNombre(), $sql);
$sql = str_replace("@te", $perro->getTelefono(), $sql);
$sql = str_replace("@co", $perro->getCorreo(), $sql);
$sql = str_replace("@fe", $perro->getFecha_nacimiento(), $sql);
return $this->cone->SqlOperacion($sql);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function Listar() {
try {
$sql = "select * from formulario";
return $this->cone->SqlSeleccion($sql);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function Eliminar($rut) {
try {
$sql = "delete from formulario where rut='$rut'";
return $this->cone->SqlOperacion($sql);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
public function Buscar($rut) {
try {
$sql = "select * from formulario where rut='$rut'";
return $this->cone->SqlSeleccion($sql);
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
}
}
<file_sep><?php
//definicion de los graficos
require './graficos/jpgraph-4.2.2/src/jpgraph.php';
require'./graficos/jpgraph-4.2.2/src/jpgraph_bar.php';
//crear conexion
$cone= mysqli_connect("localhost", "root", "oracle", "mis_perris");
$sql="select * from formulario";
$reg= mysqli_query($cone, $sql);
//guardar los datos para eje x e Y
//Se almacena en "arreglos"
while ($row = mysqli_fetch_array($reg)) {
$data[]=$row[4];//años
$etiquetas[]=$row[0];//patente
}
//se crea el grafico
$grafico=new Graph(500,500,'formulario');
//definicion de la escala
$grafico->setScale('textint');
//definicion de titulo
$grafico->title->set('Grafico de Mis Perris');//titulo
$grafico->xaxis->title->set('Perros');//titulo eje x
$grafico->yaxis->title->set('Edad');//titulo eje Y
$grafico->xaxis->SetTickLabels($etiquetas);//asignar los textos en eje x
//creacion grafico de barras
$barra=new BarPlot($data);
$barra->SetWidth(10);//asignar el ancho de la barra
//se asigna el grafico de barra al diseño del grafico principal
$grafico->Add($barra);
//se imprime el grafico
$grafico->Stroke();
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="stylesheet" href="css/tablas.css">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script>
<?php
include_once './menu.php';
?>
<h1>Listado de Clientes</h1>
<table class="table">
<tr>
<td>Rut</td>
<td>Nombre</td>
<td>Telefono</td>
<td>Correo</td>
<td>Fecha_nacimiento</td>
<td>Eliminar</td>
<td>Modificar</td>
</tr>
<?php
include_once '../controlador/Daoperris.php';
$dao = new Daoperris();
$reg = $dao->Listar();
$archivo= fopen("listado.csv","w");
fwrite($archivo, "rut;nombre;Telefono;correo;Fecha_nacimiento \n");
while ($row = mysqli_fetch_array($reg)) {
echo '<tr>';
echo '<td>' . $row[0] . "</td>";
echo '<td>' . $row[1] . "</td>";
echo '<td>' . $row[2] . "</td>";
echo '<td>' . $row[3] . "</td>";
echo '<td>' . $row[4] . "</td>";
echo '<td><a href="eliminar.php?rut=' . $row[0] . '"> Eliminar </a></td>';
echo '<td><a href="modificar.php?rut=' . $row[0] . '"> Modificar </a></td>';
echo '</tr>';
fwrite($archivo, $row[0].";".$row[1].";".$row[2].";".$row[3].";".$row[4]."\n");
}
fclose($archivo);
?>
</table>
<a href="listado.csv">Exportar Excel</a> /
<a href="lista_pdf.php"> Exportar PDF </a>
</body>
</html>
<file_sep>
<head>
<link rel="stylesheet" href="css/hoja.css">
</head>
<center>
<div class="barra">
<img style="width: 200px; position: relative; right: 325px; top: 5px" src="img/perros/logo.jpg" alt="">
<a href="home.php" class="letra" style="text-decoration: none; position: relative; top: -10px; right: 150px;" >Inicio</a>
<a href="Ingresar.php" class="letra" style="text-decoration: none; position: relative; top: -10px; right: 110px;" >Ingresar</a>
<a href="listar.php" class="letra" style="text-decoration: none; position: relative; top: -10px; right: 75px;" >Listar</a>
<a href="logout.php" class="letra" style="text-decoration: none; position: relative; top: -10px; right: 40px;" >Log Out</a>
</div>
<div class="perro">
<?php
include_once './fotos.php';
?>
</div>
<div class="barras" style="position: relative; top: -17px">
<p class="letra" style="position: relative; top: 25px; right: 450px;"> +56 9 98765431 </p>
<p class="letra" style="position: relative; top: -10px;"> Rescate y adopción de perros calle</p>
<a href=""><img style="width: 25px; height: 25px; position: relative; left: 400px; top: -50px" src="img/perros/social-inst.jpg" alt=""></a>
<a href=""><img style="width: 25px; height: 25px; position: relative; left: 400px; top: -50px" src="img/perros/social-twitter.jpg" alt=""></a>
<a href=""><img style="width: 25px; height: 25px; position: relative; left: 400px; top: -50px" src="img/perros/socialfacebook.jpg" alt=""></a>
<a href=""><img style="width: 25px; height: 25px; position: relative; left: 400px; top: -50px" src="img/perros/socialplus.jpg" alt=""></a>
</div>
</center>
<file_sep><?php
include_once '../controlador/Daoperris.php';
include_once '../modelo/perro.php';
$rut=$_POST["txtRut"];
$nombre=$_POST["txtNombre"];
$telefono=$_POST["txtTelefono"];
$correo=$_POST["txtCorreo"];
$fecha_nacimiento=$_POST["txtFecha"];
$ciudad=$_POST[("cboRegion")];
$tipo_vivienda=$_POST[("cboTipo")];
$perris=new perro();
$perris->setRut($rut);
$perris->setNombre($nombre);
$perris->setTelefono($telefono);
$perris->setCorreo($correo);
$perris->setFecha_nacimiento($fecha_nacimiento);
$perris->setCiudad($ciudad);
$perris->setTipo_vivienda($tipo_vivienda);
$dao=new Daoperris();
$filas_afectadas=$dao->Grabar($perris);
if ($filas_afectadas>0) {
echo 'Grabo';
} else {
echo 'No Grabo';
}
|
c5decc62259605b9f288236121140f511ec9b9c8
|
[
"JavaScript",
"PHP"
] | 16 |
PHP
|
pabloherreram1/mis_perris
|
3c629a36ee87c5e5f5a9d1e7b1f374f84d88fbda
|
65caeae3ade0ea8c19395e0566fce5b07f7798f3
|
refs/heads/master
|
<repo_name>Ku6epnec/StrategyCourse<file_sep>/Assets/Scripts/Abstractions/IUnitProducer.cs
public interface IUnitProducer
{
void ProduceUnit();
}
<file_sep>/Assets/Scripts/UserControlSystem/ProduceUnitCommand.cs
using UnityEngine;
public class ProduceUnitCommand : IProduceUnitCommand
{
public GameObject UnitPrefab => _unitPrefab;
[SerializeField] private GameObject _unitPrefab;
}
<file_sep>/Assets/Scripts/Abstractions/CommandExecutorBaseT.cs
using UnityEngine;
/*public abstract class CommandExecutorBase<T> : MonoBehaviour, ICommandExecutor
{
public void ExecuteCommand(object command) => ExecuteSpecificCommand((T)command);
public abstract void ExecuteSpecificCommand<T>(T command) where T : ICommand;
}*/
<file_sep>/Assets/Scripts/Core/MainBuilding.cs
using UnityEngine;
public class MainBuilding : MonoBehaviour, IUnitProducer, ISelecatable
{
public float Health => _health;
public float MaxHealth => _maxHealth;
public Sprite Icon => _icon;
[SerializeField] private GameObject _unitPrefab;
[SerializeField] private Transform _unitsParent;
[SerializeField] private float _maxHealth = 1000;
[SerializeField] private Sprite _icon;
private float _health = 1000;
public void ProduceUnit()
{
Instantiate(_unitPrefab, new Vector3(Random.Range(0, 3), 0, Random.Range(0, 8)), Quaternion.identity, _unitsParent);
}
}
|
0423dbc05b53aba43eebf34c56fbb4172bcc47fd
|
[
"C#"
] | 4 |
C#
|
Ku6epnec/StrategyCourse
|
0db5e0b352d08b5395912dc2128d41bc5a1c38e6
|
5f56084c309ac1c35891a466f1932570641abf26
|
refs/heads/master
|
<file_sep>package com.unitec.primeraapp
import android.media.MediaPlayer
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity;
import kotlinx.android.synthetic.main.activity_bienvenido.*
import kotlinx.android.synthetic.main.content_bienvenido.*
class BienvenidoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bienvenido)
setSupportActionBar(toolbar)
fab.setOnClickListener { view ->
var peso= txtpeso.text.toString().toFloat()
var altura= txtaltura.text.toString().toFloat()
var imc = Milmc()
var valor = imc.calcular(peso, altura)
// comparamos
if(valor>=20 && valor <=30){
var sonido=MediaPlayer.create(applicationContext, R.raw.feliz)
//Se inicia el sonido
sonido.start()
}
else{
var sonido2=MediaPlayer.create(applicationContext, R.raw.sad)
//Se inicia el sonido
sonido2.start()
}
Snackbar.make(view, "Tu imc es $valor", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
}
<file_sep>package com.unitec.primeraapp
class Milmc {
//Vamos a generar el metodo parar calcular el imc muy sencillo
fun calcular(peso:Float,altura:Float):Float{
var imc = peso/(altura*altura)
return imc
}
}
|
9a92a6434592ae8cadb00849f37165beee146f49
|
[
"Kotlin"
] | 2 |
Kotlin
|
VivianaYaney/PrimeraApp
|
57f0722dde03b92dcb55cfb0f915a0d17e37a54c
|
4839831e03ba4107948492433f5af3cae7ba1de8
|
refs/heads/master
|
<repo_name>pdn4kd/isochoric-expander<file_sep>/recovery_plots_n.py
import numpy as np
import matplotlib.pyplot as plt
stars = np.genfromtxt("planetfits_revised.csv", delimiter=",", names=True, dtype=None)
#nplanets = [(1,3), (1,4), (4,4)]
nplanets = [(1,6), (5,6), (5,5), (6,6)]
# iterate over: [5,e,f,n][n,p] fits, and 1-3, 4, 5, 6, 1-4, 5-6, 1-6 planet systems?
for minplanets, maxplanets in nplanets:
nn_yes_per = [star["per"] for star in stars if ((star["nn_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_yes_a = [star["a"] for star in stars if ((star["nn_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_yes_k = [star["K"] for star in stars if ((star["nn_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_yes_mass = [star["PlanetMass"] for star in stars if ((star["nn_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_no_per = [star["per"] for star in stars if ((star["nn_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_no_a = [star["a"] for star in stars if ((star["nn_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_no_k= [star["K"] for star in stars if ((star["nn_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_no_mass = [star["PlanetMass"] for star in stars if ((star["nn_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_mar_per = [star["per"] for star in stars if ((star["nn_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_mar_a = [star["a"] for star in stars if ((star["nn_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_mar_k = [star["K"] for star in stars if ((star["nn_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nn_mar_mass = [star["PlanetMass"] for star in stars if ((star["nn_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, nnam = plt.subplots()
nnam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
nnam.scatter(nn_yes_a, nn_yes_mass, label="Recovered", color="blue")
nnam.scatter(nn_mar_a, nn_mar_mass, label="Marginal", color="red")
nnam.scatter(nn_no_a, nn_no_mass, label="Excluded", color="black")
#nnam.plot(xs, y1, label="Earth density")
nnam.set_xscale('log')
nnam.set_yscale('log')
nnam.set_xlabel("Semi-Major Axis (au)")
nnam.set_xlim(6e-2,3e1)
nnam.set_ylabel("Mass (Earth-Masses)")
nnam.set_ylim(8e-2,1e4)
nnam.set_title("Fitting: Period, K, Time of Conjunction; ecc = 0 ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
nnam.legend(loc=2)
filename = "nnam" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, nnpk = plt.subplots()
nnpk.scatter(stars["per"], stars["K"], color="gray", s=1)
nnpk.scatter(nn_yes_per, nn_yes_k, label="Recovered", color="blue")
nnpk.scatter(nn_mar_per, nn_mar_k, label="Marginal", color="red")
nnpk.scatter(nn_no_per, nn_no_k, label="Excluded", color="black")
#nnpk.plot(xs, y1, label="Earth density")
nnpk.set_xscale('log')
nnpk.set_yscale('log')
nnpk.set_ylabel("Semi-Amplitude (m/s)")
nnpk.set_ylim(8e-4,2e2)
nnpk.set_xlabel("Period (Days)")
nnpk.set_xlim(6,1e5)
nnpk.set_title("Fitting: Period, K, Time of Conjunction; ecc = 0 ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
nnpk.legend(loc=2)
filename = "nnpk" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
#plt.show()
en_yes_per = [star["per"] for star in stars if ((star["en_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_yes_a = [star["a"] for star in stars if ((star["en_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_yes_k = [star["K"] for star in stars if ((star["en_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_yes_mass = [star["PlanetMass"] for star in stars if ((star["en_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_no_per = [star["per"] for star in stars if ((star["en_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_no_a = [star["a"] for star in stars if ((star["en_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_no_k= [star["K"] for star in stars if ((star["en_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_no_mass = [star["PlanetMass"] for star in stars if ((star["en_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_mar_per = [star["per"] for star in stars if ((star["en_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_mar_a = [star["a"] for star in stars if ((star["en_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_mar_k = [star["K"] for star in stars if ((star["en_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
en_mar_mass = [star["PlanetMass"] for star in stars if ((star["en_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, enam = plt.subplots()
enam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
enam.scatter(en_yes_a, en_yes_mass, label="Recovered", color="blue")
enam.scatter(en_mar_a, en_mar_mass, label="Marginal", color="red")
enam.scatter(en_no_a, en_no_mass, label="Excluded", color="black")
#enam.plot(xs, y1, label="Earth density")
enam.set_xscale('log')
enam.set_yscale('log')
enam.set_xlabel("Semi-Major Axis (au)")
enam.set_xlim(6e-2,3e1)
enam.set_ylabel("Mass (Earth-Masses)")
enam.set_ylim(8e-2,1e4)
enam.set_title("Fitting: Period, K, Time of Conjunction ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
enam.legend(loc=2)
filename = "enam" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, enpk = plt.subplots()
enpk.scatter(stars["per"], stars["K"], color="gray", s=1)
enpk.scatter(en_yes_per, en_yes_k, label="Recovered", color="blue")
enpk.scatter(en_mar_per, en_mar_k, label="Marginal", color="red")
enpk.scatter(en_no_per, en_no_k, label="Excluded", color="black")
#enpk.plot(xs, y1, label="Earth density")
enpk.set_xscale('log')
enpk.set_yscale('log')
enpk.set_ylabel("Semi-Amplitude (m/s)")
enpk.set_ylim(8e-4,2e2)
enpk.set_xlabel("Period (Days)")
enpk.set_xlim(6,1e5)
enpk.set_title("Fitting: Period, K, Time of Conjunction ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
enpk.legend(loc=2)
filename = "enpk" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
#plt.show()
f5n_yes_per = [star["per"] for star in stars if ((star["5n_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_yes_a = [star["a"] for star in stars if ((star["5n_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_yes_k = [star["K"] for star in stars if ((star["5n_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_yes_mass = [star["PlanetMass"] for star in stars if ((star["5n_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_no_per = [star["per"] for star in stars if ((star["5n_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_no_a = [star["a"] for star in stars if ((star["5n_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_no_k= [star["K"] for star in stars if ((star["5n_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_no_mass = [star["PlanetMass"] for star in stars if ((star["5n_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_mar_per = [star["per"] for star in stars if ((star["5n_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_mar_a = [star["a"] for star in stars if ((star["5n_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_mar_k = [star["K"] for star in stars if ((star["5n_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5n_mar_mass = [star["PlanetMass"] for star in stars if ((star["5n_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, f5nam = plt.subplots()
f5nam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
f5nam.scatter(f5n_yes_a, f5n_yes_mass, label="Recovered", color="blue")
f5nam.scatter(f5n_mar_a, f5n_mar_mass, label="Marginal", color="red")
f5nam.scatter(f5n_no_a, f5n_no_mass, label="Excluded", color="black")
#f5nam.plot(xs, y1, label="Earth density")
f5nam.set_xscale('log')
f5nam.set_yscale('log')
f5nam.set_xlabel("Semi-Major Axis (au)")
f5nam.set_xlim(6e-2,3e1)
f5nam.set_ylabel("Mass (Earth-Masses)")
f5nam.set_ylim(8e-2,1e4)
f5nam.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
f5nam.legend(loc=2)
filename = "5nam" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, f5npk = plt.subplots()
f5npk.scatter(stars["per"], stars["K"], color="gray", s=1)
f5npk.scatter(f5n_yes_per, f5n_yes_k, label="Recovered", color="blue")
f5npk.scatter(f5n_mar_per, f5n_mar_k, label="Marginal", color="red")
f5npk.scatter(f5n_no_per, f5n_no_k, label="Excluded", color="black")
#f5npk.plot(xs, y1, label="Earth density")
f5npk.set_xscale('log')
f5npk.set_yscale('log')
f5npk.set_ylabel("Semi-Amplitude (m/s)")
f5npk.set_ylim(8e-4,2e2)
f5npk.set_xlabel("Period (Days)")
f5npk.set_xlim(6,1e5)
f5npk.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
f5npk.legend(loc=2)
filename = "5npk" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fn_yes_per = [star["per"] for star in stars if ((star["fn_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_yes_a = [star["a"] for star in stars if ((star["fn_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_yes_k = [star["K"] for star in stars if ((star["fn_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_yes_mass = [star["PlanetMass"] for star in stars if ((star["fn_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_no_per = [star["per"] for star in stars if ((star["fn_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_no_a = [star["a"] for star in stars if ((star["fn_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_no_k= [star["K"] for star in stars if ((star["fn_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_no_mass = [star["PlanetMass"] for star in stars if ((star["fn_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_no_mass = [star["PlanetMass"] for star in stars if ((star["fn_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_mar_per = [star["per"] for star in stars if ((star["fn_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_mar_a = [star["a"] for star in stars if ((star["fn_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_mar_k = [star["K"] for star in stars if ((star["fn_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fn_mar_mass = [star["PlanetMass"] for star in stars if ((star["fn_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, fnam = plt.subplots()
fnam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
fnam.scatter(fn_yes_a, fn_yes_mass, label="Recovered", color="blue")
fnam.scatter(fn_mar_a, fn_mar_mass, label="Marginal", color="red")
fnam.scatter(fn_no_a, fn_no_mass, label="Excluded", color="black")
#fnam.plot(xs, y1, label="Earth density")
fnam.set_xscale('log')
fnam.set_yscale('log')
fnam.set_xlabel("Semi-Major Axis (au)")
fnam.set_xlim(6e-2,3e1)
fnam.set_ylabel("Mass (Earth-Masses)")
fnam.set_ylim(8e-2,1e4)
fnam.set_title("Fitting: Period, K, Time of Conjunction, Ecc ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
fnam.legend(loc=2)
filename = "fnam" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, fnpk = plt.subplots()
fnpk.scatter(stars["per"], stars["K"], color="gray", s=1)
fnpk.scatter(fn_yes_per, fn_yes_k, label="Recovered", color="blue")
fnpk.scatter(fn_mar_per, fn_mar_k, label="Marginal", color="red")
fnpk.scatter(fn_no_per, fn_no_k, label="Excluded", color="black")
#fnpk.plot(xs, y1, label="Earth density")
fnpk.set_xscale('log')
fnpk.set_yscale('log')
fnpk.set_ylabel("Semi-Amplitude (m/s)")
fnpk.set_ylim(8e-4,2e2)
fnpk.set_xlabel("Period (Days)")
fnpk.set_xlim(6,1e5)
fnpk.set_title("Fitting: Period, K, Time of Conjunction, Ecc ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
fnpk.legend(loc=2)
filename = "fnpk" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
<file_sep>/error_plots.py
import numpy as np
import matplotlib.pyplot as plt
stars = np.genfromtxt("planetfits_matched.csv", delimiter=",", names=True, dtype=None)
#nplanets = [(1,3), (1,4), (4,4)]
#nplanets = [(1,6), (5,6), (5,5), (6,6)]
nplanets = [(1,4), (1,6), (5,5), (6,6)]
# iterate over: [5,e,f,n][p] fits, and 1-3, 4, 5, 6, 1-4, 5-6, 1-6 planet systems?
for minplanets, maxplanets in nplanets:
f5p_yes_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_yes_per = [star["per_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrm_yes_per = [star["per_err_minus_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrp_yes_per = [star["per_err_plus_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_a = [star["a"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_k = [star["K"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_yes_k = [star["K_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrm_yes_k = [star["K_err_minus_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrp_yes_k = [star["K_err_plus_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_mass = [star["PlanetMass"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_no_per = [star["per_mid_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrm_no_per = [star["per_err_minus_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrp_no_per = [star["per_err_plus_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_a = [star["a"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_k= [star["K"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_no_k = [star["K_mid_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrm_no_k = [star["K_err_minus_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrp_no_k = [star["K_err_plus_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_mass = [star["PlanetMass"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_mar_per = [star["per_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrm_mar_per = [star["per_err_minus_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrp_mar_per = [star["per_err_plus_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_a = [star["a"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_k = [star["K"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_mar_k = [star["K_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrm_mar_k = [star["K_err_minus_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5perrp_mar_k = [star["K_err_plus_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_mass = [star["PlanetMass"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, f5pam = plt.subplots()
f5pam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
f5pam.scatter(f5p_yes_a, f5p_yes_mass, label="Recovered", color="#0000FF")
f5pam.scatter(f5p_mar_a, f5p_mar_mass, label="Marginal", color="#FF0000")
f5pam.scatter(f5p_no_a, f5p_no_mass, label="Excluded", color="#000000")
f5pam.set_xscale('log')
f5pam.set_yscale('log')
f5pam.set_xlabel("Actual Semi-Major Axis (au)")
f5pam.set_xlim(6e-2,3e1)
f5pam.set_ylabel("Actual Mass (Earth-Masses)")
f5pam.set_ylim(8e-2,1e4)
f5pam.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
f5pam.legend(loc=2)
filename = "5pam_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, f5ppk = plt.subplots()
f5ppk.scatter(stars["per"], stars["K"], color="gray", s=1)
#f5ppk.scatter(f5p_yes_per, f5p_yes_k, label="Recovered", color="#AAAAFF")
f5ppk.errorbar(f5pfit_yes_per, f5pfit_yes_k, xerr=[f5perrm_yes_per, f5perrp_yes_per], yerr=[f5perrm_yes_k, f5perrp_yes_k], color="#0000FF", fmt='o')
#f5ppk.scatter(f5p_mar_per, f5p_mar_k, label="Marginal", color="#FFAAAA")
f5ppk.errorbar(f5pfit_mar_per, f5pfit_mar_k, xerr=[f5perrm_mar_per, f5perrp_mar_per], yerr=[f5perrm_mar_k, f5perrp_mar_k], color="#FF0000", fmt='o')
#f5ppk.scatter(f5p_no_per, f5p_no_k, label="Excluded", color="#AAAAAA")
f5ppk.errorbar(f5pfit_no_per, f5pfit_no_k, xerr=[f5perrm_no_per, f5perrp_no_per], yerr=[f5perrm_no_k, f5perrp_no_k], color="#000000", fmt='o')
f5ppk.set_xscale('log')
f5ppk.set_yscale('log')
f5ppk.set_ylabel("Recovered Semi-Amplitude (m/s)")
f5ppk.set_ylim(8e-4,2e2)
f5ppk.set_xlabel("Recovered Period (Days)")
f5ppk.set_xlim(6,1e5)
f5ppk.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
f5ppk.legend(loc=2)
filename = "5ppk_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
ep_yes_per = [star["per"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
epfit_yes_per = [star["per_mid_ep"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrm_yes_per = [star["per_err_minus_ep"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrp_yes_per = [star["per_err_plus_ep"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_yes_a = [star["a"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_yes_k = [star["K"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
epfit_yes_k = [star["K_mid_ep"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrm_yes_k = [star["K_err_minus_ep"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrp_yes_k = [star["K_err_plus_ep"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_yes_mass = [star["PlanetMass"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_no_per = [star["per"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
epfit_no_per = [star["per_mid_ep"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrm_no_per = [star["per_err_minus_ep"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrp_no_per = [star["per_err_plus_ep"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_no_a = [star["a"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_no_k= [star["K"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
epfit_no_k = [star["K_mid_ep"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrm_no_k = [star["K_err_minus_ep"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrp_no_k = [star["K_err_plus_ep"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_no_mass = [star["PlanetMass"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_mar_per = [star["per"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
epfit_mar_per = [star["per_mid_ep"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrm_mar_per = [star["per_err_minus_ep"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrp_mar_per = [star["per_err_plus_ep"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_mar_a = [star["a"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_mar_k = [star["K"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
epfit_mar_k = [star["K_mid_ep"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrm_mar_k = [star["K_err_minus_ep"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
eperrp_mar_k = [star["K_err_plus_ep"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_mar_mass = [star["PlanetMass"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, epam = plt.subplots()
epam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
epam.scatter(ep_yes_a, ep_yes_mass, label="Recovered", color="#0000FF")
epam.scatter(ep_mar_a, ep_mar_mass, label="Marginal", color="#FF0000")
epam.scatter(ep_no_a, ep_no_mass, label="Excluded", color="#000000")
epam.set_xscale('log')
epam.set_yscale('log')
epam.set_xlabel("Actual Semi-Major Axis (au)")
epam.set_xlim(6e-2,3e1)
epam.set_ylabel("Actual Mass (Earth-Masses)")
epam.set_ylim(8e-2,1e4)
epam.set_title("Fitting: Period, K, Time of Conjunction ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
epam.legend(loc=2)
filename = "epam_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, eppk = plt.subplots()
eppk.scatter(stars["per"], stars["K"], color="gray", s=1)
#eppk.scatter(ep_yes_per, ep_yes_k, label="Recovered", color="#AAAAFF")
eppk.errorbar(epfit_yes_per, epfit_yes_k, xerr=[eperrm_yes_per, eperrp_yes_per], yerr=[eperrm_yes_k, eperrp_yes_k], color="#0000FF", fmt='o')
#eppk.scatter(ep_mar_per, ep_mar_k, label="Marginal", color="#FFAAAA")
eppk.errorbar(epfit_mar_per, epfit_mar_k, xerr=[eperrm_mar_per, eperrp_mar_per], yerr=[eperrm_mar_k, eperrp_mar_k], color="#FF0000", fmt='o')
#eppk.scatter(ep_no_per, ep_no_k, label="Excluded", color="#AAAAAA")
eppk.errorbar(epfit_no_per, epfit_no_k, xerr=[eperrm_no_per, eperrp_no_per], yerr=[eperrm_no_k, eperrp_no_k], color="#000000", fmt='o')
eppk.set_xscale('log')
eppk.set_yscale('log')
eppk.set_ylabel("Recovered Semi-Amplitude (m/s)")
eppk.set_ylim(8e-4,2e2)
eppk.set_xlabel("Recovered Period (Days)")
eppk.set_xlim(6,1e5)
eppk.set_title("Fitting: Period, K, Time of Conjunction ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
eppk.legend(loc=2)
filename = "eppk_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fp_yes_per = [star["per"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fpfit_yes_per = [star["per_mid_fp"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrm_yes_per = [star["per_err_minus_fp"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrp_yes_per = [star["per_err_plus_fp"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_yes_a = [star["a"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_yes_k = [star["K"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fpfit_yes_k = [star["K_mid_fp"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrm_yes_k = [star["K_err_minus_fp"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrp_yes_k = [star["K_err_plus_fp"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_yes_mass = [star["PlanetMass"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_no_per = [star["per"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fpfit_no_per = [star["per_mid_fp"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrm_no_per = [star["per_err_minus_fp"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrp_no_per = [star["per_err_plus_fp"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_no_a = [star["a"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_no_k= [star["K"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fpfit_no_k = [star["K_mid_fp"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrm_no_k = [star["K_err_minus_fp"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrp_no_k = [star["K_err_plus_fp"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_no_mass = [star["PlanetMass"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_mar_per = [star["per"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fpfit_mar_per = [star["per_mid_fp"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrm_mar_per = [star["per_err_minus_fp"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrp_mar_per = [star["per_err_plus_fp"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_mar_a = [star["a"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_mar_k = [star["K"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fpfit_mar_k = [star["K_mid_fp"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrm_mar_k = [star["K_err_minus_fp"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fperrp_mar_k = [star["K_err_plus_fp"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_mar_mass = [star["PlanetMass"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, fpam = plt.subplots()
fpam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
fpam.scatter(fp_yes_a, fp_yes_mass, label="Recovered", color="#0000FF")
fpam.scatter(fp_mar_a, fp_mar_mass, label="Marginal", color="#FF0000")
fpam.scatter(fp_no_a, fp_no_mass, label="Excluded", color="#000000")
fpam.set_xscale('log')
fpam.set_yscale('log')
fpam.set_xlabel("Actual Semi-Major Axis (au)")
fpam.set_xlim(6e-2,3e1)
fpam.set_ylabel("Actual Mass (Earth-Masses)")
fpam.set_ylim(8e-2,1e4)
fpam.set_title("Fitting: Period, K, Time of Conjunction, Ecc ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
fpam.legend(loc=2)
filename = "fpam_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, fppk = plt.subplots()
fppk.scatter(stars["per"], stars["K"], color="gray", s=1)
#fppk.scatter(fp_yes_per, fp_yes_k, label="Recovered", color="#AAAAFF")
fppk.errorbar(fpfit_yes_per, fpfit_yes_k, xerr=[fperrm_yes_per, fperrp_yes_per], yerr=[fperrm_yes_k, fperrp_yes_k], color="#0000FF", fmt='o')
#fppk.scatter(fp_mar_per, fp_mar_k, label="Marginal", color="#FFAAAA")
fppk.errorbar(fpfit_mar_per, fpfit_mar_k, xerr=[fperrm_mar_per, fperrp_mar_per], yerr=[fperrm_mar_k, fperrp_mar_k], color="#FF0000", fmt='o')
#fppk.scatter(fp_no_per, fp_no_k, label="Excluded", color="#AAAAAA")
fppk.errorbar(fpfit_no_per, fpfit_no_k, xerr=[fperrm_no_per, fperrp_no_per], yerr=[fperrm_no_k, fperrp_no_k], color="#000000", fmt='o')
fppk.set_xscale('log')
fppk.set_yscale('log')
fppk.set_ylabel("Recovered Semi-Amplitude (m/s)")
fppk.set_ylim(8e-4,2e2)
fppk.set_xlabel("Recovered Period (Days)")
fppk.set_xlim(6,1e5)
fppk.set_title("Fitting: Period, K, Time of Conjunction, Ecc ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
fppk.legend(loc=2)
filename = "fppk_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
np_yes_per = [star["per"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
npfit_yes_per = [star["per_mid_np"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrm_yes_per = [star["per_err_minus_np"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrp_yes_per = [star["per_err_plus_np"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_yes_a = [star["a"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_yes_k = [star["K"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
npfit_yes_k = [star["K_mid_np"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrm_yes_k = [star["K_err_minus_np"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrp_yes_k = [star["K_err_plus_np"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_yes_mass = [star["PlanetMass"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_no_per = [star["per"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
npfit_no_per = [star["per_mid_np"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrm_no_per = [star["per_err_minus_np"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrp_no_per = [star["per_err_plus_np"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_no_a = [star["a"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_no_k= [star["K"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
npfit_no_k = [star["K_mid_np"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrm_no_k = [star["K_err_minus_np"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrp_no_k = [star["K_err_plus_np"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_no_mass = [star["PlanetMass"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_mar_per = [star["per"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
npfit_mar_per = [star["per_mid_np"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrm_mar_per = [star["per_err_minus_np"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrp_mar_per = [star["per_err_plus_np"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_mar_a = [star["a"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_mar_k = [star["K"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
npfit_mar_k = [star["K_mid_np"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrm_mar_k = [star["K_err_minus_np"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
nperrp_mar_k = [star["K_err_plus_np"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_mar_mass = [star["PlanetMass"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, npam = plt.subplots()
npam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
npam.scatter(np_yes_a, np_yes_mass, label="Recovered", color="#0000FF")
npam.scatter(np_mar_a, np_mar_mass, label="Marginal", color="#FF0000")
npam.scatter(np_no_a, np_no_mass, label="Excluded", color="#000000")
npam.set_xscale('log')
npam.set_yscale('log')
npam.set_xlabel("Actual Semi-Major Axis (au)")
npam.set_xlim(6e-2,3e1)
npam.set_ylabel("Actual Mass (Earth-Masses)")
npam.set_ylim(8e-2,1e4)
npam.set_title("Fitting: Period, K, Time of Conjunction; Ecc set to 0 ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
npam.legend(loc=2)
filename = "npam_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, nppk = plt.subplots()
nppk.scatter(stars["per"], stars["K"], color="gray", s=1)
#nppk.scatter(np_yes_per, np_yes_k, label="Recovered", color="#AAAAFF")
nppk.errorbar(npfit_yes_per, npfit_yes_k, xerr=[nperrm_yes_per, nperrp_yes_per], yerr=[nperrm_yes_k, nperrp_yes_k], color="#0000FF", fmt='o')
#nppk.scatter(np_mar_per, np_mar_k, label="Marginal", color="#FFAAAA")
nppk.errorbar(npfit_mar_per, npfit_mar_k, xerr=[nperrm_mar_per, nperrp_mar_per], yerr=[nperrm_mar_k, nperrp_mar_k], color="#FF0000", fmt='o')
#nppk.scatter(np_no_per, np_no_k, label="Excluded", color="#AAAAAA")
nppk.errorbar(npfit_no_per, npfit_no_k, xerr=[nperrm_no_per, nperrp_no_per], yerr=[nperrm_no_k, nperrp_no_k], color="#000000", fmt='o')
nppk.set_xscale('log')
nppk.set_yscale('log')
nppk.set_ylabel("Recovered Semi-Amplitude (m/s)")
nppk.set_ylim(8e-4,2e2)
nppk.set_xlabel("Recovered Period (Days)")
nppk.set_xlim(6,1e5)
nppk.set_title("Fitting: Period, K, Time of Conjunction; Ecc set to 0 ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
nppk.legend(loc=2)
filename = "nppk_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
<file_sep>/README.md
# isochoric-expander
Collection of data processing scripts for analizing radial velocity timeseries and finding/confirming/excluding exoplanets. Required libraries: numpy, matplotlib, datetime, pandas, os.
Probably not very coherent initially, but should ultimately cohere with dispatch_scheduler and reimagined-palm-tree. (as well as other codes in the Earthfinder project) This is likely to retain far too many 'hand' steps to be able to be plugged in easily, but should hopefully make replication easy (if desired). Also allow for similar analysis in future projects.
Provisional workflow:
* Generate radial velocities (typically via dispatch_scheduler, then reimagined-palm-tree, then by injecting planet signals with code outside of this context)
* Generate a (provisional) list of planets per star. Currently this is beyond the context of my code, though 'real' planets can be gotten from the above planet injection code. Plans are to have a first-pass fit via repeatedly running generalized Lomb-Scargle analysis.
* Place these scripts in the same folder as the guessed planet and measured RV data.
* run planets.py to generate input files for radvel. This step should probably also generate a shell script to make the next simpler/more consistent.
* Run radvel to find the best fits. Batch runs of radvel are not yet properly automated.
* Determine what planets were successfully recovered or not. This is currently a manual process (as far as looking at best fit, somewhat disfavored etc). Recovered parameters can be put into a single CSV via recovery_parameter_extraction.py. Finding false positives (for the 'real' planets anyway) should be automatable.
* Generate plots of the recovery results with recovery_plots.py, relative_error_plots.py, and error_plots.py.
planets.py generates input files for radvel, given an existing set of planetary systems (and RVs).
recovery_plots.py generates plots, given a table of planets (same as above) plus if the fits recovered/were marginal/excluded a planet. This determination currently must be done manually based on the results of radvel model comparison (favored model == recovered, nearly indistinguishable or somewhat disfavored == marginal, rest == excluded).
recovery_data_extraction.py takes the results of some of radvel's output files (specifically CSVs with the fit planetary parameters), and combines them into a single large CSV for all stars fit a given way. Currently grabs the most likely and ±1 σ values, then converts those into ±1 σ errors.
error_plots.py generate error vs actual value plots for K, period, and (if available) e. This is in contrast to the recovery_plots.py which does period-K and a-m.
plot_false_positives_1D.py plots "1D" errors (actual value vs relative error from fit) for eccentricity, period, and semi-amplitude. plot_false_positives_2D.py plots "2D" errors (period vs semi-amplitude for real values, and with 1-σ error bars for fit values). Both break down the the points in terms of favored/marginal/excluded/false positive. (False positives being those where at least one of K or period is both >3σ and >5% away from the true value)
Currently 9 fits are being considered for testing properties: null, and [5,e,f,n][n,p]. null has all parameters fixed as a baseline. The rest fit semi-amplitude, period, and time of conjunction for all planets. e- fixes eccentricity at the 'known' value, while 5- and f- allow eccentricity to vary (capped at 0.5 and 0.99, respectively). n- fixes eccentricity at 0 (circular orbits). -p has all planets in the system, while -n drops the long period (currently >3654.0 days) ones, and fits an additional quadratic function for radial velocity. We are drifting towards 5p as the best fit given survey assumptions, and tests on recovery results.
Addendum: We are shifting towards planets65.py, as that generates eccentricities better (max of 0.65, moves large inputs below the limit to prevent unpredictable radvel behavior).
truncate.py Creates a bunch of chopped up surveys (5/10/20 year at 25/50/100% telescope time) given 20 year 100% time surveys.
<file_sep>/relative_error_plots5p.py
'''Plots of relative errors for the 5p fits. Both general and zoomed in on the most important features. Ideally also a 2-parameter plot for a vs m.'''
import numpy as np
import matplotlib.pyplot as plt
stars = np.genfromtxt("planetfits_matched.csv", delimiter=",", names=True, dtype=None)
#nplanets = [(1,3), (1,4), (1,6), (4,4), (5,5), (6,6)]
nplanets = [(1,4)]
for minplanets, maxplanets in nplanets:
f5p_yes_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_yes_per = [star["per_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_yes_per = [star["per_min_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_yes_per = [star["per_max_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_k = [star["K"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_yes_k = [star["K_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_yes_k = [star["K_min_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_yes_k = [star["K_max_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_e = [star["e"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_yes_e = [star["e_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_yes_e = [star["e_min_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_yes_e = [star["e_max_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_m = [star["PlanetMass"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pstar_yes_m = [(star["StarMass"]+star["PlanetMass"]/332946.07832806994) for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_no_per = [star["per_mid_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_no_per = [star["per_min_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_no_per = [star["per_max_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_k= [star["K"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_no_k = [star["K_mid_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_no_k = [star["K_min_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_no_k = [star["K_max_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_e= [star["e"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_no_e = [star["e_mid_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_no_e = [star["e_min_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_no_e = [star["e_max_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_m = [star["PlanetMass"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pstar_no_m = [(star["StarMass"]+star["PlanetMass"]/332946.07832806994) for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_mar_per = [star["per_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_mar_per = [star["per_min_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_mar_per = [star["per_max_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_k = [star["K"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_mar_k = [star["K_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_mar_k = [star["K_min_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_mar_k = [star["K_max_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_e = [star["e"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_mar_e = [star["e_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_mar_e = [star["e_min_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_mar_e = [star["e_max_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_m = [star["PlanetMass"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pstar_mar_m = [(star["StarMass"]+star["PlanetMass"]/332946.07832806994) for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pΔ_yes_per = np.zeros(len(f5pfit_yes_per))
f5perrp_yes_per = np.zeros(len(f5pfit_yes_per))
f5perrm_yes_per = np.zeros(len(f5pfit_yes_per))
f5pΔ_yes_k = np.zeros(len(f5pfit_yes_k))
f5perrp_yes_k = np.zeros(len(f5pfit_yes_k))
f5perrm_yes_k = np.zeros(len(f5pfit_yes_k))
f5pΔ_yes_e = np.zeros(len(f5pfit_yes_e))
f5perrp_yes_e = np.zeros(len(f5pfit_yes_e))
f5perrm_yes_e = np.zeros(len(f5pfit_yes_e))
f5pΔa_yes_e = np.zeros(len(f5pfit_yes_e))
f5perrap_yes_e = np.zeros(len(f5pfit_yes_e))
f5perram_yes_e = np.zeros(len(f5pfit_yes_e))
for j in np.arange(0, len(f5pfit_yes_per)):
f5pΔ_yes_per[j] = (f5pfit_yes_per[j] - f5p_yes_per[j]) / (f5p_yes_per[j])
f5perrp_yes_per[j] = (f5pmax_yes_per[j] - f5pfit_yes_per[j]) / (f5p_yes_per[j])
f5perrm_yes_per[j] = (f5pfit_yes_per[j] - f5pmin_yes_per[j]) / (f5p_yes_per[j])
f5pΔ_yes_k[j] = (f5pfit_yes_k[j] - f5p_yes_k[j]) / (f5p_yes_k[j])
f5perrp_yes_k[j] = (f5pmax_yes_k[j] - f5pfit_yes_k[j]) / (f5p_yes_k[j])
f5perrm_yes_k[j] = (f5pfit_yes_k[j] - f5pmin_yes_k[j]) / (f5p_yes_k[j])
f5pΔ_yes_e[j] = (f5pfit_yes_e[j] - f5p_yes_e[j]) / (f5p_yes_e[j])
f5perrp_yes_e[j] = (f5pmax_yes_e[j] - f5pfit_yes_e[j]) / (f5p_yes_e[j])
f5perrm_yes_e[j] = (f5pfit_yes_e[j] - f5pmin_yes_e[j]) / (f5p_yes_e[j])
f5pΔa_yes_e[j] = (f5pfit_yes_e[j] - f5p_yes_e[j])
f5perrap_yes_e[j] = (f5pmax_yes_e[j] - f5pfit_yes_e[j])
f5perram_yes_e[j] = (f5pfit_yes_e[j] - f5pmin_yes_e[j])
f5pΔ_no_per = np.zeros(len(f5pfit_no_per))
f5perrp_no_per = np.zeros(len(f5pfit_no_per))
f5perrm_no_per = np.zeros(len(f5pfit_no_per))
f5pΔ_no_k = np.zeros(len(f5pfit_no_k))
f5perrp_no_k = np.zeros(len(f5pfit_no_k))
f5perrm_no_k = np.zeros(len(f5pfit_no_k))
f5pΔ_no_e = np.zeros(len(f5pfit_no_e))
f5perrp_no_e = np.zeros(len(f5pfit_no_e))
f5perrm_no_e = np.zeros(len(f5pfit_no_e))
f5pΔa_no_e = np.zeros(len(f5pfit_no_e))
f5perrap_no_e = np.zeros(len(f5pfit_no_e))
f5perram_no_e = np.zeros(len(f5pfit_no_e))
for j in np.arange(0, len(f5pfit_no_per)):
f5pΔ_no_per[j] = (f5pfit_no_per[j] - f5p_no_per[j]) / (f5p_no_per[j])
f5perrp_no_per[j] = (f5pmax_no_per[j] - f5pfit_no_per[j]) / (f5p_no_per[j])
f5perrm_no_per[j] = (f5pfit_no_per[j] - f5pmin_no_per[j]) / (f5p_no_per[j])
f5pΔ_no_k[j] = (f5pfit_no_k[j] - f5p_no_k[j]) / (f5p_no_k[j])
f5perrp_no_k[j] = (f5pmax_no_k[j] - f5pfit_no_k[j]) / (f5p_no_k[j])
f5perrm_no_k[j] = (f5pfit_no_k[j] - f5pmin_no_k[j]) / (f5p_no_k[j])
f5pΔ_no_e[j] = (f5pfit_no_e[j] - f5p_no_e[j]) / (f5p_no_e[j])
f5perrp_no_e[j] = (f5pmax_no_e[j] - f5pfit_no_e[j]) / (f5p_no_e[j])
f5perrm_no_e[j] = (f5pfit_no_e[j] - f5pmin_no_e[j]) / (f5p_no_e[j])
f5pΔa_no_e[j] = (f5pfit_no_e[j] - f5p_no_e[j])
f5perrap_no_e[j] = (f5pmax_no_e[j] - f5pfit_no_e[j])
f5perram_no_e[j] = (f5pfit_no_e[j] - f5pmin_no_e[j])
f5pΔ_mar_per = np.zeros(len(f5pfit_mar_per))
f5perrp_mar_per = np.zeros(len(f5pfit_mar_per))
f5perrm_mar_per = np.zeros(len(f5pfit_mar_per))
f5pΔ_mar_k = np.zeros(len(f5pfit_mar_k))
f5perrp_mar_k = np.zeros(len(f5pfit_mar_k))
f5perrm_mar_k = np.zeros(len(f5pfit_mar_k))
f5pΔ_mar_e = np.zeros(len(f5pfit_mar_e))
f5perrp_mar_e = np.zeros(len(f5pfit_mar_e))
f5perrm_mar_e = np.zeros(len(f5pfit_mar_e))
f5pΔa_mar_e = np.zeros(len(f5pfit_mar_e))
f5perrap_mar_e = np.zeros(len(f5pfit_mar_e))
f5perram_mar_e = np.zeros(len(f5pfit_mar_e))
for j in np.arange(0, len(f5pfit_mar_per)):
f5pΔ_mar_per[j] = (f5pfit_mar_per[j] - f5p_mar_per[j]) / (f5p_mar_per[j])
f5perrp_mar_per[j] = (f5pmax_mar_per[j] - f5pfit_mar_per[j]) / (f5p_mar_per[j])
f5perrm_mar_per[j] = (f5pfit_mar_per[j] - f5pmin_mar_per[j]) / (f5p_mar_per[j])
f5pΔ_mar_k[j] = (f5pfit_mar_k[j] - f5p_mar_k[j]) / (f5p_mar_k[j])
f5perrp_mar_k[j] = (f5pmax_mar_k[j] - f5pfit_mar_k[j]) / (f5p_mar_k[j])
f5perrm_mar_k[j] = (f5pfit_mar_k[j] - f5pmin_mar_k[j]) / (f5p_mar_k[j])
f5pΔ_mar_e[j] = (f5pfit_mar_e[j] - f5p_mar_e[j]) / (f5p_mar_e[j])
f5perrp_mar_e[j] = (f5pmax_mar_e[j] - f5pfit_mar_e[j]) / (f5p_mar_e[j])
f5perrm_mar_e[j] = (f5pfit_mar_e[j] - f5pmin_mar_e[j]) / (f5p_mar_e[j])
f5pΔa_mar_e[j] = (f5pfit_mar_e[j] - f5p_mar_e[j])
f5perrap_mar_e[j] = (f5pmax_mar_e[j] - f5pfit_mar_e[j])
f5perram_mar_e[j] = (f5pfit_mar_e[j] - f5pmin_mar_e[j])
fig, f5pp = plt.subplots()
f5pp.errorbar(f5p_yes_per, f5pΔ_yes_per, yerr=[f5perrm_yes_per, f5perrp_yes_per], color="#0000FF", fmt='o')
f5pp.errorbar(f5p_mar_per, f5pΔ_mar_per, yerr=[f5perrm_mar_per, f5perrp_mar_per], color="#FF0000", fmt='o')
f5pp.errorbar(f5p_no_per, f5pΔ_no_per, yerr=[f5perrm_no_per, f5perrp_no_per], color="#000000", fmt='o')
f5pp.set_xscale('log')
f5pp.set_ylabel("Relative Error")
f5pp.set_xlabel("Period (Days)")
f5pp.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
#f5ppk.legend(loc=2)
filename = "5pp_error_" + str(minplanets) + str(maxplanets) + ".png"
#plt.savefig(filename)
fig, f5pk = plt.subplots()
f5pk.errorbar(f5p_yes_k, f5pΔ_yes_k, yerr=[f5perrm_yes_k, f5perrp_yes_k], color="#0000FF", fmt='o')
f5pk.errorbar(f5p_mar_k, f5pΔ_mar_k, yerr=[f5perrm_mar_k, f5perrp_mar_k], color="#FF0000", fmt='o')
f5pk.errorbar(f5p_no_k, f5pΔ_no_k, yerr=[f5perrm_no_k, f5perrp_no_k], color="#000000", fmt='o')
f5pk.set_xscale('log')
f5pk.set_ylabel("Relative Error")
f5pk.set_xlabel("Semi-amplitude (m/s)")
f5pk.set_ylim(-1.0,1.5)
#f5pk.set_xlim(6e-2,1e2)
f5pk.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
#f5pkk.legend(loc=2)
filename = "5pk_error_zoom_" + str(minplanets) + str(maxplanets) + ".png"
#plt.savefig(filename)
fig, f5pe = plt.subplots()
f5pe.errorbar(f5p_yes_e, f5pΔ_yes_e, yerr=[f5perrm_yes_e, f5perrp_yes_e], color="#0000FF", fmt='o')
f5pe.errorbar(f5p_mar_e, f5pΔ_mar_e, yerr=[f5perrm_mar_e, f5perrp_mar_e], color="#FF0000", fmt='o')
f5pe.errorbar(f5p_no_e, f5pΔ_no_e, yerr=[f5perrm_no_e, f5perrp_no_e], color="#000000", fmt='o')
f5pe.set_xscale('log')
f5pe.set_ylabel("Relative Error")
f5pe.set_xlabel("Eccentricity")
f5pe.set_xlim(4e-2,0.6)
f5pe.set_ylim(-1.2,2)
f5pe.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
#f5pek.legend(loc=2)
filename = "5pe_error_zoom" + str(minplanets) + str(maxplanets) + ".png"
#plt.savefig(filename)
fig, f5pea = plt.subplots()
f5pea.errorbar(f5p_yes_e, f5pΔa_yes_e, yerr=[f5perram_yes_e, f5perrap_yes_e], color="#0000FF", fmt='o')
f5pea.errorbar(f5p_mar_e, f5pΔa_mar_e, yerr=[f5perram_mar_e, f5perrap_mar_e], color="#FF0000", fmt='o')
f5pea.errorbar(f5p_no_e, f5pΔa_no_e, yerr=[f5perram_no_e, f5perrap_no_e], color="#000000", fmt='o')
f5pea.set_xscale('log')
f5pea.set_ylabel("Error")
f5pea.set_xlabel("Eccentricity")
#f5pea.set_xlim(4e-2,0.6)
#f5pea.set_ylim(-0.5,0.5)
f5pea.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
#f5peak.legend(loc=2)
filename = "5pe_error_abs_log" + str(minplanets) + str(maxplanets) + ".png"
#plt.savefig(filename)
'''
# Getting mass involves consderably more potential error
# msini = \frac{K}{K_0} \sqrt{1-e^2} (m+M)^{2/3} P^{1/3}
# Since period and eccentricity are also being fit, we would need to do an error propogation calculation to get proper error pars on mass. We are ignoring that at this time.
K0 = 28.4329/317.8284 # Magic number for getting earth masses. (without the 2nd term gives jupiter masses)
f5pfit_yes_m = np.zeros(len(f5pfit_yes_k))
f5pfit_yes_dm = np.zeros(len(f5pfit_yes_k))
for j in np.arange(0, len(f5pfit_yes_per)):
f5pfit_yes_m[j] = f5pfit_yes_k[j] / K0 * np.sqrt(1-f5p_yes_e[j]**2) * f5pstar_yes_m[j]**(2/3) * f5pfit_yes_per[j]**(1/3)
f5pfit_yes_dm[j] = (f5pfit_yes_m[j] - f5p_yes_m[j]) / f5p_yes_m[j]
f5pfit_no_m = np.zeros(len(f5pfit_no_k))
f5pfit_no_dm = np.zeros(len(f5pfit_no_k))
for j in np.arange(0, len(f5pfit_no_per)):
f5pfit_no_m[j] = f5pfit_no_k[j] / K0 * np.sqrt(1-f5p_no_e[j]**2) * f5pstar_no_m[j]**(2/3) * f5pfit_no_per[j]**(1/3)
f5pfit_no_dm[j] = (f5pfit_no_m[j] - f5p_no_m[j]) / f5p_no_m[j]
f5pfit_mar_m = np.zeros(len(f5pfit_mar_k))
f5pfit_mar_dm = np.zeros(len(f5pfit_mar_k))
for j in np.arange(0, len(f5pfit_mar_per)):
f5pfit_mar_m[j] = f5pfit_mar_k[j] / K0 * np.sqrt(1-f5p_mar_e[j]**2) * f5pstar_mar_m[j]**(2/3) * f5pfit_mar_per[j]**(1/3)
f5pfit_mar_dm[j] = (f5pfit_mar_m[j] - f5p_mar_m[j]) / f5p_mar_m[j]
fig, f5pm = plt.subplots()
f5pm.scatter(f5p_yes_m, f5pfit_yes_dm, color="#0000FF")
f5pm.scatter(f5p_mar_m, f5pfit_mar_dm, color="#FF0000")
f5pm.scatter(f5p_no_m, f5pfit_no_dm, color="#000000")
f5pm.set_xscale('log')
f5pm.set_ylabel("Relative Error")
f5pm.set_xlabel("Mass (Earths)")
f5pm.set_ylim(0,20)
f5pm.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
#f5pmk.legend(loc=2)
filename = "5pm_error" + str(minplanets) + str(maxplanets) + ".png"
#plt.savefig(filename)'''
plt.show()
<file_sep>/planetsnp.py
'''Attempts to generate configuration files for a given list of stars and their associated planets.'''
import numpy as np
import datetime
#initializing
stars = np.genfromtxt("planets.csv", delimiter=',', names=True, dtype=("U23", "U9", int, float, float, float, float, float, float, float, float, float, float))
star_name = stars[0]["HIPnumber"]
for i in np.arange(1,len(stars)):
if (star_name != stars[i]["HIPnumber"]):
planets = stars[i-1]["PlanetNumber"]
#start a new file
now = str((datetime.datetime.now()).isoformat())
star_config = open(star_name+"np.py", 'w')
star_config.write("# Test Keplerian fit configuration file for "+star_name+"\n")
star_config.write("# Features: All planets fit via period, tc, k; tc used (e fixed to 0)\n")
star_config.write("# Generated on "+now+"\n\n")
star_config.write("import os\n")
star_config.write("import pandas as pd\n")
star_config.write("import numpy as np\n")
star_config.write("import radvel\n")
star_config.write("starname = '"+star_name+"'\n")
star_config.write("nplanets = "+str(planets)+"\n")
star_config.write("instnames = [\'NEID\']\n")
star_config.write("ntels = len(instnames)\n")
star_config.write("fitting_basis = \'per tc e w k\'\n")
star_config.write("bjd0 = 2458850.\n")
star_config.write("planet_letters = {1: 'b'")
if (planets >= 2):
star_config.write(", 2: 'c'")
if (planets >= 3):
star_config.write(", 3: 'd'")
if (planets >= 4):
star_config.write(", 4: 'e'")
if (planets >= 5):
star_config.write(", 5: 'f'")
if (planets >= 6):
star_config.write(", 6: 'g'")
if (planets >= 7):
star_config.write(", 7: 'h'")
if (planets >= 8):
star_config.write(", 8: 'i'")
if (planets >= 9):
star_config.write(", 9: 'j'")
if (planets >= 10):
star_config.write(", 10: 'k'")
star_config.write("}\n\n")
star_config.write("anybasis_params = radvel.Parameters(nplanets,basis='per tp e w k')\n\n")
star_config.write("anybasis_params['dvdt'] = radvel.Parameter(value=0.0)\n")
star_config.write("anybasis_params['curv'] = radvel.Parameter(value=0.0)\n")
star_config.write("anybasis_params['gamma_NEID'] = radvel.Parameter(value=0.0)\n")
star_config.write("anybasis_params['jit_NEID'] = radvel.Parameter(value=0.0)\n")
#loop to add planets (before)
for x in np.arange(1, planets+1):
star_config.write("anybasis_params['per"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value="+str(stars[i-x]["per"])+")\n")
star_config.write("anybasis_params['tp"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value="+str(stars[i-x]["t_p"])+")\n")
star_config.write("anybasis_params['e"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value=0.0)\n")
star_config.write("anybasis_params['w"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value="+str(stars[i-x]["omega"])+")\n")
star_config.write("anybasis_params['k"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value="+str(stars[i-x]["K"])+")\n")
star_config.write("\nparams = anybasis_params.basis.to_any_basis(anybasis_params,fitting_basis)\n\n")
#loop to add planets (after)
for x in np.arange(1, planets+1):
star_config.write("params['per"+str(stars["PlanetNumber"][i-x])+"'].vary = True\n")
star_config.write("params['tc"+str(stars["PlanetNumber"][i-x])+"'].vary = True\n")
star_config.write("params['e"+str(stars["PlanetNumber"][i-x])+"'].vary = False\n")
star_config.write("params['w"+str(stars["PlanetNumber"][i-x])+"'].vary = False\n")
star_config.write("params['k"+str(stars["PlanetNumber"][i-x])+"'].vary = True\n")
#write end of file
star_config.write("params['dvdt'].vary = False\n")
star_config.write("params['curv'].vary = False\n")
star_config.write("params['gamma_NEID'].vary = False\n")
star_config.write("params['jit_NEID'].vary = False\n\n")
star_config.write("path = '"+str(stars['RVfilename'][i-1])+"'\n")
star_config.write("data = pd.read_csv(path)\n")
star_config.write("data['time'] = (data.obs_start+data.obs_end)/2\n")
star_config.write("data['mnvel'] = data.mnvel\n")
star_config.write("data['errvel'] = data.rvprec\n")
star_config.write("data['tel'] = 'NEID'\n\n")
star_config.write("priors = [\n")
star_config.write(" radvel.prior.EccentricityPrior( nplanets ),\n")
star_config.write(" radvel.prior.PositiveKPrior( nplanets ),\n")
star_config.write(" radvel.prior.HardBounds('jit_NEID', 0.0, 15.0)\n")
star_config.write("]\n\n")
star_config.write("time_base = np.mean([np.min(data.time), np.max(data.time)])\n")
star_config.close()
star_name = stars[i]["HIPnumber"]
star_name = stars[i]["HIPnumber"]
planets = stars[i]["PlanetNumber"]
#start a new file
now = str((datetime.datetime.now()).isoformat())
star_name = stars[i]["HIPnumber"]
star_config = open(star_name+"np.py", 'w')
star_config.write("# Test Keplerian fit configuration file for "+star_name+"\n")
star_config.write("# Features: All planets fit via period, tc, k; tc used (e fixed to 0)\n")
star_config.write("# Generated on "+now+"\n\n")
star_config.write("import os\n")
star_config.write("import pandas as pd\n")
star_config.write("import numpy as np\n")
star_config.write("import radvel\n")
star_config.write("starname = '"+star_name+"'\n")
star_config.write("nplanets = "+str(planets)+"\n")
star_config.write("instnames = [\'NEID\']\n")
star_config.write("ntels = len(instnames)\n")
star_config.write("fitting_basis = \'per tc e w k\'\n")
star_config.write("bjd0 = 2458850.\n")
star_config.write("planet_letters = {1: 'b'")
if (planets >= 2):
star_config.write(", 2: 'c'")
if (planets >= 3):
star_config.write(", 3: 'd'")
if (planets >= 4):
star_config.write(", 4: 'e'")
if (planets >= 5):
star_config.write(", 5: 'f'")
if (planets >= 6):
star_config.write(", 6: 'g'")
if (planets >= 7):
star_config.write(", 7: 'h'")
if (planets >= 8):
star_config.write(", 8: 'i'")
if (planets >= 9):
star_config.write(", 9: 'j'")
if (planets >= 10):
star_config.write(", 10: 'k'")
star_config.write("}\n\n")
star_config.write("anybasis_params = radvel.Parameters(nplanets,basis='per tp e w k')\n\n")
star_config.write("anybasis_params['dvdt'] = radvel.Parameter(value=0.0)\n")
star_config.write("anybasis_params['curv'] = radvel.Parameter(value=0.0)\n")
star_config.write("anybasis_params['gamma_NEID'] = radvel.Parameter(value=0.0)\n")
star_config.write("anybasis_params['jit_NEID'] = radvel.Parameter(value=0.0)\n")
#loop to add planets (before)
for x in np.arange(0, planets):
star_config.write("anybasis_params['per"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value="+str(stars[i-x]["per"])+")\n")
star_config.write("anybasis_params['tp"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value="+str(stars[i-x]["t_p"])+")\n")
star_config.write("anybasis_params['e"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value=0.0)\n")
star_config.write("anybasis_params['w"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value="+str(stars[i-x]["omega"])+")\n")
star_config.write("anybasis_params['k"+str(stars["PlanetNumber"][i-x])+"'] = radvel.Parameter(value="+str(stars[i-x]["K"])+")\n")
star_config.write("params = anybasis_params.basis.to_any_basis(anybasis_params,fitting_basis)\n\n")
#loop to add planets (after)
for x in np.arange(0, planets):
star_config.write("params['per"+str(stars["PlanetNumber"][i-x])+"'].vary = True\n")
star_config.write("params['tc"+str(stars["PlanetNumber"][i-x])+"'].vary = True\n")
star_config.write("params['e"+str(stars["PlanetNumber"][i-x])+"'].vary = False\n")
star_config.write("params['w"+str(stars["PlanetNumber"][i-x])+"'].vary = False\n")
star_config.write("params['k"+str(stars["PlanetNumber"][i-x])+"'].vary = True\n")
#write end of file
star_config.write("params['dvdt'].vary = False\n")
star_config.write("params['curv'].vary = False\n")
star_config.write("params['gamma_NEID'].vary = False\n")
star_config.write("params['jit_NEID'].vary = False\n\n")
star_config.write("path = '"+str(stars['RVfilename'][i])+"'\n")
star_config.write("data = pd.read_csv(path)\n")
star_config.write("data['time'] = data.obs_start\n")
star_config.write("data['mnvel'] = data.mnvel\n")
star_config.write("data['errvel'] = data.rvprec\n")
star_config.write("data['tel'] = 'NEID'\n\n")
star_config.write("priors = [\n")
star_config.write(" radvel.prior.EccentricityPrior( nplanets ),\n")
star_config.write(" radvel.prior.PositiveKPrior( nplanets ),\n")
star_config.write(" radvel.prior.HardBounds('jit_NEID', 0.0, 15.0)\n")
star_config.write("]\n\n")
star_config.write("time_base = np.mean([np.min(data.time), np.max(data.time)])\n")
star_config.close()
<file_sep>/error_plots2.py
import numpy as np
import matplotlib.pyplot as plt
stars = np.genfromtxt("planetfits_matched.csv", delimiter=",", names=True, dtype=None)
#nplanets = [(1,3), (1,4), (1,6), (4,4), (5,5), (6,6)]
nplanets = [(1,4)]
for minplanets, maxplanets in nplanets:
f5p_yes_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_yes_per = [star["per_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_yes_per = [star["per_min_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_yes_per = [star["per_max_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_k = [star["K"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_yes_k = [star["K_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_yes_k = [star["K_min_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_yes_k = [star["K_max_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_e = [star["e"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_yes_e = [star["e_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_yes_e = [star["e_min_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_yes_e = [star["e_max_5p"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_no_per = [star["per_mid_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_no_per = [star["per_min_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_no_per = [star["per_max_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_k= [star["K"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_no_k = [star["K_mid_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_no_k = [star["K_min_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_no_k = [star["K_max_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_e= [star["e"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_no_e = [star["e_mid_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_no_e = [star["e_min_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_no_e = [star["e_max_5p"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_mar_per = [star["per_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_mar_per = [star["per_min_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_mar_per = [star["per_max_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_k = [star["K"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_mar_k = [star["K_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_mar_k = [star["K_min_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_mar_k = [star["K_max_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_e = [star["e"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pfit_mar_e = [star["e_mid_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmin_mar_e = [star["e_min_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pmax_mar_e = [star["e_max_5p"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5pΔ_yes_per = np.zeros(len(f5pfit_yes_per))
f5perrp_yes_per = np.zeros(len(f5pfit_yes_per))
f5perrm_yes_per = np.zeros(len(f5pfit_yes_per))
f5pΔ_yes_k = np.zeros(len(f5pfit_yes_k))
f5perrp_yes_k = np.zeros(len(f5pfit_yes_k))
f5perrm_yes_k = np.zeros(len(f5pfit_yes_k))
f5pΔ_yes_e = np.zeros(len(f5pfit_yes_e))
f5perrp_yes_e = np.zeros(len(f5pfit_yes_e))
f5perrm_yes_e = np.zeros(len(f5pfit_yes_e))
for j in np.arange(0, len(f5pfit_yes_per)):
f5pΔ_yes_per[j] = (f5pfit_yes_per[j] - f5p_yes_per[j]) / (f5p_yes_per[j])
f5perrp_yes_per[j] = (f5pmax_yes_per[j] - f5pfit_yes_per[j]) / (f5p_yes_per[j])
f5perrm_yes_per[j] = (f5pfit_yes_per[j] - f5pmin_yes_per[j]) / (f5p_yes_per[j])
f5pΔ_yes_k[j] = (f5pfit_yes_k[j] - f5p_yes_k[j]) / (f5p_yes_k[j])
f5perrp_yes_k[j] = (f5pmax_yes_k[j] - f5pfit_yes_k[j]) / (f5p_yes_k[j])
f5perrm_yes_k[j] = (f5pfit_yes_k[j] - f5pmin_yes_k[j]) / (f5p_yes_k[j])
f5pΔ_yes_e[j] = (f5pfit_yes_e[j] - f5p_yes_e[j]) / (f5p_yes_e[j])
f5perrp_yes_e[j] = (f5pmax_yes_e[j] - f5pfit_yes_e[j]) / (f5p_yes_e[j])
f5perrm_yes_e[j] = (f5pfit_yes_e[j] - f5pmin_yes_e[j]) / (f5p_yes_e[j])
f5pΔ_no_per = np.zeros(len(f5pfit_no_per))
f5perrp_no_per = np.zeros(len(f5pfit_no_per))
f5perrm_no_per = np.zeros(len(f5pfit_no_per))
f5pΔ_no_k = np.zeros(len(f5pfit_no_k))
f5perrp_no_k = np.zeros(len(f5pfit_no_k))
f5perrm_no_k = np.zeros(len(f5pfit_no_k))
f5pΔ_no_e = np.zeros(len(f5pfit_no_e))
f5perrp_no_e = np.zeros(len(f5pfit_no_e))
f5perrm_no_e = np.zeros(len(f5pfit_no_e))
for j in np.arange(0, len(f5pfit_no_per)):
f5pΔ_no_per[j] = (f5pfit_no_per[j] - f5p_no_per[j]) / (f5p_no_per[j])
f5perrp_no_per[j] = (f5pmax_no_per[j] - f5pfit_no_per[j]) / (f5p_no_per[j])
f5perrm_no_per[j] = (f5pfit_no_per[j] - f5pmin_no_per[j]) / (f5p_no_per[j])
f5pΔ_no_k[j] = (f5pfit_no_k[j] - f5p_no_k[j]) / (f5p_no_k[j])
f5perrp_no_k[j] = (f5pmax_no_k[j] - f5pfit_no_k[j]) / (f5p_no_k[j])
f5perrm_no_k[j] = (f5pfit_no_k[j] - f5pmin_no_k[j]) / (f5p_no_k[j])
f5pΔ_no_e[j] = (f5pfit_no_e[j] - f5p_no_e[j]) / (f5p_no_e[j])
f5perrp_no_e[j] = (f5pmax_no_e[j] - f5pfit_no_e[j]) / (f5p_no_e[j])
f5perrm_no_e[j] = (f5pfit_no_e[j] - f5pmin_no_e[j]) / (f5p_no_e[j])
f5pΔ_mar_per = np.zeros(len(f5pfit_mar_per))
f5perrp_mar_per = np.zeros(len(f5pfit_mar_per))
f5perrm_mar_per = np.zeros(len(f5pfit_mar_per))
f5pΔ_mar_k = np.zeros(len(f5pfit_mar_k))
f5perrp_mar_k = np.zeros(len(f5pfit_mar_k))
f5perrm_mar_k = np.zeros(len(f5pfit_mar_k))
f5pΔ_mar_e = np.zeros(len(f5pfit_mar_e))
f5perrp_mar_e = np.zeros(len(f5pfit_mar_e))
f5perrm_mar_e = np.zeros(len(f5pfit_mar_e))
for j in np.arange(0, len(f5pfit_mar_per)):
f5pΔ_mar_per[j] = (f5pfit_mar_per[j] - f5p_mar_per[j]) / (f5p_mar_per[j])
f5perrp_mar_per[j] = (f5pmax_mar_per[j] - f5pfit_mar_per[j]) / (f5p_mar_per[j])
f5perrm_mar_per[j] = (f5pfit_mar_per[j] - f5pmin_mar_per[j]) / (f5p_mar_per[j])
f5pΔ_mar_k[j] = (f5pfit_mar_k[j] - f5p_mar_k[j]) / (f5p_mar_k[j])
f5perrp_mar_k[j] = (f5pmax_mar_k[j] - f5pfit_mar_k[j]) / (f5p_mar_k[j])
f5perrm_mar_k[j] = (f5pfit_mar_k[j] - f5pmin_mar_k[j]) / (f5p_mar_k[j])
f5pΔ_mar_e[j] = (f5pfit_mar_e[j] - f5p_mar_e[j]) / (f5p_mar_e[j])
f5perrp_mar_e[j] = (f5pmax_mar_e[j] - f5pfit_mar_e[j]) / (f5p_mar_e[j])
f5perrm_mar_e[j] = (f5pfit_mar_e[j] - f5pmin_mar_e[j]) / (f5p_mar_e[j])
fig, f5pp = plt.subplots()
f5pp.errorbar(f5p_yes_per, f5pΔ_yes_per, yerr=[f5perrm_yes_per, f5perrp_yes_per], color="#0000FF", fmt='o')
f5pp.errorbar(f5p_mar_per, f5pΔ_mar_per, yerr=[f5perrm_mar_per, f5perrp_mar_per], color="#FF0000", fmt='o')
f5pp.errorbar(f5p_no_per, f5pΔ_no_per, yerr=[f5perrm_no_per, f5perrp_no_per], color="#000000", fmt='o')
f5pp.set_xscale('log')
f5pp.set_ylabel("Relative Error")
f5pp.set_xlabel("Period (Days)")
f5pp.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
#f5ppk.legend(loc=2)
filename = "5pp_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, f5pk = plt.subplots()
f5pk.errorbar(f5p_yes_k, f5pΔ_yes_k, yerr=[f5perrm_yes_k, f5perrp_yes_k], color="#0000FF", fmt='o')
f5pk.errorbar(f5p_mar_k, f5pΔ_mar_k, yerr=[f5perrm_mar_k, f5perrp_mar_k], color="#FF0000", fmt='o')
f5pk.errorbar(f5p_no_k, f5pΔ_no_k, yerr=[f5perrm_no_k, f5perrp_no_k], color="#000000", fmt='o')
f5pk.set_xscale('log')
f5pk.set_ylabel("Relative Error")
f5pk.set_xlabel("Semi-amplitude (m/s)")
#f5pk.set_ylim(-0.2,1.5)
#f5pk.set_xlim(6e-2,1e2)
f5pk.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
#f5pkk.legend(loc=2)
filename = "5pk_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, f5pe = plt.subplots()
f5pe.errorbar(f5p_yes_e, f5pΔ_yes_e, yerr=[f5perrm_yes_e, f5perrp_yes_e], color="#0000FF", fmt='o')
f5pe.errorbar(f5p_mar_e, f5pΔ_mar_e, yerr=[f5perrm_mar_e, f5perrp_mar_e], color="#FF0000", fmt='o')
f5pe.errorbar(f5p_no_e, f5pΔ_no_e, yerr=[f5perrm_no_e, f5perrp_no_e], color="#000000", fmt='o')
f5pe.set_xscale('log')
f5pe.set_ylabel("Relative Error")
f5pe.set_xlabel("Eccentricity")
f5pe.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
#f5pek.legend(loc=2)
filename = "5pe_error_" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
#plt.show()
<file_sep>/recovery_data_extraction_epnp.py
'''Converting all those output CSV files into a single large CSV in an easier to deal with format'''
import numpy as np
import pandas as pd
import os.path
stars = np.genfromtxt("planets.csv", delimiter=',', names=True, dtype=("U23", "U9", int, float, float, float, float, float, float, float, float, float, float))
star_name = stars[0]["HIPnumber"]
file_postfix = "ep" # note: columns = 2+(planets*parameters). 5p and fp have 4 parameters, while ep and np have 3! ([5,e,f,n]n may have more like 5+(remaining_planets*parameters), and given the way planets are truncated can not be easily matched up)
maxplanets = 10
planetfits_results = open("planetfits_results"+file_postfix+".csv", 'w')
planetfits_results.write("Star,num,PlanetNumber,per_min_"+file_postfix+",per_mid_"+file_postfix+",per_max_"+file_postfix+",per_err_minus_"+file_postfix+",per_err_plus_"+file_postfix+",tc_min_"+file_postfix+",tc_mid_"+file_postfix+",tc_max_"+file_postfix+",tc_err_minus_"+file_postfix+",tc_err_plus_"+file_postfix+",per_min_"+file_postfix+",per_mid_"+file_postfix+",per_max_"+file_postfix+",per_err_minus_"+file_postfix+",per_err_plus\n")
for i in np.arange(1,len(stars)):
if (star_name != stars[i]["HIPnumber"]):
if (stars[i-1]["PlanetNumber"] <= maxplanets):
if (os.path.isfile(star_name+file_postfix+"/"+star_name+file_postfix+"_post_summary.csv")):
planets_pd = pd.read_csv(star_name+file_postfix+"/"+star_name+file_postfix+"_post_summary.csv")
planets_columns = planets_pd.columns
#planetfits_results.write(star_name)
for x in np.arange(1, len(planets_columns)-2, 3):
planetfits_results.write(star_name+","+str(stars[i-1]["PlanetNumber"])+","+str(int((x+2)/3)))
planetfits_results.write(","+str(planets_pd[planets_columns[x]][0])+","+str(planets_pd[planets_columns[x]][1])+","+str(planets_pd[planets_columns[x]][2])) # per
planetfits_results.write(","+str(planets_pd[planets_columns[x]][1]-planets_pd[planets_columns[x]][0])+","+str(planets_pd[planets_columns[x]][2]-planets_pd[planets_columns[x]][1]))
planetfits_results.write(","+str(planets_pd[planets_columns[x+1]][0])+","+str(planets_pd[planets_columns[x+1]][1])+","+str(planets_pd[planets_columns[x+1]][2])) # tc
planetfits_results.write(","+str(planets_pd[planets_columns[x+1]][1]-planets_pd[planets_columns[x+1]][0])+","+str(planets_pd[planets_columns[x+1]][2]-planets_pd[planets_columns[x+1]][1]))
planetfits_results.write(","+str(planets_pd[planets_columns[x+2]][0])+","+str(planets_pd[planets_columns[x+2]][1])+","+str(planets_pd[planets_columns[x+2]][2])) # k
planetfits_results.write(","+str(planets_pd[planets_columns[x+2]][1]-planets_pd[planets_columns[x+2]][0])+","+str(planets_pd[planets_columns[x+2]][2]-planets_pd[planets_columns[x+2]][1]))
planetfits_results.write("\n")
star_name = stars[i]["HIPnumber"]
planetfits_results.close()
<file_sep>/recovery_plots.py
import numpy as np
import matplotlib.pyplot as plt
stars = np.genfromtxt("planetfits_revised.csv", delimiter=",", names=True, dtype=None)
nplanets = [(1,3), (1,4), (4,4)]
#nplanets = [(1,6), (5,6), (5,5), (6,6)]
# iterate over: [5,e,f,n][n,p] fits, and 1-3, 4, 5, 6, 1-4, 5-6, 1-6 planet systems?
for minplanets, maxplanets in nplanets:
np_yes_per = [star["per"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_yes_a = [star["a"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_yes_k = [star["K"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_yes_mass = [star["PlanetMass"] for star in stars if ((star["np_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_no_per = [star["per"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_no_a = [star["a"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_no_k= [star["K"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_no_mass = [star["PlanetMass"] for star in stars if ((star["np_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_mar_per = [star["per"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_mar_a = [star["a"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_mar_k = [star["K"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
np_mar_mass = [star["PlanetMass"] for star in stars if ((star["np_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, npam = plt.subplots()
npam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
npam.scatter(np_yes_a, np_yes_mass, label="Recovered", color="blue")
npam.scatter(np_mar_a, np_mar_mass, label="Marginal", color="red")
npam.scatter(np_no_a, np_no_mass, label="Excluded", color="black")
#npam.plot(xs, y1, label="Earth density")
npam.set_xscale('log')
npam.set_yscale('log')
npam.set_xlabel("Semi-Major Axis (au)")
npam.set_xlim(6e-2,3e1)
npam.set_ylabel("Mass (Earth-Masses)")
npam.set_ylim(8e-2,1e4)
npam.set_title("Fitting: Period, K, Time of Conjunction; eccentricity set to 0 ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
npam.legend(loc=2)
filename = "npam" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, nppk = plt.subplots()
nppk.scatter(stars["per"], stars["K"], color="gray", s=1)
nppk.scatter(np_yes_per, np_yes_k, label="Recovered", color="blue")
nppk.scatter(np_mar_per, np_mar_k, label="Marginal", color="red")
nppk.scatter(np_no_per, np_no_k, label="Excluded", color="black")
#nppk.plot(xs, y1, label="Earth density")
nppk.set_xscale('log')
nppk.set_yscale('log')
nppk.set_ylabel("Semi-Amplitude (m/s)")
nppk.set_ylim(8e-4,2e2)
nppk.set_xlabel("Period (Days)")
nppk.set_xlim(6,1e5)
nppk.set_title("Fitting: Period, K, Time of Conjunction; eccentricity set to 0 ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
nppk.legend(loc=2)
filename = "nppk" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
#plt.show()
ep_yes_per = [star["per"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_yes_a = [star["a"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_yes_k = [star["K"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_yes_mass = [star["PlanetMass"] for star in stars if ((star["ep_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_no_per = [star["per"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_no_a = [star["a"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_no_k= [star["K"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_no_mass = [star["PlanetMass"] for star in stars if ((star["ep_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_mar_per = [star["per"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_mar_a = [star["a"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_mar_k = [star["K"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
ep_mar_mass = [star["PlanetMass"] for star in stars if ((star["ep_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, epam = plt.subplots()
epam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
epam.scatter(ep_yes_a, ep_yes_mass, label="Recovered", color="blue")
epam.scatter(ep_mar_a, ep_mar_mass, label="Marginal", color="red")
epam.scatter(ep_no_a, ep_no_mass, label="Excluded", color="black")
#epam.plot(xs, y1, label="Earth density")
epam.set_xscale('log')
epam.set_yscale('log')
epam.set_xlabel("Semi-Major Axis (au)")
epam.set_xlim(6e-2,3e1)
epam.set_ylabel("Mass (Earth-Masses)")
epam.set_ylim(8e-2,1e4)
epam.set_title("Fitting: Period, K, Time of Conjunction ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
epam.legend(loc=2)
filename = "epam" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, eppk = plt.subplots()
eppk.scatter(stars["per"], stars["K"], color="gray", s=1)
eppk.scatter(ep_yes_per, ep_yes_k, label="Recovered", color="blue")
eppk.scatter(ep_mar_per, ep_mar_k, label="Marginal", color="red")
eppk.scatter(ep_no_per, ep_no_k, label="Excluded", color="black")
#eppk.plot(xs, y1, label="Earth density")
eppk.set_xscale('log')
eppk.set_yscale('log')
eppk.set_ylabel("Semi-Amplitude (m/s)")
eppk.set_ylim(8e-4,2e2)
eppk.set_xlabel("Period (Days)")
eppk.set_xlim(6,1e5)
eppk.set_title("Fitting: Period, K, Time of Conjunction ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
eppk.legend(loc=2)
filename = "eppk" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
#plt.show()
f5p_yes_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_a = [star["a"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_k = [star["K"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_yes_mass = [star["PlanetMass"] for star in stars if ((star["5p_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_a = [star["a"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_k= [star["K"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_no_mass = [star["PlanetMass"] for star in stars if ((star["5p_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_per = [star["per"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_a = [star["a"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_k = [star["K"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
f5p_mar_mass = [star["PlanetMass"] for star in stars if ((star["5p_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, f5pam = plt.subplots()
f5pam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
f5pam.scatter(f5p_yes_a, f5p_yes_mass, label="Recovered", color="blue")
f5pam.scatter(f5p_mar_a, f5p_mar_mass, label="Marginal", color="red")
f5pam.scatter(f5p_no_a, f5p_no_mass, label="Excluded", color="black")
#f5pam.plot(xs, y1, label="Earth density")
f5pam.set_xscale('log')
f5pam.set_yscale('log')
f5pam.set_xlabel("Semi-Major Axis (au)")
f5pam.set_xlim(6e-2,3e1)
f5pam.set_ylabel("Mass (Earth-Masses)")
f5pam.set_ylim(8e-2,1e4)
f5pam.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
f5pam.legend(loc=2)
filename = "5pam" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, f5ppk = plt.subplots()
f5ppk.scatter(stars["per"], stars["K"], color="gray", s=1)
f5ppk.scatter(f5p_yes_per, f5p_yes_k, label="Recovered", color="blue")
f5ppk.scatter(f5p_mar_per, f5p_mar_k, label="Marginal", color="red")
f5ppk.scatter(f5p_no_per, f5p_no_k, label="Excluded", color="black")
#f5ppk.plot(xs, y1, label="Earth density")
f5ppk.set_xscale('log')
f5ppk.set_yscale('log')
f5ppk.set_ylabel("Semi-Amplitude (m/s)")
f5ppk.set_ylim(8e-4,2e2)
f5ppk.set_xlabel("Period (Days)")
f5ppk.set_xlim(6,1e5)
f5ppk.set_title("Fitting: Period, K, Time of Conjunction, Ecc (max 0.5) ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
f5ppk.legend(loc=2)
filename = "5ppk" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fp_yes_per = [star["per"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_yes_a = [star["a"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_yes_k = [star["K"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_yes_mass = [star["PlanetMass"] for star in stars if ((star["fp_Favored"] == b"Yes") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_no_per = [star["per"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_no_a = [star["a"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_no_k= [star["K"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_no_mass = [star["PlanetMass"] for star in stars if ((star["fp_Favored"] == b"No") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_mar_per = [star["per"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_mar_a = [star["a"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_mar_k = [star["K"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fp_mar_mass = [star["PlanetMass"] for star in stars if ((star["fp_Favored"] == b"Marginal") and (star["num"] >= minplanets) and (star["num"] <= maxplanets))]
fig, fpam = plt.subplots()
fpam.scatter(stars["a"], stars["PlanetMass"], color="gray", s=1)
fpam.scatter(fp_yes_a, fp_yes_mass, label="Recovered", color="blue")
fpam.scatter(fp_mar_a, fp_mar_mass, label="Marginal", color="red")
fpam.scatter(fp_no_a, fp_no_mass, label="Excluded", color="black")
#fpam.plot(xs, y1, label="Earth density")
fpam.set_xscale('log')
fpam.set_yscale('log')
fpam.set_xlabel("Semi-Major Axis (au)")
fpam.set_xlim(6e-2,3e1)
fpam.set_ylabel("Mass (Earth-Masses)")
fpam.set_ylim(8e-2,1e4)
fpam.set_title("Fitting: Period, K, Time of Conjunction, Ecc ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
fpam.legend(loc=2)
filename = "fpam" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
fig, fppk = plt.subplots()
fppk.scatter(stars["per"], stars["K"], color="gray", s=1)
fppk.scatter(fp_yes_per, fp_yes_k, label="Recovered", color="blue")
fppk.scatter(fp_mar_per, fp_mar_k, label="Marginal", color="red")
fppk.scatter(fp_no_per, fp_no_k, label="Excluded", color="black")
#fppk.plot(xs, y1, label="Earth density")
fppk.set_xscale('log')
fppk.set_yscale('log')
fppk.set_ylabel("Semi-Amplitude (m/s)")
fppk.set_ylim(8e-4,2e2)
fppk.set_xlabel("Period (Days)")
fppk.set_xlim(6,1e5)
fppk.set_title("Fitting: Period, K, Time of Conjunction, Ecc ("+str(minplanets)+"-"+str(maxplanets)+" planet systems)")
fppk.legend(loc=2)
filename = "fppk" + str(minplanets) + str(maxplanets) + ".png"
plt.savefig(filename)
|
f67e7ad64088e41a6515f8e35bcd029a1f0ed073
|
[
"Markdown",
"Python"
] | 8 |
Python
|
pdn4kd/isochoric-expander
|
56bfdc3c7efb3a242ff4ae4c556d70bb7f171e5f
|
4a536594ce880ff2d266ca02359cdb4d69f40203
|
refs/heads/master
|
<repo_name>mexpolk/dotfiles<file_sep>/README.md
```
/$$$$$$ /$$ /$$$$$$$ /$$ /$$$$$$ /$$ /$$
|_ $$_/ | $/ | $$__ $$ | $$ /$$__ $$|__/| $$
| $$ /$$ /$$ /$$$$$$ /$$$$$$$|_//$$$$$$$ | $$ \ $$ /$$$$$$ /$$$$$$ | $$ \__/ /$$| $$ /$$$$$$ /$$$$$$$
| $$| $$ /$$/|____ $$| $$__ $$ /$$_____/ | $$ | $$ /$$__ $$|_ $$_/ | $$$$ | $$| $$ /$$__ $$ /$$_____/
| $$ \ $$/$$/ /$$$$$$$| $$ \ $$| $$$$$$ | $$ | $$| $$ \ $$ | $$ | $$_/ | $$| $$| $$$$$$$$| $$$$$$
| $$ \ $$$/ /$$__ $$| $$ | $$ \____ $$ | $$ | $$| $$ | $$ | $$ /$$| $$ | $$| $$| $$_____/ \____ $$
/$$$$$$ \ $/ | $$$$$$$| $$ | $$ /$$$$$$$/ | $$$$$$$/| $$$$$$/ | $$$$/| $$ | $$| $$| $$$$$$$ /$$$$$$$/
|______/ \_/ \_______/|__/ |__/|_______/ |_______/ \______/ \___/ |__/ |__/|__/ \_______/|_______/
```
## Install Dependencies
```
brew install ag curl fzf node tmux wget python python3
pip install neovim --upgrade
pip3 install neovim --upgrade
/usr/local/opt/fzf/install
brew tap neovim/neovim
brew install neovim
brew install reattach-to-user-namespace --with-wrap-pbcopy-and-pbpaste
```
## Setup
```
git clone <EMAIL>:mexpolk/dotfiles.git ~/.dotfiles
cd .dotfiles
git submodule init && git submodule update
npm install
./bin/setup -n "<NAME>" -m "<EMAIL>" -u github-username
```
## Vim Installation
Inside VIM run `:PluginInstall`
### Setup Gist Token
Go to https://github.com/settings/tokens, and generate a new token. Then create the file `$HOME/.gist-vim` and add the token to that file:
```
token 000000000000000000000000000000000000000
```
### Install Fonts and Schemes for iTerm
* Fonts available under `nerd-fonts` directory (provided by https://nerdfonts.com/)
* Schemes available under `schemes` directory (provided by http://iterm2colorschemes.com/)
<file_sep>/zshrc
# Path to your oh-my-zsh configuration.
ZSH=$HOME/.oh-my-zsh
# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
ZSH_THEME="robbyrussell"
# Set to this to use case-sensitive completion
# CASE_SENSITIVE="true"
# Comment this out to disable weekly auto-update checks
# DISABLE_AUTO_UPDATE="true"
# Uncomment following line if you want to disable colors in ls
# DISABLE_LS_COLORS="true"
# Uncomment following line if you want to disable autosetting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment following line if you want red dots to be displayed while waiting for completion
# COMPLETION_WAITING_DOTS="true"
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Example format: plugins=(rails git textmate ruby lighthouse)
plugins=(git)
source $ZSH/oh-my-zsh.sh
# Customize to your needs...
# disable auto-correction
unsetopt correct_all
source $HOME/.dotfiles/zsh-defaults
source $HOME/.dotfiles/zsh-paths
source $HOME/.dotfiles/zsh-aliases
source $HOME/.zsh-local
# Rust
source $HOME/.cargo/env
# NVM
export NVM_DIR="$HOME/.nvm"
[ -s "/usr/local/opt/nvm/nvm.sh" ] && . "/usr/local/opt/nvm/nvm.sh" # This loads nvm
[ -s "/usr/local/opt/nvm/etc/bash_completion.d/nvm" ] && . "/usr/local/opt/nvm/etc/bash_completion.d/nvm" # This loads nvm bash_completion
# RVM
# PATH=$PATH:$HOME/.rvm/bin # Add RVM to PATH for scripting
# source "$HOME/.rvm/scripts/rvm"
### Added by the Heroku Toolbelt
# export PATH="/usr/local/heroku/bin:$PATH"
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
export FZF_DEFAULT_COMMAND='ag --hidden --ignore .git --ignore node_modules -g ""'
|
82b297069df3f702025ccc2a248b9bf0a38ee459
|
[
"Markdown",
"Shell"
] | 2 |
Markdown
|
mexpolk/dotfiles
|
4503d2ceee7b1ac0a9146cd7b782785b04b495c2
|
aa53abf9b071e020664a104bf4cd0eaa2c186b83
|
refs/heads/master
|
<repo_name>tongbal/EvenChecker<file_sep>/EvenChecker/EvenChecker/EvenChecker.cpp
/*Write a program that asks the user to input an integer,
and tells the user whether the number is even or odd.
Write a function called isEven() that returns true if an integer passed to it is even.
Use the modulus operator to test whether the integer parameter is even.q*/
#include <iostream>
bool isEven(int zahlEingabe)
{
return zahlEingabe % 2;
}
int main()
{
std::cout << "Gebe eine Zahl ein: ";
int zahlEingabe = 0;
std::cin >> zahlEingabe;
bool Auswertung= isEven(zahlEingabe);
if (Auswertung == 0)
{
std::cout << "Zahl ist gleich!\n";
}
if (Auswertung == 1)
{
std::cout << "Zahl ist ungleich!\n";
}
}
|
055decfa96c5de1d305cca5215f2126fcb8b85b3
|
[
"C++"
] | 1 |
C++
|
tongbal/EvenChecker
|
16785edeb4a0d0a5d21cf2a57f314142d370115b
|
5b7bc54d50d72850ac53070331f3662619da6dd1
|
refs/heads/master
|
<repo_name>aleksei-f/homework<file_sep>/lab2/init_raid.sh
#!/usr/bin/env bash
mdadm --create --verbose /dev/md0 --level=10 -n 6 /dev/sd[b-g]
mkfs.ext4 /dev/md0
mkdir /mnt/raid
echo "/dev/md0 /mnt/raid ext4 defaults 0 2" >> /etc/fstab
mount -a
|
ed155e09e9434e7e5be80836a711667340d03b61
|
[
"Shell"
] | 1 |
Shell
|
aleksei-f/homework
|
50bdec5cc11fa7bf6828f049200839c8690f947b
|
e54e14a97e49c4a5041912f358af35aff9b0f284
|
refs/heads/master
|
<file_sep>package se.fasilie.core.extensions
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
import se.fasilie.core.networking.Outcome
fun <T> PublishSubject<T>.toLiveData(compositeDisposable: CompositeDisposable): LiveData<T> {
val data = MutableLiveData<T>()
compositeDisposable.add(this.subscribe({ t: T -> data.value = t }))
return data
}
fun <T> PublishSubject<Outcome<T>>.failed(e: Throwable) {
with(this){
loading(false)
onNext(Outcome.failure(e))
}
}
fun <T> PublishSubject<Outcome<T>>.success(t: T) {
with(this){
loading(false)
onNext(Outcome.success(t))
}
}
fun <T> PublishSubject<Outcome<T>>.loading(isLoading: Boolean) {
this.onNext(Outcome.loading(isLoading))
}
<file_sep># Fasilie
Money returner for customers. Keeps track of purchased products from retailers during the last 90 days and notices price deductions automatically.
# Core
Some of the app core includes
- **Kotlin** - Fasilie is completely written in Kotlin.
- **Effective Networking** - Using Retrofit, Rx, Room and LiveData, Fasilie is able to handle networking in an effective way.
- **MVVM architecture** - Using lifecycle-aware ViewModels, the view observes changes in the model/repository.
- **Android Architecture Components** - Lifecycle-awareness has been achieved using a combination of LiveData, ViewModels and Room.
- **Offline first architecture** - All the data is first tried to be loaded from the db and then updated from the server. This ensures that the app is usable even in an offline mode.
- **Dependency Injection** - Uses injection by utilizing Dagger 2.
# Network

# View
TODO
# ViewModel
TODO
# Repository
TODO
# Build info
- Android Studio - 3.1 Canary 8
- Compile SDK - 27
- Min SDK - 21, Target SDK - 27
# Libraries
* [Android Support Libraries](https://developer.android.com/topic/libraries/support-library/index.html)
* [Dagger 2](https://google.github.io/dagger/)
* [Retrofit](http://square.github.io/retrofit/)
* [OkHttp](http://square.github.io/okhttp/)
* [Picasso](http://square.github.io/picasso/)
* [Stetho](http://facebook.github.io/stetho/)
* [Room](https://developer.android.com/topic/libraries/architecture/room.html)
* [ViewModel](https://developer.android.com/topic/libraries/architecture/viewmodel.html)
* [LiveData](https://developer.android.com/topic/libraries/architecture/livedata.html)
* [RxJava](https://github.com/ReactiveX/RxJava)
* [RxAndroid](https://github.com/ReactiveX/RxAndroid)
<file_sep>package se.fasilie.core.constants
import se.fasilie.core.BuildConfig
object Constants {
val API_URL = BuildConfig.BASE_URL
object DatabaseConstants {
val DB_NAME = "db_fasilie"
}
}
|
f698e77a9ab5d911cac7cea0a8c294c56d1c8657
|
[
"Markdown",
"Kotlin"
] | 3 |
Kotlin
|
elvedinelvis/Fasilie
|
05c3de27aeac3a405e5404816e66a932a9e48ce3
|
8cd8a81beb31bce12cb1cbd8d09df34daa01ae6f
|
refs/heads/master
|
<file_sep>async function handleRequest(request: Request): Promise<Response> {
// If request is for test.css just serve the raw CSS
if (/test.css$/.test(request.url)) {
return new Response(CSS, {
headers: {
'content-type': 'text/css',
},
})
} else {
// serve raw HTML using HTTP/2 for the CSS file
return new Response(HTML, {
headers: {
'content-type': 'text/html',
Link: '</http2_push/h2p/test.css>; rel=preload;',
},
})
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const CSS = `body { color: red; }`
const HTML = `
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Server push test</title>
<link rel="stylesheet" href="http2_push/h2p/test.css">
</head>
<body>
<h1>Server push test page</h1>
</body>
</html>
`
export {}
<file_sep># Javascript Style Guide
All JavaScript must adhere to [JavaScript Standard Style](https://standardjs.com/) and the [Cloudflare JS StyleGuide](./style/javascript).
## Basic Guidelines
- Always deconstruct when possible `const { url } = request` over `const url = request.url`
- Prefer the object spread operator (`{...anotherObj}`) to `Object.assign()`
- Inline `export`s with expressions whenever possible
```
// Use this:
export default class ClassName {
}
// Instead of:
class ClassName {
}
export default ClassName
```
- Place requires in the following order:
- Built in Node Modules (such as `path`)
- Local Modules (using relative paths)
- Use arrow functions `=>` over anonymous function expressions
- Place class properties in the following order:
- Class methods and properties (methods starting with `static`)
- Instance methods and properties
- [Avoid platform-dependent code](https://flight-manual.atom.io/hacking-atom/sections/cross-platform-compatibility/)
* Comment all functions using JSDoc style (e.g. `/***/` ) and if not in Typescript include the param types
## Templates
For Javascript snippets and boilerplates, please make sure your code is ran through prettier with the following config:
```javascript .prettierrc
{
"singleQuote": true,
"semi": false,
"tabWidth": 2,
"trailingComma": "all",
"printWidth": 80
}
```
For boilerplates this will be done automatically, but for snippets you can do this using by following a [tutorial on using prettier](https://medium.com/dailyjs/getting-started-with-prettier-writing-clean-concise-code-6838e0912175).
## Thanks
Thank you [Atom](https://atom.io/) for opening up your style guides to help us adopt the best practices:blush:.
<file_sep>id = "cache_ttl"
weight = 1
type = "snippet"
title = "Cache using fetch"
description = "Determine how/if to cache a resource by setting TTLs, custom cache keys, and cache headers in a fetch [`request`](/workers/reference/apis/request/) to gain granular control of browsers' and Cloudflare's caches for even your dynamic assets like caching HTML. "
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#8dd3e29985701b05e43b4dd74c387b74:https://example.com/"
tags = [ "Middleware", "Enterprise" ]
<file_sep>async function handleRequest() {
let msg = "alice and bob"
let hmacresult = await generateSignandVerify({
name: "HMAC",
hash: "sha-256"
})
console.log("Result of HMAC generate, sign, verify: ", hmacresult)
let aesresult = await generateEncryptDecrypt({
name: "AES-GCM",
length: 256
}, msg)
var dec = new TextDecoder();
if (msg == dec.decode(aesresult)) {
console.log("AES encrypt decrypt successful")
} else {
console.log("AES encrypt decrypt failed")
}
return new Response()
}
addEventListener('fetch', event => {
event.respondWith(handleRequest())
})
async function generateSignandVerify(algorithm: any) {
let rawMessage = "alice and bob"
let key = await self.crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]) as CryptoKey;
let enc = new TextEncoder();
let encoded = enc.encode(rawMessage);
let signature = await self.crypto.subtle.sign(
algorithm,
key,
encoded
);
let result = await self.crypto.subtle.verify(
algorithm,
key,
signature,
encoded
);
return result;
}
async function generateEncryptDecrypt(algorithm: any, msg: string) {
let key = await self.crypto.subtle.generateKey(
algorithm,
true,
["encrypt", "decrypt"]
) as CryptoKey;
let enc = new TextEncoder();
let encoded = enc.encode(msg);
algorithm.iv = crypto.getRandomValues(new Uint8Array(16))
let signature = await self.crypto.subtle.encrypt(
algorithm,
key,
encoded
);
let result = await self.crypto.subtle.decrypt(
algorithm,
key,
signature
);
return result;
}
<file_sep>id = "hot_link_protection"
weight = 1
type = "snippet"
title = "Hot-link Protection"
description = "Block other websites from linking to your content"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#d659b20dcf91df6e6de1bedbb94f6702:https://www.cloudflare.com/img/logo-cloudflare-dark.svg"
share_url = "/templates/snippets/hotlink-protection"
<file_sep>async function handleRequest() {
return Response.redirect(someURLToRedirectTo, code)
}
addEventListener('fetch', async event => {
event.respondWith(handleRequest())
})
/**
* @param {Request} url where to redirect the response
* @param {number?=301|302} type permanent or temporary redirect
*/
const someURLToRedirectTo = 'https://www.google.com'
const code = 301
export {}
<file_sep>function handleRequest(request: Request): Response {
const NAME = 'experiment-0'
// The Responses below are placeholders. You can set up a custom path for each test (e.g. /control/somepath ).
const TEST_RESPONSE = new Response('Test group') // e.g. await fetch('/test/sompath', request)
const CONTROL_RESPONSE = new Response('Control group') // e.g. await fetch('/control/sompath', request)
// Determine which group this requester is in.
const cookie = request.headers.get('cookie')
if (cookie && cookie.includes(`${NAME}=control`)) {
return CONTROL_RESPONSE
} else if (cookie && cookie.includes(`${NAME}=test`)) {
return TEST_RESPONSE
} else {
// If there is no cookie, this is a new client. Choose a group and set the cookie.
const group = Math.random() < 0.5 ? 'test' : 'control' // 50/50 split
const response = group === 'control' ? CONTROL_RESPONSE : TEST_RESPONSE
response.headers.append('Set-Cookie', `${NAME}=${group}; path=/`)
return response
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
export {}
<file_sep>async function handleRequest(request: Request): Promise<Response> {
// Fetch the original request
const response = await fetch(request)
// If it's an image, engage hotlink protection based on the
// Referer header.
const referer = request.headers.get('Referer')
const contentType = response.headers.get('Content-Type') || ''
if (referer && contentType.startsWith(PROTECTED_TYPE)) {
// If the hostnames don't match, it's a hotlink
if (new URL(referer).hostname !== new URL(request.url).hostname) {
// Redirect the user to your website
return Response.redirect(HOMEPAGE_URL, 302)
}
}
// Everything is fine, return the response normally.
return response
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const HOMEPAGE_URL = 'https://tutorial.cloudflareworkers.com/'
const PROTECTED_TYPE = 'images/'
export {}
<file_sep>id = "dart_hello_world"
weight = 1
type = "boilerplate"
title = "Dart Hello World"
description = "Return a Hello World Response in Dart"
repository_url = "https://github.com/cloudflare/dart-worker-hello-world"
<file_sep>async function handleRequest(): Promise<Response> {
const init = {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}
const response = await fetch(url, init)
const results = await gatherResponse(response)
return new Response(results, init)
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest())
})
/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/
async function gatherResponse(response: Response): Promise<string> {
const { headers } = response
const contentType = headers.get('content-type') || ''
if (contentType.includes('application/json')) {
return JSON.stringify(await response.json())
} else if (contentType.includes('application/text')) {
return await response.text()
} else if (contentType.includes('text/html')) {
return await response.text()
} else {
return await response.text()
}
}
/**
* Example someHost is set up to take in a JSON request
* Replace url with the host you wish to send requests to
* @param {string} someHost the host to send the request to
* @param {string} url the URL to send the request to
*/
const someHost = 'https://workers-tooling.cf/demos'
const url = someHost + '/static/json'
export {}
<file_sep>id = "auth_basic_http"
weight = 1
type = "snippet"
title = "Basic HTTP authentication"
description = "Password-protect whole websites or specific areas/pages. Browsers will prompt for a password and username - hardcoded as `demouser`/`demopassword` - before serving a protected page. This uses basic authentication through the [`WWW-Authorization` header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).
repository_url = ""
[demos.main]
text = "Demo (credentials: demouser/demopassword)"
url = "https://cloudflareworkers.com/#f5d2cc53bd3d55486ddd14b1eb6e6c83:https://www.cloudflarestatus.com/"
tags = [ "Middleware" ]
<file_sep>async function handleRequest(request) {
const url = new URL(request.url)
let apiUrl = url.searchParams.get('apiurl')
if (apiUrl == null) {
apiUrl = API_URL
}
// Rewrite request to point to API url. This also makes the request mutable
// so we can add the correct Origin header to make the API server think
// that this request isn't cross-site.
request = new Request(apiUrl, request)
request.headers.set('Origin', new URL(apiUrl).origin)
let response = await fetch(request)
// Recreate the response so we can modify the headers
response = new Response(response.body, response)
// Set CORS headers
response.headers.set('Access-Control-Allow-Origin', url.origin)
// Append to/Add Vary header so browser will cache response correctly
response.headers.append('Vary', 'Origin')
return response
}
function handleOptions(request) {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
if (
request.headers.get('Origin') !== null &&
request.headers.get('Access-Control-Request-Method') !== null &&
request.headers.get('Access-Control-Request-Headers') !== null
) {
// Handle CORS pre-flight request.
// If you want to check the requested method + headers
// you can do that here.
return new Response(null, {
headers: corsHeaders,
})
} else {
// Handle standard OPTIONS request.
// If you want to allow other HTTP Methods, you can do that here.
return new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
},
})
}
}
addEventListener('fetch', event => {
const request = event.request
const url = new URL(request.url)
if (url.pathname.startsWith(PROXY_ENDPOINT)) {
if (request.method === 'OPTIONS') {
// Handle CORS preflight requests
event.respondWith(handleOptions(request))
} else if (
request.method === 'GET' ||
request.method === 'HEAD' ||
request.method === 'POST'
) {
// Handle requests to the API server
event.respondWith(handleRequest(request))
} else {
event.respondWith(
new Response(null, {
status: 405,
statusText: 'Method Not Allowed',
}),
)
}
} else {
// Serve demo page
event.respondWith(rawHtmlResponse(DEMO_PAGE))
}
})
// We support the GET, POST, HEAD, and OPTIONS methods from any origin,
// and accept the Content-Type header on requests. These headers must be
// present on all responses to all CORS requests. In practice, this means
// all responses to OPTIONS requests.
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
}
// The URL for the remote third party API you want to fetch from
// but does not implement CORS
const API_URL = 'https://workers-tooling.cf/demos/demoapi'
// The endpoint you want the CORS reverse proxy to be on
const PROXY_ENDPOINT = '/corsproxy/'
// The rest of this snippet for the demo page
async function rawHtmlResponse(html) {
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
}
const DEMO_PAGE = `
<!DOCTYPE html>
<html>
<body>
<h1>API GET without CORS Proxy</h1>
<a target='_blank' href='https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful'>Shows TypeError: Failed to fetch since CORS is misconfigured</a>
<p id='noproxy-status'/>
<code id='noproxy'>Waiting</code>
<h1>API GET with CORS Proxy</h1>
<p id='proxy-status'/>
<code id='proxy'>Waiting</code>
<h1>API POST with CORS Proxy + Preflight</h1>
<p id='proxypreflight-status'/>
<code id='proxypreflight'>Waiting</code>
<script>
let reqs = {};
reqs.noproxy = async () => {
let response = await fetch('${API_URL}')
return await response.json()
}
reqs.proxy = async () => {
let response = await fetch(window.location.origin + '${PROXY_ENDPOINT}?apiurl=${API_URL}')
return await response.json()
}
reqs.proxypreflight = async () => {
const reqBody = {
msg: "Hello world!"
}
let response = await fetch(window.location.origin + '${PROXY_ENDPOINT}?apiurl=${API_URL}', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(reqBody),
})
return await response.json()
}
(async () => {
for (const [reqName, req] of Object.entries(reqs)) {
try {
let data = await req()
document.getElementById(reqName).innerHTML = JSON.stringify(data)
} catch (e) {
document.getElementById(reqName).innerHTML = e
}
}
})()
</script>
</body>
</html>`
<file_sep>id = "ab_testing"
weight = 1
type = "snippet"
title = "A/B Testing"
description = "Set up an A/B test by controlling what response is served based on cookies"
share_url = "/templates/snippets/ab_testing"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#12a2962014e1324e3a416a5a76e1f81f:https://tutorial.cloudflareworkers.com"
<file_sep>async function handleRequest(request: Request): Promise<Response> {
try {
const tlsVersion = request.cf.tlsVersion
// Allow only TLS versions 1.2 and 1.3
if (tlsVersion != 'TLSv1.2' && tlsVersion != 'TLSv1.3') {
return new Response('Please use TLS version 1.2 or higher.', {
status: 403,
})
}
return fetch(request)
} catch (err) {
console.error(
'request.cf does not exist in the previewer, only in production',
)
return new Response('Error in workers script' + err.message, {
status: 500,
})
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
export {}
<file_sep>id = "cloud_storage"
weight = 50
type = "featured_boilerplate"
title = "Cloud Storage"
description = "Serve private AWS bucket files from a Worker script"
repository_url = "https://github.com/conzorkingkong/cloud-storage"
tags = [ "Middleware" ]
share_url = "/templates/featured_boilerplates/cloud_storage"
<file_sep>id = "modify_req_props"
weight = 1
type = "snippet"
title = "Modify Request Property"
description = "Recommended practice for forming a [request](/workers/reference/apis/request) based off the incoming request. First, takes in the incoming request then modifies specific properties like POST `body`, `redirect`, and the Cloudflare specific property `cf` and runs the fetch."
share_url = "/templates/snippets/modify_req_props"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#27b91145f66b6cfce1b3190ed7ba0bc5:https://example.com"
tags = [ "Middleware" ]
<file_sep>id = "fetch_html"
weight = 20
type = "snippet"
title = "Fetch HTML"
description = "Sends a request to a remote server, reads HTML from the response, then serves that HTML."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#14a82a672534b0dd25b385a5d3de744c:https://example.com"
tags = [ "Middleware" ]
<file_sep>id = "post_data"
weight = 1
type = "snippet"
title = "Read POST Data"
description = "Serves an HTML form, then reads POSTs from that form data. Can also be used to read JSON or other POST data from an incoming request."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#a6a285e4e2bfbebea0be31b9eeaca3e6:https://example.com/form"
tags = [ "Originless" ]
<file_sep>id = "post_json"
weight = 1
type = "snippet"
title = "Post JSON"
description = "Sends a POST request with JSON data from the Workers script."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#edce60b7d57c1e98fbe2d931aaaaf25f:https://tutorial.cloudflareworkers.com"
tags = [ "Middleware" ]
<file_sep>async function handleRequest(event: FetchEvent): Promise<Response> {
const request = event.request
const cacheUrl = new URL(request.url)
// hostname for a different zone
cacheUrl.hostname = someOtherHostname
const cacheKey = new Request(cacheUrl.toString(), request)
const cache = caches.default
// Get this request from this zone's cache
let response = await cache.match(cacheKey)
if (!response) {
//if not in cache, grab it from the origin
response = await fetch(request)
// must use Response constructor to inherit all of response's fields
response = new Response(response.body, response)
// Cache API respects Cache-Control headers, so by setting max-age to 10
// the response will only live in cache for max of 10 seconds
response.headers.append('Cache-Control', 'max-age=10')
// store the fetched response as cacheKey
// use waitUntil so computational expensive tasks don't delay the response
event.waitUntil(cache.put(cacheKey, response.clone()))
}
return response
}
async function handlePostRequest(event: FetchEvent): Promise<Response> {
const request = event.request
const body = await request.clone().text()
const hash = await sha256(body)
const cacheUrl = new URL(request.url)
// get/store the URL in cache by prepending the body's hash
cacheUrl.pathname = '/posts' + cacheUrl.pathname + hash
// Convert to a GET to be able to cache
const cacheKey = new Request(cacheUrl.toString(), {
headers: request.headers,
method: 'GET',
})
const cache = caches.default
//try to find the cache key in the cache
let response = await cache.match(cacheKey)
// otherwise, fetch response to POST request from origin
if (!response) {
response = await fetch(request)
event.waitUntil(cache.put(cacheKey, response))
}
return response
}
addEventListener('fetch', event => {
try {
const request = event.request
if (request.method.toUpperCase() === 'POST')
return event.respondWith(handlePostRequest(event))
return event.respondWith(handleRequest(event))
} catch (e) {
return event.respondWith(new Response('Error thrown ' + e.message))
}
})
async function sha256(message: string): Promise<string> {
// encode as UTF-8
const msgBuffer = new TextEncoder().encode(message)
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer)
// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer))
// convert bytes to hex string
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('')
return hashHex
}
const someOtherHostname = 'my.herokuapp.com'
export {}
<file_sep>async function handleRequest(request) {
/**
* Best practice is to only assign new properties on the request
* object (i.e. RequestInit props) through either a method or the constructor
*/
const newRequestInit = {
// Change method
method: 'POST',
// Change body
body: JSON.stringify({ bar: 'foo' }),
// Change the redirect mode.
redirect: 'follow',
//Change headers, note this method will erase existing headers
headers: {
'Content-Type': 'application/json',
},
// Change a Cloudflare feature on the outbound response
cf: { apps: false },
}
// Change just the host
const url = new URL(someUrl)
url.hostname = someHost
// Best practice is to always use the original request to construct the new request
// thereby cloning all the attributes, applying the URL also requires a constructor
// since once a Request has been constructed, its URL is immutable.
const newRequest = new Request(
url.toString(),
new Request(request, newRequestInit),
)
// Set headers using method
newRequest.headers.set('X-Example', 'bar')
newRequest.headers.set('Content-Type', 'application/json')
try {
return await fetch(newRequest)
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500 })
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Example someHost is set up to return raw JSON
* @param {string} someUrl the URL to send the request to, since we are setting hostname too only path is applied
* @param {string} someHost the host the request will resolve too
*/
const someHost = 'example.com'
const someUrl = 'https://foo.example.com/api.js'
<file_sep>async function handleRequest() {
const init = {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
}
return new Response(someHTML, init)
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest())
})
const someHTML = `<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<p>This is all generated using a Worker</p>
<iframe
width="560"
height="315"
src="https://www.youtube.com/embed/dQw4w9WgXcQ"
frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
></iframe>
</body>
</html>
`
export {}
<file_sep>id = "bulk_redirects"
weight = 1
type = "snippet"
title = "Bulk Redirects"
description = "Redirects requests to certain URLs based a mapped object to the request's URL."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#d17c3da192fd5c83ef7d28153ab32f3f:https://example.com/redirect/bulk1"
<file_sep>/**
* Parses the toml files located in templates/meta_data and takes the JS in
* 'code' field and placing it in templates/javascript
*/
const fs = require('fs')
//requiring path and fs modules
const path = require('path')
const toml = require('toml')
var process = require('process')
// process.chdir('../')
//joining path of directory
const DIRECTORYPATH = path.join(__dirname, '/../templates/meta_data')
const JSDIRECTORYPATH = path.join(__dirname, '/../templates/javascript')
//read in all the toml files
fs.readdir(DIRECTORYPATH, function(err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err)
}
files.forEach(function(file) {
const filePath = DIRECTORYPATH + '/' + file
const jsFilePath = JSDIRECTORYPATH + '/' + file.replace('.toml', '.js')
const fileID = file.replace('.toml', '')
// console.log('fileID', fileID)
// Do whatever you want to do with the file
fs.readFile(filePath, (err, data) => {
if (err) throw err
jsonData = toml.parse(data.toString())
const id = jsonData.id
if (id != fileID) {
console.log("ID doesn't match toml fileName", id, fileID)
}
if (jsonData.type === 'snippet') {
//try to read the javascript file
fs.readFile(jsFilePath, (err, javascriptData) => {
if (err) throw err
if (!javascriptData.toString()) {
console.log('JS file doesnt exist for snippet ' + id)
}
// console.log('javascriptData', javascriptData.toString())
})
}
})
})
})
<file_sep>id = "reason_hello_world"
weight = 1
type = "boilerplate"
title = "Reason Hello World"
description = "Return a Hello World Response in Reason"
repository_url = "https://github.com/cloudflare/reason-worker-hello-world"
<file_sep>async function handleRequest(request) {
return redirect(request)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Returns a redirect determined by the country code
* @param {Request} request
*/
async function redirect(request) {
// The `cf-ipcountry` header is not supported in the preview
const country = request.headers.get('cf-ipcountry')
if (country != null && country in countryMap) {
const url = countryMap[country]
return Response.redirect(url)
} else {
return await fetch(request)
}
}
/**
* A map of the URLs to redirect to
* @param {Object} countryMap
*/
const countryMap = {
US: 'https://example.com/us',
EU: 'https://eu.example.com/',
}
<file_sep>async function handleRequest(request) {
// Make the headers mutable by re-constructing the Request.
request = new Request(request)
request.headers.set('x-my-header', 'custom value')
const URL = 'https://workers-tooling.cf/demos/static/html'
// URL is set up to respond with dummy HTML, remove to send requests to your own origin
let response = await fetch(URL, request)
// Make the headers mutable by re-constructing the Response.
response = new Response(response.body, response)
response.headers.set('x-my-header', 'custom value')
return response
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
<file_sep>const COOKIE_NAME = '__uid'
function handleRequest(request: Request): Response {
const cookie = getCookie(request, COOKIE_NAME)
if (cookie) {
// respond with the cookie value
return new Response(cookie)
}
return new Response('No cookie with name: ' + COOKIE_NAME)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Grabs the cookie with name from the request headers
* @param {Request} request incoming Request
* @param {string} name of the cookie to grab
*/
function getCookie(request: Request, name: string): string {
let result = ''
const cookieString = request.headers.get('Cookie')
if (cookieString) {
const cookies = cookieString.split(';')
cookies.forEach(cookie => {
const cookieName = cookie.split('=')[0].trim()
if (cookieName === name) {
const cookieVal = cookie.split('=')[1]
result = cookieVal
}
})
}
return result
}
export {}
<file_sep>const BLOCKED_HOSTNAMES = ['nope.mywebsite.com', 'bye.website.com']
async function handleRequest(request: Request): Promise<Response> {
// Return a new Response based on..
// On URL's hostname
const url = new URL(request.url)
if (BLOCKED_HOSTNAMES.includes(url.hostname)) {
return new Response('Blocked Host', { status: 403 })
}
// On URL's file extension (e.g. block paths ending in .doc or .xml)
const forbiddenExtRegExp = new RegExp(/\.(doc|xml)$/)
if (forbiddenExtRegExp.test(url.pathname)) {
return new Response('Blocked Extension', { status: 403 })
}
// On HTTP method
if (request.method === 'POST') {
return new Response('Response for POST')
}
// On User Agent
const userAgent = request.headers.get('User-Agent') || ''
if (userAgent.includes('bot')) {
return new Response('Block User Agent containing bot', { status: 403 })
}
// On Client's IP address
const clientIP = request.headers.get('CF-Connecting-IP')
if (clientIP === '1.2.3.4') {
return new Response('Block the IP 1.2.3.4', { status: 403 })
}
// On ASN
if (request.cf && request.cf.asn == 64512) {
return new Response('Block the ASN 64512 response')
}
// On Device Type
// Requires Enterprise "CF-Device-Type Header" zone setting or
// Page Rule with "Cache By Device Type" setting applied.
const device = request.headers.get('CF-Device-Type')
if (device === 'mobile') {
return Response.redirect('https://mobile.example.com')
}
console.error(
"Getting Client's IP address, device type, and ASN are not supported in playground. Must test on a live worker",
)
return fetch(request)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
export {}
<file_sep># Contributing Cloudflare Workers Templates
- [Template Metadata](#template-metadata)
- [Required Properties](#required-properties)
- [Optional Properties](#optional-properties)
- [Template Content](#template-content)
- [Snippet Content](#snippet-content)
- [Boilerplate Template Content](#boilerplate-template-content)
- [Updating a Template](#updating-a-template)
- [Creating a Snippet](#creating-a-snippet)
- [Creating a Boilerplate](#creating-a-boilerplate)
- [Testing Your Boilerplate](#testing-your-boilerplate)
- [Submitting a Boilerplate to the Template Registry](#submitting-a-boilerplate-to-the-template-registry)
This repository supplies the list of templates that appear in the [Template Gallery on the Cloudflare Workers documentation website](https://developers.cloudflare.com/workers/templates/).
There are two types of templates:
- *Snippet*: A simple template whose content lives in a single TypeScript file in this repository in the `templates/typescript` directory. A snippet’s code will be displayed inline in the Template Gallery. Snippets are short and intended for users to copy-and-paste into their own projects, or use as a reference.
- *Boilerplate*: A more-complex template in any programming language, whose content lives in a separate repository, may consist of multiple files, and can be used to generate a new project by invoking `wrangler generate path-to-template-repository`. Their content is not displayed directly in the Workers documentation; rather, each boilerplate includes a link to the source repository and a `wrangler generate` command to create a project from the boilerplate. They often have more detailed documentation, either in the template repository’s `README`, or in an article in the Workers docs [like this one](https://github.com/cloudflare/workers-docs/blob/master/workers-docs/src/content/templates/pages/graphql_server.md).
## Template Metadata
Each template is defined by a `toml` file in the [`templates/meta_data`](./templates/meta_data) directory. For example, this is the contents of [`hello_world.toml`](https://github.com/cloudflare/template-registry/blob/f2a21ff87a4f9c60ce1d426e9e8d2e6807b786fd/templates/meta_data/hello_world.toml#L1-L11):
```toml
id = "hello_world"
weight = 99
type = "boilerplate"
title = "Hello World"
description = "Simple Hello World in JS"
repository_url = "https://github.com/cloudflare/worker-template"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#6626eb50f7b53c2d42b79d1082b9bd37:https://tutorial.cloudflareworkers.com"
tags = [ "Originless" ]
```
### Required Properties
```yaml
id = "some_unique_alphanumeric_slug"
title = "Title of your template"
description = "Concise 1-2 sentences that explains what your template does"
```
Boilerplate templates must also have a `repository_url` property that links to the repository where the template code lives:
```yaml
repository_url = "https://github.com/<you>/<id>"
```
### Optional Properties
```yaml
share_url="/templates/pages/id " #path to another resource, like a tutorial, that will be displayed alongside the template
tags = ["TypeScript", "Enterprise"] # arbitrary tags that can be used to filter templates in the Template Gallery
[demos.main]
title = "Demo"
url = "https://cloudflareworkers.com/#6cbbd3ae7d4e928da3502cb9ce11227a:https://tutorial.cloudflareworkers.com/foo" # a live demo of your code
```
## Template Content
Templates should follow our [JavaScript/TypeScript style guide](./style/javascript.md).
### Snippet Content
Snippet template content lives in [`templates/typescript`](./templates/typescript). TypeScript snippet definitions are also transpiled to JavaScript, and the JavaScript versions are committed to source control in [`templates/javascript`](./templates/javascript).
A snippet with an `id` of `example` is expected to have a TypeScript content definition named `example.ts` and a JavaScript content definition named `example.js`.
Snippets should consist of the following components, in this specific order:
1. A `handleRequest` function definition
2. A call to `addEventListener`
3. Helper functions
4. Hardcoded constants which a user will likely change
Most of the logic should be in a function called `handleRequest`, which should have one of the following type signatures:
```typescript
function handleRequest(request: Request): Promise<Response>
function handleRequest(request: Request): Response
```
The event listener should be one of the following:
```typescript
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
addEventListener('fetch', event => {
event.respondWith(handleRequest())
})
```
Snippets *should not* contain any blank lines. This makes them easier to present in a small amount of space in the Template Gallery.
### Boilerplate Template Content
Boilerplate template content lives in another repository; only metadata about these templates lives in this repository. The metadata allows the Workers Docs to render information about these templates.
Boilerplate templates can be used to start a new project by running:
```bash
wrangler generate https://github.com/path/to/template
```
`wrangler` clones the repo containing the boilerplate template and performs some simple templating logic using [`cargo-generate`](https://github.com/ashleygwilliams/cargo-generate).
Refer to the [documentation of `cargo-generate`](https://github.com/ashleygwilliams/cargo-generate/blob/master/README.md) for information about template placeholders like `{{ project-name }}` and `{{ authors }}`, as well as the use of a `.genignore` file to determine which files from the template repository should end up in the user’s generated project directory. If there are binary or other files that you need to exclude from placeholder substitution, see the [documentation for cargo-generate.toml](https://github.com/ashleygwilliams/cargo-generate#include--exclude).
Boilerplate templates should not contain any generated artifacts, like the `worker` directory of a default `wrangler` project.
Example boilerplate templates include:
* [cloudflare/worker-template](https://github.com/cloudflare/worker-template)
* [EverlastingBugstopper/worker-typescript-template](https://github.com/EverlastingBugstopper/worker-typescript-template)
* [cloudflare/rustwasm-worker-template](https://github.com/cloudflare/rustwasm-worker-template)
* [cloudflare/worker-emscripten-template](https://github.com/cloudflare/worker-emscripten-template)
* [cloudflare/cobol-worker-template](https://github.com/cloudflare/cobol-worker-template)
* [signalnerve/workers-graphql-server](https://github.com/signalnerve/workers-graphql-server)
* [cloudflare/worker-sites-template](https://github.com/cloudflare/worker-sites-template)
* [cloudflare/worker-template-router](https://github.com/cloudflare/worker-template-router)
You can write additional documentation about your template that will be displayed in the Workers documentation, like this:
[Template Gallery | Hello World Rust](https://developers.cloudflare.com/workers/templates/pages/hello_world_rust)
Such additional documentation lives in the [cloudflare/workers-docs](https://github.com/cloudflare/workers-docs/) repository.
## Updating a Template
If you spot an error in a template, feel free to make a PR against this repository!
If you want to update the contents of a snippet, edit the TypeScript file (not the transpiled JavaScript version), and then run:
```bash
npm run transpile && npm run lint
```
This will transpile your TypeScript changes to the JavaScript version as well.
## Creating a Snippet
1. Clone this repository.
2. Run `npm install` from the repo’s root directory to install development dependencies.
3. Choose an `id` for your template. This should be a unique and descriptive “slug” like the other filenames in [`templates/meta_data`](./templates/meta_data).
4. Create a new metadata file in [`templates/meta_data`](./templates/meta_data) with the name `your_template_id.toml`.
5. Add your TypeScript template content in [`templates/typescript`](./templates/typescript) with the name `your_template_id.ts`.
6. Run `npm run transpile && npm run lint` to generate the JavaScript version of your TypeScript file.
7. Test your snippet in the [Cloudflare Workers Playground](https://cloudflareworkers.com/) or in a `wrangler` project.
8. Make a PR to this repository containing three files:
- `templates/meta_data/your_template_id.toml`
- `templates/typescript/your_template_id.ts`
- `templates/javascript/your_template_id.js`
## Creating a Boilerplate
You can get started by cloning the [template creator](https://github.com/victoriabernard92/workers-template-creator) and following the instructions in the README. You can also start from scratch and add template placeholders to any `wrangler` project.
### Testing Your Boilerplate
A boilerplate must be capable of being installed with `wrangler generate`.
Test using [`wrangler`](https://github.com/cloudflare/wrangler) to generate a new project from your boilerplate template:
```bash
wrangler generate your-template-id ./
cd your-template-slug
wrangler preview --watch
```
Finally, publish your template in a public GitHub repo, and then test your boilerplate template by running:
```bash
wrangler generate https://github.com/<you>/<your-template-id>
cd your-template-id
wrangler preview --watch
```
### Submitting a Boilerplate to the Template Registry
Create a metadata file for your template in `templates/meta_data`. Make sure to include a `repo` link to your boilerplate template’s GitHub repository.
Then make a PR to this repo with your new metadata `toml` file.
<file_sep>async function handleRequest(request) {
const url = new URL(request.url)
// Check if incoming hostname is a key in the ORIGINS object
if (url.hostname in ORIGINS) {
const target = ORIGINS[url.hostname]
url.hostname = target
// If it is, proxy request to that third party origin
return fetch(url.toString(), request)
}
// Otherwise, process request as normal
return fetch(request)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* An object with different URLs to fetch
* @param {Object} ORIGINS
*/
const ORIGINS = {
'starwarsapi.yourdomain.com': 'swapi.co',
'google.yourdomain.com': 'google.com',
}
<file_sep>id = "debugging_tips"
weight = 50
type = "snippet"
title = "Debugging Tips"
description = "Send debug information in an errored response and to a logging service."
tags = [ "Middleware" ]
share_url = "/about/tips/debugging"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#5601380cdcb173e5b712bd82113ce47a:https://blah.workers-tooling.cf/fetch/error"
<file_sep>id = "country_code"
weight = 20
type = "snippet"
title = "Country Code"
description = "Redirect a response based on the country code of the visitor"
tags = [ "Originless" ]
<file_sep>const BLOCKED_HOSTNAMES = ['nope.mywebsite.com', 'bye.website.com']
async function handleRequest(request) {
// Return a new Response based on..
// On URL's hostname
const url = new URL(request.url)
if (BLOCKED_HOSTNAMES.includes(url.hostname)) {
return new Response('Blocked Host', { status: 403 })
}
// On URL's file extension (e.g. block paths ending in .doc or .xml)
const forbiddenExtRegExp = new RegExp(/\.(doc|xml)$/)
if (forbiddenExtRegExp.test(url.pathname)) {
return new Response('Blocked Extension', { status: 403 })
}
// On HTTP method
if (request.method === 'POST') {
return new Response('Response for POST')
}
// On User Agent
const userAgent = request.headers.get('User-Agent') || ''
if (userAgent.includes('bot')) {
return new Response('Block User Agent containing bot', { status: 403 })
}
// On Client's IP address
const clientIP = request.headers.get('CF-Connecting-IP')
if (clientIP === '1.2.3.4') {
return new Response('Block the IP 1.2.3.4', { status: 403 })
}
// On ASN
if (request.cf && request.cf.asn == 64512) {
return new Response('Block the ASN 64512 response')
}
// On Device Type
// Requires Enterprise "CF-Device-Type Header" zone setting or
// Page Rule with "Cache By Device Type" setting applied.
const device = request.headers.get('CF-Device-Type')
if (device === 'mobile') {
return Response.redirect('https://mobile.example.com')
}
console.error(
"Getting Client's IP address, device type, and ASN are not supported in playground. Must test on a live worker",
)
return fetch(request)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
<file_sep>async function handleRequest(request) {
// If request is for test.css just serve the raw CSS
if (/test.css$/.test(request.url)) {
return new Response(CSS, {
headers: {
'content-type': 'text/css',
},
})
} else {
// serve raw HTML using HTTP/2 for the CSS file
return new Response(HTML, {
headers: {
'content-type': 'text/html',
Link: '</http2_push/h2p/test.css>; rel=preload;',
},
})
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const CSS = `body { color: red; }`
const HTML = `
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Server push test</title>
<link rel="stylesheet" href="http2_push/h2p/test.css">
</head>
<body>
<h1>Server push test page</h1>
</body>
</html>
`
<file_sep>async function handleRequest(request) {
/**
* Response properties are immutable. To change them, construct a new
* Response, passing modified status or statusText in the ResponseInit
* object.
* Response Headers can be modified through the headers `set` method.
*/
const originalResponse = await fetch(request)
// Change status and statusText, but preserve body and headers
let response = new Response(originalResponse.body, {
status: 500,
statusText: 'some message',
headers: originalResponse.headers,
})
// Change response body by adding the foo prop
const originalBody = await originalResponse.json()
const body = JSON.stringify({ foo: 'bar', ...originalBody })
response = new Response(body, response)
// Add a header using set method
response.headers.set('foo', 'bar')
// Set destination header to the value of the source header
const src = response.headers.get(headerNameSrc)
if (src != null) {
response.headers.set(headerNameDst, src)
console.log(
`Response header "${headerNameDst}" was set to "${response.headers.get(
headerNameDst,
)}"`,
)
}
return response
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* @param {string} headerNameSrc the header to get the new value from
* @param {string} headerNameDst the header to set based off of value in src
*/
const headerNameSrc = 'foo' //'Orig-Header'
const headerNameDst = 'Last-Modified'
<file_sep>id = "fetch_json"
weight = 30
type = "snippet"
title = "Fetch JSON"
description = "Sends a GET request and reads in JSON from the response."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#a45261f6682b048d9ed0e23a330d9cdb:https://example.com"
tags = [ "Middleware" ]
<file_sep>async function handleRequest() {
return Response.redirect(someURLToRedirectTo, code)
}
addEventListener('fetch', async event => {
event.respondWith(handleRequest())
})
/**
* @param {Request} url where to redirect the response
* @param {number?=301|302} type permanent or temporary redirect
*/
const someURLToRedirectTo = 'https://www.google.com'
const code = 301
<file_sep>id = "auth_with_headers"
weight = 1
type = "snippet"
title = "Auth with headers"
description = "Allow or deny a request based on a known pre-shared key in a header. Note while this simple implementation is helpful, it is not meant to replace more secure scripts such as signed requests using the [WebCrypto API](/reference/runtime/apis/web-crypto)."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#7373b8c3c9c46c03c81562f00f663f81:https://tutorial.cloudflareworkers.com"
tags = [ "Middleware" ]
<file_sep>id = "http2_server_push"
weight = 1
type = "snippet"
title = "HTTP/2 Server Push"
description = "Push static assests to a client's browser without waiting for HTML to render"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#f7b7e99bec493ba4f4847a095c4fa61c:https://tutorial.cloudflareworkers.com/"
<file_sep>async function handleRequest() {
const init = {
headers: {
'content-type': type,
},
}
const responses = await Promise.all([fetch(url1, init), fetch(url2, init)])
const results = await Promise.all([
gatherResponse(responses[0]),
gatherResponse(responses[1]),
])
return new Response(results.join(), init)
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest())
})
/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/
async function gatherResponse(response: Response): Promise<string> {
const { headers } = response
const contentType = headers.get('content-type') || ''
if (contentType.includes('application/json')) {
return JSON.stringify(await response.json())
} else if (contentType.includes('application/text')) {
return await response.text()
} else if (contentType.includes('text/html')) {
return await response.text()
} else {
return await response.text()
}
}
/**
* Example someHost is set up to return JSON responses
* Replace url1 and url2 with the hosts you wish to
* send requests to
* @param {string} url the URL to send the request to
*/
const someHost = 'https://workers-tooling.cf/demos'
const url1 = someHost + '/requests/json'
const url2 = someHost + '/requests/json'
const type = 'application/json;charset=UTF-8'
export {}
<file_sep>id = "hello_world_rust"
type = "boilerplate"
title = "Hello World Rust"
description = "Simple Hello World in Rust"
repository_url = "https://github.com/cloudflare/rustwasm-worker-template"
weight = 98
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#1992963c14c25bc8dc4c50f4cab740e5:https://tutorial.cloudflareworkers.com"
tags = [ "Originless", "Wasm" ]
share_url = "/templates/boilerplates/rustwasm"
<file_sep>#!/bin/bash
for f in *; do echo "File is '$f'">> "${f:0:${#f}-4}md"; done
<file_sep>async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url)
// Check if incoming hostname is a key in the ORIGINS object
if (url.hostname in ORIGINS) {
const target = ORIGINS[url.hostname]
url.hostname = target
// If it is, proxy request to that third party origin
return fetch(url.toString(), request)
}
// Otherwise, process request as normal
return fetch(request)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* An object with different URLs to fetch
* @param {Object} ORIGINS
*/
const ORIGINS: { [key: string]: string } = {
'starwarsapi.yourdomain.com': 'swapi.co',
'google.yourdomain.com': 'google.com',
}
export {}
<file_sep>async function handleRequest(request: Request): Promise<Response> {
/**
* Best practice is to only assign new properties on the request
* object (i.e. RequestInit props) through either a method or the constructor
*/
const newRequestInit = {
// Change method
method: 'POST',
// Change body
body: JSON.stringify({ bar: 'foo' }),
// Change the redirect mode.
redirect: 'follow' as RequestRedirect,
//Change headers, note this method will erase existing headers
headers: {
'Content-Type': 'application/json',
},
// Change a Cloudflare feature on the outbound response
cf: { apps: false },
}
// Change just the host
const url = new URL(someUrl)
url.hostname = someHost
// Best practice is to always use the original request to construct the new request
// thereby cloning all the attributes, applying the URL also requires a constructor
// since once a Request has been constructed, its URL is immutable.
const newRequest = new Request(
url.toString(),
new Request(request, newRequestInit),
)
// Set headers using method
newRequest.headers.set('X-Example', 'bar')
newRequest.headers.set('Content-Type', 'application/json')
try {
return await fetch(newRequest)
} catch (e) {
return new Response(JSON.stringify({ error: e.message }), { status: 500 })
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Example someHost is set up to return raw JSON
* @param {string} someUrl the URL to send the request to, since we are setting hostname too only path is applied
* @param {string} someHost the host the request will resolve too
*/
const someHost = 'example.com'
const someUrl = 'https://foo.example.com/api.js'
export {}
<file_sep>id = "typescript"
type = "boilerplate"
title = "Hello World TypeScript"
description = "Simple Hello World in TypeScript"
repository_url = "https://github.com/EverlastingBugstopper/worker-typescript-template"
weight = 90
tags = [ "Originless" ]
<file_sep>async function handleRequest(event) {
let response
try {
response = await fetch(event.request)
if (!response.ok) {
const body = await response.text()
throw new Error(
'Bad response at origin. Status: ' +
response.status +
' Body: ' +
//ensures the string is small enough to be a header
body.trim().substring(0, 10),
)
}
} catch (err) {
// Without event.waitUntil(), our fetch() to our logging service may
// or may not complete.
event.waitUntil(postLog(err.toString()))
const stack = JSON.stringify(err.stack) || err
// Copy the response and initialize body to the stack trace
response = new Response(stack, response)
// Shove our rewritten URL into a header to find out what it was.
response.headers.set('X-Debug-stack', stack)
response.headers.set('X-Debug-err', err)
}
return response
}
addEventListener('fetch', event => {
//Have any uncaught errors thrown go directly to origin
event.passThroughOnException()
event.respondWith(handleRequest(event))
})
function postLog(data) {
return fetch(LOG_URL, {
method: 'POST',
body: data,
})
}
// Service configured to receive logs
const LOG_URL = 'https://log-service.example.com/'
<file_sep>async function handleRequest(request: Request): Promise<Response> {
const psk = request.headers.get(PRESHARED_AUTH_HEADER_KEY)
if (psk === PRESHARED_AUTH_HEADER_VALUE) {
// Correct preshared header key supplied. Fetching request
// from origin
return fetch(request)
}
// Incorrect key rejecting request
return new Response('Sorry, you have supplied an invalid key.', {
status: 403,
})
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* @param {string} PRESHARED_AUTH_HEADER_KEY custom header to check for key
* @param {string} PRESHARED_AUTH_HEADER_VALUE hard coded key value
*/
const PRESHARED_AUTH_HEADER_KEY = 'X-Custom-PSK'
const PRESHARED_AUTH_HEADER_VALUE = 'mypresharedkey'
export {}
<file_sep>id = "scala_hello_world"
weight = 1
type = "boilerplate"
title = "Scala Hello World"
description = "Return a Hello World Response in Scala"
repository_url = "https://github.com/cloudflare/scala-worker-hello-world"
<file_sep>const OLD_URL = 'developer.mozilla.org'
const NEW_URL = 'mynewdomain.com'
async function handleRequest(req: Request): Promise<Response> {
const res = await fetch(req)
return rewriter.transform(res)
}
class AttributeRewriter {
attributeName: string
constructor(attributeName: string) {
this.attributeName = attributeName
}
element(element: Element) {
const attribute = element.getAttribute(this.attributeName)
if (attribute) {
element.setAttribute(
this.attributeName,
attribute.replace(OLD_URL, NEW_URL),
)
}
}
}
const rewriter = new HTMLRewriter()
.on('a', new AttributeRewriter('href'))
.on('img', new AttributeRewriter('src'))
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
export {}
<file_sep>id = "block_on_tls_version"
weight = 1
type = "snippet"
title = "Block on TLS Version"
description = "Inspects the incoming request's TLS version and blocks if under TLSv1.2."
tags = [ "Middleware" ]
<file_sep>const OLD_URL = 'developer.mozilla.org'
const NEW_URL = 'mynewdomain.com'
async function handleRequest(req) {
const res = await fetch(req)
return rewriter.transform(res)
}
class AttributeRewriter {
constructor(attributeName) {
this.attributeName = attributeName
}
element(element) {
const attribute = element.getAttribute(this.attributeName)
if (attribute) {
element.setAttribute(
this.attributeName,
attribute.replace(OLD_URL, NEW_URL),
)
}
}
}
const rewriter = new HTMLRewriter()
.on('a', new AttributeRewriter('href'))
.on('img', new AttributeRewriter('src'))
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
<file_sep>/**
* Define personal data with regular expressions
* Respond with block if credit card data, and strip
* emails and phone numbers from the response
* Execution will be limited to MIME type "text/*"
*/
async function handleRequest(request: Request): Promise<Response> {
const response = await fetch(request)
// Return origin response, if response wasn't text
const contentType = response.headers.get('content-type') || ''
if (!contentType.toLowerCase().includes('text/')) {
return response
}
let text = await response.text()
text = DEBUG
? // for testing only - replace the response from the origin with an email
text.replace('You may use this', '<EMAIL> may use this')
: text
const sensitiveRegexsMap: { [key: string]: string } = {
email: String.raw`\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b`,
phone: String.raw`\b07\d{9}\b`,
creditCard: String.raw`\b(?:4[0-9]{12}(?:[0-9]{3})?|(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})\b`,
}
for (const kind in sensitiveRegexsMap) {
const sensitiveRegex = new RegExp(sensitiveRegexsMap[kind], 'ig')
const match = await sensitiveRegex.test(text)
if (match) {
// alert a data breach by posting to a webhook server
await postDataBreach(request)
// respond with a block if credit card, else replace
// sensitive text with *'s
return kind === 'creditCard'
? new Response(kind + ' found\nForbidden\n', {
status: 403,
statusText: 'Forbidden',
})
: new Response(text.replace(sensitiveRegex, '**********'), response)
}
}
return new Response(text, response)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function postDataBreach(request: Request): Promise<Response> {
const trueClientIp = request.headers.get('cf-connecting-ip')
const epoch = new Date().getTime()
const body = {
ip: trueClientIp,
time: epoch,
request: request,
}
const init = {
body: JSON.stringify(body),
method: 'POST',
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}
return await fetch(SOME_HOOK_SERVER, init)
}
const SOME_HOOK_SERVER = 'https://webhook.flow-wolf.io/hook'
const DEBUG = true
export {}
<file_sep>id = "kotlin_hello_world"
weight = 1
type = "boilerplate"
title = "Kotlin Hello World"
description = "Return a Hello World Response in Kotlin"
repository_url = "https://github.com/cloudflare/kotlin-worker-hello-world"
<file_sep>async function handleRequest(request) {
// Fetch the original request
const response = await fetch(request)
// If it's an image, engage hotlink protection based on the
// Referer header.
const referer = request.headers.get('Referer')
const contentType = response.headers.get('Content-Type') || ''
if (referer && contentType.startsWith(PROTECTED_TYPE)) {
// If the hostnames don't match, it's a hotlink
if (new URL(referer).hostname !== new URL(request.url).hostname) {
// Redirect the user to your website
return Response.redirect(HOMEPAGE_URL, 302)
}
}
// Everything is fine, return the response normally.
return response
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
const HOMEPAGE_URL = 'https://tutorial.cloudflareworkers.com/'
const PROTECTED_TYPE = 'images/'
<file_sep>id = "binast_cf_worker"
weight = 1
type = "featured_boilerplate"
title = "Binast-Cf-Worker"
description = "Serve BinAST via a Cloudflare Worker"
repository_url = "https://github.com/xtuc/binast-cf-worker-template"
[demos.main]
text = "Demo"
url = "https://serve-binjs.that-test.site/"
tags = [ "Middleware" ]
<file_sep>async function handleRequest(request: Request): Promise<Response> {
if (!request.headers.has('authorization')) {
return getUnauthorizedResponse(
'Provide User Name and Password to access this page.',
)
}
const authorization = request.headers.get('authorization') || ''
const credentials = parseCredentials(authorization)
if (credentials[0] !== USERNAME || credentials[1] !== PASSWORD) {
return getUnauthorizedResponse(
'The User Name and Password combination you have entered is invalid.',
)
}
return await fetch(request)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Break down base64 encoded authorization string into plain-text username and password
* @param {string} authorization
* @returns {string[]}
*/
function parseCredentials(authorization: string): string[] {
const parts = authorization.split(' ')
const plainAuth = atob(parts[1])
const credentials = plainAuth.split(':')
return credentials
}
/**
* Helper function to generate Response object
* @param {string} message
* @returns {Response}
*/
function getUnauthorizedResponse(message: string): Response {
const response = new Response(message, {
status: 401,
})
response.headers.set('WWW-Authenticate', `Basic realm="${REALM}"`)
return response
}
/**
* @param {string} USERNAME User name to access the page
* @param {string} PASSWORD Password to access the page
* @param {string} REALM A name of an area (a page or a group of pages) to protect.
* Some browsers may show "Enter user name and password to access REALM"
*/
const USERNAME = 'demouser'
const PASSWORD = '<PASSWORD>'
const REALM = 'Secure Area'
export {}
<file_sep>id = "cors_header_proxy"
weight = 1
type = "snippet"
title = "CORS Header Proxy"
description = "Add necessary CORS headers to a third party API response"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#00ad8fc3ff55f6b740ed09470359dc0d:https://example.com/"
<file_sep>id = "webcrypto"
weight = 1
type = "snippet"
title = "WebCrypto Sign/Verify and Encrypt/Decrypt"
description = "Demonstrates the most common WebCrypto operations"
<file_sep>id = "sentry"
weight = 1
type = "featured_boilerplate"
title = "Sentry"
description = "Log exceptions and errors in your Workers application to Sentry.io - an error tracking tool"
repository_url = "https://github.com/bustle/cf-sentry"
tags = [ "Middleware" ]
<file_sep>id = "send_raw_json"
weight = 50
type = "snippet"
title = "Send Raw JSON"
description = "Renders a response of type `application/json` to the client"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#83bc6debecf1dd443d3fabfbde0d2b3a:https://example.com"
tags = [ "Originless" ]
<file_sep>async function handleRequest(request) {
const reqBody = await readRequestBody(request)
const retBody = `The request body sent in was ${reqBody}`
return new Response(retBody)
}
addEventListener('fetch', event => {
const { request } = event
const { url } = request
if (url.includes('form')) {
return event.respondWith(rawHtmlResponse(someForm))
}
if (request.method === 'POST') {
return event.respondWith(handleRequest(request))
} else if (request.method === 'GET') {
return event.respondWith(new Response(`The request was a GET`))
}
})
/**
* rawHtmlResponse delivers a response with HTML inputted directly
* into the worker script
* @param {string} html
*/
function rawHtmlResponse(html) {
const init = {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
}
return new Response(html, init)
}
/**
* readRequestBody reads in the incoming request body
* Use await readRequestBody(..) in an async function to get the string
* @param {Request} request the incoming request to read from
*/
async function readRequestBody(request) {
const { headers } = request
const contentType = headers.get('content-type') || ''
if (contentType.includes('application/json')) {
return JSON.stringify(await request.json())
} else if (contentType.includes('application/text')) {
return await request.text()
} else if (contentType.includes('text/html')) {
return await request.text()
} else if (contentType.includes('form')) {
const formData = await request.formData()
const body = {}
for (const entry of formData.entries()) {
body[entry[0]] = entry[1]
}
return JSON.stringify(body)
} else {
const myBlob = await request.blob()
const objectURL = URL.createObjectURL(myBlob)
return objectURL
}
}
const someForm = `
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<p>This is all generated using a Worker</p>
<form action="/demos/requests" method="post">
<div>
<label for="say">What do you want to say?</label>
<input name="say" id="say" value="Hi">
</div>
<div>
<label for="to">To who?</label>
<input name="to" id="to" value="Mom">
</div>
<div>
<button>Send my greetings</button>
</div>
</form>
</body>
</html>
`
<file_sep>account_id = "95e065d2e3f97a1e50bae58aea71df6d"
name = "template-registry"
type = "webpack"
workers_dev = true
[site]
bucket = "templates"
entry-point = "workers-site"
<file_sep>id = "private_data_loss"
weight = 1
type = "snippet"
title = "Data Loss Prevention"
description = "Prevent access to personal and sensitive data by inspecting response data from an origin server. In this example, sensitive data is defined by regexes for email, UK mobile number, or credit card number. If a match is detected, trigger a data breach alert and respond with either a block or the data stripped from the response."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#1b7ac657cfaec2635a319441800a5158:https://example.com/"
tags = [ "Middleware" ]
share_url = "/templates/snippets/private_data_loss"
<file_sep>const COOKIE_NAME = '__uid'
function handleRequest(request) {
const cookie = getCookie(request, COOKIE_NAME)
if (cookie) {
// respond with the cookie value
return new Response(cookie)
}
return new Response('No cookie with name: ' + COOKIE_NAME)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Grabs the cookie with name from the request headers
* @param {Request} request incoming Request
* @param {string} name of the cookie to grab
*/
function getCookie(request, name) {
let result = ''
const cookieString = request.headers.get('Cookie')
if (cookieString) {
const cookies = cookieString.split(';')
cookies.forEach(cookie => {
const cookieName = cookie.split('=')[0].trim()
if (cookieName === name) {
const cookieVal = cookie.split('=')[1]
result = cookieVal
}
})
}
return result
}
<file_sep>async function handleRequest(request: Request): Promise<Response> {
/**
* Response properties are immutable. To change them, construct a new
* Response, passing modified status or statusText in the ResponseInit
* object.
* Response Headers can be modified through the headers `set` method.
*/
const originalResponse = await fetch(request)
// Change status and statusText, but preserve body and headers
let response = new Response(originalResponse.body, {
status: 500,
statusText: 'some message',
headers: originalResponse.headers,
})
// Change response body by adding the foo prop
const originalBody = await originalResponse.json()
const body = JSON.stringify({ foo: 'bar', ...originalBody })
response = new Response(body, response)
// Add a header using set method
response.headers.set('foo', 'bar')
// Set destination header to the value of the source header
const src = response.headers.get(headerNameSrc)
if (src != null) {
response.headers.set(headerNameDst, src)
console.log(
`Response header "${headerNameDst}" was set to "${response.headers.get(
headerNameDst,
)}"`,
)
}
return response
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* @param {string} headerNameSrc the header to get the new value from
* @param {string} headerNameDst the header to set based off of value in src
*/
const headerNameSrc = 'foo' //'Orig-Header'
const headerNameDst = 'Last-Modified'
export {}
<file_sep>id = "bulk_origin_proxies"
weight = 1
type = "snippet"
title = "Bulk Origin Proxies"
description = "Resolve requests to your domain to a set of proxy third-party origins"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#545c79e098708ca658dcbdb860c5021a:https://starwarsapi.yourdomain.com/"
share_url = "/templates/snippets/bulk_origin_proxies"
<file_sep>id = "speedtest_worker"
weight = 1
type = "featured_boilerplate"
title = "Speedtest"
description = "Measure download / upload connection speed from the client side, using the Performance Timing API"
repository_url = "https://github.com/cloudflare/worker-speedtest-template"
<file_sep>async function handleRequest(request: Request): Promise<Response> {
const reqBody = await readRequestBody(request)
const retBody = `The request body sent in was ${reqBody}`
return new Response(retBody)
}
addEventListener('fetch', event => {
const { request } = event
const { url } = request
if (url.includes('form')) {
return event.respondWith(rawHtmlResponse(someForm))
}
if (request.method === 'POST') {
return event.respondWith(handleRequest(request))
} else if (request.method === 'GET') {
return event.respondWith(new Response(`The request was a GET`))
}
})
/**
* rawHtmlResponse delivers a response with HTML inputted directly
* into the worker script
* @param {string} html
*/
function rawHtmlResponse(html: string): Response {
const init = {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
}
return new Response(html, init)
}
/**
* readRequestBody reads in the incoming request body
* Use await readRequestBody(..) in an async function to get the string
* @param {Request} request the incoming request to read from
*/
async function readRequestBody(request: Request): Promise<string> {
const { headers } = request
const contentType = headers.get('content-type') || ''
if (contentType.includes('application/json')) {
return JSON.stringify(await request.json())
} else if (contentType.includes('application/text')) {
return await request.text()
} else if (contentType.includes('text/html')) {
return await request.text()
} else if (contentType.includes('form')) {
const formData = await request.formData()
const body: { [key: string]: FormDataEntryValue } = {}
for (const entry of formData.entries()) {
body[entry[0]] = entry[1]
}
return JSON.stringify(body)
} else {
const myBlob = await request.blob()
const objectURL = URL.createObjectURL(myBlob)
return objectURL
}
}
const someForm = `
<!DOCTYPE html>
<html>
<body>
<h1>Hello World</h1>
<p>This is all generated using a Worker</p>
<form action="/demos/requests" method="post">
<div>
<label for="say">What do you want to say?</label>
<input name="say" id="say" value="Hi">
</div>
<div>
<label for="to">To who?</label>
<input name="to" id="to" value="Mom">
</div>
<div>
<button>Send my greetings</button>
</div>
</form>
</body>
</html>
`
export {}
<file_sep>id = "hello_world"
weight = 99
type = "boilerplate"
title = "Hello World"
description = "Simple Hello World in JS"
repository_url = "https://github.com/cloudflare/worker-template"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#6626eb50f7b53c2d42b79d1082b9bd37:https://tutorial.cloudflareworkers.com"
tags = [ "Originless" ]
<file_sep>async function handleRequest(event: FetchEvent): Promise<Response> {
let response
try {
response = await fetch(event.request)
if (!response.ok) {
const body = await response.text()
throw new Error(
'Bad response at origin. Status: ' +
response.status +
' Body: ' +
//ensures the string is small enough to be a header
body.trim().substring(0, 10),
)
}
} catch (err) {
// Without event.waitUntil(), our fetch() to our logging service may
// or may not complete.
event.waitUntil(postLog((err as Error).toString()))
const stack = JSON.stringify(err.stack) || err
// Copy the response and initialize body to the stack trace
response = new Response(stack, response)
// Shove our rewritten URL into a header to find out what it was.
response.headers.set('X-Debug-stack', stack)
response.headers.set('X-Debug-err', err)
}
return response
}
addEventListener('fetch', event => {
//Have any uncaught errors thrown go directly to origin
event.passThroughOnException()
event.respondWith(handleRequest(event))
})
function postLog(data: string) {
return fetch(LOG_URL, {
method: 'POST',
body: data,
})
}
// Service configured to receive logs
const LOG_URL = 'https://log-service.example.com/'
export {}
<file_sep>async function handleRequest() {
const init = {
headers: {
'content-type': type,
},
}
const responses = await Promise.all([fetch(url1, init), fetch(url2, init)])
const results = await Promise.all([
gatherResponse(responses[0]),
gatherResponse(responses[1]),
])
return new Response(results.join(), init)
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest())
})
/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/
async function gatherResponse(response) {
const { headers } = response
const contentType = headers.get('content-type') || ''
if (contentType.includes('application/json')) {
return JSON.stringify(await response.json())
} else if (contentType.includes('application/text')) {
return await response.text()
} else if (contentType.includes('text/html')) {
return await response.text()
} else {
return await response.text()
}
}
/**
* Example someHost is set up to return JSON responses
* Replace url1 and url2 with the hosts you wish to
* send requests to
* @param {string} url the URL to send the request to
*/
const someHost = 'https://workers-tooling.cf/demos'
const url1 = someHost + '/requests/json'
const url2 = someHost + '/requests/json'
const type = 'application/json;charset=UTF-8'
<file_sep>id = "conditional_response"
weight = 60
type = "snippet"
title = "Conditional Response"
description = "Return a response based on the incoming request's URL, HTTP method, User Agent, IP address, ASN or device type (e.g. mobile)"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#cec6695f67232bc76e3f396fcb2d5cc7:https://nope.mywebsite.com/"
tags = [ "Enterprise" ]
share_url = "/templates/snippets/conditional_response"
<file_sep>async function handleRequest() {
const init = {
headers: {
'content-type': 'application/json;charset=UTF-8',
},
}
return new Response(JSON.stringify(someJSON), init)
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest())
})
const someJSON = {
result: ['some', 'results'],
errors: null,
msg: 'this is some random json',
}
export {}
<file_sep>import * as toml from 'toml'
//relative paths of the stored data (e.g. folders in ../templates)
const META_DATA_PATH = 'meta_data'
const JS_PATH = 'javascript'
declare global {
var __STATIC_CONTENT: any, __STATIC_CONTENT_MANIFEST: any
}
class CustomError extends Error {
constructor(status: number, message?: string) {
super(message) // 'Error' breaks prototype chain here
this.status = status
Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain
}
code: number
message: string
status: number
}
/**
* The DEBUG flag will do two things that help during development:
* 1. we will skip caching on the edge, which makes it easier to
* debug.
* 2. we will return an error message on exception in your Response rather
* than the default 404.html page.
*/
const DEBUG = true
addEventListener('fetch', (event: FetchEvent) => {
event.respondWith(handleEvent(event))
})
async function handleEvent(event: FetchEvent): Promise<Response> {
try {
const url: string = event.request.url
let jsonResponse
let path = new URL(url).pathname
if (new RegExp(/^\/templates\/*$/).test(path)) {
jsonResponse = await grabTemplates()
} else if (new RegExp(/^\/templates\/\w+$/).test(path)) {
let id = getIDFromPath(path)
const key = formTomlKey(id)
const jsonData = await grabTemplate(key)
jsonResponse = new Response(JSON.stringify(jsonData))
} else {
return new Response('Not a valid endpoint ' + path + ' e.g. /templates/ab_testing is valid', {
status: 404,
})
}
return jsonResponse
} catch (e) {
if (DEBUG) {
return new Response(e.stack, {
status: 500,
})
}
}
}
/**
* Looks for all the keys in __STATIC_CONTENT_MANIFEST
* and then locates and serves the TOML files
* from __STATIC_CONTENT */
async function grabTemplates(): Promise<Response> {
const manifest = JSON.parse(__STATIC_CONTENT_MANIFEST)
const allKeys = Object.keys(manifest).filter(key => key.includes('.toml'))
let results = []
for (const key of allKeys) {
// const allTomls = allKeys.reduce(async key => {
const id = getIDFromKey(key)
try {
const jsonData = await grabTemplate(key)
results.push(jsonData)
} catch (e) {
console.log('e', e)
new Response(JSON.stringify(e)) //, e.status)
}
}
return new Response(JSON.stringify(results))
}
/**
* Same as grabTemplates but for individual template
* @param key the file path to the toml
*/
async function grabTemplate(key: string): Promise<Object> {
const manifest = JSON.parse(__STATIC_CONTENT_MANIFEST)
const tomlData = await __STATIC_CONTENT.get(manifest[key])
if (!tomlData) {
throw new CustomError(404, 'Key ' + key + ' not Found')
}
const jsonData = toml.parse(tomlData)
// grab the javascript file if it exists from templates/javascript/:id.js
const jsKey = formJsKey(getIDFromKey(key))
const jsData = await __STATIC_CONTENT.get(manifest[jsKey])
if (jsData) {
jsonData.code = jsData
}
return jsonData
}
const formTomlKey = (id: string) => META_DATA_PATH + '/' + id + '.toml'
const formJsKey = (id: string) => JS_PATH + '/' + id + '.js'
/**
* Takes a URL path and gives the :id
* @param path a URL path (e.g. /templates/:id)
*/
const getIDFromPath = (path: string) => {
let fileName =
path.search(/^\/templates\/[\w]+$/) !== -1 ? path.match(/^\/templates\/\w+$/)[0] : ''
return fileName.replace('/templates/', '')
}
/**
* Takes in a file key and returns the IF
* @param key the KV / filepath key (e.g. javascript/:id.js)
*/
const getIDFromKey = (key: string) => {
let fileName = key.search(/\/\w+\.\w+$/) !== -1 ? key.match(/[\/|\w]+\.\w+$/)[0] : ''
return fileName
.replace('.toml', '')
.replace('.js', '')
.replace(JS_PATH + '/', '')
.replace(META_DATA_PATH + '/', '')
}
<file_sep>// NOTE Requires ESM through webpack project type
const crypto = require('crypto')
const SECRET = 'SECRET_KEY'
async function handleRequest(request) {
let signed = await checkSignature(request)
if (signed) {
let responseBody = 'Hello worker!'
return await signResponse(responseBody, new Response(responseBody))
} else {
return new Response('Request not signed', { status: 400 })
}
}
addEventListener('fetch', event => {
console.log(createHexSignature('asd'))
event.respondWith(handleRequest(event.request))
})
async function createHexSignature(requestBody) {
let hmac = crypto.createHmac('sha256', SECRET)
hmac.update(requestBody)
return hmac.digest('hex')
}
async function checkSignature(request) {
// hash request with secret key
let expectedSignature = await createHexSignature(await request.text())
let actualSignature = await request.headers.get('signature')
// check that hash matches signature
return expectedSignature === actualSignature
}
async function signResponse(responseBody, response) {
// create signature
const signature = await createHexSignature(responseBody)
response.headers.set('signature', signature)
//add header with signature
return response
}
<file_sep>id = "send_raw_html"
weight = 1
type = "snippet"
title = "Send Raw HTML"
share_url = "/templates/snippets/send_raw_html"
description = "Delivers an HTML page from HTML directly in the Worker script."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#ba06ef26637ab98b1f38a18dc527dc69:https://example.com"
tags = [ "Originless" ]
<file_sep>async function handleRequest() {
const init = {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
}
const response = await fetch(url, init)
const results = await gatherResponse(response)
return new Response(results, init)
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest())
})
/**
* gatherResponse awaits and returns a response body as a string.
* Use await gatherResponse(..) in an async function to get the response body
* @param {Response} response
*/
async function gatherResponse(response) {
const { headers } = response
const contentType = headers.get('content-type') || ''
if (contentType.includes('application/json')) {
return JSON.stringify(await response.json())
} else if (contentType.includes('application/text')) {
return await response.text()
} else if (contentType.includes('text/html')) {
return await response.text()
} else {
return await response.text()
}
}
/**
* Example someHost at url is set up to respond with HTML
* Replace url with the host you wish to send requests to
*/
const someHost = 'https://workers-tooling.cf/demos'
const url = someHost + '/static/html'
<file_sep># Rust Style Guide
If you are using Wasm and write in Rust, your template should adhere to rustfmt and clippy.
## Configuring rustfmt
Before submitting code in a PR, make sure that you have formatted the codebase
using [rustfmt][rustfmt]. `rustfmt` is a tool for formatting Rust code, which
helps keep style consistent across the project. If you have not used `rustfmt`
before, here's how to get setup:
**1. Use Stable Toolchain**
Use the `rustup override` command to make sure that you are using the stable
toolchain. Run this command in the `cargo-generate` directory you cloned.
```sh
rustup override set stable
```
**2. Add the rustfmt component**
Install the most recent version of `rustfmt` using this command:
```sh
rustup component add rustfmt-preview --toolchain stable
```
**3. Running rustfmt**
To run `rustfmt`, use this command:
```sh
cargo +stable fmt
```
[rustfmt]: https://github.com/rust-lang-nursery/rustfmt
<file_sep>function handleRequest(request) {
const NAME = 'experiment-0'
// The Responses below are placeholders. You can set up a custom path for each test (e.g. /control/somepath ).
const TEST_RESPONSE = new Response('Test group') // e.g. await fetch('/test/sompath', request)
const CONTROL_RESPONSE = new Response('Control group') // e.g. await fetch('/control/sompath', request)
// Determine which group this requester is in.
const cookie = request.headers.get('cookie')
if (cookie && cookie.includes(`${NAME}=control`)) {
return CONTROL_RESPONSE
} else if (cookie && cookie.includes(`${NAME}=test`)) {
return TEST_RESPONSE
} else {
// If there is no cookie, this is a new client. Choose a group and set the cookie.
const group = Math.random() < 0.5 ? 'test' : 'control' // 50/50 split
const response = group === 'control' ? CONTROL_RESPONSE : TEST_RESPONSE
response.headers.append('Set-Cookie', `${NAME}=${group}; path=/`)
return response
}
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
<file_sep>async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url)
// Only use the path for the cache key, removing query strings
// and always storing HTTPS e.g. https://www.example.com/file-uri-here
const someCustomKey = `https://${url.hostname}${url.pathname}`
let response = await fetch(request, {
cf: {
// Tell Cloudflare's CDN to always cache this fetch regardless of content type
// for a max of 5 seconds before revalidating the resource
cacheTtl: 5,
cacheEverything: true,
//Enterprise only feature, see Cache API for other plans
cacheKey: someCustomKey,
},
})
// Reconstruct the Response object to make its headers mutable.
response = new Response(response.body, response)
//Set cache control headers to cache on browser for 25 minutes
response.headers.set('Cache-Control', 'max-age=1500')
return response
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest(event.request))
})
export {}
<file_sep>async function handleRequest(event) {
const request = event.request
const cacheUrl = new URL(request.url)
// hostname for a different zone
cacheUrl.hostname = someOtherHostname
const cacheKey = new Request(cacheUrl.toString(), request)
const cache = caches.default
// Get this request from this zone's cache
let response = await cache.match(cacheKey)
if (!response) {
//if not in cache, grab it from the origin
response = await fetch(request)
// must use Response constructor to inherit all of response's fields
response = new Response(response.body, response)
// Cache API respects Cache-Control headers, so by setting max-age to 10
// the response will only live in cache for max of 10 seconds
response.headers.append('Cache-Control', 'max-age=10')
// store the fetched response as cacheKey
// use waitUntil so computational expensive tasks don't delay the response
event.waitUntil(cache.put(cacheKey, response.clone()))
}
return response
}
async function handlePostRequest(event) {
const request = event.request
const body = await request.clone().text()
const hash = await sha256(body)
const cacheUrl = new URL(request.url)
// get/store the URL in cache by prepending the body's hash
cacheUrl.pathname = '/posts' + cacheUrl.pathname + hash
// Convert to a GET to be able to cache
const cacheKey = new Request(cacheUrl.toString(), {
headers: request.headers,
method: 'GET',
})
const cache = caches.default
//try to find the cache key in the cache
let response = await cache.match(cacheKey)
// otherwise, fetch response to POST request from origin
if (!response) {
response = await fetch(request)
event.waitUntil(cache.put(cacheKey, response))
}
return response
}
addEventListener('fetch', event => {
try {
const request = event.request
if (request.method.toUpperCase() === 'POST')
return event.respondWith(handlePostRequest(event))
return event.respondWith(handleRequest(event))
} catch (e) {
return event.respondWith(new Response('Error thrown ' + e.message))
}
})
async function sha256(message) {
// encode as UTF-8
const msgBuffer = new TextEncoder().encode(message)
// hash the message
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer)
// convert ArrayBuffer to Array
const hashArray = Array.from(new Uint8Array(hashBuffer))
// convert bytes to hex string
const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('')
return hashHex
}
const someOtherHostname = 'my.herokuapp.com'
<file_sep># Template Registry
This repo runs a simple API via a Worker that serves all the template content consumed by different services (e.g. our template gallery at developers.cloudflare.com/workers/templates).
## API
The API is a Cloudflare Worker that lives in [workers-site](./workers-site). That uses KV to store the toml/JS data and parses the data for the appropriate endpoints
## Data
All the content that is served from the API lives in [templates](./templates)
To contribute see [CONTRIBUTING](./CONTRIBUTING.md)
## Get Started
To run for development
```
npm install
```
```
npm run start
```
Then in the Workers preview test a link like https://example.com/templates/ or https://example.com/templates/ab_testing
<file_sep>id = "modify_res_props"
weight = 1
type = "snippet"
title = "Modify Response"
description = "Recommended practice for mutating a fetched [response](/workers/reference/apis/response). First, fetches a request then modifies specific properties which are immutable: `status`, `statusText`, `headers` and `body`."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#daf0e96ae0ff4ce3f103c14bf6d968df:http://workers-tooling.cf/demos/static/json"
tags = [ "Middleware" ]
<file_sep>id = "python_hello_world"
weight = 1
type = "boilerplate"
title = "Python Hello World"
description = "Return a Hello World Response in Python"
repository_url = "https://github.com/cloudflare/python-worker-hello-world"
<file_sep>id = "alter_headers"
weight = 1
type = "snippet"
title = "Alter Headers"
description = "Change the headers sent in a request or returned in a response"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#5386d315ec8c899370e8e5d00cf88939:https://tutorial.cloudflareworkers.com"
share_url = "/templates/snippets/alter_headers"
<file_sep>id = "cache_api"
weight = 1
type = "snippet"
title = "Cache API"
description = "Cache using Cloudflare's [Cache API](/workers/reference/apis/cache/). This example can cache POST requests as well as change what hostname to store a response in cache. Note the previewer is not available for using Cache API."
tags = [ "Middleware" ]
<file_sep>async function handleRequest(request) {
const url = new URL(request.url)
// Only use the path for the cache key, removing query strings
// and always storing HTTPS e.g. https://www.example.com/file-uri-here
const someCustomKey = `https://${url.hostname}${url.pathname}`
let response = await fetch(request, {
cf: {
// Tell Cloudflare's CDN to always cache this fetch regardless of content type
// for a max of 5 seconds before revalidating the resource
cacheTtl: 5,
cacheEverything: true,
//Enterprise only feature, see Cache API for other plans
cacheKey: someCustomKey,
},
})
// Reconstruct the Response object to make its headers mutable.
response = new Response(response.body, response)
//Set cache control headers to cache on browser for 25 minutes
response.headers.set('Cache-Control', 'max-age=1500')
return response
}
addEventListener('fetch', event => {
return event.respondWith(handleRequest(event.request))
})
<file_sep>id = "redirect"
weight = 1
type = "snippet"
title = "Redirect"
description = "Redirect a request by sending a 301 or 302 HTTP response"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#ab385d4c4e43608684889eaa390d4218:https://example.com/"
<file_sep>async function handleRequest(request: Request): Promise<Response> {
const url = new URL(request.url)
let apiUrl = url.searchParams.get('apiurl')
if (apiUrl == null) {
apiUrl = API_URL
}
// Rewrite request to point to API url. This also makes the request mutable
// so we can add the correct Origin header to make the API server think
// that this request isn't cross-site.
request = new Request(apiUrl, request)
request.headers.set('Origin', new URL(apiUrl).origin)
let response = await fetch(request)
// Recreate the response so we can modify the headers
response = new Response(response.body, response)
// Set CORS headers
response.headers.set('Access-Control-Allow-Origin', url.origin)
// Append to/Add Vary header so browser will cache response correctly
response.headers.append('Vary', 'Origin')
return response
}
function handleOptions(request: Request): Response {
// Make sure the necessary headers are present
// for this to be a valid pre-flight request
if (
request.headers.get('Origin') !== null &&
request.headers.get('Access-Control-Request-Method') !== null &&
request.headers.get('Access-Control-Request-Headers') !== null
) {
// Handle CORS pre-flight request.
// If you want to check the requested method + headers
// you can do that here.
return new Response(null, {
headers: corsHeaders,
})
} else {
// Handle standard OPTIONS request.
// If you want to allow other HTTP Methods, you can do that here.
return new Response(null, {
headers: {
Allow: 'GET, HEAD, POST, OPTIONS',
},
})
}
}
addEventListener('fetch', event => {
const request = event.request
const url = new URL(request.url)
if (url.pathname.startsWith(PROXY_ENDPOINT)) {
if (request.method === 'OPTIONS') {
// Handle CORS preflight requests
event.respondWith(handleOptions(request))
} else if (
request.method === 'GET' ||
request.method === 'HEAD' ||
request.method === 'POST'
) {
// Handle requests to the API server
event.respondWith(handleRequest(request))
} else {
event.respondWith(
new Response(null, {
status: 405,
statusText: 'Method Not Allowed',
}),
)
}
} else {
// Serve demo page
event.respondWith(rawHtmlResponse(DEMO_PAGE))
}
})
// We support the GET, POST, HEAD, and OPTIONS methods from any origin,
// and accept the Content-Type header on requests. These headers must be
// present on all responses to all CORS requests. In practice, this means
// all responses to OPTIONS requests.
const corsHeaders = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
}
// The URL for the remote third party API you want to fetch from
// but does not implement CORS
const API_URL = 'https://workers-tooling.cf/demos/demoapi'
// The endpoint you want the CORS reverse proxy to be on
const PROXY_ENDPOINT = '/corsproxy/'
// The rest of this snippet for the demo page
async function rawHtmlResponse(html: string): Promise<Response> {
return new Response(html, {
headers: {
'content-type': 'text/html;charset=UTF-8',
},
})
}
const DEMO_PAGE = `
<!DOCTYPE html>
<html>
<body>
<h1>API GET without CORS Proxy</h1>
<a target='_blank' href='https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful'>Shows TypeError: Failed to fetch since CORS is misconfigured</a>
<p id='noproxy-status'/>
<code id='noproxy'>Waiting</code>
<h1>API GET with CORS Proxy</h1>
<p id='proxy-status'/>
<code id='proxy'>Waiting</code>
<h1>API POST with CORS Proxy + Preflight</h1>
<p id='proxypreflight-status'/>
<code id='proxypreflight'>Waiting</code>
<script>
let reqs = {};
reqs.noproxy = async () => {
let response = await fetch('${API_URL}')
return await response.json()
}
reqs.proxy = async () => {
let response = await fetch(window.location.origin + '${PROXY_ENDPOINT}?apiurl=${API_URL}')
return await response.json()
}
reqs.proxypreflight = async () => {
const reqBody = {
msg: "Hello world!"
}
let response = await fetch(window.location.origin + '${PROXY_ENDPOINT}?apiurl=${API_URL}', {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(reqBody),
})
return await response.json()
}
(async () => {
for (const [reqName, req] of Object.entries(reqs)) {
try {
let data = await req()
document.getElementById(reqName).innerHTML = JSON.stringify(data)
} catch (e) {
document.getElementById(reqName).innerHTML = e
}
}
})()
</script>
</body>
</html>`
export {}
<file_sep>async function handleRequest(request: Request): Promise<Response> {
// Make the headers mutable by re-constructing the Request.
request = new Request(request)
request.headers.set('x-my-header', 'custom value')
const URL = 'https://workers-tooling.cf/demos/static/html'
// URL is set up to respond with dummy HTML, remove to send requests to your own origin
let response = await fetch(URL, request)
// Make the headers mutable by re-constructing the Response.
response = new Response(response.body, response)
response.headers.set('x-my-header', 'custom value')
return response
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
export {}
<file_sep>id = "cobol"
weight = 1
type = "boilerplate"
title = "COBOL"
description = "Return a Hello World Response in COBOL"
repository_url = "https://github.com/cloudflare/cobol-worker-template"
tags = [ "Wasm" ]
<file_sep>id = "img_color_worker"
weight = 1
type = "featured_boilerplate"
title = "Img-Color-Worker"
description = "Retrieve the dominant color of a PNG or JPEG image"
repository_url = "https://github.com/xtuc/img-color-worker"
tags = [ "Middleware" ]
<file_sep>id = "cookie_extract"
weight = 1
type = "snippet"
title = "Extract Cookie Value"
description = "Extracts the value of a cookie, given the cookie name."
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#605946f0f09b396361d3dadb5abf29c8:https://tutorial.cloudflareworkers.com/"
share_url = "/templates/snippets/cookie_extract"
<file_sep>async function handleRequest(request: Request): Promise<Response> {
return redirect(request)
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Returns a redirect determined by the country code
* @param {Request} request
*/
async function redirect(request: Request): Promise<Response> {
// The `cf-ipcountry` header is not supported in the preview
const country = request.headers.get('cf-ipcountry')
if (country != null && country in countryMap) {
const url = countryMap[country]
return Response.redirect(url)
} else {
return await fetch(request)
}
}
/**
* A map of the URLs to redirect to
* @param {Object} countryMap
*/
const countryMap: { [key: string]: string } = {
US: 'https://example.com/us',
EU: 'https://eu.example.com/',
}
export {}
<file_sep>id = "router"
type = "boilerplate"
title = "Router"
description = "Selects the logic based on the `request` method and URL. Use with REST APIs or apps that require routing logic."
repository_url = "https://github.com/cloudflare/worker-template-router"
url = "/templates/boilerplates/router"
weight = 97
share_url = "/templates/boilerplates/router"
[demos.bar]
text = "Demo /bar"
url = "https://cloudflareworkers.com/#6cbbd3ae7d4e928da3502cb9ce11227a:https://tutorial.cloudflareworkers.com/bar"
[demos.foo]
text = "Demo /foo"
url = "https://cloudflareworkers.com/#6cbbd3ae7d4e928da3502cb9ce11227a:https://tutorial.cloudflareworkers.com/foo"
<file_sep>id = "aggregate_requests"
weight = 20
type = "snippet"
title = "Aggregate Requests"
description = "Sends two GET request to two urls and aggregates the responses into one response."
share_url = "/templates/snippets/aggregate_requests"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#eaaa52283784c21aec989c64b9db32d3:https://example.com"
tags = [ "Middleware" ]
<file_sep>async function handleRequest(request) {
const psk = request.headers.get(PRESHARED_AUTH_HEADER_KEY)
if (psk === PRESHARED_AUTH_HEADER_VALUE) {
// Correct preshared header key supplied. Fetching request
// from origin
return fetch(request)
}
// Incorrect key rejecting request
return new Response('Sorry, you have supplied an invalid key.', {
status: 403,
})
}
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* @param {string} PRESHARED_AUTH_HEADER_KEY custom header to check for key
* @param {string} PRESHARED_AUTH_HEADER_VALUE hard coded key value
*/
const PRESHARED_AUTH_HEADER_KEY = 'X-Custom-PSK'
const PRESHARED_AUTH_HEADER_VALUE = 'mypresharedkey'
<file_sep>async function handleRequest(request: Request): Promise<Response> {
const requestURL = new URL(request.url)
const path = requestURL.pathname.split('/redirect')[1]
const location = redirectMap.get(path)
if (location) {
return Response.redirect(location, 301)
}
// If in map, return the original request
return fetch(request)
}
addEventListener('fetch', async event => {
event.respondWith(handleRequest(event.request))
})
const externalHostname = 'workers-tooling.cf'
const redirectMap = new Map([
['/bulk1', 'https://' + externalHostname + '/redirect2'],
['/bulk2', 'https://' + externalHostname + '/redirect3'],
['/bulk3', 'https://' + externalHostname + '/redirect4'],
['/bulk4', 'https://google.com'],
])
export {}
<file_sep>id = "signed_request"
weight = 10
type = "snippet"
title = "Signed Request/Response"
description = "Check signatures of requests and sign responses with a private key"
share_url = "/templates/snippets/signed_request"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/?hide_editor#c22ea0102fb9dced927a9b870e9c546a:https://example.com/"
<file_sep>id = "sites"
weight = 1
type = "featured_boilerplate"
title = "Worker Sites"
description = "Get started with Workers Sites to easily deploy static assets to the Cloudflare edge."
repository_url = "https://github.com/cloudflare/worker-sites-template"
tags = [ "Originless" ]
share_url = "/sites/start-from-scratch"
<file_sep>id = "graphql_server"
type = "featured_boilerplate"
title = "Apollo GraphQL Server"
weight = 2
description = "🔥Lightning-fast, globally distributed Apollo GraphQL server, deployed at the edge using Cloudflare Workers."
repository_url = "https://github.com/signalnerve/workers-graphql-server"
share_url = "/templates/featured_boilerplates/graphql"
[demos.main]
text = "Demo"
url = "https://workers-graphql.signalnerve.workers.dev/___graphql"
<file_sep>/**
* Parses the toml files located in templates/meta_data and takes the JS in
* 'code' field and placing it in templates/javascript
*/
const fs = require('fs')
//requiring path and fs modules
const path = require('path')
const toml = require('toml')
const TOML = require('@iarna/toml')
//joining path of directory
const DIRECTORYPATH = path.join(__dirname, 'templates/meta_data')
const JSDIRECTORYPATH = path.join(__dirname, 'templates/javascript')
const createFile = (filePath, content) => {
// write to a new file named 2pac.txt
fs.writeFile(filePath, content, err => {
// throws an error, you could also catch it here
if (err) throw err
console.log('Content saved!')
})
}
//read in all the toml files
fs.readdir(DIRECTORYPATH, function(err, files) {
if (err) {
return console.log('Unable to scan directory: ' + err)
}
files.forEach(function(file) {
const filePath = DIRECTORYPATH + '/' + file
const jsFilePath = JSDIRECTORYPATH + '/' + file.replace('.toml', '.js')
// Do whatever you want to do with the file
fs.readFile(filePath, (err, data) => {
if (err) throw err
jsonData = toml.parse(data.toString())
if (jsonData.code) {
createFile(jsFilePath, jsonData.code)
}
delete jsonData.code
const tomlData = TOML.stringify(jsonData)
createFile(filePath, tomlData)
})
})
})
<file_sep>id = "rewrite_links_html"
weight = 1
type = "snippet"
title = "Rewrite links in HTML"
description = "Rewrite URL links in HTML using [HTMLRewriter](/workers/reference/apis/html-rewriter)"
<file_sep>id = "emscripten"
weight = 1
type = "featured_boilerplate"
title = "Emscripten + Wasm Image Resizer"
description = "Image Resizer in C compiled to Wasm with Emscripten"
repository_url = "https://github.com/cloudflare/worker-emscripten-template"
[demos.main]
text = "Demo"
url = "https://cloudflareworkers.com/#ddb7fa39e09cdf734180c5d083ddb390:http://placehold.jp/1200x800.png"
tags = [ "Wasm" ]
<file_sep>"use strict";
async function handleRequest() {
let msg = "alice and bob";
let hmacresult = await generateSignandVerify({
name: "HMAC",
hash: "sha-256"
});
console.log("Result of HMAC generate, sign, verify: ", hmacresult);
let aesresult = await generateEncryptDecrypt({
name: "AES-GCM",
length: 256
}, msg);
var dec = new TextDecoder();
if (msg == dec.decode(aesresult)) {
console.log("AES encrypt decrypt successful");
}
else {
console.log("AES encrypt decrypt failed");
}
return new Response();
}
addEventListener('fetch', event => {
event.respondWith(handleRequest());
});
async function generateSignandVerify(algorithm) {
let rawMessage = "alice and bob";
let key = await self.crypto.subtle.generateKey(algorithm, true, ["sign", "verify"]);
let enc = new TextEncoder();
let encoded = enc.encode(rawMessage);
let signature = await self.crypto.subtle.sign(algorithm, key, encoded);
let result = await self.crypto.subtle.verify(algorithm, key, signature, encoded);
return result;
}
async function generateEncryptDecrypt(algorithm, msg) {
let key = await self.crypto.subtle.generateKey(algorithm, true, ["encrypt", "decrypt"]);
let enc = new TextEncoder();
let encoded = enc.encode(msg);
algorithm.iv = crypto.getRandomValues(new Uint8Array(16));
let signature = await self.crypto.subtle.encrypt(algorithm, key, encoded);
let result = await self.crypto.subtle.decrypt(algorithm, key, signature);
return result;
}
<file_sep>{
"compilerOptions": {
"outDir": "./dist",
"noImplicitAny": true,
"target": "es5",
"allowJs": false,
"lib": ["webworker", "es7"]
},
"include": ["./*.ts", "./**/*.ts", "./test/**/*.ts", "./test/*.ts", "./types.d.ts"],
"exclude": ["node_modules/", "dist/"]
}
|
3ebf985c02448fbc6b1abf2794e43879d2d35f2e
|
[
"Markdown",
"TOML",
"JavaScript",
"JSON with Comments",
"TypeScript",
"Shell"
] | 107 |
TypeScript
|
cloudflare/template-registry
|
00579299522834961fb46375dd7e8fd7923e81b0
|
d9b1c5eef122c2a8eff667c2886b49253987fcfe
|
refs/heads/main
|
<file_sep>//Maneira convencional
$(document).ready(function() {
//Armazenando a classe active dentro de váriavel
var classActive = 'active';
//Adicionando ao primeiro link e conteudo a classe 'active'
$('.animais .tab-menu a').first().addClass(classActive);
$('.animais .item').first().addClass(classActive);
//Adicionando evento de click aos links
$('.animais .tab-menu a').click(function(e) {
//Prevenindo ação
e.preventDefault();
//Armazenando valor de href para o link interno
var itemId = $(this).attr('href');
//Removendo a classe ativa de todos os links e conteudos
$('.animais .tab-menu a, .animais .item').removeClass(classActive);
//Adicionando a classe ativa ao link clicado e ao seu devido conteudo
$(this).addClass(classActive);
$(itemId).addClass(classActive);
});
$('.florestas .tab-menu a').first().addClass(classActive);
$('.florestas .item').first().addClass(classActive);
$('.florestas .tab-menu a').click(function(e) {
e.preventDefault();
var itemId = $(this).attr('href');
$('.florestas .tab-menu a, .florestas .item').removeClass(classActive);
$(this).addClass(classActive);
$(itemId).addClass(classActive);
});
});
//Maneira otimizada
//A cada grupo data-group --- armazenar em variaveis os conteudos (target) e links (clicks)
$('[data-group]').each(function() {
var $allTarget = $(this).find('[data-target]'),
$allClick = $(this).find('[data-click]'),
activeClass = 'active';
$allTarget.first().addClass(activeClass);
$allClick.first().addClass(activeClass);
$allClick.click(function(e) {
e.preventDefault();
var id = $(this).data('click'),
$target = $('[data-target="' + id + '"]')
$allClick.removeClass(activeClass);
$allTarget.removeClass(activeClass);
$target.addClass(activeClass);
$(this).addClass(activeClass);
})
});<file_sep># Animais-e-Floresta
Projeto utilizando a biblioteca JQuery para eventos de clicks e transições
Foi utilizado duas maneiras diferentes de fazer os eventos. Uma de forma composta e outra de forma otimizada
|
c41a560fe6dca9115d83ec77e8efb8b44590786d
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
ThomasMoraes02/Animais-e-Floresta
|
9c04152fe0a6d5c594c64c02ca420f82e1619c70
|
541971afd6c0c50ab52fb31fca1e1c47dfa03ad8
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.