text
stringlengths 184
4.48M
|
---|
const fs = require('fs');
const requestHandler = (req,res) =>{
const url = req.url;
const method = req.method;
if (url === '/') {
res.setHeader('Content-Type', 'text/html');
res.write('<html>');
res.write('<head>');
const messages = fs.existsSync('messages.txt') ? fs.readFileSync('messages.txt', 'utf8') : '';
const lastMessage = messages.trim().split('\n').pop();
res.write(`<title>${lastMessage || 'Message Board'}</title>`);
res.write('</head>');
res.write('<body>');
res.write('<h1>Message Board</h1>');
res.write('<form action="/message" method="POST">');
res.write('<input type="text" name="message">');
res.write('<button type="submit">Submit</button>');
res.write('</form>');
if (messages) {
res.write('<h2>Previous Messages:</h2>');
res.write('<ul>');
messages.split('\n').forEach(message => {
if (message.trim() !== '') {
res.write(`<li>${message}</li>`);
}
});
res.write('</ul>');
}
res.write('</body>');
res.write('</html>');
res.end();
} else if (url === '/message' && method === 'POST') {
const body = [];
req.on('data', (chunk) => {
body.push(chunk);
});
return req.on('end', () => {
const parsedBody = Buffer.concat(body).toString();
const message = parsedBody.split('=')[1];
if (!fs.existsSync('messages.txt')) {
fs.writeFileSync('messages.txt', '');
}
fs.appendFileSync('messages.txt', message + '\n');
res.statusCode = 302;
res.setHeader('Location', '/');
return res.end();
});
}
}
module.exports = requestHandler;
|
# 면접 1주차
## 1. ==와 equal
### equal
+ 값 그 자체를 비교(객체 내부의 값을 비교)
### ==
+ 주소값을 비교(객체 인스턴스의 주소값을 비교)
## 2. Array, LinkedList, ArrayList의 특징
<img src="https://user-images.githubusercontent.com/101400894/210812278-015e4c0c-7944-4595-80c1-1b7f7aec8cdf.png" alt="image" style="zoom:67%;" align="left"/><img src="https://user-images.githubusercontent.com/101400894/210812623-41f1382f-6575-476a-b7c8-7a870431dbaf.png" alt="image" style="zoom:80%;" />
```
ArrayList는 index가 있고, LinkedList는 각 원소마다 앞,뒤 원소의 위치값을 가지고 있다.
```
### Array
> static하다(길이 고정). Array 객체를 생성한 후에는 Array의 길이를 마음대로 변경할 수 없다.
+ primitive type, Object
### ArrayList
> **일반 배열은 처음에 메모리를 할당할 때 크기를 지정해주어야 하지만,**
>
> **ArrayList는 크기를 지정하지 않고** **동적으로 값을 삽입하고 삭제**
+ Object만을 가질 수 있다.
+ **조회**
**ArrayList는 각 데이터의** **index를 가지고 있고 무작위 접근이 가능하기 때문에, 해당 index의 데이터를 한번에 가져올 수 있다.**
+ **데이터 삽입과 삭제**
데이터의 삽입과 삭제시 ArrayList는 그만큼 위치를 맞춰주어야 한다.
위의 사진으로 예를들면 5개의 데이터가 있을 때 맨 앞의 2를 삭제했다면 나머지 뒤의 4개를 앞으로 한칸씩 이동해야 한다.
삽입과 삭제가 많다면 ArrayList는 비효율적**이다.
```
ArrayList<int> arrList//x
ArrayList<Integer> arrList//O
```

### LinkedList
> **LinkedList는 내부적으로** **양방향의 연결 리스트**로 구성되어 있어 참조하려는 원소에 따라 처음부터 정방향 또는 역순으로 순회 가능
>
> **(배열의 단점을 보완하기 위해 LinkedList가 고안되었다.)**
+ **조회**
**LinkedList는 순차적 접근이기 때문에** **검색의 속도가 느리다.**
+ **데이터 삽입과 삭제**
**LinkedList는** **데이터를 추가·삭제시 가리키고 있는 주소값만 변경해주면 되기 때문에 ArrayList에 비해 상당히 효율적이다.**
**위의 사진으로 예를들면 2번째 값을 삭제하면 1번째 노드가 3번째 노드를 가리키게 하기만 하면 된다.**
📌**정적인 데이터를 활용하면서 조회가 빈번하다면 ArrayList를 사용**하는 것이 좋고,
**동적으로 추가/삭제 요구사항이 빈번하다면 LinkedList를 사용**하는 것이 좋다.
## 3. Call by value와 Call by reference의 전문성
**함수 호출의 방법**
1. Call by value ( 값에 의한 호출 ) : 인자로 받은 값을 복사하여 처리
2. Call by reference ( 참조에 의한 호출 ) : 인자로 받은 값의 주소를 참조하여 직접 값에 영향을 줌
```
기본 자료형 : call by value 로 동작 (int, short, long, float, double, char, boolean)
참조 자료형 : call by reference 로 동작 (Array, Class Instance)
```
**'Call by value'의 장단점**
장점 : 복사하여 처리하기 때문에 안전하다. 원래의 값이 보존이 된다.
단점 : 복사를 하기 때문에 메모리 사용량이 늘어난다.
**'Call by reference'의 장단점**
장점 : 복사하지 않고 직접 참조를 하기에 빠르다.
단점 : 직접 참조를 하기에 원래 값이 영향을 받는다. ( 리스크 )
```
class User {
public int age;
public User(int age) {
this.age = age;
}
}
public class ReferenceTypeTest {
@Test
@DisplayName("Reference Type 은 주소값을 넘겨 받아서 같은 객체를 바라본다" +
"그래서 변경하면 원본 변수에도 영향이 있다")
void test() {
User a = new User(10);
User b = new User(20);
// Before
assertEquals(a.age, 10);
assertEquals(b.age, 20);
modify(a, b);
// After
assertEquals(a.age, 11);
assertEquals(b.age, 20);
}
private void modify(User a, User b) {
// a, b 와 이름이 같고 같은 객체를 바라본다.
// 하지만 test 에 있는 변수와 확실히 다른 변수다.
// modify 의 a 와 test 의 a 는 같은 객체를 바라봐서 영향이 있음
a.age++;
// b 에 새로운 객체를 할당하면 가리키는 객체가 달라지고 원본에는 영향 없음
b = new User(30);
b.age++;
}
}
JAVA에서 Call by reference는 해당 객체의 주소값을 직접 넘기는 게 아닌 객체를 보는 또 다른 주소값을 만들어서 넘기다는 사실을 꼭 기억하자.
해당 객체를 보는 새로운 reference 를 참조해서 넘기는 것이다.
따라서 동일한 객체를 가르키고 있지만
main 에서의 reference 값과 swap 함수에서의 reference 값은 다르다.
따라서 위의 예제의 경우 원하는 결과가 나오지 않는다.
아래의 경우 a.age와 같이 접근후 변경하면 사용가능
```
<img src="https://user-images.githubusercontent.com/101400894/210817556-ad6698fa-d948-4a45-92e2-ea5c81583fa9.png" alt="image" style="zoom:50%;" /><img src="https://user-images.githubusercontent.com/101400894/210817662-8e98aedd-944a-4c66-8bee-0a81c0a306ca.png" alt="image" style="zoom:50%;" /><img src="https://user-images.githubusercontent.com/101400894/210817810-42f65009-3250-4061-908b-fe505f4c7f6f.png" alt="image" style="zoom:50%;" /><img src="https://user-images.githubusercontent.com/101400894/210818053-598a0765-8f25-4f82-8607-b8c0c01f4e5f.png" alt="image" style="zoom:50%;" />
## 4. 자바에서는 값에 의한 호출과 참조중 어떤 것으로 호출하는가?
???
## 5. DAO DTO VO 차이
### **DAO **
```
Data Access Object 의 약자로 데이터베이스의 data에 접근하기 위한 객체입니다.
DataBase 접근을 하기 위한 로직과 비지니스 로직을 분리하기 위해 사용합니다.
```
+ DAO의 경우는 DB와 연결할 Connection 까지 설정되어 있는 경우가 많습니다.
+ 그래서 현재 많이 쓰이는 Mybatis 등을 사용할 경우 커넥션풀까지 제공되고 있기 때문에 DAO를 별도로 만드는 경우는 드뭅니다.
### DTO
```
DTO(Data Transfer Object) 는 계층간 데이터 교환을 위한 자바빈즈를 의미합니다.
여기서 말하는 계층간의 의미는 Controller, View, Business Layer, Persistent Layer 등을 말하며 각 계층간 데이터 교환을 위한 객체를 의미합니다.
```
+ DTO는 로직을 가지지 않는 순수한 데이터 객체이고 getter, setter 메소드만 가진 클래스를 의미합니다.
+ setter/getter 에서 set과 get 이후에 나오는 단어가 property라고 약속
+ layer간(특히 서버 -> View로 이동 등)에 데이터를 넘길때에는 DTO를 쓰면 편하다는 것이 이런이유 때문입니다. View에 있는 form에서 name 필드 값을 프로퍼티에 맞춰 넘겼을 때, 받아야 하는 곳에서는 일일히 처리하는 것이 아니라 name속성의 이름이랑 매칭되는 프로퍼티에 자동적으로 DTO가 인스턴스화 되어 PersonDTO를 자료형으로 값을 받을 수 있습니다. 그래서 key-value 로 존재하는 데이터는 자동화 처리된 DTO로 변환되어 쉽게 데이터가 셋팅된 오브젝트를 받을 수 있습니다.
### **VO**
```
VO(Value Object) 는 DTO와 혼용해서 쓰이긴 하지만 미묘한 차이가 있습니다.
VO는 값 오브젝트로써 값을 위해 쓰입니다. 자바는 값 타입을 표현하기 위해 불변 클래스를 만들어서 사용하는데, 불변이라는 것은 readOnly 특징을 가집니다.
```
+ 이러한 클래스는 중간에 값을 바꿀 수 없고 새로 만들어야 한다는 특징이 있습니다.
+ 예를들어 Color클래스를 보면 Red를 표현하기 위해 Color.RED 등을 사용하며 getter기능만이 존재합니다.
📌**비슷한 VO와 DTO 를 구분하자.**
```
DTO와 VO의 공통점은 넣어진 데이터를 getter를 통해 사용하므로 주 목적은 같습니다. 그러나 DTO의 경우는 가변의 성격을 가진 클래스 입니다(setter 활용). 그에반해 VO는 불변의 성격을 가졌기에 차이점이 있습니다.
```
## 6. equals()와 hashCode()의 전문성
### Java hash code
> 객체 해시코드란 **객체를 식별하는 하나의 정수값**을 말한다. Object의 hashCode() 메소드는 **객체의 메모리 번지**를 이용해서 해시코드를 만들어 리턴하기 때문에 객체 마다 다른 값을 가지고 있다. 객체의 값을 동등성 비교시 hashCode()를 오버라이딩할 필요성이 있는데, 컬렉션 프레임워크에서 HashSet, HashMap, HashTable은 다음과 같은 방법으로 두 객체가 동등한지 비교한다.
### **hashCode()**
메소드를 실행해서 리턴된 해시코드 값이 같은지를 본다. 해시 코드값이 다르면 다른 객체로 판단하고, 해시 코드값이 같으면
### **equals()**
메소드로 다시 비교한다. 이 두 개가 모두 맞아야 동등 객체로 판단한다. 즉, 해시코드 값이 다른 엔트리끼리는 동치성 비교를 시도조차 하지 않는다.
### HashTable 동작 원리
> HashTable은 <key,value> 형태로 데이터를 저장한다. 이 때 해시 함수(Hash Function)을 이용하여 key값을 기준으로 고유한 식별값인 해시값을 만든다. (hashcode가 해시값을 만드는 역할을 한다.) 이 해시값을 버킷(Bucket)에 저장한다.
>
> 하지만 HashTable 크기는 한정적이기 때문에 같은 서로 다른 객체라 하더라도 같은 해시값을 갖게 될 수도 있다.
>
> 이것을 ***\*해시 충돌(Hash Collisions)\****이라고 한다.
>
> 이런 경우 아래와 같이 해당 버킷(Bucket)에 LinkedList 형태로 객체를 추가한다.
>
> (* 참고로 java8인가 9버전부터 LinkedList 아이템의 갯수가 8개 이상으로 넘어가면 TreeMap 자료구조로 저장된다고 한다.)
>
> 아래같은 해시값의 버킷 안에 다른 객체가 있는 경우 equals 메서드가 사용
<img src="https://user-images.githubusercontent.com/101400894/210822256-0bc45de0-0b4b-44e7-a2d7-b5a9333392ec.png" alt="image" style="zoom:80%;" align="left"/>
```
HashTable에 put 메서드로 객체를 추가하는 경우
값이 같은 객체가 이미 있다면(equals()가 true) 기존 객체를 덮어쓴다.
값이 같은 객체가 없다면(equals()가 false) 해당 entry를 LinkedList에 추가한다.
HashTable에 get 메서드로 객체를 조회하는 경우
값이 같은 객체가 있다면 (equals()가 true) 그 객체를 리턴한다.
값이 같은 객체가 없다면(equals()가 false) null을 리턴한다.
```
📌equals()와 hashcode()를 같이 재정의해야 하는 이유
```
만약 equals()와 hashcode() 중 하나만 재정의 하면 어떻게 될까? 위 예에서도 봤듯이 hashcode()를 재정의 하지 않으면 같은 값 객체라도 해시값이 다를 수 있다. 따라서 HashTable에서 해당 객체가 저장된 버킷을 찾을 수 없다.
반대로 equals()를 재정의하지 않으면 hashcode()가 만든 해시값을 이용해 객체가 저장된 버킷을 찾을 수는 있지만 해당 객체가 자신과 같은 객체인지 값을 비교할 수 없기 때문에 null을 리턴하게 된다. 따라서 역시 원하는 객체를 찾을 수 없다.
이러한 이유로 객체의 정확한 동등 비교를 위해서는 (특히 Hash 관련 컬렉션 프레임워크를 사용할때!) Object의 equals() 메소드만 재정의하지 말고 hashCode()메소드도 재정의해서 논리적 동등 객체일경우 동일한 해시코드가 리턴되도록 해야한다.
```
|
//##0. zero capture case
somestat = 9
def funto(x int ) int {
hh = 9
def inner(y int) int {
return 7 + y + somestat
}
return inner(12)
}
def doings() String {
b = funto(5)
return "" + b
}
~~~~~
//##1. simple localvar ref
somestat = 9
def funto(x int ) int {
hh = 9
def inner(y int) int {
return x+7 + y + somestat + hh
}
return inner(12)
}
def doings() String {
b = funto(5)
return "" + b
}
~~~~~
//##2. simple localvar ref 2 levels
somestat = 9
def funto(x int ) int {
hh = 9
gg = 121
def inner(y int) int {
gg += 1
def inner2(z int) int {
return x+7 + y + somestat + hh + z + gg
}
return inner2(5)
}
return inner(12)
}
def doings() String {
b = funto(5)
return "" + b
}
~~~~~
//##3. simple localvar ref via class
somestat = 9
class X{
jk = 9
def funto(x int ) int {
hh = 9
def inner(y int) int {
return x + 7 + y + somestat + hh + jk
}
return inner(12)
}
}
def doings() String {
b = new X().funto(5)
return "" + b
}
~~~~~
//##4. simple localvar ref via class - 2 levels
somestat = 9
class X{
jk = 9
def funto(x int ) int {
hh = 9
gg = 121
def inner(y int) int {
gg += 1
def inner2(z int) int {
return x+7 + y + somestat + hh + z + gg + jk
}
return inner2(5)
}
return inner(12)
}
}
def doings() String {
b = new X().funto(5)
return "" + b
}
~~~~~
//##5. simple localvar ref - funcref
somestat = 9
def funto(x int ) () int {
hh = 9
def inner(y int) int {
return x+7 + y + somestat + hh
}
return inner&(12)
}
def doings() String {
b = funto(5)()
return "" + b
}
~~~~~
//##6. simple localvar ref 2 levels- funcref
somestat = 9
def funto(x int ) () int {
hh = 9
gg = 121
def inner(y int) int {
gg += 1
def inner2(z int) int {
return x+7 + y + somestat + hh + z + gg
}
return inner2(5)
}
return inner&(12)
}
def doings() String {
b = funto(5)()
return "" + b
}
~~~~~
//##7. simple localvar ref via class- funcref
somestat = 9
class X{
jk = 9
def funto(x int ) () int {
hh = 9
def inner(y int) int {
return x + 7 + y + somestat + hh + jk
}
return inner&(12)
}
}
def doings() String {
b = new X().funto(5)()
return "" + b
}
~~~~~
//##8. simple localvar ref via class - 2 levels- funcref
somestat = 9
class X{
jk = 9
def funto(x int ) () int {
hh = 9
gg = 121
def inner(y int) int {
gg += 1
def inner2(z int) int {
return x+7 + y + somestat + hh + z + gg + jk
}
return inner2(5)
}
return inner&(12)
}
}
def doings() String {
b = new X().funto(5)()
return "" + b
}
~~~~~
//##9.a - funcref of funcref nested inner
somestat = 9
def funto(x int ) () int {
hh = 9
gg = 121
def inner(y int) () int {
gg += 1
def inner2(z int) int {
return x+7 + y + somestat + hh + z + gg
}
return inner2&(5)
}
return inner(12)&()
}
def doings() String {
b = funto(5)()
return "" + b
}
~~~~~
//##9.b - funcref of funcref nested inner
somestat = 9
class X{
jk = 9
def funto(x int ) () int {
hh = 9
gg = 121
def inner(y int) () int {
gg += 1
def inner2(z int) int {
return x+7 + y + somestat + hh + z + gg + jk
}
return inner2&(5)
}
return inner(12)&()
}
}
def doings() String {
b = new X().funto(5)()
return "" + b
}
~~~~~
//##10 - funcref of funcref nested inner
def ranger(func (int) int, upTo int) String{
ret = ""
for(n=0; n <== upTo; n++){
ret+="" + func(n)
ret+= ", "
}
return ret
}
somestat = 9
def funto(x int ) String {
h = 8
def fib(n int ) int
{
if(n == 0){ return 0 }
elif(n == 1){ return 1 }
else{ return fib(n-1) + fib(n-2)+ x + h + somestat }
}
return ranger(fib&(? int), 10)
}
def doings() String {
b = funto(5)
return "" + b
}
~~~~~
//##11 - nested class def -1
somestat = 9
class X{
fromouter = 99
public class Y{
jk = 9
def funto(x int ) int {
hh = 9
def inner(y int) int {
return x + 7 + y + somestat + hh + jk + fromouter
}
return inner(12)
}
}
}
def doings() String {
b = new X().new Y().funto(5)
return "" + b
}
~~~~~
//##11 - nested class def -2
somestat = 9
class X{
fromouter = 99
public class Y{
jk = 9
def funto(x int ) int {
hh = 9
gg = 121
def inner(y int) int {
def inner2(xxx int) int{
return x+7 + y + somestat + hh + jk + fromouter + xxx + y
}
return inner2(5)
}
return inner(12)
}
}
}
def doings() String {
b = new X().new Y().funto(5)
return "" + b
}
~~~~~
//##12 - nested function inside rhs of field assignment
class MyClass{
xx = 99
def thsignsd() => xx + 100
mc1 = { def someting(a int) => 2 + a
someting(89) }
override equals(a Object) => false
override hashCode() => 1
def doings(){
"" + mc1//('hi')
}
}
def doings(){
MyClass().doings()
}
~~~~~
//##13 - nested function inside rhs of field assignment with deps
class MyClass{
xx = 99
def thsignsd() => xx + 100
mc1 = {fr="frank"; def someting(a int) => fr+ 2 + a
someting(89) }
override equals(a Object) => false
override hashCode() => 1
def doings(){
"" + mc1//('hi')
}
}
def doings(){
MyClass().doings()
}
~~~~~
//##14. lambda gen bug on more than one nested function
//fix lambda gen bug
def lafunc(f String){
class LocalClass(a String){
v=99
override toString() {
g=911
def minime() => "ok " + g
rr = toref&('12')
rr2 = minime&()
"MyClass: " + [minime(), rr()]
}
def toref(g String) => [22 g]
override equals(a Object) => false
override hashCode() => 1
}
LocalClass('ok ' + f)
}
def doings(){
""+lafunc('there')
}
~~~~~
//##15. was a bug now its fine
def MyClass(a int){//these dont return anything
def myfunc() => a + 100
}
def doings(){
"cool"
}
|
import { create } from 'zustand'
import { devtools, persist } from 'zustand/middleware'
import { type ThemeName } from '~/themes/themes'
import { createActionName, type DevTools, type Persist, type Slice } from '~/types/storeTypes'
// State
interface SettingsState {
theme: ThemeName;
}
const settingsState: SettingsState = {
theme: 'Dark+'
}
// Action
interface SettingsAction {
setTheme: (theme: SettingsState['theme']) => void;
}
const actionName = createActionName<keyof SettingsAction>('settings')
const createSettingsAction: Slice<SettingsStore, SettingsAction, Middleware> = set => ({
setTheme: theme => {
set({ theme }, ...actionName('setTheme'))
}
})
// Store
type SettingsStore = SettingsState & SettingsAction
type Middleware = [DevTools, Persist]
export const useSettingsStore = create<SettingsStore>()(devtools(persist((...a) => ({
...settingsState,
...createSettingsAction(...a)
}), { name: 'polyfilled-settings' }), { name: 'Settings Store' }))
// Selectors
|
import React from 'react';
import {shallow} from 'enzyme';
import {Input} from '@components/Input';
import RegistrationSurnameInput from '../surname/surname_input.jsx';
import {updateValues} from '@blocks/actions/form';
jest.mock('@blocks/actions/form', () => ({
updateValues: jest.fn()
}));
const componentProps = {
value: 'test',
state: '',
error: {
code: '',
text: ''
},
hintActive: true,
activeField: 'surname',
updateUserField: jest.fn(),
dispatch: jest.fn()
};
describe('RegistrationSurnameInput', () => {
it('should render hidden fakeSurname input', () => {
const wrapper = shallow(<RegistrationSurnameInput {...componentProps} />);
const surnameInput = wrapper.find(Input).filter('#surname');
expect(surnameInput.length).toBe(1);
});
it('should call changeFakeSurname if fakeSurname input changes value', () => {
const wrapper = shallow(<RegistrationSurnameInput {...componentProps} />);
wrapper
.find(Input)
.filter('#surname')
.simulate('change', {target: {value: 'Blane', name: 'surname'}});
expect(updateValues).toBeCalled();
expect(updateValues).toBeCalledWith({value: 'Blane', field: 'surname'});
});
});
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { environment } from '../environments/environment';
import { LoggedInComponent } from './menupanel/login/logged-in.component';
import { LoginComponent } from './menupanel/login/login.component';
import { PortalComponent } from './portal/portal.component';
const baseUrl = environment.portalBaseUrl.replace(/^\/|\/$/g, '');
/**
* Application routes.
* Add the following to a route to ensure only authenticated users can access:
* canActivate: [AuthGuard]
*/
const routes: Routes = [
{ path: '', pathMatch: 'full', component: PortalComponent },
{ path: 'index.htm', pathMatch: 'full', component: PortalComponent }, // redirect legacy states from index.htm
{ path: 'index.html', pathMatch: 'full', component: PortalComponent }, // redirect legacy states from index.html
{ path: 'login', component: LoginComponent },
{ path: 'login/loggedIn', component: LoggedInComponent },
{ path: baseUrl, redirectTo: '/', pathMatch: 'full' },
{ path: '**', redirectTo: '/' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
|
package ua.khpi.oop.darius.task02;
public class ArrayEx {
public static void main(String[] args) {
double[] numbers = { 1.1, 2.2, 3.3 };
System.out.print("Array: ");
printArray(numbers);
System.out.println();
System.out.println("calcSum1(): " + calcSum1(numbers));
System.out.println("calcSum2(): " + calcSum2(numbers));
System.out.println("calcSum3(): " + calcSum3(numbers));
System.out.println("calcSum4(): " + calcSum4(numbers));
System.out.println("Average of {1.1,2.2,3.3} = " + calcAverage(numbers));
System.out.println("Number positive = " + numPositive(numbers));
double[] numbersWithNegative = { 1.1, 2.2, 3.3, -1, -2 };
System.out.print("Array: ");
printArray(numbersWithNegative);
System.out.println();
System.out.println("Number positive = " + numPositive(numbersWithNegative));
double[] moreNumbers = { 1.1, 2.2, 3.3, -1, -2, 4 };
System.out.print("Array: ");
printArray(moreNumbers);
System.out.println();
System.out.println("Number positive = " + numPositive(moreNumbers));
System.out.print("Array: ");
printArray(numbers);
System.out.println();
System.out.println("Number from 1.1 to 3.2 = " + numInRange(numbers, 1.0, 3.1));
}
public static int numInRange(double[] nums, double lowerBound, double upperBound) {
// TODO: Return the count of how many of the array entries are between the two
// bounds, inclusive.
int sum = 0;
for (int i = 0; i < nums.length; ++i) {
if (nums[i] >= lowerBound && nums[i] <= upperBound) {
sum += 1;
}
}
return sum;
}
public static void printArray(double[] numbers) {
// TODO: Print each element of the array as follows: {numbers[0], numbers[1],
// ...}.
System.out.print("{");
for (int i = 0; i < numbers.length; ++i) {
if (numbers[i] != numbers[numbers.length - 1]) {
System.out.print(numbers[i]);
System.out.print(", ");
} else {
System.out.print(numbers[i]);
}
}
System.out.print('}');
}
public static double calcAverage(double[] numbers) {
// TODO: Return the average value of 'numbers'.
return calcSum1(numbers) / numbers.length;
}
public static int numPositive(double[] numbers) {
// TODO: Return the count of how many of the array entries are greater than or
// equal to zero.
int sum = 0;
for (int i = 0; i < numbers.length; ++i) {
if (numbers[i] >= 0) {
sum += 1;
}
}
return sum;
}
public static double calcSum1(double[] numbers) {
double sum = 0;
for (double num : numbers) {
sum = sum + num; // Or sum += num
}
return sum;
}
public static double calcSum2(double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; ++i) {
sum = sum + numbers[i];
}
return sum;
}
public static double calcSum3(double[] numbers) {
double sum = 0;
int i = 0;
while (i < numbers.length) {
sum = sum + numbers[i];
i++; // Or i = i + 1, or i += 1
}
return sum;
}
// Unlike the other three versions, this one fails for a 0-length array.
public static double calcSum4(double[] numbers) {
double sum = 0;
int i = 0;
do {
sum = sum + numbers[i];
i++;
} while (i < numbers.length);
return sum;
}
}
|
ch14-spring-mybatis: spring集成mybatis
实现步骤:
1、使用的是mysql库,使用学生表 student2(id int 主键列, 自动增长
name varchar(80)
age int
)
2、创建maven项目
3、加入依赖gav
spring, mybatis, mysql驱动
mybatis-spring依赖(mybatis网站提供,用于spring项目创建mybatis对象)
spring有关事务的依赖。
mybatis和spring整合的时候,事务是自动提交的。
4、创建实体类Student
5、创建Dao接口和mapper文件写sql语句
6、写mybatis主配置文件
7、创建service接口和它的实现类
8、创建spring配置文件
1、声明数据源DataSource,使用阿里的Druid连接池
2、声明SqlSessionFactoryBean类,在这个类的内部创建SqlSessionFactory对象
3、声明MapperScannerConfiguration类,在内部创建dao代理对象
创建的对象都放在spring容器中
4、声明service,把3中的dao赋值给service属性
9、 测试dao访问数据库
|
package com.eduardo.ecommerce_golosinas.presentation.screens.profile.update
import android.content.Context
import androidx.compose.runtime.*
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.eduardo.ecommerce_golosinas.domain.model.User
import com.eduardo.ecommerce_golosinas.domain.useCase.auth.AuthUseCase
import com.eduardo.ecommerce_golosinas.domain.useCase.users.UsersUseCase
import com.eduardo.ecommerce_golosinas.domain.util.Resource
import com.eduardo.ecommerce_golosinas.presentation.screens.profile.update.mapper.toUser
import com.eduardo.ecommerce_golosinas.presentation.util.ComposeFileProvider
import com.eduardo.ecommerce_golosinas.presentation.util.ResultingActivityHandler
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.launch
import java.io.File
import javax.inject.Inject
@HiltViewModel
class ProfileUpdateViewModel @Inject constructor(
private val authUseCase: AuthUseCase,
private val usersUseCase: UsersUseCase,
private val savedStateHandle: SavedStateHandle,
@ApplicationContext private val context: Context
) : ViewModel(){
var state by mutableStateOf(ProfileUpdateState())
// argumentos
val data = savedStateHandle.get<String>("user")
var user = User.fromJson(data!!)
// IMAGENES
var file: File? = null
val resultingActivityHandler = ResultingActivityHandler()
var updateResponse by mutableStateOf<Resource<User>?>(null)
private set
init {
state = state.copy(
name = user.name,
lastname = user.lastname,
phone = user.phone,
image = user.image ?: ""
)
}
fun onUpdate() {
if (file != null) { // SI SELECCIONO UNA IMAGEN
updateWithImage()
}
else {
update()
}
}
fun updateWithImage() = viewModelScope.launch {
updateResponse = Resource.Loading
val result = usersUseCase.updateUserWithImage(user.id ?: "", state.toUser(), file!!)
updateResponse = result
}
fun updateUserSession(userResponse: User) = viewModelScope.launch{
authUseCase.updateSession(userResponse)
}
fun update() = viewModelScope.launch {
updateResponse = Resource.Loading
val result = usersUseCase.updateUser(user.id ?: "", state.toUser())
updateResponse = result
}
fun pickImage() = viewModelScope.launch {
val result = resultingActivityHandler.getContent("image/*")
if (result != null){
file = ComposeFileProvider.createFileFromUri(context, result)
state = state.copy(image = result.toString())
}
}
fun takePhoto() = viewModelScope.launch {
val result = resultingActivityHandler.takePicturePreview()
if (result != null){
state = state.copy(image = ComposeFileProvider.getPathFromBitmap(context, result))
file = File(state.image)
}
}
fun onNameInput(input: String){
state= state.copy(name = input)
}
fun onLastNameInput(input: String){
state= state.copy(lastname = input)
}
fun onImageInput(input: String){
state= state.copy(image = input)
}
fun onPhoneInput(input: String){
state= state.copy(phone = input)
}
}
|
import {
Button,
Popover,
PopoverContent,
PopoverTrigger,
} from "@nextui-org/react";
import { includes } from "lodash";
import { FormattedMessage, useIntl } from "react-intl";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { postAskForOrop } from "../lib/api";
import { useState } from "react";
const AskForOropButton = ({
boardgame,
userInfos,
classNames,
buttonVariant,
}) => {
const queryClient = useQueryClient();
const [error, setError] = useState(null);
const askForOrop = useMutation({
mutationFn: ({ title }) => postAskForOrop(title),
onSuccess: () => {
setError(null);
queryClient.invalidateQueries({ queryKey: ["searchResults"] });
queryClient.invalidateQueries({ queryKey: ["myRatings"] });
queryClient.invalidateQueries({ queryKey: ["topAskedOrop"] });
},
onError: (err) => setError(err),
});
if (!userInfos.isLogged) {
return (
<Popover placement="top" showArrow={true} className={classNames?.popover}>
<PopoverTrigger>
<Button
className={classNames?.button}
variant={buttonVariant || "light"}
size="sm"
color="success"
>
<FormattedMessage id="Orop.Ask" />
</Button>
</PopoverTrigger>
<PopoverContent>
<FormattedMessage id="Error.NeedLogin.Orop.Ask" />
</PopoverContent>
</Popover>
);
}
const { discordId } = userInfos;
if (includes(boardgame?.askedBy, discordId)) {
return (
<Button
variant={buttonVariant || "light"}
size="sm"
color="secondary"
className={classNames?.button}
isDisabled
>
<FormattedMessage id="Orop.Ask.Already" />
</Button>
);
}
return (
<Button
variant={buttonVariant || "light"}
size="sm"
color="success"
className={classNames?.button}
onPress={() => askForOrop.mutate({ title: boardgame.title[0] })}
>
<FormattedMessage id="Orop.Ask" />
</Button>
);
};
export default AskForOropButton;
|
/*
* BSD 3-Clause License
*
* Copyright (c) 2024, Bram Stout Productions
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.bramstout.mcworldexporter.entity;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import nl.bramstout.mcworldexporter.model.Direction;
import nl.bramstout.mcworldexporter.model.Model;
import nl.bramstout.mcworldexporter.nbt.NBT_Tag;
import nl.bramstout.mcworldexporter.nbt.TAG_Byte;
import nl.bramstout.mcworldexporter.nbt.TAG_Compound;
import nl.bramstout.mcworldexporter.nbt.TAG_String;
public class EntityPainting extends EntityHangable{
String motive;
public EntityPainting(String name, TAG_Compound properties) {
super(name, properties);
NBT_Tag motiveTag = properties.getElement("Motive");
if(motiveTag == null)
motiveTag = properties.getElement("variant");
motive = "back";
if(motiveTag != null)
motive = ((TAG_String) motiveTag).value;
if(!motive.contains(":"))
motive = "minecraft:" + motive;
NBT_Tag facingTag = properties.getElement("Facing");
if(facingTag == null)
facingTag = properties.getElement("facing");
byte facingByte = 0;
if(facingTag != null)
facingByte = ((TAG_Byte) facingTag).value;
if(facingByte == 4)
facing = Direction.DOWN;
else if(facingByte == 5)
facing = Direction.UP;
else if(facingByte == 2)
facing = Direction.NORTH;
else if(facingByte == 0)
facing = Direction.SOUTH;
else if(facingByte == 1)
facing = Direction.WEST;
else if(facingByte == 3)
facing = Direction.EAST;
}
@Override
public List<Model> getModels() {
Model model = new Model("painting", null, false);
model.addTexture("back", "minecraft:painting/back");
model.addTexture("front", "minecraft:painting/" + motive.replace("minecraft:", ""));
Size size = new Size(paintingSizes.getOrDefault(motive, new Size(1,1)));
float sizeX = size.x;
float sizeY = size.y;
float sizeZ = 1f;
float offsetX = getOffset((int) sizeX);
float offsetY = getOffset((int) sizeY);
float offsetZ = 0f;
sizeX *= 16f;
sizeY *= 16f;
offsetX *= 16f;
offsetY *= 16f;
float[] minMaxPoints = new float[] {offsetX, offsetY, offsetZ, offsetX + sizeX, offsetY + sizeY, offsetZ + sizeZ};
model.addFace(minMaxPoints, new float[] { 0.0f, 0.0f, 16.0f, 16.0f }, Direction.SOUTH, "#front");
model.addFace(minMaxPoints, new float[] { 0.0f, 0.0f, 16.0f, 16.0f }, Direction.NORTH, "#back");
model.addFace(minMaxPoints, new float[] { 0.0f, 0.0f, 16.0f, 16.0f }, Direction.UP, "#back");
model.addFace(minMaxPoints, new float[] { 0.0f, 0.0f, 16.0f, 16.0f }, Direction.DOWN, "#back");
model.addFace(minMaxPoints, new float[] { 0.0f, 0.0f, 16.0f, 16.0f }, Direction.EAST, "#back");
model.addFace(minMaxPoints, new float[] { 0.0f, 0.0f, 16.0f, 16.0f }, Direction.WEST, "#back");
model.rotate(facing.rotX, facing.rotY, false);
return Arrays.asList(model);
}
private int getOffset(int width) {
if(width >= 3)
return 3 - width;
return 0;
}
private static class Size{
public float x;
public float y;
public Size(float x, float y) {
this.x = x;
this.y = y;
}
public Size(Size other) {
this.x = other.x;
this.y = other.y;
}
}
private static HashMap<String, Size> paintingSizes = new HashMap<String, Size>();
static {
paintingSizes.put("minecraft:alban", new Size(1,1));
paintingSizes.put("minecraft:aztec", new Size(1,1));
paintingSizes.put("minecraft:aztec2", new Size(1,1));
paintingSizes.put("minecraft:bomb", new Size(1,1));
paintingSizes.put("minecraft:kebab", new Size(1,1));
paintingSizes.put("minecraft:plant", new Size(1,1));
paintingSizes.put("minecraft:wasteland", new Size(1,1));
paintingSizes.put("minecraft:courbet", new Size(2,1));
paintingSizes.put("minecraft:pool", new Size(2,1));
paintingSizes.put("minecraft:sea", new Size(2,1));
paintingSizes.put("minecraft:creebet", new Size(2,1));
paintingSizes.put("minecraft:sunset", new Size(2,1));
paintingSizes.put("minecraft:graham", new Size(1,2));
paintingSizes.put("minecraft:wanderer", new Size(1,2));
paintingSizes.put("minecraft:bust", new Size(2,2));
paintingSizes.put("minecraft:match", new Size(2,2));
paintingSizes.put("minecraft:skull_and_roses", new Size(2,2));
paintingSizes.put("minecraft:stage", new Size(2,2));
paintingSizes.put("minecraft:void", new Size(2,2));
paintingSizes.put("minecraft:wither", new Size(2,2));
paintingSizes.put("minecraft:fighters", new Size(4,2));
paintingSizes.put("minecraft:donkey_kong", new Size(4,3));
paintingSizes.put("minecraft:skeleton", new Size(4,3));
paintingSizes.put("minecraft:burning_skull", new Size(4,4));
paintingSizes.put("minecraft:pigscene", new Size(4,4));
paintingSizes.put("minecraft:pointer", new Size(4,4));
}
}
|
<!DOCTYPE html>
<html lang="pl">
<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="styl6.css">
<title>Style w JavaScript</title>
</head>
<body>
<div id="lewy">
<h1>Konfigurator stylu</h1>
<p>
Podaj kolor tła <br>
<input type="button" value="Indigo" id="indigo" class="c1" onclick="f1()">
<input type="button" value="SteelBlue" id="steelblue" class="c2" onclick="f2()">
<input type="button" value="Olive" id="olive" class="c3" onclick="f3()">
</p>
<p>
Podaj kolor czcionki <br>
<select id="kolorczcionki" onchange="f4()">
<option>White</option>
<option>Tan</option>
<option>Bisque</option>
<option>Plum</option>
</select>
</p>
<p>
Podaj rozmiar czcionki w procentach, np. 200%<br>
<input type="text" id="rozmiarczionki" value="100%" onchange="f5()">
</p>
<p>
Czy rysunek ma mieć ramkę? <br>
<input type="checkbox" id="ramka"onclick="f6()" checked> Rysuj ramkę
</p>
<p>
Jaki typ punktora listy? <br>
<input type="radio" name="lista" id="d" onclick="f7()"> dysk <br>
<input type="radio" name="lista" id="k" onclick="f7()"> kwadrat <br>
<input type="radio" name="lista" id="o" onclick="f7()"> okrąg <br>
</p>
</div>
<div id="prawy">
<img src="gibraltar.jpg" id="foto" alt="półwysep Gibraltar">
<ul id="punkty">
<li>element 1</li>
<li>element 2</li>
<li>element 3</li>
</ul>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
<div id="stopka">
Autor: Jakub Gad
</div>
<script>
function f1()
{
kolortla = document.getElementById("indigo").value
document.getElementById("prawy").style.background = kolortla
}
function f2()
{
kolortla = document.getElementById("steelblue").value
document.getElementById("prawy").style.background = kolortla
}
function f3()
{
kolortla = document.getElementById("olive").value
document.getElementById("prawy").style.background = kolortla
}
function f4()
{
kolorczcionki = document.getElementById("kolorczcionki").value
document.getElementById("prawy").style.color = kolorczcionki
}
function f5()
{
rozmiarczionki = document.getElementById("rozmiarczionki").value
document.getElementById("prawy").style.fontSize = rozmiarczionki
}
function f6()
{
ramka = document.getElementById("ramka").checked
if (ramka == true)
{
document.getElementById("foto").style.border = "1px solid white"
}
else
{
document.getElementById("foto").style.border = "none"
}
}
function f7()
{
d = document.getElementById("d").checked
k = document.getElementById("k").checked
o = document.getElementById("o").checked
if (d == true)
{
document.getElementById("punkty").style.listStyleType = "disc"
}
if (k == true)
{
document.getElementById("punkty").style.listStyleType = "square"
}
if (o == true)
{
document.getElementById("punkty").style.listStyleType = "circle"
}
}
</script>
</body>
</html>
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" >
<title>Gridea扩展(一)- 代码高亮 | GeraltXLi</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<link rel="shortcut icon" href="https://geraltxli.github.io/favicon.ico?v=1649342244788">
<link rel="stylesheet" href="https://geraltxli.github.io/styles/main.css">
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css" />
<link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script async src="https://www.googletagmanager.com/gtag/js?id=G-7NMQS8RTNS"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-7NMQS8RTNS');
</script>
<script data-ad-client="ca-pub-4499802252514755" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script src="https://geraltxli.github.io/instantpage.js" type="module"></script>
<meta name="description" content="
没想到Gridea默认没有代码高亮,那只能自己来了,使用highlightjs,修改一下主题里代码, 引入一下就好了。
代码高亮
下载highlight.js,点Get Version去下载进行,里面也不少各种语言等之类的选择,..." />
<meta name="keywords" content="Gridea" />
<link rel="stylesheet" type="text/css" href="https://geraltxli.github.io/highlight/styles/github-dark.css">
<script src="https://geraltxli.github.io/highlight/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<link rel="prefetch" href="https://geraltxli.github.io/post/clickhouse-dan-ji-an-zhuang-he-gao-ke-yong-ban-bu-shu/">
<link rel="prefetch" href="https://geraltxli.github.io/post/golang-aes-jia-mi-cbc-mo-shi-pkcs7-tian-chong/">
</head>
<body>
<div id="app" class="main">
<div class="sidebar" :class="{ 'full-height': menuVisible }">
<div class="top-container" data-aos="fade-right">
<div class="top-header-container">
<a class="site-title-container" href="https://geraltxli.github.io">
<img src="https://geraltxli.github.io/images/avatar.png?v=1649342244788" class="site-logo">
<h1 class="site-title">
GeraltXLi
</h1>
</a>
<div class="menu-btn" @click="menuVisible = !menuVisible">
<div class="line"></div>
</div>
</div>
<div>
<a href="https://geraltxli.github.io" class="site-nav">
首页
</a>
<a href="https://geraltxli.github.io/archives" class="site-nav">
归档
</a>
<a href="https://geraltxli.github.io/tags" class="site-nav">
标签
</a>
<a href="https://geraltxli.github.io/post/about" class="site-nav">
关于
</a>
</div>
</div>
<div class="bottom-container" data-aos="flip-up" data-aos-offset="0">
<div class="social-container">
</div>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4499802252514755"
crossorigin="anonymous"></script>
<!-- 侧边栏 -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-4499802252514755" data-ad-slot="3953701340"
data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<div class="site-description">
The flash that cuts through darkness, the light that breaks the night.<br><br>
Total <span id="busuanzi_value_site_uv"></span> visitors.
</span>
</div>
<div class="site-footer">
Powered by <a href="https://github.com/GeraltXLi" target="_blank">GeraltXLi</a> | <a class="rss" href="https://geraltxli.github.io/atom.xml" target="_blank">RSS</a>
</div>
</div>
</div>
<div class="main-container">
<div class="content-container" data-aos="fade-up">
<div class="post-detail">
<h2 class="post-title">Gridea扩展(一)- 代码高亮</h2>
<div class="post-date">2021-05-30 阅读次数:<span id="busuanzi_value_page_pv"></span></div>
<div class="feature-container" style="background-image: url('https://geraltxli.github.io/post-images/gridea-kuo-zhan.jpg')">
</div>
<div class="post-content" v-pre>
<blockquote>
<p>没想到Gridea默认没有代码高亮,那只能自己来了,使用<strong>highlightjs</strong>,修改一下主题里代码, 引入一下就好了。</p>
</blockquote>
<!-- more -->
<h2 id="代码高亮">代码高亮</h2>
<ol>
<li>下载<a href="https://highlightjs.org/">highlight.js</a>,点<code>Get Version</code>去下载进行,里面也不少各种语言等之类的选择,一般默认就够用了</li>
</ol>
<figure data-type="image" tabindex="1"><img src="https://geraltxli.github.io/post-images/1622428479016.png" alt="" loading="lazy"></figure>
<ol start="2">
<li>
<p>下载完后解压,简单点就把整个文件夹<code>highlight</code>都丢到gridea数据目录的<code>static</code>目录下(不过其实也可以直接copy里面的<code>highlight.pack.js</code>和<code>styles</code>目录)</p>
</li>
<li>
<p>去<code>themes</code>目录下修改,一般只有文章会用到,所以直接修改<code>post.ejs</code>。在head里加几行代码就行了,这里我选了<code>github-dark</code>样式,这个看自己爱好</p>
</li>
</ol>
<pre><code class="language-html"><link rel="stylesheet" type="text/css" href="<%= themeConfig.domain %>/highlight/styles/github-dark.css">
<script src="<%= themeConfig.domain %>/highlight/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</code></pre>
</div>
<div class="tag-container">
<a href="https://geraltxli.github.io/tag/4rNyBlHyH/" class="tag">
Gridea
</a>
</div>
<div class="next-post">
<div class="next">下一篇</div>
<a href="https://geraltxli.github.io/post/golang-aes-jia-mi-cbc-mo-shi-pkcs7-tian-chong/">
<h3 class="post-title">
Golang-AES加密(CBC模式,PKCS7填充)
</h3>
</a>
</div>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4499802252514755"
crossorigin="anonymous"></script>
<!-- 文章底部横向广告 -->
<ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-4499802252514755" data-ad-slot="6605298309"
data-ad-format="auto" data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<div id="gitalk-container" data-aos="fade-in"></div>
</div>
</div>
</div>
</div>
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script type="application/javascript">
AOS.init();
var app = new Vue({
el: '#app',
data: {
menuVisible: false,
},
})
</script>
<script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>
<script>
var gitalk = new Gitalk({
clientID: 'f793622868010a23cf01',
clientSecret: 'fe2e90c65c7c3ce7dfa52e619d8a807eee42fdc4',
repo: 'geraltxli.github.io',
owner: 'GeraltXLi',
admin: ['GeraltXLi'],
id: (location.pathname).substring(0, 49), // Ensure uniqueness and length less than 50
distractionFreeMode: false // Facebook-like distraction free mode
})
gitalk.render('gitalk-container')
</script>
</body>
</html>
|
@extends($activeTemplate . 'layouts.master_with_menu')
@section('content')
@php
$kycContent = getContent('kyc.content', true);
$walletImage = fileManager()->crypto();
$profileImage = fileManager()->userProfile();
@endphp
<div class="row gy-4">
@if ($user->kv == 0)
<div class="col-12">
<div class="alert alert-info" role="alert">
<h4 class="alert-heading">@lang('KYC Verification Required')</h4>
<hr>
<p class="mb-0">
{{ __(@$kycContent->data_values->kyc_required) }}
<a class="text--base" href="{{ route('user.kyc.form') }}">@lang('Click Here to Verify')</a>
</p>
</div>
</div>
@elseif($user->kv == 2)
<div class="col-12">
<div class="alert alert-warning" role="alert">
<h4 class="alert-heading">@lang('KYC Verification Pending')</h4>
<hr>
<p class="mb-0">
{{ __(@$kycContent->data_values->kyc_pending) }}
<a class="text--base" href="{{ route('user.kyc.data') }}">@lang('See KYC Data')</a>
</p>
</div>
</div>
@endif
<!-- <div class="col-xl-12 col-lg-12 col-md-12">
<h5 class="title">@lang('Referral Link')</h5>
<div class="input-group">
<input class="form-control form--control bg-white" id="key" name="key" readonly=""
type="text" value="{{ route('user.register', [auth()->user()->username]) }}">
<button class="input-group-text bg--base-two text-white border-0 copyBtn" id="copyBoard">
<i class="lar la-copy"></i>
</button>
</div>
</div> -->
@foreach ($wallets as $wallet)
<div class="col-xl-4 col-md-6 col-sm-12 d-widget-item">
<a class="d-block" href="{{ route('user.transaction.index') }}?crypto={{ $wallet->cryptoId }}">
<div class="d-widget">
<div class="d-widget__icon">
<img src="{{ getImage($walletImage->path . '/' . $wallet->cryptoImage, $walletImage->size) }}">
</div>
<div class="d-widget__content">
<h2 class="d-widget__amount">{{ showAmount($wallet->balance, 2) }} <small
class="d-widget__caption">{{ __($wallet->cryptoCode) }} </small></h2>
<h6 class="d-widget__usd text--base">
@lang('In USD') <i class="las la-arrow-right"></i>
{{ showAmount($wallet->balanceInUsd) }}
</h6>
<!-- <a class="d-block" href="{{ route('user.mining.history') }}"> <h6>Mining Balance</h6> </a>
<h5 class="d-widget__amount">{{ showAmount(auth()->user()->mining_balance, 2) }} <small class="d-widget__caption">{{ __($wallet->cryptoCode) }} </small></h5> -->
</div>
</div>
</a>
</div>
<div class="col-12">
<div class="input-group">
<br> <input class="form-control form--control bg-white" id="key" name="key" readonly=""
type="text" value="{{ $wallet->wallet_address }}">
<button class="input-group-text bg--base-two text-white border-0 copyBtn" id="copyBoard">
<i class="lar la-copy"></i>
</button> </div>
<!-- <button class="btn btn-info transferBalance">
Transfer
</button> -->
</div>
@endforeach
</div>
<div class="container1">
<div class="row">
<div class="col-3">
<a class="" href="https://bgtmining.bitcoingoldtrading.com/ads/buy/BGT/all">
<i class="fas fa-money-bill pay1"></i>
<p>Buy</p>
</a>
</div>
<div class="col-3">
<a class="" href="https://bgtmining.bitcoingoldtrading.com/ads/buy/BGT/all">
<i class="fas fa-exchange-alt pay1"></i>
<p>P2P</p>
</a>
</div>
<div class="col-3">
<a class="" href="https://bgtmining.bitcoingoldtrading.com/user/transactions">
<i class="fas fa-credit-card pay1"></i>
<p>History</p>
</a>
</div>
<div class="col-3">
<a class="" href="https://bgtmining.bitcoingoldtrading.com/ads/sell/BGT/all/all/all/">
<i class="fas fa-hand-holding-usd pay1 transferBalance"></i>
<small>Withdraw</small>
</a>
</div>
</div>
</div>
<div class="container1">
<h4 class="mt-4">@lang('Latest P2P Ads')</h4>
@include($activeTemplate . 'partials.user_ads_table')
</div>
<div class="modal fade" id="transferModal" tabindex="-1" aria-labelledby="transferModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="transferModalLabel">Transfer Balance</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="{{ route('user.main_wallet.transfer') }}" method="POST">
@csrf
<div class="modal-body">
<div class="form-group">
<label for="wallet_address">Wallet Address</label>
<input type="text" class="form-control" name="wallet_address" id="wallet_address" required
placeholder="Destination wallet address">
</div>
<div class="form-group">
<label for="transfer_amount">Amount</label>
<input type="number" step="any" class="form-control" name="transfer_amount"
id="transfer_amount" required placeholder="Amount to transfer">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">Send</button>
</div>
</form>
</div>
</div>
</div>
@endsection
@push('script')
<script>
$(document).ready(function() {
// Function to copy text to clipboard
function copyToClipboard(text) {
var input = document.createElement("textarea");
input.value = text;
document.body.appendChild(input);
input.select();
document.execCommand("copy");
document.body.removeChild(input);
}
// When the copy button is clicked
$("#copyBoard").click(function() {
var textToCopy = $("#key").val();
copyToClipboard(textToCopy);
alert("Copied to clipboard!");
});
});
(function($) {
"use strict";
$(".transferBalance").click(function(e) {
e.preventDefault();
var modal = $("#transferModal");
modal.modal('show');
});
$('.copyBtn').on('click', function() {
var copyText = document.getElementById("key");
copyText.select();
copyText.setSelectionRange(0, 99999);
document.execCommand("copy");
iziToast.success({
message: "Copied: " + copyText.value,
position: "topRight"
});
});
})(jQuery);
</script>
@endpush
@push('style')
<style>
.d-widget__usd {
font-size: 15px;
margin-top: 5px;
}
/* Targeting the <a> tags specifically */
.row a {
color: black;
/* Set link color to black */
text-decoration: none;
/* Remove underline from links */
}
.pay1 {
margin-top: 15px;
padding-top: 10px;
background-color: orange;
border-radius: 50%;
width: 40px;
height: 40px;
text-align: center;
color: white;
}
.container1 {
text-align: center;
padding: 1px;
background-color: #ffffff;
border-radius: 10px;
}
.container {
text-align: left;
}
</style>
@endpush
|
package com.its.membership_board.service;
import com.its.membership_board.dto.BoardDTO;
import com.its.membership_board.dto.PageDTO;
import com.its.membership_board.repository.BoardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class BoardService {
@Autowired
private BoardRepository boardRepository;
public void save(BoardDTO boardDTO) throws IOException {
MultipartFile boardFile = boardDTO.getBoardFile();
String boardFileName = boardFile.getOriginalFilename();
boardFileName = System.currentTimeMillis() + "-" + boardFileName;
boardDTO.setBoardFileName(boardFileName);
String savePath = "C:\\spring_img\\" + boardFileName;
System.out.println("BoardService.save");
System.out.println("boardDTO = " + boardDTO);
if (!boardFile.isEmpty()) {
boardFile.transferTo(new File(savePath));
}
boardRepository.save(boardDTO);
}
public List<BoardDTO> findAll() {
List<BoardDTO> boardDTOList = boardRepository.findAll();
return boardDTOList;
}
private static final int PAGE_LIMIT = 3;
private static final int BLOCK_LIMIT = 3;
public List<BoardDTO> pagingList(int page) {
//1페이지 요청=>
int pagingStart = (page-1) * PAGE_LIMIT;
Map<String, Integer> pagingParam = new HashMap<>();
pagingParam.put("start", pagingStart);
pagingParam.put("limit", PAGE_LIMIT);
List<BoardDTO> pagingList = boardRepository.pagingList(pagingParam);
return pagingList;
}
public PageDTO paging(int page) {
int boardCount = boardRepository.boardCount();//글 갯수 조회
//필요한 전체 페이지 갯수
//10, 3 10/3=3.333 =>4
int maxPage = (int)(Math.ceil((double)boardCount / PAGE_LIMIT));
//시작페이지를 정하는 역할
//1,4,7,10
int startPage = (((int)(Math.ceil((double)page / BLOCK_LIMIT))) - 1) * BLOCK_LIMIT + 1;
//끌페이지 값 3.6.9.12
int endPage = startPage + BLOCK_LIMIT - 1;
if(endPage > maxPage)
endPage = maxPage;
PageDTO paging = new PageDTO();
paging.setPage(page);
paging.setStartPage(startPage);
paging.setEndPage(endPage);
paging.setMaxPage(maxPage);
return paging;
}
public BoardDTO findById(BoardDTO boardDTO) {
return boardRepository.findById(boardDTO);
}
public void update(BoardDTO boardDTO) {
System.out.println("BoardService.update");
System.out.println("boardDTO = " + boardDTO);
boardRepository.update(boardDTO);
}
public void delete(Long b_id) {
boardRepository.delete(b_id);
}
public List<BoardDTO> search(String searchType, String q) {
Map<String, String> searchParam = new HashMap<>();
searchParam.put("type", searchType);
searchParam.put("q", q);
List<BoardDTO> searchList = boardRepository.search(searchParam);
return searchList;
}
}
|
import {View, Text, Image, Dimensions, Pressable, Alert} from 'react-native';
import React, {useState, useEffect} from 'react';
import {app} from '../../../../constants/app';
import Icon from 'react-native-vector-icons/AntDesign';
import {currencyFormatter} from '../../../../helpers';
import {IProduct} from '../../../../../interfaces';
import {viewFlexCenter, viewFlexSpace} from '../../../../constants/styles';
import {APP_COLORS} from '../../../../constants/colors';
import {
addFavouriteItem,
removeFavouriteItem,
} from '../../../../actions/favourites';
import {useDispatch, useSelector} from 'react-redux';
import {RootState} from '../../../../reducers';
import ImageLoader from '../../../../components/image-loader';
import {t} from 'i18next';
const {width} = Dimensions.get('window');
interface IProductItemProps {
index: number;
item: IProduct;
setSelectedProduct: any;
setShowModal: any;
}
const imageHeight = width / 2 - 90;
const ProductItem = ({
index,
item,
setSelectedProduct,
setShowModal,
}: IProductItemProps) => {
const dispatch = useDispatch();
const {language} = useSelector((state: RootState) => state.language);
const {favourites} = useSelector((state: RootState) => state.favourites);
const [productExistsInFavList, setProductExistsInFavList] = useState(false);
useEffect(() => {
const exists = favourites.find(i => i.pId === item.pId);
if (exists) {
setProductExistsInFavList(true);
} else {
setProductExistsInFavList(false);
}
}, [item]);
const addToFavList = () => {
dispatch(addFavouriteItem(item));
setProductExistsInFavList(true);
};
const removeFromFavList = () => {
Alert.alert(
'Confirmation',
'Do you want to remove this product from favourite list?',
[
{
text: 'Cancel',
style: 'cancel',
},
{
text: 'confirm',
onPress: () => {
dispatch(removeFavouriteItem(item));
setProductExistsInFavList(false);
},
},
],
{cancelable: true},
);
};
return (
<View
key={index}
style={[
viewFlexSpace,
{
borderBottomColor: APP_COLORS.PRODUCT_CARD_BORDER,
borderBottomWidth: 1,
marginBottom: 10,
},
]}>
<View style={{position: 'relative'}}>
<Pressable
onPress={() => {
setSelectedProduct(item);
setShowModal(true);
}}>
<ImageLoader
url={app.FILE_URL + item.image}
width={width / 2 - 50}
height={imageHeight}
/>
</Pressable>
<View
style={{
position: 'absolute',
top: 0,
right: 0,
}}>
{productExistsInFavList ? (
<Pressable onPress={() => removeFromFavList()}>
<View
style={[
viewFlexCenter,
{
padding: 10,
borderRadius: 100,
backgroundColor: APP_COLORS.MAROON,
marginRight: 5,
marginTop: 5,
},
]}>
<Icon name="hearto" size={25} color={APP_COLORS.WHITE} />
</View>
</Pressable>
) : (
<Pressable onPress={() => addToFavList()}>
<View
style={[
viewFlexCenter,
{
padding: 10,
borderRadius: 100,
backgroundColor: APP_COLORS.DARK_GRAY,
marginRight: 5,
marginTop: 5,
},
]}>
<Icon name="hearto" size={25} color={APP_COLORS.BLACK} />
</View>
</Pressable>
)}
</View>
</View>
<View
style={{
flex: 1,
paddingLeft: 10,
height: '100%',
position: 'relative',
}}>
<Text
style={{
color: APP_COLORS.BLACK,
fontWeight: '600',
textTransform: 'capitalize',
}}>
{language == 'kinya' ? item.kName : item.name}
</Text>
<Text style={{color: APP_COLORS.TEXT_GRAY}}>
{language == 'kinya' ? item.kDescription : item.description}
</Text>
{item.priceType === 'single' && (
<Text style={{color: APP_COLORS.TEXT_GRAY}}>
<Text
style={{
color: APP_COLORS.BLACK,
fontWeight: 'bold',
}}>
{t('priceText')}:
</Text>{' '}
{currencyFormatter(item.singlePrice)} RWF
</Text>
)}
<View
style={{
position: 'absolute',
bottom: 0,
right: 0,
}}>
<Pressable
onPress={() => {
setSelectedProduct(item);
setShowModal(true);
}}>
<View
style={{
backgroundColor: APP_COLORS.MAROON,
paddingHorizontal: 20,
paddingVertical: 5,
}}>
<Text style={{color: APP_COLORS.WHITE, fontSize: 20}}>+</Text>
</View>
</Pressable>
</View>
</View>
</View>
);
};
export default ProductItem;
|
import React, {useEffect, useState} from 'react'
import { Box } from '@chakra-ui/react'
import Card from './Card'
import firebase from "firebase";
import {useNavigate} from 'react-router-dom'
import {auth, db, storage} from '../repository/firebase/firebase';
const Category = ({ data }) => {
const [userUid, setUserUid] = useState(null);
const navigate = useNavigate();
useEffect(() => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
setUserUid(user.uid);
console.log('This is the user: ', user.uid)
} else {
// No user is signed in.
setUserUid(null);
console.log('There is no logged in user');
}
});
}, [])
let Product;
const addToCart = (product, quantity) => {
if(userUid !== null) {
console.log("product in category and not null", product);
Product = product;
Product['quantity'] = quantity ? quantity : 1;
Product['TotalProductPrice'] = Product.quantity*Product.formattedPrice;
db.collection('Cart ' + userUid).doc(product.mealId).set(Product)
.then(() => {
console.log(`added to cart baby !n and the product id is: ${product.mealId} `)
}).catch((err) => {
console.log(err);
});
} else {
navigate("/login");
}
}
return (
<Box display={"flex"} flexWrap={"wrap"} justify={{ base: 'center', md: 'center' }} justifyContent={'space-evenly'}>
{data && data?.map(elm => {
return <Card data={elm} addToCart={addToCart}/>
})}
</Box>
)
}
export default Category
|
package com.cocktails.cocktail.service.mapper;
import com.cocktails.cocktail.dto.IngredientDto;
import com.cocktails.cocktail.model.CocktailIngredient;
import com.cocktails.cocktail.model.Ingredient;
import com.cocktails.cocktail.model.emuns.IngredientType;
import com.cocktails.cocktail.model.emuns.Unit;
import lombok.val;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class CocktailIngredientMapperTest {
@Mock
private IngredientMapper ingredientMapper;
@InjectMocks
private CocktailIngredientMapper cocktailIngredientMapper;
@Test
public void cocktailIngredientToDto_ShouldReturnResult() {
// given
val ingredient = Ingredient.builder().id(1L).name("Vodka").type(IngredientType.SPIRIT).build();
val cocktailIngredient = CocktailIngredient.builder().id(1L).quantity(BigDecimal.valueOf(2.0))
.unit(Unit.OZ).ingredient(ingredient).build();
val ingredientDto = IngredientDto.builder()
.id(ingredient.getId())
.name(ingredient.getName())
.type(ingredient.getType())
.build();
when(ingredientMapper.ingredientToDto(ingredient)).thenReturn(ingredientDto);
// when
val cocktailIngredientDto = cocktailIngredientMapper.cocktailIngredientToDto(cocktailIngredient);
// then
assertEquals(cocktailIngredient.getId(), cocktailIngredientDto.getId());
assertEquals(cocktailIngredient.getQuantity(), cocktailIngredientDto.getQuantity());
assertEquals(cocktailIngredient.getUnit(), cocktailIngredientDto.getUnit());
IngredientDto resultIngredientDto = cocktailIngredientDto.getIngredient();
assertEquals(ingredient.getId(), resultIngredientDto.getId());
assertEquals(ingredient.getName(), resultIngredientDto.getName());
assertEquals(ingredient.getType(), resultIngredientDto.getType());
}
}
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { getMovies, addMovieFavorite } from "../../actions";
import MovieCard from "../MovieCard/MovieCard";
import SearchMovie from "../SearchMovie/SearchMovie";
export class FrontPage extends Component {
render() {
return (
<div className="p-5 my-5">
<SearchMovie
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
/>
<ul className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 items-start mt-4">
{this.props.movie &&
this.props.movie.map((movie) => (
<MovieCard
id={movie.imdbID}
title={movie.Title}
poster={movie.Poster}
key={movie.imdbID}
/>
))}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return {
movie: state.movies,
};
}
function mapDispatchToProps(dispatch) {
return {
getMovies: (title) => dispatch(getMovies(title)),
addMovieFavorite: (title) => dispatch(addMovieFavorite(title)),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(FrontPage);
|
package org.live.sys.controller;
import org.live.common.constants.SystemConfigConstants;
import org.live.common.response.ResponseModel;
import org.live.common.response.SimpleResponseModel;
import org.live.common.shiro.RetryLimitHashedCredentialsMatcher;
import org.live.common.support.ServletContextHolder;
import org.live.common.support.SpringContextHolder;
import org.live.common.systemlog.LogLevel;
import org.live.common.systemlog.OperateType;
import org.live.common.systemlog.SystemLog;
import org.live.common.systemlog.SystemLogAspect;
import org.live.sys.vo.SysConfigVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/sys")
public class ConfigController {
private Logger LOGGER;
@SystemLog(description = "设置系统参数", logLevel = LogLevel.ERROR, operateType = OperateType.UPDATE)
@RequestMapping(value = "/config", method = RequestMethod.POST)
@ResponseBody
public ResponseModel<Object> saveSystemConfig(SysConfigVo vo){
ResponseModel<Object> model = new SimpleResponseModel<Object>();
try {
int[] logLevelRange = { 1, 2, 3, 4 };
if (vo.getLogLevel() < 1 || vo.getLogLevel() > 4) {
// 1.info级别,2.warn级别,3,error级别 4.关闭日志
return model.error("系统日志参数错误");
}
if (vo.getPasswordRetryCount() < 0 || vo.getPasswordRetryCount() > 15) {
// 0.关闭限制 ,但值要小于15
return model.error("密码重试次数限制的参数错误");
}
ServletContextHolder.setAttribute(SystemConfigConstants.SYSTEM_TITLE_KEY, vo.getSystemTitle());
RetryLimitHashedCredentialsMatcher matcherComponent = SpringContextHolder.getBean(RetryLimitHashedCredentialsMatcher.class);
SystemLogAspect systemLogAspect = SpringContextHolder.getBean(SystemLogAspect.class);
matcherComponent.setRetryLimitCount(vo.getPasswordRetryCount());
systemLogAspect.setLogLevel(vo.getLogLevel());
model.success();
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return model;
}
@RequestMapping(value = "/config/page", method = RequestMethod.GET)
@SystemLog(description = "进入系统参数设置", logLevel = LogLevel.ERROR)
public String toSysConfigPage(Model model){
try {
String systemTitle = ServletContextHolder.getAttribute(SystemConfigConstants.SYSTEM_TITLE_KEY);
RetryLimitHashedCredentialsMatcher matcherComponent = SpringContextHolder.getBean(RetryLimitHashedCredentialsMatcher.class);
SystemLogAspect systemLogAspect = SpringContextHolder.getBean(SystemLogAspect.class);
int passwordRetryCount = matcherComponent.getRetryLimitCount();
int logLevel = systemLogAspect.getLogLevel();
model.addAttribute("systemTitle", systemTitle);
model.addAttribute("passwordRetryCount", passwordRetryCount);
model.addAttribute("logLevel", logLevel);
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
return "sys/config";
}
}
|
package lesson_fifteen
import (
"bufio"
"errors"
"fmt"
"log"
"os"
"strconv"
)
var pl = fmt.Println
func Start() string {
pl("Lesson Fifteen Started.")
pl("File I/O")
// f - file
// err - error
f, err := os.Create("15.lesson_fifteen/data.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close() // whenever out of scope, it closes the file
iPrimeArr := []int{2, 3, 5, 7, 11}
var sPrimeArr []string
// convert integer array to string array values
for _, i := range iPrimeArr {
sPrimeArr = append(sPrimeArr, strconv.Itoa(i))
}
// write the newly created string array values to the file, handle errors
for _, num := range sPrimeArr {
_, err := f.WriteString(num + "\n")
if err != nil {
log.Fatal(err)
}
}
// open the created file
f, err = os.Open("15.lesson_fifteen/data.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
// read from the file and print out all the lines one by one
scan1 := bufio.NewScanner(f)
for scan1.Scan() {
pl("Prime :", scan1.Text())
}
if err := scan1.Err(); err != nil {
log.Fatal(err)
}
// append to a file
/*
Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must
be specified.
O_RDONLY : open the file read-only
O_WRONLY : open the file write-only
O_RDWR : open the file read-write
These can be or'ed
O_APPEND : append data to the file when writing
O_CREATE : create a new file if none exists
O_EXCL : used with O_CREATE, file must not exist
O_SYNC : open for synchronous I/O
O_TRUNC : truncate regular writable file when opened
*/
err = nil // resets err if it's nil from above use...
// check if the file exists
_, err = os.Stat("15.lesson_fifteen/data.txt")
if errors.Is(err, os.ErrNotExist) {
pl("File Doesn't Exist.")
} else {
f, err = os.OpenFile(
"15.lesson_fifteen/data.txt",
os.O_APPEND|os.O_CREATE|os.O_WRONLY,
0644)
if err != nil {
log.Fatal(err)
}
defer f.Close()
if _, err = f.WriteString("13\n"); err != nil {
log.Fatal(err)
}
}
return "Lesson Fifteen Complete!"
}
|
import { useState } from "react"
import IconCalender from "../icons/IconCalender"
import IconCloseMenu from "../icons/IconCloseMenu"
import IconDown from "../icons/IconDown"
import IconPlanning from "../icons/IconPlanning"
import IconReminders from "../icons/IconReminders"
import IconTodo from "../icons/IconTodo"
import IconUp from "../icons/IconUp"
interface Props {
openMenu: boolean
setOpenMenu: React.Dispatch<React.SetStateAction<boolean>>
}
const MobileMenu = ({ openMenu, setOpenMenu }: Props) => {
const [openFeatures, setOpenFeatures] = useState(false)
const [openCompany, setOpenCompany] = useState(false)
return (
// mobile menu
<div className="mobile-menu w-screen absolute top-0 right-0 bg-Medium_Gray/50 h-[48.75rem] lg:hidden">
<div className="absolute right-0 w-[64.53%] min-h-full bg-white pt-5 px-6">
<div className="flex mb-8 close">
<div
className="ml-auto cursor-pointer"
onClick={() => setOpenMenu(!openMenu)}
>
<IconCloseMenu />
</div>
</div>
<div className="flex items-start justify-start flex-col space-y-7 mb-10">
{/* features */}
<div>
<span
className="flex items-center cursor-pointer"
onClick={() => setOpenFeatures(!openFeatures)}
>
<a href="#" className="font-medium mr-2 text-Medium_Gray">
Features
</a>
{openFeatures ? <IconUp /> : <IconDown />}
</span>
{openFeatures && (
<div className="pl-6 space-y-5 block mt-7">
<span className="flex items-center cursor-pointer">
<IconTodo />
<p className="pl-4 capitalize font-medium text-Medium_Gray">
todo list
</p>
</span>
<span className="flex items-center cursor-pointer">
<IconCalender />
<p className="pl-4 capitalize font-medium text-Medium_Gray">
calender
</p>
</span>
<span className="flex items-center cursor-pointer">
<IconReminders />
<p className="pl-4 capitalize font-medium text-Medium_Gray">
reminders
</p>
</span>
<span className="flex items-center cursor-pointer">
<IconPlanning />
<p className="pl-4 capitalize font-medium text-Medium_Gray">
planning
</p>
</span>
</div>
)}
</div>
{/* company */}
<div>
<span
className="flex items-center cursor-pointer"
onClick={() => setOpenCompany(!openCompany)}
>
<a href="#" className="font-medium mr-2 text-Medium_Gray">
Company
</a>
{openCompany ? <IconUp /> : <IconDown />}
</span>
{openCompany && (
<div className="pl-6 space-y-5 block mt-7">
<p className="capitalize font-medium text-Medium_Gray cursor-pointer">
history
</p>
<p className="capitalize font-medium text-Medium_Gray cursor-pointer">
our team
</p>
<p className="capitalize font-medium text-Medium_Gray cursor-pointer">
blog
</p>
</div>
)}
</div>
<span>
<a href="/" className="font-medium text-Medium_Gray">
Careers
</a>
</span>
<span>
<a href="/" className="font-medium text-Medium_Gray">
About
</a>
</span>
</div>
<div className="flex items-center justify-center flex-col space-y-4 ">
<a href="/">Login</a>
<a
href="/"
className="h-11 w-full grid place-items-center border-2 border-Medium_Gray rounded-xl text-Medium_Gray font-medium"
>
Register
</a>
</div>
</div>
</div>
)
}
export default MobileMenu
|
import { vi } from "vitest";
import userEvent from "@testing-library/user-event";
import { renderWithProviders, wrapWithRouter } from "../../utils/testUtils";
import LoginForm from "./LoginForm";
import { screen } from "@testing-library/react";
beforeAll(() => vi.clearAllMocks);
const handleLoginOnSubmit = vi.fn();
const usernameLabelText = "Username:";
const passwordLabelText = "Password:";
const expectedButtonText = "login";
const usernameInput = "astronary";
const passwordInput = "starstuff";
describe("Given a LoginForm component", () => {
describe("When it is rendered", () => {
test("Then it should show username and password input fields'", () => {
renderWithProviders(
wrapWithRouter(<LoginForm submitForm={handleLoginOnSubmit} />)
);
const usernameText = screen.getByLabelText(usernameLabelText);
const passwordText = screen.getByLabelText(passwordLabelText);
expect(usernameText).toBeInTheDocument();
expect(passwordText).toBeInTheDocument();
});
test("Then it should show a button with the text 'login''", () => {
renderWithProviders(
wrapWithRouter(<LoginForm submitForm={handleLoginOnSubmit} />)
);
const buttonText = screen.getByRole("button", {
name: expectedButtonText,
});
expect(buttonText).toBeInTheDocument();
});
describe("When it is rendered and the username and input fields are empty", () => {
test("Then it should show a disabled button with the text 'Login'", () => {
renderWithProviders(
wrapWithRouter(<LoginForm submitForm={handleLoginOnSubmit} />)
);
const buttonText = screen.getByRole("button", {
name: expectedButtonText,
});
expect(buttonText).toBeDisabled();
});
});
});
describe("When it is rendered and the username and password fields have been wrriten on", () => {
test("Then it should show an enabled button with the text 'Login'", async () => {
renderWithProviders(
wrapWithRouter(<LoginForm submitForm={handleLoginOnSubmit} />)
);
const userLabel = screen.getByLabelText(usernameLabelText);
const passwordLabel = screen.getByLabelText(passwordLabelText);
await userEvent.type(userLabel, usernameInput);
await userEvent.type(passwordLabel, passwordInput);
const loginButton = screen.getByRole("button", {
name: expectedButtonText,
});
expect(loginButton).toBeEnabled();
});
});
describe("When it is rendered and the username input field has been written on with 'astronary'", () => {
test("then the text 'astronary should be shown on the username field", async () => {
renderWithProviders(
wrapWithRouter(<LoginForm submitForm={handleLoginOnSubmit} />)
);
const userLabel = screen.getByLabelText(usernameLabelText);
await userEvent.type(userLabel, usernameInput);
expect(userLabel).toHaveValue(usernameInput);
});
});
describe("When it is rendered and the password input field has been written on with 'starstuff'", () => {
test("then the text 'starstuff should be shown on the username field", async () => {
renderWithProviders(
wrapWithRouter(<LoginForm submitForm={handleLoginOnSubmit} />)
);
const passwordLabel = screen.getByLabelText(passwordLabelText);
await userEvent.type(passwordLabel, passwordInput);
expect(passwordLabel).toHaveValue(passwordInput);
});
});
describe("When it is rendered, the username and password are correct and the button login is clicked", () => {
test("Then it should call the handLoginOnSubmit function", async () => {
renderWithProviders(
wrapWithRouter(<LoginForm submitForm={handleLoginOnSubmit} />)
);
const userLabel = screen.getByLabelText(usernameLabelText);
const passwordLabel = screen.getByLabelText(passwordLabelText);
await userEvent.type(userLabel, usernameInput);
await userEvent.type(passwordLabel, passwordInput);
const loginButton = screen.getByRole("button", {
name: expectedButtonText,
});
await userEvent.click(loginButton);
expect(handleLoginOnSubmit).toHaveBeenCalled();
});
});
});
|
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<!-- Link to Bootstrap CSS and your custom styles.css -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
<div class="container">
<h1 class="my-5">Welcome to the News Category Prediction</h1>
<form id="predictForm" action="{{ url_for('predict') }}" method="post">
<div class="form-group">
<label for="headline">Enter the Headline:</label>
<input type="text" id="headline" name="headline" class="form-control" required>
</div>
<!-- Add the loader with a Spinner -->
<button id="predictButton" type="submit" class="btn btn-primary" disabled>
<span id="loader" class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
Predict
</button>
</form>
</div>
<div class="container">
<div class="alert alert-info mt-4">
<p><strong>This is a News Category Detection on Headlines</strong></p>
<p>Developed by Gaurang Manchekar</p>
<p>A Deep Learning model based on the News Aggregator dataset detects the category:</p>
<ul>
<li>Buisness</li>
<li>Science and Technology</li>
<li>Health</li>
<li>Entertainment</li>
<li>Other</li>
</ul>
<p>It also provides a related link to the news.</p>
</div>
</div>
<!-- Add Bootstrap JavaScript link (required for some components) -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
// JavaScript to show loader when predict button is clicked
const predictForm = document.getElementById('predictForm');
const predictButton = document.getElementById('predictButton');
const loader = document.getElementById('loader');
const headlineInput = document.getElementById('headline');
headlineInput.addEventListener('input', function () {
// Enable the predict button when there is input in the headline field
predictButton.disabled = headlineInput.value.trim() === '';
});
predictForm.addEventListener('submit', function (event) {
// Show the loader when the form is submitted
loader.classList.remove('d-none');
predictButton.disabled = true;
});
</script>
</body>
</html>
|
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简易备忘录</title>
<!-- 引入自定义 CSS 样式 -->
<link rel="stylesheet" href="../../static/css/Memorandum.css">
</head>
<body>
<div id="memo-container">
<h1>备忘录</h1>
<div>
<!-- 输入新备忘录的文本框 -->
<input type="text" id="new-memo" placeholder="添加备忘录"/>
<!-- 添加备忘录按钮 -->
<button id="add-memo">添加</button>
</div>
<!-- 备忘录列表 -->
<ul id="memo-list"></ul>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
const newMemoInput = document.getElementById('new-memo');
const memoList = document.getElementById('memo-list');
const addMemoButton = document.getElementById('add-memo');
// 监听新备忘录文本框的按键事件
newMemoInput.addEventListener('keyup', function (event) {
if (event.key === 'Enter') {
addMemo(); // 如果按下回车键,调用添加备忘录函数
}
});
// 监听添加备忘录按钮的点击事件
addMemoButton.addEventListener('click', function () {
addMemo(); // 点击按钮时,调用添加备忘录函数
});
// 监听备忘录列表的点击事件
memoList.addEventListener('click', function (event) {
const target = event.target;
// 如果点击的是删除按钮
if (target.tagName === 'BUTTON') {
removeMemo(target.closest('.memo-item')); // 调用删除备忘录函数
}
// 如果点击的是备忘录文本
else if (target.tagName === 'SPAN') {
editMemo(target); // 调用编辑备忘录函数
}
// 如果点击的是复选框
else if (target.tagName === 'INPUT' && target.type === 'checkbox') {
toggleMemoChecked(target.closest('.memo-item')); // 调用切换备忘录选中状态函数
}
});
// 添加备忘录函数
function addMemo() {
const memoText = newMemoInput.value.trim(); // 获取输入的备忘录文本
if (memoText !== '') { // 如果备忘录文本不为空
// 检查是否已经存在相同内容的备忘录
const existingMemos = memoList.querySelectorAll('.memo-item span');
let isDuplicate = false;
existingMemos.forEach(function (existingMemo) {
if (existingMemo.textContent === memoText) {
isDuplicate = true;
}
});
if (!isDuplicate) {
const memoItem = document.createElement('li'); // 创建一个备忘录条目元素
memoItem.classList.add('memo-item'); // 添加备忘录条目的样式类
memoItem.innerHTML = `
<input type="checkbox">
<span>${memoText}</span>
<button>删除</button>
`; // 设置备忘录条目的 HTML 内容
memoList.appendChild(memoItem); // 将备忘录条目添加到备忘录列表中
newMemoInput.value = ''; // 清空输入框
} else {
alert('请勿添加重复的备忘录');
}
}
}
// 删除备忘录函数
function removeMemo(memoItem) {
// 弹出确认对话框
const confirmation = confirm("确定删除该项备忘录?");
if (confirmation) { // 如果用户确认删除
memoList.removeChild(memoItem); // 直接删除该备忘录条目
}
}
// 编辑备忘录函数
function editMemo(spanElement) {
const memoText = spanElement.innerText; // 获取备忘录文本内容
const memoItem = spanElement.closest('.memo-item'); // 获取备忘录项
const textareaElement = document.createElement('textarea'); // 创建一个文本框元素
textareaElement.style.width = "100%"
textareaElement.value = memoText; // 将备忘录文本内容设置为文本框的值
textareaElement.style.fontFamily = window.getComputedStyle(spanElement).fontFamily; // 保持原有字体不变
textareaElement.style.fontSize = window.getComputedStyle(spanElement).fontSize; // 保持原有字体大小不变
spanElement.replaceWith(textareaElement); // 将备忘录文本元素替换为输入框元素
textareaElement.focus(); // 让输入框获取焦点
// 根据内容调整 textarea 的高度
function adjustTextareaHeight() {
textareaElement.style.height = textareaElement.scrollHeight + 'px'; // 根据内容的高度调整 textarea 的高度
}
// 初始化时执行一次,确保初始高度正确
adjustTextareaHeight();
// 监听输入框的输入事件,实时调整高度
textareaElement.addEventListener('input', adjustTextareaHeight);
// 监听输入框的失焦事件,触发保存备忘录函数
textareaElement.addEventListener('blur', function () {
saveMemo(textareaElement, memoItem); // 将备忘录项作为参数传递给保存备忘录函数
});
// 监听输入框的键盘事件,如果按下的是 Enter 键,也触发保存备忘录函数
textareaElement.addEventListener('keyup', function (event) {
if (event.key === 'Enter') {
saveMemo(textareaElement, memoItem); // 将备忘录项作为参数传递给保存备忘录函数
}
});
}
// 保存备忘录函数
function saveMemo(inputElement, memoItem) {
const newMemoText = inputElement.value.trim(); // 获取输入框中的新备忘录文本内容
const originalMemoText = inputElement.getAttribute('data-original'); // 获取原始备忘录文本
if (newMemoText !== '') { // 如果新备忘录文本不为空
const newSpanElement = document.createElement('span'); // 创建一个新的 span 元素来显示备忘录文本
newSpanElement.textContent = newMemoText; // 设置新 span 元素的文本内容
inputElement.replaceWith(newSpanElement); // 将输入框元素替换为新创建的 span 元素
//判断文本是否进行了修改,如果文本进行了修改,则取消完成状态
if (newMemoText !== originalMemoText) {
// 获取复选框元素
const checkbox = memoItem.querySelector('input[type="checkbox"]');
//如果复选框此时是选中状态,就切换为未选中状态,同时取消下划线,未选中,则不做任何处理
if (checkbox.checked) {
console.log("已选中");
memoItem.classList.toggle('checked'); // 切换备忘录条目的选中状态
checkbox.checked = !checkbox.checked;
}
}
} else { // 如果新备忘录文本为空
const confirmation = confirm("确定删除该项备忘录?"); // 弹出确认对话框
if (confirmation) { // 如果用户确认删除
memoItem.parentElement.removeChild(memoItem); // 直接删除该项备忘录
}
}
}
// 切换备忘录选中状态函数
function toggleMemoChecked(memoItem) {
memoItem.classList.toggle('checked'); // 切换备忘录条目的选中状态
}
}
);
</script>
</body>
</html>
|
console.log("Create an array called ages that contains the following values: 3, 9, 23, 64, 2, 8, 28, 93.");
let ages = [3, 9, 23, 64, 2, 8, 28, 93]; // created new array with ages listed above
console.log(ages);
console.log("A. Programmatically subtract the value of the first element in the array from the value in the last element of the array.");
var firstElement = ages[0]; // create a variable to access the first element of an array
console.log(ages[ages.length-1] - firstElement); // subtracts the first element of the array from the last element
console.log("B. Add a new age to your array and repeat the step above to ensure it is dynamic. (works for arrays of different lengths).");
ages.push(60); // add a new age to the existing array
console.log(ages); // printing the array to the console with the new element
console.log(ages[ages.length-1] - firstElement); // subtracting the first element from the last element of the array
console.log("C. Use a loop to iterate through the array and calculate the average age.");
function averageAges(ages){ // create a function for the average ages. Takes in array as parameter
let sum = 0; // create variable for the sum of the numbers in the array
for(let i = 0; i < ages.length; i++){ // for loop will iterate through the array & add the numbers together
sum += ages[i]; // This will add the sum and whatever index we are on in the array
}
return sum; // returns the sum of the numbers
} console.log(averageAges(ages) / ages.length) // divides the sum of the numbers in the array by the length
console.log("2. Create an array called names that contains the following values: 'Sam', 'Tommy', 'Tim', 'Sally', 'Buck', 'Bob'");
let names = ['Sam', 'Tommy', 'Tim', 'Sally', 'Buck', 'Bob']; // created new array with names listed above
console.log(names); // print array of names to the console
console.log("A. Use a loop to iterate through the array and calculate the average number of letters per name.");
function lettersInName(names){ // create function called lettersInName and assign names as a parameter
let totalLetters = 0; // create variable for total number of letters in the array
for(let i = 0; i < names.length; i++){ // for loop to iterate through the array
totalLetters += names[i].length; // adds the numbers of letters in the array
return totalLetters // returns the total number of letters in the array
}
} console.log(lettersInName(names)) // print result to the console
console.log("B. Use a loop to iterate through the array again and concatenate all the names together, separated by spaces.")
for (let i = 0; i < names; i++){ // iterates through the array
} console.log(names.join(' ')) // concatenates the names and spaces them
console.log("3. How do you access the last element of any array?");
console.log("To access the last element of an array you would use array.length-1");
console.log("4. How do you access the first element of any array?");
console.log("Create a variable and assign it to the value of array.[0] and indicate in the [] which element you are accessing.");
console.log(`5. Create a new array called nameLengths.
Write a loop to iterate over the previously created names array and add the length of each name to the nameLengths array.`);
let nameLengths = [3, 5, 3, 5, 4, 3]; // creating new array called nameLengths with the lengths of the names in the previous array called names
for(let i = 0; i < names.length; i++){ // for loop to iterate through the names array
} console.log(names.concat(nameLengths)) // use .concat to concatenate the 2 arrays
console.log("6. Write a loop to iterate over the nameLengths array and calculate the sum of all the elements in the array.")
function sumOfLength(nameLengths){ // create a function for the sum of the numbers. Takes in array as parameter
let sum = 0; // create variable for the sum of the numbers in the array
for(let i = 0; i < names.length; i++){ // for loop will iterate through the array & add the numbers together
sum += nameLengths[i]; // This will add the sum and which index we are on in the array
}
return sum; // returns the sum of the numbers
} console.log(sumOfLength(nameLengths)) // prints the sum of the numbers in the array to the console
console.log(`7. Write a function that takes two parameters, word and n, as arguments and returns the word concatenated
to itself n number of times. (i.e. if I pass in 'Hello' and 3, I would expect the function to return
'HelloHelloHello').`);
function repeatGreeting(word, n){ // create function w/ 2 params
let result = ""; // create variable for the result
for (let i = 0; i < n; i++){ // for loop to repeat the word
result += word; // add result variable and the word
}
return result // return the result
}
console.log(repeatGreeting("Hello", 3)) // print outcome to the console
console.log(`8. Write a function that takes two parameters, firstName and lastName,
and returns a full name. The full name should be the first and the last name separated by a space.`)
function createFullName(firstName, lastName){ // create a function that takes 2 params
return firstName + " " + lastName; // return first & last name w/ space
} let fullName = createFullName("Danielle", "Tatro"); // create variable for fullName
console.log(fullName) // print full name to the console
console.log(`9. Write a function that takes an array of numbers and returns true
if the sum of all the numbers in the array is greater than 100.`);
function numberArray(numbers){ // create function that takes in the ages array from earlier
let sum = 0; // create variable for the sum of the numbers
for (let i = 0; i < numbers.length; i++){ // for loop to iterate through the array
sum += numbers[i]; // sum variable + numbers
}
return sum > 100; // returns true if the sum is greater than 100
} console.log(numberArray(ages)) // print function that takes in ages array from earlier
console.log("10. Write a function that takes an array of numbers and returns the average of all the elements in the array.");
function arrayElements(numbers){ // create a function that takes in numbers as a param
let sum = 0; // create variable for the sum
for(i = 0; i < numbers.length; i++){ // for loop to iterate through the array
sum += ages[i] // sum plus ages
}
return sum / ages.length // return the sum divided by the length of the ages array from earlier
}
console.log(arrayElements(ages)) // print to console
console.log(`11. Write a function that takes two arrays of numbers and returns true if the average
of the elements in the first array is greater than the average of the elements in the second array.`);
let array1 = [65, 2, 12, 19, 42] // create array1
let array2 = [16, 54, 0, 3, 5] // create array2
function returnTrue(array1, array2){ // create function that takes in array 1 and array 2
for (let i = 0; i < array1; i++){ // for loop to iterate through the array
array1 += array2[i] // adds value to array1 & array 2
} return array1 > array2; // return true if array1 is greater than array2
}
console.log(returnTrue(array1, array2)) // print result to the console
console.log(`12. Write a function called willBuyDrink that takes a boolean isHotOutside, and a number moneyInPocket,
and returns true if it is hot outside and if moneyInPocket is greater than 10.50.`)
function willBuyDrink(isHotOutside, moneyInPocket){ // create function
return isHotOutside && moneyInPocket > 10.50 // returns true if both isHotOutside and moneyInPocket are true
} console.log(willBuyDrink(true, 18.00)) // print result to the console
console.log(`13. Create a function of your own that solves a problem.
In comments, write what the function does and why you created it.`)
function homeworkDone(time, patience){ // create a function for if I will get my homework done
return time && patience // return true if both are true
} console.log(homeworkDone(true, false)) // returns false because I have no patience
|
import db_connection from "@/utils/db/connection";
const commonHeaders = {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
async function fetchAllArticles(client) {
const db = await client.db("headline_horizon");
const collection = await db.collection("articles");
const pipeline = [
{
$project: {
_id: 1,
category: 1,
sub_category: 1,
headline: 1,
date: 1,
image: { $arrayElemAt: ["$images", 0] },
article: { $arrayElemAt: ["$article", 0] },
},
},
{
$sort: { date: -1 }, // Sort by date in descending order
},
];
const all_articles = await collection
.aggregate(pipeline)
.limit(100) // Limit to 100 articles
.toArray();
return all_articles;
}
export async function GET() {
let responseBody = null;
let status = 500; // Default to internal server error status
try {
const client = await db_connection();
const all_articles = await fetchAllArticles(client);
if (all_articles.length > 0) {
responseBody = JSON.stringify(all_articles);
status = 200;
} else {
responseBody = JSON.stringify({
message: "No articles found",
code: 400,
});
status = 400;
}
} catch (err) {
console.error(err);
responseBody = JSON.stringify(err);
status = 400;
}
return new Response(responseBody, {
status,
headers: commonHeaders,
});
}
|
// Copyright(C) 2002-2003 Hugo Rumayor Montemayor, All rights reserved.
using System;
using System.Text;
using System.IO;
namespace Id3Lib
{
#region Global Fields
/// <summary>
/// Type of text used in frame
/// </summary>
public enum TextCode:byte
{
/// <summary>
/// ASCII(ISO-8859-1)
/// </summary>
ASCII = 0x00,
/// <summary>
/// Unicode with BOM
/// </summary>
UTF16 = 0x01,
/// <summary>
/// BigEndian Unicode without BOM
/// </summary>
UTF16BE = 0x02,
/// <summary>
/// Encoded Unicode
/// </summary>
UTF8 = 0x03
};
#endregion
/// <summary>
/// Manages binary to text and viceversa format conversions.
/// </summary>
public class TextBuilder
{
#region Methods
public TextBuilder() { }
public void TextBuilderInitialize() { }
public static string ReadText(byte[]frame,ref int index,TextCode code)
{
switch(code)
{
case TextCode.ASCII:
{
return ReadASCII(frame,ref index);
}
case TextCode.UTF16:
{
return ReadUTF16(frame,ref index);
}
case TextCode.UTF16BE:
{
return ReadUTF16BE(frame,ref index);
}
case TextCode.UTF8:
{
return ReadUTF8(frame,ref index);
}
default:
{
throw new InvalidFrameException("Invalid TextCode string type.");
}
}
}
public static string ReadTextEnd(byte[]frame, int index, TextCode code)
{
switch(code)
{
case TextCode.ASCII:
{
return ReadASCIIEnd(frame,index);
}
case TextCode.UTF16:
{
return ReadUTF16End(frame,index);
}
case TextCode.UTF16BE:
{
return ReadUTF16BEEnd(frame,index);
}
case TextCode.UTF8:
{
return ReadUTF8End(frame,index);
}
default:
{
throw new InvalidFrameException("Invalid TextCode string type.");
}
}
}
public static string ReadASCII(byte[] frame,ref int index)
{
string text = null;
int count = Memory.FindByte(frame,0,index);
if(count == -1)
{
throw new InvalidFrameException("Invalid ASCII string size");
}
if(count > 0)
{
Encoding encoding = Encoding.GetEncoding(1252); // Should be ASCII
text = encoding.GetString(frame,index,count);
index += count; // add the readed bytes
}
index++; // jump an end of line byte
return text;
}
public static string ReadUTF16(byte[] frame,ref int index)
{
string text = null;
UnicodeEncoding encoding = null;
bool readString = true;
if(frame[index] == 0xfe && frame[index+1] == 0xff) // Big Endian
{
encoding = new UnicodeEncoding(true,false);
}
else
{
if(frame[index] == 0xff && frame[index+1] == 0xfe) // Litle Endian
{
encoding = new UnicodeEncoding(false,false);
}
else
{
if(frame[index] == 0x00 && frame[index+1] == 0x00)
{
readString = false;
}
else
{
throw new InvalidFrameException("Invalid UTF16 string.");
}
}
}
index+=2; // skip the BOM or EOL
if(readString == true)
{
int count = Memory.FindShort(frame,0,index);
if(count == -1)
{
throw new InvalidFrameException("Invalid UTF16 string size.");
}
text = encoding.GetString(frame,index,count);
index += count; // add the readed bytes
index += 2; // skip the EOL
}
return text;
}
public static string ReadUTF16BE(byte[] frame,ref int index)
{
string text = null;
UnicodeEncoding encoding = new UnicodeEncoding(true,false);
int count = Memory.FindShort(frame,0,index);
if(count == -1)
{
throw new InvalidFrameException("Invalid UTF16BE string size");
}
if(count > 0)
{
text = encoding.GetString(frame,index,count);
index += count; // add the readed bytes
}
index+=2; // jump an end of line unicode char
return text;
}
public static string ReadUTF8(byte[] frame,ref int index)
{
string text = null;
int count = Memory.FindByte(frame,0,index);
if(count == -1)
{
throw new InvalidFrameException("Invalid UTF8 strng size");
}
if(count > 0)
{
text = UTF8Encoding.UTF8.GetString(frame,index,count);
index += count; // add the readed bytes
}
index++; // jump an end of line byte
return text;
}
public static string ReadASCIIEnd(byte[] frame, int index)
{
Encoding encoding = Encoding.GetEncoding(1252); // Should be ASCII
return encoding.GetString(frame,index,frame.Length-index);
}
public static string ReadUTF16End(byte[] frame, int index)
{
UnicodeEncoding encoding = null;
if(frame[index] == 0xfe && frame[index+1] == 0xff) // Big Endian
{
encoding = new UnicodeEncoding(true,false);
}
else
{
if(frame[index] == 0xff && frame[index+1] == 0xfe) // Litle Endian
{
encoding = new UnicodeEncoding(false,false);
}
else
{
throw new InvalidFrameException("Invalid UTF16 string.");
}
}
index+=2; // skip the BOM or EOL
return encoding.GetString(frame,index,frame.Length-index);
}
public static string ReadUTF16BEEnd(byte[] frame, int index)
{
UnicodeEncoding encoding = new UnicodeEncoding(true,false);
return encoding.GetString(frame,index,frame.Length-index);
}
public static string ReadUTF8End(byte[] frame,int index)
{
return UTF8Encoding.UTF8.GetString(frame,index,frame.Length-index);
}
// Write rutines
public static byte[] WriteText(string text, TextCode code)
{
switch(code)
{
case TextCode.ASCII:
{
return WriteASCII(text);
}
case TextCode.UTF16:
{
return WriteUTF16(text);
}
case TextCode.UTF16BE:
{
return WriteUTF16BE(text);
}
case TextCode.UTF8:
{
return WriteUTF8(text);
}
default:
{
throw new InvalidFrameException("Invalid TextCode string type.");
}
}
}
public static byte[] WriteTextEnd(string text, TextCode code)
{
switch(code)
{
case TextCode.ASCII:
{
return WriteASCIIEnd(text);
}
case TextCode.UTF16:
{
return WriteUTF16End(text);
}
case TextCode.UTF16BE:
{
return WriteUTF16BEEnd(text);
}
case TextCode.UTF8:
{
return WriteUTF8End(text);
}
default:
{
throw new InvalidFrameException("Invalid TextCode string type.");
}
}
}
public static byte[] WriteASCII(string text)
{
MemoryStream buffer = new MemoryStream();
BinaryWriter writer = new BinaryWriter(buffer);
if(text == null || text == "") //Write a null string
{
writer.Write((byte)0);
return buffer.ToArray();
}
Encoding encoding = Encoding.GetEncoding(1252); // Should be ASCII
writer.Write(encoding.GetBytes(text));
writer.Write((byte)0); //EOL
return buffer.ToArray();
}
public void writeASCII(string text)
{
WriteASCII(text);
}
public static byte[] WriteUTF16(string text)
{
MemoryStream buffer = new MemoryStream();
BinaryWriter writer = new BinaryWriter(buffer);
if(text == null || text == "") //Write a null string
{
writer.Write((ushort)0);
return buffer.ToArray();
}
writer.Write((byte)0xff); //Litle endian, we have UTF16BE for big endian
writer.Write((byte)0xfe);
UnicodeEncoding encoding = new UnicodeEncoding(false,false);
writer.Write(encoding.GetBytes(text));
writer.Write((ushort)0);
return buffer.ToArray();
}
public void writeUTF16(string text)
{
WriteUTF16(text);
}
public static byte[] WriteUTF16BE(string text)
{
MemoryStream buffer = new MemoryStream();
BinaryWriter writer = new BinaryWriter(buffer);
UnicodeEncoding encoding = new UnicodeEncoding(true,false);
if(text == null || text == "") // Write a null string
{
writer.Write((ushort)0);
return buffer.ToArray();
}
writer.Write(encoding.GetBytes(text));
writer.Write((ushort)0);
return buffer.ToArray();
}
public void writeUTF16BE(string text)
{
WriteUTF16BE(text);
}
public static byte[] WriteUTF8(string text)
{
MemoryStream buffer = new MemoryStream();
BinaryWriter writer = new BinaryWriter(buffer);
if(text == null || text == "") // Write a null string
{
writer.Write((byte)0);
return buffer.ToArray();
}
writer.Write(UTF8Encoding.UTF8.GetBytes(text));
writer.Write((byte)0);
return buffer.ToArray();
}
public void writeUTF8(string text)
{
WriteUTF8(text);
}
public static byte[] WriteASCIIEnd(string text)
{
MemoryStream buffer = new MemoryStream();
BinaryWriter writer = new BinaryWriter(buffer);
if(text == null || text == "")
{
return buffer.ToArray();
}
Encoding encoding = Encoding.GetEncoding(1252); // Should be ASCII
writer.Write(encoding.GetBytes(text));
return buffer.ToArray();
}
public void writeASCIIEnd(string text)
{
WriteASCIIEnd(text);
}
public static byte[] WriteUTF16End(string text)
{
MemoryStream buffer = new MemoryStream(text.Length+2);
BinaryWriter writer = new BinaryWriter(buffer);
if(text == null || text == "")
{
return buffer.ToArray();
}
UnicodeEncoding encoding;
writer.Write((byte)0xff); // Litle endian
writer.Write((byte)0xfe);
encoding = new UnicodeEncoding(false,false);
writer.Write(encoding.GetBytes(text));
return buffer.ToArray();
}
public void writeUTF16End(string text)
{
WriteUTF16End(text);
}
public static byte[] WriteUTF16BEEnd(string text)
{
MemoryStream buffer = new MemoryStream();
BinaryWriter writer = new BinaryWriter(buffer);
if(text == null || text == "")
{
return buffer.ToArray();
}
UnicodeEncoding encoding = new UnicodeEncoding(true,false);
writer.Write(encoding.GetBytes(text));
return buffer.ToArray();
}
public void writeUTF16BEEnd(string text)
{
WriteUTF16BEEnd(text);
}
public static byte[] WriteUTF8End(string text)
{
MemoryStream buffer = new MemoryStream();
BinaryWriter writer = new BinaryWriter(buffer);
if(text == null || text == "")
{
return buffer.ToArray();
}
writer.Write(UTF8Encoding.UTF8.GetBytes(text));
return buffer.ToArray();
}
public void writeUTF8End(string text)
{
WriteUTF8End(text);
}
#endregion
}
}
|
# the bit that exports worker profile class and uses the RVL
# an RPC stub is the thing on the client that makes a calling request and waits for the response
from .config import comms_config, default_service_config
from .utils import deserialize, GET
from .simplex_stubs import AsyncSimplexStub, CoroSimplexStub, SyncSimplexStub
from .duplex_stubs import AsyncDuplexStub, CoroDuplexStub, SyncDuplexStub
from .generic_stubs import AsyncStub, CoroStub, SyncStub
from types import SimpleNamespace
def get_ServiceStub(ip_addr='localhost', endpoint_prefix=default_service_config['endpoint_prefix'], name='', profile=None, stub_type=CoroStub, top_stub_type=object):
global count
# the attributes of the returned object
attrs = {}
# gets the profile if none are provided
if (profile == None):
url = 'http://'+str(ip_addr)+':'+str(comms_config.worker_port)+'/'+endpoint_prefix+name
_, profile_str = GET(url)
profile = deserialize(profile_str)
# once the profil is obtained, metaclass creation is left to get_ServiceStub_helper
return get_ServiceStub_helper(ip_addr, profile, stub_type, top_stub_type)
def get_ServiceStub_helper(ip_addr, profile, stub_type, top_stub_type):
attrs = {}
keys = list(profile.keys())
banned_keys = ['__call__', '__profile_flag__', '__func__', '__self__', '__get__', '__set__', '__delete__'] + dir(object())
for key in keys:
if (key in banned_keys): continue
member = profile[key]
if '__profile_flag__' in member:
# member is a profile for a ServiceNode
attrs[key] = get_ServiceStub_helper(ip_addr, member, stub_type, object)
else:
# If a member is not a profile, then it must be an RPC config, and so correspond to a callable object on the worker with no __dict__attribute
attrs[key] = stub_type(worker_ip=ip_addr, endpoint_prefix=member['endpoint_prefix']+'/', rpc_name=key)
parent_classes = (top_stub_type, )
if '__call__' in keys:
# if the profile has a __call__ attribute, than the corresponding object on the server is callable and has a __dict__ attribute, and so must be represented by an RPC stub bound to the given network coordinates
BoundStubClass = get_BoundStubClass(stub_type, ip_addr, profile['__call__'])
# this ensures the stub will inherit from a stub class that's bound to the configuration
parent_classes = (BoundStubClass, ) + parent_classes
ServiceStub = type('ServiceStub', parent_classes, attrs)
return ServiceStub()
def get_BoundStubClass(stub_type, ip_addr, configuration):
# a class for stubs that are bound to a certain RPC
class BoundStubClass(stub_type):
def __init__(self):
stub_type.__init__(self, worker_ip=ip_addr, endpoint_prefix=configuration['endpoint_prefix']+'/', rpc_name='__call__', comms_pattern=configuration['comms_pattern'])
return BoundStubClass
def get_RPC_stub(ip_addr, configuration):
comms_pattern = configuration['comms_pattern']
stub = None
if (comms_pattern == 'simplex'):
stub = CoroSimplexStub(worker_ip=ip_addr, endpoint_prefix=configuration['endpoint_prefix']+'/', rpc_name='__call__')
elif (comms_pattern == 'duplex'):
stub = CoroDuplexStub(worker_ip=ip_addr, endpoint_prefix=configuration['endpoint_prefix']+'/', rpc_name='__call__')
return stub
def get_RPC_stub_2(ip_addr, configuration):
def return_fn(*args):
return 'this is a test RPC stub'
return return_fn
def get_worker_profile(ip_addr):
url = 'http://'+str(ip_addr)+':'+str(comms_config.worker_port)+'/_get_profile'
_, profile_str = GET(url)
return deserialize(profile_str)
class RemoteWorker():
def __init__(self, profile_or_ip):
self.ip_addr = None
self.rpcs = None
profile = None
# profile_or_ip is either an ip address or a worker profile, here we test to see which one
try:
profile_or_ip['ip_addr']
# profile_or_ip has a member ip_addr, and so must be a profile
profile = profile_or_ip
except(TypeError):
# profile_or_ip is an ip address
profile = get_worker_profile(profile_or_ip)
# sets up all the rpc stubs
self.setup(profile)
def setup(self, profile):
self.ip_addr = profile['ip_addr']
self.name = profile['name']
# this will need to be a lookup on a services key to a number of service profiles
# self.setup_rpc_stubs(profile['rpcs'])
self.rpcs = get_ServiceStub(self.ip_addr, endpoint_prefix='rpcs/', name='rpcs', profile=profile['rpcs'])
for service_name in profile['services'].keys():
s = get_ServiceStub(self.ip_addr, endpoint_prefix=f'{service_name}/', name=service_name, profile=profile['services'][service_name])
setattr(self, service_name, s)
def setup_rpc_stubs(self, rpcs_descs):
rpcs = {}
for rpc_desc in rpcs_descs:
comms_pattern = rpc_desc['comms_pattern']
name = rpc_desc['name']
if (comms_pattern == 'simplex'):
rpcs[name] = CoroSimplexStub(worker_ip=self.ip_addr, rpc_name=name)
elif (comms_pattern == 'duplex'):
rpcs[name] = CoroDuplexStub(worker_ip=self.ip_addr, rpc_name=name)
else:
raise BaseException('unrecognised communication pattern:'+str(comms_pattern))
self.rpcs = SimpleNamespace(**rpcs)
|
const dogs = [
{
name: 'Snickers',
age: 2,
},
{
name: 'Hugo',
age: 8,
},
];
// read html
function makeGreen(){
const p = document.querySelector('p');
p.style.color = '#BADA55';
p.style.fontSize = '50px';
}
// regular
console.log("hello");
// interpolated
console.log('I am the first %s string!', 'meh');
// OR
let s = 'meh';
console.log(`I am the second ${s} string!`);
// styled
console.log('%c I am some styled text', 'font-size: 1rem; color: purple; background: white; text-shadow: 0px 0px 10px #171717;');
// warning
console.warn("THIS FUNCTION IS THE ISSUE");
// error
console.error("THIS FUNCTION IS THE ISSUE");
// info
console.info("I can see you");
// testing
console.assert(1 == 1, 'That is wrong'); // similar to if statment
// OR
console.assert(p.classList.contains("ouch"), "There is no 'ouch' in the p tag!");
// clearning
// console.clear();
// viewing dom elements
console.log(p);
console.dir(p);
// grouping together
dogs.forEach(dog => {
console.group(`${dog.name}`);
console.log(`This is ${dog.name}`);
console.log(`${dog.name} is ${dog.age}`);
console.log(`${dog.name} is ${dog.age * 7} dog years old`);
console.info("%c _____________", "background: red;");
console.groupEnd(`${dog.name};`);
});
// counting
console.count('Wes');
console.count('Wes');
console.count('Steve');
console.count('Wes');
//
console.count('Wes');
console.count('Wes');
console.count('Steve');
console.count('Wes');
// timing
console.time('fetch data');
fetch('https://api.github.com/users/webos')
.then(data => data.json())
.then(data => {
console.timeEnd('fetch data');
});
console.table(dogs);
|
{% extends "base.html" %}
{% load static %}
{% block page_header %}
<div class="container header-container">
<div class="row">
<div class="col"></div>
</div>
</div>
{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'css/item_detail.css' %}" />
<div class="container">
<div class="row">
<div class="col-12 col-md-6 col-lg-4 offset-lg-2">
<div class="product-image my-5">
{% if item.image %}
<a href="{{ item.image.url }}" target="_blank">
<img class="product-img" src="{{ item.image.url }}" alt="{{ item.name }}">
</a>
{% else %}
<a href="">
<img class="product-img" src="{{ MEDIA_URL }}noimage.png" alt="{{ item.name }}">
</a>
{% endif %}
</div>
</div>
<div class="col-12 col-md-6 col-lg-4">
<div class="product-details mb-5 mt-md-5">
<h2>{{ item.name }}</h2>
<hr>
<p class="price">€{{ item.price }}</p>
<small><p class="quantity">Available: {{ item.quantity }}</p></small>
<b><p class="card-text">Condition:</b> {{ item.condition }}</p>
<b><p>Seller:</b> <a href="{% url 'view_other_profile' username=item.seller.username %}">{{ item.seller.username }}</a></p>
<form class="add-to-bag-form" action="{% url 'add_to_bag' item.id %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="quantity">Quantity:</label>
<input class="form-control quantity-input" type="number" name="quantity" value="1" min="1" max="99"
data-item_id="{{ item.id }}" id="id_qty_{{ item.id }}">
</div>
<div class="buttons">
<a href="{% url 'item_list' %}" class="btn btn-secondary btn-back">Keep Shopping</a>
<input type="submit" class="btn btn-primary btn-add-to-bag" value="Add to Bag">
</div>
<input type="hidden" name="redirect_url" value="{{ request.path }}">
<div class="error-message" style="color: red;"></div>
</form>
</div>
</div>
<p>ITEM DESCRIPTION</p>
<hr>
<div class="col-lg-4 col-md-6 mb-4 description">
<p class="card-text">{{ item.description }}</p>
</div>
</div>
</div>
<!-- This script will validate the number of items beingg added to the bag-->
<script>
document.addEventListener("DOMContentLoaded", function () {
const quantityInput = document.querySelector(".quantity-input");
const errorMessage = document.querySelector(".error-message");
quantityInput.addEventListener("input", function () {
const inputQuantity = parseInt(this.value, 10);
const availableQuantity = parseInt("{{ item.quantity }}");
if (isNaN(inputQuantity) || inputQuantity < 1) {
errorMessage.textContent = "Quantity must be at least 1.";
} else if (inputQuantity > availableQuantity) {
errorMessage.textContent = `Only ${availableQuantity} available.`;
} else {
errorMessage.textContent = "";
}
});
// Prevent the form submission if quantity is invalid
const form = document.querySelector(".add-to-bag-form");
form.addEventListener("submit", function (event) {
const formQuantity = parseInt(quantityInput.value, 10);
const availableQuantity = parseInt("{{ item.quantity }}");
if (isNaN(formQuantity) || formQuantity < 1 || formQuantity > availableQuantity) {
errorMessage.textContent = "Please correct the quantity.";
event.preventDefault(); // Prevent form submission
}
});
});
</script>
{% endblock %}
|
import React from 'react'
import { connect } from 'react-redux'
import './cart-icon-styles.scss';
import {ReactComponent as ShoppingIcon} from '../../utilities/shopping-bag.svg';
import {toggleCartDropdown} from '../../redux/cart/cart.action'
import {selectCartItemCount} from '../../redux/cart/cart.selectors'
const CartIcon = ({toggleCartDropdown, itemCount}) => (
<div className="cart-icon" onClick={toggleCartDropdown}>
<ShoppingIcon className="shopping-icon"/>
<span className="item-count">{itemCount}</span>
</div>
)
const mapDispatchToProps = (dispatch) => ({
toggleCartDropdown: () => dispatch(toggleCartDropdown())
})
const mapStateToProps = (state) => ({
itemCount: selectCartItemCount(state)
})
export default connect(mapStateToProps, mapDispatchToProps)(CartIcon)
|
#' Modèle de Mélange Gaussien (GMM) en classification
#' Fonction de Classification
#'
#' @param Xtrain Variables descriptives des individus de l'échantillon d'apprentissage
#' @param Xtest Variables descriptives des individus de l'échantillon test
#' @param z Variable réponse à prédire pour les individus de l'échantillon d'apprentissage
#' @param K Le nombre de cluster
#' @param eps Le critère de convergence de l'algo EM
#'
#' @return
#' La variable réponse prédite dans le cluster k
#' Le nom du modèle
#' Les paramètres du modèles ainsi que le nombre de cluster, la proportion de mélange
#' @export
#'
#' @examples
#' require(rsample)
#'
#' # Données
#' split <- initial_split(iris, prop=.70, strata="Species")
#'
#' iris_train = training(split)
#' iris_test = testing(split)
#'
#' X_train = iris_train[,1:4]
#' y_train = iris_train[, 5]
#' X_test = iris_test[, 1:4]
#' y_test = iris_test[, 5]
#'
#' gmm = gmmClassif(Xtrain = X_train, Xtest = X_test, z = y_train, K = 3)
#'
#' # Affichage graphique
#' require(cluster)
#' clusplot(X_test, gmm$pred$z, lines=0,
#' shade=TRUE, color=TRUE,
#' labels=2, plotchar=FALSE,
#' span=TRUE, main=paste("Clusters of Iris"), dimens=c(1, 2, 3))
gmmClassif <- function(Xtrain, Xtest, z, K, eps = 10**-3) {
# Attention au nombre de cluster choisi
if (K > length(levels(x=z))) {
K = length(
x = levels(x = z)
)
}
# On estime le modèle
model <- gmmClassif.EM(
X = Xtrain, z = z, K = K, eps = eps
)
# On retourne les prédictions, les paramètres du modèle ainsi que sa
# vraissemblance
return(
list(
pred = gmmClassif.predict(
X = Xtest, model = model$theta
),
modelName = "Classification",
model = model$theta,
logML = model$logML
)
)
}
|
# workflow 101
### Github ssh-key setup
1. check your account: click on your avatar→settings→SSH and GPG keys(left sidebar)→confirmed SSH keys are empty
2. check if /.ssh folder is empty, if not delete all files inside
```jsx
rm -rf ~/.ssh/*
```
1. (optional)these 2 commands you can skip if you never set config before because these for resetting
```jsx
git config --unset-all user.email
git config --unset-all user.name
```
1. generate ssh-key on your local machine, “your_email” should be your github registration email, and hit **3 times of ENTER** on your keyboard(empty input for 3 questions)
```jsx
ssh-keygen -t rsa -b 4096 -C "your_email"
```
1. set config on your local machine
```jsx
git config --global user.email "your_email"
git config --global user.name "your_username"
```
1. copy and paste the string from the following command to the step1’s place(github’s SSH key)
```jsx
cat ~/.ssh/id_rsa.pub
```
### Contribute to Repo
1. find a folder you want to place the repo and sync your local machine with the remote repo
```jsx
git clone "SSH link"
```
2. Create a issue on the issue section on github, and **relink it on the main markdown file**, put all used screenshots of figures in DDIA to the img folder
3. my commonly used git operations:
- check if all the things up-to-date
```jsx
git pull
```
- check the status of all files, if it’s red, meaning not committed
```jsx
git status
```
- add all changes to staging area
```jsx
git add -A
```
- commit all changes to local repo, with a comment in “”
```jsx
git commit -m "your comment"
```
- push all changes to the remote repo
```jsx
git push
```
4. when you want to quote the images you uploaded in the img folder, remember to change the DDIA-notes/**blob**/main/ in the link to DDIA-notes/**raw**/main/ after directly copying from browser.
|
import { Link } from "react-scroll";
import { LayoutSectionInitial } from "../../shared/layouts/LayoutSectionInitial";
import { Box, Button, Container, Divider, Typography } from "@mui/material";
import { useState } from "react";
import { ScrollRestoration } from "react-router-dom";
const backgroundHome =
require("../../shared/assets/images/backgroundPageHome.webp") as string;
export const StructureLifo: React.FC = () => {
const [arrayPilha, setArrayPilha] = useState<number[]>([]);
const handleAddArrayPilha = () => {
if (arrayPilha.length <= 6) {
setArrayPilha((prev) => [...prev, prev.length + 1 - 1]);
}
};
const handleRemoveArrayPilha = () => {
const newArray = [...arrayPilha];
newArray.pop();
setArrayPilha(newArray);
};
return (
<>
<ScrollRestoration />
<LayoutSectionInitial
background={backgroundHome}
title="Estrutura de dados de Pilha"
subTitle="Entenda estrutura de dados de forma Visual "
button={
<Link to="structureLifo" smooth={true} duration={500}>
<Button variant="contained" size="medium" href="">
Leia mais
</Button>
</Link>
}
/>
<Box sx={{ my: "20px" }} id="structureLifo">
<Container>
<Typography
component="h2"
sx={{ textAlign: "center", fontWeight: "bold", my: "10px" }}
>
Estrutura de Dados de Pilha
</Typography>
<Typography paragraph>
Durante meus estudos sobre estruturas de dados, surgiu a ideia de
representar visualmente a estrutura de dados de uma pilha. Nesta
seção, vou explicar o funcionamento dessa estrutura, e em seguida,
você poderá visualizá-la de forma gráfica.
</Typography>
<Typography paragraph>
Uma pilha é uma coleção ordenada de itens que obedece ao princípio
LIFO (Last In First Out, isto é, o último a entrar é o primeiro a
sair). A adição de novos itens ou a remoção de itens existentes
ocorrem na mesma extremidade. A extremidade da pilha é conhecida
como topo, enquanto o lado oposto é conhecido como base. Os
elementos mais novos ficam próximos ao topo, e os elementos mais
antigos estão próximos da base. Temos vários exemplos de pilhas na
vida real, por exemplo, uma pilha de livros, ou uma pilha de
bandejas em uma lanchonete.
</Typography>
<Typography paragraph>
Vamos criar nossa estrutura de Pilha baseada em Array, e a linguagem
escolhida será o JavaScript. Para isso, utilizaremos os métodos da
classe Array. A seguir, proporcionarei uma breve explicação sobre os
métodos utilizados.
</Typography>
<Divider />
<Typography component="h3" sx={{ fontWeight: "bold" }}>
Inserir elementos na pilha
</Typography>
<Typography paragraph>
O primeiro método que vamos usar é o método push, responsável pela
adição de novos elementos na pilha, com um detalhe muito importante:
só podemos adicionar novos itens no topo da pilha, isto é, no final
dela. O método push é representado assim:
</Typography>
<Typography paragraph sx={{ fontWeight: "bold" }}>
const pilha = [];
</Typography>
<Typography paragraph sx={{ fontWeight: "bold" }}>
pilha.push("Primeiro valor inserido")
</Typography>
<Typography paragraph sx={{ fontWeight: "bold" }}>
pilha.push("Segundo valor inserido")
</Typography>
<Typography paragraph sx={{ fontWeight: "bold" }}>
console.log(pilha)
</Typography>
<Typography paragraph sx={{ fontWeight: "bold" }}>
//saída: [0:"Primeiro valor inserido",1:"Segundo valor inserido"];
</Typography>
<Divider />
<Typography component="h3" sx={{ fontWeight: "bold" }}>
Remover elementos da pilha
</Typography>
<Typography paragraph>
O método pop é responsável pela remoção de itens da pilha. Como a
pilha utiliza o princípio LIFO, o último item adicionado é aquele
que será removido. Por esse motivo, podemos usar o método pop da
classe Array.
</Typography>
<Typography paragraph sx={{ fontWeight: "bold" }}>
const pilha = ["Primeiro valor inserido", "Segundo valor inserido"];
</Typography>
<Typography paragraph sx={{ fontWeight: "bold" }}>
pilha.pop()
</Typography>
<Typography paragraph sx={{ fontWeight: "bold" }}>
console.log(pilha)
</Typography>
<Typography paragraph sx={{ fontWeight: "bold" }}>
//saída: [0:primeiro valor inserido];
</Typography>
</Container>
</Box>
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
minHeight: "80vh",
}}
>
<Typography sx={{ textAlign: "center", fontWeight: "bold" }}>
Entenda de forma visual o funcionamento desta estrutura
</Typography>
<Box
sx={{
minHeight: "50vh",
display: "flex",
justifyContent: "end",
flexDirection: "column",
my: "5px",
}}
>
{arrayPilha
?.slice()
.reverse()
.map((item, id) => {
return (
<Container
key={id}
sx={{ display: "flex", flexDirection: "column" }}
>
<Box
sx={{
background: "blue",
width: "50px",
borderRadius: "5px",
my: "5px",
display: "flex",
flexDirection: "column-reverse",
}}
>
<Typography color="secondary" sx={{ textAlign: "center" }}>
{item}
</Typography>
</Box>
</Container>
);
})}
</Box>
<Box>
<Button variant="contained" onClick={() => handleAddArrayPilha()}>
Inserir{" "}
</Button>
<Button
variant="contained"
onClick={() => handleRemoveArrayPilha()}
sx={{ mx: "5px" }}
>
Remover
</Button>
</Box>
</Box>
</>
);
};
|
import "./App.css";
import Headers from "./components/layout/Header";
import Footer from "./components/layout/Footer";
import Home from "./components/Home";
import { Route, BrowserRouter as Router, Routes } from "react-router-dom";
import { HelmetProvider } from "react-helmet-async";
import {ToastContainer} from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css';
import ProductDetail from "./components/products/ProductDetail";
import ProductSearch from "./components/products/ProductSearch";
import Login from "./components/user/Login";
import Register from "./components/user/Register";
import { useEffect, useState } from "react";
import store from "./store";
import { loadUser } from "./actions/userAction";
import Profile from "./components/user/Profile";
import ProtectedRoute from "./components/route/ProtectedRoute";
import UpdateProfile from "./components/user/UpdateProfile";
import UpdatePassword from "./components/user/UpdatePassword";
import ForgotPassword from "./components/user/Forgotpassword";
import ResetPassword from "./components/user/ResetPassword";
import Cart from "./components/cart/Cart";
import Shipping from "./components/cart/Shipping";
import ConfirmOrder from "./components/cart/ConfirmOrder";
import Payment from "./components/cart/Payment";
import axios from 'axios'
import { Elements } from "@stripe/react-stripe-js";
import { loadStripe } from "@stripe/stripe-js";
import OrderSuccess from "./components/cart/OrderSuccess";
import UserOrders from "./components/order/UserOrders";
import OrderDetail from "./components/order/OrderDetail";
function App() {
const [stripeApiKey,setstripeApiKey]=useState('')
useEffect(()=>{
store.dispatch(loadUser)
async function getStripeApiKey(){
const{data}=await axios.get('/api/v1/stripeapi')
setstripeApiKey(data.stripeApiKey)
}
getStripeApiKey()
},[])
return (
<Router>
<div>
<HelmetProvider>
<Headers />
<div class="container container-fluid">
<ToastContainer/>
<Routes>
<Route path='/' element={<Home />}/>
<Route path='/search/:keyword' element={<ProductSearch/>}/>
<Route path='/product/:id' element={<ProductDetail/>}/>
<Route path='/login' element={<Login/>}/>
<Route path='/register' element={<Register/>}/>
<Route path='/myprofile' element={<ProtectedRoute><Profile/></ProtectedRoute>}/>
<Route path='/myprofile/update' element={<ProtectedRoute><UpdateProfile/></ProtectedRoute>}/>
<Route path='/myprofile/update/password' element={<ProtectedRoute><UpdatePassword/></ProtectedRoute>}/>
<Route path='/password/forgot' element={<ForgotPassword/>}/>
<Route path='/password/reset/:token' element={<ResetPassword/>}/>
<Route path='/cart' element={<Cart/>}/>
<Route path='/shipping' element={<ProtectedRoute><Shipping/></ProtectedRoute>}/>
<Route path='/order/confirm' element={<ProtectedRoute><ConfirmOrder/></ProtectedRoute>}/>
<Route path='/order/success' element={<ProtectedRoute><OrderSuccess/></ProtectedRoute>}/>
<Route path='/order/:id' element={<ProtectedRoute><OrderDetail/></ProtectedRoute>}/>
<Route path='/orders' element={<ProtectedRoute><UserOrders/></ProtectedRoute>}/>
{stripeApiKey&&
<Route path='/payment' element={<ProtectedRoute><Elements stripe={loadStripe(stripeApiKey)}><Payment/></Elements></ProtectedRoute>}/>
}
</Routes>
</div>
<Footer />
</HelmetProvider>
</div>
</Router>
);
}
export default App;
|
package com.reserve.restaurantservice.dto;
import com.reserve.restaurantservice.entities.RestaurantLocation;
import com.reserve.restaurantservice.entities.RestaurantType;
import javax.persistence.Id;
import java.util.HashSet;
import java.util.Set;
public class RestaurantDto {
@Id
private Integer restaurantId;
private String restaurantName;
private String restaurantMail;
private String restaurantContactNumber;
private Set<RestaurantType> restaurantCusineType = new HashSet<>();
private String description;
// private List<RestaurantRating> rating;
private Integer approxForTwo;
private String features;
// private List<RestaurantTable> restaurantTable = new ArrayList<>();
private String tag;
private Double ratingAverage = 0.0;
private Integer reviewCount = 0;
private RestaurantLocation restaurantLocation;
private String fullAddress;
// private RestaurantManager restaurantManager;
private String timings;
private String tableCustomization;
public Integer getRestaurantId() {
return restaurantId;
}
public void setRestaurantId(Integer restaurantId) {
this.restaurantId = restaurantId;
}
public String getRestaurantName() {
return restaurantName;
}
public void setRestaurantName(String restaurantName) {
this.restaurantName = restaurantName;
}
public String getRestaurantMail() {
return restaurantMail;
}
public void setRestaurantMail(String restaurantMail) {
this.restaurantMail = restaurantMail;
}
public String getRestaurantContactNumber() {
return restaurantContactNumber;
}
public void setRestaurantContactNumber(String restaurantContactNumber) {
this.restaurantContactNumber = restaurantContactNumber;
}
public Set<RestaurantType> getRestaurantCusineType() {
return restaurantCusineType;
}
public void setRestaurantCusineType(Set<RestaurantType> restaurantCusineType) {
this.restaurantCusineType = restaurantCusineType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getApproxForTwo() {
return approxForTwo;
}
public void setApproxForTwo(Integer approxForTwo) {
this.approxForTwo = approxForTwo;
}
public String getFeatures() {
return features;
}
public void setFeatures(String features) {
this.features = features;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public Double getRatingAverage() {
return ratingAverage;
}
public void setRatingAverage(Double ratingAverage) {
this.ratingAverage = ratingAverage;
}
public Integer getReviewCount() {
return reviewCount;
}
public void setReviewCount(Integer reviewCount) {
this.reviewCount = reviewCount;
}
public RestaurantLocation getRestaurantLocation() {
return restaurantLocation;
}
public void setRestaurantLocation(RestaurantLocation restaurantLocation) {
this.restaurantLocation = restaurantLocation;
}
public String getFullAddress() {
return fullAddress;
}
public void setFullAddress(String fullAddress) {
this.fullAddress = fullAddress;
}
public String getTimings() {
return timings;
}
public void setTimings(String timings) {
this.timings = timings;
}
public String getTableCustomization() {
return tableCustomization;
}
public void setTableCustomization(String tableCustomization) {
this.tableCustomization = tableCustomization;
}
}
|
Kubernetes manages pod-to-pod communications through a combination of network plugins, services, and DNS resolution. Here's how pod-to-pod communication works in Kubernetes:
1.Pods and IP Addresses:
Each pod in a Kubernetes cluster is assigned a unique IP address. These IP addresses are routable within the cluster's network.
Pods within the same node can communicate directly using their assigned IP addresses.
Networking Plugins:
2.Kubernetes uses network plugins (CNI plugins) to manage pod networking.
Popular plugins include Calico, Cilium, Flannel, and Weave. These plugins enable pod-to-pod communication by setting up network policies and routes.
The chosen CNI plugin helps determine how pods can communicate with each other across nodes.
3.Network Policies:
Network policies are used to define rules that control which pods are allowed to communicate with each other.
Network policies can restrict or allow traffic based on pod labels, namespaces, and port numbers.
4.Pod DNS Resolution:
Kubernetes provides built-in DNS resolution to help pods discover and communicate with each other by hostname.
Pods can reach other pods using their hostname, which follows the pattern: <pod-name>.<namespace>.svc.cluster.local.
For example, a pod in the myapp namespace can communicate with a pod named backend using backend.myapp.svc.cluster.local.
5.Service Abstraction:
Kubernetes Services provide an abstraction for networking and load balancing.
A Service exposes a stable DNS name and IP, enabling communication with a set of pods (often referred to as the "backend").
The Service selects the pods based on labels.
6.Cluster Network:
Pods on different nodes communicate through the cluster network.
The network plugin and the Kubernetes control plane configure the necessary routes and rules to ensure network connectivity between pods on different nodes.
7.Ingress Controllers:
Ingress controllers are used to manage external access to services and pods within the cluster.
They provide traffic routing, load balancing, and SSL termination for external access.
8.Load Balancing:
Some cloud providers offer built-in load balancing services that can be used to distribute traffic to pods.
Kubernetes can integrate with these load balancers to expose services to the external world.
9.Firewalls and Network Policies:
Kubernetes may integrate with cloud provider firewalls or third-party security tools to implement network policies.
These policies can add an extra layer of security and access control to pod-to-pod communication.
In summary, Kubernetes handles pod-to-pod communication through the assignment of unique IP addresses, network plugins, network policies, DNS resolution, and services. This architecture ensures that pods can communicate both within the same node and across nodes in a secure and efficient manner.
|
<!DOCTYPE html>
<html lang="ru">
<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>studio</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/modern-normalize/1.1.0/modern-normalize.min.css"
integrity="sha512-wpPYUAdjBVSE4KJnH1VR1HeZfpl1ub8YT/NKx4PuQ5NmX2tKuGu6U/JRp5y+Y8XG2tV+wKQpNHVUX03MfMFn9Q=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
<link
href="https://fonts.googleapis.com/css2?family=Raleway:wght@700&family=Roboto:wght@400;500;700;900&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="css/main.min.css" />
</head>
<body>
<header class="header">
<div class="container header-container">
<a class="logo-link link logo-header" href=""
>Web<span class="logo-header-dark-wrap">Studio</span>
</a>
<nav class="main-nav">
<ul class="list main-nav_list">
<li class="main-nav_item">
<a
class="main-nav_link current link header__link"
href="index.html"
rel="index"
>Студия</a
>
</li>
<li class="main-nav_item">
<a class="main-nav_link link header__link" href="portfolio.html"
>Портфолио</a
>
</li>
<li class="main-nav_item">
<a class="main-nav_link link header__link" href="#contacts"
>Контакты</a
>
</li>
</ul>
</nav>
<ul class="list main-nav_list-connect">
<li class="main-nav_item-connect">
<a
class="main-nav_link link contact-link item-connect__link"
href="mail-to"
>
<svg class="list-connect_contacts-icon" width="16" height="12">
<use href="./image/icons.svg#icon-envelope"></use>
</svg>
[email protected]</a
>
</li>
<li class="main-nav_item-connect">
<a
class="main-nav_link link contact-link item-connect__link"
id="contacts"
href="tel"
>
<svg class="list-connect_contacts-icon" width="10" height="14">
<use href="./image/icons.svg#icon-smartphone"></use>
</svg>
+38 096 111 11 11</a
>
</li>
</ul>
<!-- MOBILIE-MENU -->
<button type="button" class="burger-button" data-menu-open>
<svg class="burger-icon-icon">
<use href="./image/icons.svg#burger-icon"></use>
</svg>
</button>
<!-- END-MOBILIE-MENU-->
<div class="mobilie-menu" data-menu>
<button type="button" class="close-burger-button" data-menu-close>
<svg class="close-burger-icon">
<use href="./image/icons.svg#close-burger-icon"></use>
</svg>
</button>
<div class="mobilie-container">
<div class="mobilie">
<ul class="mobilie-menu_nav-list list">
<li class="mobilie-menu__nav-item">
<a
class="mobilie-menu__nav-link mobilie-menu__nav-link--current"
href="./index.html"
>Студия</a
>
</li>
<li class="mobilie-menu__nav-item">
<a class="mobilie-menu__nav-link" href="./portfolio.html"
>Портфолио</a
>
</li>
<li class="mobilie-menu__nav-item">
<a class="mobilie-menu__nav-link" href="#">Контакты</a>
</li>
</ul>
</div>
<div class="mobilie_contacts">
<ul class="mobilie-menu__contacts-list list">
<li class="mobilie-menu__contacts-item">
<a
class="mobilie-menu__contacts-link"
href="tel:+380961111111"
>+38 096 111 11 11</a
>
</li>
<li class="mobilie-menu_contacts-item">
<a
class="mobilie-menu_contacts-link--mail mobilie-menu_contacts-link link"
href="mailto:[email protected]"
>[email protected]</a
>
</li>
</ul>
<ul class="social-mobilie_list list">
<li></li>
<li class="social-mobilie__item">
<a class="social-mobilie__link" href="#">Instagram</a>
</li>
<li class="social-mobilie__item">
<a class="social-mobilie__link" href="#">Twitter</a>
</li>
<li class="social-mobilie__item">
<a class="social-mobilie__link" href="#">Facebook</a>
</li>
<li class="social-mobilie__item">
<a class="social-mobilie__link" href="#">Linkedin</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</header>
<!-- HERO -->
<section class="hero">
<div class="container">
<h1 class="hero-heading">
ЭФФЕКТИВНЫЕ РЕШЕНИЯ <br />ДЛЯ ВАШЕГО БИЗНЕСА
</h1>
<button type="button" data-modal-open class="hero-button">
Заказать услугу
</button>
</div>
</section>
<!-- BENEFITS-SECTON -->
<section class="section">
<div class="container">
<ul class="benefits-list list benefits-section">
<li class="benefits-item">
<div class="benefits-icons">
<svg class="benefits-icon" width="70" height="70">
<use href="./image/icons.svg#icon-antenna"></use>
</svg>
</div>
<h3 class="benefits-title">ВНИМАНИЕ К ДЕТАЛЯМ</h3>
<p class="benefits-text">
Идейные соображения,а также начало повседневной работы по
формированию позиции.
</p>
</li>
<li class="benefits-item">
<div class="benefits-icons">
<svg class="benefits-icon" width="70" height="70">
<use href="./image/icons.svg#icon-clock"></use>
</svg>
</div>
<h3 class="benefits-title">ПУНКТУАЛЬНОСТЬ</h3>
<p class="benefits-text">
Задача организации, в особенности же рамки и место обучения кадров
влечет за собой.
</p>
</li>
<li class="benefits-item">
<div class="benefits-icons">
<svg class="benefits-icon" width="70" height="70">
<use href="./image/icons.svg#icon-diagram"></use>
</svg>
</div>
<h3 class="benefits-title">ПЛАНИРОВАНИЕ</h3>
<p class="benefits-text">
Равным образом консультация с широким активом в значительной
степени обуславливает.
</p>
</li>
<li class="benefits-item">
<div class="benefits-icons">
<svg class="benefits-icon" width="70" height="70">
<use href="./image/icons.svg#icon-astronaut"></use>
</svg>
</div>
<h3 class="benefits-title">СОВРЕМЕНЫЕ ТЕХНОЛОГИИ</h3>
<p class="benefits-text">
Значимость этих проблем настолько очевидна , что реализация
плановых заданий.
</p>
</li>
</ul>
</div>
</section>
<!-- AUXILIARY-SECTION -->
<section class="auxiliary-section">
<div class="container">
<h2 class="heading-title">Чем занимаемся</h2>
<ul class="list benefits-section">
<li class="auxiliary-item">
<picture>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/write-code-desktop-min.webp.webp 1x,
./image/desktop/write-code-desktop-min.webp.webp 2x
"
/>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/write-code-desktop-min.jpg.jpg 1x,
./image/desktop/write-code-desktop-min.jpg.jpg 2x
"
/>
<img src="#" alt="пишет-код" width="370" height="294" />
</picture>
<div class="auxiliary-wrap">
<p class="auxiliary-text">ДЕСКТОПНЫЕ ПРИЛОЖЕНИЯ</p>
</div>
</li>
<li class="auxiliary-item">
<picture>
<source
srcset="
./image/desktop/adaptive-layout-desktop-min.webp.webp 1x,
./image/desktop/adaptive-layout-desktop-min.webp.webp 2x
"
/>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/adaptive-layout-desktop-min.jpg.jpg 1x,
./image/desktop/adaptive-layout-desktop-min.jpg.jpg 2x
"
/>
<img src="#" alt="адаптивная-вёрстка" width="370" height="294" />
</picture>
<div class="auxiliary-wrap">
<p class="auxiliary-text">МОБИЛЬНЫЕ ПРИЛОЖЕНИЯ</p>
</div>
</li>
<li class="auxiliary-item">
<picture
><source
srcset="
./image/desktop/demonstration-desktop-min.webp.webp 1x,
./image/desktop/demonstration-desktop-min.webp.webp 2x
"
/>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/demonstration-desktop-min.jpg.jpg 1x,
./image/desktop/demonstration-desktop-min.jpg.jpg 2x
"
/>
<img src="#" alt="демонстрация" width="370" height="294" />
</picture>
<div class="auxiliary-wrap">
<p class="auxiliary-text">ДИЗАЙНЕРСКИЕ РЕШЕНИЯ</p>
</div>
</li>
</ul>
</div>
</section>
<section class="section team-section">
<div class="container team-container">
<h2 class="heading-title">Наша команда</h2>
<ul class="list team_list">
<li class="team-item">
<picture>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/igor-desktop-min.webp.webp 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/ihor-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 768px)"
srcset="
./image/tablet/igor-tablet-min.webp.webp 1x,
./image/tablet/[email protected] 2x
"
/>
<source
media="(min-width: 768px)"
srcset="
./image/desktop/ihor-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 280px)"
srcset="
./image/mobilie/ihor-mobilie-min.webp.webp 1x,
./image/mobilie/[email protected] 2x
"
/>
<source
media="(min-width: 280px)"
srcset="
./image/desktop/ihor-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<img src="#" alt="игорь-демьяненко" />
</picture>
<div class="team-item-wrap">
<h3 class="team-title">Игорь Демьяненко</h3>
<p class="team-text">Product Designer</p>
<ul class="social-list">
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-twitter"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-item">
<picture>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/olga-desktop-min.webp.webp 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/olga-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 768px)"
srcset="
./image/tablet/olga-tablet-min.webp.webp 1x,
./image/tablet/[email protected] 2x
"
/>
<source
media="(min-width: 768px)"
srcset="
./image/desktop/olga-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 280px)"
srcset="
./image/mobilie/olga-mobilie-min.webp.webp 1x,
./image/mobilie/[email protected] 2x
"
/>
<source
media="(min-width: 280px)"
srcset="
./image/desktop/-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<img src="#" alt="ольга-репина" />
</picture>
<div class="team-item-wrap">
<h3 class="team-title">Ольга Репина</h3>
<p class="team-text">Frontend Developer</p>
<ul class="team-social social-list">
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-twitter"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-item">
<picture>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/nikolai-desktop-min.webp.webp 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/nikolai-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 768px)"
srcset="
./image/tablet/nikolai-tablet-min.webp.webp 1x,
./image/tablet/[email protected] 2x
"
/>
<source
media="(min-width: 768px)"
srcset="
./image/desktop/nikolai-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 280px)"
srcset="
./image/mobilie/nikolai-mobilie-min.webp.webp 1x,
./image/mobilie/[email protected] 2x
"
/>
<source
media="(min-width: 280px)"
srcset="
./image/desktop/nikolai-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<img src="#" alt="николай-тарасов" />
</picture>
<div class="team-item-wrap">
<h3 class="team-title">Николай Тарасов</h3>
<p class="team-text">Marketing</p>
<ul class="team-social social-list">
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use
class="icon"
href="./image/icons.svg#icon-twitter"
></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
<li class="team-item">
<picture>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/michail-desktop-min.webp.webp 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 1200px)"
srcset="
./image/desktop/michail-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 768px)"
srcset="
./image/tablet/michail-tablet-min.webp.webp 1x,
./image/tablet/[email protected] 2x
"
/>
<source
media="(min-width: 768px)"
srcset="
./image/desktop/michail-desktop-min.jpg.jpg 1x,
./image/desktop/[email protected] 2x
"
/>
<source
media="(min-width: 280px)"
srcset="
./image/mobilie/michail-mobilie-min.webp.webp 1x,
./image/mobilie/[email protected] 2x
"
/>
<img src="#" alt="михаил-ермаков" />
</picture>
<div class="team-item-wrap">
<h3 class="team-title">Михаил Ермаков</h3>
<p class="team-text">UI Designer</p>
<ul class="team-social social-list">
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-twitter"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="social-item">
<a href="" class="social-links">
<svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</li>
</ul>
</div>
</section>
<!-- CLIENTS-SECTION -->
<section class="section">
<div class="container">
<h2 class="clients-title">Постоянные клиенты</h2>
<ul class="clients-list list">
<li class="clients-item">
<a href="" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./image/icons.svg#icon-logo-1"></use>
</svg>
</a>
</li>
<li class="clients-item">
<a href="" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./image/icons.svg#icon-logo-2"></use>
</svg>
</a>
</li>
<li class="clients-item">
<a href="" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./image/icons.svg#icon-logo-3"></use>
</svg>
</a>
</li>
<li class="clients-item">
<a href="" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./image/icons.svg#icon-logo-4"></use>
</svg>
</a>
</li>
<li class="clients-item">
<a href="" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./image/icons.svg#icon-logo-5"></use>
</svg>
</a>
</li>
<li class="clients-item">
<a href="" class="clients-link">
<svg class="clients-icon" width="106" height="60">
<use href="./image/icons.svg#icon-logo-6"></use>
</svg>
</a>
</li>
</ul>
</div>
</section>
<!-- FOOTER -->
<footer class="footer-container">
<div class="container common-container">
<div class="footer-container-wrapp">
<div class="footer-address">
<a class="footer-logo logo-link link" href="#"
>Web<span class="logo-header-light-wrap">Studio</span>
</a>
<div class="footer-address-connect">
<address class="footer-address-link">
г. Киев, пр-т Леси Укранки, 26
</address>
<ul class="list footer-list">
<li class="footer-item">
<a
class="footer-address_footer-address_contact-link link"
href="[email protected]"
>[email protected]</a
>
</li>
<li class="footer-item">
<a
class="footer-address_footer-address_contact-link link"
href="+380991111111"
>+38 099 111 11 11</a
>
</li>
</ul>
</div>
</div>
<div class="footer-social">
<h3 class="footer-social-title">ПРИСОЕДИНЯЙТЕСЬ</h3>
<ul class="footer-social-list list">
<li class="footer-social-item">
<a href="" class="social-links social-links-icon"
><svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-instagram"></use>
</svg>
</a>
</li>
<li class="footer-social-item">
<a href="" class="social-links social-links-icon"
><svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-twitter"></use>
</svg>
</a>
</li>
<li class="footer-social-item">
<a href="" class="social-links social-links-icon"
><svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-facebook"></use>
</svg>
</a>
</li>
<li class="footer-social-item">
<a href="" class="social-links social-links-icon"
><svg class="social-icon" width="20" height="20">
<use href="./image/icons.svg#icon-linkedin"></use>
</svg>
</a>
</li>
</ul>
</div>
</div>
<!-- FORM-MODAL -->
<form class="footer-form" action="#">
<p class="footer-form-title">Подпишитесь на рассылку</p>
<div class="footer-form-container">
<label class="footer-label">
<input
class="footer-form-input"
type="email"
name="email"
placeholder="E-mail"
/>
</label>
<button class="footer-form-button" type="submit">
Подписаться
<svg class="modal-form-button-icon" width="24" height="24">
<use href="./image/icons.svg#icon-send"></use>
</svg>
</button>
</div>
</form>
</div>
</footer>
<div class="backdrop is-hidden" data-modal>
<div class="modal">
<button type="button" data-modal-close class="modal-button">
<svg width="18" height="18">
<use href="./image/icons.svg#icon-close"></use>
</svg>
</button>
<form class="modal-form" action="#">
<p class="modal-form-title">
Оставьте свои данные, мы вам перезвоним
</p>
<label class="modal-form-field"
>Имя
<span class="form-input-wrap">
<input
class="modal-form-input"
type="text"
name="user-name"
minlength="2"
pattern="[a-zA-Zа-яёА-ЯЁ]+"
title="Допустимы только знаки кириллицы и латиницы"
/>
<svg class="modal-form-input-icon" width="12" height="12">
<use href="./image/icons.svg#icon-person"></use>
</svg>
</span>
</label>
<label class="modal-form-field"
>Телефон
<span class="form-input-wrap">
<input
class="modal-form-input"
type="tel"
name="user-phone"
minlength="12"
pattern="[0-9]{12}"
title="3803336669"
/>
<svg class="modal-form-input-icon" width="18" height="18">
<use href="./image/icons.svg#icon-phone-black"></use>
</svg>
</span>
</label>
<label class="modal-form-field"
>Почта
<span class="form-input-wrap">
<input class="modal-form-input" type="tel" name="user-mail" />
<svg class="modal-form-input-icon" width="18" height="18">
<use href="./image/icons.svg#icon-email"></use>
</svg>
</span>
</label>
<label class="modal-form-field-comment"
>Комментарий
<textarea
class="modal-form-message"
name="user-message"
placeholder="Введите текст"
></textarea>
</label>
<input
class="modal-form-checkbox visually-hidden"
type="checkbox"
id="accept-policy"
/>
<label class="modal-form-label-checkbox" for="accept-policy"
>Соглашаюсь с рассылкой и принимаю
<a class="checkbox-link" href="#">Условия договора</a>
</label>
<button class="modal-form-button" type="submit">Отправить</button>
</form>
</div>
</div>
<script src="./js/modal.js"></script>
<script src="./js/menu.js"></script>
</body>
</html>
|
<div class="container">
<div class="card-index">
<div class="card">
<label for="tool">What are you looking for?</p>
<%= form_tag tools_path, method: :get do %>
<%= text_field_tag :query,
params[:query],
class: "form-group",
placeholder: "Find a tool"
%>
</div>
<div class="card">
<label for="from">Starting date</p>
<%= date_field_tag :from,
params[:from],
class: "form-group",
placeholder: "From"
%>
</div>
<div class="card">
<label for="to">End date</p>
<%= date_field_tag :to,
params[:to],
class: "form-group",
placeholder: "to"
%>
</div>
</div>
<!-- <div class="card">
<label for="calendar">Check availabilities (from / to)</label>
<div class="form-group" id="datepicker">
<input type="date" name="from" />
<input type="date" name="to" />
</div>
</div> -->
<div class="card-index">
<div class="search-button">
<%= submit_tag "Search", class: "btn btn-flat" %>
</div>
<% end %>
</div>
</div>
<br>
<div class="container d-flex justify-content-between" background-color="none">
<div class="cards">
<% @tools.each do |tool| %>
<div class="card-product">
<img src="<%= tool.photo.attached? ? cl_image_path(tool.photo.key) : asset_path('hammer.jpeg')%>" />
<div class="card-product-infos d-flex justify-content-between">
<div>
<% user = User.find(tool.user_id) %>
<h2><%= link_to "Type: #{tool.tool_type}", tool_path(tool), class:"name-link"%></h2>
<p>Brand: <%= tool.name%></p>
<p>Address: <%= user.address %></p>
</div>
<div class= "d-flex align-items-center">
<h2 class= "padd-left"><strong><%= tool.price %>€</strong></h2>
</div>
</div>
</div>
<% end %>
</div>
<div class="map-users"
data-controller="mapbox"
data-mapbox-markers-value="<%= @markers.to_json %>"
data-mapbox-api-key-value="<%= ENV['MAPBOX_API_KEY'] %>"></div>
</div>
|
package chapter12_Enum.listing11;
// Use static import to bring sqrt() and pow() into view.
//import static java.lang.Math.sqrt; //static import
//import static java.lang.Math.pow; //static import
import static java.lang.Math.*; //static import
import static java.lang.System.out; //static import
class Quadraticv1 {
public static void main(String args[]) {
// a, b, and c represent the coefficients in the
// quadratic equation: ax2 + bx + c = 0
double a, b, c, x;
// Solve 4x2 + x -3 = 0 for x.
a = 4;
b = 1;
c = -3;
// Find first solution.
x = (-b + sqrt(pow(b, 2) - 4 * a * c)) / (2 * a);
System.out.println("First solution: " + x);
// Find second solution.
x = (-b - sqrt(pow(b, 2) - 4 * a * c)) / (2 * a);
System.out.println("Second solution: " + x);
out.println("Импортировав System.out, имя out можно использовать непосредственно");
}
}
|
<template>
<div class="container">
<div>
<ticker :ticker="getTickerFromAssociationsArray(all_associations)" :up="getUpOrDown(all_associations)"></ticker>
<br/>
<p>
<span>Select the number of months to display:
<select v-model="history">
<option value=0>ALL</option>
<option>12</option>
<option>24</option>
<option>36</option>
<option>48</option>
</select>
</span>
</p>
<br/>
<bar-chart v-if="loaded" :key="history" :chart-data="trimArray(all_associations)" :chart-labels="trimArray(this.getDatesFromArray(this.message))"></bar-chart>
<line-chart v-if="loaded" :key="1+history" :chart-data="trimArray(getAssociationDifferences(all_associations))" :chart-labels="trimArray(this.getDatesFromArray(this.message))"></line-chart>
<br/>
<activity-summary-chart v-if="loaded" :chart-data="getValuesFromDict(summaryActivities)" :chartLabels="getKeysFromDict(summaryActivities)"></activity-summary-chart>
</div>
</div>
</template>
<script>
import BarChart from './Chart.vue'
import LineChart from './AssociationLineChart.vue'
import Ticker from './Ticker'
import ActivitySummaryChart from './ActivitySummaryChart.vue'
export default {
name: "App",
components: {
BarChart,
LineChart,
Ticker,
ActivitySummaryChart
},
props: {
},
data () {
return {
package: null,
packageName: '',
period: 'last-month',
loaded: false,
all_associations: [],
associations: [],
activities: [],
labels: [],
message: {},
activities_message: [],
summaryActivities: {},
showError: false,
errorMessage: 'Please enter a package name',
ticker: null,
username: '',
authenticated: false,
history: 0
}
},
async mounted() {
this.loaded = false;
const response = await fetch("/api/message");
const data = await response.text();
this.message = this.convertToArray(data);
this.all_associations = this.getAssociationsFromArray(this.message);
this.labels = this.getDatesFromArray(this.message);
const activities_resp = await fetch("/api/activities");
const activities_data = await activities_resp.text();
this.activities_message = this.convertToArray(activities_data);
this.activities = this.parseActivitiesArray(this.activities_message);
this.summaryActivities = this.getSummaryActivityData(this.activities);
this.authenticated = this.getUserInfo();
this.loaded = true;
},
methods: {
trimArray: function(arr) {
var arr2 = new Array();
if (this.history > 0) {
arr2 = arr.slice(Math.max(arr.length - this.history, 0));
} else {
arr2 = arr;
}
return arr2;
},
getUserInfo: function() {
var username = ''
try {
username = JSON.parse(localStorage["auth@aad"])["userDetails"];
this.authenticated = true;
this.username = username;
} catch (SyntaxError) {
this.authenticated = false;
}
},
convertToArray: function (data, delimiter=',') {
// slice from start of text to the first \n index
// use split to create an array from string by delimiter
data = data.replace(/(\r)/gm, "");
const headers = data.slice(0, data.indexOf("\n")).split(delimiter);
// slice from \n index + 1 to the end of the text
// use split to create an array of each csv value row
const rows = data.slice(data.indexOf("\n") + 1).split("\n");
// Map the rows
// split values from each row into an array
// use headers.reduce to create an object
// object properties derived from headers:values
// the object passed as an element of the array
const arr = rows.map(function (row) {
var values = row.split(delimiter);
const el = headers.reduce(function (object, header, index) {
object[header.trim()] = values[index];
return object;
}, {});
return el;
});
return arr;
},
getAssociationsFromArray: function(arr) {
var data = new Array();
for (let i = 0; i < arr.length; i++) {
let value = "";
if (arr[i] !== undefined) {
value = arr[i]["Associations"];
data[i] = parseInt(value);
}
}
return data;
},
parseActivitiesArray: function(arr) {
let arr2 = new Array();
for (let i=0; i<arr.length; i++) {
let set = {};
set.ActivityCode = arr[i]["ActivityCode"];
set.FollowupStartDate = arr[i]["FollowupStartDate"];
set.WhoOwnerCode = arr[i]["WhoOwnerCode"];
arr2[i] = set;
}
return arr2;
},
getTickerFromAssociationsArray: function(arr) {
const ticker = arr.slice(-1)[0];
return ticker;
},
getDatesFromArray: function(arr) {
var data = new Array();
for (let i = 0; i < arr.length; i++) {
let value = "";
if (arr[i] !== undefined) {
value = arr[i]["Date"];
data[i] = value;
}
}
return data;
},
getAssociationDifferences: function(arr) {
var differences = new Number;
var percentages = new Array;
for (let i=0; i<arr.length; i++) {
if (i===0) {
differences[i] = 0;
percentages[i] = 0;
} else {
try {
differences = (arr[i] - arr[i-1])/arr[i]*100;
percentages[i] = differences.toFixed(2);
} catch (IndexOutOfBoundsException){
differences[i] = arr[i];
percentages[i] = 0;
}
}
}
return percentages;
},
getUpOrDown(arr) {
let up = false;
if (arr.slice(-1)[0] - arr.slice(-2)[0] >= 0) {
up = true;
} else {
up = false;
}
return up;
},
getSummaryActivityData: function(arr) {
let summaryDict = {};
let summaryCount = 1;
for (let i=0; i<arr.length; i++) {
let key = arr[i]["WhoOwnerCode"];
if (summaryDict[key] === undefined) {
summaryDict[key] = key;
summaryDict[key] = { Name: key, Count: summaryCount }
} else {
let value = summaryDict[key]["Count"];
summaryDict[key]["Count"] = value + 1;
}
}
console.log(summaryDict);
return summaryDict;
},
getKeysFromDict: function(dict) {
let keys = [];
let values = [];
let i = 0;
for (const [key, value] of Object.entries(dict)) {
console.log(key);
keys[i] = value.Name;
values[i] = value.Count;
i++;
}
console.log(keys);
console.log(values);
return keys;
},
getValuesFromDict: function(dict) {
let keys = [];
let values = [];
let i = 0;
for (const [key, value] of Object.entries(dict)) {
console.log(key);
keys[i] = value.Name;
values[i] = value.Count;
i++;
}
console.log(keys);
console.log(values);
return values;
}
}
}
</script>
|
import {createSlice} from '@reduxjs/toolkit';
const initialState: any = {
user: null,
isLoggedIn: true,
authToken: null,
};
export const userReducer = createSlice({
name: 'user',
initialState,
reducers: {
setAuthToken: (state, action) => {
state.authToken = action.payload;
},
setUser: (state, action) => {
state.user = action.payload;
},
signOut: state => {
state.user = null;
state.authToken = null;
state.isLoggedIn = false;
},
},
});
export const {setUser, signOut, setAuthToken} = userReducer.actions;
export default userReducer.reducer;
|
package com.example.notes.controller;
import com.example.notes.model.AuthenticationTokenBody;
import com.example.notes.security.util.JwtUtil;
import com.example.notes.service.UserDetailsDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth")
public class TokenController {
@Autowired
UserDetailsDAO userDetailsDAO;
@Autowired
AuthenticationManager authenticationManager;
@Autowired
JwtUtil jwtUtil;
@PostMapping("/token")
public ResponseEntity<String> getToken(@RequestBody AuthenticationTokenBody request){
//Authentication Manager will handle all the job of authenticating user,
// instead of us doing manual authentication using UserDetailsService.
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getEmail(),request.getPassword()));
User user = userDetailsDAO.loadUserByEmail(request.getEmail());
if(!ObjectUtils.isEmpty(user)){
return ResponseEntity.ok(jwtUtil.generateToken(user));
}
return new ResponseEntity<>("Invalid User Deatils!!", HttpStatus.BAD_REQUEST);
}
}
|
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:orientation="vertical"
tools:context=".DetailsActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="16dp"
android:text="@string/product_info_title" />
<!-- Product Name -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="@string/product_name"
style="@style/TextInputLayoutStyle">
<android.support.design.widget.TextInputEditText
android:id="@+id/product_name_edit_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:singleLine="true"/>
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="16dp"
android:baselineAligned="false">
<!-- Product Price -->
<android.support.design.widget.TextInputLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="16dp"
android:layout_marginEnd="16dp"
android:hint="@string/product_price"
style="@style/TextInputLayoutStyle">
<android.support.design.widget.TextInputEditText
android:id="@+id/price_edit_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="number"
android:digits="0123456789"
android:singleLine="true"/>
</android.support.design.widget.TextInputLayout>
<!-- Product Quantity -->
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:layout_gravity="bottom"
android:text="@string/product_quantity"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/decrease_quantity_button"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:src="@drawable/ic_keyboard_arrow_right"
android:tint="@color/colorPrimary"
android:rotation="180"/>
<TextView
android:id="@+id/quantity_text"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:gravity="center"
android:textSize="26sp"
tools:text="0"/>
<ImageView
android:id="@+id/increase_quantity_button"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:src="@drawable/ic_keyboard_arrow_right"
android:tint="@color/colorPrimary"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@android:color/darker_gray"
android:layout_marginTop="16dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginTop="16dp"
android:text="@string/supplier_info_title" />
<!-- Supplier Name -->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="@string/supplier_name"
style="@style/TextInputLayoutStyle">
<android.support.design.widget.TextInputEditText
android:id="@+id/supplier_name_edit_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:singleLine="true"/>
</android.support.design.widget.TextInputLayout>
<!--Supplier Phone Number-->
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:hint="@string/supplier_phone_number"
style="@style/TextInputLayoutStyle">
<android.support.design.widget.TextInputEditText
android:id="@+id/supplier_phone_edit_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="phone"
android:singleLine="true"/>
</android.support.design.widget.TextInputLayout>
<Button
android:id="@+id/call_supplier_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="@dimen/margin_item_view"
android:text="@string/call_supplier"/>
</LinearLayout>
</ScrollView>
|
---
title: Exercises
nav_order: 95
has_children: false
layout: default
---
## Exercises
Practice your command-line skills with the following exercises.
**Note:** To download each file to your terminal, right-click on the file and select copy link address. Then, use the following command by replacing `<Address>` with the actual URL that you just copied to download the file.
```bash
wget <Address>
```
### Submission Instructions
After completing the exercises, follow these steps:
1. Write your answers in a text file.
2. Send the text file to your instructor at `[email protected]` .
3. Expect feedback within a week after your submission to the same email address.
---
### 1. View the First 6 Lines
You have a large file ([`top-1m.csv`](/src/top-1m.csv)) and want to see only the first 6 lines. Write a command to do this.
---
### 2. Extract the Second Column
You have a text file ([`top-1m.csv`](/src/top-1m.csv)) with multiple columns separated by a comma, and you want to extract only the second column. Write a command to do this.
---
### 3. Copying a File to a New Directory
You want to copy a file ([`top-1m.csv`](/src/top-1m.csv)) from the current directory to a new directory called `backup`. Which command(s) could you use?
---
### 4. Counting Lines, Words, and Characters
You have a text file ([`romeo_and_juliet.txt`](/src/romeo_and_juliet.txt)) and want to know how many lines, words, and characters it has. Write a command to do this.
---
### 5. Searching and Replacing with `sed`
You want to search a file ([`romeo_and_juliet.txt`](/src/romeo_and_juliet.txt)) for "Romeo" and replace it with Your Name. Write a command to do this (you need to use `sed`).
---
### 6. Shuffle and Save to a New File
You want to shuffle the lines of a file ([`top-1m.csv`](/src/top-1m.csv)) and then save the first 10 lines to a new file called `newfile.txt`. Write a command to do this.
---
### 7. Sort a File Alphabetically
You want to sort a file ([`fruits.txt`](/src/fruits.txt)) in alphabetical order. Write a command to do this.
---
### 8. Counting Unique Lines
You want to count the number of unique lines in a file ([`fruits.txt`](/src/fruits.txt)). Write a command to do this.
---
### 9. View the Manual Page for `curl`
You want to see the manual page for the `curl` command. Write a command to do this.
---
|
<!DOCTYPE html>
<html>
<head>
<title>ARP Privilege Escalation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/css2?family=Raleway&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Encode+Sans+SC&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Lato:100,300,400,700,900" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="../css/style.css">
<meta name="description" content="This tutorial demonstrates how to use ARP to read files with root privileges on a Linux system.">
<meta name="keywords" content="kali, linux, kali linux, arp, privilege, escalation, arp privilege escalation, read files with root permissions">
<meta name="author" content="0xma">
</head>
<body>
<header class="header">
<div class="text-box">
<h1 class="heading-primary">
<span class="heading-primary-main">0xma</span>
<span class="heading-primary-sub">Cyber Security Articles</span>
</h1>
</div>
<div class="nav_box">
<ul class="nav_ul">
<li class="nav_li"><a href="https://twitter.com/0xmaCyberSec">About</a></li>
<li class="nav_li"><a href="https://github.com/0xma/">GitHub</a></li>
<li class="nav_li"><a href="index.html">Hacking Articles</a></li>
<li class="nav_li"><a href="../index.html">Home</a></li>
</ul>
</div>
</header>
<br>
<br>
<br>
<div class="container">
<div class="left_empty_space"></div>
<div class="center">
<p class="date">April 24, 2022</p>
<h1 class="heading">ARP Privilege Escalation</h1>
<p>In this tutorial, we will see how to use ARP to read files that can only be read by users with root level privileges. We are assuming that the ARP tool has the "ep" capabilities set. If these capabilities are set then it can allow us to read any file that we want on the Linux system.</p>
<p>It shows the permission assigned to the "arp" executable.</p>
<img src="../img/arp_privilege_escalation/001.png" alt="Viewing the permissions of the arp tool." title="Viewing the permissions of the arp tool.">
<br>
<br>
<p>The <span class="command">getcap</span> command can be used to view the capabilities assigned to <span class="command">arp</span>. We can see that the "ep" capabilities are set. This <a href="https://tbhaxor.com/understanding-linux-capabilities/">page</a> contains more information about capabilities assigned to executables.</p>
<img src="../img/arp_privilege_escalation/002.png" alt="Viewing the capabilities of arp." title="Viewing the capabilities of arp.">
<br>
<br>
<p>This <a href="https://gtfobins.github.io/gtfobins/arp/">page</a> contains more information about how to use <span class="command">arp</span> to read files from the Linux system. For this demo, we are trying to read the contents of the "/root/root.txt" file which can only be read by the root user.</p>
<img src="../img/arp_privilege_escalation/003.png" alt="Viewing the root file." title="Viewing the root file.">
<br>
<br>
<p>Next, we can try to read the "/etc/shadow" file.</p>
<img src="../img/arp_privilege_escalation/004.png" alt="Viewing the /etc/shadow file." title="Viewing the /etc/shadow file.">
<br>
<br>
<p>We can use <span class="command">grep</span> and <span class="command">cut</span> to filter the results so that we could just read the "/etc/shadow" file. This is something I learned from <a href="https://0xdf.gitlab.io/2022/02/12/htb-earlyaccess.html">0xdf's</a> blog post.</p>
<img src="../img/arp_privilege_escalation/005.png" alt="Viewing the /etc/shadow file." title="Viewing the /etc/shadow file.">
<br>
<br>
<p>We can also read the root user's private SSH key. Using this key, we can login to the target box as the root user.</p>
<img src="../img/arp_privilege_escalation/006.png" alt="Viewing the .ssh/id_rsa file." title="Viewing the .ssh/id_rsa file.">
<p>If you liked reading this article, you can follow me on Twitter: <a href="https://twitter.com/0xmaCyberSec">0xmaCyberSec</a>.</p>
<br>
<hr>
<br>
<div class="bottom_links">
<div id="right_margin_widget">
<div class="widget_title">Related Tutorials</div>
<hr>
<ul class="remove_bullet_points">
<li class="style_bullet_points"><a href="../hacking/capture_ldap_credentials.html" class="widget_links">Capture LDAP Credentials</a></li>
<li class="style_bullet_points"><a href="../hacking/privilege_escalation_via_server_operators_group.html" class="widget_links">Privilege Escalation via Server Operators Group</a></li>
<li class="style_bullet_points"><a href="../hacking/exploit_printnightmare.html" class="widget_links">Exploit PrintNightmare</a></li>
<li class="style_bullet_points"><a href="../hacking/extract_passwords_with_lazagne.html" class="widget_links">Extract Passwords with LaZagne</a></li>
<li class="style_bullet_points"><a href="../hacking/local_privilege_escalation_on_linux_kernel.html" class="widget_links">Local Privilege Escalation on Linux Kernel < 4.4.0-116</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_2016_medusa.html" class="widget_links">Bruteforce Windows Server SMB Credentials with Medusa</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_2016_hydra.html" class="widget_links">Brute Force Windows Server SMB Credentials with Hydra</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_2016_ncrack.html" class="widget_links">Brute Force Windows Server SMB Credentials with NCrack</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_crackmapexec.html" class="widget_links">Brute Force Windows Server SMB Credentials with CrackMapExec</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_metasploit.html" class="widget_links">Brute Force Windows Server SMB Credentials with Metasploit</a></li>
</ul>
</div>
<!-- <div id="right_margin_widget">
<div class="widget_title">Latest Tutorials</div>
<hr>
<ul class="remove_bullet_points">
<li class="style_bullet_points"><a href="../hacking/escalate_privileges_via_pip.html" class="widget_links">Escalate Privileges via pip</a></li>
<li class="style_bullet_points"><a href="../hacking/modifying_etc_passwd_file.html" class="widget_links">Escalate Privileges by Modifying the /etc/passwd File</a></li>
<li class="style_bullet_points"><a href="../hacking/wpadmin_shell_upload.html" class="widget_links">wp_admin_shell_upload</a></li>
<li class="style_bullet_points"><a href="../hacking/extract_passwords_with_lazagne.html" class="widget_links">Extract Passwords with LaZagne</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_2016_medusa.html" class="widget_links">Bruteforce Windows Server SMB Credentials with Medusa</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_2016_hydra.html" class="widget_links">Brute Force Windows Server SMB Credentials with Hydra</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_2016_ncrack.html" class="widget_links">Brute Force Windows Server SMB Credentials with NCrack</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_crackmapexec.html" class="widget_links">Brute Force Windows Server SMB Credentials with CrackMapExec</a></li>
<li class="style_bullet_points"><a href="../hacking/brute_force_windows_server_metasploit.html" class="widget_links">Brute Force Windows Server SMB Credentials with Metasploit</a></li>
<li class="style_bullet_points"><a href="../hacking/exploit_printnightmare.html" class="widget_links">Exploit PrintNightmare</a></li>
</ul>
</div> -->
</div>
<br>
<br>
<br>
</div>
</div>
<div class="right_empty_space"></div>
<footer>
<div class="footer">
<span class="copyright">Copyright © 2022</span>
</div>
</footer>
</body>
</html>
|
import React, { useEffect, useState } from 'react';
import { Collapse, CardBody, Card, CardHeader } from 'reactstrap';
const CardFaq = (props) => {
const [collapse, setCollapse] = useState([]);
useEffect(() => {
const isOpen = [];
props.content.forEach((item) => {
isOpen.push(item.isOpen);
});
setCollapse([...isOpen]);
}, []);
const toggle = (index) => {
const tempArray = [];
for (let i = 0; i < collapse.length; i++) {
// tempArray.push(false);
if (i == index) {
tempArray.push(!collapse[i]);
} else {
tempArray.push(false);
}
}
setCollapse([...tempArray]);
console.log(tempArray);
};
return (
<div className="cardFaq row">
{props.content.map((item, index) => {
return (
<div className="questionBox1 w-100">
<div
className="question"
onClick={() => {
toggle(index);
}}
data-event={index}
>
<div>{item.question}</div>
<div className="circle">
{collapse[index] ? (
<div className="symbol">-</div>
) : (
<div className="symbol">+</div>
)}
</div>
</div>
<Collapse isOpen={collapse[index]}>
<div className="answer" style={{ textAlign: 'justify' }}>
{item.answer}
</div>
</Collapse>
</div>
);
})}
</div>
);
};
export default CardFaq;
|
/*
16562-친구비
우선 union을 이용하여 친구비를 한 번만 낼 수 있는 그룹을 찾는다.
union을 할 때, parent는 친구비가 더 낮은 친구를 위주로 union을 한다.
union 작업이 다 끝난 뒤에는 parent가 음의 값을 가지는 경우 친구비를 계산하여 모든 친구와 친구가 되기 위해 필요한 친구 비를 구한다.
그리고 k를 기준으로 친구를 할 수 있음과 없음을 구분하여 결과를 출력한다.
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <limits.h>
#include <math.h>
#include <queue>
#include <string>
#include <stack>
#include <list>
#include <stdlib.h>
#include <cstring>
#include <deque>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<char, ll> pci;
typedef pair<int, pair<int, int>> piii;
int find(int a, vector<int>& parent) {
if (parent[a] < 0) return a;
parent[a] = find(parent[a], parent);
return parent[a];
}
void merge(int a, int b, vector<int>& parent, vector<int> &arr) {
int reta = find(a, parent);
int retb = find(b, parent);
if (reta == retb) return;
if (arr[reta] < arr[retb]) {
parent[reta] += parent[retb];
parent[retb] = reta;
}
else {
parent[retb] += parent[reta];
parent[reta] = retb;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m, k;
cin >> n >> m >> k;
vector<int> arr(n + 1);
vector<int> parent(n + 1, -1);
for (int i = 1; i <= n; i++) cin >> arr[i];
while (m--) {
int a, b;
cin >> a >> b;
merge(a, b, parent, arr);
}
int sum = 0;
for (int i = 1; i <= n; i++) {
if (parent[i] < 0) sum += arr[i];
}
if (sum > k) cout << "Oh no\n";
else cout << sum;
return 0;
}
|
package com.water.controller;
import com.water.constans.BaseConstants;
import com.water.dto.MoveDTO;
import com.water.dto.PointDTO;
import com.water.entity.Marker;
import com.water.result.Result;
import com.water.service.MarkerService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
@RequestMapping("api/marker")
public class MarkerController {
@Resource
MarkerService markerService;
/**
* 获取指定地图的所有点位
* @param pointDTO
* @return
*/
@PostMapping("get")
public Result<List<Marker>> getMarker(@RequestBody PointDTO pointDTO){
String mapName = pointDTO.getMapName();
int floor = pointDTO.getFloor();
return Result.success(markerService.getMarkers(mapName,floor));
}
/**
* 扫描机器人中指定地图的所有点位存入mysql
* @param pointDTO
* @return
*/
@PostMapping("scan")
public Result<String> scanMarker(@RequestBody PointDTO pointDTO){
String address = pointDTO.getAddress();
String mapName = pointDTO.getMapName();
markerService.scanMarker(address,mapName);
return Result.success(BaseConstants.SUCCESS);
}
/**
* 让机器人进行点位间移动
* @param moveDTO
* @return
*/
@PostMapping("move")
public Result<String> move(@RequestBody MoveDTO moveDTO){
int count = moveDTO.getCount();
String address = moveDTO.getAddress();
List<String> markers = moveDTO.getMarkers();
markerService.toMarker(address,count,markers);
return Result.success(BaseConstants.SUCCESS);
}
}
|
import { ChangeEvent,KeyboardEvent, useState } from "react"
import AddBoxTwoToneIcon from '@mui/icons-material/AddBoxTwoTone';
type AddItemFormPropsType = {
callback: (title: string)=> void
style: {[key:string]:string}
}
export function AddItemForm(props: AddItemFormPropsType)
{
let [title, setTitle] = useState("")
let [error, setError] = useState<string | null>(null)
const addTask = (todolistId: string) => {
if (title.trim() !== "") {
props.callback(title.trim());
setTitle("");
} else {
setTitle("");
setError("Title is required");
}
}
const onChangeHandler = (e: ChangeEvent<HTMLInputElement>) => {
setTitle(e.currentTarget.value)
}
const onKeyDownHandler = (e: KeyboardEvent<HTMLInputElement>) => {
setError(null);
if (e.key === 'Enter') {
addTask(title);
}
}
return(
<div className='addItemForm'>
<input value={title}
onChange={onChangeHandler}
onKeyDown={onKeyDownHandler}
className={error ? "error" : ""}
style={props.style}
/>
{/* <button onClick={()=>{addTask(title)}}>+</button> */}
{/* <DeleteForeverTwoToneIcon
style={{ color: 'black',
fontSize: 30,}}
/> */}
<AddBoxTwoToneIcon
style={{ color: 'lime',
fontSize: 30,transform: 'translateY(10px)'}}
onClick={()=>{addTask(title)}}
/>
{error && <div className="error-message">{error}</div>}
</div>
)
}
|
# Render yml/yaml files action
This action retrieves secrets and variables from the GitHub context and replaces with values in file(s) (yml/yaml extensions) stated in target parameter if it finds a string with *ENV_* prefix that is *ENV_<variable/secret name>*. If file parameter is given true then it processes single file provided in target, if not it processes files in folder given in target parameter.
## Inputs
### `target`
**Required** The name of folder/file contains file(s) to be edited which has *ENV_* words in it.
### `secrets-context`
The secrets context which has secrets in it. (`${{ toJson(secrets) }}`)
### `variables-context`
The variables context which has environment variables in it. (`${{ toJson(vars) }}`)
## Outputs
Replaced files on the fly.
## Example usage
```yaml
uses: ftasbasi/[email protected]
with:
secrets-context: ${{ toJson(secrets) }}
variables-context: ${{ toJson(vars) }}
target: foldername/filename
file: true # default false
env:
VAR1: "sample value" # for changing ENV_VAR1 in files
```
##### Let's say we provide ENVIRONMENT_NAME=test-env and STORAGE_SIZE=20Gi as env parameter or a GitHub environment variable directly, here is the sample output:
Before:
```
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
namespace: ENV_ENVIRONMENT_NAME
name: postgresql-ENV_ENVIRONMENT_NAME
spec:
accessModes:
- ReadWriteMany
storageClassName: manual
resources:
requests:
storage: ENV_STORAGE_SIZE
```
After:
```
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
namespace: test-env
name: postgresql-test-env
spec:
accessModes:
- ReadWriteMany
storageClassName: manual
resources:
requests:
storage: 20Gi
```
|
# Test Containers
## What is Testcontainers?
It’s a Java library that allows you to bring up docker images during the testing process and use real images of databases, message queues, etc.. instead of mocking or using H2. There are some ready-to-use test containers (Mysql, Kafka,…) but if you can’t find your desired module you can use any custom image that you want.
You can find ready-to-use modules on the [Testcontainers website](https://www.testcontainers.org/ "https://www.testcontainers.org/").
## How to use it?
In this example, we use JUnit 5 (Testcontainers supports JUnit 4 too). To start, we need to add two dependencies to the POM file of the project:
```xml
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.15.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<version>1.15.3</version>
<scope>test</scope>
</dependency>
```
For this example, we use Mysql and ActiveMQ. For Mysql we need to add another dependency:
```xml
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mysql</artifactId>
<version>1.15.3</version>
<scope>test</scope>
</dependency>
```
On top of the test class, we add a `@Testcontainers` annotation:
```java
@SpringBootTest(classes = Application.class)
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
@AutoConfigureMockMvc
@ActiveProfiles("it")
@ContextConfiguration(classes = {Application.class})
@Testcontainers
@Slf4j
class ExampleControllerIT {
```
This annotation enables Testcontainers JUnit extension which finds all fields inside the test class annotated with `@Container` and calls their container lifecycle methods.
Now we need to define our containers as variables inside the test class. We should define them as static fields. For Mysql, we have a ready-to-use container:
```java
@Container
private static final JdbcDatabaseContainer<?> mysql = new MySQLContainer<>("mysql:5.7.22")
.waitingFor(Wait.forListeningPort());
```
For ActiveMQ, we need to Define a Generic container:
```java
@Container
private static final GenericContainer<?> activemq = new GenericContainer<>(DockerImageName.parse("rmohr/activemq:5.14.0"))
.withExposedPorts(61616)
.withPrivilegedMode(true)
.waitingFor(Wait.forListeningPort());
```
You can set up your docker config in the generic container here.
Testcontainers uses random port mapping so we need to set the URL of Mysql and ActiveMQ after the container is up and running. We can use `@DynamicPropertySource` annotation to config spring boot values:
```java
@DynamicPropertySource
static void registerDynamicProperties(DynamicPropertyRegistry registry) {
String activeMQUrl = String.format("tcp://%s:%d", activemq.getContainerIpAddress(), activemq.getFirstMappedPort());
registry.add("spring.activemq.broker-url", () -> activeMQUrl);
registry.add("spring.datasource.url", () -> mysql.getJdbcUrl() + "?useSSL=false");
registry.add("spring.datasource.username", mysql::getUsername);
registry.add("spring.datasource.password", mysql::getPassword);
}
```
This spring annotation waits for the containers to be ready and gives you the ability to add dynamic values to the Environment’s set of PropertySources. Methods annotated with this annotation must be static and have a single `DynamicPropertyRegistry` argument.
Now we can run the test. Make sure your Docker daemon is started. The first run might take forever because it needs to download the images, but the next run will be faster.
|
/*
* This source file is part of the tqmesh library.
* This code was written by Florian Setzwein in 2022,
* and is covered under the MIT License
* Refer to the accompanying documentation for details
* on usage and license.
*/
#pragma once
#include <vector>
#include <utility>
#include "Mesh.h"
#include "MeshCleanup.h"
namespace TQMesh {
namespace TQAlgorithm {
using namespace CppUtils;
/*********************************************************************
* This class handles the merger between two meshes,
* where the vertices, elements and edges of a donor mesh are
* copied to a receiver mesh - if both meshes share common interface
* edges.
*********************************************************************/
class MeshMerger
{
public:
using VertexVector = std::vector<Vertex*>;
using EdgeVector = std::vector<Edge*>;
using VertexPair = std::vector<std::pair<Vertex*, Vertex*>>;
/*------------------------------------------------------------------
| Constructor / Destructor
------------------------------------------------------------------*/
MeshMerger(Mesh& receiver, Mesh& donor)
: receiver_ { &receiver }
, donor_ { &donor }
, new_vertices_ { donor.vertices().size(), nullptr }
{}
virtual ~MeshMerger() {}
/*------------------------------------------------------------------
| Copy donor entities to receiver (if they share boundary edges)
------------------------------------------------------------------*/
bool merge()
{
if ( merged_ )
return false;
MeshCleanup::setup_facet_connectivity(*receiver_);
MeshCleanup::setup_facet_connectivity(*donor_);
// Assign indices to donor mesh
MeshCleanup::assign_mesh_indices(*receiver_);
MeshCleanup::assign_mesh_indices(*donor_);
// Search for vertices that are located on the inteface
// boundary between donor and receiver
// -> These vertices will not be copied
if ( !collect_interface_boundary_vertices() )
return false;
// Copy all relevant donor entities
copy_donor_vertices();
copy_donor_quads();
copy_donor_triangles();
copy_donor_interior_edges();
copy_donor_boundary_edges();
// Find boundary inteface edges that should be turned into
// interior edges
convert_boundary_interface_edges();
// Finally, we need to make sure that all boundary vertices
// are still marked as "on_boundary" (this information might have
// been lost while collecting interface boundary vertices )
for ( const auto& e_ptr : receiver_->boundary_edges() )
{
e_ptr->v1().add_property(VertexProperty::on_boundary);
e_ptr->v2().add_property(VertexProperty::on_boundary);
}
// Forbid to run again
merged_ = true;
return true;
} // merge()
private:
/*------------------------------------------------------------------
| Loop over all the receiver's boundary edges and loacte all twin
| edges that are connected to the donor mesh.
| Return false if both meshes share no boundary edges.
------------------------------------------------------------------*/
bool collect_interface_boundary_vertices()
{
std::size_t n_twins = 0;
for ( const auto& e_ptr : receiver_->boundary_edges() )
{
Edge* e_twin = e_ptr->twin_edge();
if ( !e_twin )
continue;
Facet* f_twin = e_twin->facet_l();
ASSERT( f_twin, "MeshBuilder::merge_meshes(): "
"Invalid boundary edge connectivity." );
if ( f_twin->mesh() != donor_ )
continue;
auto v1_index = e_twin->v1().index();
auto v2_index = e_twin->v2().index();
// Keep in mind, that both edges point in different directions
new_vertices_[v2_index] = &(e_ptr->v1());
new_vertices_[v1_index] = &(e_ptr->v2());
// We remove the "on_boundary" property, but we want to preserve the
// location of the interface vertices and thus set them as "fixed"
new_vertices_[v1_index]->remove_property( VertexProperty::on_boundary );
new_vertices_[v2_index]->remove_property( VertexProperty::on_boundary );
new_vertices_[v1_index]->add_property( VertexProperty::is_fixed );
new_vertices_[v2_index]->add_property( VertexProperty::is_fixed );
++n_twins;
}
return (n_twins > 0);
} // collect_interface_boundary_vertices()
/*------------------------------------------------------------------
| Copy all donor vertices to the receiver, which have not been
| flagged as interface boundary vertices
------------------------------------------------------------------*/
void copy_donor_vertices()
{
for ( const auto& v_ptr : donor_->vertices() )
{
auto v_index = v_ptr->index();
if ( !new_vertices_[v_index] )
{
Vertex& v_new = receiver_->add_vertex( v_ptr->xy() );
v_new.add_property( v_ptr->properties() );
new_vertices_[v_index] = &v_new;
}
}
} // copy_donor_vertices()
/*------------------------------------------------------------------
| Copy all the donor's quad elements
------------------------------------------------------------------*/
void copy_donor_quads()
{
for ( const auto& q_ptr : donor_->quads() )
{
auto v1_index = q_ptr->v1().index();
auto v2_index = q_ptr->v2().index();
auto v3_index = q_ptr->v3().index();
auto v4_index = q_ptr->v4().index();
Vertex* v1 = new_vertices_[v1_index];
Vertex* v2 = new_vertices_[v2_index];
Vertex* v3 = new_vertices_[v3_index];
Vertex* v4 = new_vertices_[v4_index];
ASSERT(v1, "MeshMerger::copy_donor_quads(): Invalid data structure.");
ASSERT(v2, "MeshMerger::copy_donor_quads(): Invalid data structure.");
ASSERT(v3, "MeshMerger::copy_donor_quads(): Invalid data structure.");
ASSERT(v4, "MeshMerger::copy_donor_quads(): Invalid data structure.");
receiver_->add_quad( *v1, *v2, *v3, *v4, q_ptr->color() );
}
} // copy_donor_quads()
/*------------------------------------------------------------------
| Copy all the donor's triangle elements
------------------------------------------------------------------*/
void copy_donor_triangles()
{
for ( const auto& t_ptr : donor_->triangles() )
{
auto v1_index = t_ptr->v1().index();
auto v2_index = t_ptr->v2().index();
auto v3_index = t_ptr->v3().index();
Vertex* v1 = new_vertices_[v1_index];
Vertex* v2 = new_vertices_[v2_index];
Vertex* v3 = new_vertices_[v3_index];
ASSERT(v1, "MeshMerger::copy_donor_triangles(): Invalid data structure.");
ASSERT(v2, "MeshMerger::copy_donor_triangles(): Invalid data structure.");
ASSERT(v3, "MeshMerger::copy_donor_triangles(): Invalid data structure.");
receiver_->add_triangle( *v1, *v2, *v3, t_ptr->color() );
}
} // copy_donor_triangles()
/*------------------------------------------------------------------
| Copy all the donor's interior edges
------------------------------------------------------------------*/
void copy_donor_interior_edges()
{
for ( const auto& e_ptr : donor_->interior_edges() )
{
auto v1_index = e_ptr->v1().index();
auto v2_index = e_ptr->v2().index();
Vertex* v1 = new_vertices_[v1_index];
Vertex* v2 = new_vertices_[v2_index];
ASSERT(v1, "MeshMerger::copy_donor_interior_edges(): Invalid data structure.");
ASSERT(v2, "MeshMerger::copy_donor_interior_edges(): Invalid data structure.");
receiver_->interior_edges().add_edge( *v1, *v2 );
}
} // copy_donor_interior_edges()
/*------------------------------------------------------------------
| Copy all the donor's boundary edges
------------------------------------------------------------------*/
void copy_donor_boundary_edges()
{
EdgeList& boundary_edges = receiver_->boundary_edges();
for ( const auto& e_ptr : donor_->boundary_edges() )
{
Edge* e_twin = e_ptr->twin_edge();
// Skip if edge is an interface to this mesh
if ( e_twin &&
e_twin->facet_l() &&
e_twin->facet_l()->mesh() == receiver_ )
continue;
auto v1_index = e_ptr->v1().index();
auto v2_index = e_ptr->v2().index();
Vertex* v1 = new_vertices_[v1_index];
Vertex* v2 = new_vertices_[v2_index];
ASSERT(v1, "MeshBuilder::merge_meshes(): Invalid data structure.");
ASSERT(v2, "MeshBuilder::merge_meshes(): Invalid data structure.");
Edge& e_new = boundary_edges.add_edge(*v1, *v2, e_ptr->marker());
// Add interface to possible other receiver meshes
if ( e_twin )
{
e_twin->twin_edge( &e_new );
e_new.twin_edge( e_twin );
}
}
} // copy_donor_boundary_edges()
/*------------------------------------------------------------------
| Turn boundary interface edges into interior edges
------------------------------------------------------------------*/
void convert_boundary_interface_edges()
{
EdgeVector bdry_edges_to_remove;
VertexPair new_intr_edges;
for ( const auto& e_ptr : receiver_->boundary_edges() )
{
Edge* e_twin = e_ptr->twin_edge();
if ( !e_twin )
continue;
Facet* f_twin = e_twin->facet_l();
ASSERT( f_twin, "MeshMerger::convert_boundary_interface_edges(): "
"Invalid boundary edge connectivity." );
if ( f_twin->mesh() != donor_ )
continue;
auto v1_index = e_twin->v1().index();
auto v2_index = e_twin->v2().index();
Vertex* v1 = new_vertices_[v1_index];
Vertex* v2 = new_vertices_[v2_index];
ASSERT(v1, "MeshMerger::convert_boundary_interface_edges(): Invalid data structure.");
ASSERT(v2, "MeshMerger::convert_boundary_interface_edges(): Invalid data structure.");
new_intr_edges.push_back( {v2, v1} );
bdry_edges_to_remove.push_back( e_ptr.get() );
}
// Remove old edges
for ( Edge* e : bdry_edges_to_remove )
receiver_->remove_boundary_edge( *e );
// Add new interior edges
for ( auto v : new_intr_edges )
receiver_->interior_edges().add_edge( *v.first, *v.second );
// Clean up
receiver_->clear_waste();
} // convert_boundary_interface_edges()
/*------------------------------------------------------------------
| Attribute
------------------------------------------------------------------*/
Mesh* donor_;
Mesh* receiver_;
VertexVector new_vertices_;
bool merged_ { false };
}; // MeshMerger
} // namespace TQAlgorithm
} // namespace TQMesh
|
# 如何在 GitHub 中创建自动拉取请求清单
> 原文:<https://www.freecodecamp.org/news/create-a-pr-checklist-in-github/>
如果你曾经参与过一个项目,不管是你工作中的应用还是开源工具,你很可能已经创建了一个拉请求。这要求您的代码更改为合并到主代码库中。
我们使用拉请求来确保只有高质量的代码被合并到我们的主要分支中。但是有时候,在开发一个新特性的艰苦的编码会议之后,我们会错过一些小事情。
在最坏的情况下,这些错误可能会被队友忽略,并合并到主代码库中,造成错误或低效。在最好的情况下,发现这些微小的问题会占用其他团队成员的时间去注意和指出。
我特别容易打开一个懒惰的拉请求,所以我做了任何开发人员都会做的事情...我找到了一个自动制作公关清单的方法,并强迫自己去做这项工作!
本教程向您展示了如何在浏览器中构建一个扩展,该扩展将自动生成一个拉式请求清单,并隐藏“创建拉式请求”按钮,直到您检查完该清单上的每一项。
## 拿上你的工具
在你开始之前,你会想要得到一些东西。
### 列出要在代码中检查的内容
忘记任何工具或任何自动化...花几分钟时间思考**什么是好的拉动式请求**,并列出这些项目。
是什么让您可以轻松查看其他拉动式请求?或者你经常发现人们评论的一个常见错误是什么?
如果你需要一些想法,这里是我在我自己的列表中列出的。
* 所有东西都按字母顺序排列
* 关于评审员如何在本地测试代码的说明
* 已添加测试
* 功能/错误修复的屏幕截图(如果适用)
* 如果添加了任何新文本,它都是国际化的
* 任何新元素都有咏叹调标签
* 调试后无意外`console.logs`遗留
* 我对变量和函数使用了清晰简洁的名字吗?
* 我是否解释了所有可能的解决方案,以及为什么我选择了那个方案?
* 添加任何注释以使新功能更加清晰
* 添加公关标签
* 更新任何历史/变更日志文件
如果您仍然不确定,请与您团队中更高级的开发人员交谈,看看他们在审查拉请求时在寻找什么。
### 创建一个 PixieBrix 帐户(您的浏览器自动化工具)
有一些浏览器扩展可以让你创建自动化,但是我发现 [PixieBrix](https://pixiebrix.com/) 非常强大,社区也非常友好和有帮助。
> PixieBrix 为扩展您和您的团队已经使用的 web 应用程序提供了最通用的低代码平台。结果呢?您可以获得所需的高效、个性化体验...值得拥有。(来源: [PixieBrix](https://www.pixiebrix.com/) 网站)
为了实现我下面描述的自动化,你需要注册一个免费的 PixieBrix 账户。
只需在他们的网站上选择“免费开始”,并按照向导创建一个帐户。系统会提示您安装 [PixieBrix Chrome 扩展](https://chrome.google.com/webstore/detail/pixiebrix/mpjjildhmpddojocokjkgmlkkkfjnepo)。
现在你已经准备好了!
## 如何构建拉式请求清单自动化
好的,你都准备好了。现在是时候建造了。
如果你想走最简单的路线,你可以直接[激活我已经建立的扩展](https://app.pixiebrix.com/activate?id=@brittany-joiner/gh-on-a-pr),然后随心所欲地编辑。
但是如果你想从头开始构建它,并且更加熟悉浏览器自动化是如何工作的,请遵循以下步骤。
### 步骤 1–在 PixieBrix 中打开页面编辑器
要在 PixieBrix 中构建扩展,您不需要 VSCode 或任何其他编辑器。你可以完全在你的浏览器里做任何事情。
我喜欢从我希望动作发生的页面开始,在这个例子中是`github.com`。
要访问编辑器,右击任何网页打开上下文菜单并选择`Inspect`。滚动你的标签*(你知道,就是那些写着`Elements`、`Console`、`Network`等的标签)*,直到你看到`PixieBrix`。

Right click to Inspect, then go to PixieBrix tab
您可能会被提示授予一些权限,但随后您会发现一个空白页,左上角有一个按钮,上面写着“添加”。那是我们将开始的地方。
### 步骤 2–添加触发器砖块
要在 PixieBrix 中建立扩展,您需要将砖块链接在一起。你可以把砖块想象成函数,扩展是主要的函数,在你配置的序列中执行较小的函数。
您有多种选择来触发此扩展。

Extension Trigger Options in PixieBrix
你可以选择一个手动操作,比如在页面上添加一个按钮,或者一个上下文菜单(当你右击一个网页的时候——就是你进入你的检查器的那个菜单!)或者您可以使用 quickbar 命令(键盘快捷键)。
侧边栏面板在浏览器的右侧打开一个面板,它实际上不是一个触发器,而是用来为另一个触发器创建一个显示。
对于这个特定的工作流,使用`Trigger`选项,每当您加载特定的网页并且满足您配置的附加标准时,该选项都会运行扩展。
这是它最初的样子:

你可以把顶部的名字改成你喜欢的名字,比如`Github PR Checklist`。
要配置触发器,请考虑何时希望看到您的清单。你可以让它在你去 GitHub 的任何时候启动,但这可能比你想要的更频繁,因为当你阅读问题或在回购中搜索某些东西时,你不需要清单。
我决定每当页面上有一个`create pull request`按钮元素时触发,这表示我将要打开一个拉请求。所以这可能是一个很好的时间来检查我的清单!
因此,浏览打开一个拉请求的动作,并导航到有绿色按钮的页面(同时保持页面编辑器打开)。

GitHub Create pull request button
一旦你看到那个按钮,滚动到触发器块的`Advanced: Match Rules`部分,并寻找`Selectors`字段。

Selector section in PixieBrix trigger brick configuration
在那里,您可以使用鼠标按钮打开一个元素选择器视图,并单击选择按钮,或者您可以直接在字段中复制这个类。
```
.hx_create-pr-button
```
所以现在你已经创建了一个触发器,告诉你什么时候加载一个托管在`github.com`的页面。
好了,我们已经确定了按钮的类别,所以最难的部分已经过去了!现在我们只需要隐藏它,显示清单,然后在清单完成后再次显示它。
### 步骤 3–隐藏`create pull request`按钮
选择触发器砖块下方的加号按钮添加另一个砖块。您将看到一个市场打开,允许您搜索所有可用的砖块。搜索`hide`就能看到这块砖。

Hide brick in PixieBrix marketplace
将鼠标悬停在“隐藏”砖块上以查看更多选项,然后选择“添加”将其添加到您的扩展中。
这个砖块需要的唯一配置是**隐藏哪个元素**。在这种情况下,它将与我们在触发器中使用的元素完全相同 create pull request 按钮。所以您可以复制同一个类,并将其设置为选择器的值。
### 步骤 4–打开侧边栏
再加一个叫`Show Sidebar`的砖。这将在浏览器的右侧打开一个面板来显示内容。
我将`panelHeading`字段设置为`PR`,以指定它应该加载`PR`选项卡。如果您还没有设置其他侧面板,您不需要在这里放置任何东西,您可以跳到下一步。
### 第 5 步-将自己分配到问题中
在我们进入清单之前,除了显示清单和隐藏按钮之外,我还添加了一个自动化功能。
我创建了一个操作来将自己分配给该问题。只是点击一下,但为什么不让机器人来做呢?😊
为此,添加另一个称为`Simulate a DOM event`砖块的砖块。这块砖确实如其名...它假装对一个特定的元素做了什么,比如点击它。
为您希望与之交互的元素提供一个选择器和一个事件。
就像在触发器和隐藏砖块中一样,您可以使用鼠标按钮在屏幕上打开选择器选择器,并选择`assign yourself`链接来自动将这些类应用到选择器字段。
您也可以通过复制并粘贴到`selector`字段来手动应用该类:
```
#new_pull_request .js-issue-assign-self
```
确保选择`event`的`click`,一切就绪!
### 步骤 6–创建您的清单
现在,我们在我们的扩展肉。是时候列出清单了。选择加号按钮并添加`Show a modal or sidebar form`砖块。
这是设计表单的砖块,对于我们在提交拉取请求之前想要确认或考虑的每个项目,都将是一个复选框字段。
#### 设置表单标题和描述
这些纯粹是装饰性的,所以你可以随意设置。

Form settings for PixieBrix Show form brick
#### 配置您的第一个字段
在打开拉取请求之前,拿起您要查看的项目列表,选择第一个项目。这将是我们的第一个表单字段,您需要在 PixieBrix 中设置以下字段:
* `name`
* `label`
* `input type`
名称和标签可以是任何你想要的。**保持名称简单**,因为在下一步检查其真假时,您将需要引用它。**标签是出现在复选框**旁边的可视内容。对于输入类型,选择**复选框**。

PixieBrix form field configuration
您可以在 PixieBrix 页面编辑器的右侧面板上预览它的外观。

Preview form in PixieBrix preview panel
#### 将其余项目作为新字段添加
滚动字段上方以选择蓝色按钮“添加新字段”,并根据您的条目数重复以上操作。
#### 最终形态结构
快好了!滚动表单域选项下方的**,直到看到`Submit Button Text`。你可以保持原样,但是我定制了我的说`Ready to Open`让按钮动作更清晰。**
最重要的是,通过选择下拉菜单将`Location`值改为`sidebar`而不是`modal`。这会将表单设置为出现在我们在上一步中打开的侧栏中。
### 步骤 7–完成清单后,显示`create pull request`按钮
向这个扩展添加最后一块砖,名为`Show`。这类似于 Hide,我们将传递给它我们一直为`create pull request`按钮引用的同一个类。
如果你需要复习的话,这又是一次:
```
.hx_create-pr-button
```
还有一部分需要配置,因为我们希望控制何时执行这个砖块,因为我们只想在表单提交中的每一项都被选中时显示按钮。
我们可以将表单中的每个字段都设置为必填字段,这样您就可以在检查完所有内容后再提交表单。但是另一种方法是在这个砖块上的高级选项下编辑`Condition`字段。
您可以在这里指定何时运行这个特定的程序块。如果检查表中的每个字段都为真,您将构建一个返回真的语句。
这就是语法看起来的样子,尽管您需要用每一项的名称替换`item`值。
```
{{ "true" if @form.item1 and @form.item2 and @form.item3 and @form.item4 and @form.item5 and @form.item6 and @form.item7 and @form.item8 and @form.item9 and @form.item10 [email protected] }}
```
完成后,您的砖块应该看起来像这样:

Show brick configuration
选择 PixieBrix 页面编辑器右上角的蓝色保存按钮来保存您的扩展。
## 带它去兜一圈
现在试试吧!无论您已经[激活了预构建的扩展](https://app.pixiebrix.com/activate?id=@brittany-joiner/gh-on-a-pr),还是按照教程自己构建了它,您都已经准备好测试了。
打开一个 pull 请求,您会看到侧边栏表单,没有绿色按钮。检查列表中的所有项目,并提交,然后突然你的按钮出现,你已经被分配到 PR!

Demo of PR Checklist
如果您在开始构建它时有任何问题,或者它没有按预期工作,PixieBrix 社区是活跃的,维护人员总是愿意加入并提供帮助。
但是如果你更喜欢视觉学习,更喜欢观看,我制作了一个视频,向你展示如何[建立这个自动化的公关清单](https://youtu.be/cpZ1J2s-2jk)。
感谢您的阅读!
|
import React from "react";
import classes from "./Navbar.module.css";
import { AiFillCodeSandboxSquare } from "react-icons/ai";
import {
TbUserSquareRounded,
TbCircleKey,
TbHexagonLetterO,
} from "react-icons/tb";
import { RiQuestionnaireLine } from "react-icons/ri";
import { LiaCoinsSolid } from "react-icons/lia";
import { LuBadgePercent } from "react-icons/lu";
import { IoIosArrowDown } from "react-icons/io";
import userImg from "../../assets/user.jpeg";
const Navbar = () => {
return (
<div className="navbar">
<div className={classes.logo}>
<div className={classes["logo-icon"]}>
<TbHexagonLetterO size={30} />
</div>
<p>Dashboard</p>
</div>
<nav className={classes.navlist}>
<ul>
<div className={`${classes["nav-links-1"]} ${classes.active} `}>
<div className={classes["icon-div"]}>
<TbCircleKey size={22} />
</div>
<li>
Dashboard <i className={`${classes.arrow} ${classes.right}`}></i>
</li>
</div>
<div className={classes["nav-links"]}>
<div className={classes["icon-div"]}>
<AiFillCodeSandboxSquare size={22} />
</div>
<li>
Product <i className={`${classes.arrow} ${classes.right}`}></i>
</li>
</div>
<div className={classes["nav-links"]}>
<div className={classes["icon-div"]}>
<TbUserSquareRounded size={22} />
</div>
<li>
Customers <i className={`${classes.arrow} ${classes.right}`}></i>
</li>
</div>
<div className={classes["nav-links"]}>
<div className={classes["icon-div"]}>
<LiaCoinsSolid size={22} />
</div>
<li>
Income <i className={`${classes.arrow} ${classes.right}`}></i>
</li>
</div>
<div className={classes["nav-links"]}>
<div className={classes["icon-div"]}>
<LuBadgePercent size={22} />
</div>
<li>
Promote <i className={`${classes.arrow} ${classes.right}`}></i>
</li>
</div>
<div className={classes["nav-links"]}>
<div className={classes["icon-div"]}>
<RiQuestionnaireLine size={22} />
</div>
<li>
Help <i className={`${classes.arrow} ${classes.right}`}></i>
</li>
</div>
</ul>
</nav>
<div className={classes["user-profile"]}>
<div className={classes["user-img"]}>
<img src={userImg} alt="user-img" />
</div>
<div className={classes["user-info"]}>
<h5>Evana</h5>
<p>Project Manager</p>
</div>
<div className={classes["down-arrow"]}>
<IoIosArrowDown />
</div>
</div>
</div>
);
};
export default Navbar;
|
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { UserModule } from './user/user.module';
import { join } from 'path';
import { ProductModule } from './product/product.module';
import { PurchaseModule } from './purchase/purchase.module';
import { KickbackModule } from './kickback/kickback.module';
import { KickbackGeneratedModule } from './kickback-generated/kickback-generated.module';
@Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'mysql',
host: configService.get('DB_HOST'),
port: +configService.get('DB_PORT'),
username: configService.get('DB_USERNAME'),
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_DATABASE'),
entities: [join(process.cwd(), 'dist/**/*.entity.js')],
synchronize: true,
driver: require("mysql"),
}),
inject: [ConfigService],
}),
UserModule,
ProductModule,
PurchaseModule,
KickbackModule,
KickbackGeneratedModule,
],
exports: [TypeOrmModule],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
|
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<div id="app"></div>
<template id="da">
<h2>你好</h2>
<component-a></component-a>
</template>
<template id="component-a">
<h2>我是component-a里的标签</h2>
</template>
<script src="../js/vue.js"></script>
<script>
const ComponentA = {
template: `#component-a`
}
const App = {
template: `#da`,
components: {
// key 组件名称
// volue 组件对象
// key: volue
ComponentA: ComponentA
},
data() {
return {
}
}
}
const app = Vue.createApp(App)
app.mount("#app");
</script>
</body>
</html>
|
//
// VehicleDetailView.swift
// TaskApp
//
// Created by Filip Nesic on 19.4.24..
//
import SwiftUI
struct VehicleDetailView: View {
var selectedModel: VehicleModel
private var formattedNumber: String {
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 6 // Set the maximum number of decimal places
formatter.numberStyle = .decimal
return formatter.string(from: NSNumber(value: selectedModel.rating)) ?? ""
}
var body: some View {
ZStack {
Color.black
.ignoresSafeArea()
VStack {
AsyncImage(url: URL(string: selectedModel.imageURL)) { vehicleImage in
vehicleImage
.resizable()
.frame(width: UIScreen.main.bounds.width - 30, height: 220)
.clipShape(.rect(cornerRadius: 12))
} placeholder: {
ProgressView()
.tint(Color.accentColor)
.controlSize(.large)
}
Group {
HStack {
Text("Model:")
Spacer()
Text(selectedModel.name)
}
HStack {
Text("Rating:")
Spacer()
HStack {
Text("\(formattedNumber)")
.foregroundStyle(Color.white)
Image(systemName: "star.fill")
.foregroundStyle(Color.white)
}
}
HStack {
Text("Cena:")
Spacer()
Text("\(selectedModel.price)€")
}
HStack {
Text("Latitude:")
Spacer()
Text("\(selectedModel.location.latitude)")
}
HStack {
Text("Longitude:")
Spacer()
Text("\(selectedModel.location.longitude)")
}
Spacer()
}
.foregroundStyle(Color.white)
.padding()
}
.toolbar {
ToolbarItem(placement: .principal) {
Text("Vozilo")
.font(.headline)
.foregroundColor(.white)
}
}
}
.background(Color.black)
}
}
|
= About WinZoomPanel
== WinZoomPanel
The WinZoomPanel™ is a control container which allows the user to zoom into its contents and then to scroll through the zoomed contents. It offers all of the same features as the link:winpanel.html[WinPanel], with the exception of the
link:{ApiPlatform}win.misc{ApiVersion}~infragistics.win.misc.ultrapanel~autoscroll.html[AutoScroll]
property, which is forced true because zooming necessitates scrolling to access the entire panel.
== Zooming
The WinZoomPanel's zooming capability is accessed through the
link:{ApiPlatform}win.misc{ApiVersion}~infragistics.win.misc.zoomproperties.html[ZoomProperties]:
* link:{ApiPlatform}win.misc{ApiVersion}~infragistics.win.misc.zoomproperties~allowpanningwithmouse.html[AllowPanningWithMouse]
allows the user to pan a zoomed in WinZoomPanel using Control + mouse drag. This allows the user to reach portions of the WinZoomPanel offscreen due to zooming.
* link:{ApiPlatform}win.misc{ApiVersion}~infragistics.win.misc.zoomproperties~allowpanningwithmouse.html[AllowZoomingWithMouseWheel]
allows the user to zoom the WinZoomPanel using Control+mouse wheel. The WinZoomPanel will receive Control+mouse wheel messages to any of its child controls, giving the user a consistent zooming experience anywhere within the WinZoomPanel.
* link:{ApiPlatform}win.misc{ApiVersion}~infragistics.win.misc.zoomproperties~zoomfactor.html[ZoomFactor]
sets the multiple by which the WinZoomPanel's child controls will be magnified, with 1 as the designed size.
* link:{ApiPlatform}win.misc{ApiVersion}~infragistics.win.misc.zoomproperties~maxzoomfactor.html[MaxZoomFactor]
sets the maximum multiple beyond which the WinZoomPanel will not continue to zoom in.
//* link:{placeholder.html[MinZoomFactor]
//sets the minimum multiple below which the WinZoomPanel will not continue to zoom out. By default, this is set to 1.0, so if zooming out is desired this must be set to a value lower than 1.0.
To implement zooming with our controls, two properties were added to
link:{ApiPlatform}win{ApiVersion}~infragistics.win.ultracontrolbase.html[ControlBase]
regarding their zoom:
* link:{ApiPlatform}win{ApiVersion}~infragistics.win.ultracontrolbase~supportszooming.html[SupportsZooming]
toggles whether or not the control will honor a WinZoomPanel's zooming.
* link:{ApiPlatform}win{ApiVersion}~infragistics.win.ultracontrolbase~zoomfactor.html[ZoomFactor]
gets how much the control is currently zoomed.
== Related Topics
* link:winzoompanel-known-limitations.html[Known Limitations]
* link:winzoompanel-zoom-supported-controls.html[Supported Controls]
|
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate, useParams } from "react-router";
import { setCart, setCartItem } from "../redux/CartSlice";
import { toast } from "react-toastify";
import { motion } from "framer-motion";
function Info() {
const { id } = useParams();
const allItems = useSelector((state) => state.items.jewelryItems);
const [pro, setPro] = useState(null);
const cartItems = useSelector((state) => state.cart.cartItems);
const dispatch = useDispatch();
const cart = useSelector((state) => state.cart.cartShow);
useEffect(() => {
if (allItems) {
setPro(allItems.find((ele) => ele.id === id));
}
}, [id, []]);
const navigate = useNavigate();
const order = () => {
const there = cartItems.find((ele) => ele.id === pro.id);
if (!there) {
dispatch(setCartItem([...cartItems, pro]));
localStorage.setItem("cart", JSON.stringify([...cartItems, pro]));
dispatch(setCart(!cart));
} else {
toast.warning(`This Item is already in your cart`, {
position: "top-center",
theme: "dark",
autoClose: 2000,
});
}
};
return (
<>
{pro ? (
<div>
<motion.div
transition={{ ease: "easeOut", duration: 0.7 }}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="pt-20 w-full h-auto"
>
<div className="px-5 md:px-12 w-full min-h-[80vh] pt-1">
<div className="flex flex-col md:flex-row h-full justify-between gap-3 md:gap-0">
<div className=" w-full md:w-[48%] h-[570px] order-2 md:order-1 ">
<img
src={pro.imgUrl}
alt=""
className="w-full h-full object-cover bg-slate-100"
/>
</div>
<div className=" w-full md:w-[49%] h-auto md:h-[570px] order-1 md:order-2 py-3 flex flex-col md:items-start items-center justify-between">
<div className="text-center md:text-start">
<span className="text-xl text-gray-500">
{pro.category}
</span>
<h1 className="text-5xl tracking-wider mt-4">
{pro.title}
</h1>
{pro.onSale ? (
<div className="flex flex-col gap-2 mt-5">
<div className="flex gap-3 items-center">
<span className="no-underline text-xl font-semibold color-black">
Old Price:
</span>{" "}
<p className="text-xl text-gray-400 line-through font-semibold">
{pro.price}.00DZD
</p>
</div>
<div className="flex gap-3 items-center">
<span className="no-underline text-2xl font-bold color-black">
New Price:
</span>
<p className="text-2xl text-primary font-bold ">
{pro.newPrice}
.00DZD
</p>
</div>
</div>
) : (
<div className="flex gap-3 items-center mt-5">
<span className="no-underline text-2xl font-bold color-black">
Price:
</span>
<p className="text-2xl text-primary font-bold ">
{pro.price}.00DZD
</p>
</div>
)}
{pro.stock > 0 ? (
<p className=" text-green-600 text-2xl mt-6 font-semibold">
{pro.stock} Pice in stock
</p>
) : (
<p className="text-red-600 text-2xl mt-6 font-semibold">
Out of stock
</p>
)}
</div>
<p className=" text-base min-h-[150px] text-gray-500 text-center md:text-start leading-8">
{pro.discription}
</p>
<div className=" w-full flex justify-evenly items-center mt-3 md:mt-0 flex-wrap gap-2 ">
<button
onClick={order}
className=" py-2 px-5 border border-primary rounded-2xl font-semibold text-base transition-all hover:bg-primary hover:text-white ease-in-out duration-200"
type="button"
>
Add to cart
</button>
<button
className="py-2 px-5 border border-primary bg-primary text-white rounded-2xl font-semibold text-base transition-all hover:bg-transparent hover:text-black ease-in-out duration-200"
type="button"
onClick={() => {
navigate(-1);
}}
>
Go back
</button>
</div>
</div>
</div>
</div>
</motion.div>
</div>
) : (
<div className="h-[81vh]"></div>
)}
</>
);
}
export default Info;
|
/*
Cleaning Data in SQL Queries
Skills used: Self Joins, CTE's, Substring Operations, Windows Functions, Converting Data Types, Flagging Duplicates, Deleting Unused Data
*/
SELECT *
FROM PortfolioProject..NashvilleHousing
--------------------------------------------------------------------------------
-- Standardize Date Format
SELECT SaleDate, CONVERT(DATE, SaleDate)
FROM PortfolioProject..NashvilleHousing
ALTER TABLE PortfolioProject..NashvilleHousing
ALTER COLUMN SaleDate Date
--------------------------------------------------------------------------------
-- Populate Property Address data
SELECT *
FROM PortfolioProject..NashvilleHousing
ORDER BY ParcelID
SELECT tbl1.ParcelID, tbl1.PropertyAddress, tbl2.ParcelID, tbl2.PropertyAddress,
ISNULL(tbl1.PropertyAddress, tbl2.PropertyAddress)
FROM PortfolioProject..NashvilleHousing tbl1
JOIN PortfolioProject..NashvilleHousing tbl2
ON tbl1.ParcelID = tbl2.ParcelID
AND tbl1.[UniqueID ] <> tbl2.[UniqueID ]
WHERE tbl1.PropertyAddress IS NULL
UPDATE tbl1
SET PropertyAddress = ISNULL(tbl1.PropertyAddress, tbl2.PropertyAddress)
FROM PortfolioProject..NashvilleHousing tbl1
JOIN PortfolioProject..NashvilleHousing tbl2
ON tbl1.ParcelID = tbl2.ParcelID
AND tbl1.[UniqueID ] <> tbl2.[UniqueID ]
WHERE tbl1.PropertyAddress IS NULL
--------------------------------------------------------------------------------
-- Breaking out Address Into Individual Columns (Address, City, State)
SELECT PropertyAddress
FROM PortfolioProject..NashvilleHousing
SELECT
SUBSTRING(PropertyAddress, 1, CHARINDEX(',', PropertyAddress) - 1) AS Address,
SUBSTRING(PropertyAddress, CHARINDEX(',', PropertyAddress) + 1, LEN(PropertyAddress)) AS City
FROM PortfolioProject..NashvilleHousing
ALTER TABLE PortfolioProject..NashvilleHousing
ADD PropertySplitAddress nvarchar(255);
UPDATE NashvilleHousing
SET PropertySplitAddress = SUBSTRING(PropertyAddress, 1, CHARINDEX(',', PropertyAddress) - 1)
ALTER TABLE PortfolioProject..NashvilleHousing
ADD PropertySplitCity nvarchar(255);
UPDATE NashvilleHousing
SET PropertySplitCity = SUBSTRING(PropertyAddress, CHARINDEX(',', PropertyAddress) + 1, LEN(PropertyAddress))
SELECT OwnerAddress
FROM PortfolioProject..NashvilleHousing
SELECT
PARSENAME(REPLACE(OwnerAddress,',', '.'), 3),
PARSENAME(REPLACE(OwnerAddress,',', '.'), 2),
PARSENAME(REPLACE(OwnerAddress,',', '.'), 1)
FROM PortfolioProject..NashvilleHousing
ALTER TABLE PortfolioProject..NashvilleHousing
ADD OwnerSplitAddress nvarchar(255);
ALTER TABLE PortfolioProject..NashvilleHousing
ADD OwnerSplitCity nvarchar(255);
ALTER TABLE PortfolioProject..NashvilleHousing
ADD OwnerSplitState nvarchar(255);
UPDATE NashvilleHousing
SET OwnerSplitAddress = PARSENAME(REPLACE(OwnerAddress,',', '.'), 3)
UPDATE NashvilleHousing
SET OwnerSplitCity = PARSENAME(REPLACE(OwnerAddress,',', '.'), 2)
UPDATE NashvilleHousing
SET OwnerSplitState = PARSENAME(REPLACE(OwnerAddress,',', '.'), 1)
--------------------------------------------------------------------------------
-- Change Y and N to Yes and No in "Sold as Vacant" field
SELECT DISTINCT(SoldAsVacant), COUNT(SoldAsVacant)
FROM PortfolioProject..NashvilleHousing
GROUP BY SoldAsVacant
ORDER by 2
SELECT SoldAsVacant,
CASE WHEN SoldAsVacant = 'Y' THEN 'Yes'
WHEN SoldAsVacant = 'N' THEN 'No'
END
FROM PortfolioProject..NashvilleHousing
UPDATE NashvilleHousing
SET SoldAsVacant =
CASE WHEN SoldAsVacant = 'Y' THEN 'Yes'
WHEN SoldAsVacant = 'N' THEN 'No'
END
--------------------------------------------------------------------------------
-- Remove Duplicates
WITH RowNumCTE AS
(
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY ParcelID,
PropertyAddress,
SalePrice,
SaleDate,
LegalReference
ORDER BY UniqueID
) row_num
FROM PortfolioProject..NashvilleHousing
)
-- In daily practice I would set up a disposition table that has all the unique ID, and set the disposition code to disposable for IDs where row_num > 1
SELECT *
FROM RowNumCTE
WHERE row_num > 1
--------------------------------------------------------------------------------
-- Delete Unused Columns
ALTER TABLE PortfolioProject..NashvilleHousing
DROP COLUMN OwnerAddress, PropertyAddress, TaxDistrict
-----------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------
--- Importing Data using OPENROWSET and BULK INSERT (ETL)
sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO
USE PortfolioProject
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO
-- Using BULK INSERT
USE PortfolioProject;
GO
BULK INSERT NashvilleHousing FROM 'D:\Portfolio Project\PortfolioProjects\2. SQL Data Cleaning\Nashville Housing Data for Data Cleaning (reuploaded).xlsx'
WITH (
FIELDTERMINATOR = ',',
ROWTERMINATOR = '\n'
);
GO
-- Using OPENROWSET
USE PortfolioProject;
GO
SELECT * INTO NashvilleHousing
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0; Database=D:\Portfolio Project\PortfolioProjects\2. SQL Data Cleaning\Nashville Housing Data for Data Cleaning (reuploaded).xlsx', [Sheet1$]);
GO
|
# frozen_string_literal: true
RSpec.describe Sentence, type: :model do
describe 'associations' do
it { should have_many(:entities) }
end
describe 'validations' do
it { should validate_presence_of(:content) }
it { should validate_uniqueness_of(:content).with_message('has already been taken') }
end
end
|
import pytest
DISCOUNT_PROMOS = {
'11': {
'promo_id': 301,
'promo_type': 'one_plus_one',
'promo_title': 'Два по цене одного',
},
'12': {
'promo_id': 302,
'promo_type': 'gift',
'promo_title': 'Блюдо в подарок',
},
'13': {
'promo_id': 303,
'promo_type': 'discount',
'promo_title': 'Скидка на меню или некоторые позиции',
},
'14': {
'promo_id': 304,
'promo_type': 'free_delivery',
'promo_title': 'Бесплатная доставка',
},
'15': {
'promo_id': 305,
'promo_type': 'plus_happy_hours',
'promo_title': 'Повышенный кешбэк в счастливые часы',
},
'16': {
'promo_id': 306,
'promo_type': 'plus_first_orders',
'promo_title': 'Повышенный кешбэк для новичков',
},
'26': {
'promo_id': 306,
'promo_type': 'plus_first_orders',
'promo_title': 'Повышенный кешбэк для новичков',
},
}
def make_response(found_promos, unknown_discounts):
response = {'found_promos': [], 'unknown_discounts': unknown_discounts}
for discount_id in found_promos:
data = DISCOUNT_PROMOS[discount_id].copy()
data['discount_id'] = discount_id
response['found_promos'].append(data)
return response
@pytest.mark.parametrize(
['discount_ids', 'found_promos', 'unknown_discounts'],
[
pytest.param(
['100', '200'], [], ['100', '200'], id='unknown discounts only',
),
pytest.param(['11'], ['11'], [], id='promo with single discount'),
pytest.param(['26'], ['26'], [], id='promo with multiple discounts'),
pytest.param(
['26', '16'],
['26', '16'],
[],
id='multiple discounts for same promo',
),
pytest.param(
['11', '12', '15', '16', '13', '14'],
['11', '12', '15', '16', '13', '14'],
[],
id='multiple discounts',
),
pytest.param(
['11', '100', '13', '200', '12'],
['11', '13', '12'],
['100', '200'],
id='both known and unknown',
),
],
)
async def test_promos_internal_create_from_core(
taxi_eats_restapp_promo, discount_ids, found_promos, unknown_discounts,
):
response = await taxi_eats_restapp_promo.post(
'/internal/eats-restapp-promo/v1/promos_by_discounts',
json={'discount_ids': discount_ids},
)
assert response.status_code == 200
assert response.json() == make_response(found_promos, unknown_discounts)
|
import {
TableContainer,
Paper,
Table,
TableBody,
TableRow,
TableCell,
Typography,
} from '@mui/material';
import useStoreContext from '../../app/context/StoreContext';
import { curranctFormat } from '../../app/util/util';
export default function BasketSummary() {
const { basket } = useStoreContext();
const subtotal =
basket?.items.reduce((sum, item) => sum + item.quantity * item.price, 0) ??
0;
const deliveryFee = subtotal > 10000 ? 0 : 1600;
return (
<>
<TableContainer component={Paper} variant={'outlined'}>
<Table>
<TableBody>
<TableRow>
<TableCell colSpan={2}>Subtotal</TableCell>
<TableCell align="right">{curranctFormat(subtotal)}</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={2}>Delivery fee*</TableCell>
<TableCell align="right">{curranctFormat(deliveryFee)}</TableCell>
</TableRow>
<TableRow>
<TableCell colSpan={2}>Total</TableCell>
<TableCell align="right">
{curranctFormat(subtotal + deliveryFee)}
</TableCell>
</TableRow>
<TableRow>
<TableCell>
<span style={{ fontStyle: 'italic' }}>
*Orders over 1000 SEK qualify for free delivery
</span>
</TableCell>
</TableRow>
</TableBody>
</Table>
</TableContainer>
</>
);
}
|
<%= form_for @booking do |f|%>
<% @booking.errors.full_messages.each do |error| %>
<ul>
<li><%= error %></li>
</ul>
<% end %>
<div class="booking">
<div class="row">
<div class="form-group">
<%= f.label :requested_date, "Date of booking:",:class=>"col-sm-8 control-label ml-3" %>
<div class="col-sm-12 ml-3">
<%= f.date_select :requested_date,default: Date.today+1.day %>
<div class="row ml-2">
<small>Note: Do not Provide date which is more than 10 days from now</small>
</div>
</div>
</div>
<div class="form-group">
<%= f.label :no_of_guests, "No. of guests : ",:class=>"col-sm-12 mx-2 control-label" %>
<div class="col-sm-12 mx-4">
<%= f.select :no_of_guests, [2,3,4,5,6,7,8,9,10], default: 2 %>
</div>
</div>
<div class="form-group">
<%= f.label :requested_time, "Time : ",:class=>"col-sm-8 control-label" %>
<div class="col-sm-12">
<%= f.time_select :requested_time, default: current_time %>
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<%= f.label :name, "Name : ",:class=>"col-sm-8 control-label ml-3" %>
<div class="col-sm-12">
<%= f.text_field :name, :class=>"form-control ml-3", :value => current_user.username %>
</div>
</div>
<div class="form-group">
<%= f.label :email, "Email : ",:class=>"col-sm-8 control-label" %>
<div class="col-sm-12">
<%= f.email_field :email, :class=>"form-control", :value => current_user.email %>
</div>
</div>
<div class="form-group">
<%= f.label :phone, "Mobile No : ",:class=>"col-sm-8 control-label" %>
<div class="col-sm-12">
<%= f.text_field :phone, :class=>"form-control" %>
</div>
</div>
</div>
<%= f.hidden_field :restaurant_id,:value => session[:restaurant_id] %>
<%= f.hidden_field :user_id,:value => current_user.id %>
<%= f.submit "Submit", :class=>"btn btn-primary ml-3 mb-2" %>
<div class="row ml-3">
<small>Note: You can Edit or cancel your Booking till it is 2 days left for your desired booking date</small>
</div>
</div>
<% end %>
|
import type { NextPage } from "next";
import Card from "../components/Card";
import styles from "../styles/Home.module.css";
import { Input, Button, Link } from "@nextui-org/react";
import { Text } from "@nextui-org/react";
import { useRouter } from "next/router";
import { useCallback, useState } from "react";
import { setCookies } from "cookies-next";
import Header from "../components/Header";
const Home: NextPage = () => {
const router = useRouter();
const [disappear, setDisappear] = useState(false);
const toSignIn = useCallback(() => {
setDisappear(true);
setTimeout(() => {
router.push("signin");
}, 300);
}, [router]);
const [email, setEmail] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const [wrong, setWrong] = useState(false);
const handleSubmit = async () => {
if (!loading) {
setLoading(true);
if (email && password && username) {
try {
const res = await fetch("http://localhost:8000/auth/signup", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username, email, password }),
}).then((t) => {
if (t.status === 400) return null;
return t.json();
});
if (res) {
router.push("/signin");
} else {
setWrong(true);
}
} catch (e) {
setWrong(true);
}
}
setLoading(false);
}
};
return (
<div className={styles.container}>
<Header />
<div className="flex flex-col gap-3 justify-start items-start">
<h1 className="header-1">Sign Up</h1>
<br />
{wrong && (
<div className="p-6 rounded-xl mb-5 w-full flex justify-center bg-red-200 text-red-600 border border-red-100 text-sm">
<p>Make sure the form is valid or email is already used</p>
</div>
)}
{/* username input */}
<div
style={{
marginBottom: "10px",
display: "flex",
flexDirection: "column",
}}
>
<Input
label="Username"
placeholder="Username"
onChange={(event) => {
setUsername(event.target.value);
}}
></Input>
</div>
{/* email input */}
<div
style={{
marginBottom: "10px",
display: "flex",
flexDirection: "column",
}}
>
<Input
label="Email"
placeholder="Email"
onChange={(event) => {
setEmail(event.target.value);
}}
></Input>
</div>
{/* password input */}
<div
style={{
marginBottom: "10px",
display: "flex",
flexDirection: "column",
}}
>
<Input.Password
label="Password"
placeholder="Password"
onChange={(event) => {
setPassword(event.target.value);
}}
></Input.Password>
</div>
{/* password input */}
<div
style={{
marginBottom: "20px",
display: "flex",
flexDirection: "column",
}}
>
<Input.Password
label="Repeat Password"
placeholder="Repeat Password"
></Input.Password>
</div>
<div style={{ marginBottom: "10px" }}>
<Text>
Already have an account? <Link onClick={toSignIn}>Sign In</Link>{" "}
</Text>
</div>
<div className={styles.bottom}>
<Button className="bg-pink-400" onClick={handleSubmit}>
Sign Up
</Button>
</div>
</div>
</div>
);
};
export default Home;
|
import express, { Router, Request, Response, RequestHandler } from "express";
import { RouterHandler } from "./RouteHandler";
import { STATUS_CODE } from "../enum/statusCode";
import { addExpressHandlers } from "../helpers/expressHandlers";
export class RouteManager {
private route: Router;
public readonly path: string;
private controller: any;
private routeHandler: RouterHandler;
constructor(path: string, controller: any) {
this.controller = controller;
this.path = path;
this.route = express.Router();
this.routeHandler = new RouterHandler();
}
getRouter() {
return this.route;
}
get(
endpoint: string,
callback: RequestHandler,
middlewares?: RequestHandler[]
) {
const getHandler = (req: Request, res: Response) =>
this.routeHandler.executeCallbackWithResponse(
req,
res,
STATUS_CODE.SUCCESS,
callback.bind(this.controller)
);
const handlers = addExpressHandlers(getHandler, middlewares);
this.route.get(endpoint, ...handlers);
}
post(
endpoint: string,
callback: RequestHandler,
middlewares?: RequestHandler[]
) {
const postHandler = (req: Request, res: Response) =>
this.routeHandler.executeCallbackWithResponse(
req,
res,
STATUS_CODE.CREATED,
callback.bind(this.controller)
);
const handlers = addExpressHandlers(postHandler, middlewares);
this.route.post(endpoint, ...handlers);
}
patch(
endpoint: string,
callback: RequestHandler,
middlewares?: RequestHandler[]
) {
const handlers = addExpressHandlers(
(req: Request, res: Response) =>
this.routeHandler.executeCallbackWithResponse(
req,
res,
STATUS_CODE.SUCCESS,
callback.bind(this.controller)
),
middlewares
);
this.route.patch(endpoint, ...handlers);
}
delete(
endpoint: string,
callback: RequestHandler,
middlewares?: RequestHandler[]
) {
const deleteHandler = (req: Request, res: Response) =>
this.routeHandler.executeCallbackWithResponse(
req,
res,
STATUS_CODE.SUCCESS,
callback.bind(this.controller)
);
const handlers = addExpressHandlers(deleteHandler, middlewares);
this.route.delete(endpoint, handlers);
}
}
|
import React, { ChangeEventHandler, useEffect, useState } from 'react';
import styled from 'styled-components';
import useTheme from '@material-ui/core/styles/useTheme';
import Avatar from '@material-ui/core/Avatar';
import Fab from '@material-ui/core/Fab';
import Chip from '@material-ui/core/Chip';
import IconButton from '@material-ui/core/IconButton';
import TextField from '@material-ui/core/TextField';
import Typography from '@material-ui/core/Typography';
import ChevronLeft from '@material-ui/icons/ChevronLeft';
import Send from '@material-ui/icons/Send';
import usePanel, { IPanel, IPanelContext } from '../../hooks/usePanel';
import Div from '../elements/Div';
import MessageList from './MessageList';
import { IUser, IMessage } from '../../types/types';
import getFixtures from '../../fixtures';
type IMessagesProps = {
recipients: IUser[];
};
const NewMessageDiv = styled(Div)`
${({ theme }): string => `
& > * {
margin: ${theme.spacing(1)}px;
}
`}
`;
const StyledChip = styled(Chip)`
${({ theme }): string => `
margin: ${theme.spacing(0.5)}px;
`}
`;
const StyledTextField = styled(TextField)`
flex-grow: 1;
`;
const Messages: React.FC<IMessagesProps> = ({ recipients }) => {
const theme = useTheme();
const { updatePanel } = usePanel() as IPanelContext;
const [newMessage, setNewMessage] = useState('');
const [loading, setLoading] = useState(true);
const [messages, setMessages] = useState<IMessage[] | undefined>();
useEffect(() => {
let isMounted = true;
getFixtures(['messages'], ({ messages: foundMessages }) => {
if (isMounted) {
setMessages(foundMessages);
setLoading(false);
}
});
return (): void => {
isMounted = false;
};
}, []);
const handleChange: ChangeEventHandler<HTMLInputElement> = (e) => {
setNewMessage(e.target.value);
};
const handleSend = (): void => {
setNewMessage('');
};
const handleReturn = (): void => {
updatePanel({ screenIndex: 1 });
};
return (
<Div flex flexColumn>
<Div flex alignItems="flex-start" p={theme.spacing(1, 0)}>
<IconButton onClick={handleReturn}>
<ChevronLeft />
</IconButton>
<Div flex flexWrap maxHeight="300px" overflow="auto">
{[
<Typography key="a">À : </Typography>,
...recipients.map(({ _id, name, img }) => (
<StyledChip
avatar={<Avatar alt={name} src={img} />}
key={_id}
label={name}
size="small"
/>
)),
]}
</Div>
</Div>
<MessageList loading={loading} messages={messages} />
<NewMessageDiv flex align="flex-start">
<StyledTextField
multiline
onChange={handleChange}
rowsMax={5}
value={newMessage}
variant="outlined"
/>
<Fab color="secondary" onClick={handleSend}>
<Send />
</Fab>
</NewMessageDiv>
</Div>
);
};
export const displayMessages = (
recipients: IUser[],
updatePanel: (updates: Partial<IPanel>) => void,
) => (): void => {
updatePanel({
chapters: [null, null, <Messages key="messages" recipients={recipients} />],
screenIndex: 2,
open: true,
});
};
export default Messages;
|
import React from "react";
import { useState } from "react";
import { Routes, Route } from "react-router-dom";
import Dashboard from "./Dashboard";
import Resume from "./pages/resume";
import Home from "./pages/Home";
import { CssBaseline, ThemeProvider } from "@mui/material";
import { ColorModeContext, useMode } from "./theme";
import Topbar from "./components/Topbar";
import Sidebar from "./components/Sidebar";
const App = () => {
const [theme, colorMode] = useMode();
const [isSidebar, setIsSidebar] = useState(true);
return (
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>
<CssBaseline />
<div className="app">
<Sidebar isSidebar={isSidebar} />
<main className="content">
<Topbar setIsSidebar={setIsSidebar} />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/admin/dashboard" element={<Dashboard />} />
<Route path="/user/resume-builder" element={<Resume />} />
</Routes>
</main>
</div>
</ThemeProvider>
</ColorModeContext.Provider>
);
};
export default App;
|
extends Node
class_name ThothSerializer
######################################
## variable serialization
######################################
static func _serialize_variable(variable, object_convert_to_references = false):
match typeof(variable):
TYPE_NIL:
return null
TYPE_VECTOR2:
return _serialize_vector2(variable)
TYPE_VECTOR3:
return _serialize_vector3(variable)
TYPE_COLOR:
return _serialize_color(variable)
TYPE_BASIS:
return _serialize_basis(variable)
TYPE_TRANSFORM3D:
return _serialize_transform(variable)
TYPE_TRANSFORM2D:
return _serialize_transform2d(variable)
TYPE_ARRAY:
return _serialize_array(variable)
TYPE_OBJECT:
if object_convert_to_references:
return _serialize_object_reference(variable)
return _serialize_object(variable)
return variable
######################################
## data types serialization
######################################
static func _serialize_vector2(input):
return {
"type": "vector2",
"x" : input.x,
"y" : input.y
}
static func _serialize_vector3(input):
return {
"type": "vector3",
"x" : input.x,
"y" : input.y,
"z" : input.z
}
static func _serialize_color(input):
return {
"type": "color",
"r" : input.r,
"g" : input.g,
"b" : input.b,
"a" : input.a
}
static func _serialize_basis(input):
return {
"type": "basis",
"x": _serialize_variable(input.x),
"y": _serialize_variable(input.y),
"z": _serialize_variable(input.z)
}
static func _serialize_transform(input):
return {
"type": "transform",
"basis": _serialize_variable(input.basis),
"origin": _serialize_variable(input.origin)
}
static func _serialize_transform2d(input):
return {
"type": "transform2d",
"x": _serialize_variable(input.x),
"y": _serialize_variable(input.y),
"origin": _serialize_variable(input.origin)
}
static func _serialize_array(input):
var array = []
for entry in input:
array.push_back(_serialize_variable(entry, true))
return {
"type": "array",
"data": array
}
static func _serialize_object(object):
if not is_instance_valid(object):
return null
#find if object is serializable
var serializable = ThothSerializable._serialize_get_serializable(object)
if serializable == null:
return null
var serialized = {
"type" : "object",
"name": _serialize_get_name(object),
}
if object is TileMap:
serialized["core_object"] = true
serialized["object_type"] = "TileMap"
elif object.scene_file_path == "":
serialized["core_object"] = true
serialized["object_type"] = object.get_class()
else:
serialized["scene_file_path"] = object.scene_file_path
#serialize transformation
if serializable.transform:
serialized["transform"] = _serialize_variable(object.transform)
#serialize object variables
if len(serializable.variables):
serialized["variables"] = {}
for variable in serializable.variables:
serialized["variables"][variable] = _serialize_variable(object.get(variable), true)
#serialize children
if serializable.children:
serialized["children"] = _serialize_children(object)
return serialized
static func _serialize_object_reference(object):
return {
"type" : "object_reference",
"name": _serialize_get_path(object)
}
static func _serialize_children(object):
var children = {}
for child in object.get_children():
if child is ThothSerializable or child is ThothGameState:
continue
if ThothSerializable._serialize_get_serializable(child):
children[_serialize_get_name(child)] = _serialize_object(child)
else:
var recurse = _serialize_children(child)
if recurse == {}:
continue
children[_serialize_get_name(child)] = recurse
return children
static func _serialize_get_name(object):
return str(object.name).replace("@","_")
static func _serialize_get_path(object):
return str(object.get_path()).replace("@","_")
|
<template>
<v-container>
<v-row>
<v-col class="text-left">
<span class="body-1">Dodatno pretraži prema:</span>
</v-col>
</v-row>
<v-row>
<v-col>
<v-select
v-model="selectedBotanicalFamilies"
label="Botaničkoj porodici"
placeholder="npr. Usnače"
clearable
multiple
:items="botanicalFamilies"
item-text="croatianName"
item-value="id"
color="green"
item-color="green"
></v-select>
</v-col>
</v-row>
<v-row>
<v-col>
<v-select
v-model="selectedBioactiveSubstances"
label="Bioaktivnoj tvari"
placeholder="npr. Eterično ulje"
clearable
multiple
:items="bioactiveSubstances"
item-text="name"
item-value="id"
color="green"
item-color="green"
></v-select>
</v-col>
</v-row>
<v-row>
<v-col>
<v-select
v-model="selectedUsefulParts"
label="Uporabnom dijelu"
placeholder="npr. Nadzemni dio"
clearable
multiple
:items="usefulParts"
item-text="croatianName"
item-value="id"
color="green"
item-color="green"
></v-select>
</v-col>
</v-row>
<v-row>
<v-col>
<v-btn
color="green"
dark
@click="search"
width="100%"
>
Pretraži
</v-btn>
</v-col>
</v-row>
</v-container>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
name: 'AdditionalFilters',
data() {
return {
selectedBotanicalFamilies: [],
selectedBioactiveSubstances: [],
selectedUsefulParts: [],
};
},
watch: {
'$route.query.botanickePorodice': {
immediate: true,
deep: true,
handler() {
const {
botanickePorodice,
} = this.$route.query;
this.selectedBotanicalFamilies = botanickePorodice
? botanickePorodice.split(',').map((val) => parseInt(val, 0))
: [];
},
},
'$route.query.bioaktivneTvari': {
immediate: true,
deep: true,
handler() {
const {
bioaktivneTvari,
} = this.$route.query;
this.selectedBioactiveSubstances = bioaktivneTvari
? bioaktivneTvari.split(',').map((val) => parseInt(val, 0))
: [];
},
},
'$route.query.uporabniDijelovi': {
immediate: true,
deep: true,
handler() {
const {
uporabniDijelovi,
} = this.$route.query;
this.selectedUsefulParts = uporabniDijelovi
? uporabniDijelovi.split(',').map((val) => parseInt(val, 0))
: [];
},
},
},
computed: {
...mapState({
botanicalFamilies: (state) => state.botanicalFamily.botanicalFamilies,
bioactiveSubstances: (state) => state.bioactiveSubstance.bioactiveSubstances,
usefulParts: (state) => state.usefulPart.usefulParts,
}),
},
created() {
if (!this.botanicalFamilies.length) {
this.loadBotanicalFamilies();
}
if (!this.bioactiveSubstances.length) {
this.loadBioactiveSubstances();
}
if (!this.usefulParts.length) {
this.loadUsefulParts();
}
},
methods: {
...mapActions({
loadBotanicalFamilies: 'botanicalFamily/loadAll',
loadBioactiveSubstances: 'bioactiveSubstance/loadAll',
loadUsefulParts: 'usefulPart/loadAll',
}),
search() {
if (this.selectedBotanicalFamilies.length
|| this.selectedBioactiveSubstances.length
|| this.selectedUsefulParts.length
) {
this.$router.push({
name: 'SearchResult',
query: {
naziv: this.$route.query.naziv,
botanickePorodice: this.selectedBotanicalFamilies.length
? this.selectedBotanicalFamilies.map((val) => val).join(',')
: undefined,
bioaktivneTvari: this.selectedBioactiveSubstances.length
? this.selectedBioactiveSubstances.map((val) => val).join(',')
: undefined,
uporabniDijelovi: this.selectedUsefulParts.length
? this.selectedUsefulParts.map((val) => val).join(',')
: undefined,
},
}).catch(() => {});
}
},
},
};
</script>
|
/**
* Heading
*
* Set heading size and vertical spacing
*
* @param {int} modular-scale-factor - Heading size on the modular scale
* @param {int} [top-vertical-rhythm-factor: 1] - Heading top margin in vertical rhythm unit
* @param {int} [bottom-vertical-rhythm-factor: 1] - Heading bottom margin in vertical rhythm unit
*
* @example @include t-heading(1, 1, 1);
*/
@mixin t-heading(
$modular-scale-factor,
$top-vertical-rhythm-factor: 1,
$bottom-vertical-rhythm-factor: 1
) {
margin-bottom: t-vertical-rhythm(
$bottom-vertical-rhythm-factor,
"em",
t-modular-scale($modular-scale-factor)
);
font-size: t-modular-scale($modular-scale-factor);
* + & {
margin-top: t-vertical-rhythm(
$top-vertical-rhythm-factor,
"em",
t-modular-scale($modular-scale-factor)
);
}
@content;
}
// These types are also available as utilities: .u-heading--*
@mixin t-heading--xl {
@include t-heading(6, 2, 2) {
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
}
}
@mixin t-heading--lg {
@include t-heading(5, 2, 2) {
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
}
}
@mixin t-heading--1 {
@include t-heading(4, 2, 2) {
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
}
}
@mixin t-heading--2 {
@include t-heading(3, 2, 2) {
font-weight: 700;
}
}
@mixin t-heading--3 {
@include t-heading(2, 2, 1) {
font-style: italic;
font-weight: 400;
}
}
@mixin t-heading--4 {
@include t-heading(1, 1, 1) {
font-weight: 400;
}
}
@mixin t-heading--5 {
@include t-heading(0, 1, 1) {
font-weight: 400;
}
}
@mixin t-heading--6 {
@include t-heading(-1, 1, 1) {
font-weight: 400;
}
}
|
import copy
import datetime as dt
import pytest
from transactions.clients.trust import event_stats
_UNCHANGED_EVENT_STATS = [
{
'created': dt.datetime(2020, 4, 3, 3, 2),
'detailed': {'card': {'CheckBasket': {'success': 2, 'error': 1}}},
'success': 2,
'error': 1,
'name': 'billing_call_simple',
},
]
@pytest.mark.now('2020-04-03T03:02:08+00:00')
@pytest.mark.config(
TRANSACTIONS_UPDATE_EVENT_STATS_FOR=['card'],
TRANSACTIONS_UPDATE_SERVICE_STATS_FOR=['card'],
TRANSACTIONS_USE_LIGHTWEIGHT_STATUS_ENABLED=True,
TRANSACTIONS_USE_LIGHTWEIGHT_STATUS_PROBABILITY=1.0,
)
@pytest.mark.parametrize(
(
'pass_collection, billing_service_id, method, status, '
'expected_event_stats'
),
[
(
True,
'card',
'CheckBasket',
'success',
[
{
'created': dt.datetime(2020, 4, 3, 3, 2),
'detailed': {
'card': {'CheckBasket': {'success': 3, 'error': 1}},
},
'success': 3,
'error': 1,
'name': 'billing_call_simple',
},
],
),
(False, 'card', 'CheckBasket', 'success', _UNCHANGED_EVENT_STATS),
(True, 'uber', 'CheckBasket', 'success', _UNCHANGED_EVENT_STATS),
],
)
@pytest.mark.parametrize(
'events_to_statistics_enabled',
[
pytest.param(False, id='statistics_disabled'),
pytest.param(
True,
marks=pytest.mark.config(
TRANSACTIONS_BILLING_EVENTS_TO_STATISTICS_ENABLED=True,
),
id='statistics_enabled',
),
],
)
@pytest.mark.filldb(event_stats='for_test_save_for')
async def test_save_for(
db,
web_context,
mock_statistics_agent,
pass_collection,
billing_service_id,
method,
status,
expected_event_stats,
events_to_statistics_enabled,
):
@mock_statistics_agent('/v1/metrics/store')
async def statistics_handler(request):
assert request.json == {
'metrics': [
{
'name': (
'billing_call_simple.detailed.card.CheckBasket.success'
),
'value': 1,
},
{'name': 'billing_call_simple.total.success', 'value': 1},
],
}
return {}
config = web_context.config
collection = db.event_stats if pass_collection else None
stats = event_stats.EventStats(
collection, config, web_context.clients.statistics_agent,
)
await stats.save_for(billing_service_id, method, status)
docs = await db.event_stats.find().to_list(None)
_assert_same_event_stats(docs, expected_event_stats)
should_report_for_service = (
billing_service_id in config.TRANSACTIONS_UPDATE_SERVICE_STATS_FOR
)
if events_to_statistics_enabled and should_report_for_service:
assert statistics_handler.times_called == 1
def _assert_same_event_stats(actual, expected):
assert _prepare(actual) == _prepare(expected)
def _prepare(event_stats_):
result = copy.deepcopy(sorted(event_stats_, key=_by_created))
for item in result:
item.pop('_id', None)
return result
def _by_created(stat):
return stat['created']
|
def goodIntegers(arr: list) -> list[int]:
"""Returns list of numbers that its value is equal to number of elements less than themselves.
Args:
arr (list): list of integers, non-repeated
Returns:
list[int]: list of good integers
"""
n = len(arr)
goodIntegers = []
arr.sort()
for i in range(n):
if arr[i]==i:
goodIntegers.append(arr[i])
return goodIntegers
arr = [-1, -2, 2, 3 ,4]
result = goodIntegers(arr)
print(result)
|
select * from
CovidDeaths order by 3,4;
--select * from
--CovidVaccinations order by 3,4;
select Location, date,total_cases,new_cases,total_deaths,population
from CovidDeaths
order by 1,2;
--total cases vs total deaths
select location,date,total_cases,total_deaths,(total_deaths/total_cases) * 100 as DeathPercentage
from CovidDeaths
where location = 'INDIA'
order by 1,2;
--totalcases vs population
select location,date,total_cases,population,(total_cases/population)*100 as ChancesOfInfection
from CovidDeaths
--where location = 'INDIA'
order by 1,2;
--Countries with highest Infection rate
select location,MAX(total_cases) as max_cases,population,MAX((total_cases /population))*100 as PercentagePopulationInfected
from CovidDeaths
--where location = 'INDIA
group by location,population
order by PercentagePopulationInfected DESC;
--Countries with highest death percentage per Population
select location,population,max(total_deaths),max((total_deaths/population)) * 100 as PercentageDeath
from CovidDeaths
group by location,population
order by PercentageDeath DESC;
--Countries with highest death count
select location,max(cast (total_deaths as int)) as TotalDeathCount
from CovidDeaths
where continent is not null
group by location
order by TotalDeathCount DESC;
--Continents with highest death count
select continent,max(cast (total_deaths as int)) as TotalDeathCount
from CovidDeaths
where continent is not null
group by continent
order by TotalDeathCount DESC;
--
select date,sum(new_cases) as TotalCases,sum(cast (new_deaths as int)) as TotalDeaths,sum(cast (new_deaths as int))/sum(new_cases) * 100 as DeathPercentage
from CovidDeaths
where continent is not null
group by date
order by 1,2;
-- joining covid deaths and covid vaccinations table
select *
from CovidDeaths dea
join CovidVaccinations vac
on dea.location=vac.location and
dea.date=vac.date;
--total population vs total vaccination *****57:00***
select dea.continent,dea.location,dea.date,dea.population,vac.new_vaccinations,vac.total_vaccinations
from CovidDeaths dea
join CovidVaccinations vac
on dea.location=vac.location and
dea.date=vac.date
where dea.continent is not null
order by 2,3;
--partition
select dea.continent,dea.location,dea.date,dea.population,vac.new_vaccinations,
sum(convert (bigint ,vac.new_vaccinations)) over (partition by dea.Location order by dea.Location,dea.date)
as PeopleVaccinated
from CovidDeaths dea
join CovidVaccinations vac
on dea.location=vac.location and
dea.date=vac.date
where dea.continent is not null
order by 2,3;
--cte
with PopVsVac (Continent,location,date,population,new_vaccinations,PeopleVaccinated)
as
(
select dea.continent,dea.location,dea.date,dea.population,vac.new_vaccinations,
sum(convert (bigint ,vac.new_vaccinations)) over (partition by dea.Location order by dea.Location,dea.date)
as PeopleVaccinated
from CovidDeaths dea
join CovidVaccinations vac
on dea.location=vac.location and
dea.date=vac.date
--where dea.continent is not null
--order by 2,3
)
select *,(PeopleVaccinated/Population) * 100 from PopVsVac
--temp table
Drop table if exists #PercentPopulationVaccinated
create table #PercentPopulationVaccinated(
continent nvarchar(255),
location nvarchar(255),
date datetime,
population numeric,
new_vaccinations numeric,
PeopleVaccinated numeric)
insert into #PercentPopulationVaccinated
select dea.continent,dea.location,dea.date,dea.population,vac.new_vaccinations,
sum(convert (bigint ,vac.new_vaccinations)) over (partition by dea.Location order by dea.Location,dea.date)
as PeopleVaccinated
from CovidDeaths dea
join CovidVaccinations vac
on dea.location=vac.location and
dea.date=vac.date
--where dea.continent is not null
select *,(PeopleVaccinated/Population) * 100 from #PercentPopulationVaccinated
--creating data to store for visualizations
create view PercentPopulationVaccinated as
select dea.continent,dea.location,dea.date,dea.population,vac.new_vaccinations,
sum(convert (bigint ,vac.new_vaccinations)) over (partition by dea.Location order by dea.Location,dea.date)
as PeopleVaccinated
from CovidDeaths dea
join CovidVaccinations vac
on dea.location=vac.location and
dea.date=vac.date
where dea.continent is not null
|
import {
HttpException,
HttpStatus,
Injectable,
NotFoundException,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { validate } from 'uuid';
import { User } from '../users/user.model';
import { Task } from './task.model';
import { ListService } from '../lists/list.service';
import { CreateTaskDto } from './dto/create.task.dto';
import { UpdateTaskDto } from './dto/update.task.dto';
@Injectable()
export class TaskService {
constructor(
@InjectModel(Task) private taskRepository: typeof Task,
private listService: ListService
) {}
async createTask(user: User, id: string, dto: CreateTaskDto): Promise<Task> {
if (!validate(id))
throw new HttpException(
'The id of the user is invalid!',
HttpStatus.BAD_REQUEST
);
if (dto.urgency) {
const urgencyList = ['LOW', 'MEDIUM', 'HIGH'];
if (!urgencyList.includes(dto.urgency))
throw new HttpException(
`The urgency state - ${dto.urgency} is not compatible`,
HttpStatus.BAD_REQUEST
);
}
const list = await this.listService.getUserListByUserId(user, id);
const task = await this.taskRepository.create(dto, {
returning: true,
include: { all: true },
});
if (!task)
throw new HttpException('Task is not created!', HttpStatus.BAD_REQUEST);
task.list_id = list.id;
const currentTask = await task.save();
return currentTask;
}
async getAllTasks(user: User, id: string): Promise<Task[]> {
if (!validate(id))
throw new HttpException(
'The id of the user is invalid!',
HttpStatus.BAD_REQUEST
);
const list = await this.listService.getUserListByUserId(user, id);
const tasks = await this.taskRepository.findAll({
where: { list_id: list.id },
include: { all: true },
});
if (!tasks) throw new NotFoundException('Tasks not found');
return tasks;
}
async getOneTask(user: User, id: string): Promise<Task> {
if (!validate(id))
throw new HttpException(
'The id of the user is invalid!',
HttpStatus.BAD_REQUEST
);
const lists = await this.listService.getUserListsByUserId(user);
const isOwner = lists.some((val) =>
val.task.some((item) => item.id === id)
);
if (!isOwner) throw new NotFoundException('Task not found');
const task = await this.taskRepository.findOne({
where: { id: id },
include: { all: true },
});
return task;
}
async updateTask(user: User, id: string, dto: UpdateTaskDto): Promise<Task> {
if (!validate(id))
throw new HttpException(
'The id of the user is invalid!',
HttpStatus.BAD_REQUEST
);
if (
!dto.description &&
!dto.title &&
!dto.urgency &&
typeof dto.isDone !== 'boolean'
)
throw new HttpException(
'You passed 0 args to update!',
HttpStatus.BAD_REQUEST
);
if (dto.urgency) {
const urgencyList = ['LOW', 'MEDIUM', 'HIGH'];
if (!urgencyList.includes(dto.urgency))
throw new HttpException(
`The urgency state - ${dto.urgency} is not compatible`,
HttpStatus.BAD_REQUEST
);
}
const lists = await this.listService.getUserListsByUserId(user);
const isOwner = lists.some((val) =>
val.task.some((item) => item.id === id)
);
if (!isOwner) throw new NotFoundException('Task not found');
const task = await this.taskRepository.findOne({
where: { id: id },
});
if (!task) throw new NotFoundException('Task not found!');
await task.update(
{
title: dto?.title,
description: dto?.description,
urgency: dto?.urgency,
isDone: dto?.isDone,
},
{ silent: false }
);
await task.reload();
return task;
}
async deleteTaskById(user: User, id: string): Promise<void> {
if (!validate(id))
throw new HttpException(
'The id of the user is invalid!',
HttpStatus.BAD_REQUEST
);
const lists = await this.listService.getUserListsByUserId(user);
const isOwner = lists.some((val) =>
val.task.some((item) => item.id === id)
);
if (!isOwner) throw new NotFoundException('Task not found');
await this.taskRepository.destroy({
where: { id: id },
individualHooks: true,
});
}
}
|
import 'dart:developer';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'inicio.dart';
import 'edicao.dart';
import 'contatos.dart';
import 'sobre.dart';
class Scanner extends StatelessWidget {
final scaffoldKey = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text("Scanner"),
),
drawer: Drawer(
child: SafeArea(
child:Column(
children: [
const SizedBox(height: 10),
ListTile(
leading: Icon(Icons.home),
title: Text("Home"),
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Inicio()),
);
},
),
ListTile(
leading: Icon(Icons.edit),
title: Text("Editar Perfil"),
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Edicao()),
);
},
),
ListTile(
leading: Icon(Icons.contacts_outlined),
title: Text("Meus Contatos"),
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Contatos()),
);
},
),
ListTile(
leading: Icon(Icons.info_outline),
title: Text("Sobre"),
onTap: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Sobre()),
);
},
),
],
)
)
),
body: Container(
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Image.asset('images/logo.png', width: 100, height: 100,),
const SizedBox(height: 30),
FilledButton.tonal(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => const QRViewExample(),
));
},
child: Text(' Scannear QR Code'),
),
]
)
)
);
}
}
class QRViewExample extends StatefulWidget {
const QRViewExample({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _QRViewExampleState();
}
class _QRViewExampleState extends State<QRViewExample> {
Barcode? result;
QRViewController? controller;
final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');
// In order to get hot reload to work we need to pause the camera if the platform
// is android, or resume the camera if the platform is iOS.
@override
void reassemble() {
super.reassemble();
if (Platform.isAndroid) {
controller!.pauseCamera();
}
controller!.resumeCamera();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(flex: 4, child: _buildQrView(context)),
Expanded(
flex: 1,
child: FittedBox(
fit: BoxFit.contain,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
if (result != null)
Text(
'Barcode Type: ${describeEnum(
result!.format)} Data: ${result!.code}')
else
const Text('Scan a code'),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
margin: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () async {
await controller?.toggleFlash();
setState(() {});
},
child: FutureBuilder(
future: controller?.getFlashStatus(),
builder: (context, snapshot) {
return Text('Flash: ${snapshot.data}');
},
)),
),
Container(
margin: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () async {
await controller?.flipCamera();
setState(() {});
},
child: FutureBuilder(
future: controller?.getCameraInfo(),
builder: (context, snapshot) {
if (snapshot.data != null) {
return Text(
'Camera facing ${describeEnum(
snapshot.data!)}');
} else {
return const Text('loading');
}
},
)),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
margin: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () async {
await controller?.pauseCamera();
},
child: const Text('pause',
style: TextStyle(fontSize: 20)),
),
),
Container(
margin: const EdgeInsets.all(8),
child: ElevatedButton(
onPressed: () async {
await controller?.resumeCamera();
},
child: const Text('resume',
style: TextStyle(fontSize: 20)),
),
)
],
),
],
),
),
)
],
),
);
}
Widget _buildQrView(BuildContext context) {
// For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
var scanArea = (MediaQuery
.of(context)
.size
.width < 400 ||
MediaQuery
.of(context)
.size
.height < 400)
? 150.0
: 300.0;
// To ensure the Scanner view is properly sizes after rotation
// we need to listen for Flutter SizeChanged notification and update controller
return QRView(
key: qrKey,
onQRViewCreated: _onQRViewCreated,
overlay: QrScannerOverlayShape(
borderColor: Colors.red,
borderRadius: 10,
borderLength: 30,
borderWidth: 10,
cutOutSize: scanArea),
onPermissionSet: (ctrl, p) => _onPermissionSet(context, ctrl, p),
);
}
void _onQRViewCreated(QRViewController controller) {
setState(() {
this.controller = controller;
});
controller.scannedDataStream.listen((scanData) {
setState(() {
result = scanData;
});
});
}
void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) {
log('${DateTime.now().toIso8601String()}_onPermissionSet $p');
if (!p) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('no Permission')),
);
}
}
@override
void dispose() {
controller?.dispose();
super.dispose();
}
}
|
/** @format */
import React, { useState, useEffect } from 'react';
import { isEmpty } from 'lodash';
import { useDebounce } from '../utils/hooks';
import { TextField, InputAdornment } from '@material-ui/core';
import { Search, Clear } from '@material-ui/icons';
function SearchFilter(props) {
const { keyword, setKeyword } = props;
const [search, setSearch] = useState(keyword);
const dSearch = useDebounce(search, 500);
const onSearchChange = (val) => {
const newKeyword = isEmpty(val) ? '' : val;
return setSearch(newKeyword);
};
useEffect(() => setKeyword(dSearch), [dSearch]);
return (
<TextField
id="AP_content-search"
value={search}
variant="outlined"
fullWidth
disabled={props.disabled}
placeholder="Search by name"
autoComplete="off"
onChange={(e) => onSearchChange(e.target.value)}
inputProps={{ style: { padding: 10 } }}
InputProps={{
endAdornment: (
<InputAdornment position="end">
{search.length === 0 ? (
<Search />
) : (
<Clear
data-testid="AP_postmodal_search-filter-clear"
style={{ cursor: 'pointer' }}
onClick={() => onSearchChange('')}
/>
)}
</InputAdornment>
),
}}
/>
);
}
export default SearchFilter;
|
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" name="viewport" content="Width=device-width, initial-scale=1">
<style>
* { margin: 0; padding: 0;}
header { background:wheat; display:flex; justify-content: space-between; margin-bottom: 10px;}
#logo { width: 100px; height: 50px;}
nav { background:wheat;}
nav ul li {display: inline;}
#hero { background:seashell; display:flex; justify-content: center; margin-bottom: 10px;}
.herographic {background:seashell;}
.herographic img {width:100%;}
.heroheading {margin: 0 0 10px 10px; background:seashell;}
.herobutton {background:silver; width: 50%; text-align: center; border-radius: 10px; padding: 10px; margin: 0 auto;}
#article { display: flex; justify-content: center; margin-bottom: 10px;}
.articlecontainer { background:wheat; width: 300px; margin: 0 1em;}
.articlecontainer img { width:100%;}
footer {background:mistyrose; height: 50px; text-align:center;}
footer nav {background: mistyrose;}
</style>
</head>
<body>
<header>
<div id="logo">
<img src="https://via.placeholder.com/100x50">
</div>
<nav>
<ul>
<li> <a href="#">Menu Item</a></li>
<li> <a href="#">Menu Item 2</a></li>
<li> <a href="#">Menu Item 3</a></li>
</ul>
</nav>
</header>
<section id="hero">
<div class="herographic"><img src="https://via.placeholder.com/300x300"> </div>
<div style="display:flex; flex-direction: column; justify-content:center;"><div class="heroheading"> <h1>HeroHeader1</h1></div>
<div class="herobutton"> HeroButton</div>
</div>
</section>
<section id="article">
<div class="articlecontainer">
<img src="https://via.placeholder.com/300x200">
<h2> Article Title 1</h2>
<p> A preview of the Article's text. Read me!</p>
</div>
<div class="articlecontainer">
<img src="https://via.placeholder.com/300x200">
<h2> Article Title 2</h2>
<p> A preview of the Article's text. Read me!</p>
</div>
<div class="articlecontainer">
<img src="https://via.placeholder.com/300x200">
<h2> Article Title 2</h2>
<p> A preview of the Article's text. Read me!</p>
</div>
</section>
<footer>
<nav>
<ul>
<li> <a href="#">Menu Item</a></li>
<li> <a href="#">Menu Item 2</a></li>
<li> <a href="#">Menu Item 3</a></li>
</ul>
</nav>
</footer>
</body>
</html>
|
<!DOCTYPE html>
<!--suppress ALL -->
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head th:replace="fragments/head :: head"></head>
<body>
<div class="container">
<div th:replace="fragments/header :: header"></div>
<div class="container">
<form class="form-horizontal" th:object="${client}"
th:action="@{/updateClient}" name="edit_form" id="edit_form"
method="post" role="form">
<div class="form-group">
<input type="hidden" id="id" th:name="id" th:value="*{id}" />
</div>
<table class="table table-bordered table-hover horizontal-align">
<thead>
<tr>
<th style="width: 25%">Name</th>
<th style="width: 25%">Moniker</th>
<th style="width: 25%">IsVip</th>
<th style="width: 25%">Town</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control" id="name"
th:name="name" th:value="*{name}" maxlength="100" /></td>
<td><input type="text" class="form-control" id="moniker"
th:name="moniker" th:value="*{moniker}" maxlength="100" /></td>
<td><input type="text" class="form-control"
th:name="isVip" th:value="*{isVip}" maxlength="100" />
</td>
<td><input type="text" class="form-control"
th:name="town" th:value="*{town}" maxlength="100" />
</td>
</tr>
</tbody>
</table>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</body>
</html>
|
import { createEffect } from 'solid-js'
import { createMachine, assign } from 'xstate'
import { useMachine } from '../hooks/useMachine'
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
context: {
count: 0,
disabledCount: 0,
},
states: {
inactive: {
entry: assign({ disabledCount: (ctx) => ctx.disabledCount + 1 }),
on: { TOGGLE: 'active' },
},
active: {
entry: assign({ count: (ctx) => ctx.count + 1 }),
on: { TOGGLE: 'inactive' },
},
},
})
export default function Machine() {
console.log('Create')
const [state, send] = useMachine(toggleMachine)
createEffect(() => {
// This illustrates how machine updates
// without triggering other parts of context
console.log('Off', state.context.disabledCount)
})
return (
<main style={{ padding: '1rem' }}>
<h1>XState Solid Example</h1>
<h2>Granular State Machine</h2>
<button onClick={() => send('TOGGLE')}>Click me ({state.matches('active') ? '✅' : '❌'})</button>{' '}
<code>
Toggled <strong>{state.context.count}</strong> times
</code>
</main>
)
}
|
<template>
<div class="mx-10 md:mx-0">
<p class="text-center text-main-700 tracking-widest">{{ chartTitle }}</p>
<div :id="props.id" ref="elPieChart" class="w-full lg:h-96 h-64"></div>
<ul class="md:flex md:justify-center lg:block">
<li v-for="item of districtsData" :key="item.president" class="tracking-wider">
<div class="mx-auto px-3 md:px-6 lg:px-8 w-52 md:w-60 lg:w-64">
<p
class="py-1 text-xl border-l-8 mb-3 pl-5"
:class="{
'border-pfp': item.president === '宋楚瑜',
'border-kmt': item.president === '韓國瑜',
'border-dpp': item.president === '蔡英文'
}"
>
{{ item.president }} /
{{ item.vicePresident }}
</p>
</div>
</li>
</ul>
</div>
</template>
<script setup>
import { useSetPieChart } from '@/composables/pieChart.mjs'
import { useDistrictStore } from '@/stores/districtStore.mjs'
const props = defineProps({
id: {
type: String,
required: true
}
})
const districtStore = useDistrictStore()
const route = useRoute()
const county = ref(route.params.countyid)
const xAxisData = ref([])
const elPieChart = ref(null)
const chart = ref(null)
const yAxisData = ref([])
const color = {
electionGroups1: '#F2854A',
electionGroups2: '#4889C1',
electionGroups3: '#58AC6F'
}
// 取得行政區資料
const districtsData = computed(() => districtStore.votesGetter)
const districtGetter = computed(() => districtStore.districtGetter)
const chartTitle = ref('')
const w = ref(0)
const getData = () => {
chartTitle.value = `${county.value}${districtGetter.value}`
yAxisData.value = districtsData.value.map((item) => {
return {
name: `${item.rate}%`,
value: item.rate,
society: item.society,
itemStyle: {
color: color[item.id]
},
label: {
position: item.rate > 30 ? 'inside' : '',
color: item.rate > 30 ? 'white' : color[item.id],
fontSize: 16
}
}
})
xAxisData.value = districtsData.value.map((item) => `${item.president}/${item.vicePresident}`)
// echart 生成圖表
chart.value = useSetPieChart(elPieChart.value, chartTitle.value, yAxisData.value)
}
watch([districtsData, districtGetter], () => {
getData()
})
// 監聽視窗寬度
const handleResize = (width) => {
w.value = width || window.innerWidth
}
watch(
w,
() => {
getData()
},
{
deep: true
}
)
defineExpose({ handleResize })
onMounted(() => {
if (Object.keys(districtsData.value).length > 0) {
getData()
}
})
</script>
<style lang="scss" scoped>
.w-200 {
width: 200px;
}
</style>
|
// Libraries
import React from 'react';
import axios from 'axios';
import { useAppDispatch, useAppSelector } from '../../redux/hooks';
// CSS
import './playlist.css';
import { setSelectedSong } from '../../redux/slices/songSlice';
import { ItemSong } from '../../typeInterface/InterfaceSong';
import { PlaylistItem } from '../../typeInterface/InterfacePlaylist';
type Props = {
data: PlaylistItem;
};
function Playlist({ data }: Props) {
const dispatch = useAppDispatch();
const selectedSong = useAppSelector((state) => state.song.selectedSong);
const accessToken = useAppSelector((state) => state.token.accessToken);
const addSongsToPlaylist = async (playlistId: PlaylistItem['id']) => {
try {
const res = await axios.post(`https://api.spotify.com/v1/playlists/${playlistId}/tracks?access_token=${accessToken}`, {
uris: selectedSong?.map((song: ItemSong) => song.uri),
});
console.log(res);
return res;
} catch (err) {
console.log(err);
}
return null;
};
const handleAddSongtoPlaylist = async (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
try {
const playlistId = data.id;
if (playlistId) {
if (selectedSong !== []) {
const res = await addSongsToPlaylist(playlistId);
if (res) {
console.log('Berhasil Upload');
dispatch(setSelectedSong([]));
alert(`Song has been added to playlist ${data.name}`);
}
}
}
} catch (error) {
console.log(error);
}
};
return (
<div className="card-playlist col-1 p-0 text-white">
<div className="card-head w-100 d-flex">
<div className="card-head-img mx-auto align-self-center">
{data.images.length !== 0
? (<img src={data.images[0].url} className="card-img-top" alt="playlist-cover" />)
: (
<img
src="https://cdn5.vectorstock.com/i/1000x1000/91/59/music-note-line-icon-on-black-background-black-vector-26849159.jpg"
className="card-img-top"
alt="playlist-cover"
/>
)}
</div>
</div>
<div className="card-body p-3">
<h5 className="playlist-title">{data.name}</h5>
<p className="display-name">
By
{data.owner.display_name}
</p>
<button className="btn btn-add-to-playlist text-white" type="button" onClick={handleAddSongtoPlaylist}>
Add to Playlist +
</button>
</div>
</div>
);
}
export default Playlist;
|
<?php
namespace App\Http\Controllers\Admin;
use App\Enums\AppointmentStatus;
use App\Http\Controllers\Controller;
use App\Models\Appointment;
use Illuminate\Http\Request;
class AppointmentController extends Controller
{
public function index(Request $request) {
$status = (int)$request->status;
return Appointment::query()
->with('client:id,first_name,last_name')
->when($status, function($query) use($status){
return $query->where('status', AppointmentStatus::from($status));
})
->latest()
->paginate()
->through(fn ($appoinment) => [
'id' => $appoinment->id,
'start_time' => $appoinment->start_time->format('Y-m-d h:i A'),
'end_time' => $appoinment->end_time->format('Y-m-d h:i A'),
'status' => [
'name' => $appoinment->status->name,
'color' => $appoinment->status->color(),
],
'client' => $appoinment->client,
]);
}
public function store() {
$validated = request()->validate([
'client_id' => 'required',
'title' => 'required',
'description' => 'required',
'start_time' => 'required',
'end_time' => 'required',
],[
'client_id.required' => 'The name field os required'
]);
Appointment::create([
'title' => $validated['title'],
'clients_id' => $validated['client_id'],
'start_time' => $validated['start_time'],
'end_time' => $validated['end_time'],
'description' => $validated['description'],
'status' => AppointmentStatus::SCHEDULED,
]);
return response()->json(['message' => 'success']);
}
public function edit($id) {
return Appointment::find($id);
}
public function update($id) {
$appoinment = Appointment::find($id);
$validated = request()->validate([
'clients_id' => 'required',
'title' => 'required',
'description' => 'required',
'start_time' => 'required',
'end_time' => 'required',
],[
'client_id.required' => 'The name field os required'
]);
$appoinment->update($validated);
return response()->json(['message' => 'success', 'success' => true]);
}
public function destroy($id) {
$appoinment = Appointment::find($id);
$appoinment->delete();
if ($appoinment == '1') {
$success = true;
$message = "Usuario excluído com sucesso";
} else {
$success = true;
$message = "Usuario não encontrado";
}
return response()->json([
'success' => $success,
'message' => $message,
]);
}
}
|
import { Request, Response } from 'express';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { User } from '../../models/User';
export async function loginUser(req: Request, res: Response) {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ message: 'Invalid email or password.' });
}
if (!user.password) {
throw new Error('User does not have a password field.');
}
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) {
return res.status(400).json({ message: 'Invalid password.' });
}
if (!process.env.JWT_SECRET) {
throw new Error('JWT_SECRET is not defined');
}
const token = jwt.sign({ _id: user._id, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1d' });
res.status(200).json({ user, token });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Error logging in.' });
}
}
|
// ========== AUTH LANDING PAGE ==========
// This page is used to display the login page when a user is not yet logged in / displays an error page when the login fails / displays a loading page when the login is in progress
// === Imports ===
// - Auth0
import { useAuth0 } from "@auth0/auth0-react";
// - React
import { Navigate, Link } from "react-router-dom";
// - Components
import Error from "../../Error";
import LoginButton from "../LoginButton";
// - Styles
import "./index.scss";
// === Return Button ===
function ReturnHomeButton() {
return (
<button className="return__home">
<Link to="/">
<svg
width="24"
height="25"
viewBox="0 0 24 25"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M15 18.5L9 12.5L15 6.5"
stroke="black"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
Return Home
</Link>
</button>
);
}
// === Auth Landing Page ===
export default function AuthLanding() {
const { error, isAuthenticated, isLoading } = useAuth0();
if (error) {
<div className="authlanding">
<ReturnHomeButton />
<div className="authlanding__title">
<h1>Login failed</h1>
</div>
<div className="authlanding__subtitle">
<p>
Sorry, we were unable to sign you in, the error below might be useful.
</p>
</div>
<div className="authlanding__login">
<Error error={error} />
<LoginButton />
</div>
</div>;
}
if (!isLoading && isAuthenticated) {
return <Navigate to="/" />;
}
if (!isLoading && !isAuthenticated) {
return (
<div className="authlanding">
<ReturnHomeButton />
<div className="authlanding__title">
<h1>Login required</h1>
</div>
<div className="authlanding__subtitle">
<p>Please log in to access this page.</p>
</div>
<div className="authlanding__login">
<LoginButton />
</div>
</div>
);
}
return (
<div className="authlanding">
<ReturnHomeButton />
<div className="authlanding__title">
<h1>Signing in</h1>
</div>
<div className="authlanding__subtitle">
<p>Please wait while we sign you in!</p>
</div>
<div className="authlanding__login">
<LoginButton />
</div>
</div>
);
}
|
/*
File Name: MapEditor.h
Project Name: The balloon
Author(s)
Main: Hyunjin Kim
All content 2021 DigiPen (USA) Corporation, all rights reserved.
*/
#pragma once
#include "../../Engine/Headers/Engine.h"
#include "../../Engine/Headers/Vec2.h"
#include "../../Engine/Headers/texture.h"
#include "../../Engine/Headers/Sound.h"
#include "Objects.h"
#include "GameMap.h"
#include "BlockImgs.h"
#include <vector>
#include <doodle/doodle.hpp>
namespace DOG { class Camera; }
class MapEditor
{
private:
friend class SaveManager;
using Tile = Object::Base;
using TilePointer = Object::Base*;
using TileChunk = GameMap::MapChunk;
static constexpr int TilePixel = static_cast<int>(Object::Block::size); // pixels of a single square tile
static constexpr int ChunkPixel = TilePixel * GameMap::MapChunk::size_c; // pixels of a single square chunk
static constexpr math::ivec2 MapPixel = math::ivec2{ GameMap::ChunckSize } * ChunkPixel; // pixels of each width and height of whole map
static constexpr int TileNumber = GameMap::MapChunk::size_c; // numbers of tiles for each row and column in one chunk
static constexpr int ChunkNumber = GameMap::ChunckSize.x * GameMap::ChunckSize.y; // numbers of chuncks for each row and column in whole map
public:
MapEditor();
void Update();
void DrawStatic();
void DrawDynamic();
void UnLoad();
void EditWith(GameMap& map);
void SetCamera(DOG::Camera* cam);
void Load();
bool IsConfigurating();
void SetChapter(int chapter2) { currentChapter = chapter2; }
math::ivec2 GetMousePos();
double scale_amt;
enum class Menu {
Mouse, Block, Area, Enemy, Item, Image, Save, Load, Clear, Size
};
private:
std::vector<math::ivec2> temp_tile_datas;
std::vector<math::irect2> lines;
std::vector<DOG::Button> menu_buttons;
std::vector<std::vector<DOG::Button>> button_list;
std::vector<std::string> file_list;
std::vector<DOG::Button> file_buttons;
std::vector<DOG::Texture*> textures;
void update_edit_win();
void update_fname_input();
void update_fselect_win();
void load_fnames();
void check_editBar();
void save_map();
void clear_map();
void place_plant(TileChunk& chunk, TilePointer t);
void image_tile_setup();
DOG::Input editKey, backspace, enter , normal_inc, normal_dec;
DOG::Input test = DOG::Input::Keyboard::_1;
std::string save_dir_name;
Object::Type s_type;
Menu sel_menu;
BlockImg block_image;
bool isKeyPressed;
bool isMousePressed;
bool isEditing;
bool isSelectingFile;
bool isReadytoSave;
bool isMenuOpened;
bool isDragging;
int currentChapter = 1;
int Normal_num = 0;
int image_selected = 0;
GameMap* map;
DOG::Camera* camera;
};
|
import numpy as np
class Dense:
def __init__(self, n_units, ativacao, inicializador, use_bias, input_dim=None):
"""
n_units: nº de neurônios da camada atual
ativacao: Classe da função de ativação
inicializador: Classe do inicializador
bias: Se a camada terá um viés
(opcional) input_dim: nº de input features para a camada
"""
self.input_dim = input_dim
self.n_units = n_units
self.ativacao = ativacao
self.inicializador = inicializador
self.save_ativacoes = [] # Lista para armazenar ativações
self.save_gradientes = [] # Lista para armazenar gradientes dos pesos
self.delta = None
self.pesos = None
self.pre_ativacao = None
self.X = None
self.use_bias = use_bias
if use_bias:
self.bias = np.zeros((1, n_units))
def forward(self, x):
self.X = x
if self.use_bias:
self.pre_ativacao = np.dot(self.X, self.pesos) + self.bias
else:
self.pre_ativacao = np.dot(self.X, self.pesos)
s = self.ativacao.calcular(self.pre_ativacao)
self.save_ativacoes.append(s)
return s
def backward(self, gradiente_saida_anterior):
# Derivada da funcao de ativacao
derivada_ativacao = self.ativacao.derivada(self.pre_ativacao)
self.delta = np.multiply(gradiente_saida_anterior, derivada_ativacao)
self.gradiente_pesos = np.matmul(self.X.T, self.delta)
self.save_gradientes.append(self.gradiente_pesos)
if self.use_bias:
self.gradiente_bias = np.sum(self.delta, axis=0, keepdims=True)
# Calcula o gradiente do erro para propagar para a camada anterior
dl_dy_novo = np.matmul(self.delta, self.pesos.T)
return dl_dy_novo
|
#ifndef DALU_DOCKING_H
#define DALU_DOCKING_H
#include <ros/ros.h>
#include <tf2_ros/transform_listener.h>
#include <geometry_msgs/TransformStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <math.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Empty.h>
#include <tf/tf.h>
#include <std_srvs/SetBool.h>
class DaluDocking
{
private:
ros::NodeHandle nh_;
ros::NodeHandle nh_private_;
// ROS interfaces
ros::Subscriber stop_sub_;
ros::Subscriber start_sub_;
ros::Publisher success_pub_;
ros::Publisher vel_pub_;
ros::Timer run_timer_;
tf2_ros::Buffer tfBuffer_;
tf2_ros::TransformListener tfListener_;
ros::Subscriber pose_sub_;
ros::ServiceServer run_service_;
bool goal_received_;
bool run_;
bool x_loop_;
bool y_loop_;
bool yaw_loop_;
geometry_msgs::PoseStamped goal_pose_;
// For recording xy coordinates of docking goal
int history_index_;
std::vector<double> x_history_;
std::vector<double> y_history_;
// ROS params
int p_frames_tracked_;
double p_xy_tolerance_;
double p_yaw_tolerance_;
double p_max_linear_vel_;
double p_min_linear_vel_;
double p_max_turn_vel_;
double p_min_turn_vel_;
void initialize();
bool loadParams();
void setupTopics();
// ROS callbacks
void stopCallback(const std_msgs::Empty::ConstPtr& msg);
void startCallback(const std_msgs::Empty::ConstPtr& msg);
void goalCallback(const geometry_msgs::PoseStamped::ConstPtr& msg);
bool runService(std_srvs::SetBool::Request& request, std_srvs::SetBool::Response& response);
// Docking loop
void runDocking(const ros::TimerEvent& event);
// Find average xy coordinates of docking goal based on past transforms
bool historyAveraging(geometry_msgs::TransformStamped& goal);
// Run when docking ended
void cleanupTask(bool success);
// Convert transform to pose
void tfToPose(geometry_msgs::TransformStamped tf, geometry_msgs::PoseStamped& pose);
// Get yaw from quaternion
double getYaw(geometry_msgs::PoseStamped pose);
public:
DaluDocking();
};
#endif
|
package com.example.bluetooth_checkin;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.util.Set;
import java.util.ArrayList;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
public class MainActivity extends AppCompatActivity {
Button enablebt,disablebt,scanbt;
private BluetoothAdapter BTAdapter;
private Set<BluetoothDevice>pairedDevices;
ListView lv;
public final static String EXTRA_ADDRESS = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enablebt=(Button)findViewById(R.id.button_enablebt);
disablebt=(Button)findViewById(R.id.button_disablebt);
scanbt=(Button)findViewById(R.id.button_scanbt);
BTAdapter = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
if (BTAdapter.isEnabled()){
scanbt.setVisibility(View.VISIBLE);
}
}
public void on(View v){
if (!BTAdapter.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//Thuc hien vieic mo bluetooth. Yeu cau bat bluetooth
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Mở Device Bluetooth",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Thiết bị đã mở Device Bluetooth", Toast.LENGTH_SHORT).show();
}
scanbt.setVisibility(View.VISIBLE);
lv.setVisibility(View.VISIBLE);
}
public void off(View v){
BTAdapter.disable();
Toast.makeText(getApplicationContext(), "Tắt Device Bluetooth" ,Toast.LENGTH_SHORT).show();
scanbt.setVisibility(View.INVISIBLE);
lv.setVisibility(View.GONE);
}
public void deviceList(View v){
ArrayList deviceList = new ArrayList();
pairedDevices = BTAdapter.getBondedDevices();
if (pairedDevices.size() < 1) {
Toast.makeText(getApplicationContext(), "Không tìm thấy Device Bluetooth để kết nối...", Toast.LENGTH_SHORT).show();
} else {
for (BluetoothDevice bt : pairedDevices) deviceList.add(bt.getName() + " " + bt.getAddress());
Toast.makeText(getApplicationContext(), "Hiển thị các Devices đã được kết nối...", Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, deviceList);
lv.setAdapter(adapter);
lv.setOnItemClickListener(myListClickListener);
}
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
Toast.makeText(getApplicationContext(), info, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, CommsActivity.class);
intent.putExtra(EXTRA_ADDRESS, address);
startActivity(intent);
}
};
}
|
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { BallTriangle } from "react-loader-spinner";
const StartPage = () => {
const navigate = useNavigate();
const [name, setName] = useState('');
const [topic, setTopic] = useState('');
const [passcode, setPasscode] = useState('');
const [loader, setLoader] = useState(false);
const [disable, setDisable] = useState(false);
const change = (e) => {
switch(e.target.id) {
case "userName":
setName(name => e.target.value);
break;
case "sessionTopic":
setTopic(topic => e.target.value);
break;
case "sessionPasscode":
setPasscode(passcode => e.target.value);
break;
}
};
const joinSession = async () => {
if (name === "" || topic === "") return;
setDisable(disable => !disable);
setLoader(loader => !loader);
let UIToolKitConfig = {
userIdentity: "",
sessionKey: "",
geoRegions: "",
cloudRecordingOption: "",
cloudRecordingElection: "",
webEndpoint: "",
dependentAssets: "",
advancedTelemetry: true,
videoSDKJWT: "",
userName: "",
sessionName: "",
sessionPasscode: "",
features: [ "video", "audio", "share", "chat", "settings", "users", "roles" ],
};
let settings = {
mode: "cors",
method: 'POST',
headers: {
"Content-Type": "text/plain"
}
};
await fetch("https://zoom-auth-server-20be414301cf.herokuapp.com/zoomtoken" + "?name=" + name+ "&topic=" + topic + "&password=" + passcode, settings).then( async (res) => {
await res.text().then( async (data) => {
console.log(data);
if (data) {
UIToolKitConfig.videoSDKJWT = data.toString().trim();
UIToolKitConfig.userName = name;
UIToolKitConfig.sessionName = topic;
UIToolKitConfig.sessionPasscode = passcode;
} else {
console.log(data);
}
});
});
setLoader(loader => !loader);
navigate("/meetingspage", {state: UIToolKitConfig});
};
return (
<React.Fragment>
<div className="flex flex-col items-center w-96 mt-96 m-auto">
<h1 className="text-3xl">UIToolKit React</h1>
<input className="h-12 px-2 text-xl border-2 border-solid rounded-lg mt-2 border-sky-600 hover:border-sky-700 w-1/2" type="text" placeholder=" User Name" id="userName" onChange={change}/>
<input className="h-12 px-2 text-xl border-2 border-solid rounded-lg mt-2 border-sky-600 hover:border-sky-700 w-1/2" type="text" placeholder=" Session Topic" id="sessionTopic" onChange={change}/>
<input className="h-12 px-2 text-xl border-2 border-solid rounded-lg mt-2 border-sky-600 hover:border-sky-700 w-1/2" type="text" placeholder=" Session Passcode" id="sessionPasscode" onChange={change}/>
<button className="flex items-center justify-center h-12 border-solid rounded-lg mt-2 bg-sky-600 w-1/2 text-white hover:bg-sky-700 active:bg-sky-800" type="button" disabled={disable} onClick={joinSession}>{loader ? <BallTriangle height={25} width={100} radius={5} color="white" ariaLabel="ball-triangle-loading" wrapperClass={{}} wrapperStyle="" visible={true}/> : 'Join Session'} </button>
</div>
</React.Fragment>
);
};
export default StartPage;
|
use bevy::{prelude::*, render::view::RenderLayers};
use bevy_vector_shapes::{prelude::ShapePainter, shapes::LinePainter};
use crate::{
game::{
health::Health,
player::{calories::Calories, Player},
DespawnOnExitGame,
},
AppState,
};
const BAR_LENGTH: f32 = 1.0;
const BAR_WIDTH: f32 = 0.03;
const TEXT_SCALE: f32 = BAR_WIDTH / 20.0;
const FONT_SIZE: f32 = 36.0;
const HEALTH_OFFSET: f32 = -0.7;
const CALORIES_OFFSET: f32 = -0.75;
const RIGHT_LABEL_OFFSET: f32 = BAR_LENGTH / 2.0 + 0.1;
const LEFT_LABEL_OFFSET: f32 = -BAR_LENGTH / 2.0 - 0.15;
pub struct PlayerUiPlugin;
impl Plugin for PlayerUiPlugin {
fn build(&self, app: &mut App) {
app.add_systems(OnEnter(AppState::Game), setup)
.add_systems(Update, player_status_ui);
}
}
#[derive(Component)]
pub struct HealthValue;
#[derive(Component)]
pub struct GlucoseValue;
#[derive(Component)]
pub struct CaloriesValue;
#[derive(Component)]
pub struct HealthLabel;
#[derive(Component)]
pub struct GlucoseLabel;
#[derive(Component)]
pub struct CaloriesLabel;
pub fn create_label(label: String, position: Vec3) -> Text2dBundle {
Text2dBundle {
text: Text::from_section(
label,
TextStyle {
font_size: FONT_SIZE,
..default()
},
),
transform: Transform::from_translation(position).with_scale(Vec3::splat(TEXT_SCALE)),
..default()
}
}
fn setup(mut commands: Commands) {
commands.spawn((
create_label(
String::from("100"),
Vec3::new(RIGHT_LABEL_OFFSET, HEALTH_OFFSET, 0.0),
),
HealthValue,
RenderLayers::layer(1),
DespawnOnExitGame,
));
commands.spawn((
create_label(
String::from(""),
Vec3::new(RIGHT_LABEL_OFFSET, CALORIES_OFFSET, 0.0),
),
CaloriesValue,
RenderLayers::layer(1),
DespawnOnExitGame,
));
commands.spawn((
create_label(
String::from("HEALTH"),
Vec3::new(LEFT_LABEL_OFFSET, HEALTH_OFFSET, 0.0),
),
HealthLabel,
RenderLayers::layer(1),
DespawnOnExitGame,
));
commands.spawn((
create_label(
String::from("CALORIES"),
Vec3::new(LEFT_LABEL_OFFSET, CALORIES_OFFSET, 0.0),
),
CaloriesLabel,
RenderLayers::layer(1),
DespawnOnExitGame,
));
}
fn player_status_ui(
mut painter: ShapePainter,
q_player: Query<(&Health, &Calories), With<Player>>,
mut q_health: Query<&mut Text, With<HealthValue>>,
mut q_calories: Query<&mut Text, (With<CaloriesValue>, Without<HealthValue>)>,
) {
painter.set_2d();
painter.render_layers = Some(RenderLayers::layer(1));
let Ok((health, calories)) = q_player.get_single() else {
return;
};
// bar
show_bar(
&mut painter,
(health.current as f32 / health.max as f32).min(1.0),
HEALTH_OFFSET,
Color::RED,
&mut q_health.single_mut().sections[0].value,
);
show_bar(
&mut painter,
(calories.0).min(100.0) as f32 / 100.0,
CALORIES_OFFSET,
Color::CYAN,
&mut q_calories.single_mut().sections[0].value,
);
}
fn show_bar(
painter: &mut ShapePainter,
portion: f32,
y_offset: f32,
color: Color,
label: &mut String,
) {
let portion = portion.clamp(0.0, 1.0);
let start_x = -BAR_LENGTH / 2.0;
let end_x = BAR_LENGTH / 2.0;
painter.thickness = BAR_WIDTH;
painter.color = Color::BLACK;
painter.line(
Vec3::new(start_x, y_offset, 0.0),
Vec3::new(end_x, y_offset, 0.0),
);
painter.color = color;
painter.line(
Vec3::new(start_x, y_offset, 0.0),
Vec3::new(start_x * (1.0 - portion) + end_x * portion, y_offset, 0.0),
);
*label = ((portion * 100.0).ceil() as i32).to_string();
}
|
/**
* Copyright 2022 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_CPU_SAMPLE_DISTORTED_BOUNDING_BOX_V2_H_
#define MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_CPU_SAMPLE_DISTORTED_BOUNDING_BOX_V2_H_
#include <stdint.h>
#include <algorithm>
#include <vector>
#include "plugin/device/cpu/kernel/cpu_kernel.h"
#include "plugin/factory/ms_factory.h"
namespace mindspore {
namespace kernel {
class Region {
public:
Region() { SetPiont(0, 0, 0, 0); }
Region(int xmin, int ymin, int xmax, int ymax) { SetPiont(xmin, ymin, xmax, ymax); }
void SetPiont(int xmin, int ymin, int xmax, int ymax) {
min_x_ = xmin;
min_y_ = ymin;
max_x_ = xmax;
max_y_ = ymax;
}
float Area() const { return static_cast<float>((max_x_ - min_x_) * (max_y_ - min_y_)); }
Region Intersect(const Region &r) const {
const int pmin_x = std::max(min_x_, r.min_x_);
const int pmin_y = std::max(min_y_, r.min_y_);
const int pmax_x = std::min(max_x_, r.max_x_);
const int pmax_y = std::min(max_y_, r.max_y_);
if (pmin_x > pmax_x || pmin_y > pmax_y) {
return Region();
} else {
return Region(pmin_x, pmin_y, pmax_x, pmax_y);
}
}
int min_x_;
int min_y_;
int max_x_;
int max_y_;
};
template <typename T, size_t ElementCount>
class Array {
public:
Array() {
for (size_t i = 0; i < ElementCount; ++i) {
data_[i] = T(0);
}
}
const T &operator[](size_t index) const { return data_[index]; }
T &operator[](size_t index) { return data_[index]; }
size_t size() const { return ElementCount; }
private:
T data_[ElementCount];
};
class MSPhiloxRandom {
public:
static constexpr size_t kIndex0 = 0;
static constexpr size_t kIndex1 = 1;
static constexpr size_t kIndex2 = 2;
static constexpr size_t kIndex3 = 3;
static constexpr size_t kKeyCount = 2;
static constexpr size_t kResultElementCount = 4;
static constexpr size_t loop_rounds = 10;
/*
* The type for the 64-bit key stored in the form of two 32-bit uint
* that are used in the diffusion process.
*/
using ResType = Array<uint32_t, kResultElementCount>;
using Key = Array<uint32_t, kKeyCount>;
MSPhiloxRandom() {}
static constexpr int kMoveStepInBit = 32;
explicit MSPhiloxRandom(uint64_t seed) {
key_[kIndex0] = static_cast<uint32_t>(seed);
key_[kIndex1] = static_cast<uint32_t>(seed >> kMoveStepInBit);
}
explicit MSPhiloxRandom(uint64_t seed_lo, uint64_t seed_hi) {
key_[kIndex0] = static_cast<uint32_t>(seed_lo);
key_[kIndex1] = static_cast<uint32_t>(seed_lo >> kMoveStepInBit);
counter_[kIndex2] = static_cast<uint32_t>(seed_hi);
counter_[kIndex3] = static_cast<uint32_t>(seed_hi >> kMoveStepInBit);
}
MSPhiloxRandom(ResType counter, Key key) : counter_(counter), key_(key) {}
ResType const &counter() const { return counter_; }
Key const &key() const { return key_; }
// Skip the specified number of samples of 128-bits in the current stream.
void Skip(uint64_t count) {
const uint32_t count_lo = static_cast<uint32_t>(count);
uint32_t count_hi = static_cast<uint32_t>(count >> kMoveStepInBit);
counter_[kIndex0] += count_lo;
if (counter_[kIndex0] < count_lo) {
++count_hi;
}
counter_[kIndex1] += count_hi;
if (counter_[kIndex1] < count_hi) {
if (++counter_[kIndex2] == 0) {
++counter_[kIndex3];
}
}
}
/*
* Returns a group of four random numbers using the underlying Philox
* algorithm.
*/
ResType operator()() {
ResType counter = counter_;
Key key = key_;
for (size_t i = 0; i < loop_rounds; i++) {
counter = SingleRoundCompute(counter, key);
RaiseKey(&key);
}
SkipOne();
return counter;
}
private:
// We use the same constants as recommended by the original paper.
static constexpr uint32_t kMSPhiloxW32A = 0x9E3779B9;
static constexpr uint32_t kMSPhiloxW32B = 0xBB67AE85;
static constexpr uint32_t kMSPhiloxM4x32A = 0xD2511F53;
static constexpr uint32_t kMSPhiloxM4x32B = 0xCD9E8D57;
// Helper function to skip the next sample of 128-bits in the current stream.
void SkipOne() {
if (++counter_[kIndex0] == 0) {
if (++counter_[kIndex1] == 0) {
if (++counter_[kIndex2] == 0) {
++counter_[kIndex3];
}
}
}
}
/*
* Helper function to return the lower and higher 32-bits from two 32-bit
* integer multiplications.
*/
static void HighLowMultiply(uint32_t a, uint32_t b, uint32_t *result_low, uint32_t *result_high) {
const uint64_t product = static_cast<uint64_t>(a) * static_cast<uint64_t>(b);
*result_low = static_cast<uint32_t>(product);
*result_high = static_cast<uint32_t>(product >> kMoveStepInBit);
}
// Helper function for a single round of the underlying Philox algorithm.
static ResType SingleRoundCompute(const ResType &counter, const Key &key) {
uint32_t low0;
uint32_t high0;
HighLowMultiply(kMSPhiloxM4x32A, counter[kIndex0], &low0, &high0);
uint32_t low1;
uint32_t high1;
HighLowMultiply(kMSPhiloxM4x32B, counter[kIndex2], &low1, &high1);
ResType result;
result[kIndex0] = high1 ^ counter[kIndex1] ^ key[kIndex0];
result[kIndex1] = low1;
result[kIndex2] = high0 ^ counter[kIndex3] ^ key[kIndex1];
result[kIndex3] = low0;
return result;
}
void RaiseKey(Key *key) {
(*key)[kIndex0] += kMSPhiloxW32A;
(*key)[kIndex1] += kMSPhiloxW32B;
}
private:
ResType counter_;
Key key_;
};
class SampleDistortedBoundingBoxV2CPUKernelMod : public DeprecatedNativeCpuKernelMod {
public:
SampleDistortedBoundingBoxV2CPUKernelMod() = default;
~SampleDistortedBoundingBoxV2CPUKernelMod() override = default;
void InitKernel(const CNodePtr &kernel_node) override;
bool Launch(const std::vector<kernel::AddressPtr> &inputs, const std::vector<kernel::AddressPtr> &workspace,
const std::vector<kernel::AddressPtr> &outputs) override;
protected:
std::vector<KernelAttr> GetOpSupport() override;
private:
int64_t seed = 0;
int64_t seed2 = 0;
std::vector<float> aspect_ratio_range;
std::vector<float> area_range;
int64_t max_attempts = 100;
bool use_image_if_no_bounding_boxes = false;
TypeId dtype_{kTypeUnknown};
MSPhiloxRandom generator_;
using ResType = Array<uint32_t, MSPhiloxRandom::kResultElementCount>;
ResType unused_results_;
size_t used_result_index_ = MSPhiloxRandom::kResultElementCount;
float RandFloat();
uint32_t Uniform(uint32_t n);
uint64_t New64();
void InitMSPhiloxRandom(int64_t seed, int64_t seed2);
uint32_t GenerateSingle();
bool SatisfiesOverlapConstraints(const Region &crop, float minimum_object_covered,
const std::vector<Region> &bounding_boxes);
bool GenerateRandomCrop(int original_width, int original_height, float min_relative_crop_area,
float max_relative_crop_area, float aspect_ratio, Region *crop_rect);
template <typename T>
void LaunchSDBBExt2(const std::vector<AddressPtr> &inputs, const std::vector<AddressPtr> &outputs);
};
} // namespace kernel
} // namespace mindspore
#endif // MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_CPU_SAMPLE_DISTORTED_BOUNDING_BOX_V2_H_
|
/*
* Copyright (c) 2024 AVI-SPL, Inc. All Rights Reserved.
*/
package com.avispl.symphony.dal.avdevices.wirelesspresentation.mersive.solsticepodgen3.common;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* ActiveRoutingProperty
*
* @author Harry / Symphony Dev Team<br>
* Created on 3/22/2024
* @since 1.1.0
*/
public enum ActiveRoutingProperty {
STATE("Status", "state", SolsticeConstant.SESSION_DATA),
CONNECTION("NumberOfConnections", "connections", SolsticeConstant.SESSION_DATA),
FRAMES_PER_SECOND("FramesPerSecond", "framesPerSecond", SolsticeConstant.SESSION_DATA),
BYTE_PER_SECOND("BytesPerSecond", "bytesPerSecond", SolsticeConstant.SESSION_DATA),
SOURCE_DECORATION("SourceDecoration", "sourceDecoration", SolsticeConstant.SESSION_DATA),
TRIAL("Trial", "trial", SolsticeConstant.LICENSING),
SUBSCRIPTION("SubscriptionExpiration", "subscription", SolsticeConstant.LICENSING),
LICENSED("Licensed", "licensed", SolsticeConstant.LICENSING),
;
private final String name;
private final String value;
private final String type;
/**
* Constructs a ActiveRoutingProperty with the specified values.
*
* @param name the name of the property
* @param value the group of the property
* @param type whether the property is a control property
*/
ActiveRoutingProperty(String name, String value, String type) {
this.name = name;
this.value = value;
this.type = type;
}
/**
* Retrieves {@link #name}
*
* @return value of {@link #name}
*/
public String getName() {
return name;
}
/**
* Retrieves {@link #value}
*
* @return value of {@link #value}
*/
public String getValue() {
return value;
}
/**
* Retrieves {@link #type}
*
* @return value of {@link #type}
*/
public String getType() {
return type;
}
/**
* Retrieves a list of ActiveRoutingProperty enums based on the provided type.
*
* @param type The type of ActiveRoutingProperty enums to filter by.
* @return A list of ActiveRoutingProperty enums matching the specified type.
*/
public static List<ActiveRoutingProperty> getListByType(String type) {
return Arrays.stream(ActiveRoutingProperty.values()).filter(item -> item.getType().equals(type))
.collect(Collectors.toList());
}
}
|
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>
<h1>실습</h1>
<!--
1. 테이블 태그를 이용해서 게시판 만들기
2. 행을 클릭하면, 해당 행의 게시글 정보를
아래쪽 결과창(div태그)에 보여주기
-->
<table border="1">
<tr>
<td>글번호</td>
<td>제목</td>
<td>작성자</td>
<td>작성일</td>
<td>조회수</td>
</tr>
<tr>
<td>1</td>
<td>제목01</td>
<td>작성자01</td>
<td>월요일</td>
<td>111</td>
</tr>
<tr>
<td>2</td>
<td>제목02</td>
<td>작성자02</td>
<td>화요일</td>
<td>222</td>
</tr>
<tr>
<td>3</td>
<td>제목03</td>
<td>작성자03</td>
<td>화요일</td>
<td>333</td>
</tr>
</table>
<div id="result"></div>
<script>
//tr 클릭 이벤트
//클릭된 행의 모든 td 태그의 내용을 확인
//내용을 div#result 에 보여주기
//js
const result = document.querySelector("#result");
const trArr = document.querySelectorAll("tr");
for(let x of trArr){
x.addEventListener("click", (event)=>{
const trTag = event.currentTarget;
console.log(trTag);
const tdList = trTag.children;
result.innerText = "";
for(let tdTag of tdList){
result.innerText += tdTag.innerText + " / ";
}
});
}
//jquery
// const result = $("#result");
// const trArr = $("tr");
// trArr.click((event)=>{
// let str = "";
// const trTag = event.target.parentNode;
// $(trTag).children().each((idx,td)=>{
// str += td.innerText + " / ";
// });
// result.text( str );
// });
</script>
</body>
</html>
|
from typing import Optional, Callable, List
import torch
import torchmetrics
from torch import nn
from torchmetrics import Accuracy, AveragePrecision, AUROC, Dice, F1Score
from vision_models_playground.datasets.datasets import get_voc_detection_dataset_yolo, get_voc_detection_dataset_yolo_aug
from vision_models_playground.losses.yolo_v1_loss import YoloV1Loss
from vision_models_playground.metrics.wrapper import YoloV1ClassMetricWrapper, YoloV1MeanAveragePrecision
from vision_models_playground.models.segmentation.yolo_v1 import ResNetYoloV1
from vision_models_playground.train.train_models import train_model
from vision_models_playground.utility.config import config_wrapper
def train_yolo_v1(
model: nn.Module,
train_dataset: Optional[torch.utils.data.Dataset] = None,
test_dataset: Optional[torch.utils.data.Dataset] = None,
loss_fn: Optional[Callable] = None,
optimizer: Optional[torch.optim.Optimizer] = None,
num_epochs: int = 100,
batch_size: int = 64,
print_every_x_steps: int = 1,
metrics: Optional[List[torchmetrics.Metric]] = None,
num_bounding_boxes: int = 2,
device: Optional[torch.device] = None,
num_workers: Optional[int] = None,
):
if train_dataset is None:
train_dataset = get_voc_detection_dataset_yolo()[0]
if test_dataset is None:
test_dataset = get_voc_detection_dataset_yolo()[1]
num_classes = len(train_dataset.classes)
# init loss function
if loss_fn is None:
loss_fn = YoloV1Loss(num_classes=num_classes, num_bounding_boxes=num_bounding_boxes)
classification_metrics_kwargs = {
'num_classes': num_classes,
'task': 'multiclass'
}
if metrics is None:
classification_metrics = [
Accuracy(**classification_metrics_kwargs).cuda(),
AveragePrecision(**classification_metrics_kwargs).cuda(),
AUROC(**classification_metrics_kwargs).cuda(),
Dice(**classification_metrics_kwargs).cuda(),
F1Score(**classification_metrics_kwargs).cuda()
]
metrics: List[torchmetrics.Metric] = [
YoloV1ClassMetricWrapper(metric, num_bounding_boxes=num_bounding_boxes, num_classes=num_classes)
for metric in classification_metrics
]
train_model(
model,
train_dataset,
test_dataset,
loss_fn,
optimizer,
num_epochs,
batch_size,
print_every_x_steps,
metrics,
device=device,
num_workers=num_workers
)
def main():
in_channels = 3
num_bounding_boxes = 2
grid_size = 7
num_epochs = 130
batch_size = 16
train_dataset = get_voc_detection_dataset_yolo_aug(
num_bounding_boxes=num_bounding_boxes,
grid_size=grid_size,
download=False
)[0]
test_dataset = get_voc_detection_dataset_yolo(
num_bounding_boxes=num_bounding_boxes,
grid_size=grid_size,
download=False
)[1]
num_classes = len(train_dataset.classes)
ResNetYoloV1WithConfig = config_wrapper(ResNetYoloV1)
model = ResNetYoloV1WithConfig(
in_channels=in_channels,
num_classes=num_classes,
num_bounding_boxes=num_bounding_boxes,
grid_size=grid_size,
mlp_size=1024,
internal_size=1024
)
train_yolo_v1(
model=model,
train_dataset=train_dataset,
test_dataset=test_dataset,
num_epochs=num_epochs,
batch_size=batch_size,
num_bounding_boxes=num_bounding_boxes,
)
if __name__ == '__main__':
main()
|
import torch
from torchvision import models as resnet_model
from torch import nn
import timm
import torch.nn.functional as F
class SEBlock(nn.Module):
def __init__(self, channel, r=16):
super(SEBlock, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc = nn.Sequential(
nn.Linear(channel, channel // r, bias=False),
nn.ReLU(inplace=True),
nn.Linear(channel // r, channel, bias=False),
nn.Sigmoid(),
)
def forward(self, x):
b, c, _, _ = x.size()
y = self.avg_pool(x).view(b, c)
y = self.fc(y).view(b, c, 1, 1)
y = torch.mul(x, y)
return y
class ChannelPool(nn.Module):
def forward(self, x):
return torch.cat( (torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)), dim=1 )
class BasicConv(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False):
super(BasicConv, self).__init__()
self.out_channels = out_planes
self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)
self.bn = nn.BatchNorm2d(out_planes,eps=1e-5, momentum=0.01, affine=True) if bn else None
self.relu = nn.ReLU() if relu else None
def forward(self, x):
x = self.conv(x)
if self.bn is not None:
x = self.bn(x)
if self.relu is not None:
x = self.relu(x)
return x
class SpatialAttention(nn.Module):
def __init__(self):
super(SpatialAttention, self).__init__()
kernel_size = 7
self.compress = ChannelPool()
self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(kernel_size-1) // 2, relu=False)
def forward(self, x):
x_compress = self.compress(x)
x_out = self.spatial(x_compress)
scale = F.sigmoid(x_out) # broadcasting
return x * scale
### Spacial attention block
""" class SpatialAttention(nn.Module):
def __init__(self, kernel_size=7):
super(SpatialAttention, self).__init__()
self.conv = nn.Conv2d(2, 1, kernel_size, padding=(kernel_size - 1) // 2, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
avg_out = torch.mean(x, dim=1, keepdim=True)
max_out, _ = torch.max(x, dim=1, keepdim=True)
x = torch.cat([avg_out, max_out], dim=1)
x = self.conv(x)
x = self.sigmoid(x)
return x """
class DecoderBottleneckLayer(nn.Module):
def __init__(self, in_channels):
super(DecoderBottleneckLayer, self).__init__()
self.conv1 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1)
self.norm1 = nn.BatchNorm2d(in_channels)
self.relu1 = nn.ReLU(inplace=True)
self.conv3 = nn.Conv2d(in_channels, in_channels, kernel_size=3, padding=1)
self.norm3 = nn.BatchNorm2d(in_channels)
self.relu3 = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv1(x)
x = self.norm1(x)
x = self.relu1(x)
x = self.conv3(x)
x = self.norm3(x)
x = self.relu3(x)
return x
class ParaPVTCNN_SA(nn.Module):
def __init__(self, n_channels=3, num_classes=9, dim=320, patch_size=2):
super(ParaPVTCNN_SA, self).__init__()
self.num_classes = num_classes
self.n_channels = n_channels
self.patch_size = patch_size
self.dim = dim
embed_dim = [64, 128, 256, 512] # PVT uses different dimensions for different stages
resnet = resnet_model.resnet34(weights=resnet_model.ResNet34_Weights.DEFAULT)
# Create the PVT model
self.transformer = timm.create_model(
'pvt_v2_b2_li',
pretrained=True,
features_only=True,
)
self.firstconv = resnet.conv1
self.firstbn = resnet.bn1
self.firstrelu = resnet.relu
self.encoder1 = resnet.layer1
self.encoder2 = resnet.layer2
self.encoder3 = resnet.layer3
self.encoder4 = resnet.layer4
# Update SEBlock initialization with correct input channels
self.SE_1 = SEBlock(embed_dim[3] + 512)
self.SE_2 = SEBlock(dim + 256)
self.SE_3 = SEBlock(embed_dim[1] + 128)
self.SA = SpatialAttention()
self.decoder1 = DecoderBottleneckLayer(embed_dim[3] + 512)
self.decoder2 = DecoderBottleneckLayer(dim + embed_dim[2] + 512) # Trouver la bonne formule mathématique
self.decoder3 = DecoderBottleneckLayer(512)
self.up3_1 = nn.ConvTranspose2d(embed_dim[3] + 512, embed_dim[2] + 256, kernel_size=2, stride=2)
self.up2_1 = nn.ConvTranspose2d(dim + embed_dim[2] + 512, embed_dim[1] + 128, kernel_size=2, stride=2)
self.up1_1 = nn.ConvTranspose2d(512, embed_dim[0], kernel_size=4, stride=4)
self.out = nn.Conv2d(embed_dim[0], num_classes, kernel_size=1)
def forward(self, x):
b, c, h, w = x.shape
e0 = self.firstconv(x)
e0 = self.firstbn(e0)
e0 = self.firstrelu(e0)
e1 = self.encoder1(e0)
e2 = self.encoder2(e1)
e3 = self.encoder3(e2)
e4 = self.encoder4(e3)
# Get features from PVT model
features = self.transformer(x)
v1_cnn = features[0]
v2_cnn = features[1]
v3_cnn = features[2]
v4_cnn = features[3]
# Ensure the dimensions match
v4_cnn = nn.functional.interpolate(v4_cnn, size=e4.shape[2:], mode='bilinear', align_corners=False)
cat_1 = torch.cat([v4_cnn, e4], dim=1)
cat_1 = self.SE_1(cat_1)
cat_1 = self.SA(cat_1) * cat_1
cat_1 = self.decoder1(cat_1)
cat_1 = self.up3_1(cat_1)
v3_cnn = nn.functional.interpolate(v3_cnn, size=e3.shape[2:], mode='bilinear', align_corners=False)
cat_2 = torch.cat([v3_cnn, e3], dim=1)
cat_2 = self.SE_2(cat_2)
cat_2 = self.SA(cat_2) * cat_2
cat_2 = torch.cat([cat_2, cat_1], dim=1)
cat_2 = self.decoder2(cat_2)
cat_2 = self.up2_1(cat_2)
v2_cnn = nn.functional.interpolate(v2_cnn, size=e2.shape[2:], mode='bilinear', align_corners=False)
cat_3 = torch.cat([v2_cnn, e2], dim=1)
cat_3 = self.SE_3(cat_3)
cat_3 = self.SA(cat_3) * cat_3
cat_3 = torch.cat([cat_3, cat_2], dim=1)
cat_3 = self.decoder3(cat_3)
cat_3 = self.up1_1(cat_3)
out = self.out(cat_3)
return out
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>商品信息编辑</title>
<link href="css/jquery.stepy.css" th:href="@{/css/jquery.stepy.css}" rel="stylesheet">
<div th:include="common :: commonheader"></div>
<link rel="stylesheet" th:href="@{/layui/css/layui.css}">
<style>
.layui-form-pane, .layui-form-label {
width: 110px;
padding: 8px 15px;
height: 38px;
line-height: 20px;
border-width: 1px;
border-style: solid;
border-radius: 2px 0 0 2px;
text-align: center;
background-color: #FBFBFB;
overflow: hidden;
box-sizing: border-box
}
</style>
</head>
<body class="sticky-header">
<section>
<div th:replace="common :: #leftmenu"></div>
<!-- main content start-->
<div class="main-content">
<div th:replace="common :: headermenu"></div>
<!-- 页面标题开始-->
<div class="page-heading">
<h3>
商品信息编辑
</h3>
<ul class="breadcrumb">
<li>
<a href="#">后台主页</a>
</li>
<li>
<a href="#">商品信息管理</a>
</li>
<li class="active">商品信息编辑</li>
</ul>
</div>
<!-- 页面标题结束-->
<!--内容区域开始-->
<div class="wrapper" style="font:14px STKaiti;color: #6b6b6b;">
<div class="col-md-12">
<section class="panel">
<header class="panel-heading">商品信息编辑</header>
<div class="panel-body" style="height: 909px">
<form class="layui-form"
style="margin: 0 auto;max-width: 460px;padding-top: 40px;"
lay-filter="example">
<div class="layui-form-item">
<label class="layui-form-label">商品ID:</label>
<div class="layui-input-block">
<input type="number" placeholder="请填写商品ID" name="id"
class="layui-input" lay-verify="number" required/>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">商品名称:</label>
<div class="layui-input-block">
<input type="text" placeholder="请填写商品名称"
name="name" class="layui-input" required>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">商品金额:</label>
<div class="layui-input-block">
<input type="number" placeholder="请填写商品金额" name="amount"
class="layui-input" lay-verify="number" required>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">商品类型:</label>
<div class="layui-input-block">
<select lay-verify="required" name="category">
<option value="0" selected>请选择</option>
<option value="水果">水果</option>
<option value="蔬菜">蔬菜</option>
<option value="零食">零食</option>
</select>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">商品数量:</label>
<div class="layui-input-block">
<input type="number" placeholder="请填写商品数量" name="num"
class="layui-input" lay-verify="number" required>
</div>
</div>
<div class="layui-inline">
<label class="layui-form-label">生产日期</label>
<div class="layui-input-inline">
<input type="text" name="date" id="date" lay-verify="date"
placeholder="yyyy-MM-dd"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">商品产地:</label>
<div class="layui-input-block">
<input type="text" placeholder="请填写商品产地" name="address"
class="layui-input" required>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">审核人:</label>
<div class="layui-input-block">
<select name="reviewer" lay-verify="required">
<option value="" selected>请选择</option>
<option value="张三">张三</option>
<option value="李四">李四</option>
</select>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">备注说明:</label>
<div class="layui-input-block">
<textarea placeholder="备注……" name="notes"
class="layui-textarea"></textarea>
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn layui-btn-normal" lay-submit
lay-filter="saveBtn">确认保存
</button>
</div>
</div>
</form>
</div>
<script th:src="@{/layui/layui.js}"></script>
<script>
layui.use(['form', 'layedit', 'laydate', 'layer'], function () {
var form = layui.form
, layer = layui.layer
, layedit = layui.layedit
, laydate = layui.laydate
, data = JSON.parse(sessionStorage.getItem("data"));
//表单赋值
form.val("example", {
"id": data.id
, "name": data.name
, "amount": data.amount
, "category": data.category
, "num": data.num
, "date": data.date
, "address": data.address
, "reviewer": data.reviewer
, "notes": data.notes
});
//日期
laydate.render({
elem: '#date'
});
laydate.render({
elem: '#date1'
});
//监听提交
form.on('submit(saveBtn)', function (data) {
layer.alert(JSON.stringify(data), {
title: '最终的提交信息'
})
return false;
});
});
</script>
</section>
</div>
</div>
<!--内容区域结束-->
<!--footer section start-->
<div th:replace="common :: #footer"></div>
<!--footer section end-->
</div>
<!-- main content end-->
</section>
<!-- Placed js at the end of the document so the pages load faster -->
<div th:replace="common :: #commonscript"></div>
</body>
</html>
|
package HomeTask01_2;
// 2. Описать в ООП стиле логику взаимодействия объектов реального мира между собой: шкаф-человек.
// Какие члены должны быть у каждого из классов (у меня на семинаре студенты пришли к тому, чтобы продумать
// логику взаимодействия жена разрешает открыть дверцу шкафа мужу, после чего эту дверцу можно открыть)
// Подумать как описать логику взаимодействия человека и домашнего питомца. Сценарий: “Человек “зовёт”
// котика “кис-кис”, котик отзывается. Какое ещё взаимодействие может быть?
// У задач нет единственного правильного решения
public class Task02 {
public static void main(String[] args) {
Husband h1 = new Husband("Brad", "husband");
h1.about();
Wife w1 = new Wife("Amy", "wife", false);
w1.about();
Cat c1 = new Cat("Barsik", "on wardrobe");
c1.about(); // Кот на шкафу
h1.catCall(c1, h1); // Брэд зовет кота
c1.about(); // Кот у Брэда
w1.catCall(c1, w1); // Эми зовет кота
c1.about(); // Кот у Эми
Furniture f1 = new Furniture("wardrobe", "closed");
f1.about();
h1.wardOpen(w1, f1); // Брэд хочет открыть шкаф (но нет разрешения от Эми)
w1.givePermit(); // Эми дает разрешение
h1.wardOpen(w1, f1); // Брэд открывает шкаф
h1.wardClose(f1); // Брэд закрывает шкаф
h1.wardOpen(w1, f1); // Брэд открывает шкаф
h1.wardOpen(w1, f1); // Брэд хочет открыть шкаф (но он уже открыт)
w1.wardClose(f1); // Эми закрывает шкаф
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.