text
stringlengths 184
4.48M
|
---|
//! This is how you create modules with submodules.
//! Create a folder with the name of the module,
//! create a `mod.rs`-file, then declare the modules connected to that.
//! This file is the entry-point for the module.
//! There are other ways to do this which you can read in the documentation.
//! `use` the modules to re-export them for better ergonomics at the use-site.
// Here we make the module public but only within the crate.
pub(crate) mod exercise1;
pub(crate) mod exercise2;
pub(crate) mod exercise3;
pub(crate) mod exercise4;
pub(crate) mod exercise5;
|
import {
Body,
Controller,
HttpException,
HttpStatus,
Post,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { SignUpDto } from './dtos/signup.dto';
import { LoginDto } from './dtos/login.dto';
import { EmailAlreadyExistsException } from '@exceptions/email-already-exists.exception';
import { UserPayload } from '@interfaces/user-payload.interface';
@Controller('auth')
export class AuthController {
constructor(private authService: AuthService) {}
@UsePipes(ValidationPipe)
@Post('/signup')
async signUp(
@Body() signUpDto: SignUpDto,
): Promise<{ token: string; user: UserPayload }> {
try {
return await this.authService.signUp(signUpDto);
} catch (err) {
if (err instanceof EmailAlreadyExistsException) {
throw new HttpException(
'E-mail já está sendo usado',
HttpStatus.BAD_REQUEST,
);
}
throw new HttpException(
'Erro interno do servidor',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
@UsePipes(ValidationPipe)
@Post('/login')
async login(
@Body() loginDto: LoginDto,
): Promise<{ token: string; user: UserPayload }> {
try {
return this.authService.login(loginDto);
} catch (err) {
throw new HttpException(
'Erro interno do servidor',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
}
|
<template>
<div>
<h2>{{name}}</h2>
<h2>{{age}}</h2>
<button @click="changeName">修改Name</button>
<button @click="changeAge">修改Age</button>
</div>
</template>
<script>
import { ref, watchEffect } from 'vue';
export default {
setup(props) {
// watchEffect会自动收集响应式依赖
const name = ref("heywecome");
const age = ref(18);
const changeName = () => {
name.value = "kangkang";
};
const changeAge = () => {
age.value++;
if(age.value > 25){
stop();
}
}
// 一开始就会默认执行一次
const stop = watchEffect((onInvalidate) => {
const timer = setTimeout(() => {
console.log("网络请求成功");
}, 2000);
onInvalidate(() => {
// 在这个函数中清除额外的副作用
clearTimeout(timer);
console.log(onInvalidate);
})
console.log("name", name.value);
console.log(age.value);
})
return {
name,
age,
changeName,
changeAge
}
}
}
</script>
<style lang="scss" scoped>
</style>
|
package com.amazon.lookout.mitigation.service.activity.validator;
import static com.amazon.lookout.mitigation.service.activity.validator.RequestValidator.REGIONAL_CELL_NAME_PATTERN;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.amazon.blackwatch.bwircellconfig.model.BwirCellConfig;
import com.amazon.lookout.mitigation.service.UpdateBlackWatchMitigationRegionalCellPlacementRequest;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import com.amazon.aws158.commons.metric.TSDMetrics;
import com.amazon.aws158.commons.packet.PacketAttributesEnumMapping;
import com.amazon.blackwatch.mitigation.state.model.BlackWatchTargetConfig;
import com.amazon.lookout.mitigation.service.AbortDeploymentRequest;
import com.amazon.lookout.mitigation.service.ApplyBlackWatchMitigationRequest;
import com.amazon.lookout.mitigation.service.UpdateBlackWatchMitigationRequest;
import com.amazon.lookout.mitigation.service.ChangeBlackWatchMitigationOwnerARNRequest;
import com.amazon.lookout.mitigation.service.CreateMitigationRequest;
import com.amazon.lookout.mitigation.service.DeactivateBlackWatchMitigationRequest;
import com.amazon.lookout.mitigation.service.DeleteMitigationFromAllLocationsRequest;
import com.amazon.lookout.mitigation.service.ListActiveMitigationsForServiceRequest;
import com.amazon.lookout.mitigation.service.ListBlackWatchLocationsRequest;
import com.amazon.lookout.mitigation.service.ListBlackWatchMitigationsRequest;
import com.amazon.lookout.mitigation.service.MitigationActionMetadata;
import com.amazon.lookout.mitigation.service.MitigationDefinition;
import com.amazon.lookout.mitigation.service.SimpleConstraint;
import com.amazon.lookout.mitigation.service.activity.helper.RequestTestHelper;
import com.amazon.lookout.mitigation.service.constants.DeviceName;
import com.amazon.lookout.mitigation.service.mitigation.model.MitigationTemplate;
import com.amazon.lookout.test.common.util.TestUtils;
import com.google.common.collect.Lists;
import org.junit.rules.ExpectedException;
public class RequestValidatorTest {
private final TSDMetrics tsdMetrics = mock(TSDMetrics.class);
private final String mitigationName = "TestMitigationName";
private final String template1 = MitigationTemplate.BlackWatchPOP_PerTarget_EdgeCustomer;
private final String template2 = MitigationTemplate.BlackWatchBorder_PerTarget_AWSCustomer;
private final String userName = "TestUserName";
private final String toolName = "TestToolName";
private final String description = "TestDesc";
private static final String currentRegion = "test-region";
private BwirCellConfig bwirCellConfig =
spy(new BwirCellConfig(System.getProperty("user.dir") + "/build/private/etc/cells/"));
private RequestValidator validator = new RequestValidator(currentRegion, bwirCellConfig);
@Rule
public ExpectedException invalidRegion = ExpectedException.none();
@Rule
public ExpectedException invalidCellNamePattern = ExpectedException.none();
@Rule
public ExpectedException invalidCellName = ExpectedException.none();
@Rule
public ExpectedException notYetLaunchedCells = ExpectedException.none();
@BeforeClass
public static void setUpOnce() {
TestUtils.configureLogging();
}
@Before
public void setUpBeforeTest() {
when(tsdMetrics.newSubMetrics(anyString())).thenReturn(tsdMetrics);
}
@Test
public void testValidateAbortDeploymentRequest() {
String[] validBWTemplates = {
MitigationTemplate.BlackWatchBorder_PerTarget_AWSCustomer,
MitigationTemplate.BlackWatchPOP_EdgeCustomer,
MitigationTemplate.BlackWatchPOP_PerTarget_EdgeCustomer
};
AbortDeploymentRequest abortRequest = new AbortDeploymentRequest();
abortRequest.setJobId(1);
abortRequest.setDeviceName(DeviceName.BLACKWATCH_POP.name());
// valid template
for (String template : validBWTemplates) {
abortRequest.setMitigationTemplate(template);
validator.validateAbortDeploymentRequest(abortRequest);
}
}
/**
* Test the case where the request is completely valid. We expect the validation to be completed without any exceptions.
*/
@Test
public void testHappyCase() {
// RateLimit MitigationTemplate
CreateMitigationRequest request = new CreateMitigationRequest();
request.setMitigationName(mitigationName);
request.setMitigationTemplate(template1);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setToolName(toolName);
metadata.setDescription(description);
request.setMitigationActionMetadata(metadata);
SimpleConstraint constraint = new SimpleConstraint();
constraint.setAttributeName(PacketAttributesEnumMapping.DESTINATION_IP.name());
constraint.setAttributeValues(Lists.newArrayList("1.2.3.4"));
MitigationDefinition definition = new MitigationDefinition();
definition.setConstraint(constraint);
request.setMitigationDefinition(definition);
validator.validateCreateRequest(request);
// CountMode MitigationTemplate
request.setMitigationTemplate(template1);
validator.validateCreateRequest(request);
}
/**
* Test the case where the request is missing the mitigationName
* We expect an exception to be thrown in this case.
*/
@Test
public void testMissingMitigationName() {
// RateLimit MitigationTemplate
CreateMitigationRequest request = new CreateMitigationRequest();
request.setMitigationTemplate(template1);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setToolName(toolName);
metadata.setDescription(description);
request.setMitigationActionMetadata(metadata);
SimpleConstraint constraint = new SimpleConstraint();
constraint.setAttributeName(PacketAttributesEnumMapping.DESTINATION_IP.name());
constraint.setAttributeValues(Lists.newArrayList("1.2.3.4"));
MitigationDefinition definition = new MitigationDefinition();
definition.setConstraint(constraint);
request.setMitigationDefinition(definition);
Throwable caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid mitigation name"));
}
assertNotNull(caughtException);
// CountMode MitigationTemplate
request.setMitigationTemplate(template2);
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid mitigation name"));
}
assertNotNull(caughtException);
}
/**
* Test the case where the request has invalid mitigationNames (empty, only spaces, special characters (non-printable ascii).
* We expect an exception to be thrown in this case.
*/
@Test
public void testInvalidMitigationNames() {
CreateMitigationRequest request = new CreateMitigationRequest();
request.setMitigationName("");
request.setMitigationTemplate(template1);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setToolName(toolName);
metadata.setDescription(description);
request.setMitigationActionMetadata(metadata);
SimpleConstraint constraint = new SimpleConstraint();
constraint.setAttributeName(PacketAttributesEnumMapping.DESTINATION_IP.name());
constraint.setAttributeValues(Lists.newArrayList("1.2.3.4"));
MitigationDefinition definition = new MitigationDefinition();
definition.setConstraint(constraint);
request.setMitigationDefinition(definition);
Throwable caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid mitigation name"));
}
assertNotNull(caughtException);
// Check mitigationNames with all spaces
request.setMitigationName(" ");
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid mitigation name"));
}
assertNotNull(caughtException);
// Check mitigationNames with non-printable ascii characters.
char invalidChar = 0x00;
request.setMitigationName("Some name with invalid char: " + String.valueOf(invalidChar));
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid mitigation name"));
}
assertNotNull(caughtException);
// Check mitigationNames with delete non-printable ascii character.
invalidChar = 0x7F;
request.setMitigationName("Some name with delete char: " + String.valueOf(invalidChar));
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid mitigation name"));
}
assertNotNull(caughtException);
// Check extra long mitigationNames.
StringBuffer buffer = new StringBuffer();
for (int index=0; index < 500; ++index) {
buffer.append("a");
}
request.setMitigationName(buffer.toString());
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid mitigation name"));
}
assertNotNull(caughtException);
}
/**
* Test the case where the request is missing the mitigationTemplate
* We expect an exception to be thrown in this case.
*/
@Test
public void testMissingOrInvalidRateLimitMitigationTemplate() {
CreateMitigationRequest request = new CreateMitigationRequest();
request.setMitigationName(mitigationName);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setToolName(toolName);
metadata.setDescription(description);
request.setMitigationActionMetadata(metadata);
SimpleConstraint constraint = new SimpleConstraint();
constraint.setAttributeName(PacketAttributesEnumMapping.DESTINATION_IP.name());
constraint.setAttributeValues(Lists.newArrayList("1.2.3.4"));
MitigationDefinition definition = new MitigationDefinition();
definition.setConstraint(constraint);
request.setMitigationDefinition(definition);
Throwable caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException.getMessage().startsWith("Invalid mitigation template found"));
request.setMitigationTemplate("BadTemplate");
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid mitigation template found"));
// Check mitigationTemplate with non-printable ascii characters.
char invalidChar = 0x00;
request.setMitigationTemplate(MitigationTemplate.BlackWatchPOP_PerTarget_EdgeCustomer + String.valueOf(invalidChar));
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid mitigation template"));
}
assertNotNull(caughtException);
}
/**
* Test the case where the request is missing the mitigationDefinition
* We expect an exception to be thrown in this case.
*/
@Test
public void testMissingMitigationActionMetadata() {
CreateMitigationRequest request = new CreateMitigationRequest();
request.setMitigationName(mitigationName);
request.setMitigationTemplate(template1);
SimpleConstraint constraint = new SimpleConstraint();
constraint.setAttributeName(PacketAttributesEnumMapping.DESTINATION_IP.name());
constraint.setAttributeValues(Lists.newArrayList("1.2.3.4"));
MitigationDefinition definition = new MitigationDefinition();
definition.setConstraint(constraint);
request.setMitigationDefinition(definition);
Throwable caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
}
/**
* Test the case where the request is missing the mitigationName
* We expect an exception to be thrown in this case.
*/
@Test
public void testMissingUserName() {
CreateMitigationRequest request = new CreateMitigationRequest();
request.setMitigationName(mitigationName);
request.setMitigationTemplate(template1);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setToolName(toolName);
metadata.setDescription(description);
request.setMitigationActionMetadata(metadata);
SimpleConstraint constraint = new SimpleConstraint();
constraint.setAttributeName(PacketAttributesEnumMapping.DESTINATION_IP.name());
constraint.setAttributeValues(Lists.newArrayList("1.2.3.4"));
MitigationDefinition definition = new MitigationDefinition();
definition.setConstraint(constraint);
request.setMitigationDefinition(definition);
Throwable caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid user name"));
// Check userName with non-printable ascii characters.
char invalidChar = 0x00;
metadata.setUser("Test User: " + String.valueOf(invalidChar));
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid user name"));
}
assertNotNull(caughtException);
}
/**
* Test the case where the request is missing the mitigationName
* We expect an exception to be thrown in this case.
*/
@Test
public void testMissingToolName() {
CreateMitigationRequest request = new CreateMitigationRequest();
request.setMitigationName(mitigationName);
request.setMitigationTemplate(template1);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setDescription(description);
request.setMitigationActionMetadata(metadata);
SimpleConstraint constraint = new SimpleConstraint();
constraint.setAttributeName(PacketAttributesEnumMapping.DESTINATION_IP.name());
constraint.setAttributeValues(Lists.newArrayList("1.2.3.4"));
MitigationDefinition definition = new MitigationDefinition();
definition.setConstraint(constraint);
request.setMitigationDefinition(definition);
Throwable caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid tool name"));
// Check toolName with non-printable ascii characters.
char invalidChar = 0x00;
metadata.setToolName("Tool: " + String.valueOf(invalidChar));
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid tool name"));
}
assertNotNull(caughtException);
}
/**
* Test the case where the request is missing the mitigationName
* We expect an exception to be thrown in this case.
*/
@Test
public void testMissingMitigationDescription() {
CreateMitigationRequest request = new CreateMitigationRequest();
request.setMitigationName(mitigationName);
request.setMitigationTemplate(template1);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setToolName(toolName);
request.setMitigationActionMetadata(metadata);
SimpleConstraint constraint = new SimpleConstraint();
constraint.setAttributeName(PacketAttributesEnumMapping.DESTINATION_IP.name());
constraint.setAttributeValues(Lists.newArrayList("1.2.3.4"));
MitigationDefinition definition = new MitigationDefinition();
definition.setConstraint(constraint);
request.setMitigationDefinition(definition);
Throwable caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid description found"));
// Check description with non-printable ascii characters.
char invalidChar = 0x00;
metadata.setDescription("Description: " + String.valueOf(invalidChar));
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid description found"));
}
assertNotNull(caughtException);
// Check extra long description.
StringBuffer buffer = new StringBuffer();
for (int index=0; index < 1000; ++index) {
buffer.append("a");
}
metadata.setDescription("Description: " + buffer);
caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Invalid description found"));
}
assertNotNull(caughtException);
}
/**
* Test the happy case for a delete request. We don't expect any exception to be thrown in this case.
*/
@Test
public void testValidateDeleteRequestHappyCase() {
// RateLimit MitigationTemplate
DeleteMitigationFromAllLocationsRequest request = new DeleteMitigationFromAllLocationsRequest();
request.setMitigationName(mitigationName);
request.setMitigationTemplate(template1);
request.setMitigationVersion(2);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setToolName(toolName);
metadata.setDescription("Test description");
request.setMitigationActionMetadata(metadata);
validator.validateDeleteRequest(request);
// CountMode MitigationTemplate
validator.validateDeleteRequest(request);
}
/**
* Test the case for a delete request with no mitigation version provided as input.
* We expect an exception to be thrown in this case.
*/
@Test
public void testDeleteRequestWithInvalidMitigationVersion() {
// RateLimit MitigationTemplate
DeleteMitigationFromAllLocationsRequest request = new DeleteMitigationFromAllLocationsRequest();
request.setMitigationName(mitigationName);
request.setMitigationTemplate(template1);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setToolName(toolName);
metadata.setDescription("Test description");
request.setMitigationActionMetadata(metadata);
Throwable caughtException = null;
try {
validator.validateDeleteRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
assertTrue(ex.getMessage().startsWith("Version of the mitigation to be deleted should be set to >=1"));
}
assertNotNull(caughtException);
}
/**
* Test the case for a create request with duplicates in the related tickets.
* We expect an exception to be thrown in this case.
*/
@Test
public void testCreateRequestWithDuplicateRelatedTickets() {
CreateMitigationRequest request = RequestTestHelper.generateCreateMitigationRequest(
template1, mitigationName);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setToolName(toolName);
metadata.setDescription("Test description");
metadata.setRelatedTickets(Lists.newArrayList("Tkt1", "Tkt2", "Tkt2"));
request.setMitigationActionMetadata(metadata);
Throwable caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Duplicate related tickets found in actionMetadata"));
}
/*
* Test to ensure the number of tickets is restricted.
*/
@Test
public void testCreateRequestWithInvalidRelatedTickets() {
CreateMitigationRequest request = RequestTestHelper.generateCreateMitigationRequest(
template1, mitigationName);
MitigationActionMetadata metadata = new MitigationActionMetadata();
metadata.setUser(userName);
metadata.setToolName(toolName);
metadata.setDescription("Test description");
metadata.setRelatedTickets(Lists.newArrayList("00123456789"));
request.setMitigationActionMetadata(metadata);
List<String> relatedTickets = Lists.newArrayList();
for (int index=0; index < 200; ++index) {
relatedTickets.add("000001" + index);
}
metadata.setRelatedTickets(relatedTickets);
Throwable caughtException = null;
try {
validator.validateCreateRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException.getMessage().startsWith("Exceeded the number of tickets that can be specified for a single mitigation"));
}
@Test
public void testListActiveMitigationsForService() {
ListActiveMitigationsForServiceRequest request = new ListActiveMitigationsForServiceRequest();
// locations is optional
request.setDeviceName(DeviceName.BLACKWATCH_POP.name());
validator.validateListActiveMitigationsForServiceRequest(request);
// valid device name
request.setDeviceName("BLACKWATCH_POP");
validator.validateListActiveMitigationsForServiceRequest(request);
}
@Test
public void testvalidateListBlackWatchMitigationsRequest() {
ListBlackWatchMitigationsRequest request = new ListBlackWatchMitigationsRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Khaleesi").withToolName("JUnit")
.withDescription("Test Descr")
.withRelatedTickets(Arrays.asList("1234", "5655")).build());
//valid request with only the MitigationActionMetadata, all other fields are null.
validator.validateListBlackWatchMitigationsRequest(request);
String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
String validResourceId = "192.168.0.1";
String validResourceType = "IPAddress";
String validOwnerARN = "arn:aws:iam::005436146250:user/blackwatch_host_status_updator_blackwatch_pop_pro";
//valid mitigationid, resourceid, resourcetype, ownerarn.
request.setMitigationId(validMitigationId);
request.setResourceId(validResourceId);
request.setResourceType(validResourceType);
request.setOwnerARN(validOwnerARN);
validator.validateListBlackWatchMitigationsRequest(request);
request.setMaxResults(5L);
validator.validateListBlackWatchMitigationsRequest(request);
//Invalid mitigationId;
Throwable caughtException = null;
char invalidChar = 0x00;
request.setMitigationId(validMitigationId + String.valueOf(invalidChar));
try {
validator.validateListBlackWatchMitigationsRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid mitigation ID"));
request.setMitigationId(validMitigationId);
//invalid resource id
caughtException = null;
request.setResourceId(validResourceId + String.valueOf(invalidChar));
try {
validator.validateListBlackWatchMitigationsRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid resource ID"));
request.setResourceId(validResourceId);
//invalid resource type
caughtException = null;
request.setResourceType(validResourceType + String.valueOf(invalidChar));
try {
validator.validateListBlackWatchMitigationsRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid resource type"));
request.setResourceType(validResourceType);
//invalid user ARN
caughtException = null;
request.setOwnerARN(validOwnerARN + String.valueOf(invalidChar));
try {
validator.validateListBlackWatchMitigationsRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid user ARN"));
request.setOwnerARN(validOwnerARN);
//invalid max result
caughtException = null;
request.setMaxResults(0L);
try {
validator.validateListBlackWatchMitigationsRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid maxNumberOfEntriesToFetch"));
}
@Test
public void testvalidateDeactivateBlackWatchMitigationRequest() {
DeactivateBlackWatchMitigationRequest request = new DeactivateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Khaleesi").withToolName("JUnit")
.withDescription("Test Descr")
.withRelatedTickets(Arrays.asList("1234", "5655")).build());
Throwable caughtException = null;
//invalid request with only the MitigationActionMetadata, all other fields are null.
try {
validator.validateDeactivateBlackWatchMitigationRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
//valid mitigationid
request.setMitigationId(validMitigationId);
validator.validateDeactivateBlackWatchMitigationRequest(request);
//Invalid mitigationId;
char invalidChar = 0x00;
request.setMitigationId(validMitigationId + String.valueOf(invalidChar));
try {
validator.validateDeactivateBlackWatchMitigationRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid mitigation ID"));
request.setMitigationId(validMitigationId);
}
@Test
public void testApplyMitigationRequestValidator() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Khaleesi")
.withToolName("Dragons")
.withDescription("MOD butt kicking.")
.withRelatedTickets(Arrays.asList("1234", "5655"))
.build());
char invalidChar = 0x00;
Throwable caughtExcepion = null;
String userARN = "arn:aws:iam::005436146250:user/blackwatch_host_status_updator_blackwatch_pop_pro";
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Invalid resource type"));
caughtExcepion = null;
String resourceId = "IPList1234";
request.setResourceId(resourceId);
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Invalid resource type"));
caughtExcepion = null;
String resourceType = "IPAddressXYZZZZ";
request.setResourceType(resourceType);
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Unsupported resource type"));
caughtExcepion = null;
resourceType = "IPAddressList";
request.setResourceType(resourceType);
String JSON = "XHHSHS";
request.setMitigationSettingsJSON(JSON);
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Could not parse"));
caughtExcepion = null;
//Allow null for the JSON.
request.setMitigationSettingsJSON(null);
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("A default rate limit must"));
caughtExcepion = null;
// Specify a global rate limit.
request.setGlobalPPS(120L);
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
JSON="{\"ipv6_per_dest_depth\":56, \"mitigation_config\":{}}";
request.setMitigationSettingsJSON(JSON);
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
try {
validator.validateApplyBlackWatchMitigationRequest(request, "ABABA" + String.valueOf(invalidChar));
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Invalid user ARN"));
caughtExcepion = null;
try {
validator.validateApplyBlackWatchMitigationRequest(request, "");
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Invalid user ARN"));
caughtExcepion = null;
try {
validator.validateApplyBlackWatchMitigationRequest(request, null);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Invalid user ARN"));
caughtExcepion = null;
request.getMitigationActionMetadata().setUser("");
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Invalid user"));
caughtExcepion = null;
request.getMitigationActionMetadata().setUser("Valid");
request.getMitigationActionMetadata().setToolName("");
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Invalid tool"));
caughtExcepion = null;
request.getMitigationActionMetadata().setToolName("Towel");
request.getMitigationActionMetadata().setRelatedTickets(Arrays.asList("1234", "1234"));
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage().startsWith("Duplicate related tickets"));
caughtExcepion = null;
}
private Long getDefaultRateLimit(final BlackWatchTargetConfig targetConfig) {
return targetConfig
.getMitigation_config()
.getGlobal_traffic_shaper()
.get("default")
.getGlobal_pps();
}
@Test
public void testValidateUpdateBlackWatchMitigationWithPPS() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
final Long theRateLimit = 120L;
request.setGlobalPPS(theRateLimit);
String resouceType = "IPAddress";
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
assertSame(theRateLimit, getDefaultRateLimit(newTargetConfig));
}
@Test
public void testValidateUpdateBlackWatchMitigationRegionalCellPlacementWithValidCellNames() {
UpdateBlackWatchMitigationRegionalCellPlacementRequest request =
new UpdateBlackWatchMitigationRegionalCellPlacementRequest();
List<String> cellNames = Stream.of("bzg-pdx-c1", "BZG-PDX-C2").collect(Collectors.toList());
request.setCellNames(cellNames);
validator.validateUpdateBlackWatchMitigationRegionalCellPlacementRequest(request, "gamma", "us-west-2");
}
@Test
public void testValidateUpdateBlackWatchMitigationRegionalCellPlacementWithInvalidCellNamePattern() {
UpdateBlackWatchMitigationRegionalCellPlacementRequest request =
new UpdateBlackWatchMitigationRegionalCellPlacementRequest();
List<String> cellNames = Stream.of("bzg-pdx-c1", "bz-pdx1-c2").collect(Collectors.toList());
request.setCellNames(cellNames);
invalidCellNamePattern.expect(IllegalArgumentException.class);
invalidCellNamePattern.expectMessage(String.format(
"Unrecognized cellName pattern found: 'bz-pdx1-c2', expected pattern is: '%s'.", REGIONAL_CELL_NAME_PATTERN));
validator.validateUpdateBlackWatchMitigationRegionalCellPlacementRequest(request, "gamma", "us-west-2");
}
@Test
public void testValidateUpdateBlackWatchMitigationRegionalCellPlacementWithCellNameNotInCellConfig() {
UpdateBlackWatchMitigationRegionalCellPlacementRequest request =
new UpdateBlackWatchMitigationRegionalCellPlacementRequest();
List<String> cellNames = Stream.of("bzg-pdx-c1", "BZG-XYZ-C2").collect(Collectors.toList());
request.setCellNames(cellNames);
invalidCellName.expect(IllegalArgumentException.class);
invalidCellName.expectMessage("cellName: 'BZG-XYZ-C2' not found in Bwir cell config");
validator.validateUpdateBlackWatchMitigationRegionalCellPlacementRequest(request, "gamma", "us-west-2");
}
@Test
public void testValidateUpdateBlackWatchMitigationRegionalCellPlacementRequestOnNotYetLaunchedCells() {
UpdateBlackWatchMitigationRegionalCellPlacementRequest request =
new UpdateBlackWatchMitigationRegionalCellPlacementRequest();
List<String> cellNames = Stream.of("bza-pdx-c1", "BZA-PDX-C2").collect(Collectors.toList());
request.setCellNames(cellNames);
String domain = "alpha";
String realm = "us-west-2";
notYetLaunchedCells.expect(IllegalArgumentException.class);
notYetLaunchedCells.expectMessage(String.format("Domain: %s and Realm: %s doesn't contain "
+ "any BWIR cells yet, but UpdateCellPlacementRequest contains cells: %s",
domain, realm, cellNames));
validator.validateUpdateBlackWatchMitigationRegionalCellPlacementRequest(request, domain, realm);
}
@Test
public void testValidateUpdateBlackWatchMitigationRegionalCellPlacementWithSpecialDomainCase() {
UpdateBlackWatchMitigationRegionalCellPlacementRequest request =
new UpdateBlackWatchMitigationRegionalCellPlacementRequest();
List<String> cellNames = Stream.of("bzg-pdx-c1", "bzg-pdx-c2").collect(Collectors.toList());
request.setCellNames(cellNames);
validator.validateUpdateBlackWatchMitigationRegionalCellPlacementRequest(request, "gamma-border", "us-west-2");
}
@Test
public void testValidateUpdateBlackWatchMitigationWithJson() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
final Long theRateLimit = 120L;
String json = String.format(""
+ "{"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": %d"
+ " }"
+ " }"
+ " }"
+ "}", theRateLimit);
request.setMitigationSettingsJSON(json);
String resouceType = "IPAddress";
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
assertSame(theRateLimit.longValue(), getDefaultRateLimit(newTargetConfig).longValue());
}
@Test
public void testValidateUpdateBlackWatchMitigationWithInvalidJsonBypassValidations() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
request.setBypassConfigValidations(true);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
final Long theRateLimit = 0L;
String json = String.format(""
+ "{"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": %d"
+ " }"
+ " }"
+ " }"
+ "}", theRateLimit);
request.setMitigationSettingsJSON(json);
String resouceType = "IPAddress";
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
assertSame(theRateLimit.longValue(), getDefaultRateLimit(newTargetConfig).longValue());
}
@Test
public void testValidateUpdateBlackWatchMitigationWithEmptyJsonForGLB() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
String json = "{}";
request.setMitigationSettingsJSON(json);
String resouceType = "GLB";
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
}
@Test
public void testChangeOwnerARNRequestvalidation() {
ChangeBlackWatchMitigationOwnerARNRequest request = new ChangeBlackWatchMitigationOwnerARNRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Khaleesi")
.withToolName("JUnit")
.withDescription("Test Descr")
.withRelatedTickets(Arrays.asList("1234", "5655"))
.build());
Throwable caughtException = null;
//invalid request with only the MitigationActionMetadata, all other fields are null.
try {
validator.validateChangeBlackWatchMitigationOwnerARNRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
caughtException = null;
String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
String validOwnerARN = "arn:aws:iam::005436146250:user/blackwatch_host_status_updator_blackwatch_pop_pro";
char invalidChar = 0x00;
//valid
request.setMitigationId(validMitigationId);
request.setExpectedOwnerARN(validOwnerARN);
request.setNewOwnerARN(validOwnerARN);
validator.validateChangeBlackWatchMitigationOwnerARNRequest(request);
//Invalid mitigationId;
request.setMitigationId(validMitigationId + String.valueOf(invalidChar));
try {
validator.validateChangeBlackWatchMitigationOwnerARNRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
assertTrue(caughtException instanceof IllegalArgumentException);
assertTrue(caughtException.getMessage().startsWith("Invalid mitigation ID"));
request.setMitigationId(validMitigationId);
//Invalid newOwnerARN;
request.setNewOwnerARN(validOwnerARN + String.valueOf(invalidChar));
try {
validator.validateChangeBlackWatchMitigationOwnerARNRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
caughtException = null;
request.setNewOwnerARN(validOwnerARN);
//Invalid expectedOwnerARN;
request.setExpectedOwnerARN(validOwnerARN + String.valueOf(invalidChar));
try {
validator.validateChangeBlackWatchMitigationOwnerARNRequest(request);
} catch (Exception ex) {
caughtException = ex;
}
assertNotNull(caughtException);
}
@Test
public void testValidateListBlackWatchLocationsRequest() {
ListBlackWatchLocationsRequest request = new ListBlackWatchLocationsRequest();
// valid region name
request.setRegion("test-region");
validator.validateListBlackWatchLocationsRequest(request);
// region name is optional, so valid input
request.setRegion(null);
validator.validateListBlackWatchLocationsRequest(request);
// invalid region name
request.setRegion("not-valid-region-name");
Throwable caughtException = null;
try {
validator.validateListBlackWatchLocationsRequest(request);
} catch (IllegalArgumentException ex) {
caughtException = ex;
}
assertNotNull(caughtException);
}
@Test(expected=IllegalArgumentException.class)
public void testDefaultRateLimitNotSpecified() {
// A well-formed request, but it does not specify a default rate limit anywhere.
// Expect validation to fail.
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddressList");
request.setMitigationSettingsJSON("{}");
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test
public void testDefaultRateLimitSpecifiedInAPIField() {
// The default rate limit is specified by the GlobalPPS API parameter
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddressList");
request.setGlobalPPS(1000L);
request.setMitigationSettingsJSON("{}");
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test
public void testDefaultRateLimitSpecifiedInJSON() {
// The default rate limit is specified by the JSON global_traffic_shaper key
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddressList");
String json = "{\"mitigation_config\": {\"global_traffic_shaper\": {\"default\": {\"global_pps\": 1000}}}}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test(expected=IllegalArgumentException.class)
public void testDefaultRateLimitSpecifiedInAPIFieldAndJSON() {
// The default rate limit is specified by both the GlobalPPS API parameter
// and the JSON global_traffic_shaper field
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddressList");
request.setGlobalPPS(1000L);
String json = "{\"mitigation_config\": {\"global_traffic_shaper\": {\"default\": {\"global_pps\": 1000}}}}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test(expected=IllegalArgumentException.class)
public void testNamedRateLimitSpecifiedInJSON() {
// A named shaper rate limit is specified by the JSON global_traffic_shaper key,
// but the default rate isn't specified anywhere
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddressList");
String json = "{\"mitigation_config\": {\"global_traffic_shaper\": {\"name1\": {\"global_pps\": 1000}}}}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test
public void testZeroRateLimitSpecifiedInJSON() {
// We tolerate a rate limit of zero when only the default shaper is present.
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddressList");
String json = ""
+ "{"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": 0"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test(expected=IllegalArgumentException.class)
public void testNamedZeroRateLimitSpecifiedInJSON() {
// A zero rate limit for any other shaper should be rejected
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddressList");
String json = ""
+ "{"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"not_default\": {"
+ " \"global_pps\": 0"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test(expected=IllegalArgumentException.class)
public void testNamedDefaultZeroRateLimitSpecifiedInJSON() {
// A zero rate limit for the default shaper is rejected when more than one
// shaper exist.
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddressList");
String json = ""
+ "{"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": 0"
+ " },"
+ " \"not_default\": {"
+ " \"global_pps\": 1000"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
// similar test as testNamedDefaultZeroRateLimitSpecifiedInJSON but since
// bypass validation is set, the test should succeed.
@Test
public void testNamedDefaultZeroRateLimitSpecifiedInJSONBypassValidation() {
// A zero rate limit for the default shaper is rejected when more than one
// shaper exist.
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddressList");
request.setBypassConfigValidations(true);
String json = ""
+ "{"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": 0"
+ " },"
+ " \"not_default\": {"
+ " \"global_pps\": 1000"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test
public void testInvalidIPv4ResourceIdIpAddressListMitigation() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(
MitigationActionMetadata.builder().withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.withRelatedTickets(Arrays.asList("1234", "5655"))
.build());
request.setResourceId("10.0.12.0/24");
request.setResourceType("IPAddressList");
Throwable caughtExcepion = null;
String userARN = "arn:aws:iam::005436146250:user/blackwatch_host_status_updator_blackwatch_pop_pro";
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage()
.startsWith("Invalid resource ID! An IP Address List resource ID cannot be a Network CIDR"));
}
@Test
public void testInvalidIPv6ResourceIdIpAddressListMitigation() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(
MitigationActionMetadata.builder().withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.withRelatedTickets(Arrays.asList("1234", "5655"))
.build());
request.setResourceId("2001:1111:2222:3333::/64");
request.setResourceType("IPAddressList");
Throwable caughtExcepion = null;
String userARN = "arn:aws:iam::005436146250:user/blackwatch_host_status_updator_blackwatch_pop_pro";
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage()
.startsWith("Invalid resource ID! An IP Address List resource ID cannot be a Network CIDR"));
}
/**
* Test the case where the request resourceId contains an ascii-printable whitespace.
*/
@Test
public void testInvalidWhitespaceResourceIdIpAddressListMitigation() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(
MitigationActionMetadata.builder().withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.withRelatedTickets(Arrays.asList("1234", "5655"))
.build());
request.setResourceId("ResourceId 1 2 3 ");
request.setResourceType("IPAddressList");
Throwable caughtExcepion = null;
String userARN = "arn:aws:iam::005436146250:user/blackwatch_host_status_updator_blackwatch_pop_pro";
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage()
.startsWith("Invalid resource ID! An IP Address List resource ID cannot contain whitespace characters"));
}
@Test
public void testGlbRequestsAreValidated() {
invalidRegion.expect(IllegalArgumentException.class);
invalidRegion.expectMessage("Key: no-such-1 must be a region in the aws partition");
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(
MitigationActionMetadata.builder().withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.withRelatedTickets(Arrays.asList("1234", "5655"))
.build());
request.setResourceId("AGlbArn");
request.setResourceType("GLB");
String json = ""
+ "{" +
" \"glb_mitigation_config\": {\n" +
" \"listener_configs\": {\n" +
" \"default\": {\n" +
" \"regional_capacity_limits\": {\n" +
" \"no-such-1\": {\n" + // this should cause the validate call, if made, to throw an exception
" \"global_pps\": 330000\n" +
" },\n" +
" \"eu-west-2\": {\n" +
" \"global_pps\": 440000\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n"+
"}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
// Test BWiR resource type validation
@Test
public void testValidApplyBlackWatchMitigationBWiRIPAddress() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("IPAddress");
String json = "{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": 1000,"
+ " \"global_bps\": 9999"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test
public void testValidApplyBlackWatchMitigationBWiRIPAddressList() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("IPAdResourceId123");
request.setResourceType("IPAddressList");
String json = "{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\", \"GLOBAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": 1000,"
+ " \"global_bps\": 9999"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test
public void testValidApplyBlackWatchMitigationBWiRElasticIP() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("ElasticIP");
String json = "{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": 1000,"
+ " \"global_bps\": 9999"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test
public void testInvalidApplyBlackWatchMitigationBWiRELB() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("ELB");
String json = "{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": 1000,"
+ " \"global_bps\": 9999"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
Throwable caughtExcepion = null;
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage()
.startsWith("Unsupported resource type specified for BWiR"));
}
@Test
public void testInvalidApplyBlackWatchMitigationBWiRGLB() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("GLB");
String json = "{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": 1000,"
+ " \"global_bps\": 9999"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
Throwable caughtExcepion = null;
try {
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage()
.startsWith("Unsupported resource type specified for BWiR"));
}
@Test
public void testValidApplyBlackWatchMitigationGlobalResourceType() {
ApplyBlackWatchMitigationRequest request = new ApplyBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
request.setResourceId("ResourceId123");
request.setResourceType("GLB");
String json = "{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"GLOBAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": 1000,"
+ " \"global_bps\": 9999"
+ " }"
+ " }"
+ " }"
+ "}";
request.setMitigationSettingsJSON(json);
String userARN = "arn:aws:iam::005436146250:user/blackwatch";
validator.validateApplyBlackWatchMitigationRequest(request, userARN);
}
@Test
public void testValidUpdateBlackWatchMitigationBWiRIPAddress() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
final Long theRateLimit = 120L;
String json = String.format("{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": %d"
+ " }"
+ " }"
+ " }"
+ "}", theRateLimit);
request.setMitigationSettingsJSON(json);
String resouceType = "IPAddress";
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
assertSame(theRateLimit.longValue(), getDefaultRateLimit(newTargetConfig).longValue());
}
@Test
public void testValidUpdateBlackWatchMitigationBWiRIPAddressList() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
final Long theRateLimit = 120L;
String json = String.format("{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": %d"
+ " }"
+ " }"
+ " }"
+ "}", theRateLimit);
request.setMitigationSettingsJSON(json);
String resouceType = "IPAddressList";
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
assertSame(theRateLimit.longValue(), getDefaultRateLimit(newTargetConfig).longValue());
}
@Test
public void testValidUpdateBlackWatchMitigationBWiRElasticIP() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
final Long theRateLimit = 120L;
String json = String.format("{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": %d"
+ " }"
+ " }"
+ " }"
+ "}", theRateLimit);
request.setMitigationSettingsJSON(json);
String resouceType = "ElasticIP";
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
assertSame(theRateLimit.longValue(), getDefaultRateLimit(newTargetConfig).longValue());
}
@Test
public void testInValidUpdateBlackWatchMitigationBWiRELB() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
final Long theRateLimit = 120L;
String json = String.format("{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": %d"
+ " }"
+ " }"
+ " }"
+ "}", theRateLimit);
request.setMitigationSettingsJSON(json);
String resouceType = "ELB";
Throwable caughtExcepion = null;
try {
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage()
.startsWith("Unsupported resource type specified for BWiR"));
}
@Test
public void testInValidUpdateBlackWatchMitigationBWiRGLB() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
final Long theRateLimit = 120L;
String json = String.format("{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"REGIONAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": %d"
+ " }"
+ " }"
+ " }"
+ "}", theRateLimit);
request.setMitigationSettingsJSON(json);
String resouceType = "GLB";
Throwable caughtExcepion = null;
try {
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
} catch (Exception ex) {
caughtExcepion = ex;
}
assertNotNull(caughtExcepion);
assertTrue(caughtExcepion instanceof IllegalArgumentException);
assertTrue(caughtExcepion.getMessage()
.startsWith("Unsupported resource type specified for BWiR"));
}
@Test
public void testValidUpdateBlackWatchMitigationGlobalGLB() {
UpdateBlackWatchMitigationRequest request = new UpdateBlackWatchMitigationRequest();
request.setMitigationActionMetadata(MitigationActionMetadata.builder()
.withUser("Username")
.withToolName("Toolname")
.withDescription("Description")
.build());
final String validMitigationId = "US-WEST-1_2016-02-05T00:43:04.6767Z_55";
request.setMitigationId(validMitigationId);
final String userARN = "arn:aws:iam::005436146250:user/blackwatch";
final Long theRateLimit = 120L;
String json = String.format("{"
+ " \"global_deployment\": {"
+ " \"placement_tags\": [\"GLOBAL\"]"
+ " },"
+ " \"mitigation_config\": {"
+ " \"global_traffic_shaper\": {"
+ " \"default\": {"
+ " \"global_pps\": %d"
+ " }"
+ " }"
+ " }"
+ "}", theRateLimit);
request.setMitigationSettingsJSON(json);
String resouceType = "GLB";
final BlackWatchTargetConfig newTargetConfig = validator.validateUpdateBlackWatchMitigationRequest(
request, resouceType, new BlackWatchTargetConfig(), userARN);
assertSame(theRateLimit.longValue(), getDefaultRateLimit(newTargetConfig).longValue());
}
}
|
package stronghold.model.database;
import stronghold.model.components.general.User;
import stronghold.model.components.lobby.Game;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
public class FriendsDB implements Serializable {
private HashMap<User, ArrayList<User>> friends;
public static FriendsDB friendsDB=new FriendsDB();
private final String path = "src/main/java/stronghold/database/datasets/friends.ser";
public static FriendsDB getInstance() {
return friendsDB;
}
private FriendsDB(){
try (
FileInputStream fileInputStream = new FileInputStream(path);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)
){
friends = (HashMap<User, ArrayList<User>>) objectInputStream.readObject();
} catch (Exception e) {
friends = new HashMap<>();
}
}
public void addFriendForUsers(User user1, User user2){
if(!friends.containsKey(user1)){
friends.put(user1, new ArrayList<>());
}
if(!friends.containsKey(user2)){
friends.put(user2, new ArrayList<>());
}
if(!friends.get(user1).contains(user2)){
friends.get(user1).add(user2);
}
if(!friends.get(user2).contains(user1)){
friends.get(user2).add(user1);
}
}
public void removeFriendFromUsers(User user1, User user2){
if(friends.get(user1).contains(user2)){
friends.get(user1).remove(user2);
}
if(friends.get(user2).contains(user1)){
friends.get(user2).remove(user1);
}
}
public HashMap<User, ArrayList<User>> getFriends() {
return friends;
}
public void update() throws IOException {
try (
FileOutputStream fileOutputStream = new FileOutputStream(path, false);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream)){
objectOutputStream.writeObject(friends);
}
}
}
|
import React, { useState, useEffect } from "react";
import axios from "axios";
import StadiumMap from "./StadiumMap";
import { API_BASE_URL } from "../apiConfig";
const MapInfo = () => {
const [teams, setTeams] = useState([]);
const [selectedTeam, setSelectedTeam] = useState([]);
useEffect(() => {
fetchTeams();
}, []);
const fetchTeams = async () => {
try {
const response = await axios.get(`${API_BASE_URL}team`);
console.log("Teams data:", response.data);
setTeams(response.data);
console.log(response);
if (response.data.length > 0) {
setSelectedTeam(response.data[0]);
}
console.log(response.data[0]);
} catch (error) {
console.error("Error fetching teams:", error);
}
};
return (
<>
<div>
<div className="container-flex">
<div className="tab-container overflow-auto">
{teams.map((team) => (
<button
key={team.teamId}
onClick={() => setSelectedTeam(team)}
className={`btn ${
selectedTeam && selectedTeam.teamId === team.teamId
? "btn-active"
: "btn-light btn-hover"
} m-1 flex-fill`}
>
{team.name}
</button>
))}
</div>
<section class="py-1 bg-dark" id="features">
<div class="container px-4 my-1">
<div class="row gx-5">
<div class="col-lg-12">
<h2 class="fw-bolder mb-0 text-white pt-3 pb-3">
Team Information
</h2>
<h3 class="mb-0 text-white pt-3 pb-3">
Click on your favourite team to find out more about the club
and see a map of your favourite club's stadium!
</h3>
</div>
</div>
</div>
</section>
<div className="d-flex w-100 justify-content-between pt-2 pb-5">
<div className="team-info w-50">
{selectedTeam && (
<>
<div
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: "20px",
}}
>
<img
src={`team-badges/${selectedTeam.badgeURL}`}
alt="Team Badge"
style={{
marginTop: "20px",
width: "100px",
height: "100px",
objectFit: "contain",
}}
/>
<h2>{selectedTeam.name}</h2>
<p className="px-5 text-center lead w-100 fs-4">
{selectedTeam.description || "No description available."}
</p>
</div>
</>
)}
</div>
<div className="map-container pt-5 w-50">
{selectedTeam && (
<StadiumMap
key={`${selectedTeam.lat}-${selectedTeam.lng}`}
lat={selectedTeam.lat}
lng={selectedTeam.lng}
/>
)}
</div>
</div>
</div>
</div>
</>
);
};
export default MapInfo;
|
package com.hanw.community.service;
import com.hanw.community.dao.MessageMapper;
import com.hanw.community.entity.Message;
import com.hanw.community.util.SensitiveFilter;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.util.HtmlUtils;
import java.util.List;
/**
* @author hanW
* @create 2022-08-10 12:43
*/
@Service
public class MessageService {
@Autowired
private MessageMapper messageMapper;
@Autowired
private SensitiveFilter sensitiveFilter;
public List<Message> findConversations(int userId, int offset, int limit) {
return messageMapper.selectConversations(userId, offset, limit);
}
public int findConversationCount(int userId) {
return messageMapper.selectConversationCount(userId);
}
public List<Message> findLetters(String conversationId, int offset, int limit) {
return messageMapper.selectLetters(conversationId, offset, limit);
}
public int findLetterCount(String conversationId) {
return messageMapper.selectLetterCount(conversationId);
}
public int findLetterUnreadCount(int userId, String conversationId) {
return messageMapper.selectLetterUnreadCount(userId, conversationId);
}
public int addMessage(Message message){
//转义HTML标记
message.setContent(HtmlUtils.htmlEscape(message.getContent()));
//过滤敏感词
message.setContent(sensitiveFilter.filter(message.getContent()));
return messageMapper.insertMessage(message);
}
public int readMessage(List<Integer> ids){
return messageMapper.updateStatus(ids,1);
}
public Message findLatestNotice(int userId,String topic){
return messageMapper.selectLatestNotice(userId,topic);
}
public int findNoticeCount(int userId,String topic){
return messageMapper.selectNoticeCount(userId,topic);
}
public int findUnreadNoticeCount(int userId,String topic){
return messageMapper.selectUnreadNoticeCount(userId,topic);
}
public List<Message> findNotices(int userId, String topic, int offset, int limit) {
return messageMapper.selectNotices(userId, topic, offset, limit);
}
}
|
import { Link } from 'react-router-dom';
import { useState } from 'react';
import { useAuth } from '../hooks/useAuth.js';
export default function Register() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [passwordConfirmation, setPasswordConfirmation] = useState('');
const [errors, setErrors] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const { register } = useAuth({
middleware: 'guest',
redirectIfAuthenticated: '/products',
});
const submitForm = async (event) => {
event.preventDefault();
await setIsLoading(true);
await register({
name,
email,
password,
password_confirmation: passwordConfirmation,
setErrors,
});
await setIsLoading(false);
};
console.log(errors);
return (
<div className="flex items-center justify-center min-h-screen max-w-lg mx-auto">
<form
onSubmit={submitForm}
className="flex flex-col items-center justify-center w-full space-y-4 card bg-white dark:bg-gray-800 shadow-xl py-12"
>
<h1 className="font-bold text-3xl text-gray-200">Register new account</h1>
<label className="form-control w-full max-w-md">
<div className="label">
<span className="label-text">Name</span>
</div>
<input
value={name}
onChange={(event) => setName(event.target.value)}
type="text"
className="input input-bordered input-primary w-full max-w-md"
/>
{errors?.name && (
<div className="label">
<span className="label-text-alt text-error">{errors.name}</span>
</div>
)}
</label>
<label className="form-control w-full max-w-md">
<div className="label">
<span className="label-text">E-mail</span>
</div>
<input
value={email}
onChange={(event) => setEmail(event.target.value)}
type="email"
className="input input-bordered input-primary w-full max-w-md"
/>
{errors?.email && (
<div className="label">
<span className="label-text-alt text-error">{errors.email}</span>
</div>
)}
</label>
<label className="form-control w-full max-w-md">
<div className="label">
<span className="label-text">Password</span>
</div>
<input
value={password}
onChange={(event) => setPassword(event.target.value)}
type="password"
className="input input-bordered input-primary w-full max-w-md"
autoComplete="new-password"
/>
{errors?.password && (
<div className="label">
<span className="label-text-alt text-error">{errors.password}</span>
</div>
)}
</label>
<label className="form-control w-full max-w-md">
<div className="label">
<span className="label-text">Confirm password</span>
</div>
<input
value={passwordConfirmation}
onChange={(event) => setPasswordConfirmation(event.target.value)}
type="password"
className="input input-bordered input-primary w-full max-w-md"
required
autoComplete="new-password"
/>
</label>
<div>
Already have an account?{' '}
<Link className="link link-hover text-success font-bold tracking-wide" to="/login">
Login
</Link>
</div>
<button
type="submit"
disabled={isLoading}
className="btn btn-outline btn-info w-full max-w-md uppercase"
>
{isLoading ? <span className="loading loading-spinner"></span> : 'sign up'}
</button>
</form>
</div>
);
}
|
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'dayOfProgrammer' function below.
*
* The function is expected to return a STRING.
* The function accepts INTEGER year as parameter.
*/
public static String dayOfProgrammer(int year) {
int month = 0;
int days = 0;
while(days<256)
{
month++;
if(month==2)
{
if(year==1918)
days+=15;
else if(year<1918)
{
if(year%4==0)
{
days+=29;
}
else
{
days+=28;
}
}
else
{
if((year%4==0 && year%100!=0) || year%400==0)
{
days+=29;
}
else
{
days+=28;
}
}
}
else if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
days+=31;
else
days+=30;
}
int day = 0;
if(month==2)
{
if(year==1918)
day=15;
else if(year<1918)
{
if(year%4==0)
{
day=29;
}
else
{
day=28;
}
}
else
{
if((year%4==0 && year%100!=0) || year%400==0)
{
day=29;
}
else
{
day=28;
}
}
}
else if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
day=31;
else
day=30;
while(days>256)
{
day--;
days--;
}
return String.format("%02d.%02d.%04d",day,month,year);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int year = Integer.parseInt(bufferedReader.readLine().trim());
String result = Result.dayOfProgrammer(year);
bufferedWriter.write(result);
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}
|
import React from "react";
import "../../css/app.css";
import { useState } from "react";
import { Inertia } from "@inertiajs/inertia";
import { InertiaLink, useForm } from "@inertiajs/inertia-react";
const SuccessStoriesForm = (props) => {
const { data, setData, errors, post } = useForm({
achievement: "",
description: "",
category: "",
date_of_achievement: "",
video_url: "",
snapshot: null,
});
function handleSubmit(e) {
e.preventDefault();
post(route("successStorySubmit"), {
onSuccess: (res) => {
alert('Success');
},
}),
{
forceFormData: true,
};
}
return (
<div id="bg">
<div class="bg-white max-w-2xl mx-auto p-10 mt-5">
<div class="flex flex-col justify-center items-center h-12 text-3xl font-extrabold bg-blue-600 mb-2">
<h3 class="text-lg text-white">
Share your Success Stories
</h3>
</div>
<form onSubmit={handleSubmit}>
<div class="grid gap-6 mb-6 lg:grid-cols-2 mt-2">
<div>
<label
for="name"
class="block mb-2 text-black font-bold"
>
{" "}
Name
</label>
<input required={true}
name="name"
type="text"
placeholder={props.auth.name}
class="bg-white border border-gray-300 text-gray-900 text-medium rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:focus:ring-blue-500 dark:focus:border-blue-500"
disabled
/>
</div>
<div>
<label
for="phone"
class="block mb-2 text-black font-bold"
>
Mobile Number
</label>
<input required={true}
name="phone"
type="tel"
placeholder={props.auth.phone}
class="bg-white border border-gray-300 text-gray-900 text-medium rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:focus:ring-blue-500 dark:focus:border-blue-500"
disabled
/>
</div>
<div>
<label
for="achievement"
class="block mb-2 text-black font-bold"
>
Achievement Title
</label>
<input required={true}
name="achievement"
type="text"
class="bg-white border border-gray-300 text-gray-900 text-medium rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:focus:ring-blue-500 dark:focus:border-blue-500"
value={data.achievement}
onChange={(e) =>
setData("achievement", e.target.value)
}
/>
</div>
<div>
<label
for="description"
class="block mb-2 text-black font-bold"
>
Description
</label>
<textarea
required={true}
name="description"
id="message"
rows="4"
class="block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
placeholder="Your message..."
value={data.description}
onChange={(e) =>
setData("description", e.target.value)
}
></textarea>
</div>
<div>
<label
for="category"
class="block mb-2 text-black font-bold"
>
Category
</label>
<select
required
name="category"
class="bg-white border border-gray-300 text-gray-900 text-medium rounded-lg block w-full p-2.5 "
value={data.category}
onChange={(e) =>
setData("category", e.target.value)
}
>
<option value="">Choose Category</option>
<option value="National">National</option>
<option value="International">
International
</option>
</select>
</div>
<div>
<label
for="date_of_achievement"
class="block mb-2 text-black font-bold"
>
Date of Achievement
</label>
<input required={true}
name="date_of_achievement"
type="date"
class="bg-white border border-gray-300 text-gray-900 text-medium rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:focus:ring-blue-500 dark:focus:border-blue-500"
value={data.date_of_achievement}
onChange={(e) =>
setData(
"date_of_achievement",
e.target.value
)
}
/>
</div>
<div>
<label
for="video_url"
class="block mb-2 text-black font-bold"
>
Videos
</label>
<input required={true}
name="video_url"
type="text"
class="bg-white border border-gray-300 text-gray-900 text-medium rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:focus:ring-blue-500 dark:focus:border-blue-500"
value={data.video_url}
onChange={(e) =>
setData("video_url", e.target.value)
}
/>
</div>
<div>
<label
for="snapshot"
class="block mb-2 text-black font-bold"
>
Snapshots
</label>
<input required={true}
name="snapshot"
type="file"
class="bg-white border border-gray-300 text-gray-900 text-medium rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:focus:ring-blue-500 dark:focus:border-blue-500"
//value={data.snapshot}
onChange={(e) =>
setData("snapshot", e.target.files[0])
}
/>
</div>
</div>
<div class="flex items-center justify-center">
<button
type="submit"
class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
>
Submit
</button>
</div>
</form>
</div>
</div>
);
};
export default SuccessStoriesForm
|
package com.suchness.intellisense.authorization;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.nimbusds.jose.JWSObject;
import com.suchness.intellisense.common.constant.AuthConstant;
import com.suchness.intellisense.common.domain.UserDto;
import com.suchness.intellisense.config.IgnoreUrlsConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import reactor.core.publisher.Mono;
import java.net.URI;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/***
* author: rushi
* create_time : 2020/11/2011:37
*******/
@Component
public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private IgnoreUrlsConfig ignoreUrlsConfig;
@Override
public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
ServerHttpRequest request = authorizationContext.getExchange().getRequest();
URI uri = request.getURI();
PathMatcher pathMatcher = new AntPathMatcher();
//白名单路径直接放行
List<String> ignoreUrls = ignoreUrlsConfig.getUrls();
for (String ignoreUrl : ignoreUrls) {
if (pathMatcher.match(ignoreUrl, uri.getPath())) {
return Mono.just(new AuthorizationDecision(true));
}
}
//对应跨域的预检请求直接放行
if(request.getMethod()==HttpMethod.OPTIONS){
return Mono.just(new AuthorizationDecision(true));
}
//管理端路径需校验权限
Map<Object, Object> resourceRolesMap = redisTemplate.opsForHash().entries(AuthConstant.RESOURCE_ROLES_MAP_KEY);
Iterator<Object> iterator = resourceRolesMap.keySet().iterator();
List<String> authorities = new ArrayList<>();
while (iterator.hasNext()) {
String pattern = (String) iterator.next();
if (pathMatcher.match(pattern, uri.getPath())) {
authorities.addAll(Convert.toList(String.class, resourceRolesMap.get(pattern)));
}
}
authorities = authorities.stream().map(i -> i = AuthConstant.AUTHORITY_PREFIX + i).collect(Collectors.toList());
//认证通过且角色匹配的用户可访问当前路径
return mono
.filter(Authentication::isAuthenticated)
.flatMapIterable(Authentication::getAuthorities)
.map(GrantedAuthority::getAuthority)
.any(authorities::contains)
.map(AuthorizationDecision::new)
.defaultIfEmpty(new AuthorizationDecision(false));
}
}
|
def callLimit(limit: int):
'''take an argument of call limit &
returns a reference to the callLimiter function'''
count = 0
def callLimiter(function):
'''takes another funtion as an argument &
returns a reference to the limit_function function.'''
def limit_function(*args, **kwds):
'''returns the result of calling the function with
the provided arguments, or None if the call limit is reached.'''
nonlocal count
if count < limit:
count += 1
# function(*args, **kwds)
return function(*args, **kwds)
elif count == limit:
print("Error:", function, "call too many time")
return limit_function
return callLimiter
|
<template>
<div
class="upload-area active-upload"
:class="{ focus: uploadAreaActive }"
@dragover.prevent
@drop.stop.prevent="onDrop"
@paste="onPaste"
v-loading="imageLoading"
element-loading-text="图片上传中..."
element-loading-background="rgba(0, 0, 0, 0.5)"
>
<label for="uploader" class="active-upload" v-if="uploadAreaActive"></label>
<input id="uploader" type="file" @change="onSelect" multiple="multiple" />
<div class="tips active-upload" v-if="!toUploadImage.curImgBase64Url">
<i class="icon el-icon-upload active-upload"></i>
<div class="text active-upload">拖拽、粘贴、或点击此处上传</div>
</div>
<img
class="active-upload"
v-if="toUploadImage.curImgBase64Url"
:src="toUploadImage.curImgBase64Url"
alt="Pictures to be uploaded"
/>
</div>
</template>
<script lang="ts">
import { computed, defineComponent, reactive, toRefs } from 'vue'
import { store, useStore } from '@/store'
import { filenameHandle } from '@/common/utils/file-handle-helper'
import selectedFileHandle from '@/common/utils/selected-file-handle'
import createToUploadImageObject from '@/common/utils/create-to-upload-image'
import paste from '@/common/utils/paste'
export default defineComponent({
name: 'upload-area',
props: {
imageLoading: {
type: Boolean,
default: false
}
},
setup() {
const store = useStore()
const reactiveData = reactive({
userConfigInfo: computed(() => store.getters.getUserConfigInfo).value,
uploadAreaActive: computed((): boolean => store.getters.getUploadAreaActive),
uploadSettings: computed(() => store.getters.getUploadSettings).value,
toUploadImage: computed(() => store.getters.getToUploadImage).value,
// 选择图片
onSelect(e: any) {
store.commit('CHANGE_UPLOAD_AREA_ACTIVE', true)
// eslint-disable-next-line no-restricted-syntax
for (const file of e.target.files) {
selectedFileHandle(file, this.uploadSettings.imageMaxSize)?.then((base64) => {
this.getImage(base64, file)
})
}
},
// 拖拽图片
onDrop(e: any) {
store.commit('CHANGE_UPLOAD_AREA_ACTIVE', true)
// eslint-disable-next-line no-restricted-syntax
for (const file of e.dataTransfer.files) {
selectedFileHandle(file, this.uploadSettings.imageMaxSize)?.then((base64) => {
this.getImage(base64, file)
})
}
},
// 复制图片
async onPaste(e: any) {
const { base64, file } = await paste(e, this.uploadSettings.imageMaxSize)
this.getImage(base64, file)
},
// 获取图片对象
getImage(base64Data: string, file: File) {
if (
this.toUploadImage.list.length === this.toUploadImage.uploadedNumber &&
this.toUploadImage.list.length > 0 &&
this.toUploadImage.uploadedNumber > 0
) {
store.dispatch('TO_UPLOAD_IMAGE_CLEAN_LIST')
store.dispatch('TO_UPLOAD_IMAGE_CLEAN_UPLOADED_NUMBER')
}
const curImg = createToUploadImageObject()
curImg.imgData.base64Url = base64Data
// eslint-disable-next-line prefer-destructuring
curImg.imgData.base64Content = base64Data.split(',')[1]
const { name, hash, suffix } = filenameHandle(file.name)
curImg.uuid = hash
curImg.fileInfo.size = file.size
curImg.fileInfo.lastModified = file.lastModified
curImg.filename.name = name
curImg.filename.hash = hash
curImg.filename.suffix = suffix
curImg.filename.now = this.userConfigInfo.personalSetting.defaultHash
? `${name}.${hash}.${suffix}`
: `${name}.${suffix}`
curImg.filename.initName = name
curImg.filename.isHashRename = this.userConfigInfo.personalSetting.defaultHash
store.dispatch('TO_UPLOAD_IMAGE_LIST_ADD', JSON.parse(JSON.stringify(curImg)))
store.dispatch('TO_UPLOAD_IMAGE_SET_CURRENT', {
uuid: hash,
base64Url: base64Data
})
}
})
return {
...toRefs(reactiveData)
}
}
})
</script>
<style scoped lang="stylus">
@import "upload-area.styl"
</style>
|
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router-dom";
import { CarFullDetails } from "../../models/CarFullDetails";
import { RootState } from "../../redux/configureStore";
import { getCarDetails } from "../../redux/store/carDetails/actions";
import { Container, Row, Col, Image, Button } from "react-bootstrap";
import { Link } from "react-router-dom";
import "./CarDetails.scss";
function CarDetails() {
let { id } = useParams();
let key = 0;
const car = useSelector<RootState>(
(state) => JSON.parse(JSON.stringify(state.carDetails)).cardetails
) as CarFullDetails;
const [carid] = useState(id!);
const bookingLink = "/booking/" + carid;
const dispatch = useDispatch();
useEffect(() => {
dispatch(getCarDetails(carid));
}, [dispatch, carid]);
return (
<div className="totaldiv">
<h5>{car?.specifications.name}</h5>
<Container className="detailsContainer">
<Row>
<Col>
<Image src={car?.specifications.image} alt="No Image Available" />
</Col>
<Col className="col2">
<h6>Car Specifications</h6>
<p>
<span>Fuel type</span>
<br />
{car?.specifications.fuel_type}
</p>
<p>
<span>Engine</span>
<br />
{car?.specifications.engine_cc}
</p>
<p>
<span>Torque</span>
<br />
{car?.specifications.torque}
</p>
<p>
<span>Acceleration</span>
<br />
{car?.specifications.acceleration}
</p>
<p>
<span>Top Speed</span>
<br />
{car?.specifications.top_speed}
</p>
<p>
<span>Variants</span>
<br />
{car?.specifications.variant.map((v) => (
<li key={++key}>{v}, </li>
))}
</p>
</Col>
</Row>
<hr />
<Row>
<Col>
<Image src={car?.exterior.image} alt="No Image Available" />
</Col>
<Col className="col2">
<h6>Exteriors</h6>
<span>color</span>
<div
style={{
height: "3rem",
width: "10rem",
backgroundColor: car?.exterior.color,
margin: "0.5rem",
border: "0.1rem solid black",
}}
/>
<p>
<span>Dimension</span>
<br />
This car measures {car?.exterior.length} <br />
in length and has a {car?.exterior.width} wheelbase .
</p>
</Col>
</Row>
<hr />
<Row>
<Col>
<Image src={car?.interior.image1} alt="No Image Available" />
<br />
<Image src={car?.interior.image2} alt="No Image Available" />{" "}
</Col>
<Col className="col2">
<h6>Interior finishes</h6>
<span>color</span>
<div
style={{
height: "3rem",
width: "10rem",
backgroundColor: car?.interior.color,
margin: "0.5rem",
border: "0.1rem solid black",
}}
/>
<ul>
{car?.interior.text.map((c) => (
<li key={++key}>{<p>{c} </p>}</li>
))}
</ul>
<h6>Cost {car?.cost}</h6>
</Col>
</Row>
<Row className="justify-content-end">
<Button id="btn_booknow" variant="info">
<Link to={bookingLink} state={{ car: car }}>
Book Now
</Link>
</Button>
</Row>
</Container>
</div>
);
}
export default CarDetails;
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from passport.backend.core.test.test_utils.utils import check_url_equals
from passport.backend.social.broker.communicators.communicator import AuthorizeOptions
from passport.backend.social.broker.communicators.LastFmCommunicator import LastFmCommunicator
from passport.backend.social.broker.exceptions import CommunicationFailedError
from passport.backend.social.broker.test import TestCase
from passport.backend.social.common.application import Application
from passport.backend.social.common.test.consts import (
APPLICATION_SECRET1,
APPLICATION_TOKEN1,
AUTHORIZATION_CODE1,
EXTERNAL_APPLICATION_ID1,
EXTERNAL_APPLICATION_ID2,
RETPATH1,
)
from passport.backend.social.common.useragent import Url
class TestLastFmCommunicatorParseAccessToken(TestCase):
def setUp(self):
super(TestLastFmCommunicatorParseAccessToken, self).setUp()
app = Application()
self._communicator = LastFmCommunicator(app)
def test_ok(self):
response = {
'session': {
'name': 'andrey1931',
'key': APPLICATION_TOKEN1,
'subscriber': 0,
},
}
token = self._communicator.parse_access_token(json.dumps(response))
self.assertEqual(token, {'value': APPLICATION_TOKEN1, 'expires': None})
def test_no_session(self):
with self.assertRaises(CommunicationFailedError):
self._communicator.parse_access_token(json.dumps({}))
def test_no_session_key(self):
response = {
'session': {
'name': 'andrey1931',
'subscriber': 0,
},
}
with self.assertRaises(CommunicationFailedError):
self._communicator.parse_access_token(json.dumps(response))
def test_invalid_authorization_code(self):
response = {
'error': 4,
'message': 'Unauthorized Token - This token has not been issued',
}
with self.assertRaises(CommunicationFailedError):
self._communicator.parse_access_token(json.dumps(response))
def test_unknown_error(self):
with self.assertRaises(CommunicationFailedError):
self._communicator.parse_access_token(json.dumps({'error': 12431551}))
def test_not_json_document(self):
with self.assertRaises(CommunicationFailedError):
self._communicator.parse_access_token('')
class TestLastFmCommunicatorGetAuthorizeRedirectUrl(TestCase):
def setUp(self):
super(TestLastFmCommunicatorGetAuthorizeRedirectUrl, self).setUp()
app = Application(
id=EXTERNAL_APPLICATION_ID1,
domain='social.yandex.net',
)
self._communicator = LastFmCommunicator(app)
def _build_authorize_url(self, callback_url, client_id=EXTERNAL_APPLICATION_ID1):
return str(
Url(
url='https://www.last.fm/api/auth',
params={
'api_key': client_id,
'cb': str(
Url(
url='https://social.yandex.net/broker/redirect',
params={'url': callback_url},
),
),
},
),
)
def test_callback_url(self):
check_url_equals(
self._communicator.get_authorize_url(AuthorizeOptions(callback_url=RETPATH1)),
self._build_authorize_url(callback_url=RETPATH1),
)
def test_client_id(self):
check_url_equals(
self._communicator.get_authorize_url(AuthorizeOptions(
callback_url=RETPATH1,
client_id=EXTERNAL_APPLICATION_ID2,
)),
self._build_authorize_url(
callback_url=RETPATH1,
client_id=EXTERNAL_APPLICATION_ID2,
),
)
class TestLastFmCommunicatorGetAccessTokenUrl(TestCase):
def setUp(self):
super(TestLastFmCommunicatorGetAccessTokenUrl, self).setUp()
app = Application(
id=EXTERNAL_APPLICATION_ID1,
secret=APPLICATION_SECRET1,
)
self._communicator = LastFmCommunicator(app)
def _build_access_token_url(self, signature, verifier=AUTHORIZATION_CODE1,
client_id=EXTERNAL_APPLICATION_ID1):
return str(
Url(
url='https://ws.audioscrobbler.com/2.0',
params={
'method': 'auth.getSession',
'format': 'json',
'api_sig': signature,
'token': verifier,
'api_key': client_id,
},
),
)
def _build_kwargs(self, **kwargs):
kwargs.setdefault('code', AUTHORIZATION_CODE1)
return kwargs
def test_code(self):
url, data, headers = self._communicator.get_access_token_request(
**self._build_kwargs(
code=AUTHORIZATION_CODE1,
)
)
check_url_equals(
url,
self._build_access_token_url(
verifier=AUTHORIZATION_CODE1,
signature='63fd3f223aa6f75e4d6372e312642d50',
),
)
self.assertIsNone(data)
self.assertIsNone(headers)
def test_client_id(self):
url, data, headers = self._communicator.get_access_token_request(
**self._build_kwargs(
client_id=EXTERNAL_APPLICATION_ID2,
)
)
check_url_equals(
url,
self._build_access_token_url(
client_id=EXTERNAL_APPLICATION_ID2,
signature='7382b171d7aefe42592b7ff1a2fbc5d5',
),
)
self.assertIsNone(data)
self.assertIsNone(headers)
def test_location(self):
url, data, headers = self._communicator.get_access_token_request(
**self._build_kwargs(
callback_url=RETPATH1,
)
)
check_url_equals(
url,
self._build_access_token_url(
# Location не указывается в access_token_url, поэтому не
# учитывается в подписи.
signature='63fd3f223aa6f75e4d6372e312642d50',
),
)
self.assertIsNone(data)
self.assertIsNone(headers)
|
import { initTardis } from "@datasources/tardis"
import { TardisInstrumentInfoFilter, tardisOptionInstrumentDataSource } from "@datasources/tardis_instrument_datasource"
import { IInstrumentInfo } from "@interfaces/services/instrument_info"
import { ensure } from "@lib/utils/ensure"
import { parseContractType } from "@lib/utils/helpers"
import * as _ from "lodash"
import { Context, Service, ServiceBroker } from "moleculer"
import { MFIV_ASSETS } from "node-volatility-mfiv"
// import * as Cron from "moleculer-cron"
import { InstrumentInfo } from "tardis-dev"
import { chainFrom } from "transducist"
import { PartialInstrumentInfo } from "./../src/lib/types"
export default class InstrumentInfoService extends Service {
private instrumentInfos: PartialInstrumentInfo[] = []
private lastUpdatedAt?: Date
public constructor(public broker: ServiceBroker) {
super(broker)
this.parseServiceSchema({
// Name
name: ensure("SERVICE_NAME", "instrument_info"),
// Settings
settings: {
refreshDefaults: {
exchange: ensure("INSTRUMENT_INFO_REFRESH_EXCHANGE", "deribit"),
asset: ensure("INSTRUMENT_INFO_REFRESH_BASE_CURRENCY"),
type: ensure("INSTRUMENT_INFO_REFRESH_TYPE ", "option"),
contractType: parseContractType(process.env.INSTRUMENT_INFO_REFRESH_CONTRACT_TYPE, [
"call_option",
"put_option"
]),
expirationDates: [],
timestamp: undefined
// active: false
} as IInstrumentInfo.InstrumentInfoParams
},
// Metadata
metadata: {},
// Dependencies
dependencies: [],
// mixins: [Cron],
// crons: [
// {
// name: "InstrumentInfoRefresh",
// cronTime: process.env.INSTRUMENT_INFO_REFRESH_CRONTIME,
// onTick: () => {
// console.log("InstrumentInfo doRefresh()")
// // const result = await this.actions.risklessRate({ source: this.settings.risklessRateSource })
// // this.logger.info("aave rate", result)
// // await this.broker.broadcast("rate.updated", result, ["index"])
// },
// timeZone: "UTC"
// }
// ],
// Actions
actions: {
refreshInstrumentInfos: {
visibility: "public",
params: {
exchange: { type: "string", enum: ["deribit"], default: "deribit" },
asset: { type: "string", enum: MFIV_ASSETS },
type: { type: "string", enum: ["option"], default: "option" },
contractType: { type: "array", items: "string", default: ["call_option", "put_option"] }
},
handler(
this: InstrumentInfoService,
ctx: Context<IInstrumentInfo.RefreshParams>
): Promise<IInstrumentInfo.RefreshResponse> {
this.logger.info("refresh", ctx.params)
return Promise.resolve(this.fetchInstruments({ ...ctx.params, expirationDates: [] }))
}
},
instrumentInfo: {
visibility: "public",
// TODO: Enable caching to this action
cache: {
// These cache entries will be expired after 5 seconds instead of 30.
ttl: 60 * 5
},
params: {
timestamp: { type: "string" },
exchange: { type: "string", enum: ["deribit"], default: "deribit" },
asset: { type: "string", enum: MFIV_ASSETS },
type: { type: "string", enum: ["option"], default: "option" },
contractType: { type: "array", items: "string", default: ["call_option", "put_option"] },
active: { type: "boolean", default: true },
expirationDates: { type: "array", items: "string", minSize: 1 }
},
handler(
this: InstrumentInfoService,
ctx: Context<IInstrumentInfo.InstrumentInfoParams>
): Promise<IInstrumentInfo.InstrumentInfoResponse> {
this.logger.info("instrumentInfo", ctx.params)
return Promise.resolve(this.fetchAvailableInstruments(ctx.params))
}
},
available: {
visibility: "public",
// TODO: Enable caching to this action
cache: {
// These cache entries will be expired after 5 seconds instead of 30.
ttl: 60 * 5
},
params: {
exchange: { type: "string", enum: ["deribit"], default: "deribit" },
asset: { type: "string", enum: MFIV_ASSETS }
},
handler(
this: InstrumentInfoService,
ctx: Context<IInstrumentInfo.AvailableParams>
): Promise<IInstrumentInfo.AvailableResponse> {
this.logger.info("available", ctx.params)
return this.fetchAvailable(ctx.params)
}
}
},
started(this: InstrumentInfoService) {
initTardis()
if (this.settings?.refreshDefaults === undefined) {
throw new Error("Settings have not been set yet. Check that `refreshDefaults` has been declared in settings.")
}
const refreshDefaults = this.settings.refreshDefaults as IInstrumentInfo.InstrumentInfoParams
/**
* Prime the cache with a fresh request
*/
return new Promise<void>((resolve, reject) => {
this.refresh(refreshDefaults)
.then(() => resolve())
.catch(reject)
})
}
})
}
/**
* Refresh the internal collection of PartialInstrumentInfo
*
* @param params
* @returns
*/
private async refresh(params: IInstrumentInfo.InstrumentInfoParams) {
return this.fetchInstruments(params)
}
private async fetchInstruments(
this: InstrumentInfoService,
params: IInstrumentInfo.InstrumentInfoParams
): Promise<PartialInstrumentInfo[]> {
this.logger.info("fetchInstruments", params)
const toPartialInstrumentInfo = (info: InstrumentInfo): PartialInstrumentInfo => {
const { baseCurrency, ...partial } = info
const transformed = { ...partial, asset: baseCurrency }
return _.pick(transformed, [
"id",
"exchange",
"asset",
"type",
"active",
"availableTo",
"availableSince",
"optionType",
"expiry"
]) as PartialInstrumentInfo
}
this.instrumentInfos = chainFrom(await tardisOptionInstrumentDataSource({ ...params, baseCurrency: params.asset }))
.map(toPartialInstrumentInfo)
.toArray()
this.lastUpdatedAt = new Date()
this.logger.info(`found ${this.instrumentInfos.length} instruments`)
return this.instrumentInfos
}
/**
* Find the ids of the available InstrumentInfos based on the params context
* @param params
* @returns string[]
*/
private fetchAvailableInstruments(params: IInstrumentInfo.InstrumentInfoParams): string[] {
const timestamp = params.timestamp as string
const Available = (item: PartialInstrumentInfo) =>
item.availableSince <= timestamp && item.availableTo ? item.availableTo > timestamp : true
this.logger.info(`fetching available instruments for ${timestamp}`, params)
const availableInstruments = chainFrom(this.instrumentInfos)
.filter(Available)
.filter(item => !!item.expiry && params.expirationDates.includes(item.expiry))
.map(item => item.id)
.toArray()
this.logger.info(`Found ${availableInstruments.length} available instruments`, availableInstruments)
return availableInstruments
}
private async fetchAvailable(params: IInstrumentInfo.AvailableParams): Promise<string[]> {
this.logger.info("fetch available instruments", params)
const tardisParams: TardisInstrumentInfoFilter = {
exchange: params.exchange,
baseCurrency: params.asset,
contractType: ["call_option", "put_option"],
type: "option"
}
const available = chainFrom(await tardisOptionInstrumentDataSource(tardisParams))
.map(item => item.id)
.toArray()
this.logger.info(`Found ${available.length} available instruments`, available)
return available
}
}
|
import { motion } from "framer-motion";
import { useRef, useEffect, useState } from "react";
import images from "./images";
import './slider.css';
function Carousel() {
const [width, setWidth] = useState(0);
const carousel = useRef();
const [currentIndex, setCurrentIndex] = useState(0);
useEffect(() => {
setWidth(carousel.current.scrollWidth - carousel.current.offsetWidth);
}, []);
// Auto-slide delay in milliseconds (e.g., 3000ms = 3 seconds)
const autoSlideDelay = 3000;
useEffect(() => {
const interval = setInterval(() => {
// Calculate the next index for auto-sliding
const nextIndex = (currentIndex + 1) % images.length;
setCurrentIndex(nextIndex);
}, autoSlideDelay);
// Clear the interval when the component unmounts or currentIndex changes
return () => clearInterval(interval);
}, [currentIndex]);
return (
<div className="slider">
<motion.div ref={carousel} className="carousel" whileTop={{ cursor: "grabbing" }}>
<motion.div
drag="x"
dragConstraints={{ right: 0, left: -width }}
className="inner-carousel"
style={{ transform: `translateX(${-currentIndex * 100}%)` }} // Update the position based on the currentIndex
>
{images.map((Image, index) => (
<motion.div className="item" key={Image}>
<img src={Image} alt="" />
</motion.div>
))}
</motion.div>
</motion.div>
</div>
);
}
export default Carousel;
|
import type { Items } from "./Items"
export default function Listing( props: Items) {
const {items} = props;
const determineCurrency = (currency: string) => {
if (currency === 'USD') {
return '$';
} else if (currency === 'EUR') {
return '€';
} else {
return currency;
}
};
const determineQuantity = (quantity: number) => {
if (quantity <= 10) {
return 'level-low';
} else if (quantity <= 20) {
return 'level-medium';
} else {
return 'level-high';
}
}
const shortenText = (text : string) => {
if (text.length > 50) {
return text.slice(0,50) + '...';
}
return text
}
return (
<div className="item-list">
{
items.map((item, index) => {
return <div className="item">
<div className="item-image">
<a href = {item.url}>
{item.MainImage && item.MainImage.url_570xN ? <img className="" src={item.MainImage.url_570xN}></img> : <></>}
</a>
</div>
<div className="item-details">
<p className="item-title">{item.title ? shortenText(item.title) : ''}</p>
<p className="item-price">{`${determineCurrency(item.currency_code)}${item.price}`}</p>
<p className = {`item-quantity ${determineQuantity(item.quantity)}`}>{item.quantity}</p>
</div>
</div>
})
}
</div>
)
}
|
This has been taken from:
https://community.bose.com/t5/SoundTouch-Archive/Alarm-Clock-function-via-Raspberry-Pi/td-p/44575
Alarm Clock function via Raspberry Pi
Deskyeti
Deskyeti Friendly Fanatic
03-24-2017 01:07 PM
Alarm Clock function via Raspberry Pi
I was as suprised as everyone else to discover the SoundTouch does not have an alarm function. It looks like people have been asking for this for ages and several people have baked their own solution. I had a poke around the API and I found that a few simple commands can be used to create a working alarm clock.
You need a little bit of UNIX skill but only very basic stuff to get this working on a Raspberry Pi (or any other system you have up & running all the time).
Create a BASH script form the code below, mine is called stWake.sh and I stored it in the /home/pi directory - I've tried to make it easy to understand by adding lots of comments, the actual script is only a few lines long.......
#!/bin/bash
# Script to turn on the SoundTouch speaker
# Set volume to level 1 (don't want to deafen anyone)
# Set to play BBC Radio 5 Live
# Increase the volume in steps up to desired level
if [ "$1" = "" ]; then
echo "parameter1 is device IP address minus the port number"
echo "parameter2 is target volume level between 1 and 100 - 100 is VERY LOUD"
echo "parameter3 is the time value for the volume ramp up"
exit
fi
if [ "$2" = "" ]; then
echo "parameter2 is target volume"
exit
fi
if [ "$3" = "" ]; then
echo "Parameter3 is the time value"
exit
fi
# SoundTouch listens on port 8090, set the host URL based on P1 + the port number
host=$1:8090
# Zero the volume level in the counter
vol=0
# Target volume is P2
targetvol=$2
# time between volume increase commands - this can be whole number or fractions e.g. .5 or .2
rampup=$3
# Set the volume to 1 in case someone left the speaker turned up loud
curl --request POST --header "Content-Type: application/xml" --data ' <volume>1</volume> ' $host/volume
# Set the station you wish to listen to - I have BBC Radio 5 Live
# If you want to use a different station, set the speaker playing the required station and then#
# from a browser enter the following HTTP://your.speaker.ip.address:8090/playing_now
# This will return full details of the station. You only need the location and the itemName fields.
# Replace this in the command below to set your own station choice.
curl --request POST --header "Content-Type: application/xml" --data ' <ContentItem source="INTERNET_RADIO" sourceAccount="" location="76505"> <itemName>BBC Radio 5 Live - UK Only</itemName></ContentItem> ' $host/select
# Wait for 2 seconds while the station starts to play
sleep 2
# This loop uses the input parameters P2 - targetvol & P3 - rampup to gradually increase the volume to the desired level.
# I have found a delay of .2 works quite well and for me a target of 25 is good on my ST10 speaker
until [ $vol -ge $targetvol ]; do
let vol+=1
curl --request POST --header "Content-Type: application/xml" --data " <volume>$vol</volume> " $host/volume
sleep $rampup
echo volume $vol
done
Remember to set the script as executable (CHMOD +x stWake.sh)
The script takes three parameters - the IP address of your chosen speaker, the target volume you want it to go up to and finally a delay which controls the speed of the rampup which can be in seconds or fractions of seconds (e.g. .5 or .2)
Create a CRON job at your chosen time and day(s) with the settings
20 6 * * 1-5 /home/pi/stWake.sh your.speaker.ip.address 25 .2
This will fire the alarm at 06:20 Monday to Friday and will turn on the speaker to the selected station and gradually ramp up the volume to your chosen level.
Create another CRON job to turn it off with this script:-
#!/bin/bash
#Parameter 1 is the IP addres
if [ "$1" = "" ]; then
echo "Parameter1 is the IP Address of your speaker"
exit
fi
host=$1:8090
curl --request POST --header "Content-Type: application/xml" --data ' <key state="press" sender="Gabbo">POWER</key> ' http://$host/key
I called this on stShutdown.sh and it is called with a single parameter which is the IP address of your chosen speaker - /home/pi/stShutdown.sh your.speaker.ip.address
|
<!-- <?xml version="1.0" encoding="UTF-8"?> -->
<!-- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" -->
<!-- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -->
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:p="http://xmlns.jcp.org/jsf/passthrough"
>
<ui:composition template="/templates/common.xhtml">
<ui:define name="header" >
<h:outputStylesheet library="css" name="list_picture.css" />
<h:outputStylesheet library="css" name="jasny-bootstrap.min.css" />
</ui:define>
<ui:define name="title">
Add picture in album
<ui:insert name="titleAlbumId" />
</ui:define>
<ui:define name="content">
<!-- h:form -->
<h:form enctype="multipart/form-data">
<!-- h:form -->
<ui:insert name="inputSelectAlbumId" />
<div class="form-group">
<h:outputLabel for="title" value="Title" />
<h:inputText id="title" p:placeholder="Title" styleClass="form-control" p:required="required" value="#{pictureController.picture.title}"
title="Title"/>
<!-- validator="#{ajoutAlbum.validerNomAlbum}" -->
</div>
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-preview thumbnail" data-trigger="fileinput" style="width: 200px; height: 150px;"></div>
<div>
<span class="btn btn-default btn-file">
<span class="fileinput-new">Select image</span>
<span class="fileinput-exists">Change</span>
<h:inputFile id="uriString" name="uriString" value="#{pictureController.picture.part}" p:type="file" p:accept="image/*" p:required="required" />
</span>
<a href="#" class="btn btn-default fileinput-exists" data-dismiss="fileinput">Remove</a>
</div>
</div>
</div>
<ui:insert name="submitButton" />
</h:form>
</ui:define>
<ui:define name="footer">
<h:outputScript name="jasny-bootstrap.min.js" library="js" />
</ui:define>
</ui:composition>
</html>
<!-- vim: sw=4 ts=4 et:
-->
|
import 'package:copy_with_extension/copy_with_extension.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:invidious/downloads/models/downloaded_video.dart';
import 'package:invidious/videos/models/base_video.dart';
import 'package:invidious/videos/models/dislike.dart';
import 'package:logging/logging.dart';
import '../../downloads/states/download_manager.dart';
import '../../globals.dart';
import '../../player/states/player.dart';
import '../../settings/models/errors/invidiousServiceError.dart';
import '../../settings/states/settings.dart';
import '../models/video.dart';
part 'video.g.dart';
const String coulnotLoadVideos = 'cannot-load-videos';
final log = Logger('Video');
class VideoCubit extends Cubit<VideoState> {
final DownloadManagerCubit downloadManager;
final PlayerCubit player;
final SettingsCubit settings;
VideoCubit(super.initialState, this.downloadManager, this.player, this.settings) {
onReady();
}
Future<void> onReady() async {
try {
var state = this.state.copyWith();
Video video = await service.getVideo(state.videoId);
state.video = video;
state.loadingVideo = false;
if (settings.state.useReturnYoutubeDislike) {
Dislike dislike = await service.getDislikes(state.videoId);
state.dislikes = dislike.dislikes;
}
emit(state);
getDownloadStatus();
if (settings.state.autoplayVideoOnLoad) {
playVideo(false);
}
} catch (err) {
var state = this.state.copyWith();
if (err is InvidiousServiceError) {
state.error = (err).message;
} else {
state.error = coulnotLoadVideos;
}
state.loadingVideo = false;
emit(state);
rethrow;
}
}
getDownloadStatus() {
var state = this.state.copyWith();
state.downloadedVideo = db.getDownloadByVideoId(state.videoId);
initStreamListener();
if (!isClosed) emit(state);
}
@override
close() async {
var state = this.state.copyWith();
state.scrollController.dispose();
if (downloadManager.state.downloadProgresses.containsKey(state.videoId)) {
downloadManager.removeListener(state.videoId, onDownloadProgress);
}
super.close();
}
onDownload() {
var state = this.state.copyWith();
state.downloading = true;
state.downloadProgress = 0;
emit(state);
}
onDownloadProgress(double progress) {
var state = this.state.copyWith();
if (state.video != null) {
state.downloadProgress = progress;
if (progress < 1) {
state.downloading = true;
} else {
getDownloadStatus();
state = this.state.copyWith();
state.downloading = false;
}
emit(state);
}
}
initStreamListener() {
if (downloadManager.state.downloadProgresses.containsKey(state.videoId)) {
downloadManager.addListener(state.videoId, onDownloadProgress);
}
}
togglePlayRecommendedNext(bool? value) {
var state = this.state.copyWith();
settings.setPlayRecommendedNext(value ?? false);
emit(state);
}
selectIndex(int index) {
var state = this.state.copyWith();
state.selectedIndex = index;
emit(state);
scrollUp();
}
void restartVideo(bool? audio){
if (state.video != null) {
player.showBigPlayer();
player.seek(Duration.zero);
}
}
void playVideo(bool? audio) {
if (state.video != null) {
List<BaseVideo> videos = [state.video!];
if (!settings.state.distractionFreeMode && settings.state.playRecommendedNext) {
videos.addAll(state.video?.recommendedVideos ?? []);
}
player.playVideo(videos, audio: audio);
}
}
scrollUp() {
state.scrollController.animateTo(0, duration: animationDuration, curve: Curves.easeInOutQuad);
}
}
@CopyWith(constructor: "_")
class VideoState {
Video? video;
int? dislikes;
bool loadingVideo = true;
int selectedIndex = 0;
String videoId;
bool isLoggedIn = service.isLoggedIn();
bool downloading = false;
double downloadProgress = 0;
DownloadedVideo? downloadedVideo;
ScrollController scrollController = ScrollController();
double opacity = 1;
String error = '';
VideoState({required this.videoId});
bool get downloadFailed => downloadedVideo?.downloadFailed ?? false;
bool get isDownloaded {
if (video != null) {
return downloadedVideo != null;
} else {
return false;
}
}
VideoState._(this.scrollController, this.video, this.dislikes, this.loadingVideo, this.selectedIndex, this.videoId,
this.isLoggedIn, this.downloading, this.downloadProgress, this.downloadedVideo, this.opacity, this.error);
}
|
/* eslint-disable no-underscore-dangle */
import React, { useMemo } from 'react';
import { useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
interface ItemProps {
orga: IOrganisation;
}
const OrgasListItem: React.FC<ItemProps> = ({ orga }) => {
return (
<Link to={`/orga/${orga._id}`} className='card' key={orga._id}>
<div className='grow font-bold text-secondary'>{orga.orgName}</div>
</Link>
);
};
const OrgasList: React.FC = () => {
const organisations = useSelector((state: IState) => state.user.organisations);
const memoedOrgas = useMemo(() => {
return organisations;
}, [organisations]);
return (
<>
<h2 className='font-bold mb-4'>Vos groupes :</h2>
<div className='mb-8'>
{memoedOrgas &&
memoedOrgas?.length > 0 &&
memoedOrgas?.map((orga: IOrganisation) => <OrgasListItem key={orga?._id} orga={orga} />)}
</div>
</>
);
};
export default OrgasList;
|
import React from "react";
import styled from "styled-components";
import { Search, ShoppingCartOutlined } from "@material-ui/icons";
import { Badge } from "@material-ui/core";
import { mobil } from "../resposive";
import { useNavigate } from "react-router-dom";
const Container = styled.div`
height: 60px;
${mobil({ height: "50px" })}
`;
const Wrapper = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 20px;
${mobil({ padding: "10px 0" })}
`;
const Left = styled.div`
flex: 1;
display: flex;
align-items: center;
`;
const Language = styled.span`
font-size: 14px;
cursor: pointer;
${mobil({ display: "none" })}
`;
const SearchContainer = styled.div`
display: flex;
align-items: center;
border: 0.5px solid lightgray;
margin-left: 25px;
${mobil({ marginLeft: "5px" })}
padding: 5px;
`;
const Input = styled.input`
border: none;
${mobil({ width: "50px" })}
`;
const Center = styled.div`
flex: 1;
text-align: center;
`;
const Logo = styled.h1`
font-weight: bold;
white-space: nowrap;
${mobil({ fontSize: "20px" })}
`;
const Right = styled.div`
flex: 1;
display: flex;
align-items: center;
justify-content: flex-end;
${mobil({ justifyContent: "center", flex: 2 })}
`;
const MenuItem = styled.div`
font-size: 14px;
cursor: pointer;
margin-left: 25px;
white-space: nowrap;
${mobil({ fontSize: "12px", marginLeft: "5px" })}
`;
const Navbar = () => {
const navigate = useNavigate();
return (
<Container>
<Wrapper>
<Left>
<Language>EN</Language>
<SearchContainer>
<Input placeholder="Search" />
<Search style={{ color: "gray", fontSize: 16 }} />
</SearchContainer>
</Left>
<Center>
<Logo>MEN'S WEAR</Logo>
</Center>
<Right>
<MenuItem onClick={() => navigate("/register")}>REGISTER</MenuItem>
<MenuItem onClick={() => navigate("/login")}>SIGN IN</MenuItem>
<MenuItem>
<Badge badgeContent={4} color="primary">
<ShoppingCartOutlined />
</Badge>
</MenuItem>
</Right>
</Wrapper>
</Container>
);
};
export default Navbar;
|
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="{% url "movies:by_genres" %}">
<i class="fas fa-film"></i> Main page</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown"
aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavDropdown">
<ul class="navbar-nav">
{% if user.is_authenticated %}
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button"
data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-photo-video"></i> My movies lists
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
{% for list in user.movies_lists.all %}
<li><a class="dropdown-item" href="{{ list.get_absolute_url }}">
<i class="fas fa-film"></i> {{ list.title }}
</a></li>
{% endfor %}
</ul>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button"
data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-user-circle"></i> My account <strong>[ {{ user.username }} ]</strong>
</a>
<ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<li><a class="dropdown-item" href="{% url "users:profile" %}">
<i class="fas fa-user"></i> Profile</a>
</li>
<li><a class="dropdown-item" href="{% url "users:password_change" %}">
<i class="fas fa-user-edit"></i>Change password
</a></li>
<li><a class="dropdown-item link-danger" href="{% url "users:logout" %}">
<i class="fas fa-sign-out-alt"></i> Logout
</a></li>
</ul>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" style="color: var(--bs-blue)" href="{% url "users:signup" %}">
<strong><i class="fas fa-user-plus"></i> Sign up</strong>
</a>
</li>
<li class="nav-item">
<a class="nav-link" style="color: var(--bs-green)" href="{% url "users:login" %}">
<strong><i class="fas fa-sign-out-alt"></i> Login</strong>
</a>
</li>
{% endif %}
</ul>
</div>
</div>
</nav>
<br class="my-2">
|
package com.jaspergoes.bilight;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.jaspergoes.bilight.helpers.PortMapper;
import com.jaspergoes.bilight.milight.Controller;
import java.util.regex.Pattern;
public class AddRemoteActivity extends AppCompatActivity {
private EditText port;
private EditText ip;
private TextView ip_local_warn;
private Button connect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Should not be able to get here, if Controller has not been instantiated in MainActivity */
if (Controller.INSTANCE == null) {
finish();
return;
}
setContentView(R.layout.activity_add_remote);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
TextWatcher validate = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
validate();
}
@Override
public void afterTextChanged(Editable editable) {
validate();
}
};
ip = (EditText) findViewById(R.id.edit_ipaddress);
ip.addTextChangedListener(validate);
port = (EditText) findViewById(R.id.edit_port);
port.setText(Integer.toString(Controller.defaultMilightPort));
port.addTextChangedListener(validate);
ip_local_warn = (TextView) findViewById(R.id.ip_local_warn);
ip_local_warn.setVisibility(View.GONE);
connect = (Button) findViewById(R.id.connect);
connect.setEnabled(false);
connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Controller.isConnecting = true;
new Thread(new Runnable() {
@Override
public void run() {
Controller.INSTANCE.setDevice(ip.getText().toString().trim(), Integer.parseInt(port.getText().toString().trim()), getApplicationContext());
}
}).start();
finish();
}
});
findViewById(R.id.current_external_ip).setVisibility(View.GONE);
new Thread(new Runnable() {
@Override
public void run() {
/* Try UPnP approach */
final String outerIP = PortMapper.getExternalIP();
if (outerIP != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Button b = (Button) findViewById(R.id.current_external_ip);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText e = (EditText) findViewById(R.id.edit_ipaddress);
e.setText(outerIP);
e.requestFocus();
}
});
b.setVisibility(View.VISIBLE);
}
});
}
}
}).start();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putString("hostip", ((EditText) findViewById(R.id.edit_ipaddress)).getText().toString());
savedInstanceState.putString("hostport", ((EditText) findViewById(R.id.edit_port)).getText().toString());
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
((EditText) findViewById(R.id.edit_ipaddress)).setText(savedInstanceState.getString("hostip"));
((EditText) findViewById(R.id.edit_port)).setText(savedInstanceState.getString("hostport"));
validate();
}
private void validate() {
boolean valid = true;
boolean local = false;
String t;
t = ip.getText().toString().trim();
Pattern ipPattern = Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
if (!ipPattern.matcher(t).matches()) {
Pattern hostPattern = Pattern.compile("(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\\.)+[a-zA-Z]{2,63}$)");
if (!hostPattern.matcher(t).matches()) {
valid = false;
}
} else {
local = isLocalV4Address(t);
}
t = port.getText().toString().trim();
try {
int n = Integer.parseInt(t);
if (n < 1 || n > 65535) valid = false;
} catch (NumberFormatException e) {
valid = false;
}
ip_local_warn.setVisibility(local ? View.VISIBLE : View.GONE);
connect.setEnabled(valid);
}
private boolean isLocalV4Address(String ipAddress) {
/* Fuggggggly function to check whether ip address entered is or might be local */
boolean isLocal = false;
if (ipAddress != null && !ipAddress.isEmpty()) {
String[] ip = ipAddress.split("\\.");
if (ip.length == 4) {
try {
short[] ipNumber = new short[]{
Short.parseShort(ip[0]),
Short.parseShort(ip[1]),
Short.parseShort(ip[2]),
Short.parseShort(ip[3])
};
if (ipNumber[0] == 10) { // Class A
isLocal = true;
} else if (ipNumber[0] == 172 && (ipNumber[1] >= 16 && ipNumber[1] <= 31)) { // Class B
isLocal = true;
} else if (ipNumber[0] == 192 && ipNumber[1] == 168) { // Class C
isLocal = true;
}
} catch (NumberFormatException e) {
}
}
}
return isLocal;
}
}
|
<!-- Concept: Template -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo App</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
</head>
<body>
<div style="margin-top: 50px;" class="ui container">
<h1 class="ui center aligned header">To Do App</h1>
<!-- When the submit button is pressed, this form goes to the add route -->
<form class="ui form" action="/add" method="post">
<div class="field">
<label>Todo Title</label>
<input type="text" name="title" placeholder="Enter Todo..."><br>
</div>
<button class="ui blue button" type="submit">Add</button>
</form>
<hr>
<!-- This loop iterates through every item in the todo_list list -->
{% for todo in todo_list %}
<div class="ui segment">
<p class="ui big header">{{todo.id }} | {{ todo.title }}</p>
<!-- Checks if the todo item is completed and indicates it -->
{% if todo.complete == False %}
<span class="ui gray label">Not Complete</span>
{% else %}
<span class="ui green label">Completed</span>
{% endif %}
<!-- When this link is pressed the page goes to the update route -->
<a class="ui blue button" href="/update/{{ todo.id }}">Update</a>
<!-- When this link is pressed the page goes to the delete route -->
<a class="ui red button" href="/delete/{{ todo.id }}">Delete</a>
</div>
{% endfor %}
</div>
</body>
</html>
|
import Footer from '@/components/Footer/Footer.component';
import Metadata from '@/components/Metadata.component';
import Navbar from '@/components/Navbar/Navbar.component';
import VideoPlayer from '@/components/VideoPlayer/VideoPlayer.component';
import { ServerAxios } from '@/libs/http';
import styles from '@/styles/pages/assignmentById.module.css';
import { DocumentIcon, UserCircleIcon, VideoCameraIcon } from '@heroicons/react/20/solid';
import { GetServerSideProps, NextPage } from 'next';
import { useState } from 'react';
interface Material {
id: string;
name: string;
type: 'FILE' | 'VIDEO';
location: string;
}
interface Teacher {
firstname: string;
lastname: string;
nickname?: string;
id: string;
}
interface Lesson {
id: string;
title: string;
descripton?: any;
materialsId: string[];
materials: Material[];
lastUpdated: string;
teacherId: string;
teacher: Teacher;
}
interface Assignment {
id: string;
assignDate: Date;
expireDate: Date;
isFinished: boolean;
assignToId: string;
lessonId: string;
lesson: Lesson;
}
type Props = {
assignment: Assignment
}
const CourseWatchPage: NextPage<Props> = ({ assignment }) => {
const [currentVideo, setCurrentVideo] = useState<string | null>(
assignment.lesson.materials.find((m) => m.type === 'VIDEO')?.location || null
)
const formatLastUpdated = new Intl.DateTimeFormat('th-TH', {
month: 'long',
day: '2-digit',
year: 'numeric'
})
.format(new Date(assignment.lesson.lastUpdated))
const changeVideo = (id: string) => {
setCurrentVideo(id);
}
return (
<>
<Metadata
title={`${assignment.lesson.title || 'บทเรียน'} | สถาบันกวดวิชาเดอะโปร - THE PRO TUTOR`}
/>
<Navbar />
<div className={styles.layout}>
<div className={styles.root}>
<div className='container mx-auto w-full'>
<div className='pt-24 py-10 h-full'>
<h2 className='font-bold text-2xl md:text-4xl text-white mb-8 px-4'>
{assignment.lesson.title}
</h2>
<div className='grid grid-cols-1 lg:grid-cols-2 gap-1 md:gap-2 px-4 md:px-0 h-full'>
<div className='w-full h-full aspect-video'>
<VideoPlayer source={currentVideo || ''} />
</div>
<section className='lg:px-8 py-4 lg:py-2 text-white flex flex-col gap-4 w-full'>
<div className='bg-white text-black p-4 rounded flex flex-row items-center gap-2'>
<UserCircleIcon width={52} height={52} />
<div className='flex flex-col'>
<h6 className='font-medium text-large md:text-xl'>
{assignment.lesson.teacher.firstname} {assignment.lesson.teacher.lastname} {
assignment.lesson.teacher.nickname && (
`(${assignment.lesson.teacher.nickname})`
)}
</h6>
<p>อัพเดทล่าสุด: {formatLastUpdated}</p>
</div>
</div>
{/* {assignment.lesson.descripton && (
<div className='border p-4 rounded flex flex-col gap-2'>
<h4 className='font-medium text-2xl underline'>
คำอธิบาย
</h4>
<article className='prose prose-base'>
{assignment.lesson.descripton}
</article>
</div>
)} */}
<div className='border p-4 rounded flex flex-col gap-2 w-full'>
<h4 className='font-medium text-2xl underline'>
เอกสารประกอบการเรียน
</h4>
<ul className='grid grid-cols-1'>
{assignment.lesson.materials.map((material, index) => {
if (material.type === 'FILE') {
return (
<li key={index}>
<a
key={index}
href={`${process.env.NEXT_PUBLIC_URL}/api/file/${material.id}`}
target='_blank'
rel="noreferrer"
className='h-full inline-flex gap-2 items-center cursor-pointer hover:underline'
>
<DocumentIcon width={20} height={20} />
{material.name}
</a>
</li>
)
} else {
return (
<li
key={index}
onClick={() => changeVideo(material.location)}
className='inline-flex gap-2 items-center cursor-pointer hover:underline'
>
<VideoCameraIcon width={20} height={20} />
{material.name}
</li>
)
}
})}
</ul>
</div>
</section>
</div>
</div>
</div>
</div>
<Footer />
</div>
</>
)
}
export const getServerSideProps: GetServerSideProps<Props> = async ({ req, params }) => {
const { status, data } = await ServerAxios.get<Assignment>(
`/assignment/${params!.id}`, {
withCredentials: true,
headers: {
Cookie: req.headers.cookie
},
validateStatus: () => true
})
console.log(JSON.stringify(data, null, 4));
if (status === 404) {
return {
notFound: true
}
}
return {
props: {
assignment: data
}
}
}
export default CourseWatchPage
|
import { useEffect } from 'react';
// import ReactDOM from 'react-dom';
// import { } from '@ya.praktikum/react-developer-burger-ui-components';
import { useDispatch, useSelector } from 'react-redux';
import {
Outlet,
useLoaderData,
useLocation,
useNavigate,
} from 'react-router-dom';
import { OrderCard, Modal } from '../../ui-kit/';
import { useModal } from '../../../hooks/useModal';
import { PATH, POINT, WebsocketStatus } from '../../../utils/data';
import { OrderDetails } from '../order-details/order-details';
/* ####################
СТИЛИ и ТИПИЗАЦИЯ ======
##################### */
import styles from './order-list.module.scss';
import { OrderListPropTypes } from './order-list.types.js';
import {
feedWsConnect,
feedWsDisconnect,
myFeedWsConnect,
myFeedWsDisconnect,
} from '../../../services';
/* ####################
|||||||||||||||||||||||
##################### */
export function OrderList({ type }) {
const dispatch = useDispatch();
const location = useLocation();
const navigate = useNavigate();
const { status } = useSelector((store) => store[type]);
const { tokenData } = useSelector((store) => store.user);
const { openModal, closeModal } = useModal();
const { isModalOpen } = useSelector((store) => store.modal);
const { orders } = useSelector((store) => store[type]);
const background = location.state && location.state.background;
const oneOrderFlag =
location.pathname.includes(`/${PATH.ORDERS}/`) && !background;
useEffect(() => {
// Инициализация данных из WSS
if (status === WebsocketStatus.OFFLINE) {
dispatch(
{
feed: feedWsConnect(
`${process.env.REACT_APP_WSS_URL}${POINT.ORDERS_ALL}`,
),
myFeed: myFeedWsConnect(
`${process.env.REACT_APP_WSS_URL}${
POINT.ORDERS
}?token=${localStorage.getItem('accessToken').split(' ').pop()}`,
),
}[type],
);
}
return () => {
dispatch(
{ feed: feedWsDisconnect(), myFeed: myFeedWsDisconnect() }[type],
);
};
}, [tokenData]);
return !oneOrderFlag ? (
<>
<ul className={styles.wrapper}>
{Object.keys(orders)
.sort((a, b) => b - a)
.map((number, index) => {
const order = orders[number];
return (
<li
className={styles.card}
onClick={() => {
openModal();
navigate(`${order.number}`, {
state: { background: location },
key: order.number,
});
}}
key={order.number + 'list' + index}
>
<OrderCard order={order} />
</li>
);
})}
</ul>
<Modal status={isModalOpen} closeModal={closeModal}>
<Outlet />
</Modal>
</>
) : (
<OrderDetails type={type} />
);
}
/* #####################
##################### */
OrderList.propTypes = OrderListPropTypes;
|
The ``101-lazy_matrix_mul`` module
Using ``lazy_matrix_mul``
---------------------
First import the function from the module:
>>> lazy_matrix_mul = __import__('101-lazy_matrix_mul').lazy_matrix_mul
Now use it:
>>> print(lazy_matrix_mul([[1, 2], [3, 4]], [[1, 2], [3, 4]]))
[[ 7 10]
[15 22]]
matrixes must be lists:
>>> lazy_matrix_mul(1.34, [[1, 2], [3, 4]])
Traceback (most recent call last):
...
ValueError: Scalar operands are not allowed, use '*' instead
>>> lazy_matrix_mul([[1, 2], [3, 4]], 0)
Traceback (most recent call last):
...
ValueError: Scalar operands are not allowed, use '*' instead
matrixes must be lists of lists:
>>> lazy_matrix_mul([1, 2, 3, 4], [[1, 2], [3, 4]])
Traceback (most recent call last):
...
ValueError: shapes (4,) and (2,2) not aligned: 4 (dim 0) != 2 (dim 0)
>>> lazy_matrix_mul([[1, 2], [3, 4]], ['a', 'b', 'c', 'd'])
Traceback (most recent call last):
...
ValueError: shapes (2,2) and (4,) not aligned: 2 (dim 1) != 4 (dim 0)
matrixes should contain only integers of floats:
>>> lazy_matrix_mul([['hi', 2.2], [True, 2]], [[1, 2], [3, 4]])
Traceback (most recent call last):
...
TypeError: invalid data type for einsum
>>> lazy_matrix_mul([[1, 2], [3, 4]], [['hi', 2.2], [True, 2]])
Traceback (most recent call last):
...
TypeError: invalid data type for einsum
matrixes rows must be of same size:
>>> lazy_matrix_mul([[9, 2], [1, 4, 7]], [[1, 2], [3, 4]])
Traceback (most recent call last):
...
ValueError: setting an array element with a sequence.
>>> lazy_matrix_mul([[1, 2], [3, 4]], [[9, 2], [1, 4, 7]])
Traceback (most recent call last):
...
ValueError: setting an array element with a sequence.
matrixes can't be empty
>>> lazy_matrix_mul([], [[1, 2], [3, 4]])
Traceback (most recent call last):
...
ValueError: shapes (0,) and (2,2) not aligned: 0 (dim 0) != 2 (dim 0)
>>> lazy_matrix_mul([[1, 2], [3, 4]], [])
Traceback (most recent call last):
...
ValueError: shapes (2,2) and (0,) not aligned: 2 (dim 1) != 0 (dim 0)
missing two arguments
>>> lazy_matrix_mul()
Traceback (most recent call last):
...
TypeError: lazy_matrix_mul() missing 2 required positional arguments: 'm_a' and 'm_b'
missing one argument
>>> lazy_matrix_mul([[4, 5], [1, 2]])
Traceback (most recent call last):
...
TypeError: lazy_matrix_mul() missing 1 required positional argument: 'm_b'
matrixes can't be multiplied:
>>> lazy_matrix_mul([[1, 4], [2, 5]], [[1, 4], [2, 5], [1,7]])
Traceback (most recent call last):
...
ValueError: shapes (2,2) and (3,2) not aligned: 2 (dim 1) != 3 (dim 0)
|
import pytest
import requests
import copy
import allure
from resources.config import *
from resources.constants import *
@allure.title("Creating an order")
class TestCreatingOrder:
@allure.title("Creating an order with ingredients")
@allure.description("Verifying that an authenticated user can place an order by selecting ingredients")
def test_creating_order_with_ingredients(self, login_user, create_ingredients):
response_token = login_user.json()['accessToken']
headers = {"authorization": response_token}
response = requests.post(f"{def_url}orders", headers=headers, data=create_ingredients)
assert response.status_code == 200
assert response.json()['success'] == True
assert response.json()['name'] is not None
assert response.json()['order'] is not None
@allure.title("Creating an order without ingredients")
@allure.description("Checking that an authenticated user cannot place an order without selecting ingredients")
def test_creating_order_without_ingredients(self, login_user):
data = {}
response_token = login_user.json()['accessToken']
headers = {"authorization": response_token}
response = requests.post(f"{def_url}orders", headers=headers, data=data)
assert response.status_code == 400, "It didn't return the response code we were expecting."
assert response.json()['success'] == False
assert response.json()['message'] == "Ingredient ids must be provided"
@allure.title("Creating an order with an invalid hash")
@allure.description("Verifying that an authenticated user cannot place an order by specifying the wrong ingredients")
def test_creating_order_with_invalid_hash(self, login_user, create_ingredients):
data = copy.deepcopy(create_ingredients)
data["ingredients"] = ["1", "2"]
response_token = login_user.json()['accessToken']
headers = {"authorization": response_token}
response = requests.post(f"{def_url}orders", headers=headers, data=data)
assert response.status_code == 500, "It didn't return the response code we were expecting."
@allure.title("Creation of an order by a non-authenticated user")
@allure.description("Checking that an un-authenticated user can place an order by selecting ingredients")
def test_creating_order_by_non_authenticated_user(self, create_ingredients):
response = requests.post(f"{def_url}orders", data=create_ingredients)
assert response.status_code == 200, "It didn't return the response code we were expecting."
assert response.json()['success'] == True
|
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link rel="stylesheet" href="./css/login.css">
<script src="js/funcoes.js"></script>
</head>
<body>
<!DOCTYPE html>
<html lang="pt">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./css/login.css">
<title>Moto Dicas</title>
</head>
<body style="background-color: black;">
<header>
<main id="Inicio" class="inicio">
<div class="navbar" id="nav">
<ul>
<li> <a href="./index.html">Inicio<br>
<div class="barra"></div>
</a> </li>
<li> <a href="./projeto.html">Projeto<br>
<div class="barra"></div>
</a> </li>
<li> <a> | </a> </li>
<li> <a href="./Login.html">Login<br>
<div class="barra"></div>
</a></li>
<li><a href="./cadastro.html">cadastre-se<br>
<div class="barra"></div>
</a></li>
<a><img class="img-logo"
src="./imagens/logos/logo-tipo (3).png"><img></a>
<div class="text-logo"> Moto </div>
<div class="text-logo2">Dicas</div>
</ul>
</div>
<div class="cadastro-form ">
<span class="cadastro-form-title">
Ola! Faça seu Login
</span>
<br>
<div class="input-email " data-validate="Valid email is required: ex@abc.xyz">
<input class="input1" type="text" name="email" placeholder="Email" id="email_input">
<span class="sombra-input1"></span>
</div>
<br>
<div class="input-senha ">
<input class="input1" type="password" name="senha" placeholder="Senha" id="senha_input">
<span class="sombra-input1"></span>
</div>
<br>
<div class="container-cadastro-form-btn">
<button class="cadastro-form-btn" onclick="entrar()">Entrar</button>
</div>
</div>
<div id="cardErro" style="display: none;">
<div id="mensagem_erro"></div>
</div>
</main>
</header>
<div id="div_aguardar"></div>
</body>
</html>
<script>
function entrar() {
aguardar();
var emailVar = email_input.value;
var senhaVar = senha_input.value;
if (emailVar == "" || senhaVar == "") {
cardErro.style.display = "block"
mensagem_erro.innerHTML = "Confira se os campos estão devidamente preenchido";
finalizarAguardar();
return false;
}
else {
setInterval(sumirMensagem, 5000)
}
console.log("FORM LOGIN: ", emailVar);
console.log("FORM SENHA: ", senhaVar);
fetch("/usuarios/autenticar", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
emailServer: emailVar,
senhaServer: senhaVar
})
}).then(function (resposta) {
console.log("ESTOU NO THEN DO entrar()!")
if (resposta.ok) {
console.log(resposta);
resposta.json().then(json => {
console.log(json);
console.log(JSON.stringify(json));
sessionStorage.EMAIL_USUARIO = json.email;
sessionStorage.NOME_USUARIO = json.nome;
sessionStorage.ID_USUARIO = json.id;
setTimeout(function () {
window.location = "./SegundaTela/index2.html";
}, 1000); // apenas para exibir o loading
});
} else {
console.log("Houve um erro ao tentar realizar o login!");
resposta.text().then(texto => {
console.error(texto);
finalizarAguardar(texto);
});
}
}).catch(function (erro) {
console.log(erro);
})
return false;
}
function sumirMensagem() {
cardErro.style.display = "none"
}
</script>
|
import {
basic,
createForm,
maxLength,
serialize,
textAreaWidget,
textField,
textFieldType,
textFieldWidget,
maxLengthValidator,
unserialize,
equals,
orType,
or,
allowedValues,
allowedValuesValidator,
equalsValidator,
booleanField,
checkboxWidget,
textAreaWidgetType,
textFieldWidgetType,
tagsWidget,
tagsWidgetType,
checkboxWidgetType,
booleanFieldType,
SerializedComponent,
FormComponent,
SerializedRule,
} from "../src";
describe("Serializer", () => {
const form = createForm();
form.add(
textField({
name: "text",
label: "Text field",
required: true,
widget: textFieldWidget(),
validators: [],
}),
);
form.add(
textField({
name: "textarea",
label: "Textarea",
widget: textAreaWidget(),
required: false,
rules: [
["text", equals("text")],
or([
["text", allowedValues(["asdf", "asdf2"])],
["text", equals("text2")],
]),
],
validators: [maxLength(5)],
}),
);
form.add(
booleanField({
name: "bool",
label: "Boolean",
required: true,
widget: checkboxWidget(),
validators: [],
}),
);
form.add(
textField({
name: "multiple",
multiple: true,
multipleWidget: tagsWidget(),
}),
);
test("Serialize", () => {
const serializedForm = serialize(form);
expect(serializedForm.schemaParts).toHaveLength(1);
const components = serializedForm.components as SerializedComponent[];
expect(components[0].type).toBe("text");
expect(components[0].widget.type).toBe("textfield");
expect(components[1].type).toBe("text");
expect(components[1].widget.type).toBe("textarea");
expect(components[1].validators[0].type).toBe("maxLength");
expect(components[1].validators[0].settings).toBe(5);
expect(components[2].dataType).toBe("boolean");
const rules = components[1].rules as SerializedRule[];
if (Array.isArray(rules)) {
expect(rules[0][0]).toBe("text");
expect(rules[0][1].type).toBe("equals");
expect((rules[0][1].settings as Record<string, unknown>).value).toBe(
"text",
);
}
expect(Array.isArray(rules[1])).toBe(false);
const firstRule = rules[1] as any;
if (!Array.isArray(firstRule)) {
expect(firstRule.type).toBe("or");
const groupRules = firstRule.rules;
expect(groupRules[0][1].type).toBe("allowedValues");
expect(groupRules[0][1].settings.values).toHaveLength(2);
expect(groupRules[1][1].type).toBe("equals");
}
expect(components[3].multiple).toBe(true);
expect(components[3].multipleWidget?.type).toBe("tags");
});
test("Remove unused members from form", () => {
const serializedForm = serialize(form) as unknown;
expect(
(serializedForm as Record<string, unknown>).submitListeners,
).not.toBeDefined();
});
test("Unserialize", async () => {
const serializedForm = serialize(form);
const unserializedForm = unserialize(
serializedForm,
[textFieldType, booleanFieldType],
[basic],
[textAreaWidgetType, textFieldWidgetType, checkboxWidgetType],
[tagsWidgetType],
[maxLengthValidator, allowedValuesValidator, equalsValidator],
[orType],
);
const components = unserializedForm.components as FormComponent[];
expect(components[0].type.name).toBe("text");
expect(components[0].widget.type.name).toBe("textfield");
expect(components[1].widget.type.name).toBe("textarea");
expect(components[1].validators[0].type.name).toBe("maxLength");
expect(components[1].validators[0].settings).toBe(5);
expect((components[1] as any).rules[0][1].type.name).toBe("equals");
if (!Array.isArray(components[1].rules[1])) {
expect(components[1].rules[1].type.name).toBe("or");
}
expect(components[3].multiple).toBe(true);
expect(components[3].multipleWidget?.type.name).toBe("tags");
});
});
|
#### 1、添加辅助坐标轴
```javascript
// @params {Object} size 坐标轴线长度
const axes = new THREE.AxesHelper(20);
scene.add(axes);
```
#### 2、通过鼠标拖动、缩放和旋转查看 3D 场景
```javascript
const trackballControls = initTrackballControls(camera, renderer);
function render() {
trackballControls.update();
requestAnimationFrame(render);
renderer.render(scene, camera);
}
```
#### 3、查看动画帧率,fps
```javascript
const stats = initStats();
function render() {
stats.update()
}
```
#### 4、添加调试工具
```javascript
const gui = new dat.GUI();
const cubeParams = {
rotationSpeedX: 0.01,
rotationSpeedY: 0.01,
color: "#00ff00"
};
gui.add(cubeParams, 'rotationSpeedX', 0, 0.1);
gui.add(cubeParams, 'rotationSpeedY', 0, 0.1);
gui.addColor(cubeParams, 'color').onChange(function(value) {
cube.material.color.set(value);
});
function render() {
requestAnimationFrame(animate);
cube.rotation.x += cubeParams.rotationSpeedX;
cube.rotation.y += cubeParams.rotationSpeedY;
renderer.render(scene, camera);
}
```
|
// https://pdm.lsupathways.org/3_audio/2_synthsandmusic/1_lesson_1/envelopes/
//
function noise_filter() {
const filter = new Tone.Filter(1500, "highpass").toDestination();
filter.frequency.rampTo(20000, 10);
const noise = new Tone.Noise().connect(filter).start();
}
function noise_note() {
let osc,
ampEnv,
ampLfo,
highFilter,
lowFilter,
noise,
ampEnvNoise;
//function setup() {
let reverb = new Tone.Reverb().toDestination();
reverb.generate().then(() => {
document.body.innerHTML = 'Reverb Ready! '
});
ampLfo = new Tone.LFO('4n', -60, -3).start();
lfo2 = new Tone.LFO(10, 50, 500).start();
highFilter = new Tone.Filter(200, "highpass");
lowFilter = new Tone.Filter(200, "lowpass");
osc = new Tone.AMOscillator({
frequency: '440',
type: "sine",
modulationType: "square"
}).start();
noise = new Tone.Noise().start();
ampEnv = new Tone.AmplitudeEnvelope({
"attack": 0.1,
"decay": 0.2,
"sustain": 1,
"release": 0.8
}).connect(reverb);
// where the LFO is connected to what its modulating
ampLfo.connect(osc.volume);
lfo2.connect(lowFilter.frequency);
highFilter.connect(ampEnv);
lowFilter.connect(ampEnv);
osc.connect(highFilter);
noise.connect(lowFilter);
let notes = [297.898, 330, 335.238, 342.222, 391.111, 385, 440];
let randomNote = Math.floor(Math.random()*notes.length);
console.log(notes[randomNote])
osc.frequency.value = notes[randomNote];
ampEnv.triggerAttackRelease(1);
/*
function keyPressed() {
console.log(keyCode);
if (keyCode == 32) {
let notes = [297.898, 330, 335.238, 342.222, 391.111, 385, 440];
let randomNote = Math.floor(Math.random()*notes.length);
console.log(notes[randomNote])
osc.frequency.value = notes[randomNote];
ampEnv.triggerAttackRelease(1);
} else if (keyCode == ENTER) {
ampEnv.attack = random(0.1, 2);
ampEnv.decay = random(0.2, 0.5);
ampEnv.release = random(0.1, 2);
console.log(`attack: ${ampEnv.attack}, decay: ${ampEnv.decay}, release: ${ampEnv.release}`)
} else if (keyCode == 49) {
lfo2.frequency.value = 1;
ampLfo.frequency.value = 2;
} else if (keyCode == 50) {
lfo2.frequency.value = 2;
ampLfo.frequency.value = 4;
} else if (keyCode == 51) {
lfo2.frequency.value = 3;
ampLfo.frequency.value = 6;
} else if (keyCode == 52) {
lfo2.frequency.value = 4;
ampLfo.frequency.value = 8;
}
}
*/
}
function tsynth(f) {
let synth_opt = {
"oscillator": {
"volume": 0.9,
"count": 3,
//"spread": 40,
"spread": 10,
//"type": "square"
"type": "sawtooth"
},
"envelope": {
"attack": 0.5,
"decay": 0.5,
"sustain": 1,
"release": 5
},
"detune": -1,
"filterEnvelope": {
"attack": 0.5,
"decay": 0.5,
"sustain": 1,
"release": 5
},
"filter" : {
"type": "lowpass",
//"gain": 1,
"frequency": f,
"rolloff" : -12,
"Q": 0.25
}
};
let _xx = {
"filterEnvelope": {
"attack": -100.5,
"decay": 0.5,
"sustain": 1,
"release": 100
}
};
let amp_opt = {
"attack": 0.1,
"decay": 0.2,
"sustain": 1.0,
"release": 0.8
};
let filt_opt = {
"type": "lowpass",
//"gain": 1,
"frequency": f,
"rolloff" : -12,
"Q": 1
};
//let filter = new Tone.Filter(filt_opt);
let filter = new Tone.Filter(f, "lowpass");
let delay = new Tone.FeedbackDelay(0.125, 0.125);
let synth =
new Tone.PolySynth( Tone.MonoSynth,
synth_opt );
synth.connect(filter);
filter.connect(delay);
//synth.connect(delay);
delay.toDestination();
//filter.toDestination();
//synth = synth.connect(delay);
//synth = synth.connect(filter);
//synth = synth.toDestination();
//synth.triggerAttackRelease("C4", "8n");
synth.triggerAttackRelease(["C4", "E4", "A4"], 1);
}
function init() {
const synth = new Tone.Synth().toDestination();
//play a middle 'C' for the duration of an 8th note
synth.triggerAttackRelease("C4", "8n");
}
function init1() {
const synth1 = new Tone.Synth({
oscillator : {
volume: 5,
count: 3,
spread: 40,
type : "fatsawtooth"
}
}).toDestination();
synth1.triggerAttackRelease("C4", "8n");
}
function init2() {
const synth = new Tone.PolySynth().toDestination();
// set the attributes across all the voices using 'set'
synth.set({ detune: -1200 });
// play a chord
synth.triggerAttackRelease(["C4", "E4", "A4"], 1);
}
var g_info = {};
function init3() {
let _synth = new Tone.Synth({
oscillator : {
volume: 1,
count: 3,
spread: 90,
type : "fatsawtooth"
},
envelope : {
attack: 2,
decay: 1,
sustain: 0.4,
release: 4
}
});
let synth = new Tone.PolySynth( Tone.Synth, _synth.get() ).toDestination();
//const synth = new Tone.PolySynth( Tone.Synth ).toDestination();
synth.set({ detune: -10 });
synth.triggerAttackRelease(["C4", "E4", "A4"], 1);
g_info.synth = synth;
}
function init4() {
let _synth = new Tone.MonoSynth({
oscillator : {
volume: 1,
count: 3,
spread: 90,
type : "fatsawtooth"
},
envelope : {
attack: 2,
decay: 1,
sustain: 0.4,
release: 4
},
filterEnvelope : {
attack: 2,
decay: 1,
sustain: 0.4,
release: 4
}
});
let synth = new Tone.PolySynth( Tone.MonoSynth, _synth.get() ).toDestination();
synth.set({ detune: -10 });
//synth.triggerAttackRelease(["C4", "E4", "A4"], 1);
synth.triggerAttackRelease(["C4"], 1);
g_info.synth = synth;
}
function multiple_osc_test() {
let ampEnv = new Tone.AmplitudeEnvelope({
attack: 0.1,
decay: 0.2,
sustain: 1.0,
release: 0.8
}).toDestination();
let osc0 = new Tone.Oscillator(440, "sine");
let osc1 = new Tone.Oscillator(440.5, "sawtooth");
let osc2 = new Tone.Oscillator(439.5, "sawtooth");
// create an oscillator and connect it
//const osc123 = new Tone.Oscillator().connect(ampEnv).start();
osc0.connect(ampEnv).start();
osc1.connect(ampEnv).start();
osc2.connect(ampEnv).start();
ampEnv.triggerAttackRelease("8t");
}
function _x() {
let ampEnvelope;
let noise;
let filterCutoff;
ampEnvelope = new Tone.AmplitudeEnvelope({
"attack": 0.1,
"decay": 0.2,
"sustain": 1.0,
"release": 0.8
}).toDestination();
// lets put a filter between the noise and envelope
// hi pass filter - lets the highs pass through
filter = new Tone.Filter({
"type" : "lowpass", //change the filter type to see differnt results
"Q" : 3
}).connect(ampEnvelope)
// see: https://tonejs.github.io/docs/r13/Noise
noise = new Tone.Noise()
.connect(filter)
.start();
filter.frequency.value = 200
noise.type = 'pink' // brown, white, pink
filterCutoff = createSlider(200, 10000, 1000, 0.1);
filterCutoff.position(100, 300);
}
function _x1() {
let osc,
ampEnv,
ampLfo,
highFilter,
lowFilter,
noise,
ampEnvNoise;
let reverb = new Tone.Reverb().toDestination();
ampLfo = new Tone.LFO('4n', -60, -3).start();
lfo2 = new Tone.LFO(10, 50, 500).start();
highFilter = new Tone.Filter(200, "highpass");
lowFilter = new Tone.Filter(200, "lowpass");
osc = new Tone.AMOscillator({
frequency: '440',
type: "sine",
modulationType: "square"
}).start();
noise = new Tone.Noise().start();
ampEnv = new Tone.AmplitudeEnvelope({
"attack": 0.1,
"decay": 0.2,
"sustain": 1,
"release": 0.8
}).connect(reverb);
// where the LFO is connected to what its modulating
ampLfo.connect(osc.volume);
lfo2.connect(lowFilter.frequency);
highFilter.connect(ampEnv);
lowFilter.connect(ampEnv);
osc.connect(highFilter);
noise.connect(lowFilter);
}
|
<template>
<div class="app-container">
角色列表
<!--查询表单-->
<div class="search-div">
<el-form label-width="70px" size="small">
<el-row>
<el-col :span="24">
<el-form-item label="角色名称">
<el-input style="width: 100%" v-model="searchObj.roleName" placeholder="角色名称"></el-input>
</el-form-item>
</el-col>
</el-row>
<el-row style="display:flex">
<el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData()">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetData">重置</el-button>
</el-row>
</el-form>
</div>
<!-- 工具条 -->
<div class="tools-div">
<el-button type="success" icon="el-icon-plus" size="mini" @click="add">添 加</el-button>
<el-button class="btn-add" size="mini" @click="batchRemove()" >批量删除</el-button>
</div>
<!-- 表格 -->
<el-table
v-loading="listLoading"
:data="list"
stripe
border
style="width: 100%;margin-top: 10px;"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection"/>
<el-table-column
label="序号"
width="70"
align="center">
<template slot-scope="scope">
{{ (page - 1) * limit + scope.$index + 1 }}
</template>
</el-table-column>
<el-table-column prop="roleName" label="角色名称"/>
<el-table-column prop="roleCode" label="角色编码"/>
<el-table-column prop="createTime" label="创建时间" width="160"/>
<el-table-column label="操作" width="200" align="center">
<template slot-scope="scope">
<el-button type="primary" icon="el-icon-edit" size="mini" @click="edit(scope.row.id)" title="修改"/>
<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeDataById(scope.row.id)" title="删除"/>
<el-button type="warning" icon="el-icon-baseball" size="mini" @click="showAssignAuth(scope.row)" title="分配权限"/>
</template>
</el-table-column>
</el-table>
<!-- 分页组件 -->
<el-pagination
:current-page="page"
:total="total"
:page-size="limit"
style="padding: 30px 0; text-align: center;"
layout="total, prev, pager, next, jumper"
@current-change="fetchData"
/>
<el-dialog title="添加/修改" :visible.sync="dialogVisible" width="40%" >
<el-form ref="dataForm" :model="sysRole" label-width="150px" size="small" style="padding-right: 40px;">
<el-form-item label="角色名称">
<el-input v-model="sysRole.roleName"/>
</el-form-item>
<el-form-item label="角色编码">
<el-input v-model="sysRole.roleCode"/>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false" size="small" icon="el-icon-refresh-right">取 消</el-button>
<el-button type="primary" icon="el-icon-check" @click="saveOrUpdate()" size="small">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
import api from '@/api/system/role'
export default {
name: "list",
data() {
return {
listLoading: true,
list: [],
total: 0,
page: 1,
limit: 3,
searchObj: {},
sysRole:{},
dialogVisible:false,
selectValue:[]
}
},
created() {
this.fetchData()
},
methods: {
showAssignAuth(row) {
this.$router.push('/system/assignAuth?id='+row.id+'&roleName='+row.roleName);
},
batchRemove(){
if (this.selectValue.length === 0){
this.$message.warning('请选择要删除的记录!!')
return
}
this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => { // promise
var idList = []
for (var i = 0; i < this.selectValue.length; i++) {
idList.push(this.selectValue[i].id)
}
api.batchRemove(idList)
.then(response=>{
this.$message({
type:'success',
message:'删除成功!!'
})
})
this.fetchData()
// api.removeId(id)
// .then(response=>{
// this.$message.success(response.message || '删除成功')
// })
// // 点击确定,远程调用ajax
// this.fetchData()
})
},
handleSelectionChange(selection){
this.selectValue = selection
console.log(this.selectValue)
},
updateRole(){
api.update(this.sysRole)
.then(response=>{
this.$message({
type:'success',
message:'修改成功!!'
})
this.dialogVisible = false
this.fetchData()
})
},
edit(id){
this.dialogVisible = true
api.getRoleId(id)
.then(response=>{
this.sysRole = response.data
})
},
saveOrUpdate(){
if (!this.sysRole.id){
this.saveRole()
}else{
this.updateRole()
}
},
saveRole(){
api.saveRole(this.sysRole)
.then(response=>{
this.$message({
type:'success',
message:'添加成功!!'
});
this.dialogVisible = false
this.fetchData()
})
},
add(){
this.dialogVisible = true
this.sysRole = {}
},
resetData(){
this.searchObj = {}
this.fetchData()
},
fetchData(pageNum = 1) {
this.page = pageNum
api.getPageList(this.page, this.limit, this.searchObj)
.then(response => {
this.listLoading = false
// console.log(response)
this.list = response.data.records
// console.log('>>',this.list)
this.total = response.data.total
})
},
removeDataById(id){
this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => { // promise
api.removeId(id)
.then(response=>{
this.$message.success(response.message || '删除成功')
})
// 点击确定,远程调用ajax
this.fetchData()
})
},
}
}
</script>
<style scoped>
</style>
|
<template>
<div>
<div v-if="currentItem" class="mx-auto px-4 py-2 h-screen overflow-y-auto">
<div class="mx-auto">
<div class="flex items-center mb-4 border-b border-gray-900">
<router-link
to="/"
class="text-gray-900 font-bold text-xl hover:text-blue-900"
>{{ $t('detail_view.back') }}</router-link
>
<div class="w-full text-center">
<h1 class="text-3xl font-bold text-gray-900">
{{ currentItem.title }}
</h1>
</div>
</div>
<div class="mt-4 flex items-center">
<div class="flex-shrink-0">
<i class="pi pi-user text-2xl text-gray-900"></i>
</div>
<div class="ml-3 text-sm text-gray-500">
<p>
<span class="font-medium">{{ currentItem.by }}</span>
<span class="mx-1">·</span>
<span>{{
format(new Date(currentItem.time * 1000), "MMMM dd - HH:mm")
}}</span>
</p>
<a
:href="currentItem.url"
target="_blank"
rel="noopener noreferrer"
class="text-gray-500 hover:text-blue-800"
>{{ currentItem.url }}</a
>
</div>
</div>
<div class="mt-6">
<div v-show="iframeLoaded" class="border border-gray-200 rounded">
<div v-if="!iframeError">
<iframe
class="w-full rounded"
height="500"
:src="currentItem.url"
@error="iframeError = true"
@load="iframeLoaded = true"
></iframe>
</div>
<div v-else class="text-center text-red-500 font-bold">
{{ $t("detail_view.iframe_error") }}
</div>
</div>
<div v-if="!iframeLoaded">
<PrimeProgressSpinner />
</div>
</div>
<div class="mt-6">
<CommentComponent
v-for="kid in currentItem.kids"
:key="kid"
:comment-id="kid"
/>
</div>
</div>
</div>
<div v-else class="w-full h-full text-center flex items-center">
<PrimeProgressSpinner />
</div>
</div>
</template>
<script setup lang="ts">
import router from "@/router";
import { useItemsStore } from "@/store/items";
import { onBeforeMount, ref, toRefs } from "vue";
import { format } from "date-fns";
import CommentComponent from "@/components/CommentComponent.vue";
// The iframeLoaded and iframeError variables are used to track the state of the iframe. If the iframe has loaded, then it is set to true. If there is an error, then it is set to false.
const { currentItem } = toRefs(useItemsStore());
const iframeLoaded = ref(false);
const iframeError = ref(false);
// Set the current item to the item with the given ID
onBeforeMount(() => {
useItemsStore().setCurrentItem(String(router.currentRoute.value.params.id));
});
</script>
|
import React, { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import showMessage from '../../../libraries/messages/messages';
import projectMessage from '../../../main/messages/projectMessage';
import clientHTTPService from '../../../main/services/clientHTTPService';
import projectHTTPService from '../../../main/services/projectHTTPService';
import userHTTPService from '../../../main/services/userHTTPService';
import projectValidation from '../../../main/validations/projectValidation';
import './AddProject.css';
const AddProject = (props) => {
const { register, handleSubmit, reset, errors } = useForm()
const [clients, setClients] = useState([]);
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(false);
const [milestones,setMilestones]=useState([])
// console.log(errors)
const onSubmit = (data) => {
const sendData = {...data,milestones};
projectHTTPService.createProject(sendData).then(data => {
setMilestones([])
showMessage('Confirmation', projectMessage.add, 'success')
props.closeModal()
reset()
})
}
useEffect(() => {
retrieveUsers()
retrieveClients()
}, []);
const retrieveClients = () => {
setLoading(true)
clientHTTPService.getAllClient().then(data => {
setLoading(false)
setClients(data.data)
});
;
};
const handleMilestoneChange = (event, index) => {
const { name, value, type, checked } = event.target;
if (type === 'checkbox') {
const updatedMilestones = [...milestones];
updatedMilestones[index] = {
...updatedMilestones[index],
[name]: checked,
};
setMilestones(updatedMilestones);
} else {
const updatedMilestones = [...milestones];
updatedMilestones[index] = {
...updatedMilestones[index],
[name]: value,
};
setMilestones(updatedMilestones);
}
};
const retrieveUsers = () => {
setLoading(true)
userHTTPService.getAllUser()
.then(response => {
setUsers(response.data.users);
// console.log(response.data)
setLoading(false)
})
.catch(e => {
console.log(e);
});
};
const addMilestone = () => {
const newMilestone = {
title: "",
description: "",
amount:0,
completed: false,
};
setMilestones([...milestones, newMilestone]);
};
const removeMilestone = (index) => {
const updatedMilestones = [...milestones];
updatedMilestones.splice(index, 1);
setMilestones( updatedMilestones);
};
return (
<div className="AddProject">
<form method="POST" class="" onSubmit={handleSubmit(onSubmit)}>
<div className='row'>
<div class="form-group col-md-6">
<label>Client Name<span class="text-danger">*</span></label>
<select {...register('client', { required: true })}
name="client" class="selectpicker form-control border-1 rounded "
><option value={''}>Select client</option>
{
clients.map(item =>
<option value={item._id}>{item.first_name + ' ' + item.last_name}</option>
)
}
</select>
{/* <div className="error text-danger">
{errors.client && projectValidation.client}
</div> */}
</div>
<div class="form-group col-md-6">
<label>Project Name<span class="text-danger">*</span></label>
<input {...register('title', { required: true })}
type="text" name="title" class="form-control" required="" />
<div className="error text-danger">
{errors?.title}
</div>
</div>
<div class="form-group">
<label>Project Description<span class="text-danger">*</span></label>
<textarea {...register('description', { required: true })}
type="text" name="description" class="form-control"></textarea>
{/* <div className="error text-danger">
{errors.description && projectValidation.description}
</div> */}
</div>
<div class="form-group col-md-6">
<label>Project Cost<span class="text-danger">*</span></label>
<div class="input-group mb-3">
<input {...register('contractValue', { required: true })}
type="number" name="contractValue" class="form-control" />
<div class="input-group-append">
<span class="input-group-text" id="basic-addon2"> $</span>
</div>
</div>
</div>
<div class="form-group col-md-6">
<label>Contract Type<span class="text-danger">*</span></label>
<select {...register('contractType', { required: true })} name="contractType" id="project"
class="selectpicker form-control border-1 rounded " tabIndex="-1" aria-hidden="true">
<option value={''}>Select type</option>
<option value="Fixed-price contracts">Fixed-price</option>
<option value="Hourly contracts">Hourly</option>
</select>
</div>
<div className="form-group">
<div className='Add_milestones'>
<label>Milestones</label>
<button type="button" onClick={addMilestone}>➕</button></div>
<div className='milestones_main'>
{milestones.map((milestone, index) => (
<div className='submilestones_task' key={index}>
<input
className='area_desc'
type="text"
name={`title`}
value={milestone.title}
onChange={(e) => handleMilestoneChange(e, index)}
placeholder={`Milestone ${index + 1}`}
/>
<div>
<textarea
className='area_desc'
type="text"
name={`description`}
value={milestone.description}
onChange={(e) => handleMilestoneChange(e, index)}
placeholder="Description"
/>
</div>
<div>
<input
className='area_desc'
type="number"
min={0}
name={`amount`}
value={milestone.amount}
onChange={(e) => handleMilestoneChange(e, index)}
placeholder="Description"
/>
{/* <label>
Completed
<input
type="checkbox"
name={`milestones[${index}].completed`}
checked={milestone.completed}
onChange={(e) => handleMilestoneChange(e, index)}
/>
</label> */}
<button type="button" className='remove_milestone' onClick={() => removeMilestone(index)}>Remove</button></div>
</div>
))}
</div>
</div>
<div class="form-group col-md-6">
<label>Start Date<span class="text-danger">*</span></label>
<input {...register('starting_date', { required: true })}
type="date" name="starting_date" class="form-control datepicker" />
{/* <div className="error text-danger">
{errors.starting_date && projectValidation.starting_date}
</div> */}
</div>
<div class="form-group col-md-6">
<label>End Date<span class="text-danger">*</span></label>
<input {...register('ending_date', { required: true })}
type="date" name="ending_date" class="form-control datepicker" />
{/* <div className="error text-danger">
{errors.ending_date && projectValidation.ending_date}
</div> */}
</div>
<div class="form-group col-md-6">
<label>Assigned To<span class="text-danger">*</span></label>
<select {...register('users', { required: true })}
name="users" class="selectpicker form-control border-1 rounded "
> <option value={''}>Select user</option>
{
users.map(item =>
<option value={item._id}>{item.username}</option>
)
}
</select>
{/* <div className="error text-danger">
{errors.users && projectValidation.users}
</div> */}
</div>
<div class="form-group col-md-6">
<label>Status<span class="text-danger">*</span></label>
<select {...register('status', { required: true })}
name="status" class="selectpicker form-control border-1 rounded ">
<option value={''}>Select status</option>
<option value="Todo">ToDo</option>
<option value="In Progress">In Progress</option>
<option value="Done">Done</option>
<option value="Blocked">Blocked</option>
</select>
{/* <div className="error text-danger">
{errors.status && projectValidation.status}
</div> */}
</div>
</div>
<button type="submit" id="save-form" class="btn btn-success"><i className="fa fa-check"></i>
<font ><font > Save</font></font></button></form>
</div>
)
};
export default AddProject;
|
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WebStudio</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css"
/>
<!--browser style sheet normalization-->
<link rel="stylesheet" href="css/main.min.css" />
</head>
<body>
<header class="header">
<div class="container">
<nav class="header__nav">
<a href="./" class="logo logo--header">
<!-- logo -->
<span class="logo__left">Web</span
><span class="logo__right">Studio</span>
</a>
<ul class="nav-panel container-list">
<li class="nav-panel__item">
<a href="./" class="link nav-panel__link nav-panel__link--active"
>Студия</a
>
</li>
<li class="nav-panel__item">
<a href="./portfolio.html" class="link nav-panel__link"
>Портфолио</a
>
</li>
<li class="nav-panel__item">
<a href="" class="link nav-panel__link">Контакты</a>
</li>
</ul>
</nav>
<ul class="header-contacts">
<li class="header-contacts__item">
<a
href="mailto:info@devstudio.com"
class="link header-contacts__link"
>
<svg class="header-contacts__icon" width="16" height="12">
<use href="./images/icons/icons-sprite.svg#contact-mail"></use>
</svg>
info@devstudio.com
</a>
</li>
<li class="header-contacts__item">
<a href="tel:+380961111111" class="link header-contacts__link">
<svg class="header-contacts__icon" width="10" height="16">
<use href="./images/icons/icons-sprite.svg#contact-phone"></use>
</svg>
+38 096 111 11 11
</a>
</li>
</ul>
</div>
</header>
<div data-modal class="modal-backdrop is-hidden">
<div class="modal-window">
<button data-modal-close class="btn btn--close-modal" type="button">
<svg class="btn--close-modal__icon" width="11" height="11">
<use href="./images/icons/icons-sprite.svg#btn-close"></use>
</svg>
<!-- <img src="./images/icons/btn-close.svg" alt="Close" width="11"> -->
</button>
<p class="modal-window__header">
Оставьте свои данные, мы вам перезвоним
</p>
<form name="form_call" class="modal-form">
<label class="modal-form__element">
<span class="modal-form__label">Имя</span>
<input
class="modal-form__input"
type="text"
name="call_name"
required
/>
<svg class="modal-form__icon" width="18" height="18">
<use href="./images/icons/icons-sprite.svg#modal-icon-name"></use>
</svg>
</label>
<label class="modal-form__element">
<span class="modal-form__label">Телефон</span>
<input
id="call-phone"
class="modal-form__input"
type="tel"
name="call_phone"
required
/>
<svg class="modal-form__icon" width="18" height="18">
<use
href="./images/icons/icons-sprite.svg#modal-icon-phone"
></use>
</svg>
</label>
<label class="modal-form__element">
<span class="modal-form__label">Почта</span>
<input
id="call-email"
class="modal-form__input"
type="email"
name="call_email"
/>
<svg class="modal-form__icon" width="18" height="18">
<use
href="./images/icons/icons-sprite.svg#modal-icon-email"
></use>
</svg>
</label>
<label class="modal-form__element">
<span class="modal-form__label">Комментарий</span>
<textarea
id="call-comment"
class="modal-form__comment"
rows="4"
name="call_comment"
placeholder="Введите текст"
></textarea>
</label>
<label class="modal-form__terms">
<input
id="call-accept"
class="modal-form__chk-acc-real vis-hide"
type="checkbox"
/>
<!-- hidden real checkbox -->
<svg class="modal-form__chk-accept" width="16" height="15">
<use href="./images/icons/icons-sprite.svg#modal-checkbox"></use>
</svg>
<svg
class="modal-form__chk-accept modal-form__chk-accept--checked"
width="16"
height="15"
>
<use
href="./images/icons/icons-sprite.svg#modal-checkbox-checked"
></use>
</svg>
<!-- fake checkbox -->
<span>
Соглашаюсь с рассылкой и принимаю
<a href="" target="_blank">Условия договора</a>
</span>
</label>
</form>
<button class="btn btn--hero-style btn--submit-modal" type="submit">
Отправить
</button>
</div>
</div>
<main>
<section class="section section--hero">
<!-- HERO-->
<div class="container container--flex-col">
<h1 class="section--hero__header">
Эффективные решения <br />
для вашего бизнеса
</h1>
<button data-modal-open class="btn btn--hero-style" type="button">
Заказать услугу
</button>
</div>
</section>
<section class="section">
<!-- traits of the corp-->
<div class="container container--flex-col">
<h2 class="section__header vis-hide">Особенности компании</h2>
<ul class="traits-list container-list">
<li class="trait">
<div class="trait__icon-container">
<svg class="trait__icon" width="70" height="70">
<use
href="./images/icons/icons-sprite.svg#feature-antenna"
></use>
</svg>
</div>
<h3 class="trait__header">Внимание к деталям</h3>
<p class="trait__desc">
Идейные соображения, а также начало повседневной работы по
формированию позиции.
</p>
</li>
<li class="trait">
<div class="trait__icon-container">
<svg class="trait__icon" width="70" height="70">
<use
href="./images/icons/icons-sprite.svg#feature-clock"
></use>
</svg>
</div>
<h3 class="trait__header">Пунктуальность</h3>
<p class="trait__desc">
Задача организации, в особенности же рамки и место обучения
кадров влечет за собой.
</p>
</li>
<li class="trait">
<div class="trait__icon-container">
<svg class="trait__icon" width="70" height="70">
<use
href="./images/icons/icons-sprite.svg#feature-diagram"
></use>
</svg>
</div>
<h3 class="trait__header">Планирование</h3>
<p class="trait__desc">
Равным образом консультация с широким активом в значительной
степени обуславливает.
</p>
</li>
<li class="trait">
<div class="trait__icon-container">
<svg class="trait__icon" width="70" height="70">
<use
href="./images/icons/icons-sprite.svg#feature-astronaut"
></use>
</svg>
</div>
<h3 class="trait__header">Современные технологии</h3>
<p class="trait__desc">
Значимость этих проблем настолько очевидна, что реализация
плановых заданий.
</p>
</li>
</ul>
</div>
</section>
<section class="section section--bottom-pad">
<div class="container container--flex-col">
<h2 class="section__header">Чем мы занимаемся</h2>
<ul class="container-list">
<li class="wedo-item inline">
<img
src="./images/what-we-do/img1.jpg"
alt="Разработка десктопных приложений"
width="370"
class="wedo-item__image"
/>
<div class="wedo-item__desc">
<p class="wedo-item__label">Десктопные приложения</p>
</div>
</li>
<li class="wedo-item inline">
<img
src="./images/what-we-do/img2.jpg"
alt="Разработка мобильных приложений"
width="370"
class="wedo-item__image"
/>
<div class="wedo-item__desc">
<p class="wedo-item__label">Мобильные приложения</p>
</div>
</li>
<li class="wedo-item inline">
<img
src="./images/what-we-do/img3.jpg"
alt="Дизайнерские решения"
width="370"
class="wedo-item__image"
/>
<div class="wedo-item__desc">
<p class="wedo-item__label">Дизайнерские решения</p>
</div>
</li>
</ul>
</div>
</section>
<section class="section section--bottom-pad section--bkg-gray">
<div class="container container--flex-col">
<h2 class="section__header">Наша команда</h2>
<ul class="container-list">
<li class="team-member inline">
<img
src="./images/team/demyanenko.jpg"
alt="Фото Игоря Демьяненко"
width="270"
/>
<div class="team-member__info">
<h3 class="team-member__name">Игорь Демьяненко</h3>
<p class="team-member__position">Product Designer</p>
<ul class="social-list team-member__social-list">
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-instagram"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-twitter"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-facebook"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-linkedin"
></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-member inline">
<img
src="./images/team/repina.jpg"
alt="Фото Ольги Репиной"
width="270"
/>
<div class="team-member__info">
<h3 class="team-member__name">Ольга Репина</h3>
<p class="team-member__position">Frontend Developer</p>
<ul class="social-list team-member__social-list">
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-instagram"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-twitter"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-facebook"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-linkedin"
></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-member inline">
<img
src="./images/team/tarasov.jpg"
alt="Фото Николая Тарасова"
width="270"
/>
<div class="team-member__info">
<h3 class="team-member__name">Николай Тарасов</h3>
<p class="team-member__position">Marketing</p>
<ul class="social-list team-member__social-list">
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-instagram"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-twitter"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-facebook"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-linkedin"
></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-member inline">
<img
src="./images/team/ermakov.jpg"
alt="Фото Михаила Ермакова"
width="270"
/>
<div class="team-member__info">
<h3 class="team-member__name">Михаил Ермаков</h3>
<p class="team-member__position">UI Designer</p>
<ul class="social-list team-member__social-list">
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-instagram"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-twitter"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-facebook"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link" href="">
<svg class="social-list__icon" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#social-linkedin"
></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
</ul>
</div>
</section>
<section class="section section--bottom-pad">
<div class="container container--flex-col">
<h2 class="section__header">Постоянные клиенты</h2>
<ul class="clients-list">
<li class="client">
<a href="" class="client__link">
<svg class="client__logo" width="106" height="60">
<use href="./images/icons/icons-sprite.svg#client-1"></use>
</svg>
</a>
</li>
<li class="client">
<a href="" class="client__link">
<svg class="client__logo" width="106" height="60">
<use href="./images/icons/icons-sprite.svg#client-2"></use>
</svg>
</a>
</li>
<li class="client">
<a href="" class="client__link">
<svg class="client__logo" width="106" height="60">
<use href="./images/icons/icons-sprite.svg#client-3"></use>
</svg>
</a>
</li>
<li class="client">
<a href="" class="client__link">
<svg class="client__logo" width="106" height="60">
<use href="./images/icons/icons-sprite.svg#client-4"></use>
</svg>
</a>
</li>
<li class="client">
<a href="" class="client__link">
<svg class="client__logo" width="106" height="60">
<use href="./images/icons/icons-sprite.svg#client-5"></use>
</svg>
</a>
</li>
<li class="client">
<a href="" class="client__link">
<svg class="client__logo" width="106" height="60">
<use href="./images/icons/icons-sprite.svg#client-6"></use>
</svg>
</a>
</li>
</ul>
</div>
</section>
</main>
<footer class="footer">
<div class="container container--footer">
<div class="footer-block--corp">
<p class="logo logo--footer">
<span class="logo__left logo--footer__left">Web</span
><span class="logo__right logo--footer__right">Studio</span>
</p>
<address>
<ul class="footer-contacts">
<li class="footer-contacts__item">
<p class="addr">г. Киев, пр-т Леси Украинки, 26</p>
</li>
<li class="footer-contacts__item">
<a
class="link link--footer-contacts"
href="mailto:info@example.com"
>info@example.com</a
>
</li>
<li class="footer-contacts__item">
<a
class="link link--footer-contacts"
href="tel:+38-099-111-11-11"
>+38 099 111 11 11</a
>
</li>
</ul>
</address>
</div>
<div class="footer-block footer-block--social">
<p class="footer-block__label">Присоединяйтесь</p>
<ul class="social-list">
<li class="social-list__item">
<a class="social-list__link social-list__link--footer" href="">
<svg class="social-list__icon--footer" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#footer-social-instagram"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link social-list__link--footer" href="">
<svg class="social-list__icon--footer" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#footer-social-twitter"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link social-list__link--footer" href="">
<svg class="social-list__icon--footer" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#footer-social-facebook"
></use>
</svg>
</a>
</li>
<li class="social-list__item">
<a class="social-list__link social-list__link--footer" href="">
<svg class="social-list__icon--footer" width="20" height="20">
<use
href="./images/icons/icons-sprite.svg#footer-social-linkedin"
></use>
</svg>
</a>
</li>
</ul>
</div>
<form name="form_subscribe" class="footer-block form-subscribe">
<label for="email-subscribe" class="footer-block__label"
>Подпишитесь на рассылку</label
>
<input
id="email-subscribe"
class="form-subscribe__input"
type="email"
name="email_subscribe"
placeholder="E-mail"
/>
<button class="btn btn--subscribe" type="submit">
Подписаться
<svg class="btn--subscribe__icon" width="24" height="24">
<use href="./images/icons/icons-sprite.svg#btn-telegram"></use>
</svg>
</button>
</form>
</div>
</footer>
<script src="./js/modal.js"></script>
<!-- script for opening modal window-->
</body>
</html>
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 19 19:12:37 2022
@author: Acelya
"""
import pandas as pd
dictionary={"Name":["Açelya","Ali","Can","Sarp","Ege"],
"Maas":[300,800,600,200,100],
"Yas":[23,30,18,36,28]}
dataframe1 = pd.DataFrame(dictionary)
head=dataframe1.head() #ilk 5 data
tail=dataframe1.tail() #son 5 data
#%% Pandas Basic Methods
print(dataframe1.columns)
print(dataframe1.info())
#infoda pandas kütüphanesi string yazmak yerine object yazar.
#satırlara sample diyoruz.
print(dataframe1.dtypes)
print(dataframe1.describe())
#describe metodu--> numeric featurları(max,min,mean,std) verileri gösterir.columns(age,maas)
#%% Indexing and Slicing
print(dataframe1["Name"])
print(dataframe1.Yas)
print(dataframe1.Maas)
dataframe1["yeni feature"]=[1,2,3,4,5]
print(dataframe1.yeni_feature)
print(dataframe1.loc[:,"Yas"])
print(dataframe1.loc[:3,"Yas"]) #pandas da 3 indexi dahil
print(dataframe1.loc[:4,"Name":"Yas"])
print(dataframe1.loc[:4,["Name","Yas"]])
print(dataframe1.loc[::-1,:]) #Tersten yazdır değerleri
print(dataframe1.loc[:,:"Yas"]) #Yasa kadar yaz.
print("*****")
print(dataframe1.iloc[:,2])#indeksi 2 olan sütunu yazdır.Bütün satırları yazdır.(:)
#%% Filtering Pandas Data Frame
#Mesela maaşı 200 üstü olan insanları bulmak için filtreleme yapılır.
filtre1=dataframe1.Maas>200
filtrelenmis_data=dataframe1[filtre1]
filtre2=dataframe1.Yas>20
dataframe1[filtre1 & filtre2]
print(dataframe1[dataframe1.Yas>29])
#%% List Comprehension
import numpy as np
ortalama_maas=dataframe1.Maas.mean()
print(ortalama_maas)
ortalama_maas_np=np.mean(dataframe1.Maas)
print(ortalama_maas_np)
#list comprehension:
dataframe1["Maas Seviyesi"]=["yuksek" if ortalama_maas < each else "dusuk"for each in dataframe1.Maas]
dataframe1.columns=[each.lower() for each in dataframe1.columns]
dataframe1.columns=[each.split()[0]+"_"+each.split()[1] if(len(each.split())>1) else each for each in dataframe1.columns]
#%% Drop and Concatenating data
#column drop ediyoroz. axis=1 --> column siler, axis=0--> row siler.inplace=true yaptımızı datafram1e eşitliyor.
dataframe1.drop(["Name"],axis=1,inplace=True)
#numpy da vstack ve hstack vardı.Vertical veya horizantal birleştirme
data1=dataframe1.head()
data2=dataframe1.tail()
#vertical birleştirme
data_concat=pd.concat([data1,data2],axis=0)
maas=dataframe1.Maas
yas=dataframe1.Yas
data_h_concat=pd.concat([maas,yas],axis=1)
#%% Transforming Data
dataframe1["list_comp"]=[each*2 for each in dataframe1.Yas]
# apply metodu
def multiply(age):
return age*2
dataframe1["apply_method"]=dataframe1.Yas.apply(multiply)
|
import './App.css';
import Home from './components/Home';
import Navbar from './components/Navbar';
import {
BrowserRouter as Router,
Routes,
Route,
} from "react-router-dom";
import About from './components/About';
import NoteState from './context/notes/NoteState';
import Alert from './components/Alert';
import Login from './components/Login';
import Signup from './components/Signup';
import { useState } from 'react';
function App() {
const [alert,setAlert]=useState(null)
const showAlert=(message,type)=>{
setAlert({
msg:message,
type:type})
setTimeout(() => {
setAlert(null)
}, 1500);
}
return (
<>
<NoteState>
<Router>
<Navbar showAlert={showAlert}/>
<Alert alert={alert}/>
<div className="container">
<Routes>
<Route exact path="/" element={ <Home showAlert={showAlert} />}></Route>
<Route exact path="/about" element={ <About />}></Route>
<Route exact path="/login" element={ <Login showAlert={showAlert} />}></Route>
<Route exact path="/signup" element={ <Signup showAlert={showAlert} />}></Route>
</Routes>
</div>
</Router>
</NoteState>
</>
);
}
export default App;
|
NSA Security-Enhanced Linux (SELinux) is an implementation of a
flexible mandatory access control architecture in the Linux operating
system. The SELinux architecture provides general support for the
enforcement of many kinds of mandatory access control policies,
including those based on the concepts of Type Enforcement®, Role-
Based Access Control, and Multi-Level Security. Background
information and technical documentation about SELinux can be found at
http://www.nsa.gov/research/selinux.
The /etc/selinux/config configuration file controls whether SELinux
is enabled or disabled, and if enabled, whether SELinux operates in
permissive mode or enforcing mode. The SELINUX variable may be set
to any one of disabled, permissive, or enforcing to select one of
these options. The disabled option completely disables the SELinux
kernel and application code, leaving the system running without any
SELinux protection. The permissive option enables the SELinux code,
but causes it to operate in a mode where accesses that would be
denied by policy are permitted but audited. The enforcing option
enables the SELinux code and causes it to enforce access denials as
well as auditing them. Permissive mode may yield a different set of
denials than enforcing mode, both because enforcing mode will prevent
an operation from proceeding past the first denial and because some
application code will fall back to a less privileged mode of
operation if denied access.
The /etc/selinux/config configuration file also controls what policy
is active on the system. SELinux allows for multiple policies to be
installed on the system, but only one policy may be active at any
given time. At present, multiple kinds of SELinux policy exist:
targeted, mls for example. The targeted policy is designed as a
policy where most user processes operate without restrictions, and
only specific services are placed into distinct security domains that
are confined by the policy. For example, the user would run in a
completely unconfined domain while the named daemon or apache daemon
would run in a specific domain tailored to its operation. The MLS
(Multi-Level Security) policy is designed as a policy where all
processes are partitioned into fine-grained security domains and
confined by policy. MLS also supports the Bell And LaPadula model,
where processes are not only confined by the type but also the level
of the data.
You can define which policy you will run by setting the SELINUXTYPE
environment variable within /etc/selinux/config. You must reboot and
possibly relabel if you change the policy type to have it take effect
on the system. The corresponding policy configuration for each such
policy must be installed in the /etc/selinux/{SELINUXTYPE}/
directories.
A given SELinux policy can be customized further based on a set of
compile-time tunable options and a set of runtime policy booleans.
system-config-selinux allows customization of these booleans and
tunables.
Many domains that are protected by SELinux also include SELinux man
pages explaining how to customize their policy.
|
using System;
/*
* Copyright 2013 MovingBlocks
*
* 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.
*/
namespace org.terasology.entitySystem.@event
{
using RegisterMode = org.terasology.entitySystem.systems.RegisterMode;
/// <summary>
/// This annotation is used to mark up methods that can be registered to receive events through the EventSystem
/// <p/>
/// These methods should have the form
/// <code>public void handlerMethod(EventType event, EntityRef entity)</code>
///
/// @author Immortius <immortius@gmail.com>
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false]
public class ReceiveEvent : System.Attribute
{
/// <summary>
/// What components that the entity must have for this method to be invoked
/// </summary>
internal virtual Type[] components() default
{
};
RegisterMode netFilter() default RegisterMode.ALWAYS;
int priority() default EventPriority.PRIORITY_NORMAL;
}
}
|
package marcelo.com.br.jumper.engine;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import marcelo.com.br.jumper.R;
import marcelo.com.br.jumper.elements.Cano;
import marcelo.com.br.jumper.elements.Canos;
import marcelo.com.br.jumper.elements.GameOver;
import marcelo.com.br.jumper.elements.Passaro;
import marcelo.com.br.jumper.elements.Pontuacao;
import marcelo.com.br.jumper.graphic.Tela;
/**
* Created by Marcelo on 30/12/2017.
*/
public class Game extends SurfaceView implements Runnable, View.OnTouchListener {
private Context context;
private boolean isRunning = true;
private final SurfaceHolder holder = getHolder();
private Canvas canvas;
private Passaro passaro;
private Canos canos;
private Bitmap background;
private Tela tela;
private Pontuacao pontuacao;
private Som som;
public Game(Context context) {
super(context);
this.context = context;
tela = new Tela(context);
this.som = new Som(context);
inicializaElementos();
setOnTouchListener(this);
}
private void inicializaElementos() {
this.pontuacao = new Pontuacao(som);
this.passaro = new Passaro(tela, context, som);
this.canos = new Canos(tela, pontuacao, context);
Bitmap back = BitmapFactory.decodeResource(getResources(), R.drawable.background);
this.background = Bitmap.createScaledBitmap(back, back.getWidth(), tela.getAltura(), false);
}
@Override
public void run() {
while(isRunning) {
if(!holder.getSurface().isValid()) continue;
canvas = holder.lockCanvas();
canvas.drawBitmap(background, 0, 0, null);
passaro.desenhaNo(canvas);
passaro.cai();
canos.desenhaNo(canvas);
canos.move();
pontuacao.desenhaNo(canvas);
if(new VerificadorDeColisao(passaro, canos).temColisao()) {
som.play(Som.COLISAO);
new GameOver(tela).desenhaNo(canvas);
isRunning = false;
}
holder.unlockCanvasAndPost(canvas);
}
}
public void pause(){
this.isRunning = false;
}
public void inicia(){
this.isRunning = true;
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
passaro.pula();
return false;
}
}
|
package is.hail.check
import scala.collection.generic.CanBuildFrom
import scala.language.higherKinds
object Arbitrary {
def apply[T](arbitrary: Gen[T]): Arbitrary[T] =
new Arbitrary(arbitrary)
implicit def arbBoolean: Arbitrary[Boolean] = new Arbitrary(
Gen.oneOf(true, false)
)
implicit def arbByte: Arbitrary[Byte] = new Arbitrary(Gen.oneOfGen(
Gen.oneOf(Byte.MinValue, -1, 0, 1, Byte.MaxValue),
Gen(p => p.rng.getRandomGenerator.nextInt().toByte),
))
implicit def arbInt: Arbitrary[Int] = new Arbitrary(
Gen.oneOfGen(
Gen.oneOf(Int.MinValue, -1, 0, 1, Int.MaxValue),
Gen.choose(-100, 100),
Gen(p => p.rng.getRandomGenerator.nextInt()),
)
)
implicit def arbLong: Arbitrary[Long] = new Arbitrary(
Gen.oneOfGen(
Gen.oneOf(Long.MinValue, -1L, 0L, 1L, Long.MaxValue),
Gen.choose(-100, 100),
Gen(p => p.rng.getRandomGenerator.nextLong()),
)
)
implicit def arbFloat: Arbitrary[Float] = new Arbitrary(
Gen.oneOfGen(
Gen.oneOf(
Float.MinValue,
-1.0f,
-Float.MinPositiveValue,
0.0f,
Float.MinPositiveValue,
1.0f,
Float.MaxValue,
),
Gen.choose(-100.0f, 100.0f),
Gen(p => p.rng.nextUniform(Float.MinValue, Float.MaxValue, true).toFloat),
)
)
implicit def arbDouble: Arbitrary[Double] = new Arbitrary(
Gen.oneOfGen(
Gen.oneOf(
Double.MinValue,
-1.0,
-Double.MinPositiveValue,
0.0,
Double.MinPositiveValue,
1.0,
Double.MaxValue,
),
Gen.choose(-100.0, 100.0),
Gen(p => p.rng.nextUniform(Double.MinValue, Double.MaxValue, true)),
)
)
implicit def arbString: Arbitrary[String] = new Arbitrary(Gen.frequency(
(1, Gen.const("")),
(
10,
Gen { (p: Parameters) =>
val s = p.rng.getRandomGenerator.nextInt(12)
val b = new StringBuilder()
for (i <- 0 until s)
b += Gen.randomOneOf(p.rng, Gen.printableChars)
b.result()
},
),
))
implicit def arbBuildableOf[C[_], T](
implicit a: Arbitrary[T],
cbf: CanBuildFrom[Nothing, T, C[T]],
): Arbitrary[C[T]] =
Arbitrary(Gen.buildableOf(a.arbitrary))
def arbitrary[T](implicit arb: Arbitrary[T]): Gen[T] = arb.arbitrary
}
class Arbitrary[T](val arbitrary: Gen[T])
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using FMH.Workspace.Data;
using StringExtensions;
namespace FMH.Workspace.WorkspaceManager
{
/// <summary>
/// Workspace manager for mod developed for Minecraft 1.20 and older
/// </summary>
public class WorkspaceManagerV2 : IWorkspaceManager
{
/// <summary>
/// Workspace properties
/// </summary>
public WorkspaceProperties WorkspaceProperties { get; set; }
/// <summary>
/// Mod properties
/// </summary>
public ModProperties ModProperties { get; set; }
/// <summary>
/// Mod version history
/// </summary>
public ModVersionsHistory ModVersionsHistory { get; set; }
/// <summary>
/// Assets properties
/// </summary>
public AssetsProperties AssetsProperties { get; set; }
/// <summary>
/// Source code properties
/// </summary>
public SourceCodeProperties SourceCodeProperties { get; set; }
/// <summary>
/// Read data from build.gralde file
/// </summary>
/// <returns><c>true</c> if success, else <c>false</c></returns>
public bool ReadBuildGradle()
{
// No data to read for this file
return true;
}
/// <summary>
/// Read data from gradle.properties file
/// </summary>
/// <returns><c>true</c> if success, else <c>false</c></returns>
public bool ReadGradleProperties()
{
string filePath = Path.Combine(WorkspaceProperties.WorkspacePath, "gradle.properties");
string[] fileLines = File.ReadAllLines(filePath);
try
{
foreach (var line in fileLines)
{
var infoLine = line.Split("=");
if (string.Equals(infoLine[0], "minecraft_version"))
{
this.ModProperties.ModMinecraftVersion = line.Split('=')[1]
.Replace("[", string.Empty)
.Replace("]", string.Empty)
.Replace("(", string.Empty)
.Replace(")", string.Empty)
.Replace(",", string.Empty);
this.WorkspaceProperties.MCVersion = this.ModProperties.ModMinecraftVersion;
}
if (string.Equals(infoLine[0], "forge_version"))
{
this.ModProperties.ModAPIVersion = line.Split('=')[1]
.Replace("[", string.Empty)
.Replace("]", string.Empty)
.Replace("(", string.Empty)
.Replace(")", string.Empty)
.Replace(",", string.Empty);
this.WorkspaceProperties.APIVersion = this.ModProperties.ModAPIVersion;
}
if (string.Equals(infoLine[0], "mapping_version"))
this.ModProperties.ModMappingsVersion = line.Split('=')[1];
if (string.Equals(infoLine[0], "mod_id"))
this.ModProperties.ModID = line.Split('=')[1];
if (string.Equals(infoLine[0], "mod_name"))
this.ModProperties.ModName = line.Split('=')[1];
if (string.Equals(infoLine[0], "mod_license"))
this.ModProperties.ModLicense = line.Split('=')[1];
if (string.Equals(infoLine[0], "mod_version"))
this.ModProperties.ModVersion = line.Split('=')[1];
if (string.Equals(infoLine[0], "mod_group_id"))
this.ModProperties.ModGroup = line.Split('=')[1];
if (string.Equals(infoLine[0], "mod_authors"))
this.ModProperties.ModAuthors = line.Split('=')[1];
if (string.Equals(infoLine[0], "mod_description"))
this.ModProperties.ModDescription = line.Split('=')[1];
}
this.WorkspaceProperties.ModAPI = ModAPIType.Forge;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Read data from mod.toml file
/// </summary>
/// <returns><c>true</c> if success, else <c>false</c></returns>
public bool ReadModToml()
{
string filePath = Path.Combine(WorkspaceProperties.WorkspacePath, @"src\main\resources\META-INF\mods.toml");
string fileContent = File.ReadAllText(filePath);
try
{
this.ModProperties.ModIssueTracker = fileContent.Between("issueTrackerURL=\"", "\"", StringComparison.CurrentCulture);
this.ModProperties.ModUpdateJSONURL = fileContent.Between("updateJSONURL=\"", "\"", StringComparison.CurrentCulture);
this.ModProperties.ModWebsite = fileContent.Between("displayURL=\"", "\"", StringComparison.CurrentCulture);
this.ModProperties.ModLogo = fileContent.Between("logoFile=\"", "\"", StringComparison.CurrentCulture);
this.ModProperties.ModCredits = fileContent.Between("credits=\"", "\"", StringComparison.CurrentCulture);
this.ModProperties.ModAuthors = fileContent.Between("authors=\"", "\"", StringComparison.CurrentCulture);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Write build.gradle file
/// </summary>
/// <returns><c>true</c> if success, else <c>false</c></returns>
public void WriteBuildGradle()
{
// No data to write for this file
return;
}
/// <summary>
/// Write gradle.properties file
/// </summary>
public void WriteGradleProperties()
{
StringBuilder outputText = new StringBuilder();
string filePath = Path.Combine(WorkspaceProperties.WorkspacePath, "gradle.properties");
string forgeVersionShort = ModProperties.ModAPIVersion;
string forgeVersionRange = forgeVersionShort.Split('.')[0];
// Default memory used for gradle commands
outputText.AppendLine("org.gradle.jvmargs=-Xmx3G");
outputText.AppendLine("org.gradle.daemon=false");
outputText.AppendLine();
// Environment Properties
outputText.AppendLine(string.Format("minecraft_version={0}", ModProperties.ModMinecraftVersion));
outputText.AppendLine(string.Format("minecraft_version_range=[{0}]", ModProperties.ModMinecraftVersion));
outputText.AppendLine(string.Format("forge_version={0}", forgeVersionShort));
outputText.AppendLine(string.Format("forge_version_range=[{0},)", forgeVersionRange));
outputText.AppendLine(string.Format("loader_version_range=[{0},)", forgeVersionRange));
outputText.AppendLine(string.Format("mapping_channel={0}", "official"));
outputText.AppendLine(string.Format("mapping_version={0}", ModProperties.ModMinecraftVersion));
outputText.AppendLine(string.Format("mod_id={0}", ModProperties.ModID));
outputText.AppendLine(string.Format("mod_name={0}", ModProperties.ModName));
outputText.AppendLine(string.Format("mod_license={0}", ModProperties.ModLicense));
outputText.AppendLine(string.Format("mod_version={0}", ModProperties.ModVersion));
outputText.AppendLine(string.Format("mod_group_id={0}", ModProperties.ModGroup));
outputText.AppendLine(string.Format("mod_authors={0}", ModProperties.ModAuthors));
outputText.AppendLine(string.Format("mod_description={0}", ModProperties.ModDescription));
// Replace gradle.properties file
File.WriteAllText(filePath, outputText.ToString());
}
/// <summary>
/// Write mod.toml file
/// </summary>
public void WriteModToml()
{
StringBuilder outputText = new StringBuilder();
string filePath = Path.Combine(WorkspaceProperties.WorkspacePath, @"src\main\resources\META-INF\mods.toml");
// General section
outputText.AppendLine("modLoader=\"javafml\"");
outputText.AppendLine("loaderVersion=\"${loader_version_range}\"");
outputText.AppendLine("license=\"${mod_license}\"");
if (!string.IsNullOrEmpty(ModProperties.ModIssueTracker))
outputText.AppendLine(string.Format("issueTrackerURL=\"{0}\"", ModProperties.ModIssueTracker));
// Mod section
outputText.AppendLine();
outputText.AppendLine("[[mods]]");
outputText.AppendLine("modId=\"${mod_id}\"");
outputText.AppendLine("version=\"${mod_version}\"");
outputText.AppendLine("displayName=\"${mod_name}\"");
if (!string.IsNullOrEmpty(ModProperties.ModUpdateJSONURL))
outputText.AppendLine(string.Format("updateJSONURL=\"{0}\"", ModProperties.ModUpdateJSONURL));
if (!string.IsNullOrEmpty(ModProperties.ModWebsite))
outputText.AppendLine(string.Format("displayURL=\"{0}\"", ModProperties.ModWebsite));
if (!string.IsNullOrEmpty(ModProperties.ModLogo))
outputText.AppendLine("logoFile=\"logo.png\"");
if (!string.IsNullOrEmpty(ModProperties.ModCredits))
outputText.AppendLine(string.Format("credits=\"{0}\"", ModProperties.ModCredits));
if (!string.IsNullOrEmpty(ModProperties.ModAuthors))
outputText.AppendLine(string.Format("authors=\"{0}\"", ModProperties.ModAuthors));
outputText.AppendLine("description='''${mod_description}'''");
// Dependencies section
outputText.AppendLine();
outputText.AppendLine("[[dependencies.${mod_id}]]");
outputText.AppendLine("\tmodId=\"forge\"");
outputText.AppendLine("\tmandatory=true");
outputText.AppendLine("\tversionRange=\"${forge_version_range}\"");
outputText.AppendLine("\tordering=\"NONE\"");
outputText.AppendLine("\tside=\"BOTH\"");
outputText.AppendLine();
outputText.AppendLine("[[dependencies.${mod_id}]]");
outputText.AppendLine("\tmodId=\"minecraft\"");
outputText.AppendLine("\tmandatory=true");
outputText.AppendLine("\tversionRange=\"${minecraft_version_range}\"");
outputText.AppendLine("\tordering=\"NONE\"");
outputText.AppendLine("\tside=\"BOTH\"");
// Replace mod.toml file
File.WriteAllText(filePath, outputText.ToString());
}
/// <summary>
/// Check if the workspace is valid for Forge Modding Helper
/// </summary>
/// <param name="supportedMinecraftVersions">Supported minecraft versions</param>
/// <returns><c>true</c> if this is a valid workspace, else <c>false</c></returns>
public bool CheckWorkspaceValidity(List<string> supportedMinecraftVersions)
{
// Check configs files
if (!File.Exists(Path.Combine(WorkspaceProperties.WorkspacePath, @"src\main\resources\META-INF\mods.toml"))
|| !File.Exists(Path.Combine(WorkspaceProperties.WorkspacePath, "gradle.properties")))
return false;
// Read files
if (!ReadModToml()
|| !ReadGradleProperties())
return false;
// Check mandatory data
if (string.IsNullOrEmpty(ModProperties.ModID)
|| string.IsNullOrEmpty(ModProperties.ModGroup)
|| string.IsNullOrEmpty(ModProperties.ModMinecraftVersion)
|| string.IsNullOrEmpty(ModProperties.ModMappingsVersion)
|| string.IsNullOrEmpty(ModProperties.ModVersion)
|| string.IsNullOrEmpty(ModProperties.ModName)
|| string.IsNullOrEmpty(ModProperties.ModAPIVersion))
return false;
// Check Minecraft version
if (!supportedMinecraftVersions.Contains(ModProperties.ModMinecraftVersion))
return false;
return true;
}
}
}
|
import Navbar from "./Navbar";
import Home from "./Home";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Create from "./Create";
import FarmDetails from "./FarmDetails";
import Products from "./Products";
function App() {
return (
<Router>
<div className="App">
<Navbar />
<div className="content">
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/create">
<Create />
</Route>
<Route exact path="/farmcentrals/:id">
<FarmDetails />
</Route>
<Route exact path="/products">
<Products />
</Route>
</Switch>
</div>
</div>
</Router>
);
}
export default App;
|
import streamlit as st
import plotly.express as px
from backend import get_data
st.title("Weather Forecast for the Next Days")
place = st.text_input('Place: ')
days = st.slider("Forecast days: ", min_value=1, max_value=5,
help="Select the number of forecast days")
option = st.selectbox("Selece data to view",
("Temperatures", "Sky"))
st.subheader(f"{option} for the next {days} days in {place}")
if place:
try:
filtered_data = get_data(place, days)
if option == 'Temperatures':
temperatures = [dict["main"]["temp"] / 10 for dict in filtered_data]
dates = [dict["dt_txt"] for dict in filtered_data]
figure = px.line(x=dates, y=temperatures, labels={"x": "Date", "y": "Temperatures"})
st.plotly_chart(figure)
if option == 'Sky':
images = {"Clear" : "images/clear.png", "Clouds": "images/cloud.png",
"Rain" : "images/rain.png", "Snow" : "images/snow.png"}
sky_conditions = [dict["weather"][0]["main"] for dict in filtered_data]
image_paths = [images[condition] for condition in sky_conditions]
st.image(image_paths, width=115)
except KeyError:
st.subheader("City is not found")
|
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#CBDF9966"
android:orientation="vertical">
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom"
android:layout_marginTop="200dp"
android:background="@drawable/bg_login"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginStart="20dp"
android:padding="10dp"
android:text="@string/sign_in"
android:textColor="@color/black"
android:textSize="35sp" />
//android:textStyle="bold"
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"
android:baselineAligned="true"
android:imeOptions="actionNext"
app:boxBackgroundColor="@color/white"
app:endIconMode="clear_text"
app:startIconDrawable="@drawable/ic_email"
app:startIconTint="@color/mainColor"
>
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/et_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/enter_email"
android:imeOptions="actionNext"
android:paddingBottom="-10dp"
android:singleLine="true"
/>
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="5dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="1dp"
app:boxBackgroundColor="@color/white"
app:passwordToggleEnabled="true"
app:startIconDrawable="@drawable/ic_lock"
app:startIconTint="@color/mainColor"
>
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/enter_password"
android:imeOptions="actionGo"
android:inputType="textPassword"
android:paddingBottom="-10dp" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:id="@+id/tv_forget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginEnd="30dp"
android:text="@string/forget_password"
android:textColor="@color/mainColor"
android:textSize="14dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center_vertical"
android:orientation="horizontal"
android:weightSum="10
">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="8">
<Button
android:id="@+id/btn_signIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="20dp"
android:background="@drawable/bg_button"
android:padding="5dp"
android:text="@string/sign_in"
android:textAllCaps="false"
android:textColor="@color/white"
android:textSize="18sp" />
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:layout_gravity="center"
android:outlineAmbientShadowColor="@color/brown"
android:visibility="gone" />
</RelativeLayout>
<ImageButton
android:id="@+id/btn_fingerprint"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginEnd="40dp"
android:background="#0000"
android:padding="8dp"
android:src="@drawable/ic_fingerprint_icon"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
</LinearLayout>
<ImageView
android:id="@+id/imageView"
android:layout_width="179dp"
android:layout_height="146dp"
android:layout_gravity="top|end"
android:layout_marginTop="57dp"
android:layout_marginRight="20dp"
android:src="@drawable/ic_lib_with_admin_icon"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</FrameLayout>
|
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmployeeComponent } from './employee/employee.component';
import { FeedbackComponent } from './feedback/feedback.component';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { SystemComponent } from './system/system.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'employee',
component: EmployeeComponent
},
{
path: 'feedback',
component: FeedbackComponent
},
{
path: 'profile',
component: ProfileComponent
},
{
path: 'system',
component: SystemComponent
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class AdminRoutingModule { }
|
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable} from 'rxjs';
import { RoleService } from './role.service';
import * as moment from 'moment';
import {environment} from '../../../environments/environment';
import {NatureContratVo} from '../model/NatureContrat.model';
@Injectable({
providedIn: 'root'
})
export class NatureContratService {
private API = ''
constructor(private http: HttpClient, private roleService: RoleService) {
this.role$ = this.roleService.role$;
this.role$.subscribe(role => {
this.API = environment.apiUrl + role.toLowerCase() + '/natureContrat/';
})
}
private _natureContrats: Array<NatureContratVo> ;
private _selectedNatureContrat: NatureContratVo;
private _natureContratSelections: Array<NatureContratVo>;
private _createNatureContratDialog: boolean;
private _editNatureContratDialog: boolean;
private _viewNatureContratDialog: boolean;
public editNatureContrat$ = new BehaviorSubject<boolean>(false);
private role$: Observable<string>;
private _searchNatureContrat: NatureContratVo ;
// methods
public findAll(){
return this.http.get<Array<NatureContratVo>>(this.API);
}
public save(): Observable<NatureContratVo> {
return this.http.post<NatureContratVo>(this.API, this.selectedNatureContrat);
}
delete(natureContrat: NatureContratVo) {
return this.http.delete<number>(this.API + 'id/' + natureContrat.id);
}
public edit(): Observable<NatureContratVo> {
return this.http.put<NatureContratVo>(this.API, this.selectedNatureContrat);
}
public findByCriteria(natureContrat:NatureContratVo):Observable<Array<NatureContratVo>>{
return this.http.post<Array<NatureContratVo>>(this.API +'search', natureContrat);
}
public findByIdWithAssociatedList(natureContrat:NatureContratVo):Observable<NatureContratVo>{
return this.http.get<NatureContratVo>(this.API + 'detail/id/' +natureContrat.id);
}
// getters and setters
get natureContrats(): Array<NatureContratVo> {
if(this._natureContrats==null){
this._natureContrats=new Array<NatureContratVo>();
}
return this._natureContrats;
}
set natureContrats(value: Array<NatureContratVo>) {
this._natureContrats = value;
}
get selectedNatureContrat(): NatureContratVo {
if(this._selectedNatureContrat==null){
this._selectedNatureContrat=new NatureContratVo();
}
return this._selectedNatureContrat;
}
set selectedNatureContrat(value: NatureContratVo) {
this._selectedNatureContrat = value;
}
get natureContratSelections(): Array<NatureContratVo> {
if(this._natureContratSelections==null){
this._natureContratSelections=new Array<NatureContratVo>();
}
return this._natureContratSelections;
}
set natureContratSelections(value: Array<NatureContratVo>) {
this._natureContratSelections = value;
}
get createNatureContratDialog(): boolean {
return this._createNatureContratDialog;
}
set createNatureContratDialog(value: boolean) {
this._createNatureContratDialog = value;
}
get editNatureContratDialog(): boolean {
return this._editNatureContratDialog;
}
set editNatureContratDialog(value: boolean) {
this._editNatureContratDialog = value;
}
get viewNatureContratDialog(): boolean {
return this._viewNatureContratDialog;
}
set viewNatureContratDialog(value: boolean) {
this._viewNatureContratDialog = value;
}
get searchNatureContrat(): NatureContratVo {
if(this._searchNatureContrat==null){
this._searchNatureContrat=new NatureContratVo();
}
return this._searchNatureContrat;
}
set searchNatureContrat(value: NatureContratVo) {
this._searchNatureContrat = value;
}
}
|
/******* BISMILLAHIR RAHMANIR RAHIM *******/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
//TypeDEfN
typedef long long int ll;
typedef pair<ll, ll> pll;
typedef vector<ll> vll;
typedef vector<pll> vpll;
typedef vector<string> vs;
typedef unordered_map<ll,ll> umll;
typedef map<ll,ll> mll;
//Constants
const ll INF= LONG_LONG_MAX;
const ll MOD=1e9+7;
inline void normal(ll &a) { a %= MOD; (a < 0) && (a += MOD); }
inline ll modMul(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a*b)%MOD; }
inline ll modAdd(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); return (a+b)%MOD; }
inline ll modSub(ll a, ll b) { a %= MOD, b %= MOD; normal(a), normal(b); a -= b; normal(a); return a; }
inline ll modPow(ll b, ll p) { ll r = 1; while(p) { if(p&1) r = modMul(r, b); b = modMul(b, b); p >>= 1; } return r; }
inline ll modInverse(ll a) { return modPow(a, MOD-2); }
inline ll modDiv(ll a, ll b) { return modMul(a, modInverse(b)); }
typedef tree<int, null_type, less<int>, rb_tree_tag,tree_order_statistics_node_update> OS;
// cout << *p.find_by_order(k) << endl; Returns the address of the element at kth index (while using zero-based indexing)
// cout << p.order_of_key(k)<<endl; Returns the number of elements strictly smaller than k.
// Macros
#define F first
#define S second
#define pb push_back
#define mp make_pair
#define vr(v) v.begin(),v.end()
#define fio(i,n) for(int i=1;i<=n;i++)
#define fiz(i,n) for(int i=0;i<n;i++)
#define fd(i,n) for(int i=n;i>=0;i--)
#define co(n) cout<<n<<endl
#define coy cout<<"Yes"<<endl
#define con cout<<"No"<<endl
#define ci(n) cin>>n
#define w(x) while(x--)
#define ci2(a,b) cin>>a>>b
#define ci3(a,b,c) cin>>a>>b>>c
#define srt(v) sort(v.begin(),v.end());
#define rsrt(v) sort(v.rbegin(),v.rend());
#define rvs(v) reverse(v.begin(),v.end());
#define gcd(a,b) __gcd(a,b)
#define lcm(a,b) (a*b)/gcd(a,b)
#define PI 2*acos(0.0)
#define pii pair<int,int>
#define coutv(v) for(auto it:v)cout<<it<<' ';cout<<endl;
#define cinv(v) for(auto &it:v)cin>>it;
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL);
/*
Time Complexity : O(N^2), Here Two nested loop creates the time complexity. Where N is the size of the
array(nums).
Space Complexity : O(1), Constant space. Extra space is only allocated for the Vector(output), however the
output does not count towards the space complexity.
Solved using Array(Two Nested Loop) + Sorting. Optimized Approach.
*/
vector<vector<int>> fourSum(vector<int>& num, int target) {
vector<vector<int> > res;
if (num.empty())
return res;
int n = num.size();
sort(num.begin(),num.end());
for (int i = 0; i < n; i++) {
int target_3 = target - num[i];
for (int j = i + 1; j < n; j++) {
int target_2 = target_3 - num[j];
int front = j + 1;
int back = n - 1;
while(front < back) {
int two_sum = num[front] + num[back];
if (two_sum < target_2) front++;
else if (two_sum > target_2) back--;
else {
vector<int> quadruplet(4, 0);
quadruplet[0] = num[i];
quadruplet[1] = num[j];
quadruplet[2] = num[front];
quadruplet[3] = num[back];
res.push_back(quadruplet);
// Processing the duplicates of number 3
while (front < back && num[front] == quadruplet[2]) ++front;
// Processing the duplicates of number 4
while (front < back && num[back] == quadruplet[3]) --back;
}
}
// Processing the duplicates of number 2
while(j + 1 < n && num[j + 1] == num[j]) ++j;
}
// Processing the duplicates of number 1
while (i + 1 < n && num[i + 1] == num[i]) ++i;
}
return res;
}
void solve(){
ll a1,a2,b,r,c,n,m,p,q,x,y,z,s=0,Ts=0,cnt=0,mx=0,ok=0,ya=0;
string st;
ci2(n,m);
vector<int>v(n);
for(int i=0;i<n;i++)
{
cin>>v[i];
}
vector<vector<int>> ans=fourSum(v,m);
for(auto it: ans){
for(auto it2: it){
cout<<it2<<" ";
}
cout<<endl;
}
}
int main(){
fastio;
int t=1,tc=0;
//cin>>t;
for(int i=1;i<=t;i++){
// cout<<"Case #"<<i<<": ";
solve();
}
}
/***************** ALHAMDULILLAH *****************/
/*
input:
10 9
4 3 3 4 4 2 1 2 1 1
-2 -2 -1 -1 -1 0 0 0 2 2 2
output:
1 1 3 4
1 2 2 4
1 2 3 3
*/
|
### What you'll learn
- The command line
- Navigating and managing the file system
- Authenticating and authorizing users
- Accessing resources
## Bash
Bash, short for Bourne Again Shell, is a powerful command language interpreter used in Unix and Linux-based operating systems. It is an enhanced version of the original Bourne shell, offering additional features like command-line editing and compatibility with
## Argument (Linux)
Specific information needed by a command

### Standard FHS directories
Directly below the root directory, you’ll find standard FHS directories. In the diagram, home, bin, and etc are standard FHS directories. Here are a few examples of what standard directories contain:
- /home: Each user in the system gets their own home directory.
- /bin: This directory stands for “binary” and contains binary files and other executables. Executables are files that contain a series of commands a computer needs to follow to run programs and perform other functions.
- /etc: This directory stores the system’s configuration files.
- /tmp: This directory stores many temporary files. The /tmp directory is commonly used by attackers because anyone in the system can modify data in these files.
- /mnt: This directory stands for “mount” and stores media, such as USB drives and hard drives.
|
import { spawn } from "node:child_process";
import { GitCommit, GitIndex, GitRef } from "../../universal/git.js";
import { handleError } from "../handleError.js";
import { buffer } from "../utils.js";
import { GitExtension, Repository } from "../store/vscode.git/types.js";
import { gitCheckout } from "./commands/gitCheckout.js";
import { gitLogCommits } from "./commands/gitLogCommits.js";
import { gitLogHeadHash } from "./commands/gitLogHeadHash.js";
import { gitResetHead } from "./commands/gitResetHead.js";
import { gitShowRefFile } from "./commands/gitShowRefFile.js";
import { gitShowRefs } from "./commands/gitShowRefs.js";
import { gitStashList } from "./commands/gitStashList.js";
import { gitStatus } from "./commands/gitStatus.js";
import { GitCommand } from "./commands/utils.js";
import { ensureLogger } from "../logger.js";
export class GitRepository {
constructor(
private repository: Repository,
private extension: GitExtension,
) {}
public async getCommits(): Promise<{
stashes: GitRef[];
commits: AsyncIterable<GitCommit>;
}> {
const stashes = await buffer(this.execGit(gitStashList()));
const commits = this.execGit(gitLogCommits());
return {
stashes: stashes.map((s) => ({ type: "stash", hash: s.hash })),
commits: this.addStashes(commits, stashes),
};
}
public getRefs() {
return this.execGit(gitShowRefs());
}
public async getIndex() {
const status = this.execGit(gitStatus());
const index: GitIndex = {
parents: [await this.getLastCommitHash()],
tracked: [],
untracked: [],
};
for await (const [tracked, untracked] of status) {
tracked && index.tracked.push(tracked);
untracked && index.untracked.push(untracked);
}
return index;
}
public async getLastCommitHash() {
return await this.execGit(gitLogHeadHash());
}
public async reset(ref: string, mode: "soft" | "mixed" | "hard") {
return await this.execGit(gitResetHead(ref, mode));
}
public trueMerge() {}
public ffMerge() {}
public async showFile(ref: string, path: string) {
return await this.execGit(gitShowRefFile(ref, path));
}
public async checkout(branch: string) {
return await this.execGit(gitCheckout(branch));
}
private execGit = <T>(cmd: GitCommand<T>): T => {
const api = this.extension.getAPI(1);
const repository = this.repository;
ensureLogger().appendLine(`[git] ${api.git.path} ${cmd.args.join(" ")}`);
const child = spawn(api.git.path, cmd.args, {
cwd: repository.rootUri.fsPath,
});
child.on("error", (e) => handleError(e));
return cmd.parse(
child.stdout,
new Promise((resolve) => {
child.on("exit", (...args) => resolve(args));
}),
);
};
private async *addStashes(
commits: AsyncIterable<GitCommit>,
stashes: GitCommit[],
) {
for await (const c of commits) {
for (const s of stashes) {
if (s.parents.includes(c.hash)) {
yield s;
}
}
yield c;
}
}
}
|
import 'package:clipboard/clipboard.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:quicklai/constant/show_toast_dialog.dart';
import 'package:quicklai/controller/refercode_controller.dart';
import 'package:quicklai/theam/constant_colors.dart';
import 'package:sizer/sizer.dart';
class ReferCodeScreen extends StatelessWidget {
const ReferCodeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GetX<ReferCodeController>(
init: ReferCodeController(),
builder: (controller) {
return Scaffold(
backgroundColor: ConstantColors.background,
body: controller.isLoading.value == true
? const Center(child: CircularProgressIndicator())
: controller.userModel.value.data?.referralCode == null
? Center(
child: Text(
"Something want wrong".tr,
style: const TextStyle(color: Colors.white),
),
)
: Stack(
alignment: Alignment.topCenter,
children: [
SingleChildScrollView(
child: Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
decoration: const BoxDecoration(image: DecorationImage(image: AssetImage('assets/images/referBG.png'), fit: BoxFit.cover)),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 55),
Row(
children: [
InkWell(
onTap: () {
Navigator.pop(context);
},
child: const Icon(
Icons.arrow_back,
color: Colors.white,
))
],
),
Image.asset(
'assets/images/referIcon.png',
fit: BoxFit.contain,
width: 30.w,
),
const SizedBox(
height: 80,
),
],
),
),
),
const SizedBox(
height: 50,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 18),
Text(
"Invite Friend & Businesses".tr,
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w500, letterSpacing: 2.0, fontSize: 16),
),
const SizedBox(
height: 18,
),
Text(
"${"Invite QuicklAi to sign up using your code and you’ll get".tr} ${controller.userModel.value.data!.refferedLimit.toString()} ${"search limit".tr}",
textAlign: TextAlign.start,
style: const TextStyle(
fontSize: 14,
color: Colors.white, //Color(0XFF666666),
fontWeight: FontWeight.w500,
letterSpacing: 2.0),
),
const SizedBox(
height: 30,
),
Center(
child: GestureDetector(
onTap: () {
FlutterClipboard.copy(controller.userModel.value.data!.referralCode!.toString()).then((value) {
SnackBar snackBar = SnackBar(
content: Text(
"Coupon code copied".tr,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.white),
),
backgroundColor: Colors.green,
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
});
},
child: DottedBorder(
borderType: BorderType.RRect,
radius: const Radius.circular(10),
padding: const EdgeInsets.all(16),
color: const Color(0xff807890),
strokeWidth: 1.5,
dashPattern: const [3],
child: Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
child: Container(
padding: const EdgeInsets.only(left: 16, right: 16, top: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(controller.userModel.value.data!.referralCode!.toString(),
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 16,
fontFamily: "Poppins",
fontWeight: FontWeight.bold,
letterSpacing: 0.5,
color: ConstantColors.primary) //ConstantColors.primary),
),
Text('Tap to Copy'.tr,
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontFamily: "Poppins", fontWeight: FontWeight.w500, letterSpacing: 0.5, color: Colors.white) //ConstantColors.primary),
),
],
)),
),
),
),
),
const SizedBox(height: 18),
Column(
children: [
referIconTile(icons: 'assets/images/linkIcon.png', title: 'Invite a Friend'.tr),
referIconTile(icons: 'assets/images/addFriend.png', title: 'They Register'.tr),
referIconTile(icons: 'assets/images/icreaseSearch.png', title: 'Increase Search Limit'.tr)
],
),
Padding(
padding: EdgeInsets.only(top: 26.sp),
child: SizedBox(
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: ConstantColors.primary, //ConstantColors.primary,
padding: const EdgeInsets.only(top: 12, bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0),
side: BorderSide(color: ConstantColors.primary //ConstantColors.primary,
),
),
),
onPressed: () async {
ShowToastDialog.showLoader('Please wait'.tr);
controller.share();
},
child: Text(
'Refer a Friend'.tr,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.white,
),
),
),
),
),
],
),
)
],
),
),
Positioned(
top: 55.w,
child: Container(
decoration: BoxDecoration(color: ConstantColors.primary, borderRadius: BorderRadius.circular(10)),
width: 90.w,
height: 22.w,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Refer your friends and".tr,
style: const TextStyle(color: Colors.white, letterSpacing: 1.5),
),
Text(
"Increase Search Limit".tr,
style: const TextStyle(fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 1.5),
),
],
),
),
),
],
),
);
});
}
Widget referIconTile({required icons, required title}) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(top: 8, bottom: 8, right: 14),
child: Image.asset(
icons,
fit: BoxFit.contain,
width: 13.w,
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Text(title,
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 14, fontFamily: "Poppins", fontWeight: FontWeight.w500, letterSpacing: 0.5, color: Colors.white) //ConstantColors.primary),
),
),
],
);
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">
<title>Inicio- Dev Andrew</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="img/logo.png" type="image/x-icon">
<link rel="stylesheet" href="fontawesome-free-6.4.0-web/css/all.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg">
<div class="container-fluid">
<a class="navbar-brand logo" href="#"><img src="img/logo.png" alt="Logo do Site"></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-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">
<ul class="navbar-nav">
<a class="nav-link navbar-link" aria-current="page" href="#">Home</a>
<a class="nav-link navbar-link" href="#skills">Skills</a>
<a class="nav-link navbar-link" href="#projects">Projects</a>
<a class="nav-link navbar-link" href="#container-certificados">Certificações</a>
<a class="nav-link navbar-link" href="#about">Sobre</a>
<button class="btMusic" id="music">
<img src="img/music-player.svg" alt="Svg music player">
</button>
</ul>
</div>
</div>
</nav>
<main class="mainn">
<div id="text-boas-vindas"></div>
<section class="container-perfil">
<div class="container text-center">
<div class="row">
<div class="col-md-3 filho-links-perfil">
<a href="https://www.linkedin.com/in/andrewgpsilva/" target="_blank"><i
class="fa-brands fa-linkedin fa-2xl icon-linkedin icon-redes"></i></a>
<a href="https://github.com/AndrewGPSilva" target="_blank"><i
class="fa-brands fa-github fa-2xl icon-github icon-redes"></i></a>
<a href="https://www.facebook.com/Andrew13G" target="_blank"><i
class="fa-brands fa-facebook fa-2xl icon-facebook icon-redes"></i></a>
</div>
<div class="col-md-6">
<div class="divisao-texto"><h2>PERFIL <i class="fa-solid fa-user"></i></h2></div>
<div class="dois-filho">
<img src="img/20230506_133653.jpg" alt="Imagem de Perfil" />
<p style="text-decoration: underline;">Andrew Silva</p>
</div>
</div>
<div class="col-md-3 filho-links-perfil">
<a href="https://www.instagram.com/andrew_gpereira/" target="_blank"><i
class="fa-brands fa-instagram fa-2xl icon-instagram icon-redes"></i></a>
<a href="https://www.tiktok.com/@gps_drew_dev" target="_blank"><i
class="fa-brands fa-tiktok fa-2xl icon-tiktok icon-redes"></i></a>
<a href="https://twitter.com/AndrewGPS13" target="_blank"><i
class="fa-brands fa-twitter fa-2xl icon-twitter icon-redes"></i></a>
</div>
<div class="containerLinksMobile">
<a href="https://www.linkedin.com/in/andrewgpsilva/" target="_blank"><i
class="fa-brands fa-linkedin fa-2xl icon-linkedin icon-redes"></i></a>
<a href="https://github.com/AndrewGPSilva" target="_blank"><i
class="fa-brands fa-github fa-2xl icon-github icon-redes"></i></a>
<a href="https://www.facebook.com/Andrew13G" target="_blank"><i
class="fa-brands fa-facebook fa-2xl icon-facebook icon-redes"></i></a>
<a href="https://www.instagram.com/andrew_gpereira/" target="_blank"><i
class="fa-brands fa-instagram fa-2xl icon-instagram icon-redes"></i></a>
<a href="https://www.tiktok.com/@gps_drew_dev" target="_blank"><i
class="fa-brands fa-tiktok fa-2xl icon-tiktok icon-redes"></i></a>
<a href="https://twitter.com/AndrewGPS13" target="_blank"><i
class="fa-brands fa-twitter fa-2xl icon-twitter icon-redes"></i></a>
</div>
</div>
</div>
</section>
<div class="divisao-texto">
<h2>SKILLS <i class="fa-solid fa-bolt fa-sm"></i></h2>
</div>
<section class="skills section" id="skills">
<div class="skills-texto">
<h2> <My <br> Skills/></h2>
</div>
<div class="skills-filho">
<div class="div-icon"><i class="fa-brands fa-php fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-laravel fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-node-js fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-java fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-vuejs fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-git-alt fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-square-js fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-bootstrap fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-sharp fa-solid fa-database fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-html5 fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-css3 fa-2xl icon-skills"></i></div>
<div class="div-icon"><i class="fa-brands fa-react fa-2xl icon-skills"></i></div>
</div>
</section>
<div class="divisao-texto">
<h2>PROJETOS <i class="fa-solid fa-file fa-sm"></i></h2>
</div>
<section class="projects section" id="projects">
<div class="card text-center" style="width: 20rem;">
<iframe width="319px" height="200" src="https://www.youtube.com/embed/lDSNpT-zP7g"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen></iframe>
<div class="card-body">
<h2 class="card-title">Cárdapio Digital</h2>
<p class="card-text">Projeto utilizando PHP como back-end, realizando todos os 4 conceitos do CRUD.
</p>
</div>
</div>
<div class="card text-center" style="width: 20rem;">
<iframe width="319" height="200" src="https://www.youtube.com/embed/uGSDovBg1p4?si=7qOWLZjR1WmLogFT"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen></iframe>
<div class="card-body">
<h2 class="card-title">Projeto Place TV</h2>
<p class="card-text">Projeto utilizando laravel, uma nova versão do place tv mas com muito mais
coisas, login, crud, validações...</p>
</div>
</div>
<div class="card text-center" style="width: 20rem;">
<iframe width="319" height="200" src="https://www.youtube.com/embed/r6V_st9eKco?si=Ordv3-7EsqQQ7dnm"
title="YouTube video player" frameborder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
allowfullscreen></iframe>
<div class="card-body">
<h2 class="card-title">Portfólio com VUE 3</h2>
<p class="card-text">Projeto para replicar esse portfólio só que dessa vez usando o framework Vue</p>
</div>
</div>
<div class="card text-center" style="width: 20rem;">
<a href="https://me-conheca.vercel.app/" target="_blank"><img src="img/meconheca.png"
class="card-img-top img-space-animes" alt="Imagem do Site para me conhecer"></a>
<div class="card-body">
<h2 class="card-title">Me conheça mais</h2>
<p class="card-text">Projeto usando React.js<br>Onde é possivel conhecer um pouco mais detalhada a
minha trajetória!</p>
<a href="https://me-conheca.vercel.app/" target="_blank" class="btn btn-primary fs-4">Acessar
site</a>
</div>
</div>
<div class="card text-center" style="width: 20rem;">
<a href="https://placetv.vercel.app/" target="_blank"><img src="img/Captura de Tela (17).png"
class="card-img-top img-space-animes" alt="Imagem do Site Place TV"></a>
<div class="card-body">
<h2 class="card-title">Place TV</h2>
<p class="card-text">Projeto pessoal em Andamento<br>Onde irei falar sobre o Anime e trazer
atualizações diariamente!</p>
<a href="https://placetv.vercel.app/" target="_blank" class="btn btn-primary fs-4">Acessar site</a>
</div>
</div>
<div class="card text-center" style="width: 20rem;">
<a href="https://tailwind-node-react.vercel.app/" target="_blank"><img src="https://i.ibb.co/vZ6bBPT/1695377218898.jpg"
class="card-img-top img-space-animes" alt="Imagem do Site GPSflix"></a>
<div class="card-body">
<h2 class="card-title">GPSflix</h2>
<p class="card-text">Projeto utilizando React Js, Tailwind CSS no Front-End e uma API minha com Node Js no Back-End.</p>
<a href="https://tailwind-node-react.vercel.app/" target="_blank" class="btn btn-primary fs-4">Acessar site</a>
</div>
</div>
<div class="card text-center" style="width: 20rem;">
<a href="https://space-animes-bt6b9x6uz-andrewgpsilva.vercel.app/" target="_blank"><img
src="img/space-animes.png" class="card-img-top img-space-animes"
alt="Imagem do Site Space Animes"></a>
<div class="card-body">
<h2 class="card-title">Space Animes</h2>
<p class="card-text">Projeto utilizando React.js<br>Onde mostro alguns dos meus animes preferidos!
</p>
<a href="https://space-animes-bt6b9x6uz-andrewgpsilva.vercel.app/" target="_blank"
class="btn btn-primary fs-4">Acessar site</a>
</div>
</div>
<div class="card text-center" style="width: 20rem;">
<a href="https://tripula-one-piece.vercel.app/" target="_blank"><img src="img/organo.png"
class="card-img-top img-space-animes" alt="Imagem do Site Monte sua Tripulação"></a>
<div class="card-body">
<h2 class="card-title">Monte sua Tripulação</h2>
<p class="card-text">Projeto usando React.js<br>Onde é possivel montar sua própria tripulação!</p>
<a href="https://tripula-one-piece.vercel.app/" target="_blank" class="btn btn-primary fs-4">Acessar
site</a>
</div>
</div>
<div class="card text-center" style="width: 20rem;">
<a href="https://banco-conversoes.vercel.app/" target="_blank"><img src="img/apibank.png"
class="card-img-top img-space-animes" alt="Imagem do Site Place Bank"></a>
<div class="card-body">
<h2 class="card-title">Veja Cotações</h2>
<p class="card-text">Projeto usando API com JS<br>Onde é possivel visualizar em tempo real a cotação
do Dólar e de Ienes!</p>
<a href="https://banco-conversoes.vercel.app/" target="_blank" class="btn btn-primary fs-4">Acessar
site</a>
</div>
</div>
</section>
<div class="divisao-texto-certificados">
<h2>CERTIFICAÇÕES <i class="fa-solid fa-envelope fa-2xl"></i></h2>
</div>
<section id="container-certificados" class="container-certificados">
<table class="table table-bordered border-primary">
<thead>
<tr>
<th scope="col">TECNOLOGIAS</th>
<th scope="col">LINK</th>
</tr>
</thead>
<tbody class="table-group-divider">
<tr>
<td>Bootstrap</td>
<td><a href="https://cursos.alura.com.br/certificate/f185d254-f27f-4ae8-b209-29b50196172e?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>Java</td>
<td><a href="https://cursos.alura.com.br/certificate/0af21e4e-04b5-4858-9f7d-be9518e4e590?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>Javascript</td>
<td><a href="https://cursos.alura.com.br/degree/certificate/acfd4d6b-f502-45c6-af2e-0ed4f711e05e?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>Laravel</td>
<td><a href="https://cursos.alura.com.br/degree/certificate/14dbb833-ad67-457b-84e1-e6f2c53bef6b?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>Node Js</td>
<td><a href="https://cursos.alura.com.br/certificate/b7e418ad-6ac5-41c2-962a-d176d5562684?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>PHP</td>
<td><a href="https://cursos.alura.com.br/certificate/ed534a54-b593-4e2f-8350-7ecd8129ec57?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>React Js</td>
<td><a href="https://cursos.alura.com.br/degree/certificate/d6cba813-20d8-4352-b3da-8ec2a2f5758f?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>Spring Boot</td>
<td><a href="https://cursos.alura.com.br/certificate/be62c82e-efe3-4fd4-853b-b9583339d32b?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>Tailwind CSS</td>
<td><a href="https://cursos.alura.com.br/certificate/b25aea5c-72a2-4e39-8e15-e556f9e284e0?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>Typescript</td>
<td><a href="https://cursos.alura.com.br/certificate/075720d3-519d-4c35-8535-7b4aaca9eb94?lang=pt_BR" target="_blank">VER</a></td>
</tr>
<tr>
<td>Vue Js</td>
<td><a href="https://cursos.alura.com.br/certificate/6125f29d-8fae-40fd-9c2c-7068f2962417?lang=pt_BR" target="_blank">VER</a></td>
</tr>
</tbody>
</table>
</section>
<div class="divisao-texto-about">
<h2>ABOUT <i class="fa-regular fa-address-card fa-2xl"></i></h2>
</div>
<section class="sobre-form" id="about">
<div class="sobre">
<button class="quer-me-conhecer" id="quer-me-conhecer">Leia mais...</button>
<p id="sobre-infos" class="sobre-infos">Oi, tudo bem? Eu sou aluno da plataforma da Alura e faço Analíse
e Desenvolvimento de Sistemas pela FAM!
Minha trajetória com programação começou em 2017 através do curso técnico de Mecatrônica que fiz
pelo Senai, lá tive contato com a linguagem C!
Nesse curso mencionado fui o responsável pelo desenvolvimento de um aplicativo mobile android onde
todas as funções do meu TCC iria ser controlado diretamente pelo aplicativo, não só comandos mas
também o recebimento de informações como temperatura, umidade e entre outras coisas.
Após essa experiência tive contato novamente com o mundo da programação através da faculdade que fiz
por 1 ano antes de vir de fato para TI, cursei 2 períodos de Bacharel em Matemática onde lá tive
contato com a linguagem Python!
E foi ai que eu percebi que era aquilo que eu desejava para minha vida, não se passou muito tempo e
já comecei com cursos referente o front-end! Nessa disciplina onde utilizei Python fui responsável
pela criação de um sistema onde o funcionário de RH iria digitar valores e informações sobre um
funcionário e com o cálculo iria retornar o valor de aumento através de fórmulas no sistema!
Desde então, venho me empenhando cada dia mais para me tornar um desenvolvedor Back End, já tenho
dominio em diversas tecnologias e estou mais do que pronto para o mercado de TI!</p>
</div>
<div class="divisao-linha"></div>
<div class="form">
<h2>Entre em Contato</h2>
<form>
<div class="form-nome">
<label>Nome</label>
<input type="text" placeholder="Digite aqui seu nome..." required>
</div>
<div class="form-email">
<label>Email</label>
<input type="email" placeholder="Digite aqui seu email..." required>
</div>
<div class="form-mensagem">
<label>Mensagem</label>
<textarea name="" id="" cols="30" rows="2" placeholder="Digite sua mensagem..."
required></textarea>
</div>
<button>
<div>
<span>
<p>ENVIAR</p>
<p>:)</p>
</span>
</div>
<div>
<span>
<p>CLIQUE</p>
<p>:D</p>
</span>
</div>
</button>
</form>
</div>
<div class="divisao-linha-dois"></div>
</section>
<button id="btnTopo" class="btn-topo" onclick="retornarAoTopo()">
<i class="fa-solid fa-arrow-up"></i>
</button>
</main>
<footer>
<h2>© Desenvolvido por Andrew</h2>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
crossorigin="anonymous"></script>
<script type="module" src="/js/main.js"></script>
</body>
</html>
|
import React from "react";
import "./Testimonials.css";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
// import { Pagination } from "swiper";
import "swiper/css/pagination";
import profilePic1 from "../../img/profile1.jpg";
import profilePic2 from "../../img/profile2.jpg";
import profilePic3 from "../../img/profile3.jpg";
import profilePic4 from "../../img/profile4.jpg";
const Testimonials = () => {
const clients = [
{
img: profilePic1,
review:
"I stumbled upon this website and was blown away by the quality of service. The user-friendly interface made it easy to navigate and find exactly what I needed. The services provided were top-notch, and the support team was responsive and helpful throughout. I highly recommend this website!",
},
{
img: profilePic2,
review:
"I had a fantastic experience with this website and its services. From the moment I landed on the homepage, I was impressed by the professionalism and attention to detail. The services were delivered promptly, and the results exceeded my expectations. I'll definitely be returning for more!.",
},
{
img: profilePic3,
review:
"I've been a loyal customer of this website for years, and I can't praise it enough. The services offered are not only affordable but also of exceptional quality. The website is constantly updated with useful information, and I always feel like they genuinely care about their clients. It's a five-star experience!.",
},
{
img: profilePic4,
review:
"I've tried several similar websites, but this one stands out from the rest. The services are competitively priced, and the website's layout is clean and intuitive. What sets them apart is their commitment to customer satisfaction. They went above and beyond to address my concerns and deliver a solution that worked for me. I'm extremely satisfied.",
},
];
return (
<div className="t-wrapper" id="testimonial">
<div className="t-heading">
<span>Clients always get </span>
<span>Exceptional Work </span>
<span>from me...</span>
<div className="blur t-blur1" style={{ background: "var(--purple)" }}></div>
<div className="blur t-blur2" style={{ background: "skyblue" }}></div>
</div>
<Swiper
// install Swiper modules
// modules={[Pagination]}
// slidesPerView={1}
// pagination={{ clickable: true }}
>
{clients.map((client, index) => {
return (
<SwiperSlide key={index}>
<div className="testimonial">
<img src={client.img} alt="" />
<span>{client.review}</span>
</div>
</SwiperSlide>
);
})}
</Swiper>
</div>
);
};
export default Testimonials;
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Responsive design</title>
<link rel="stylesheet" type="text/css" href="../style.css">
<script src="https://kit.fontawesome.com/011cc9ac28.js" crossorigin="anonymous"></script>
</head>
<body>
<div class="contenedor-contenedor-nav-principal-y-logo">
<div class="contenedor-nav-principal-y-logo">
<div class="logo-container">
<a class="logo" href="../index.html">JM</a>
</div>
<nav class="nav">
<ul class="nav__ul">
<li class="nav__li"></i><a href="../index.html"><i class="fas fa-home"></i>Inicio</a></li>
<li class="nav__li"><a href="../sobre-mi.html" class="nav__item"><i
class="fa-solid fa-circle-user"></i>Sobre mi</a></li>
<li class="nav__li"><a href="../ejercicios.html" class="nav__item"><i
class="fa-solid fa-dumbbell"></i>Ejercicios</a></li>
<li class="nav__li"><a href="../contacto.html" class="nav__item"><i
class="fa-solid fa-address-book"></i>Contacto</a></li>
</ul>
<ul class="nav__responsive-ul">
<div class="nav__responsive-button-container">
<div class="nav__responsive-button fa-solid fa-bars"></div>
</div>
<div class="nav__li-container">
<li class="nav__responsive-li "><a href="../index.html" class="nav__item"><i
class="fas fa-home"></i>Inicio</a></li>
<li class="nav__responsive-li"><a href="../sobre-mi.html" class="nav__item"><i
class="fa-solid fa-circle-user"></i>Sobre mi</a></li>
<li class="nav__responsive-li"><a href="../ejercicios.html" class="nav__item"><i
class="fa-solid fa-dumbbell"></i>Ejercicios</a></li>
<li class="nav__responsive-li"><a href="../contacto.html" class="nav__item"><i
class="fa-solid fa-address-book"></i>Contacto</a></li>
</div>
</ul>
</nav>
</div>
</div>
<div class="contenedor">
<h1>Responsive design con @media</h1>
<p>Usamos @media screen para adaptar el diseño al tamaño de pantalla segun va aumentando o disminuyendo.</p>
<div class="div-responsive-design">
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Magni voluptates nostrum doloremque fuga
doloribus ea, error minima aliquid accusamus voluptate corporis cum natus? Esse deleniti libero, itaque
culpa at repudiandae?</p>
</div>
<h1>Responsive design con @media + grid</h1>
<p>Usamos @media screen + grid, para adaptar el diseño al tamaño de pantalla segun va aumentando o disminuyendo.
</p>
<div class="contenedor-reponsive-grid">
<div class="header__responsive"><b>Header</b></div>
<div class="main__responsive"><b>principal</b></div>
<div class="aside__responsive"><b>lateral</b></div>
<div class="footer__responsive"><b>footer</b></div>
</div>
</div>
</body>
|
# Mybatis获取参数值的两种方式
- MyBatis获取参数值的两种方式:${}和#{}
- **${}的本质就是字符串拼接,#{}的本质就是占位符赋值**
- ${}使用字符串拼接的方式拼接sql,若为字符串类型或日期类型的字段进行赋值时,需要手动加单引号;
- 但是#{}使用占位符赋值的方式拼接sql,此时为字符串类型或日期类型的字段进行赋值时,可以自动添加单引号
- **建议分成两种情况进行处理**
1. 实体类类型的参数
2. 使用@Param标识参数
## 单个字面量类型的参数
若mapper接口中的方法参数为单个的字面量类型,此时可以使用\${}和#{}以任意的名称(最好见名识意)获取参数的值,也就是说#{}或者${}里面的参数的名称是无所谓的,注意${}需要手动加单引号
```
<!--User getUserByUsername(String username);-->
<select id="getUserByUsername" resultType="User">
select * from t_user where username = #{username}
select * from t_user where username = #{aaa}
以上两种是一样的
</select>
```
```
<!--User getUserByUsername(String username);-->
<select id="getUserByUsername" resultType="User">
select * from t_user where username = '${username}'
</select>
```
## 多个字面量类型的参数
- 若mapper接口中的方法参数为多个时,此时MyBatis会自动将这些参数放在一个map集合中
1. 以arg0,arg1...为键,以参数为值;
2. 以param1,param2...为键,以参数为值;
- 因此只需要通过\${}和#{}访问map集合的键就可以获取相对应的值,注意${}需要手动加单引号。
- 使用arg或者param都行,要注意的是,arg是从arg0开始的,param是从param1开始的
```
<!--User checkLogin(String username,String password);-->
<select id="checkLogin" resultType="User">
select * from t_user where username = #{arg0} and password = #{arg1}
</select>
```
```
<!--User checkLogin(String username,String password);-->
<select id="checkLogin" resultType="User">
select * from t_user where username = '${param1}' and password = '${param2}'
</select>
```
## map集合类型的参数
若mapper接口中的方法需要的参数为多个时,此时可以手动创建map集合,将这些数据放在map中只需要通过\${}和#{}访问map集合的键就可以获取相对应的值,注意${}需要手动加单引号
```
<!--User checkLoginByMap(Map<String,Object> map);-->
<select id="checkLoginByMap" resultType="User">
select * from t_user where username = #{username} and password = #{password}
</select>
```
```
@Test
public void checkLoginByMap() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
Map<String,Object> map = new HashMap<>();
map.put("usermane","admin");
map.put("password","123456");
User user = mapper.checkLoginByMap(map);
System.out.println(user);
}
```
## 实体类类型的参数
若mapper接口中的方法参数为实体类对象时此时可以使用\${}和#{},通过访问实体类对象中的属性名获取属性值,属性是实体类中的get、set方法。没有成员变量,但是有相应的get、set值,也就证明实体类中有这个属性,注意${}需要手动加单引号
```
<!--int insertUser(User user);-->
<insert id="insertUser">
insert into t_user values(null,#{username},#{password},#{age},#{sex},#{email})
</insert>
```
```
@Test
public void insertUser() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
User user = new User(null,"Tom","123456",12,"男","123@321.com");
mapper.insertUser(user);
}
```
## 使用@Param标识参数
- 可以通过@Param注解标识mapper接口中的方法参数,此时,会将这些参数放在map集合中
1. 以@Param注解的value属性值为键,以参数为值;
2. 以param1,param2...为键,以参数为值;
- 只需要通过\${}和#{}访问map集合的键就可以获取相对应的值,注意${}需要手动加单引号
```
<!--User CheckLoginByParam(@Param("username") String username, @Param("password") String password);-->
<select id="CheckLoginByParam" resultType="User">
select * from t_user where username = #{username} and password = #{password}
</select>
```
```
@Test
public void checkLoginByParam() {
SqlSession sqlSession = SqlSessionUtils.getSqlSession();
ParameterMapper mapper = sqlSession.getMapper(ParameterMapper.class);
mapper.CheckLoginByParam("admin","123456");
}
```
|
import * as Joi from 'joi';
import { GroupValidationRule } from '~/common/enums/enums';
import { GroupValidationMessage } from '~/common/enums/group/group';
import { GroupsUpdateRequestDto } from '~/common/types/types';
import { getNameOf } from '~/helpers/helpers';
const groupUpdate = Joi.object({
[getNameOf<GroupsUpdateRequestDto>('name')]: Joi.string()
.trim()
.min(GroupValidationRule.NAME_MIN_LENGTH)
.max(GroupValidationRule.NAME_MAX_LENGTH)
.required()
.messages({
'string.empty': GroupValidationMessage.NAME_REQUIRE,
'string.min': GroupValidationMessage.NAME_MIN_LENGTH,
'string.max': GroupValidationMessage.NAME_MAX_LENGTH,
'string.base': GroupValidationMessage.NAME_STRING,
'any.required': GroupValidationMessage.NAME_REQUIRE,
}),
[getNameOf<GroupsUpdateRequestDto>('permissionIds')]: Joi.array()
.items(Joi.number())
.min(GroupValidationRule.PERMISSION_IDS_MIN_LENGTH)
.required()
.messages({
'array.empty': GroupValidationMessage.PERMISSION_IDS_REQUIRE,
'array.min': GroupValidationMessage.PERMISSION_IDS_MIN_LENGTH,
'array.base': GroupValidationMessage.PREMISSION_IDS_INTEGER,
'any.required': GroupValidationMessage.PERMISSION_IDS_REQUIRE,
}),
[getNameOf<GroupsUpdateRequestDto>('userIds')]: Joi.array()
.items(Joi.number())
.required()
.messages({
'array.base': GroupValidationMessage.USER_IDS_INTEGER,
'any.required': GroupValidationMessage.USER_IDS_REQUIRE,
}),
});
export { groupUpdate };
|
"""
Zad. 5 (DevsMentoring)
Stwórz program symulujący talię kart (klasa Deck) oraz pojedyncze karty (klasa Card). Karta ma być związana z takimi polami jak: wartość (np. 9) oraz figura (np. Diamond).
W klasie Deck znajdować ma się lista reprezentująca stos kart w ramach jednej talii. W Deck znaleźć mają się takie metody jak: shuffle (która może wykorzystywać metodę o tej samej
nazwie - shuffle - z biblioteki random) oraz deal (która będzie usuwała i zwracała ostatnią kartę z talii).
Podpowiedź:
Talia kart ma się składać z 52 różnych obiektów Card o wszystkich możliwych kombinacjach pól, np. (A - Diamond, A - Clubs itd). Aby utworzyć taką kombinację, utwórz dwie niezależne
listy - w pierwszej przechowuj możliwe figury, a w drugiej wartości. Następnie przechodząc pętlami, łącz je ze sobą i twórz obiekty.
"""
class Card:
def __init__(self, color: str, value: str) -> None:
self.color = color
self.value = value
def __repr__(self):
return f"Card({self.color}, {self.value})"
def __eq__(self, other):
if isinstance(other, Card):
return (self.color == other.color and
self.value == other.value)
class Deck:
values = [str(n) for n in range(2, 11)] + list('JQKA')
colors = 'spades diamonds clubs hearts'.split()
def __init__(self) -> None:
self.cards = Deck.build()
@staticmethod
def build() -> list[Card]:
cards = []
for c in Deck.colors:
for v in Deck.values:
cards.append(Card(color=c, value=v))
return cards
def shuffle(self):
from random import shuffle
shuffle(self.cards)
def play_last(self):
return self.cards.pop()
# value = []
# color = ["Hearts", "Clubs", "Diamonds" ,"Spades"]
# for number in range(1, 14):
# value.append(number)
# value[0] = "As"
# value[10] = "J"
# value[11] = "Q"
# value[12] = "K"
# for c in color:
# for v in value:
# self.cards.append(Card(c, v))
# print(self.cards)
# shuffle = random.shuffle(self.cards)
# return(shuffle)
def main():
french_deck = Deck()
print(french_deck.cards)
card_1 = Card('Clubs', 5)
card_2 = Card('Clubs', 5)
print(id(card_1))
print(id(card_2))
print(card_1 == card_2)
if __name__ == '__main__':
main()
"""
# draw five cards
print("You got:")
for i in range(5):
print(deck[i][0], "of", deck[i][1])
"""
|
<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lesson 3: Lists, Conditionals, and Computed Properties</title>
<script src="https://unpkg.com/vue@3"></script>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="h-full grid place-items-center">
<div id="app">
<section v-show="inProgressAssignments.length">
<h2 class="font-bold mb-2">In Progress</h2>
<ul>
<li
v-for="assignment in inProgressAssignments"
:key="assignment.id"
>
<label>
{{ assignment.name }}
<input type="checkbox" v-model="assignment.complete" >
</label>
</li>
</ul>
<!-- <pre>
{{ assignments }}
</pre> -->
</section>
<!-- v-if => display the section if the condition evaluates to true -->
<!-- v-show => display the section if the condition evaluates to false -->
<section v-show="completedAssignments.length" class="mt-8">
<h2 class="font-bold mb-2">Completed</h2>
<ul>
<li
v-for="assignment in completedAssignments"
:key="assignment.id"
>
<label>
{{ assignment.name }}
<input type="checkbox" v-model="assignment.complete" >
</label>
</li>
</ul>
</section>
</div>
<script>
let app = {
data() {
return {
assignments: [
{ name: 'Finished project', complete: false, id: 1 },
{ name: 'Read Chapter 4', complete: false, id: 2 },
{ name: 'Turn in homework', complete: false, id: 3 },
]
}
},
computed: {
inProgressAssignments() {
return this.assignments.filter(a => ! a.complete)
},
completedAssignments() {
return this.assignments.filter(a => a.complete)
}
}
};
Vue.createApp(app).mount('#app')
</script>
</body>
</html>
|
import axios from "axios";
import { Pagination, TextInput } from "flowbite-react";
import React, { useEffect, useState } from "react";
import { useContext } from "react";
import { IoIosArrowDown } from "react-icons/io";
import swal from "sweetalert";
import { AuthContext } from "../../context/AuthContext";
export default function ContactsTable() {
const { cookies } = useContext(AuthContext);
const [data, setData] = useState();
const [search, setSearch] = useState("");
const [columns, setColumns] = useState();
const [w, setW] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [nPages, setNPages] = useState(1);
const [recordsPerPage, setRecordsPerPage] = useState(10);
const [indexOfLastRecord, setIndexOfLastRecord] = useState(); // = currentPage * recordsPerPage;
const indexOfFirstRecord =
indexOfLastRecord - recordsPerPage < 0
? 0
: indexOfLastRecord - recordsPerPage;
const [currentRecords, setCurrentRecords] = useState([]);
const reArrangeData = (data) => {
const dataForTable = data?.map((contact) => ({
id: contact.id,
date: makeDateHumanReadable(contact.created_at),
message: contact.message,
email: contact.email,
}));
setData(dataForTable);
};
useEffect(() => {
if (cookies.Token && localStorage.getItem("admin")) {
axios
.get("/api/allContacts", {
headers: {
Authorization: `Bearer ${cookies.Token}`,
},
})
.then((res) => {
reArrangeData(res.data.contacts);
})
.catch((err) => {
swal("Error", err.message, "error");
});
}
}, []);
useEffect(() => {
setColumns([
{
name: "Id",
id: "id",
sort: true,
},
{
name: "Email",
id: "email",
sort: true,
},
{
name: "Message",
id: "message",
sort: true,
},
{
name: "Date",
id: "date",
sort: true,
},
]);
}, []);
useEffect(() => {
data?.length - (currentPage - 1) * recordsPerPage < recordsPerPage
? setIndexOfLastRecord(data?.length)
: setIndexOfLastRecord(recordsPerPage * currentPage);
const num = Math.ceil(data?.length / recordsPerPage);
if (num) {
num <= 1 ? setNPages(1) : setNPages(num);
}
}, [data, currentPage, recordsPerPage]);
useEffect(() => {
// setCurrentRecords()
if (search == "") {
setCurrentRecords(data?.slice(indexOfFirstRecord, indexOfLastRecord));
} else {
const filtered = data?.filter((entry) =>
Object.values(entry).some(
(val) =>
(typeof val === "string" &&
val.toLowerCase().includes(search.toLowerCase())) ||
(typeof val === "number" &&
val.toString().includes(search.toString()))
)
);
setCurrentRecords(filtered);
}
}, [data, search, indexOfFirstRecord, indexOfLastRecord]);
// check state effect
function sortByKey(array, key, sort) {
sort
? setData([...array].sort((a, b) => (a[key] < b[key] ? 1 : -1)))
: setData([...array].sort((a, b) => (a[key] > b[key] ? 1 : -1)));
setW(!w);
}
function makeDateHumanReadable(dateString) {
const date = new Date(dateString);
return date.toLocaleDateString() + " " + date.toLocaleTimeString();
}
return (
<section className="w-7/12 m-auto p-6 bg-white rounded-md shadow-md dark:bg-gray-800 space-y-5">
<h2 className="text-lg font-semibold text-gray-700 capitalize dark:text-white">
Contacts
</h2>
<TextInput
id="email1"
type="email"
placeholder="Search"
required={true}
className="w-52 my-2"
onChange={(e) => setSearch(e.target.value)}
/>
<div className="overflow-x-auto relative shadow-md sm:rounded-lg">
<table className="w-full text-sm text-left text-gray-500 dark:text-gray-400">
<thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
<tr>
{columns?.map((col, i) => {
return (
<th key={i} scope="col" className="py-3 px-6">
{col.sort ? (
<span
onClick={() => sortByKey(data, col.id, w)}
className="flex items-center gap-2 cursor-pointer hover:text-gray-500"
>
{col.name}
<IoIosArrowDown size={12} />
</span>
) : (
<span className="flex items-center gap-2 ">
{col.name}
</span>
)}
</th>
);
})}
</tr>
</thead>
<tbody>
{currentRecords?.length > 0 ? (
currentRecords?.map((item, i) => {
return (
<tr
key={i}
className="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600"
>
<td className="whitespace-nowrap px-2 py-2 font-medium text-gray-900 dark:text-white">
{item.id}
</td>
<td className="whitespace-nowrap px-2 py-2 font-medium text-gray-900 dark:text-white">
{item.email}
</td>
<td className="whitespace-nowrap px-2 py-2 font-medium text-gray-900 dark:text-white">
{item.message}
</td>
<td className="whitespace-nowrap px-2 py-2 font-medium text-gray-900 dark:text-white">
{item.date}
</td>
</tr>
);
})
) : (
<tr className="dark:bg-gray-900">
<td colSpan={columns?.length}>
<div className="flex justify-center items-center ">
<p>No Data Was Found</p>
</div>
</td>
</tr>
)}
</tbody>
<tfoot>
<tr>
<td colSpan={columns?.length}>
<div className="flex justify-around items-center ">
<div>
{search === "" ? (
<span>
{indexOfFirstRecord + 1}-{indexOfLastRecord} of{" "}
{data?.length}
</span>
) : (
<span>Results found: {currentRecords?.length}</span>
)}
</div>
<Pagination
className={` ${
(nPages == 1 || search !== "") && "invisible"
} pb-2`}
currentPage={currentPage}
totalPages={nPages}
onPageChange={(e) => setCurrentPage(e)}
/>
<div
className={`flex gap-2 items-center ${
search !== "" && "invisible"
}`}
>
<label className=" whitespace-nowrap ">
Rows per page:
</label>
<div className=" ">
<div className="my-1 ">
<select
onChange={(e) =>
setRecordsPerPage(parseInt(e.target.value))
}
className=" block text-[9px] md:text-[12px] md:px-7 md:py-2 px-2 py-1 dark:bg-slate-700 rounded-md border border-gray-300 focus:border-indigo-500 focus:outline-none focus:ring-indigo-500 "
>
<option className="" defaultValue="10">
10
</option>
<option defaultValue="20">20</option>
<option defaultValue="30">30</option>
<option defaultValue="50">50</option>
</select>
</div>
</div>
</div>
</div>
</td>
</tr>
</tfoot>
</table>
</div>
</section>
);
}
|
import { config } from './config';
import cors from 'cors';
import http from 'http';
import express, { Request, Response } from 'express';
import { Server } from 'socket.io';
import { AppDataSource } from './data-source';
import { setAppApiController } from './controller';
import { setupPassportStrategies } from './auth/strategies';
import {
boomErrorHandler,
errorHandler,
logErrors,
} from './middlewares/errorHandler';
import { generateWaterSchedulers, resetSchedules } from './scheduler';
require('console-stamp')(console, {
format: ':date(yyyy/mm/dd HH:MM:ss.l):label',
});
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
const server = http.createServer(app);
export const io = new Server(server);
AppDataSource.initialize()
.then(async () => {
await resetSchedules();
await generateWaterSchedulers();
})
.catch((error) => console.log(error));
// passport strategies
setupPassportStrategies();
// routes
setAppApiController(app);
// middlewares
app.use(logErrors);
app.use(boomErrorHandler);
app.use(errorHandler);
io.on('connection', (socket) => {
console.log('a user connected');
// console.log(io.sockets.adapter.rooms);
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
app.get('/test', (req: Request, res: Response) => {
console.log(io.sockets.adapter.rooms);
res.json({
test: 'hello',
});
});
server.listen(config.appPort, () => {
console.log('listening on *:', config.appPort);
});
|
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const morgan = require('morgan');
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(morgan('combined'));
app.enableCors();
const configSerrvice = app.get<ConfigService>(ConfigService);
const config = new DocumentBuilder()
.setTitle('Vently API')
.setDescription('The Vently API description')
.setVersion('1.0')
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);
await app.listen(configSerrvice.get('PORT'));
}
bootstrap();
|
<form [formGroup]="form" (ngSubmit)="submit()">
<div class="form-group">
<label for="exampleFormControlSelect1">Search by</label>
<select class="form-control" id="selectSearch"
#selectSearch formControlName="selectSearch">
<option value="1" selected>Company name</option>
<option value="2">Start city destination</option>
<option value="3">Landing city destination</option>
</select>
<div *ngIf="f.selectSearch.touched && f.selectSearch.invalid" class="alert alert-danger">
<div *ngIf="f.selectSearch.errors.required">Select is required.</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Input search</label>
<div class="input-group-prepend">
<input formControlName="search" type="text" #search
placeholder="enter text..." class="form-control" aria-label="search"
id="search" aria-describedby="searchHelp">
<button type="button" class="btn btn-outline-secondary"
(click) = "search.value = ''">
<svg class="bi bi-backspace" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M6.603 2h7.08a1 1 0 011 1v10a1 1 0 01-1 1h-7.08a1 1 0 01-.76-.35L1 8l4.844-5.65A1 1 0 016.603 2zm7.08-1a2 2 0 012 2v10a2 2 0 01-2 2h-7.08a2 2 0 01-1.519-.698L.241 8.65a1 1 0 010-1.302L5.084 1.7A2 2 0 016.603 1h7.08z" clip-rule="evenodd"/>
<path fill-rule="evenodd" d="M5.83 5.146a.5.5 0 000 .708l5 5a.5.5 0 00.707-.708l-5-5a.5.5 0 00-.708 0z" clip-rule="evenodd"/>
<path fill-rule="evenodd" d="M11.537 5.146a.5.5 0 010 .708l-5 5a.5.5 0 01-.708-.708l5-5a.5.5 0 01.707 0z" clip-rule="evenodd"/>
</svg>
</button>
</div>
</div>
<div *ngIf="f.search.touched && f.search.invalid" class="alert alert-danger">
<div *ngIf="f.search.errors.required">Search text is required.</div>
</div>
<button type="submit" [disabled]="!form.valid" class="btn btn-primary">Search</button>
<button type="button" class="btn btn-primary" style="float: right;" (click)="showAll();">Show all</button>
</form>
|
package de.metas.ui.web.dashboard;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.concurrent.Immutable;
import org.adempiere.exceptions.AdempiereException;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import de.metas.ui.web.exceptions.EntityNotFoundException;
import de.metas.ui.web.websocket.WebSocketConfig;
import de.metas.util.Check;
@Immutable
public class UserDashboard {
public UserDashboard EMPTY;
private int id;
private int adClientId;
private Map<Integer,UserDashboardItem> _targetIndicatorItemsById;
private Map<Integer,UserDashboardItem> _kpiItemsById;
private String websocketEndpoint;
private Integer id;
private Integer adClientId;
private List<UserDashboardItem> targetIndicatorItems;
private List<UserDashboardItem> kpiItems;
public Set<Integer> getItemIds(DashboardWidgetType dashboardWidgetType){
return getItemsById(dashboardWidgetType).keySet();
}
public String getWebsocketEndpoint(){
return websocketEndpoint;
}
public int getId(){
return id;
}
public Map<Integer,UserDashboardItem> getItemsById(DashboardWidgetType widgetType){
if (widgetType == DashboardWidgetType.TargetIndicator) {
return _targetIndicatorItemsById;
} else if (widgetType == DashboardWidgetType.KPI) {
return _kpiItemsById;
} else {
throw new AdempiereException("Unknown widget type: " + widgetType);
}
}
public int getAdClientId(){
return adClientId;
}
public Collection<UserDashboardItem> getItems(DashboardWidgetType dashboardWidgetType){
return getItemsById(dashboardWidgetType).values();
}
public Builder addItem(UserDashboardItem item){
Check.assumeNotNull(item, "Parameter item is not null");
switch(item.getWidgetType()) {
case TargetIndicator:
targetIndicatorItems.add(item);
break;
case KPI:
kpiItems.add(item);
break;
}
return this;
}
public void assertItemIdExists(DashboardWidgetType dashboardWidgetType,int itemId){
// will fail if itemId does not exist
getItemById(dashboardWidgetType, itemId);
}
public UserDashboard build(){
Check.assumeNotNull(id, "Parameter id is not null");
return new UserDashboard(this);
}
public Builder builder(){
return new Builder();
}
public Builder setAdClientId(Integer adClientId){
this.adClientId = adClientId;
return this;
}
public Builder setId(int id){
this.id = id;
return this;
}
@Override
public String toString(){
return MoreObjects.toStringHelper(this).omitNullValues().add("id", id).add("targetIndicatorItems", _targetIndicatorItemsById.isEmpty() ? null : _targetIndicatorItemsById).add("kpiItemsById", _kpiItemsById.isEmpty() ? null : _kpiItemsById).toString();
}
public UserDashboardItem getItemById(DashboardWidgetType dashboardWidgetType,int itemId){
final UserDashboardItem item = getItemsById(dashboardWidgetType).get(itemId);
if (item == null) {
throw new EntityNotFoundException("No " + dashboardWidgetType + " item found").setParameter("itemId", itemId);
}
return item;
}
}
|
class Api::V2::CatchesController < ApplicationController
before_action :set_user
before_action :set_catch, only: [:show, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
def create
@catch = @user.catches.build(catch_params)
@catch.cloudinary_urls = params[:cloudinary_urls] if params[:cloudinary_urls]
begin
@catch.save!
render json: CatchSerializer.new(@catch), status: 201
rescue ActiveRecord::RecordInvalid => e
render json: { error: e.message }, status: 422
end
end
def index
catches = @user.catches.all
render json: CatchSerializer.new(catches), status: 200
end
def show
render json: CatchSerializer.new(@catch), status: 200
end
def update
if params[:cloudinary_urls]
@catch.cloudinary_urls = params[:cloudinary_urls]
end
if @catch.update(catch_params)
render json: CatchSerializer.new(@catch), status: 200
else
render json: { error: "Validation failed: #{@catch.errors.full_messages.join(", ")}" }, status: 422
end
end
def destroy
@catch.destroy
render json: { message: "Catch successfully deleted" }, status: 200
end
private
def set_user
@user = User.find(params[:user_id])
end
def set_catch
@catch = @user.catches.find(params[:id])
end
def catch_params
params.require(:catch).permit(:species, :weight, :length, :spot_name, :latitude, :longitude, :lure, cloudinary_urls: [])
end
def record_not_found(error)
model_name = error.message.split(" ")[2..2].join(" ").gsub(/#/, '').singularize
render json: { error: "No #{model_name} with that ID could be found" }, status: :not_found
end
def purge_photos(ids_to_delete)
photo_ids = ids_to_delete.split(",").map(&:to_i)
purged_photos = []
errors = []
photo_ids.each do |id|
begin
photo = @catch.photos.find(id)
photo.purge_later
purged_photos << id
rescue ActiveRecord::RecordNotFound => e
errors << "Photo with ID #{id} could not be found"
end
end
end
end
|
import panaderia from "./panaderia.js";
// Función para actualizar la lista según la búsqueda
function actualizarListaBusqueda(busquedaUsuario) {
const contenedor = document.getElementById("listado-productos");
let contenidoHtml = "";
panaderia.tipos.forEach((tipo) => {
// Filtra los tipos que tienen un título que coincide con lo que se busca
if (tipo.nombre.toLowerCase().includes(busquedaUsuario.toLowerCase())) {
contenidoHtml += `<article>
<h4>${tipo.nombre}</h4>
<ol>
${tipo.productos
.filter((producto) => producto.nombre.toLowerCase().includes(busquedaUsuario.toLowerCase()))
.map((producto) => `<li>${producto.nombre}</li>`).join("")}
</ol>
</article>`;
} else {
// Si no coincide con el título, busca en los nombres de los productos
const productosCoincidentes = tipo.productos
.filter((producto) => producto.nombre.toLowerCase().includes(busquedaUsuario.toLowerCase()));
// Si hay productos que coinciden, muestra el tipo y los productos
if (productosCoincidentes.length > 0) {
contenidoHtml += `<article>
<h4>${tipo.nombre}</h4>
<ol>
${productosCoincidentes.map((producto) => `<li>${producto.nombre}</li>`).join("")}
</ol>
</article>`;
}
}
});
contenedor.innerHTML = contenidoHtml;
}
// Maneja el evento de cambio en el cuadro de texto de búsqueda
document.getElementById("buscarProducto").addEventListener("input", function (event) {
const terminoBusqueda = event.target.value.trim();
actualizarListaBusqueda(terminoBusqueda);
});
// Inicializa la lista con todos los productos al cargar la página
actualizarListaBusqueda("");
|
DROP DATABASE if EXISTS Hamacoteca;
CREATE DATABASE Hamacoteca;
USE Hamacoteca;
CREATE TABLE roles_administradores(
id_rol INT AUTO_INCREMENT PRIMARY KEY,
nombre_rol VARCHAR(60),
CONSTRAINT uq_nombre_rol_unico UNIQUE(nombre_rol)
);
CREATE TABLE administradores(
id_administrador INT AUTO_INCREMENT PRIMARY KEY,
nombre_administrador VARCHAR(50) NOT NULL,
apellido_administrador VARCHAR(50) NOT NULL,
clave_administrador VARCHAR(100) NOT NULL,
correo_administrador VARCHAR(50) NOT NULL,
CONSTRAINT uq_correo_administrador_unico UNIQUE(correo_administrador),
CONSTRAINT chk_correo_administrador_formato CHECK (correo_administrador REGEXP '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$'),
telefono_administrador VARCHAR(15) NOT NULL,
dui_administrador VARCHAR(10) NOT NULL,
CONSTRAINT uq_dui_administrador_unico UNIQUE(dui_administrador),
fecha_nacimiento_administrador DATE NOT NULL,
alias_administrador VARCHAR(25) NOT NULL,
CONSTRAINT uq_alias_administrador_unico UNIQUE(alias_administrador),
fecha_creacion DATETIME DEFAULT NOW(),
id_rol INT,
CONSTRAINT fk_rol_administradores FOREIGN KEY (id_rol)
REFERENCES roles_administradores(id_rol),
intentos_administrador INT DEFAULT 0,
fecha_clave DATETIME NULL,
fecha_bloqueo DATETIME NULL,
foto_administrador VARCHAR(50) NULL,
CONSTRAINT chk_url_foto_administrador CHECK (foto_administrador LIKE '%.jpg' OR foto_administrador LIKE '%.png' OR foto_administrador LIKE '%.jpeg' OR foto_administrador LIKE '%.gif')
);
CREATE TABLE clientes(
id_cliente INT AUTO_INCREMENT PRIMARY KEY,
nombre_cliente VARCHAR(50) NOT NULL,
apellido_cliente VARCHAR(50) NOT NULL,
clave_cliente VARCHAR(50) NOT NULL,
correo_cliente VARCHAR(50) NOT NULL,
CONSTRAINT uq_correo_cliente_unico UNIQUE(correo_cliente),
CONSTRAINT chk_correo_cliente_formato CHECK (correo_cliente REGEXP '^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$'),
dui_cliente VARCHAR(10) NOT NULL,
CONSTRAINT uq_dui_cliente_unico UNIQUE(dui_cliente),
genero_cliente ENUM('Masculino', 'Femenino', 'No definido') NOT NULL,
fecha_nacimiento_cliente DATE NOT NULL,
telefono_cliente VARCHAR(15) NOT NULL,
estado_cliente BOOLEAN DEFAULT 1 NULL,
fecha_registro DATETIME DEFAULT NOW(),
direccion_cliente VARCHAR(100) NOT NULL,
foto_cliente VARCHAR(50) NULL,
CONSTRAINT chk_url_foto_cliente CHECK (foto_cliente LIKE '%.jpg' OR foto_cliente LIKE '%.png' OR foto_cliente LIKE '%.jpeg' OR foto_cliente LIKE '%.gif')
);
CREATE TABLE categorias(
id_categoria INT AUTO_INCREMENT PRIMARY KEY,
nombre_categoria VARCHAR(50) NOT NULL,
CONSTRAINT uq_nombre_categoria_unico UNIQUE(nombre_categoria),
descripcion_categoria TEXT NOT NULL
);
CREATE TABLE materiales(
id_material INT AUTO_INCREMENT PRIMARY KEY,
nombre_material VARCHAR(60) NOT NULL,
CONSTRAINT uq_nombre_material_unico UNIQUE(nombre_material),
descripcion_material TEXT NOT NULL,
foto_material VARCHAR(60) NULL,
CONSTRAINT chk_url_foto_material CHECK (foto_material LIKE '%.jpg' OR foto_material LIKE '%.png' OR foto_material LIKE '%.jpeg' OR foto_material LIKE '%.gif')
);
CREATE TABLE hamacas(
id_hamaca INT AUTO_INCREMENT PRIMARY KEY,
nombre_hamaca VARCHAR(60) NOT NULL,
descripcion_hamaca TEXT NOT NULL,
precio DECIMAL(5,2) NOT NULL,
CONSTRAINT chk_precio_mayor_a_cero CHECK (precio >= 0),
estado_venta ENUM('Disponible', 'Agotado') NOT NULL,
cantidad_hamaca INT NOT NULL,
CONSTRAINT chk_cantidad_hamaca_mayor_a_cero CHECK (cantidad_hamaca >= 0),
foto_principal VARCHAR(50),
CONSTRAINT chk_url_foto_principal CHECK (foto_principal LIKE '%.jpg' OR foto_principal LIKE '%.png' OR foto_principal LIKE '%.jpeg' OR foto_principal LIKE '%.gif'),
id_administrador INT,
CONSTRAINT fk_administrador_de_hamaca FOREIGN KEY (id_administrador)
REFERENCES administradores(id_administrador),
id_categoria INT,
CONSTRAINT fk_categoria_de_la_hamaca FOREIGN KEY (id_categoria)
REFERENCES categorias(id_categoria),
id_material INT,
CONSTRAINT fk_material_de_la_hamaca FOREIGN KEY (id_material)
REFERENCES materiales(id_material)
);
CREATE TABLE fotos(
id_foto INT AUTO_INCREMENT PRIMARY KEY,
url VARCHAR(60) NOT NULL,
CONSTRAINT chk_url_foto CHECK (url LIKE '%.jpg' OR url LIKE '%.png' OR url LIKE '%.jpeg' OR url LIKE '%.gif'),
id_hamaca INT,
CONSTRAINT fk_fotos_de_las_hamacas FOREIGN KEY (id_hamaca)
REFERENCES hamacas(id_hamaca)
);
CREATE TABLE pedidos(
id_pedido INT AUTO_INCREMENT PRIMARY KEY,
estado_pedido ENUM('Entregado', 'En camino', 'Cancelado') NOT NULL,
fecha_pedido DATETIME DEFAULT NOW(),
direccion_pedido VARCHAR(50) NOT NULL,
id_cliente INT,
CONSTRAINT fk_carrito_del_cliente FOREIGN KEY (id_cliente)
REFERENCES clientes(id_cliente)
);
CREATE TABLE detalles_pedidos(
id_detalles_pedidos INT AUTO_INCREMENT PRIMARY KEY,
id_pedido INT,
CONSTRAINT fk_detalles_pedido FOREIGN KEY (id_pedido)
REFERENCES pedidos(id_pedido),
precio_producto DECIMAL(5,2) NOT NULL,
CONSTRAINT chk_precio_producto_mayor_a_cero CHECK(precio_producto > 0),
cantidad_comprada INT NOT NULL,
CONSTRAINT chk_cantidad_comprada_mayor_a_cero CHECK(cantidad_comprada > 0),
id_hamaca INT,
CONSTRAINT fk_hamacas_en_el_carrito FOREIGN KEY (id_hamaca)
REFERENCES hamacas(id_hamaca)
);
CREATE TABLE valoraciones(
id_valoracion INT AUTO_INCREMENT PRIMARY KEY,
calificacion_producto INT NOT NULL,
CONSTRAINT chk_calificacion_producto_mayor_a_cero CHECK(calificacion_producto > 0),
comentario_producto TEXT NULL,
fecha_valoracion DATETIME DEFAULT NOW(),
estado_comentario BOOLEAN NOT NULL DEFAULT 1,
id_detalles_pedidos INT,
CONSTRAINT fk_valoraciones_de_las_hamacas FOREIGN KEY (id_detalles_pedidos)
REFERENCES detalles_pedidos(id_detalles_pedidos)
);
|
---
aliases:
- /ja/security_monitoring/detection_rules/
- /ja/cloud_siem/detection_rules/
- /ja/security_platform/detection_rules/
- /ja/security/security_monitoring/log_detection_rules/
further_reading:
- link: /security/default_rules/#all
tag: Documentation
text: デフォルトの検出ルールについて
- link: /security/notifications/
tag: ドキュメント
text: セキュリティ通知について
- link: https://www.datadoghq.com/blog/detect-abuse-of-functionality-with-datadog/
tag: ブログ
text: Datadog で機能の悪用を検出
- link: https://www.datadoghq.com/blog/impossible-travel-detection-rules/
tag: ブログ
text: 不可能な旅行検出ルールで不審なログイン行為を検出する
kind: documentation
title: 検出ルール
---
検出ルールは、取り込まれたすべてのログとクラウド構成に適用される条件ロジックを定義します。ルールに定義されたケースに一定期間中に少なくとも 1 つ一致すると、セキュリティシグナルが生成されます。これらのシグナルは、[Signal Explorer][16] で確認できます。
## すぐに使える検出ルール
Datadog は、攻撃者のテクニックや潜在的な誤構成にフラグを立てるための[すぐに使える検出ルール][1]を提供しています。新しい検出ルールがリリースされると、構成に応じてアカウント、Application Security Management ライブラリ、Agent に自動的にインポートされます。
すぐに使えるルールは以下のセキュリティ製品で利用できます。
- [Cloud SIEM][2] は、取り込んだログをリアルタイムに分析するログ検出を使用します。
- Cloud Security Management (CSM):
- [CSM Misconfigurations][4] では、クラウド構成およびインフラストラクチャー構成検出ルールを使用して、クラウド環境の状態をスキャンします。
- [CSM Threats][5] は、Datadog Agent と検出ルールを使用して、システムのアクティビティをアクティブに監視・評価します。
- [CSM Identity Risks][14] では、IAM に基づくリスクをクラウドインフラストラクチャー内で検出するために検出ルールを使用します。
- [Application Security Management][6] (ASM) は、Datadog [APM][7]、[Datadog Agent][8]、検出ルールを活用し、アプリケーション環境における脅威を検出します。
## ベータ検出ルール
Datadog のセキュリティリサーチチームは、継続的に新しいすぐに使えるセキュリティ検出ルールを追加しています。その目的は、インテグレーションやその他の新機能のリリースとともに高品質の検出を提供することですが、そのルールを一般的に利用可能にする前に、多くの場合、大規模での検出のパフォーマンスを観察する必要があります。これにより、Datadog のセキュリティリサーチは、当社の基準を満たさない検出の機会を改善したり、非推奨にしたりする時間を得ることができます。
## カスタム検出ルール
ご自身の環境やワークロードに基づいてルールをカスタマイズする必要がある場合があります。例えば、ASM を使用している場合、ビジネスが行われていない地域から機密アクションを実行するユーザーを検出する検出ルールをカスタマイズしたいと思うかもしれません。
[カスタムルールを作成](#create-detection-rules)するには、デフォルトのルールを複製してそのコピーを編集するか、一から独自のルールを作成します。
## 検出ルールの検索とフィルタリング
Datadog ですぐに使える検出ルールとカスタム検出ルールを表示するには、[**Security** > **Configuration**][15] ページに移動します。ルールは、各製品 (Application Security、Cloud Security Management、Cloud SIEM) の個別のページにリストされています。
ルールを検索してフィルタリングするには、検索ボックスとファセットを使用して値でクエリします。例えば、指定したルールタイプのルールだけを表示するには、ルールタイプにカーソルを合わせて `only` を選択します。また、受信した問題を調査したりトリアージする際に、`source` や `severity` などのファセットでフィルタリングすることもできます。
{{< img src="security/default_detection_rules.png" alt="Configuration ページでは、デフォルトおよびカスタムの Cloud SIEM 検出ルールが表示されています" width="100%">}}
## 検出ルールを作成する
カスタム検出ルールを作成するには、Detection Rules ページの右上隅にある **New Rule** ボタンをクリックします。また、[既存のデフォルトルールまたはカスタムルールを複製](#clone-a-rule)してテンプレートとして使用することもできます。
詳しい説明は以下の記事をご覧ください。
- [Cloud SIEM][3]
- [ASM][11]
- [CSM Misconfigurations][12]
- [CSM Threats][13]
## 検出ルールを管理する
### ルールの有効化・無効化
ルールを有効または無効にするには、ルール名の右側にあるスイッチを切り替えます。
また、ルールの一括有効化、無効化も可能です。
1. **Select Rules** をクリックします。
1. 有効化または無効化したいルールを選択します。
1. **Edit Rules** ドロップダウンメニューをクリックします。
1. **Enable Rules** または **Disable Rules** を選択します。
### ルールを編集する
すぐに使える検出ルールでは、抑制クエリの追加や編集のみが可能です。クエリを更新したり、トリガーを調整したり、通知を管理したりするには、[デフォルトルールを複製](#clone-a-rule)して、カスタムルールのテンプレートとして使用します。その後、[デフォルトのルールを無効にする](#enable-or-disable-rules)ことができます。
- デフォルトルールを編集するには、ルールの横にある縦の 3 点メニューをクリックして、**Edit default rule** を選択します。
- カスタムルールを編集するには、ルールの横にある縦の 3 点メニューをクリックして、**Edit rule** を選択します。
### ルールを複製する
ルールを複製するには、ルールの横にある縦の 3 点メニューをクリックして、**Clone rule** を選択します。
ルールの複製は、既存のルールを複製して軽く設定を変更し、他の検出領域をカバーしたい場合に便利です。例えば、ログ検出ルールを複製し、**Threshold** から **Anomaly** に変更することで、同じクエリとトリガーを使用して脅威検出に新しい次元を追加することができます。
### すべてのチームを取得する
カスタムルールを削除するには、ルールの横にある縦の 3 点メニューをクリックして、**Delete rule** を選択します。
**注**: 削除できるのはカスタムルールだけです。デフォルトのルールを削除するには、[それを無効にする](#enable-or-disable-rules)必要があります。
### 編集権限を制限する
デフォルトでは、すべてのユーザーが検出ルールにフルアクセスできます。粒度の高いアクセス制御を使用して、1 つのルールを編集できる[ロール][10]を制限するには
1. ルールの横にある縦の 3 点メニューをクリックし、**Permissions** を選択します。
1. **Restrict Access** をクリックします。ダイアログボックスが更新され、組織のメンバーはデフォルトで **Viewer** アクセス権を持っていることが表示されます。
1. ドロップダウンメニューを使用して、セキュリティルールを編集できるロール、チーム、またはユーザーを 1 つ以上選択します。
1. **Add** をクリックします。
1. **Save** をクリックします。
**注:** 規則の編集アクセス権を維持するために、保存する前に、少なくとも 1 つのロールのメンバーであることを含めることがシステムから要求されます。
ルールへのアクセスを復元するには
1. ルールの横にある縦の 3 点メニューをクリックし、**Permissions** を選択します。
1. **Restore Full Access** をクリックします。
1. **Save** をクリックします。
### 生成されたシグナルを表示する
[Signals Explorer][16] でルールのセキュリティシグナルを表示するには、縦 3 点メニ ューをクリックし、**View generated signals** を選択します。これは、ルールごとに複数のソースのシグナルを相関付ける場合や、ルールの監査を完了する場合に便利です。
### ルールを JSON としてエクスポートする
ルールのコピーを JSON としてエクスポートするには、ルールの横にある縦の 3 点メニューをクリックし、**Export as JSON** を選択します。
## ルール非推奨
すべての検出ルールに対して定期的な監査が実施され、高いシグナル品質が維持されます。非推奨となったルールは、改善されたルールに置き換えられます。
ルール非推奨のプロセスは以下の通りです。
1. ルールに非推奨の日付が書かれた警告が表示されています。UI では、警告が以下に表示されます。
- シグナルサイドパネルの **Rule Details > Playbook** セクション
- Misconfigurations サイドパネル (CSM Misconfigurations のみ)
- その特定のルールの[ルールエディター][15]
2. ルールが非推奨になると、ルールが削除されるまでに 15 か月の期間があります。これは、シグナルの保持期間が 15 か月であるためです。この間、UI で[ルールの複製](#clone-a-rule)を行うと、ルールを再び有効にすることができます。
3. 一度削除されたルールは、複製して再度有効にすることはできません。
## その他の参考資料
{{< partial name="whats-next/whats-next.html" >}}
[1]: /ja/security/default_rules/
[2]: /ja/security/cloud_siem/
[3]: /ja/security/cloud_siem/log_detection_rules/
[4]: /ja/security/misconfigurations/
[5]: /ja/security/threats/
[6]: /ja/security/application_security/
[7]: /ja/tracing/
[8]: /ja/agent/
[9]: https://app.datadoghq.com/security/configuration/rules
[10]: /ja/account_management/rbac/
[11]: /ja/security/application_security/threats/custom_rules/
[12]: /ja/security/misconfigurations/custom_rules
[13]: /ja/security/threats/workload_security_rules?tab=host#create-custom-rules
[14]: /ja/security/identity_risks/
[15]: https://app.datadoghq.com/security/configuration/
[16]: https://app.datadoghq.com/security
|
import { StateCreator } from 'zustand'
export interface CounterSlice {
counter: {
count: number
increaseCount: () => void
decreaseCount: () => void
resetCount: () => void
}
}
export const initialState: CounterSlice = {
counter: {
count: 0,
increaseCount: () => { },
decreaseCount: () => { },
resetCount: () => { },
}
}
export const createCounterSlice: StateCreator<
CounterSlice,
[],
[],
CounterSlice
> = (set) => ({
counter: {
...initialState.counter,
increaseCount: () => set((state) => ({ counter: { ...state.counter, count: state.counter.count + 1 } })),
decreaseCount: () => set((state) => ({ counter: { ...state.counter, count: state.counter.count - 1 } })),
resetCount: () => set((state) => ({ counter: { ...state.counter, count: initialState.counter.count } })),
}
})
|
#include "PCH.h"
#include "Renderer.h"
#include "SevenSegment.h"
#include "TimeString.h"
void SevenSegment::Init(ID2D1Factory2* pD2DFactory, ID2D1DeviceContext* dc, float size, float skew, D2D1::ColorF color1, D2D1::ColorF color2)
{
constexpr float padding = 1.1f;
m_Length = size / 2.0f;
m_Width = m_Length * 0.2f;
m_CornerLength = m_Length - m_Width;
m_DigitWidth = (m_Length * 2.0f + m_Width * 2.0f) * padding;
m_DigitHeight = (m_Length * 4.0f + m_Width * 2.0f) * padding;
//m_Scale = size / 20.0f;
float shadowoffset = m_Width * 1.2f;
//pulls in segment so there is a gap between them.
const float pull = m_Length * 0.22f;
const float length = m_Length - pull;
const float cornerlength = m_CornerLength - pull;
const float width = m_Width;
ComPtr<ID2D1PathGeometry> Geometry;
ComPtr<ID2D1GeometrySink> Sink;
HR(pD2DFactory->CreatePathGeometry(Geometry.ReleaseAndGetAddressOf()));
HR(Geometry->Open(Sink.ReleaseAndGetAddressOf()));
Sink->SetFillMode(D2D1_FILL_MODE_WINDING);
D2D1_POINT_2F p1 = { -length, 0.0f };
D2D1_POINT_2F p2 = { -cornerlength,-width };
D2D1_POINT_2F p3 = { cornerlength ,-width };
D2D1_POINT_2F p4 = { length, 0.0f };
D2D1_POINT_2F p5 = { cornerlength, width };
D2D1_POINT_2F p6 = { -cornerlength, width };
Sink->BeginFigure(p1, D2D1_FIGURE_BEGIN_FILLED);
Sink->AddLine(p2);
Sink->AddLine(p3);
Sink->AddLine(p4);
Sink->AddLine(p5);
Sink->AddLine(p6);
Sink->EndFigure(D2D1_FIGURE_END_CLOSED);
HR(Sink->Close());
ComPtr<ID2D1SolidColorBrush> FillBrush;
HR(dc->CreateSolidColorBrush(color1, FillBrush.ReleaseAndGetAddressOf()));
ComPtr<ID2D1SolidColorBrush> OutlineBrush;
HR(dc->CreateSolidColorBrush(color2, OutlineBrush.ReleaseAndGetAddressOf()));
D2D1_SIZE_F BitmapSize = { GetDigitWidth() + 2.0f, GetDigitHeight() + 2.0f }; // Adding a 1 pixel border
auto CreateBitmaps = [&] (BYTE digit, ID2D1SolidColorBrush* fillbrush, ID2D1SolidColorBrush* outlinebrush)
{
ComPtr<ID2D1BitmapRenderTarget> BitmapRenderTarget;
ComPtr<ID2D1Bitmap> Bitmap;
HR(dc->CreateCompatibleRenderTarget(BitmapSize, &BitmapRenderTarget));
BitmapRenderTarget->BeginDraw();
D2D1::Matrix3x2F transform = D2D1::Matrix3x2F::Translation(BitmapSize.width / 2.0f, BitmapSize.height / 2.0f);
RasterizeDigit(BitmapRenderTarget.Get(), Geometry.Get(), digit, transform, fillbrush, outlinebrush);
HR(BitmapRenderTarget->EndDraw());
HR(BitmapRenderTarget->GetBitmap(Bitmap.ReleaseAndGetAddressOf()));
ComPtr<ID2D1Effect> ShadowEffect;
ComPtr<ID2D1Effect> AffineTransformEffect;
ComPtr<ID2D1Effect> CompositeEffect;
HR(dc->CreateEffect(CLSID_D2D1Shadow, ShadowEffect.ReleaseAndGetAddressOf()));
HR(dc->CreateEffect(CLSID_D2D12DAffineTransform, AffineTransformEffect.ReleaseAndGetAddressOf()));
HR(dc->CreateEffect(CLSID_D2D1Composite, CompositeEffect.ReleaseAndGetAddressOf()));
ShadowEffect->SetInput(0, Bitmap.Get());
AffineTransformEffect->SetInputEffect(0, ShadowEffect.Get());
D2D1_MATRIX_3X2_F matrix = D2D1::Matrix3x2F::Translation(shadowoffset, shadowoffset);
AffineTransformEffect->SetValue(D2D1_2DAFFINETRANSFORM_PROP_TRANSFORM_MATRIX, matrix);
CompositeEffect->SetInputEffect(0, AffineTransformEffect.Get());
CompositeEffect->SetInput(1, Bitmap.Get());
return CompositeEffect;
};
for (int i = 0; i < DIGITCOUNT; i++)
{
Bitmaps[i] = CreateBitmaps(i, FillBrush.Get(), OutlineBrush.Get());
}
D2D1::Matrix3x2F translationdown = D2D1::Matrix3x2F::Translation(0.0f, GetDigitHeight() / 2.0f);
D2D1::Matrix3x2F skewmatrix = D2D1::Matrix3x2F::Skew(skew, 0.0f);
D2D1::Matrix3x2F translationup = D2D1::Matrix3x2F::Translation(0.0f, -GetDigitHeight() / 2.0f);
m_Skew = translationup * skewmatrix * translationdown;
}
float SevenSegment::GetStringWidth(const TimeString& timeString)
{
const int size = timeString.GetSize();
float stringwidth = 0;
for (int i = 0; i < size; i++)
{
char value = timeString.GetChar(i);
char nextvalue = timeString.GetChar(i + 1);
stringwidth += GetDigitSpacing(value, nextvalue);
}
return stringwidth;
}
float SevenSegment::GetStringWidth(const TimeStringSmall& timeString)
{
const int size = timeString.GetSize();
float stringwidth = 0;
for (int i = 0; i < size; i++)
{
char value = timeString.GetChar(i);
char nextvalue = timeString.GetChar(i + 1);
stringwidth += GetDigitSpacing(value, nextvalue);
}
return stringwidth;
}
void SevenSegment::DrawDigits(ID2D1DeviceContext* dc, const TimeString& timeString, D2D1::Matrix3x2F transform)
{
D2D1::Matrix3x2F maintransform = m_Skew * transform;
D2D1::Matrix3x2F digittransform = D2D1::Matrix3x2F::Identity();
D2D1_RECT_F rect = D2D1::RectF(0.0f, 0.0f, GetDigitWidth(), GetDigitHeight());
const int size = timeString.GetSize();
for (int i = 0; i < size; i++)
{
char value = timeString.GetChar(i);
char nextvalue = timeString.GetChar(i + 1);
ID2D1Effect* Digit = GetBitmap(value);
if (i == size - 1)
dc->SetTransform(D2D1::Matrix3x2F::Scale(0.7f, 0.7f) * D2D1::Matrix3x2F::Translation(0.0f, GetDigitHeight() * 0.3f) * digittransform * maintransform);
else if (value == 'd')
dc->SetTransform(D2D1::Matrix3x2F::Scale(0.7f, 0.7f) * D2D1::Matrix3x2F::Translation(0.0f, GetDigitHeight() * 0.3f) * digittransform * maintransform);
else
dc->SetTransform(digittransform * maintransform);
digittransform = D2D1::Matrix3x2F::Translation(GetDigitSpacing(value, nextvalue), 0.0f) * digittransform;
if (Digit)
{
dc->DrawImage(Digit);
}
}
}
void SevenSegment::DrawDigits(ID2D1DeviceContext* dc, const TimeStringSmall& timeString, D2D1::Matrix3x2F transform)
{
D2D1::Matrix3x2F maintransform = m_Skew * transform;
D2D1::Matrix3x2F digittransform = D2D1::Matrix3x2F::Identity();
D2D1_RECT_F rect = D2D1::RectF(0.0f, 0.0f, GetDigitWidth(), GetDigitHeight());
const int size = timeString.GetSize();
for (int i = 0; i < size; i++)
{
char value = timeString.GetChar(i);
char nextvalue = timeString.GetChar(i + 1);
ID2D1Effect* Digit = GetBitmap(value);
if (i == size - 1)
dc->SetTransform(D2D1::Matrix3x2F::Scale(0.7f, 0.7f) * D2D1::Matrix3x2F::Translation(0.0f, GetDigitHeight() * 0.3f) * digittransform * maintransform);
else if (value == 'd')
dc->SetTransform(D2D1::Matrix3x2F::Scale(0.7f, 0.7f) * D2D1::Matrix3x2F::Translation(0.0f, GetDigitHeight() * 0.3f) * digittransform * maintransform);
else
dc->SetTransform(digittransform * maintransform);
digittransform = D2D1::Matrix3x2F::Translation(GetDigitSpacing(value, nextvalue), 0.0f) * digittransform;
if (Digit)
{
dc->DrawImage(Digit);
}
}
}
void SevenSegment::LocalDrawDigits(ID2D1DeviceContext* dc, int timeoffset, D2D1::Matrix3x2F transform)
{
D2D1::Matrix3x2F maintransform = m_Skew * transform;
D2D1::Matrix3x2F digittransform = D2D1::Matrix3x2F::Identity();
D2D1_RECT_F rect = D2D1::RectF(0.0f, 0.0f, GetDigitWidth(), GetDigitHeight());
int hours = (timeoffset / 60) % 12;
if (hours == 0)
hours = 12;
int minutes = timeoffset % 60;
char digits[6] =
{
char((hours / 10) + 48),
char((hours % 10) + 48),
':',
char((minutes / 10) + 48),
char((minutes % 10) + 48),
'0'
};
if (digits[0] == '0')
{
digits[0] = 0;
digittransform = digittransform * D2D1::Matrix3x2F::Translation(-GetDigitWidth() / 2.0f, 0.0f);
}
for (int i = 0; i < 5; i++)
{
ID2D1Effect* Digit = GetBitmap(digits[i]);
dc->SetTransform(digittransform * maintransform);
digittransform = digittransform * D2D1::Matrix3x2F::Translation(GetDigitWidth(), 0.0f);
if (Digit)
{
dc->DrawImage(Digit);
}
}
}
ID2D1Effect* SevenSegment::GetBitmap(char value)
{
switch (value)
{
case '0':
return Bitmaps[0].Get();
case '1':
return Bitmaps[1].Get();
case '2':
return Bitmaps[2].Get();
case '3':
return Bitmaps[3].Get();
case '4':
return Bitmaps[4].Get();
case '5':
return Bitmaps[5].Get();
case '6':
return Bitmaps[6].Get();
case '7':
return Bitmaps[7].Get();
case '8':
return Bitmaps[8].Get();
case '9':
return Bitmaps[9].Get();
case ':':
return Bitmaps[10].Get();
case '.':
return Bitmaps[11].Get();
case 'd':
return Bitmaps[12].Get();
default:
return nullptr;
}
}
float SevenSegment::GetDigitSpacing(char value, char nextvalue)
{
float digitWidth = GetDigitWidth() * 1.1f;
float periodwidth = GetDigitWidth() * 0.75f;
if (value == ':' || value == '.' || nextvalue == ':' || nextvalue == '.')
return periodwidth;
else
return digitWidth;
}
void SevenSegment::RasterizeDigit(ID2D1BitmapRenderTarget* bitmapRT, ID2D1PathGeometry* geometry, BYTE digit, const D2D1::Matrix3x2F& transform, ID2D1SolidColorBrush* fillbrush, ID2D1SolidColorBrush* outlinebrush)
{
const float Offset = m_Length;
const float bigoffset = Offset * 2.0f;
const float outlinewidth = m_Length * 0.25f;
const D2D1::Matrix3x2F transforms[7] =
{
D2D1::Matrix3x2F::Translation(0.0f, -bigoffset),
D2D1::Matrix3x2F::Rotation(90, { 0.0f, 0.0f }) * D2D1::Matrix3x2F::Translation(-Offset, -Offset),
D2D1::Matrix3x2F::Rotation(90, { 0.0f, 0.0f }) * D2D1::Matrix3x2F::Translation(Offset, -Offset),
D2D1::Matrix3x2F::Translation(0.0f, 0.0f),
D2D1::Matrix3x2F::Rotation(90, { 0.0f, 0.0f }) * D2D1::Matrix3x2F::Translation(-Offset, Offset),
D2D1::Matrix3x2F::Rotation(90, { 0.0f, 0.0f }) * D2D1::Matrix3x2F::Translation(Offset, Offset),
D2D1::Matrix3x2F::Translation(0.0f, bigoffset)
};
auto drawsegment = [&] (int segmentindex)
{
bitmapRT->SetTransform(transforms[segmentindex] * transform);
bitmapRT->DrawGeometry(geometry, outlinebrush, outlinewidth);
bitmapRT->FillGeometry(geometry, fillbrush);
};
float dotradius = m_Width;
switch (digit)
{
case 10: // colon
{
D2D1_ELLIPSE ellipse = { {0.0f, -m_Length}, dotradius, dotradius };
bitmapRT->SetTransform(transform);
bitmapRT->DrawEllipse(ellipse, outlinebrush, outlinewidth);
bitmapRT->FillEllipse(ellipse, fillbrush);
ellipse = { {0.0f, m_Length}, dotradius, dotradius };
bitmapRT->DrawEllipse(ellipse, outlinebrush, outlinewidth);
bitmapRT->FillEllipse(ellipse, fillbrush);
break;
}
case 11: // dot
{
D2D1_ELLIPSE ellipse = { {0.0f, m_Length * 2.0f}, dotradius, dotradius };
bitmapRT->SetTransform(transform);
bitmapRT->DrawEllipse(ellipse, outlinebrush, outlinewidth);
bitmapRT->FillEllipse(ellipse, fillbrush);
break;
}
case 12: // 'd'
drawsegment(2);
drawsegment(3);
drawsegment(4);
drawsegment(5);
drawsegment(6);
break;
case 0:
drawsegment(0);
drawsegment(1);
drawsegment(2);
drawsegment(4);
drawsegment(5);
drawsegment(6);
break;
case 1:
drawsegment(2);
drawsegment(5);
break;
case 2:
drawsegment(0);
drawsegment(2);
drawsegment(3);
drawsegment(4);
drawsegment(6);
break;
case 3:
drawsegment(0);
drawsegment(2);
drawsegment(3);
drawsegment(5);
drawsegment(6);
break;
case 4:
drawsegment(1);
drawsegment(2);
drawsegment(3);
drawsegment(5);
break;
case 5:
drawsegment(0);
drawsegment(1);
drawsegment(3);
drawsegment(5);
drawsegment(6);
break;
case 6:
drawsegment(0);
drawsegment(1);
drawsegment(3);
drawsegment(4);
drawsegment(5);
drawsegment(6);
break;
case 7:
drawsegment(0);
drawsegment(2);
drawsegment(5);
break;
case 8:
drawsegment(0);
drawsegment(1);
drawsegment(2);
drawsegment(3);
drawsegment(4);
drawsegment(5);
drawsegment(6);
break;
case 9:
drawsegment(0);
drawsegment(1);
drawsegment(2);
drawsegment(3);
drawsegment(5);
drawsegment(6);
break;
}
}
|
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gestione Drink</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-image: url('https://as1.ftcdn.net/v2/jpg/01/58/23/40/1000_F_158234051_x1Mw49rCAUBEgiTQXmagMYx14k4mdpXR.jpg');
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.overlay {
background-color: rgba(255, 255, 255, 0.8); /* Sfondo del contenitore con trasparenza */
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); /* Effetto ombra */
}
.container {
max-width: 600px;
margin: 50px auto;
text-align: center;
}
button {
margin: 5px;
padding: 10px 20px;
background-color: #007bff;
color: #fff;
border: none;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #0056b3;
}
ul {
list-style-type: none;
padding: 0;
}
li {
margin-bottom: 10px;
}
.fixed-drinks {
font-style: italic;
color: #888;
}
</style>
</head>
<body>
<div class="overlay">
<div class="container">
<h1>Gestione Drink</h1>
<button id="btnConta">Conta Elementi</button>
<button id="btnAdd">Add</button>
<button id="btnDelete">Delete</button>
<button id="btnBuy">Buy</button>
<h2>Lista Drink</h2>
<ul id="listaDrink">
<!-- Qui verranno aggiunti dinamicamente gli elementi -->
</ul>
<p class="fixed-drinks">Specialità del posto :</p>
<ul class="fixed-drinks" id="fixedDrinkList">
<!-- Qui verranno aggiunti dinamicamente gli elementi non modificabili -->
</ul>
</div>
</div>
<script>
const drinkListFixed = ['Vino', 'Birra', 'Coca-Cola'];
const drinkList = ['Caffè', 'Te', 'Succhi', 'Acqua'];
let orderList = [];
// Funzione per mostrare la lista dei drink
function mostraLista() {
const listaDrinkElement = document.getElementById('listaDrink');
listaDrinkElement.innerHTML = ''; // Resetta la lista
drinkList.forEach((drink, index) => {
const li = document.createElement('li');
li.textContent = `${index + 1}. ${drink}`;
listaDrinkElement.appendChild(li);
});
const fixedDrinkListElement = document.getElementById('fixedDrinkList');
fixedDrinkListElement.innerHTML = ''; // Resetta la lista
drinkListFixed.forEach((drink, index) => {
const li = document.createElement('li');
li.textContent = `${index + 1}. ${drink}`;
fixedDrinkListElement.appendChild(li);
});
}
// Event listener per il bottone Conta Elementi
document.getElementById('btnConta').addEventListener('click', () => {
alert(`Numero di drink: ${drinkList.length}`);
});
// Event listener per il bottone Add
document.getElementById('btnAdd').addEventListener('click', () => {
const newDrink = prompt('Inserisci il nuovo drink:');
if (newDrink) {
drinkList.push(newDrink.trim());
mostraLista();
}
});
// Event listener per il bottone Delete
document.getElementById('btnDelete').addEventListener('click', () => {
const indexToRemove = prompt('Inserisci l\'indice del drink da eliminare:');
if (indexToRemove && !isNaN(indexToRemove)) {
const index = parseInt(indexToRemove) - 1;
if (index >= 0 && index < drinkList.length) {
drinkList.splice(index, 1);
mostraLista();
} else {
alert('Indice non valido.');
}
} else {
alert('Inserisci un numero valido.');
}
});
// Event listener per il bottone Buy
document.getElementById('btnBuy').addEventListener('click', () => {
orderList = []; // Resetta la lista degli ordini
while (true) {
const order = prompt('Inserisci il numero del drink che desideri acquistare (0 per terminare):');
if (order === null || order === '' || isNaN(order)) {
alert('Inserisci un numero valido.');
} else {
const orderNum = parseInt(order);
if (orderNum === 0) {
break;
} else if (orderNum >= 1 && orderNum <= drinkList.length) {
orderList.push(orderNum);
} else {
alert('Numero del drink non valido.');
}
}
}
// Ordina la lista degli ordini in ordine crescente
orderList.sort((a, b) => a - b);
mostraListaOrdinata();
});
// Funzione per mostrare la lista dei drink ordinata
function mostraListaOrdinata() {
const listaDrinkElement = document.getElementById('listaDrink');
listaDrinkElement.innerHTML = ''; // Resetta la lista
orderList.forEach((order, index) => {
const drinkIndex = order - 1;
if (drinkIndex >= 0 && drinkIndex < drinkList.length) {
const li = document.createElement('li');
li.textContent = `${index + 1}. ${drinkList[drinkIndex]}`;
listaDrinkElement.appendChild(li);
}
});
}
// Inizializza la lista dei drink al caricamento della pagina
mostraLista();
</script>
</body>
</html>
|
// /************* ECE312 Project 2 Milestone 2 *******************/
// By: Ben McDaniel and Jacob Teaney
// Our approach to this code is to establish the 4 messages as character
// arrays storing octets as two hex digits. We then send these using the
// bind and sendto example code provided in the example. Our received
// message is decoded using a combination of bitwise operations, including
// shifting and using targeted bitwise ands to extract bits based on the
// given protocol
// /************* ECE312 Project 2 Milestone 2 *******************/
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>
#define SERVER "137.112.38.47"
#define PORT 2324
#define BUFSIZE 1024
uint16_t fixed_checksum(char* buffer, int nBytes);
void displayMessage(char* buffer, int nBytes);
void printPayload(char* buffer, int length);
char* getNextMessage();
void messageSendSuccess();
void printPayloadRHMP(char* buffer, int length);
int messageCount = 1;
int main() {
int clientSocket, nBytes;
char buffer[BUFSIZE];
struct sockaddr_in clientAddr, serverAddr;
/*Create UDP socket*/
if ((clientSocket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("cannot create socket");
return 0;
}
/* Bind to an arbitrary return address.
* Because this is the client side, we don't care about the address
* since no application will initiate communication here - it will
* just send responses
* INADDR_ANY is the IP address and 0 is the port (allow OS to select port)
* htonl converts a long integer (e.g. address) to a network representation
* htons converts a short integer (e.g. port) to a network representation */
memset((char *) &clientAddr, 0, sizeof (clientAddr));
clientAddr.sin_family = AF_INET;
clientAddr.sin_addr.s_addr = htonl(INADDR_ANY);
clientAddr.sin_port = htons(0);
if (bind(clientSocket, (struct sockaddr *) &clientAddr, sizeof (clientAddr)) < 0) {
perror("bind failed");
return 0;
}
/* Configure settings in server address struct */
memset((char*) &serverAddr, 0, sizeof (serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr(SERVER);
memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
//only send 4 requests
if(messageCount > 4){
exit(0);
}
uint8_t msg1[] = {0x09, 0xA8, 0x00, 0x05, 0x68, 0x65, 0x6C, 0x6C, 0x6F, 0x00, 0xB2, 0x80};
uint8_t msg2[] = {0x09, 0xA8, 0x00, 0x02, 0x68, 0x69, 0x8D, 0xEC};
uint8_t msg3[] = {0x09, 0x74, 0x18, 0x84, 0x12, 0x63, 0x07, 0x18, 0xC4, 0x8C}; //In RHMP, instead of [a, b, c, d, e, f, g, h], does [b, c, f, a, d, e, g, h].
uint8_t msg4[] = {0x09, 0x74, 0x18, 0x84, 0x12, 0x63, 0x07, 0x03, 0xC4, 0xA1};
//iterate through messages with each main call
if(messageCount == 1){
printf("Sending RHP Message: hello\n");
if (sendto(clientSocket, msg1, sizeof(msg1), 0,
(struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0) {
perror("sendto failed");
return 0;
}
/* Receive message from server */
nBytes = recvfrom(clientSocket, buffer, BUFSIZE, 0, NULL, NULL);
displayMessage(buffer, nBytes);
}else if(messageCount == 2){
printf("Sending RHP Message: hi\n");
if (sendto(clientSocket, msg2, sizeof(msg2), 0,
(struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0) {
perror("sendto failed");
return 0;
}
/* Receive message from server */
nBytes = recvfrom(clientSocket, buffer, BUFSIZE, 0, NULL, NULL);
displayMessage(buffer, nBytes);
}else if(messageCount == 3){
printf("Sending RHMP Message of type: Message_Request\n");
if (sendto(clientSocket, msg3, sizeof(msg3), 0,
(struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0) {
perror("sendto failed");
return 0;
}
/* Receive message from server */
nBytes = recvfrom(clientSocket, buffer, BUFSIZE, 0, NULL, NULL);
displayMessage(buffer, nBytes);
}else{
printf("Sending RHMP Message of type: ID_Request\n");
if (sendto(clientSocket, msg4, sizeof(msg4), 0,
(struct sockaddr *) &serverAddr, sizeof (serverAddr)) < 0) {
perror("sendto failed");
return 0;
}
/* Receive message from server */
nBytes = recvfrom(clientSocket, buffer, BUFSIZE, 0, NULL, NULL);
displayMessage(buffer, nBytes);
}
close(clientSocket);
return 0;
}
/*
* Used to increment the total number of messages successfully sent
*/
void messageSendSuccess(){
messageCount += 1;
}
/*
* Handles parsong through the given message and displaying all of the information about it.
* Will display all of the relevent information for the message such as the payload, RHP Version,
* commID, among other things.
*/
void displayMessage(char* buffer, int nBytes){
printf("Message Recieved\n");
printf(" RHP Version: %d\n",buffer[0]);
uint16_t commID = (uint8_t)buffer[2]<<8;
commID += (uint8_t)buffer[1];
printf(" commID: %u\n",commID);
uint8_t length = (uint8_t)buffer[3]&0b01111111;
printf(" Length: %d\n", length);
uint8_t type = (uint8_t)buffer[3]&0b10000000;
if(type != 0) {
type = 1;
}
printf(" Type: %d\n",type);
if(type == 0){
//RHP message
printPayload(buffer, length);
}else{
//RHMP message
printPayloadRHMP(buffer, length);
}
uint16_t messageChecksum = (uint16_t)buffer[nBytes-2]<<8;
messageChecksum += (uint8_t)buffer[nBytes-1];
printf(" Message Checksum: %d\n", messageChecksum);
uint16_t checksum = fixed_checksum(buffer, nBytes);
printf(" Calculated Checksum: %d", checksum);
if(checksum != messageChecksum){
printf("Checksum Failed, resending message\n\n");
}else{
messageSendSuccess();
}
main();
}
/*
* Given a received RHP message, this function will parse thorugh it and print the payload contained within it.
* It is assumed that this payload is not a RHMP, and rather a string.
*/
void printPayload(char* buffer, int length){
//known that message starts on buffer[4]
printf(" Payload: ");
for(int i = 0; i < length; i++){
printf("%c", buffer[4+i]);
}
printf("\n");
}
/*
* Given that a RHMP message is received, this function, given a char[<Hex Octets>] and the size of said message, will parse through the
* message, formating the received data into more legible data, and printing this out in a reasonable and readable way.
*/
void printPayloadRHMP(char* buffer, int length){
//know that the payload starts on buffer[4]
printf(" RHMP Protocol:\n");
int dstPort = (buffer[4]<<4) + (buffer[5]>>4);
printf(" dstPort: %d\n", dstPort);
int srcPort = ((buffer[5]&0b00001111)<<4) + (buffer[6]);
printf(" srcPort: %d\n", srcPort);
uint8_t type = (uint8_t)buffer[7];
printf(" RHMP Type: %d\n", type);
printf(" Payload: \n");
if(type == 40) { //Priting a text response
printf("Received Text:");
for(int i = 9; i < length+4; i+=2){
printf("%c%c", (uint8_t)buffer[i],(uint8_t)buffer[i+1]);
}
printf("\n");
} else if(type == 5) { //Printing the ID (in hex and decimal)
uint32_t Id = (uint8_t)buffer[8]<<0;
Id += (uint8_t)buffer[9]<<8;
Id += (uint8_t)buffer[10]<<16;
Id += (uint8_t)buffer[11]<<24;
printf(" Received ID (Dec): %u\n", Id); //Should be divisible by our ID numbers (or the one attached with the message sent)
printf(" Received ID (Hex): 0x%x\n", Id);
}
}
/*
* Returns the internet checksum for the given message
*/
uint16_t fixed_checksum(char* buffer, int nBytes){
uint16_t sum = 0;
uint16_t pastSum = 0;
for(int i = 0; i < nBytes-2; i+=2){
sum += (uint8_t)buffer[i]<<8;
sum += (uint8_t)buffer[i+1];
if(sum < pastSum){
sum += 1;
}
pastSum = sum;
}
sum = ~(uint16_t)sum;
return sum;
}
|
from rest_framework import serializers
from post.models import Post,Comment
from user_management.serializers import ProfileSerializer
from django.utils.timesince import timesince
class CommentSerializer(serializers.ModelSerializer):
user = ProfileSerializer()
likes = ProfileSerializer(many=True)
class Meta:
model = Comment
fields=['id','user','likes','content',"edited"]
class PostSerializer(serializers.ModelSerializer):
user = ProfileSerializer()
likes = ProfileSerializer(many=True)
comments = serializers.SerializerMethodField()
humanized_created_at = serializers.SerializerMethodField()
humanized_shared_at = serializers.SerializerMethodField()
is_image = serializers.SerializerMethodField()
shared_by = ProfileSerializer()
def get_is_image(self,obj):
return obj.is_image()
def get_humanized_created_at(self,obj):
return timesince(obj.created_at)
def get_humanized_shared_at(self,obj):
return timesince(obj.shared_at) if obj.shared_at else None
class Meta:
model = Post
fields = [
'id',
'user',
"content",
"likes",
"comments",
"media_file",
"humanized_created_at",
"is_image",
"privacy",
"humanized_shared_at",
"shared",
"shared_by",
"original_post_id"
]
def get_comments(self, obj):
comments = Comment.objects.filter(post=obj)
serializer = CommentSerializer(comments, many=True)
return serializer.data
|
//Factory function that can return handlers functions
exports.deleteOne = (Model) => async (req, res, next) => {
try {
const document = await Model.findByIdAndDelete(req.params.id);
if (!document) {
return next("No document found with that ID");
}
res.status(204).json({
status: "Success",
data: null,
});
} catch (err) {
res.status(404).json({
status: "Faild",
massage: err,
});
}
};
exports.createOne = (Model) => async (req, res, next) => {
try {
const document = await Model.create(req.body);
if (!document) {
return next("No document found with that ID");
}
res.status(201).json({
status: "Success",
data: { document },
});
} catch (err) {
res.status(404).json({
status: "Faild",
message: err,
});
}
};
exports.updateOne = (Model) => async (req, res, next) => {
try {
const document = await Model.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true,
});
if (!document) {
return next("No document found with that ID");
}
res.status(201).json({
status: "Success",
data: { document },
});
} catch (err) {
res.status(404).json({
status: "Faild",
message: err,
});
}
};
exports.getOne = (Model) => async (req, res, next) => {
try{
const document = await Model.findById(req.params.id);
if(!document){
return next("No document found with that ID");
}
res.status(201).json({
status: "Success",
data: { document },
});
}catch(err){
res.status(404).json({
status: "Faild",
message: err,
});
}
};
exports.getAll = (Model) => async (req, res, next) => {
try {
//Build Query
//1-Filtering
const queryObj = { ...req.query }; //Shallow Copy
const excludedFields = ["page", "sort", "limit", "fields"];
excludedFields.forEach((e) => delete queryObj[e]);
// console.log(req.query, queryObj );
//2-Filtering Mongo (convert obj to str to make functions on it)
//{rating: {gte: "3"}} => {rating: {$gte: 3}} (gte, gt, lte, lt)
let queryStr = JSON.stringify(queryObj);
queryStr = queryStr.replace(/\b(gte|gt|lte|lt)\b/g, (match) => `$${match}`);
console.log(JSON.parse(queryStr));
console.log(req.query, queryObj);
// const query = Model.find(queryObj);
let query = Model.find(JSON.parse(queryStr)); //Return query so I can chain other methods
// 2- Sorting
if(req.query.sort){
query = query.sort(req.query.sort);
}else{
query = query.sort('-createdAt');
}
// 3- Pagination
//page=2&limit=10, 1-10(page1), 11-20(page2), 21-30(page3)
//*1 => convert str to num, || 1 => page number1
const page = req.query.page * 1 || 1;
const limit = req.query.limit * 1 || 40;
const skip = (page - 1) * limit;
query = query.skip(skip).limit(limit);
if(req.query.page){
const numbers = await Model.countDocuments();
if(skip >= numbers){
throw new Error('This Page Is Not Exist!')
}
}
const documents = await query;
if (!documents) {
return next("No document found with that ID");
}
res.status(201).json({
status: "Success",
results: documents.length,
data: {documents} ,
});
} catch (err) {
res.status(404).json({
status: "Faild",
message: 'This Page Is Not Exist!',
});
}
};
|
---
title: 'Unlock Your Potential: Overcoming Tech Fears for Online Coaches'
description: 'Addressing the common fears and misconceptions about technology in online coaching and empowering coaches to embrace digital tools to unlock their full potential.'
date: '2023-07-08'
tags: online coaching, tech fears, digital tools
imageUrl: 'https://unsplash.com/photos/KE0nC8-58MQ/download?force=true'
---
## Introduction
In the age of digitalization, technology has seeped into every aspect of our lives, transforming the way we live, work, and communicate. It's revolutionized numerous industries, making operations more efficient, improving customer experiences, and opening up a world of possibilities that were once unimaginable. Yet, when it comes to online coaching, a certain reluctance to fully embrace this digital revolution is palpable amongst many coaches. Fear, confusion, and a host of misconceptions often overshadow the potential benefits that could revolutionize their practice. If this resonates with you, you're not alone.
## Understanding the Fear
Three major fears commonly surface when coaches confront the idea of integrating technology into their practice.
1. **Loss of Human Connection**: Many worry about losing the 'human touch' that forms the backbone of their coaching practice. They fear that technology will render their interactions impersonal and robotic.
2. **Technological Complexity**: For those not particularly tech-savvy, technology, with all its complexity, can seem overwhelming. The fear of not being able to understand or effectively use these tools can be a significant deterrent.
3. **Data Security**: In a world where data breaches are increasingly common, concerns about data security can be a major hurdle to embracing technology.
## Busting the Myths
These fears, while valid, often stem from misconceptions. Let's unpack the reality of each:
1. **Enhanced Personalization**: Contrary to the fear of losing personal touch, technology actually enhances the personalization of your coaching. Modern coaching tools offer features like customizable programs, personalized communication options, and even AI-powered insights that enable you to tailor your coaching to a degree not possible without them.
2. **User-friendly Design**: Most tech tools are designed to be user-friendly, with interfaces that are intuitive and easy-to-navigate. Plenty of resources, from tutorials to customer support, are available to help users get acquainted with these tools.
3. **Data Protection Measures**: As for data security, adopting the right practices and tools can ensure your and your clients' data remains protected. Most reputable tech solutions come with stringent security protocols to protect user data.
## Tangible Benefits of Tech Adoption
The benefits of embracing technology in coaching are far-reaching.
1. **Increased Efficiency**: By automating administrative tasks such as scheduling, invoicing, and record-keeping, you can serve more clients without increasing your workload.
2. **Improved Client Experience**: With seamless scheduling, easy payment options, and efficient communication channels, clients enjoy a smooth, professional coaching experience.
3. **More Time for Coaching**: Perhaps most importantly, technology frees up your time, enabling you to focus on what you do best - coaching, without getting bogged down by administrative tasks.
## Overcoming the Fear: A Gradual Approach
Getting started with technology may seem daunting, but it doesn't have to be. Begin by researching different tools that could benefit your practice and select one to start with. Take your time to learn how it works and gradually integrate it into your routine. There's no rush or right way to do this, so move at a pace that feels comfortable for you. Reach out to peers who have successfully used technology in their coaching for advice and support.
## Conclusion
Embracing technology is not as scary as it seems. The initial effort to integrate it into your coaching practice will pay dividends in the long run, in terms of increased efficiency, better client experiences, and more time for you to focus on coaching. So take that first step and unlock your full potential as an online coach. Remember, every expert was once a beginner. You've got this!
|
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
<script th:src="@{/js/code.jquery.com_jquery-3.7.0.min.js}"></script>
<script th:src="@{/js/bootstrap.min.js}"></script>
<title>Редактирование объявления</title>
</head>
<body>
<div class="container-fluid p-0">
<header th:insert="blocks/header :: header"></header>
<div class="container">
<form class="mt-3" th:action="@{/posts/update}" method="post" enctype="multipart/form-data">
<input type="hidden" id="postId" name="id" th:value="${post.id}">
<input type="hidden" id="carId" name="car.id" th:value="${post.car.id}">
<input type="hidden" id="priceBefore" name="priceBefore" th:value="${priceBefore}">
<div class="mb-3">
<label for="car" class="form-label"><b>Марка</b></label>
<input type="text" class="form-control" id="car" name="car.name" th:value="${post.car.name}"
placeholder="Введите название автомобиля" required>
</div>
<div class="mb-3">
<label for="engine"><b>Двигатель</b></label>
<select class="form-control" id="engine" name="car.engine.id">
<option th:each="engine : ${engines}"
th:value="${engine.id}" th:text="${engine.name}"
th:selected="${engine == post.car.engine}">
</option>
</select>
</div>
<div class="mb-3">
<label for="gear"><b>Коробка</b></label>
<select class="form-control" id="gear" name="car.gear" >
<option th:each="gear : ${T(ru.job4j.cars.model.Gear).values()}"
th:value="${gear}" th:text="${gear.getName}"
th:selected="${gear == post.car.gear}">
</option>
</select>
</div>
<div class="mb-3">
<label for="year"><b>Год выпуска</b></label>
<select class="form-control" id="year" name="car.yearMade" >
<option th:each="year : ${#numbers.sequence(1900, #dates.year(#dates.createNow()))}"
th:value="${year}" th:text="${year}"
th:selected="${year == post.car.yearMade}">
</option>
</select>
</div>
<div class="mb-3">
<label for="mileage" class="form-label"><b>Пробег</b></label>
<input type="text" class="form-control" id="mileage" name="car.mileage" th:value="${post.car.mileage}"
placeholder="Введите пробег, км" required>
</div>
<div class="mb-3">
<label for="price" class="form-label"><b>Цена</b></label>
<input type="number" class="form-control" id="price" name="priceAfter"
th:value="${priceBefore}"
placeholder="Введите цену" required>
</div>
<div class="mb-3" th:each="photo : ${photos}">
<img th:src="@{/files/{fileId}(fileId=${photo.id})}" class="w-50" alt="No image">
<input type="checkbox" name="deletePhotos" th:value="${photo.id}"/> Удалить фото
</div>
<div class="mb-3">
<label for="formFile"><b>Добавьте несколько фотографий</b></label>
<input class="form-control form-control-sm w-100" type="file" id="formFile" name="files" multiple>
</div>
<div class="mb-3">
<b>Статус объявления</b><br>
<input type="checkbox" name="sold" th:checked="${post.sold}"/> Продано
</div>
<div class="mb-3">
<label for="description" class="form-label"><b>Описание</b></label>
<textarea class="form-control" id="description" name="description" rows="8"
placeholder="Комментарии продавца" required th:text="${post.description}"></textarea>
</div>
<div class="mb-3 row">
<div class="col-6"></div>
<div class="col-6">
<div class="row">
<div class="col-6"><a class="btn btn-danger w-100" th:href="@{/posts/{id}(id=${post.id})}">Отмена</a>
</div>
<div class="col-6">
<button class="btn btn-primary w-100" type="submit">Сохранить</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../static/css/bootstrap.css" th:href="@{/css/bootstrap.css}">
<title>Register</title>
</head>
<body>
<div class="container" style="max-width:600px;margin-top: 50px">
<h1 class="page-header">Register page</h1>
<div class="well">
<form action="/register" method="post" th:object="${userForm}">
<div class="form-group">
<label for="nameId">UserName</label>
<input type="text" name="name" id="nameId" class="form-control" th:field="*{name}">
<p class="form-control-static text-danger" th:if="${#fields.hasErrors('name')}" th:errors="*{name}">can not empty</p>
</div>
<div class="form-group">
<label for="passwordId">Password</label>
<input type="text" name="password" id="passwordId" class="form-control" th:field="*{password}">
<p class="form-control-static text-danger" th:if="${#fields.hasErrors('password')}" th:errors="*{password}">can not empty</p>
</div>
<div class="form-group">
<label for="emailId">E-mail</label>
<input type="text" name="email" id="emailId" class="form-control" th:fiels="*{email}">
<p class="form-control-static text-danger" th:if="${#fields.hasErrors('email')}" th:errors="*{email}">can not empty</p>
</div>
<p>
<button type="submit" class="btn btn-primary">Submit</button>
</p>
</form>
</div>
</div>
<script src="../static/js/jquery-3.5.0.min.js" th:src="@{/js/jquery-3.5.0.min.js}"></script>
<script src="../static/js/bootstrap.js" th:src="@{/js/bootstrap.js}"></script>
</body>
</html>
|
import React from 'react'
import { addOns } from '../constants/constants'
const AddOnCards = ({ isMonthly,selectedAddOns, handleAddOnSelect}) => {
return (
<div className='mt-8 flex flex-col gap-4 w-full'>
{addOns.map((addOn) => (
<div
key={addOn.id}
className={`p-6 flex justify-between transition-all duration-500 items-center rounded-lg cursor-pointer border hover:scale-105 ${
selectedAddOns.includes(addOn)
? 'bg-[#f3f3ff] border-[#473dff] scale-105'
: 'border-[#d3d3d3]'
}`}
onClick={() => handleAddOnSelect(addOn)}
>
<div className='flex gap-6 items-center'>
<input
type='checkbox'
className={`w-4 h-4 border rounded ${
selectedAddOns.includes(addOn)
? 'bg-[#01386a] border-[#01386a]'
: 'border-white'
}`}
checked={selectedAddOns.includes(addOn)}
readOnly
/>
<div className='flex flex-col'>
<h1 className='text-sm font-bold'>{addOn.name}</h1>
<h1 className='text-[#828282] text-xs'>
{addOn.description}
</h1>
</div>
</div>
<h1 className='text-xs text-[#473dff] font-medium'>
+${isMonthly ? addOn.price : addOn.price * 10}/
{isMonthly ? 'mo' : 'yr'}
</h1>
</div>
))}
</div>
)
}
export default AddOnCards
|
import {
faEdit,
faPaperclip,
faTrash,
} from "@fortawesome/free-solid-svg-icons";
import React, { useCallback, useEffect, useMemo } from "react";
import styled from "styled-components";
import {
getFullPath,
getNoteById,
getNoteByPath,
getParents,
} from "../../shared/domain/note";
import { p2, rounded, THEME } from "../css";
import { Listener, Store, StoreContext } from "../store";
import { Icon } from "./shared/Icon";
import { clamp, orderBy, uniq, uniqBy } from "lodash";
import { ClosedEditorTab, Section } from "../../shared/ui/app";
import { Scrollable } from "./shared/Scrollable";
import { Focusable } from "./shared/Focusable";
import { arrayify } from "../../shared/utils";
import { isProtocolUrl } from "../../shared/domain/protocols";
import OpenColor from "open-color";
import { deleteNoteIfConfirmed } from "../utils/deleteNoteIfConfirmed";
import { EditorSpacer, EditorTab, TabDrag } from "./EditorTab";
import { MouseButton } from "../io/mouse";
export const TOOLBAR_HEIGHT = "4.3rem"; // 4.2rem + 1px for border
export interface EditorToolbarProps {
store: Store;
}
export function EditorToolbar(props: EditorToolbarProps): JSX.Element {
const { store } = props;
const { state } = store;
const { notes, editor } = state;
const tabs = useMemo(() => {
const rendered = [];
const { activeTabNoteId } = editor;
const onClick = async (noteId: string) => {
await store.dispatch("editor.openTab", { note: noteId, active: noteId });
};
const onClose = async (noteId: string) => {
await store.dispatch("editor.closeTab", noteId);
};
const onUnpin = async (noteId: string) => {
await store.dispatch("editor.unpinTab", noteId);
};
const onDrag = async (noteId: string, drag: TabDrag) => {
const tab = editor.tabs.find(t => t.note.id === noteId);
if (tab == null) {
throw new Error(`No tab for note ID: ${noteId} found.`);
}
let newIndex: number;
// Validating where we'll move the note to based on if it's pinned or not
// will be handled in the store listener so we can disregard if a note is
// pinned or not here.
switch (drag.type) {
case "absolute":
switch (drag.side) {
case "left":
newIndex = 0;
break;
case "right":
newIndex = editor.tabs.length - 1;
break;
}
break;
case "relative": {
const targetIndex = editor.tabs.findIndex(
t => t.note.id === drag.noteId,
);
if (targetIndex === -1) {
throw new Error(`No target tab for note ID: ${noteId} found.`);
}
newIndex = targetIndex;
break;
}
}
await store.dispatch("editor.moveTab", { noteId, newIndex });
};
// Put pinned tabs note first
for (const tab of editor.tabs) {
const note = getNoteById(notes, tab.note.id);
const notePath = getFullPath(notes, note);
rendered.push(
<EditorTab
key={note.id}
noteId={note.id}
noteName={note.name}
notePath={notePath}
active={activeTabNoteId === note.id}
isPinned={tab.isPinned}
isPreview={tab.isPreview}
onClick={onClick}
onClose={onClose}
onUnpin={onUnpin}
onDrag={onDrag}
/>,
);
}
return rendered;
}, [notes, editor, store]);
const [previousTab, nextTab] = useMemo(() => {
// Don't bother allowing switching tabs if there's no active tab, or there's
// only 1 tab currently active since it'd be a no-op.
if (editor.activeTabNoteId == null || editor.tabs.length <= 1) {
return [null, null];
}
const tabsByLastActive = orderBy(editor.tabs, ["lastActive"], ["desc"]);
const currentIndex = tabsByLastActive.findIndex(
t => t.note.id === editor.activeTabNoteId,
);
let previousIndex = (currentIndex - 1) % tabsByLastActive.length;
// Need to wrap it around
if (previousIndex < 0) {
previousIndex = tabsByLastActive.length + previousIndex;
}
const nextIndex = Math.abs((currentIndex + 1) % tabsByLastActive.length);
return [tabsByLastActive[previousIndex], tabsByLastActive[nextIndex]];
}, [editor.tabs, editor.activeTabNoteId]);
const switchToNextTab: Listener<"editor.nextTab"> = useCallback(
(_, ctx) => {
if (nextTab == null) {
return;
}
setActiveTab(ctx, nextTab.note.id);
},
[nextTab],
);
const switchToPreviousTab: Listener<"editor.previousTab"> = useCallback(
(_, ctx) => {
if (previousTab == null) {
return;
}
setActiveTab(ctx, previousTab.note.id);
},
[previousTab],
);
const closeTab: Listener<
| "editor.closeActiveTab"
| "editor.closeTab"
| "editor.closeAllTabs"
| "editor.closeOtherTabs"
| "editor.closeTabsToLeft"
| "editor.closeTabsToRight"
> = async ({ type, value }, ctx) => {
const { editor } = ctx.getState();
if (editor.activeTabNoteId == null || editor.tabs.length === 0) {
return;
}
let noteIdsToClose: string[] = [];
switch (type) {
case "editor.closeActiveTab":
noteIdsToClose = [editor.activeTabNoteId];
break;
case "editor.closeTab":
if (value == null) {
return;
}
noteIdsToClose = [value];
break;
case "editor.closeAllTabs":
noteIdsToClose = editor.tabs
.filter(t => !t.isPinned)
.map(t => t.note.id);
break;
case "editor.closeOtherTabs":
noteIdsToClose = editor.tabs
.filter(
t => !t.isPinned && t.note.id !== (value ?? editor.activeTabNoteId),
)
.map(t => t.note.id);
break;
case "editor.closeTabsToLeft": {
const start = editor.tabs.findIndex(t => !t.isPinned);
const end = editor.tabs.findIndex(
t => t.note.id === (value ?? editor.activeTabNoteId),
);
noteIdsToClose = editor.tabs.slice(start, end).map(t => t.note.id);
break;
}
case "editor.closeTabsToRight": {
const firstNonPinnedIndex = editor.tabs.findIndex(t => !t.isPinned);
const activeTabIndex = editor.tabs.findIndex(
t => t.note.id === (value ?? editor.activeTabNoteId),
);
const end = Math.max(firstNonPinnedIndex, activeTabIndex + 1);
noteIdsToClose = editor.tabs.slice(end).map(t => t.note.id);
break;
}
default:
throw new Error(`Invalid action ${value}`);
}
ctx.setCache(prev => {
const newlyClosedTabs: ClosedEditorTab[] = noteIdsToClose.map(noteId => {
const previousIndex = editor.tabs.findIndex(t => t.note.id === noteId);
return {
noteId,
previousIndex,
isPreview: editor.tabs[previousIndex].isPreview,
};
});
const closedTabs = [...newlyClosedTabs, ...prev.closedTabs];
// Each tab can only be opened once so we remove duplicates to ensure we
// don't let the user try to re-open a tab that's already been re-opened.
const deduplicatedClosedTabs = uniqBy(closedTabs, t => t.noteId);
return {
closedTabs: deduplicatedClosedTabs,
};
});
ctx.setUI(prev => {
const tabs = prev.editor.tabs.filter(
t => !noteIdsToClose.includes(t.note.id),
);
let activeTabNoteId: string | undefined;
switch (type) {
case "editor.closeAllTabs":
activeTabNoteId = undefined;
break;
case "editor.closeTab":
case "editor.closeActiveTab": {
const [tabsByLastActive] = orderBy(tabs, ["lastActive"], ["desc"]);
activeTabNoteId = tabsByLastActive?.note.id;
break;
}
default:
activeTabNoteId = prev.editor.activeTabNoteId;
}
let isEditing = prev.editor.isEditing;
if (tabs.length === 0) {
isEditing = false;
}
return {
...prev,
editor: {
activeTabNoteId,
tabs,
isEditing,
},
};
});
};
const openAttachments = useCallback(async () => {
const { activeTabNoteId } = store.state.editor;
if (activeTabNoteId == null) {
return;
}
await store.dispatch("app.openNoteAttachments", activeTabNoteId);
}, [store]);
const onMouseUp = useCallback(
async (ev: MouseEvent) => {
switch (ev.button) {
case MouseButton.Forward:
await store.dispatch("editor.previousTab");
break;
case MouseButton.Back:
await store.dispatch("editor.nextTab");
break;
}
},
[store],
);
useEffect(() => {
store.on("editor.openTab", openTab);
store.on("editor.reopenClosedTab", reopenClosedTab);
store.on(
[
"editor.closeActiveTab",
"editor.closeTab",
"editor.closeAllTabs",
"editor.closeOtherTabs",
"editor.closeTabsToLeft",
"editor.closeTabsToRight",
],
closeTab,
);
store.on("editor.nextTab", switchToNextTab);
store.on("editor.previousTab", switchToPreviousTab);
store.on("editor.updateTabsScroll", updateTabsScroll);
store.on("editor.deleteNote", deleteNote);
store.on("editor.pinTab", pinTab);
store.on("editor.unpinTab", unpinTab);
store.on("editor.moveTab", moveTab);
store.on("editor.revealTabNoteInSidebar", revealTabNoteInSidebar);
window.addEventListener("mouseup", onMouseUp);
return () => {
store.off("editor.openTab", openTab);
store.off("editor.reopenClosedTab", reopenClosedTab);
store.off(
[
"editor.closeActiveTab",
"editor.closeTab",
"editor.closeAllTabs",
"editor.closeOtherTabs",
"editor.closeTabsToLeft",
"editor.closeTabsToRight",
],
closeTab,
);
store.off("editor.nextTab", switchToNextTab);
store.off("editor.previousTab", switchToPreviousTab);
store.off("editor.updateTabsScroll", updateTabsScroll);
store.off("editor.deleteNote", deleteNote);
store.off("editor.pinTab", pinTab);
store.off("editor.unpinTab", unpinTab);
store.off("editor.moveTab", moveTab);
store.off("editor.revealTabNoteInSidebar", revealTabNoteInSidebar);
window.removeEventListener("mouseup", onMouseUp);
};
}, [store, switchToNextTab, switchToPreviousTab, onMouseUp]);
return (
<EditorToolbarFocusable section={Section.EditorToolbar} store={store}>
<LeftSpacer side="left">
<ToolbarButton
title="Toggle edit/view mode"
onClick={async () => await store.dispatch("editor.toggleView")}
highlighted={store.state.editor.isEditing}
>
<Icon icon={faEdit} />
</ToolbarButton>
<ToolbarButton title="Open attachments" onClick={openAttachments}>
<Icon icon={faPaperclip} />
</ToolbarButton>
<ToolbarButton
title="Delete note"
onClick={async () => await store.dispatch("editor.deleteNote")}
>
<Icon icon={faTrash} />
</ToolbarButton>
</LeftSpacer>
<TabsScrollable
orientation="horizontal"
scroll={editor.tabsScroll}
onScroll={s => store.dispatch("editor.updateTabsScroll", s)}
>
{tabs}
<RightSpacer side="right" />
</TabsScrollable>
</EditorToolbarFocusable>
);
}
const LeftSpacer = styled(EditorSpacer)`
display: flex;
flex-direction: row;
align-items: center;
padding-left: 1rem;
padding-right: 1.4rem;
`;
const RightSpacer = styled(EditorSpacer)`
flex-grow: 1;
min-width: 0.4rem;
`;
const ToolbarButton = styled.button<{ highlighted?: boolean }>`
border: none;
background-color: transparent;
${p2}
${rounded}
font-size: 1.6rem;
height: 2.9rem;
margin-right: 0.2rem;
i {
color: ${p =>
p.highlighted ? OpenColor.orange[7] : THEME.editor.toolbar.buttonColor};
}
&:hover {
cursor: pointer;
background-color: ${THEME.editor.toolbar.hoveredButtonBackground}!important;
}
`;
const EditorToolbarFocusable = styled(Focusable)`
display: flex;
flex-direction: row;
border-bottom: 1px solid ${THEME.editor.toolbar.border};
width: 100%;
background-color: ${THEME.editor.toolbar.background};
height: 4.4rem;
`;
const TabsScrollable = styled(Scrollable)`
display: flex;
align-items: center;
width: calc(100% - 1rem) !important;
white-space: nowrap;
::-webkit-scrollbar-thumb {
background: ${THEME.editor.toolbar.scrollbarColor};
}
`;
export const openTab: Listener<"editor.openTab"> = async (ev, ctx) => {
// Keep in sync with sidebar.openSelectedNotes listener
if (ev.value?.note == null) {
return;
}
const { notes } = ctx.getState();
const notesToOpen = arrayify(ev.value.note);
const noteIds: string[] = [];
let activeTabNoteId: string | undefined = undefined;
for (const note of notesToOpen) {
if (isProtocolUrl("note", note)) {
const foundNote = getNoteByPath(notes, note);
noteIds.push(foundNote.id);
} else {
noteIds.push(note);
}
}
const { active } = ev.value;
if (active) {
if (isProtocolUrl("note", active)) {
activeTabNoteId = getNoteByPath(notes, active).id;
} else {
activeTabNoteId = active;
}
}
if (noteIds.length === 0) {
return;
}
openTabsForNotes(ctx, noteIds);
setActiveTab(ctx, activeTabNoteId);
if (ev.value.focus) {
ctx.focus([Section.Editor], { overwrite: true });
}
if (ev.value.scrollTo) {
ctx.setUI({
sidebar: {
scrollToNoteId: activeTabNoteId,
},
});
}
cleanupClosedTabsCache(ctx);
};
export const reopenClosedTab: Listener<"editor.reopenClosedTab"> = async (
_,
ctx,
) => {
const { closedTabs } = ctx.getCache();
if (closedTabs.length === 0) {
return;
}
const { noteId, previousIndex, isPreview } = closedTabs[0];
ctx.setCache(prev => {
const closedTabs = prev.closedTabs.slice(1);
return {
closedTabs,
};
});
const { notes, editor } = ctx.getState();
// Sanity check to ensure we don't open a duplicate tab.
if (editor.tabs.findIndex(t => t.note.id === noteId) !== -1) {
return;
}
const note = getNoteById(notes, noteId);
ctx.setUI(prev => {
const { tabs } = prev.editor;
const newIndex = Math.min(previousIndex, tabs.length);
tabs.splice(newIndex, 0, { note, isPreview });
return {
editor: {
tabs,
},
};
});
setActiveTab(ctx, noteId);
};
export const deleteNote: Listener<"editor.deleteNote"> = async (_, ctx) => {
const {
editor: { activeTabNoteId },
} = ctx.getState();
if (activeTabNoteId == null) {
return;
}
await deleteNoteIfConfirmed(ctx, activeTabNoteId);
};
export const updateTabsScroll: Listener<"editor.updateTabsScroll"> = async (
{ value: tabsScroll },
ctx,
) => {
if (tabsScroll != null) {
ctx.setUI({
editor: {
tabsScroll,
},
});
}
};
export const pinTab: Listener<"editor.pinTab"> = async (
{ value: tabNoteId },
ctx,
) => {
if (tabNoteId == null) {
return;
}
const state = ctx.getState();
if (state.editor.tabs.findIndex(t => t.note.id === tabNoteId) === -1) {
return;
}
ctx.setUI(prev => {
const tabs = prev.editor.tabs;
const tab = tabs.find(t => t.note.id === tabNoteId)!;
tab.isPinned = true;
return {
editor: {
tabs: orderBy(tabs, ["isPinned"], ["asc"]),
},
};
});
};
export const unpinTab: Listener<"editor.unpinTab"> = async (
{ value: tabNoteId },
ctx,
) => {
if (tabNoteId == null) {
return;
}
const state = ctx.getState();
if (state.editor.tabs.findIndex(t => t.note.id === tabNoteId) === -1) {
return;
}
ctx.setUI(prev => {
const tabs = prev.editor.tabs;
const tab = tabs.find(t => t.note.id === tabNoteId)!;
delete tab.isPinned;
return {
editor: {
tabs: orderBy(tabs, ["isPinned"], ["asc"]),
},
};
});
};
export const moveTab: Listener<"editor.moveTab"> = async ({ value }, ctx) => {
if (value == null || value.newIndex === -1) {
return;
}
const { noteId, newIndex } = value;
const { editor } = ctx.getState();
const originalIndex = editor.tabs.findIndex(t => t.note.id === noteId);
if (originalIndex === -1) {
throw new Error(`No tab for note ID: ${noteId} found.`);
}
const clampedNewIndex = clamp(newIndex, 0, editor.tabs.length - 1);
if (originalIndex === clampedNewIndex) {
return;
}
const tab = editor.tabs[originalIndex]!;
let validatedIndex: number;
if (tab.isPinned) {
validatedIndex = Math.min(
clampedNewIndex,
editor.tabs.findIndex(t => !t.isPinned) - 1,
);
} else {
validatedIndex = Math.max(
clampedNewIndex,
editor.tabs.findIndex(t => !t.isPinned),
);
}
if (originalIndex === validatedIndex) {
return;
}
ctx.setUI(prev => {
const tabs = prev.editor.tabs;
const [tab] = tabs.splice(originalIndex, 1);
tabs.splice(validatedIndex, 0, tab);
return {
editor: {
tabs,
},
};
});
};
export const revealTabNoteInSidebar: Listener<
"editor.revealTabNoteInSidebar"
> = async ({ value }, ctx) => {
if (value == null) {
return;
}
// The note we want to show in the sidebar may be hidden due to a collapsed
// parent so we expand any if needed.
const { notes } = ctx.getState();
const noteToReveal = getNoteById(notes, value);
const noteToRevealParentIds = getParents(noteToReveal, notes).map(n => n.id);
ctx.setUI(prev => {
const prevExpanded = prev.sidebar.expanded ?? [];
const newExpanded = uniq([...prevExpanded, ...noteToRevealParentIds]);
return {
sidebar: {
selected: [noteToReveal.id],
scrollToNoteId: value,
expanded: newExpanded,
},
};
});
};
export function openTabsForNotes(
ctx: StoreContext,
noteIds: string[],
newActiveTabNoteId?: string,
): void {
if (noteIds.length === 0) {
return;
}
const { editor, notes } = ctx.getState();
let tabs = [...editor.tabs];
for (const noteId of noteIds) {
let newTab = false;
let tab = editor.tabs.find(t => t.note.id === noteId);
if (tab == null) {
newTab = true;
const note = getNoteById(notes, noteId);
tab = { note };
// Only open tabs in preview mode if we opened a single tab.
if (noteIds.length === 1) {
tab.isPreview = true;
// Only one preview tab can be open at once.
tabs = tabs.filter(t => !t.isPreview);
}
}
// Second open of a tab takes it out of preview mode.
else if (tab.isPreview) {
delete tab.isPreview;
}
tab.lastActive = new Date();
if (newTab) {
tabs.push(tab);
}
}
let { activeTabNoteId } = editor;
if (newActiveTabNoteId) {
activeTabNoteId = newActiveTabNoteId;
}
if (!activeTabNoteId) {
activeTabNoteId = tabs[0].note.id;
}
ctx.setUI({
editor: {
tabs,
activeTabNoteId,
},
});
}
export function setActiveTab(
ctx: StoreContext,
activeTabNoteId: string | undefined,
): void {
const { sidebar, editor, notes } = ctx.getState();
// When active tab changes, we select the note in the sidebar to make it easy
// for the user to see what note they are working on. If the note is nested though
// we need to expand parents to make sure it's visible.
let { expanded = [] } = sidebar;
if (activeTabNoteId != null && activeTabNoteId != editor.activeTabNoteId) {
const activeNote = getNoteById(notes, activeTabNoteId!);
const activeTabSidebarParents = getParents(activeNote, notes);
if (activeTabSidebarParents.length > 0) {
expanded = uniq([...expanded, ...activeTabSidebarParents.map(p => p.id)]);
}
}
ctx.setUI({
editor: {
activeTabNoteId,
},
sidebar: {
expanded,
selected: [activeTabNoteId],
},
});
}
export function cleanupClosedTabsCache(ctx: StoreContext): void {
const { tabs } = ctx.getState().editor;
// Filter out any closed tabs that have been reopened.
ctx.setCache(prev => {
const closedTabs = prev.closedTabs.filter(
ct => !tabs.some(t => t.note.id === ct.noteId),
);
return {
closedTabs,
};
});
}
|
//
// LoginCoordinator.swift
// MyntToDo
//
// Created by Perennial on 01/02/23.
//
import Foundation
import UIKit
import RxSwift
class LoginCoordinator: Coordinator, StoryboardInitializable {
var loginVC: LoginVC!
var rootVC: UINavigationController!
var signUpCoordinator: SignUpCoordinator!
var toDoListCoordinator: ToDoListCoordinator!
let disposeBag = DisposeBag()
func start() -> UIViewController {
loginVC = LoginCoordinator.instantiateViewController(storyboard: .main, identifier: LoginVC.storyboardIdentifier) as? LoginVC
let viewModel = LoginViewModel()
loginVC.viewModel = viewModel
viewModel.showError.subscribe { [weak self] in
self?.showErrorAlert(with: $0)
}.disposed(by: disposeBag)
viewModel.showSignUp.subscribe { _ in
self.showSignUp()
}.disposed(by: disposeBag)
viewModel.showUser.subscribe { [weak self] in
self?.showToDoList(user: $0)
}.disposed(by: disposeBag)
return loginVC
}
}
extension LoginCoordinator {
func showErrorAlert(with msg: String) {
loginVC.showAlert(title: "Alert", message: msg)
}
func showSignUp() {
signUpCoordinator = SignUpCoordinator()
signUpCoordinator.rootVC = rootVC
let signUpVC = signUpCoordinator.start()
self.rootVC.pushViewController(signUpVC, animated: true)
}
func showToDoList(user: User) {
toDoListCoordinator = ToDoListCoordinator()
toDoListCoordinator.rootVC = rootVC
let toDoListVC = toDoListCoordinator.start() as! ToDoLIstVC
self.rootVC.pushViewController(toDoListVC, animated: true)
}
}
|
#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node*left;
struct node*right;
};
struct node* createNode(int data)
{
//Creating a node pointer.
struct node*n;
n=(struct node*)malloc(sizeof(struct node));//ALLOCATing memeory in the heap.
n->data=data;//setting the data.
n->left=NULL;//setting the left node to null.
n->right=NULL;//setting the right node to null.
return n;//Finally returing the created node.
};
void inOrder(struct node*root)
{
if(root!=NULL)
{
inOrder(root->left);
printf("%d ",root->data);
inOrder(root->right);
}
}
int isBST(struct node*root)
{
static struct node*prev=NULL;
if(root!=NULL)
{
if(!isBST(root->left))
{
return 0;
}
if(prev!=NULL && root->data<=prev->data)
{
return 0;
}
prev=root;
return isBST(root->right);
}
else
{
return 1;
}
}
struct node* searchIter(struct node*root, int key)
{
while(root!=NULL)
{
if(key==root->data)
{
return root;
}
else if(key<root->data)
{
root=root->left;
}
else
{
root=root->right;
}
}
return NULL;
};
int main()
{
// Constructing the root node - Using Function (Recommended)
struct node *p = createNode(5);
struct node *p1 = createNode(3);
struct node *p2 = createNode(6);
struct node *p3 = createNode(1);
struct node *p4 = createNode(4);
// Finally The tree looks like this:
// 4
// / \
// 1 6
// / \
// 5 2
// Finally The tree looks like this for binary search tree:
// 5
// / \
// 3 6
// / \
// 1 4
// Linking the root node with left and right children
p->left = p1;
p->right = p2;
p1->left = p3;
p1->right = p4;
struct node*n=searchIter(p,10);
if(n!=NULL)
{
printf("found:%d",n->data);
}
else
{
printf("Element not found");
}
return(0);
}
|
import styles from "./Navbar.module.scss";
import navbarLogoImg from "../../../assets/logo.png";
import { Link } from "react-router-dom";
import { BsMoonStarsFill } from "react-icons/bs/";
import { useState } from "react";
import TopFilter from "../Filter/TopFilter";
const Navbar = ({ setFilter }) => {
const [isShowTopList, setIsShowTopList] = useState(false);
return (
<div className={styles.navbar}>
<Link to="/" className={styles.navbar_logo}>
{
<img
src={navbarLogoImg}
alt="logo"
className={styles.navbar_logo_img}
/>
}
<h1 className={styles.navbar_logo_title}>AniList</h1>
<BsMoonStarsFill className={styles.navbar_logo_icon} />
</Link>
<div className={styles.navbar_links}>
<div style={{ position: "relative" }}>
<Link
className={
styles.navbar_link +
` ` +
(isShowTopList && styles.navbar_link_hover)
}
to="/"
onMouseOver={() => {
setIsShowTopList(true);
}}
onMouseOut={() => {
setIsShowTopList(false);
}}
onClick={() => {
setFilter("");
}}
>
Top
</Link>
{isShowTopList && (
<TopFilter
setFilter={setFilter}
setIsShowTopList={setIsShowTopList}
/>
)}
</div>
<Link className={styles.navbar_link} to="/airing">
Airing now
</Link>
<Link className={styles.navbar_link} to="/upcoming">
Next season
</Link>
<Link className={styles.navbar_link} to="/characters">
Characters
</Link>
</div>
</div>
);
};
export default Navbar;
|
import { Component, Host, h, State } from '@stencil/core';
import { ColumnDescription } from '../../../../common/table-abstractions/types';
import { ErrorType, GenericResponse } from '../../../../common/types';
import { fetchAs } from '../../../../common/utility';
import { globals } from '../../../../core/global.store';
import { v4 as uuidv4 } from 'uuid';
class CreateFundingAccountExRequest {
token: string;
fundingAccount: {
account_number: number;
name: string;
};
}
class CreateFundingAccountExResponse extends GenericResponse {
fundingAccount: ScFundingAccount;
}
class ScFundingAccountListRequest {
token: string;
}
class ScFundingAccountListResponse {
error: ErrorType;
fundingAccounts: ScFundingAccount[];
}
class ScFundingAccountUpdateRequest {
token: string;
column: string;
value: any;
id: string;
}
class ScFundingAccountUpdateResponse {
error: ErrorType;
fundingAccount: ScFundingAccount | null = null;
}
class DeleteFundingAccountExRequest {
id: string;
token: string;
}
class DeleteFundingAccountExResponse extends GenericResponse {
id: string;
}
@Component({
tag: 'sc-funding-accounts',
styleUrl: 'sc-funding-accounts.css',
shadow: true,
})
export class ScFundingAccounts {
@State() fundingAccountsResponse: ScFundingAccountListResponse;
newAccount_number: number;
newName: string;
handleUpdate = async (id: string, columnName: string, value: string): Promise<boolean> => {
const updateResponse = await fetchAs<ScFundingAccountUpdateRequest, ScFundingAccountUpdateResponse>('sc/funding-accounts/update-read', {
token: globals.globalStore.state.token,
column: columnName,
id: id,
value: value !== '' ? value : null,
});
console.log(updateResponse);
if (updateResponse.error == ErrorType.NoError) {
this.fundingAccountsResponse = {
error: ErrorType.NoError,
fundingAccounts: this.fundingAccountsResponse.fundingAccounts.map(fundingAccount => (fundingAccount.id === id ? updateResponse.fundingAccount : fundingAccount)),
};
globals.globalStore.state.notifications = globals.globalStore.state.notifications.concat({ text: 'item updated successfully', id: uuidv4(), type: 'success' });
return true;
} else {
globals.globalStore.state.notifications = globals.globalStore.state.notifications.concat({ text: updateResponse.error, id: uuidv4(), type: 'error' });
return false;
}
};
handleDelete = async id => {
const deleteResponse = await fetchAs<DeleteFundingAccountExRequest, DeleteFundingAccountExResponse>('sc/funding-accounts/delete', {
id,
token: globals.globalStore.state.token,
});
if (deleteResponse.error === ErrorType.NoError) {
this.getList();
globals.globalStore.state.notifications = globals.globalStore.state.notifications.concat({ text: 'item deleted successfully', id: uuidv4(), type: 'success' });
return true;
} else {
globals.globalStore.state.notifications = globals.globalStore.state.notifications.concat({ text: deleteResponse.error, id: uuidv4(), type: 'error' });
return false;
}
};
async getList() {
this.fundingAccountsResponse = await fetchAs<ScFundingAccountListRequest, ScFundingAccountListResponse>('sc/funding-accounts/list', {
token: globals.globalStore.state.token,
});
}
// async getFilesList() {
// this.filesResponse = await fetchAs<CommonFileListRequest, CommonFileListResponse>('common-files/list', {
// token: globals.globalStore.state.token,
// });
// }
// neo4j_idChange(event) {
// this.newNeo4j_id = event.target.value;
// }
account_numberChange(event) {
this.newAccount_number = event.target.value;
}
nameChange(event) {
this.newName = event.target.value;
}
handleInsert = async (event: MouseEvent) => {
event.preventDefault();
event.stopPropagation();
const createResponse = await fetchAs<CreateFundingAccountExRequest, CreateFundingAccountExResponse>('sc/funding-accounts/create-read', {
token: globals.globalStore.state.token,
fundingAccount: {
// neo4j_id: this.newNeo4j_id,
account_number: this.newAccount_number,
name: this.newName,
},
});
if (createResponse.error === ErrorType.NoError) {
globals.globalStore.state.editMode = false;
this.getList();
globals.globalStore.state.notifications = globals.globalStore.state.notifications.concat({ text: 'item inserted successfully', id: uuidv4(), type: 'success' });
} else {
globals.globalStore.state.notifications = globals.globalStore.state.notifications.concat({ text: createResponse.error, id: uuidv4(), type: 'error' });
}
};
columnData: ColumnDescription[] = [
{
field: 'id',
displayName: 'ID',
width: 250,
editable: false,
deleteFn: this.handleDelete,
},
// {
// field: 'neo4j_id',
// displayName: 'neo4j_id',
// width: 200,
// editable: true,
// updateFn: this.handleUpdate,
// },
{
field: 'account_number',
displayName: 'Account Number',
width: 200,
editable: true,
updateFn: this.handleUpdate,
},
{
field: 'name',
displayName: 'Name',
width: 200,
editable: true,
updateFn: this.handleUpdate,
},
{
field: 'created_at',
displayName: 'Created At',
width: 250,
editable: false,
},
{
field: 'created_by',
displayName: 'Created By',
width: 100,
editable: false,
},
{
field: 'modified_at',
displayName: 'Last Modified',
width: 250,
editable: false,
},
{
field: 'modified_by',
displayName: 'Last Modified By',
width: 100,
editable: false,
},
{
field: 'owning_person',
displayName: 'Owning Person ID',
width: 100,
editable: true,
updateFn: this.handleUpdate,
},
{
field: 'owning_group',
displayName: 'Owning Group ID',
width: 100,
editable: true,
updateFn: this.handleUpdate,
},
];
async componentWillLoad() {
await this.getList();
// await this.getFilesList();
}
render() {
return (
<Host>
<slot></slot>
{/* table abstraction */}
{this.fundingAccountsResponse && <cf-table rowData={this.fundingAccountsResponse.fundingAccounts} columnData={this.columnData}></cf-table>}
{/* create form - we'll only do creates using the minimum amount of fields
and then expect the user to use the update functionality to do the rest*/}
{globals.globalStore.state.editMode === true && (
<form class="form-thing">
{/* <div id="neo4j_id-holder" class="form-input-item form-thing">
<span class="neo4j_id-thing">
<label htmlFor="neo4j_id">No4j_id</label>
</span>
<span class="form-thing">
<input type="text" id="neo4j_id" name="neo4j_id" onInput={event => this.neo4j_idChange(event)} />
</span>
</div> */}
<div id="account_number-holder" class="form-input-item form-thing">
<span class="form-thing">
<label htmlFor="account_number">Account Number</label>
</span>
<span class="form-thing">
<input type="number" id="account_number" name="account_number" onInput={event => this.account_numberChange(event)} />
</span>
</div>
<div id="name-holder" class="form-input-item form-thing">
<span class="form-thing">
<label htmlFor="name">Name</label>
</span>
<span class="form-thing">
<input type="text" id="name" name="name" onInput={event => this.nameChange(event)} />
</span>
</div>
<span class="form-thing">
<input id="create-button" type="submit" value="Create" onClick={this.handleInsert} />
</span>
</form>
)}
</Host>
);
}
}
|
import { Request, Response } from 'express';
import {
ErrorFormatter,
logger,
RequestMethodDebugFormatter,
RequestMethodInfoFormatter,
WarningFormatter,
} from '../logger';
export const Loggable = () => {
return function (
target: Object,
propertyKey: string,
descriptor: PropertyDescriptor
) {
if ((global as any).__TESTING__) {
return descriptor;
}
const originalMethod = descriptor.value;
descriptor.value = function (
req: Request,
res: Response,
next: () => void
) {
const baseLogInfo = {
httpMethod: req.method,
route: req.originalUrl,
};
const { authorization, ...headers } = req.headers;
// INFO - Request con query params y headers.
logger.log({
level: 'info',
message: `Request to method: ${propertyKey}`,
queryParams: req.query,
headers: headers,
formatter: RequestMethodInfoFormatter,
...baseLogInfo,
});
const { password, ...restBody } = req.body;
// DEBUG - Request con parámetros y body.
logger.log({
level: 'debug',
message: `Request to method: ${propertyKey}`,
reqParams: req.params,
reqBody: restBody,
formatter: RequestMethodDebugFormatter,
...baseLogInfo,
});
const originalJsonMethod = res.json;
const loggableJsonMethond = (message: string) => {
res.json = originalJsonMethod;
if (res.statusCode >= 400 && res.statusCode < 500) {
// Warnings - ocurrieron errores "esperados".
logger.log({
level: 'warn',
message: `Warning in method: ${propertyKey}`,
statusCode: res.statusCode,
errors: message,
formatter: WarningFormatter,
...baseLogInfo,
});
}
if (res.statusCode >= 500) {
// ERROR - Errores "inesperados".
logger.log({
level: 'error',
message: `Something unexpected happened in ${propertyKey}`,
statusCode: res.statusCode,
error: message,
formatter: ErrorFormatter,
...baseLogInfo,
});
}
return res.json(message);
};
res.json = loggableJsonMethond;
return originalMethod.call(this, req, res, next);
};
return descriptor;
};
};
|
package businessLogic;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import dataAccess.DataAccessHibernate;
import dataAccess.DataAccessHibernateInterface;
import dominio.Question;
import dominio.Event;
import exceptions.EventFinished;
import exceptions.QuestionAlreadyExist;
public class BLFacadeImplementation implements BLFacade {
DataAccessHibernateInterface dbManager;
public BLFacadeImplementation() {
this.dbManager = new DataAccessHibernate();
}
public BLFacadeImplementation(DataAccessHibernateInterface da) {
dbManager= da;
}
/**
* This method creates a question for an event, with a question text and the minimum bet
*
* @param event to which question is added
* @param question text of the question
* @param betMinimum minimum quantity of the bet
* @return the created question, or null, or an exception
* @throws EventFinished if current data is after data of the event
* @throws QuestionAlreadyExist if the same question already exists for the event
*/
public Question createQuestion(Event event, String question, float betMinimum) throws EventFinished, QuestionAlreadyExist{
Question qry=null;
if(new Date().compareTo(event.getEventDate())>0)
throw new EventFinished(ResourceBundle.getBundle("Etiquetas").getString("ErrorEventHasFinished"));
qry=dbManager.createQuestion(event,question,betMinimum);
return qry;
}
/**
* This method invokes the data access to retrieve the events of a given date
*
* @param date in which events are retrieved
* @return collection of events
*/
public List<Event> getEvents(Date date) {
List<Event> events=dbManager.getEvents(date);
return events;
}
/**
* This method invokes the data access to retrieve the dates a month for which there are events
*
* @param date of the month for which days with events want to be retrieved
* @return collection of dates
*/
public List<Date> getEventsMonth(Date date) {
List<Date> dates=dbManager.getEventsMonth(date);
return dates;
}
/**
* This method invokes the data access to initialize the database with some events and questions.
* It is invoked only when the option "initialize" is declared in the tag dataBaseOpenMode of resources/config.xml file
*/
public void initializeBD(){
dbManager.initializeDB();
}
}
|
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NEAScripts
{
public class SQLCommandBuilder<T> : SQLBase<T>
{
SQLConnection connection;
public SQLCommandBuilder(SQLConnection conn, int tablecase) : base("")
{
connection = conn; //Create an instance of SQL connection
tableName = GetTableNameFromCase(tablecase); //Assign corresponding tableName from tableCase inputted
}
public override void BuildInsertCommand(T data)
{
var properties = data.GetType()
.GetProperties(); //Gets all properties from class T
var propertyNames = properties.Select(p => p.Name); //Transforms properties object into proporties collection and returns list of corresponding strings of names
var propertyValues = properties.Select(p => p.GetValue(data)); //Returns the corresponding value of properties from T object
try
{
string command = $"INSERT INTO {tableName} ({string.Join(", ", propertyNames)}) VALUES" + //Creates command line for SQL insert based on object property columns and values
$"('{string.Join("', '", propertyValues)}')";
MySqlCommand sqlCommand = new MySqlCommand(command, connection.dataSource());
sqlCommand.ExecuteNonQuery(); //Executes SQL Statement
}
catch (Exception ex)
{
throw new ArgumentNullException(ex.Message); //Catches null exception
}
}
public override List<T> BuildSelectCommand(string[] values, string condition) //Method to Executed a SQL Select statement from values and condition parameters and return a List of type T
{
try
{
string columnNames = values.Length > 0 ? string.Join(", ", values) : "*"; //If value length is larger than 0 that becomes the string else it is *(represents all)
string command = $"SELECT {columnNames} FROM {tableName} {GenericWhereClause(condition)}";
MySqlCommand sqlCommand = new MySqlCommand(command, connection.dataSource());
MySqlDataReader reader = sqlCommand.ExecuteReader(); //Builds a Data Reader object
List<T> resultList = new List<T>(); //Creates a list of type T
while (reader.Read())
{
T data = Activator.CreateInstance<T>(); //Activator.Create instance creates an instance of type T
foreach (var property in typeof(T).GetProperties()) // loops through each property name in type T
{
if (values.Contains(property.Name) || columnNames == "*") //If values being searched is in database or all columns are selected go ahead
{
var value = reader[property.Name];
if (value != DBNull.Value) //DBNULL Represnets a non existen value in DataBase, so if value corresponds to a column name in database
{
property.SetValue(data, value);
}
else
{
property.SetValue(data, value); //Default value if value does not correspond to column
}
}
}
resultList.Add(data); //Adds data object to list
}
return resultList; //Returns list of type T
}
catch (Exception ex)
{
throw new ArgumentNullException(ex.Message); //Handles null exception and prints out message
}
}
private string GenericWhereClause(string tableCondition) //Method to return the where clause for the SQL statement
{
string whereClause = string.Empty;
if (tableCondition == null) // returns a empty string if no codition is inputted
{
whereClause = string.Empty;
}
else //returns a WHERE clause if string inputted is not empty
{
whereClause = $"WHERE {tableCondition}";
}
return whereClause; //returns whereClause
}
private string GetTableNameFromCase(int tableCase) //Method to retrun table name based on tableCase inputted
{
string tableName = string.Empty;
switch (tableCase)
{
case 1: //returns transaction_entry if table case = 1
tableName = "transaction_entry";
break;
case 2: //returns user_detials if table case = 2;
tableName = "user_details";
break;
}
return tableName; //returns tableName
}
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<!-- HTML Basic Head -->
<meta charset="UTF-8">
<title>Example - Types Usage</title>
<!-- Style -->
<link href="style.css" type="text/css" rel="stylesheet" />
<!-- Load JS Tools -->
<script type="text/javascript" src="../js-tools.js"></script>
</head>
<body>
<!-- HTML Content -->
<div id="content">
<i>Console for details (F12)</i>
</div>
<!-- Use JS Tools -->
<script type="text/javascript">
// -------------------------------------------------------------------------------------------------------------
// JS Tools -->
// Types
//
// 1. Integer
//
// Create some Integer Types
var my_integer_01 = new jst.type.Integer(1); // 1
var my_integer_02 = new jst.type.Integer("11.1%"); // 11
var my_integer_03 = new jst.type.Integer(111.11); // 111
var my_integer_04 = new jst.type.Integer("A1a1A1bc1.1A1"); // 1111
var my_integer_05 = new jst.type.Integer(false); // 0
var my_integer_06 = new jst.type.Integer(null); // 0
var my_integer_07 = new jst.type.Integer(true); // 1
console.log(my_integer_01.value);
console.log(my_integer_02.value);
console.log(my_integer_03.value);
console.log(my_integer_04.value);
console.log(my_integer_05.value);
console.log(my_integer_06.value);
console.log(my_integer_07.value);
//
// 2. Float
//
// Create some Integer Types
var my_float_01 = new jst.type.Float(2); // 2.0 => 2
var my_float_02 = new jst.type.Float("2.02 %"); // 2.02
var my_float_03 = new jst.type.Float(2.0202); // 2.0202
var my_float_04 = new jst.type.Float("Num 2Test.22 Test22"); // 2.2222
var my_float_05 = new jst.type.Float(false); // 0
console.log(my_float_01.value);
console.log(my_float_02.value);
console.log(my_float_03.value);
console.log(my_float_04.value);
console.log(my_float_05.value);
//
// 3. String
//
// Create some Integer Types
var my_string_01 = new jst.type.String(3.0); // "3.0" => "3"
var my_string_02 = new jst.type.String("3.03"); // "3.03"
var my_string_03 = new jst.type.String(null); // "null"
var my_string_04 = new jst.type.String(false); // "false"
var my_string_05 = new jst.type.String(true); // "true"
console.log(my_string_01.value);
console.log(my_string_02.value);
console.log(my_string_03.value);
console.log(my_string_04.value);
console.log(my_string_05.value);
//
// 4. Boolean | Bool | Bit
//
// Create some Integer Types
var my_bool_01 = new jst.type.Boolean(4.0); // true
var my_bool_02 = new jst.type.Boolean("My Text"); // true
var my_bool_03 = new jst.type.Boolean(false); // false
var my_bool_04 = new jst.type.Boolean(null); // false
console.log(my_bool_01.value);
console.log(my_bool_02.value);
console.log(my_bool_03.value);
console.log(my_bool_04.value);
// -------------------------------------------------------------------------------------------------------------
</script>
</body>
</html>
|
class Carro:
def __init__(self, nome):
self.nome = nome
self._motor = None
def exibeNome(self):
if self.motor:
print(f'Nome do carro: {self.nome}')
else:
print('Carro ainda sem motor')
@property
def motor(self):
return self._motor
@motor.setter
def motor(self, motor):
self._motor = motor
class Motor:
def __init__(self, nome):
self.nome = nome
def exibeNome(self):
print(f'Nome do motor: {self.nome}')
class Fabricante:
def __init__(self, nome):
self.nome = nome
self.carros = []
def exibeNome(self):
print(f'Nome do fabricante: {self.nome}')
def adicionaCarro(self, carro, motor=None):
self.carros.append(Carro(carro))
if motor:
self.carros[-1].motor = motor
def setCarroMotor(self, carro_nome, motor):
for carros in (carronome for carronome in self.carros if carronome.nome == carro_nome):
carros.motor = motor
def exibeCarros(self):
if self.carros:
print('Modelo dos carros:')
for carro in self.carros:
print('-------------------------')
carro.exibeNome()
carro.motor.exibeNome()
return
print('sem carros a serem exibidos')
def exibeInformacoes(self):
self.exibeNome()
self.exibeCarros()
motor1 = Motor('motor top1')
motor2 = Motor('motor top2')
fabricante = Fabricante('Gol')
fabricante.adicionaCarro('Gol bola', motor1)
fabricante.adicionaCarro('Fusca')
fabricante.setCarroMotor('Fusca', motor2)
fabricante.exibeInformacoes()
|
import * as Yup from "yup";
// form
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
// components
import FormProvider, { RHFTextField } from "../../components/hook-form";
import { Button } from "@mui/material";
import { useDispatch, useSelector } from "react-redux";
import { ForgotPassword } from "../../redux/slices/auth";
// ----------------------------------------------------------------------
const ResetPasswordForm = () => {
const dispatch = useDispatch();
const ResetPasswordSchema = Yup.object().shape({
email: Yup.string()
.required("Необходимо ввести эллектронную почту")
.email("Некорректная электронная почта"),
});
const methods = useForm({
resolver: yupResolver(ResetPasswordSchema),
defaultValues: { email: "demo@tawk.com" },
});
const {
reset,
setError,
handleSubmit,
formState: { errors, isSubmitting, isSubmitSuccessful },
} = methods;
const onSubmit = async (data) => {
try {
// submit data to backend
dispatch(ForgotPassword(data));
} catch (error) {
console.error(error);
reset();
setError("afterSubmit", {
...error,
message: error.message,
});
}
};
return (
<FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
<RHFTextField name="email" label="Электронная почта" />
<Button
fullWidth
size="large"
type="submit"
variant="contained"
sx={{
mt: 3,
bgcolor: "text.primary",
color: (theme) =>
theme.palette.mode === "light" ? "common.white" : "grey.800",
"&:hover": {
bgcolor: "text.primary",
color: (theme) =>
theme.palette.mode === "light" ? "common.white" : "grey.800",
},
}}
>
Отправить Запрос
</Button>
</FormProvider>
);
};
export default ResetPasswordForm;
|
STEP 1 i first download the extract the debezium mysql connector archive
sudo curl https://repo1.maven.org/maven2/io/debezium/debezium-connector-mysql/1.0.0.Final/debezium-connector-mysql-1.0.0.Final-plugin.tar.gz | tar xvz
ii then you build your docker image for the kafka connect and connector
by using this dockerfile
FROM strimzi/kafka:0.20.1-kafka-2.5.0
USER root:root
RUN mkdir -p /opt/kafka/plugins/debezium
COPY ./debezium-connector-mysql/ /opt/kafka/plugins/debezium/
USER 1001
then you use docker image to create your kafka connector
the prepare a Dockerfile which adds the connector files to the strimzi kafka connect image
Docker build . -t henriksin1/connect-debezium
docker push henriksin1/connect-debezium
or use the docker repo stated here
step 2 create namespace for all the deployments
kubectl apply -f 0-namespace.yaml
step 3 deploy strimzi operators from the operator lifecycle manager this simplifies the process to mointor the kafka clusters
each operator manages kafka and performs a seperate function.
this installation deploys the custom resources definition CRD is an extension of the Kubernetes API that is not necessarily available in a default Kubernetes installation. It represents a customization of a particular Kubernetes installation. However, many core Kubernetes functions are now built using custom resources, making Kubernetes more modular.
basically we are customizing our resources for the operators to run effortlessly
run this commands
to obtain the latest releases
curl -L https://github.com/operator-framework/operator-lifecycle-manager/releases/download/v0.26.0/install.sh -o install.sh
chmod +x install.sh
./install.sh v0.26.0
or
using helm install the repo
helm repo add strimzi https://strimzi.io/charts
then install using
helm install my-strimzi-kafka-operator strimzi/strimzi-kafka-operator --version 0.38.0 -n kafka
then you run
kubectl create -f https://operatorhub.io/install/strimzi-kafka-operator.yaml
it contains
- Cluster Operator for kafka clusters
The Cluster Operator handles the deployment and management of Apache Kafka clusters on Kubernetes. It automates the setup of Kafka brokers, and other Kafka components and resources.
including dependies like zookeeper
- Topic Operator for topics
The Topic Operator manages the creation, configuration, and deletion of topics within Kafka clusters.
- User Operator for kafka users
The User Operator manages Kafka users that require access to Kafka brokers.
When you deploy Strimzi, you first deploy the Cluster Operator. The Cluster Operator is then ready to handle the deployment of Kafka. You can also deploy the Topic Operator and User Operator using the Cluster Operator (recommended) or as standalone operators. You would use a standalone operator with a Kafka cluster that is not managed by the Cluster Operator.
step 4
deploy our secrets this allows the connectors and kafka have access into the data base and run the topics
run
kubectl -n kafka create secret generic debezium-secret --from-file=secrets.properties
create the file secrets.properties
step 5
deploy the roleback access control
picture here
kubectl apply -f rbac-debezium-role.yaml
step 6
deploy the service account to combine with the rbac and secrets
picture
kubectl apply -f serviceaccount.yaml
step 7
deploy the rbac cluster binding resources which binds the service to the role
picture
kubectl apply -f rbac-cluster-binding.yaml
step 8
deploy the kafka cluster we are using the
picture
kubectl apply -f kafka-kluster.yaml
note confirm the cluster is running
kubectl wait kafka/my-cluster --for=condition=Ready --timeout=300s -n kafka
then you exec into the kafka cluster to run the topics and see if its consumed
after the kafka pod is running you run
this to produce a topic
kubectl -n kafka exec my-cluster-kafka-0 -c kafka -i -t -- bin/kafka-console-producer.sh --bootstrap-server my-cluster-kafka-bootstrap:9092 --topic my-topic
then open another terminal to confirm the topics are consumed
kubectl -n kafka exec my-cluster-kafka-0 -c kafka -i -t -- bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my-topic --from-beginning
-- bin/kafka-console-consumer.sh --bootstrap-server my-cluster-kafka-bootstrap:9092 --topic my-topic --from-beginning
- the components deployed in kafka
- a broker uses apache ZooKeeper for storing configurations data and for cluster coordination
- A broker is referred to a server or node that orchestrates the storage and passing of messages
- ZooKeeper cluster of replicated ZooKeeper instances
- topic = provides a destination for the storage of data each topic is split into one or more partitions
- kafka cluster a group of broker instances
- partition - partitioning takes a single topic log and breaks it into multiple logs each of whiich can live on a seperate node in a kafka cluster
- Kafka Connect cluster for external data connections
- Kafka MirrorMaker cluster to mirror the Kafka cluster in a secondary cluster
Kafka MirrorMaker replicates data between two Kafka clusters, within or across data centers.
MirrorMaker takes messages from a source Kafka cluster and writes them to a target Kafka cluster.
- Kafka Exporter to extract additional Kafka metrics data for monitoring
Kafka Exporter
Kafka Exporter extracts data for analysis as Prometheus metrics, primarily data relating to offsets, consumer groups, consumer lag and topics. Consumer lag is the delay between the last message written to a partition and the message currently being picked up from that partition by a consumer
- Kafka Bridge to make HTTP-based requests to the Kafka cluster
Cruise Control to rebalance topic partitions across broker nodes
- use cases of kafka cases
- and kafka uses
step 9
once you have deployed your kafka cluster
then you deploy the my sql cluster database
after deploying the database
kubectl apply -f 6-sql.yaml
then confirm the database is running and find the end port
kubectl describe service mysql -n kafka
use it and connect with your local mysql workbench
pictures
to connect the sql database serving as a microservice
Step 10
run the kafka connector
first we deploy
kafka connect
you need to deploy a kafka cluster connect
Kafka Connect
Kafka Connect is an integration toolkit for streaming data between Kafka brokers and other systems using Connector plugins. Kafka Connect provides a framework for integrating Kafka with an external data source or target, such as a database like my-sql maria-db, for import or export of data using connectors like debzium.
Connectors are plugins that provide the connection configuration needed.
like debzium connector
A source connector pushes external data into Kafka.
A sink connector extracts data out of Kafka
External data is translated and transformed into the appropriate format.
You can deploy Kafka Connect with build configuration that automatically builds a container image with the connector plugins you require for your data connections.
then deploy a debezium connector to the cluster connector
after deploying the mysql container for collection of the data
then you use docker image to create your kafka connector
to run the kafka connect
kubectl apply -f kafka-connect.yaml
then you confirm all the pods are running
kubectl get all -n kafka
then run
kubectl logs debezium-connect-cluster-connect-0 -n kafka
check if the logs are good
step 11
create your kafka connector file
kubectl apply -f debezium-connector.yaml
pictures of logs with sql
the run
kubectl describe kafkaconnector debezium-connector-mysql -n kafka
once it shows you have connection you can run your topics
now its show time
kubectl -n kafka exec my-cluster-kafka-0 -c kafka -i -t -- bin/kafka-topics.sh --bootstrap-server localhost:9092 --list
pics
kubectl -n kafka exec my-cluster-kafka-0 -c kafka -i -t -- bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic mysql.inventory.customers
this gives you the consumer results for every topic that given from the data base
exec into the database
kubectl exec -it mysql-6597659cb8-j9rk4 -n kafka -- sh
then
mysql -h mysql -u root -p
password:
mysql> use inventory;
mysql> show tables;
+---------------------+
| Tables_in_inventory |
+---------------------+
| addresses |
| customers |
| geom |
| orders |
| products |
| products_on_hand |
+---------------------+
6 rows in set (0.00 sec)
mysql> SELECT * FROM customers;
+------+------------+-----------+-----------------------+
| id | first_name | last_name | email |
+------+------------+-----------+-----------------------+
| 1001 | Sally | Thomas | sally.thomas@acme.com |
| 1002 | George | Bailey | gbailey@foobar.com |
| 1003 | Edward | Walker | ed@walker.com |
| 1004 | Anne | Kretchmar | annek@noanswer.org |
+------+------------+-----------+-----------------------+
mysql> UPDATE customers SET first_name='Anne Marie' WHERE id=1004;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
every data given is transferred on the other terminal
kubectl -n kafka exec my-cluster-kafka-0 -c kafka -i -t -- bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic mysql --from-beginning
### Step 1: Encode PostgreSQL admin username and password using base64
Linux
# Encode a string to base64
echo 'admin' | base64
# Decode our base64 string
echo 'YQBkAG0AaQBuAA==' | base64 --decode
Windows PowerShell
# Encode a string
$MYTEXT = 'admin'
$ENCODED = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($MYTEXT))
Write-Output $ENCODED
# Decode a string
$MYTEXT = 'YQBkAG0AaQBuAA=='
$DECODED = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($MYTEXT))
Write-Output $DECODED
Python
# Encoding a string
import base64
encoded = base64.b64encode(b'admin')
encoded
# Decoding
decoded = base64.b64decode(b'dGhlZGV2b3BzbGlmZS5jb20=')
decoded
|
import { Session } from 'express-session';
import { Document, WithId } from 'mongodb';
export interface UserBasic {
username: string;
password: string;
email: string;
}
export interface CarObject {
CarName: string;
CarPrice: string;
CarFuel: string;
CarKM: string;
CarCC: string;
CarYear: string;
Href: string;
Id: string;
ImageUrl: string;
PostedBy: string;
}
export interface CarValues {
carMake: string;
carModel: string;
carYearStart: string;
carYearEnd: string;
}
export interface UserUnsafeFull {
username: string;
password: string;
email: string;
joinDate: string;
favorites: Array<CarObject>;
posts: Array<CarObject>;
userImageUrl: string;
}
export interface UserSafeFull {
username: string;
email: string;
joinDate: string;
favorites: Array<CarObject>;
posts: Array<CarObject>;
userImageUrl: string;
[key: string]: string | boolean | Array<CarObject>;
}
export interface UserUnsafeDB extends WithId<Document> {
username: string;
password: string;
email: string;
joinDate: string;
favorites: Array<CarObject>;
posts: Array<CarObject>;
userImageUrl: string;
}
export interface SessionUserDB extends WithId<Document> {
username: string;
loggedIn: boolean;
}
export interface CarCollectionFull {
websiteCars: CarObject[];
}
export interface CarCollectionUser {
userCars: CarObject[];
}
export interface CarsCollectionPage {
carsPage: CarObject[];
}
export interface CarsCollectionWebsite {
success: boolean;
gotAllPages: boolean;
collection: CarsCollectionPage[];
}
export interface ResultingCollection {
kupujem: CarsCollectionPage;
polovni: CarsCollectionPage;
}
export interface CarRequestValues extends CarValues {
polovniNum: string;
kupujemNum: string;
}
export interface CustomSession extends Session {
user?: UserSafeFull;
}
export interface DocUpdateData {
collection: 'Users' | 'UsersCars' | 'Sessions';
documentToChange: {
keyType: 'username' | 'Id'; // ex. 'if updating user data it would be: {username : } or {posts.id : }'
keySearchValue: string;
};
dataToChange: any;
}
export interface CarObjectDB extends CarObject, WithId<Document> {}
|
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:$name_snake_case$_mobile/models/task.dart';
class TaskItemView extends StatelessWidget {
final Task item;
final GestureTapCallback onTap;
TaskItemView({Key key, @required this.item, @required this.onTap})
: super(key: key);
@override
Widget build(BuildContext context) {
return Card(
elevation: 8.0,
margin: new EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
child: Container(
decoration: BoxDecoration(color: Color.fromRGBO(64, 75, 96, .9)),
child: new ListTile(
contentPadding:
EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
leading: Container(
padding: EdgeInsets.only(right: 12.0),
decoration: new BoxDecoration(
border: new Border(
right:
new BorderSide(width: 1.0, color: Colors.white24))),
child: Icon(Icons.autorenew, color: Colors.white),
),
title: Text(
item.text,
style:
TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
subtitle: Column(
children: <Widget>[
Row(
children: <Widget>[
Icon(Icons.person, color: Colors.yellowAccent),
Text(item.assigneeName,
style: TextStyle(color: Colors.white))
],
),
Container(
alignment: Alignment.topLeft,
child: Text(item.expireTime),
)
],
),
),
));
}
}
|
import { Component, OnInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { GearComponent } from '../gear/gear.component';
@Component({
selector: 'app-chronometer',
templateUrl: './chronometer.component.html',
styleUrls: ['./chronometer.component.scss']
})
export class ChronometerComponent implements OnInit {
constructor(private dialog : MatDialog) { }
ngOnInit(): void {
}
minutes : number = 0;
seconds : number = 10;
firstZero : number = 0;
startStop : string = 'START';
value : number = 0;
totalSeconds : number = this.calculateSeconds();
countSeconds : number = 0;
clicked : boolean = false;
logicChrono() : void{
if (!this.clicked) {
this.chrono();
this.clicked = true;
this.startStop = 'STOP';
} else {
this.clicked = false;
this.startStop = 'START';
}
}
chrono() : void{
if (this.minutes != 0 || this.seconds != 0) {
let toZero = setInterval(() => {
this.countSeconds++;
this.value = (this.countSeconds/this.totalSeconds) * 100;
if (this.seconds == 0) {
this.seconds = 59;
this.minutes--;
}else {
this.seconds--;
}
if (this.minutes == 0 && this.seconds == 0){
clearInterval(toZero);
}
if (!this.clicked) {
clearInterval(toZero);
}
}, 1000);
}
}
calculateSeconds() : number {
if (this.minutes > 0) {
return this.minutes * 60 + this.seconds;
}else {
return this.seconds;
}
}
openDialog() {
const dialogRef = this.dialog.open(GearComponent, {data :
{minutes : this.minutes, seconds : this.seconds}
});
dialogRef.afterClosed().subscribe( (result) => {
this.minutes = result.minutes;
this.seconds = result.seconds;
this.totalSeconds = this.calculateSeconds();
this.value = 0;
this.countSeconds = 0;
})
}
}
|
/**
* @athenna/common
*
* (c) João Lenon <lenon@athenna.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import { Parser } from '#src/helpers/Parser'
export class Number {
/**
* Get the higher number from an array of numbers.
*/
public static getHigher(numbers: number[]): number {
// eslint-disable-next-line prefer-spread
return Math.max.apply(Math, numbers)
}
/**
* Get km radius between two coordinates.
*/
public static getKmRadius(
centerCord: { latitude: number; longitude: number },
pointCord: { latitude: number; longitude: number }
): number {
const deg2rad = deg => deg * (Math.PI / 180)
const radius = 6371
const { latitude: latitude1, longitude: longitude1 } = centerCord
const { latitude: latitude2, longitude: longitude2 } = pointCord
const dLat = deg2rad(latitude2 - latitude1)
const dLon = deg2rad(longitude2 - longitude1)
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(latitude1)) *
Math.cos(deg2rad(latitude2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2)
const center = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
return radius * center
}
/**
* Get the lower number from an array of numbers.
*/
public static getLower(numbers: number[]): number {
// eslint-disable-next-line prefer-spread
return Math.min.apply(Math, numbers)
}
/**
* Extract all numbers inside a string and
* return as a unique number.
*/
public static extractNumber(string: string): number {
return Parser.stringToNumber(string.replace(/\D/g, ''))
}
/**
* Extract all numbers inside a string.
*/
public static extractNumbers(string: string): number[] {
return string.match(/\d+/g).map(numberString => {
return Parser.stringToNumber(numberString)
})
}
/**
* The average of all numbers in function arguments.
*/
public static argsAverage(...args: number[]): number {
return Number.arrayAverage(args)
}
/**
* The average of all numbers in the array.
*/
public static arrayAverage(array: number[]): number {
return array.reduce((acc, curr) => acc + curr, 0) / array.length
}
/**
* Generate a random integer from a determined interval of numbers.
*/
public static randomIntFromInterval(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1) + min)
}
}
|
package vn.edu.usth.stockdashboard;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import vn.edu.usth.stockdashboard.utils.DbQuery;
import vn.edu.usth.stockdashboard.utils.RestDataNotify;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
public class SignUpActivity extends AppCompatActivity implements RestDataNotify {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
EditText firstName = findViewById(R.id.first_name);
EditText lastName = findViewById(R.id.last_name);
EditText username = findViewById(R.id.usernameEditText);
EditText password = findViewById(R.id.passwordInput);
EditText confirmPassword = findViewById(R.id.cfInput);
Button signUp = findViewById(R.id.buttonSignUp);
signUp.setOnClickListener(v -> {
String confirmPasswordString = confirmPassword.getText().toString();
String passwordString = password.getText().toString();
if (!confirmPasswordString.equals(passwordString)) {
Toast.makeText(this, "Password and confirm password are not the same", Toast.LENGTH_SHORT).show();
return;
}
Thread thread = new Thread(() -> {
try {
DbQuery dbQuery = DbQuery.getInstance();
dbQuery.addDataNotify(this);
dbQuery.register(
firstName.getText().toString(),
lastName.getText().toString(),
username.getText().toString(),
password.getText().toString(),
Float.toString(20000)
);
} catch (IOException e) {
e.printStackTrace();
}
});
thread.start();
});
}
@Override
public void onRestDataReceived(String response) {
runOnUiThread(() -> {
if (response.equals("ERROR")) {
Toast.makeText(this, "Sign up failed", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Sign up successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, LogInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
|
import React from 'react'
import { Decision } from 'src/lib/explat/recommendations'
import { AnalysisStrategy } from 'src/lib/explat/schemas'
import Fixtures from 'src/test-helpers/fixtures'
import { render } from 'src/test-helpers/test-utils'
import DeploymentRecommendation from './DeploymentRecommendation'
test('renders MissingAnalysis correctly', () => {
const { container } = render(
<DeploymentRecommendation
analysis={{
analysisStrategy: AnalysisStrategy.PpNaive,
decision: Decision.MissingAnalysis,
}}
experiment={Fixtures.createExperimentFull()}
/>,
)
expect(container).toMatchInlineSnapshot(`
<div>
Not analyzed yet
</div>
`)
})
test('renders ManualAnalysisRequired correctly', () => {
const { container } = render(
<DeploymentRecommendation
analysis={{
analysisStrategy: AnalysisStrategy.PpNaive,
decision: Decision.ManualAnalysisRequired,
}}
experiment={Fixtures.createExperimentFull()}
/>,
)
expect(container).toMatchInlineSnapshot(`
<div>
<span
class="makeStyles-tooltipped-2"
title="Contact @experimentation-review on #a8c-experiments"
>
Manual analysis required
</span>
</div>
`)
})
test('renders recommendation for NoDifference decision correctly', () => {
const { container } = render(
<DeploymentRecommendation
analysis={{
analysisStrategy: AnalysisStrategy.PpNaive,
decision: Decision.NoDifference,
strongEnoughData: true,
}}
experiment={Fixtures.createExperimentFull()}
/>,
)
expect(container).toMatchInlineSnapshot(`
<div>
Deploy either variation
</div>
`)
})
test('renders recommendation correctly when data is not strong enough', () => {
const { container } = render(
<DeploymentRecommendation
analysis={{
analysisStrategy: AnalysisStrategy.PpNaive,
decision: Decision.NoDifference,
strongEnoughData: false,
}}
experiment={Fixtures.createExperimentFull()}
/>,
)
expect(container).toMatchInlineSnapshot(`
<div>
Not enough certainty
</div>
`)
})
test('renders recommendation for VariantBarelyAhead decision correctly', () => {
const { container } = render(
<DeploymentRecommendation
analysis={{
analysisStrategy: AnalysisStrategy.PpNaive,
decision: Decision.VariantBarelyAhead,
strongEnoughData: true,
chosenVariationId: 123,
}}
experiment={Fixtures.createExperimentFull({
variations: [
{
variationId: 123,
name: 'variation_name_123',
allocatedPercentage: 1,
isDefault: false,
},
],
})}
/>,
)
expect(container).toMatchInlineSnapshot(`
<div>
Deploy
variation_name_123
cautiously
</div>
`)
})
test('renders recommendation for VariantAhead decision correctly', () => {
const { container } = render(
<DeploymentRecommendation
analysis={{
analysisStrategy: AnalysisStrategy.PpNaive,
decision: Decision.VariantAhead,
strongEnoughData: true,
chosenVariationId: 123,
}}
experiment={Fixtures.createExperimentFull({
variations: [
{
variationId: 123,
name: 'variation_name_123',
allocatedPercentage: 1,
isDefault: false,
},
],
})}
/>,
)
expect(container).toMatchInlineSnapshot(`
<div>
Deploy
variation_name_123
cautiously
</div>
`)
})
test('renders recommendation for VariantWinning decision correctly', () => {
const { container } = render(
<DeploymentRecommendation
analysis={{
analysisStrategy: AnalysisStrategy.PpNaive,
decision: Decision.VariantWinning,
strongEnoughData: true,
chosenVariationId: 123,
}}
experiment={Fixtures.createExperimentFull({
variations: [
{
variationId: 123,
name: 'variation_name_123',
allocatedPercentage: 1,
isDefault: false,
},
],
})}
/>,
)
expect(container).toMatchInlineSnapshot(`
<div>
Deploy
variation_name_123
with confidence
</div>
`)
})
|
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from 'src/app/modules/auth/services/auth.service';
import * as XLSX from 'xlsx';
import { UsersService } from '../../../shared/services/users.service';
@Component({
selector: 'app-import',
templateUrl: './import.component.html',
styleUrls: ['./import.component.scss'],
})
export class ImportComponent implements OnInit {
file: any;
fileName: string;
excelData: any;
employerId: string = this.authService.getUserId();
public submitted: boolean = false;
constructor(
private usersService: UsersService,
private router: Router,
private authService: AuthService
) {}
ngOnInit(): void {}
redirectToSetup() {
this.router.navigate(['employer/setup']);
}
redirectToEmployees() {
this.router.navigate(['employer/employees']);
}
fileChange(event) {
this.fileName = event.target.files[0].name;
this.file = event.target.files[0];
}
import() {
if (this.file) {
let fileReader = new FileReader();
fileReader.readAsBinaryString(this.file);
fileReader.onload = (e) => {
const data = XLSX.read(fileReader.result, {type: 'binary'});
const sheetNames = data.SheetNames;
this.excelData = XLSX.utils.sheet_to_json(data.Sheets[sheetNames[0]]);
this.excelData.forEach(consumer => {
this.usersService
.createConsumer(this.employerId, consumer)
.subscribe((data) => {
this.submitted = true;
setTimeout(() => {
this.submitted = false;
}, 3000);
});
});
}
}
}
}
|
<!DOCTYPE html>
<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" type="text/css" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="estilos.css">
<title>Maverick Escola de aviação</title>
</head>
<body>
<header> <!--Parte do Menu-->
<nav class="navbar navbar-default">
<div class="container">
<div>
<button class="btn-sm negrito" onclick="darkMode()">Darkmode</button>
</div>
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapse-navbar" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Maverick Escola de aviação</a>
</div>
<div class="collapse navbar-collapse" id="collapse-navbar">
<ul class="nav navbar-nav">
<li><a href="#sobre-nos">Sobre Nós</a></li>
<li><a href="#nossas-aeronaves">Nossas Aeronaves</a></li>
<li><a href="#cursos">Cursos</a></li>
<li><a href="#contato">Contato</a></li>
<li><a href="#login">Login</a></li>
<li><a href="#cadastro">Cadastro</a></li>
</ul>
</div>
</div>
</nav>
<div class="container MEA-bannerWrapper">
<div class="MEA-banner">
<h1>Maverick Escola de aviação</h1>
<p>Formando pilotos com o melhor treinamento, aeronaves e tecnologia desde 1995</p>
<a href="#contato" class="btn btn-primary btn-lg">Contate-nos agora</a>
</div>
</div>
</header> <!--Parte do Menu-->
<section id="sobre-nos" class="container">
<h2>Sobre Nós</h2>
<div class="row">
<img class="img-responsive col-sm-6" src="img/helicopteros/BELL407-cp.jpg">
<div class="panel-group col-sm-6" id="paineis-sobre">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" data-toggle="collapse" data-target="#primeiro-paragrafo" data-parent="#paineis-sobre">Desde 1995</h3>
</div>
<div id="primeiro-paragrafo" class="collapse in">
<div class="panel-body">
<p class="negrito">A Maverick Escola de Aviação forma pilotos para todas as areas desde 1995</p>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" data-toggle="collapse" data-target="#segundo-paragrafo" data-parent="#paineis-sobre">Preços Acessiveis</h3>
</div>
<div id="segundo-paragrafo" class="collapse">
<div class="panel-body">
<p class="negrito">Cursos teóricos a partir de R$1000,00.</p>
<p class="negrito">Horas de vôo a partir de R$450,00 para aviões e R$850,00 para helicópteros</p>
</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title" data-toggle="collapse" data-target="#terceiro-paragrafo" data-parent="#paineis-sobre">Alegria em formar
pilotos</h3>
</div>
<div id="terceiro-paragrafo" class="collapse">
<div class="panel-body">
<p class="negrito">Aeronaves modernas para voar desde a primeira hora de vôo tanto para VFR quanto para IFR.</p>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="nossas-aeronaves" class="container">
<h2>Nossas Aeronaves</h2>
<div class="row">
<div class="col-sm-6 col-md-4 col-lg-3">
<figure class="thumbnail">
<img src="img/helicopteros/r22-aeronave.jpg" alt="Foto do R-22">
<figcaption class="caption">
<h3>R-22</h3>
<p>O R-22 pode ser uma ótima aeronave para aqueles que estão querendo um bom custo benefício em suas primeiras horas de voo</p>
</figcaption>
</figure>
</div>
<div class="col-sm-6 col-md-4 col-lg-3">
<figure class="thumbnail">
<img src="img/helicopteros/r44-aeronave.jpg" alt="Foto do R-44">
<figcaption class="caption">
<h3>R-44</h3>
<p>O R-44 é uma excelente aeronave para aqueles que desejam mais tecnologia e conforto em seu início nas horas de vôo. Possui tecnologia para IFR</p>
</figcaption>
</figure>
</div>
<div class="col-sm-6 col-md-4 col-lg-3">
<figure class="thumbnail">
<img src="img/avioes/cessna152-aeronave.jpg" alt="Foto do Cessna-152">
<figcaption class="caption">
<h3>Cessna 152</h3>
<p>O Cessa 152 é uma ótima escolha para todos que desejam começar numa boa aeronave com um excelente custo benefício para vôos VFR.</p>
</figcaption>
</figure>
</div>
<div class="col-sm-6 col-md-6 col-lg-3">
<figure class="thumbnail">
<img src="img/avioes/aero-boero115.jpg" alt="Foto do Aero Boero 115">
<figcaption class="caption">
<h3>Boero 115</h3>
<p>O Boero 115 é a aeronave de maior custo benefício para as aulas práticas, sendo sempre uma boa escolha para iniciantes.</p>
</figcaption>
</figure>
</div>
<div class="col-sm-6 col-md-6 col-lg-3">
<figure class="thumbnail">
<img src="img/helicopteros/bell407-aeronave.jpg" alt="Foto do Bell 407">
<figcaption class="caption">
<h3>Bell 407</h3>
<p>O Bell 407 é um helicóptero civil monomotor fabricado pela estadunidense Bell Helicopter, equipado com tecnologia para vôos VFR e IFR.</p>
</figcaption>
</figure>
</div>
</div>
</section>
<section id="cursos">
<div class="titulo-cursos">
<h2 class="container titulo-cursos">Nossos Cursos</h2>
</div>
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Indicators, bullets -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
<li data-target="#carousel-example-generic" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<figure class="item active">
<img src="img/avioes/cockpit1.jpg">
<figcaption class="carousel-caption">
<h3>Cursos Piloto privado e comercial para aviões</h3>
<p>Aulas com pilotos e instrutores renomados.</p>
</figcaption>
</figure>
<figure class="item">
<img src="img/helicopteros/cockpit2BELL.jpg">
<figcaption class="carousel-caption">
<h3>Cursos Piloto privado e comercial para Asas Rotativas</h3>
<p class="negrito">Aeronaves para vôos VFR e IFR.</p>
</figcaption>
</figure>
<figure class="item">
<img src="img/avioes/comissario.jpg">
<figcaption class="carousel-caption">
<h3>Cursos para Comissários de Vôo</h3>
<p>Simulados e materiais inclusos para iniciar seus estudos com mais praticidade.</p>
</figcaption>
</figure>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</section>
<section id="contato" class="container">
<h2>Contato</h2>
<h4>Entre em contato conosco</h4>
<form>
<div class="form-group">
<label for="contato-name">Nome:</label>
<input class="form-control" id="contato-name" type="text" placeholder="Seu Nome">
</div>
<div class="form-group">
<label for="contato-email">Email</label>
<div class="input-group">
<div class="input-group-addon">@</div>
<input type="email" class="form-control" id="contato-email" placeholder="Seu E-mail">
</div>
</div>
<div class="grupo-radio">
<div class="radio">
<label>
<input type="radio" name="tipo-pessoa" checked>
Pessoa Física
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="tipo-pessoa">
Pessoa Jurídica
</label>
</div>
</div><!--
--><select class="contato-select form-control">
<option disabled selected>Tipo de curso</option>
<option>Helicóptero</option>
<option>Avião</option>
<option>Comissário</option>
</select>
<button class="btn btn-primary" type="submit">Enviar</button>
</form>
</section>
<footer>
<address>
<strong>Maverick Escola de Aviação</strong><br>
Rua Imaculada Conceição, 1155 Prado Velho<br>
Curitiba - PR<br>
CEP 80215-901<br>
Tel.: (41) 91024-2048
</address>
<address>
E-mail: contato.meaviacao@outlook.com
</address>
</footer>
<script src="Jquery.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="bootstrap/js/navbar-animation-fix.js"></script>
<script src="darkMode.js"></script>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.