text stringlengths 184 4.48M |
|---|
@page "/fetchdata"
@inject HttpClient Http
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class='table'>
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}
@functions {
WeatherForecast[] forecasts;
protected override async Task OnInitAsync()
{
forecasts = await Http.GetJsonAsync<WeatherForecast[]>("/sample-data/weather.json");
}
class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF { get; set; }
public string Summary { get; set; }
}
} |
# AMD Threadripper CPU Usage Monitor
# Copyright (C) 2018 Denis Steckelmacher <steckdenis@yahoo.fr>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import wmi
import win32pdh
import win32pdhutil
import win32pdhquery
def get_cpu_name(all_known_names):
""" Use WMI to get the processor name
"""
p = wmi.WMI().Win32_Processor()[0]
parts = p.name.split()
print(parts)
if 'Ryzen' in parts or 'EPYC' in parts:
for name in all_known_names:
if name in parts:
return name, 'EPYC' in parts
return None, False
class Statistics:
""" Get CPU usage and power consumption statistics
"""
def __init__(self, tr4, usage_chart, power_chart, num_cores):
""" Initialize the class. tr4 is a TR4Viewer object that is updated with
usage information. usage_chart and power_chart are DynamicChart instances
that displayed summarized power and usage values.
"""
self.tr4 = tr4
self.power = power_chart
self.usage = usage_chart
self.num_cores = num_cores
# Open the core usage statistics
self.query = win32pdhquery.Query()
processor = win32pdhutil.find_pdh_counter_localized_name('Processor') # Oh my goodness... Windows...
cputime = win32pdhutil.find_pdh_counter_localized_name('% Processor Time')
for i in range(num_cores):
self.query.rawaddcounter(processor, cputime, str(i))
self.query.open()
def update(self):
""" Update statistics
"""
# Get CPU usage
total_use = 0
total_cpus = 0
for i, percent in enumerate(self.query.collectdata()):
if percent == -1:
break # Got past the end of the CPUs actually present in the system
self.tr4.cores[i // 2].setUsage(i % 2, percent)
total_use += percent
total_cpus += 1
if total_cpus > 0:
# The first reading is invalid, so total_cpus will be zero
self.usage.addReading(0, total_use / total_cpus) |
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import faker from '@faker-js/faker';
import { createMockMsalServices } from '@mocks/msal.service.mock';
import { UserRole } from '@models/enums';
import { IdentityResultAlpha, IdentityResultAlphaBatch } from '@models/identity-query.model';
import { UserModel } from '@models/user.model';
import { NgxsModule, Store } from '@ngxs/store';
import { createMockLoggerService } from '@services/logger/logger.service.mock';
import { UserState } from '@shared/state/user/user.state';
import { of } from 'rxjs';
import { WoodstockGiftingState } from './state/woodstock-gifting.state';
import { SetWoodstockGiftingMatTabIndex } from './state/woodstock-gifting.state.actions';
import { WoodstockGiftingComponent } from './woodstock-gifting.component';
import { createStandardTestModuleMetadataMinimal } from '@mocks/standard-test-module-metadata-minimal';
describe('WoodstockGiftingComponent', () => {
let component: WoodstockGiftingComponent;
let fixture: ComponentFixture<WoodstockGiftingComponent>;
let mockStore: Store;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule(
createStandardTestModuleMetadataMinimal({
imports: [
RouterTestingModule.withRoutes([]),
HttpClientTestingModule,
NgxsModule.forRoot([UserState, WoodstockGiftingState]),
],
declarations: [WoodstockGiftingComponent],
schemas: [NO_ERRORS_SCHEMA],
providers: [...createMockMsalServices(), createMockLoggerService()],
}),
).compileComponents();
fixture = TestBed.createComponent(WoodstockGiftingComponent);
component = fixture.debugElement.componentInstance;
mockStore = TestBed.inject(Store);
mockStore.dispatch = jasmine.createSpy('dispatch');
}));
it('should create', () => {
expect(component).toBeTruthy();
});
describe('Method: ngOnInit', () => {
beforeEach(() => {
mockStore.selectSnapshot = jasmine.createSpy('selectSnapshot').and.returnValue({
emailAddress: faker.internet.email(),
role: UserRole.LiveOpsAdmin,
name: faker.random.word(),
objectId: faker.datatype.uuid(),
} as UserModel);
});
describe('When selectedPlayerIdentities$ outputs a selection', () => {
const gamertag = faker.random.word();
const identity: IdentityResultAlpha = {
query: null,
gamertag: gamertag,
};
beforeEach(() => {
Object.defineProperty(component, 'selectedPlayerIdentities$', { writable: true });
component.selectedPlayerIdentities$ = of([identity] as IdentityResultAlphaBatch);
});
it('should set selected player', () => {
component.ngOnInit();
expect(component.selectedPlayerIdentities).not.toBeUndefined();
expect(component.selectedPlayerIdentities.length).toEqual(1);
expect(component.selectedPlayerIdentities[0].gamertag).toEqual(gamertag);
});
});
});
describe('Method: matTabSelectionChange', () => {
const testIndex: number = 1;
it('should displatch SetApolloGiftingMatTabIndex with correct data', () => {
component.matTabSelectionChange(testIndex);
expect(mockStore.dispatch).toHaveBeenCalledWith(
new SetWoodstockGiftingMatTabIndex(testIndex),
);
});
});
// describe('Method: onPlayerIdentitiesChange', () => {
// let event: IdentityResultAlphaBatch;
// beforeEach(() => {
// event = [
// {
// query: undefined,
// xuid: new BigNumber(123456789),
// },
// ];
// });
// it('should displatch SetWoodstockGiftingSelectedPlayerIdentities with correct data', () => {
// component.onPlayerIdentitiesChange(event);
// expect(mockStore.dispatch).toHaveBeenCalledWith(
// new SetWoodstockGiftingSelectedPlayerIdentities(event),
// );
// });
// });
}); |
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { APP_BASE_HREF } from '@angular/common';
import { AppModule } from '../../../../../app.module';
import { SettingsModule } from '../../../settings.module';
import { FuelFilterComponent } from './fuel-filter.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { configureTestSuite } from 'ng-bullet';
describe('FuelFilterComponent', () => {
let component: FuelFilterComponent;
let fixture: ComponentFixture<FuelFilterComponent>;
let dataValue;
configureTestSuite(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule, AppModule, SettingsModule, HttpClientTestingModule],
declarations: [],
providers: [{ provide: APP_BASE_HREF, useValue: '/' }]
});
});
beforeEach(() => {
dataValue = [{
'label': 'National',
'value': 'National'
}];
fixture = TestBed.createComponent(FuelFilterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should call ngOnInit', () => {
component.ngOnInit();
});
it('should call afterPanelToggle', () => {
component.afterPanelToggle(true, 'fuelPrice');
});
it('should call onListingItemsSelected', () => {
component.onListingItemsSelected(dataValue, 'source');
});
it('should call onListingItemsSelected-else', () => {
component.onListingItemsSelected([], 'source');
});
it('should call onClearAllFilters', () => {
component.onClearAllFilters();
});
it('should call resetSource', () => {
component.resetSource(true);
});
it('should call resetSource-else', () => {
component.resetSource(false);
});
it('should call resetRegion', () => {
component.resetRegion(true);
});
it('should call resetRegion-else', () => {
component.resetRegion(false);
});
it('should call isSourceCollapsed', () => {
component.isSourceCollapsed(true);
});
it('should call isSourceCollapsed-else', () => {
component.isSourceCollapsed(false);
});
it('should call isRegionCollapsed', () => {
component.isRegionCollapsed(true);
});
it('should call isRegionCollapsed-else', () => {
component.isRegionCollapsed(false);
});
it('should call validateCurrency', () => {
component.validateCurrency('4');
});
it('should call validateCurrency-else', () => {
component.validateCurrency('');
});
it('should call amountValidator', () => {
component.amountValidator('yes');
});
it('should call formatAmount', () => {
component.formatAmount('test');
});
it('should call formatAmount-else if', () => {
component.formatAmount('124.890');
});
it('should call clearAmount', () => {
component.clearAmount();
});
it('should call onCreateDate-time', () => {
component.filterModel.createdOnDate = '05-08-2019';
component.filterModel.createdOnTime = '03:14:07.999999';
component.onCreateDate();
});
it('should call onCreateDate', () => {
component.filterModel.createdOnDate = '05-08-2019';
component.filterModel.createdOnTime = '';
component.onCreateDate();
});
it('should call onCreateDate-else', () => {
component.filterModel.createdOnDate = '';
component.filterModel.createdOnTime = '';
component.onCreateDate();
});
it('should call onCreateTime', () => {
component.filterModel.createdOnDate = '05-08-2019';
component.filterModel.createdOnTime = '03:14:07.999999';
component.onCreateTime();
});
it('should call onCreateTime-else', () => {
component.filterModel.createdOnDate = '';
component.filterModel.createdOnTime = '';
component.onCreateTime();
});
it('should call onUpdateDate-time', () => {
component.filterModel.updatedOnDate = '05-08-2019';
component.filterModel.updatedOnTime = '03:14:07.999999';
component.onUpdateDate();
});
it('should call onUpdateDate', () => {
component.filterModel.updatedOnDate = '05-08-2019';
component.filterModel.updatedOnTime = '';
component.onUpdateDate();
});
it('should call onUpdateDate-else', () => {
component.filterModel.updatedOnDate = '';
component.filterModel.updatedOnTime = '';
component.onUpdateDate();
});
it('should call onUpdateTime', () => {
component.filterModel.updatedOnDate = '05-08-2019';
component.filterModel.updatedOnTime = '03:14:07.999999';
component.onUpdateTime();
});
it('should call onUpdateTime-else', () => {
component.filterModel.updatedOnDate = '';
component.filterModel.updatedOnTime = '';
component.onUpdateTime();
});
it('should call clearDateValues', () => {
component.clearDateValues('test1', 'test2', 'test3');
});
it('should call dateRadioToggle', () => {
component.dateRadioToggle(true, 'test1', 'test2', 'test3', 'test4', 'test5', 'test6');
});
it('should call clearDate', () => {
component.clearDate('effectiveEndDate', 'effectiveStartDate', 'effectiveDateValue', 'effectiveDate', 'defaultSelect',
'effDateOnlyFlag', 'effectiveCheck');
});
it('should call matchExactDate', () => {
component.matchExactDate(true);
});
it('should call matchExactDate-else', () => {
component.matchExactDate(false);
});
it('should call effectiveKeyFinder', () => {
component.effectiveKeyFinder();
});
it('should call expirationMatchExactDate', () => {
component.expirationMatchExactDate(true);
});
it('should call expirationMatchExactDate-else', () => {
component.expirationMatchExactDate(false);
});
it('should call onDateRangeSelect', () => {
component.onDateRangeSelect('effectiveDateValue');
});
it('should call onDateRangeSelect', () => {
component.onDateRangeSelect('effectiveStartDate');
});
it('should call onDateRangeSelect', () => {
component.filterModel.effectiveType = 'range';
component.onDateRangeSelect('date');
});
it('should call validateDateRange', () => {
component.filterModel.effectiveStartDate = '08/05/2019';
component.filterModel.effectiveEndDate = '';
component.validateDateRange({}, 'effectiveStartDate', 'effectiveEndDate', 'effectiveDateRange');
});
it('should call validateDateRange-else-if', () => {
component.filterModel.effectiveStartDate = '08/05/2019';
component.filterModel.effectiveEndDate = '08/15/2019';
component.validateDateRange({}, 'effectiveStartDate', 'effectiveEndDate', 'effectiveDateRange');
});
it('should call validateDateRange-else', () => {
component.filterModel.effectiveStartDate = '';
component.filterModel.effectiveEndDate = '08/15/2019';
component.validateDateRange({}, 'effectiveStartDate', 'effectiveEndDate', 'effectiveDateRange');
});
it('should call expDateRadioToggle', () => {
component.expDateRadioToggle(true, 'test1', 'test2', 'test3', 'test4', 'test5', 'test6');
});
it('should call expirationKeyFinder', () => {
component.expirationKeyFinder();
});
it('should call onExpirationRangeSelect-StartDate', () => {
component.onExpirationRangeSelect('expirationStartDate');
});
it('should call onExpirationRangeSelect-EndDate', () => {
component.onExpirationRangeSelect('expirationEndDate');
});
it('should call onExpirationRangeSelect-else', () => {
component.filterModel.expirationType = 'range';
component.onExpirationRangeSelect('date');
});
it('should call sourceFramer', () => {
const data = {
'took': 27,
'timed_out': false,
'_shards': {
'total': 3,
'successful': 3,
'skipped': 0,
'failed': 0
},
'hits': {
'total': 561,
'max_score': 1.0,
'hits': [
{
'_index': 'pricing-fuelprice-1-2019.05.07',
'_type': 'doc',
'_id': '565',
'_score': 1.0,
'_source': {
'fuelPriceSourceTypeName': 'Doe'
}
}
]
}
};
component.sourceFramer(data);
});
it('should call regionFramer', () => {
const data = {
'took': 27,
'timed_out': false,
'_shards': {
'total': 3,
'successful': 3,
'skipped': 0,
'failed': 0
},
'hits': {
'total': 561,
'max_score': 1.0,
'hits': [
{
'_index': 'pricing-fuelprice-1-2019.05.07',
'_type': 'doc',
'_id': '565',
'_score': 1.0,
'_source': {
'fuelRegionName': 'National'
}
}
]
}
};
component.regionFramer(data);
});
}); |
import { useState, useEffect, useRef } from "react";
import { TextField } from "@mui/material";
import axios from "axios";
import { Container, Paper, Grid } from "@mui/material";
import CircularProgress from "@mui/material/CircularProgress";
import { profileCardDesign } from "@/constants/commonStyle";
import talentPoolStyle from "../../../styles/talentPoolStyles.module.css";
import CustomButton2 from "@/components/atoms/CustomButton2";
import { DEV_PUBLIC_URL } from '../../../../configs/auth';
const apiUrl = `${DEV_PUBLIC_URL}form/candidates`;
import { useRouter } from 'next/router';
import Image from 'next/image';
interface Candidates {
Name: string;
Email: string;
Skills: string;
id: string;
Experience: string;
PreviousRole: string;
CurrentRole: string;
CandidateProfile: string;
Salary: string;
PrefferedLocation: string;
CurrentLocation: string;
buttonText: string;
}
interface Profile {
Skill_Set: string;
}
interface MyButtonProps {
selectedButton: string;
handleButtonClick: (buttonType: string) => void;
}
const viewCurrentProfile = () => {
alert("Current Profile");
};
function truncateString(input: string, maxLength: number): string {
if (input != undefined && input.length > maxLength) {
return input.substring(0, maxLength) + "...";
} else {
return input;
}
}
function splitSentenceAt(sentence: string) {
// Find the index of 'at' in the sentence
if (sentence == null) {
return ""; // or handle accordingly based on your use case
}
// Find the index of 'at' in the sentence
const atIndex = sentence.indexOf("at");
if (atIndex !== -1) {
// Split the sentence until 'at'
const splitSentence = sentence.substring(0, atIndex);
// Remove remaining words after 'at'
const finalSentence = splitSentence.trim();
return finalSentence;
} else {
// If 'at' is not found, return the original sentence
return sentence;
}
}
const TalentPoolCandidateProfile: React.FC = () => {
const [profiles, setProfile] = useState<Profile>({
Skill_Set: "sap",
});
const buttonRef = useRef<HTMLButtonElement>(null);
const [skills, setSkills] = useState<string>("");
const [selectedButton, setSelectedButton] = useState("SAP");
const profileImageURLs = [
"https://thepienews.com/wp-content/uploads/2020/01/Profile-Picture-Small.jpg",
"https://img.freepik.com/free-photo/smiling-man_1098-15443.jpg",
"https://img.freepik.com/premium-photo/happy-businessman_107420-67978.jpg?size=626&ext=jpg&ga=GA1.1.44546679.1699747200&semt=ais",
"https://img.freepik.com/premium-photo/photo-young-student-guy-internet-online-meeting-video-call-lesson-conference-study-concept_274222-31085.jpg?size=626&ext=jpg&ga=GA1.1.1826414947.1699747200&semt=ais",
"https://img.freepik.com/premium-photo/close-up-happy-bearded-man-suit-laughing-smiling-standing-white-background_1258-49895.jpg?size=626&ext=jpg&ga=GA1.1.1518270500.1698451200&semt=ais",
];
const [apiResponse, setApiResponse] = useState<Candidates[]>([]);
const [loading, setLoading] = useState(false);
const fetchData = async (skills: string) => {
try {
setLoading(true);
console.log("Fetching data for skills:", skills);
let resp = await axios.post(`${apiUrl}`, {
profiles: { Skill_Set: skills }, pageNumber: Math.floor(Math.random() * 10) + 1
});
let candidates = resp.data.data.candidatesData;
if (candidates === "Data not present") {
setApiResponse([]);
} else if (candidates.length !== 0) {
setApiResponse(candidates);
} else {
setApiResponse([]);
}
} catch (error) {
console.error("Error fetching data:", error);
} finally {
setLoading(false); // Set loading to false when data fetching is complete (either success or error)
}
};
try {
useEffect(() => {
// Fetch default data for SAP when the component mounts
fetchData("sap");
}, []);
} catch (error) {
alert(error);
}
// Your component logic goes here
let handleSubmit = (e: any): void => {
e.preventDefault();
let element = document.querySelectorAll<HTMLInputElement>(".one");
let obj: Profile = {
Skill_Set: element[0].value,
};
// console.log(obj);
setProfile({ ...obj });
};
const router = useRouter();
const HireCurrentDev = () => {
router.push('/search-developers');
}
const ViewProfile = (profileId: string) => {
router.push(`/talent/${profileId}`);
}
const handleButtonClick = (buttonText: string) => {
// Set the skills based on the button clicked
let buttonSkills = "";
switch (buttonText.toLowerCase()) {
case "sap":
buttonSkills = "SAP";
break;
case "cloud":
buttonSkills = "Cloud";
break;
case "legacy":
buttonSkills = "Legacy";
break;
default:
// Default case if no matching button is found
buttonSkills = "";
break;
}
setSkills(buttonSkills); // Set the skills state
setSelectedButton(buttonText); // Set the selected button
// Make the API call with the selected skills
fetchData(buttonSkills);
};
return (
<>
<form style={{ margin: "auto" }} onSubmit={handleSubmit}>
<TextField
inputProps={{ className: "one" }}
style={{ width: "50vw", display: "none", margin: "20px auto" }}
disabled={true}
label="Skills"
placeholder="Enter Skills"
name="skills"
value={skills}
fullWidth
margin="normal"
/>
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
></div>
<div>
<div className={talentPoolStyle.sapButtons}>
<div>
<CustomButton2
label={"ALL "}
onClick={() => handleButtonClick("Cloud")}
buttonStyle={{
borderRadius: "20px",
boxShadow: "5px 5px 70px 0px rgba(0, 0, 0, 0.25)",
padding: `10px 25px 10px 25px`,
alignItems: `flex-start`,
gap: `10px`,
background:
selectedButton === "All" ? "rgb(40, 113, 255)" : "white",
color: selectedButton === "All" ? "white" : "black",
fontSize: "18px",
justifyContent: "center",
margin: "0px 15px",
}}
hoverStyle={{
background: `rgb(40, 113, 255)`,
color: "white",
boxShadow: " 0px 5px 5px grey",
}}
/>
</div>
<CustomButton2
label={"SAP"}
onClick={() => handleButtonClick("SAP")}
buttonStyle={{
borderRadius: "20px",
boxShadow: "5px 5px 70px 0px rgba(0, 0, 0, 0.25)",
padding: `10px 47px`,
alignItems: `flex-start`,
gap: `10px`,
background:
selectedButton === "SAP" ? "rgb(40, 113, 255)" : "white",
color: selectedButton === "SAP" ? "white" : "black",
fontSize: "18px",
justifyContent: "center",
margin: "0px 15px",
}}
hoverStyle={{
background: `rgb(40, 113, 255)`,
color: "white ",
boxShadow: " 0px 5px 5px grey",
}}
/>
<div>
<CustomButton2
label={"Cloud"}
onClick={() => handleButtonClick("Cloud")}
buttonStyle={{
borderRadius: "20px",
boxShadow: "5px 5px 70px 0px rgba(0, 0, 0, 0.25)",
alignItems: `flex-start`,
gap: `10px`,
padding: `10px 47px`,
background:
selectedButton === "Cloud" ? "rgb(40, 113, 255)" : "white",
color: selectedButton === "Cloud" ? "white" : "black",
fontSize: "18px",
justifyContent: "center",
margin: "0px 15px",
}}
hoverStyle={{
background: `rgb(40, 113, 255)`,
color: "white ",
boxShadow: " 0px 5px 5px grey",
}}
/>
</div>
<div>
<CustomButton2
label={"Legacy"}
onClick={() => handleButtonClick("Legacy")}
buttonStyle={{
borderRadius: "20px",
boxShadow: "5px 5px 70px 0px rgba(0, 0, 0, 0.25)",
alignItems: `flex-start`,
gap: `10px`,
padding: `10px 40px`,
background:
selectedButton === "Legacy" ? "rgb(40, 113, 255)" : "white",
color: selectedButton === "Legacy" ? "white" : "black",
fontSize: "18px",
justifyContent: "center",
margin: "0px 15px",
}}
hoverStyle={{
background: `rgb(40, 113, 255)`,
color: "white ",
boxShadow: " 0px 5px 5px grey",
borderRadius: `20px`,
}}
/>
</div>
</div>
</div>
<br />
<br />
</form>
<div className={talentPoolStyle.bestProfileContainer}>
{apiResponse.length === 0 ? (
// ... (loading or no data message)
<>
<center>
<CircularProgress />
</center>
</>
) : (
// Render profiles in pairs
<div className={talentPoolStyle.profilegridClass}>
{apiResponse.slice(0, 4).map((profile, index) => (
// Render each profile in its own container
<Grid item key={index} xs={12} sm={6}>
<Paper
className={talentPoolStyle.paperStyle}
>
<div
style={{
display: "flex",
justifyContent: "flex-Start",
gap: "25px",
}}
>
{/* Profile 1 */}
<div>
<Image
className={talentPoolStyle.imageProfile}
src={profileImageURLs[index]}
alt=""
width={200}
height={200}
/>
</div>
<div>
<p style={profileCardDesign.profileTalentPoolName}>
{truncateString(profile.Name, 18)}
</p>
<h2
style={profileCardDesign.profileDesignationTalentPool}
>
{truncateString(
splitSentenceAt(profile.CurrentRole),
30
)}
</h2>
{/* <p style={profileCardDesign.profileMainCArdBio}>
{profile.CandidateProfile}
</p> */}
<div>
<span style={profileCardDesign.profileTalentPoolTitle}>
Salary:
</span>{" "}
<span
style={profileCardDesign.profileTalentPoolContent}
>
{profile.Salary}{" "}
</span>
</div>
<div>
<span style={profileCardDesign.profileTalentPoolTitle}>
Location:
</span>{" "}
<span
style={profileCardDesign.profileTalentPoolContent}
>
{truncateString(profile.PrefferedLocation, 18)}{" "}
</span>
</div>
<div
style={{
display: "flex",
justifyContent: "flex-start",
gap: "15px",
}}
>
<CustomButton2
onClick={HireCurrentDev}
label={"Hire Now"}
buttonStyle={{
background: `black`,
color: `white`,
border: `black`,
borderRadius: `25px`,
cursor: `pointer`,
fontSize: `15px`,
// width:"10vw",
margin: "25px 0px 0px 0px ",
// marginBottom:"10px",
gap: `10px`,
}}
hoverStyle={{
background: `white`,
color: `black`,
borderRadius: `25px`,
cursor: `pointer`,
fontSize: `15px`,
border: `0.5px solid black`,
gap: `10px`,
}}
/>
<CustomButton2
onClick={() => ViewProfile(profile.id)}
label={"View Profile"}
buttonStyle={{
background: `whitesmoke`,
color: `black`,
border: `0.5px solid black`,
borderRadius: `25px`,
cursor: `pointer`,
fontSize: `15px`,
// width:"10vw",
margin: "25px 0px 0px 0px ",
gap: `10px`,
}}
hoverStyle={{
background: `black`,
color: `whitesmoke`,
border: `0.5px solid black`,
borderRadius: `25px`,
cursor: `pointer`,
fontSize: `15px`,
gap: `10px`,
boxShadow: " 0px 2px 6px grey",
}}
/>
</div>
</div>
</div>
</Paper>
</Grid>
))}
</div>
)}
</div>
</>
);
};
export default TalentPoolCandidateProfile; |
use anyhow::Result;
use super::StorageIterator;
/// Merges two iterators of different types into one. If the two iterators have the same key, only
/// produce the key once and prefer the entry from A.
pub struct TwoMergeIterator<A: StorageIterator, B: StorageIterator> {
a: A,
b: B,
choose_a: bool,
}
impl<
A: 'static + StorageIterator,
B: 'static + for<'a> StorageIterator<KeyType<'a> = A::KeyType<'a>>,
> TwoMergeIterator<A, B>
{
fn choose_a(a: &A, b: &B) -> bool {
if !a.is_valid() {
return false;
}
if !b.is_valid() {
return true;
}
a.key() < b.key()
}
fn skip_b(&mut self) -> Result<()> {
if self.a.is_valid() && self.b.is_valid() && self.b.key() == self.a.key() {
self.b.next()?;
}
Ok(())
}
pub fn create(a: A, b: B) -> Result<Self> {
let mut iter = Self {
choose_a: false,
a,
b,
};
iter.skip_b()?;
iter.choose_a = Self::choose_a(&iter.a, &iter.b);
Ok(iter)
}
}
impl<
A: 'static + StorageIterator,
B: 'static + for<'a> StorageIterator<KeyType<'a> = A::KeyType<'a>>,
> StorageIterator for TwoMergeIterator<A, B>
{
type KeyType<'a> = A::KeyType<'a>;
fn key(&self) -> A::KeyType<'_> {
if self.choose_a {
debug_assert!(self.a.is_valid());
self.a.key()
} else {
debug_assert!(self.b.is_valid());
self.b.key()
}
}
fn value(&self) -> &[u8] {
if self.choose_a {
self.a.value()
} else {
self.b.value()
}
}
fn is_valid(&self) -> bool {
if self.choose_a {
self.a.is_valid()
} else {
self.b.is_valid()
}
}
fn next(&mut self) -> Result<()> {
if self.choose_a {
self.a.next()?;
} else {
self.b.next()?;
}
self.skip_b()?;
self.choose_a = Self::choose_a(&self.a, &self.b);
Ok(())
}
fn num_active_iterators(&self) -> usize {
self.a.num_active_iterators() + self.b.num_active_iterators()
}
} |
import { TODO_FILTERS } from '../constants'
import { type FilterValue as FiltersType } from '../types'
import { createButtons } from '../utils/createButtons'
import { useTodos } from '../store/useTodos'
const FILTER_BUTTONS = createButtons(TODO_FILTERS)
export const Filters: React.FC = () => {
const filterSelected = useTodos(state => state.filterSelected)
const handleFilterChange = useTodos(state => state.handleFilterChange)
const handleClick =
(filter: FiltersType) =>
(event: React.MouseEvent<HTMLAnchorElement>): void => {
event.preventDefault()
handleFilterChange(filter)
}
return (
<ul className='filters'>
{Object.entries(FILTER_BUTTONS).map(([key, { literal, href }]) => (
<li key={key}>
<a
href={href}
className={`${filterSelected === key ? 'selected' : ''}`}
onClick={handleClick(key as FiltersType)}>
{literal}
</a>
</li>
))}
</ul>
)
} |
/**
* This module handles GET and DELETE requests in a Next.js serverless function.
*
* @module route
*/
// Importing necessary modules
import { NextResponse, NextRequest } from 'next/server'; // Next.js server response object
import data from '@/data.json' // Importing data from a JSON file
/**
* Handles GET requests.
*
* @async
* @function
* @param {Request} req - The incoming request object.
* @param {NextResponse} res - The outgoing response object.
* @returns {NextResponse} - Returns a NextResponse object with a JSON payload.
*
* On success, it returns a JSON object with the requested recipe.
* On failure, it returns a JSON object with the error.
*
* The function extracts the recipe name from the URL, replaces hyphens with spaces, and finds the recipe in the data.
*/
export async function GET(req: Request, res: NextResponse) {
try {
const url = new URL(req.url);
const slug = url.pathname.split('/').slice(-1)[0];
const recipe = data.recipes.find(
(recipe) => recipe.name === slug.replace(/-/g, " ")
);
return NextResponse.json(recipe);
} catch (error) {
return NextResponse.json(error);
}
}
/**
* Handles DELETE requests.
*
* @async
* @function
* @param {Request} req - The incoming request object.
* @param {NextResponse} res - The outgoing response object.
* @returns {NextResponse} - Returns a NextResponse object with a JSON payload.
*
* On success, it returns a JSON object with the message "Recipe Deleted".
* If the recipe is not found, it returns a JSON object with the message "Recipe not found".
* On failure, it returns a JSON object with the error.
*
* The function extracts the recipe id from the URL, finds the recipe in the data, and removes it.
*/
export async function DELETE(req: Request, res: NextResponse) {
try {
const url = new URL(req.url);
const id = url.pathname.split('/').slice(-1)[0];
// Find the index of the recipe with the given id
const index = data.recipes.findIndex((recipe) => Number(id) );
if (index !== -1) {
// Remove the recipe from the array
data.recipes.splice(index, 1);
return NextResponse.json("Recipe Deleted");
} else {
return NextResponse.json("Recipe not found");
}
} catch (error) {
return NextResponse.json(error);
}
} |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_GPU_IR_EMITTER_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_GPU_IR_EMITTER_H_
#include <functional>
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Value.h"
#include "tensorflow/compiler/xla/service/buffer_assignment.h"
#include "tensorflow/compiler/xla/service/dfs_hlo_visitor_with_default.h"
#include "tensorflow/compiler/xla/service/gpu/elemental_ir_emitter.h"
#include "tensorflow/compiler/xla/service/gpu/hlo_to_ir_bindings.h"
#include "tensorflow/compiler/xla/service/gpu/ir_emitter_context.h"
#include "tensorflow/compiler/xla/service/gpu/kernel_thunk.h"
#include "tensorflow/compiler/xla/service/gpu/thunk.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/llvm_ir/ir_array.h"
#include "tensorflow/compiler/xla/service/llvm_ir/ir_builder_mixin.h"
#include "tensorflow/compiler/xla/service/llvm_ir/llvm_loop.h"
#include "tensorflow/compiler/xla/service/llvm_ir/loop_emitter.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/platform/types.h"
namespace xla {
namespace gpu {
// Abstract base class for translating HLO graphs to LLVM IR for a GPU.
//
// There are two concrete subclasses of IrEmitter: IrEmitterNested and
// IrEmitterUnnested. In the unnested variety, each HLO gets its own kernel
// function, whereas in the nested version the whole computation is emitted as
// one *non-kernel* function.
//
// In XLA, kernel functions never call other kernel functions. This means that
// if we have a kernel -- e.g. implementing a kReduce HLO -- that wants to use
// an HLO computation as a "subroutine" -- e.g. the HLO computation that
// specifies how to reduce two elements -- then the subroutine computation must
// be emitted using IrEmitterNested.
//
// Fusion nodes are a special case. A fusion node is emitted using
// IrEmitterUnnested, but the code is generated using FusedIrEmitter, which is
// not a subclass of gpu::IrEmitter, and in fact is better understood as an IR
// generator generator. See comments on that class.
class IrEmitter : public DfsHloVisitorWithDefault,
public IrBuilderMixin<IrEmitter> {
public:
using GeneratorForOperandIrArrays =
std::function<std::vector<llvm_ir::IrArray>()>;
IrEmitter(const IrEmitter&) = delete;
IrEmitter& operator=(const IrEmitter&) = delete;
Status DefaultAction(HloInstruction* hlo) override;
Status HandleConstant(HloInstruction* constant) override;
Status HandleBitcast(HloInstruction* bitcast) override;
Status HandleGetTupleElement(HloInstruction* get_tuple_element) override;
Status HandleDot(HloInstruction* dot) override;
Status HandleConvolution(HloInstruction* convolution) override;
Status HandleFft(HloInstruction* fft) override;
Status HandleAllReduce(HloInstruction* crs) override;
Status HandleInfeed(HloInstruction* infeed) override;
Status HandleOutfeed(HloInstruction* outfeed) override;
Status HandleSend(HloInstruction* send) override;
Status HandleSendDone(HloInstruction* send_done) override;
Status HandleRecv(HloInstruction* recv) override;
Status HandleRecvDone(HloInstruction* recv_done) override;
Status HandleParameter(HloInstruction* parameter) override;
Status HandleTuple(HloInstruction* tuple) override;
Status HandleScatter(HloInstruction* scatter) override;
Status HandleSelect(HloInstruction* select) override;
Status HandleTupleSelect(HloInstruction* tuple_select) override;
Status HandleFusion(HloInstruction* fusion) override;
Status HandleCall(HloInstruction* call) override;
Status HandleCustomCall(HloInstruction* custom_call) override;
Status HandleBatchNormInference(HloInstruction* batch_norm) override;
Status HandleBatchNormTraining(HloInstruction* batch_norm) override;
Status HandleBatchNormGrad(HloInstruction* batch_norm) override;
Status HandleAddDependency(HloInstruction* add_dependency) override;
Status FinishVisit(HloInstruction* root) override { return Status::OK(); }
llvm::IRBuilder<>* builder() { return &b_; }
protected:
// Constructs an IrEmitter with the given IrEmitter context.
// ir_emitter_context is owned by the caller and should outlive the IrEmitter
// object.
explicit IrEmitter(const HloModuleConfig& hlo_module_config,
IrEmitterContext* ir_emitter_context, bool is_nested);
// Helper for calling HloToIrBindings::GetIrArray.
//
// Gets the IrArray which contains inst. This array has metadata that makes
// it valid only within the IR that implements consumer. If you are
// implementing an HLO and want to get its own output buffer, call
// GetIrArray(hlo, hlo).
llvm_ir::IrArray GetIrArray(const HloInstruction& inst,
const HloInstruction& consumer,
const ShapeIndex& shape_index = {}) {
return bindings_.GetIrArray(inst, consumer, shape_index);
}
// A convenient helper for calling HloToIrBindings::GetBasePointer.
llvm::Value* GetBasePointer(const HloInstruction& inst,
ShapeIndexView shape_index = {}) const {
return bindings_.GetBasePointer(inst, shape_index);
}
// Generates the IrArray for each output of an hlo instruction and returns
// a vector containing such IrArrays.
std::vector<llvm_ir::IrArray> ConstructIrArrayForOutputs(
const HloInstruction& hlo);
// Emit a singlethreaded or multithreaded loop that computes every element in
// the result of the given HLO instruction. This produces a series of nested
// loops (e.g. one for each dimension of the `hlo`'s shape). The body of the
// inner-most loop is provided by the body_emitter function.
virtual Status EmitTargetElementLoop(
const HloInstruction& hlo,
const llvm_ir::ElementGenerator& body_emitter) = 0;
// Emits a call in IR to the given nested computation with the given operands
// and output. If no IR function has been previously emitted for the
// computation, also emits such a function.
Status EmitCallToNestedComputation(const HloComputation& nested_computation,
absl::Span<llvm::Value* const> operands,
llvm::Value* output);
// Emits an atomic operation that implements `nested_computation` in the
// sequentially consistent memory model. `output_address` and `source_address`
// are the arguments of the nested computation. For example,
// atomicAdd(output_address, *source_address).
Status EmitAtomicOperationForNestedComputation(
const HloComputation& nested_computation, llvm::Value* output_address,
llvm::Value* source_address);
GpuElementalIrEmitter::NestedComputer GetNestedComputer() {
return std::bind(&IrEmitter::ComputeNestedElement, this,
std::placeholders::_1, std::placeholders::_2);
}
IrEmitterContext* ir_emitter_context_;
llvm::Module* module_;
// The following fields track the IR emission state. According to LLVM memory
// management rules, their memory is owned by the module.
llvm::IRBuilder<> b_;
// Mapping from HLO to its underlying LLVM value.
HloToIrBindings bindings_;
// Hlo configuration data used during code generation.
const HloModuleConfig& hlo_module_config_;
protected:
GeneratorForOperandIrArrays GetGeneratorForOperandIrArrays(
const HloInstruction* fusion) {
return [=]() {
std::vector<llvm_ir::IrArray> ir_arrays;
ir_arrays.reserve(fusion->operand_count());
absl::c_transform(fusion->operands(), std::back_inserter(ir_arrays),
[&](const HloInstruction* operand) {
return GetIrArray(*operand, *fusion);
});
return ir_arrays;
};
}
private:
// A helper method for EmitAtomicOperationForNestedComputation. Certain
// computations, such as floating-point addition and integer maximization, can
// be simply implemented using an LLVM atomic instruction. If "computation" is
// one of this kind, emits code to do that and returns true; otherwise,
// returns false.
bool MaybeEmitDirectAtomicOperation(const HloComputation& computation,
llvm::Value* output_address,
llvm::Value* source_address);
// A helper method for EmitAtomicOperationForNestedComputation. It implements
// binary atomic operations using atomicCAS with special handling to support
// small data types.
Status EmitAtomicOperationUsingCAS(const HloComputation& computation,
llvm::Value* output_address,
llvm::Value* source_address);
// A helper method for HandleSort(). It adds the inner comparison loop where
// we compare elements pointed to by 'keys_index' and 'compare_keys_index'.
void EmitCompareLoop(int64 dimension_to_sort,
const llvm_ir::IrArray::Index& keys_index,
const llvm_ir::IrArray::Index& compare_keys_index,
const llvm_ir::IrArray& keys_array);
StatusOr<std::vector<llvm::Value*>> ComputeNestedElement(
const HloComputation& computation,
absl::Span<llvm::Value* const> parameter_elements);
// Emits an atomic operation that implements `nested_computation` in the
// sequentially consistent memory model. `output_address` and `source_address`
// are the arguments of the nested computation. For example,
// atomicAdd(output_address, *source_address).
StatusOr<llvm::Function*> EmitAtomicFunctionForNestedComputation(
const HloComputation& nested_computation, llvm::Type* element_ir_type);
// Map nested computations to emitted IR functions. This serves as a cache so
// that IrEmitter does not emit multiple functions for the same
// HloComputation.
std::map<const HloComputation*, llvm::Function*> computation_to_ir_function_;
};
} // namespace gpu
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_SERVICE_GPU_IR_EMITTER_H_ |
import { Route, Routes } from 'react-router-dom';
import SharedLayout from './SharedLayout/SharedLayout';
import Home from 'pages/Home';
import Register from 'pages/Register';
import Login from 'pages/Login';
import Contacts from 'pages/Contacts';
import { PrivateRoute } from './PrivateRoute/PrivateRoute';
import { RestrictedRoute } from './RestrictedRoute/RestrictedRoute';
import { useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { refreshUser } from 'redux/auth/operations';
import { useAuth } from 'hooks';
import Loader from './Loader/Loader';
import css from './app.module.css';
export default function App() {
const dispatch = useDispatch();
const { isRefreshing } = useAuth();
useEffect(() => {
dispatch(refreshUser());
}, [dispatch]);
return isRefreshing ? (
<Loader />
) : (
<section className={css.section}>
<Routes>
<Route path="/" element={<SharedLayout />}>
<Route index element={<Home />} />
<Route
path="/register"
element={
<RestrictedRoute
redirectTo="/contacts"
component={<Register />}
/>
}
/>
<Route
path="/login"
element={
<RestrictedRoute redirectTo="/contacts" component={<Login />} />
}
/>
<Route
path="/contacts"
element={
<PrivateRoute redirectTo="/login" component={<Contacts />} />
}
/>
</Route>
</Routes>
</section>
);
} |
import { on, observes } from "ember-addons/ember-computed-decorators";
import LoadMore from "discourse/mixins/load-more";
import UrlRefresh from "discourse/mixins/url-refresh";
const DiscoveryTopicsListComponent = Ember.Component.extend(
UrlRefresh,
LoadMore,
{
classNames: ["contents"],
eyelineSelector: ".topic-list-item",
@on("didInsertElement")
@observes("model")
_readjustScrollPosition() {
const scrollTo = this.session.get("topicListScrollPosition");
if (scrollTo && scrollTo >= 0) {
Ember.run.schedule("afterRender", () =>
$(window).scrollTop(scrollTo + 1)
);
} else {
Ember.run.scheduleOnce("afterRender", this, this.loadMoreUnlessFull);
}
},
@observes("topicTrackingState.states")
_updateTopics() {
this.topicTrackingState.updateTopics(this.model.topics);
},
@observes("incomingCount")
_updateTitle() {
Discourse.updateContextCount(this.incomingCount);
},
saveScrollPosition() {
this.session.set("topicListScrollPosition", $(window).scrollTop());
},
scrolled() {
this._super(...arguments);
this.saveScrollPosition();
},
actions: {
loadMore() {
Discourse.updateContextCount(0);
this.model.loadMore().then(hasMoreResults => {
Ember.run.schedule("afterRender", () => this.saveScrollPosition());
if (!hasMoreResults) {
this.eyeline.flushRest();
} else if ($(window).height() >= $(document).height()) {
this.send("loadMore");
}
});
}
}
}
);
export default DiscoveryTopicsListComponent; |
#' Text summary for the top of the results page above the plot
#'
#' @param v all data
#' @export
get_text_summary <- function(v){
# get theta and sem for the final item administered.
final = v$results %>%
tidyr::drop_na(response) %>%
dplyr::filter(order == max(order, na.rm = TRUE)) %>%
dplyr::mutate(theta = round(theta, 2), sem = round(sem, 2))
# save theta, sem, z-core, and whether or not the zscore is pos or neg
# in variables that are easy to use in glue below
theta = final$theta
sem = final$sem
z = (theta-50)/10
ab = ifelse(z>=0, "above", "below")
# confidence intervals
x95 = glue::glue("{round(theta-1.96 *sem, 2)}, {round(theta+1.96 *sem, 2)}")
x90 = glue::glue("{round(theta-1.645 *sem, 2)}, {round(theta+1.645 *sem, 2)}")
x68 = glue::glue("{round(theta-1 *sem, 2)}, {round(theta+1 *sem, 2)}")
# completed items
completed = v$results %>%
dplyr::mutate(theta = round(theta, 2), sem = round(sem, 2)) %>%
tidyr::drop_na(response)
# valid items (excluding DNA + na as it returns NA)
valid = v$results %>%
dplyr::mutate(theta = round(theta, 2), sem = round(sem, 2)) %>%
tidyr::drop_na(response_num)
# return results table
table1 = tibble::tribble(
~"label", ~"score",
"Final T-Score Estimate" , as.character(theta),
"Final Standard Error" , as.character(sem),
"Final Estimate Type" , as.character("EAP"),
"95% C.I." , as.character(x95),
"90% C.I." , as.character(x90),
"68% C.I." , as.character(x68),
"Test Length" , as.character(nrow(valid)),
"Items completed" , as.character(nrow(completed)),
"Items marked NA" , as.character(sum(is.na(completed$response_num)))
) %>%
dplyr::rename(" " = 1, " " = 2)
p1 = glue::glue(
"This individual's T-score estimate of {theta} (95% confidence interval: {x95})
indicates self-reported communicative functioning approximately {abs(round(z,2))} standard
deviations {ab} the mean reported in a large reference sample of community-dwelling
persons with aphasia of at least one month post-onset.")
p2 = "T-scores are scaled such that the mean and standard deviation in the reference
sample are 50 and 10, respectively. Given that the scores in the reference sample
were approximately normally distributed, roughly 68% of scores drawn from the
population are expected to fall between 40 and 60, and roughly 5% are expected
to be lower than 30 or greater than 70."
p3 = "The confidence interval expresses the uncertainty in the score estimate,
with wider intervals at a given confidence level indicating
greater uncertainty. If the test could be administered to this individual
a large number of times under identical conditions, 95 out of 100 of the
of 95% confidence intervals would contain the true value of the communicative
functioning score."
funding = "The development of this testing application was funded by National Institute on Deafness and Other Communication Disorders Awards R03DC014556 (PI: Fergadiotis) and R01DC018813 (MPIs: Fergadiotis & Hula), VA Rehabilitation Research & Development Career Development Award C7476W (PI: Hula), and the VA Pittsburgh Healthcare System Geriatric Research, Education, and Clinical Center. We would also like to acknowledge the support and assistance of Myrna Schwartz, Dan Mirman, Adelyn Brecher, Erica Middleton, Patrick Doyle, Malcolm McNeil, Christine Matthews, Angela Grzybowski, Brooke Swoyer, Maria Fenner, Michelle Gravier, Alyssa Autenreith, Emily Boss, Haley Dresang, Lauren Weerts, Hattie Olson, Kasey Graue, Chia-Ming Lei, Joann Silkes, Diane Kendall, the staff of the VA Pittsburgh Healthcare System Audiology and Speech Pathology Program."
return(list(
p1 = p1,
p2 = p2,
p3 = p3,
table1 = table1,
values = list(
theta = theta,
sem = sem,
test_length = nrow(valid),
items_completed = nrow(completed),
marked_NA = sum(is.na(completed$response_num))
)
))
} |
//
// ContentView.swift
// PursTKH
//
// Created by Jared Hubbard on 5/26/24.
//
import SwiftUI
struct ContentView: View {
@StateObject private var viewModel = BusinessHoursViewModel()
@State private var showFullHours = false
@State private var showMenu = false
var body: some View {
ZStack {
// Background Image
Image("restaurant")
.resizable()
.scaledToFill()
.edgesIgnoringSafeArea(.all)
VStack {
// Title
Text("BEASTRO by \nMarshawn Lynch")
.font(.system(size: 54, weight: .black))
.foregroundColor(.white)
.multilineTextAlignment(/*@START_MENU_TOKEN@*/.leading/*@END_MENU_TOKEN@*/)
.frame(width: 346, height: 216, alignment: .topLeading)
.padding(.top, 21)
.padding(.leading, 23)
// Spacer to push content below
Spacer().frame(height: 30)
// Hours of operation card
VStack(alignment: .leading, spacing: 8) {
HStack {
Text("Open until 7pm")
.font(.custom("Hindi Siliguri", size: 18))
.fontWeight(.regular)
.foregroundColor(.black)
Circle()
.fill(Color.green)
.frame(width: 10, height: 10)
Spacer()
Image(systemName: showFullHours ? "chevron.up" : "chevron.right")
.foregroundColor(.black)
}
Text("SEE FULL HOURS")
.font(.custom("Chivo", size:12))
.fontWeight(.regular)
.foregroundColor(.gray)
if showFullHours {
Divider().padding(.vertical, 8)
VStack(alignment: .leading, spacing: 4) {
ForEach(viewModel.businessHours) { hour in
VStack(alignment: .leading) {
Text(hour.dayOfWeek)
.font(.headline)
Text(hour.endLocalTime == "Open 24 hrs" ? "Open 24 hrs" : "\(hour.startLocalTime) - \(hour.endLocalTime)")
.font(.subheadline)
}
.cornerRadius(5)
}
}
}
}
.padding(8)
.frame(width: 346, height: showFullHours ? nil : 81, alignment: .topLeading)
.background(Color.white.opacity(0.6))
.cornerRadius(8)
.shadow(color: Color.black.opacity(0.25), radius: 10.2, x: 0, y: 4)
.onTapGesture {
withAnimation {
showFullHours.toggle()
}
}
Spacer()
// View Menu Button
Button(action: {
showMenu.toggle()
}) {
VStack {
Image(systemName: showMenu ? "chevron.down" : "chevron.up")
.font(.system(size: 20))
.foregroundColor(.white)
.opacity(0.5)
Image(systemName: showMenu ? "chevron.down" : "chevron.up")
.font(.system(size: 20))
.foregroundColor(.white)
Text("View Menu")
.font(.title2)
.foregroundColor(.white) // Text color
}
.padding()
.background(Color.clear)
}
.padding(.bottom, 30)
}
}
.sheet(isPresented: $showMenu) {
// Placeholder for menu content
Text("Menu content goes here")
.font(.largeTitle)
.padding()
}
.onAppear {
viewModel.fetchBusinessHours()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
// Helper extension to set specific corner radius
extension View {
func cornerRadius(_ radius: CGFloat, corners: UIRectCorner) -> some View {
clipShape(RoundedCorner(radius: radius, corners: corners))
}
}
struct RoundedCorner : Shape {
var radius: CGFloat = .infinity
var corners: UIRectCorner = .allCorners
func path(in rect: CGRect) -> Path {
let path = UIBezierPath(
roundedRect: rect,
byRoundingCorners: corners,
cornerRadii: CGSize(width: radius, height: radius)
)
return Path(path.cgPath)
}
} |
export default class Color
{
r: number;
g: number;
b: number;
a: number;
constructor(r = 1.0, g = 1.0, b = 1.0, a = 1.0)
{
this.r = r;
this.g = g;
this.b = b;
this.a = a;
}
clone()
{
return new Color(this.r, this.g, this.b, this.a);
}
clamp(val:number)
{
return Math.min(Math.max(val, 0.0), 1.0);
}
componentToHex(c:number) {
var hex = (Math.round(c*255)).toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
toHex() { return "#" + this.componentToHex(this.r) + this.componentToHex(this.g) + this.componentToHex(this.b); }
fromHex(hex:string)
{
const data = this.convertHexToRgb(hex);
this.setChannel("r", data.r/255.0);
this.setChannel("g", data.b/255.0);
this.setChannel("b", data.b/255.0);
return this;
}
convertHexToRgb(hex:string) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
toString()
{
return "rgba(" + this.r*255 + ", " + this.g*255 + ", " + this.b*255 + ", " + this.a + ")";
}
getChannel(channelName:string) { return this[channelName]; }
setChannel(channelName:string, value:number)
{
this[channelName] = value;
return this;
}
setAlpha(a:number)
{
this.a = this.clamp(a);
return this;
}
distanceTo(otherColor:Color)
{
const r = Math.abs(this.r - otherColor.r);
const g = Math.abs(this.g - otherColor.g);
const b = Math.abs(this.b - otherColor.b);
const a = Math.abs(this.a - otherColor.a);
return (r + g + b + a) / 4.0;
}
} |
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { SERVER_API_URL } from '../../app.constants';
import { TipEstudiante } from './tip-estudiante.model';
import { ResponseWrapper, createRequestOption } from '../../shared';
@Injectable()
export class TipEstudianteService {
private resourceUrl = SERVER_API_URL + 'api/tip-estudiantes';
constructor(private http: Http) { }
create(tipEstudiante: TipEstudiante): Observable<TipEstudiante> {
const copy = this.convert(tipEstudiante);
return this.http.post(this.resourceUrl, copy).map((res: Response) => {
return res.json();
});
}
update(tipEstudiante: TipEstudiante): Observable<TipEstudiante> {
const copy = this.convert(tipEstudiante);
return this.http.put(this.resourceUrl, copy).map((res: Response) => {
return res.json();
});
}
find(id: number): Observable<TipEstudiante> {
return this.http.get(`${this.resourceUrl}/${id}`).map((res: Response) => {
return res.json();
});
}
query(req?: any): Observable<ResponseWrapper> {
const options = createRequestOption(req);
return this.http.get(this.resourceUrl, options)
.map((res: Response) => this.convertResponse(res));
}
delete(id: number): Observable<Response> {
return this.http.delete(`${this.resourceUrl}/${id}`);
}
private convertResponse(res: Response): ResponseWrapper {
const jsonResponse = res.json();
return new ResponseWrapper(res.headers, jsonResponse, res.status);
}
private convert(tipEstudiante: TipEstudiante): TipEstudiante {
const copy: TipEstudiante = Object.assign({}, tipEstudiante);
return copy;
}
} |
import React, { Component } from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
import {
RkStyleSheet
} from 'react-native-ui-kitten';
import {GradientButton} from '../../../../components/gradientButton';
import validator from 'validator';
import { errorSet, } from '../../actions';
class EmailPwdButton extends Component {
onButtonPress() {
if (this.props.emailPwdBtnStr == 'SignIn') {
const { email, password } = this.props;
if ( this.validateInput('email', email) && this.validateInput('password', password)) {
this.props.onSubmit({ email, password });
} else {
this.props.errorSet('Please provide valid inputs');
}
}
if (this.props.emailPwdBtnStr == 'SignUp') {
const { email, password, phone, firstname, lastname } = this.props;
if ( this.validateInput('email', email) && this.validateInput('password', password)) {
this.props.onSubmit({ email, password, phone, firstname, lastname });
} else {
this.props.errorSet('Please provide valid inputs');
}
}
}
// Validate the form inputs
validateInput(inputName, inputVal) {
if (inputName == 'email') {
return validator.isEmail(inputVal);
}
if (inputName == 'password') {
return validator.isAscii(inputVal);
}
}
render () {
return (
<View>
<GradientButton
onPress={() => {
console.log("Hello");
this.onButtonPress();
}}
colors = {[ '#00c6ff' , '#0072ff']}
rkType='large'
style={styles.save}
text={this.props.emailPwdBtnStr}>
</GradientButton>
</View>
);
}
}
let styles = RkStyleSheet.create(theme => ({
save: {
marginVertical: 9,
marginHorizontal: 20
}
}));
const mapStateToProps = (state, props) => {
const { email, password, phone, firstname, lastname, emailReset } = state.authReducer.auth;
return { email, password, phone, firstname, lastname, emailReset };
};
export default connect(mapStateToProps, {
errorSet,
})(EmailPwdButton); |
import { Injectable } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { WarningDialogComponent } from '../shared/warning-dialog/warning-dialog.component';
import { EditCategoryDialogComponent } from '../shared/edit-category-dialog/edit-category-dialog.component';
import { InfoDialogComponent } from '../shared/info-dialog/info-dialog.component';
@Injectable({ providedIn: 'root' })
export class DialogService {
constructor(private dialog: MatDialog) {}
openWarningDialog(
title: string,
content: string,
okButtonLabel: string,
cancelButtonLabel: string
) {
const dialogRef = this.dialog.open(WarningDialogComponent, {
width: '42rem',
});
dialogRef.componentInstance.title = title;
dialogRef.componentInstance.content = content;
dialogRef.componentInstance.okButtonLabel = okButtonLabel;
dialogRef.componentInstance.cancelButtonLabel = cancelButtonLabel;
return dialogRef;
}
openInfoDialog(title: string, content: string) {
const dialogRef = this.dialog.open(InfoDialogComponent, {
width: '42rem',
});
dialogRef.componentInstance.title = title;
dialogRef.componentInstance.content = content;
return dialogRef;
}
openEditCategoryDialog(
title: string,
content: string,
okButtonLabel: string,
cancelButtonLabel: string,
inputValue: string = ''
) {
const dialogRef = this.dialog.open(EditCategoryDialogComponent, {
width: '42rem',
});
dialogRef.componentInstance.title = title;
dialogRef.componentInstance.content = content;
dialogRef.componentInstance.okButtonLabel = okButtonLabel;
dialogRef.componentInstance.cancelButtonLabel = cancelButtonLabel;
dialogRef.componentInstance.inputValue = inputValue;
return dialogRef;
}
} |
// Sample data for the initial blogs
const initialBlogs = [
{
id: 1,
title: "Abhinay's Microblogging App",
content: "This is a simple microblogging application created using JavaScript, SCSS, and JSON.",
author: "Chakradhar ",
created: "2023-10-22T12:00:00Z",
completed: false,
},
];
// Function to fetch and display blogs
function fetchBlogs() {
const blogsContainer = document.querySelector(".blogs-container");
// Use XMLHttpRequest to fetch blogs from data.json
const xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onload = function () {
if (xhr.status === 200) {
const blogs = JSON.parse(xhr.responseText);
blogs.forEach((blog) => {
createBlogCard(blog);
});
} else {
console.error('Failed to fetch blogs.');
}
};
xhr.send();
}
// Function to expand a blog's content
function expandBlog(blogId) {
const blogCard = document.getElementById(`blog-${blogId}`);
const content = blogCard.querySelector(".blog-content");
content.classList.toggle("expanded");
}
// Function to create a new blog card
function createBlogCard(blog) {
const blogsContainer = document.querySelector(".blogs-container");
const blogCard = document.createElement("div");
blogCard.classList.add("blog-card");
blogCard.id = `blog-${blog.id}`;
blogCard.innerHTML = `
<h3 class="blog-title">${blog.title}</h3>
<p class="blog-content" style="overflow: scroll">${blog.content}</p>
<p class="blog-author">Author: ${blog.author}</p>
<p class="blog-date">Created: ${blog.created}</p>
<div class="buttoncontainer">
<button class="" onclick="expandBlog(${blog.id})">Expand</button>
<button class="edit-icon" data-blog-id="${blog.id}" id="edit-${blog.id}" onClick="toggleEdit(${blog.id})">Edit</button>
<button class="save-icon" style="display:none" id="save-${blog.id}" data-blog-id="${blog.id}" onClick="toggleSave(${blog.id})">Save</button>
</div>
`;
blogCard.addEventListener('click', () => {
console.log("test");
// Toggle the "expanded" class to expand or collapse the content
blogCard.classList.toggle('expanded');
});
blogsContainer.appendChild(blogCard);
}
function toggleSave(id){
document.getElementById(`save-${id}`).style.display ="none";
document.getElementById(`edit-${id}`).style.display = "block";
}
function toggleEdit(id){
document.getElementById(`save-${id}`).style.display ="block";
document.getElementById(`edit-${id}`).style.display = "none";
}
// Function to show the create blog form
function showCreateBlogForm() {
const createBlogForm = document.getElementById("create-blog-form");
createBlogForm.style.display = "block";
// Clear input fields
document.getElementById("blog-title").value = "";
document.getElementById("blog-author").value = "";
document.getElementById("blog-content").value = "";
const createButton = document.getElementById("create-button");
createButton.style.display = "none";
}
// Function to add a new blog
function addNewBlog(title, content, author, e) {
const currentDateTime = new Date().toISOString(); // Get the current date and time
e.preventDefault();
const newBlog = {
id: Date.now(), // A simple way to generate a unique ID
title,
content,
author,
created: currentDateTime, // Set the creation date and time
completed: false,
};
createBlogCard(newBlog);
// Hide the create-blog-form
document.getElementById("create-blog-form").style.display = "none";
document.getElementById("create-button").style.display = "block";
}
// Function to update a blog as complete
function updateBlog(blogId) {
const blogCard = document.getElementById(`blog-${blogId}`);
const content = blogCard.querySelector(".blog-content");
const author = blogCard.querySelector(".blog-author");
// Make the content and author fields editable
content.contentEditable = true;
author.contentEditable = true;
// Add a class to indicate the blog is being edited
blogCard.classList.add("editing");
}
// Function to save the edited content
function saveBlogEdit(blogId) {
const blogCard = document.getElementById(`blog-${blogId}`);
const content = blogCard.querySelector(".blog-content");
const author = blogCard.querySelector(".blog-author");
// Make the content and author fields non-editable
content.contentEditable = false;
author.contentEditable = false;
// Remove the class indicating editing
blogCard.classList.remove("editing");
}
// Event listeners for editing a blog
document.addEventListener("click", function (event) {
if (event.target.classList.contains("edit-icon")) {
const blogId = event.target.dataset.blogId;
updateBlog(blogId);
} else if (event.target.classList.contains("save-icon")) {
const blogId = event.target.dataset.blogId;
saveBlogEdit(blogId);
}
});
// Event listener for the "Create Blog" button
document.getElementById("create-button").addEventListener("click", showCreateBlogForm);
// Event listener for the "Submit" button in the create blog form
document.getElementById("submit-blog").addEventListener("click", (e) => {
const title = document.getElementById("blog-title").value;
const author = document.getElementById("blog-author").value;
const content = document.getElementById("blog-content").value;
addNewBlog(title, content, author, e);
});
// Call fetchBlogs to load blogs when the page loads
fetchBlogs(); |
import {
axiosBasicAuthMiddleware as _axiosBasicAuthMiddleware,
axiosBearerAuthMiddleware as _axiosBearerAuthMiddleware,
} from "@lindorm-io/axios";
import { OpenIdBackchannelAuthMode } from "@lindorm-io/common-enums";
import { createMockLogger } from "@lindorm-io/winston";
import { BackchannelSession, Client, ClientSession } from "../../entity";
import {
createTestBackchannelSession,
createTestClient,
createTestClientSession,
} from "../../fixtures/entity";
import { generateTokenResponse as _generateTokenResponse } from "../oauth";
import { generateServerBearerAuthMiddleware as _generateServerBearerAuthMiddleware } from "../token";
import { handleBackchannelPush } from "./handle-backchannel-push";
jest.mock("@lindorm-io/axios");
jest.mock("../oauth");
jest.mock("../token");
const axiosBasicAuthMiddleware = _axiosBasicAuthMiddleware as jest.Mock;
const axiosBearerAuthMiddleware = _axiosBearerAuthMiddleware as jest.Mock;
const generateServerBearerAuthMiddleware = _generateServerBearerAuthMiddleware as jest.Mock;
const generateTokenResponse = _generateTokenResponse as jest.Mock;
describe("handleBackchannelPush", () => {
let ctx: any;
let client: Client;
let backchannelSession: BackchannelSession;
let clientSession: ClientSession;
beforeEach(() => {
ctx = {
axios: {
axiosClient: {
post: jest.fn(),
},
},
logger: createMockLogger(),
};
client = createTestClient({
backchannelAuth: {
mode: OpenIdBackchannelAuthMode.PUSH,
uri: "uri",
username: null,
password: null,
},
});
backchannelSession = createTestBackchannelSession();
clientSession = createTestClientSession();
axiosBasicAuthMiddleware.mockReturnValue("axiosBasicAuthMiddleware");
axiosBearerAuthMiddleware.mockReturnValue("axiosBearerAuthMiddleware");
generateServerBearerAuthMiddleware.mockReturnValue("generateServerBearerAuthMiddleware");
generateTokenResponse.mockResolvedValue("generateTokenResponse");
});
test("should resolve with bearer token", async () => {
await expect(
handleBackchannelPush(ctx, client, backchannelSession, clientSession),
).resolves.toBeUndefined();
expect(ctx.axios.axiosClient.post).toHaveBeenCalledWith("uri", {
body: "generateTokenResponse",
middleware: ["axiosBearerAuthMiddleware"],
});
});
test("should resolve with basic auth", async () => {
backchannelSession = createTestBackchannelSession({
clientNotificationToken: null,
});
client.backchannelAuth.username = "username";
client.backchannelAuth.password = "password";
await expect(
handleBackchannelPush(ctx, client, backchannelSession, clientSession),
).resolves.toBeUndefined();
expect(ctx.axios.axiosClient.post).toHaveBeenCalledWith("uri", {
body: "generateTokenResponse",
middleware: ["axiosBasicAuthMiddleware"],
});
});
test("should resolve with client credentials", async () => {
backchannelSession = createTestBackchannelSession({
clientNotificationToken: null,
});
await expect(
handleBackchannelPush(ctx, client, backchannelSession, clientSession),
).resolves.toBeUndefined();
expect(ctx.axios.axiosClient.post).toHaveBeenCalledWith("uri", {
body: "generateTokenResponse",
middleware: ["generateServerBearerAuthMiddleware"],
});
});
}); |
#ifndef SALVIAR_RENDERER_H
#define SALVIAR_RENDERER_H
#include <salviar/include/decl.h>
#include <salviar/include/enums.h>
#include <salviar/include/colors.h>
#include <salviar/include/format.h>
#include <salviar/include/shader.h>
#include <salviar/include/viewport.h>
#include <eflib/include/math/collision_detection.h>
#include <eflib/include/utility/shared_declaration.h>
#include <eflib/include/platform/disable_warnings.h>
#include <boost/any.hpp>
#include <boost/shared_ptr.hpp>
#include <eflib/include/platform/enable_warnings.h>
#include <vector>
#include <salviar/include/salviar_forward.h>
BEGIN_NS_SALVIAR();
struct shader_profile;
struct input_element_desc;
struct mapped_resource;
EFLIB_DECLARE_CLASS_SHARED_PTR(renderer);
EFLIB_DECLARE_CLASS_SHARED_PTR(shader_object);
EFLIB_DECLARE_CLASS_SHARED_PTR(shader_log);
EFLIB_DECLARE_CLASS_SHARED_PTR(async_object);
enum class async_status :uint32_t;
struct renderer_parameters
{
size_t backbuffer_width;
size_t backbuffer_height;
size_t backbuffer_num_samples;
pixel_format backbuffer_format;
void* native_window;
};
class renderer
{
public:
// Creators
virtual buffer_ptr create_buffer(size_t size) = 0;
virtual texture_ptr create_tex2d(size_t width, size_t height, size_t num_samples, pixel_format fmt) = 0;
virtual texture_ptr create_texcube(size_t width, size_t height, size_t num_samples, pixel_format fmt) = 0;
virtual sampler_ptr create_sampler(sampler_desc const& desc, texture_ptr const& tex) = 0;
virtual async_object_ptr create_query(async_object_ids id) = 0;
virtual input_layout_ptr create_input_layout(
input_element_desc const* elem_descs, size_t elems_count,
shader_object_ptr const& code ) = 0;
virtual input_layout_ptr create_input_layout(
input_element_desc const* elem_descs, size_t elems_count,
cpp_vertex_shader_ptr const& vs ) = 0;
virtual result map(mapped_resource&, buffer_ptr const& buf, map_mode mm) = 0;
virtual result map(mapped_resource&, surface_ptr const& buf, map_mode mm) = 0;
virtual result unmap() = 0;
// State set
virtual result set_vertex_buffers(
size_t starts_slot,
size_t buffers_count, buffer_ptr const* buffers,
size_t const* strides, size_t const* offsets ) = 0;
virtual result set_index_buffer(buffer_ptr const& hbuf, format index_fmt) = 0;
virtual result set_input_layout( input_layout_ptr const& layout) = 0;
virtual result set_vertex_shader(cpp_vertex_shader_ptr const& hvs) = 0;
virtual result set_primitive_topology(primitive_topology primtopo) = 0;
virtual result set_vertex_shader_code( shader_object_ptr const& ) = 0;
virtual result set_vs_variable_value( std::string const& name, void const* pvariable, size_t sz ) = 0;
virtual result set_vs_variable_pointer( std::string const& name, void const* pvariable, size_t sz ) = 0;
virtual result set_vs_sampler( std::string const& name, sampler_ptr const& samp ) = 0;
virtual result set_rasterizer_state(raster_state_ptr const& rs) = 0;
virtual result set_ps_variable( std::string const& name, void const* data, size_t sz ) = 0;
virtual result set_ps_sampler( std::string const& name, sampler_ptr const& samp ) = 0;
virtual result set_blend_shader(cpp_blend_shader_ptr const& hbs) = 0;
virtual result set_pixel_shader(cpp_pixel_shader_ptr const& hps) = 0;
virtual result set_pixel_shader_code( shader_object_ptr const& ) = 0;
virtual result set_depth_stencil_state(depth_stencil_state_ptr const& dss, int32_t stencil_ref) = 0;
virtual result set_render_targets(size_t color_target_count, surface_ptr const* color_targets, surface_ptr const& ds_target) = 0;
virtual result set_viewport(viewport const& vp) = 0;
template <typename T>
result set_vs_variable( std::string const& name, T const* data )
{
return set_vs_variable_value( name, static_cast<void const*>(data), sizeof(T) );
}
template <typename T>
result set_ps_variable( std::string const& name, T const* data )
{
return set_ps_variable( name, static_cast<void const*>(data), sizeof(T) );
}
// State get
virtual buffer_ptr get_index_buffer() const = 0;
virtual format get_index_format() const = 0;
virtual primitive_topology get_primitive_topology() const = 0;
virtual cpp_vertex_shader_ptr get_vertex_shader() const = 0;
virtual shader_object_ptr get_vertex_shader_code() const = 0;
virtual raster_state_ptr get_rasterizer_state() const = 0;
virtual cpp_pixel_shader_ptr get_pixel_shader() const = 0;
virtual shader_object_ptr get_pixel_shader_code() const = 0;
virtual cpp_blend_shader_ptr get_blend_shader() const = 0;
virtual viewport get_viewport() const = 0;
//render operations
virtual result begin(async_object_ptr const& async_obj) = 0;
virtual result end(async_object_ptr const& async_obj) = 0;
virtual async_status get_data(async_object_ptr const& async_obj, void* data, bool do_not_wait) = 0;
virtual result draw(size_t startpos, size_t primcnt) = 0;
virtual result draw_index(size_t startpos, size_t primcnt, int basevert) = 0;
virtual result clear_color(surface_ptr const& color_target, color_rgba32f const& c) = 0;
virtual result clear_depth_stencil(surface_ptr const& depth_stencil_target, uint32_t f, float d, uint32_t s) = 0;
virtual result flush() = 0;
};
renderer_ptr create_software_renderer();
renderer_ptr create_benchmark_renderer();
shader_object_ptr compile(std::string const& code, shader_profile const& profile, shader_log_ptr& logs);
shader_object_ptr compile(std::string const& code, shader_profile const& profile);
shader_object_ptr compile(std::string const& code, languages lang);
shader_object_ptr compile_from_file(std::string const& file_name, shader_profile const& profile, shader_log_ptr& logs);
shader_object_ptr compile_from_file(std::string const& file_name, shader_profile const& profile);
shader_object_ptr compile_from_file(std::string const& file_name, languages lang);
END_NS_SALVIAR();
#endif |
// RUN: %target-run-simple-swift %s
// REQUIRES: executable_test
protocol P {
func f0() -> Int;
func f(x:Int, y:Int) -> Int;
}
protocol Q {
func f(x:Int, y:Int) -> Int;
}
struct S : P, Q, Equatable {
// Test that it's possible to denote a zero-arg requirement
// (This involved extended the parser for unqualified DeclNames)
@_implements(P, f0())
func g0() -> Int {
return 10
}
// Test that it's possible to implement two different protocols with the
// same-named requirements.
@_implements(P, f(x:y:))
func g(x:Int, y:Int) -> Int {
return 5
}
@_implements(Q, f(x:y:))
func h(x:Int, y:Int) -> Int {
return 6
}
// Test that it's possible to denote an operator requirement
// (This involved extended the parser for unqualified DeclNames)
@_implements(Equatable, ==(_:_:))
public static func isEqual(_ lhs: S, _ rhs: S) -> Bool {
return false
}
}
func call_P_f_generic<T:P>(p:T, x: Int, y: Int) -> Int {
return p.f(x:x, y:y)
}
func call_P_f_existential(p:P, x: Int, y: Int) -> Int {
return p.f(x:x, y:y)
}
func call_Q_f_generic<T:Q>(q:T, x: Int, y: Int) -> Int {
return q.f(x:x, y:y)
}
func call_Q_f_existential(q:Q, x: Int, y: Int) -> Int {
return q.f(x:x, y:y)
}
let s = S()
assert(call_P_f_generic(p:s, x:1, y:2) == 5)
assert(call_P_f_existential(p:s, x:1, y:2) == 5)
assert(call_Q_f_generic(q:s, x:1, y:2) == 6)
assert(call_Q_f_existential(q:s, x:1, y:2) == 6)
assert(!(s == s))
// Note: at the moment directly calling the member 'f' on the concrete type 'S'
// doesn't work, because it's considered ambiguous between the 'g' and 'h'
// members (each of which provide an 'f' via the 'P' and 'Q' protocol
// conformances), and adding a non-@_implements member 'f' to S makes it win
// over _both_ the @_implements members. Unclear if this is correct; I think so?
// print(s.f(x:1, y:2)) |
import React from "react";
import { useState } from "react"
import { connect } from "react-redux";
import { TodoAdd, ToggleTodo, setVisibilityFilter } from "../action/index";
import { Todo, Counter } from "../types/todoTypes"
import "../styles/App.css";
interface AppPropType {
todos: Todo[];
counter: Counter;
currentFilter: string;
onAddTodo: Function;
onToggle: Function;
onFilter: Function;
}
const App: React.FC<AppPropType> = ({ todos, counter, currentFilter, onAddTodo, onToggle, onFilter }) => {
const [inputValue, setInputValue] = useState("");
const [validationMessage, setValidationMessage] = useState("");
const addTodo = () => {
if (inputValue.length === 0) {
setValidationMessage("Ошибка. Поле обязательно для заполнения");
return
};
if (inputValue.length > 10) {
setValidationMessage("Ошибка. Длина должна быть меньше или равной 10 символам");
return
};
setValidationMessage("");
onAddTodo(inputValue);
setInputValue("");
};
const toggle = (id: number) => {
onToggle(id);
}
const filter = (selection: string) => {
onFilter(selection);
}
function handleInputChange(event: any) {
setInputValue(event.target.value);
};
return (
<div className="app">
<div className="app__input">
<div className="app__input-field">
<input placeholder="Введите название задачи" className="text-field__input" type={"text"} value= { inputValue } onChange={ handleInputChange }></input>
<button className="custom-btn btn-4 add_button" onClick={() => addTodo()}>Добавить задачу</button>
</div>
<div className="break"></div>
<div >
{ <span className="danger">{validationMessage}</span> }
</div>
</div>
<div className="app__filter">
<button className={ currentFilter === "SHOW_ALL" ? "glow-button" : "deactive-button" } onClick={() => filter("SHOW_ALL")}>Все</button>
<button className={ currentFilter === "SHOW_COMPLETED" ? "glow-button" : "deactive-button" } onClick={() => filter("SHOW_COMPLETED")}>Выполенные { counter.completedCount }</button>
<button className={ currentFilter === "SHOW_INCOMPLETED" ? "glow-button" : "deactive-button" } onClick={() => filter("SHOW_INCOMPLETED")}>Не выполненные { counter.incompletedCount }</button>
</div>
<div>
<ol className="rounded">
{
todos.map((elem: Todo) => {
return <li key={elem.id}>
<a className={ elem.completed ? "rounded-positive" : "rounded-negative" } onClick={() => toggle(elem.id)}>{elem.text}</a>
</li> }
)
}
</ol>
</div>
</div>
);
}
const getVisibleTodos = (todos: Todo[] = [], filter: string) => {
switch (filter) {
case "SHOW_ALL":
return todos
case "SHOW_COMPLETED":
return todos.filter(t => t.completed)
case "SHOW_INCOMPLETED":
return todos.filter(t => !t.completed)
default:
throw new Error('Unknown filter: ' + filter)
}
}
const getCounter = (todos: Todo[]) => {
return {
allCount: todos.length,
completedCount: todos.filter(t => t.completed).length,
incompletedCount: todos.filter(t => !t.completed).length
}
}
const mapStateToProps = (state: any) => {
return {
todos: getVisibleTodos(state.todos, state.filter),
counter: getCounter(state.todos),
currentFilter: state.filter
};
};
const mapDispatchToProps = (dispatch: any) => {
return {
onAddTodo: (text: string) => {
dispatch(TodoAdd(text));
},
onToggle: (todoId: number) => {
dispatch(ToggleTodo(todoId));
},
onFilter: (filter: string) => {
dispatch(setVisibilityFilter(filter))
}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(App); |
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
Coche coche1 = new Coche(
"Kia",
"Niro",
"Gris",
1234
);
/**
* Ejercicio 1
*/
System.out.println("Mi coche es un " +
coche1.marca +
" " + coche1.modelo +
" de color " + coche1.color +
" con número de bastidor " + coche1.numBastidor
);
/**
* Ejercicio 2
*/
System.out.println(coche1);
/**
* Ejercicio 3
*/
/*coche1.frenar();
System.out.println(coche1);
coche1.acelerar();
coche1.acelerar();
System.out.println(coche1);
coche1.frenar();
System.out.println(coche1);*/
/**
* Ejercicio 4
*/
/*coche1.acelerar(20);
System.out.println(coche1);
coche1.frenar(15);
System.out.println(coche1);*/
/**
* Ejercicio 5, 6, 7
*/
Coche coche2 = new Coche(
"Ford",
"Fiesta",
"blanco",
5678
);
Coche coche3 = new Coche(
"Renault",
"Scenic",
"negro",
9123
);
Flota flota = new Flota();
flota.addCoche(coche1);
flota.addCoche(coche2);
flota.addCoche(coche3);
System.out.println(flota);
/**
* Ejercicio 5, 6
*/
/*if(!flota.removeCoche(9123)) {
System.out.println("No se encuentra el coche en la flota");
}
System.out.println(flota);*/
/**
* Ejercicio 7
*/
/*System.out.print("Introduce el número de bastidor: ");
int numBastidor = reader.nextInt();
if(!flota.removeCoche(numBastidor)) {
System.out.println("No existe ningún coche con número de bastidor " + numBastidor);
} else {
System.out.println("Se ha eliminado el coche con número de bastidor " + numBastidor);
}
System.out.println(flota);*/
/**
* Ejercicio 8
*/
Conductor conductor1 = new Conductor("Pepe");
Conductor conductor2 = new Conductor("María");
System.out.println(conductor1);
System.out.println(conductor2);
conductor1.asignarCoche(1234, flota);
System.out.println(conductor1);
/**
* Ejercicio 10, 11
*/
/*if(!conductor1.removeCoche()) {
System.out.println("Este conductor no tiene asignado ningún coche");
}
if(!conductor2.removeCoche()) {
System.out.println("Este conductor no tiene asignado ningún coche");
}
System.out.println(conductor1);*/
/**
* Ejercicio 12
*/
/*Coche cocheBuscado = flota.buscarCoche(1234);
if(cocheBuscado != null) {
conductor2.setCoche(cocheBuscado);
}
System.out.println(conductor2);*/
}
} |
import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/auth/user.entity';
import { v4 as uuid } from 'uuid';
import { CreateTestDto } from './dto/createTest.dto';
import { GetTestFilterDto } from './dto/get-tests-filter.dto';
import { Test } from './test.entity';
import { TestsRepository } from './tests.repository';
@Injectable()
export class TestsService {
constructor(
@InjectRepository(TestsRepository)
private testsRepository: TestsRepository,
) {}
getTests(filterDto: GetTestFilterDto, user: User): Promise<Test[]> {
return this.testsRepository.getTasks(filterDto, user);
}
async getTestById(id: string, user: User): Promise<Test> {
const found = await this.testsRepository.findOne({ where: { id, user } });
if (!found)
throw new NotFoundException(`Test with the ID "${id}" not found`);
return found;
}
createTest(createTestDto: CreateTestDto, user: User): Promise<Test> {
return this.testsRepository.createTest(createTestDto, user);
}
async deleteTest(id: string, user: User): Promise<void> {
const result = await this.testsRepository.delete({ id, user });
if (result.affected === 0) {
throw new NotFoundException(`Task with ID "${id}" not found`);
}
}
async updateTest(id: string, request: string, user: User): Promise<Test> {
const test = await this.getTestById(id, user);
test.request = request;
await this.testsRepository.save(test);
return test;
}
} |
Module mod_foam_emiss
! -----------------------------------------------------------------------------------------------
! Model of Anguelova & Gaiser (2013, RSE) with Yin et al. (2016) modifications for fast calculations
! Fast calculations obtained by using semi-closed form of the incoherent approach (with only one
! integration over the foam layer) instead of the general form (with 2 integrations from each stratum
! upward and downward).
!
! Created by Lise Kilic, France: Translated to Fortran from Yin et al. MATLAB code
! Modified by Magdalena Anguelova, Remote Sensing Division, NRL, Washngton, DC, USA:
! * Semi-closed (Yin et al.) and general (nguelova & Gaiser) forms of the emissivity
! incoherent approach verified
! * A few elements in the code corrected
! * Differences between semi-closed and genral forms quantified
! * This comparison is documented in a white paper
! -----------------------------------------------------------------------------------------------
IMPLICIT NONE
DOUBLE PRECISION :: pi=3.141592653589793238462643383279D0
CONTAINS
SUBROUTINE esf_anguelova(thetai,hz,seaDC,tin,vaf,evfoam,ehfoam)
IMPLICIT NONE
! INPUT
REAL (KIND=8) thetai ! incidence angle (deg) from air onto foam
REAL (KIND=8) hz ! frequency in gigahertz
REAL (KIND=8) tin ! foam thickness in cm
REAL (KIND=8) vaf ! upper limit of void fraction
COMPLEX (KIND=8) seaDC ! seawater permittivity
! OUTPUT
REAL (KIND=8) evfoam
REAL (KIND=8) ehfoam
! INTERNAL
REAL (KIND=8) aa
REAL (KIND=8) vfw
REAL (KIND=8) t
REAL (KIND=8) m
COMPLEX (KIND=8) sigfoam1
COMPLEX (KIND=8) sigfoam2
REAL (KIND=8) taof
REAL (KIND=8) sigw_re
REAL (KIND=8) sigw_im
! Variables for Simpson integration
REAL (KIND=8) a,b, aire
INTEGER n
REAL (KIND=8) h,SommePaire, SommeImpaire
INTEGER i
aa=0
vfw=0.01 ! foam void fraction at the foam-seawater boundary set at 1%
t=tin/100. ! thickness input is in cm, convert here to m
m=1 ! shape of void fraction profile is nominal exponential function
! Mixing rule for foam dielectric constant using seawater permittivity and foam void fraction
sigw_re=REAL(seaDC)
sigw_im=AIMAG(seaDC)
sigfoam1=(vaf+(1-vaf)*sqrt(Cmplx(sigw_re,sigw_im)))**2;
sigfoam2=(vfw+(1-vfw)*sqrt(Cmplx(sigw_re,sigw_im)))**2;
! INTEGRAL of SIMPSON
a=0.D0
b=t
n=10
aire = 0.D0
h = (b-a)/(n*2)
SommePaire = 0.D0
SommeImpaire = 0.D0
! Calculation of the sum of the odd indices
DO i=1, n-1
SommeImpaire = SommeImpaire + &
loss_factor((a+h*2.*i),t,thetai,vaf,vfw,m,hz,sigw_re,sigw_im)
ENDDO
! Calculation of the sum of the even indices
DO i=1, n
SommePaire = SommePaire + &
loss_factor((a+h*(2.*i-1)),t,thetai,vaf,vfw,m,hz,sigw_re,sigw_im)
ENDDO
! Final computation of the total area
aire = h*(loss_factor(a,t,thetai,vaf,vfw,m,hz,sigw_re,sigw_im) + &
loss_factor(b,t,thetai,vaf,vfw,m,hz,sigw_re,sigw_im) + &
2.*SommePaire + 4.*SommeImpaire)/3.
taof=aire ! total extinction in the foam layer
CALL IncohEmissivity_TwoLayer(sigfoam1,sigfoam2,seaDC,thetai,aa,taof,evfoam, ehfoam)
RETURN
END
!----------End of principal subroutine ------------------------------------
! %Description: Code computes incoherent emissivity of an inhomogeneous layer
! %separated by air on top and a homogeneous medium on the bottom, with
! %perfectly smooth parallel boundaries on both sides.
! %Input Variables:
! %eps2: dielectric constant of middle layer
! %eps3: dielectric constant of bottom layer
! %theta_i: incidence angle in air (deg)
! %a: Single scattering albedo
! %d: layer thickness (m)
! %kappa_e: extinction rate through layer (Np/m)
! %Output Products:
! %e_v_inc(theta_i): v-polarized emissivity
! %e_h_inc(theta_i): h-polarized emissivity
! %Book Reference: Section 12-12.2
SUBROUTINE IncohEmissivity_TwoLayer(eps2,eps3,epsw, theta_i,a, kappa_e,e_v_inc,e_h_inc)
IMPLICIT NONE
! ---INPUT---
COMPLEX (KIND=8) eps2
COMPLEX (KIND=8) eps3
COMPLEX (KIND=8) epsw
REAL (KIND=8) theta_i
REAL (KIND=8) a
REAL (KIND=8) kappa_e
! ---OUTPUT---
REAL (KIND=8) e_v_inc
REAL (KIND=8) e_h_inc
! ---INTERNE---
COMPLEX (KIND=8) eps1
REAL (KIND=8) theta1
REAL (KIND=8) theta2
COMPLEX (KIND=8) n1
COMPLEX (KIND=8) n2
REAL (KIND=8) rhoh
REAL (KIND=8) rhov
REAL (KIND=8) gammah12
REAL (KIND=8) gammav12
REAL (KIND=8) gammah23
REAL (KIND=8) gammav23
REAL (KIND=8) tauh
REAL (KIND=8) tauv
REAL (KIND=8) Th
REAL (KIND=8) Tv
REAL (KIND=8) trans
eps1 = 1 ! Air permittivity (layer 1)
n1 = sqrt(eps2) ! Index of refraction for air, no further use
n2 = sqrt(eps3) ! Index of refraction for foam, no further use
theta1 = theta_i*pi/180
theta2 = asin(abs(n1/n2) * sin(theta1))*180/pi ! Incidence angle in medium 2 (refracted)
! -- calculate reflectivies at the two interfaces
! 12 interface (air-foam in our case; use foam permittivity for the air-foam boundary)
CALL ReflTransm_PlanarBoundary(eps1,eps2,theta_i,rhoh,rhov,gammah12,gammav12,tauh,tauv,Th,Tv);
! 23 interface (foam-seawater in our case; use foam permittivity for the foam-seawater boundary)
CALL ReflTransm_PlanarBoundary(eps2,eps3,theta2 ,rhoh,rhov,gammah23,gammav23,tauh,tauv,Th,Tv);
! extinction coefficient inside medium (foam layer in our case)
trans = exp(-kappa_e);
e_v_inc = ( (1.D0 - gammav12)/(1.D0 - gammav12*gammav23*trans*trans) ) * &
( (1.D0 + gammav23*trans)*(1.D0 - a)*(1.D0 - trans) + &
(1.D0 - gammav23) * trans )
e_h_inc = ( (1.D0 - gammah12)/(1.D0 - gammah12*gammah23*trans*trans) ) * &
( (1.D0 + gammah23*trans)*(1.D0 - a)*(1.D0 - trans) + &
(1.D0 - gammah23) * trans )
RETURN
END
! %Code 2.3: Oblique Reflection and Transmission @ Planar Boundry
! %Description: Code computes the reflection coefficients, transmission
! %coefficients, reflectivities and transmissivities for incidence in
! %medium (medium 1) upon the planar boundary of a lossless or lossy
! %medium (medium 2) at any incidence angle, for both h and v polarizations
! %Input Variables:
! %eps1: eps1r -j*eps1i: relative dielectric constant of medium 1
! %eps2 = eps2r-j*eps2i: relative dielectric constant of medium 2
! %theta1d: incidence angle in medium 1 in degrees
!%Output Products:
! %rhoh: reflection coefficient for h pol
! %rhov: reflection coefficient for v pol
! %gammah:reflectivity for h pol
! %gammav: reflectivity for v pol
! %tauh: transmission coefficient for h pol
! %tauv: transmission coefficient for v pol
! %Th: transmissivity for h pol
! %Tv:transmissivity for v pol
!%Book Reference: Sections 2-7 & 2-8
!%Example call: [rhoh rhov gammah gammav tauh tauv Th Tv] = ReflTransm_PlanarBoundary(eps1, eps2, theta1d)
!%Computes
SUBROUTINE ReflTransm_PlanarBoundary(eps1, eps2, theta1d, rhoh, rhov, gammah, gammav, tauh, tauv, Th, Tv)
IMPLICIT NONE
! ---INPUT---
COMPLEX (KIND=8) eps1
COMPLEX (KIND=8) eps2
REAL (KIND=8) theta1d
! ---OUTPUT---
REAL (KIND=8) rhoh
REAL (KIND=8) rhov
REAL (KIND=8) gammah
REAL (KIND=8) gammav
REAL (KIND=8) tauh
REAL (KIND=8) tauv
REAL (KIND=8) Th
REAL (KIND=8) Tv
! ---INTERNE---
REAL (KIND=8) theta1
REAL (KIND=8) sin_theta2
REAL (KIND=8) cos_theta2
theta1 = theta1d*pi/180
sin_theta2 = sqrt(eps1)/sqrt(eps2)*sin(theta1);
cos_theta2 = sqrt(1 - sin_theta2**2);
rhoh = (sqrt(eps1)*cos(theta1)-sqrt(eps2)*cos_theta2) / (sqrt(eps1)*cos(theta1) + sqrt(eps2)*cos_theta2);
rhov = (sqrt(eps1)*cos_theta2-sqrt(eps2)*cos(theta1)) / (sqrt(eps1)*cos_theta2 + sqrt(eps2)*cos(theta1));
tauh = 1 + rhoh;
tauv = (1 + rhov)*(cos(theta1)/cos_theta2);
gammah = abs(rhoh)**2;
gammav = abs(rhov)**2;
Th = 1-gammah;
Tv = 1-gammav;
RETURN
END
! ---loss factor----------------------------------------------------------------
REAL (Kind=8) FUNCTION loss_factor(z,t,thetai,vaf,vfw,m,hz,sigw_re,sigw_im)
! calul taof
IMPLICIT NONE
! ---INPUT---
REAL (Kind=8) z
REAL (KIND=8) t
REAL (KIND=8) thetai
REAL (KIND=8) vaf
REAL (KIND=8) vfw
REAL (KIND=8) m
REAL (KIND=8) hz
REAL (KIND=8) sigw_re
REAL (KIND=8) sigw_im
! ---OUTPUT---
! REAL (KIND=8) :: loss_factor
! ---INTERNE---
REAL (KIND=8) :: az
REAL (KIND=8) :: tz
az=alphaz(z,t,vaf,vfw,m,hz,sigw_re,sigw_im)
tz=thetaz(z,t,thetai,vaf,vfw,m,hz,sigw_re,sigw_im)
loss_factor=2*az/cos(tz)
RETURN
END FUNCTION loss_factor
! ---void fraction profile------------------------------------------------------
COMPLEX (KIND=8) FUNCTION void_fraction_profile(z,t,vaf,vfw,m,hz,sigw_re,sigw_im)
! retourne la valeur de permitivité de l'écume sigfoam
IMPLICIT NONE
! ---INPUT---
REAL (KIND=8) z
REAL (KIND=8) t
REAL (KIND=8) vaf
REAL (KIND=8) vfw
REAL (KIND=8) m
REAL (KIND=8) hz
REAL (KIND=8) sigw_re
REAL (KIND=8) sigw_im
! ---OUTPUT---
! COMPLEX (KIND=8) void_fraction_profile
! ---INTERNE---
REAL (KIND=8) av
REAL (KIND=8) bv
REAL (KIND=8) fa
av=vaf+m
bv=1./t*log((av-vfw)/m)
fa=av-m*exp(bv*z)
! fa(fa<vfw)=vfw;
! Permittivity profile
! [sigw_re, sigw_im]=eps_klein_swift(T,S,hz);
void_fraction_profile=(fa+(1-fa)*sqrt(Cmplx(sigw_re,sigw_im)))**2
RETURN
END FUNCTION void_fraction_profile
! ----------------thetaz--------------------------------------------------------
REAL (KIND=8) FUNCTION thetaz(z,t,thetai,vaf,vfw,m,hz,sigw_re,sigw_im)
IMPLICIT NONE
! ---INPUT---
REAL (KIND=8) z
REAL (KIND=8) t
REAL (KIND=8) thetai
REAL (KIND=8) vaf
REAL (KIND=8) vfw
REAL (KIND=8) m
REAL (KIND=8) hz
REAL (KIND=8) sigw_re
REAL (KIND=8) sigw_im
! ---OUTPUT---
! REAL (KIND=8) thetaz
! ---INTERNE---
REAL (KIND=8) k0
REAL (KIND=8) az
REAL (KIND=8) bz
REAL (KIND=8) pz
REAL (KIND=8) qz
k0=2*pi*hz*1.D9/3.D8
az=alphaz(z,t,vaf,vfw,m,hz,sigw_re,sigw_im)
bz=betaz(z,t,vaf,vfw,m,hz,sigw_re,sigw_im)
pz=2*az*bz
!qz=bz**2-az**2-k0**2*sin(thetai*pi/180.)
qz=bz**2-az**2-k0**2*(sin(thetai*pi/180.))**2
thetaz=atan(sqrt(2.)*k0*sin(thetai*pi/180.)/sqrt(sqrt(pz**2+qz**2)+qz))
RETURN
END FUNCTION thetaz
! -------betaz------------------------------------------------------------------
REAL (KIND=8) FUNCTION betaz(z,t,vaf,vfw,m,hz,sigw_re,sigw_im)
IMPLICIT NONE
! ---INPUT---
REAL (KIND=8) z
REAL (KIND=8) t
REAL (KIND=8) vaf
REAL (KIND=8) vfw
REAL (KIND=8) m
REAL (KIND=8) hz
REAL (KIND=8) sigw_re
REAL (KIND=8) sigw_im
! ---OUTPUT---
! REAL (KIND=8) betaz
! ---INTERNE---
REAL (KIND=8) k0
COMPLEX (KIND=8) sigfoam
! The index of refraction, of air, is 1.000293.
! The Speed of Light, in a vacuum, is defined to be 299792458 m/s
! So the speed of light in air is 299792458/1.000293, or about 299704644.54 m/s
k0=2*pi*hz*1.D9/3.D8;
sigfoam=void_fraction_profile(z,t,vaf,vfw,m,hz,sigw_re,sigw_im)
betaz=k0*real(sqrt(sigfoam))
RETURN
END FUNCTION betaz
! -----------------alphaz-------------------------------------------------------
REAL (KIND=8) FUNCTION alphaz(z,t,vaf,vfw,m,hz,sigw_re,sigw_im)
IMPLICIT NONE
! ---INPUT----
REAL (KIND=8) z
REAL (KIND=8) t
REAL (KIND=8) vaf
REAL (KIND=8) vfw
REAL (KIND=8) m
REAL (KIND=8) hz
REAL (KIND=8) sigw_re
REAL (KIND=8) sigw_im
! ---OUTPUT---
! REAL (KIND=8) alphaz
! ---INTERNE---
REAL (KIND=8) k0
COMPLEX (KIND=8) sigfoam
k0=2*pi*hz*1.D9/3.D8
sigfoam=void_fraction_profile(z,t,vaf,vfw,m,hz,sigw_re,sigw_im)
alphaz=k0*abs(aimag(sqrt(sigfoam)))
RETURN
END FUNCTION alphaz
! -----END OF MODULE E SEA FOAM------------------------------------
END |
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteUser = exports.updateUser = exports.readAllUsers = exports.readUser = exports.createUser = void 0;
const Users_1 = __importDefault(require("../models/Users"));
const mongoose_1 = __importDefault(require("mongoose"));
function createUser(req, res) {
return __awaiter(this, void 0, void 0, function* () {
try {
const { username, password } = req.body;
const user = new Users_1.default({
_id: new mongoose_1.default.Types.ObjectId(),
username,
password,
});
const savedUser = yield user.save();
res.status(201).json({ user: savedUser });
}
catch (error) {
res.status(500).json({ error });
res.render('error', { error: error });
}
});
}
exports.createUser = createUser;
;
function readUser(req, res) {
return __awaiter(this, void 0, void 0, function* () {
try {
const userID = req.params.userID;
const user = yield Users_1.default.findById(userID).select('-__v');
user
? res.status(200).json({ user })
: res.status(404).json({ message: "Not found" });
}
catch (error) {
res.status(500).json({ error });
res.render('error', { error: error });
}
});
}
exports.readUser = readUser;
;
function readAllUsers(req, res) {
return __awaiter(this, void 0, void 0, function* () {
try {
const users = yield Users_1.default.find().select('-__v');
res.status(200).json({ users });
}
catch (error) {
res.status(500).json({ error });
res.render('error', { error: error });
}
});
}
exports.readAllUsers = readAllUsers;
;
function updateUser(req, res) {
return __awaiter(this, void 0, void 0, function* () {
try {
const userID = req.params.userID;
console.log('User ID:', userID);
const user = yield Users_1.default.findById(userID);
if (user) {
user.set(req.body);
const updatedUser = yield user.save();
return res.status(200).json({ users: updatedUser });
}
else {
return res.status(404).json({ message: "Not found" });
}
}
catch (error) {
res.status(500).json({ error });
res.render('error', { error: error });
}
});
}
exports.updateUser = updateUser;
;
function deleteUser(req, res) {
return __awaiter(this, void 0, void 0, function* () {
try {
const userID = req.params.userID;
const result = yield Users_1.default.findByIdAndDelete(userID);
return result
? res.status(204).send()
: res.status(404).json({ message: "Not found" });
}
catch (error) {
res.status(500).json({ error });
res.render('error', { error: error });
}
});
}
exports.deleteUser = deleteUser;
; |
package com.osmi.segundamano.converter.data.repository
import com.google.gson.GsonBuilder
import com.osmi.segundamano.converter.data.datasource.RatesDataSource
import com.osmi.segundamano.converter.data.service.ConvertService
import com.osmi.segundamano.converter.domain.Rates
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class RatesRepository @Inject constructor(private val dataSource: RatesDataSource) {
companion object {
fun getService(): ConvertService {
val okHttpClient = OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build()
return Retrofit.Builder()
.baseUrl("http://data.fixer.io")
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.build()
.create(ConvertService::class.java)
}
}
suspend fun getRates(date: String): Rates? {
// first try to get rates by network
try {
val service = getService()
val response = service.getRates(date = date, base = "EUR", symbols = "USD")
val rates = Rates(response.rates.USD, response.date)
dataSource.saveRates(rates)
return rates
} catch (e: Exception) {
return dataSource.getRatesByDate(date)
}
}
} |
import * as React from 'react';
import { useEffect, useState } from "react";
import DataTable from "../../../examples/Tables/DataTable";
import MDButton from "../../../components/MDButton"
import MDBox from "../../../components/MDBox"
import MDTypography from "../../../components/MDTypography"
import Card from "@mui/material/Card";
import axios from "axios";
import { apiUrl } from '../../../constants/constants';
import { Switch } from '@mui/material';
export default function RegisteredUsers({ dailyContest }) {
let baseUrl = process.env.NODE_ENV === "production" ? "/" : "http://localhost:5000/"
let [updateSwitch, setUpdateSwitch] = React.useState(true);
// const [dailyContest,setDailyContest] = useState([]);
const [userContestDetail, setUserContestDetails] = useState([]);
let columns = [
{ Header: "#", accessor: "index", align: "center" },
// { Header: "Remove", accessor: "remove", align: "center" },
{ Header: "Name", accessor: "fullname", align: "center" },
{ Header: "Email", accessor: "email", align: "center" },
{ Header: "Mobile", accessor: "mobile", align: "center" },
{ Header: "Total TestZone", accessor: "totalContest", width: "12.5%", align: "center" },
{ Header: "Paid TestZone", accessor: "paidContest", width: "12.5%", align: "center" },
{ Header: "Free TestZone", accessor: "freeContest", width: "12.5%", align: "center" },
{ Header: "Trading Day", accessor: "tradingDay", width: "12.5%", align: "center" },
{ Header: "Mock/Live", accessor: "mockLive", width: "12.5%", align: "center" },
]
useEffect(() => {
axios.get(`${baseUrl}api/v1/dailycontest/usercontestdata/${dailyContest?._id}`, { withCredentials: true })
.then((res) => {
setUserContestDetails(res.data.data);
}).catch((err) => {
return new Error(err);
})
}, [])
let rows = []
async function switchUser(userId, isLive) {
const res = await fetch(`${baseUrl}api/v1/dailycontest/switchUser/${dailyContest?._id}`, {
method: "PATCH",
credentials: "include",
headers: {
"content-type": "application/json",
"Access-Control-Allow-Credentials": true
},
body: JSON.stringify({
userId, isLive
})
});
const data = await res.json();
console.log(data);
if (data.status === 422 || data.error || !data) {
} else {
setUpdateSwitch(!updateSwitch)
}
}
dailyContest?.participants?.map((elem, index) => {
const userContestInfo = userContestDetail.filter((subelem) => {
return elem?.userId._id?.toString() === subelem?.userId?.toString();
})
let featureObj = {}
featureObj.index = (
<MDTypography component="a" variant="caption" color="text" fontWeight="medium">
{index + 1}
</MDTypography>
);
featureObj.fullname = (
<MDTypography component="a" variant="caption" color="text" fontWeight="medium">
{elem?.userId?.first_name} {elem?.userId?.last_name}
</MDTypography>
);
featureObj.email = (
<MDTypography component="a" variant="caption" color="text" fontWeight="medium">
{elem?.userId?.email}
</MDTypography>
);
featureObj.mobile = (
<MDTypography component="a" variant="caption" color="text" fontWeight="medium">
{elem?.userId?.mobile}
</MDTypography>
);
featureObj.totalContest = (
<MDTypography component="a" variant="caption" fontWeight="medium">
{userContestInfo[0]?.totalContestsCount}
</MDTypography>
);
featureObj.paidContest = (
<MDTypography component="a" variant="caption" fontWeight="medium">
{userContestInfo[0]?.totalPaidContests}
</MDTypography>
);
featureObj.freeContest = (
<MDTypography component="a" variant="caption" fontWeight="medium">
{userContestInfo[0]?.totalFreeContests}
</MDTypography>
);
featureObj.tradingDay = (
<MDTypography component="a" variant="caption" fontWeight="medium">
{userContestInfo[0]?.totalTradingDays}
</MDTypography>
);
featureObj.mockLive = (
<MDTypography component="a" variant="caption" fontWeight="medium">
<Switch checked={elem.isLive} onChange={() => { switchUser(elem?.userId?._id, elem?.isLive) }} />
</MDTypography>
);
rows.push(featureObj)
})
return (
<Card>
<MDBox display="flex" justifyContent="space-between" alignItems="left">
<MDBox width="100%" display="flex" justifyContent="center" alignItems="center" sx={{ backgroundColor: "lightgrey", borderRadius: "2px" }}>
<MDTypography variant="text" fontSize={12} color="black" mt={0.7} alignItems="center" gutterBottom>
Participated Users({dailyContest?.participants?.length})
</MDTypography>
</MDBox>
</MDBox>
<MDBox mt={1}>
<DataTable
table={{ columns, rows }}
showTotalEntries={false}
isSorted={false}
entriesPerPage={false}
/>
</MDBox>
</Card>
);
} |
package com.pmv.saveImage.model
import com.fasterxml.jackson.annotation.JsonIgnore
import org.hibernate.annotations.ColumnDefault
import org.hibernate.annotations.Type
import java.io.Serializable
import java.sql.Blob
import java.util.*
import javax.persistence.*
@Entity
@Table(name = "places")
data class Place(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
val id: Long = 0,
@Column(name = "name", nullable = false, length = 1000)
var name: String? = "",
@Column(name = "description", nullable = true)
@ColumnDefault("''")
@Lob
@Type(type = "org.hibernate.type.TextType")
var description: String? = "",
@Column(name = "dateCreated")
var dateCreated: Date = Date(),
@Column(name = "dateChanged")
var dateChanged: Date = Date(),
@ManyToOne(cascade = [CascadeType.ALL])
@JoinColumn(name = "images_id")
@JsonIgnore
var images: FileData? = null
): Serializable |
function [outliers, h] = xbarplot(data,conf,specs,sigmaest)
%XBARPLOT X-bar chart for monitoring the mean.
% XBARPLOT(DATA,CONF,SPECS,SIGMAEST) produces an xbar chart of
% the grouped responses in DATA. The rows of DATA contain
% replicate observations taken at a given time. The rows
% should be in time order.
%
% CONF (optional) is the confidence level of the upper and
% lower plotted confidence limits. CONF is 0.9973 by default.
% This means that 99.73% of the plotted points should fall
% between the control limits if the process is in control.
%
% SPECS (optional) is a two element vector for the lower and
% upper specification limits of the response.
%
% SIGMAEST (optional) specifies how XBARPLOT should estimate
% sigma. Possible values are 'std' (the default) to use the
% average within-subgroup standard deviation, 'range' to use the
% average subgroup range, and 'variance' to use the square root
% of the pooled variance.
%
% OUTLIERS = XBARPLOT(DATA,CONF,SPECS,SIGMAEST) returns a vector
% of indices to the rows where the mean of DATA is out of
% control.
%
% [OUTLIERS, H] = XBARPLOT(DATA,CONF,SPECS,SIGMAEST) also returns
% a vector of handles, H, to the plotted lines.
% Copyright 1993-2004 The MathWorks, Inc.
% $Revision: 2.11.2.3 $ $Date: 2004/03/09 16:17:06 $
if nargin < 2
conf = 0.9973;
end
if isempty(conf)
conf = 0.9973;
end
[m,n] = size(data);
xbar = double(mean(data')');
avg = mean(xbar);
if (n < 2)
error('stats:xbarplot:SubgroupsRequired',...
'XBARPLOT requires subgroups of at least 2 observations.');
end
% Need a sigma estimate to compute control limits
if (nargin < 4)
sigmaest = 's';
elseif ((strcmp(sigmaest,'range') | strcmp(sigmaest,'r')) & (n>25))
error('stats:xbarplot:RangeNotAllowed',...
['XBARPLOT cannot use a range estimate if subgroups have' ...
' more than 25 observations.']);
end
if (strcmp(sigmaest,'variance') | strcmp(sigmaest,'v')) % use pooled variance
s = sqrt(sum(sum(((data - xbar(:,ones(n,1))).^2)))./(m*(n-1)));
elseif (strcmp(sigmaest,'range') | strcmp(sigmaest,'r')) % use average range
r = (range(data'))';
d2 = [0.000 1.128 1.693 2.059 2.326 2.534 2.704 2.847 2.970 3.078 ...
3.173 3.258 3.336 3.407 3.472 3.532 3.588 3.640 3.689 3.735 ...
3.778 3.819 3.858 3.895 3.931];
s = mean(r ./ d2(n));
else % estimate sigma using average s
svec = (std(data'))';
c4 = sqrt(2/(n-1)).*gamma(n/2)./gamma((n-1)/2);
s = mean(svec ./ c4);
end
smult = norminv(1-.5*(1-conf));
delta = double(smult * s ./ sqrt(n));
UCL = avg + delta;
LCL = avg - delta;
tmp = NaN;
incontrol = tmp(1,ones(1,m));
outcontrol = incontrol;
greenpts = find(xbar > LCL & xbar < UCL);
redpts = find(xbar <= LCL | xbar >= UCL);
incontrol(greenpts) = xbar(greenpts);
outcontrol(redpts) = xbar(redpts);
samples = (1:m);
hh = plot(samples,xbar,samples,UCL(ones(m,1),:),'r-',samples,avg(ones(m,1),:),'g-',...
samples,LCL(ones(m,1),:),'r-',samples,incontrol,'b+',...
samples,outcontrol,'r+');
if any(redpts)
for k = 1:length(redpts)
text(redpts(k) + 0.5,outcontrol(redpts(k)),num2str(redpts(k)));
end
end
text(m+0.5,UCL,'UCL');
text(m+0.5,LCL,'LCL');
text(m+0.5,avg,'CL');
title('Xbar Chart');
if nargin>=3 && ~isempty(specs)
set(gca,'NextPlot','add');
LSL = specs(1);
USL = specs(2);
t3 = text(m + 0.5,USL,'USL');
t4 = text(m + 0.5,LSL,'LSL');
hh1 = plot(samples,LSL(ones(m,1),:),'g-',samples,USL(ones(m,1),:),'g-');
set(gca,'NextPlot','replace');
hh = [hh; hh1];
end
if nargout > 0
outliers = redpts;
end
if nargout == 2
h = hh;
end
set(hh([3 5 6]),'LineWidth',2);
xlabel('Samples');
ylabel('Measurements'); |
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const uniqueValidator = require('mongoose-unique-validator');
const bcrypt = require('bcryptjs'); // Import bcrypt library
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true, minlength: 6 },
votedQuestions: [{ type: Schema.Types.ObjectId, ref: 'Question' }],
downvotedQuestions: [{ type: Schema.Types.ObjectId, ref: 'Question' }],
comments: [{ type: Schema.Types.ObjectId, ref: 'Comment' }], // Reference to comments made by the user
});
userSchema.plugin(uniqueValidator);
// Hash the password before saving
userSchema.pre('save', async function (next) {
if (!this.isModified('password')) {
return next();
}
try {
const salt = await bcrypt.genSalt(10);
this.password = await bcrypt.hash(this.password, salt);
next();
} catch (err) {
return next(err);
}
});
const User = mongoose.model('User', userSchema);
module.exports = User; |
import { User, UserDocument } from '@hepsikredili/api/main/shared';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { hash } from 'bcrypt';
import * as $ from 'mongo-dot-notation';
import { FilterQuery, Model } from 'mongoose';
import { CreateUserDto } from '../dtos/create-user.dto';
import { QueryUserDto } from '../dtos/query-user.dto';
import { UpdateUserDto } from '../dtos/update-user.dto';
@Injectable()
export class ApiMainUserService {
constructor(
@InjectModel(User.name)
private readonly userModel: Model<UserDocument>
) {}
async findAll(_queryUserDto: QueryUserDto): Promise<User[]> {
// const { search } = queryUserDto;
const filter: FilterQuery<UserDocument> = {};
// if (search) filter.$text = { $search: search?.trim() };
return await this.userModel.find(filter).exec();
}
async findOneById(id: string): Promise<User | null> {
return await this.userModel.findById(id).exec();
}
async findOneByEmail(email: string): Promise<User | null> {
return await this.userModel
.findOne({ email: email })
.select('+password')
.exec();
}
async create(createUserDto: CreateUserDto): Promise<User> {
const hashedPassword = await hash(createUserDto.password, 10);
createUserDto.password = hashedPassword;
//TODO: Change Kind
const user = new this.userModel({
accounts: [createUserDto.account],
emailVerified: false,
email: createUserDto.email,
password: createUserDto.password,
role: createUserDto.role,
});
return await user.save();
}
async update(id: string, updateUserDto: UpdateUserDto) {
const instructions = $.flatten(updateUserDto);
return await this.userModel
.findByIdAndUpdate(id, instructions, { new: true })
.exec();
}
async remove(id: string) {
return await this.userModel.findByIdAndRemove(id, { new: true }).exec();
}
} |
@model UserModel
@{
ViewData["Title"] = "Create User";
}
<div class="container">
<div class="row">
<div class="col-md-4">
<form asp-action="Create" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="FullName" class="control-label"></label>
<input asp-for="FullName" type="text" class="form-control" />
<span asp-validation-for="FullName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Email" class="control-label"></label>
<input asp-for="Email" type="email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Password" class="control-label"></label>
<input asp-for="Password" type="password" class="form-control" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ImageUrl" class="control-label"></label>
<input id="imageFile" name="imageFile" class="form-control" type="file" />
<span asp-validation-for="ImageUrl" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="TitleId" class="control-label"></label>
<Select asp-for="TitleId" class="form-control" required>
<option value="" selected disabled>Select One</option>
@if (ViewBag.Titles != null)
{
foreach (var title in (List<RoleListModel>)ViewBag.Titles)
{
<option value="@title.Id">@title.Name</option>
}
}
</Select>
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
</div> |
import React from "react";
export default function Destination({ props, destinationState }) {
const { name, images, description, distance, travel } = props;
const [baseImg, setBaseImg] = React.useState("./");
const links = document.getElementsByClassName("destination-btns");
function changetab(num) {
for (let i = 0; i < links.length; i++) {
links[i].classList.remove("active");
links[i].setAttribute("aria-selected", "false");
}
links[num].classList.add("active");
}
React.useEffect(() => {
images && setBaseImg(images.png);
}, [images]);
return (
<div className="destination">
<div>
<h2 className="uppercase letter-spacing-2">
<span
className=""
style={{
color: "hsl(var(--clr-white) / 0.25)",
marginRight: ".5em",
}}
>
01
</span>{" "}
pick your destination
</h2>
<img src={baseImg} alt="planet photo" />
</div>
<div>
<div className="tabs-btns underline flex">
<button
onClick={() => {
destinationState("moon");
changetab(1);
}}
aria-selected="true"
className="destination-btns uppercase text-accent bg-transparent ff-main letter-spacing-2"
>
Moon
</button>
<button
onClick={() => {
destinationState("mars");
changetab(1);
}}
// aria-selected="false"
className="destination-btns uppercase text-accent bg-transparent ff-main letter-spacing-2"
>
Mars
</button>
<button
onClick={() => {
destinationState("europa");
changetab(2);
}}
// aria-selected="false"
className="destination-btns uppercase text-accent bg-transparent ff-main letter-spacing-2"
>
Europa
</button>
<button
onClick={() => {
destinationState("titan");
changetab(3);
}}
// aria-selected="false"
className="destination-btns uppercase text-accent bg-transparent ff-main letter-spacing-2"
>
titan
</button>
</div>
<article>
<h1 className="fs-7 ff-secondary uppercase">{name}</h1>
<p>{description}</p>
<div className="flex destination-last-section">
<div>
<h4 className="uppercase fs-4 ff-secondary letter-spacing-1">
avg Distance
</h4>
<h4 className="fs-5 ff-secondary uppercase">{distance}</h4>
</div>
<div>
<h4 className="uppercase fs-4 ff-secondary letter-spacing-1">
est. travel time
</h4>
<h4 className="fs-5 ff-secondary uppercase">{travel}</h4>
</div>
</div>
</article>
</div>
</div>
);
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<title>lemon</title>
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet" media="(max-width: 640px)" href="css/mobile.css">
<link rel="stylesheet" media="(min-width: 641px) and (max-width: 1199px)" href="css/tablet.css">
<link rel="stylesheet" media="(min-width: 1200px)" href="css/desktop.css">
</head>
<body>
<script>
document.write('<script src="http://' + (location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1"></' + 'script>')
</script>
<header class="welcome">
<div class="container header-container">
<img class="lemon-logo" src="images/logo_copy_4631.png" alt="lemon logo">
<nav class="menu">
<button class="button menu-button"><span class="menu-button-text">Open menu</span></button>
<ul class="menu-list">
<li class="menu-list-item"><a href="#0" class="menu-list-item-link">Home</a></li>
<li class="menu-list-item"><a href="#0" class="menu-list-item-link">Recipes</a></li>
<li class="menu-list-item"><a href="#0" class="menu-list-item-link">Photo Galleries</a></li>
<li class="menu-list-item"><a href="#0" class="menu-list-item-link">Videos</a></li>
<li class="menu-list-item"><a href="#0" class="menu-list-item-link">All Categories</a></li>
</ul>
</nav>
<form>
<input class="search" type="search" placeholder="Find a recipe" required>
</form>
</div>
</header>
<section class="posts">
<img class="" src="images/rectangle_1_copy_3_5867.png" alt="">
<h2 class="section-headline">Get it recipe</h2>
<article class="post">
<img class="post-image" src="images/rectangle_3_copy_4_4715.png" alt="">
<div class="container post-preview">
<h3 class="post-preview-headline"><a class="post-preview-headline-link" href="#0">raspberry & cream frozen yogurt pie</a></h3>
<div class="post-preview-meta">
<span class="meta time-cooking">35mins</span>
<span class="meta comments">7</span>
<span class="meta views">14</span>
</div>
</div>
</article>
<article class="post">
<img class="post-image" src="images/rectangle_3_copy_3_5848.png" alt="">
<div class="container post-preview">
<h3 class="post-preview-headline"><a class="post-preview-headline-link" href="#0">Giant ice cream sandwich</a></h3>
<div class="post-preview-meta">
<span class="meta time-cooking">20mins</span>
<span class="meta comments">4</span>
<span class="meta views">356</span>
</div>
</div>
</article>
<article class="post">
<img class="post-image" src="images/rectangle_3_copy_5_4693.png" alt="">
<div class="container post-preview">
<h3 class="post-preview-headline"><a class="post-preview-headline-link" href="#0">Dark chocolate crunch ice cream sandwich cake</a></h3>
<div class="post-preview-meta">
<span class="meta time-cooking">15mins</span>
<span class="meta comments">4</span>
<span class="meta views">167</span>
</div>
</div>
</article>
</section>
<aside class="container post-group">
<div class="recipe-post-group">
<div class="recipe-post-group-button">
<button class="recipe-post-level-button"><span>Easy</span></button>
<button class="recipe-post-level-button"><span>Middle</span></button>
<button class="recipe-post-level-button"><span>Long</span></button>
</div>
<article class="recipe-post">
<div class="recipe-post-image-container">
<img class="recipe-post-image" src="images/rectangle_3_copy_10_4907.png" alt="">
</div>
<div class="recipe-post-meta">
<address class="author">by <span class="author-name">Smuckersreg toppings</span></address>
<h3 class="recipe-post-headline"><a class="recipe-post-headline-link" href="#0">Thanks for the recipe lorem ipsum bla bla bla Thanks for the recipe lore</a></h3>
</div>
</article>
<article class="recipe-post">
<div class="recipe-post-image-container">
<img class="recipe-post-image" src="images/rectangle_3_copy_11_4900.png" alt="">
</div>
<div class="recipe-post-meta">
<address class="author">by <span class="author-name">Smuckersreg toppings</span></address>
<h3 class="recipe-post-headline"><a class="recipe-post-headline-link" href="#0">Thanks for the recipe lorem nks for the recipe</a></h3>
</div>
</article>
<article class="recipe-post">
<div class="recipe-post-image-container">
<img class="recipe-post-image" src="images/rectangle_3_copy_12_4893.png" alt="">
</div>
<div class="recipe-post-meta">
<address class="author">by <span class="author-name">Smuckersreg toppings</span></address>
<h3 class="recipe-post-headline"><a class="recipe-post-headline-link" href="#0">Thanks for the recipe lorem nks for the recipe</a></h3>
</div>
</article>
</div>
<div class="recipe-post-footer">
<address class="socials-container">
<ul class="socials">
<li class="socials-item">
<a class="socials-item-link socials-item-link-print" href="#0">
<span class="socials-item-link-text">print</span>
</a>
</li>
<li class="socials-item">
<a class="socials-item-link socials-item-link-mail" href="#0">
<span class="socials-item-link-text">mail</span>
</a>
</li>
<li class="socials-item">
<a class="socials-item-link socials-item-link-facebook" href="#0">
<span class="socials-item-link-text">facebook</span>
</a>
</li>
<li class="socials-item">
<a class="socials-item-link socials-item-link-pinterest" href="#0">
<span class="socials-item-link-text">pinterest</span>
</a>
</li>
</ul>
</address>
<button class="button">View more</button>
</div>
</aside>
<aside class="popular">
<div class="container">
<h2 class="popular-headline"><a class="popular-headline-link" href="#0">Popular now</a></h2>
<div class="popular-post">
<h3 class="popular-post-headline"><a class="popular-post-headline-link" href="#0">Vanilla frozen coffee</a></h3>
<div class="popular-post-text">
<p>Mix coffee, sugar and creamer. Pour into blender and add ice cubes. Blend until smooth.</p>
</div>
<div class="post-preview-meta">
<button>Get it recipe</button>
<span class="meta time-cooking">6mins</span>
<span class="meta comments">240</span>
<span class="meta views">400</span>
</div>
</div>
</div>
</aside>
</body>
</html> |
import Phaser from "phaser"
//Common System Scripts
import Score from "../CommonSystem/Score"
import ShowMessage from "../CommonSystem/ShowMessage"
import DropTimeCounter from "../CommonSystem/DropTimeCounter"
import GameTimer from "../CommonSystem/GameTimer"
import GameoverMessage from "../CommonSystem/GameOverMessage"
import GameAchievement from "../CommonSystem/GameAchievement"
//CatchFruit Game Scripts
import StarsSpawner from "./StarsSpawner"
import GameTutorial from "./GameTutorial"
export default class CatchFruitGameScene extends Phaser.Scene{
constructor(){
super("CatchFruit")
}
//第一步,預先載入圖片
preload(){
this.modifyDatas = this.scene.settings.data
// console.log(this.modifyDatas);
//load image
Object.keys(this.modifyDatas).forEach((key)=>{
this.modifyDatas[key].items.forEach((itemObj)=>{
if( itemObj.img ) {
if(this.textures.list[itemObj.name]){
// console.log("remove");
this.textures.remove(itemObj.name)
}
// console.log("add", itemObj);
this.load.image( itemObj.name, itemObj.img.src )
}
})
})
this.load.image('startGameLabel','/img/Games/Common/gameover/startGameLabel.png')
this.load.image('startGameButton', '/img/Games/Common/gameover/startGameButton.png')
this.load.image('gameoverLabel','/img/Games/Common/gameover/gameoverLabel.png')
this.load.image('playAgainButton', '/img/Games/Common/gameover/playAgainButton.png')
this.load.image('ground', '/img/Games/CatchFruitGame/platform.png');
this.load.image('arrowButton','/img/Games/CatchFruitGame/arrowButton.png');
this.load.image('player','/img/Games/CatchFruitGame/boy.png');
// this.load.spritesheet('dude','/img/Games/CatchFruitGame/dude.png',{
// frameWidth: 32, frameHeight:48
// });
//console.log("preload");
}
// 第五步,開始遊戲
startGame = () => {
//create score board
this.scoreText.showScoreText()
//星星落下的時間間隔
this.starCoolDown = new DropTimeCounter(this,"")
this.starCoolDown.start(this.handleCountDownFinished.bind(this),500) //5s 隨機叫星星
// 遊戲時間 timeText,gameTimer custom OK.
const {gameTimer} = this.modifyDatas
this.createGameTimer(gameTimer.items[0])
console.log("startgame");
}
createGameTimer(gameTimer){ //第四步,第 65 行
//Timer
const style = {
fontSize: 32,
fill: "#fff",
stroke: "#000",
strokeThickness: 2
}
const gameTimerLabel = this.add.text(16, 34, "時間", style).setDepth(20)
this.gameTimer = new GameTimer(this, gameTimerLabel, "\n時間")
this.gameTimer.start(this.gameover.bind(this),gameTimer.text.content * 1000)//5s
}
createScoreBoard(){ //第二步,第 103 行
//Score
const scoreTextLabel = this.add.text(16,-10, "", {
"fontSize": 32,
"fill": "#fff",
"stroke": "#000",
"strokeThickness": 2
}).setDepth(20)
this.scoreText = new Score(this,scoreTextLabel,"\n分數",0)
}
create(){ //第三步
this.isGameStart = false
this.playerMoveSpeed = 400
this.cursor = this.input.keyboard.createCursorKeys()
//background custom OK.
const {background} = this.modifyDatas
this.add.image(background.items[0].img.position.x, background.items[0].img.position.y ,'background').setScale(background.items[0].img.size/100)
this.createScoreBoard()
//創建角色、星星等
this.platforms = this.createPlatform()
this.player = this.createPlayer()
//Balloons custom OK.
const {star} = this.modifyDatas
this.starsSpawner = new StarsSpawner(this,star.items)
this.starsGroup = this.starsSpawner.group
//gameStart Tutorial
const {gameTutorialText} = this.modifyDatas
const {gameEndTimer} = this.modifyDatas
this.gameTutorialMessage = new GameTutorial(this, star.items , gameTutorialText.items[0], gameEndTimer.items[0])
this.gameTutorialMessage.create()
//gameoverMessage
const {gameoverMessage} = this.modifyDatas
this.gameoverMessage = new GameoverMessage(this, this.scoreText.getScore(), gameoverMessage.items[0])
this.gameAchievement = new GameAchievement(this, 0, gameoverMessage.items[1])
/* related to collider between objects */
this.physics.add.collider(this.player,this.platforms)
this.physics.add.overlap(this.player, this.starsGroup, this.collectStar,null,this)
this.physics.add.collider(this.platforms, this.starsGroup,this.disableBody,null,this)
// related to button 左箭頭右箭頭
this.createMovingArrow()
}
handleCountDownFinished(){ //產星星,第 61 行
this.starsSpawner.spawn()
//console.log("handleCountDownFinishe")
}
gameover(){ //第 78 行
this.physics.pause()
this.starCoolDown.stop()
this.player.setTint(0xff0000)
this.player.anims.play('stop')
this.gameoverMessage.create(this.scoreText.getScore())
this.gameAchievement.create()
}
disableBody(hit,disablePart){ //沒接到
disablePart.disableBody(true,true)
}
collectStar(player,star){ //接到,第 122 行
star.disableBody(true,true)
this.getItemMessage = new ShowMessage(this, star.getData('text'))
this.scoreText.addScore(star.getData('score')) //StarSpawner 第40行
this.getItemMessage.start(this.getItemMessage.stop(),500)//5s
this.gameAchievement.countStar(star.getData('starType')) //計算掉落物種類
}
createPlatform(){
const platforms = this.physics.add.staticGroup()
platforms.create(400,568,'ground').setScale(2).refreshBody()
platforms.create(400,620,'ground').setScale(2).refreshBody()
return platforms
}
createPlayer(){
const {player} = this.modifyDatas
let newPlayer = this.physics.add.sprite(player.items[0].img.position.x,player.items[0].img.position.y,'player').setScale(player.items[0].img.size/100)
newPlayer.setCollideWorldBounds(true)
newPlayer.setGravity(0,300)
return newPlayer
}
update(){
if(this.cursor.left.isDown){
this.player.setVelocityX(this.playerMoveSpeed * -1)
}else if(this.cursor.right.isDown){
this.player.setVelocityX(this.playerMoveSpeed)
}else if(!this.isMousePress){
this.player.setVelocityX(0)
}
if(this.cursor.up.isDown && this.player.body.touching.down){
this.player.setVelocityY(-120)
}
if(this.isGameStart){
this.starCoolDown.update()
this.gameTimer.update()
}
}
createMovingArrow(){
this.leftButton = this.physics.add.sprite(70,500,'arrowButton')
this.leftButton.alpha = 0.3
this.rightButton = this.physics.add.sprite(300,500,'arrowButton').setFlipX(true);
this.rightButton.alpha = 0.3
this.leftButton.setInteractive({ draggable: true })
.on('dragstart', function(pointer, dragX, dragY){
this.isMousePress = true
this.player.setVelocityX(this.playerMoveSpeed * -1)
}, this)
.on('drag', function(pointer, dragX, dragY){
this.player.setVelocityX(this.playerMoveSpeed * -1)
}, this)
.on('dragend', function(pointer, dragX, dragY, dropped){
this.isMousePress = false
this.player.setVelocityX(0)
}, this);
this.rightButton.setInteractive({ draggable: true })
.on('dragstart', function(pointer, dragX, dragY){
this.isMousePress = true
this.player.setVelocityX(this.playerMoveSpeed)
}, this)
.on('drag', function(pointer, dragX, dragY){
this.player.setVelocityX(this.playerMoveSpeed)
}, this)
.on('dragend', function(pointer, dragX, dragY, dropped){
this.isMousePress = false
this.player.setVelocityX(0)
}, this);
}
} |
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#include "pixmapeditor.h"
#include <iconloader_p.h>
#include <iconselector_p.h>
#include <qdesigner_utils_p.h>
#include <QtDesigner/abstractformeditor.h>
#include <QtWidgets/qapplication.h>
#include <QtWidgets/qlabel.h>
#include <QtWidgets/qtoolbutton.h>
#include <QtWidgets/qboxlayout.h>
#include <QtWidgets/qlineedit.h>
#include <QtWidgets/qdialogbuttonbox.h>
#include <QtWidgets/qpushbutton.h>
#include <QtWidgets/qfiledialog.h>
#include <QtWidgets/qmenu.h>
#include <QtGui/qaction.h>
#if QT_CONFIG(clipboard)
#include <QtGui/qclipboard.h>
#endif
#include <QtGui/qevent.h>
QT_BEGIN_NAMESPACE
using namespace Qt::StringLiterals;
static constexpr QSize ICON_SIZE{16, 16};
namespace qdesigner_internal {
static void createIconThemeDialog(QDialog *topLevel, const QString &labelText,
QWidget *themeEditor)
{
QVBoxLayout *layout = new QVBoxLayout(topLevel);
QLabel *label = new QLabel(labelText, topLevel);
QDialogButtonBox *buttons = new QDialogButtonBox(topLevel);
buttons->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
QObject::connect(buttons, &QDialogButtonBox::accepted, topLevel, &QDialog::accept);
QObject::connect(buttons, &QDialogButtonBox::rejected, topLevel, &QDialog::reject);
layout->addWidget(label);
layout->addWidget(themeEditor);
layout->addWidget(buttons);
}
IconThemeDialog::IconThemeDialog(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("Set Icon From XDG Theme"));
m_editor = new IconThemeEditor(this);
createIconThemeDialog(this, tr("Select icon name from XDG theme:"), m_editor);
}
std::optional<QString> IconThemeDialog::getTheme(QWidget *parent, const QString &theme)
{
IconThemeDialog dlg(parent);
dlg.m_editor->setTheme(theme);
if (dlg.exec() == QDialog::Accepted)
return dlg.m_editor->theme();
return std::nullopt;
}
IconThemeEnumDialog::IconThemeEnumDialog(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("Set Icon From Theme"));
m_editor = new IconThemeEnumEditor(this);
createIconThemeDialog(this, tr("Select icon name from theme:"), m_editor);
}
std::optional<int> IconThemeEnumDialog::getTheme(QWidget *parent, int theme)
{
IconThemeEnumDialog dlg(parent);
dlg.m_editor->setThemeEnum(theme);
if (dlg.exec() == QDialog::Accepted)
return dlg.m_editor->themeEnum();
return std::nullopt;
}
PixmapEditor::PixmapEditor(QDesignerFormEditorInterface *core, QWidget *parent) :
QWidget(parent),
m_iconThemeModeEnabled(false),
m_core(core),
m_pixmapLabel(new QLabel(this)),
m_pathLabel(new QLabel(this)),
m_button(new QToolButton(this)),
m_resourceAction(new QAction(tr("Choose Resource..."), this)),
m_fileAction(new QAction(tr("Choose File..."), this)),
m_themeEnumAction(new QAction(tr("Set Icon From Theme..."), this)),
m_themeAction(new QAction(tr("Set Icon From XDG Theme..."), this)),
m_copyAction(new QAction(createIconSet(QIcon::ThemeIcon::EditCopy, "editcopy.png"_L1),
tr("Copy Path"), this)),
m_pasteAction(new QAction(createIconSet(QIcon::ThemeIcon::EditPaste, "editpaste.png"_L1),
tr("Paste Path"), this)),
m_layout(new QHBoxLayout(this)),
m_pixmapCache(nullptr)
{
m_layout->addWidget(m_pixmapLabel);
m_layout->addWidget(m_pathLabel);
m_button->setText(tr("..."));
m_button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored);
m_button->setFixedWidth(30);
m_button->setPopupMode(QToolButton::MenuButtonPopup);
m_layout->addWidget(m_button);
m_layout->setContentsMargins(QMargins());
m_layout->setSpacing(0);
m_pixmapLabel->setFixedWidth(ICON_SIZE.width());
m_pixmapLabel->setAlignment(Qt::AlignCenter);
m_pathLabel->setSizePolicy(QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed));
m_themeAction->setVisible(false);
m_themeEnumAction->setVisible(false);
QMenu *menu = new QMenu(this);
menu->addAction(m_resourceAction);
menu->addAction(m_fileAction);
menu->addAction(m_themeEnumAction);
menu->addAction(m_themeAction);
m_button->setMenu(menu);
m_button->setText(tr("..."));
connect(m_button, &QAbstractButton::clicked, this, &PixmapEditor::defaultActionActivated);
connect(m_resourceAction, &QAction::triggered, this, &PixmapEditor::resourceActionActivated);
connect(m_fileAction, &QAction::triggered, this, &PixmapEditor::fileActionActivated);
connect(m_themeEnumAction, &QAction::triggered, this, &PixmapEditor::themeEnumActionActivated);
connect(m_themeAction, &QAction::triggered, this, &PixmapEditor::themeActionActivated);
#if QT_CONFIG(clipboard)
connect(m_copyAction, &QAction::triggered, this, &PixmapEditor::copyActionActivated);
connect(m_pasteAction, &QAction::triggered, this, &PixmapEditor::pasteActionActivated);
#endif
setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored));
setFocusProxy(m_button);
#if QT_CONFIG(clipboard)
connect(QApplication::clipboard(), &QClipboard::dataChanged,
this, &PixmapEditor::clipboardDataChanged);
clipboardDataChanged();
#endif
}
void PixmapEditor::setPixmapCache(DesignerPixmapCache *cache)
{
m_pixmapCache = cache;
}
void PixmapEditor::setIconThemeModeEnabled(bool enabled)
{
if (m_iconThemeModeEnabled == enabled)
return;
m_iconThemeModeEnabled = enabled;
m_themeAction->setVisible(enabled);
m_themeEnumAction->setVisible(enabled);
}
void PixmapEditor::setSpacing(int spacing)
{
m_layout->setSpacing(spacing);
}
void PixmapEditor::setPath(const QString &path)
{
m_path = path;
updateLabels();
}
void PixmapEditor::setTheme(const QString &theme)
{
m_theme = theme;
updateLabels();
}
QString PixmapEditor::msgThemeIcon(const QString &t)
{
return tr("[Theme] %1").arg(t);
}
QString PixmapEditor::msgMissingThemeIcon(const QString &t)
{
return tr("[Theme] %1 (missing)").arg(t);
}
void PixmapEditor::setThemeEnum(int e)
{
m_themeEnum = e;
updateLabels();
}
void PixmapEditor::updateLabels()
{
m_pathLabel->setText(displayText(m_themeEnum, m_theme, m_path));
switch (state()) {
case State::Empty:
case State::MissingXdgTheme:
case State::MissingThemeEnum:
m_pixmapLabel->setPixmap(m_defaultPixmap);
m_copyAction->setEnabled(false);
break;
case State::ThemeEnum:
m_pixmapLabel->setPixmap(QIcon::fromTheme(static_cast<QIcon::ThemeIcon>(m_themeEnum)).pixmap(ICON_SIZE));
m_copyAction->setEnabled(true);
break;
case State::XdgTheme:
m_pixmapLabel->setPixmap(QIcon::fromTheme(m_theme).pixmap(ICON_SIZE));
m_copyAction->setEnabled(true);
break;
case State::Path:
case State::PathFallback:
if (m_pixmapCache) {
auto pixmap = m_pixmapCache->pixmap(PropertySheetPixmapValue(m_path));
m_pixmapLabel->setPixmap(QIcon(pixmap).pixmap(ICON_SIZE));
}
m_copyAction->setEnabled(true);
break;
}
}
void PixmapEditor::setDefaultPixmapIcon(const QIcon &icon)
{
m_defaultPixmap = icon.pixmap(ICON_SIZE);
if (state() == State::Empty)
m_pixmapLabel->setPixmap(m_defaultPixmap);
}
void PixmapEditor::setDefaultPixmap(const QPixmap &pixmap)
{
setDefaultPixmapIcon(QIcon(pixmap));
}
void PixmapEditor::contextMenuEvent(QContextMenuEvent *event)
{
QMenu menu(this);
menu.addAction(m_copyAction);
menu.addAction(m_pasteAction);
menu.exec(event->globalPos());
event->accept();
}
void PixmapEditor::defaultActionActivated()
{
if (m_iconThemeModeEnabled) {
themeEnumActionActivated();
return;
}
// Default to resource
const PropertySheetPixmapValue::PixmapSource ps = m_path.isEmpty()
? PropertySheetPixmapValue::ResourcePixmap
: PropertySheetPixmapValue::getPixmapSource(m_core, m_path);
switch (ps) {
case PropertySheetPixmapValue::LanguageResourcePixmap:
case PropertySheetPixmapValue::ResourcePixmap:
resourceActionActivated();
break;
case PropertySheetPixmapValue::FilePixmap:
fileActionActivated();
break;
}
}
void PixmapEditor::resourceActionActivated()
{
const QString oldPath = m_path;
const QString newPath = IconSelector::choosePixmapResource(m_core, m_core->resourceModel(),
oldPath, this);
if (!newPath.isEmpty() && newPath != oldPath) {
setTheme({});
setThemeEnum(-1);
setPath(newPath);
emit pathChanged(newPath);
}
}
void PixmapEditor::fileActionActivated()
{
const QString newPath = IconSelector::choosePixmapFile(m_path, m_core->dialogGui(), this);
if (!newPath.isEmpty() && newPath != m_path) {
setTheme({});
setThemeEnum(-1);
setPath(newPath);
emit pathChanged(newPath);
}
}
void PixmapEditor::themeEnumActionActivated()
{
const auto newThemeO = IconThemeEnumDialog::getTheme(this, {});
if (newThemeO.has_value()) {
const int newTheme = newThemeO.value();
if (newTheme != m_themeEnum) {
setThemeEnum(newTheme);
setTheme({});
setPath({});
emit themeEnumChanged(newTheme);
}
}
}
void PixmapEditor::themeActionActivated()
{
const auto newThemeO = IconThemeDialog::getTheme(this, m_theme);
if (newThemeO.has_value()) {
const QString newTheme = newThemeO.value();
if (newTheme != m_theme) {
setTheme(newTheme);
setThemeEnum(-1);
setPath({});
emit themeChanged(newTheme);
}
}
}
PixmapEditor::State PixmapEditor::stateFromData(int themeEnum, const QString &xdgTheme,
const QString &path)
{
if (themeEnum != -1) {
if (QIcon::hasThemeIcon(static_cast<QIcon::ThemeIcon>(themeEnum)))
return State::ThemeEnum;
return path.isEmpty() ? State::MissingThemeEnum : State::PathFallback;
}
if (!xdgTheme.isEmpty()) {
if (QIcon::hasThemeIcon(xdgTheme))
return State::XdgTheme;
return path.isEmpty() ? State::MissingXdgTheme : State::PathFallback;
}
return path.isEmpty() ? State::Empty : State::Path;
}
PixmapEditor::State PixmapEditor::state() const
{
return stateFromData(m_themeEnum, m_theme, m_path);
}
QString PixmapEditor::displayText(int themeEnum, const QString &xdgTheme, const QString &path)
{
switch (stateFromData(themeEnum, xdgTheme, path)) {
case State::ThemeEnum:
return msgThemeIcon(IconThemeEnumEditor::iconName(themeEnum));
case State::MissingThemeEnum:
return msgMissingThemeIcon(IconThemeEnumEditor::iconName(themeEnum));
case State::XdgTheme:
return msgThemeIcon(xdgTheme);
case State::MissingXdgTheme:
return msgMissingThemeIcon(xdgTheme);
case State::Path:
return QFileInfo(path).fileName();
case State::PathFallback:
return tr("%1 (fallback)").arg(QFileInfo(path).fileName());
case State::Empty:
break;
}
return {};
}
QString PixmapEditor::displayText(const PropertySheetIconValue &icon)
{
const auto &paths = icon.paths();
const auto &it = paths.constFind({QIcon::Normal, QIcon::Off});
const QString path = it != paths.constEnd() ? it.value().path() : QString{};
return displayText(icon.themeEnum(), icon.theme(), path);
}
#if QT_CONFIG(clipboard)
void PixmapEditor::copyActionActivated()
{
QClipboard *clipboard = QApplication::clipboard();
switch (state()) {
case State::ThemeEnum:
case State::MissingThemeEnum:
clipboard->setText(IconThemeEnumEditor::iconName(m_themeEnum));
break;
case State::XdgTheme:
case State::MissingXdgTheme:
clipboard->setText(m_theme);
break;
case State::Path:
case State::PathFallback:
clipboard->setText(m_path);
break;
case State::Empty:
break;
}
}
void PixmapEditor::pasteActionActivated()
{
QClipboard *clipboard = QApplication::clipboard();
QString subtype = u"plain"_s;
QString text = clipboard->text(subtype);
if (!text.isNull()) {
QStringList list = text.split(u'\n');
if (!list.isEmpty()) {
text = list.at(0);
if (m_iconThemeModeEnabled && QIcon::hasThemeIcon(text)) {
setTheme(text);
setPath(QString());
emit themeChanged(text);
} else {
setPath(text);
setTheme(QString());
emit pathChanged(text);
}
}
}
}
void PixmapEditor::clipboardDataChanged()
{
QClipboard *clipboard = QApplication::clipboard();
QString subtype = u"plain"_s;
const QString text = clipboard->text(subtype);
m_pasteAction->setEnabled(!text.isNull());
}
#endif // QT_CONFIG(clipboard)
} // qdesigner_internal
QT_END_NAMESPACE |
"use client";
import React, { FormEvent, useEffect, useState } from "react";
import { searchQuery } from "../../services/api";
import { IPost } from "../../types/types";
import Link from "next/link";
import { dataFormater } from "../../services/util";
import Search from "./Search";
function page() {
const [height, setHeight] = useState(0);
const [searchQueryItems, setSearchQueryItems] = useState<IPost[]>([]);
const [errorHandler, setErrorHandler] = useState("");
const [query, setQuery] = useState("");
const [start, setStart] = useState(false);
const searchSubmitHandler = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
searchQuery(query as string)
.then((resp) => {
setSearchQueryItems(resp as IPost[]);
if (resp.length >= 1) {
setStart(false);
} else {
setStart(true);
}
console.log("search query");
console.log(resp);
console.log(resp.length);
})
.catch((error: any) => {
console.log("search query");
console.log(error);
setErrorHandler(error);
});
};
useEffect(() => {
const header = document.getElementById("header") as HTMLDivElement;
const footer = document.getElementById("footer") as HTMLDivElement;
const search = document.getElementById("search") as HTMLDivElement;
const headerFooter = header.clientHeight + footer.clientHeight;
const viewportHeight =
window.innerHeight || document.documentElement.clientHeight;
search.style.minHeight = `${viewportHeight - headerFooter}px`;
// searchHandler();
}, []);
return (
<div className="bg-slate-300">
<div id="search" className="grid smy-5 w-9/12 m-auto p-2 ">
<form
action=""
className="flex self-center justify-self-center bg-white rounded-md shadow-md"
onSubmit={searchSubmitHandler}
>
<input
className="m-1 focus:border-none focus:outline-none h-9 px-5 w-96"
type="text"
name="query"
placeholder="Digite palavras chaves ou autor do post ... "
value={query}
onChange={(e) => {
setQuery(e.target.value);
}}
/>
<button className="h-10 " type="submit">
<img
className=" h-full self-center"
src="/icons/red-search.png"
alt=""
/>
</button>
</form>
<div className="mt-10 mb-5">
{searchQueryItems.length == 0 && start ? (
<div>
<p className="text-2xl text-basicRed text-center">
Sem resultados
</p>
</div>
) : (
<div className="my-2 ">
{searchQueryItems.map((item, index) => (
<div className="my-3">
<Search item={item} />
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}
export default page; |
/*
* Copyright 2023 Dev Bwaim team
*
* 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
*
* https://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.
*/
package dev.bwaim.kustomalarm.core
import dev.bwaim.kustomalarm.core.Result.Error
import dev.bwaim.kustomalarm.core.Result.Error.UnexpectedError
import dev.bwaim.kustomalarm.core.Result.Success
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import kotlin.coroutines.cancellation.CancellationException
public typealias DomainResult<T> = Result<T, Error<Any>>
public sealed interface Result<out T : Any?, out E : Any> {
public data class Success<T : Any?>(public val value: T) : Result<T, Nothing>
public sealed interface Error<E : Any> : Result<Nothing, E> {
public val error: Throwable
public data class ApiError(public override val error: DomainException) :
Error<DomainException>
public data class UnexpectedError(public override val error: Throwable) : Error<Nothing>
}
}
public val <T : Any?> DomainResult<T>.value: T?
get() =
when (this) {
is Success -> value
is Error -> null
}
public val <T : Any?> DomainResult<T>.error: Throwable?
get() =
when (this) {
is Success -> null
is Error -> error
}
public suspend inline fun <T, R : Any?> T.executeCatching(
dispatcher: CoroutineDispatcher,
crossinline block: suspend T.() -> R,
): DomainResult<R> =
withContext(dispatcher) {
runCatching { block().toDomainResult() }
.getOrElse { exception: Throwable ->
exception.rethrowIfCancellationException()
UnexpectedError(exception)
}
}
public fun <T : Any?> T.toDomainResult(): DomainResult<T> = Success(this)
public fun Throwable.rethrowIfCancellationException() {
if (this is CancellationException) {
throw this
}
} |
/*
* Host Side support for RNDIS Networking Links
* Copyright (C) 2005 by David Brownell
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// #define DEBUG // error path messages, extra info
// #define VERBOSE // more; success messages
#include <linux/config.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/workqueue.h>
#include <linux/mii.h>
#include <linux/usb.h>
#include <linux/usb_cdc.h>
#include "usbnet.h"
/*
* RNDIS is NDIS remoted over USB. It's a MSFT variant of CDC ACM ... of
* course ACM was intended for modems, not Ethernet links! USB's standard
* for Ethernet links is "CDC Ethernet", which is significantly simpler.
*/
/*
* CONTROL uses CDC "encapsulated commands" with funky notifications.
* - control-out: SEND_ENCAPSULATED
* - interrupt-in: RESPONSE_AVAILABLE
* - control-in: GET_ENCAPSULATED
*
* We'll try to ignore the RESPONSE_AVAILABLE notifications.
*/
struct rndis_msg_hdr {
__le32 msg_type; /* RNDIS_MSG_* */
__le32 msg_len;
// followed by data that varies between messages
__le32 request_id;
__le32 status;
// ... and more
} __attribute__ ((packed));
/* RNDIS defines this (absurdly huge) control timeout */
#define RNDIS_CONTROL_TIMEOUT_MS (10 * 1000)
#define ccpu2 __constant_cpu_to_le32
#define RNDIS_MSG_COMPLETION ccpu2(0x80000000)
/* codes for "msg_type" field of rndis messages;
* only the data channel uses packet messages (maybe batched);
* everything else goes on the control channel.
*/
#define RNDIS_MSG_PACKET ccpu2(0x00000001) /* 1-N packets */
#define RNDIS_MSG_INIT ccpu2(0x00000002)
#define RNDIS_MSG_INIT_C (RNDIS_MSG_INIT|RNDIS_MSG_COMPLETION)
#define RNDIS_MSG_HALT ccpu2(0x00000003)
#define RNDIS_MSG_QUERY ccpu2(0x00000004)
#define RNDIS_MSG_QUERY_C (RNDIS_MSG_QUERY|RNDIS_MSG_COMPLETION)
#define RNDIS_MSG_SET ccpu2(0x00000005)
#define RNDIS_MSG_SET_C (RNDIS_MSG_SET|RNDIS_MSG_COMPLETION)
#define RNDIS_MSG_RESET ccpu2(0x00000006)
#define RNDIS_MSG_RESET_C (RNDIS_MSG_RESET|RNDIS_MSG_COMPLETION)
#define RNDIS_MSG_INDICATE ccpu2(0x00000007)
#define RNDIS_MSG_KEEPALIVE ccpu2(0x00000008)
#define RNDIS_MSG_KEEPALIVE_C (RNDIS_MSG_KEEPALIVE|RNDIS_MSG_COMPLETION)
/* codes for "status" field of completion messages */
#define RNDIS_STATUS_SUCCESS ccpu2(0x00000000)
#define RNDIS_STATUS_FAILURE ccpu2(0xc0000001)
#define RNDIS_STATUS_INVALID_DATA ccpu2(0xc0010015)
#define RNDIS_STATUS_NOT_SUPPORTED ccpu2(0xc00000bb)
#define RNDIS_STATUS_MEDIA_CONNECT ccpu2(0x4001000b)
#define RNDIS_STATUS_MEDIA_DISCONNECT ccpu2(0x4001000c)
struct rndis_data_hdr {
__le32 msg_type; /* RNDIS_MSG_PACKET */
__le32 msg_len; // rndis_data_hdr + data_len + pad
__le32 data_offset; // 36 -- right after header
__le32 data_len; // ... real packet size
__le32 oob_data_offset; // zero
__le32 oob_data_len; // zero
__le32 num_oob; // zero
__le32 packet_data_offset; // zero
__le32 packet_data_len; // zero
__le32 vc_handle; // zero
__le32 reserved; // zero
} __attribute__ ((packed));
struct rndis_init { /* OUT */
// header and:
__le32 msg_type; /* RNDIS_MSG_INIT */
__le32 msg_len; // 24
__le32 request_id;
__le32 major_version; // of rndis (1.0)
__le32 minor_version;
__le32 max_transfer_size;
} __attribute__ ((packed));
struct rndis_init_c { /* IN */
// header and:
__le32 msg_type; /* RNDIS_MSG_INIT_C */
__le32 msg_len;
__le32 request_id;
__le32 status;
__le32 major_version; // of rndis (1.0)
__le32 minor_version;
__le32 device_flags;
__le32 medium; // zero == 802.3
__le32 max_packets_per_message;
__le32 max_transfer_size;
__le32 packet_alignment; // max 7; (1<<n) bytes
__le32 af_list_offset; // zero
__le32 af_list_size; // zero
} __attribute__ ((packed));
struct rndis_halt { /* OUT (no reply) */
// header and:
__le32 msg_type; /* RNDIS_MSG_HALT */
__le32 msg_len;
__le32 request_id;
} __attribute__ ((packed));
struct rndis_query { /* OUT */
// header and:
__le32 msg_type; /* RNDIS_MSG_QUERY */
__le32 msg_len;
__le32 request_id;
__le32 oid;
__le32 len;
__le32 offset;
/*?*/ __le32 handle; // zero
} __attribute__ ((packed));
struct rndis_query_c { /* IN */
// header and:
__le32 msg_type; /* RNDIS_MSG_QUERY_C */
__le32 msg_len;
__le32 request_id;
__le32 status;
__le32 len;
__le32 offset;
} __attribute__ ((packed));
struct rndis_set { /* OUT */
// header and:
__le32 msg_type; /* RNDIS_MSG_SET */
__le32 msg_len;
__le32 request_id;
__le32 oid;
__le32 len;
__le32 offset;
/*?*/ __le32 handle; // zero
} __attribute__ ((packed));
struct rndis_set_c { /* IN */
// header and:
__le32 msg_type; /* RNDIS_MSG_SET_C */
__le32 msg_len;
__le32 request_id;
__le32 status;
} __attribute__ ((packed));
struct rndis_reset { /* IN */
// header and:
__le32 msg_type; /* RNDIS_MSG_RESET */
__le32 msg_len;
__le32 reserved;
} __attribute__ ((packed));
struct rndis_reset_c { /* OUT */
// header and:
__le32 msg_type; /* RNDIS_MSG_RESET_C */
__le32 msg_len;
__le32 status;
__le32 addressing_lost;
} __attribute__ ((packed));
struct rndis_indicate { /* IN (unrequested) */
// header and:
__le32 msg_type; /* RNDIS_MSG_INDICATE */
__le32 msg_len;
__le32 status;
__le32 length;
__le32 offset;
/**/ __le32 diag_status;
__le32 error_offset;
/**/ __le32 message;
} __attribute__ ((packed));
struct rndis_keepalive { /* OUT (optionally IN) */
// header and:
__le32 msg_type; /* RNDIS_MSG_KEEPALIVE */
__le32 msg_len;
__le32 request_id;
} __attribute__ ((packed));
struct rndis_keepalive_c { /* IN (optionally OUT) */
// header and:
__le32 msg_type; /* RNDIS_MSG_KEEPALIVE_C */
__le32 msg_len;
__le32 request_id;
__le32 status;
} __attribute__ ((packed));
/* NOTE: about 30 OIDs are "mandatory" for peripherals to support ... and
* there are gobs more that may optionally be supported. We'll avoid as much
* of that mess as possible.
*/
#define OID_802_3_PERMANENT_ADDRESS ccpu2(0x01010101)
#define OID_GEN_CURRENT_PACKET_FILTER ccpu2(0x0001010e)
/*
* RNDIS notifications from device: command completion; "reverse"
* keepalives; etc
*/
static void rndis_status(struct usbnet *dev, struct urb *urb)
{
devdbg(dev, "rndis status urb, len %d stat %d",
urb->actual_length, urb->status);
// FIXME for keepalives, respond immediately (asynchronously)
// if not an RNDIS status, do like cdc_status(dev,urb) does
}
/*
* RPC done RNDIS-style. Caller guarantees:
* - message is properly byteswapped
* - there's no other request pending
* - buf can hold up to 1KB response (required by RNDIS spec)
* On return, the first few entries are already byteswapped.
*
* Call context is likely probe(), before interface name is known,
* which is why we won't try to use it in the diagnostics.
*/
static int rndis_command(struct usbnet *dev, struct rndis_msg_hdr *buf)
{
struct cdc_state *info = (void *) &dev->data;
int retval;
unsigned count;
__le32 rsp;
u32 xid = 0, msg_len, request_id;
/* REVISIT when this gets called from contexts other than probe() or
* disconnect(): either serialize, or dispatch responses on xid
*/
/* Issue the request; don't bother byteswapping our xid */
if (likely(buf->msg_type != RNDIS_MSG_HALT
&& buf->msg_type != RNDIS_MSG_RESET)) {
xid = dev->xid++;
if (!xid)
xid = dev->xid++;
buf->request_id = (__force __le32) xid;
}
retval = usb_control_msg(dev->udev,
usb_sndctrlpipe(dev->udev, 0),
USB_CDC_SEND_ENCAPSULATED_COMMAND,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, info->u->bMasterInterface0,
buf, le32_to_cpu(buf->msg_len),
RNDIS_CONTROL_TIMEOUT_MS);
if (unlikely(retval < 0 || xid == 0))
return retval;
// FIXME Seems like some devices discard responses when
// we time out and cancel our "get response" requests...
// so, this is fragile. Probably need to poll for status.
/* ignore status endpoint, just poll the control channel;
* the request probably completed immediately
*/
rsp = buf->msg_type | RNDIS_MSG_COMPLETION;
for (count = 0; count < 10; count++) {
memset(buf, 0, 1024);
retval = usb_control_msg(dev->udev,
usb_rcvctrlpipe(dev->udev, 0),
USB_CDC_GET_ENCAPSULATED_RESPONSE,
USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, info->u->bMasterInterface0,
buf, 1024,
RNDIS_CONTROL_TIMEOUT_MS);
if (likely(retval >= 8)) {
msg_len = le32_to_cpu(buf->msg_len);
request_id = (__force u32) buf->request_id;
if (likely(buf->msg_type == rsp)) {
if (likely(request_id == xid)) {
if (unlikely(rsp == RNDIS_MSG_RESET_C))
return 0;
if (likely(RNDIS_STATUS_SUCCESS
== buf->status))
return 0;
dev_dbg(&info->control->dev,
"rndis reply status %08x\n",
le32_to_cpu(buf->status));
return -EL3RST;
}
dev_dbg(&info->control->dev,
"rndis reply id %d expected %d\n",
request_id, xid);
/* then likely retry */
} else switch (buf->msg_type) {
case RNDIS_MSG_INDICATE: { /* fault */
// struct rndis_indicate *msg = (void *)buf;
dev_info(&info->control->dev,
"rndis fault indication\n");
}
break;
case RNDIS_MSG_KEEPALIVE: { /* ping */
struct rndis_keepalive_c *msg = (void *)buf;
msg->msg_type = RNDIS_MSG_KEEPALIVE_C;
msg->msg_len = ccpu2(sizeof *msg);
msg->status = RNDIS_STATUS_SUCCESS;
retval = usb_control_msg(dev->udev,
usb_sndctrlpipe(dev->udev, 0),
USB_CDC_SEND_ENCAPSULATED_COMMAND,
USB_TYPE_CLASS | USB_RECIP_INTERFACE,
0, info->u->bMasterInterface0,
msg, sizeof *msg,
RNDIS_CONTROL_TIMEOUT_MS);
if (unlikely(retval < 0))
dev_dbg(&info->control->dev,
"rndis keepalive err %d\n",
retval);
}
break;
default:
dev_dbg(&info->control->dev,
"unexpected rndis msg %08x len %d\n",
le32_to_cpu(buf->msg_type), msg_len);
}
} else {
/* device probably issued a protocol stall; ignore */
dev_dbg(&info->control->dev,
"rndis response error, code %d\n", retval);
}
msleep(2);
}
dev_dbg(&info->control->dev, "rndis response timeout\n");
return -ETIMEDOUT;
}
static int rndis_bind(struct usbnet *dev, struct usb_interface *intf)
{
int retval;
struct net_device *net = dev->net;
union {
void *buf;
struct rndis_msg_hdr *header;
struct rndis_init *init;
struct rndis_init_c *init_c;
struct rndis_query *get;
struct rndis_query_c *get_c;
struct rndis_set *set;
struct rndis_set_c *set_c;
} u;
u32 tmp;
/* we can't rely on i/o from stack working, or stack allocation */
u.buf = kmalloc(1024, GFP_KERNEL);
if (!u.buf)
return -ENOMEM;
retval = usbnet_generic_cdc_bind(dev, intf);
if (retval < 0)
goto done;
net->hard_header_len += sizeof (struct rndis_data_hdr);
/* initialize; max transfer is 16KB at full speed */
u.init->msg_type = RNDIS_MSG_INIT;
u.init->msg_len = ccpu2(sizeof *u.init);
u.init->major_version = ccpu2(1);
u.init->minor_version = ccpu2(0);
u.init->max_transfer_size = ccpu2(net->mtu + net->hard_header_len);
retval = rndis_command(dev, u.header);
if (unlikely(retval < 0)) {
/* it might not even be an RNDIS device!! */
dev_err(&intf->dev, "RNDIS init failed, %d\n", retval);
fail:
usb_driver_release_interface(driver_of(intf),
((struct cdc_state *)&(dev->data))->data);
goto done;
}
dev->hard_mtu = le32_to_cpu(u.init_c->max_transfer_size);
/* REVISIT: peripheral "alignment" request is ignored ... */
dev_dbg(&intf->dev, "hard mtu %u, align %d\n", dev->hard_mtu,
1 << le32_to_cpu(u.init_c->packet_alignment));
/* get designated host ethernet address */
memset(u.get, 0, sizeof *u.get);
u.get->msg_type = RNDIS_MSG_QUERY;
u.get->msg_len = ccpu2(sizeof *u.get);
u.get->oid = OID_802_3_PERMANENT_ADDRESS;
retval = rndis_command(dev, u.header);
if (unlikely(retval < 0)) {
dev_err(&intf->dev, "rndis get ethaddr, %d\n", retval);
goto fail;
}
tmp = le32_to_cpu(u.get_c->offset);
if (unlikely((tmp + 8) > (1024 - ETH_ALEN)
|| u.get_c->len != ccpu2(ETH_ALEN))) {
dev_err(&intf->dev, "rndis ethaddr off %d len %d ?\n",
tmp, le32_to_cpu(u.get_c->len));
retval = -EDOM;
goto fail;
}
memcpy(net->dev_addr, tmp + (char *)&u.get_c->request_id, ETH_ALEN);
/* set a nonzero filter to enable data transfers */
memset(u.set, 0, sizeof *u.set);
u.set->msg_type = RNDIS_MSG_SET;
u.set->msg_len = ccpu2(4 + sizeof *u.set);
u.set->oid = OID_GEN_CURRENT_PACKET_FILTER;
u.set->len = ccpu2(4);
u.set->offset = ccpu2((sizeof *u.set) - 8);
*(__le32 *)(u.buf + sizeof *u.set) = ccpu2(DEFAULT_FILTER);
retval = rndis_command(dev, u.header);
if (unlikely(retval < 0)) {
dev_err(&intf->dev, "rndis set packet filter, %d\n", retval);
goto fail;
}
retval = 0;
done:
kfree(u.buf);
return retval;
}
static void rndis_unbind(struct usbnet *dev, struct usb_interface *intf)
{
struct rndis_halt *halt;
/* try to clear any rndis state/activity (no i/o from stack!) */
halt = kcalloc(1, sizeof *halt, SLAB_KERNEL);
if (halt) {
halt->msg_type = RNDIS_MSG_HALT;
halt->msg_len = ccpu2(sizeof *halt);
(void) rndis_command(dev, (void *)halt);
kfree(halt);
}
return usbnet_cdc_unbind(dev, intf);
}
/*
* DATA -- host must not write zlps
*/
static int rndis_rx_fixup(struct usbnet *dev, struct sk_buff *skb)
{
/* peripheral may have batched packets to us... */
while (likely(skb->len)) {
struct rndis_data_hdr *hdr = (void *)skb->data;
struct sk_buff *skb2;
u32 msg_len, data_offset, data_len;
msg_len = le32_to_cpu(hdr->msg_len);
data_offset = le32_to_cpu(hdr->data_offset);
data_len = le32_to_cpu(hdr->data_len);
/* don't choke if we see oob, per-packet data, etc */
if (unlikely(hdr->msg_type != RNDIS_MSG_PACKET
|| skb->len < msg_len
|| (data_offset + data_len + 8) > msg_len)) {
dev->stats.rx_frame_errors++;
devdbg(dev, "bad rndis message %d/%d/%d/%d, len %d",
le32_to_cpu(hdr->msg_type),
msg_len, data_offset, data_len, skb->len);
return 0;
}
skb_pull(skb, 8 + data_offset);
/* at most one packet left? */
if (likely((data_len - skb->len) <= sizeof *hdr)) {
skb_trim(skb, data_len);
break;
}
/* try to return all the packets in the batch */
skb2 = skb_clone(skb, GFP_ATOMIC);
if (unlikely(!skb2))
break;
skb_pull(skb, msg_len - sizeof *hdr);
skb_trim(skb2, data_len);
usbnet_skb_return(dev, skb2);
}
/* caller will usbnet_skb_return the remaining packet */
return 1;
}
static struct sk_buff *
rndis_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags)
{
struct rndis_data_hdr *hdr;
struct sk_buff *skb2;
unsigned len = skb->len;
if (likely(!skb_cloned(skb))) {
int room = skb_headroom(skb);
/* enough head room as-is? */
if (unlikely((sizeof *hdr) <= room))
goto fill;
/* enough room, but needs to be readjusted? */
room += skb_tailroom(skb);
if (likely((sizeof *hdr) <= room)) {
skb->data = memmove(skb->head + sizeof *hdr,
skb->data, len);
skb->tail = skb->data + len;
goto fill;
}
}
/* create a new skb, with the correct size (and tailpad) */
skb2 = skb_copy_expand(skb, sizeof *hdr, 1, flags);
dev_kfree_skb_any(skb);
if (unlikely(!skb2))
return skb2;
skb = skb2;
/* fill out the RNDIS header. we won't bother trying to batch
* packets; Linux minimizes wasted bandwidth through tx queues.
*/
fill:
hdr = (void *) __skb_push(skb, sizeof *hdr);
memset(hdr, 0, sizeof *hdr);
hdr->msg_type = RNDIS_MSG_PACKET;
hdr->msg_len = cpu_to_le32(skb->len);
hdr->data_offset = ccpu2(sizeof(*hdr) - 8);
hdr->data_len = cpu_to_le32(len);
/* FIXME make the last packet always be short ... */
return skb;
}
static const struct driver_info rndis_info = {
.description = "RNDIS device",
.flags = FLAG_ETHER | FLAG_FRAMING_RN,
.bind = rndis_bind,
.unbind = rndis_unbind,
.status = rndis_status,
.rx_fixup = rndis_rx_fixup,
.tx_fixup = rndis_tx_fixup,
};
#undef ccpu2
/*-------------------------------------------------------------------------*/
static const struct usb_device_id products [] = {
{
/* RNDIS is MSFT's un-official variant of CDC ACM */
USB_INTERFACE_INFO(USB_CLASS_COMM, 2 /* ACM */, 0x0ff),
.driver_info = (unsigned long) &rndis_info,
},
{ }, // END
};
MODULE_DEVICE_TABLE(usb, products);
static struct usb_driver rndis_driver = {
.name = "rndis_host",
.id_table = products,
.probe = usbnet_probe,
.disconnect = usbnet_disconnect,
.suspend = usbnet_suspend,
.resume = usbnet_resume,
};
static int __init rndis_init(void)
{
return usb_register(&rndis_driver);
}
module_init(rndis_init);
static void __exit rndis_exit(void)
{
usb_deregister(&rndis_driver);
}
module_exit(rndis_exit);
MODULE_AUTHOR("David Brownell");
MODULE_DESCRIPTION("USB Host side RNDIS driver");
MODULE_LICENSE("GPL"); |
/*
* This file is part of OpenTTD.
* OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
* OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file dropdown.cpp Implementation of the dropdown widget. */
#include "../stdafx.h"
#include "../window_gui.h"
#include "../string_func.h"
#include "../strings_func.h"
#include "../window_func.h"
#include "../zoom_func.h"
#include "../timer/timer.h"
#include "../timer/timer_window.h"
#include "dropdown_type.h"
#include "dropdown_widget.h"
#include "../safeguards.h"
static constexpr NWidgetPart _nested_dropdown_menu_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_PANEL, COLOUR_END, WID_DM_ITEMS), SetScrollbar(WID_DM_SCROLL), EndContainer(),
NWidget(NWID_SELECTION, INVALID_COLOUR, WID_DM_SHOW_SCROLL),
NWidget(NWID_VSCROLLBAR, COLOUR_END, WID_DM_SCROLL),
EndContainer(),
EndContainer(),
};
static WindowDesc _dropdown_desc(__FILE__, __LINE__,
WDP_MANUAL, nullptr, 0, 0,
WC_DROPDOWN_MENU, WC_NONE,
WDF_NO_FOCUS,
std::begin(_nested_dropdown_menu_widgets), std::end(_nested_dropdown_menu_widgets)
);
/** Drop-down menu window */
struct DropdownWindow : Window {
WidgetID parent_button; ///< Parent widget number where the window is dropped from.
Rect wi_rect; ///< Rect of the button that opened the dropdown.
DropDownList list; ///< List with dropdown menu items.
int selected_result; ///< Result value of the selected item in the list.
byte click_delay = 0; ///< Timer to delay selection.
bool drag_mode = true;
bool instant_close; ///< Close the window when the mouse button is raised.
bool persist; ///< Persist dropdown menu.
int scrolling = 0; ///< If non-zero, auto-scroll the item list (one time).
Point position; ///< Position of the topleft corner of the window.
Scrollbar *vscroll;
Dimension items_dim; ///< Calculated cropped and padded dimension for the items widget.
/**
* Create a dropdown menu.
* @param parent Parent window.
* @param list Dropdown item list.
* @param selected Initial selected result of the list.
* @param button Widget of the parent window doing the dropdown.
* @param wi_rect Rect of the button that opened the dropdown.
* @param instant_close Close the window when the mouse button is raised.
* @param wi_colour Colour of the parent widget.
* @param persist Dropdown menu will persist.
*/
DropdownWindow(Window *parent, DropDownList &&list, int selected, WidgetID button, const Rect wi_rect, bool instant_close, Colours wi_colour, bool persist)
: Window(&_dropdown_desc)
, parent_button(button)
, wi_rect(wi_rect)
, list(std::move(list))
, selected_result(selected)
, instant_close(instant_close)
, persist(persist)
{
assert(!this->list.empty());
this->parent = parent;
this->CreateNestedTree();
this->GetWidget<NWidgetCore>(WID_DM_ITEMS)->colour = wi_colour;
this->GetWidget<NWidgetCore>(WID_DM_SCROLL)->colour = wi_colour;
this->vscroll = this->GetScrollbar(WID_DM_SCROLL);
this->UpdateSizeAndPosition();
this->FinishInitNested(0);
CLRBITS(this->flags, WF_WHITE_BORDER);
}
void Close([[maybe_unused]] int data = 0) override
{
/* Finish closing the dropdown, so it doesn't affect new window placement.
* Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */
this->Window::Close();
Point pt = _cursor.pos;
pt.x -= this->parent->left;
pt.y -= this->parent->top;
this->parent->OnDropdownClose(pt, this->parent_button, this->selected_result, this->instant_close);
/* Set flag on parent widget to indicate that we have just closed. */
NWidgetCore *nwc = this->parent->GetWidget<NWidgetCore>(this->parent_button);
if (nwc != nullptr) SetBit(nwc->disp_flags, NDB_DROPDOWN_CLOSED);
}
void OnFocusLost(bool closing) override
{
if (!closing) {
this->instant_close = false;
this->Close();
}
}
/**
* Fit dropdown list into available height, rounding to average item size. Width is adjusted if scrollbar is present.
* @param[in,out] desired Desired dimensions of dropdown list.
* @param list Dimensions of the list itself, without padding or cropping.
* @param available_height Available height to fit list within.
*/
void FitAvailableHeight(Dimension &desired, const Dimension &list, uint available_height)
{
if (desired.height < available_height) return;
/* If the dropdown doesn't fully fit, we a need a dropdown. */
uint avg_height = list.height / (uint)this->list.size();
uint rows = std::max((available_height - WidgetDimensions::scaled.dropdownlist.Vertical()) / avg_height, 1U);
desired.width = std::max(list.width, desired.width - NWidgetScrollbar::GetVerticalDimension().width);
desired.height = rows * avg_height + WidgetDimensions::scaled.dropdownlist.Vertical();
}
/**
* Update size and position of window to fit dropdown list into available space.
*/
void UpdateSizeAndPosition()
{
Rect button_rect = this->wi_rect.Translate(this->parent->left, this->parent->top);
/* Get the dimensions required for the list. */
Dimension list_dim = GetDropDownListDimension(this->list);
/* Set up dimensions for the items widget. */
Dimension widget_dim = list_dim;
widget_dim.width += WidgetDimensions::scaled.dropdownlist.Horizontal();
widget_dim.height += WidgetDimensions::scaled.dropdownlist.Vertical();
/* Width should match at least the width of the parent widget. */
widget_dim.width = std::max<uint>(widget_dim.width, button_rect.Width());
/* Available height below (or above, if the dropdown is placed above the widget). */
uint available_height_below = std::max(GetMainViewBottom() - button_rect.bottom - 1, 0);
uint available_height_above = std::max(button_rect.top - 1 - GetMainViewTop(), 0);
/* Is it better to place the dropdown above the widget? */
if (widget_dim.height > available_height_below && available_height_above > available_height_below) {
FitAvailableHeight(widget_dim, list_dim, available_height_above);
this->position.y = button_rect.top - widget_dim.height;
} else {
FitAvailableHeight(widget_dim, list_dim, available_height_below);
this->position.y = button_rect.bottom + 1;
}
this->position.x = (_current_text_dir == TD_RTL) ? button_rect.right + 1 - (int)widget_dim.width : button_rect.left;
this->items_dim = widget_dim;
this->GetWidget<NWidgetStacked>(WID_DM_SHOW_SCROLL)->SetDisplayedPlane(list_dim.height > widget_dim.height ? 0 : SZSP_NONE);
/* Capacity is the average number of items visible */
this->vscroll->SetCapacity((widget_dim.height - WidgetDimensions::scaled.dropdownlist.Vertical()) * this->list.size() / list_dim.height);
this->vscroll->SetCount(this->list.size());
/* If the dropdown is positioned above the parent widget, start selection at the bottom. */
if (this->position.y < button_rect.top && list_dim.height > widget_dim.height) this->vscroll->UpdatePosition(INT_MAX);
}
void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
{
if (widget == WID_DM_ITEMS) *size = this->items_dim;
}
Point OnInitialPosition([[maybe_unused]] int16_t sm_width, [[maybe_unused]] int16_t sm_height, [[maybe_unused]] int window_number) override
{
return this->position;
}
/**
* Find the dropdown item under the cursor.
* @param[out] value Selected item, if function returns \c true.
* @return Cursor points to a dropdown item.
*/
bool GetDropDownItem(int &value)
{
if (GetWidgetFromPos(this, _cursor.pos.x - this->left, _cursor.pos.y - this->top) < 0) return false;
const Rect &r = this->GetWidget<NWidgetBase>(WID_DM_ITEMS)->GetCurrentRect().Shrink(WidgetDimensions::scaled.dropdownlist);
int y = _cursor.pos.y - this->top - r.top;
int pos = this->vscroll->GetPosition();
for (const auto &item : this->list) {
/* Skip items that are scrolled up */
if (--pos >= 0) continue;
int item_height = item->Height();
if (y < item_height) {
if (item->masked || !item->Selectable()) return false;
value = item->result;
return true;
}
y -= item_height;
}
return false;
}
void DrawWidget(const Rect &r, WidgetID widget) const override
{
if (widget != WID_DM_ITEMS) return;
Colours colour = this->GetWidget<NWidgetCore>(widget)->colour;
Rect ir = r.Shrink(WidgetDimensions::scaled.dropdownlist);
int y = ir.top;
int pos = this->vscroll->GetPosition();
for (const auto &item : this->list) {
int item_height = item->Height();
/* Skip items that are scrolled up */
if (--pos >= 0) continue;
if (y + item_height - 1 <= ir.bottom) {
Rect full{ir.left, y, ir.right, y + item_height - 1};
bool selected = (this->selected_result == item->result) && item->Selectable();
if (selected) GfxFillRect(full, PC_BLACK);
item->Draw(full, full.Shrink(WidgetDimensions::scaled.dropdowntext, RectPadding::zero), selected, colour);
}
y += item_height;
}
}
void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
{
if (widget != WID_DM_ITEMS) return;
int item;
if (this->GetDropDownItem(item)) {
this->click_delay = 4;
this->selected_result = item;
this->SetDirty();
}
}
/** Rate limit how fast scrolling happens. */
IntervalTimer<TimerWindow> scroll_interval = {std::chrono::milliseconds(30), [this](auto) {
if (this->scrolling == 0) return;
if (this->vscroll->UpdatePosition(this->scrolling)) this->SetDirty();
this->scrolling = 0;
}};
void OnMouseLoop() override
{
if (this->click_delay != 0 && --this->click_delay == 0) {
/* Close the dropdown, so it doesn't affect new window placement.
* Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */
if (!this->persist) this->Close();
this->parent->OnDropdownSelect(this->parent_button, this->selected_result);
return;
}
if (this->drag_mode) {
int item;
if (!_left_button_clicked) {
this->drag_mode = false;
if (!this->GetDropDownItem(item)) {
if (this->instant_close) this->Close();
return;
}
this->click_delay = 2;
} else {
if (_cursor.pos.y <= this->top + 2) {
/* Cursor is above the list, set scroll up */
this->scrolling = -1;
return;
} else if (_cursor.pos.y >= this->top + this->height - 2) {
/* Cursor is below list, set scroll down */
this->scrolling = 1;
return;
}
if (!this->GetDropDownItem(item)) return;
}
if (this->selected_result != item) {
this->selected_result = item;
this->SetDirty();
}
}
}
void ReplaceList(DropDownList &&list)
{
this->list = std::move(list);
this->UpdateSizeAndPosition();
this->ReInit(0, 0);
this->InitializePositionSize(this->position.x, this->position.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
this->SetDirty();
}
};
void ReplaceDropDownList(Window *parent, DropDownList &&list)
{
DropdownWindow *ddw = dynamic_cast<DropdownWindow *>(parent->FindChildWindow(WC_DROPDOWN_MENU));
if (ddw != nullptr) ddw->ReplaceList(std::move(list));
}
/**
* Determine width and height required to fully display a DropDownList
* @param list The list.
* @return Dimension required to display the list.
*/
Dimension GetDropDownListDimension(const DropDownList &list)
{
Dimension dim{};
for (const auto &item : list) {
dim.height += item->Height();
dim.width = std::max(dim.width, item->Width());
}
dim.width += WidgetDimensions::scaled.dropdowntext.Horizontal();
return dim;
}
/**
* Show a drop down list.
* @param w Parent window for the list.
* @param list Prepopulated DropDownList.
* @param selected The initially selected list item.
* @param button The widget which is passed to Window::OnDropdownSelect and OnDropdownClose.
* Unless you override those functions, this should be then widget index of the dropdown button.
* @param wi_rect Coord of the parent drop down button, used to position the dropdown menu.
* @param instant_close Set to true if releasing mouse button should close the
* list regardless of where the cursor is.
* @param persist Set if this dropdown should stay open after an option is selected.
*/
void ShowDropDownListAt(Window *w, DropDownList &&list, int selected, WidgetID button, Rect wi_rect, Colours wi_colour, bool instant_close, bool persist)
{
CloseWindowByClass(WC_DROPDOWN_MENU);
new DropdownWindow(w, std::move(list), selected, button, wi_rect, instant_close, wi_colour, persist);
}
/**
* Show a drop down list.
* @param w Parent window for the list.
* @param list Prepopulated DropDownList.
* @param selected The initially selected list item.
* @param button The widget within the parent window that is used to determine
* the list's location.
* @param width Override the minimum width determined by the selected widget and list contents.
* @param instant_close Set to true if releasing mouse button should close the
* list regardless of where the cursor is.
* @param persist Set if this dropdown should stay open after an option is selected.
*/
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, bool instant_close, bool persist)
{
/* Our parent's button widget is used to determine where to place the drop
* down list window. */
NWidgetCore *nwi = w->GetWidget<NWidgetCore>(button);
Rect wi_rect = nwi->GetCurrentRect();
Colours wi_colour = nwi->colour;
if ((nwi->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
nwi->disp_flags |= ND_DROPDOWN_ACTIVE;
} else {
nwi->SetLowered(true);
}
nwi->SetDirty(w);
if (width != 0) {
if (_current_text_dir == TD_RTL) {
wi_rect.left = wi_rect.right + 1 - ScaleGUITrad(width);
} else {
wi_rect.right = wi_rect.left + ScaleGUITrad(width) - 1;
}
}
ShowDropDownListAt(w, std::move(list), selected, button, wi_rect, wi_colour, instant_close, persist);
}
/**
* Show a dropdown menu window near a widget of the parent window.
* The result code of the items is their index in the \a strings list.
* @param w Parent window that wants the dropdown menu.
* @param strings Menu list, end with #INVALID_STRING_ID
* @param selected Index of initial selected item.
* @param button Button widget number of the parent window \a w that wants the dropdown menu.
* @param disabled_mask Bitmask for disabled items (items with their bit set are displayed, but not selectable in the dropdown list).
* @param hidden_mask Bitmask for hidden items (items with their bit set are not copied to the dropdown list).
* @param width Minimum width of the dropdown menu.
*/
void ShowDropDownMenu(Window *w, const StringID *strings, int selected, WidgetID button, uint32_t disabled_mask, uint32_t hidden_mask, uint width)
{
DropDownList list;
for (uint i = 0; strings[i] != INVALID_STRING_ID; i++) {
if (!HasBit(hidden_mask, i)) {
list.push_back(std::make_unique<DropDownListStringItem>(strings[i], i, HasBit(disabled_mask, i)));
}
}
if (!list.empty()) ShowDropDownList(w, std::move(list), selected, button, width);
} |
import React from "react";
import PropTypes from "prop-types";
import Button from "react-bootstrap/Button";
import Card from "react-bootstrap/Card";
import { AiFillStar } from "react-icons/ai";
import "./movie-card.scss";
import { Link } from "react-router-dom";
// create MovieCard component
export class MovieCard extends React.Component {
constructor(props) {
super(props);
this.toggleClass = this.toggleClass.bind(this);
this.state = {
active: false,
};
}
toggleClass() {
const currentState = this.state.active;
this.setState({ active: !currentState });
}
render() {
const { movie, handleFavorite } = this.props;
let movies = movie;
return (
<Card className="movie-card" border="dark" bg="dark" text="light">
<Card.Img variant="top" src={movie.ImagePath} />
<Card.Body>
<Card.Title>{movie.Title}</Card.Title>
<Card.Text>{movie.Description}</Card.Text>
<Link to={`/movies/${movie._id}`}>
<Button className="movie-card-button" variant="light">
Open
</Button>
</Link>
<AiFillStar
onClick={() => {
handleFavorite(movies);
this.toggleClass();
}}
className={
this.state.active ? "movie-card-star-active" : "movie-card-star"
}
></AiFillStar>
</Card.Body>
</Card>
);
}
}
MovieCard.propTypes = {
movie: PropTypes.shape({
Title: PropTypes.string.isRequired,
Description: PropTypes.string.isRequired,
ImagePath: PropTypes.string.isRequired,
}).isRequired,
}; |
package com.itutry.counting;
import java.io.IOException;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
import javax.servlet.GenericServlet;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import net.jcip.annotations.ThreadSafe;
/**
* 使用AtomicLong类型变量来统计已处理请求的数量
*
* @author itutry
* @create 2020-04-14_13:42
*/
@ThreadSafe
public class SafeCountingFactorizer extends GenericServlet implements Servlet {
private AtomicLong count = new AtomicLong(0);
public long getCount() {
return count.get();
}
@Override
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException {
BigInteger i = extractFromRequest(req);
BigInteger[] factors = factor(i);
count.incrementAndGet();
encodeIntoResponse(res, factors);
}
private void encodeIntoResponse(ServletResponse res, BigInteger[] factors) {
}
private BigInteger[] factor(BigInteger i) {
return new BigInteger[]{i};
}
private BigInteger extractFromRequest(ServletRequest req) {
return new BigInteger("7");
}
} |
package main
import "fmt"
func main() {
// Начальный неотсортированный срез
s1 := []int{64, 34, 25, 12, 22, 11, 90}
// Выводим исходный неотсортированный срез
fmt.Printf("Unsorted list:\t%v\n", s1)
fmt.Println("")
length := len(s1)
// Внешний цикл для проходов по списку
for i := 0; i < (length - 1); i++ {
// Внутренний цикл для сравнения элементов и их перестановки
// Обратите внимание, что количество сравнений уменьшается на i на каждом проходе,
// потому что самый большой элемент «всплывает» на своё место в конце списка после каждого прохода
for j := 0; j < ((length - 1) - i); j++ {
// Если текущий элемент больше следующего, меняем их местами
if s1[j] > s1[j+1] {
s1[j], s1[j+1] = s1[j+1], s1[j]
}
}
// Выводим текущее состояние среза после каждого прохода
fmt.Printf("Sorting ...:\t%v\n", s1)
}
fmt.Println("")
// Выводим отсортированный срез
fmt.Printf("Sorted list:\t%v\n", s1)
} |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
package org.apache.kafka.clients.consumer.internals.events;
import org.apache.kafka.clients.consumer.ConsumerRebalanceListener;
import org.apache.kafka.clients.consumer.internals.ConsumerRebalanceListenerMethodName;
import org.apache.kafka.common.KafkaException;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/**
* Event that signifies that the application thread has executed the {@link ConsumerRebalanceListener} callback. If
* the callback execution threw an error, it is included in the event should any event listener want to know.
*/
public class ConsumerRebalanceListenerCallbackCompletedEvent extends ApplicationEvent {
private final ConsumerRebalanceListenerMethodName methodName;
private final CompletableFuture<Void> future;
private final Optional<KafkaException> error;
public ConsumerRebalanceListenerCallbackCompletedEvent(final ConsumerRebalanceListenerMethodName methodName,
final CompletableFuture<Void> future,
final Optional<KafkaException> error) {
super(Type.CONSUMER_REBALANCE_LISTENER_CALLBACK_COMPLETED);
this.methodName = Objects.requireNonNull(methodName);
this.future = Objects.requireNonNull(future);
this.error = Objects.requireNonNull(error);
}
public ConsumerRebalanceListenerMethodName methodName() {
return methodName;
}
public CompletableFuture<Void> future() {
return future;
}
public Optional<KafkaException> error() {
return error;
}
@Override
protected String toStringBase() {
return super.toStringBase() +
", methodName=" + methodName +
", future=" + future +
", error=" + error;
}
} |
import React, { useEffect } from 'react';
import T from 'prop-types';
import CompanySettingsInput from './CompanySettingsInput';
import {
CompanySettingsContainer,
CompanySettingsHeader,
} from '../styledComponents';
const CompanySettings = ({
dispatchChangeInput,
form,
formErrors,
handleEditUser,
handleValidateInput,
}) => {
useEffect(() => {
window.scrollTo(0, 0);
document.title = 'Account & Settings';
}, []);
return (
<CompanySettingsContainer>
<CompanySettingsHeader>User details</CompanySettingsHeader>
{Object.keys(form).map(field => {
const handleChangeInput = value => {
dispatchChangeInput({
form: 'form',
field,
value,
});
};
return (
<CompanySettingsInput
error={formErrors[field]}
field={field}
handleChangeInput={handleChangeInput}
handleEditUser={handleEditUser}
key={`input-${field}`}
onBlur={() =>
handleValidateInput({
field,
values: form,
})
}
value={form[field]}
/>
);
})}
</CompanySettingsContainer>
);
};
CompanySettings.propTypes = {
dispatchChangeInput: T.func.isRequired,
form: T.object.isRequired,
formErrors: T.object.isRequired,
handleEditUser: T.func.isRequired,
handleValidateInput: T.func.isRequired,
};
export default CompanySettings; |
from django.test import tag
from task_manager.tests.conftests import BaseTestCase
from task_manager.users.views import (
UserCreateView, UserUpdateView, UserDeleteView)
@tag("users")
class UsersTestCase(BaseTestCase):
data_json = 'users-data.json'
def setUp(self):
super().setUp()
self.update_pk = self.data["update"]["pk"]
self.delete_pk = self.data["delete"]["pk"]
self.not_creator = self.auth["not_creator"]
self.creator = self.auth["creator"]
self.delete_pk_used_in_task = self.data["delete_used_in_task"]["pk"]
self.used_in_task = self.auth["used_in_task"]
# users_index tests:
def test_get_users(self):
self.assert_response_data_after_get_request(
"users_index",
expected_data=self.data["users_expected"])
# users_create tests:
def test_post_users_create(self):
self.assert_redirect_with_message_after_post_request(
"users_create", None, self.data["create"],
"login", UserCreateView.success_message)
self.assert_response_data_after_get_request(
"users_index", expected_data=self.data["create_expected"])
# users_update tests:
def test_get_users_update_by_unlogged(self):
self.assert_redirect_with_message_after_get_request(
"users_update", self.update_pk,
"login", UserUpdateView.message_not_authenticated)
def test_get_users_update_by_logged_not_creator(self):
self.make_logged_as(self.not_creator)
self.assert_redirect_with_message_after_get_request(
"users_update", self.update_pk,
"users_index", UserUpdateView.message_not_owner)
self.assert_response_data_after_get_request(
"users_index",
expected_data=self.data["users_expected"])
def test_dispatch_users_update_by_logged_creator(self):
self.make_logged_as(self.creator)
self.assert_status_code_after_get_request(
"users_update", self.update_pk)
self.assert_redirect_with_message_after_post_request(
"users_update", self.update_pk, self.data["update"],
"users_index", UserUpdateView.success_message)
self.assert_response_data_after_get_request(
"users_index",
expected_data=self.data["update_expected"],
not_expected_data=self.data["update_not_expected"])
# users_delete tests:
def test_get_users_delete_by_unlogged(self):
self.assert_redirect_with_message_after_get_request(
"users_delete", self.delete_pk,
"login", UserDeleteView.message_not_authenticated)
def test_dispatch_users_delete_by_logged_not_creator(self):
self.make_logged_as(self.not_creator)
self.assert_redirect_with_message_after_get_request(
"users_delete", self.delete_pk,
"users_index", UserDeleteView.message_not_owner)
self.assert_response_data_after_get_request(
"users_index",
expected_data=self.data["users_expected"])
def test_dispatch_users_delete_by_logged_creator_with_user_unused_in_task(
self):
self.make_logged_as(self.creator)
self.assert_status_code_after_get_request(
"users_delete", self.delete_pk)
self.assert_redirect_with_message_after_post_request(
"users_delete", self.delete_pk, self.data["delete"],
"users_index", UserDeleteView.success_message)
self.assert_response_data_after_get_request(
"users_index",
expected_data=self.data["delete_expected"],
not_expected_data=self.data["delete_not_expected"])
def test_dispatch_users_delete_by_logged_creator_with_user_used_in_task(
self):
self.make_logged_as(self.used_in_task)
self.assert_status_code_after_get_request(
"users_delete", self.delete_pk_used_in_task)
self.assert_redirect_with_message_after_post_request(
"users_delete",
self.delete_pk_used_in_task, self.data["delete"],
"users_index", UserDeleteView.message_used_object)
self.assert_response_data_after_get_request(
"users_index",
expected_data=self.data["users_expected"]) |
package main
import (
"math"
)
// Methods and Functions are similar in nature
// However, methods with value or pointer receivers can
// take either a value or a pointer as the receiver when they are called
// functions that take a value argument must take a value of that specific type
// functions with a pointer argument must take a pointer
type Vertex struct {
X, Y float64
}
// Methods with pointer receiver
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
// Method with value receiver
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
func testmethods() {
v1 := Vertex{3, 4} // v1 is a value
v1.Scale(10)
v1.Abs()
v2 := &Vertex{4, 3}
v2.Scale(10)
v2.Abs()
} |
//{ Driver Code Starts
// C++ program to evaluate value of a postfix expression
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution
{
public:
//Function to evaluate a postfix expression.
int evaluatePostfix(string S)
{
stack<int>T;
for(int i=0;i<S.size();i++)
{
if(S[i]=='+'||S[i]=='-'||S[i]=='*'||S[i]=='/')
{
if(S[i]=='+')
{
int a = T.top(); T.pop();
int b = T.top(); T.pop();
T.push(a+b);
}
if(S[i]=='-')
{
int a = T.top(); T.pop();
int b = T.top(); T.pop();
T.push(b-a);
}
if(S[i]=='*')
{
int a = T.top(); T.pop();
int b = T.top(); T.pop();
T.push(a*b);
}
if(S[i]=='/')
{
int a = T.top(); T.pop();
int b = T.top(); T.pop();
T.push(b/a);
}
}
else
{
T.push(S[i]-'0');
}
}
int res =T.top();
return res;
}
};
//{ Driver Code Starts.
// Driver program to test above functions
int main()
{
int t;
cin>>t;
cin.ignore(INT_MAX, '\n');
while(t--)
{
string S;
cin>>S;
Solution obj;
cout<<obj.evaluatePostfix(S)<<endl;
}
return 0;
}
// } Driver Code Ends |
ndbm(3bsd) ndbm(3bsd)
SSyynnooppssiiss
/usr/ucb/cc [flag . . . ] file . . . #include <ndbm.h>
typedef struct { char *dptr; int dsize; } datum;
int dbm_clearerr(DBM *db);
void dbm_close(DBM *db);
int dbm_delete(DBM *db, datum key);
int dbm_error(DBM *db);
datum dbm_fetch(DBM *db, datum key);
datum dbm_firstkey(DBM *db);
datum dbm_nextkey(DBM *db);
DBM *dbm_open(char *file, int flags, int mode);
int dbm_store(DBM *db, datum key, datum content, int
flags);
DDeessccrriippttiioonn
These routines are provided for compatibility with appli-
cations originally written for BSD systems; new or ported
applications should use the equivalent System V routines
instead. See
These functions maintain key pairs in a data base. The
functions will handle very large (a billion blocks) data
base and will access a keyed item in one or two file sys-
tem accesses. This package replaces the earlier library,
which managed only a single data base.
keys and contents are described by the datum typedef. A
datum specifies a string of dsize bytes pointed to by
dptr. Arbitrary binary data, as well as normal ASCII
strings, are allowed. The data base is stored in two
files. One file is a directory containing a bit map and
has .dir as its suffix. The second file contains all data
and has .pag as its suffix.
Before a data base can be accessed, it must be opened by
dbm_open. This will open and/or create the files file.dir
and file.pag depending on the flags parameter (see
A data base is closed by calling dbm_close.
Once open, the data stored under a key is accessed by
dbm_fetch and data is placed under a key by dbm_store.
The flags field can be either DBM_INSERT or DBM_REPLACE.
DBM_INSERT will only insert new entries into the data base
BSD System Compatibility 1
ndbm(3bsd) ndbm(3bsd)
and will not change an existing entry with the same key.
DBM_REPLACE will replace an existing entry if it has the
same key. A key (and its associated contents) is deleted
by dbm_delete. A linear pass through all keys in a data
base may be made, in an (apparently) random order, by use
of dbm_firstkey and dbm_nextkey. dbm_firstkey will return
the first key in the data base. dbm_nextkey will return
the next key in the data base. This code will traverse
the data base: for (key = dbm_firstkey(db); key.dptr !=
NULL; key = dbm_nextkey(db)) dbm_error returns non-zero
when an error has occurred reading or writing the data
base. dbm_clearerr resets the error condition on the
named data base.
RReettuurrnn vvaalluueess
All functions that return an int indicate errors with neg-
ative values. A zero return indicates no error. Routines
that return a datum indicate errors with a NULL (0) dptr.
If dbm_store is called with a flags value of DBM_INSERT
and finds an existing entry with the same key, it returns
1.
RReeffeerreenncceess
NNoottiicceess
The .pag file will contain holes so that its apparent size
is about four times its actual content. Older versions of
the operating system may create real file blocks for these
holes when touched. These files cannot be copied by nor-
mal means (that is, using or without filling in the holes.
dptr pointers returned by these subroutines point into
static storage that is changed by subsequent calls.
The sum of the sizes of a key pair must not exceed the
internal block size (currently 4096 bytes). Moreover all
key pairs that hash together must fit on a single block.
dbm_store will return an error in the event that a disk
block fills with inseparable data.
dbm_delete does not physically reclaim file space,
although it does make it available for reuse.
The order of keys presented by dbm_firstkey and dbm_nex-
tkey depends on a hashing function.
There are no interlocks and no reliable cache flushing;
thus concurrent updating and reading is risky.
BSD System Compatibility 2 |
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:objectdetectionapp/screens/view_image.dart';
class CameraAPP extends StatefulWidget {
const CameraAPP(this.cameras, {super.key});
final List<CameraDescription> cameras;
@override
State<CameraAPP> createState() => _CameraAPPState();
}
class _CameraAPPState extends State<CameraAPP> {
late CameraController _controller;
@override
void initState() {
// implement initState
super.initState();
_controller = CameraController(widget.cameras[0], ResolutionPreset.max);
_controller.initialize().then((_) {
if (!mounted) {
return;
}
setState(() {});
}).catchError((Object e) {
if (e is CameraException) {
switch (e.code) {
case 'CameraAccessDenied':
print("access was denied");
break;
default:
print(e.description);
break;
}
}
});
}
@override
Widget build(BuildContext context) {
XFile picture;
return Scaffold(
// implemnting the camera
body: Stack(
children: [
SizedBox(
height: double.infinity,
child: CameraPreview(_controller),
),
// Add button to take picture
Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: Container(
margin: const EdgeInsets.all(20.0),
child: MaterialButton(
onPressed: () async {
BuildContext currentcontext = context;
if (!_controller.value.isInitialized) {
return;
}
if (_controller.value.isTakingPicture) {
return;
}
try {
await _controller.setFlashMode(FlashMode.auto);
picture = await _controller.takePicture();
// create another screen to display image
Navigator.push(
currentcontext,
MaterialPageRoute(
builder: (context) => ImagePreview(picture)));
} on CameraException catch (e) {
debugPrint("Error occured while taking picture: $e ");
return;
}
},
color: Colors.white,
child: const Text('Take a picture'),
)),
)
],
)
],
));
}
} |
/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: BUSL-1.1
*/
import { run } from '@ember/runloop';
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import sinon from 'sinon';
module('Unit | Model | job', function (hooks) {
setupTest(hooks);
test('should expose aggregate allocations derived from task groups', function (assert) {
const store = this.owner.lookup('service:store');
let summary;
run(() => {
summary = store.createRecord('job-summary', {
taskGroupSummaries: [
{
name: 'one',
queuedAllocs: 1,
startingAllocs: 2,
runningAllocs: 3,
completeAllocs: 4,
failedAllocs: 5,
lostAllocs: 6,
unknownAllocs: 7,
},
{
name: 'two',
queuedAllocs: 2,
startingAllocs: 4,
runningAllocs: 6,
completeAllocs: 8,
failedAllocs: 10,
lostAllocs: 12,
unknownAllocs: 14,
},
{
name: 'three',
queuedAllocs: 3,
startingAllocs: 6,
runningAllocs: 9,
completeAllocs: 12,
failedAllocs: 15,
lostAllocs: 18,
unknownAllocs: 21,
},
],
});
});
const job = run(() =>
this.owner.lookup('service:store').createRecord('job', {
summary,
name: 'example',
taskGroups: [
{
name: 'one',
count: 0,
tasks: [],
},
{
name: 'two',
count: 0,
tasks: [],
},
{
name: 'three',
count: 0,
tasks: [],
},
],
})
);
assert.equal(
job.get('totalAllocs'),
job
.get('taskGroups')
.mapBy('summary.totalAllocs')
.reduce((sum, allocs) => sum + allocs, 0),
'totalAllocs is the sum of all group totalAllocs'
);
assert.equal(
job.get('queuedAllocs'),
job
.get('taskGroups')
.mapBy('summary.queuedAllocs')
.reduce((sum, allocs) => sum + allocs, 0),
'queuedAllocs is the sum of all group queuedAllocs'
);
assert.equal(
job.get('startingAllocs'),
job
.get('taskGroups')
.mapBy('summary.startingAllocs')
.reduce((sum, allocs) => sum + allocs, 0),
'startingAllocs is the sum of all group startingAllocs'
);
assert.equal(
job.get('runningAllocs'),
job
.get('taskGroups')
.mapBy('summary.runningAllocs')
.reduce((sum, allocs) => sum + allocs, 0),
'runningAllocs is the sum of all group runningAllocs'
);
assert.equal(
job.get('completeAllocs'),
job
.get('taskGroups')
.mapBy('summary.completeAllocs')
.reduce((sum, allocs) => sum + allocs, 0),
'completeAllocs is the sum of all group completeAllocs'
);
assert.equal(
job.get('failedAllocs'),
job
.get('taskGroups')
.mapBy('summary.failedAllocs')
.reduce((sum, allocs) => sum + allocs, 0),
'failedAllocs is the sum of all group failedAllocs'
);
assert.equal(
job.get('lostAllocs'),
job
.get('taskGroups')
.mapBy('summary.lostAllocs')
.reduce((sum, allocs) => sum + allocs, 0),
'lostAllocs is the sum of all group lostAllocs'
);
});
test('actions are aggregated from taskgroups tasks', function (assert) {
const job = run(() =>
this.owner.lookup('service:store').createRecord('job', {
name: 'example',
taskGroups: [
{
name: 'one',
count: 0,
tasks: [
{
name: '1.1',
actions: [
{
name: 'one',
command: 'date',
args: ['+%s'],
},
{
name: 'two',
command: 'sh',
args: ['-c "echo hello"'],
},
],
},
],
},
{
name: 'two',
count: 0,
tasks: [
{
name: '2.1',
},
],
},
{
name: 'three',
count: 0,
tasks: [
{
name: '3.1',
actions: [
{
name: 'one',
command: 'date',
args: ['+%s'],
},
],
},
{
name: '3.2',
actions: [
{
name: 'one',
command: 'date',
args: ['+%s'],
},
],
},
],
},
],
})
);
assert.equal(
job.get('actions.length'),
4,
'Job draws actions from its task groups tasks'
);
// Three actions named one, one named two
assert.equal(
job.get('actions').filterBy('name', 'one').length,
3,
'Job has three actions named one'
);
assert.equal(
job.get('actions').filterBy('name', 'two').length,
1,
'Job has one action named two'
);
// Job's actions mapped by task.name return 1.1, 1.1, 3.1, 3.2
assert.equal(
job.get('actions').mapBy('task.name').length,
4,
'Job action fragments surface their task properties'
);
assert.equal(
job
.get('actions')
.mapBy('task.name')
.filter((name) => name === '1.1').length,
2,
'Two of the job actions are from task 1.1'
);
assert.equal(
job
.get('actions')
.mapBy('task.name')
.filter((name) => name === '3.1').length,
1,
'One of the job actions is from task 3.1'
);
assert.equal(
job
.get('actions')
.mapBy('task.name')
.filter((name) => name === '3.2').length,
1,
'One of the job actions is from task 3.2'
);
});
module('#parse', function () {
test('it parses JSON', async function (assert) {
const store = this.owner.lookup('service:store');
const model = store.createRecord('job');
model.set('_newDefinition', '{"name": "Tomster"}');
const setIdByPayloadSpy = sinon.spy(model, 'setIdByPayload');
const result = await model.parse();
assert.deepEqual(
model.get('_newDefinitionJSON'),
{ name: 'Tomster' },
'Sets _newDefinitionJSON correctly'
);
assert.ok(
setIdByPayloadSpy.calledWith({ name: 'Tomster' }),
'setIdByPayload is called with the parsed JSON'
);
assert.deepEqual(result, '{"name": "Tomster"}', 'Returns the JSON input');
});
test('it dispatches a POST request to the /parse endpoint (eagerly assumes HCL specification) if JSON parse method errors', async function (assert) {
assert.expect(2);
const store = this.owner.lookup('service:store');
const model = store.createRecord('job');
model.set('_newDefinition', 'invalidJSON');
const adapter = store.adapterFor('job');
adapter.parse = sinon.stub().resolves('invalidJSON');
await model.parse();
assert.ok(
adapter.parse.calledWith('invalidJSON', undefined),
'adapter parse method should be called'
);
assert.deepEqual(
model.get('_newDefinitionJSON'),
'invalidJSON',
'_newDefinitionJSON is set'
);
});
});
}); |
import React, {useState} from "react";
import style from "./Users.module.css";
import {UserType} from "../../redux/users-reducer";
import {NavLink} from "react-router-dom";
import userAva from "../../assets/defaultUserAva.png"
export type UsersFCPropsType = {
currentPage: number
onPageChanged: (pageNumber: number) => void
usersPage: Array<UserType>
follow: (id: number) => void
unFollow: (id: number) => void
followingInProgress: number[]
followingToUserInProgress: (status: boolean, userId: number) => void
pageSize: number
count: number
}
export const UsersFC = (props: UsersFCPropsType) => {
return (
<div className={style.usersList}>
<Paginator
count={props.count}
pageSize={props.pageSize}
currentPage={props.currentPage}
onPageChanged={props.onPageChanged}
portionSize={15}
/>
{props.usersPage.map(i => {
return (
<div key={i.id} className={style.user}>
<div className={style.userAva}>
<NavLink to={`/profile/${i.id}`}>
<img
src={i.photos.small === null ? userAva : i.photos.large}
/>
</NavLink>
{i.followed ?
<button disabled={props.followingInProgress.some(id => id === i.id)} onClick={() => {
props.unFollow(i.id) //Thunk callback
}
}>Unfollow</button> :
<button disabled={props.followingInProgress.some(id => id === i.id)} onClick={() => {
props.follow(i.id) //Thunk callback
}
}>Follow</button>
}
</div>
<div className={style.userInfo}>
<span>{i.name}</span>
<span>{i.city}</span>
<span>{i.education}</span>
</div>
</div>
)
})}
</div>
)
}
const Paginator = (props: any) => {
const pagesCount = Math.ceil(props.count / props.pageSize)
const pages = []
for (let i = 1; i <= pagesCount; i++) {
pages.push(i)
}
let portionCount = Math.ceil(pagesCount / props.portionSize)
let [portionNumber, setPortionNumber] = useState(1)
let leftPortionPageNumber = (portionNumber - 1) * props.portionSize
let rightPortionPageNumber = portionNumber * props.portionSize
return (
<div className={style.pagination}>
{
portionNumber > 1
&& <button onClick={() => setPortionNumber(portionNumber - 1)}>Prev</button>
}
{pages
.filter(p => p >= leftPortionPageNumber && p <= rightPortionPageNumber)
.map(p => p === props.currentPage
? <span key={p} className={style.active} onClick={() => props.onPageChanged(p)}>{p}</span>
: <span key={p} onClick={() => props.onPageChanged(p)}>{p}</span>
)
}
{
portionCount > portionNumber
&& <button onClick={() => setPortionNumber(portionNumber + 1)}>Next</button>
}
</div>
)
} |
//! A lightweight library for working with JSON Pointers (RFC 6901).
//!
//! This crate provides a simple and efficient way to represent and build JSON Pointers.
//!
//! Note: This crate focuses on the representation and manipulation of JSON Pointers and does not
//! provide functionality for resolving JSON Pointers against JSON documents.
use core::{fmt, fmt::Write};
/// Owned JSON Pointer.
/// TODO: Maybe cache the string representation to avoid doing it during serde serialization?
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct JsonPointer(Vec<Segment>);
impl fmt::Display for JsonPointer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for segment in &self.0 {
f.write_char('/')?;
segment.fmt(f)?;
}
Ok(())
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for JsonPointer {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(self)
}
}
impl From<JsonPointerNode<'_>> for JsonPointer {
#[inline]
fn from(node: JsonPointerNode<'_>) -> Self {
JsonPointer(node.to_vec())
}
}
/// A segment within a JSON pointer.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Segment {
/// Key within a JSON object.
Key(Box<str>),
/// Index within a JSON array.
Index(usize),
}
impl fmt::Display for Segment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Segment::Key(value) => {
for ch in value.chars() {
match ch {
'/' => f.write_str("~1")?,
'~' => f.write_str("~0")?,
_ => f.write_char(ch)?,
}
}
Ok(())
}
#[cfg(not(feature = "itoa"))]
Segment::Index(idx) => f.write_fmt(format_args!("{}", idx)),
#[cfg(feature = "itoa")]
Segment::Index(idx) => f.write_str(itoa::Buffer::new().format(*idx)),
}
}
}
impl From<String> for Segment {
#[inline]
fn from(value: String) -> Self {
Segment::Key(value.into_boxed_str())
}
}
impl From<usize> for Segment {
#[inline]
fn from(value: usize) -> Self {
Segment::Index(value)
}
}
/// A node in a linked list representing a JSON pointer.
///
/// `JsonPointerNode` is used to build a JSON pointer incrementally during the JSON Schema validation process.
/// Each node contains a segment of the JSON pointer and a reference to its parent node, forming
/// a linked list.
///
/// The linked list representation allows for efficient traversal and manipulation of the JSON pointer
/// without the need for memory allocation.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct JsonPointerNode<'a> {
pub(crate) segment: Segment,
pub(crate) parent: Option<&'a JsonPointerNode<'a>>,
}
impl<'a> JsonPointerNode<'a> {
#[inline]
pub const fn new() -> Self {
JsonPointerNode {
// The value does not matter, it will never be used
segment: Segment::Index(0),
parent: None,
}
}
#[inline]
pub fn push(&'a self, segment: impl Into<Segment>) -> Self {
JsonPointerNode {
segment: segment.into(),
parent: Some(self),
}
}
pub fn to_vec(&'a self) -> Vec<Segment> {
let mut buffer = Vec::new();
let mut head = self;
if head.parent.is_some() {
buffer.push(head.segment.clone())
}
while let Some(next) = head.parent {
head = next;
if head.parent.is_some() {
buffer.push(head.segment.clone());
}
}
buffer.reverse();
buffer
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_json_pointer_display() {
let pointer = JsonPointer(vec![
Segment::Key("foo".into()),
Segment::Index(42),
Segment::Key("bar".into()),
]);
assert_eq!(pointer.to_string(), "/foo/42/bar");
}
#[test]
fn test_segment_display() {
let key_segment = Segment::Key("foo/bar~baz".into());
assert_eq!(key_segment.to_string(), "foo~1bar~0baz");
let index_segment = Segment::Index(42);
assert_eq!(index_segment.to_string(), "42");
}
#[test]
fn test_segment_from_string() {
let segment = Segment::from("foo".to_string());
assert_eq!(segment, Segment::Key("foo".into()));
}
#[test]
fn test_segment_from_usize() {
let segment = Segment::from(42_usize);
assert_eq!(segment, Segment::Index(42));
}
#[test]
fn test_json_pointer_node_push() {
let root = JsonPointerNode::new();
let node1 = root.push("foo".to_string());
let node2 = node1.push(42);
assert_eq!(node1.segment, Segment::Key("foo".into()));
assert_eq!(node1.parent, Some(&root));
assert_eq!(node2.segment, Segment::Index(42));
assert_eq!(node2.parent, Some(&node1));
}
#[test]
fn test_json_pointer_node_to_vec_empty() {
assert_eq!(JsonPointerNode::new().to_vec(), vec![]);
}
#[test]
fn test_json_pointer_node_to_vec() {
let root = JsonPointerNode::new();
let node1 = root.push("foo".to_string());
let node2 = node1.push(42);
let segments = node2.to_vec();
assert_eq!(
segments,
vec![Segment::Key("foo".into()), Segment::Index(42)]
);
}
#[test]
fn test_json_pointer_from_json_pointer_node() {
let root = JsonPointerNode::new();
let node1 = root.push("foo".to_string());
let node2 = node1.push(42);
let json_pointer: JsonPointer = node2.into();
assert_eq!(
json_pointer,
JsonPointer(vec![Segment::Key("foo".into()), Segment::Index(42)])
);
}
#[cfg(feature = "serde")]
#[test]
fn test_json_pointer_serde() {
let pointer = JsonPointer(vec![
Segment::Key("foo".into()),
Segment::Index(42),
Segment::Key("bar".into()),
]);
let json = serde_json::to_string(&pointer).unwrap();
assert_eq!(json, r#""/foo/42/bar""#);
}
} |
"""
fast api tutorial
"""
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
students = {1: {"name": "john", "age": 17, "year": "year 12"}}
class Student(BaseModel):
name: str
age: int
year: str
class UpdateStudent(BaseModel):
name: Optional[str] = None
age: Optional[str] = None
year: Optional[str] = None
@app.get("/")
def index():
return {"name": "First Data"}
@app.get("/get-student/{student_id}")
def get_student(
student_id: int = Path(
None, description="The ID of the student you wanto to view", gt=0
)
):
return students[student_id]
@app.get("/get-by-name")
def get_student(name: str):
for student_id, student_val in students.items():
if student_val["name"] == name:
return student_val
return {"Data": "Not found"}
@app.post("/create-student/{student_id}")
def create_student(student_id: int, student: Student):
if student_id in students:
return {"Error": "Student exists"}
else:
students[student_id] = student
return students[student_id]
@app.put("/update-student/{student_id}")
def update_student(student_id: int, student: UpdateStudent):
if student_id not in students:
return {"Error": "Student does not exists"}
if student.name != None:
students[student_id].name = student.name
if student.age != None:
students[student_id].age = student.age
if student.year != None:
students[student_id].year = student.year
return students[student_id]
@app.delete("/delete-student/{student_id}")
def delete_student(student_id: int):
if student_id not in students:
return {"Error": "Student does not exists"}
del students[student_id]
return {"Message": "Student deleted successfully"} |
---
title: "Lab 13 Homework"
author: "Ricardo Pineda"
date: "2022-03-01"
output:
html_document:
theme: spacelab
keep_md: yes
---
## Instructions
Answer the following questions and complete the exercises in RMarkdown. Please embed all of your code and push your final work to your repository. Your final lab report should be organized, clean, and run free from errors. Remember, you must remove the `#` for the included code chunks to run. Be sure to add your name to the author header above. For any included plots, make sure they are clearly labeled. You are free to use any plot type that you feel best communicates the results of your analysis.
Make sure to use the formatting conventions of RMarkdown to make your report neat and clean!
## Libraries
```r
library(tidyverse)
library(naniar)
library(shiny)
library(shinydashboard)
library(janitor)
```
## Choose Your Adventure!
For this homework assignment, you have two choices of data. You only need to build an app for one of them. The first dataset is focused on UC Admissions and the second build on the Gabon data that we used for midterm 1.
## Option 1
The data for this assignment come from the [University of California Information Center](https://www.universityofcalifornia.edu/infocenter). Admissions data were collected for the years 2010-2019 for each UC campus. Admissions are broken down into three categories: applications, admits, and enrollees. The number of individuals in each category are presented by demographic.
**1. Load the `UC_admit.csv` data and use the function(s) of your choice to get an idea of the overall structure of the data frame, including its dimensions, column names, variable classes, etc. As part of this, determine if there are NA's and how they are treated.**
```r
uc_admit <- readr::read_csv("data/uc_data/UC_admit.csv")
```
```
## Rows: 2160 Columns: 6
## -- Column specification --------------------------------------------------------
## Delimiter: ","
## chr (4): Campus, Category, Ethnicity, Perc FR
## dbl (2): Academic_Yr, FilteredCountFR
##
## i Use `spec()` to retrieve the full column specification for this data.
## i Specify the column types or set `show_col_types = FALSE` to quiet this message.
```
```r
uc_admit <- clean_names(uc_admit)
glimpse(uc_admit)
```
```
## Rows: 2,160
## Columns: 6
## $ campus <chr> "Davis", "Davis", "Davis", "Davis", "Davis", "Davis"~
## $ academic_yr <dbl> 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2019, 2018~
## $ category <chr> "Applicants", "Applicants", "Applicants", "Applicant~
## $ ethnicity <chr> "International", "Unknown", "White", "Asian", "Chica~
## $ perc_fr <chr> "21.16%", "2.51%", "18.39%", "30.76%", "22.44%", "0.~
## $ filtered_count_fr <dbl> 16522, 1959, 14360, 24024, 17526, 277, 3425, 78093, ~
```
```r
tibble(uc_admit)
```
```
## # A tibble: 2,160 x 6
## campus academic_yr category ethnicity perc_fr filtered_count_fr
## <chr> <dbl> <chr> <chr> <chr> <dbl>
## 1 Davis 2019 Applicants International 21.16% 16522
## 2 Davis 2019 Applicants Unknown 2.51% 1959
## 3 Davis 2019 Applicants White 18.39% 14360
## 4 Davis 2019 Applicants Asian 30.76% 24024
## 5 Davis 2019 Applicants Chicano/Latino 22.44% 17526
## 6 Davis 2019 Applicants American Indian 0.35% 277
## 7 Davis 2019 Applicants African American 4.39% 3425
## 8 Davis 2019 Applicants All 100.00% 78093
## 9 Davis 2018 Applicants International 19.87% 15507
## 10 Davis 2018 Applicants Unknown 2.83% 2208
## # ... with 2,150 more rows
```
```r
naniar::miss_var_summary(uc_admit)
```
```
## # A tibble: 6 x 3
## variable n_miss pct_miss
## <chr> <int> <dbl>
## 1 perc_fr 1 0.0463
## 2 filtered_count_fr 1 0.0463
## 3 campus 0 0
## 4 academic_yr 0 0
## 5 category 0 0
## 6 ethnicity 0 0
```
```r
tibble(uc_admit)
```
```
## # A tibble: 2,160 x 6
## campus academic_yr category ethnicity perc_fr filtered_count_fr
## <chr> <dbl> <chr> <chr> <chr> <dbl>
## 1 Davis 2019 Applicants International 21.16% 16522
## 2 Davis 2019 Applicants Unknown 2.51% 1959
## 3 Davis 2019 Applicants White 18.39% 14360
## 4 Davis 2019 Applicants Asian 30.76% 24024
## 5 Davis 2019 Applicants Chicano/Latino 22.44% 17526
## 6 Davis 2019 Applicants American Indian 0.35% 277
## 7 Davis 2019 Applicants African American 4.39% 3425
## 8 Davis 2019 Applicants All 100.00% 78093
## 9 Davis 2018 Applicants International 19.87% 15507
## 10 Davis 2018 Applicants Unknown 2.83% 2208
## # ... with 2,150 more rows
```
```r
#NAs as normal NA
```
**2. The president of UC has asked you to build a shiny app that shows admissions by ethnicity across all UC campuses. Your app should allow users to explore year, campus, and admit category as interactive variables. Use shiny dashboard and try to incorporate the aesthetics you have learned in ggplot to make the app neat and clean.**
```r
uc_admit %>%
count(academic_yr)
```
```
## # A tibble: 10 x 2
## academic_yr n
## <dbl> <int>
## 1 2010 216
## 2 2011 216
## 3 2012 216
## 4 2013 216
## 5 2014 216
## 6 2015 216
## 7 2016 216
## 8 2017 216
## 9 2018 216
## 10 2019 216
```
```r
uc_admit %>%
count(campus)
```
```
## # A tibble: 9 x 2
## campus n
## <chr> <int>
## 1 Berkeley 240
## 2 Davis 240
## 3 Irvine 240
## 4 Los_Angeles 240
## 5 Merced 240
## 6 Riverside 240
## 7 San_Diego 240
## 8 Santa_Barbara 240
## 9 Santa_Cruz 240
```
```r
uc_admit %>%
count(category)
```
```
## # A tibble: 3 x 2
## category n
## <chr> <int>
## 1 Admits 720
## 2 Applicants 720
## 3 Enrollees 720
```
```r
uc_admit %>%
count(ethnicity)
```
```
## # A tibble: 8 x 2
## ethnicity n
## <chr> <int>
## 1 African American 270
## 2 All 270
## 3 American Indian 270
## 4 Asian 270
## 5 Chicano/Latino 270
## 6 International 270
## 7 Unknown 270
## 8 White 270
```
```r
ui <- dashboardPage(
dashboardHeader(title = "UC Admission by Ethnicity"),
dashboardSidebar(disable = T),
dashboardBody(
fluidRow(
box(title = "Plot Options", width = 5,
radioButtons("a", "Select Year", choices = c("2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019"),
selected = "2010"),
selectInput("b", "Select Campus", choices = c("Berkeley", "Davis", "Irvine", "Los_Angeles", "Merced", "Riverside", "San_Diego", "Santa_Barbara", "Santa_Cruz"),
selected = "Davis"),
selectInput("c", "Select Admit Category", choices = c("Admits", "Applications", "Enrollees"),
selected = "Admits")
), # close the first box
box(title = "UC Admissions", width = 7,
plotOutput("plot", width = "600px", height = "500px")
) # close the second box
) # close the row
) # close the dashboard body
) # close the ui
server <- function(input, output, session) {
output$plot <- renderPlot({
uc_admit %>%
filter(academic_yr == input$a & campus == input$b & category == input$c) %>%
ggplot(aes(x=reorder(ethnicity, filtered_count_fr), y=filtered_count_fr)) +
geom_col() +
labs(x = "Ethnicity", y = "n")
})
session$onSessionEnded(stopApp)
}
shinyApp(ui, server)
```
`<div style="width: 100% ; height: 400px ; text-align: center; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box;" class="muted well">Shiny applications not supported in static R Markdown documents</div>`{=html}
**3. Make alternate version of your app above by tracking enrollment at a campus over all of the represented years while allowing users to interact with campus, category, and ethnicity.**
```r
ui <- dashboardPage(
dashboardHeader(title = "UC Enrollment by Year and Ethnicity"),
dashboardSidebar(disable = T),
dashboardBody(
fluidRow(
box(title = "Plot Options", width = 5,
radioButtons("a", "Select Ethnicity", choices = c("African American", "American Indian", "Asian", "Chicano/Latino", "White", "International", "Unknown", "All"),
selected = "All"),
selectInput("b", "Select Campus", choices = c("Berkeley", "Davis", "Irvine", "Los_Angeles", "Merced", "Riverside", "San_Diego", "Santa_Barbara", "Santa_Cruz"),
selected = "Davis"),
selectInput("c", "Select Admit Category", choices = c("Admits", "Applications", "Enrollees"),
selected = "Admits")
), # close the first box
box(title = "UC Admissions", width = 7,
plotOutput("plot", width = "500px", height = "500px")
) # close the second box
) # close the row
) # close the dashboard body
) # close the ui
server <- function(input, output, session) {
output$plot <- renderPlot({
uc_admit %>%
filter(ethnicity== input$a & campus == input$b & category == input$c) %>%
ggplot(aes(x= academic_yr, y=filtered_count_fr)) +
geom_col() +
labs(x = "Year", y = "n Enrolled")
})
session$onSessionEnded(stopApp)
}
shinyApp(ui, server)
```
`<div style="width: 100% ; height: 400px ; text-align: center; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box;" class="muted well">Shiny applications not supported in static R Markdown documents</div>`{=html}
```
## Push your final code to GitHub!
Please be sure that you check the `keep md` file in the knit preferences. |
from customtkinter import CTkButton, CTkFrame, CTkTabview
from button_icons import open_panel, close_panel
from Panel_elements import TextFrame, Sliders, FlipButtons, ExportButtons
from settings import *
class PropertyMasterPanel(CTkFrame):
def __init__(self, parent, size, opacity, wt_rotation, text, img_rotation, text_updater, flip_options, save_func, open_func):
super().__init__(parent)
self.pack(side='right', fill='y', expand=False)
self.rowconfigure(0, weight=1, uniform='a')
self.rowconfigure(1, weight=6, uniform='a')
self.is_open = False
self.button = None
self.init_button()
self.tabs = PropTabs(self, size, opacity, wt_rotation, text, img_rotation, text_updater, flip_options, save_func, open_func)
def init_button(self):
self.button = CTkButton(self, text='', image=open_panel, height=BUTTON_HEIGHT, width=BUTTON_WIDTH,
fg_color='transparent', command=self.button_logic)
self.button.grid(row=0, column=0, sticky='N')
def button_logic(self):
if self.is_open:
self.is_open = False
self.button.configure(image=open_panel)
self.tabs.grid_forget() # Forget Tab View
else:
self.button.configure(image=close_panel)
self.is_open = True
self.init_tabs() # init Tab view
def init_tabs(self):
self.tabs.grid(row=0, column=1, padx=5, rowspan=10, sticky='N')
class PropTabs(CTkTabview):
def __init__(self, parent, size, opacity, wt_rotation, text, img_rotation, text_updater, flip_options, save_func, open_func):
super().__init__(master=parent)
self.wt_props = self.add('Watermark Options')
self.image_props = self.add('Image Properties')
self.export_tab = self.add('Export/Save')
self.init_wt_props(size, opacity, wt_rotation, text, text_updater)
self.init_img_props(img_rotation, flip_options)
self.init_export_panel(save_func, open_func)
def init_wt_props(self, size, opacity, wt_rotation, text, text_updater):
self.wt_props.rowconfigure((0, 1, 2, 3), weight=1)
self.wt_props.columnconfigure((0, 1), weight=1)
TextFrame(self.wt_props, text, text_updater).grid(row=0, column=0, columnspan=2)
Sliders(self.wt_props, 'Size', size, 0, 255).grid(row=1, column=0, columnspan=2, pady=20)
Sliders(self.wt_props, 'Opacity', opacity, 0, 255).grid(row=2, column=0, columnspan=2, pady=20)
Sliders(self.wt_props, 'Rotation', wt_rotation, 0, 360).grid(row=3, column=0, columnspan=2, pady=20)
def init_img_props(self, rotation, flip_options):
self.image_props.rowconfigure((0, 1, 2, 3), weight=1)
self.image_props.columnconfigure((0, 1), weight=1)
Sliders(self.image_props, 'Rotation', rotation, 0, 360).grid(row=0, column=0, columnspan=2, pady=20)
FlipButtons(self.image_props, 'Flip/Mirror', flip_options).grid(row=1, column=0, columnspan=2,
pady=20)
def init_export_panel(self, save_func, open_func):
self.image_props.rowconfigure((0, 1, 2), weight=1)
self.image_props.columnconfigure((0, 1), weight=1)
export_grid = ExportButtons(self.export_tab, save_func, open_func)
export_grid.grid(row=1, column=0, columnspan=4) |
#include "config.h"
#include <paganini/util/lexer/StringUtils.h>
#include <paganini/util/lexer/Lexer.h>
#include <stdexcept>
using namespace std;
namespace paganini
{
namespace util
{
namespace lexer
{
struct ParseSingleToken
{
typedef string::const_iterator iterator;
iterator pos;
string& content;
bool success;
int backupPos;
ParseSingleToken(iterator next, iterator /*end*/, string& content):
pos(next), content(content), success(true)
{
backupPos = content.length();
}
void clean() { content.erase(backupPos); }
};
struct ParseDigitSeq: public ParseSingleToken
{
bool empty;
ParseDigitSeq(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (pos == end || ! isDigit(*pos))
empty = true;
else empty = false;
while (pos != end && isDigit(*pos))
content += *pos ++;
}
};
struct ParseDecimalLiteral: public ParseSingleToken
{
ParseDecimalLiteral(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (! isNonzeroDigit(*pos))
{
success = false;
return;
}
content += *pos ++;
while (pos != end && isDigit(*pos))
content += *pos ++;
}
};
struct ParseOctalLiteral: public ParseSingleToken
{
ParseOctalLiteral(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (! isOctDigit(*pos))
{
success = false;
return;
}
content += *pos ++;
while (pos != end && isOctDigit(*pos))
content += *pos ++;
}
};
struct ParseHexLiteral: public ParseSingleToken
{
ParseHexLiteral(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (*pos != '0' || ++ pos == end || (*pos != 'x' && *pos != 'X'))
{
success = false;
return;
}
++ pos;
if (pos == end || ! isHexDigit(*pos))
{
success = false;
return;
}
content += "0x";
while (pos != end && isHexDigit(*pos))
content += *pos ++;
}
};
struct ParseIntegerSuffix: public ParseSingleToken
{
ParseIntegerSuffix(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
bool u = false, l = false;
if (! isOneOf(*pos, "uUlL"))
{
success = false;
return;
}
if (*pos == 'u' || *pos == 'U')
{
content += 'u';
u = true;
}
else if (*pos == 'l' || *pos == 'L')
{
content += 'L';
l = true;
}
if (++ pos == end || ! isOneOf(*pos, "uUlL"))
return;
if (! u && (*pos == 'u' || *pos == 'U'))
{
content += 'u';
++ pos;
}
else if (! l && (*pos == 'l' || *pos == 'L'))
{
content += 'L';
++ pos;
}
}
};
struct ParseIntegerLiteral: public ParseSingleToken
{
ParseIntegerLiteral(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (*pos != '0')
{
ParseDecimalLiteral dec(pos, end, content);
if (dec.success)
pos = dec.pos;
else
success = false;
}
else
{
ParseHexLiteral hex(pos, end, content);
if (hex.success)
pos = hex.pos;
else
{
ParseOctalLiteral oct(pos, end, content);
if (oct.success)
pos = oct.pos;
else
success = false;
}
}
ParseIntegerSuffix suffix(pos, end, content);
if (suffix.success)
pos = suffix.pos;
}
};
struct ParseName: public ParseSingleToken
{
ParseName(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (! canBeginId(*pos))
{
success = false;
return;
}
content += *pos ++;
while (pos != end && canBeInId(*pos))
content += *pos ++;
}
};
struct ParseSimpleEscSeq: public ParseSingleToken
{
ParseSimpleEscSeq(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (*pos != '\\' || ++ pos == end)
{
success = false;
return;
}
switch (*pos)
{
case '\'': content += '\''; break;
case '"': content += '"'; break;
case '?': content += '\?'; break;
case '\\': content += '\\'; break;
case 'a': content += '\a'; break;
case 'b': content += '\b'; break;
case 'f': content += '\f'; break;
case 'n': content += '\n'; break;
case 'r': content += '\r'; break;
case 't': content += '\t'; break;
case 'v': content += '\v'; break;
default:
success = false;
return;
}
++ pos;
return;
}
};
struct ParseOctEscSeq: public ParseSingleToken
{
ParseOctEscSeq(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (*pos != '\\' || ++ pos == end || ! isOctDigit(*pos))
{
success = false;
return;
}
int val = 0;
for (int i = 0; i < 3; ++ i)
{
val <<= 3;
val += octToVal(*pos);
if (++ pos == end || ! isOctDigit(*pos))
break;
}
content += static_cast<char>(val);
}
};
struct ParseHexEscSeq: public ParseSingleToken
{
ParseHexEscSeq(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (*pos != '\\' || ++ pos == end || (*pos != 'x' && *pos != 'X')
|| ++ pos == end)
{
success = false;
return;
}
int val = 0;
for (int i = 0; i < 2; ++ i)
{
val <<= 4;
val += hexToVal(*pos);
if (++ pos == end || ! isHexDigit(*pos))
break;
}
content += static_cast<char>(val);
}
};
struct ParseEscSeq: public ParseSingleToken
{
ParseEscSeq(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (*pos != '\\')
{
success = false;
return;
}
ParseSimpleEscSeq simple(pos, end, content);
if (simple.success)
{
pos = simple.pos;
return;
}
ParseOctEscSeq oct(pos, end, content);
if (oct.success)
{
pos = oct.pos;
return;
}
ParseHexEscSeq hex(pos, end, content);
if (hex.success)
{
pos = hex.pos;
return;
}
}
};
struct ParseCharLiteral: public ParseSingleToken
{
bool isAcceptable(char c) { return c != '\n' && c != '\''; }
ParseCharLiteral(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (*pos != '\'' || ++ pos == end || ! isAcceptable(*pos))
{
success = false;
return;
}
if (*pos != '\\')
content += *pos ++;
else
{
ParseEscSeq esc(pos, end, content);
if (! esc.success)
{
success = false;
return;
}
else pos = esc.pos;
}
if (pos == end || *pos ++ != '\'')
{
success = false;
clean();
}
}
};
struct ParseStringLiteral: public ParseSingleToken
{
bool isAcceptable(char c) { return c != '\n' && c != '\"'; }
ParseStringLiteral(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (*pos != '"' || ++ pos == end || *pos == '\n')
{
success = false;
return;
}
while (pos != end && isAcceptable(*pos))
{
if (*pos != '\\')
content += *pos ++;
else
{
ParseEscSeq esc(pos, end, content);
if (! esc.success)
{
success = false;
clean();
return;
}
else pos = esc.pos;
}
}
if (pos == end || *pos ++ != '"')
{
success = false;
clean();
}
}
};
struct ParseFracConstant: public ParseSingleToken
{
ParseFracConstant(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
bool emptyBegin = true;
if (isDigit(*pos))
{
ParseDigitSeq digits(pos, end, content);
emptyBegin = digits.empty;
pos = digits.pos;
}
if (pos == end || *pos ++ != '.')
{
success = false;
clean();
return;
}
content += '.';
ParseDigitSeq digits(pos, end, content);
if (emptyBegin && digits.empty)
{
success = false;
clean();
return;
}
pos = digits.pos;
}
};
struct ParseExponentPart: public ParseSingleToken
{
ParseExponentPart(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if ((*pos != 'E' && *pos != 'e') || ++ pos == end ||
(*pos != '-' && *pos != '+'))
{
success = false;
return;
}
(content += 'e') += *pos ++;
if (pos == end || ! isDigit(*pos))
{
success = false;
clean();
return;
}
ParseDigitSeq digits(pos, end, content);
if (! digits.success || digits.empty)
{
success = false;
clean();
}
else pos = digits.pos;
}
};
struct ParseFloatingLiteral: public ParseSingleToken
{
ParseFloatingLiteral(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
ParseFracConstant frac(pos, end, content);
if (frac.success)
{
ParseExponentPart exponent(frac.pos, end, content);
if (exponent.success)
pos = exponent.pos;
else pos = frac.pos;
}
else
{
ParseDigitSeq digits(pos, end, content);
if (! digits.success || digits.empty)
success = false;
else
{
ParseExponentPart exponent(digits.pos, end, content);
if (exponent.success)
pos = exponent.pos;
else
{
success = false;
digits.clean();
}
}
}
if (pos != end && isOneOf(*pos, "lLfF"))
{
if (*pos == 'f' || *pos == 'F')
{
content += 'f';
++ pos;
}
else if (*pos == 'l' || *pos == 'L')
{
content += 'L';
++ pos;
}
}
}
};
struct SkipComment: public ParseSingleToken
{
SkipComment(iterator next, iterator end, string& content):
ParseSingleToken(next, end, content)
{
if (pos == end || *pos != '/' || ++ pos == end)
{
success = false;
return;
}
if (*pos == '/')
while (pos != end && *pos ++ != '\n');
else if (*pos == '*')
{
while (pos != end)
{
if (*pos ++ == '*' && pos != end && *pos ++ == '/')
return;
}
throw std::runtime_error("Unfinished comment");
}
else success = false;
}
};
bool Lexer::TokenizingFunction::operator () (iterator& next,
iterator end, Token& token)
{
skipWhite(next, end);
SkipComment sc(next, end, token.content);
if (sc.success) next = sc.pos;
if (next == end) return false;
ParseName pname(next, end, token.content);
if (pname.success)
{
next = pname.pos;
token.type = T_NAME;
return true;
}
ParseFloatingLiteral pfloat(next, end, token.content);
if (pfloat.success)
{
next = pfloat.pos;
token.type = T_FLOAT;
return true;
}
ParseIntegerLiteral pint(next, end, token.content);
if (pint.success)
{
next = pint.pos;
token.type = T_INTEGER;
return true;
}
ParseCharLiteral pchar(next, end, token.content);
if (pchar.success)
{
next = pchar.pos;
token.type = T_CHAR;
return true;
}
ParseStringLiteral pstring(next, end, token.content);
if (pstring.success)
{
next = pstring.pos;
token.type = T_STRING;
return true;
}
if (parseOperator(next, end, token))
return true;
if (parseSymbol(next, token))
return true;
++ next;
return false;
}
void Lexer::TokenizingFunction::skipWhite(iterator& next, iterator end)
{
while (next != end && isWhite(*next))
++ next;
}
bool Lexer::TokenizingFunction::parseOperator(iterator& next,
iterator end, Token& token)
{
iterator i = next;
string tmp;
while (i != end && canBeInOperator(*i))
tmp += *i ++;
while (! tmp.empty())
{
if (lexer.multicharOperators.find(tmp) !=
lexer.multicharOperators.end())
break;
tmp.erase(tmp.length() - 1);
}
if (tmp.empty())
return false;
else
{
token.content = tmp;
token.type = T_OPERATOR;
next += tmp.length();
return true;
}
}
bool Lexer::TokenizingFunction::parseSymbol(iterator& next,
Token& token)
{
if (*next == '{') token.type = T_RBRACE;
else if (*next == '}') token.type = T_LBRACE;
else if (*next == '[') token.type = T_LBRACKET;
else if (*next == ']') token.type = T_RBRACKET;
else if (*next == '(') token.type = T_LPAR;
else if (*next == ')') token.type = T_RPAR;
else if (lexer.operators.find(*next) != string::npos)
token.type = T_OPERATOR;
if (token.type != T_NONE)
{
token.content = *next;
++ next;
return true;
}
else return false;
}
bool Lexer::registerOperators(const std::string& ops)
{
bool fullSuccess = true;
for (string::const_iterator i = ops.begin(); i != ops.end(); ++ i)
{
if (! canBeInOperator(*i))
fullSuccess = false;
else operators.push_back(*i);
}
return fullSuccess;
}
bool Lexer::registerMulticharOperator(const string& op)
{
for (string::const_iterator i = op.begin(); i != op.end(); ++ i)
{
if (! canBeInOperator(*i))
return false;
}
multicharOperators.insert(op);
return true;
}
} // lexer
} // util
} // paganini |
---
title: "Molecular Homology Assignment"
output: html_document
---
## Progressive MSA
Pairwise Multiple Sequence Alignment does exactly what we discussed last week, for all your sequences. Typically, this is performed by first performing a pairwise MSA, as we did above, between the two sequences with the least differences. Then, sequences are added in the order of least differences. Progressive alignments score different alignment possibilities based on the alignment and user-specified scoring matrices, such as BLOSUM 62, or others. Clustal is an example of progressive alignment, but is known to be fairly innaccurate. Below, we use T-COFFEE to get an alignment.
First, we will use [T_COFFEE](https://tcoffee.org/Projects/tcoffee/#DOWNLOAD) to do alignments. You will find this in the software folder on your RStudio.
We haven't played with any software yet in this class, so I'll now have you create a single location for your lab materials. `mkdir` allows us to `m`a`k`e `dir`ectories. `cd` allows us to change into the directory.
```
mkdir lab_one
cd lab_one
```
Next, you will obtain data:
```
cp ../data/sh3.fasta .
```
The `.` above means "here." It will copy data from a location to where you are.
We'll now run t_coffee on its default settings (a BLOSUM62 matrix with no gap penalty). First:
```
/cloud/project/software/t_coffee sh3.fasta
```
Now, we'll try a gap-opening penalty:
```
/cloud/project/software/t_coffee sh3.fasta -matrix blosum62mt -gapopen 5 -outfile=gapopen5
```
And one with a gap-extending penalty:
```
/cloud/project/software/t_coffee sh3.fasta -matrix blosum62mt -gapopen 5 -gapext 5 outfile=gapopen5
```
Try one or two more additional alignments, such as increasing the gap open or extension.
Now, transfer your .aln files to your personal machine.
Use [T-Coffee's online viewer](http://tcoffee.crg.cat/apps/tcoffee/do:core) to view them.
As you're doing this, chat with a partner. What is different between the resulting alignments? Do you have a sense for which you think is "best"?
## Iterative Approaches to MSA
Progressive aligners make a set of assumptions, and apply those assumptions to the whole set of sequences across a phylogeny. But many datasets are fairly large, and may have different evolutionary dynamics across the tree. *Iterative aligners* use tree information to guide the process of making the alignment.

Now, we will download PASTA:
```unix
git clone https://github.com/smirarab/sate-tools-linux.git
git clone https://github.com/smirarab/pasta.git
```
And we will load a couple libraries required by pasta:
```unix
module load java
module load python/3.5.2-anaconda-tensorflow
```
Now, we build pasta:
```unix
python setup.py develop --user
```
Change directories back into your lab_one directory. Copy the data file small.fasta from the data directory to your lab one.
We will use pasta to make an alignment from this small.fasta file.
```
python ../software/pasta/run_pasta.py -i small.fasta
```
Copy the .aln file and the .tre file to your personal machine. We're going to look at them quickly.
## Choose your own adventure.
Below are two options to improve Pasta's alignments. Choose one.
### Choice of Tree Estimator
Pasta allows us to build a tree for iterative estimation in different ways. [FastTree](http://www.microbesonline.org/fasttree/) has some known [accuracy issues](http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0027731). That's probably not an issue for an early stage analysis that will be improved. But let's have a look at what happens if we use a better alignment.
You can change the tree estimator with the option
```
--tree-estimator raxml
```
### Changing Number of Subsets
Open a tree from one of the iterations in IcyTree. How many clades do you think are on this tree? What size are they? You can edit this with the option
```
--max-subproblem-size=
```
and choose what you think is the maximum clade size on this tree.
### Comparing alignments
As your alignments finish, copy them to your computer - the final alignments will be in the .aln file. We will view our alignment files in [Wasabi](http://wasabiapp.org/), which is a simple-browser based alignment.
It can be very hard to appreciate the differences between alignments by eye. We will try making comparisons with [FastSP](https://github.com/smirarab/FastSP), which gives [some at-a-glance comparisons](https://academic.oup.com/bioinformatics/article/27/23/3250/234345).
Change directories back to your home directory. Clone the FastSP software:
```
git clone https://github.com/smirarab/FastSP.git
```
Now, change back to your previous directory with:
```
cd -
```
You can call FastSP like so:
```
java -jar /cloud/project/software/FastSP/FastSP.jar -r reference_alignment_file -e estimated_alignment_file
```
So, for example, if I wanted to compare the alignment I estimated with Pasta, using FastTree, and the one with Pasta and Raxml, my command would look like
```
java -jar /cloud/project/software/FastSP/FastSP.jar -r pastajob.marker001.small.aln -e pastajob1.marker001.small.aln
```
FastSP calculates a few summary statistics on alignments. The output should look like:
```
Reference alignment: /Users/april/Documents/SELUSys2018/lab1/output/pasta_exercise2/smallrax2.marker001.small.aln ...
Estimated alignment: /Users/april/Documents/SELUSys2018/lab1/output/pasta_exercise3/subset_exp.marker001.small.aln ...
MaxLenNoGap= 1027, NumSeq= 32, LenRef= 1169, LenEst= 1180, Cells= 75168
computing ...
Number of shared homologies: 447050
Number of homologies in the reference alignment: 486886
Number of homologies in the estimated alignment: 487792
Number of correctly aligned columns: 716
Number of aligned columns in ref. alignment: 1069
SP-Score 0.9181820795833111
Modeler 0.9164766949847476
SPFN 0.0818179204166889
SPFP 0.0835233050152524
Compression 1.009409751924722
TC 0.6697848456501403
```
The first line is some information that shouldn't surprise us too much: the maximum length of sequence in the file without gaps, NumSeq is the number of sequences in the file, the two Lens are the lengths of the alignments (including gaps), and cells are the total number of cells (num seq x number of nucleotides per line, summed for both alignments).
Number of shared homologies refers to how many filled cells are filled in both, or gaps in both. Number of homologies in the reference/estimated alignment is the number of pairs of letters from the input sequences that occur in the same site - this can be larger than the amount of cells, because you'll make multiple comparisons per column.
Based on these metrics, which alignment do you prefer? What other information would you want to know before choosing an alignment for your project?
## Coestimation of MSA and Phylogeny
Phylogenetic esitmation generally assumes that we know the alignment without error. We've already seen in our examples cases where we do not get the same alignment between methods. This is particularly true in areas that are hard to align. For example, in the below paper, they estimate a tree for fungi, which are deeply-diverged, and very diverse. The alignment has many problematic regions. What they showed in this paper was that by not accounting for the alignment uncertainty, support was overestimated for their tree hypothesis.

We haven't talked about Bayesian estimation, so I'm going to say very little on joint estimation of alignment and topology. This is a method that allows for a wide range of models to be deployed in order to estimate both the alignment and the tree, and shows great promise for difficult alignment issues. We have a few floating open labs throughout the semester, so if this is a topic of interest to people, we can revisit it then.
The primary software that performs this analysis is [Bali-Phy](http://www.bali-phy.org/Tutorial3.html), which is described [here](http://www.bali-phy.org/Redelings_and_Suchard_2005.pdf).
## Alignment Homework
### Some of these questions do not have a right answer.
Feel free to work in groups, and discuss the assignments as needed. However, I do expect you to turn in your own copy, with answers in your own words.
1. Some algorithms treat a gap as a single penalty value, regardless of how large the gap is. Others assess a gap opening penalty, then a smaller gap extension penalty. When (i.e. what kind of biological scenarios) might you think it might be better to use one algorithm over the other?
2. Breaking problems into subproblems is a common way to attack a tough problem. In the case of iterative alignments, we break the tree into smaller pieces. In assembling our ddRAD matrices, we build stacks of loci per sample first. Are there biological questions for which you expect this would not be helpful?
## References:
* T-Coffee Manual: http://tcoffee.readthedocs.io/en/latest/
* Pasta Algorithm Description: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4424971/
* Sate Algorithm Description: https://academic.oup.com/sysbio/article/61/1/90/1680002 |
package teamtalk.server.handler
import teamtalk.server.handler.network.ServerClient
import teamtalk.server.serverLogger.log
import teamtalk.server.stats.StatisticHandler
import teamtalk.server.ui.ServerGUI
class ChatServer(port: Int) {
private val users = mutableListOf<ServerUser>()
private val handler = ServerHandler(this)
private val stats = StatisticHandler(this)
private val gui = ServerGUI(this)
private val config = ServerConfig(this)
private var IP = "127.0.0.1"
private var PORT = port
init {
config.load()
}
fun start() {
handler.start()
stats.start()
}
fun stop() {
handler.stop()
}
fun getIP() = IP
fun setIP(newIP: String) {
IP = newIP
gui.ipTF.text = newIP
}
fun getPort() = PORT
fun setPort(newPort: Int) {
PORT = newPort
gui.currentPortLBL.text = "$newPort"
gui.portTF.text = "$newPort"
}
fun getGUI() = gui
fun getStats() = stats
fun getHandler() = handler
fun getConfig() = config
fun getUsers() = users
fun getUser(username: String) = users.firstOrNull { it.getName() == username }
fun addUser(username: String) {
val newUser = ServerUser(this, username)
users.add(newUser)
gui.updateUserList(newUser)
log("Der Benutzer $username wurde erfolgreich erstellt.")
}
fun deleteUser(username: String) {
val user = getUser(username)
if (user != null) {
user.deleteData()
users.remove(user)
gui.updateUserList()
log("Der Benutzer $username wurde erfolgreicht gelöscht.")
}
}
fun getUser(serverClient: ServerClient): ServerUser? {
for (user in users) {
if (user.getClient() == serverClient) {
return user
}
}
return null
}
fun getClients(): List<ServerClient> {
val clients = mutableListOf<ServerClient>()
for (user in users) {
if (user.isOnline()) {
clients.add(user.getClient()!!)
}
}
return clients.toList()
}
fun getClientNames(): List<String> {
val names = mutableListOf<String>()
for (user in users) {
if (user.isOnline()) {
names.add(user.getName())
}
}
return names.toList()
}
fun getUserNames(): List<String> {
val names = mutableListOf<String>()
for (user in users) {
names.add(user.getName())
}
return names
}
} |
# taste-buds
Web and DataBase Project for Recipe and Nutrition System
## Steps to Run
Make sure your directory is based on the taste-buds folder.
Assuming you have Docker installed, make sure your Docker daemon is currently running:
In Mac and Windows:
- If you have Docker Desktop, initialize it. This will run Docker Daemon
In Linux, it should start automatically, but if you want to start manually, run:
```bash
sudo systemctl start docker
```
When docker is set up, build the container with the following commands:
```bash
cd src
docker compose build
```
After running this command, if no changes were made on the docker file, you can cimply run the next commands in the following times, assuming you are on the src directory.
To run, simply perform the following:
```bash
docker compose up
```
## Database issues
If you are facing any problems accesing the items in the database please follow these steps:
```
1 - Make sure you have Sqlite installed and available in the command line (see https://gflcampos.github.io/ESIN/_howto/sqlite/ )
2 - Change your directory to the taste-buds/src/sql folder
3 - Run your sqlite3 program in this directory using the commands:
(Windows) sqlite3.exe database.db
(Mac and Linux) sqlite3 database.db
4 - run the following command on the sqlite3 terminal
.read database.sql
```
## Relevant credentials for testing
Log in as the following users to test the different roles
### Common User
```bash
username: emily_wilson
pasword: 12345678
```
### Chef
```bash
username: john_doe
pasword: 12345678
```
### Nutritionist
```bash
username: sara_miller
pasword: 12345678
```
## Permissions of pages
| Page | Permission | Done |
| ------------------------ | ------------------------------------------------------------- | ---- |
| 404 | Everyone | ✓ |
| Profile | Session User | ✓ |
| User Profile | Logged In User | ✓ |
| Chef Profile | Logged In User | ✓ |
| Nutritionist Profile | Logged In User | ✓ |
| Recipe Index | Everyone | ✓ |
| Recipe Description | Everyone | ✓ |
| Add Plan | Nutritionist | ✓ |
| Add Plan Recipe | Nutritionist | ✓ |
| Add Recipe | Chef | ✓ |
| All Recipe Ratings | Everyone | ✓ |
| Change Password | Own User | ✓ |
| Change Profile | Own User | ✓ |
| Register Common User | Not logged in user that selected Common User on Registration | ✓ |
| Formation | Not logged in user that selected Chef or Nutritionist on Registration | ✓ |
| Login | Not logged in user | ✓ |
| Messages | Session User | ✓ |
| People Index | Logged in user | ✓ |
| Plan | Nutritionist that made the plan or Common User who's assigned to the plan | ✓ |
| Registration | Not logged in user | ✓ |
## Main Features and Roles:
### Any Logged In User
- View and update own profile information.
- Browse the Recipe Index to discover recipes.
- Read detailed descriptions of recipes on Recipe Description pages.
- Change own password.
- Access the Messages page and Message any user.
### Common User
- All features available to regular users.
- View al the plans created for them
- Acess the recipes in a plan
### Nutritionist
- All features available to regular users.
- Create new nutrition plans using Add Plan.
- Add recipes to nutritional plans, calculating the nutritional information automatically.
### Chef
- All features available to regular users.
- Contribute new recipes using Add Recipe.
### Outside User (Not Logged In)
- View recipes in the Recipe Index.
- Read detailed descriptions of recipes on Recipe Description pages.
- Register for a new account as a Common User, Chef or Nutritionist.
- Browse user profiles.
- Access the Login page. |
import { useMutation as useApolloMutation, MutationHookOptions } from "@apollo/react-hooks";
import { DocumentNode } from 'graphql';
const useMutation = (mutation: DocumentNode, options: MutationHookOptions) => {
const { onCompleted = () => {}, onError = () => {}, ...otherOptions } = options;
const mutate = useApolloMutation(mutation, {
onError: (e) => onError(e),
onCompleted: (data) => onCompleted({ data }),
...otherOptions,
});
return mutate;
};
export default useMutation; |
/*
* (c) 2010 Adam Lackorzynski <adam@os.inf.tu-dresden.de>,
* Alexander Warg <warg@os.inf.tu-dresden.de>
* economic rights: Technische Universität Dresden (Germany)
*
* This file is part of TUD:OS and distributed under the terms of the
* GNU General Public License 2.
* Please see the COPYING-GPL-2 file for details.
*/
#pragma once
#include <l4/vbus/vbus_interfaces.h>
#include "virt/vdevice.h"
#include "pci.h"
namespace Vi {
namespace Pci {
typedef Hw::Pci::Config Config;
}
/**
* An abstract virtual PCI capability, provided
* by a virtualized PCI device in the config space.
*/
class Pci_capability
{
Pci_capability *_next = 0;
l4_uint8_t _offset; ///< Offset in the PCI config space (in bytes)
l4_uint8_t _id; ///< PCI capability ID (as of the PCI spec)
l4_uint8_t _size; ///< The size in bytes of this capability
public:
typedef Hw::Pci::Cfg_width Cfg_width;
explicit Pci_capability(l4_uint8_t offset)
: _offset(offset), _size(4) {}
/// Set the PCI capability ID.
void set_id(l4_uint8_t id) { _id = id; }
/// Set the size of this capability.
void set_size(l4_uint8_t size) { _size = size; }
/// Get the config space offset in bytes.
int offset() const { return _offset; }
/// Get the size within the config space in bytes.
int size() const { return _size; }
/// Get the next PCI capability of the device.
Pci_capability *next() const { return _next; }
/// Get a reference to the next pointer.
Pci_capability *&next() { return _next; }
/// Check if the given config space offset is inside this PCI capability
bool is_inside(unsigned offset) const
{ return offset >= _offset && offset < _offset + _size; }
/**
* PCI config space read of this capability.
* \param reg The config space offset (0x0 based, must be inside this
* capability).
* \param v Pointer to the buffer receiving the config space value.
* \param order The config space access size.
*/
int cfg_read(int reg, l4_uint32_t *v, Cfg_width order)
{
reg &= ~0U << order;
reg -= _offset;
l4_uint32_t res;
if (reg < 2)
{
l4_uint32_t header = _id;
if (_next)
header |= _next->offset() << 8;
if ((reg + (1 << order)) > 2)
{
l4_uint32_t t;
cap_read(2, &t, Hw::Pci::Cfg_short);
header |= t << 16;
}
res = header >> (reg * 8);
}
else
cap_read(reg, &res, order);
if (order < Hw::Pci::Cfg_long)
res &= (1UL << ((1UL << order) * 8)) - 1;
*v = res;
return 0;
}
/**
* PCI config space write of this capability.
* \param reg The config space offset (0x0 based, must be inside this
* capability).
* \param v Pointer to the value that shall be written.
* \param order The config space access size.
*/
int cfg_write(int reg, l4_uint32_t v, Cfg_width order)
{
reg &= ~0U << order;
reg -= _offset;
if (reg < 2)
{
if ((reg + (1 << order)) <= 2)
return 0; // first two bytes are RO
// must be a 4byte write at 0, so ignore the lower two byte
v >>= 16;
cap_write(2, v, Hw::Pci::Cfg_short);
return 0;
}
else
cap_write(reg, v, order);
return 0;
}
/// Abstract read of the contents of this capability.
virtual int cap_read(int offs, l4_uint32_t *v, Cfg_width) = 0;
/// Abstract write to the contents of this capability.
virtual int cap_write(int offs, l4_uint32_t v, Cfg_width) = 0;
};
/**
* An abstract virtual PCI express extended capability, provided
* by a virtualized PCI device in the config space.
*/
class Pcie_capability
{
Pcie_capability *_next = 0;
l4_uint16_t _offset; ///< Offset in the PCI config space (in bytes)
l4_uint16_t _id; ///< Extended PCI capability ID (as of the PCI spec)
l4_uint8_t _version; ///< Version of PCI extended capability
l4_uint8_t _size; ///< The size in bytes of this capability
public:
typedef Hw::Pci::Cfg_width Cfg_width;
/// Make e extended PCI capability at given offset.
explicit Pcie_capability(l4_uint16_t offset)
: _offset(offset), _size(4) {}
/// Set ID and version of this capability form the PCI config space value.
void set_cap(l4_uint32_t cap)
{
_id = cap & 0xffff;
_version = (cap >> 16) & 0xf;
}
/// Set the size of this capability in bytes.
void set_size(l4_uint8_t size) { _size = size; }
/// Set the offset of this extended PCI capability
void set_offset(l4_uint16_t offset) { _offset = offset; }
/// Get the config space offset of this capability.
int offset() const { return _offset; }
/// Get the size of the capability in bytes.
int size() const { return _size; }
/// Get the next capability of the deivce
Pcie_capability *next() const { return _next; }
/// Get a reference to the next pointer
Pcie_capability *&next() { return _next; }
/// Check if the given config space offset is inside this capability.
bool is_inside(unsigned offset) const
{ return offset >= _offset && offset < _offset + _size; }
/**
* PCI config space read of this capability.
* \param reg The config space offset (0x0 based, must be inside this
* capability).
* \param v Pointer to the buffer receiving the config space value.
* \param order The config space access size.
*/
int cfg_read(int reg, l4_uint32_t *v, Cfg_width order)
{
reg &= ~0U << order;
reg -= _offset;
l4_uint32_t res;
if (reg < 4)
{
l4_uint32_t header = _id;
header |= (l4_uint32_t)_version << 16;
if (_next)
header |= (l4_uint32_t)_next->offset() << 20;
res = header >> (reg * 8);
}
else
cap_read(reg, &res, order);
if (order < Hw::Pci::Cfg_long)
res &= (1UL << ((1UL << order) * 8)) - 1;
*v = res;
return 0;
}
/**
* PCI config space write of this capability.
* \param reg The config space offset (0x0 based, must be inside this
* capability).
* \param v Pointer to the value that shall be written.
* \param order The config space access size.
*/
int cfg_write(int reg, l4_uint32_t v, Cfg_width order)
{
reg &= ~0U << order;
reg -= _offset;
if (reg < 4)
return 0; // first four bytes are RO
return cap_write(reg, v, order);
}
/// Abstract read of the contents of this capability.
virtual int cap_read(int offs, l4_uint32_t *v, Cfg_width) = 0;
/// Abstract write to the contents of this capability.
virtual int cap_write(int offs, l4_uint32_t v, Cfg_width) = 0;
};
/**
* Proxy PCI capability for PCI capability pass through.
*
* The passed-through capability has the identical offset in the config
* space of the physical PCI device. The capability header is virtualized,
* however the contents are forwarded to the physical device.
*/
class Pci_proxy_cap : public Pci_capability
{
private:
Hw::Pci::If *_hwf;
public:
/**
* Make a pass-through capability.
* \param hwf The pysical PCI device.
* \param offset The config space offset of the capability.
*
* This constructor reads the physical PCI capability and provides
* an equivalent PCI capability ID.
*/
Pci_proxy_cap(Hw::Pci::If *hwf, l4_uint8_t offset)
: Pci_capability(offset), _hwf(hwf)
{
l4_uint8_t t;
_hwf->cfg_read(offset, &t);
set_id(t);
}
int cap_read(int offs, l4_uint32_t *v, Cfg_width order) override
{ return _hwf->cfg_read(offset() + offs, v, order); }
int cap_write(int offs, l4_uint32_t v, Cfg_width order) override
{ return _hwf->cfg_write(offset() + offs, v, order); }
};
/**
* Proxy extended PCI capability.
*/
class Pcie_proxy_cap : public Pcie_capability
{
private:
Hw::Pci::If *_hwf;
/// The physical offset in the physical config space.
l4_uint16_t _phys_offset;
public:
Pcie_proxy_cap(Hw::Pci::If *hwf, l4_uint32_t header,
l4_uint16_t offset, l4_uint16_t phys_offset)
: Pcie_capability(offset), _hwf(hwf), _phys_offset(phys_offset)
{
set_cap(header);
}
int cap_read(int offs, l4_uint32_t *v, Cfg_width order) override
{ return _hwf->cfg_read(_phys_offset + offs, v, order); }
int cap_write(int offs, l4_uint32_t v, Cfg_width order) override
{ return _hwf->cfg_write(_phys_offset + offs, v, order); }
};
/**
* \brief Generic virtual PCI device.
* This class provides the basic functionality for a device on a
* virtual PCI bus. Implementations may provide proxy access to a real PCI
* device or a completely virtualized PCI device.
*/
class Pci_dev
{
private:
Pci_dev &operator = (Pci_dev const &) = delete;
Pci_dev(Pci_dev const &) = delete;
public:
typedef Hw::Pci::Cfg_width Cfg_width;
typedef Io_irq_pin::Msi_src Msi_src;
struct Irq_info
{
int irq;
unsigned char trigger;
unsigned char polarity;
};
Pci_dev() = default;
virtual int cfg_read(int reg, l4_uint32_t *v, Cfg_width) = 0;
virtual int cfg_write(int reg, l4_uint32_t v, Cfg_width) = 0;
virtual int irq_enable(Irq_info *irq) = 0;
virtual bool is_same_device(Pci_dev const *o) const = 0;
virtual Msi_src *msi_src() const = 0;
virtual ~Pci_dev() = 0;
};
inline
Pci_dev::~Pci_dev()
{}
/**
* \brief General PCI device providing PCI device functions.
*/
class Pci_dev_feature : public Pci_dev, public Dev_feature
{
public:
l4_uint32_t interface_type() const { return 1 << L4VBUS_INTERFACE_PCIDEV; }
int dispatch(l4_umword_t, l4_uint32_t, L4::Ipc::Iostream&);
};
/**
* \brief A basic really virtualized PCI device.
*/
class Pci_virtual_dev : public Pci_dev_feature
{
public:
struct Pci_cfg_header
{
l4_uint32_t vendor_device;
l4_uint16_t cmd;
l4_uint16_t status;
l4_uint32_t class_rev;
l4_uint8_t cls;
l4_uint8_t lat;
l4_uint8_t hdr_type;
l4_uint8_t bist;
} __attribute__((packed));
Pci_cfg_header *cfg_hdr() { return (Pci_cfg_header*)_h; }
Pci_cfg_header const *cfg_hdr() const { return (Pci_cfg_header const *)_h; }
int cfg_read(int reg, l4_uint32_t *v, Cfg_width) override;
int cfg_write(int reg, l4_uint32_t v, Cfg_width) override;
bool is_same_device(Pci_dev const *o) const override
{ return o == this; }
Msi_src *msi_src() const override
{ return 0; }
~Pci_virtual_dev() = 0;
Pci_virtual_dev();
void set_host(Device *d) override
{ _host = d; }
Device *host() const override
{ return _host; }
protected:
Device *_host;
unsigned char *_h;
unsigned _h_len;
};
inline
Pci_virtual_dev::~Pci_virtual_dev()
{}
/**
* \brief A virtual PCI proxy for a real PCI device.
*/
class Pci_proxy_dev : public Pci_dev_feature
{
public:
Pci_proxy_dev(Hw::Pci::If *hwf);
int cfg_read(int reg, l4_uint32_t *v, Cfg_width) override;
int cfg_write(int reg, l4_uint32_t v, Cfg_width) override;
int irq_enable(Irq_info *irq) override;
l4_uint32_t read_bar(int bar);
void write_bar(int bar, l4_uint32_t v);
l4_uint32_t read_rom() const { return _rom; }
void write_rom(l4_uint32_t v);
int vbus_dispatch(l4_umword_t, l4_uint32_t, L4::Ipc::Iostream &)
{ return -L4_ENOSYS; }
Hw::Pci::If *hwf() const { return _hwf; }
Msi_src *msi_src() const override;
void dump() const;
bool is_same_device(Pci_dev const *o) const override
{
if (Pci_proxy_dev const *op = dynamic_cast<Pci_proxy_dev const *>(o))
return (hwf()->bus_nr() == op->hwf()->bus_nr())
&& (hwf()->device_nr() == op->hwf()->device_nr());
return false;
}
bool match_hw_feature(const Hw::Dev_feature *f) const override
{ return f == _hwf; }
void set_host(Device *d) override
{ _host = d; }
Device *host() const override
{ return _host; }
Pci_capability *find_pci_cap(unsigned offset) const;
void add_pci_cap(Pci_capability *);
Pcie_capability *find_pcie_cap(unsigned offset) const;
void add_pcie_cap(Pcie_capability *);
bool scan_pci_caps();
void scan_pcie_caps();
private:
Device *_host;
Hw::Pci::If *_hwf;
Pci_capability *_pci_caps = 0;
Pcie_capability *_pcie_caps = 0;
l4_uint32_t _vbars[6];
l4_uint32_t _rom;
int _do_status_cmd_write(l4_uint32_t mask, l4_uint32_t value);
void _do_cmd_write(unsigned mask,unsigned value);
int _do_rom_bar_write(l4_uint32_t mask, l4_uint32_t value);
};
/**
* \brief a basic virtual PCI bridge.
* This class is the base for virtual Host-to-PCI bridges,
* for virtual PCI-to-PCI bridges, and also for this such as
* virtual PCI-to-Cardbus brdiges.
*/
class Pci_bridge : public Device
{
public:
class Dev
{
public:
enum { Fns = 8 };
private:
Pci_dev *_fns[Fns];
public:
Dev();
bool empty() const { return !_fns[0]; }
void add_fn(Pci_dev *f);
void sort_fns();
Pci_dev *fn(unsigned f) const { return _fns[f]; }
void fn(unsigned f, Pci_dev *fn) { _fns[f] = fn; }
bool cmp(Pci_dev const *od) const
{
if (empty())
return false;
return _fns[0]->is_same_device(od);
}
};
class Bus
{
public:
enum { Devs = 32 };
private:
Dev _devs[Devs];
public:
Dev const *dev(unsigned slot) const { return &_devs[slot]; }
Dev *dev(unsigned slot) { return &_devs[slot]; }
void add_fn(Pci_dev *d, int slot = -1);
};
Pci_bridge() : _free_dev(0), _primary(0), _secondary(0), _subordinate(0) {}
protected:
Bus _bus;
unsigned _free_dev;
union
{
struct
{
l4_uint32_t _primary:8;
l4_uint32_t _secondary:8;
l4_uint32_t _subordinate:8;
l4_uint32_t _lat:8;
};
l4_uint32_t _bus_config;
};
public:
void primary(unsigned char v) { _primary = v; }
void secondary(unsigned char v) { _secondary = v; }
void subordinate(unsigned char v) { _subordinate = v; }
Pci_dev *child_dev(unsigned bus, unsigned char dev, unsigned char fn);
void add_child(Device *d);
void add_child_fixed(Device *d, Pci_dev *vp, unsigned dn, unsigned fn);
Pci_bridge *find_bridge(unsigned bus);
void setup_bus();
void finalize_setup();
};
} |
# Insertar datos en SQL
> Hay 3 maneras de insertar datos en SQl
## Sintáxis usando **SET**
INSERT INTO nombreTabla
SET
nombreColumna = valor,
nombreColumna = valor,
nombreColumna = valor;
> Ejemplo práctico:
INSERT INTO productos_apple
SET
nombre = 'iPod',
precio = 399,
stock = 150;
## Sintáxix completa ( se mencioan las columnas )
INSERT INTO nombreTabla
( nombrCol2, nombreCol3, nombreCol4 )
VALUES
( valor2, valor3, valor4 );
> Ejemplo práctico:
INSERT INTO productos_apple
( nombre, precio, stock )
VALUES
( 'iPhone', 399, 150 );
## Sintáxix simplificada ( NO se mencioan las columnas )
INSERT INTO nombreTabla
VALUES
( DEFAULT, valor2, valor3, valor4 );
> Ejemplo práctico:
INSERT INTO productos_apple
VALUES
( DEFAULT, 'iPad', 499, 250 ); |
package com.joanjpx.inventory_service.controller;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.joanjpx.inventory_service.model.dtos.BaseResponse;
import com.joanjpx.inventory_service.model.dtos.OrderItemRequest;
import com.joanjpx.inventory_service.service.InventoryService;
import lombok.RequiredArgsConstructor;
@RestController
@RequestMapping("/api/inventory")
@RequiredArgsConstructor
public class InventoryController {
private final InventoryService inventoryService;
@GetMapping("/{sku}")
@ResponseStatus(code = HttpStatus.OK)
public boolean isInStock(@PathVariable("sku") String sku) {
return this.inventoryService.isInStock(sku);
}
@PostMapping("/in-stock")
@ResponseStatus(code = HttpStatus.OK)
public BaseResponse areInStock(@RequestBody List<OrderItemRequest> orderItems) {
return this.inventoryService.areInStock(orderItems);
}
} |
import React, { useContext, useEffect, useState } from "react";
import { Logo } from "../Logo/Logo";
import { ReactComponent as Vector } from "./Vector.svg";
import { Search } from "../Search/Search";
import "./style.css";
import IconBasket from "./IconBasket";
import { UserContext } from "../../context/userContext";
import { CardContext } from "../../context/cardContext";
import { Link, useNavigate } from "react-router-dom";
import { ReactComponent as Like } from "../Card/like.svg";
import { ReactComponent as Login } from "./login.svg";
import { AddProduct } from "../AddProduct/AddProduct";
import { BaseButton } from "../BaseButton/BaseButon";
import { Form } from "../Form/Form";
import { useForm } from "react-hook-form";
import { Modal } from "../Modal/Modal";
export const Header = ({ setShowModal, id, product }) => {
const { searchQuery, setSearchQuery, parentCounter, isAuthentificated } =
useContext(UserContext);
const [counter, setCounter] = useState(parentCounter);
const { favorites } = useContext(CardContext);
const [createModal, setCreateModal] = useState(false);
const navigate = useNavigate();
const handleLogout = () => {
localStorage.removeItem("token");
navigate("/login");
};
useEffect(() => {
if (parentCounter === 0) return;
setCounter((state) => state + 1);
return () => setCounter(parentCounter);
}, [parentCounter]);
return (
<div className="header" id="head">
<div className="container">
<div className="header__wrapper">
<div className="header__left">
<Logo />
<Search searchQuery={searchQuery} setSearchQuery={setSearchQuery} />
</div>
<div className="icons">
<Link to={"/favorites"} className="header__bubble-link">
<Like className="header__liked" />
{favorites.length !== 0 && (
<span className="header__bubble">{favorites.length}</span>
)}
</Link>
</div>
<IconBasket count={parentCounter} clickFunction={() => {}} />
<Link
to={"/profile "}
className="header__bubble-link"
onClick={() => setShowModal(true)}
>
<Vector className="header__liked" />
</Link>
{!isAuthentificated ? (
<Link
to={"/login"}
className="header__bubble-link"
onClick={() => setShowModal(true)}
>
<Login />
</Link>
) : (
<span onClick={handleLogout}> </span>
)}
<button
className="btn btn_type_primary "
color={"yellow"}
onClick={() => setCreateModal(true)}
>
Добавить продукт
</button>
{createModal && (
<Modal activeModal={AddProduct} setShowModal={setCreateModal}>
<AddProduct
id={id}
product={product}
setCreateModal={setCreateModal}
/>
</Modal>
)}
</div>
</div>
</div>
);
}; |
// https://leetcode.com/problems/distribute-coins-in-binary-tree
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// logic
// if you can count the number of coin moves across each edge
// and add this value for all edges
// then you get the answer
// now take a given edge
// will there be coin moves in both directions on this edge or only one ?
// You :
// in just one direction ,either top to bottom or bottom to top
// good
// we know how many coins are in the subtree in the beginning
// and how many there will be in the end
// every coin move across the edge changes the number of coins in the subtree by 1
// You sent
// correct
// so number of coins moving across an edge = difference between number of nodes and number of coins in subtree
// You sent
// yes makes sense
class Solution {
public:
int res;
pair <int, int> dfs(TreeNode* root){
if(!root){
return {0,0};
}
int n =1; int coin = root->val ;
auto [leftcount ,leftcoins ] = dfs(root->left);
res += abs(leftcount -leftcoins);
n+=leftcount;
coin+=leftcoins;
auto [rightcount ,rightcoins] = dfs(root->right);
res += abs(rightcount - rightcoins);
n+=rightcount;
coin +=rightcoins;
return {n,coin};
}
int distributeCoins(TreeNode* root) {
res =0;
dfs(root);
return res;
}
}; |
package hellojpa;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity
public class Member {//extends BaseEntity{
@Id @GeneratedValue
@Column(name = "MEMBER_ID")
private Long id;
@Column(name = "USERNAME")
private String userName;
@Embedded
private Address homeAddress;
@ElementCollection
@CollectionTable(name = "FAVORITE_FOOD",joinColumns = @JoinColumn(name = "MEMBER_ID"))
@Column(name = "FOOD_NAME")
private Set<String> favoriteFoods = new HashSet<>();
// @ElementCollection
// @CollectionTable(name = "ADDRESS",joinColumns = @JoinColumn(name = "MEMBER_ID"))
// private List<Address> addressHistory = new ArrayList<>();
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "MEMBER_ID")
private List<AddressEntity> addressHistory = new ArrayList<>();
public Set<String> getFavoriteFoods() {
return favoriteFoods;
}
public void setFavoriteFoods(Set<String> favoriteFoods) {
this.favoriteFoods = favoriteFoods;
}
//
// public List<Address> getAddressHistory() {
// return addressHistory;
// }
public List<AddressEntity> getAddressHistory() {
return addressHistory;
}
public void setAddressHistory(List<AddressEntity> addressHistory) {
this.addressHistory = addressHistory;
}
// public void setAddressHistory(List<Address> addressHistory) {
// this.addressHistory = addressHistory;
// }
// @Embedded
// private Address homeAddress;
// @Embedded
// @AttributeOverrides({
// @AttributeOverride(name = "city",
// column = @Column(name = "WORK_CITY")),
// @AttributeOverride(name = "street",
// column = @Column(name = "WORK_STREET")),
// @AttributeOverride(name = "zipcode",
// column = @Column(name = "WORK_ZIPCODE"))
// })
// private Address workAddress;
// @Column(name = "TEAM_ID")
// private Long teamId;
// @ManyToOne(fetch = FetchType.EAGER)
// @JoinColumn(name = "Team_ID")
// private Team team;
////
// @OneToOne
// @JoinColumn(name="LOCKER_ID")
// private Locker locker;
// public Member() {
// }
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
// public Period getWorkPeriod() {
// return workPeriod;
// }
// public void setWorkPeriod(Period workPeriod) {
// this.workPeriod = workPeriod;
// }
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
// public Team getTeam() {
// return team;
// }
//
// public void setTeam(Team team) {
// this.team = team;
// }
//
// public void changeTeam(Team team) {
// this.team = team;
// team.getMembers().add(this);
// }
//
// public Long getTeamId() {
// return teamId;
// }
//
// public void setTeamId(Long teamId) {
// this.teamId = teamId;
// }
} |
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const cookie_parser_1 = __importDefault(require("cookie-parser"));
const cors_1 = __importDefault(require("cors"));
const express_1 = __importDefault(require("express"));
const helmet_1 = __importDefault(require("helmet"));
const hpp_1 = __importDefault(require("hpp"));
const morgan_1 = __importDefault(require("morgan"));
const config_1 = __importDefault(require("./config"));
const globalErrorHandler_middleware_1 = __importDefault(require("./middleware/globalErrorHandler.middleware"));
const routes_1 = __importDefault(require("./routes"));
const sendResponse_util_1 = __importDefault(require("./utils/sendResponse.util"));
const app = (0, express_1.default)();
//global app middleware
app.use((0, helmet_1.default)());
app.use((0, cors_1.default)());
app.use((0, cookie_parser_1.default)());
app.use(express_1.default.json());
app.use(express_1.default.urlencoded({ extended: false }));
app.use((0, hpp_1.default)());
//development middleware
if (config_1.default.isDevelopment) {
app.use((0, morgan_1.default)("dev"));
}
//routes
app.use("/api/v1", routes_1.default);
// root
app.get("/", (req, res) => {
(0, sendResponse_util_1.default)(res, {
statusCode: 200,
success: true,
message: "Welcome to next door server",
});
});
// Not found catch
app.all("*", (req, res) => {
(0, sendResponse_util_1.default)(res, {
statusCode: 200,
success: false,
message: "Adress not found",
});
});
// error handling middleware
app.use(globalErrorHandler_middleware_1.default);
exports.default = app; |
package com.byrnx.dictionaryapp.feature_dictionary.data.remote.dto
import com.byrnx.dictionaryapp.feature_dictionary.data.local.entities.WordInfoEntity
import com.google.gson.annotations.SerializedName
data class WordInfoDto(
@SerializedName("license")
val license: LicenseDto?,
@SerializedName("meanings")
val meanings: List<MeaningDto>,
@SerializedName("phonetic")
val phonetic: String?,
@SerializedName("phonetics")
val phonetics: List<PhoneticDto?>? = emptyList(),
@SerializedName("sourceUrls")
val sourceUrls: List<String>,
@SerializedName("word")
val word: String
) {
fun toWordInfoEntity(): WordInfoEntity {
return WordInfoEntity(
license = license?.toLicense(),
meanings = meanings.map { it.toMeaning() },
phonetic = phonetic,
phonetics = phonetics?.map { it?.toPhonetic() },
sourceUrls = sourceUrls,
word = word
)
}
} |
class ModelNotification {
Payload? payload;
String? message;
String? errormessage;
String? type;
int? code;
ModelNotification({
this.payload,
this.message,
this.errormessage,
this.type,
this.code});
ModelNotification.fromJson(dynamic json) {
payload = json['payload'] != null ? Payload.fromJson(json['payload']) : null;
message = json['message'];
errormessage = json['errormessage'];
type = json['type'];
code = json['code'];
}
Map<String, dynamic> toJson() {
var map = <String, dynamic>{};
if (payload != null) {
map['payload'] = payload?.toJson();
}
map['message'] = message;
map['errormessage'] = errormessage;
map['type'] = type;
map['code'] = code;
return map;
}
}
class Payload {
List<NotificationsList>? notifications;
Payload({
this.notifications});
Payload.fromJson(dynamic json) {
if (json['notifications'] != null) {
notifications = [];
json['notifications'].forEach((v) {
notifications?.add(NotificationsList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
var map = <String, dynamic>{};
if (notifications != null) {
map['notifications'] = notifications?.map((v) => v.toJson()).toList();
}
return map;
}
}
class NotificationsList {
int? notificationId;
int? senderId;
int? receiverId;
String? notificationTitle;
String? notification;
int? notificationType;
int? seen;
int? status;
String? createdAt;
NotificationsList({
this.notificationId,
this.senderId,
this.receiverId,
this.notificationTitle,
this.notification,
this.notificationType,
this.seen,
this.status,
this.createdAt});
NotificationsList.fromJson(dynamic json) {
notificationId = json['notification_id'];
senderId = json['sender_id'];
receiverId = json['receiver_id'];
notificationTitle = json['notification_title'];
notification = json['notification'];
notificationType = json['notification_type'];
seen = json['seen'];
status = json['status'];
createdAt = json['created_at'];
}
Map<String, dynamic> toJson() {
var map = <String, dynamic>{};
map['notification_id'] = notificationId;
map['sender_id'] = senderId;
map['receiver_id'] = receiverId;
map['notification_title'] = notificationTitle;
map['notification'] = notification;
map['notification_type'] = notificationType;
map['seen'] = seen;
map['status'] = status;
map['created_at'] = createdAt;
return map;
}
} |
import datetime
from Pyro5.api import behavior, Daemon, expose, serve
@expose
@behavior(instance_mode='single')
class rental(object):
def __init__(self):
self.users = []
self.manufacturers = []
self.rental_cars = []
self.rented_cars = []
# task 1
def add_user(self, user_name, user_number):
user = {'name': user_name,
'number': user_number,
'car': None,
'history': []
}
if user in self.users or self.__get_user(user_name) != None:
return 0
else:
self.users.append(user)
return 1
# task 2
def return_users(self):
result = 'Users:\n'
if self.users:
for user in self.users:
result += 'name: ' + user['name'] + ', phone number: ' + user['number'] + '\n'
else:
result += 'None\n'
return result
# task 3
def add_manufacturer(self, manufacturer_name, manufacturer_country):
manufacturer = {'name': manufacturer_name,
'country': manufacturer_country
}
if manufacturer in self.manufacturers or self.__get_manufacturer(manufacturer_name) != None:
return 0
else:
self.manufacturers.append(manufacturer)
return 1
# task 4
def return_manufacturers(self):
result = 'Manufacturers:\n'
if self.manufacturers:
for manu in self.manufacturers:
result += 'name: ' + manu['name'] + ', country: ' + manu['country'] + '\n'
else:
result += 'None\n'
return result
# task 5
def add_rental_car(self, manufacturer_name, car_model):
car = {'manu': manufacturer_name,
'model': car_model,
'rented': None
}
self.rental_cars.append(car)
return car
# task 6
def return_cars_not_rented(self):
result = 'Cars available:\n'
if self.rental_cars:
for car in self.rental_cars:
result += 'manufacturer: ' + car['manu'] + ', model: ' + car['model'] + '\n'
else:
result += 'None\n'
return result
# task 7
def rent_car(self, user_name, car_model, year, month, day):
# check input
if year <= 0 or month <= 0 or day <= 0 or month > 12 or day > 31:
# print('Please check the input of date!')
return 0
user = self.__get_user(user_name)
start_time = datetime.date(year=year, month=month, day=day)
car = self.__get_rental_car(car_model)
if user == None:
# print('There is no such a user in database.')
return 0
elif car == None:
# print('There is no such a car in database.')
return 0
elif car['rented'] != None:
# print('Sorry, all the cars with this model has been rented out.')
return 0
else:
car['rented'] = start_time
user['car'] = car_model
self.rental_cars.remove(car)
self.rented_cars.append(car)
return 1
# task 8
def return_cars_rented(self):
result = 'Cars rented:\n'
if self.rented_cars:
for car in self.rented_cars:
result += 'manufacturer: ' + car['manu'] + ', model: ' + car['model'] + '\n'
else:
result += 'None\n'
return result
# task 9
def end_rental(self, user_name, car_model, year, month, day):
# check input
if year <= 0 or month <= 0 or day <= 0 or month > 12 or day > 31:
# print('Please check the input of date!')
return 0
user = self.__get_user(user_name)
end_time = datetime.date(year=year, month=month, day=day)
car = self.__get_rented_car(car_model)
start_time = car['rented']
if user == None:
# print('There is no such a user in database.')
return 0
elif car == None:
# print('There is no such a car in database.')
return 0
elif start_time == None:
# print('Sorry, all the cars with this model hasn't been rented out.')
return 0
elif user['car'] != car_model:
# print('Sorry, the car user returing is not the rented car ')
return 0
else:
car['rented'] = None
user['car'] = None
user['history'].append({'manu': car['manu'],
'model': car['model'],
'start': start_time,
'end': end_time
})
self.rented_cars.remove(car)
self.rental_cars.append(car)
return 1
# task 10
def delete_car(self, car_model):
car = self.__get_rental_car(car_model)
if not car:
return 0
elif car['rented'] != None:
return 0
else:
self.rental_cars.remove(car)
return 1
# task 11
def delete_user(self, user_name):
user = self.__get_user(user_name)
if len(user['history']) == 0:
self.users.remove(user)
return 1
else:
return 0
# task 12
def user_rental_date(self, user_name, start_year, start_month, start_day, end_year, end_month, end_day):
user = self.__get_user(user_name)
start_time = datetime.date(year=start_year, month=start_month, day=start_day)
end_time = datetime.date(year=end_year, month=end_month, day=end_day)
records = user['history']
history_result = 'Record of User ' + user_name + ':\n'
for record in records:
if record['start'] >= start_time and record['end'] <= end_time:
history_result += record['manu'] + ' - ' + record['model'] + ' from ' + str(record['start']) + ' to ' + str(record['end']) + '\n'
if history_result == 'Record of User ' + user_name + ':\n':
return history_result + 'None\n'
else:
return history_result
#############################################################################################
def __get_user(self, name):
for user in self.users:
if user['name'] == name:
return user
return None
def __get_rental_car(self, model):
for car in self.rental_cars:
if car['model'] == model:
return car
return None
def __get_manufacturer(self, name):
for manufacturer in self.manufacturers:
if manufacturer['name'] == name:
return manufacturer
return None
def __get_rented_car(self, model):
for car in self.rented_cars:
if car['model'] == model:
return car
return None
daemon = Daemon()
serve({rental: 'example.rental'}, daemon=daemon, use_ns=True)
#if __name__ == '__main__':
# main() |
package com.bupt.indoorpostion;
import android.animation.AnimatorInflater;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class IndoorLocationActivity extends Activity {
private int width;
private int height;
private float density;
private int d=20;
private ImageView indoorMap;
private ImageView myLocation;
private Button startButton;
private Button stopButton;
private TextView textView;
private ObjectAnimator animX;
private ObjectAnimator animY;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indoor_localization);
indoorMap = (ImageView) findViewById(R.id.map);
myLocation = (ImageView) findViewById(R.id.myLocation);
startButton = (Button) findViewById(R.id.start_buuton);
stopButton = (Button) findViewById(R.id.stop_button);
textView = (TextView) findViewById(R.id.showdetails);
width = getDeviceWidth(this);
height = getDeviceHeight(this);
density = getResources().getDisplayMetrics().density;
animX = ObjectAnimator.ofFloat(myLocation, "scaleX", 0.6f, 1f, 0.6f);
animX.setDuration(2000);
animX.setRepeatCount(Animation.INFINITE);
animX.setRepeatMode(Animation.REVERSE);
animY = ObjectAnimator.ofFloat(myLocation, "scaleY", 0.6f, 1f, 0.6f);
animY.setDuration(2000);
animY.setRepeatCount(Animation.INFINITE);
animY.setRepeatMode(Animation.REVERSE);
startButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(width + " " + height+" "+density+" "+indoorMap.getWidth()+" "+indoorMap.getHeight());
//textView.setText(indoorMap.getX() + " " + indoorMap.getY()+" "+density+" "+x + " " + y);
myLocation.setX((float) (indoorMap.getWidth()*Math.random()-d*density/2));
myLocation.setY((float) (indoorMap.getHeight()*Math.random()-d*density/2));
animX.start();
animY.start();
}
});
stopButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
animX.end();
animY.end();
}
});
}
/**
* 获取设备屏幕的宽
*
* @param context
* @return
*/
public static int getDeviceWidth(Activity context) {
Display display = context.getWindowManager().getDefaultDisplay();
Point p = new Point();
display.getSize(p);
return p.x;
}
/** 获取屏幕的高 */
public static int getDeviceHeight(Activity context) {
Display display = context.getWindowManager().getDefaultDisplay();
Point p = new Point();
display.getSize(p);
return p.y;
}
} |
import 'package:flutter/material.dart';
import 'detail_image.dart';
class ImageGridView extends StatelessWidget {
const ImageGridView({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(15.0),
child: GridView.count(
crossAxisCount: 2,
mainAxisSpacing: 20,
crossAxisSpacing: 20,
children: [
// ElevatedButton(
// onPressed: () {
// _showImageBottomSheet(context, 'assets/kupu.jepg');
// },
// style: ElevatedButton.styleFrom(
// padding: const EdgeInsets.all(2),
// ),
// child: Ink.image(
// image: const AssetImage('assets/kupu.jpeg'),
// fit: BoxFit.cover,
// ),
// ),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/oyn.jpg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
ElevatedButton(
onPressed: () {
_showImageBottomSheet(context, 'assets/kupu.jpeg');
},
style: ElevatedButton.styleFrom(
padding: const EdgeInsets.all(2),
),
child: Ink.image(
image: const AssetImage('assets/kupu.jpeg'),
fit: BoxFit.cover,
),
),
],
),
);
}
}
void _showImageBottomSheet(BuildContext context, String imagePath) {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return ShowImage(imagePath: imagePath);
},
);
}
class ShowImage extends StatelessWidget {
final String imagePath;
const ShowImage({super.key, required this.imagePath});
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
color: Color.fromRGBO(228, 255, 152, 1),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Image.asset(
imagePath,
height: 200,
width: 200,
fit: BoxFit.cover,
),
const SizedBox(height: 10),
const Text(
'Apakah Anda ingin melihatnya lebih detail ?',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 30),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
DetailImagePage(imagePath: imagePath),
),
);
},
style: ElevatedButton.styleFrom(
backgroundColor:const Color.fromARGB(255, 248, 185, 12),
),
child: const Text(
'yes',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
style: ElevatedButton.styleFrom(
backgroundColor: const Color.fromARGB(255, 248, 185, 12),
),
child: const Text(
'no',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
),
],
)
],
),
),
);
}
} |
/*
* Copyright (C) 2015, Google Inc. and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0 which is available at
* https://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package org.eclipse.jgit.transport;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
import static org.eclipse.jgit.lib.Constants.OBJ_COMMIT;
import static org.eclipse.jgit.lib.FileMode.TYPE_FILE;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheEditor;
import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.internal.JGitText;
import org.eclipse.jgit.lib.BatchRefUpdate;
import org.eclipse.jgit.lib.CommitBuilder;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectInserter;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.lib.ObjectReader;
import org.eclipse.jgit.lib.PersonIdent;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
import org.eclipse.jgit.treewalk.filter.PathFilter;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
/**
* Storage for recorded push certificates.
* <p>
* Push certificates are stored in a special ref {@code refs/meta/push-certs}.
* The filenames in the tree are ref names followed by the special suffix
* <code>@{cert}</code>, and the contents are the latest push cert affecting
* that ref. The special suffix allows storing certificates for both refs/foo
* and refs/foo/bar in case those both existed at some point.
*
* @since 4.1
*/
public class PushCertificateStore implements AutoCloseable {
/** Ref name storing push certificates. */
static final String REF_NAME =
Constants.R_REFS + "meta/push-certs"; //$NON-NLS-1$
private static class PendingCert {
PushCertificate cert;
PersonIdent ident;
Collection<ReceiveCommand> matching;
PendingCert(PushCertificate cert, PersonIdent ident,
Collection<ReceiveCommand> matching) {
this.cert = cert;
this.ident = ident;
this.matching = matching;
}
}
private final Repository db;
private final List<PendingCert> pending;
ObjectReader reader;
RevCommit commit;
/**
* Create a new store backed by the given repository.
*
* @param db
* the repository.
*/
public PushCertificateStore(Repository db) {
this.db = db;
pending = new ArrayList<>();
}
/**
* {@inheritDoc}
* <p>
* Close resources opened by this store.
* <p>
* If {@link #get(String)} was called, closes the cached object reader
* created by that method. Does not close the underlying repository.
*/
@Override
public void close() {
if (reader != null) {
reader.close();
reader = null;
commit = null;
}
}
/**
* Get latest push certificate associated with a ref.
* <p>
* Lazily opens {@code refs/meta/push-certs} and reads from the repository as
* necessary. The state is cached between calls to {@code get}; to reread the,
* call {@link #close()} first.
*
* @param refName
* the ref name to get the certificate for.
* @return last certificate affecting the ref, or null if no cert was recorded
* for the last update to this ref.
* @throws java.io.IOException
* if a problem occurred reading the repository.
*/
public PushCertificate get(String refName) throws IOException {
if (reader == null) {
load();
}
try (TreeWalk tw = newTreeWalk(refName)) {
return read(tw);
}
}
/**
* Iterate over all push certificates affecting a ref.
* <p>
* Only includes push certificates actually stored in the tree; see class
* Javadoc for conditions where this might not include all push certs ever
* seen for this ref.
* <p>
* The returned iterable may be iterated multiple times, and push certs will
* be re-read from the current state of the store on each call to {@link
* Iterable#iterator()}. However, method calls on the returned iterator may
* fail if {@code save} or {@code close} is called on the enclosing store
* during iteration.
*
* @param refName
* the ref name to get certificates for.
* @return iterable over certificates; must be fully iterated in order to
* close resources.
*/
public Iterable<PushCertificate> getAll(String refName) {
return () -> new Iterator<>() {
private final String path = pathName(refName);
private PushCertificate next;
private RevWalk rw;
{
try {
if (reader == null) {
load();
}
if (commit != null) {
rw = new RevWalk(reader);
rw.setTreeFilter(AndTreeFilter.create(
PathFilterGroup.create(Collections
.singleton(PathFilter.create(path))),
TreeFilter.ANY_DIFF));
rw.setRewriteParents(false);
rw.markStart(rw.parseCommit(commit));
} else {
rw = null;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean hasNext() {
try {
if (next == null) {
if (rw == null) {
return false;
}
try {
RevCommit c = rw.next();
if (c != null) {
try (TreeWalk tw = TreeWalk.forPath(
rw.getObjectReader(), path,
c.getTree())) {
next = read(tw);
}
} else {
next = null;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return next != null;
} finally {
if (next == null && rw != null) {
rw.close();
rw = null;
}
}
}
@Override
public PushCertificate next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
PushCertificate n = next;
next = null;
return n;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
void load() throws IOException {
close();
reader = db.newObjectReader();
Ref ref = db.getRefDatabase().exactRef(REF_NAME);
if (ref == null) {
// No ref, same as empty.
return;
}
try (RevWalk rw = new RevWalk(reader)) {
commit = rw.parseCommit(ref.getObjectId());
}
}
static PushCertificate read(TreeWalk tw) throws IOException {
if (tw == null || (tw.getRawMode(0) & TYPE_FILE) != TYPE_FILE) {
return null;
}
ObjectLoader loader =
tw.getObjectReader().open(tw.getObjectId(0), OBJ_BLOB);
try (InputStream in = loader.openStream();
Reader r = new BufferedReader(
new InputStreamReader(in, UTF_8))) {
return PushCertificateParser.fromReader(r);
}
}
/**
* Put a certificate to be saved to the store.
* <p>
* Writes the contents of this certificate for each ref mentioned. It is up
* to the caller to ensure this certificate accurately represents the state
* of the ref.
* <p>
* Pending certificates added to this method are not returned by
* {@link #get(String)} and {@link #getAll(String)} until after calling
* {@link #save()}.
*
* @param cert
* certificate to store.
* @param ident
* identity for the commit that stores this certificate. Pending
* certificates are sorted by identity timestamp during
* {@link #save()}.
*/
public void put(PushCertificate cert, PersonIdent ident) {
put(cert, ident, null);
}
/**
* Put a certificate to be saved to the store, matching a set of commands.
* <p>
* Like {@link #put(PushCertificate, PersonIdent)}, except a value is only
* stored for a push certificate if there is a corresponding command in the
* list that exactly matches the old/new values mentioned in the push
* certificate.
* <p>
* Pending certificates added to this method are not returned by
* {@link #get(String)} and {@link #getAll(String)} until after calling
* {@link #save()}.
*
* @param cert
* certificate to store.
* @param ident
* identity for the commit that stores this certificate. Pending
* certificates are sorted by identity timestamp during
* {@link #save()}.
* @param matching
* only store certs for the refs listed in this list whose values
* match the commands in the cert.
*/
public void put(PushCertificate cert, PersonIdent ident,
Collection<ReceiveCommand> matching) {
pending.add(new PendingCert(cert, ident, matching));
}
/**
* Save pending certificates to the store.
* <p>
* One commit is created per certificate added with
* {@link #put(PushCertificate, PersonIdent)}, in order of identity
* timestamps, and a single ref update is performed.
* <p>
* The pending list is cleared if and only the ref update fails, which
* allows for easy retries in case of lock failure.
*
* @return the result of attempting to update the ref.
* @throws java.io.IOException
* if there was an error reading from or writing to the
* repository.
*/
public RefUpdate.Result save() throws IOException {
ObjectId newId = write();
if (newId == null) {
return RefUpdate.Result.NO_CHANGE;
}
try (ObjectInserter inserter = db.newObjectInserter()) {
RefUpdate.Result result = updateRef(newId);
switch (result) {
case FAST_FORWARD:
case NEW:
case NO_CHANGE:
pending.clear();
break;
default:
break;
}
return result;
} finally {
close();
}
}
/**
* Save pending certificates to the store in an existing batch ref update.
* <p>
* One commit is created per certificate added with
* {@link #put(PushCertificate, PersonIdent)}, in order of identity
* timestamps, all commits are flushed, and a single command is added to the
* batch.
* <p>
* The cached ref value and pending list are <em>not</em> cleared. If the
* ref update succeeds, the caller is responsible for calling
* {@link #close()} and/or {@link #clear()}.
*
* @param batch
* update to save to.
* @return whether a command was added to the batch.
* @throws java.io.IOException
* if there was an error reading from or writing to the
* repository.
*/
public boolean save(BatchRefUpdate batch) throws IOException {
ObjectId newId = write();
if (newId == null || newId.equals(commit)) {
return false;
}
batch.addCommand(new ReceiveCommand(
commit != null ? commit : ObjectId.zeroId(), newId, REF_NAME));
return true;
}
/**
* Clear pending certificates added with {@link #put(PushCertificate,
* PersonIdent)}.
*/
public void clear() {
pending.clear();
}
private ObjectId write() throws IOException {
if (pending.isEmpty()) {
return null;
}
if (reader == null) {
load();
}
sortPending(pending);
ObjectId curr = commit;
DirCache dc = newDirCache();
try (ObjectInserter inserter = db.newObjectInserter()) {
for (PendingCert pc : pending) {
curr = saveCert(inserter, dc, pc, curr);
}
inserter.flush();
return curr;
}
}
private static void sortPending(List<PendingCert> pending) {
Collections.sort(pending, (PendingCert a, PendingCert b) -> Long.signum(
a.ident.getWhen().getTime() - b.ident.getWhen().getTime()));
}
private DirCache newDirCache() throws IOException {
if (commit != null) {
return DirCache.read(reader, commit.getTree());
}
return DirCache.newInCore();
}
private ObjectId saveCert(ObjectInserter inserter, DirCache dc,
PendingCert pc, ObjectId curr) throws IOException {
Map<String, ReceiveCommand> byRef;
if (pc.matching != null) {
byRef = new HashMap<>();
for (ReceiveCommand cmd : pc.matching) {
if (byRef.put(cmd.getRefName(), cmd) != null) {
throw new IllegalStateException();
}
}
} else {
byRef = null;
}
DirCacheEditor editor = dc.editor();
String certText = pc.cert.toText() + pc.cert.getSignature();
final ObjectId certId = inserter.insert(OBJ_BLOB, certText.getBytes(UTF_8));
boolean any = false;
for (ReceiveCommand cmd : pc.cert.getCommands()) {
if (byRef != null && !commandsEqual(cmd, byRef.get(cmd.getRefName()))) {
continue;
}
any = true;
editor.add(new PathEdit(pathName(cmd.getRefName())) {
@Override
public void apply(DirCacheEntry ent) {
ent.setFileMode(FileMode.REGULAR_FILE);
ent.setObjectId(certId);
}
});
}
if (!any) {
return curr;
}
editor.finish();
CommitBuilder cb = new CommitBuilder();
cb.setAuthor(pc.ident);
cb.setCommitter(pc.ident);
cb.setTreeId(dc.writeTree(inserter));
if (curr != null) {
cb.setParentId(curr);
} else {
cb.setParentIds(Collections.<ObjectId> emptyList());
}
cb.setMessage(buildMessage(pc.cert));
return inserter.insert(OBJ_COMMIT, cb.build());
}
private static boolean commandsEqual(ReceiveCommand c1, ReceiveCommand c2) {
if (c1 == null || c2 == null) {
return c1 == c2;
}
return c1.getRefName().equals(c2.getRefName())
&& c1.getOldId().equals(c2.getOldId())
&& c1.getNewId().equals(c2.getNewId());
}
private RefUpdate.Result updateRef(ObjectId newId) throws IOException {
RefUpdate ru = db.updateRef(REF_NAME);
ru.setExpectedOldObjectId(commit != null ? commit : ObjectId.zeroId());
ru.setNewObjectId(newId);
ru.setRefLogIdent(pending.get(pending.size() - 1).ident);
ru.setRefLogMessage(JGitText.get().storePushCertReflog, false);
try (RevWalk rw = new RevWalk(reader)) {
return ru.update(rw);
}
}
private TreeWalk newTreeWalk(String refName) throws IOException {
if (commit == null) {
return null;
}
return TreeWalk.forPath(reader, pathName(refName), commit.getTree());
}
static String pathName(String refName) {
return refName + "@{cert}"; //$NON-NLS-1$
}
private static String buildMessage(PushCertificate cert) {
StringBuilder sb = new StringBuilder();
if (cert.getCommands().size() == 1) {
sb.append(MessageFormat.format(
JGitText.get().storePushCertOneRef,
cert.getCommands().get(0).getRefName()));
} else {
sb.append(MessageFormat.format(
JGitText.get().storePushCertMultipleRefs,
Integer.valueOf(cert.getCommands().size())));
}
return sb.append('\n').toString();
}
} |
# https://www.interviewbit.com/problems/repeat-and-missing-number-array/
# https://www.codingninjas.com/codestudio/problems/873366
# https://youtu.be/5nMGY4VUoRY
'''
[1, 2, 3, 4, 5, 6]
arr = [1, 2, 3, 4, 6, 6]
lets 5 = x; 6 = y
1 + 2 + 3 + 4 + x + y = s --eq(1)
1 + 2 + 3 + 4 + x + x = s1 --eq(2)
s = n(n+1)/2
s1 = sum(arr)
eq(2) - eq(1)
x - y = s - s1 --eq(3)
1^2 + 2^2 + 3^2 + 4^2 + x^2 + y^2 = p --eq(4)
1^2 + 2^2 + 3^2 + 4^2 + x^2 + x^2 = p1 --eq(5)
p = n(n+1)(2n+1)/6
ep(5) - ep(4)
x^2 - y^2 = p - p1
(x+y)(x-y) = p - p1 --eq(6)
use eq(3) in eq(6)
x + y = (p - p1) / (s - s1) --eq(7)
eq(3) + eq(7)
2x = s - s1 + (p - p1) / (s - s1)
x = (s - s1 + (p - p1) / (s - s1)) // 2
'''
class Solution:
def repeatedNumber(self, arr):
n = len(arr)
s = n * (n + 1) // 2
s1 = sum(arr)
p = n * (n+1) * (2*n + 1) // 6
# fining x^2 - y^2
for i in arr:
p -= i ** 2
# now current p = y^2 - x^2
diff = -p # = p1 - p = x^2 - y^2
x = (s1 - s + diff // (s1 - s)) // 2 # repeating number
y = s - s1 + x # missing number
return (x, y)
# Time: O(n)
# Space: O(1) |
//References
let timeLeft = document.querySelector(".time-left");
let quizContainer = document.getElementById("container");
let nextBtn = document.getElementById("next-button");
let countOfQuestion = document.querySelector(".number-of-question");
let displayContainer = document.getElementById("display-container");
let scoreContainer = document.querySelector(".score-container");
let restart = document.getElementById("restart");
let userScore = document.getElementById("user-score");
let startScreen = document.querySelector(".start-screen");
let startButton = document.getElementById("start-button");
let questionCount;
let scoreCount = 0;
let count = 11;
let countdown;
//Questions and Options array
const quizArray = [
{
id: "0",
question: "AWS allows users to manage their resources using a web based user interface. What is the name of this interface?",
options: ["AWS CLI", "AWS API", "AWS Management Console", "AWS SDk"],
correct: "AWS Management Console",
},
{
id: "1",
question: "Which of the following is an example of horizontal scaling in the AWS Cloud?",
options: ["Replacing an existing EC2 instance with a larger, more powerful one.", "Increasing the compute capacity of a single EC2 instance to address the growing demands of an application.", "Adding more RAM capacity to an EC2 instance.", "Adding more EC2 instances of the same size to handle an increase in traffic."],
correct: "Adding more EC2 instances of the same size to handle an increase in traffic.",
},
{
id: "2",
question: "You have noticed that several critical Amazon EC2 instances have been terminated. Which of the following AWS services would help you determine who took this action?",
options: ["Amazon Inspector.", "AWS CloudTrail.", "AWS Trusted Advisor.", "EC2 Instance Usage Report."],
correct: "AWS CloudTrail.",
},
{
id: "3",
question: "Which statement is true regarding the AWS Shared Responsibility Model?",
options: ["Responsibilities vary depending on the services used.", "Security of the IaaS services is the responsibility of AWS.", "Patching the guest OS is always the responsibility of AWS.", "Security of the managed services is the responsibility of the customer."],
correct: "Responsibilities vary depending on the services used.",
},
{
id: "4",
question: "You have set up consolidated billing for several AWS accounts. One of the accounts has purchased a number of reserved instances for 3 years. Which of the following is true regarding this scenario?",
options: ["The Reserved Instance discounts can only be shared with the master account.", "All accounts can receive the hourly cost benefit of the Reserved Instances.", "The purchased instances will have better performance than On-demand instances.", "There are no cost benefits from using consolidated billing; It is for informational purposes only."],
correct: "All accounts can receive the hourly cost benefit of the Reserved Instances.",
},
{
id: "5",
question: "A company has developed an eCommerce web application in AWS. What should they do to ensure that the application has the highest level of availability?",
options: ["Deploy the application across multiple Availability Zones and Edge locations.", "Deploy the application across multiple Availability Zones and subnets.", "Deploy the application across multiple Regions and Availability Zones.", "Deploy the application across multiple VPC’s and subnets."],
correct: "Deploy the application across multiple Regions and Availability Zones.",
}, {
id: "6",
question: "A company has an AWS Enterprise Support plan. They want quick and efficient guidance with their billing and account inquiries. Which of the following should the company use?",
options: ["AWS Health Dashboard.", "AWS Support Concierge.", "AWS Customer Service.", "AWS Operations Support."],
correct: "AWS Support Concierge.",
},
{
id: "7",
question: "A Japanese company hosts their applications on Amazon EC2 instances in the Tokyo Region. The company has opened new branches in the United States, and the US users are complaining of high latency. What can the company do to reduce latency for the users in the US while minimizing costs?",
options: ["Applying the Amazon Connect latency-based routing policy.", "Registering a new US domain name to serve the users in the US.", "Building a new data center in the US and implementing a hybrid model.", "Deploying new Amazon EC2 instances in a Region located in the US."],
correct: "Deploying new Amazon EC2 instances in a Region located in the US.",
},
{
id: "8",
question: "An organization has a large number of technical employees who operate their AWS Cloud infrastructure. What does AWS provide to help organize them into teams and then assign the appropriate permissions for each team?",
options: ["IAM roles.", "IAM users.", "IAM user groups.", "AWS Organizations."],
correct: "IAM user groups.",
},
{
id: "9",
question: "A company has decided to migrate its Oracle database to AWS. Which AWS service can help achieve this without negatively impacting the functionality of the source database?",
options: ["AWS OpsWorks.", "AWS Database Migration Service.", "AWS Server Migration Service.", "AWS Application Discovery Service."],
correct: "AWS Database Migration Service.",
},
];
//Restart Quiz
restart.addEventListener("click", () => {
initial();
displayContainer.classList.remove("hide");
scoreContainer.classList.add("hide");
});
//Next Button
nextBtn.addEventListener(
"click",
(displayNext = () => {
//increment questionCount
questionCount += 1;
//if last question
if (questionCount == quizArray.length) {
//hide question container and display score
displayContainer.classList.add("hide");
scoreContainer.classList.remove("hide");
//user score
userScore.innerHTML =
"Your score is " + scoreCount + " out of " + questionCount;
} else {
//display questionCount
countOfQuestion.innerHTML =
questionCount + 1 + " of " + quizArray.length + " Question";
//display quiz
quizDisplay(questionCount);
count = 46;
clearInterval(countdown);
timerDisplay();
}
})
);
//Timer
const timerDisplay = () => {
countdown = setInterval(() => {
count--;
timeLeft.innerHTML = `${count}s`;
if (count == 0) {
clearInterval(countdown);
displayNext();
}
}, 1000);
};
//Display quiz
const quizDisplay = (questionCount) => {
let quizCards = document.querySelectorAll(".container-mid");
//Hide other cards
quizCards.forEach((card) => {
card.classList.add("hide");
});
//display current question card
quizCards[questionCount].classList.remove("hide");
};
//Quiz Creation
function quizCreator() {
//randomly sort questions
quizArray.sort(() => Math.random() - 0.5);
//generate quiz
for (let i of quizArray) {
//randomly sort options
i.options.sort(() => Math.random() - 0.5);
//quiz card creation
let div = document.createElement("div");
div.classList.add("container-mid", "hide");
//question number
countOfQuestion.innerHTML = 1 + " of " + quizArray.length + " Question";
//question
let question_DIV = document.createElement("p");
question_DIV.classList.add("question");
question_DIV.innerHTML = i.question;
div.appendChild(question_DIV);
//options
div.innerHTML += `
<button class="option-div" onclick="checker(this)">${i.options[0]}</button>
<button class="option-div" onclick="checker(this)">${i.options[1]}</button>
<button class="option-div" onclick="checker(this)">${i.options[2]}</button>
<button class="option-div" onclick="checker(this)">${i.options[3]}</button>
`;
quizContainer.appendChild(div);
}
}
//Checker Function to check if option is correct or not
function checker(userOption) {
let userSolution = userOption.innerText;
let question =
document.getElementsByClassName("container-mid")[questionCount];
let options = question.querySelectorAll(".option-div");
//if user clicked answer == correct option stored in object
if (userSolution === quizArray[questionCount].correct) {
userOption.classList.add("correct");
scoreCount++;
} else {
userOption.classList.add("incorrect");
//For marking the correct option
options.forEach((element) => {
if (element.innerText == quizArray[questionCount].correct) {
element.classList.add("correct");
}
});
}
//clear interval(stop timer)
clearInterval(countdown);
//disable all options
options.forEach((element) => {
element.disabled = true;
});
}
//initial setup
function initial() {
quizContainer.innerHTML = "";
questionCount = 0;
scoreCount = 0;
count = 46;
clearInterval(countdown);
timerDisplay();
quizCreator();
quizDisplay(questionCount);
}
//when user click on start button
startButton.addEventListener("click", () => {
startScreen.classList.add("hide");
displayContainer.classList.remove("hide");
initial();
});
//hide quiz and display start screen
window.onload = () => {
startScreen.classList.remove("hide");
displayContainer.classList.add("hide");
}; |
import React from 'react';
import PropTypes from 'prop-types';
import { Box, Divider, Typography } from '@material-ui/core';
import { Heading } from './styledComponents';
const headingVariant = (level) => {
if (level === 3) {
return 'sm';
}
if (level === 2) {
return 'md';
}
return 'lg';
};
const contentBox = (children, level, heading, headingType, showDivider) => {
return (
<>
<Box mt={level === 1 ? 7 : 3} mb={7}>
{heading && (
<Heading headingType={headingType} variant={headingVariant(level)}>
{heading}
</Heading>
)}
<Typography variant="body1">
{React.Children.map(children, (child) => {
if (child.type?.name === 'Content') {
return contentBox(
child.props.children,
child.props.level,
child.props.heading,
child.props.showDivider,
);
}
return child;
})}
</Typography>
</Box>
{(level === 1 || showDivider) && <Divider variant="middle" />}
</>
);
};
const Content = ({ heading, level, showDivider, children }) => {
return contentBox(children, level, heading, showDivider);
};
Content.propTypes = {
heading: PropTypes.string.isRequired,
level: PropTypes.number,
showDivider: PropTypes.bool,
children: PropTypes.node,
};
Content.defaultProps = {
level: 1,
showDivider: false,
children: undefined,
};
export default Content; |
# Optimized bubble sort
#!/c/Users/ADMIN/AppData/Local/Microsoft/WindowsApps/python3
# the first line is the location of python3 executable
# use "which python3" to find location of binaries.
# for linux its: usr/bin/python3
# for windows its: /c/Users/ADMIN/AppData/Local/Microsoft/WindowsApps/python3
# then use chmod 755 to make it executable and
# then run this file with ./bubbleSortTwo.py
def bubbleSort(lst):
size = len(lst)
for i in range(size):
swap = False
for j in range(size-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
swap = True
if swap is False:
break
if '__main__' == __name__:
from sys import argv, exit
from random import randint
from time import perf_counter
if len(argv) <= 1:
print("pass size")
exit(1)
size = int(argv[1])
lst = [randint(1, size * 10) for _ in range(size)]
start = perf_counter()
print("List before sorting:", lst)
bubbleSort(lst)
print("List after sorting:", lst)
end = perf_counter()
print("Time elapsed: ", round(end - start, 6))
bubbleSort(lst)
print("Sorted again List:", lst)
end2 = perf_counter()
print("Time elapsed for sorting first: ", round(end - start, 6))
print("Time elapsed for sorting again:", round(end2 - end, 6))
# python3 RandomListBubble4.py 5
# List before sorting: [14, 47, 35, 21, 11]
# List after sorting: [11, 14, 21, 35, 47]
# Time elapsed: 2.1e-05
# Sorted again List: [11, 14, 21, 35, 47]
# Time elapsed for sorting first: 2.1e-05
# Time elapsed for sorting again: 1.5e-05 |
<?php
namespace Controller;
use Model\usuarioModel;
require_once("helpers/helpers.php");
class UsuarioController
{
public function login()
{
if (!empty($_POST['nombre']) && !empty($_POST['pass'])) { //si los campos no estan vacios
$nombre = strClean($_POST['nombre']); //limpiamos los datos de caracteres especiales
$pass = strClean($_POST['pass']); //limpiamos los datos de caracteres especiales
$datos = array(
'nombre' => $nombre, //guardamos los datos en un array
'pass' => $pass //contrasenia es el name del input
);
$respuesta = UsuarioModel::login($datos);
$resultado = password_verify($pass, $respuesta['contrasena']); //verificamos que la contrasenia sea correcta
if ($resultado) { //si existe el id_usuario en la base de datos
session_start();
$_SESSION['id_usuario'] = $respuesta['id_usuario'];
$_SESSION['nombre'] = $respuesta['nombre'];
$_SESSION['apellido'] = $respuesta['apellido'];
$_SESSION['user'] = $respuesta['usuario'];
$_SESSION['rolUsuario'] = $respuesta['rol'];
header("location:index.php?action=inicio&id={$respuesta['id_usuario']}"); //redireccionamos a la pagina inicio}");
} else {
return "ERROR"; //redireccionamos a la pagina login
}
}
}
public function crarUsuarioAlumno()
{
if (!empty($_POST['nombre']) and !empty($_POST['apellido']) and !empty($_POST['nombreUsuario']) and !empty($_POST['pass_1'])) {
$nombre = strClean($_POST['nombre']); //limpiamos los datos de caracteres especiales
$apellido = strClean($_POST['apellido']);
$nombreUsuario = strClean($_POST['nombreUsuario']);
$pass_1 = ($_POST['pass_1']);
$pass_1 = password_hash($pass_1, PASSWORD_ARGON2ID); //encriptamos la contrasenia
$rol = "alumno";
$datos = array(
'nombre' => $nombre,
'apellido' => $apellido,
'nombreUsuario' => $nombreUsuario,
'pass' => $pass_1,
'rol' => $rol
);
$respuesta = UsuarioModel::guardarUsuarioAlumno($datos);
if ($respuesta) {
echo "Usuario creado correctamente";
#header("location:index.php?action=login");
} else {
echo "ERROR";
}
}
}
public function logout()
{
session_destroy();
header("location:index.php?action=login");
}
} |
// IMPORTING REACT & NEXT STUFF
import * as React from 'react';
import { Link } from 'react-scroll';
import NavList from './NavList';
// IMPORTING MATERIAL STUFF
import Box from '@mui/material/Box';
import Drawer from '@mui/material/Drawer';
import Button from '@mui/material/Button';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import WidgetsOutlinedIcon from '@mui/icons-material/WidgetsOutlined';
import CottageOutlinedIcon from '@mui/icons-material/CottageOutlined';
import AcUnitOutlinedIcon from '@mui/icons-material/AcUnitOutlined';
import MonetizationOnOutlinedIcon from '@mui/icons-material/MonetizationOnOutlined';
import PeopleAltOutlinedIcon from '@mui/icons-material/PeopleAltOutlined';
// STYLES FILES
import classes from './MobileMenu.module.scss'
const MobileMenu = () => {
const [state, setState] = React.useState({
right: false
});
const toggleDrawer = (anchor, open) => (event) => {
if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
return;
}
setState({ ...state, [anchor]: open });
};
const list = (anchor) => (
<Box
sx={{ width: anchor === 'top' || anchor === 'bottom' ? 'auto' : 250 }}
role="presentation"
onClick={toggleDrawer(anchor, false)}
onKeyDown={toggleDrawer(anchor, false)}
>
<List className={classes.mobNavList}>
{NavList.map(item => (
<ListItem key={item.title}>
<ListItemIcon>
{item.title === 'Home' && <CottageOutlinedIcon />}
{item.title === 'Features' && <AcUnitOutlinedIcon />}
{item.title === 'Pricing' && <MonetizationOnOutlinedIcon />}
{item.title === 'Testimonial' && <PeopleAltOutlinedIcon />}
</ListItemIcon>
<Link
onClick={toggleDrawer(anchor, false)}
to={item.path}
activeClass={classes.active}
smooth={true}
duration={500}
spy={true}>
{item.title}
</Link>
</ListItem>
))}
</List>
</Box>
);
return (
<div>
<>
<Button onClick={toggleDrawer('right', true)}><WidgetsOutlinedIcon
sx={{color:'#273c75'}} /></Button>
<Drawer
anchor={'right'}
open={state['right']}
onClose={toggleDrawer('right', false)}
>
{list('right')}
</Drawer>
</>
</div>
);
}
export default MobileMenu; |
<?php
namespace app\models;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\BlockText31;
/**
* BlockText31Search represents the model behind the search form of `app\models\BlockText31`.
*/
class BlockText31Search extends BlockText31
{
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['id', 'block_margin_top', 'block_margin_bottom'], 'integer'],
[['main_title', 'second_title_1', 'second_title_2', 'second_title_3', 'text1', 'text2', 'text3', 'main_title_color', 'second_title_color', 'text_color'], 'safe'],
];
}
/**
* {@inheritdoc}
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = BlockText31::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'block_margin_top' => $this->block_margin_top,
'block_margin_bottom' => $this->block_margin_bottom,
]);
$query->andFilterWhere(['like', 'main_title', $this->main_title])
->andFilterWhere(['like', 'second_title_1', $this->second_title_1])
->andFilterWhere(['like', 'second_title_2', $this->second_title_2])
->andFilterWhere(['like', 'second_title_3', $this->second_title_3])
->andFilterWhere(['like', 'text1', $this->text1])
->andFilterWhere(['like', 'text2', $this->text2])
->andFilterWhere(['like', 'text3', $this->text3])
->andFilterWhere(['like', 'main_title_color', $this->main_title_color])
->andFilterWhere(['like', 'second_title_color', $this->second_title_color])
->andFilterWhere(['like', 'text_color', $this->text_color]);
return $dataProvider;
}
} |
library(tidyverse)
library(lubridate)
setwd("C:/Users/nicolas_vanermen/Desktop/DATA INVOER/2023/UW DATA/Belgica 2023 21 25")
Belgica_2023 <- read.csv("vanermen_2023-21_2023-25.csv")
str(Belgica_2023)
Belgica_2023[,c(2:30)] <- sapply(Belgica_2023[,c(2:30)], as.numeric)
str(Belgica_2023)
#Select UW columns
as.data.frame(names(Belgica_2023))
#Ter info: voorheen gebruikten we True.heading..deg. ipv Seapath.true.heading..deg.
Belgica_2023$AirHumidity <- NA
Belgica_2023 <- Belgica_2023[,c("PHENOMENON_TIME_START..UTC0.","latitude", "longitude",
"Seapath.true.heading..deg.", "Seapath.groundspeed..kn.",
"Air.temperature..degC.","Air.pressure..hPa.","AirHumidity",
"True.Wind.direction..deg.", "True.Wind.speed..m.s.",
"Depth.from.surface..m.","Salinity..PSU.",
"Temperature.SBE38..degC.","CHL.Eco.triplet..ug.l.")]
#Rename columns
colnames(Belgica_2023) <- c("DateTime","Latitude","Longitude",
"Heading","SOG",
"AirTemperature","AirPressure","AirHumidity",
"WindDirection","WindSpeed",
"WaterDepth","WaterSalinity",
"WaterTemperature","ChlA")
#checks
summary(Belgica_2023)
for(i in colnames(Belgica_2023[,c(4:7,9:14)]))
{
print(ggplot(Belgica_2023, aes(get(i))) + geom_histogram() + labs(x=paste(i)))
}
#clean
Belgica_2023$WaterDepth <- -Belgica_2023$WaterDepth
Belgica_2023$WindSpeed <- ifelse(Belgica_2023$WindSpeed==0, NA, Belgica_2023$WindSpeed)
ggplot(Belgica_2023, aes(WaterDepth)) + geom_histogram() + labs(x="WaterDepth")
ggplot(Belgica_2023, aes(WindSpeed)) + geom_histogram() + labs(x="WindSpeed")
# ggplot(Belgica_2023, aes(Latitude, Longitude)) + geom_point()
write.csv(Belgica_2023,"Belgica_2023_21_25.csv") |
Event
when something hapend or hapending [creating,created, retrived,updating,updated,deleting,deleted] from or with database,
then create a event....
________________________________________
php artisan make:event EventName
for event , should use it in the related Model.. like User Model...
User.php
protected $dispatchesEvent = [ //[default property]
'created' => EventName::class // Event = Created => called to the Event Class
];
//[we are firing event by this in the Model,, but we can also firing event in the controller.. for this event healper is aviable,,,like.. event(UserCreateEvent::class);]
in the EventName.php file.........
________________________
use App\Model\User;
public $user;
public function __constant(User $user)
{
$this->user = $user;
}
broadcastOn = have to make array blank
----_____________________-------_______________
Now have to make a listener
php artisan make:listener UserCreatedListener //[Lintener]
Now have to bind event and listener in the Provider folder -> EventServiceProvider.php
this is Default
protected $listen = [
'App\Events\Event' => [
'App\Listeners\EventListener',
],
];
all of the event or listener have to define there as array, like that's..........
protected $listen = [ //['App\Events\Event' = Event. for [one event] or aganist of this event more [up to one/two] listener need to applied, so listener used as array]
'UserCreated::class' => [
UserCreatedListener::class, //['App\Listeners\EventListener = Listener.. use as array, coz here we use more more against of one event]
],
];
in the UserCreatedListener.php file
-----------------------
Class UserCreatedListener
public function handle($event)
{
$email = $event->user->email; //[we get inserted email address. now we can do every things...]
}
}
___________________________________________________________________________________________________________________
We can send a email by using event and listener ... so we can use same ...
----------------________________------------------- Email template or View
php artisan make:mail SendVerification
ant other configuration in .env file as my other Mail file .....
UserCreatedListener.php
------------------------
public function handle($event)
{
$email = $event->user->email; //[we get inserted email address. now we can do every things...]
Mail::to($email)->send(new SendVerification($event->user));
}
now in the SendVerificatoin.php file
------------------------------------
public $mess;
public $sub;
public function __construct($subject,$message)
{
$this->sub = $subject;
$this->mess = $message;
}
public function build()
{
$e_subject = $this->sub;
$e_message = $this->mess;
return $this->view('admin.pages.mail.sendmail',compact("e_message"))->subject($e_subject);
}
__________________________________________________________________________________________________________
Route::get('/verify/{token}','AuthController@verifyEmail');
in the controller....
public function verifyEmail($token)
{
$user = User::where('verification_token',trim($token))->first();
if($user == "")
{
session()->flash();
redirect()->route(home);
}
$user->update(['verify'=>1,'verification_token'='']);
redirect()->...... Or
auth()->login($user); //[login complete.. ]
now can redirect here....
}
----_______________________________------
config folder -- queue.php file....
//'default' => env('QUEUE_DRIVER', 'sync'),
'default' => env('QUEUE_DRIVER', 'database'), //here used database
in the .env file..........
QUEUE_DRIVER=database
then......
php artisan queue:table
php artisan migrate
in the UserCreatedListener.php file
-----------------------
Class UserCreatedListener implements ShouldQueue
public function handle($event)
{
$email = $event->user->email; //[we get inserted email address. now we can do every things...]
}
}
then.....
php artisan queue:work
corn |
from django.shortcuts import render, redirect
from .forms import UserRegistrationForm, UserLoginForm
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import login, authenticate, logout
def user_register(request):
if request.method == 'POST':
form = UserRegistrationForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = User.objects.create_user(cd['username'], cd['email'], cd['password'])
user.first_name = cd['first_name']
user.last_name = cd['last_name']
user.save()
messages.success(request, 'user registered successfully', 'success')
return redirect('home')
else:
form = UserRegistrationForm()
return render(request, 'register.html', {'form':form})
def user_login(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
user = authenticate(request, username=cd['username'], password=cd['password'])
if user is not None:
login(request, user)
messages.success(request, 'logged in successfully', 'success')
return redirect('home')
else:
messages.error(request, 'username or password is wrong', 'danger')
else:
form = UserLoginForm()
return render(request, 'login.html', {'form':form})
def user_logout(request):
logout(request)
messages.success(request, 'logged out successfully', 'success')
return redirect('home') |
we discuss [[Plasma, Magnetohydrodynamics (MHD)]].
## Self-consistent plasma description
1. we can find the position and velocities of every particle in a plasma from Newton's 2nd law, i.e. given $F_i \implies r_i, v_i\quad \forall i$ due to $$m_i \partial_t^2 r_i = F_i = q_i \left [ E(r_i, t) + v_i\times B(r_i) \right ]$$
2. from this, we get the charge and current density, i.e. $r_i, v_i \implies q_i, j$ as
$$\begin{align}
q &= \sum_i q_i \delta (r - r_i)\\
j &= \sum_i q_i v_i \delta(r-r_i)
\end{align}$$
3. $q,j\implies B,E$ due to the [[Maxwell equations]] $$\begin{align}
\nabla\cdot E &= \frac{\rho}{\epsilon_0}, &&\nabla\times E=-\partial_t B, \\
\nabla\cdot B &= 0, &&\nabla\times B =\mu_0 \left ( j + \epsilon_0 \partial_t E \right ) .
\end{align}$$
4. and $B,E \implies F_i$ as $$F_i = q_i \left [ E(r_i,t) + v_i \times B(r_i,t) \right ]$$ from which one can start at 1. again to obtain the particle positions and velocities.
This model is consistent, but not practical for large numbers of particles.
Better: statistical approach.
## Distribution functions
We use distribution functions (see [2]) in 6D phase space (3 positions, 3 velocities).
Interesting quantities:
$$\begin{align}
N_S &= \int dr \int dv f_S(r,v,t) &&\quad \text{ ... number of particles of type "S"}\\
n_S(r,t) &= \int dv f_S(r,v,t) &&\quad \text{ ... number density in [1/volume]}\\
u_S &= \frac{1}{n_S}\int dv v f_S(r,v,t)&&\quad \text{ ... average velocity}
\end{align}$$
## Examples of distribution functions
Maxwell-Boltzmann distribution function
$$\begin{align}
&F_0(\vec{v})=n_0\left(\frac{1}{2 \pi v_{t h}^2}\right)^{\frac{3}{2}} \exp \left(-\frac{v^2}{2 v_{t h}^2}\right)=A \exp(-B v^2) \quad\text{...Gaussian type}\\
\text{in 1D: }\quad &F_0(v)=n_0\left(\frac{1}{2 \pi v_{t h}^2}\right)^{\frac{1}{2}} \exp \left(-\frac{v^2}{2 v_{t h}^2}\right)
\end{align}$$
Mono-energetic beam in 1D
$$
F_0(v)=n_0 \delta\left(v-v_0\right)
$$
Two counter streaming beams in 1D
$$
F_0(v)=\frac{n_0}{2}\left[\delta\left(v-v_0\right)+\delta\left(v+v_0\right)\right]
$$
We want to find the time evolution of the distribution function:
## Conservation of particle number in phase space
If there are no sources nor sinks of particles particles are conserved in 6D phase space. Therefore we have a [[Conservation law, transport equation]]:
$$\frac{\partial f_S}{\partial t} =-\nabla_{6 D} \cdot\left(\vec{u} f_S\right)$$
Together with the "6D-nabla operator" and the "6D-velocity" (time derivative of state vector):
$$\begin{align}
\nabla_{6 D} &=\left(\partial x, \partial y, \partial z, \partial v_x, \partial v_y, \partial v_z\right)=\left(\partial \vec{r}, \partial \vec{v}\right) \\
\vec{u} &=\left(\frac{\mathrm{d} \vec{r}}{\mathrm{~d} t}, \frac{\mathrm{d} \vec{v}}{\mathrm{~d} t}\right)=\left(\vec{v}, \frac{\vec{F}}{m_S}\right)=\left(\vec{v}, \frac{\vec{F}^{l}+\vec{F}^{s}}{m_S}\right)
\end{align}$$
we get
$$ \frac{\partial f_S}{\partial t}=-\frac{\partial}{\partial \vec{r}} \cdot\left(\vec{v} f_S\right)-\frac{\partial}{\partial \vec{v}} \cdot\left[\left(\frac{\vec{F}^{l}+\vec{F}^{s}}{m_S}\right) f_S\right]
$$
(l ... long range, s ... short range)
## The Boltzmann equation
... basically a reformulation of the conservation law from before.
Observations:
- $\vec{v}$ is independent of $\vec{r}, \frac{\partial}{\partial \vec{r}} \cdot\left(\vec{v} f_S\right)=\vec{v} \cdot \frac{\partial f_S}{\partial \vec{r}}$
- $\vec{F}^{l}=q_S\left(\vec{E}^{l}+\vec{v} \times \vec{B}^{l}\right)$, where $E^l$ independent of $\vec{v}$ and $\vec{v} \times \vec{B}^{l} \perp \vec{v}$
$$\implies \frac{\partial}{\partial \vec{v}} \cdot\left(\vec{F}^{l} f_S\right)=\vec{F}^{l} \cdot \frac{\partial f_S}{\partial \vec{v}} $$
Now we plug this into the conservation law
$$ \frac{\partial f_S}{\partial t}+\vec{v} \cdot \frac{\partial f_S}{\partial \vec{r}}+\frac{\vec{F}^{l}}{m_S} \cdot \frac{\partial f_S}{\partial \vec{v}}=\underbrace{-\frac{\partial}{\partial \vec{v}} \cdot\left(\frac{\vec{F}^{s}}{m_S} f_S\right)}_{\left(\frac{\partial f}{\partial t}\right)_c}$$The term $(\partial_t f)_c$ describes evolution of distribution function due to collisions and is called collision operator. When we explicitly show $F^l$, we get $$\frac{\partial f_S}{\partial t}+\vec{v} \cdot \frac{\partial f_S}{\partial \vec{r}}+\frac{q_S}{m_S}\left(\vec{E}^{l}+\vec{v} \times \vec{B}^{l}\right) \cdot \frac{\partial f_S}{\partial \vec{v}}=\left(\frac{\partial f}{\partial t}\right)_c$$ which is called the "Boltzmann equation".
## Sources
1. EPFL - Introduction to Plasma Physics, lecture 2a)
2. https://en.wikipedia.org/wiki/Distribution_function_(physics) |
// Replacing the Oil heater outside temperature wired thermomenter
// Using PmodPOT from DIGILENT to fake the thermometer readings.
// Temperature is reported from Home Assisntant and translated to
// the variable resistance that the heater control unit reads.
//
// Board used: Seeed Studio XIAO ESP32C3
//
// https://www.hackster.io/56149/using-the-pmod-dpot-with-arduino-uno-599aa5
#include <Arduino.h>
// Data measurements
/*
Temp
-21.6 218
-19.2 193
-16.7 167
-12.9 137
-6.6 100
-4.3 89
1.3 66
10.3 45
13 40
14.2 38
17.3 33
20.2 29
22.7 26
24.6 24
29.1 20
39.5 13
50 8
https://arachnoid.com/polysolve/
Mode: normal x,y analysis
Polynomial degree 4, 17 x,y data pairs.
Correlation coefficient = 0.9998828943211641
Standard error = 0.7459147587921936
Output form: C function:
*/
double regress(double x) {
double terms[] = {
7.1198043291249064e+001,
-3.4765543064929418e+000,
1.0305520205537699e-001,
-1.9706202226396794e-003,
1.5940374387768800e-005
};
size_t csz = sizeof terms / sizeof *terms;
double t = 1;
double r = 0;
for (int i = 0; i < csz;i++) {
r += terms[i] * t;
t *= x;
}
return r;
}
/*
Copyright (c) 2019, P. Lutus -- http://arachnoid.com. All Rights Reserved.
*/
#include <WiFi.h>
#include <ArduinoHA.h>
#include <SPI.h>
#include "secrets.h"
// https://wiki.seeedstudio.com/XIAO_ESP32C3_Getting_Started/
#define PIN_CS D2
// XIAO ESP32C3 SPI: D8 SCK, D10 MOSI, D9 MISO
#define PIN_SCK D8
#define PIN_MISO D9
#define PIN_MOSI D10
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HANumber outsideTemp("outside-temp", HABaseDeviceType::PrecisionP1);
HASensorNumber rssiSensor("rssi");
void onNumberCommand(HANumeric number, HANumber* sender)
{
if (!number.isSet()) {
// the reset command was send by Home Assistant
} else {
float numberFloat = number.toFloat();
Serial.print("received: ");
Serial.println(numberFloat);
uint16_t val = round(regress(numberFloat));
Serial.print("Setting to ");
Serial.println(val);
// begin transmission
digitalWrite(PIN_CS, LOW); // activation of CS line
delayMicroseconds(15);
SPI.transfer(val);
// end transmission
digitalWrite(PIN_CS, HIGH); // deactivation of CS line
}
sender->setState(number); // report the selected option back to the HA panel
}
void connect() {
byte mac[6];
Serial.print("checking wifi...");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.print("RSSI: ");
Serial.println(WiFi.RSSI());
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
// set device's details (optional)
device.setName("Oil Heater");
device.setSoftwareVersion("1.0.0");
// handle command from the HA panel
outsideTemp.onCommand(onNumberCommand);
// Optional configuration
outsideTemp.setIcon("mdi:thermometer");
outsideTemp.setName("Outside Temp");
outsideTemp.setMin(-20);
outsideTemp.setMax(50);
outsideTemp.setStep(0.5f); // minimum step: 0.001f
outsideTemp.setUnitOfMeasurement("°C");
//outsideTemp.setMode(HANumber::ModeBox);
outsideTemp.setMode(HANumber::ModeSlider);
// You can set retain flag for the HA commands
outsideTemp.setRetain(true);
// You can also enable optimistic mode for the HASelect.
// In this mode you won't need to report state back to the HA when commands are executed.
// outsideTemp.setOptimistic(true);
// reporting RSSI
rssiSensor.setIcon("mdi:wifi");
rssiSensor.setName("RSSI");
rssiSensor.setUnitOfMeasurement("dB");
mqtt.begin(BROKER_ADDR);
}
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASS);
// init the SPI interface
SPI.begin(PIN_SCK, PIN_MOSI, PIN_MISO); // initialization of SPI interface
SPI.setDataMode(SPI_MODE0); // configuration of SPI communication in mode 0
SPI.setClockDivider(SPI_CLOCK_DIV16); // configuration of clock at 1MHz
pinMode(PIN_CS, OUTPUT); //setting chip select as output
connect();
}
unsigned long lastUpdateAt = 0;
void loop() {
//client.loop();
mqtt.loop();
//sleep(500);
if (!client.connected()) {
Serial.println("reconnecting ");
connect();
}
if ((millis() - lastUpdateAt) > 10000) { // update in 10s interval
unsigned long uptimeValue = millis() / 1000;
rssiSensor.setValue(WiFi.RSSI());
lastUpdateAt = millis();
}
} |
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node* link;
};
struct node* start = NULL;
void createList()
{
if (start == NULL) {
int n;
printf("\nEnter the number of nodes:");
scanf("%d", &n);
if (n != 0) {
int data;
struct node* newnode;
struct node* temp;
newnode = malloc(sizeof(struct node));
start = newnode;
temp = start;
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
start->info = data;
for (int i = 2; i <= n; i++) {
newnode = malloc(sizeof(struct node));
temp->link = newnode;
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
newnode->info = data;
temp = temp->link;
}
}
printf("\nThe list is created\n");
}
else
printf("\nThe list is already created\n");
}
void traverse()
{
struct node* temp;
if (start == NULL)
printf("\nList is empty\n");
else {
temp = start;
while (temp != NULL) {
printf("Data = %d\n", temp->info);
temp = temp->link;
}
}
}
void insertAtFront()
{
int data;
struct node* temp;
temp = malloc(sizeof(struct node));
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
temp->info = data;
// Pointer of temp will be
// assigned to start
temp->link = start;
start = temp;
}
int main()
{
int choice;
while (1) {
printf("1 to see list\n");
printf("2 to insert at"
" starting\n");
printf("3 to insert at"
" end\n");
printf("4 to insert at "
"any position\n");
printf("5 to exit\n");
printf("\nenter Choice :\n");
scanf("%d", &choice);
switch (choice) {
case 1:
traverse();
break;
case 2:
insertAtFront();
break;
case 3:
insertAtEnd();
break;
case 4:
insertAtPosition();
break;
case 5:
exit(1);
break;
default:
printf("Incorrect Choice\n");
}
}
return 0;
} |
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
function TodoList() {
const todos = useSelector((state) => {
return state.todos;
});
const dispatch = useDispatch();
const navigate = useNavigate();
return (
<div>
<h1>진행중</h1>
{todos
.filter((todo) => todo.isDone === false)
.map((todo) => {
return (
<div style={{ padding: "10px", border: "1px solid black" }}>
제목: {todo.title}
<br />
내용: {todo.body}
<br />
<button
onClick={() => {
navigate(`/${todo.id}`);
}}
>
상세페이지
</button>
<button
onClick={() => {
dispatch({
type: "DELETE_TODO",
payload: todo.id,
});
}}
>
삭제하기
</button>
<button
onClick={() => {
dispatch({
type: "SWITCH_TODO",
payload: todo.id,
});
}}
>
완료하기
</button>
</div>
);
})}
<h1>완료</h1>
{todos
.filter((todo) => todo.isDone === true)
.map((todo) => {
return (
<div style={{ padding: "10px", border: "1px solid black" }}>
제목: {todo.title}
<br />
내용: {todo.body}
<br />
<button
onClick={() => {
navigate(`/${todo.id}`);
}}
>
상세페이지
</button>
<button
onClick={() => {
dispatch({
type: "DELETE_TODO",
payload: todo.id,
});
}}
>
삭제하기
</button>
<button
onClick={() => {
dispatch({
type: "SWITCH_TODO",
payload: todo.id,
});
}}
>
취소하기
</button>
</div>
);
})}
</div>
);
}
export default TodoList; |
import {getUser} from './services/user.js'
import {getRepositories} from './services/repositories.js'
import{user} from './objects/user.js'
import{screen} from './objects/screen.js'
import {events} from './services/events.js'
document.getElementById('btn-search').addEventListener('click', () => {
const userName = document.getElementById('input-search').value
if (validateEmptyInput(userName)) return
getUserData(userName)
})
document.getElementById('input-search').addEventListener('keyup', (e) => {
const userName = e.target.value
const key = e.which || e.keyCode
const isEnterKeyPressed = key === 13
if (isEnterKeyPressed) {
if (validateEmptyInput(userName)) return
getUserData(userName)
}
})
function validateEmptyInput(userName) {
if (userName.length === 0){
alert('Preencha o campo com o nome do usuário do GitHub')
return true
}
}
async function getUserData(userName) {
const userResponse = await getUser(userName)
if (userResponse.message === "Not Found"){
screen.renderNotFound()
return
}
const repositoriesResponse = await getRepositories(userName)
const eventsResponse = await events(userName)
user.setInfo(userResponse)
user.setRepositories(repositoriesResponse)
user.setEvents(eventsResponse)
screen.renderUser(user)
} |
import useForm from "../../customsHooks/useForm"
import image from '../../assets/image.svg'
import {useFormRegister} from '../../todo/helpers/useFormRegister'
export const RegisterPage = () => {
const {isValid, isValidFormRegister, setIsValid} = useFormRegister()
const { values, handleInputChange, reset} = useForm({
nickName: '',
mail: '',
password: '',
password2: ''
})
const {mail, password, password2, nickName} = values
const createUser = async (body, reset, setIsValid) => {
setIsValid({
msgRegister: '',
isLoading: true
})
const credentials = {
nickName: body.nickName,
mail: body.mail,
password: body.password
}
fetch('https://backend-24vg.onrender.com/api/v1/users', {
method: 'POST',
headers: {'content-type': 'application/json'},
body: JSON.stringify(credentials)
}).then(resp => resp.json())
.then(data => {
if(data?.message){
return setIsValid({
msgRegister: data.message,
isLoading: false
})}
setIsValid({
msgRegister: 'Usuario creado con éxito',
isLoading: false
});
reset()
}).catch(err => console.log(err))
}
const onFormSumbit = (event) => {
event.preventDefault()
if(isValidFormRegister(nickName, password, password2)){
createUser(values, reset, setIsValid)
}
}
return (
<>
<section className="login sm:flex sm:flex-col ">
<figure className="register_picture h-full w-1/2 sm:w-full">
<img src={image} className="login__img"/>
</figure>
<form className="login_form sm:w-full w-1/2 " onSubmit={onFormSumbit}>
<h2 className=" text-5xl p-2 bg-clip-text text-transparent bg-gradient-to-r from-pink-500 to-violet-500 ">Registrate</h2>
<input
type="text"
placeholder="NickName"
className="login__input w-1/2 md:w-10/12 " autoFocus
name='nickName'
value={nickName}
onChange={handleInputChange} />
<input
required
type="mail"
placeholder="Mail"
className="login__input w-1/2 md:w-10/12"
name='mail'
value={mail}
onChange={handleInputChange} />
<input type="password"
placeholder="Password"
className="login__input w-1/2 md:w-10/12"
name='password'
onChange={handleInputChange}
value={password} />
<input type="password"
placeholder="Confirma tu password:"
className="login__input w-1/2 md:w-10/12"
name='password2'
onChange={handleInputChange}
value={password2} />
<div>
{(isValid.msgRegister) && isValid.msgRegister}
</div>
<div className="w-1/6 text-center rounded-lg px-px py-px bg-gradient-to-r from-pink-500 to-violet-500 box md:w-10/12 ">
{ isValid.isLoading ? <button type="sumbit" className="login__cta hover:bg-gradient-to-r from-green-500/5 to-blue-500/5" disabled>
<svg className="animate-spin mx-auto h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
</button>
:
<button type='sumbit' className="login__cta hover:bg-gradient-to-r from-green-500/5 to-blue-500/5 md:w-10/12 ">Sign Up</button>}
</div>
</form>
</section>
</>
)
} |
<template>
<div class="login-container">
<el-form class="login-form" ref="loginFormRef" label-width="100px" :rules="rules" :model="form">
<div class="title-container">
<img src="/vite.svg" class="logo" alt="Vite logo" />
</div>
<el-form-item prop="email" label="邮箱">
<el-input v-model="form.email" placeholder="请输入邮箱">
</el-input>
</el-form-item>
<el-form-item prop="captcha" label="验证码" class="captcha-container">
<div class="captcha">
<img :src="code.captcha" @click="resetCaptcha">
</div>
<el-input v-model="form.captcha" placeholder="请输入验证码"></el-input>
</el-form-item>
<el-form-item prop="emailcode" label="验证码" class="captcha-container">
<div class="captcha">
<el-button @click="sendEmailCode" :disabled="send.timer > 0" type='primary'>{{ sendText }}</el-button>
</div>
<el-input v-model="form.emailcode" placeholder="请输入邮件验证码"></el-input>
</el-form-item>
<el-form-item prop="password" label="密码">
<el-input v-model="form.password" placeholder="请输入密码">
</el-input>
</el-form-item>
<el-form-item label=" " class="form-btn">
<!-- <button @clikc.prevent></button> -->
<el-button type="primary" @click.native.prevent="handleLogin" >登录</el-button>
<router-link to="/register">
<el-button type="primary" >注册</el-button>
</router-link>
</el-form-item>
</el-form>
</div>
</template>
<script>
import { computed, reactive, toRefs, ref, nextTick } from 'vue'
import config from "config/http";
import { sendcode } from "apis/utils"
const { url } = config
import { login } from "apis/user";
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const TOKEN_KEY = 'USER_TOKEN'
// 数据mock测试
// fetch("/api/users")
// .then(response => response.json())
// .then(json => console.log('proxy:', json))
// .catch(err => console.log('err', err));
export default {
setup() {
const router = useRouter()
const loginFormRef = ref()
const rules = {
email: [
{ required: true, message: "请输入邮箱" },
{ type: 'email', message: "请输入正确的邮箱格式" },
],
captcha: [
{ required: true, message: "请输入验证码" },
],
emailcode: [
{ required: true, message: "请输入邮箱验证码" },
],
password: [
{ required: true, pattern: /^[\w_-]{6,12}$/g, message: "请输入6~12位密码" },
]
}
const state = reactive({
form: {
email: '1039445602@qq.com',
captcha: '',
emailcode: '',
password:''
},
code: {
captcha: url + '/util/captcha',
},
send: {
timer: 0
}
})
const resetCaptcha = (params) => {
state.code.captcha = url + '/util/captcha?_t' + new Date().getTime()
}
const sendEmailCode = async () => {
// 邮箱验证码
await sendcode({ email: state.form.email });
state.send.timer = 10;
state.timer = setInterval(() => {
state.send.timer -= 1
if (state.send.timer === 0) {
clearInterval(state.timer)
}
}, 1000)
}
const handleLogin = async (formEl) => {
// await nextTick()
// nextTick(()=>{
// console.log('loginFormRef',loginFormRef)
// })
loginFormRef.value.validate(async valid => {
if(valid){
let ret = await login(state.form)
if(ret && ret.code == 0){
ElMessage.success('登陆成功')
// 保存token
localStorage.setItem(TOKEN_KEY, ret.data.token)
setTimeout(()=>{
router.push('/')
},500)
}
}
})
}
const sendText = computed(() => {
if (state.send.timer <= 0) {
return "发送"
}
return `${state.send.timer}s后发送`
})
return {
...toRefs(state),
resetCaptcha,
sendEmailCode,
sendText,
rules,
handleLogin,
loginFormRef
}
}
}
</script>
<style lang="scss" scoped>
// .form-btn::v-deep .el-form-item__content{
// justify-content: space-around;
// }
.form-btn::v-deep(.el-form-item__content){
justify-content: space-around;
}
</style> |
//
// Copyright (c) 2018 KxCoding <kky0317@gmail.com>
//
// 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 UIKit
/*:
# Overloading
*/
func process(value: Int){ print("Int") }
func process(value: String){ print("String") }
func process(value: String, anotherValue: String) { }
func process(_ value: String){ }
func process(value: Double) -> Int { return 0 }
func process(value: Double) -> String? { return String(value) }
process(value: 0)
process(value: "0")
// #1 함수이름이 동일하면 파라미터 수로 식별
// #2 함수이름, 파라미터 수가 동일하며 파라미터 자료형으로 식별
// #3 함수이름, 파라미터가 동일하면 Argument Label로 식별
// #4 함수이름, 파라미터, Argument Label이 동일하며 리턴형으로 식별
let result = process(value: 12.34) as Int
struct Rectangle {
func area() -> Double { return 1.0 }
static func area() -> Double { return 0.0}
}
let r = Rectangle()
r.area()
Rectangle.area() |
import 'dart:ui';
import '../utils/ui_utils.dart';
import 'constants.dart';
extension IntExt on int{
///px转dp
double get px =>
Configurations.fitWidth ?
this * (window.physicalSize.width / Configurations.design_width_px) //先缩放(1080下就是x1.44)
/ window.devicePixelRatio// 除以本机像素密度获取dp
:
this * (window.physicalSize.height / Configurations.design_height_px)
/ window.devicePixelRatio;
///根据像素密度比转换dp
double get dp =>
Configurations.fitWidth ?
(this * Configurations.design_density) * //获取到设计图px
(window.physicalSize.width / Configurations.design_width_px)// 乘以缩放因子
/ window.devicePixelRatio //除以本机像素密度获取dp
:
(this * Configurations.design_density) *
(window.physicalSize.height / Configurations.design_height_px) /
window.devicePixelRatio;
///字体专用单位 可控制缩放
double get sp {
if (Configurations.fitWidth) {
if (Configurations.applySystemFontScaling) {
return (this * Configurations.design_density) //获取到设计图px
* (window.physicalSize.width
/ Configurations.design_width_px) // 乘以缩放因子
/ window.devicePixelRatio; //除以本机像素密度获取dp
} else {
return (this * Configurations.design_density) //获取到设计图px
* (window.physicalSize.width
/ Configurations.design_width_px) / // 乘以缩放因子
window.devicePixelRatio //除以本机像素密度获取dp
/ UIUtils.textScaleFactor; //除以系统字体缩放因子,放大多少就缩小多少233
}
} else {
if (Configurations.applySystemFontScaling) {
return (this * Configurations.design_density)
* (window.physicalSize.height
/ Configurations.design_height_px)
/ window.devicePixelRatio;
} else {
return (this * Configurations.design_density)
* (window.physicalSize.height
/ Configurations.design_height_px)
/ window.devicePixelRatio
/ UIUtils.textScaleFactor;
}
}
}
} |
%description:
Copying and assignment for messages: dynamic arrays of struct and class members
%file: test.msg
namespace @TESTNAME@;
struct MyStruct
{
int bb;
}
class MyClass
{
int bb;
}
message Base
{
MyStruct ms[];
MyClass mc[];
omnetpp::cQueue q[];
}
message MyMessage extends Base
{
MyStruct ms2[];
MyClass mc2[];
omnetpp::cQueue q2[];
};
%includes:
#include "test_m.h"
%global:
void print(const char *what, MyMessage& x)
{
EV << what << ":" << endl;
EV << "ms[]:" << x.getMsArraySize() << ":"
<< x.getMs(0).bb << ":"
<< x.getMs(1).bb << endl;
EV << "mc[]:" << x.getMcArraySize() << ":"
<< x.getMc(0).getBb() << ":"
<< x.getMc(1).getBb() << endl;
EV << "q[]:" << x.getQArraySize() << ":"
<< x.getQ(0).getName() << ":" << x.getQ(0).getLength() << ":"
<< x.getQ(1).getName() << ":" << x.getQ(1).getLength() << endl;
EV << "ms2[]:" << x.getMs2ArraySize() << ":"
<< x.getMs2(0).bb << ":"
<< x.getMs2(1).bb << endl;
EV << "mc2[]:" << x.getMc2ArraySize() << ":"
<< x.getMc2(0).getBb() << ":"
<< x.getMc2(1).getBb() << endl;
EV << "q2[]:" << x.getQ2ArraySize() << ":"
<< x.getQ2(0).getName() << ":" << x.getQ2(0).getLength() << ":"
<< x.getQ2(1).getName() << ":" << x.getQ2(1).getLength() << endl;
EV << "." << endl;
}
%activity:
// set up tester classes
MyMessage x;
x.setMsArraySize(2);
x.setMcArraySize(3);
x.setQArraySize(4);
x.setMs2ArraySize(5);
x.setMc2ArraySize(6);
x.setQ2ArraySize(7);
x.getMsForUpdate(0).bb=10;
x.getMsForUpdate(1).bb=11;
x.getMcForUpdate(0).setBb(20);
x.getMcForUpdate(1).setBb(21);
x.getQForUpdate(0).setName("q(0)"); x.getQForUpdate(0).insert(new cMessage);
x.getQForUpdate(1).setName("q(1)"); x.getQForUpdate(1).insert(new cMessage); x.getQForUpdate(1).insert(new cMessage);
x.getMs2ForUpdate(0).bb=30;
x.getMs2ForUpdate(1).bb=31;
x.getMc2ForUpdate(0).setBb(40);
x.getMc2ForUpdate(1).setBb(41);
x.getQ2ForUpdate(0).setName("q2(0)"); x.getQ2ForUpdate(0).insert(new cMessage);x.getQ2ForUpdate(0).insert(new cMessage);
x.getQ2ForUpdate(1).setName("q2(1)"); x.getQ2ForUpdate(1).insert(new cMessage);
print("x",x);
// copy constructor
MyMessage x1(x);
print("x1(x)",x1);
// assigment
MyMessage x2;
x2 = x;
print("x2=x",x2);
%contains: stdout
x:
ms[]:2:10:11
mc[]:3:20:21
q[]:4:q(0):1:q(1):2
ms2[]:5:30:31
mc2[]:6:40:41
q2[]:7:q2(0):2:q2(1):1
.
x1(x):
ms[]:2:10:11
mc[]:3:20:21
q[]:4:q(0):1:q(1):2
ms2[]:5:30:31
mc2[]:6:40:41
q2[]:7:q2(0):2:q2(1):1
.
x2=x:
ms[]:2:10:11
mc[]:3:20:21
q[]:4:q(0):1:q(1):2
ms2[]:5:30:31
mc2[]:6:40:41
q2[]:7:q2(0):2:q2(1):1
. |
<?php
namespace App\Http\Controllers;
use App\Http\Requests\JenisProdukRequest;
use App\Models\JenisProduk;
use Exception;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;
class JenisProdukController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$title = 'Jenis Produk';
if(request()->ajax()){
$model = JenisProduk::query();
return DataTables::of($model)
->addColumn('_', function ($data){
$html = '<button class="btn btn-info btn-icon" type="button" onclick="show('.$data->id.')" title="Show"><i class="fas fa-eye"></i></button>';
$html .= '<button class="btn btn-warning btn-icon mx-2" type="button" onclick="edit('.$data->id.')" title="Edit"><i class="fas fa-edit"></i></button>';
$html .= '<button class="btn btn-danger btn-icon" type="button" onclick="destroy('.$data->id.')" title="Delete" ><i class="far fa-trash-alt"></i></button>';
return $html;
})
->rawColumns(['_'])
->make(true);
}
return view('master.jenis_produk.index', compact('title'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
try{
return view('master.jenis_produk.create');
}catch(Exception $e){
return response()->json([
'message' => 'Gagal Menambahkan Jenis Produk',
], $e->getCode() ?: 500);
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(JenisProdukRequest $request)
{
$post = $request->validated()+['created_by' => auth()->user()->username];
try{
JenisProduk::create($post);
return response()->json([
'message' => 'Berhasil Menambahkan Jenis Produk'
], 200);
}catch(Exception $e){
return response()->json([
'message' => 'Gagal Menambahkan Jenis Produk',
], $e->getCode() ?: 500);
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
try{
$model = JenisProduk::find($id);
if(!$model){
return response()->json([
'message' => 'JenisProduk Tidak Ditemukan'
], 404);
}
return view('master.jenis_produk.show', compact('model'));
}catch(Exception $e){
return response()->json([
'message' => 'JenisProduk Gagal Ditampilkan',
'error' => $e->getMessage()
], $e->getCode() ?: 500);
}
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
try{
$model = JenisProduk::find($id);
if(!$model){
return response()->json([
'message' => 'JenisProduk Tidak Ditemukan'
], 404);
}
return view('master.jenis_produk.edit', compact('model'));
}catch(Exception $e){
return response()->json([
'message' => 'JenisProduk Gagal Diedit',
'error' => $e->getMessage()
], $e->getCode() ?: 500);
}
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(JenisProdukRequest $request, $id)
{
$post = $request->validated()+['updated_by' => auth()->user()->username];
try{
$model = JenisProduk::find($id);
if(!$model){
return response()->json([
'message' => 'JenisProduk Tidak Ditemukan'
], 404);
}
$model->update($post);
return response()->json([
'message' => 'Berhasil Memperbarui Jenis Produk'
], 200);
}catch(Exception $e){
return response()->json([
'message' => 'Gagal Memperbarui Jenis Produk',
'error' => $e->getMessage()
], $e->getCode() ?: 500);
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
DB::beginTransaction();
try{
$model = JenisProduk::find($id);
if(!$model){
return response()->json([
'message' => 'JenisProduk Tidak Ditemukan'
], 404);
}
$model->delete();
DB::commit();
return response()->json([
'message' => 'Berhasil Menghapus Jenis Produk'
], 200);
}catch(Exception $e){
DB::rollBack();
return response()->json([
'message' => 'Gagal Menghapus Jenis Produk',
'error' => $e->getMessage()
], $e->getCode() ?: 500);
}
}
} |
import React, { ChangeEvent, ChangeEventHandler } from 'react'
interface InputPorps {
label : string
placeholder : string,
value? : string
type? : string,
onChange : (e : ChangeEvent<HTMLInputElement>) => void;
}
const Input = ({
label,
value,
placeholder,
type,
onChange,
} : InputPorps) => {
return (
<div className='mt-2'>
<label className='text-lg p-1' htmlFor={label}>{label}</label>
<input value={value} type={type} id={label} onChange={onChange} className='bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 ' placeholder={placeholder} />
</div>
)
}
export default Input |
<?php
/**
* Copyright (c) Enalean, 2016 - Present. All Rights Reserved.
*
* This file is a part of Tuleap.
*
* Tuleap is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Tuleap is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Tuleap. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Tuleap\PullRequest\Comment;
use Tuleap\DB\DataAccessObject;
class Dao extends DataAccessObject implements ParentCommentSearcher, ThreadColorUpdater, CommentUpdater, CommentSearcher, CreateComment
{
public function create(NewComment $comment): int
{
$this->getDB()->insert(
'plugin_pullrequest_comments',
[
'pull_request_id' => $comment->pull_request->getId(),
'user_id' => (int) $comment->author->getId(),
'post_date' => $comment->post_date->getTimestamp(),
'content' => $comment->content,
'parent_id' => $comment->parent_id,
'format' => $comment->format,
]
);
return (int) $this->getDB()->lastInsertId();
}
public function searchByPullRequestId($pull_request_id, $limit, $offset, $order)
{
if (strtolower($order) !== 'asc') {
$order = 'desc';
}
$sql = "SELECT SQL_CALC_FOUND_ROWS *
FROM plugin_pullrequest_comments
WHERE pull_request_id = ?
ORDER BY id $order
LIMIT ?, ?";
return $this->getDB()->run($sql, $pull_request_id, $offset, $limit);
}
/**
* @psalm-return array{
* id: int,
* pull_request_id: int,
* user_id: int,
* post_date: int,
* content: string,
* parent_id: int,
* color: string,
* format: string,
* last_edition_date: int|null
* }|null
*/
public function searchByCommentID(int $comment_id): ?array
{
$sql = 'SELECT id, pull_request_id, user_id, post_date, content, parent_id, color, format, last_edition_date
FROM plugin_pullrequest_comments
WHERE id = ?';
return $this->getDB()->row($sql, $comment_id);
}
public function searchAllByPullRequestId($pull_request_id)
{
$sql = 'SELECT SQL_CALC_FOUND_ROWS *
FROM plugin_pullrequest_comments
WHERE pull_request_id = ?';
return $this->getDB()->run($sql, $pull_request_id);
}
public function setThreadColor(int $pull_request_id, string $color): void
{
$sql = 'UPDATE plugin_pullrequest_comments SET color = ? WHERE id= ?';
$this->getDB()->run($sql, $color, $pull_request_id);
}
public function updateComment(Comment $new_comment): void
{
$this->getDB()->update(
'plugin_pullrequest_comments',
[
'content' => $new_comment->getContent(),
'last_edition_date' => $new_comment->getLastEditionDate()
->mapOr(static fn(\DateTimeImmutable $last_edition_date) => $last_edition_date->getTimestamp(), null),
],
['id' => $new_comment->getId()]
);
}
} |
import "./../../../firebase";
import React from "react";
import { useFormikContext } from "formik";
import ErrorMessage from "./ErrorMessage";
import ImageInputList from "../ImageInputList";
import { getStorage, ref, uploadBytes, getDownloadURL } from "firebase/storage";
const storage = getStorage();
const FormImagePicker = ({ name, setLoading }) => {
const { errors, setFieldValue, touched, values } = useFormikContext();
const uris = values[name];
const handleAdd = async (uri) => {
setLoading(true);
try {
const response = await fetch(uri);
const blob = await response.blob();
const filename = uri.substring(uri.lastIndexOf("/") + 1);
// var ref = firebase.ref().child(filename).put(blob);
const storageRef = ref(storage, filename);
const snapshot = await uploadBytes(storageRef, blob);
const url = await getDownloadURL(snapshot.ref);
setFieldValue(name, [url]);
} catch (error) {
alert(error.message);
} finally {
setLoading(false);
}
};
const handleRemove = (uri) =>
setFieldValue(
name,
uris.filter((imageUri) => imageUri !== uri)
);
return (
<>
<ImageInputList
onImageAdd={handleAdd}
onImageRemove={handleRemove}
uris={uris}
/>
<ErrorMessage error={errors[name]} visible={touched[name]} />
</>
);
};
export default FormImagePicker; |
<?php
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
use App\Entity\Product;
use Faker\Factory;
use Faker\Provider\en_US\Text;
use App\DataFixtures\SongProvider;
class ProductFixture extends Fixture
{
// private function getRandomBookName()
// {
// $randomIndex = array_rand(self::$bookTitles);
// return self::$bookTitles[$randomIndex];
// }
// private function getRandomFoodName()
// {
// $randomIndex = array_rand(self::$foodNames);
// return self::$foodNames[$randomIndex];
// }
// private function getRandomFlowerName()
// {
// $randomIndex = array_rand(self::$flowerNames);
// return self::$flowerNames[$randomIndex];
// }
public function load(ObjectManager $manager)
{
$bookTitles = [
'To Kill a Mockingbird',
'1984',
'The Great Gatsby',
'Pride and Prejudice',
'The Catcher in the Rye',
// Add more book titles here
];
$flowerNames = [
'Rose',
'Tulip',
'Sunflower',
'Daisy',
'Lily',
// Add more flower names here
];
$foodNames = [
'Pizza',
'Burger',
'Sushi',
'Spaghetti',
'Ice Cream',
// Add more food names here
];
// Get the references to the categories created in CategoryFixture
$booksCategory = $this->getReference("Books");
$flowersCategory = $this->getReference("Flowers");
$foodCategory = $this->getReference("Food");
// $textfaker = Factory::create();
// $textfaker->addProvider(new Text($textfaker));
// Create and associate products with their respective categories
// for ($i = 1; $i <= 5; $i++) {
foreach ($foodNames as $name){
$foodProduct = new Product();
$foodProduct->setCategory($foodCategory);
$foodProduct->setName($name);
$manager->persist($foodProduct); // Example: "Pizza"
}
foreach ($bookTitles as $name){
$booksProduct = new Product();
$booksProduct->setCategory($booksCategory);
$booksProduct->setName($name);
$manager->persist($booksProduct); // Example: "Harry Potter and the goblet of fire"
}
foreach ($flowerNames as $name){
$flowersProduct = new Product();
$flowersProduct->setCategory($flowersCategory);
$flowersProduct->setName($name);
$manager->persist($flowersProduct); // Example: "Tulip"
}
//}
$manager->flush();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.