text
stringlengths 184
4.48M
|
---|
# Copyright 2021-2023 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.
"""
This module defines the BaseFrame class which is used to represent a frame.
"""
from abc import ABC, abstractmethod
from mindpandas.compiler.lazy.query_plan import PlanOpMixin
class BaseFrame(ABC, PlanOpMixin):
"""
An abstract class used to represent a frame
"""
@classmethod
def create(cls):
from mindpandas.backend.eager.eager_frame import EagerFrame
return EagerFrame()
@abstractmethod
def map(self, map_func):
pass
@abstractmethod
def map_reduce(self, map_func, reduce_func, axis=0):
pass
@abstractmethod
def repartition(self, output_shape, mblock_size):
pass
@abstractmethod
def to_pandas(self):
pass
@abstractmethod
def to_numpy(self):
pass
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { async, ComponentFixture, inject, TestBed } from '@angular/core/testing';
import { RegulatoryReportingFilingService } from '../services/regulatory-reporting-filing.service';
import { RegulatoryReportingFilingComponent } from './regulatory-reporting-filing.component';
import { of } from 'rxjs';
import { MotifButtonModule, MotifCardModule, MotifFormsModule, MotifIconModule, MotifPaginationModule, MotifProrgressIndicatorsModule, MotifTableModule } from '@ey-xd/ng-motif';
import { CommonModule } from '@angular/common';
import { environment } from '../../../../../../src/environments/environment';
import { EycRrSettingsService } from '../../services/eyc-rr-settings.service';
import { HttpClientModule } from '@angular/common/http';
import { RouterTestingModule } from '@angular/router/testing';
import { AgGridModule } from 'ag-grid-angular';
describe('RegulatoryReportingFilingComponent', () => {
let component: RegulatoryReportingFilingComponent;
let fixture: ComponentFixture<RegulatoryReportingFilingComponent>;
let filingService: RegulatoryReportingFilingService;
let mockFilings = {
"success": true,
"message": "",
"corelationId": null,
"data": [
{
"filingName": "Form PF",
"filingId": 1,
"filingStatus": [
{
"stage": "Fund Scoping",
"stageId": 1,
"stageCode": "FUND_SCOPING",
"progress": "In Progress",
"displayOrder": 1
},
{
"stage": "Intake",
"stageId": 2,
"stageCode": "DATA_INTAKE",
"progress": "In Progress",
"displayOrder": 2
},
{
"stage": "Reporting",
"stageId": 3,
"stageCode": "REPORTING",
"progress": "Not Started",
"displayOrder": 3
},
{
"stage": "Client review",
"stageId": 4,
"stageCode": "CLIENT_REVIEW",
"progress": "Not Started",
"displayOrder": 4
},
{
"stage": "Submission",
"stageId": 5,
"stageCode": "SUBMISSION",
"progress": "Not Started",
"displayOrder": 5
}
],
"dueDate": "2021-05-30",
"startDate": null,
"period": "Q4 2021"
}
]
};
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ RegulatoryReportingFilingComponent ],
imports: [
AgGridModule.withComponents([]),
CommonModule,
MotifCardModule,
MotifButtonModule,
MotifFormsModule,
MotifIconModule,
MotifProrgressIndicatorsModule,
MotifTableModule,
HttpClientModule,
MotifPaginationModule,
RouterTestingModule,
HttpClientTestingModule
],
providers: [RegulatoryReportingFilingService,
EycRrSettingsService,
{provide:"apiEndpoint", useValue: environment.apiEndpoint},
{provide:"rrproduction", useValue: environment.production}]
})
.compileComponents();
fixture = TestBed.createComponent(RegulatoryReportingFilingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
filingService = TestBed.get(RegulatoryReportingFilingService);
}));
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call getFilingsData and return list of flilingsData', async(()=> {
let activeFilings = []
// spyOn(filingService, 'getFilings').and.returnValue(of(response))
fixture.detectChanges();
const result$ = filingService.getFilings();
result$.subscribe(resp => {
resp['data'].forEach((item) => {
const eachitem: any = {
name: item.filingName,
dueDate: item.dueDate,
startDate: item.startDate,
comments: [],
status: item.filingStatus,
filingName: item.filingName,
period: item.period,
filingId: item.filingId
};
activeFilings.push(eachitem);
});
expect(component.activeFilings).toEqual(activeFilings);
})
}));
it('should format date', () => {
expect(component.formatDate(1624288509000)).toEqual('06/21/2021');
});
it('should change tab to selected', () => {
component.reportTabChange(3);
expect(component.tabIn).toEqual(3);
});
it('should get active filing data', () => {
let resp = mockFilings;
let filings = [];
spyOn(filingService, 'getFilings').and.returnValue(of(resp));
// spyOn(filingService, 'getFilingsHitory').and.returnValue(of(resp2));
component.getActiveFilingsData();
fixture.detectChanges();
resp['data'].forEach((item) => {
const eachitem: any = {
name: item.filingName,
dueDate: item.dueDate,
startDate: item.startDate,
comments: [],
status: item.filingStatus,
filingName: item.filingName,
period: item.period,
filingId: item.filingId
};
filings.push(eachitem);
});
expect(component.activeFilings).toEqual(filings);
});
it('should get completed filing data', () => {
let resp = mockFilings;
let filings = [];
spyOn(filingService, 'getFilingsHistory').and.returnValue(of(resp));
component.currentPage = 1;
component.noOfCompletdFilingRecords = 1;
component.getCompletedFilingsData();
component.noCompletedDataAvilable = false;
component.noActivatedDataAvilable = false;
fixture.detectChanges();
resp['data'].forEach((item) => {
const eachitem: any = {
name: item.filingName + ' // ' + item.period,
period: item.period,
dueDate: item.dueDate,
startDate: item.startDate,
comments: [],
status: item.filingStatus
};
filings.push(eachitem);
});
expect(component.completedFilings).toEqual(filings);
});
it('should validate characters in search`', () => {
const test1 = { keyCode: 65, preventDefault: function() {}};
const test2 = { keyCode: 48, preventDefault: function() {} };
const test3 = { keyCode: 164, preventDefault: function() {} };
expect(component.searchFilingValidation(test1)).toEqual(true);
expect(component.searchFilingValidation(test2)).toEqual(true);
expect(component.searchFilingValidation(test3)).toEqual(false);
});
// it('grid API is available after `detectChanges`', () => {
// fixture.detectChanges();
// expect(component.gridApi).toBeTruthy();
// });
// it('should populate grid cells as expected', () => {
// component.funds = dummyFunds;
// component.createFundRowData();
// fixture.detectChanges();
// const hostElement = fixture.nativeElement;
// const cellElements = hostElement.querySelectorAll('.ag-cell-value');
// expect(cellElements.length).toEqual(20);
// });
// it('should search table', () => {
// component.funds = dummyFunds;
// component.createFundRowData();
// fixture.detectChanges();
// const hostElement = fixture.nativeElement;
// // component.gridApi.setQuickFilter('19614013');
// const input = {
// el: {
// nativeElement: {
// value: '19614013'
// }
// }
// }
// component.searchFunds(input);
// const cellElements = hostElement.querySelectorAll('.ag-cell-value');
// expect(cellElements.length).toEqual(4);
// })
});
|
import React from 'react';
import {NavLink} from 'react-router-dom';
import styles from './Header.module.css';
import {connect} from 'react-redux';
import {authLogOut} from '../../actions/users';
import {history} from '../../utils/history';
const Header = (props) => {
const logOut = () => {
props.authLogOut();
localStorage.removeItem('user');
history.push('/map');
}
return (
<div className={styles.header}>
<div className={styles.header_logo}>
<h1>Оренбург</h1>
</div>
<div className={styles.header_right}>
<NavLink className={styles.header_link} to="/map" activeClassName={styles.active_header_link}>Карта</NavLink>
{!props.user ? (<NavLink className={styles.header_link} to="/auth" activeClassName={styles.active_header_link}>Войти</NavLink>) : (
<React.Fragment>
<NavLink className={styles.header_link} to='/marker' activeClassName={styles.active_header_link}>Добавить метку</NavLink>
<NavLink className={styles.header_link} to='/personal' activeClassName={styles.active_header_link}>Личный кабинет</NavLink>
<span className={styles.header_link} onClick={()=>logOut()} >Выйти</span>
</React.Fragment>
)}
</div>
</div>
)
}
const mapStateToProps = store => ({
user: store.usersReducer.user
})
const mapDispatchToProps = dispatch => ({
authLogOut: () => dispatch(authLogOut())
})
export default connect(mapStateToProps, mapDispatchToProps)(Header);
|
import 'package:flutter/material.dart';
import 'package:greentrack/Screens/main/main_screen.dart';
import 'package:nb_utils/nb_utils.dart';
import '../../../components/already_have_an_account_acheck.dart';
import '../../../components/button.dart';
import '../../../constants.dart';
import '../../Signup/signup_screen.dart';
class LoginForm extends StatefulWidget {
const LoginForm({
Key? key,
}) : super(key: key);
@override
State<LoginForm> createState() => _LoginFormState();
}
class _LoginFormState extends State<LoginForm> {
@override
Widget build(BuildContext context) {
return Form(
child: Column(
children: [
Container(
width: 370,
child: TextFormField(
keyboardType: TextInputType.emailAddress,
textInputAction: TextInputAction.next,
cursorColor: kPrimaryColor,
onSaved: (email) {},
decoration: const InputDecoration(
label: Text("Adresse email"),
border: OutlineInputBorder(),
prefixIcon: Padding(
padding: EdgeInsets.all(defaultPadding),
child: Icon(Icons.person),
),
),
),
),
Container(
width: 370,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: defaultPadding),
child: TextFormField(
textInputAction: TextInputAction.done,
obscureText: true,
cursorColor: kPrimaryColor,
decoration: const InputDecoration(
label: Text("Mot de passe"),
border: OutlineInputBorder(),
prefixIcon: Padding(
padding: EdgeInsets.all(defaultPadding),
child: Icon(Icons.lock),
),
),
),
),
),
const SizedBox(height: defaultPadding),
CustomButon(
onPress: () {
MainScreen().launch(context);
}, title: 'Connexion', color: kPrimaryColor,
),
const SizedBox(height: defaultPadding),
AlreadyHaveAnAccountCheck(
press: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return const SignUpScreen();
},
),
);
},
),
],
),
);
}
}
|
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, vi } from "vitest";
import Button from "../../components/Button";
describe("Render the button and trigger the onclick event", () => {
const onClick = vi.fn();
test("Render the button ", async () => {
render(<Button onClick={onClick}>GMM</Button>);
const buttonEl = screen.getByRole("button", {
name: /GMM/i,
});
expect(buttonEl).toBeInTheDocument();
});
test("trigger the onclick event", async () => {
render(<Button onClick={onClick}>GMM</Button>);
const buttonEl = screen.getByRole("button", {
name: /GMM/i,
});
fireEvent.click(buttonEl);
expect(onClick).toHaveBeenCalled();
});
});
|
<%@page language="java" contentType="text/html; charset=utf-8"%>
<%String rootPath=request.getContextPath();
String panelId=request.getParameter("panelId");
%>
<script type="text/javascript">
/*!
* Ext JS Library 3.1.0
* Copyright(c) 2006-2009 Ext JS, LLC
* [email protected]
* http://www.extjs.com/license
*/
Ext.onReady(function(){
// create the Data Store
var store = new Ext.data.Store({
// load using HTTP
url: 'sheldon.xml',
// the return will be XML, so lets set up a reader
reader: new Ext.data.XmlReader({
// records will have an "Item" tag
record: 'Item',
id: 'ASIN',
totalRecords: '@total'
}, [
// set up the fields mapping into the xml doc
// The first needs mapping, the others are very basic
{name: 'Author', mapping: 'ItemAttributes > Author'},
'Title', 'Manufacturer', 'ProductGroup'
])
});
// create the grid
var grid = new Ext.grid.GridPanel({
store: store,
anchor:'-1 -1',
columns: [
new Ext.grid.RowNumberer({width:44}),
{header: "Author", width: 120, dataIndex: 'Author', sortable: true},
{header: "Title", width: 180, dataIndex: 'Title', sortable: true},
{header: "Manufacturer", width: 115, dataIndex: 'Manufacturer', sortable: true},
{header: "Product Group", width: 100, dataIndex: 'ProductGroup', sortable: true}
],
width:540,
height:200,
frame: true,
trackMouseOver: false,
sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
//enableColumnMove: false,
title: 'Sponsored Projects',
bbar: new Ext.PagingToolbar({
firstText : '首页',
lastText : '尾页',
nextText : '下一页',
prevText : '上一页',
refreshText : '刷新',
beforePageText : '第',
afterPageText : '页,共 {0} 页',
displayMsg : '共 {2} 条,当前显示当前显示当前显示 {0} 到 {1} 条',
emptyMsg : '没有符合条件的数据',
pageSize: 10,
store: store,
displayInfo: true,
items : [
'-',
'每页显示:',
new Ext.form.ComboBox({
editable : false,
triggerAction: 'all',
width : 50,
store : [10,20,30,40,50,100,200,300,400,500],
value : 10,
listeners : {
'select' : function(c, record, index){
grid.getBottomToolbar().pageSize = c.getValue();
grid.getBottomToolbar().changePage(1);
}
}
})
]
,
plugins: new Ext.ux.ProgressBarPager({defaultText:'正在装载数据...'}),
listeners : {
'beforechange' : function(a, b){
store.baseParams.limit = b.limit;
store.baseParams.start = b.start;
}
}
})
});
store.load();
Ext.getCmp('<%=panelId%>').add(grid);
Ext.getCmp('<%=panelId%>').doLayout();
});
</script>
|
import dash
from dash import dcc, html
from dash.dependencies import Input, Output, State
from flask import request
from main import main_
app = dash.Dash(__name__)
server = app.server
app.layout = html.Div([
html.H1("Text Similarity Calculator"),
html.Div([
html.Label("Text 1 "),
dcc.Input(id='text1-input', type='text', value=''),
], style={'margin-bottom': '10px'}),
html.Div([
html.Label("Text 2 "),
dcc.Input(id='text2-input', type='text', value=''),
], style={'margin-bottom': '10px'}),
html.Div([
html.Button('Calculate Similarity', id='calculate-button'),
html.Div(id='store-clicks', style={'display': 'none'}),
], style={'margin-bottom': '10px'}),
html.Div(id='output-similarity')
])
@app.callback(
Output('store-clicks', 'children'),
[Input('calculate-button', 'n_clicks')]
)
def store_click_count(n_clicks):
return n_clicks
@app.callback(
Output('output-similarity', 'children'),
[Input('store-clicks', 'children')],
[State('text1-input', 'value'),
State('text2-input', 'value')]
)
def calculate_similarity(n_clicks, text1, text2):
if n_clicks is not None and n_clicks > 0:
score = main_(text1, text2)
return f"Similarity Score: {score}"
else:
return ''
@app.server.route('/api', methods=['POST', 'GET'])
def handle_api():
if request.method == 'POST':
data = request.json
text1 = data.get('text1', '')
text2 = data.get('text2', '')
score = main_(text1, text2)
return {'similarity_score': score}
elif request.method == 'GET':
text1 = request.args.get('text1', '')
text2 = request.args.get('text2', '')
score = main_(text1, text2)
return {'similarity_score': score}
if __name__ == '__main__':
server.run(debug=False)
|
//
// JNS_StatusItemController.h
// MenuApp
//
// Created by Jonathan Nathan, JNSoftware LLC on 1/12/11.
// Copyright 2011 JNSoftware LLC. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#import <Cocoa/Cocoa.h>
// The typedef enums aren't strictly necessary but they help to clarify
// what's going on in your code. We're also using 1-based indexes because this
// app is rooted in AppleScript which also uses 1-based indexes as opposed to
// Objective-C that uses 0-based indexes.
typedef enum {
MenuAppDisplayOptionTitleOnly = 1,
MenuAppDisplayOptionIconOnly = 2,
MenuAppDisplayOptionTitleAndIcon = 3
} MenuAppDisplayOption;
typedef enum {
MenuAppAnimationOptionNone = 1,
MenuAppAnimationOptionAnimateIcon = 2,
MenuAppAnimationOptionUseSpinner = 3
} MenuAppAnimationOption;
@interface JNS_StatusItemController : NSObject {
NSStatusItem *statusItem;
NSTimer *animationTimer;
int updateCount;
NSMenu *menu;
}
- (void)createStatusItemWithMenu:(NSMenu *)_menu;
- (void)showMenu;
- (void)updateDisplay;
- (void)updateAnimation:(MenuAppAnimationOption)animationOption;
- (void)toggleIconAnimation:(BOOL)shouldStart;
- (void)releaseStatusItem;
@end
|
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:idute_app/components/constants/colors.dart';
import 'package:idute_app/components/constants/size_config.dart';
import 'package:idute_app/components/widgets/normal_text_widget.dart';
class ShareBottomSheet extends StatefulWidget {
const ShareBottomSheet({super.key});
@override
State<ShareBottomSheet> createState() => _ShareBottomSheetState();
}
class _ShareBottomSheetState extends State<ShareBottomSheet> {
final TextEditingController _searchController = TextEditingController();
List<String> data = [];
@override
Widget build(BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Container(
width: SizeConfig.screenWidth,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(
height: 20,
),
Container(
width: 50,
height: 5,
decoration: BoxDecoration(
color: AppColors.kFillColor,
borderRadius: BorderRadius.circular(10)),
),
const SizedBox(height: 30.0),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: TextFormField(
controller: _searchController,
style: Theme.of(context).textTheme.bodySmall!.copyWith(),
decoration: InputDecoration(
prefixIcon: Padding(
padding: const EdgeInsets.all(10.0),
child: SvgPicture.asset("assets/icons/search.svg"),
),
isCollapsed: true,
contentPadding:
EdgeInsets.only(top: 13, bottom: 10, left: 10),
fillColor: AppColors.kcardColor,
hintStyle: Theme.of(context)
.textTheme
.bodySmall!
.copyWith(fontSize: 14),
filled: true,
hintText: "Search",
border: OutlineInputBorder(
borderSide: BorderSide.none,
borderRadius: BorderRadius.circular(10))),
),
),
const SizedBox(
height: 12,
),
ListView.builder(
shrinkWrap: true,
itemCount: 5,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
setState(
() {
if (data.contains("Ayush")) {
data.remove("Ayush");
} else {
data.add("Ayush");
}
},
);
},
child: Container(
padding: EdgeInsets.symmetric(
vertical: 10, horizontal: 12),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
const CircleAvatar(
backgroundImage:
AssetImage("assets/images/profile.png"),
),
const SizedBox(
width: 10,
),
Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
buildText(
text: "Ayush Mahawar", txtSize: 12),
buildText(
text: "Technology",
txtSize: 12,
color: AppColors.kFillColor)
],
)
],
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
width: 20,
height: 20,
child: (data.isNotEmpty)
? Icon(
Icons.circle,
color: Colors.white,
size: 12,
)
: null,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
width: 1, color: Colors.white)),
),
)
],
),
),
);
}),
const SizedBox(
height: 10,
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10),
width: SizeConfig.screenWidth,
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)))),
onPressed: () {},
child: buildText(
text: "Send",
color: AppColors.sBackgroundColor,
fontWeight: FontWeight.bold)),
),
const SizedBox(
height: 20,
),
],
),
),
);
},
);
;
}
}
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { CityComponent } from './city/city.component';
import { CityFormComponent } from './city-form/city-form.component';
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full'},
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: 'city', component: CityComponent},
{ path: 'city/new', component: CityFormComponent },
{ path: 'city/:id', component: CityFormComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
package com.example.travelplanner;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class AlbumFragment extends Fragment {
private static final int PICK_IMAGE_REQUEST = 1;
private Button btnChooseImage;
private ImageView imageView;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_album, container, false);
btnChooseImage = rootView.findViewById(R.id.selectImageButton);
imageView = rootView.findViewById(R.id.albumImageView);
btnChooseImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openImageChooser();
}
});
return rootView;
}
private void openImageChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == Activity.RESULT_OK && data != null && data.getData() != null) {
Uri imageUri = data.getData();
// 이미지를 앱 내부 저장소로 복사
copyImageToAppStorage(imageUri);
}
}
private void copyImageToAppStorage(Uri imageUri) {
try {
// 이미지 파일의 원본 경로 가져오기
String imagePath = getImagePath(imageUri);
// 이미지 파일을 앱 내부 저장소로 복사
File destinationFile = getDestinationFile();
copyFile(new File(imagePath), destinationFile);
// 이미지가 성공적으로 저장되었음을 알림
Toast.makeText(getActivity(), "Image saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
// 이미지 저장 중에 오류 발생한 경우에 대한 예외 처리
Toast.makeText(getActivity(), "Failed to save image", Toast.LENGTH_SHORT).show();
}
}
private String getImagePath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
String imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
return null;
}
private File getDestinationFile() {
File directory = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
String fileName = "image.jpg";
return new File(directory, fileName);
}
private void copyFile(File sourceFile, File destinationFile) throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(sourceFile);
outputStream = new FileOutputStream(destinationFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
//
// RandomColorChar.swift
// modal
//
// Created by Patrick Fuller on 3/8/22.
//
import Foundation
import SwiftUI
class RandomColorChar: ObservableObject {
@Published var randomRed: CGFloat = 0
@Published var randomGreen: CGFloat = 0
@Published var randomBlue: CGFloat = 0
@Published var randomCharInt = 0
var color: Color {
Color(red: randomRed, green: randomGreen, blue: randomBlue)
}
var char: Character {
Character(UnicodeScalar(randomCharInt + 65) ?? "A")
}
init() {
mutate()
}
func mutate() {
randomRed = CGFloat.random(in: 0...1)
randomGreen = CGFloat.random(in: 0...1)
randomBlue = CGFloat.random(in: 0...1)
randomCharInt = Int.random(in: 0...26)
}
}
|
import React, { useState } from 'react'
import "./style.css"
import Menu from "./menuApi"
import MenuCard from './MenuCard'
import Navbar from './Navbar'
const uniqueList =[
... new Set(
Menu.map((currElem)=>{
return currElem.category
})
), "All"
]
console.log(uniqueList)
const Restaurant = () => {
const [menuData, setMenuData]= useState(Menu)
const [menuList, setMenuList]= useState(uniqueList)
const filterItem=(category) =>{
if(category==="All"){
setMenuData(Menu)
return
}
const updatedList=Menu.filter((currElem)=>{
return currElem.category=== category;
})
setMenuData(updatedList)
}
return (
<>
<Navbar filterItem={filterItem} menuList={menuList}/>
<MenuCard menuData={menuData}/>
</>
)
}
export default Restaurant
|
using System.Collections.Generic;
using Telegram.Bot.Types.ReplyMarkups;
using TelegramBot.Commands;
namespace TelegramBot
{
/// <summary>
/// Класс анализатор команд.
/// </summary>
public class CommandParser
{
/// <summary>
/// Список объектов команд бота.
/// </summary>
private List<IChatCommand> Command;
/// <summary>
/// Поле класса контроллера добавления слова в словарь.
/// </summary>
private AddingController addingController;
/// <summary>
/// Конструктор. Инициализирует список команд бота и AddingController.
/// </summary>
public CommandParser()
{
Command = new List<IChatCommand>();
addingController = new AddingController();
}
/// <summary>
/// Добавляет объект команды в список объектов команд.
/// </summary>
/// <param name="chatCommand"></param>
public void AddCommand(IChatCommand chatCommand)
{
Command.Add(chatCommand);
}
/// <summary>
/// Проверяет наличие команды в списке.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public bool IsMessageCommand(string message)
{
return Command.Exists(x => x.CheckMessage(message));
}
/// <summary>
/// Проверяет реализует ли данная команда IChatTextCommand.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public bool IsTextCommand(string message)
{
var command = Command.Find(x => x.CheckMessage(message));//ищем по списку соответствующую команду
return command is IChatTextCommand;//является ли command объектом типа IChatTextCommand?
}
/// <summary>
/// Проверяет реализует ли данная команда IKeyBoardCommand.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public bool IsButtonCommand(string message)
{
var command = Command.Find(x => x.CheckMessage(message));
return command is IKeyBoardCommand;
}
/// <summary>
/// Проверяет реализует ли данная команда IKeyBoardCommandCheck.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public bool IsButtonCommandCheck(string message)
{
var command = Command.Find(x => x.CheckMessage(message));
return command is ICommandCheck;
}
/// <summary>
/// Проверяет возможность выполнения команды по дополнительным критериям.
/// </summary>
/// <param name="chat"></param>
/// <returns></returns>
public bool ButtonCommandCheckPossibility(string message, Conversation chat)
{
var command = Command.Find(x => x.CheckMessage(message)) as ICommandCheck;
return command.CheckPossibility(chat);
}
/// <summary>
/// Возвращает сообщение если использование клавиатуры не возможно.
/// </summary>
/// <param name="message"></param>
/// <param name="chat"></param>
/// <returns></returns>
public string GetErrCheckText(string message)
{
var command = Command.Find(x => x.CheckMessage(message)) as ICommandCheck;
return command.ReturnErrText();
}
/// <summary>
/// Возвращает из объекта команды, выполняющей конкретное действие, текстовое
/// сообщение об успешности выполнения команды, либо об ошибке.
/// </summary>
/// <param name="message"></param>
/// <param name="chat"></param>
/// <returns></returns>
public string GetMessageText(string message, Conversation chat)
{
var command = Command.Find(x => x.CheckMessage(message)) as IChatTextCommand;
if (command is IChatTextCommandWithAction)
{
if (!(command as IChatTextCommandWithAction).DoAction(chat))
{
return "Ошибка выполнения команды!";
};
}
return command.ReturnText();
}
/// <summary>
/// Возвращает из обекта команды сообщение - пояснение к клавиатуре.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public string GetInformationalMeggase(string message)
{
var command = Command.Find(x => x.CheckMessage(message)) as IKeyBoardCommand;
return command.InformationalMessage();
}
/// <summary>
/// Возвращает из объекта команды клавиатуру.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public InlineKeyboardMarkup GetKeyBoard(string message)
{
var command = Command.Find(x => x.CheckMessage(message)) as IKeyBoardCommand;
return command.ReturnKeyBoard();
}
/// <summary>
/// Обеспечивает объекту команды подписку на событие нажатия кнопки.
/// </summary>
/// <param name="message"></param>
/// <param name="chat"></param>
public void AddCallback(string message, Conversation chat)
{
var command = Command.Find(x => x.CheckMessage(message)) as IKeyBoardCommand;
command.AddCallBack(chat);
}
/// <summary>
/// Проверяет соответствует ли полученное сообщение коменде добавления нового слова в словарь.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
public bool IsAddingCommand(string message)
{
var command = Command.Find(x => x.CheckMessage(message));//ищем по списку
return command is AddWordCommand;//проверяем является ли найденный объект нужным типом
}
/// <summary>
/// Запускает процедуру ввода нового слова в словарь конкретного чата.
/// </summary>
/// <param name="message"></param>
/// <param name="chat"></param>
public void StartAddingWord(string message, Conversation chat)
{
var command = Command.Find(x => x.CheckMessage(message)) as AddWordCommand;//ищем и приводим к нужному типу
//т.к. изначально тип IChatCommand
addingController.AddFirstState(chat);
command.StartProcessAsync(chat);
}
/// <summary>
/// Выполняет переход к следующей стадии добавления слова в словарь.
/// </summary>
/// <param name="message"></param>
/// <param name="chat"></param>
public void NextStage(string message, Conversation chat)
{
var command = Command.Find(x => x is AddWordCommand) as AddWordCommand;
command.DoForStageAsync(addingController.GetStage(chat), chat, message);
addingController.NextStage(chat);
}
/// <summary>
/// Позволяет продолжить тренировку.
/// </summary>
/// <param name="message"></param>
/// <param name="chat"></param>
public void ContinueTraining(string message, Conversation chat)
{
var command = Command.Find(x => x is TrainingCommand) as TrainingCommand;
command.NextStepAsync(chat, message);
}
}
}
|
<!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>
<h1>Lectura de JSON simple</h1>
<button type="button" id="botonLeer">Leer documento</button>
<ul id="resultado"></ul>
<script src="./jquery-3.6.1.min.js"></script>
<script>
$(document).ready(function () {
$("#botonLeer").click(function () {
$.ajax({
url: "documents/clientes.json",
method: "GET",
dataType: "json",
success: function (data) {
console.log("Leyendo servicio");
let html = "";
$.each(data.mascotas, function (indice, cliente) {
html += `<li>Key: ${indice}, Value: ${cliente.nombre}</li>`;
});
$("#resultado").html(html);
},
error: function (error) {
console.log(error.message);
},
});
});
});
</script>
</body>
</html>
|
<script setup>
import { ref } from 'vue'
defineProps({
languages: {
type: Object,
required: true,
},
})
const isOpen = ref([])
function toggleAccordion(index) {
if (isOpen.value.includes(index)) {
isOpen.value = isOpen.value.filter((i) => i !== index)
return
}
isOpen.value.push(index)
}
</script>
<template>
<div id="accordion" class="accordion-container">
<div
v-for="(post, index) in languages.posts"
:key="index"
:class="['accordion', { 'is-open': isOpen.includes(index) }]"
>
<div class="accordion-header" @click="toggleAccordion(index)">
<button v-if="!isOpen.includes(index)" class="accordion__toggle--open">
{{ post.language }}
</button>
<button v-else class="accordion__toggle--closed">
{{ post.language }}
</button>
</div>
<div
v-if="isOpen.includes(index)"
class="accordion__body--open"
:class="post.class"
>
<div class="accordion__body--closed">
<div class="accordion-content">
{{ post.text }}
<strong>{{ post.sub }}</strong>
</div>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.accordion-container {
display: flex;
justify-content: center;
align-items: center;
flex-flow: column nowrap;
gap: 0.5rem;
margin: 1rem;
padding: 0.5rem;
min-height: 20rem;
}
.accordion__toggle--closed,
.accordion__toggle--open {
border: 2px solid blue;
box-shadow: 3px 0 100px 1px blue;
font-family: 'Moonhouse';
font-size: 1.25rem;
color: #cbcbcb;
padding: 0.5rem;
min-width: 10rem;
border-radius: 10px;
background-color: #0000c9;
}
.accordion__toggle--closed,
.accordion__toggle--open:hover {
border: 4px solid blue;
box-shadow: 1px 1px 8px 1px #482ff7;
}
.accordion__toggle--closed,
.accordion__toggle--open:focus {
border: 4px solid blue;
box-shadow: 1px 1px 8px 1px #482ff7;
}
.accordion__body--closed {
max-height: 0;
margin: 2rem 0;
}
.blue {
text-shadow: 1px 1px 25px #482ff7;
}
.green {
text-shadow: 1px 1px 25px green;
}
.red {
text-shadow: 1px 1px 25px #ff8080;
}
.accordion__body--open {
color: #8f8f8f;
font-size: 1.1rem;
line-height: 1.5rem;
font-family: sans-serif;
padding-bottom: 2rem;
margin: 1rem 0 2rem;
height: 20rem;
border-radius: 8px;
display: flex;
flex-flow: column nowrap;
overflow: auto;
}
.is-open {
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
}
@media only screen and (max-width: 600px) {
.accordion__body--open {
margin: 1rem 0 2rem;
}
}
.accordion {
margin-top: 0.25rem;
padding: 0 2rem;
}
.accordion-content {
font-family: 'Poppins';
padding: 0.5rem;
overflow: hidden;
}
.card {
margin: 0.5rem;
padding: 0.5rem 1rem 1rem;
}
.card-body {
padding: 1.25rem;
}
.collapse {
padding: 0;
max-height: 10em;
overflow: hidden;
transition: 0.3s ease all;
}
.is-closed .collapse {
max-height: 0;
}
</style>
|
import pandas as pd
import sqlalchemy
import threading
from sqlalchemy import inspect
from sqlalchemy import text
from backtest_engine.database.borsdata.constants import API_KEY
from backtest_engine.database.borsdata.borsdata_client import BorsdataClient
from backtest_engine.database.borsdata.borsdata_api import BorsdataAPI
class priceDataBase:
def __init__(self, country ,market, start_date, end_date):
self.client = BorsdataClient()
self.api = BorsdataAPI(API_KEY)
self.country = country
self.market = market
self.start_date = start_date
self.end_date = end_date
engine_name = f'prices_{self.market}_{self.country}'
self.engine_name = engine_name.replace(" ", "_")
self.engine = sqlalchemy.create_engine('sqlite:////Users/oskarfransson/vs_code/trading/backtest_engine/database/files/' + self.engine_name)
#names_ids = pd.read_csv('/Users/oskarfransson/vs_code/trading/database/excel_exporter/instrument_with_meta_data.csv')[['name','ins_id', 'market', 'country']]
self.csv_file = self.client.instruments_with_meta_data()
names_ids = self.csv_file[['name','ins_id', 'market', 'country']]
self.filter_names_ids = names_ids[(names_ids.country == self.country) & (names_ids.market == self.market)]
self.id_list = self.filter_names_ids.ins_id.values.tolist()
def create_database(self):
df_list = {}
symbols = []
def _helper(idn):
df0 = self.api.get_instrument_stock_prices(idn,from_date=self.start_date, to_date=self.end_date)
symbol = self.filter_names_ids[self.filter_names_ids.ins_id == idn].name.values.tolist()[0]
symbol = symbol.replace("&", "and")
symbol = symbol.replace(" ", "_")
symbol = symbol.replace(".", "")
symbol = symbol.replace("-", "_")
df_list[symbol] = df0.copy()
symbols.append(symbol)
print(symbol)
threads = [threading.Thread(target=_helper, args=(idn,)) for idn in self.id_list]
[thread.start() for thread in threads]
[thread.join() for thread in threads]
for symbol in symbols:
new_data = df_list[symbol]
new_data = new_data.rename(columns={'date':'datetime'})
new_data.to_sql(symbol, self.engine)
return None
def export_database(self, query_string = '*'):
data_frames = {}
inspector = inspect(self.engine)
symbols = inspector.get_table_names()
with self.engine.begin() as conn:
if len(symbols) > 1:
for symbol in symbols:
try:
query = text(f'SELECT {query_string} FROM {symbol}')
data = pd.read_sql_query(query, conn)#.set_index('date')
#data.index = pd.DatetimeIndex(data.index)
data_frames[symbol] = data
except sqlalchemy.exc.OperationalError:
print(f'OperationalError. Skips {symbol}')
pass
else:
query = text(f'SELECT {query_string} FROM {symbols[0]}')
data = pd.read_sql_query(query, conn)#.set_index('date')
#data.index = pd.DatetimeIndex(data.index)
data_frames[symbol] = data
return symbols,data_frames
|
package com.shcoding.routes
import com.shcoding.domain.repository.HeroRepository
import com.shcoding.domain.util.ServerResponse
import com.shcoding.routes.util.EndPoints
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.koin.ktor.ext.inject
fun Route.allHeroes() {
val repository: HeroRepository by inject()
get(EndPoints.ALL_HEROES) {
try {
val page = call.request.queryParameters["page"]?.toInt() ?: 1
require(page in 1..5)
val response = repository.getAllHeroes(page)
call.respond(message = response, status = HttpStatusCode.OK)
} catch (e: NumberFormatException) {
call.respond(
status = HttpStatusCode.BadRequest,
message = ServerResponse(
success = false,
message = "Only numbers allowed!!"
)
)
} catch (e: IllegalArgumentException) {
call.respond(
status = HttpStatusCode.NotFound,
message = ServerResponse(
success = false,
message = "Heroes not found!!"
)
)
}
}
}
|
import {
Body,
Controller,
Delete,
ForbiddenException,
Get,
Patch,
Post,
UseGuards,
} from '@nestjs/common';
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth-guard';
import { PageRolesGuard } from 'src/page/guards/page-roles.guard';
import { GetTodo } from 'src/todo/get-todo.decorator';
import { TodoItem } from 'src/todo-item/todo-item.entity';
import { Todo } from 'src/todo/todo.entity';
import { CreateTodoItemDto } from './dto/create-todo-item.dto';
import { UpdateTodoItemDto } from './dto/update-todo-item.dto';
import { GetTodoItem } from './get-todo-item.decorator';
import { TodoItemService } from './todo-item.service';
import { Roles } from 'src/page/roles.decorator';
import { GetUser } from 'src/user/get-user.decorator';
import { User } from 'src/user/user.entity';
import { parseTodoItemForOutput } from './serializers/todo-item.serializer';
import { Page } from 'src/page/page.entity';
import { GetPage } from 'src/page/get-page.decorator';
@Controller('/pages/:pageId/todos/:todoId/todo-items')
export class TodoItemController {
constructor(private todoItemService: TodoItemService) {}
@Post()
@Roles('owner', 'member')
@UseGuards(JwtAuthGuard, PageRolesGuard)
async createTodoItem(
@GetUser() user: User,
@GetTodo() todo: Todo,
@Body()
createTodoItemDto: CreateTodoItemDto,
) {
const todoItem = await this.todoItemService.createTodoItem(
todo,
user,
createTodoItemDto,
);
return parseTodoItemForOutput(todoItem);
}
@Get('/:todoItemId')
@Roles('owner', 'member')
@UseGuards(JwtAuthGuard, PageRolesGuard)
async getTodoItem(@GetTodoItem() todoItem: TodoItem) {
return parseTodoItemForOutput(todoItem);
}
@Get('/:todoItemId/public')
async getPublicTodoItem(
@GetPage() page: Page,
@GetTodoItem() todoItem: TodoItem,
) {
if (page.private) {
throw new ForbiddenException();
}
return parseTodoItemForOutput(todoItem);
}
@Patch('/:todoItemId/complete')
@Roles('owner', 'member')
@UseGuards(JwtAuthGuard, PageRolesGuard)
async toggleCompleteTodoItem(
@GetTodoItem() todoItem: TodoItem,
@GetUser() user: User,
@GetPage() page: Page,
) {
const responseTodoItem = await this.todoItemService.toggleCompleteTodoItem(
todoItem,
user,
page,
);
return parseTodoItemForOutput(responseTodoItem);
}
@Patch('/:todoItemId')
@Roles('owner', 'member')
@UseGuards(JwtAuthGuard, PageRolesGuard)
async updateTodoItem(
@GetTodoItem() todoItem: TodoItem,
@GetUser() user: User,
@GetPage() page: Page,
@Body() updateTodoItemDto: UpdateTodoItemDto,
) {
const responseTodoItem =
await this.todoItemService.updateTodoItemBasicInformation(
todoItem,
user,
page,
updateTodoItemDto,
);
return parseTodoItemForOutput(responseTodoItem);
}
@Delete('/:todoItemId')
@Roles('owner', 'member')
@UseGuards(JwtAuthGuard, PageRolesGuard)
async deleteTodoItem(
@GetTodoItem() todoItem: TodoItem,
@GetUser() user: User,
@GetPage() page: Page,
) {
return await this.todoItemService.deleteTodoItem(todoItem, user, page);
}
}
|
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PWA web2-lab5</title>
<link rel="manifest" href="./manifest.json" />
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
crossorigin="anonymous">
<link rel="stylesheet" href="./assets/site.css">
<link rel="icon" href="/assets/img/favicon.png" type="image/x-icon">
</head>
<body>
<nav class="navbar navbar-expand-lg">
<div class="collapse navbar-collapse d-flex align-items-center">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="index.html">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="404.html">404</a>
</li>
<li class="nav-item">
<a class="nav-link" href="offline.html">Offline</a>
</li>
<li class="nav-item">
<a class="nav-link" href="books">All books</a>
</li>
<li class="nav-item">
<a class="nav-link" href="add">Add your book</a>
</li>
</ul>
</div>
</nav>
<div class="w-100 d-flex align-items-center justify-content-center">
<h2> Web2-lab5 PWA</h3>
</div>
<div class="w-100 d-flex align-items-center justify-content-center">
<h3> Bookshelf app </h3>
</div>
<div class="w-100 d-flex align-items-center justify-content-center">
<img src="./assets/img/bookshelf.jpg" alt="Bookshelf logo" height="200" width="200"/>
</div>
<div>
<h2> Recommended books:</h2>
<h3> You can click on the images to get more information</h3>
</div>
<div id="books">
</div>
<script>
navigator.serviceWorker.register('./sw.js', {type : "module"})
.then(reg => console.log('SW registered!', reg))
.catch(err => console.error('Error registering service worker', err))
//Displaying books
function createImageDivs(bookName, bookData) {
const bookListContainer = document.getElementById("books")
const withoutPath = bookData.img.replace("/assets/img/", "")
const lastDotIndex = withoutPath.lastIndexOf('.') //dohvaca tocku za prepoznavanje ekstenzije
const newName = withoutPath.substring(0, lastDotIndex)
console.log("bez ekstenzije: " + newName)
const bookLink = document.createElement("a")
bookLink.href = "/books?name=" + newName
const bookImage = document.createElement("img")
bookImage.src = bookData.img
bookImage.alt = "Book Cover"
bookImage.classList.add("bookImg")
bookImage.height = 300
bookImage.width = 200
bookLink.appendChild(bookImage)
bookListContainer.appendChild(bookLink)
}
window.addEventListener("DOMContentLoaded", async () => {
try {
const response = await fetch("./books.json")
const booksData = await response.json()
console.log("books addign in indeks.html")
Object.keys(booksData).forEach(bookName => {
console.log("adding:" + bookName)
console.log(booksData[bookName])
createImageDivs(bookName, booksData[bookName])
})
} catch (error) {
console.error("Error fetching books data:", error)
}
})
</script>
</body>
</html>
|
import invariant from 'tiny-invariant';
import { BaseCurrency } from './base-currency';
import { Currency } from './currency';
import { Address } from 'viem';
import { checkValidAddress, validateAndParseAddress } from '../utils/validate-and-parse-address';
export interface SerializedToken {
chainId: number;
address: Address;
decimals: number;
symbol?: string;
name?: string;
}
/**
* Represents an ERC20 token with a unique address and some metadata.
*/
export class Token extends BaseCurrency {
public readonly isNative: false = false as const;
public readonly isToken: true = true as const;
/**
* The contract address on the chain on which this token lives
*/
public readonly address: Address;
public readonly projectLink?: string;
public constructor(chainId: number, address: Address, decimals: number, symbol?: string, name?: string, bypassChecksum?: boolean) {
super(chainId, decimals, symbol, name);
if (bypassChecksum) {
this.address = checkValidAddress(address);
} else {
this.address = validateAndParseAddress(address);
}
}
/**
* Returns true if the two tokens are equivalent, i.e. have the same chainId and address.
* @param other other token to compare
*/
public equals(other: Currency): boolean {
return other.isToken && this.chainId === other.chainId && this.address === other.address;
}
/**
* Returns true if the address of this token sorts before the address of the other token
* @param other other token to compare
* @throws if the tokens have the same address
* @throws if the tokens are on different chains
*/
public sortsBefore(other: Token): boolean {
invariant(this.chainId === other.chainId, 'CHAIN_IDS');
invariant(this.address !== other.address, 'ADDRESSES');
return this.address.toLowerCase() < other.address.toLowerCase();
}
/**
* Return this token, which does not need to be wrapped
*/
public get wrapped(): Token {
return this;
}
public get serialize(): SerializedToken {
return {
address: this.address,
chainId: this.chainId,
decimals: this.decimals,
symbol: this.symbol,
name: this.name,
};
}
}
|
import type { Metadata } from "next";
import { GeistSans } from "geist/font/sans";
import "./globals.css";
export const metadata: Metadata = {
metadataBase: new URL("https://ahmedshahlassicenter.vercel.app"),
title: "Ahmed Shah Lassi Center",
description:
"Tabdeeli ke Zaiqe, Shake ki Baat - Har Sip mein Chhupi Khushiyan!",
openGraph: {
title: "Ahmed Shah Lassi Center",
description:
"Tabdeeli ke Zaiqe, Shake ki Baat - Har Sip mein Chhupi Khushiyan!",
url: "https://ahmedshahlassicenter.vercel.app",
siteName: "Ahmed Shah Lassi Center",
locale: "en_US",
type: "website",
},
robots: {
index: true,
follow: true,
googleBot: {
index: true,
follow: true,
"max-video-preview": -1,
"max-image-preview": "large",
"max-snippet": -1,
},
},
twitter: {
title: "Ahmed Shah Lassi Center",
card: "summary_large_image",
},
verification: {
google: "zHB4gjR-LZ7okfLYgT9olSwGCyo9geeG3Ky4RUpnr1k",
yandex: "b76b50212a9d9960",
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en" className={`dark ${GeistSans.className}`}>
<body className="antialiased max-w-2xl mb-40 flex flex-col md:flex-row mx-4 mt-8 lg:mx-auto">
<main className="flex-auto min-w-0 mt-6 flex flex-col px-2 md:px-0">
{children}
</main>
</body>
</html>
);
}
|
#include "PicturaPCH.h"
#include "Console.h"
namespace Pictura
{
Mutex Console::m_ConsoleMutex;
bool Console::Initialized;
Console::Console()
{
}
Console::~Console()
{
}
bool Console::Init()
{
if (Initialized) { return true; }
#ifdef PLATFORM_WINDOWS
Initialized = CreateNewConsole(1024);
return Initialized;
#endif
}
void Console::Print(String Message, Console::ConsoleColor Color)
{
String code;
m_ConsoleMutex.lock();
#ifndef PLATFORM_WINDOWS //Unix system code (Use ANSI escape sequence)
switch (Color)
{
case Pictura::Console::ConsoleColor::Black:
code = "\033[0;30m";
break;
case Pictura::Console::ConsoleColor::Grey:
code = "\033[0;37m";
break;
case Pictura::Console::ConsoleColor::White:
code = "\033[1;37m";
break;
case Pictura::Console::ConsoleColor::Red:
code = "\033[1;31m";
break;
case Pictura::Console::ConsoleColor::DarkRed:
code = "\033[0;31m";
break;
case Pictura::Console::ConsoleColor::Green:
code = "\033[1;32m";
break;
case Pictura::Console::ConsoleColor::DarkGreen:
code = "\033[0;32m";
break;
case Pictura::Console::ConsoleColor::Yellow:
code = "\033[1;33m";
break;
case Pictura::Console::ConsoleColor::DarkYellow:
code = "\033[0;33m";
break;
case Pictura::Console::ConsoleColor::Blue:
code = "\033[1;34m";
break;
case Pictura::Console::ConsoleColor::DarkBlue:
code = "\033[0;34m";
break;
case Pictura::Console::ConsoleColor::Magenta:
code = "\033[1;35m";
break;
case Pictura::Console::ConsoleColor::DarkMagenta:
code = "\033[0;35m";
break;
case Pictura::Console::ConsoleColor::Cyan:
code = "\033[1;36m";
break;
case Pictura::Console::ConsoleColor::DarkCyan:
code = "\033[0;36m";
break;
default:
code = "\033[1;37m";
break;
}
std::cout << code + Message + "\033[0;21m" << std::endl;
#else //Windows NT system code (Use Console API)
const auto hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
const auto color = Types::ToUnderlying(Color);
FlushConsoleInputBuffer(hConsole);
SetConsoleTextAttribute(hConsole, color);
std::cout << Message << std::endl;
SetConsoleTextAttribute(hConsole, 7);
OutputDebugString(WideString(Message.begin(), Message.end()).c_str());
OutputDebugString(L"\n");
#endif
m_ConsoleMutex.unlock();
}
void Console::Pause(String PauseMessage)
{
Console::Print(PauseMessage);
std::cin.ignore();
}
}
|
import { createHash } from 'crypto';
/**
* Récupère les données de l'endpoint en utilisant les identifiants
* particuliers developer.marvels.com
* @param url l'end-point
* @return {Promise<json>}
*/
export const getData = async (url) => {
const publicKey = "561ece8f131e029a49cfc0bf7db1672e";
const privateKey = "ed0882e95add46617750f2da836dd287d855eb22";
const ts = Date.now();
const hash = await getHash(publicKey, privateKey, ts);
const apiUrl = `${url}?apikey=${publicKey}&ts=${ts}&hash=${hash}&offset=100`;
try {
const response = await fetch(apiUrl);
const datas = await response.json();
const resultsWithThumbnail = datas.data.results.filter(character =>
character.thumbnail && character.thumbnail.path !== "image_not_available"
);
const characters = resultsWithThumbnail.map(character => ({
name: character.name,
description: character.description,
thumbnail: character.thumbnail,
imageUrl: `${character.thumbnail.path}/portrait_xlarge.${character.thumbnail.extension}`
}));
return characters;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}
/**
* Calcul la valeur md5 dans l'ordre : timestamp+privateKey+publicKey
* cf documentation developer.marvels.com
* @param publicKey
* @param privateKey
* @param timestamp
* @return {Promise<ArrayBuffer>} en hexadecimal
*/
export const getHash = async (publicKey, privateKey, timestamp) => {
// exo 3
const hash = createHash('md5');
hash.update(timestamp + privateKey + publicKey);
return hash.digest('hex');
}
|
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Login } from '../Models/login';
import { Register } from '../Models/register';
import { Observable, throwError, Subject } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { environment } from 'src/environments/environment.development';
import { jwtAuth } from '../Models/jwtAuth';
import { FixedSizeVirtualScrollStrategy } from '@angular/cdk/scrolling';
import {of} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
registerUrl = "/AuthManagement/Register";
loginUrl = "/AuthManagement/Login";
weatherUrl = "/WeatherForecast";
constructor(private http: HttpClient) { }
public register(user: Register): Observable<jwtAuth> {
return this.http.post<jwtAuth>(`${environment.apiUrl}${this.registerUrl}`, user).pipe(catchError(this.errorHandler))
}
errorHandler(error: HttpErrorResponse) {
return throwError(() => new Error(error.error));
}
public login(user: Login): Observable<jwtAuth> {
return this.http.post<jwtAuth>(`${environment.apiUrl}${this.loginUrl}`, user).pipe(catchError(this.errorHandler))
}
public getWeather(): Observable<any> {
return this.http.get<any>(`${environment.apiUrl}${this.weatherUrl}`);
}
public isLoggedIn() {
const token = localStorage.getItem('jwtToken');
if (token) {
const payload = atob(token.split('.')[1]); // decode payload of token
const parsedPayload = JSON.parse(payload); // convert payload into an Object
return parsedPayload.exp > Date.now() / 1000; // check if token is expired
} else {
return false;
}
}
public getUserName(): Observable<string> {
const token = localStorage.getItem('jwtToken');
if (token) {
const payload = atob(token.split('.')[1]); // decode payload of token
const parsedPayload = JSON.parse(payload); // convert payload into an Object
const message = "Welcome, " + parsedPayload.name + "!";
this.eventStream.next(message);
return of(message);
//return message.asObservable();
} else {
return of("");
}
}
eventStream = new Subject<string>();
}
|
import ChatBody from "components/ChatBody";
import Contact from "components/Contact";
import Head from "next/head";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { getUserName, socket } from "socket";
import { User } from "types";
function Chatroom() {
if (!socket.user) return <h1>403 Forbidden</h1>;
const [user, setUser] = useState(socket.user.name);
const [avatars, setAvatars] = useState<User[]>([]);
const router = useRouter();
const updateOnlineUsers = () => {
fetch("http://localhost:8000/user/online").then(async (res) => {
let onlineUsers: number[] = await res.json();
setAvatars(await Promise.all(onlineUsers.map(getUserName)));
});
};
useEffect(() => {
updateOnlineUsers();
socket.on("userChange", (user: string) => setUser(user));
socket.on("newUser", (_: any) => {
updateOnlineUsers();
});
}, []);
useEffect(() => {
if (!socket.user.name) {
router.push("/");
}
}, [router]);
return (
<>
<Head>
<title>{`Chat of ${user}`}</title>
<meta name="chaterbox" content="chat app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<div className="text-white p-5 grid grid-rows-[repeat(12,1fr)] grid-cols-10 h-[100vh] gap-5">
<span className="text-[3rem] col-span-10 ">Hey there {user}!!</span>
<div className="w-full col-span-4 row-start-2 row-end-[13] mt-10 border border-white">
{avatars.map((user: User) => {
console.table(user);
if (!user) return;
let { id, name, avatar } = user;
return <Contact name={name} avatar_url={avatar} key={id} />;
})}
</div>
<ChatBody />
<br />
</div>
</>
);
}
export default Chatroom;
|
import getRandomId, { ID } from "src/utils/getRandomId";
export class WeightCollection {
_id: ID;
_weights: Weight[];
_goal: number;
_duration: Duration;
constructor(weights: Weight[] = [], id = getRandomId(), goal = 0, duration = { months: 0, weeks: 0, days: 0, hours: 0, minutes: 0, seconds: 0 }) {
this._id = id;
this._weights = weights;
this._goal = goal;
this._duration = duration;
}
static fromJSON(rawJSON: any) {
return new WeightCollection(
rawJSON._weights.map((rawWeight: any) => Weight.fromJSON(rawWeight)),
rawJSON._id,
rawJSON._goal,
rawJSON._duration
);
}
set weights(value: Weight[]) {
this._weights = value;
}
set goal(value: number) {
this._goal = value;
}
set duration(value: Duration) {
this._duration = value;
}
get id() {
return this._id;
}
get weights() {
return this._weights;
}
get goal() {
return this._goal;
}
get duration() {
return this._duration;
}
getCopy() {
return new WeightCollection([...this._weights], this._id, this._goal, this._duration);
}
getWeightById(searchId: ID) {
return this._weights.find(item => item._id === searchId);
}
getWeightByDate(date: Date) {
return this._weights.find(item => item.timestamp.toDateString() === date.toDateString());
}
}
export class Weight {
_id: ID;
_weightValue: number;
_timestamp: Date;
constructor(weight: number, timestamp = new Date(), id = getRandomId()) {
this._id = id;
this._timestamp = timestamp;
this._weightValue = weight;
}
static fromJSON(rawJSON: any) {
return new Weight(rawJSON._weightValue, new Date(rawJSON._timestamp), rawJSON._id);
}
get value() {
return this._weightValue;
}
get id() {
return this._id;
}
get timestamp() {
return this._timestamp;
}
getCopy(updatedWeightValue = this._weightValue) {
return new Weight(updatedWeightValue, this._timestamp, this._id);
}
}
interface Duration {
months: number;
weeks: number;
days: number;
hours: number;
minutes: number;
seconds: number;
}
|
<?php
use PHPUnit\Framework\TestCase;
use function PHPUnit\Framework\assertEquals;
class RegexTest extends TestCase
{
public function testRegexRoute(): void
{
$routePath = "/home/detail/{id}";
preg_match_all('/\{(.*?)\}/', $routePath, $match);
assertEquals($match[1], ['id']);
}
public function testRegexPath(): void
{
$path = "/home/detail/1";
preg_match('#^/home/detail/([a-zA-Z0-9])$#', $path, $match);
array_shift($match);
assertEquals($match[0], 1);
}
public function testRegexMain(): void
{
// $routePath = "/home/detail/{id}";
$routePath = '/home/detail/{id}/product/{productId}';
// $path = "/home/detail/1";
$path = "/home/detail/1/product/2";
if (preg_match_all('/\{(.*?)\}/', $routePath, $routePatternMatch)) {
// $routePath = preg_replace('/\{(.*?)\}/', $routePath, '#^/home/detail/([a-zA-Z0-9])$#');
$routePath = preg_replace('/\{(.*?)\}/', '([a-zA-Z0-9])', $routePath);
$routePath = '#' . $routePath . '$#';
if (preg_match_all($routePath, $path, $pathMatch)) {
array_shift($pathMatch);
assertEquals($pathMatch, [[1], [2]]);
}
}
}
}
|
#!/usr/bin/env -S deno run -A
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
import { $, Repo } from "./deps.ts";
import { Repos } from "./repos.ts";
const repos = await Repos.load();
const denoRepo = repos.get("deno");
const deno_ast = repos.getCrate("deno_ast");
const nonDenoRepos = repos.getRepos().filter((c) => c.name !== "deno");
// create a branch, commit, push for the non-deno repos
for (const repo of nonDenoRepos) {
if (!await repo.hasLocalChanges()) {
continue;
}
const currentBranch = await repo.gitCurrentBranch();
$.logStep("Analyzing", repo.name);
$.logLight("Branch:", currentBranch);
if (
confirm(
`Bump deps? (Note: do this after the dependency crates have PUBLISHED)`,
)
) {
await bumpDeps(repo);
for (const crate of repo.crates) {
await crate.cargoCheck();
}
if (
currentBranch === "main" &&
confirm(`Branch for ${repo.name}?`)
) {
await repo.gitBranch("deno_ast_" + deno_ast.version);
}
if (
await repo.hasLocalChanges() &&
confirm(`Commit and push for ${repo.name}?`)
) {
await repo.gitAdd();
await repo.gitCommit(`feat: upgrade deno_ast to ${deno_ast.version}`);
await repo.gitPush();
}
}
}
// now branch, commit, and push for the deno repo
$.logStep("Analyzing Deno");
const currentBranch = await denoRepo.gitCurrentBranch();
$.logLight("Branch:", currentBranch);
if (confirm(`Bump deps for deno?`)) {
await bumpDeps(denoRepo);
for (const crate of denoRepo.crates) {
await crate.cargoCheck();
}
if (
currentBranch === "main" &&
confirm(`Branch for deno?`)
) {
await denoRepo.gitBranch("deno_ast_" + deno_ast.version);
}
if (
await denoRepo.hasLocalChanges() && confirm(`Commit and push for deno?`)
) {
await denoRepo.gitAdd();
await denoRepo.gitCommit(
`chore: upgrade to deno_ast ${deno_ast.version}`,
);
await denoRepo.gitPush();
}
}
async function bumpDeps(repo: Repo) {
for (const crate of repo.crates) {
for (const depCrate of repos.getCrateLocalSourceCrates(crate)) {
await crate.revertLocalSource(depCrate);
const version = await depCrate.getLatestVersion();
if (version == null) {
throw new Error(`Did not find version for ${crate.name}`);
}
await crate.setDependencyVersion(depCrate.name, version);
}
}
}
|
#!/usr/bin/python3
"""
This class represents.
"""
class Square:
"""
This class represents.
"""
def __init__(self, size=0, position=(0, 0)):
"""
Initializes a new square with a given size and position.
"""
self.size = size
self.position = position
@property
def size(self):
return self.__size
@size.setter
def size(self, value):
if not isinstance(value, int):
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
@property
def position(self):
return self.__position
@position.setter
def position(self, value):
if (
not isinstance(value, tuple) or
len(value) != 2 or
not all(isinstance(i, int) for i in value) or
not all(i >= 0 for i in value)
):
raise TypeError("position must be a tuple of 2 positive integers")
self.__position = value
def area(self):
"""
Calculates and returns the area of the square.
"""
return self.size ** 2
def my_print(self):
"""
Prints a representation of the square.
"""
if self.size == 0:
print()
return
for i in range(self.position[1]):
print()
for i in range(self.size):
print(" " * self.position[0] + "#" * self.size)
def __str__(self):
"""
Returns a string representation of the square.
"""
output = ""
if self.size == 0:
return ""
for i in range(self.position[1]):
output += "\n"
for i in range(self.size):
output += " " * self.position[0] + "#" * self.size + "\n"
return output[:-1]
|
#Name: Robert King
#Prog Purpose: This program computes grades for students using a
# Python LIST of data in Python DICTIONARIES (as student records)
# Each student has 3 graded items: Homework, Midterm exam, and Final exam.
# Each item is worth 100 points.
# The student's final grade is the average of the three graded items.
import datetime
stu = []
student_file = "students.csv"
out_file = "stu_report.txt"
def main():
read_data_file()
calculate_grades()
create_report_file()
def read_data_file():
datafile = open(student_file,"r") #The "r" indicates this is a READ file
lines = datafile.readlines() #Read the entire file into a variable called lines
for i in lines:
stu.append(i.split(",")) #Split the data by commas and add each section to the list
datafile.close()
def calculate_grades():
global average, totA, totB, totC, totD, totF
totA = totB = totC = totD = totF = 0
gradestotal = 0
for i in range(len(stu)):
hw = int(stu[i][2]) # Last name is pos. 0, first name is pos. 1, so homework is pos. 2
midex = int(stu[i][3]) #Midterm exam is in position 3
stu[i][4] = stu[i][4][:-1] #Remove the \n from the final exam string (end of the input line)
finex = int(stu[i][4]) #Final exam is in position 4
sum_grades = hw + midex + finex
finalgr = sum_grades / 3
gradestotal += finalgr #Add the grade to the total for calculating the average
stu[i].append(finalgr)
if finalgr >= 90:
lettergrade = 'A'
totA += 1
elif finalgr >= 80:
lettergrade = 'B'
totB += 1
elif finalgr >= 70:
lettergrade = 'C'
totC += 1
elif finalgr >= 60:
lettergrade = 'D'
totD += 1
else:
lettergrade = 'F'
totF += 1
stu[i].append(lettergrade)
average = gradestotal / len(stu)
def create_report_file():
line = "\n*************************************************************"
repfile = open(out_file,"w")
repfile.write("\n****************** CSC 230 Grade Report ******************")
repfile.write("\nReport Date/Time :" + str(datetime.datetime.now()))
repfile.write("\nTotal number of students:" + str(len(stu)))
repfile.write("\nAverage student grade :" + format(average, '5,.2f'))
repfile.write("\nTotal number of A grades:" + str(totA))
repfile.write("\nTotal number of B grades:" + str(totB))
repfile.write("\nTotal number of C grades:" + str(totC))
repfile.write("\nTotal number of D grades:" + str(totD))
repfile.write("\nTotal number of F grades:" + str(totF))
repfile.write(line)
repfile.write("\nNAME HW\tMID\tFIN\tFINAL GRADE")
repfile.write(line)
for i in range(len(stu)):
sname = '{0:<18}'.format(stu[i][0]+', '+stu[i][1])
hw = str(stu[i][2])
midex = str(stu[i][3])
finex = str(stu[i][4])
fingrade = format(stu[i][5],'6,.2f')
repfile.write("\n"+ sname + "\t" + hw + "\t" + midex + "\t" +finex + "\t" + fingrade + " "+ stu[i][6])
repfile.write(line)
repfile.close()
print("Open this file to view the Grades Report: " + out_file)
main()
|
import React, { useCallback, useEffect, useState } from "react";
import { Button, Modal } from "react-bootstrap";
import { getFoodContract, acceptFoodContract } from "../../utils/foodshare";
const AcceptContract = ({ contractId, receiverId }) => {
const [contract, setContract] = useState({});
const { postId, donorId, agreedQuantity } = contract;
const [loading, setLoading] = useState(false);
const [show, setShow] = useState(false);
const [showLogistics, setShowLogistics] = useState(false);
const fetchContractsDetails = useCallback(async () => {
try {
setLoading(true);
await getFoodContract(contractId).then((res) => {
if (res.Ok) {
console.log("Contract details fetched:", res.Ok);
setContract(res.Ok);
} else if (res.Err) {
console.error("Error fetching contract:", res.Err);
// Optionally set an error state to display in the UI
}
});
setLoading(false);
} catch (error) {
console.error("Error fetching contract details:", error);
setLoading(false);
}
}, [contractId]);
const handleAcceptContract = async () => {
try {
setLoading(true);
const res = await acceptFoodContract(receiverId, contractId);
console.log("Accept contract response:", res);
setLoading(false);
console.log(res);
if (res.Err) {
alert(`Error: ${res.Err.Error}`); // Displaying error to the user
} else {
setShow(false); // Close modal on successful acceptance
setShowLogistics(true); // Show logistics modal on successful acceptance
alert("Contract accepted successfully!");
}
} catch (error) {
console.error(error);
setLoading(false);
alert("Failed to accept contract due to an unexpected error.");
}
};
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const handleLogisticsClose = () => setShowLogistics(false);
useEffect(() => {
fetchContractsDetails();
}, [contractId, fetchContractsDetails]);
return (
<>
<Button
variant="primary"
onClick={handleShow}
disabled={loading || contract.status?.Accepted}
>
View Contract
</Button>
<Modal show={show} onHide={handleClose}>
<Modal.Header closeButton>
<Modal.Title>Contract Details</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Post Id: {postId}</p>
<p>Donor Id: {donorId}</p>
<p>
Agreed Quantity:{" "}
{contract.agreedQuantity
? contract.agreedQuantity.toString()
: "N/A"}
</p>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleClose} disabled={loading}>
Close
</Button>
<Button
variant="primary"
onClick={handleAcceptContract}
disabled={loading || contract.status?.Accepted}
>
Accept Contract
</Button>
</Modal.Footer>
</Modal>
<Modal show={showLogistics} onHide={handleLogisticsClose}>
<Modal.Header closeButton>
<Modal.Title>Logistics Decision</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Do you need logistics for this contract?</p>
</Modal.Body>
<Modal.Footer>
<Button
variant="secondary"
onClick={handleLogisticsClose}
disabled={loading}
>
No
</Button>
<Button
variant="primary"
onClick={handleLogisticsClose}
disabled={loading}
>
Yes
</Button>
</Modal.Footer>
</Modal>
</>
);
};
export default AcceptContract;
|
import React, { memo } from 'react';
import { Switch, Route } from 'react-router-dom';
import { NotAuthGuard } from '../guards/NotAuthGuard/index';
import { SplitView } from '../../layouts/SplitView/index';
import { NotFoundPage } from '../../pages/NotFoundPage/index';
import { Signup } from '../../pages/auth/Signup/Loadable';
import { Login } from '../../pages/auth/Login/index';
import { StandaloneView } from '../../layouts/StandaloneView/index';
import { EmailVerification } from 'app/pages/auth/EmailVerification';
import { TwoAuthLogin } from '../../pages/auth/TwoAuthLogin/index';
import { ForgotPassword } from 'app/pages/auth/ForgotPassword';
import { ResetPassword } from 'app/pages/auth/ResetPassword';
import { SocialAccounts } from 'app/pages/auth/SocialAccounts';
import { MainView } from 'app/layouts/MainView';
import { useSelector } from 'react-redux';
import { authSelector } from '../../pages/auth/slice/selectors';
interface Props {}
export const AuthRoute = memo((props: Props) => {
// TODO: Make this come from the redux state once that is setup
const isAuthenticated = useSelector(authSelector) || false;
return (
<Switch>
<NotAuthGuard exact path="/auth/signup" isAuthenticated={isAuthenticated}>
<SplitView>
<Signup />
</SplitView>
</NotAuthGuard>
<NotAuthGuard exact path="/auth/login" isAuthenticated={isAuthenticated}>
<SplitView>
<Login />
</SplitView>
</NotAuthGuard>
<NotAuthGuard
exact
path="/auth/email-verification"
isAuthenticated={isAuthenticated}
>
<StandaloneView>
<EmailVerification />
</StandaloneView>
</NotAuthGuard>
<NotAuthGuard
exact
path="/auth/two-auth-login"
isAuthenticated={isAuthenticated}
>
<StandaloneView>
<TwoAuthLogin />
</StandaloneView>
</NotAuthGuard>
<NotAuthGuard
exact
path="/auth/forgot-password"
isAuthenticated={isAuthenticated}
>
<StandaloneView>
<ForgotPassword />
</StandaloneView>
</NotAuthGuard>
<NotAuthGuard
exact
path="/auth/reset-password"
isAuthenticated={isAuthenticated}
>
<StandaloneView>
<ResetPassword />
</StandaloneView>
</NotAuthGuard>
<NotAuthGuard
exact
path="/auth/socialacount"
isAuthenticated={isAuthenticated}
>
<MainView>
<SocialAccounts />
</MainView>
</NotAuthGuard>
<Route path="*" component={NotFoundPage} />
</Switch>
);
});
|
// Import required libraries
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
// Initialize Express app
const app = express();
const PORT = process.env.PORT || 3030;
// Connect to MongoDB database
mongoose.connect(' mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.1.5', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Define User schema
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 1,
maxlength: 50
},
avatar: {
type: String,
default: ''
},
email: {
type: String,
required: true,
unique: true,
match: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
},
password: {
type: String,
required: true
},
created_at: {
type: Date,
default: Date.now
}
});
// Create User model
const User = mongoose.model('User', userSchema);
// Middleware for parsing JSON body
app.use(express.json());
app.get("/", (req, res)=>{
res.send("Welcome to Bug Tracker")
})
// Route for registering a new user
app.post('/api/register', async (req, res) => {
try {
// Extract user details from request body
const { name, avatar, email, password } = req.body;
// Check if the email is already registered
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ error: 'Email already registered' });
}
// Hash the password
const hashedPassword = await bcrypt.hash(password, 10);
// Create a new user object
const newUser = new User({
name,
avatar,
email,
password: hashedPassword
});
// Save the user to the database
await newUser.save();
// Respond with success message
res.status(201).json({ message: 'User registered successfully' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Server error' });
}
});
// Route for logging in a user
app.post('/api/login', async (req, res) => {
try {
// Extract email and password from request body
const { email, password } = req.body;
// Find the user by email
const user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ error: 'Invalid email or password' });
}
// Compare the password with the hashed password in the database
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
return res.status(400).json({ error: 'Invalid email or password' });
}
// Create JWT token
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, {
expiresIn: '1h'
});
// Respond with token
res.status(200).json({ token });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Server error' });
}
});
passport.use(new GoogleStrategy({
clientID: 'your-google-client-id',
clientSecret: 'your-google-client-secret',
callbackURL: 'http://localhost:3000/auth/google/callback' // Replace with your callback URL
},
(accessToken, refreshToken, profile, done) => {
// This function is called when a user successfully authenticates via Google
// You can save the user to your database or perform other actions here
return done(null, profile);
}
));
// Route for Google OAuth callback
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
(req, res) => {
// Successful authentication, redirect or respond as needed
res.redirect('/');
}
);
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
|
class Solution:
"""
Can use a map to quickly switch the value that we are comparing to. Need to
check both for when starting with 1 and starting with 0.
Time: O(n)
Space: O(1)
"""
def minOperations(self, s: str) -> int:
mapp = {"1": "0", "0": "1"}
def changes(val):
count = 0
for i in range(len(s)):
if s[i] != val:
count += 1
val = mapp[val]
return count
return min(changes("0"), changes("1"))
|
import React from 'react'
import { shell } from 'electron'
import { getThemeInput, getThemePrimary } from '../../utils/index'
const { dialog } = require('electron').remote
const { app } = window.require('electron').remote
export class SettingsModal extends React.Component {
constructor (props) {
super(props)
this.state = {
show: props.show || false
}
}
latestVersion () {
let updateMessage = 'Latest Version'
let explain = ''
if (this.props.version[1] === 'nightly') { // Explains that nightly is beta release, otherwise it's a stable release
explain = 'beta'
} else {
explain = 'stable'
}
// Index 0 is version number, Index 1 is nightly or stable
if (this.props.version[0] > app.getVersion()) {
updateMessage = 'New '.concat(this.props.version[0], ' ', explain, ' release available!')
}
return <div>
You are using World of Addons {app.getVersion()} - {updateMessage}
<br />
<a href='#' onClick={() => shell.openExternal('https://github.com/WorldofAddons/worldofaddons/releases')}>Latest Release: {this.props.version[0]} {this.props.version[1]} ({explain})</a>
<br />
</div>
}
onToggleModal (e) {
this.setState({ show: !this.state.show })
if (this.state.show === false) { // Fetch config settings when opening modal
this.props.onSettings()
}
}
onModAddonDir () {
const { settings } = this.props
const path = dialog.showOpenDialog({ properties: ['openDirectory'], defaultPath: settings.addonDir })
if (path !== undefined) {
settings.addonDir = path[0]
this.props.onNewSettings(settings)
}
}
onModAddonRecordFile () {
const { settings } = this.props
const path = dialog.showOpenDialog({ properties: ['openFile'], filters: [{ name: '.json', extensions: ['json'] }], defaultPath: settings.addonRecordFile })
if (path !== undefined) {
settings.addonRecordFile = path[0]
this.props.onNewSettings(settings)
}
}
onToggleCheckUpdateOnStart () {
const { settings } = this.props
settings.checkUpdateOnStart = !settings.checkUpdateOnStart
this.props.onNewSettings(settings)
}
onToggleLight () {
const { settings } = this.props
if (settings.theme !== 'light') {
settings.theme = 'light'
this.props.onNewSettings(settings)
}
}
onToggleDark () {
const { settings } = this.props
if (settings.theme !== 'dark') {
settings.theme = 'dark'
this.props.onNewSettings(settings)
}
}
renderThemeSelection (theme) {
const { settings } = this.props
if (settings.theme === theme) {
return <i className='material-icons green-text'>done</i>
} else {
return <i />
}
}
renderToggleExplain () {
const { settings } = this.props
if (settings.checkUpdateOnStart === true) {
return <p>On launch, World of Addons will auto-check for addon updates.</p>
} else {
return <p>World of Addons will not auto-check for updates.</p>
}
}
renderSettingsBtn () {
return (
<button className='navBarItem waves-effect waves-green btn-small' onClick={this.onToggleModal.bind(this)}>
<i className='material-icons'>settings</i>
</button>
)
}
renderModal () {
const { settings } = this.props
const containerCss = getThemePrimary(this.props.theme)
const inputCss = getThemeInput(this.props.theme)
return (
<div className={`modal-content ${containerCss}`}>
<div className='row'>
<button className='btn-flat waves-effect waves-green red-text' onClick={this.onToggleModal.bind(this)}><b>Close</b></button>
</div>
<div className='row'>
<table>
<tbody>
<tr>
<td><b>Install Location</b><p className='small'>World of Warcraft addon directory.</p></td>
<td className='settingsRight'>
<button className={`pathButton ${inputCss}`} onClick={(e) => this.onModAddonDir(e)} >
{settings.addonDir}
</button>
</td>
</tr>
<tr>
<td><b>Record File</b><br /><p>Information about your addons (version, hosts, etc.) are saved here.</p></td>
<td className='settingsRight'>
<button className={`pathButton ${inputCss}`} onClick={(e) => this.onModAddonRecordFile(e)} >
{settings.addonRecordFile}
</button>
</td>
</tr>
<tr>
<td>
<b>Auto-Check Update</b>
<br />
{this.renderToggleExplain()}
</td>
<td className='settingsRight'>
<div className='switch settingsRight'>
<label>
Off
<input type='checkbox' checked={settings.checkUpdateOnStart} onChange={(e) => this.onToggleCheckUpdateOnStart(e)} />
<span className='lever' />
On
</label>
</div>
</td>
</tr>
<tr>
<td>
<b>Theme</b><br />
Light/Dark mode toggle
</td>
<td className='settingsRight'>
<div className='row'>
<div className='col s3'>
<button className='btn-floating btn-large waves-effect waves-teal grey lighten-5' onClick={(e) => this.onToggleLight(e)}>{this.renderThemeSelection('light')}</button>
</div>
<div className='col s2'>
<button className='btn-floating btn-large waves-effect waves-teal blue-grey darken-3' onClick={(e) => this.onToggleDark(e)}>{this.renderThemeSelection('dark')}</button>
</div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
{this.latestVersion()}
<div className='row'>
<button className='btn-small btn-margin waves-effect waves-teal' href='#' onClick={() => shell.openExternal('https://github.com/WorldofAddons/worldofaddons/releases')}>All Versions <i className='material-icons'>history</i></button>
<button className='btn-small btn-margin waves-effect waves-teal' href='#' onClick={() => shell.openExternal('https://github.com/WorldofAddons/')}>Github <i className='material-icons'>home</i></button>
<button className='btn-small btn-margin waves-effect waves-teal' href='#' onClick={() => shell.openExternal('https://github.com/WorldofAddons/worldofaddons/wiki')}>Help / Wiki <i className='material-icons'>help_outline</i></button>
</div>
</div>
)
}
render () {
return (
<div>
{this.renderSettingsBtn()}
{this.state.show ? this.renderModal() : null}
{this.state.show ? <div className='overlay' onClick={this.onToggleModal.bind(this)} /> : null}
</div>
)
}
}
|
import matrix as mx
def _bfs(maze, path=""):
for x, pos in enumerate(maze[0]):
print(f'{x, pos = }')
if pos == 'O':
start = x
break
else:
raise ValueError('coulf not find "O" in the first row')
def find_maze_start(maze, start_char='S'):
R, C = len(maze), len(maze[0])
start = (0, 0)
for r in range(R):
for c in range(C):
if maze[r][c] == 'S':
start = (r, c)
break
else:
continue # no break detected, ignore parent break
break # parent break
else:
return None # never found S, never break loop
return start
class ExitNotFoundException(Exception):
pass
def format_maze(maze, visited, visited_char='.', start_char='S'):
R, C = len(maze), len(maze[0])
top = bottom = f'+{"-".join("-" for _ in maze[0])}+'
updated_maze = [
[visited_char if visited[row][col] and maze[row][col] != start_char
else maze[row][col] for col in range(C)]
for row in range(R)
]
rows = [f'|{" ".join(map(str, row))}|' for row in updated_maze]
return [top] + rows + [bottom]
def print_status(maze, visited, coord, queue):
mx.display(format_maze(maze, visited))
print(f'{coord = }')
print(f'{queue = }')
input()
def valid_direction(new_row, new_col, maze, visited, obstacle_char) -> bool:
R, C = len(maze), len(maze[0])
return (
new_row >= 0 and new_row < R
and new_col >= 0 and new_col < C
and maze[new_row][new_col] != obstacle_char
and not visited[new_row][new_col]
)
def solve_maze(maze, exit_char='E', obstacle_char='#'):
from collections import deque
R, C = len(maze), len(maze[0])
LEFT, RIGHT, UP, DOWN = (0, -1), (0, 1), (-1, 0), (1, 0)
DIRECTIONS = (RIGHT, LEFT, DOWN, UP)
visited = [[False] * C for _ in range(R)]
start = find_maze_start(maze)
queue = deque()
queue.append((*start, 0)) # 0 = distance
while len(queue) != 0:
coord = queue.pop() # value from the right
row, col, dist = coord
visited[row][col] = True
print_status(maze, visited, coord, queue)
if maze[row][col] == exit_char:
return dist
for dir_row, dir_col in DIRECTIONS:
new_row, new_col = row + dir_row, col + dir_col
if not valid_direction(new_row, new_col, maze, visited, obstacle_char):
continue
else:
queue.appendleft((new_row, new_col, dist+1))
print(f'{queue = }')
raise ExitNotFoundException(f'could not find exit')
def main():
matrix = mx.load(filename='maze.txt', split=None)
bordered_matrix = mx.format_border(matrix, ' ')
mx.display(bordered_matrix)
print(solve_maze(matrix))
if __name__ == '__main__':
main()
|
const nodemailer = require('nodemailer')
const { google } = require('googleapis')
const OAuth2 = google.auth.OAuth2
const getTransporter = () => {
const oauth2Client = new OAuth2(
process.env.GMAIL_CLIENT_ID,
process.env.GMAIL_CLIENT_SECRET,
'https://developers.google.com/oauthplayground' // Redirect URL
)
oauth2Client.setCredentials({ refresh_token: process.env.GMAIL_REFRESH_TOKEN })
const accessToken = oauth2Client.getAccessToken()
return nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
type: 'OAuth2',
user: '[email protected]',
clientId: process.env.GMAIL_CLIENT_ID,
clientSecret: process.env.GMAIL_CLIENT_SECRET,
refreshToken: process.env.GMAIL_REFRESH_TOKEN,
accessToken: accessToken
}
})
}
const sendConfirmationEmail = async (firstName, lastName, email, confirmationToken) => {
const transporter = getTransporter()
const server_url = process.env.NODE_ENV === process.env.ENVIRONMENT_DEV
? process.env.URL_DEV
: process.env.URL_PROD
const info = await transporter.sendMail({
from: `"Find You" <${process.env.EMAIL_USER}>`,
to: email,
subject: `Please confirm your registration`,
text: `
Dear ${firstName} ${lastName},
Welcome to Find You!
Please confirm your registration by following the link below:
${server_url}/user/confirm/${confirmationToken}
Thank you for trusting us and we hope you find yourself on our website :)
Best regards,
The Find You team
`
})
}
const sendPasswordResetEmail = async (firstName, lastName, email, resetToken) => {
const transporter = getTransporter()
const server_url = process.env.NODE_ENV === process.env.ENVIRONMENT_DEV
? process.env.URL_DEV
: process.env.URL_PROD
const info = await transporter.sendMail({
from: `"Find You" <${process.env.EMAIL_USER}>`,
to: email,
subject: `Password reset request`,
text: `
Dear ${firstName ? firstName : ''} ${lastName ? lastName : ''} ${(!firstName && !lastName) ? 'User' : ''},
Someone has requested to reset the password of your account on ${server_url.split('//')[1]}.
If this was you, please follow the link below. It will take you to a secure page where you can reset your password. The page will expire in one hour.
${server_url}/user/password/reset/${resetToken}
Please ignore this message if the request was not made by you!
Hope you have a good day and you keep finding yourself on our website :)
Best regards,
The Find You team
`
})
}
const parsePurchaseHistory = (purchaseHistory) => {
const activeProductIds = new Set()
const archivedProductIds = new Set()
const purchaseInfo = []
for (const purchase of purchaseHistory) {
const productsInfo = []
for (const product of purchase.products) {
productsInfo.push({
price: product.price,
discountPrice: product.discountPrice,
quantity: product.quantity,
sizeName: product.sizeName,
productId: product.productId
})
if (product.isArchived) {
archivedProductIds.add(product.productId)
continue
}
activeProductIds.add(product.productId)
}
purchaseInfo.push({
products: productsInfo,
dateAdded: purchase.dateAdded
})
}
return {
activeProductIds: Array.from(activeProductIds),
archivedProductIds: Array.from(archivedProductIds),
purchaseInfo
}
}
const checkPurchaseAvailability = (cartItemsById, productsById) => {
const unavailablePurchases = []
for (const [productId, productItems] of Object.entries(cartItemsById)) {
const product = productsById[productId]
for (const [sizeName, customerQuantity] of productItems) {
const size = product && product.sizes.find(s => s.sizeName === sizeName)
if (!size) {
unavailablePurchases.push({ productId, sizeName, availableQuantity: 0 })
continue
}
const sizeAvailableQuantity = size.count
if (sizeAvailableQuantity < customerQuantity) {
unavailablePurchases.push({ productId, sizeName, availableQuantity: sizeAvailableQuantity })
}
}
}
return unavailablePurchases
}
module.exports = {
sendConfirmationEmail,
sendPasswordResetEmail,
parsePurchaseHistory,
checkPurchaseAvailability
}
|
class Team
#インスタンス変数の作成
attr_accessor :name, :win, :lose, :draw
def initialize(name, win, lose, draw)
self.name = name
self.win = win
self.lose = lose
self.draw = draw
end
#勝率の計算
def calc_win_rate
win_rate = self.win.to_f / (self.win.to_f + self.lose.to_f)
end
#勝率の表示
def show_team_result
puts "#{self.name}の2020年の成績は #{self.win}勝 #{self.lose}敗 #{self.draw}分、勝率は#{calc_win_rate}です。"
end
end
#インスタンス生成
Giants = Team.new("Giants",67,45,8)
Tigers = Team.new("Tigers",60,53,7)
Dragons= Team.new("Dragons",60,55,5)
BayStars = Team.new("Baystars",56,58,6)
Carp = Team.new("Carp",52,56,12)
Swallows = Team.new("Swallows",41,69,10)
#メソッドの呼び出し
Giants.show_team_result()
Tigers.show_team_result()
Dragons.show_team_result()
BayStars.show_team_result()
Carp.show_team_result()
Swallows.show_team_result()
|
<div class="container">
<h3>Angular2 Forms</h3>
<form novalidate autocomplete="off" #f="ngForm">
<div class="form-group">
<label for="empNo">Employee No.</label>
<input type="text" class="form-control" name="empNo" [(ngModel)]="empNo" required minlength="3">
</div>
<div class="form-group">
<label for="empName">Employee Name</label>
<input type="text" class="form-control" name="empName" [(ngModel)]="emp.empName" pattern="[0-9]+">
</div>
<div class="form-group">
<label for="designation">Designation</label>
<input type="text" class="form-control" name="designation" [(ngModel)]="emp.designation">
</div>
<div class="form-group">
<label for="">Gender</label>
<div class = "radio">
<label>
<input type = "radio" name = "gender" id = "male" value = "Male" checked [(ngModel)]="emp.gender"> Male
</label>
<label>
<input type = "radio" name = "gender" id = "female" value = "Female" [(ngModel)]="emp.gender"> Female
</label>
</div>
</div>
<button [disabled]="!f.valid" type="submit" class="btn btn-primary">Submit</button>
<br>
{{emp | json}}
</form>
{{f.value | json}}
</div>
|
package com.github.shepherdxie.jocker.executor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.shepherdxie.jocker.ResponseReader;
import com.github.shepherdxie.utils.FileUtil;
import com.github.shepherdxie.utils.HttpsUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Objects;
/**
* @author Shepherd Xie
* @since 2024/4/11
*/
public class HttpsClientDockerExecutor implements DockerExecutor {
private final SSLSocketFactory sslSocketFactory;
private final X509TrustManager x509TrustManager;
public HttpsClientDockerExecutor(String clientCertPath, String clientKeyPath, String caCertPath) throws IOException {
this.sslSocketFactory = HttpsUtils.getSslSocketFactory(clientCertPath, clientKeyPath, caCertPath);
this.x509TrustManager = HttpsUtils.getTrustManager();
}
public HttpsClientDockerExecutor(SSLSocketFactory sslSocketFactory, X509TrustManager x509TrustManager) {
this.sslSocketFactory = sslSocketFactory;
this.x509TrustManager = x509TrustManager;
}
@Override
public ExecutorResponse execute(ExecutorRequest request) {
return null;
}
public <T> T exec(Class<T> valueType) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
// Docker 守护进程的主机地址和端口
String dockerHost = MessageFormat.format(
"https://{0}:{1}",
FileUtil.getSecurityConfig("docker.host"),
FileUtil.getSecurityConfig("docker.port")
);
// 创建 OkHttpClient 对象
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(Objects.requireNonNull(sslSocketFactory), x509TrustManager)
.build();
// 构建请求
Request request = new Request.Builder()
.url(dockerHost + "/v1.44/info")
.build();
// 发送请求并获取响应
try (Response response = client.newCall(request).execute()) {
return ResponseReader.readValue(response, valueType);
}
}
}
|
package com.example.giphy.gif.data.local.storage
import androidx.paging.PagingSource
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Upsert
import com.example.giphy.gif.data.local.models.GifLocalModel
@Dao
interface GifsDao {
@Upsert
suspend fun upsertGifs(gifs: List<GifLocalModel>)
@Query("DELETE FROM GIFS")
suspend fun deleteGifs()
@Transaction
@Query("SELECT * FROM GIFS WHERE :searchQuery = GIF_SEARCH_QUERY ORDER BY GIF_OFFSET ASC, GIF_PAGE_INDEX ASC")
fun getGifsPagingSource(searchQuery: String): PagingSource<Int, GifLocalModel>
@Transaction
suspend fun insertRefreshPage(
gifs: List<GifLocalModel>,
replaceRemotePageKeys: suspend () -> Unit
) {
deleteGifs()
upsertGifs(gifs)
replaceRemotePageKeys()
}
@Transaction
suspend fun insertPage(
gifs: List<GifLocalModel>,
insertRemotePageKeys: suspend () -> Unit
) {
upsertGifs(gifs)
insertRemotePageKeys()
}
@Query("DELETE FROM GIFS WHERE GIF_ID = :id")
fun delete(id: String)
}
|
package ru.kozlovv.MyFirstTest1AppSpringBoot.hello;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
public class HelloController {
private List<String> dataArrayList;
private Map<String, String> dataHashMap;
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
@GetMapping("/update-array")
public void updateArrayList (@RequestParam(value = "word", defaultValue = "") String word) {
if (dataArrayList == null && word.equals("")) {
dataArrayList = new ArrayList<>();
} else {
if (dataArrayList != null) {
dataArrayList.add(word);
}
}
}
@GetMapping("/show-array")
public String showArrayList(){
if(dataArrayList != null) {
return String.format(dataArrayList.toString());
} else {
return "Список не создан";
}
}
@GetMapping("/update-map")
public void updateHashMap (@RequestParam(value = "data", defaultValue = "") String data) {
if (dataHashMap == null && data.equals("")) {
dataHashMap = new HashMap<>();
} else {
if (dataHashMap != null) {
dataHashMap.put(data + "KEY", data + "Value");
}
}
}
@GetMapping("/show-map")
public String showHashMap() {
if(dataHashMap != null) {
return String.format(dataHashMap.toString());
} else {
return "Таблица не создана";
}
}
@GetMapping("/show-all-length")
public String showAllLength() {
String arrLength;
String mapLength;
if(dataArrayList != null) {
arrLength = Integer.toString(dataArrayList.size());
} else {
arrLength = "Список не создан";
}
if (dataHashMap != null) {
mapLength = Integer.toString(dataHashMap.size());
} else {
mapLength = "Таблица не создана";
}
return "Количество элментов ArrayList: " + arrLength + " " +
"Количество элементов HashTable: " + mapLength;
}
}
|
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. 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
// OWNER 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.
// A sample program demonstrating using Google C++ testing framework.
//
// Author: [email protected] (Zhanyong Wan)
// This sample shows how to write a simple unit test for a function,
// using Google C++ testing framework.
//
// Writing a unit test using Google C++ testing framework is easy as 1-2-3:
// Step 1. Include necessary header files such that the stuff your
// test logic needs is declared.
//
// Don't forget gtest.h, which declares the testing framework.
#include <limits.h>
#include "gtest/gtest.h"
// Step 2. Use the TEST macro to define your tests.
//
// TEST has two parameters: the test case name and the test name.
// After using the macro, you should define your test logic between a
// pair of braces. You can use a bunch of macros to indicate the
// success or failure of a test. EXPECT_TRUE and EXPECT_EQ are
// examples of such macros. For a complete list, see gtest.h.
//
// <TechnicalDetails>
//
// In Google Test, tests are grouped into test cases. This is how we
// keep test code organized. You should put logically related tests
// into the same test case.
//
// The test case name and the test name should both be valid C++
// identifiers. And you should not use underscore (_) in the names.
//
// Google Test guarantees that each test you define is run exactly
// once, but it makes no guarantee on the order the tests are
// executed. Therefore, you should write your tests in such a way
// that their results don't depend on their order.
//
// </TechnicalDetails>
// Tests Factorial().
// Tests factorial of negative numbers.
// TEST(FactorialTest, Negative) {
// // This test is named "Negative", and belongs to the "FactorialTest"
// // test case.
// EXPECT_EQ(1, Factorial(-5));
// EXPECT_EQ(1, Factorial(-1));
// EXPECT_GT(Factorial(-10), 0);
// // <TechnicalDetails>
// //
// // EXPECT_EQ(expected, actual) is the same as
// //
// // EXPECT_TRUE((expected) == (actual))
// //
// // except that it will print both the expected value and the actual
// // value when the assertion fails. This is very helpful for
// // debugging. Therefore in this case EXPECT_EQ is preferred.
// //
// // On the other hand, EXPECT_TRUE accepts any Boolean expression,
// // and is thus more general.
// //
// // </TechnicalDetails>
// }
// Tests factorial of 0.
TEST(EssausTest, Zero) {
EXPECT_EQ(1, 1);
}
// // Tests factorial of positive numbers.
// TEST(FactorialTest, Positive) {
// EXPECT_EQ(1, Factorial(1));
// EXPECT_EQ(2, Factorial(2));
// EXPECT_EQ(6, Factorial(3));
// EXPECT_EQ(40320, Factorial(8));
// }
// // Tests IsPrime()
// // Tests negative input.
// TEST(IsPrimeTest, Negative) {
// // This test belongs to the IsPrimeTest test case.
// EXPECT_FALSE(IsPrime(-1));
// EXPECT_FALSE(IsPrime(-2));
// EXPECT_FALSE(IsPrime(INT_MIN));
// }
// // Tests some trivial cases.
// TEST(IsPrimeTest, Trivial) {
// EXPECT_FALSE(IsPrime(0));
// EXPECT_FALSE(IsPrime(1));
// EXPECT_TRUE(IsPrime(2));
// EXPECT_TRUE(IsPrime(3));
// }
// // Tests positive input.
// TEST(IsPrimeTest, Positive) {
// EXPECT_FALSE(IsPrime(4));
// EXPECT_TRUE(IsPrime(5));
// EXPECT_FALSE(IsPrime(6));
// EXPECT_TRUE(IsPrime(23));
// }
// Step 3. Call RUN_ALL_TESTS() in main().
//
// We do this by linking in src/gtest_main.cc file, which consists of
// a main() function which calls RUN_ALL_TESTS() for us.
//
// This runs all the tests you've defined, prints the result, and
// returns 0 if successful, or 1 otherwise.
//
// Did you notice that we didn't register the tests? The
// RUN_ALL_TESTS() macro magically knows about all the tests we
// defined. Isn't this convenient?
|
package lab5.client.commands;
import java.io.IOException;
import lab5.client.exceptions.IncorrectDataOfFileException;
import lab5.client.utility.AskMarine;
import lab5.client.utility.IOManager;
import lab5.client.utility.SpaceMarineCollection;
/**
* Command 'remove_lower'. Removes elements lower than user entered.
*/
public class RemoveLowerCommand extends Command {
private final SpaceMarineCollection spaceMarineCollection;
private final AskMarine asker;
private final IOManager ioManager;
public RemoveLowerCommand(SpaceMarineCollection spaceMarineCollection, AskMarine asker, IOManager ioManager) {
super("remove_lower {element}", "remove all items smaller than the specified one from the collection");
this.spaceMarineCollection = spaceMarineCollection;
this.asker = asker;
this.ioManager = ioManager;
}
/**
* Executes the command.
* @return Command exit status.
* @throws IOException When something with file went wrong.
* @throws IncorrectDataOfFileException When in file data isn't correct.
*/
@Override
public boolean run(String str) throws IOException, IncorrectDataOfFileException {
if (!str.isEmpty()) {
ioManager.printerr("Incorrect input. Right: '" + name + "'.");
return false;
}
Integer specifiedHealth = asker.askHealth();
Integer specifiedHeart = asker.askHeartCount();
if (spaceMarineCollection.removeIf(spMar ->
{
if (spMar.getHealth() < specifiedHealth) {
return true;
}
return (spMar.getHealth() == specifiedHealth) && (spMar.getHeartCount() < specifiedHeart);
})) {
ioManager.println("All items have been successfully deleted.");
} else {
ioManager.println("No element has been deleted.");
}
return true;
}
}
|
"use client";
import { getBalanceStats } from "@/actions/user/get";
import SkeletonWrapper from "@/components/SkeletonWrapper";
import { Card } from "@/components/ui/card";
import { dateToUTCDate, formatter } from "@/lib/constants";
import { cn } from "@/lib/utils";
import { TOverviewSchema } from "@/lib/zodSchema";
import { UserSettings } from "@prisma/client";
import { useQuery } from "@tanstack/react-query";
import { LucideIcon, TrendingDown, TrendingUp, Wallet } from "lucide-react";
import { useCallback } from "react";
import CountUp from "react-countup";
import { toast } from "sonner";
type Props = {
userSettings: UserSettings;
dateRange: TOverviewSchema;
};
const StatCards = ({ userSettings, dateRange }: Props) => {
const statsQuery = useQuery({
queryKey: ["overview", "stats", dateRange.from, dateRange.to],
queryFn: async () =>
await getBalanceStats({
from: dateToUTCDate(dateRange.from),
to: dateToUTCDate(dateRange.to),
}),
});
if (statsQuery.data && !statsQuery.data?.success)
toast.error(statsQuery.data?.message);
const statsData = statsQuery?.data?.data;
const income = statsData?.income || 0;
const expense = statsData?.expense || 0;
const balance = income - expense;
return (
<section className="relative flex w-full flex-wrap gap-2 md:flex-nowrap">
<StatCard
value={income}
title="Income"
icon={TrendingUp}
currency={userSettings.currency}
isLoading={statsQuery.isFetching}
iconClassName="text-emerald-500 bg-emerald-400/10"
/>
<StatCard
value={expense}
title="Expense"
icon={TrendingDown}
currency={userSettings.currency}
isLoading={statsQuery.isFetching}
iconClassName="text-rose-500 bg-rose-400/10"
/>
<StatCard
value={balance}
title="Balance"
icon={Wallet}
currency={userSettings.currency}
isLoading={statsQuery.isFetching}
iconClassName="text-violet-500 bg-violet-400/10"
/>
</section>
);
};
export default StatCards;
type StatCardProps = {
isLoading: boolean;
currency: string;
value: number;
title: string;
icon: LucideIcon;
iconClassName?: string;
};
const StatCard = ({
value,
currency,
title,
icon: Icon,
isLoading,
iconClassName,
}: StatCardProps) => {
const formattingFn = useCallback(
(value: number) => {
return formatter(currency).format(value);
},
[currency]
);
return (
<SkeletonWrapper isLoading={isLoading} className="flex-1 w-full">
<Card className="flex h-24 w-full items-center gap-3 p-4">
<Icon
className={cn("size-12 items-center rounded-lg p-2", iconClassName)}
/>
<div>
<p className="text-muted-foreground capitalize">{title}</p>
<CountUp
preserveValue
redraw={false}
end={value}
formattingFn={formattingFn}
decimals={2}
className="text-lg sm:text-xl md:text-2xl font-semibold"
/>
</div>
</Card>
</SkeletonWrapper>
);
};
|
import React, { useState, useEffect } from 'react';
const ApiDataExample = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
// Set loading state to true when starting the request
setLoading(true);
// Fetch data from the API
const response = await fetch('https://jsonplaceholder.typicode.com/todos');
// Check if the response is successful (status code in the range 200-299)
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const jsonData = await response.json(); // Parse the JSON data
// Update state with the fetched data
setData(jsonData);
setLoading(false); // Set loading state to false when the request is complete
} catch (error) {
// Handle errors
setError(error.message);
setLoading(false); // Set loading state to false when an error occurs
}
};
fetchData(); // Call the fetchData function
}, []);
return (
<div>
<h2>API Data Example</h2>
{loading && <p>Loading...</p>}
{error && <p>Error: {error}</p>}
{data.length > 0 && (
<ul>
{data.map((item) => (
<li key={item.id}>{item.title} {item.completed}</li>
))}
</ul>
)}
</div>
);
};
export default ApiDataExample;
|
//
// ViewController.swift
// AutoLayoutStarter
//
// Created by Derrick Park on 2019-04-17.
// Copyright © 2019 Derrick Park. All rights reserved.
//
import UIKit
// custom hex color
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
assert(red >= 0 && red <= 233, "Invalid red component")
assert(green >= 0 && green <= 62, "Invalid green component")
assert(blue >= 0 && blue <= 55, "Invalid blue component")
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)
}
convenience init(rgb: Int) {
self.init(
red: (rgb >> 16) & 0xE9,
green: (rgb >> 8) & 0x3E,
blue: rgb & 0x37
)
}
}
let ligthOrange = UIColor(rgb: 0xE93E37)
class ViewController: UIViewController {
let mainView: UIView = {
let main = UIView()
// important when setting contraints programmatically
main.translatesAutoresizingMaskIntoConstraints = false
main.backgroundColor = .green
return main
}()
let squareButton: UIButton = {
let butt = UIButton(type: .system)
butt.setTitle("Square", for: .normal)
butt.translatesAutoresizingMaskIntoConstraints = false
butt.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
butt.addTarget(self, action: #selector(squareTapped), for: .touchUpInside)
return butt
}()
let portraitButton: UIButton = {
let butt = UIButton(type: .system)
butt.setTitle("Portrait", for: .normal)
butt.translatesAutoresizingMaskIntoConstraints = false
butt.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
butt.addTarget(self, action: #selector(portraitTapped), for: .touchUpInside)
return butt
}()
let landScapeButton: UIButton = {
let butt = UIButton(type: .system)
butt.setTitle("Landscape", for: .normal)
butt.translatesAutoresizingMaskIntoConstraints = false
butt.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
butt.addTarget(self, action: #selector(landscapeTapped), for: .touchUpInside)
return butt
}()
var widthAnchor: NSLayoutConstraint?
var heightAnchor: NSLayoutConstraint?
// Assignment code
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(mainView)
setupLayout()
// purple box
let purpleBox = UIView()
purpleBox.backgroundColor = .purple
purpleBox.translatesAutoresizingMaskIntoConstraints = false
mainView.addSubview(purpleBox)
NSLayoutConstraint.activate([
// 1. bottom margin
purpleBox.bottomAnchor.constraint(equalTo: mainView.bottomAnchor, constant: -20),
// 2. right margin
purpleBox.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: -20),
// 3. height
purpleBox.heightAnchor.constraint(equalToConstant: 50),
// 4. width relative to the greenView's widt
purpleBox.widthAnchor.constraint(equalTo: mainView.widthAnchor, multiplier: 0.7)
])
// stack view for blue squares
let stackViewBlueSquare = UIView()
//stackViewBlueSquare.backgroundColor = .yellow
stackViewBlueSquare.translatesAutoresizingMaskIntoConstraints = false
mainView.addSubview(stackViewBlueSquare)
NSLayoutConstraint.activate([
// top margin
stackViewBlueSquare.topAnchor.constraint(equalTo: mainView.topAnchor, constant: 80),
// bottom margin
stackViewBlueSquare.bottomAnchor.constraint(equalTo: mainView.bottomAnchor, constant: -40),
// center x anchor
stackViewBlueSquare.centerXAnchor.constraint(equalTo: mainView.centerXAnchor),
// center y anchor
stackViewBlueSquare.centerYAnchor.constraint(equalTo: mainView.centerYAnchor),
// variable height
stackViewBlueSquare.heightAnchor.constraint(equalTo: mainView.heightAnchor, multiplier: 0.7),
// fixed width
stackViewBlueSquare.widthAnchor.constraint(equalToConstant: 50)
])
// top square box
let topBlueSquare = UIView()
topBlueSquare.backgroundColor = .blue
topBlueSquare.translatesAutoresizingMaskIntoConstraints = false
stackViewBlueSquare.addSubview(topBlueSquare)
NSLayoutConstraint.activate([
// top margin
topBlueSquare.topAnchor.constraint(equalTo: stackViewBlueSquare.topAnchor, constant: 0),
// left margin
topBlueSquare.leftAnchor.constraint(equalTo: stackViewBlueSquare.leftAnchor, constant: 0),
// fixed height
topBlueSquare.heightAnchor.constraint(equalToConstant: 50),
// variable width depending of container stack
topBlueSquare.widthAnchor.constraint(equalTo: stackViewBlueSquare.widthAnchor, multiplier: 1)
])
// bottom square box
let bottomBlueSquare = UIView()
bottomBlueSquare.backgroundColor = .blue
bottomBlueSquare.translatesAutoresizingMaskIntoConstraints = false
stackViewBlueSquare.addSubview(bottomBlueSquare)
NSLayoutConstraint.activate([
// bottom margin
bottomBlueSquare.bottomAnchor.constraint(equalTo: stackViewBlueSquare.bottomAnchor, constant: 0),
// left margin
bottomBlueSquare.leftAnchor.constraint(equalTo: stackViewBlueSquare.leftAnchor, constant: 0),
// fixed height
bottomBlueSquare.heightAnchor.constraint(equalToConstant: 50),
// variable width depending of container stack
bottomBlueSquare.widthAnchor.constraint(equalTo: stackViewBlueSquare.widthAnchor, multiplier: 1)
])
// middle square box
let middleBlueSquare = UIView()
middleBlueSquare.backgroundColor = .blue
middleBlueSquare.translatesAutoresizingMaskIntoConstraints = false
stackViewBlueSquare.addSubview(middleBlueSquare)
NSLayoutConstraint.activate([
// left margin
middleBlueSquare.leftAnchor.constraint(equalTo: stackViewBlueSquare.leftAnchor, constant: 0),
// center x anchor
middleBlueSquare.centerXAnchor.constraint(equalTo: stackViewBlueSquare.centerXAnchor),
// center y anchor
middleBlueSquare.centerYAnchor.constraint(equalTo: stackViewBlueSquare.centerYAnchor),
// fixed height
middleBlueSquare.heightAnchor.constraint(equalToConstant: 50),
// variable width depending of container stack
middleBlueSquare.widthAnchor.constraint(equalTo: stackViewBlueSquare.widthAnchor, multiplier: 1)
])
// orange top box
let orangeBox = UIView()
orangeBox.backgroundColor = ligthOrange
orangeBox.translatesAutoresizingMaskIntoConstraints = false
mainView.addSubview(orangeBox)
NSLayoutConstraint.activate([
// top margin
orangeBox.topAnchor.constraint(equalTo: mainView.topAnchor, constant: 20),
// right margin
orangeBox.rightAnchor.constraint(equalTo: mainView.rightAnchor, constant: -20),
// fixed height
orangeBox.heightAnchor.constraint(equalToConstant: 50),
// fixed width
orangeBox.widthAnchor.constraint(equalToConstant: 200),
])
// orange top inner box 1
let orangeBoxInnerLeft = UIView()
orangeBoxInnerLeft.backgroundColor = .orange
orangeBoxInnerLeft.translatesAutoresizingMaskIntoConstraints = false
orangeBox.addSubview(orangeBoxInnerLeft)
NSLayoutConstraint.activate([
// top margin
orangeBoxInnerLeft.topAnchor.constraint(equalTo: orangeBox.topAnchor, constant: 7),
// left margin
orangeBoxInnerLeft.leftAnchor.constraint(equalTo: orangeBox.leftAnchor, constant: 8),
// fixed height
orangeBoxInnerLeft.heightAnchor.constraint(equalToConstant: 35),
// fixed width
orangeBoxInnerLeft.widthAnchor.constraint(equalToConstant: 110),
])
// orange top inner box 2
let orangeBoxInnerRight = UIView()
orangeBoxInnerRight.backgroundColor = .orange
orangeBoxInnerRight.translatesAutoresizingMaskIntoConstraints = false
orangeBox.addSubview(orangeBoxInnerRight)
NSLayoutConstraint.activate([
// top margin
orangeBoxInnerRight.topAnchor.constraint(equalTo: orangeBox.topAnchor, constant: 7),
// right margin
orangeBoxInnerRight.rightAnchor.constraint(equalTo: orangeBox.rightAnchor, constant: -8),
// fixed height
orangeBoxInnerRight.heightAnchor.constraint(equalToConstant: 35),
// fixed width
orangeBoxInnerRight.widthAnchor.constraint(equalToConstant: 65),
])
}
fileprivate func setupLayout() {
mainView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
mainView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
widthAnchor = mainView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.7, constant: 0)
widthAnchor?.isActive = true
heightAnchor = mainView.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: 0.7, constant: 0)
heightAnchor?.isActive = true
let buttStackView = UIStackView(arrangedSubviews: [
squareButton, portraitButton, landScapeButton])
buttStackView.translatesAutoresizingMaskIntoConstraints = false
buttStackView.axis = .horizontal
buttStackView.alignment = .center
buttStackView.distribution = .fillEqually
view.addSubview(buttStackView)
NSLayoutConstraint.activate([
buttStackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -50),
buttStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
buttStackView.heightAnchor.constraint(equalToConstant: 50),
buttStackView.widthAnchor.constraint(equalTo: view.widthAnchor)
])
}
@objc private func squareTapped() {
view.layoutIfNeeded()
UIView.animate(withDuration: 2.0) {
self.widthAnchor?.isActive = false
self.widthAnchor? = self.mainView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.9)
self.widthAnchor?.isActive = true
self.heightAnchor?.isActive = false
self.heightAnchor? = self.mainView.heightAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.9)
self.heightAnchor?.isActive = true
self.view.layoutIfNeeded()
}
}
@objc private func portraitTapped() {
view.layoutIfNeeded()
UIView.animate(withDuration: 2.0) {
self.widthAnchor?.isActive = false
self.widthAnchor? = self.mainView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.7)
self.widthAnchor?.isActive = true
self.heightAnchor?.isActive = false
self.heightAnchor? = self.mainView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.7)
self.heightAnchor?.isActive = true
self.view.layoutIfNeeded()
}
}
@objc private func landscapeTapped() {
view.layoutIfNeeded()
UIView.animate(withDuration: 2.0) {
self.widthAnchor?.isActive = false
self.widthAnchor? = self.mainView.widthAnchor.constraint(equalTo: self.view.widthAnchor, multiplier: 0.95)
self.widthAnchor?.isActive = true
self.heightAnchor?.isActive = false
self.heightAnchor? = self.mainView.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 0.4)
self.heightAnchor?.isActive = true
self.view.layoutIfNeeded()
}
}
}
|
# Information
This is a simple blog project made with react.js php and mysql
Go to the bottom to see how to run manually [without docker](#without-docker)
# The repo is a monorepo containing front-end at the root and backend in the /backend folder
# To run the project
# * Check the line endings in /backend/db_migrate.sh file, it may cause container OS not being able to find migrate_db.php file (On Windows maybe, replace CRLF with LF)*
docker, docker compose plugin, node.js and npm must be installed, and docker engine must be started
# Step 1
add
```
MYSQL_DATABASE=blog
MYSQL_ROOT_PASSWORD=123456
MYSQL_HOST=mysql-dev
MYSQL_PASSWORD=123456
```
to `/backend/config/.env.dev` (You can use also MYSQL_USER with MYSQL_PASSWORD to change the DB user)
# Step 2
add
```
REACT_APP_API_URL="localhost:80"
REACT_APP_TOKEN_KEY="token"
```
to `/.env`
# Step 3
run
```
npm install
```
to install all node.js dependencies
# Step 4
run
```
npm start
```
to start the project
`npm start` will start all backend services (PHP/MySQL) with profile named 'dev' and with `/backend/config/.env.dev` file,
(there is also a profile named 'prod' but it is not configured yet), and after successfull launch of containers it will
serve react.js frontend app with webpack-dev-server
# API Container
docker compose will run the containers, as the API container depends on MySQL container
it waits for MySQL container status to become 'service_healthy'. This container will automatically run the migrations.
The source code is mapped to the `/app` folder of the container with a docker volume.
# MySQL Container
this is the first container that starts up as the API container depends on it, it will perform health check
and change status when MySQL is ready to accept connections. The MySQL data is
mapped to the `/backend/docker/mysql/data` folder of repository.
# Without Docker
Running project without docker involves several steps:
# Step 1
install php 7.4, composer, mysql 8.0, node.js and npm
# Step 2
configure server (Apache/ngiNX) to serve and rewrite any coming request to /backend/src/index.php file
# Step 3
run `composer install` in `/backend` folder to install all php dependencies
# Step 4
run `npm install` in `/` folder to install all node.js dependencies
# Step 5
the backend works with mysql through PDO interface so the appropriate driver must be installed and enabled in php.ini
# Step 6
check running the project in docker for setup of environment variables (configure the DB connection)
# Step 7
run migrate_db.php file in `/backend/src` folder to migrate the DB and create the tables
# Step 8
run `npm start` in `/` folder to start the project
# P.S.
Most part of development is done today, and most time went on configuration of docker and apache,
(it was not clear how to run migrations on container start up, then I figured it out).
I designed the app to be able to implement also the authentication part.
The backend is implemented but not fully tested yet,
also there are parts that are done in most straightforward way,
to save time, but they can be done better.
As the task required not to use any backend framework just some essential libraries, I've not used any migration
library, but I've implemented a migration file, which is running the migrations as RAW SQL queries.
Backend routing is implemented with Klein router, data validation is done with Respect/Validation library.
On frontend there is no any UI, there are several services and main components + redux store.
Front-end dependencies are installed by hand no create-react-app is used (now I'm wondering why? :)).
# The End
|
import React, { useState } from "react";
export const cartContext = React.createContext();
export const CartContextProvider = ({ children }) => {
const [totalAmount, setTotalAmount] = useState(0);
const [cartCount, setCartCount] = useState(0);
const [cartItems, setCartItems] = useState([]);
const [cartOpen, setCartOpen] = useState(false);
const openCart = () => {
setCartOpen(true);
};
const closeCart = () => {
setCartOpen(false);
};
return (
<cartContext.Provider
value={{
cartCount,
setCartCount,
cartItems,
setCartItems,
totalAmount,
setTotalAmount,
openCart,
closeCart,
cartOpen,
}}
>
{children}
</cartContext.Provider>
);
};
|
import React from 'react'
import Header from './components/header/Header'
import Nav from './components/nav/Nav'
import About from './components/about/About'
import Experience from './components/experience/Experience'
import Portfolio from './components/portfolio/Portfolio'
import Contact from './components/contact/Contact'
import Footer from './components/footer/Footer'
import { useContext} from "react";
import { themeContext } from './Context';
import Services from './components/services/Services'
const App = () => {
const theme = useContext(themeContext);
const darkMode = theme.state.darkMode;
return (
<div className='contain'
style={{
background: darkMode ? "black" : "",
color: darkMode ? "white" : "",
}}
>
<Header />
<Nav />
<About />
<Experience />
<Services/>
<Portfolio />
<Contact />
<Footer />
</div>
)
}
export default App
|
<?php
namespace ArtARTs36\MergeRequestLinter\Application\Rule\Rules;
use ArtARTs36\MergeRequestLinter\Application\Rule\Definition\Definition;
use ArtARTs36\MergeRequestLinter\Domain\Request\MergeRequest;
use ArtARTs36\MergeRequestLinter\Domain\Rule\RuleDefinition;
use ArtARTs36\MergeRequestLinter\Shared\Attributes\Description;
#[Description('Merge Request must have any {labels}.')]
final class HasAnyLabelsRule extends AbstractLabelsRule
{
public const NAME = '@mr-linter/has_any_labels';
protected function doLint(MergeRequest $request): bool
{
if ($this->labels->isEmpty()) {
return ! $request->labels->isEmpty();
}
return ! $this->labels->diff($request->labels)->equalsCount($this->labels);
}
public function getDefinition(): RuleDefinition
{
if ($this->labels->isEmpty()) {
return new Definition('Merge Request must have any labels');
}
return new Definition(sprintf(
'Merge Request must have any labels of: [%s]',
$this->labels->implode(', '),
));
}
}
|
package com.sist.main2;
class Common
{
int a=10;
int b=20;
public void display()
{
System.out.println("Common:display call...");
}
}
class Child extends Common //is-a
{
// a,b 들어와있음
public void display()
{
System.out.println("Child:display call...");
}
}
class Child2
{
// 상속없이 오버라이딩 => 익명의 클래스
Common c=new Common(); //a,b 상속안하고 클래스 갖고와서 생성해도 쓸수 있음 a,b=> has-a
public void display()
{
System.out.println("Child2:display call...");
}
}
public class MainClass2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Child c1=new Child();
System.out.println(c1.a);
System.out.println(c1.b);
c1.display();
Child2 c2=new Child2();
System.out.println(c2.c.a);
System.out.println(c2.c.b);
c2.c.display();
}
}
|
<!doctype html>
<html lang="en"
xmlns:th="http://thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
layout:decorate="~{page_layout/layout}">
<head>
<meta charset="UTF-8">
<title>Vehicles</title>
</head>
<body>
<div layout:fragment="main-content">
<div th:if="${ not#lists.isEmpty(vehicles)}">
<div>
<h5>User: <span sec:authentication="name"></span>, Vehicle list:</h5>
<hr>
</div>
<table class="table table-dark table-striped">
<thead>
<tr>
<th scope="col">License Plate</th>
<th scope="col">Brand</th>
<th scope="col">Model</th>
<th scope="col">Type</th>
<th scope="col">MOT</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="vehicle : ${vehicles}">
<td th:text="${vehicle.licensePlate}"></td>
<td th:text="${vehicle.brand}"></td>
<td th:text="${vehicle.model}"></td>
<td th:text="${vehicle.type}"></td>
<td th:text="${vehicle.mot == true ? 'Yes' : 'No'}"></td>
<td>
<button type="submit" th:id="${vehicle.licensePlate}"
name="deleteVehicle" class="btn btn-danger btn-sm"><i class="remove user icon"></i>Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
<div th:if="${#lists.isEmpty(vehicles)}">
<p>You don't have any vehicles.</p>
</div>
<div>
<a href="/vehicleform" class="btn btn-primary">Add Vehicle</a>
<a href="/transferform" class="btn btn-success" th:if="${ not#lists.isEmpty(vehicles)}">Make Transfer</a>
</div>
<script type="text/javascript">
$("[name='deleteVehicle']").click(function() {
var urlCall = "/vehicles/";
$.ajax({
url : urlCall + $(this).attr('id'),
type : 'DELETE',
success : function(result) {
console.log(result);
$(location).attr("href", value="/vehiclelist");
},
error : function(result) {
console.log(result);
},
});
});
</script>
</div>
</body>
</html>
|
package fr.esprit.usermanagement.controllers;
import fr.esprit.usermanagement.docx.DocService;
import fr.esprit.usermanagement.dtos.Role;
import fr.esprit.usermanagement.dtos.UserDto;
import fr.esprit.usermanagement.exceptions.EntityAlreadyExistException;
import fr.esprit.usermanagement.exceptions.EntityNotFoundException;
import fr.esprit.usermanagement.exceptions.ErrorOccurredException;
import fr.esprit.usermanagement.exceptions.InvalidEntityException;
import fr.esprit.usermanagement.services.IUserService;
import fr.esprit.usermanagement.utils.KeycloakConfig;
import lombok.RequiredArgsConstructor;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/admin/realms/analytix") // Changed the base path
@RequiredArgsConstructor
@CrossOrigin("*")
public class UserController {
private final IUserService userService;
@PostMapping("extract/{userId}")
public void getUserDoc(@PathVariable String userId) throws Exception {
DocService.createXml();
DocService.makeWord();
DocService.makePdfByXcode();
}
@GetMapping("/users/{userId}")
public ResponseEntity<UserDto> getUser(@PathVariable String userId){
return new ResponseEntity<>(userService.getUser(userId), HttpStatus.OK);
}
@GetMapping("/users") // Changed the path
public ResponseEntity<?> getAllUserSql() throws SQLException {
return userService.getAllUsers();
}
@PostMapping("/users/{userId}/reset-password/{password}") // Changed the path
public ResponseEntity<?> resetUserPassword(@PathVariable String userId, @PathVariable String password) {
return userService.resetUserPassword(userId, password);
}
@PostMapping("/token") // No change
public String getToken() {
return userService.getToken();
}
@PostMapping("/roles/{roleName}") // No change
public ResponseEntity<?> createRole(@PathVariable(value = "roleName") String roleName) throws EntityAlreadyExistException, EntityNotFoundException {
return userService.createRole(roleName);
}
@GetMapping("/roles/permissions") // No change
public ResponseEntity<?> getAllPermissions() {
return userService.getPermissions();
}
@PutMapping("/roles") // No change
public ResponseEntity<?> updateRole(@RequestBody Role role) throws EntityNotFoundException {
return userService.updateRole(role);
}
@DeleteMapping("/roles/{roleName}") // No change
public ResponseEntity<?> deleteRole(@PathVariable(value = "roleName") String roleName) throws InvalidEntityException, ErrorOccurredException {
return userService.deleteRole(roleName);
}
@DeleteMapping("/users/{userId}") // Changed the path
public ResponseEntity<?> deleteUser(@PathVariable(value = "userId") String userId) throws InvalidEntityException, ErrorOccurredException {
return userService.deleteUser(userId);
}
@PostMapping("/roles/assign-permissions") // Changed the path
public ResponseEntity<?> assignCompositeRolesForRole(@RequestBody Map<String, Object> requestBody) throws EntityNotFoundException {
String roleId = (String) requestBody.get("roleId");
List<String> rolesIds = (List<String>) requestBody.get("rolesIds");
return userService.assignCompositeRolesForRole(roleId, rolesIds);
}
@GetMapping("/roles") // No change
public ResponseEntity<?> getAllRoles() {
return userService.getAllRoles();
}
@PostMapping("/users/assign-roles") // Changed the path
public ResponseEntity<?> assignRolesToUser(@RequestBody Map<String, Object> requestBody) throws EntityNotFoundException {
String userId = (String) requestBody.get("userId");
List<String> roleIds = (List<String>) requestBody.get("roleIds");
return userService.assignRolesToUser(userId, roleIds);
}
@PostMapping("/users") // Changed the path
public ResponseEntity<?> createUser(@RequestBody UserDto user) throws EntityAlreadyExistException {
return userService.createUser(user);
}
@PutMapping("/users") // Changed the path
public ResponseEntity<?> updateUser(@RequestBody UserDto user) throws EntityAlreadyExistException {
return userService.editUser(user);
}
}
|
import * as React from 'react'
import {
IconButton,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TablePagination,
TableRow,
Tooltip
} from '@mui/material'
import { DeleteIcon, EditIcon } from '@/components/icon'
import { Article, Recruitment } from '@prisma/client'
import { FormUser, QueryParams, TArticleWithAuthor, TypeId } from '@/types'
import { useRouter } from 'next/router'
import { toast } from 'react-toastify'
import Link from 'next/link'
import { formatVND } from '@/utils/formatCurrency'
import { useControlPopup } from '@/components/hooks'
import { DialogConfirm } from '@/ui/molecules'
type Props = {
data: Recruitment[]
params: QueryParams<Recruitment>
setPage: React.Dispatch<React.SetStateAction<number>>
total: number
// handleOpen: () => void
handleDelete: (id: TypeId) => void
}
export default function TableRecruitment(props: Props) {
const { data = [], params, setPage, total, handleDelete } = props
console.log('data', data)
const numPage = params.page ? params.page - 1 : 0
const router = useRouter()
const { open, handleClose, handleOpen } = useControlPopup()
const [rowSelected, setRowSelected] = React.useState<Recruitment>()
const renderDetailsButton = (row: Recruitment) => {
const { id } = row
return (
<>
<IconButton
onClick={() => {
setRowSelected(row)
handleOpen()
}}
>
<Tooltip children={<DeleteIcon color='error' />} title={'Delete Recruitment'} />
</IconButton>
<IconButton>
<Link href={`/admin/recruitment/${id}`}>
<Tooltip children={<EditIcon />} title={'Edit Recruitment'} />
</Link>
</IconButton>
</>
)
}
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label='simple table'>
<TableHead>
<TableRow>
<TableCell> Id</TableCell>
<TableCell align='center'>Title</TableCell>
<TableCell align='center'>Min Salary</TableCell>
<TableCell align='center'>Max Salary</TableCell>
<TableCell align='center'>Amount</TableCell>
<TableCell align='center'>Action</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data.map((row) => (
<TableRow key={row.id} sx={{ '&:last-child td, &:last-child th': { border: 0 } }}>
<TableCell component='th' scope='row'>
{row.id}
</TableCell>
<TableCell align='center'>{row.title}</TableCell>
<TableCell align='center'>{formatVND(row.minSalary)}</TableCell>
<TableCell align='center'>{formatVND(row.maxSalary)}</TableCell>
<TableCell align='center'>{row.amount}</TableCell>
<TableCell align='center'>{renderDetailsButton(row)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<TablePagination
// rowsPerPageOptions={[10, 25, 100]}
component='div'
count={total}
rowsPerPage={params.limit || 5}
page={numPage}
onPageChange={(event, newPage) => {
if (newPage >= 0) {
setPage(newPage + 1)
}
}}
// onRowsPerPageChange={handleChangeRowsPerPage}
/>
<DialogConfirm
open={open}
onClose={handleClose}
onSubmit={() => handleDelete(rowSelected?.id as TypeId)}
title={'Xác nhận xoá'}
description={'Bạn có muốn xoá bài tuyển dụng này'}
/>
</TableContainer>
)
}
|
/*mymatrix.h*/
/*
AUTHOR: BRANDON KIM
PROGRAM OVERVIEW: This file allows users to access the mymatrix class
which allows them to do various functions similar to a matrix.
*/
/// Assignment details and provided code are created and
/// owned by Adam T Koehler, PhD - Copyright 2023.
/// University of Illinois Chicago - CS 251 Spring 2023
//
// mymatrix
//
// The mymatrix class provides a matrix (2D array) abstraction.
// The size can grow dynamically in both directions (rows and
// cols). Also, rows can be "jagged" --- i.e. rows can have
// different column sizes, and thus the matrix is not necessarily
// rectangular. All elements are initialized to the default value
// for the given type T. Example:
//
// mymatrix<int> M; // 4x4 matrix, initialized to 0
//
// M(0, 0) = 123;
// M(1, 1) = 456;
// M(2, 2) = 789;
// M(3, 3) = -99;
//
// M.growcols(1, 8); // increase # of cols in row 1 to 8
//
// for (int r = 0; r < M.numrows(); ++r)
// {
// for (int c = 0; c < M.numcols(r); ++c)
// cout << M(r, c) << " ";
// cout << endl;
// }
//
// Output:
// 123 0 0 0
// 0 456 0 0 0 0 0 0
// 0 0 789 0
// 0 0 0 -99
//
#pragma once
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;
template < typename T >
class mymatrix {
private: struct ROW {
T * Cols; // dynamic array of column elements
int NumCols; // total # of columns (0..NumCols-1)
};
ROW * Rows; // dynamic array of ROWs
int NumRows; // total # of rows (0..NumRows-1)
//
// getVerticalList:
//
// This function makes an array of elements from the column of index.
// Gets the columns array used for matrix multiplication
//
T * getVerticalList(int index,
const mymatrix < T > & other, int size1) {
T * verticalList = new T[size1];
for (int i = 0; i < size1; i++) {
verticalList[i] = other.Rows[i].Cols[index];
}
return verticalList;
}
//
// dotProduct:
//
// This function calculates the dot product of 2 lists, which
// multiplication corresponding elements and adds up the total of those products and returns that value;
//
T dotProduct(ROW Row1, T * list2, int size1) {
T sum = T {};
for (int i = 0; i < size1; i++) {
sum += Row1.Cols[i] * list2[i];
}
return sum;
}
public:
//
// default constructor:
//
// Called automatically by C++ to construct a 4x4 matrix. All
// elements are initialized to the default value of T.
//
mymatrix() {
Rows = new ROW[4]; // an array with 4 ROW structs:
NumRows = 4;
// initialize each row to have 4 columns:
for (int r = 0; r < NumRows; ++r) {
Rows[r].Cols = new T[4]; // an array with 4 elements of type T:
Rows[r].NumCols = 4;
// initialize the elements to their default value:
for (int c = 0; c < Rows[r].NumCols; ++c) {
Rows[r].Cols[c] = T {}; // default value for type T:
}
}
}
//
// parameterized constructor:
//
// Called automatically by C++ to construct a matrix with R rows,
// where each row has C columns. All elements are initialized to
// the default value of T.
//
mymatrix(int R, int C) {
if (R < 1)
throw invalid_argument("mymatrix::constructor: # of rows");
if (C < 1)
throw invalid_argument("mymatrix::constructor: # of cols");
//Throw error if user is trying to make 0x0 matrix or smaller.
Rows = new ROW[R];
NumRows = R;
for (int r = 0; r < NumRows; ++r) {
Rows[r].Cols = new T[C]; // an array with C elements of type T:
Rows[r].NumCols = C;
// initialize the elements to their default value:
for (int c = 0; c < Rows[r].NumCols; ++c) {
Rows[r].Cols[c] = T {}; // default value for type T:
}
}
}
//
// copy constructor:
//
// Called automatically by C++ to construct a matrix that contains a
// copy of an existing matrix. Example: this occurs when passing
// mymatrix as a parameter by value
//
// void somefunction(mymatrix<int> M2) <--- M2 is a copy:
// { ... }
//
mymatrix(const mymatrix < T > & other) {
Rows = new ROW[other.NumRows]; // an array with the same number of ROW structs as passed in
NumRows = (((other).NumRows));
for (int r = 0; r < other.NumRows; ++r) {
Rows[r].Cols = new T[((other).Rows[r].NumCols)];
Rows[r].NumCols = (((other).Rows[r].NumCols));
// initialize the elements to the same as other passed in
for (int c = 0; c < Rows[r].NumCols; ++c) {
Rows[r].Cols[c] = (other).Rows[r].Cols[c]; // values from other matrix
}
}
}
//
// numrows
//
// Returns the # of rows in the matrix. The indices for these rows
// are 0..numrows-1.
//
int numrows() const {
return NumRows;
}
//
// numcols
//
// Returns the # of columns in row r. The indices for these columns
// are 0..numcols-1. Note that the # of columns can be different
// row-by-row since "jagged" rows are supported --- matrices are not
// necessarily rectangular.
//
int numcols(int r) const {
if (r < 0 || r >= NumRows)
throw invalid_argument("mymatrix::numcols: row");
return Rows[r].NumCols;
}
//
// growcols
//
// Grows the # of columns in row r to at least C. If row r contains
// fewer than C columns, then columns are added; the existing elements
// are retained and new locations are initialized to the default value
// for T. If row r has C or more columns, then all existing columns
// are retained -- we never reduce the # of columns.
//
// Jagged rows are supported, i.e. different rows may have different
// column capacities -- matrices are not necessarily rectangular.
//
void growcols(int r, int C) {
if (r < 0 || r >= NumRows)
throw invalid_argument("mymatrix::growcols: row");
if (C < 1)
throw invalid_argument("mymatrix::growcols: columns");
if (Rows[r].NumCols < C) {
int previousCols = Rows[r].NumCols;
T * Cols1 = Rows[r].Cols;
Rows[r].Cols = new T[C]; //Making a new Cols array with the updated size.
Rows[r].NumCols = C;
//Then copy in the old values of the old Cols
for (int i = 0; i < C; i++) {
if (i < previousCols) {
Rows[r].Cols[i] = Cols1[i];
} else {
Rows[r].Cols[i] = T {}; //Default value for the rest of the elements
}
}
}
// else rows retained
}
//
// grow
//
// Grows the size of the matrix so that it contains at least R rows,
// and every row contains at least C columns.
//
// If the matrix contains fewer than R rows, then rows are added
// to the matrix; each new row will have C columns initialized to
// the default value of T. If R <= numrows(), then all existing
// rows are retained -- we never reduce the # of rows.
//
// If any row contains fewer than C columns, then columns are added
// to increase the # of columns to C; existing values are retained
// and additional columns are initialized to the default value of T.
// If C <= numcols(r) for any row r, then all existing columns are
// retained -- we never reduce the # of columns.
//
void grow(int R, int C) {
if (R < 1)
throw invalid_argument("mymatrix::grow: # of rows");
if (C < 1)
throw invalid_argument("mymatrix::grow: # of cols");
if (NumRows < R) {
//Make a new matrix here?
int numRows1 = NumRows;
ROW * Rows1 = Rows; //Has R rows, so more than the old.
Rows = new ROW[R];
NumRows = R;
int numCols1;
for (int r = 0; r < NumRows; ++r) {
if (r < numRows1) { //if the current row is within the number of rows, then the row gets same number of elements as old array.
numCols1 = Rows1[r].NumCols;
} else {
numCols1 = 1; //New rows created default to set with 1 element. Changed later with growCols throughout the list.
}
Rows[r].Cols = new T[numCols1]; // an array with 4 elements of type T:
Rows[r].NumCols = numCols1;
if (r < numRows1) { //Either copies old elements into the new one or initializes the new elements with default value
for (int c = 0; c < Rows[r].NumCols; ++c) {
Rows[r].Cols[c] = Rows1[r].Cols[c];
}
} else {
for (int c = 0; c < Rows[r].NumCols; ++c) {
Rows[r].Cols[c] = T {};
}
}
}
// Grow cols for each row.. Last step
for (int r = 0; r < NumRows; r++) {
if (Rows[r].NumCols < C) {
growcols(r, C);
}
}
} else { // Grow cols anyway for each row.. Last step, just doesn't add rows now
for (int r = 0; r < NumRows; r++) {
if (Rows[r].NumCols < C) {
growcols(r, C);
}
}
}
//else keep rows the same
}
//
// size
//
// Returns the total # of elements in the matrix.
//
int size() const {
int count1 = 0;
for (int r = 0; r < NumRows; ++r) {
for (int c = 0; c < Rows[r].NumCols; ++c) {
count1++;
}
}
return (count1);
}
//
// at
//
// Returns a reference to the element at location (r, c); this
// allows you to access the element or change it:
//
// M.at(r, c) = ...
// cout << M.at(r, c) << endl;
//
T & at(int r, int c) const {
if (r < 0 || r >= NumRows)
throw invalid_argument("mymatrix::at: row");
if (c < 0 || c >= Rows[r].NumCols)
throw invalid_argument("mymatrix::at: col");
return (Rows[r].Cols[c]);
}
//
// ()
//
// Returns a reference to the element at location (r, c); this
// allows you to access the element or change it:
//
// M(r, c) = ...
// cout << M(r, c) << endl;
//
T & operator()(int r, int c) const {
if (r < 0 || r >= NumRows)
throw invalid_argument("mymatrix::(): row");
if (c < 0 || c >= Rows[r].NumCols)
throw invalid_argument("mymatrix::(): col");
return (Rows[r].Cols[c]);
}
//
// scalar multiplication
//
// Multiplies every element of this matrix by the given scalar value,
// producing a new matrix that is returned. "This" matrix is not
// changed.
//
// Example: M2 = M1 * 2;
//
mymatrix < T > operator * (T scalar) {
mymatrix < T > result;
result.Rows = new ROW[NumRows]; // an array with same number of ROW structs:
// initialize each row to have same columns:
for (int r = 0; r < NumRows; ++r) {
result.Rows[r].Cols = new T[Rows[r].NumCols];
result.Rows[r].NumCols = Rows[r].NumCols;
// initialize the elements to the multiple times same elements
for (int c = 0; c < result.Rows[r].NumCols; ++c) {
result.Rows[r].Cols[c] = (scalar * (T(Rows[r].Cols[c])));
}
}
return result;
}
//
// matrix multiplication
//
// Performs matrix multiplication M1 * M2, where M1 is "this" matrix and
// M2 is the "other" matrix. This produces a new matrix, which is returned.
// "This" matrix is not changed, and neither is the "other" matrix.
//
// Example: M3 = M1 * M2;
//
// NOTE: M1 and M2 must be rectangular, if not an exception is thrown. In
// addition, the sizes of M1 and M2 must be compatible in the following sense:
// M1 must be of size RxN and M2 must be of size NxC. In this case, matrix
// multiplication can be performed, and the resulting matrix is of size RxC.
//
mymatrix < T > operator * (const mymatrix < T > & other) {
//Checking if this matrix has the same number of elements in each column throughout
int columnCounter = Rows[0].NumCols;
for (int i = 0; i < NumRows; i++) {
if (Rows[i].NumCols != columnCounter) {
throw runtime_error("mymatrix::*: this not rectangular");
break;
}
}
columnCounter = other.Rows[0].NumCols; //resetting counter to check other matrix
for (int i = 0; i < other.NumRows; i++) {
if (other.Rows[i].NumCols != columnCounter) {
throw runtime_error("mymatrix::*: other not rectangular");
break;
}
}
if (Rows[0].NumCols != other.NumRows) {
throw runtime_error("mymatrix::*: size mismatch");
}
int RowsOfResult = NumRows;
int ColsOfResult = other.Rows[0].NumCols;
//Result matrix will have size: RowsOfResult * ColsOfResult
mymatrix < T > result(RowsOfResult, ColsOfResult);
//Sizes match so we can multiply :
int sum = T {};
for (int r = 0; r < RowsOfResult; r++) {
for (int i = 0; i < ColsOfResult; i++) {
T * C = getVerticalList(i, other, other.NumRows); //Gets the column of elements
sum = dotProduct(Rows[r], C, other.NumRows); //Gets the dot product of 2 lists
result.at(r, i) = sum;
}
sum = T {};
}
return result;
}
//
// _output
//
// Outputs the contents of the matrix; for debugging purposes.
//
void _output() {
for (int r = 0; r < this -> NumRows; ++r) {
for (int c = 0; c < this -> Rows[r].NumCols; ++c) {
cout << this -> Rows[r].Cols[c] << " ";
}
cout << endl;
}
}
};
|
package com.example.introduction_kotlin.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.example.introduction_kotlin.R
import kotlinx.android.synthetic.main.fragment_question.*
/**
* A simple [Fragment] subclass.
* Use the [QuestionFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class QuestionFragment : Fragment() , View.OnClickListener{
lateinit var navController: NavController
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_question, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = Navigation.findNavController(view)
btn_question.setOnClickListener(this) // class 파일에서 구현한 onClick 을 도출
}
override fun onClick(v: View?) {
when(v?.id){
R.id.btn_question ->{
navController.navigate(R.id.action_questionFragment_to_selectionFragment)
}
}
}
}
|
import CalendarPicker from "react-native-calendar-picker";
import { config } from "./configs";
import { AntDesign } from "@expo/vector-icons";
import { ComponentProps, useState } from "react";
import { formatDate, getDay } from "date-fns";
interface DatePickerProps extends ComponentProps<typeof CalendarPicker> {
onChange: (date: Date) => void
}
const DatePicker = ({ onChange }: DatePickerProps) => {
const disabledDays = [0, 6] // sunday and saturday
return (
<CalendarPicker
onDateChange={onChange}
previousComponent={<AntDesign name="arrowleft" size={config.fontSizes.lg} color={config.colors.background} />}
nextComponent={<AntDesign name="arrowright" size={config.fontSizes.lg} color={config.colors.background} />}
dayLabelsWrapper={{ borderColor: config.colors.complementary_1 }}
selectedDayColor={config.colors.background}
selectedDayTextColor={config.colors.Primary}
disabledDates={date => disabledDays.includes(getDay(date))}
disabledDatesTextStyle={{
color: config.colors.complementary_1
}}
todayBackgroundColor={config.colors.Primary}
todayTextStyle={{
fontWeight: "bold",
}}
textStyle={{
fontSize: config.fontSizes.sm,
color: config.colors.background
}}
minDate={new Date()}
restrictMonthNavigation
selectYearTitle="Selecione o ano"
weekdays={["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"]}
months={[
"Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro"
]}
/>
);
};
export default DatePicker;
|
SELECT * FROM EMP ORDER BY DEPTNO, SAL;
SELECT * FROM EMP WHERE ENAME = 'MILLER';
SELECT * FROM EMP WHERE ENAME LIKE '_I%';
SELECT * FROM EMP WHERE UPPER(ENAME) LIKE2 '%R';
-- 1981년 이후 입사자 검색
SELECT * FROM EMP WHERE EXTRACT(YEAR FROM HIREDATE) >= 1981;
SELECT * FROM EMP WHERE DEPTNO != 20;
SELECT * FROM EMP WHERE REGEXP_LIKE(ENAME, '^.+?TT$', 'i');
SELECT COMM, NVL2(COMM, COMM, -9999) FROM EMP;
--각 부서별로 그룹화, 부서원의 최대 급여가 3000 이하인 부서의 SAL의 총합
--JOB이 CLERK인 직원들에 대해서 각 부서별로 그룹화, 부서원의 최소 급여가 1000 이하인 부서에서 직원들의 급여 총합
-- 부서번호 오름차순 정렬
SELECT DEPTNO, SUM(SAL) FROM EMP GROUP BY DEPTNO HAVING MAX(SAL) <= 3000
ORDER BY DEPTNO ASC;
SELECT
UPPER('Apple KOREA'),
LOWER('Apple KOREA'),
INITCAP('Apple KOREA')
FROM DUAL;
-- 사원이름에서 두번째와 세번째 글자만 추출해라.
SELECT SUBSTR(ENAME, 2, 2), ENAME FROM EMP;
--급여 1500 이상인 사원의 급여를 15% 인상한 금액, 단 소수점 이하는 버린다.
SELECT ENAME, JOB, SAL, FLOOR(SAL * 1.15) FROM EMP WHERE SAL >= 1500;
SELECT ENAME, JOB, SAL, TRUNC(SAL * 1.15, -1) FROM EMP WHERE SAL >= 1500;
--급여가 1500 이상인 직원들에 대해서 부서별로 그룹화
--부서원의 최소 급여가 1000 이상, 최대 급여가 5000 이하인 부서에서 직원들의 평균 급여
--부서로 내림차순 정렬
SELECT DEPTNO, ROUND(AVG(SAL), 2) FROM EMP WHERE SAL >= 1500
GROUP BY DEPTNO
HAVING MIN(SAL) >= 1000 AND MAX(SAL) <= 5000
ORDER BY DEPTNO DESC;
-- JOIN 세가지 방법
SELECT * FROM EMP;
SELECT * FROM DEPT;
SELECT * FROM EMP A, DEPT B
WHERE A.DEPTNO = B.DEPTNO; -- EQUI-JOIN
SELECT * FROM EMP A JOIN DEPT B
ON A.DEPTNO = B.DEPTNO;
SELECT * FROM EMP A INNER JOIN DEPT B
ON A.DEPTNO = B.DEPTNO;
SELECT * FROM EMP A JOIN DEPT B
USING (DEPTNO);
--사원의 사원번호, 이름, 근무부서를 가져온다.
SELECT A.EMPNO 사원번호, A.ENAME 사원이름, B.DNAME 근무부서
FROM EMP A JOIN DEPT B
ON A.DEPTNO = B.DEPTNO;
--시카고에 근무하는 사원들의 사원번호,이름, 직무를 FETCH
SELECT A.EMPNO 사원번호, A.ENAME 사원이름, A.JOB 직무, B.LOC 근무지
FROM EMP A JOIN DEPT B USING (DEPTNO)
WHERE B.LOC = 'CHICAGO';
-- SALGRADE 테이블의 연봉 범위별 등급을 사원들에게 적용시켜라.
SELECT A.EMPNO, A.ENAME, A.JOB, A.SAL, B.GRADE, B.LOSAL, B.HISAL
FROM EMP A JOIN SALGRADE B
ON A.SAL BETWEEN B.LOSAL AND B.HISAL;
-- 급여등급이 4등급인 사원들의 사원번호, 이름, 급여, 부서이름, 근무지역 FETCH
SELECT A.EMPNO, A.ENAME, A.SAL, B.GRADE, C.DNAME, C.LOC
FROM EMP A, SALGRADE B, DEPT C
WHERE A.SAL BETWEEN B.LOSAL AND B.HISAL
AND A.DEPTNO = C.DEPTNO
AND B.GRADE = 4;
-- 각 급여 등급별 // 급여 총합과 평균, 사원 수, 최대 급여, 최소 급여 FETCH
SELECT
SUM(A.SAL) AS 등급급여총합,
ROUND(AVG(A.SAL), 0) AS 등급급여평균,
COUNT(*) AS 사원수,
MAX(A.SAL) AS 등급군최대급여,
MIN(A.SAL) AS 등급군최소급여
FROM EMP A JOIN SALGRADE B
ON A.SAL BETWEEN B.LOSAL AND B.HISAL
GROUP BY B.GRADE;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>DOM Learning</title>
<style>
.bg-black {
background-color: #212121;
color: #fff;
}
</style>
</head>
<body class="bg-black">
<div>
<h1 id="h1" class="heading1">
DOM learning with the help of chai aur code channel
<span style="display: none;">Span text</span>
</h1>
<h1 id="h2" class="heading2">
Testing heading two
</h1>
<h1 id="h3" class="heading3">
testing heading three
</h1>
<p>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Pariatur,
accusamus.
</p>
<input type="password" name="password" id="" aria-label="password" placeholder="password"/>
<ul>
<li class="list-item">1</li>
<li class="list-item">2</li>
<li class="list-item">3</li>
<li class="list-item">4</li>
<li class="list-item">5</li>
</ul>
</div>
<script>
const title = document.getElementById("h1");
console.log(title);
console.log(title.textContent) // return all the text either display or not
console.log(title.innerText) // return only visible text
console.log(title.innerHTML) // return all the html inside that tag
// querySelector....
let tag = document.querySelector("h1");
console.log("Element selected by html tag : ",tag); // return only first tag
tag = document.querySelector("#h2"); // element select by id
console.log("Element selected by id: ",tag);
tag = document.querySelector(".heading3"); // element select by id
console.log("Element selected by classname: ",tag);
tag = document.querySelector("input[type=password]"); // element select by tag with some attribute
console.log("Element selected by tag with attribute: ",tag);
let tempList = document.querySelectorAll('li'); // return ...node list... not array we can use foreach but not map
console.log(tempList);
// apply some styling on tempList
// tempList.style.backgroundColor = 'green' // return error
tempList[0].style.backgroundColor = 'green'
// tempList.forEach((item)=>{
// item.innerText = 'NodeList : 5'
// })
tempList = document.getElementsByClassName("list-item") // return HTML Collection not nodelist or array
console.log(tempList);
// now the tampList is HTMLCollection so foreach also not work...
// tempList.forEach((item)=>{
// item.innerText = 5
// }) // return error
// now we going to change HTML/NodeLIst to array
const tempListArray = Array.from(tempList);
console.log(tempListArray);
// tempListArray.style.title = "Unordered List" // generates error
tempListArray.forEach((item)=>{
item.innerText = `tempListArray `+5
item.style.backgroundColor = 'gray'
item.style.padding = '5px'
item.style.fontSize = "large"
item.style.borderRadius = "30px"
item.style.textAlign = "center"
item.style.marginBottom = "10px"
})
</script>
</body>
</html>
|
<template>
<div class="hy-form">
<div class="header">
<slot name="header"></slot>
</div>
<el-form :label-width="labelWidth">
<el-row :gutter="10">
<template v-for="item in formItems" :key="item.label">
<el-col v-bind="colLayout">
<el-form-item
:label="item.label"
:rules="item.rules"
:style="itemStyle"
>
<template
v-if="item.type === 'input' || item.type === 'password'"
>
<el-input
:placeholder="item.placeholder"
:show-password="item.type === 'password'"
v-bind="item.otherOptions"
:model-value="modelValue[`${item.field}`]"
@update:modelValue="handleValueChange($event, item.field)"
></el-input>
</template>
<template v-else-if="item.type === 'select'">
<el-select
style="width: 100%"
:placeholder="item.placeholder"
v-bind="item.otherOptions"
:model-value="modelValue[`${item.field}`]"
@update:modelValue="handleValueChange($event, item.field)"
>
<el-option
v-for="option in item.options"
:key="option.value"
:label="option.label"
:value="option.value"
>
</el-option>
</el-select>
</template>
<template v-else-if="item.type === 'datepicker'">
<el-date-picker
v-bind="item.otherOptions"
:model-value="modelValue[`${item.field}`]"
@update:modelValue="handleValueChange($event, item.field)"
></el-date-picker>
</template>
</el-form-item>
</el-col>
</template>
</el-row>
</el-form>
<div class="footer">
<slot name="footer"></slot>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, PropType, ref, watch } from 'vue'
import { IFormItem } from '../types'
export default defineComponent({
props: {
modelValue: {
type: Object,
default: () => ({})
},
formItems: {
type: Array as PropType<IFormItem[]>,
default: () => []
},
labelWidth: {
type: String,
default: '100px'
},
itemStyle: {
type: Object,
default: () => ({ padding: '10px 30px' })
},
colLayout: {
type: Object,
default: () => ({
xl: 6,
lg: 8,
md: 12,
sm: 24,
xs: 24
})
}
},
emits: ['update:modelValue'],
setup(props, { emit }) {
// const formData = ref({ ...props.modelValue })
// watch(
// formData,
// (newValue) => {
// emit('update:modelValue', newValue)
// },
// { deep: true }
// )
const handleValueChange = (value: any, field: string) => {
emit('update:modelValue', { ...props.modelValue, [field]: value })
}
return {
handleValueChange
}
}
})
</script>
<style lang="less" scoped>
.hy-form {
padding-top: 22px;
}
</style>
|
# Potřeby
## Definice
Je to pocit nedostatku, který je potřeba odstranit.
- Hmotné
- Auto
- Dům
- Mobil
- Nehmotné
- Znalost cizích jazyků
- Přátelství
- Statky
- Slouží k uspokojování hmotných potřeby
- Dělení podle hmotnosti
- Hmotné
- Nehmotné
- Dělení podle spotřeby
- Spotřební
- Slouží k přímě spotřebě (v domácnosti - rohlíky, mouka)
- Kapitál
- Slouží jako surovina pro další výroba (ve firmě)
- Dělení podle původu
- Volné
- Vzduch, voda... - volně k dispozici
- Ekonomické
- Vyroben člověkem
- Dělení podle poplatku
- Veřejné
- WC, lavičky v parku, park, osvětlení, chodník
- Soukromé
- Někomu to patří (ne stát)
- něčí dvůr, placený WC atd
- Služby
- Slouží k uspokojování nehmotných potřeb
- Dělení
- Osobní
- Pečují o osoby (fitness, kadeřník etc)
- Věcné
- Pečují o věci (autoservis)
1. Učebnice EKO - Hmotné potřeby, Statky - hmotné, ekonomické, soukromé
2. mobil - Hmotné potřeby, Statky - hmotné, ekonomické, soukromé
3. Jít s kamarády na fotbal - nehmotné potřeby
4. kadeřník - nehmotné potřeby, služby - osobní
5. borůvky v lese - hmotné potřeby, volné, veřejné
6. lampy u silnice - hmotné, ekonomické, veřejné
# 3 základní ekonomické subjekty
- Firma
- Nabízí domácnostem práci
- Domácnosti
- Stát
- Nabízí firmám práci
- Školství, zdravotnictví etc pro domácnosti
# 3 základní ekonomické otázky
1. Co... (vyrábět)
2. Jak... (vyrábět - náklady, jaké výrobní prostředky využiji)
3. Pro koho...
## Zvykový systém
Vychází z tradice. Středověk.
1. Co -
2. Jak -
3. Pro koho -
## Příkazový systém
1. Co - Podle toho, co nám řeknou
2. Jak - podle toho, co nám řeknou
3. Pro koho - pro toho, koho nám řeknou
## Tržní systém
Kapitalismus.
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">
<link href="" rel="stylesheet">
<script type="text/javascript" src="lib/vue.js"></script>
<style>
.left-enter-active {
animation: left 1.5s;
}
.left-leave-active {
animation: left 1.5s reverse;
}
@keyframes left {
0% {
opacity: 0;
transform: translateX(-100%);
}
100% {
opacity: 1;
transform: translateX(0px);
}
}
.right-enter-active {
animation: right 1.5s;
}
.right-leave-active {
animation: right 1.5s reverse;
}
@keyframes right {
0% {
opacity: 0;
transform: translateX(100%);
}
100% {
opacity: 1;
transform: translateX(0px);
}
}
</style>
</head>
<body>
<div id="box">
<navbar @myevent="myEvent"></navbar>
<sidebar v-show="isShow" direction="right"></sidebar>
</div>
<script>
Vue.component("navbar", {
template: `
<div style="background-color: yellow;">
导航栏 --<button @click="handleClick">click</button>
</div>
`,
methods: {
handleClick() {
this.$emit("myevent")
}
},
})
Vue.component("sidebar", {
props: ["direction"],
template: `
<transition appear :name="direction">
<div style="background-color: blue;width:200px;" >
<ul>
<li>好友</li>
<li>设置</li>
<li>退出</li>
</ul>
</div>
</transition>
`
})
var vm = new Vue({
el: "#box",
data: {
isShow: false,
},
methods: {
myEvent() {
this.isShow = !this.isShow
}
}
})
</script>
</body>
</html>
|
import {
mkdir,
readdir,
stat,
copyFile,
writeFile,
readFile,
} from "fs/promises";
import { join, extname } from "path";
const sourceDir = "./src/locales";
const destDir = "./dist/locales";
// Function to minify JSON content
function minifyJSON(content) {
return JSON.stringify(JSON.parse(content));
}
// Function to recursively copy directories
async function copyDirAsync(src, dest) {
try {
await mkdir(dest, { recursive: true });
const files = await readdir(src);
await Promise.all(
files.map(async (file) => {
const srcPath = join(src, file);
const destPath = join(dest, file);
const fileStat = await stat(srcPath);
if (fileStat.isDirectory()) {
// Recursively copy subdirectories
await copyDirAsync(srcPath, destPath);
} else {
// Check if it's a JSON file
if (extname(file) === ".json") {
// Read JSON content
const content = await readFile(srcPath, "utf-8");
// Minify JSON content
const minifiedContent = minifyJSON(content);
// Write minified JSON to destination
await writeFile(destPath, minifiedContent);
} else {
// Copy files
await copyFile(srcPath, destPath);
}
}
}),
);
console.log("JSON files copied successfully!");
} catch (error) {
console.error("Error copying JSON files:", error);
}
}
// Copy the source directory to the destination directory
await copyDirAsync(sourceDir, destDir);
|
import React, { Component, Fragment } from "react";
import { Link } from "react-router-dom";
import { connect } from "react-redux";
import PostHaiku from "../haiku/PostHaiku";
import Notifications from "./Notifications";
import PropTypes from "prop-types";
// MUI
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Button from "@material-ui/core/Button";
//import Tooltip from "@material-ui/core/Tooltip";
// icons
import HomeIcon from "@material-ui/icons/Home";
import FilterVintageIcon from "@material-ui/icons/FilterVintage";
import WrappedButton from "../../util/WrappedButton";
import { Typography } from "@material-ui/core";
import GitHubButton from "react-github-btn";
class Navbar extends Component {
render() {
const { authenticated } = this.props;
return (
<AppBar>
<Toolbar>
<FilterVintageIcon color="secondary" />
<Typography color="secondary">haiku twitter</Typography>
<div className="nav-container">
{authenticated ? (
<Fragment>
<Link to="/">
<WrappedButton tooltipTitle="Home">
<HomeIcon color="secondary" />
</WrappedButton>
</Link>
<PostHaiku />
<Notifications />
</Fragment>
) : (
<Fragment>
<Button color="secondary" component={Link} to="/">
Home
</Button>
<Button color="secondary" component={Link} to="/login">
Log In
</Button>
<Button color="secondary" component={Link} to="/signup">
Sign Up
</Button>
</Fragment>
)}
</div>
<GitHubButton
href="https://github.com/AndrewYinLi/haiku-twitter"
data-size="large"
data-show-count="true"
aria-label="Star AndrewYinLi/haiku-twitter on GitHub"
>
Star
</GitHubButton>
</Toolbar>
</AppBar>
);
}
}
Navbar.propTypes = {
authenticated: PropTypes.bool.isRequired
};
const mapStateToProps = state => ({
authenticated: state.user.authenticated
});
export default connect(mapStateToProps)(Navbar);
|
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import './style.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Toaster } from 'react-hot-toast'
import { createTheme, ThemeProvider } from '@mui/material';
const theme = createTheme({
palette: {
primary: {
main: '#769662',
},
},
overrides: {
MuiPaginationItem: {
page: {
'&.Mui-selected': {
backgroundColor: '#769662',
color: '#fff',
},
},
},
},
});
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
<Toaster/>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
|
/**
* 特点:1、动态地给某个对象添加一些额外的职责。
* 2、在不改变原对象的基础上,通过对其进行包装扩展,使原有对象可以满足用户的更复杂需求,而不会影响从这个类中派生的其他对象。
*
* 优点:1、装饰类和被装饰类都只关心自身的核心业务,实现了解耦。
* 2、可以动态扩展一个实现类的功能。
*
*
*
* 装饰者模式和适配器模式有点类似,区别是装饰者模式是需要传入一个被装饰类的实例,以这个实例为基础进行装饰,而适配器模式传入一个实例,在构造函数中直接新建一个被适配类的实例。
*/
class Person{
constructor(name){
this.name = name;
}
say(){
console.log(`${this.name} say hello`);
}
}
class Decorator{
constructor(person){
this.person = person;
}
cloth (){
this.cloth = 'T-shirt';
}
}
let personWithCloth = new Decorator(new Person('Tom'));
personWithCloth.cloth();
console.log(personWithCloth.cloth);
console.log(personWithCloth.person.name);
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- Bootstrap CSS -->
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
crossorigin="anonymous"
/>
<!-- Custom styles for this page -->
<link rel="stylesheet" href="./CSS/style.css" />
<title>Anna Chernova - software developer</title>
</head>
<body>
<header class="headerCustom" id="header">
<!-- nav -->
<nav class="navbar navbar-expand-lg navCustom">
<div class="container-fluid">
<a class="navbar-logo" href="#contacts"><img src="./images/header logo pic.png" alt="navbar-logo" class="img-logo"></a>
<!-- nav buttons -->
<ul class="nav nav-pills row justify-content-center">
<li class="nav-item col">
<a class="nav-link" aria-current="page" href="#jumbotron">About me</a>
</li>
<li class="nav-item col">
<a class="nav-link" href="#skills">Skills</a>
</li>
<li class="nav-item col-md-3">
<a class="nav-link" href="#CV">CV</a>
</li>
<li class="nav-item col">
<a class="nav-link" href="#contacts">Contacts</a>
</li>
<li class="nav-item dropdown col">
<a class="nav-link dropdown-toggle dropdown-toggleCustom" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false">Portfolio</a>
<div class="dropdown-menu dropdown">
<a class="dropdown-item" href="#app1">HTML5 & CSS3</a>
<a class="dropdown-item" href="#app2">Code Refactor</a>
<a class="dropdown-item" href="#app3">Study guide</a>
<a class="dropdown-item" href="#app4">Password generator</a>
<a class="dropdown-item" href="#app5">Finances console</a>
</div>
</li>
</li>
</ul>
</div>
</nav>
<!-- END nav -->
</header>
<div class="pageWrapper">
<!------------ Jumbotron --------------->
<div class="jumbotron jumbotron-fluid" id="jumbotron" >
<div class="row">
<div class="images d-flex justify-content-center col-lg-4 col-sm-12">
<img src="./images/anna-chernova-pic.png" alt="Anna Chernova avatar" class="img-fluid rounded jumboPic">
</div>
<div class="container col-lg-8 col-sm-12 " id="about_me">
<h2 class="jumbo-h2">Hi there,</h2>
<h3 class="jumbo-h3">I am Anna Chernova!</h3>
<p class="jumbo-p">I'm a novice <mark class="textMarks">software developer</mark> with a 15-year background in journalism and PR. After graduating from a Northcoders Software Development bootcamp in 2023, I dove headfirst into the world of <mark class="textMarks">HTML, CSS, JavaScript, and React/React Native</mark>. Then I hungered for more knowledge and enrolled in a Front-end Development bootcamp with EdX.</p>
<p>I'm on a mission to merge my storytelling power with tech skills and become a pro at creating <mark class="textMarks">user-friendly and valuable apps</mark>.</p>
<p>Originally hailing from Moscow, I am an Italian citizen living in the UK since 2014 (greetings from Folkestone, Kent). Let's connect and create something awesome together!</p>
</div>
</div>
</div>
<!----------- END Jumbotron --------->
<!-------------- skills ----------------->
<div class="skills skillsCustom" id="skills">
<div class="row">
<h3 class="section-h3 my-4">Skills</h3>
</div>
<div class="container buttonsContainer">
<button type="button" class="btn btn-primary">Git</button>
<button type="button" class="btn btn-secondary">GitHub</button>
<button type="button" class="btn btn-success">HTML5</button>
<button type="button" class="btn btn-danger">CSS3</button>
<button type="button" class="btn btn-warning">Flexbox</button>
<button type="button" class="btn btn-info">Grid</button>
<button type="button" class="btn btn-light btn-light-withBorder">Bootstrap</button>
<button type="button" class="btn btn-dark">JavaScript</button>
<button type="button" class="btn btn-primary">jQuery</button>
<button type="button" class="btn btn-secondary">APIs</button>
<button type="button" class="btn btn-success">Node.js</button>
<button type="button" class="btn btn-danger">NPM</button>
<button type="button" class="btn btn-warning">JSON</button>
<button type="button" class="btn btn-info">ECMAScript6</button>
<button type="button" class="btn btn-light btn-light-withBorder">Object-Oriented Programing</button>
<button type="button" class="btn btn-dark">React.js</button>
<button type="button" class="btn btn-primary">React Hooks</button>
<button type="button" class="btn btn-secondary">JSX</button>
<button type="button" class="btn btn-success">Terminal</button>
<button type="button" class="btn btn-danger">Figma</button>
<button type="button" class="btn btn-warning">Canva</button>
</div>
</div>
<!--------------END skills -------------->
<!----------- Portfolio ----------------->
<div class="portfolio">
<div class="row">
<h3 class="section-h3 my-4">Portfolio</h3>
</div>
<!-- main app example -->
<div class="portfolioApps container my-4" id="app1">
<a href="https://anna702.github.io/portfolio_page/" target="_blank" class="row gx-4 topPortfolioRow my-4">
<div class="col app-main">
<div class="row app-text align-items-center">
<h4>HTML5 & CSS3</h4>
<p>Portfolio page created with flexbox, grid and CSS variables</p>
</div>
</div>
</a>
<!-- 2 and 3 app examples -->
<div class="row secondPortfolioRow gx-4">
<!-- app 2 -->
<a href="https://github.com/Anna702/code_refactor" target="_blank" class="col-sm-12 col-md-6">
<div class="col portfolio-app-small app-02 col-relative-app" id="app2">
<div class="row app-text">
<h4>Code Refactor</h4>
<p>HTML, CSS, and Git to make a code more accessible and DRY</p>
</div>
</div>
</a>
<!-- app 3 -->
<a href="https://anna702.github.io/prework-study-guide/" target="_blank" class="col-sm-12 col-md-6">
<div class="col portfolio-app-small app-03 col-relative-app" id="app3">
<div class="row app-text">
<h4>Prework Study Guide</h4>
<p>My first task at the Fronted Developmnent Bootcamp</p>
</div>
</div>
</a>
</div>
<!-- 4 and 5 app examples -->
<div class="row thirdPortfolioRow gx-4">
<!-- app 4 -->
<a href="https://anna702.github.io/Password-generator/" class="col-sm-12 col-md-6">
<div class="col portfolio-app-small app-04 col-relative-app" id="app4">
<div class="row app-text">
<h4>Password generator</h4>
<p>An app that can be used to generate a random password based on selected criteria</p>
</div>
</div>
</a>
<!-- app 5 -->
<a href="https://github.com/Anna702/Console-Finances" class="col-sm-12 col-md-6">
<div class="col portfolio-app-small app-05 col-relative-app" id="app5">
<div class="row app-text">
<h4>Finances console</h4>
<p>This app was created for analyzing the financial records of a company, with the financial dataset provided by client</p>
</div>
</div>
</a>
</div>
</div>
</div>
<!----------- END Portfolio --------->
<!-- CV DownLoad -->
<div class="CV cvCustom" id="CV">
<div class="row">
<h3 class="section-h3 my-4">Download my CV</h3>
</div>
<div class="row">
<div class="col">
<p class="col-12">Are you still looking for a software developer with a unique blend of technical expertise and communication skills? Look no further! Let's connect and explore opportunities for collaboration.</p>
<p>Download my CV in PDF and learn more about my creative background and tech industry journey.</p>
</div>
</div>
<a href="./assets/Anna Chernova_trainee software developer_CV.pdf">
<button class="btn btn-primary">CV Download</button>
</a>
</div>
<!-- END CV Download -->
<!-- contacts -->
<div class="contacts" id="contacts">
<div class="row">
<h3 class="section-h3 my-4">Contacts</h3>
</div>
<div class="row">
<div class="col-md-6">
<p>Feel free to contact me through the following channels:</p>
</div>
<div class="col-md-6">
<ul class="listCustom" style="list-style: none">
<li><a href="mailto:[email protected]" style="color: black; text-decoration: none"><img src="./images/icons8-email-32.png" alt="email icon" class="iconCustom">[email protected]</a></li>
<li><a href="https://github.com/Anna702" style="color: black; text-decoration: none" target="_blank"><img src="./images/icons8-github-32.png" alt="Github icon" class="iconCustom">GitHub</a></li>
<li><a href="https://www.linkedin.com/in/annache/" style="color: black; text-decoration: none" target="_blank"><img src="./images/icons8-linkedin-32.png" alt="LinkedIn icon" class="iconCustom">LinkedIn</a></li>
</ul>
</div>
</div>
</div>
<!-- END contacts -->
<!-- go up -->
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-auto">
<a href="#header"><button class="btn bg-dark text-light">Back to top</button><img src="./images/icons8-arrow-up-24.png" alt="arrow up icon"></a>
</div>
</div>
</div>
<!-- END go up -->
</div>
<!-- Footer -->
<footer class="bg-dark text-light text-center py-4 footerCustom">
<div class="container-fluid ">
<p class="footer-p-1">© 2023 Anna Chernova.</p>
<p class="footer-p-2">I am an artist - that is my vision.</p>
</div>
</footer>
<!-- END Footer -->
<!----------- Bootstrap JS ---------->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<!---------- END Bootstrap JS ------->
</div>
</body>
</html>
|
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Cta } from "../../components/Cta";
import { Loading } from "../../components/Loading";
import { api } from "../../services/api";
import { SelectQuantity } from "../../components/SelectQuantity";
import { useToast } from "../../hooks/useToast";
import { Accordion } from "../../components/Accordion";
import { Button } from "../../components/Button";
import { useBasketBadge } from "../../hooks/useBasketBadge";
import ctaImg from "../../assets/cta-2.png";
import { ProductImageDetails } from "../../components/ProductImageDetails";
import {
Content,
Line,
PriceContainer,
ProductContainer,
ProductDetails,
} from "./styles";
import Swal from "sweetalert2";
import { convertValue } from "utils/mask";
interface ProductProps {
_id: string;
name: string;
price: number;
images: string[];
description: string;
quantity: number;
}
export function Product() {
const { id } = useParams();
const [product, setProduct] = useState<ProductProps>();
const [loading, setLoading] = useState(false);
const [quantity, setQuantity] = useState(1);
const { createBasketBadge } = useBasketBadge();
const Toast = useToast();
useEffect(() => {
setLoading(true);
if (id) {
api.get<ProductProps>(`products/${id}`).then(({ data }) => {
setProduct(data);
setLoading(false);
});
}
}, [id]);
function getBasketProducts() {
const basketItems: ProductProps[] = JSON.parse(
localStorage.getItem("arte-festas-card") || "[]"
);
return basketItems;
}
function saveInBasket(products: ProductProps[]) {
localStorage.setItem("arte-festas-card", JSON.stringify(products));
}
function changeProductQuantityInBasket(id: string, quantity: number) {
const newCardItems = getBasketProducts().map((item) => {
const newQuantity = item.quantity ? item.quantity + quantity : quantity;
if (item._id === id) {
return { ...item, quantity: newQuantity };
}
return item;
});
saveInBasket(newCardItems);
Toast.fire({
icon: "success",
title: "Produto atualizado com sucesso!",
});
}
function alertProductExistsInBasket(id = "", quantity: number) {
Swal.fire({
title: "Atenção",
text: `Esse produto já foi adicionado a sua cesta, deseja adicionar mais ${quantity} a quantidade atual?`,
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#EF4983CC",
cancelButtonColor: "#d33",
confirmButtonText: "Confirmar",
cancelButtonText: "Cancelar",
}).then((result) => {
if (result.isConfirmed) {
changeProductQuantityInBasket(id, quantity);
}
});
}
function addNewBasketProduct(product?: ProductProps) {
if (!product) return;
const parseProduct = { ...product, quantity };
const basketItems = [...getBasketProducts(), parseProduct];
localStorage.setItem("arte-festas-card", JSON.stringify(basketItems));
createBasketBadge(basketItems.length);
Toast.fire({
icon: "success",
title: "Produto adicionado a cesta com sucesso!",
});
}
function handleAddToCart() {
const existsProduct = getBasketProducts().find(
(item) => item._id === product?._id
);
if (existsProduct) {
alertProductExistsInBasket(product?._id, quantity);
return;
}
addNewBasketProduct(product);
}
return (
<>
{loading && <Loading />}
<Cta
title="Os melhores <span>produtos</span> para você"
subtitle="Solte sua imaginação ao criar novos <span>produtos</span>"
paragraph="Que tal trabalhar com algo novo ?
Aqui você encontra o que há de mais novo no mercdo, para vocẽ poder inovar"
reverse={false}
image={ctaImg}
/>
{product && (
<Content>
<ProductContainer>
<ProductImageDetails images={product.images} />
<Line />
<ProductDetails>
<h2>{product.name}</h2>
<p>{product.description}</p>
<PriceContainer>
<SelectQuantity quantity={quantity} setQuantity={setQuantity} />
<p>{convertValue(product.price * quantity)}</p>
</PriceContainer>
<Button onClick={handleAddToCart} fullWidth>
Comprar
</Button>
</ProductDetails>
</ProductContainer>
{product.description && (
<Accordion title="Detalhes">
<p>{product.description}</p>
</Accordion>
)}
</Content>
)}
</>
);
}
|
package com.orive.security.organisation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.time.LocalDate;
import java.util.List;
@RestController
@RequestMapping(value = "company")
@CrossOrigin(origins = "*")
public class CompanyController {
private static final Logger logger = LoggerFactory.getLogger(CompanyController.class);
@Autowired
private CompanyService companyService;
// Create a new Company
@PostMapping(value = "/create/company" , consumes = "multipart/form-data")
// @PreAuthorize("hasRole('client_HR')")
public ResponseEntity<?> saveCompanyEntity(
@RequestParam("address") String address,
@RequestParam("cin") String cin,
@RequestParam("city") String city,
@RequestParam("companyName") String companyName,
@RequestParam("companyType") String companyType,
@RequestParam("contactNumber") Long contactNumber,
@RequestParam("country") String country,
@RequestParam("createdDate") LocalDate createdDate,
@RequestParam("email") String email,
@RequestParam(value = "file", required = false) MultipartFile fileDocument,
@RequestParam("gst") String gst,
@RequestParam("legalOrTradingName") String legalOrTradingName,
@RequestParam("registrationNumber") String registrationNumber,
@RequestParam("state") String state,
@RequestParam("uan") String uan,
@RequestParam("website") String website,
@RequestParam("zipCode") int zipCode,
@RequestParam("status") String status
) {
String result = companyService.saveCompanyEntity(
address, cin, city, companyName, companyType, contactNumber, country, createdDate, email, fileDocument, gst, legalOrTradingName, registrationNumber, state, uan, website, zipCode, status);
if (result != null && result.startsWith("Error")) {
return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
} else if (result != null) {
return new ResponseEntity<>(result, HttpStatus.OK);
} else {
return new ResponseEntity<>("Failed to save Company entity", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
// Get companies logo by name
@GetMapping("/{companyName}")
// @PreAuthorize("hasRole('client_HR')")
public ResponseEntity<?> downloadImage(@PathVariable String companyName){
byte[] imageData=companyService.downloadImage(companyName);
return ResponseEntity.status(HttpStatus.OK)
.contentType(MediaType.valueOf("image/png"))
.body(imageData);
}
// Get all companies
@GetMapping("/get/company")
// @PreAuthorize("hasRole('client_HR')")
public ResponseEntity<List<CompanyDto>> getAllCompany() {
List<CompanyDto> companies = companyService.getAllCompany();
logger.info("Retrieved {} companies from the database", companies.size());
return new ResponseEntity<>(companies, HttpStatus.OK);
}
// Get company by ID
@GetMapping("/get/{companyId}")
// @PreAuthorize("hasRole('client_HR')")
public ResponseEntity<CompanyEntity> getCompanyById(@PathVariable Long companyId) {
try {
CompanyEntity company = companyService.getCompanyById(companyId);
return ResponseEntity.ok(company);
} catch (ResourceNotFoundException e) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
// Update company by ID
@PutMapping("/update/{companyId}")
// @PreAuthorize("hasRole('client_HR')")
public ResponseEntity<Void> partialUpdateCompany(
@PathVariable Long companyId,
@RequestBody CompanyEntity companyEntity) {
companyService.partialUpdateCompany(companyId, companyEntity);
return new ResponseEntity<>(HttpStatus.OK);
}
// Delete Company by ID
@DeleteMapping("/delete/{companyId}")
// @PreAuthorize("hasRole('client_HR')")
public ResponseEntity<Void> deleteCompany(@PathVariable Long companyId) {
companyService.deleteCompany(companyId);
logger.info("Deleted company with ID: {}", companyId);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
//Count the total Company
@GetMapping("/count/company")
// @PreAuthorize("hasRole('client_HR')")
public long countCompany()
{
return companyService.countCompany();
}
}
|
用于计算交易路径的 sqrt 价格的库。
## Functions
### getSqrtPriceX96
```solidity
function getSqrtPriceX96(
bytes path
) internal returns (uint256 sqrtPriceX96)
```
获取指定路径当前兑换价格的sqrtPriceX96值
#### Parameters:
| Name | Type | Description |
| :--- | :--- | :------------------------------------------------------------------- |
|`path` | bytes | 兑换路径
#### Return Values:
| Name | Type | Description |
| :----------------------------- | :------------ | :--------------------------------------------------------------------------- |
|`sqrtPriceX96`| bytes | 给定路径 tokenOut / tokenIn 当前价格的sqrt (X 2^96)值
### getSqrtPriceX96Last
```solidity
function getSqrtPriceX96Last(
bytes path
) internal returns (uint256 sqrtPriceX96Last)
```
获取指定路径历史兑换价格的sqrtPriceX96Last值
#### Parameters:
| Name | Type | Description |
| :--- | :--- | :------------------------------------------------------------------- |
|`path` | bytes | 兑换路径
#### Return Values:
| Name | Type | Description |
| :----------------------------- | :------------ | :--------------------------------------------------------------------------- |
|`sqrtPriceX96Last`| bytes | 给定路径 tokenOut / tokenIn 历史价格的sqrt (X 2^96)值
### verifySlippage
```solidity
function verifySlippage(
bytes path,
address uniV3Factory,
uint32 maxSqrtSlippage
) internal returns (uint256)
```
验证指定的兑换路径交易滑点是否满足设定条件
#### Parameters:
| Name | Type | Description |
| :--- | :--- | :------------------------------------------------------------------- |
|`path` | bytes | 兑换路径
|`uniV3Factory` | address | Uniswap V3 工厂合约地址
|`maxSqrtSlippage` | uint32 | 最大交易滑点,最大值: 1e4
#### Return Values:
| Name | Type | Description |
| :----------------------------- | :------------ | :--------------------------------------------------------------------------- |
|`current`| bytes | 路径的当前价格
|
import 'package:appimcnew/model/configuracoes_model.dart';
import 'package:appimcnew/repository/configuracoes_repository.dart';
import 'package:appimcnew/shared/widgets/text_label.dart';
import 'package:flutter/material.dart';
class ConfiguracaoPage extends StatefulWidget {
const ConfiguracaoPage({super.key});
@override
State<ConfiguracaoPage> createState() => _ConfiguracaoPageState();
}
class _ConfiguracaoPageState extends State<ConfiguracaoPage> {
TextEditingController nomeUsuarioController = TextEditingController();
TextEditingController alturaController = TextEditingController();
late ConfiguracoesRepository configuracoesRepository;
var configuracoesModel = ConfiguracoesModel.vazio();
@override
void initState() {
// TODO: implement initState
super.initState();
carregarDados();
}
void carregarDados() async {
configuracoesRepository = await ConfiguracoesRepository.load();
configuracoesModel = configuracoesRepository.obterDados();
nomeUsuarioController.text = configuracoesModel.nomeUsuario;
alturaController.text = configuracoesModel.altura.toString();
setState(() {});
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(title: const Text("Configuração Hive")),
body: ListView(
children: [
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: TextLabel(texto: "Nome"),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: TextField(
decoration: const InputDecoration(hintText: "Nome Usuario"),
controller: nomeUsuarioController,
)),
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
child: TextLabel(texto: "Altura (Ex:120 cm)"),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: TextField(
keyboardType: TextInputType.number,
decoration: const InputDecoration(hintText: "Altura"),
controller: alturaController,
)),
TextButton(
onPressed: () async {
FocusManager.instance.primaryFocus?.unfocus();
try {
configuracoesModel.altura =
double.parse(alturaController.text);
} catch (e) {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
title: const Text("Meu App"),
content: const Text("Altura invalida"),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text("OK"))
],
);
});
return;
}
configuracoesModel.nomeUsuario = nomeUsuarioController.text;
configuracoesRepository.salvar(configuracoesModel);
Navigator.pop(context);
},
child: const Text("Salvar"))
],
),
));
}
}
|
---
title: Apuntes de desarrollo web - HTML, CSS y JS
description:
---
<div class="topbar">
<a href="index.html" class="back">Atrás</a>
<h1>JavaScript</h1>
</div>
<ul class="index">
<li><a href=#principios>Principios</a></li>
<li><a href=#consola>Consola</a></li>
<li><a href=#variables>Variables</a></li>
<li><a href=#operadores>Operadores</a></li>
<li><a href=#seleccionar-nodos>Seleccionar nodos en el DOM</a></li>
<li><a href=#alterar-contenido>Alterar el contenido del DOM</a></li>
<li><a href=#alterar-clases>Alterar clases en elementos del DOM</a></li>
<li><a href=#alterar-atributos>Alterar atributos en elementos del DOM</a></li>
<li><a href=#condicionales>Condicionales</a></li>
<li><a href=#loops>Loops</a></li>
<li><a href=#funciones>Funciones</a></li>
<li><a href=#eventos>Eventos</a></li>
<li><a href=#listeners>Listeners</a></li>
</ul>
<div class="main">
<div class="main__block" id="principios">
<h2>Principios</h2>
<dl>
<dt>¿Para qué sirve JavaScript?</dt>
<dd>
<p>
JavaScript es el lenguaje de programación que se ejecuta del lado del cliente (es decir, en el navegador) en vez de en el servidor, como es el caso de PHP.
</p>
<p>
Las funciones de JavaScript son: acceder al contenido de una web, modificar el contenido de una web, programar reglas y reaccionar a eventos.
</p>
<p>
La programación del lado del navegador puede sufrir muchos problemas (el archivo de JS no se descarga bien, sufre modificaciones en el navegador del usuario, o una función estaba mal escrita y el script deja de funcionar), por lo que se recomienda siempre que una web sea capaz de emplearse si JavaScript(aunque sea de manera muy simplificada).
</p>
</dd>
<dt>Scripts</dt>
<dd>
Los scripts son instrucciones que se ejecutan de manera lineal, como los pasos de una receta. Es la forma en la que escribimos instrucciones en JavaScript.
</dd>
<dt>Programación orientada a objetos</dt>
<dd>
Los lenguajes de programación modernos tienden a usar un modelo de datos que se llaman "objetos". Estos objetos son elementos que tienen propiedades y valores propios, y también métodos (funciones internas). Una web se renderiza en un navegador como el objeto <code>document</code>, que se visualiza dentro del objeto <code>window</code> o ventana del navegador.
</dd>
<dt>Etiqueta <code><script></code></dt>
<dd>
<p>
La etiqueta script se escribe <code><script></script></code>, y dentro podemos poner cualquier código JS, que se ejecutará dentro de la página. Si queremos cargar un archivo externo <code>.js</code>, utilizaremos el atributo <code>src</code> dentro de esta etiqueta. Ejemplo: <code><script src="scripts.js"></script></code>
</p>
<p>
El código JavaScript se ejecuta en el punto del HTML en el que se encuentra, por lo que se suele recomendar ponerlo al final de nuestro html (justo antes del cierre de <code><body></code>), para que no bloquee la carga de la página.
</p>
</dd>
<dt>Sintaxis</dt>
<dd>
<p>
Las declaraciones en JavaScript (por ejemplo, asignar un valor a una variable) se finalizan con <code>;</code>, de forma muy similar a CSS. Ejemplo: <code>var edadUsuario = 20;</code>
</p>
<p>
Los comentarios en JavaScript se escriben igual que en CSS: <code>/* aquí el comentario */</code>. Además, en JS contamos con el comentario de línea, poniendo <code>//</code> al principio de la misma.
</p>
<p>
Cuando queremos agrupar una o varias declaraciones en una función o un condicional (como <code>if</code>…<code>else</code>), usaremos <code>{}</code>. Ejemplo: <code>if(edadUsuario>20){alert("Eres mayor de edad.");}</code>
</p>
<p>
El paréntesis suele indicar una función, y lo que ponemos entre paréntesis, el parámetro que pasamos a dicha función. Ejemplo: <code>alert("Hola");</code>
</p>
<p>
El punto (.) indica pertenencia, por lo que cuando lo encontremos en una declaración, probablemente se refiere a la propiedad de un objeto. Ejemplo: <code>document.URL;</code>. Si lo que tenemos a continuación es un paréntesis, probablemente se refiere a un método (función interna) propio del objeto. Ejemplo: <code>console.log("Hola");</code>
</p>
<p>
En JavaScript, los listados de elementos se empiezan a contar desde el 0, no el 1. Si nos queremos referir al primero, hablaremos por tanto del "elemento en la posicion 0 del listado".
</p>
</dd>
<dt>DOM</dt>
<dd>El DOM (Document Object Model) es el objeto <code>document</code>, que es como se renderiza una página web en el navegador. Cuando hablamos de que usamos JavaScript para recoger o alterar información de una web, hablamos siempre de "acceder al DOM".</dd>
</dl>
</div>
<div class="main__block" id="consola">
<h2>Consola</h2>
<dl>
<dt>Consola</dt>
<dd>
La consola es una pestaña en el inspector de DOM (o las herramientas de desarrollo) que nos permite introducir instrucciones de JS y leer mensajes de error o de log. Para mostrar mensajes en la consola, podemos utilizar el método <code>log</code> del objeto <code>console</code>, de esta manera: <code>console.log("mensaje que quieras mostrar");</code>
</dd>
</dl>
</div>
<div class="main__block" id="variables">
<h2>Variables</h2>
<dl>
<dt>Variables</dt>
<dd>
<p>
Las variables son elementos que pueden tener un valor que se pueda modificar a lo largo de nuestro script, sea este texto, un número, un valor booleano o un array.
</p>
<p>
Una variable se declara con la instrucción <code>var</code> y el nombre que queramos (que no empiece por números, tenga guiones o espacios, o sea una palabra restringida de JavaScript). Ejemplo: <code>var edadUsuario;</code>
</p>
<p>
Si sabemos el valor inicial de una variable, podemos asignarlo al mismo tiempo que la declaramos: <code>var edadUsuario = 20;</code>
</p>
<p>
Además, podemos hacer una declaración múltiple de variables separadas por comas.
<br>Ejemplo: <code>var edadUsuario = 20, nombreUsuario = "Laura", socio = true;</code>
</p>
</dd>
<dt>Strings (texto)</dt>
<dd>
<p>
El valor de las variables cuyo valor es texto se declara entre comillas, lo que nos permite poner casi cualquier carácter sin que el resto de nuestro script se vea afectado. Ejemplo: <code>var nombreUsuario = "Laura López";</code>
</p>
<p>
Cuando queremos poner comillas dentro de comillas (por ejemplo, un string que contenga etiquetas HTML), deberíamos anidar comillas simples dentro de las comillas dobles.
<br>Ejemplo: <code>var respuestaForm = "<p class='respuesta' >¡Muchas gracias!</p>";</code>
</p>
</dd>
<dt>Variables numéricas</dt>
<dd>
Un valor numérico se asigna a una variable sin comillas (de lo contrario, estaríamos creando un string). Ejemplo: <code>var edadUsuario = 20;</code>
</dd>
<dt>Variables booleanas</dt>
<dd>
Una variable booleana es aquella cuyo valor es "verdadero" (<code>true</code>) o "falso" (<code>false</code>).
<br>Ejemplo: <code>var esSocio = true;</code>
</dd>
<dt>Arrays (listados)</dt>
<dd>
<p>
Un array es una variable especial que puede contener varios valores (o un objeto bastante simple).
</p>
<p>
La forma más sencilla de declarar un array es con <code>[]</code>, es decir: <code>var coloresDisponibles = ["rojo", "azul", "amarillo"];</code>
</p>
<p>
La forma más sencilla de recuperar un valor concreto de un array es refiriéndose a la posición que ocupa en el listado. Ejemplo: <code>coloresDisponibles[0];</code>
</p>
</dd>
</dl>
</div>
<div class="main__block" id="operadores">
<h2>Operadores</h2>
<dl>
<dt>Operador de asignación: <code>=</code></dt>
<dd>
El operador <code>=</code> permite asignar un valor a una variable. Para comparar dos valores, usaremos el comparador <code>==</code>.
</dd>
<dt>Operador aritmético de adición: <code>+</code></dt>
<dd>
El operador <code>+</code> permite sumar valores numéricos o concatenar strings. Es el único operador aritmético que podremos usar con texto.
</dd>
<dt>Operador aritmético de sustracción: <code>-</code></dt>
<dd>
Permite hacer una resta entre dos valores numéricos.
</dd>
<dt>Operador aritmético de división: <code>/</code></dt>
<dd>
Divide dos valores numéricos.
</dd>
<dt>Operador aritmético de multiplicación: <code>*</code></dt>
<dd>
Multiplica dos valores numéricos.
</dd>
<dt>Operador aritmético de incremento: <code>++</code></dt>
<dd>
Podemos añadir el operador <code>++</code> al final del nombre de una variable para incrementar en 1 su valor. Una variable "ejemplo" que tenga un valor de 3, subirá a 4 si escribimos <code>ejemplo++;</code>.
</dd>
<dt>Operador aritmético de decremento: <code>--</code></dt>
<dd>
Podemos añadir el operador <code>--</code> al final del nombre de una variable para reducir en 1 su valor. Una variable "ejemplo" que tenga un valor de 3, bajará a 2 si escribimos <code>ejemplo--;</code>.
</dd>
<dt>Operador aritmético de módulo: <code>%</code></dt>
<dd>
Permite obtener el resto de una división de dos números (por ejemplo, <code>10 % 3</code> daría como resultado 1).
</dd>
<dt>Operador de comparación: <code>==</code></dt>
<dd>
Permite comprobar si dos valores son iguales.
</dd>
<dt>Operador de comparación: <code>!=</code></dt>
<dd>
Permite comprobar si dos valores son diferentes.
</dd>
<dt>Operador de comparación: <code>===</code></dt>
<dd>
Podemos usar <code>===</code> en vez de <code>==</code> si queremos comprobar no solo que dos valores son iguales, sino que son estrictamente del mismo tipo (por ejemplo, no es lo mismo el valor numérico 3 que el valor literal "3", pero <code>==</code> diría que sí es lo mismo, mientras que <code>===</code> no).
</dd>
<dt>Operador de comparación: <code>!==</code></dt>
<dd>
Al igual que <code>===</code>, permite comparar dos valores estrictamente; en este caso si el valor y/o el tipo de variable son diferentes.
</dd>
<dt>Operador de comparación: <code>></code></dt>
<dd>
Permite saber si un valor es mayor que otro.
</dd>
<dt>Operador de comparación: <code><</code></dt>
<dd>
Permite saber si un valor es menor que otro.
</dd>
<dt>Operador de comparación: <code>>=</code></dt>
<dd>
Permite saber si un valor es mayor o igual que otro.
</dd>
<dt>Operador de comparación: <code><=</code></dt>
<dd>
Permite saber si un valor es menor o igual que otro.
</dd>
<dt>Operador lógico AND: <code>&&</code></dt>
<dd>
Permite saber si dos expresiones se cumplen. Por ejemplo: <code>((5 > 2) && (2 <= 3))</code>
</dd>
<dt>Operador lógico OR: <code>||</code></dt>
<dd>
Permite saber si al menos una de dos expresiones se cumplen. Por ejemplo: <code>((4 > 2) || (1 > 6))</code>
</dd>
<dt>Operador lógico NOT: <code>!</code></dt>
<dd>
Permite saber si una expresión no se cumple. Por ejemplo: <code>!(4 < 2)</code>
</dd>
</dl>
</div>
<div class="main__block" id="seleccionar-nodos">
<h2>Seleccionar nodos en el DOM</h2>
<dl>
<dt><code>document.getElementById()</code></dt>
<dd>
Una forma de seleccionar un nodo (elemento) en el HTML para poder manipularlo, es por su atributo <code>id</code>. Por ejemplo, si queremos acceder al div con el <code>id="principal"</code> y guardar esta búsqueda en una variable, podemos escribir <code>var contenedor = document.getElementById("principal");</code>
</dd>
<dt><code>document.querySelector()</code></dt>
<dd>
Devuelve el primer elemento que encuentra con el selector CSS que hayamos utilizado. En este caso, al contrario que con otros métodos como <code>document.getElementById()</code>, tendremos que especificar si es un id con una <code>#</code>, una clase con un <code>.</code> o un tag html. Ejemplo: <code>document.querySelector(".visible");</code>
</dd>
<dt><code>document.querySelectorAll()</code></dt>
<dd>
Similar a <code>document.querySelector()</code>, pero devuelve un listado de nodos (array) con todos los elementos que coincidan con la selección, por ejemplo: <code> var listado = document.querySelectorAll("li");</code>… aunque solo exista un elemento de este tipo. Por eso, para referirnos a un elemento de esa lista de nodos, nos referiremos a su posición en el array: <code>listado[0];</code>
</dd>
</dl>
</div>
<div class="main__block" id="alterar-contenido">
<h2>Alterar el contenido del DOM</h2>
<dl>
<dt><code>elemento.textContent</code></dt>
<dd>
Hay varias formas de alterar el contenido de un nodo. Si solo queremos cambiar el texto de un nodo, podemos hacerlo accediendo a la propiedad <code>textContent</code>. Por ejemplo, para un nodo que hayamos guardado en la variable "contenedor", podemos cambiar su texto así: <code>contenedor.textContent = "Un nuevo texto";</code>
</dd>
<dt><code>document.write()</code></dt>
<dd>
Una forma de escribir contenido con JS en el HTML es <code>document.write()</code>. Sin embargo, este código ejecuta la escritura en donde la encuentre, por lo que normalmente no lo pondremos en un archivo externo sino directamente en el HTML. En general, no es aconsejable usar este método para añadir contenido al DOM.
</dd>
</dl>
</div>
<div class="main__block" id="alterar-clases">
<h2>Alterar clases en elementos del DOM</h2>
<dl>
<dt><code>elemento.classList.add()</code></dt>
<dd>
Permite añadir una clase a un elemento del DOM. Ejemplo: <code>elemento.classList.add("activo");</code>
</dd>
<dt><code>elemento.classList.remove()</code></dt>
<dd>
Permite quitar una clase a un elemento del DOM. Ejemplo: <code>elemento.classList.remove("activo");</code>
</dd>
<dt><code>elemento.classList.contains()</code></dt>
<dd>
Permite comprobar si un elemento del DOM tiene una clase en particular. Ejemplo:
<br><code>if (elemento.classList.contains("activo")){/*código*/}</code>
</dd>
<dt><code>elemento.classList.toggle()</code></dt>
<dd>
Permite añadir una clase a un elemento del DOM si no la tiene, o quitársela si la tiene. Ejemplo: <code>elemento.classList.toggle("activo");</code>
</dd>
</dl>
</div>
<div class="main__block" id="alterar-atributos">
<h2>Alterar atributos en elementos del DOM</h2>
<dl>
<dt><code>elemento.getAttribute()</code></dt>
<dd>
Permite recuperar el valor de un atributo de un elemento. Ejemplo:
<br><code>var valorHref = elemento.getAttribute("href");</code>
</dd>
<dt><code>elemento.setAttribute()</code></dt>
<dd>
Asigna el valor de un atributo en un elemento, y el atributo si no existiera. Ejemplo:
<br><code>elemento.setAttribute("href", "http://google.com");</code>
</dd>
<dt><code>elemento.removeAttribute()</code></dt>
<dd>
Elimina un atributo de un elemento. Ejemplo: <code>elemento.removeAttribute("style");</code>
</dd>
<dt><code>elemento.hasAttribute()</code></dt>
<dd>
Comprueba si un elemento tiene un atributo o no. Ejemplo:
<br><code>if(elemento.hasAttribute("href")){/* código */}</code>
</dd>
</dl>
</div>
<div class="main__block" id="condicionales">
<h2>Condicionales</h2>
<dl>
<dt><code>if</code>… <code>else</code></dt>
<dd>
<p>
La forma más habitual de que unas líneas de nuestro script se ejecuten solo cuando se cumpla una condición es con <code>if</code>. Escribimos <code>if</code>, la condición entre paréntesis y después, entre <code>{}</code>, las líneas de código sujetas a la condición.
</p>
<p>
Podemos encadenar condiciones con <code>else</code>. Tras el cierre de <code>{}</code> del primer <code>if</code>, podemos escribir una alternativa por si no se cumple la primera condición.
</p>
<p>
Si queremos que la segunda opción o posteriores solo se apliquen si se da una condición, usaremos <code>else if</code>, seguido de la condición entre paréntesis y luego las líneas de código entre <code>{}</code>.
</p>
<p>Ejemplo de todo esto:
</p>
<code>
<pre>
var edadUsuario = 18;
if(edadUsuario > 17){
console.log("es mayor de edad");
}
else if(edadUsuario < 12){
console.log("es un niño");
}
else{
console.log("es un adolescente");
}
</pre>
</code>
</dd>
</dl>
</div>
<div class="main__block" id="loops">
<h2>Loops</h2>
<dl>
<dt><code>for</code></dt>
<dd>
Un loop como <code>for</code> permite repetir varias veces una serie de instrucciones empleando para ello un contador. De esta manera, podemos decirle que empezando de 0, y hasta que no queden más nodos en un array, repita una instrucción, sumando 1 al contador cada vez. Ejemplo de <code>for</code> en funcionamiento:
<code>
<pre>
for(var contador=0; contador < listaTabs.length; contador++){
listaTabs[contador].classList.add("visible");
}
</pre>
</code>
</dd>
</dl>
</div>
<div class="main__block" id="funciones">
<h2>Funciones</h2>
<dl>
<dt><code>function()</code></dt>
<dd>
Una función nos permite agrupar código entre <code>{}</code> para poderlo reutilizar o llamar cuando es necesario. Normalmente le asignaremos un nombre y podemos pasarle argumentos a través del paréntesis. Ejemplo:
<br>
<code>
<pre> function escribeConsola(mensaje){
console.log(mensaje);
}
//En otra parte del código, la llamamos
escribeConsola("Hola!");
</pre>
</code>
</dd>
</dl>
</div>
<div class="main__block" id="eventos">
<h2>Eventos</h2>
<dl>
<dt>Los eventos</dt>
<dd>
<p>
Los eventos son cambios en el DOM, provocados por el ratón (por ejemplo, <code>click</code> o <code>mouseover</code>), por el navegador (<code>load</code> o <code>scroll</code>), teclado (<code>keypress</code>), foco (<code>focus</code> o <code>blur</code>), formularios (<code>submit</code> o <code>change</code>)…
</p>
<p>
En JavaScript, muchas veces recurriremos a estos eventos para programar reglas (por ejemplo, que se validen los campos de un formuario antes de enviarse, que es el evento <code>submit</code>). Tienes una <a href="https://developer.mozilla.org/en-US/docs/Web/Events#Standard_events">lista completa en la Mozilla Developer Network</a>.
</p>
</dd>
<dt><code>evento.preventDefault()</code></dt>
<dd>
Este método evita que los elementos sobre los que se ha hecho clic realicen su comportamiento por defecto, como enviar un formulario cuando se ha hecho clic en un botón con <code>type="submit"</code> o acceder a una url cuando se ha hecho clic en un link.
</dd>
<dt><code>evento.stopPropagation()</code></dt>
<dd>
Este método evita el "event bubling", o que un clic en un elemento que ya tenía una función asociada (mendiante un listener) afecte a un elemento padre que también tenga una función asociada.
</dd>
<dt><code>return false;</code></dt>
<dd>
Esta expresión lanza a la vez <code>evento.preventDefault()</code> y <code>evento.stopPropagation()</code>, pero también deja de procesar el código de una función que pueda venir a continuación, por lo que muchos desarrolladores prefieren evitar su uso.
</dd>
<dt><code>evento.target</code></dt>
<dd>
Si asociamos un evento (por ejemplo, el evento click) con una función, es posible que desde esta función nos queramos referir a este evento, por lo que muchas veces pasamos el propio evento como la primera variable (ejemplo: <code>function(evento){ /*código*/ }</code>). Este evento es un objeto que contiene una serie de propiedades, de las cuales la más popular es <code>evento.target</code>, que indica el nodo (tag html) en el que se ha hecho click (o equivalente).
</dd>
</dl>
</div>
<div class="main__block" id="listeners">
<h2>Listeners</h2>
<dl>
<dt>Los listeners</dt>
<dd>
Un event listener nos permite asociar funciones a eventos concretos tanto del navegador como nodos en el DOM. Debemos procurar no asignar el mismo más de una vez en cada elemento o provocaremos que una función se ejecute varias veces.
</dd>
<dt><code>elemento.addEventListener()</code></dt>
<dd>
Para asignar un listener, seleccionaremos un nodo y mediante <code>addEventListener()</code> le asociaremos un evento y una función, y opcionalmente <code>false</code> o <code>true</code> si queremos asegurar la dirección del "event bubling" (por defecto <code>false</code>).
<br>Ejemplo:
<br>
<code>
<pre>
function comprobarFormulario(){
//código de la función
}
var formulario = document.getElementById("formulario-envio");
formulario.addEventListener("submit", comprobarFormulario, false);
</pre>
</code>
</dd>
</dl>
</div>
</div>
|
import { Component, NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CartComponent } from './component/cart/cart.component';
import { DashboardComponent } from './component/dashboard/dashboard.component';
import { EditProfileComponent } from './component/edit-profile/edit-profile.component';
import { ForgotPasswordComponent } from './component/forgot-password/forgot-password.component';
import { HeaderComponent } from './component/header/header.component';
import { LoginComponent } from './component/login/login.component';
import { MyOrderComponent } from './component/my-order/my-order.component';
import { ResetComponent } from './component/reset/reset.component';
import { SignupComponent } from './component/signup/signup.component';
import { WhishlistLoginSignupComponent } from './component/whishlist-login-signup/whishlist-login-signup.component';
import { WishlistComponent } from './component/wishlist/wishlist.component';
import { DisplayBooksComponent } from './display-books/display-books.component';
import { OrderSucessfulComponent } from './order-sucessful/order-sucessful.component';
import { AuthGuard } from './service/auth.guard';
const routes: Routes = [
// {path:'', component:LoginComponent},
// {path:'', component:SignupComponent},
{path:'loginform', component:LoginComponent},
{ path: '' , redirectTo: 'loginform', pathMatch: 'full' },
{path:'signupform', component:SignupComponent },
{ path: 'reset/:token', component: ResetComponent},
{path:'forgot', component:ForgotPasswordComponent},
{path:'books', component:DashboardComponent, canActivate: [AuthGuard]},
{path:'display/:id', component:DisplayBooksComponent},
{path: 'search/:searchTerm', component:DisplayBooksComponent},
{path:'profile', component:EditProfileComponent},
{path: 'myorder', component: MyOrderComponent},
{path:'cart',component:CartComponent},
{path:'wishlist',component:WishlistComponent},
{path:'wishlistlogin',component:WhishlistLoginSignupComponent},
{ path: 'order', component: OrderSucessfulComponent },
// { path: '' , redirectTo: 'loginform', pathMatch: 'full'},
{ path: '' , redirectTo: 'signupform', pathMatch: 'full'},
{path:'forgot', component:ForgotPasswordComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
<!DOCTYPE html>
<html lang="pt-br" xmlns:th="http://www.thymeleaf.org">
<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>Smart School</title>
<link
href="../static/css/style.css"
th:href="@{/css/style.css}"
rel="stylesheet"
/>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://use.fontawesome.com/releases/v5.0.8/css/all.css"
/>
<style>
.input-group {
padding: 10px;
}
</style>
</head>
<body>
<div th:replace="fragmentos/navSecretaria :: nav"></div>
<main class="container">
<ul class="nav justify-content-center p-3">
<li class="nav-item">
<a
class="nav-link active"
aria-current="page"
href="/manteralunos"
style="
background-color: #e6e6fa;
border-radius: 25px;
margin: 8px;
"
>Atualizar Cadastro Aluno</a
>
</li>
<li class="nav-item">
<a class="nav-link" href="/manterprofessores"
>Atualizar Cadastro Professores</a
>
</li>
<li class="nav-item">
<a class="nav-link" href="/mantersala"
>Atualizar Cadastro Salas de Aula</a
>
</li>
</ul>
<div
class="alert alert-success"
role="alert"
th:if="${!#strings.isEmpty(sucessmensage)}"
>
<span th:text="${sucessmensage}">!</span>
</div>
<form class="input-group mb-3" th:action="@{/manteralunos}">
<input
type="text"
class="form-control"
placeholder="Login ou CPF"
th:name="identidadeAluno"
/>
<button
class="btn btn-outline-secondary"
id="button-addon2"
type="submit"
>
Procurar
</button>
</form>
<form
class=""
action="/manteralunos"
method="POST"
th:object="${aluno}"
>
<div class="input-group">
<span class="input-group-text">Login</span>
<input
type="text"
aria-label="Login"
class="form-control"
th:field="*{usuario.login}"
maxlength="10"
readonly
/>
</div>
<div class="input-group">
<span class="input-group-text">RG</span>
<input
type="number"
aria-label="RG"
class="form-control"
th:field="*{usuario.rg}"
maxlength="11"
required
/>
</div>
<div class="input-group">
<span class="input-group-text">Telefone</span>
<input
type="number"
aria-label="Telefone"
class="form-control"
th:field="*{usuario.telefone}"
maxlength="11"
required
/>
<div
class="alert alert-warning"
th:if="${#fields.hasErrors('usuario.telefone')}"
th:errors="*{usuario.telefone}"
></div>
</div>
<div class="input-group">
<span class="input-group-text">Endereço</span>
<input
type="text"
aria-label="Endereco"
class="form-control"
th:field="*{usuario.endereco}"
required
/>
</div>
<div class="input-group">
<span class="input-group-text">Data de Nascimento</span>
<input
type="date"
aria-label="Data de Nascimento"
class="form-control"
th:field="*{usuario.dataNasc}"
required
/>
</div>
<div class="input-group">
<span class="input-group-text">E-mail</span>
<input
type="email"
aria-label="E-mail"
class="form-control"
th:field="*{usuario.email}"
required
/>
</div>
<div class="input-group">
<span class="input-group-text">Nome</span>
<input
type="text"
aria-label="Nome"
class="form-control"
th:field="*{usuario.nome}"
required
/>
</div>
<div class="input-group">
<span class="input-group-text">CPF</span>
<input
type="number"
aria-label="CPF"
class="form-control"
th:field="*{usuario.cpf}"
maxlength="11"
minlength="11"
readonly
/>
</div>
<div
class="alert alert-warning"
th:if="${#fields.hasErrors('usuario.cpf')}"
th:errors="*{usuario.cpf}"
></div>
<div class="input-group">
<span class="input-group-text">Matricula</span>
<input
type="text"
aria-label="Matricula"
class="form-control"
th:field="*{matricula}"
maxlength="14"
/>
</div>
<div class="input-group">
<span class="input-group-text">Nome da Mãe</span>
<input
type="text"
aria-label="Nome da Mãe"
class="form-control"
th:field="*{nomeMae}"
required
/>
</div>
<div class="input-group">
<span class="input-group-text">Nome do Pai</span>
<input
type="text"
aria-label="Nome do Pai"
class="form-control"
th:field="*{nomePai}"
required
/>
</div>
<div class="input-group">
<span class="input-group-text">Data da Matrícula</span>
<input
type="date"
aria-label="DataMatricula"
class="form-control"
th:field="*{dataMatricula}"
/>
</div>
<div class="input-group">
<span class="input-group-text"
>Telefone do responsável</span
>
<input
type="number"
aria-label="Telefone"
class="form-control"
th:field="*{telResponsavel}"
maxlength="11"
required
/>
</div>
<div
class="alert alert-warning"
th:if="${#fields.hasErrors('telResponsavel')}"
th:errors="*{telResponsavel}"
></div>
<div class="d-grid gap-2 col-6 mx-auto p-3">
<button class="btn btn-primary btn-sm" type="submit">
Alterar
</button>
</div>
</form>
<form th:action="@{/manteralunos}" th:method="delete">
<input
type="hidden"
th:name="login"
th:value="${aluno?.usuario.login}"
/>
<div class="d-grid gap-2 col-6 mx-auto p-3">
<button class="btn btn-primary btn-sm" type="submit">
Apagar
</button>
</div>
</form>
</main>
<div th:replace="fragmentos/footer :: footer"></div>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ"
crossorigin="anonymous"
></script>
</body>
</html>
|
#pragma once
#include <chrono>
#include <memory>
#include <functional>
#include "DraggableQWidget.h"
#include "UpdatableGameWindow.h"
#include "ScaleableLabel.h"
#include "ColorChangerWidgetHelper.h"
#include <QLCDNumber>
#include <QMenu>
#include <QGridLayout>
class NestedTimerWindow: public DraggableQWidget, public UpdatableGameWindow, public ColorChangerWidgetHelper
{
public:
NestedTimerWindow();
void RefreshState() override;
inline bool IsStillOpen() const override { return isVisible(); }
void AddNestedTimer(const std::string &name);
void SetActiveTimer(const std::string &name);
void StopAllTimers();
void ResetAllTimers();
std::function<void()> OnRefresh;
protected:
void mousePressEvent(QMouseEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
private slots:
QAction *actionExit = nullptr;
QMenu *contextMenu = nullptr;
std::chrono::steady_clock::time_point totalTimerStart;
std::chrono::steady_clock::time_point totalTimerEnd;
bool isTimerActivated = false;
QLCDNumber *totalNumberDisplay = nullptr;
QGridLayout *nestedTimersLayout = nullptr;
struct NestedTimer
{
std::string Name;
bool Activated = false;
bool Touched = false;
std::chrono::steady_clock::time_point End;
ScaleableLabel *Label = nullptr;
QLCDNumber *NumberDisplay = nullptr;
};
std::vector<NestedTimer> nestedTimers;
};
|
import stdlib.
import rec.
module Ordinal-03.
-- Define Ord as an inductive datatype.
data Ord: ★
= zer : Ord
| suc : Ord ➔ Ord
| lim : (Nat ➔ Ord) ➔ Ord.
-- we can now define primitive recursion on an ordinal via
-- pattern matching. Defining recursion in this way saves
-- us the hassle of doing it on a per-operation basis.
o-rec : ∀ X: ★. X ➔ (X ➔ X) ➔ ((Nat ➔ X) ➔ X) ➔ Ord ➔ X
= Λ X. λ base. λ step. λ limit. λ o. μ o-rec'. o {
| zer ➔ base
| suc o' ➔ step (o-rec' o')
| lim l ➔ limit (λ n. o-rec' (l n))
}.
-- We can define all of our operations succinctly via o-rec.
ordAdd : Ord ➔ Ord ➔ Ord
= λ a. o-rec a suc lim.
one : Ord = suc zer.
two : Ord = suc one.
three : Ord = suc two.
four : Ord = suc three.
ordMul : Ord ➔ Ord ➔ Ord
= λ a. o-rec zer (λ r. ordAdd r a) lim.
ordExp : Ord ➔ Ord ➔ Ord
= λ a. o-rec (suc zer) (λ r. ordMul r a) lim.
-- Defining Omega
-------------------------------------------------
-- We can get Omega and epsilon_0 in the same way as we did in
-- implicit-02.
finiteOrdinals : Nat ➔ Ord = rec zer suc.
omega : Ord = lim finiteOrdinals.
-- Omega tower is the act of recursing repeated
-- omega exponentiation over omega as base,
-- which we get becaouse of our uniform typing of ordExp.
omegaTower : Nat ➔ Ord
= rec omega (ordExp omega).
-- And now we take the limit...
-- and get ε_0!
epsilon0 : Ord = lim omegaTower.
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Route, Routes } from "react-router-dom";
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import Header from "./components/Header";
import Home from "./pages/Home";
import Cadastrar from "./pages/Cadastrar";
const queryClient = new QueryClient();
function App() {
return (
<>
<QueryClientProvider client={queryClient}>
<Header />
<Routes>
<Route element={<Home />} path="/" />
<Route element={<Cadastrar />} path="/cadastrar" />
</Routes>
</QueryClientProvider>
</>
);
}
export default App;
|
---
title: Gegevens ophalen van shapes op een kaart | Microsoft Azure kaarten
description: In dit artikel leert u hoe u shapegegevens kunt ophalen die op een kaart zijn getekend met behulp van de Microsoft Azure Maps Web SDK.
author: philmea
ms.author: philmea
ms.date: 09/04/2019
ms.topic: conceptual
ms.service: azure-maps
services: azure-maps
manager: philmea
ms.openlocfilehash: 88db018575f92e777223f383c65cd6db51ba515a
ms.sourcegitcommit: 849bb1729b89d075eed579aa36395bf4d29f3bd9
ms.translationtype: MT
ms.contentlocale: nl-NL
ms.lasthandoff: 04/28/2020
ms.locfileid: "80334413"
---
# <a name="get-shape-data"></a>Vormgegevens ophalen
Dit artikel laat u zien hoe u gegevens kunt ophalen van shapes die op de kaart worden getekend. We gebruiken de functie **drawingManager. getSource ()** in [Draw Manager](https://docs.microsoft.com/javascript/api/azure-maps-drawing-tools/atlas.drawing.drawingmanager?view=azure-node-latest#getsource--). Er zijn verschillende scenario's waarin u de geojson-gegevens van een getekende vorm wilt extra heren en deze elders kunt gebruiken.
## <a name="get-data-from-drawn-shape"></a>Gegevens ophalen van een teken vorm
De volgende functie haalt de bron gegevens van de getekende vorm op en voert deze uit naar het scherm.
```Javascript
function getDrawnShapes() {
var source = drawingManager.getSource();
document.getElementById('CodeOutput').value = JSON.stringify(source.toJson(), null, ' ');
}
```
Hieronder ziet u het volledige programma voor het uitvoeren van code, waarin u een vorm kunt tekenen om de functionaliteit te testen:
<br/>
<iframe height="686" title="Vormgegevens ophalen" src="//codepen.io/azuremaps/embed/xxKgBVz/?height=265&theme-id=0&default-tab=result" frameborder="no" allowtransparency="true" allowfullscreen="true" style='width: 100%;'>Zie de pen <a href='https://codepen.io/azuremaps/pen/xxKgBVz/'>Get Shape Data</a> by Azure Maps (<a href='https://codepen.io/azuremaps'>@azuremaps</a>) op <a href='https://codepen.io'>CodePen</a>.
</iframe>
## <a name="next-steps"></a>Volgende stappen
Meer informatie over het gebruik van aanvullende functies van de module teken hulpprogramma's:
> [!div class="nextstepaction"]
> [Reageren op tekengebeurtenissen](drawing-tools-events.md)
> [!div class="nextstepaction"]
> [Interactietypen en sneltoetsen](drawing-tools-interactions-keyboard-shortcuts.md)
Meer informatie over de klassen en methoden die in dit artikel worden gebruikt:
> [!div class="nextstepaction"]
> [Kaart](https://docs.microsoft.com/javascript/api/azure-maps-control/atlas.map?view=azure-iot-typescript-latest)
> [!div class="nextstepaction"]
> [Drawing Manager](https://docs.microsoft.com/javascript/api/azure-maps-drawing-tools/atlas.drawing.drawingmanager?view=azure-node-latest)
> [!div class="nextstepaction"]
> [Werk balk tekenen](https://docs.microsoft.com/javascript/api/azure-maps-drawing-tools/atlas.control.drawingtoolbar?view=azure-node-latest)
|
public class UseStringMethods {
public static void main(String[] args) {
UseStringMethods stringMethods = new UseStringMethods();
String Str = "The String class represents character strings.";
String findStr = "string";
stringMethods.printWords(Str);
stringMethods.findString(Str,findStr);
stringMethods.findAnyCaseString(Str,findStr);
stringMethods.countChar(Str,'s');
stringMethods.printContainWords(Str,"ss");
}
// 문자열 단위로 나누기
public void printWords(String str){
String[] words = str.split(" ");
for(String tempStr : words){
System.out.println(tempStr);
}
}
// 해당 문자열이 나타나는지
public void findString(String str, String findStr){
int idx = str.indexOf(findStr);
if(idx != -1){
System.out.println(str + " is appeared at " + idx);
}
}
// 대소문자 상관없이 찾는 문자는 어디에서 시작위치인지
public void findAnyCaseString(String str, String findStr){
String lowerStr = str.toLowerCase();
String lowerFindStr = findStr.toLowerCase();
int idx = lowerStr.indexOf(lowerFindStr);
if(idx != -1){
System.out.println("string is appeared at " +idx );
}
}
// 해당 문자 몇개 있는지 확인
public void countChar(String str, char c){
char[] strArray = str.toCharArray();
int count = 0;
for(char tempChar : strArray){
if(tempChar == c){
count ++;
}
}
System.out.println("char \'" + c + "\' count is "+ count);
}
// 문자열 단위로 나눈후 찾는 문자열이 포함되는지
public void printContainWords(String str, String findStr){
String[] words = str.split(" ");
int count = 0;
for(String tempStr : words){
if(tempStr.contains(findStr)){
System.out.println(tempStr + " contains "+ findStr);
// count++;
}
}
// 해당 문자열이 여러개 있을 수 있어서 반복문 내에서 작동 안시킴
if(count != 0){
System.out.println("class contains "+ findStr);
}
}
}
|
using Microsoft.EntityFrameworkCore;
using Modelos.Models;
namespace Modelos.ApplicationContexts;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options) : base(options)
{
}
public DbSet<Empresa> Empresas { get; set; }
public DbSet<Gestion> Gestiones { get; set; }
public DbSet<Periodo> Periodos { get; set; }
public DbSet<Usuario> Usuarios { get; set; }
public DbSet<Moneda> Monedas { get; set; }
public DbSet<EmpresaMoneda> EmpresaMonedas { get; set; }
public DbSet<DetalleComprobante> DetalleComprobantes { get; set; }
public DbSet<Comprobante> Comprobantes { get; set; }
public DbSet<Cuenta> Cuentas { get; set; }
public DbSet<Nota> Nota { get; set; }
public DbSet<ArticuloCategoria> ArticuloCategoria { get; set; }
public DbSet<Articulo> Articulo { get; set; }
public DbSet<Categoria> Categoria { get; set; }
public DbSet<Lote> Lotes { get; set; }
public DbSet<Detalle> Detalle { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Comprobante>(entity =>
{
entity.Property(e => e.Tc)
.HasPrecision(18, 4);
});
modelBuilder.Entity<Articulo>(entity =>
{
entity.Property(e => e.PrecioVenta)
.HasPrecision(18, 4);
});
modelBuilder.Entity<DetalleComprobante>(entity =>
{
entity.Property(e => e.NombreCuenta)
.HasColumnType("nvarchar(max)");
});
modelBuilder.Entity<DetalleComprobante>(entity =>
{
entity.Property(e => e.MontoDebe).HasPrecision(18, 4);
entity.Property(e => e.MontoDebeAlt).HasPrecision(18, 4);
entity.Property(e => e.MontoHaber).HasPrecision(18, 4);
entity.Property(e => e.MontoHaberAlt).HasPrecision(18, 4);
});
modelBuilder.Entity<Lote>(entity =>
{
entity.Property(e=> e.PrecioCompra).HasPrecision(18, 4);
});
modelBuilder.Entity<Lote>()
.HasKey(l => new { l.IdLote, l.IdArticulo });
modelBuilder.Entity<Nota>()
.Property(n => n.IdComprobante)
.IsRequired(false);
modelBuilder.Entity<Detalle>()
.HasKey(d => new { d.IdArticulo, d.NroLote, d.IdNota });
modelBuilder.Entity<Nota>()
.Property(n => n.Total)
.HasPrecision(18, 4);
modelBuilder.Entity<Detalle>()
.Property(d => d.PrecioVenta)
.HasPrecision(18, 4);
#region Configuracion Empresa
modelBuilder.Entity<Empresa>().HasIndex(i => i.Sigla).IsUnique(false);
modelBuilder.Entity<Empresa>().HasIndex(i => i.Nombre).IsUnique(false);
modelBuilder.Entity<Empresa>().Property(i => i.IdUsuario)
.IsRequired(false);
modelBuilder.Entity<Empresa>().HasIndex(i => i.IdUsuario);
#endregion
#region Configuracion EmpresaMoneda
modelBuilder.Entity<EmpresaMoneda>()
.Property(em => em.Cambio)
.HasPrecision(18, 2);
#endregion
#region Configuracion de Relaciones
modelBuilder.Entity<Empresa>()
.HasOne(empresa => empresa.Usuario)
.WithMany(usuario => usuario.Empresas)
.HasForeignKey(empresa => empresa.IdUsuario);
modelBuilder.Entity<Empresa>().HasMany(e => e.Cuentas)
.WithOne(c => c.Empresa)
.HasForeignKey(c => c.IdEmpresa)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Gestion>()
.HasOne(gestion => gestion.Usuario)
.WithMany(usuario => usuario.Gestiones)
.HasForeignKey(gestion => gestion.IdUsuario)
.OnDelete(DeleteBehavior.NoAction);
modelBuilder.Entity<Periodo>()
.HasOne(p => p.Usuario)
.WithMany(u => u.Periodos)
.HasForeignKey(p => p.IdUsuario)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Periodo>()
.HasOne(p => p.Gestion)
.WithMany(g => g.Periodos)
.HasForeignKey(p => p.IdGestion)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Cuenta>().HasOne(cuenta => cuenta.Empresa)
.WithMany(empresa => empresa.Cuentas)
.HasForeignKey(cuenta => cuenta.IdEmpresa);
modelBuilder.Entity<Cuenta>().HasOne(cuenta => cuenta.IdCuentaPadreNavigation)
.WithMany(cuenta => cuenta.CuentasHijas)
.HasForeignKey(cuenta => cuenta.IdCuentaPadre)
.OnDelete(DeleteBehavior.NoAction);
modelBuilder.Entity<Moneda>().HasOne(m => m.Usuario)
.WithMany(u => u.Monedas)
.HasForeignKey(m => m.IdUsuario)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Comprobante>().HasOne(c => c.Usuario)
.WithMany(u => u.Comprobantes)
.HasForeignKey(c => c.IdUsuario)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Comprobante>().HasOne(c => c.Moneda)
.WithMany()
.HasForeignKey(c => c.IdMoneda)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Comprobante>().HasMany(c => c.DetalleComprobantes)
.WithOne(d => d.Comprobante)
.HasForeignKey(d => d.IdComprobante)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<DetalleComprobante>().HasOne(d => d.Usuario)
.WithMany(u => u.DetalleComprobantes)
.HasForeignKey(d => d.IdUsuario)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<DetalleComprobante>().HasOne(d => d.Comprobante)
.WithMany(c => c.DetalleComprobantes)
.HasForeignKey(d => d.IdComprobante)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<DetalleComprobante>().HasOne(d => d.Cuenta)
.WithMany(c => c.DetalleComprobantes)
.HasForeignKey(d => d.IdCuenta)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Usuario>().HasMany(u => u.EmpresaMonedas)
.WithOne(em => em.Usuario)
.HasForeignKey(em => em.IdUsuario)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Usuario>().HasMany(u => u.Comprobantes)
.WithOne(c => c.Usuario)
.HasForeignKey(c => c.IdUsuario)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Usuario>().HasMany(u => u.DetalleComprobantes)
.WithOne(d => d.Usuario)
.HasForeignKey(d => d.IdUsuario)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Usuario>().HasMany(u => u.Monedas)
.WithOne(m => m.Usuario)
.HasForeignKey(m => m.IdUsuario)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<EmpresaMoneda>().HasOne(em => em.Usuario)
.WithMany(u => u.EmpresaMonedas)
.HasForeignKey(em => em.IdUsuario)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<EmpresaMoneda>().HasOne(em => em.Empresa)
.WithMany(e => e.EmpresaMonedas)
.HasForeignKey(em => em.IdEmpresa)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<EmpresaMoneda>().HasOne(em => em.MonedaPrincipal)
.WithMany()
.HasForeignKey(em => em.IdMonedaPrincipal)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<EmpresaMoneda>().HasOne(em => em.MonedaAlternativa)
.WithMany()
.HasForeignKey(em => em.IdMonedaAlternativa)
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<Comprobante>().HasOne(comprobante => comprobante.Empresa)
.WithMany(empresa => empresa.Comprobantes)
.HasForeignKey(comprobante => comprobante.IdEmpresa)
.OnDelete(DeleteBehavior.NoAction);
#endregion
// Relación de uno a muchos entre Empresa y Categoria
modelBuilder.Entity<Categoria>()
.HasOne(categoria => categoria.Empresa)
.WithMany(empresa => empresa.HijosCategorias)
.HasForeignKey(categoria => categoria.IdEmpresa)
.OnDelete(DeleteBehavior.NoAction);
// Relación recursiva de uno a muchos entre Categoria y Categoria
modelBuilder.Entity<Categoria>()
.HasOne(categoria => categoria.IdCategoriaPadreNavigation)
.WithMany(categoria => categoria.HijosCategoria)
.HasForeignKey(categoria => categoria.IdCategoriaPadre)
.OnDelete(DeleteBehavior.NoAction);
// Relación entre usuario y categoria
modelBuilder.Entity<Categoria>()
.HasOne(c => c.Usuario)
.WithMany(u => u.HijosCategorias)
.HasForeignKey(c => c.IdUsuario)
.OnDelete(DeleteBehavior.NoAction);
// Relación entre Empresa y Usuario
modelBuilder.Entity<Empresa>()
.HasOne(e => e.Usuario)
.WithMany(u =>
u.Empresas) // Asegúrate de que "Empresas" es la colección correcta en la entidad Usuario
.HasForeignKey(e => e.IdUsuario)
.OnDelete(DeleteBehavior.NoAction);
// Relación entre usuario y categoria
modelBuilder.Entity<Usuario>()
.HasMany(u => u.HijosCategorias)
.WithOne(c => c.Usuario)
.HasForeignKey(c => c.IdUsuario)
.OnDelete(DeleteBehavior
.NoAction); // añade esta línea para evitar las eliminaciones en cascada
//configurando articulo
modelBuilder.Entity<Usuario>()
.HasMany(u => u.Articulos)
.WithOne(c => c.Usuario)
.HasForeignKey(c => c.IdUsuario)
.OnDelete(DeleteBehavior
.NoAction); // añade esta línea para evitar las eliminaciones en cascada
modelBuilder.Entity<Articulo>()
.HasOne(categoria => categoria.Empresa)
.WithMany(empresa => empresa.Articulos)
.HasForeignKey(categoria => categoria.IdEmpresa)
.OnDelete(DeleteBehavior.NoAction);
//configurando articulocategoria
modelBuilder.Entity<ArticuloCategoria>()
.HasKey(ac => new { ac.IdArticulo, ac.IdCategoria });
modelBuilder.Entity<ArticuloCategoria>()
.HasOne(ac => ac.Articulo)
.WithMany(a => a.ArticuloCategorias)
.HasForeignKey(ac => ac.IdArticulo);
modelBuilder.Entity<ArticuloCategoria>()
.HasOne(ac => ac.Categoria)
.WithMany(c => c.ArticuloCategorias)
.HasForeignKey(ac => ac.IdCategoria);
modelBuilder.Entity<Usuario>()
.HasMany(u => u.Notas)
.WithOne(c => c.Usuario)
.HasForeignKey(c => c.IdUsuario)
.OnDelete(DeleteBehavior.NoAction);
modelBuilder.Entity<Nota>()
.HasOne(categoria => categoria.Empresa)
.WithMany(empresa => empresa.Notas)
.HasForeignKey(categoria => categoria.IdEmpresa)
.OnDelete(DeleteBehavior.NoAction);
modelBuilder.Entity<Nota>()
.HasOne(categoria => categoria.Comprobante)
.WithMany(empresa => empresa.Notas)
.HasForeignKey(categoria => categoria.IdComprobante)
.OnDelete(DeleteBehavior.NoAction);
}
}
|
'use strict'
const requester = require('@utils/requester')
const { requestBodyGenerator } = require('@utils/requestBodyGenerator')
const { cacheSave, cacheGet, getKeys, getMessage, sendMessage } = require('@utils/redis')
const { v4: uuidv4 } = require('uuid')
const env = require('../envHelper')
const { send } = require('../telemetry')
const { createAuthorizationHeaderForBPP } = require('../utils/auth')
exports.search = async (req, res) => {
try {
const transactionId = uuidv4()
const messageId = uuidv4()
console.log("search")
console.log({transactionId})
const requestBody = requestBodyGenerator('bg_search', { keyword: req.query.keyword }, transactionId, messageId)
const rs = await requester.postRequest(
env.BECKN_BG_URI + '/search',
{},
requestBody,
{ shouldSign: true }
)
console.log(`search: `, rs.data)
send(requestBody.context, requestBody.message, rs.data)
setTimeout(async () => {
const data = await cacheGet(`${transactionId}:ON_SEARCH`)
if (!data) res.status(403).send({ message: 'No search data Found' })
else res.status(200).send({ data: data })
}, 25000)
} catch (err) {
console.log('err',err)
res.status(400).send({ status: false })
}
}
exports.onSearch = async (req, res) => {
console.log(`onSearch: `, req.body.context)
try {
const transactionId = req.body.context.transaction_id
const messageId = req.body.context.message_id
const data = await cacheGet(`${transactionId}:ON_SEARCH`)
if (data) {
data.push(req.body)
await cacheSave(`${transactionId}:ON_SEARCH`, data)
await cacheSave('LATEST_ON_SEARCH_RESULT', data)
} else {
await cacheSave(`${transactionId}:ON_SEARCH`, [req.body])
await cacheSave('LATEST_ON_SEARCH_RESULT', [req.body])
}
res.status(200).json({
"message": {
"ack": {
"status": "ACK"
}
}
})
} catch (err) {
}
}
exports.select = async (req, res) => {
try {
const transactionId = req.body.transaction_id
const messageId = uuidv4()
const bppUri = req.body.bpp_uri
const bppId = req.body.bpp_id
const itemId = req.body.item_id
const providerId = req.body.provider_id
const requestBody = requestBodyGenerator('bpp_select', { itemId, providerId, bppUri, bppId }, transactionId, messageId)
const endPoint = bppUri.endsWith("/") ? bppUri : bppUri + "/"
const rs = await requester.postRequest(
endPoint + 'select',
{},
requestBody,
{ shouldSign: true }
)
send(requestBody.context, requestBody.message, rs.data)
const message = await getMessage(`${transactionId}:ON_SELECT:MESSAGE`)
if (message !== transactionId)
return res.status(400).json({ message: 'Something Went Wrong (Redis Message Issue)' })
const data = await cacheGet(`${transactionId}:ON_SELECT`)
if (!data) return res.status(403).send({ message: 'No data Found' })
else return res.status(200).send({ data: data })
} catch (err) {
console.log(err)
res.status(400).send({ status: false })
}
}
exports.onSelect = async (req, res) => {
try {
const transactionId = req.body.context.transaction_id
await cacheSave(`${transactionId}:ON_SELECT`, req.body)
await sendMessage(`${transactionId}:ON_SELECT:MESSAGE`, transactionId)
res.status(200).json({
"message": {
"ack": {
"status": "ACK"
}
}
})
} catch (err) {
console.log(err)
}
}
exports.init = async (req, res) => {
try {
const transactionId = req.body.transaction_id
const messageId = uuidv4()
const bppUri = req.body.bpp_uri
const itemId = req.body.item_id
const providerId = req.body.provider_id
const endPoint = bppUri.endsWith("/") ? bppUri : bppUri + "/"
await requester.postRequest(
endPoint + 'init',
{},
requestBodyGenerator('bpp_init', { itemId, providerId }, transactionId, messageId),
{ shouldSign: true }
)
const message = await getMessage(`${transactionId}:ON_INIT:MESSAGE`)
if (message !== transactionId)
return res.status(400).json({ message: 'Something Went Wrong (Redis Message Issue)' })
const data = await cacheGet(`${transactionId}:ON_INIT`)
if (!data) return res.status(403).send({ message: 'No data Found' })
else return res.status(200).send({ data: data })
} catch (err) {
console.log(err)
res.status(400).send({ status: false })
}
}
exports.onInit = async (req, res) => {
console.log(`onInit: `, req.body)
try {
const transactionId = req.body.context.transaction_id
await cacheSave(`${transactionId}:ON_INIT`, req.body)
await sendMessage(`${transactionId}:ON_INIT:MESSAGE`, transactionId)
res.status(200).json({
"message": {
"ack": {
"status": "ACK"
}
}
})
} catch (err) {
console.log(err)
}
}
exports.confirm = async (req, res) => {
try {
const transactionId = req.body.transaction_id
const messageId = uuidv4()
const bppUri = req.body.bpp_uri
const itemId = req.body.item_id
const providerId = req.body.provider_id
const endPoint = bppUri.endsWith("/") ? bppUri : bppUri + "/"
await requester.postRequest(
endPoint + 'confirm',
{},
requestBodyGenerator('bpp_confirm', { itemId, providerId }, transactionId, messageId),
{ shouldSign: true }
)
const message = await getMessage(`${transactionId}:ON_CONFIRM:MESSAGE`)
if (message !== transactionId + messageId)
return res.status(400).json({ message: 'Something Went Wrong (Redis Message Issue)' })
const data = await cacheGet(`${transactionId}:ON_CONFIRM`)
if (!data) return res.status(403).send({ message: 'No data Found' })
res.status(200).send({ data: data })
} catch (err) {
console.log(err)
res.status(400).send({ status: false })
}
}
exports.onConfirm = async (req, res) => {
console.log(`onConfirm: `, req.body)
try {
const transactionId = req.body.context.transaction_id
const messageId = req.body.context.message_id
await cacheSave(`${transactionId}:ON_CONFIRM`, req.body)
await sendMessage(`${transactionId}:ON_CONFIRM:MESSAGE`, transactionId + messageId)
res.status(200).json({
"message": {
"ack": {
"status": "ACK"
}
}
})
} catch (err) {}
}
exports.cancel = async (req, res) => {
try {
const transactionId = req.body.transaction_id
const messageId = uuidv4()
const bppUri = req.body.bppUri
const orderId = req.body.orderId
const cancellation_reason_id = 1
const itemId = req.body.itemId
await requester.postRequest(
bppUri + '/cancel',
{},
requestBodyGenerator('bpp_cancel', { orderId, cancellation_reason_id }, transactionId, messageId),
{ shouldSign: true }
)
const message = await getMessage(`${transactionId}:${messageId}`)
if (message !== transactionId + messageId)
return res.status(400).json({ message: 'Something Went Wrong (Redis Message Issue)' })
const data = await cacheGet(`${transactionId}:${messageId}:ON_CANCEL`)
if (!data) return res.status(403).send({ message: 'No data Found' })
res.status(200).send({ data: data })
await cacheSave(`${bppUri}:${itemId}:ENROLLED`, false)
} catch (err) {
console.log(err)
res.status(400).send({ status: false })
}
}
exports.onCancel = async (req, res) => {
try {
const transactionId = req.body.context.transaction_id
const messageId = req.body.context.message_id
await cacheSave(`${transactionId}:${messageId}:ON_CANCEL`, req.body)
await sendMessage(`${transactionId}:${messageId}`, transactionId + messageId)
res.status(200).json({ status: true, message: 'BAP Received CANCELLATION From BPP' })
} catch (err) {}
}
exports.status = async (req, res) => {
try {
const transactionId = req.body.transaction_id
const messageId = uuidv4()
const bppUri = req.body.bppUri
const orderId = req.body.orderId
await requester.postRequest(
bppUri + '/status',
{},
requestBodyGenerator('bpp_status', { orderId }, transactionId, messageId),
{ shouldSign: true }
)
const message = await getMessage(`${transactionId}:${messageId}`)
if (message !== transactionId + messageId)
return res.status(400).json({ message: 'Something Went Wrong (Redis Message Issue)' })
const data = await cacheGet(`${transactionId}:${messageId}:ON_STATUS`)
if (!data) return res.status(403).send({ message: 'No data Found' })
res.status(200).send({ data: data })
} catch (err) {
console.log(err)
res.status(400).send({ status: false })
}
}
exports.onStatus = async (req, res) => {
try {
const transactionId = req.body.context.transaction_id
const messageId = req.body.context.message_id
await cacheSave(`${transactionId}:${messageId}:ON_STATUS`, req.body)
await sendMessage(`${transactionId}:${messageId}`, transactionId + messageId)
res.status(200).json({ status: true, message: 'BAP Received STATUS From BPP' })
} catch (err) {}
}
exports.userEnrollmentStatus = async (req, res) => {
try {
const bppUri = req.body.bppUri
const itemId = req.body.itemId
res.status(200).send({ isEnrolled: (await cacheGet(`${bppUri}:${itemId}:ENROLLED`)) ? true : false })
} catch (err) {}
}
exports.enrolledSessions = async (req, res) => {
try {
const enrollmentStatues = await getKeys('*:*:ENROLLED')
let collector = {}
await Promise.all(
enrollmentStatues.map(async (key) => {
const parts = key.split(':')
let itemId
let bppUri
if (parts.length === 5) {
bppUri = [parts[0], parts[1], parts[2]].join(':')
itemId = parts[3]
} else {
bppUri = [parts[0], parts[1]].join(':')
itemId = parts[2]
}
const session = await cacheGet(key)
if (session) {
//Probably Not Thread Safe
if (!collector[bppUri]) collector[bppUri] = [session]
else collector[bppUri].push(session)
}
})
)
res.status(200).send(collector)
} catch (err) {
}
}
exports.signHeader = async (req, res) => {
const message = req.body;
const header = await createAuthorizationHeaderForBPP(JSON.stringify(message))
res.status(200).send({header})
}
|
import knexConnect from "../database/knex/knexConnect.js";
import AppError from "../utils/AppError.js";
class FoodsController {
async index(request, response) {
const { id } = request.user;
function getAggregateFunction(columnName) {
const dbClient = knexConnect.client.config.client;
if (dbClient === "mysql" || dbClient === "sqlite3") {
return `GROUP_CONCAT(${columnName}.name) as ${columnName}`;
}
if (dbClient === "postgresql") {
return `STRING_AGG(${columnName}.name, ', ') as ${columnName}`;
}
throw new Error("Unsupported database client");
}
try {
const foodsQuery = knexConnect("foods")
.where("foods.users_id", id)
.select("foods.*")
.orderBy("foods.name", "asc");
const ingredientsQuery = knexConnect("foodsIngredients")
.select(
"food_id",
knexConnect.raw(getAggregateFunction("foodsIngredients")),
)
.groupBy("food_id");
const tagsQuery = knexConnect("foodsTags")
.select("food_id", knexConnect.raw(getAggregateFunction("foodsTags")))
.groupBy("food_id");
const [foods, ingredients, tags] = await Promise.all([
foodsQuery,
ingredientsQuery,
tagsQuery,
]);
const ingredientsMap = ingredients.reduce((acc, ingredient) => {
acc[ingredient.food_id] = ingredient.foodsIngredients;
return acc;
}, {});
const tagsMap = tags.reduce((acc, tag) => {
acc[tag.food_id] = tag.foodsTags;
return acc;
}, {});
const result = foods.map((food) => ({
...food,
foodsIngredients: ingredientsMap[food.id] || "",
foodsTags: tagsMap[food.id] || "",
}));
if (result.length === 0) {
throw new AppError("Não foram encontrados pratos cadastrados!", 200);
}
return response.json(result);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
console.error("Erro:", error.message);
throw new AppError(
error.message ||
"Não foi possível listar os pratos! Tente novamente mais tarde!",
error.statusCode || 500,
);
}
}
async show(request, response) {
const { id } = request.params;
try {
const food = await knexConnect("foods")
.select("foods.*")
.where("foods.id", id)
.first();
if (!food) {
throw new AppError("Prato não encontrado!", 404);
}
const ingredients = await knexConnect("foodsIngredients")
.select("name")
.where("food_id", id);
const tags = await knexConnect("foodsTags")
.select("name")
.where("food_id", id);
food.ingredients = ingredients.map((ingredient) => ingredient.name);
food.tags = tags.map((tag) => tag.name);
return response.status(200).json(food);
} catch (error) {
if (error instanceof AppError) {
throw error;
}
console.error("Erro:", error.message);
throw new AppError("Não foi possível mostrar o prato!");
}
}
async create(request, response) {
const { name, category, description, price, tags, ingredients } =
request.body;
const { id, role } = request.user;
if (id === undefined || role !== "admin") {
throw new AppError(
"Usuário sem autorização para cadastrar ou alterar produtos!",
401,
);
}
if (!name || typeof name !== "string" || name.trim() === "") {
throw new AppError(
"Nome do prato é obrigatório e não pode estar vazio!",
400,
);
}
if (!category || typeof category !== "string" || category.trim() === "") {
throw new AppError(
"Categoria do prato é obrigatória e não pode estar vazia!",
400,
);
}
if (
!description ||
typeof description !== "string" ||
description.trim() === ""
) {
throw new AppError(
"Descrição do prato é obrigatória e não pode estar vazia!",
400,
);
}
if (price === undefined || typeof price !== "number" || price <= 0) {
throw new AppError(
"Preço do prato é obrigatório e deve ser um número positivo!",
400,
);
}
if (!Array.isArray(tags) || tags.length === 0) {
throw new AppError(
"Tags são obrigatórias e devem ser um array não vazio!",
400,
);
}
if (!Array.isArray(ingredients) || ingredients.length === 0) {
throw new AppError(
"Ingredientes são obrigatórios e devem ser um array não vazio!",
400,
);
}
const food = {
name,
category,
description,
price,
users_id: Number(id),
};
const trx = await knexConnect.transaction();
try {
const [foodID] = await trx("foods").insert(food);
const foodsTags = tags.map((tag) => ({ name: tag, food_id: foodID }));
await trx("foodsTags").insert(foodsTags);
const foodIngredients = ingredients.map((ingredient) => ({
name: ingredient,
food_id: foodID,
}));
await trx("foodsIngredients").insert(foodIngredients);
await trx.commit();
} catch (error) {
await trx.rollback();
throw new AppError(`Não foi possível inserir o prato! ${error.message}`);
}
return response.status(201).json("Prato cadastrado com sucesso!");
}
async update(request, response) {
const { id: foodId } = request.params;
const { name, category, description, price, tags, ingredients } =
request.body;
const { id, role } = request.user;
if (id === undefined || role !== "admin") {
throw new AppError(
"Usuário sem autorização para cadastrar ou alterar produtos!",
401,
);
}
if (!name || typeof name !== "string" || name.trim() === "") {
throw new AppError(
"Nome do prato é obrigatório e não pode estar vazio!",
400,
);
}
if (!category || typeof category !== "string" || category.trim() === "") {
throw new AppError(
"Categoria do prato é obrigatória e não pode estar vazia!",
400,
);
}
if (
!description ||
typeof description !== "string" ||
description.trim() === ""
) {
throw new AppError(
"Descrição do prato é obrigatória e não pode estar vazia!",
400,
);
}
if (price === undefined || typeof price !== "number" || price <= 0) {
throw new AppError(
"Preço do prato é obrigatório e deve ser um número positivo!",
400,
);
}
if (!Array.isArray(tags) || tags.length === 0) {
throw new AppError(
"Tags são obrigatórias e devem ser um array não vazio!",
400,
);
}
if (!Array.isArray(ingredients) || ingredients.length === 0) {
throw new AppError(
"Ingredientes são obrigatórios e devem ser um array não vazio!",
400,
);
}
const food = {
name,
category,
description,
price,
users_id: Number(id),
};
const trx = await knexConnect.transaction();
try {
const updatedRows = await trx("foods").where({ id: foodId }).update(food);
if (updatedRows === 0) {
throw new AppError("Prato não encontrado!", 404);
}
await trx("foodsTags").where({ food_id: foodId }).del();
await trx("foodsIngredients").where({ food_id: foodId }).del();
const foodsTags = tags.map((tag) => ({ name: tag, food_id: foodId }));
await trx("foodsTags").insert(foodsTags);
const foodIngredients = ingredients.map((ingredient) => ({
name: ingredient,
food_id: foodId,
}));
await trx("foodsIngredients").insert(foodIngredients);
await trx.commit();
return response.status(200).json("Prato atualizado com sucesso!");
} catch (error) {
await trx.rollback();
console.error("Error during update:", error.message);
throw new AppError(
`Não foi possível atualizar o prato! ${error.message}`,
);
}
}
async delete(request, response) {
const { id } = request.params;
const { role } = request.user;
if (role !== "admin") {
throw new AppError("Usuário sem autorização para deletar produtos!", 401);
}
try {
const deletedRows = await knexConnect("foods").where({ id }).del();
if (deletedRows === 0) {
throw new AppError("Prato não encontrado!", 404);
}
return response
.status(200)
.json({ message: "Prato deletado com sucesso!" });
} catch (error) {
if (error.message) {
throw new AppError(error.message);
}
throw new AppError(`Não foi possível deletar o prato! ${error.message}`);
}
}
}
export default FoodsController;
|
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:pdv_app/utils/app_router.dart';
import '../model/sale.dart';
class SaleItem extends StatelessWidget {
final Sale sale;
const SaleItem({super.key, required this.sale});
@override
Widget build(BuildContext context) {
return Card(
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: const EdgeInsets.all(6),
child: FittedBox(
child: Text(
'R\$${(sale.product.preco * sale.quantity).toStringAsFixed(2)}',
),
),
),
),
title: Text(sale.product.nome),
subtitle: Text(
DateFormat('d/MM/y').format(sale.date),
),
trailing: Text(sale.paymentTypeString),
onTap: () {
Navigator.of(context).pushNamed(
AppRouter.showSale,
arguments: sale,
);
},
),
);
}
}
|
console.log("app.js")
const stompClient = new StompJs.Client({
brokerURL: 'ws://localhost:8090/chat-info'
});
stompClient.onConnect = (frame) => {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/messages', (data) => {
console.log("data: "+data)
showGreeting(JSON.parse(data.body).content);
});
};
stompClient.onWebSocketError = (error) => {
console.error('Error with websocket', error);
};
stompClient.onStompError = (frame) => {
console.error('Broker reported error: ' + frame.headers['message']);
console.error('Additional details: ' + frame.body);
};
function setConnected(connected) {
$("#connect").prop("disabled", connected);
$("#disconnect").prop("disabled", !connected);
if (connected) {
$("#conversation").show();
}
else {
$("#conversation").hide();
}
$("#greetings").html("");
}
function connect() {
console.log("connecting to stomp client")
// stompClient.activate();
}
function disconnect() {
stompClient.deactivate();
setConnected(false);
console.log("Disconnected");
}
function sendName() {
stompClient.publish({
destination: "/app/hello",
body: JSON.stringify({'name': $("#name").val()})
});
}
function showGreeting(message) {
$("#greetings").append("<tr><td>" + message + "</td></tr>");
}
// $(function () {
// $("form").on('submit', (e) => e.preventDefault());
// $( "#connect" ).click(() => connect());
// $( "#disconnect" ).click(() => disconnect());
// $( "#send" ).click(() => sendName());
// });
|
import React from "react";
import dribbble from "../assets/dribbble.png";
import linkedin from "../assets/linkedin.png";
import github from "../assets/github.png";
import { useNavigate } from "react-router-dom";
const Nav = () => {
const navigate = useNavigate();
return (
<div className="body">
<div className="nav-landing font-poppins text-white flex justify-between items-center">
<div className="left-side">
<h2 className="text-2xl sm:text-[30px] font-bold text-[#00E0FF] cursor-pointer" onClick={() => navigate("/")}>
Portofolio
</h2>
</div>
<div className="center-side hidden gap-[67px] sm:flex font-semibold sm:text-[20px]">
<h2 className="cursor-pointer" onClick={() => navigate("/skills")}>
Skills
</h2>
<h2 className="cursor-pointer" onClick={() => navigate("/projects")}>
Project
</h2>
<h2 className="cursor-pointer">Experience</h2>
<h2 className="cursor-pointer">Contact</h2>
</div>
<div className="right-side hidden gap-[30px] sm:flex ">
<img src={dribbble} className="w-[30px]" />
<img src={linkedin} className="w-[30px]" />
<img src={github} className="w-[30px]" />
</div>
<div className="dropdown dropdown-bottom dropdown-end sm:hidden">
<label tabIndex={0} className="btn btn-ghost btn-circle">
<svg xmlns="http://www.w3.org/2000/svg" className="h-7 w-7" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 6h16M4 12h16M4 18h7" />
</svg>
</label>
<ul tabIndex={0} className="dropdown-content z-20 menu p-2 shadow bg-base-100 rounded-box w-52">
<li>
<a>Skills</a>
</li>
<li>
<a>Project</a>
</li>
<li>
<a>Experience</a>
</li>
<li>
<a>Contact</a>
</li>
<li>
<a>Dribbble.com</a>
</li>
<li>
<a>LinkedIn</a>
</li>
<li>
<a>GitHub</a>
</li>
</ul>
</div>
</div>
</div>
);
};
export default Nav;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
<div style="display: flex;">
<div v-for="(attribute, index) in attributes">
<button :id="index" @click="changeColor(attribute, index)">{{attribute}}</button>
</div>
</div>
<div>You are chossing <span
style="color: yellow;background-color: red;">{{chossing}}</span></div>
</div>
</body>
<script type="module">
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
createApp({
data() {
return {
attributes: [
"home",
"about",
"service",
"contact us"
],
chossing: 'Hello Vue!',
preBut:null,
}
},
methods: {
changeColor(attribute, index) {
this.chossing = attribute;
if (this.preBut !== null) {
this.preBut.style.backgroundColor = "";
}
this.preBut=document.getElementById(index);
this.preBut.style.backgroundColor = "red";
}
}
}).mount('#app')
</script>
</html>
|
VZ-1 / VZ-10 (and possibly VZ-8) Sound Synthesis Elements
Voices
Each voice is created using (upto) 8 modules (M1 - M8) each consisting of a DCO and DCA.
Pairs of modules form internal lines:
M1 & M2 = Line A
M3 & M4 = Line B
M5 & M6 = Line C
M7 & M8 = Line D
M1 DCO1--DCA1--|
|-- Line A
M2 DCO2--DCA2--|
M3 DCO3--DCA3--|
|-- Line B
M4 DCO4--DCA4--|
M5 DCO5--DCA5--|
|-- Line C
M6 DCO6--DCA6--|
M7 DCO7--DCA7--|
|-- Line D
M8 DCO8--DCA8--|
Each line may be formed by combining the pair of modules thus [1..4(6..7)]:
Simple Sum: My + Mx
Ring Modulation: My + Mx x My
Phase Modulation: My(Mx)
The second of the pair of modules always feeds the line.
The first module may be mixed with the second module to feed the line.
The first module may phase modulate the second module.
The second module may ring modulate the first module. The output of the ring modulation is mixed with the second module to feed the line.
The second module may be phase modulated by the output of the previous Line [0(0..2)].
DCO
===
Each module has a DCO.
Each DCO waveform may be selected from: SINE / SAW1 / SAW2 / SAW3 / SAW4 / SAW5 / NOISE1 / NOISE2 [1..4(0..2,3..5)]
Increasing Sawtooth values have increasing quantity of harmonic content.
Noise 2 includes some fundamental pitch
Each DCO may be detuned +/-127 notes and +/-100 cent(63 x 1.6 cent steps). Alternatively the "harmonic" value may be set. Adjusting either the harmonic or the octave / note / fine values automatically adjusts the other. [5..20]
Each DCO may be set to a fixed frequency set by the Octave / note / fine settings and may be offset by the x16 switch.
DCA
===
Each module has a DCA.
Each DCA has an 8 step envelope.
A sustain point can be attached to one envelope step.
An end point can be attached to one envelope step. This clears remaining steps.
Depth of envelope can be set [175..182(0..6)]
There is a 6 step key follow curve to control the amplitude of each DCA.
Amplitude of each DCA may be affected by key velocity. Sensitivity and curve of key velocity may be set.
Sensitivity to envelope bias and tremolo can be adjusted for each DCA. These bias may be from after-touch, definable wheel 1/2 or foot VR. [165..172(0..3)]
Each module may be disabled [175..182(7)]
Global
======
DCO
There is an 8 step DCO envelope to control the pitch of all DCOs.
A sustain point can be attached to one envelope step.
An end point can be attached to one envelope step.
The scale of the pitch envelope can be adjusted with Range / Depth setting.
There is a 6 step key follow curve to control the pitch of all DCOs.
The key velocity control of pitch may be controlled setting sensitivity and curve.
Vibrato can be set globally for all DCO:
Waveform: Triangle / Sawtooth Up / Sawtooth Down / Square
Depth
Rate
Delay
Multi switch allows independent trigger of vibrato for each key
The octave can be set globally for all DCO.
DCA
Tremolo can be set globally for all DCO:
Waveform: Triangle / Sawtooth Up / Sawtooth Down / Square
Depth
Rate
Delay
Multi switch allows independent trigger of vibrato for each key
The overall amplitude / level can be set globally for all DCA. This is independent to synth volume control.
Each voice can be named up to 12 characters.
Common
There is a 6 step key follow rate curve which affects the rate at which keyboard follow will react for both DCOs and DCAs.
There is an 8 step key velocity rate curve which affects the rate at which keyboard velocity will react for both DCOs and DCAs.
Sensitivity
Curve
DCO steps to affect
DCA steps to affect
SYSEX
=====
Bits ABCDEFGH of 8-bit word with A=MSB
00 F,G,H = Ext phase M4,M6,M8
01 A,B = Line A: 0=Mix,1=Phase,2=Ring. C-E/F-H = M2/M1 Waveform: 0=Sine, 1-5=Saw1-5, 6-8=Noise1-2
02-04 Same as 01 for Line B-D and M3-8
05 A-F = M1 Fine detune. G = M1 Pitch fix. H = Range
06 A = M1 Detune polarity (1=+). B-H = Detune note(*1)
07-20 Same as 05 & 06 for M2-8
21 A = M1 DCA key velocity rate bias step 1 enable???. B-H = M1 DCA envelope step 1 rate(*2)
22-28 Same as 21 for M2-8
29 Same as 21 for DCO
30 A = M1 DCA envelope step 1 sustain point. B-H = M1 DCA envelope step 1 level(*3)
31-37 Same as 30 for M2-8
38 Same as 30 for DCO.(*4)
39-164 Same as 21-38 for envelope steps 2-8
165 B-D = M1 DCA envelope end (last step #). F-H = M1 Amp Sens (0-7)
166-172 Same as 165 for M2-8
173 B-D = DCO envelope end (last step #)
174 B-H Level(*5) [00~7F = 99~0]
175 A = M1 On/off. B-H = M1 DCA envelope depth(*5)
176-182 Same as 175 for M2-8
183 A = DCO range. C-H = DCO envelope depth(*6)
184 B-H M1 DCA key follow step 1 key(*7)
185 B-H M1 DCA key follow step 1 level(*5)
186-195 Same as 184 & 185 for steps 2-6
196-279 Same as 184-195 for M2-8
280 B-H = DCO key follow step 1 key(*7)
281 C-H = DCO key follow step 1 level(*6)
283-291 Same as 280 & 281 for steps 2-6
292 B-H = Key follow step 1 key(*7)
293 B-H = Key follow step 1 rate(*2)
294-303 Same as 292 & 293 for steps 2-6
304 A-C = M1 key velocity curve. D-H = M1 key velocity sensitivity
305-311 Same as 304 for M2-8
312 Same as 304 for DCO
313 Same as 304 for rate???
314 A = Octave polarity (1=+). B-C = Octave. E = Vibrato multi. G-H = Vibrato waveform [0=Triangle, 1=Sawtooth Up, 2=Sawtooth Down, 3=Square]
315 B-H = Vibrato depth
316 B-H = Vibrato rate
317 B-H = Vibrato delay
318 E = Tremolo mulit. G-H = Tremolo waveform [0=Triangle, 1=Sawtooth Up, 2=Sawtooth Down, 3=Square]
319 B-H Tremolo depth
320 B-H Tremolo rate
321 B-H Tremolo delay
322-333 Voice name (ASCII)
334-335 Not used
|
using GameEngine.GameComponents;
using GameEngine.Input;
using GameEngine.Utility.ExtensionMethods.ClassExtensions;
using GameEngine.Utility.ExtensionMethods.InterfaceFunctions;
using GameEngine.Utility.ExtensionMethods.PrimitiveExtensions;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace ExampleAStar
{
public class ExampleAStar : Game
{
public ExampleAStar()
{
Graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
Width = 50;
Height = 50;
TileWidth = 20;
Graphics.PreferredBackBufferWidth = (Width * 3 + 4) * TileWidth;
Graphics.PreferredBackBufferHeight = Height * TileWidth;
Rocks = new bool[Width,Height];
Grass = new List<Point>(Width * Height);
RockThreshold = 0.35f;
Search = 0;
HTerrain = new RectangleComponent[Width,Height];
HQ = new PriorityQueue<FDistancePoint,float>(Comparer<float>.Create((a,b) => a.CompareTo(b)));
HPrev = new Dictionary<Point,FDistancePoint>();
HDone = true;
ATerrain = new RectangleComponent[Width,Height];
AQ = new PriorityQueue<FDistancePoint,float>(Comparer<float>.Create((a,b) => a.CompareTo(b)));
APrev = new Dictionary<Point,FDistancePoint>();
ADone = true;
DTerrain = new RectangleComponent[Width,Height];
DQ = new PriorityQueue<DistancePoint,int>(Comparer<int>.Create((a,b) => a.CompareTo(b)));
DPrev = new Dictionary<Point,DistancePoint>();
DDone = true;
return;
}
protected override void LoadContent()
{
// Title will not persist if set in the constructor, so we'll set it here
Window.Title = "Zero-cost A* vs A* vs. Dijkstra";
Renderer = new SpriteBatch(GraphicsDevice);
Input = new InputManager();
Input.AddKeyInput("Escape",Keys.Escape);
Input.AddEdgeTriggeredInput("Exit","Escape",true);
Input.AddKeyInput("Space",Keys.Space);
Input.AddEdgeTriggeredInput("Step","Space",true);
Input.AddKeyInput("R",Keys.R);
Input.AddEdgeTriggeredInput("Run","R",true);
Input.AddKeyInput("F5",Keys.F5);
Input.AddEdgeTriggeredInput("Reset","F5",true);
GenerateRun();
return;
}
private void GenerateRun()
{
Components.Clear();
Components.Add(Input);
GenerateTerrain();
SetCaveToRocks();
SelectStartEnd();
InitializeH();
InitializeAStar();
InitializeDijkstra();
return;
}
private void GenerateTerrain()
{
Random rand = new Random();
for(int i = 0;i < Width;i++)
for(int j = 0;j < Height;j++)
{
Rocks[i,j] = rand.NextSingle() <= RockThreshold;
Components.Add(HTerrain[i,j] = new RectangleComponent(this,Renderer,TileWidth,TileWidth,Color.White));
HTerrain[i,j].Translate(new Vector2(TileWidth * i,TileWidth * j));
Components.Add(ATerrain[i,j] = new RectangleComponent(this,Renderer,TileWidth,TileWidth,Color.White));
ATerrain[i,j].Translate(new Vector2(TileWidth * (Width + 2 + i),TileWidth * j));
Components.Add(DTerrain[i,j] = new RectangleComponent(this,Renderer,TileWidth,TileWidth,Color.White));
DTerrain[i,j].Translate(new Vector2(TileWidth * (2 * Width + 4 + i),TileWidth * j));
}
return;
}
private void SetCaveToRocks()
{
Grass.Clear();
for(int i = 0;i < Width;i++)
for(int j = 0;j < Height;j++)
if(Rocks[i,j])
{
HTerrain[i,j].Tint = Color.Black;
ATerrain[i,j].Tint = Color.Black;
DTerrain[i,j].Tint = Color.Black;
}
else
{
Grass.Add(new Point(i,j));
HTerrain[i,j].Tint = Color.Green;
ATerrain[i,j].Tint = Color.Green;
DTerrain[i,j].Tint = Color.Green;
}
return;
}
private void SelectStartEnd()
{
if(Grass.Count < 2)
throw new Exception("What are you doing?");
Random rand = new Random();
int temp;
Source = Grass[temp = rand.Next(Grass.Count)];
// Move the random choice already made to the front to get it out of the way
Point ptemp = Grass[temp];
Grass[temp] = Grass[0];
Grass[0] = ptemp;
Destination = Grass[1 + rand.Next(Grass.Count - 1)];
HTerrain[Source.X,Source.Y].Tint = Color.Blue;
HTerrain[Destination.X,Destination.Y].Tint = Color.Red;
ATerrain[Source.X,Source.Y].Tint = Color.Blue;
ATerrain[Destination.X,Destination.Y].Tint = Color.Red;
DTerrain[Source.X,Source.Y].Tint = Color.Blue;
DTerrain[Destination.X,Destination.Y].Tint = Color.Red;
return;
}
private void InitializeH()
{
HQ.Clear();
HPrev.Clear();
HQ.Enqueue(new FDistancePoint(Source,0),Source.Distance(Destination));
HPrev[Source] = new FDistancePoint(null,0);
HDone = false;
return;
}
private void InitializeAStar()
{
AQ.Clear();
APrev.Clear();
AQ.Enqueue(new FDistancePoint(Source,0),Source.Distance(Destination));
APrev[Source] = new FDistancePoint(null,0);
ADone = false;
return;
}
private void InitializeDijkstra()
{
DQ.Clear();
DPrev.Clear();
DQ.Enqueue(new DistancePoint(Source,0),0);
DPrev[Source] = new DistancePoint(null,int.MinValue);
DDone = false;
return;
}
protected override void Update(GameTime delta)
{
// Quitting always gets priority
if(Input!["Exit"].CurrentDigitalValue)
Exit();
if(Input["Reset"].CurrentDigitalValue)
{
GenerateRun();
// We'll eat any other inputs
base.Update(delta);
return;
}
if(Input["Step"].CurrentDigitalValue)
Search = 1;
if(Input["Run"].CurrentDigitalValue)
if(Search > 0)
Search = 0;
else
Search = int.MaxValue;
if(Search > 0)
{
StepSearch();
Search--;
}
base.Update(delta);
return;
}
private void StepSearch()
{
if(!HDone)
StepH();
if(!ADone)
StepAStar();
if(!DDone)
StepDijkstra();
return;
}
private void StepH()
{
FDistancePoint next;
if(HQ.Count == 0 || (next = HQ.Dequeue()).Location!.Value == Destination)
{
MarkHPath();
HDone = true;
return;
}
// Skip visited vertices but don't count that as a step
// Also note that next.Location is never null
if(HPrev.TryGetValue(next.Location!.Value,out FDistancePoint me) && me.Visited)
{
StepH();
return;
}
// Mark ourselves as visited (structs are passed by value, so we need to assign it like so)
me.Visited = true;
HPrev[next.Location.Value] = me;
// Special case source coloring (can't get to destination here)
if(next.Location.Value != Source)
HTerrain[next.Location.Value.X,next.Location.Value.Y].Tint = Color.Cyan;
Point[] neighbors = new Point[] {next.Location.Value + new Point(0,1),next.Location.Value + new Point(0,-1),next.Location.Value + new Point(1,0),next.Location.Value + new Point(-1,0)};
foreach(Point p in neighbors)
{
// If we are out of bounds or if we've already found a shorter path to this neighbor, skip it
// If the neighbor has no predecessor, it is Source and we should skip it since you can't get to Source faster than starting there (this case should never come up)
// We also skip rocks
if(p.X < 0 || p.X >= Width || p.Y < 0 || p.Y >= Height || Rocks[p.X,p.Y] || HPrev.TryGetValue(p,out FDistancePoint n) && (n.Visited || n.Distance <= next.Distance + 1))
continue;
HQ.Enqueue(new FDistancePoint(p,next.Distance + 1),p.Distance(Destination));
HPrev[p] = new FDistancePoint(next.Location,next.Distance + 1);
// We shouldn't overwrite visited colors here since we skip visited vertices
if(p == Destination)
HTerrain[p.X,p.Y].Tint = Color.PaleVioletRed;
else
HTerrain[p.X,p.Y].Tint = Color.Purple;
}
return;
}
private void MarkHPath()
{
HTerrain[Destination.X,Destination.Y].Tint = Color.Red;
if(!HPrev.ContainsKey(Destination))
return;
FDistancePoint p = HPrev[Destination];
while(p.Location.HasValue && p.Location.Value != Source)
{
HTerrain[p.Location.Value.X,p.Location.Value.Y].Tint = Color.Yellow;
p = HPrev[p.Location.Value];
}
return;
}
private void StepAStar()
{
FDistancePoint next;
if(AQ.Count == 0 || (next = AQ.Dequeue()).Location!.Value == Destination)
{
MarkAPath();
ADone = true;
return;
}
// Skip visited vertices but don't count that as a step
// Also note that next.Location is never null
if(APrev.TryGetValue(next.Location!.Value,out FDistancePoint me) && me.Visited)
{
StepAStar();
return;
}
// Mark ourselves as visited (structs are passed by value, so we need to assign it like so)
me.Visited = true;
APrev[next.Location.Value] = me;
// Special case source coloring (can't get to destination here)
if(next.Location.Value != Source)
ATerrain[next.Location.Value.X,next.Location.Value.Y].Tint = Color.Cyan;
Point[] neighbors = new Point[] {next.Location.Value + new Point(0,1),next.Location.Value + new Point(0,-1),next.Location.Value + new Point(1,0),next.Location.Value + new Point(-1,0)};
foreach(Point p in neighbors)
{
// Grab the distance to p
int pdistance = next.Distance + 1;
float hpdistance = pdistance + p.Distance(Destination);
// If we are out of bounds or if we've already found a shorter path to this neighbor, skip it
// If the neighbor has no predecessor, it is Source and we should skip it since you can't get to Source faster than starting there (this case should never come up)
// We also skip rocks
if(p.X < 0 || p.X >= Width || p.Y < 0 || p.Y >= Height || Rocks[p.X,p.Y] || APrev.TryGetValue(p,out FDistancePoint n) && (n.Visited || n.Distance <= pdistance))
continue;
AQ.Enqueue(new FDistancePoint(p,pdistance),hpdistance);
APrev[p] = new FDistancePoint(next.Location,pdistance);
// We shouldn't overwrite visited colors here since we skip visited vertices
if(p == Destination)
ATerrain[p.X,p.Y].Tint = Color.PaleVioletRed;
else
ATerrain[p.X,p.Y].Tint = Color.Purple;
}
return;
}
private void MarkAPath()
{
ATerrain[Destination.X,Destination.Y].Tint = Color.Red;
if(!APrev.ContainsKey(Destination))
return;
FDistancePoint p = APrev[Destination];
while(p.Location.HasValue && p.Location.Value != Source)
{
ATerrain[p.Location.Value.X,p.Location.Value.Y].Tint = Color.Yellow;
p = APrev[p.Location.Value];
}
return;
}
private void StepDijkstra()
{
DistancePoint next;
if(DQ.Count == 0 || (next = DQ.Dequeue()).Location!.Value == Destination)
{
MarkDijkstraPath();
DDone = true;
return;
}
// Skip visited vertices but don't count that as a step
// Also note that next.Location is never null
if(DPrev.TryGetValue(next.Location!.Value,out DistancePoint me) && me.Visited)
{
StepDijkstra();
return;
}
// Mark ourselves as visited (structs are passed by value, so we need to assign it like so)
me.Visited = true;
DPrev[next.Location.Value] = me;
// Special case source coloring (can't get to destination here)
if(next.Location.Value != Source)
DTerrain[next.Location.Value.X,next.Location.Value.Y].Tint = Color.Cyan;
Point[] neighbors = new Point[] {next.Location.Value + new Point(0,1),next.Location.Value + new Point(0,-1),next.Location.Value + new Point(1,0),next.Location.Value + new Point(-1,0)};
foreach(Point p in neighbors)
{
// If we are out of bounds or if we've already found a shorter path to this neighbor, skip it
// If the neighbor has no predecessor, it is Source and we should skip it since you can't get to Source faster than starting there (this case should never come up)
// We also skip rocks
if(p.X < 0 || p.X >= Width || p.Y < 0 || p.Y >= Height || Rocks[p.X,p.Y] || DPrev.TryGetValue(p,out DistancePoint n) && (n.Visited || n.Distance <= next.Distance + 1))
continue;
DQ.Enqueue(new DistancePoint(p,next.Distance + 1),next.Distance + 1);
DPrev[p] = new DistancePoint(next.Location,next.Distance + 1);
// We shouldn't overwrite visited colors here since we skip visited vertices
if(p == Destination)
DTerrain[p.X,p.Y].Tint = Color.PaleVioletRed;
else
DTerrain[p.X,p.Y].Tint = Color.Purple;
}
return;
}
private void MarkDijkstraPath()
{
DTerrain[Destination.X,Destination.Y].Tint = Color.Red;
if(!DPrev.ContainsKey(Destination))
return;
DistancePoint p = DPrev[Destination];
while(p.Location.HasValue && p.Location.Value != Source)
{
DTerrain[p.Location.Value.X,p.Location.Value.Y].Tint = Color.Yellow;
p = DPrev[p.Location.Value];
}
return;
}
protected override void Draw(GameTime delta)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
Renderer!.Begin(SpriteSortMode.BackToFront);
base.Draw(delta);
Renderer.End();
return;
}
private GraphicsDeviceManager Graphics;
private SpriteBatch? Renderer;
private InputManager? Input;
private Point Source;
private Point Destination;
private int Search;
private readonly bool[,] Rocks;
private readonly List<Point> Grass;
private readonly float RockThreshold;
private readonly RectangleComponent[,] HTerrain;
private readonly PriorityQueue<FDistancePoint,float> HQ;
private readonly Dictionary<Point,FDistancePoint> HPrev;
private bool HDone;
private readonly RectangleComponent[,] ATerrain;
private readonly PriorityQueue<FDistancePoint,float> AQ;
private readonly Dictionary<Point,FDistancePoint> APrev;
private bool ADone;
private readonly RectangleComponent[,] DTerrain;
private readonly PriorityQueue<DistancePoint,int> DQ;
private readonly Dictionary<Point,DistancePoint> DPrev;
private bool DDone;
private readonly int Width;
private readonly int Height;
private readonly int TileWidth;
}
public struct DistancePoint : IEquatable<DistancePoint>
{
public DistancePoint(Point? loc, int dist)
{
Location = loc;
Distance = dist;
Visited = false;
return;
}
public static bool operator ==(DistancePoint a, DistancePoint b) => a.Location == b.Location;
public static bool operator !=(DistancePoint a, DistancePoint b) => !(a == b);
public bool Equals(DistancePoint other) => this == other;
public override bool Equals([NotNullWhen(true)] object? obj) => obj is DistancePoint p && this == p;
public override int GetHashCode() => HashCode.Combine(Location.GetHashCode(),Distance.GetHashCode());
public override string? ToString() => Location is null ? "NaL" : Location.ToString();
public Point? Location;
public int Distance;
public bool Visited;
}
public struct FDistancePoint : IEquatable<FDistancePoint>
{
public FDistancePoint(Point? loc, int dist)
{
Location = loc;
Distance = dist;
Visited = false;
return;
}
public static bool operator ==(FDistancePoint a, FDistancePoint b) => a.Location == b.Location;
public static bool operator !=(FDistancePoint a, FDistancePoint b) => !(a == b);
public bool Equals(FDistancePoint other) => this == other;
public override bool Equals([NotNullWhen(true)] object? obj) => obj is FDistancePoint p && this == p;
public override int GetHashCode() => HashCode.Combine(Location.GetHashCode(),Distance.GetHashCode());
public override string? ToString() => Location is null ? "NaL" : Location.ToString();
public Point? Location;
public int Distance;
public bool Visited;
}
}
|
import { vec3 } from "gl-matrix";
interface FormatStringOptions {
throwOnError?: boolean;
stringifyJSON?: boolean;
}
export function formatString(
str: string,
data: object,
options: FormatStringOptions = {}
) {
let inFormat = false;
let formatDepth = 0;
let formatValue = "";
let result = "";
for (let i = 0; i < str.length; i++) {
const char = str[i];
switch (char) {
case "$": {
if (inFormat) {
formatValue += char;
break;
}
inFormat = true;
break;
}
case "{": {
if (inFormat) {
formatDepth++;
if (formatDepth > 1) {
formatValue += char;
}
break;
}
result += char;
break;
}
case "}": {
if (!inFormat) {
result += char;
break;
}
formatDepth--;
if (formatDepth > 0) {
formatValue += char;
break;
}
inFormat = false;
let evalled: any;
try {
evalled = eval(formatValue);
} catch (e) {
if (options.throwOnError) {
throw e;
}
}
if (typeof evalled === "object" && options.stringifyJSON) {
result += JSON.stringify(evalled);
break;
}
result += evalled;
formatValue = "";
break;
}
default: {
if (inFormat) {
formatValue += char;
break;
}
result += char;
break;
}
}
}
return result;
}
export function raySphereIntersection(
ray_origin: vec3,
ray_dir: vec3,
sphere_origin: vec3,
sphere_radius: number
): number {
const ray_minus_sphere = vec3.sub(vec3.create(), ray_origin, sphere_origin);
const a = vec3.dot(ray_dir, ray_dir);
const b = 2 * vec3.dot(ray_dir, ray_minus_sphere);
const c =
vec3.dot(ray_minus_sphere, ray_minus_sphere) -
sphere_radius * sphere_radius;
const discriminant = b * b - 4 * a * c;
// if (discriminant < 0) {
// return -1;
// } else {
return (-b - Math.sqrt(discriminant)) / (2 * a);
// }
}
|
using System.Collections.ObjectModel;
using Ardalis.GuardClauses;
using FluentValidation.Results;
using OneOf;
using OneOf.Types;
using Payment.Bank.Application.Accounts.Features.ActivateAccount.v1;
using Payment.Bank.Common.Abstractions.Queries;
using Payment.Bank.Common.Abstractions.Commands;
using Payment.Bank.Application.Accounts.Features.CreateAccount.v1;
using Payment.Bank.Application.Accounts.Features.DeactivateAccount.v1;
using Payment.Bank.Application.Accounts.Features.GetAccount.v1;
namespace Payment.Bank.Application.Accounts.Services;
public class AccountService(
IQueryHandler<GetAccountQuery, OneOf<GetAccountResponse, ReadOnlyCollection<ValidationFailure>, NotFound>> getAccountQueryHandler,
ICommandHandler<CreateAccountCommand, OneOf<CreateAccountResponse, ReadOnlyCollection<ValidationFailure>>> createAccountCommandHandler,
ICommandHandler<ActivateAccountCommand, OneOf<ActivateAccountResponse, ReadOnlyCollection<ValidationFailure>, NotFound>> activateAccountCommandHandler,
ICommandHandler<DeactivateAccountCommand, OneOf<DeactivateAccountResponse, ReadOnlyCollection<ValidationFailure>, NotFound>> deactivateAccountCommandHandler)
: IAccountService
{
private readonly IQueryHandler<GetAccountQuery, OneOf<GetAccountResponse, ReadOnlyCollection<ValidationFailure>, NotFound>>
_getAccountQueryHandler = Guard.Against.Null(getAccountQueryHandler, nameof(getAccountQueryHandler));
private readonly ICommandHandler<CreateAccountCommand, OneOf<CreateAccountResponse, ReadOnlyCollection<ValidationFailure>>>
_createAccountCommandHandler = Guard.Against.Null(createAccountCommandHandler, nameof(createAccountCommandHandler));
private readonly ICommandHandler<ActivateAccountCommand, OneOf<ActivateAccountResponse, ReadOnlyCollection<ValidationFailure>, NotFound>>
_activateAccountCommandHandler = Guard.Against.Null(activateAccountCommandHandler, nameof(activateAccountCommandHandler));
private readonly ICommandHandler<DeactivateAccountCommand, OneOf<DeactivateAccountResponse, ReadOnlyCollection<ValidationFailure>, NotFound>>
_deactivateAccountCommandHandler = Guard.Against.Null(deactivateAccountCommandHandler, nameof(deactivateAccountCommandHandler));
public async Task<OneOf<GetAccountResponse, ValidationResult, NotFound>> GetAccountAsync(
GetAccountQuery query,
CancellationToken cancellationToken = default)
{
Guard.Against.Null(query, nameof(query));
var result = await this._getAccountQueryHandler.HandleAsync(query, cancellationToken).ConfigureAwait(false);
return result.Match<OneOf<GetAccountResponse, ValidationResult, NotFound>>(
getAccountResponse => getAccountResponse,
validationFailed => new ValidationResult(validationFailed),
notFound => notFound);
}
public async Task<OneOf<CreateAccountResponse, ValidationResult>> CreateAccountAsync(
CreateAccountCommand command,
CancellationToken cancellationToken = default)
{
Guard.Against.Null(command, nameof(command));
var result = await this._createAccountCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
return result.Match<OneOf<CreateAccountResponse, ValidationResult>>(
createAccountResponse => createAccountResponse,
validationFailed => new ValidationResult(validationFailed));
}
public async Task<OneOf<ActivateAccountResponse, ValidationResult, NotFound>> ActivateAccountAsync(
ActivateAccountCommand command,
CancellationToken cancellationToken = default)
{
Guard.Against.Null(command, nameof(command));
var result = await this._activateAccountCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
return result.Match<OneOf<ActivateAccountResponse, ValidationResult, NotFound>>(
activateAccountResponse => activateAccountResponse,
validationFailed => new ValidationResult(validationFailed),
notFound => notFound);
}
public async Task<OneOf<DeactivateAccountResponse, ValidationResult, NotFound>> DeactivateAccountAsync(DeactivateAccountCommand command, CancellationToken cancellationToken = default)
{
Guard.Against.Null(command, nameof(command));
var result = await this._deactivateAccountCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false);
return result.Match<OneOf<DeactivateAccountResponse, ValidationResult, NotFound>>(
deactivateAccountResponse => deactivateAccountResponse,
validationFailed => new ValidationResult(validationFailed),
notFound => notFound);
}
}
|
import { useState } from "react";
import CardContainer from "./CardContainer";
import CardTemplate from "./CardTemplate";
import { Button } from "@chakra-ui/react";
import { Song } from "../hooks/useSongs";
import SmallCard from "./smallcard";
interface props {
songs: Song[];
}
const RecSongs = ({ songs }: props) => {
const [itemsToShow, setItemsToShow] = useState(5);
const handleShowMore = () => {
setItemsToShow(itemsToShow + 5);
};
return (
<>
{songs.slice(0, 5).map((song) => (
<CardContainer key={song.id}>
<CardTemplate song={song} color="#1db954" />
</CardContainer>
))}
{songs.slice(5, itemsToShow).map((lsong) => (
<CardContainer key={lsong.id}>
<SmallCard color="#1db954" song={lsong}></SmallCard>
</CardContainer>
))}
{itemsToShow < songs.length && (
<Button onClick={handleShowMore} marginBottom="20px" marginLeft="20px">
Show More...
</Button>
)}
</>
);
};
export default RecSongs;
|
package User;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import java.util.Scanner;
public class UserNet {
static final String HOST = "127.0.0.1";
static final int PORT = 8000;
private static Scanner sc = new Scanner(System.in);
private static String input;
private static String name;
public static void main(String[] args) throws Exception {
System.out.println("Do you want to speak? Y/N");
input = sc.nextLine();
if (input.equalsIgnoreCase("Y")) {
System.out.println("Please enter your name");
name = sc.nextLine();
System.out.println("Welcome " + name + ".\n" +
"Type your message to chat or type \"quit\" to exit.\n");
chat(name);
} else if (input.equalsIgnoreCase("N")) {
System.out.println("Have a good day");
} else {
System.out.println("what do you want???");
}
}
private static void chat(String name) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel socketChannel) {
ChannelPipeline channelPipeline = socketChannel.pipeline();
channelPipeline.addLast(new StringDecoder());
channelPipeline.addLast(new StringEncoder());
channelPipeline.addLast(new UserHandler());
}
});
ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync();
while (sc.hasNext()) {
input = sc.nextLine();
if (input.equals("quit")) System.exit(0);
Channel channel = channelFuture.sync().channel();
channel.writeAndFlush(name + " says " + input);
channel.flush();
}
channelFuture.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
}
|
<div class="row">
<div class="col-lg-12">
<div class="add-user-component">
<div class="card card-main">
<div class="card-header card-header-main download-report">
<div class="row">
<div class="col-auto mr-auto">Portfolio Company List</div>
<div class="col-auto">
<a [routerLink]="['/add-portfolio-company']" class="btn btn-primary"
title="Add Portfolio Company"
[hideIfUnauthorized]='{featureId:feature.PortfolioCompany,action:"add"}'>
<fa name="plus-square"></fa> <span class="hide-on-mobile">Portfolio Company</span>
</a>
</div>
</div>
</div>
<div class="card-body">
<div class="ui-widget-header" style="padding:4px 10px;border-bottom: 0 none;text-align: left !important">
<div class="row">
<div class="col-8 col-lg-5 mr-auto search"> <span class="fa fa-search"></span>
<input #gb type="text" pInputText placeholder="Search" class="form-control search-box"
[(ngModel)]="globalFilter">
</div>
<div class="col-auto col-sm-auto align-self-center m-download" [hideIfUnauthorized]='{featureId:feature.PortfolioCompany,action:"export"}'>
<p-splitButton icon="fa fa-download" [model]="exportItems" title="Export Files" tabindex="1">
</p-splitButton>
</div>
</div>
</div>
<p-dataTable [reorderableColumns]="true" #tblPortfolio
emptyMessage="{{blockedTable? 'Please Wait...':'No record found'}}"
[totalRecords]="totalRecords" [value]="pcs" [lazy]="true"
(onLazyLoad)="loadPortfolioLazy($event)" [rows]="10" [paginator]="true" [responsive]="true"
[rowsPerPageOptions]="pagerLength" [globalFilter]="gb" sortMode="multiple">
<p-column field="companyName" header="Company Name" [sortable]="true">
<ng-template pTemplate="body" let-pc="rowData"> <a class="click-view company-name"
href="javascript:void(0);"
[routerLink]="['/portfolio-company-detail', pc.encryptedPortfolioCompanyId]"
title="View Details"
[hideIfUnauthorized]='{featureId:feature.PortfolioCompany,action:"view"}'>{{pc.companyName}}</a>
</ng-template>
</p-column>
<p-column field="Sector.Sector" header="Sector" [sortable]="true">
<ng-template pTemplate="body" let-pc="rowData"> {{pc.sectorDetail?.sector}} </ng-template>
</p-column>
<p-column field="SubSector.SubSector" header="Sub-Sector" [sortable]="true">
<ng-template pTemplate="body" let-pc="rowData"> {{pc.subSectorDetail?.subSector}}
</ng-template>
</p-column>
<p-column field="MappingPCGeographicLocation.Min(Country.Country)" header="Headquarter"
[sortable]="true">
<ng-template pTemplate="body" let-pc="rowData"> <span *ngIf="pc.geographicLocations"><span
*ngIf="pc.geographicLocations[0]?.region !=null">
{{ pc.geographicLocations[0].region?.region }},</span>{{ pc.geographicLocations[0]?.country?.country }}<span
*ngIf="pc.geographicLocations[0]?.state !=null">,
{{ pc.geographicLocations[0].state?.state }}</span><span
*ngIf="pc.geographicLocations[0]?.city!=null">,
{{ pc.geographicLocations[0].city?.city }}</span></span>
</ng-template>
</p-column>
<p-column field="website" header="Website" [sortable]="true">
<ng-template pTemplate="body" let-pc="rowData"> <a title="View Website"
href="//{{pc.website}}" target="_blank">{{pc.website}}</a> </ng-template>
</p-column>
<p-column styleClass="col-button" header="Action">
<ng-template pTemplate="body" let-pc="rowData">
<div class="add-control-btn text-center">
<a class="btn btn-edit" title="Edit"
[routerLink]="['/add-portfolio-company', pc.encryptedPortfolioCompanyId]"
[hideIfUnauthorized]='{featureId:feature.PortfolioCompany,action:"edit"}'>
<fa name="edit"></fa>
</a>
</div>
</ng-template>
</p-column>
</p-dataTable>
</div>
</div>
</div>
</div>
</div>
|
#include <stdio.h>
// Function to find the maximum of two integers
int max(int a, int b) {
return (a > b) ? a : b;
}
// Function to solve the Knapsack problem using dynamic programming
int knapsack(int W, int wt[], int val[], int n) {
int i, w;
int K[n + 1][W + 1];
// Build table K[][] in bottom-up manner
for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0)
K[i][w] = 0;
else if (wt[i - 1] <= w)
K[i][w] = max(val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]);
else
K[i][w] = K[i - 1][w];
}
}
// Return the maximum value that can be put in a knapsack of capacity W
return K[n][W];
}
int main() {
int n, W;
// Input number of items
printf("Enter the number of items: ");
scanf("%d", &n);
int val[n], wt[n];
// Input values and weights of the items
printf("Enter the values of the items:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &val[i]);
}
printf("Enter the weights of the items:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &wt[i]);
}
// Input the maximum capacity of the knapsack
printf("Enter the maximum capacity of the knapsack: ");
scanf("%d", &W);
// Calculate and print the maximum value that can be put in the knapsack
printf("The maximum value that can be put in the knapsack is %d\n", knapsack(W, wt, val, n));
return 0;
}
|
import tkinter as tk
import turtle
from pathlib import Path
import tqdm
from l_system.base import Lsystem
from l_system.rendering.turtle import LSystemTurtle, TurtleConfiguration
class LSystemRenderer:
def __init__(
self,
l_system: Lsystem,
turtle_configuration: TurtleConfiguration,
title: str | None = None,
width: int = 400,
height: int = 400,
):
"""
Renders an L-system (`l_system`) on screen using`turtle` graphics.
Args:
l_system: An instantiated L-System object.
turtle_configuration: A configuration object for the turtle rendering.
title: Title of the rendering window.
width: Window width.
height: Window height.
"""
self.lsystem = l_system
self.title = title if title is not None else l_system.name()
self.width = width
self.height = height
self._turtle_conf = turtle_configuration
self.lsystem.apply()
self._turtle = LSystemTurtle(
self.width,
self.height,
delta=self._turtle_conf.angle,
forward_step=self._turtle_conf.forward_step,
speed=self._turtle_conf.speed,
heading=self._turtle_conf.initial_heading_angle,
fg_color=self._turtle_conf.fg_color,
bg_color=self._turtle_conf.bg_color,
)
def draw(self, animate: bool = True, save_to_eps_file: Path | None = None) -> None:
"""
Draw the L-system on screen using the `turtle` Python module.
Args:
animate: Will show turtle animations if set to `True`, otherwise it will render the final state of the
L-System without any animations.
save_to_eps_file: If a `Path` object provided, it will save the rendered L-System to an `eps` file. If set
to `None` it will only render the L-System without storing it.
"""
try:
self._update_world_coordinates()
self._turtle.animate(animate)
self._run_all_moves()
self._turtle.hideturtle()
self._turtle.update()
if save_to_eps_file:
self._turtle.save_to_eps(f"{save_to_eps_file}.eps")
self._turtle.mainloop()
except (turtle.Terminator, tk.TclError):
print("Exiting...")
self._turtle.bye()
def _run_all_moves(self) -> None:
"""Runs all the `turtle` moves of the L-system."""
for i, l_str in tqdm.tqdm(
enumerate(self.lsystem, start=1),
total=len(self.lsystem),
desc=f"Rendering L-System '{self.lsystem.name()}'",
):
self._turtle.set_title(f"{self.title} | {100*(i/len(self.lsystem)):.0f} %")
k = self._turtle_conf.turtle_move_mapper.get(l_str, l_str)
self._turtle.move(k)
def _update_world_coordinates(self) -> None:
"""Updates the `turtle` world coordinates by first running the `turtle` on the L-System to find min, max
coordinates. Then it uses these values to make sure the final L-System is visible in the window."""
self._turtle.animate(False)
self._run_all_moves()
minx, miny, maxx, maxy = self._turtle.bounding_box.to_tuple()
w = maxx - minx
h = maxy - miny
epsilon = 0.00001
r = max(w, h) / (min(w, h) + epsilon)
if maxx - minx > maxy - miny:
self._turtle.screen.setworldcoordinates(minx, miny - 1, maxx, (maxy - 1) * r)
else:
self._turtle.screen.setworldcoordinates(minx, miny, maxx * r, maxy)
self._turtle.reset()
|
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ include file="layout/header.jsp" %>
<div class="py-5" style="background-color: #F9F9F9" id="main-container">
<c:forEach var="mainIntroduce" items="${mainIntroduceList}" varStatus="status">
<c:choose>
<c:when test="${status.index % 2 == 0}">
<div class="container post-container ps-5" style="height:450px" data-index="${status.index + 1}" id="content-${mainIntroduce.id}">
<div class="row">
<div class="col-5 me-5">
<img src="${mainIntroduce.imgURL}" id="postImage-${mainIntroduce.id}" alt="Description of Image" class="img-fluid responsive-image">
</div>
<div class="col-5 pt-3">
<h2 id="postTitle-${mainIntroduce.id}">${mainIntroduce.postTitle}</h2><hr>
<div id="postContent-${mainIntroduce.id}">${mainIntroduce.postContent}</div>
</div>
<div class="col-2">
</div>
</div>
<div class="edit-controls" style="display: none;">
<div class="my-3 me-5 d-flex justify-content-end">
<button type="button" class="btn btn-outline-secondary me-2" onclick="updateForm(event, ${mainIntroduce.id}, ${status.index + 1})">수정하기</button>
<button type="button" class="btn btn-outline-danger me-5" onclick="deletePost(${mainIntroduce.id})">삭제하기</button>
</div>
</div>
</div>
</c:when>
<c:otherwise>
<div class="container post-container pe-5" style="height:450px" data-index="${status.index + 1}" id="content-${mainIntroduce.id}">
<div class="row">
<div class="col-1">
</div>
<div class="col-5 pt-3">
<h2 id="postTitle-${mainIntroduce.id}">${mainIntroduce.postTitle}</h2><hr>
<div id="postContent-${mainIntroduce.id}">${mainIntroduce.postContent}</div>
</div>
<div class="col-5 ms-5">
<img src="${mainIntroduce.imgURL}" id="postImage-${mainIntroduce.id}" alt="Description of Image" class="img-fluid responsive-image">
</div>
</div>
<div class="edit-controls" style="display: none;">
<div class="my-3 me-1 d-flex justify-content-end">
<button type="button" class="btn btn-outline-secondary me-2" onclick="updateForm(event, ${mainIntroduce.id}, ${status.index + 1})">수정하기</button>
<button type="button" class="btn btn-outline-danger me-5" onclick="deletePost(${mainIntroduce.id})">삭제하기</button>
</div>
</div>
</div>
</c:otherwise>
</c:choose>
</c:forEach>
<div id="postBox">
</div>
<!-- 새 글 쓰기 -->
<div class="edit-controls" style="display: none;">
<div class="container mt-5" style="width: 1100px">
<form id="postForm">
<div class="mb-3">
<label for="postTitle" class="form-label">제목</label>
<input type="text" class="form-control" id="postTitle-new" placeholder="제목을 입력하세요">
</div>
<div class="mb-3">
<label for="postContent" class="form-label">내용</label>
<textarea class="form-control" id="postContent-new" rows="7" placeholder="내용을 입력하세요"></textarea>
</div>
<div class="mb-3">
<label for="postImage" class="form-label">사진 업로드</label>
<input type="file" id="fileInput-new">
<div id="imagePreview" class="mt-3"></div>
</div>
<div class="my-3 d-flex justify-content-end">
<button type="button" class="btn btn-primary" onclick="addPost()">글 등록하기</button>
</div>
</form>
</div>
</div>
<!-- 새 글 쓰기 -->
<script src="/js/mainpage.js"></script>
<%@ include file="layout/footer.jsp" %>
|
package com.itheima.reggie.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;
/*
全局异常处理
*/
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/*
异常处理方法
*/
@ExceptionHandler(SQLIntegrityConstraintViolationException.class)
public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
log.error(e.getMessage());
if (e.getMessage().contains("Duplicate entry")){
String[] split = e.getMessage().split(" ");
String msg = split[2] + "已经存在";
return R.error(msg);
}
return R.error("未知错误,请联系管理员");
}
@ExceptionHandler(CustomException.class)
public R<String> exceptionHandler(CustomException e){
log.error(e.getMessage());
return R.error(e.getMessage());
}
}
|
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Announcement>
*/
class AnnouncementFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
"user_id" => User::all()->random()->id,
"title" => $this->faker->persianText(40),
"summary" => $this->faker->persianParagraph(),
"slug" => $this->faker->slug(),
"image" => $this->faker->image(),
"body" => $this->faker->persianText(2000),
"published_at" => $this->faker->date(),
"views_count" => $this->faker->numberBetween(1, 1000),
"status" => $this->faker->boolean(),
];
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.