text
stringlengths 184
4.48M
|
---|
package com.yanxiuhair.framework.aspectj;
import java.util.Objects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.yanxiuhair.common.annotation.DataSource;
import com.yanxiuhair.common.config.datasource.DynamicDataSourceContextHolder;
import com.yanxiuhair.common.utils.StringUtils;
/**
* @ClassName: DataSourceAspect
* @Description: 多数据源处理
* @author: gaoxiaochuang
* @date: 2020年10月19日 上午10:11:52
*
* @Copyright: 2020 http://www.yanxiuhair.com/ Inc. All rights reserved.
* 注意:本内容仅限于许昌妍秀发制品有限公司内部传阅,禁止外泄以及用于其他的商业目
*/
@Aspect
@Order(1)
@Component
public class DataSourceAspect {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("@annotation(com.yanxiuhair.common.annotation.DataSource)"
+ "|| @within(com.yanxiuhair.common.annotation.DataSource)")
public void dsPointCut() {
}
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
DataSource dataSource = getDataSource(point);
if (StringUtils.isNotNull(dataSource)) {
DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
}
try {
return point.proceed();
} finally {
// 销毁数据源 在执行方法之后
DynamicDataSourceContextHolder.clearDataSourceType();
}
}
/**
* 获取需要切换的数据源
*/
public DataSource getDataSource(ProceedingJoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
if (Objects.nonNull(dataSource)) {
return dataSource;
}
return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
}
}
|
<?php
namespace App\Http\Controllers;
use App\Models\Trains;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class UserController extends Controller
{
//Showing Register Form
public function register(){
return view('users.form')->with("form","register");
}
//Storing User
public function store(Request $request){
// if ($request->email=="[email protected]" || str_contains($request->name,"admin")) {
// return back()->withErrors(['email'=>'Invalid Credentials'])->onlyInput('email');
// }
$users=User::get();
foreach ($users as $user) {
if ($user->email==$request->email) {
return back()->withErrors(['email'=>'Already Have An Account With This Email '])->onlyInput('email');
}
}
$formFeilds=$request->validate([
'name'=>['required','min:3'],
'email'=>['required','email',Rule::unique('users','email')],
'password'=>'required|confirmed|min:6'
]);
// $contains=(int)strpos($formFeilds['name'],"admin");
//Hash Password
$formFeilds['password']=bcrypt($formFeilds['password']);
//Create User
$user=User::create($formFeilds);
//login
auth()->login($user);
return redirect('/')->with('message','User Created And Logged In.');
}
//logout
public function logout(Request $request){
auth()->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/')->with('message','You Have Been Logged Out !');
}
//show login form
public function login(){
return view('users.form')->with("form","login");
}
//authenticate user
public function authenticate(Request $request){
$formFeilds=$request->validate([
'email'=>['required','email'],
'password'=>'required'
]);
if($formFeilds["email"]=="[email protected]"){
return back()->withErrors(['email'=>'Invalid Credentials'])->onlyInput('email');
}
if(auth()->attempt($formFeilds)){
$request->session()->regenerate();
return redirect('/')->with('message','You are now logged in !');
}
return back()->withErrors(['email'=>'Invalid Credentials'])->onlyInput('email');
}
public function authenticateAdmin(Request $request){
$formFeilds=$request->validate([
'email'=>['required','email'],
'password'=>'required'
]);
if(strtolower($formFeilds["email"])=="[email protected]" && $formFeilds["password"]=="9920096388"){
if(auth()->attempt($formFeilds)){
$request->session()->regenerate();
return redirect('/')->with('message','Welcome Back Admin!');
}
}
return back()->withErrors(['email'=>'Invalid Credentials'])->onlyInput('email');
}
//Shoing Edit User Form
public function edit(){
return view('users.edit');
}
//Updating User
public function update(Request $request){
$formFeilds=$request->validate([
'name'=>['required','min:3'],
'email'=>['required','email'],
'password'=>'required|confirmed|min:6'
]);
//Hash Password
$formFeilds['password']=bcrypt($formFeilds['password']);
if($formFeilds['password']==auth()->user()->password){
return back()->withErrors(['password'=>'Password Must Be Unique'])->onlyInput('password');
}
//Create User
$user=User::where("id",auth()->user()->id)->first();
$user->update($formFeilds);
auth()->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/')->with('message','User Updated Successfully.');
}
//Admin Controllers
//show admin login form
public function adminLogin(){
return view('users.form')->with("form","admin");
}
}
|
package com.learn.jvm.jdk8;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
/**
* @author yds
* @title: CountDownLatch
* @description: TODO
* @date 2021/3/8 15:07
*/
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
CountDownLatch latch = new CountDownLatch(4);
System.out.println("正在等待所有玩家准备好");
for(int i = 0; i < latch.getCount(); i++){
new Thread(new MyThread(latch), "player"+i).start();
}
latch.await();
System.out.println("开始游戏");
}
private static class MyThread implements Runnable{
private CountDownLatch latch ;
public MyThread(CountDownLatch latch){
this.latch = latch;
}
@Override
public void run() {
try {
Random rand = new Random();
int randomNum = rand.nextInt((3000 - 1000) + 1) + 1000;//产生1000到3000之间的随机整数
Thread.sleep(randomNum);
System.out.println(Thread.currentThread().getName()+" 已经准备好了, 所使用的时间为 "+((double)randomNum/1000)+"s");
latch.countDown();
System.out.println("还剩余" + latch.getCount() + "玩家未准备");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
// @ts-ignore
import { InfernActionsTypes , BaseThunkType} from './redux-store.ts';
// @ts-ignore
import { secutiryAPI } from './../api/security-api.ts';
// @ts-ignore
import { authAPI } from './../api/auth-api.ts';
import { FormAction, stopSubmit } from 'redux-form';
// @ts-ignore
import { ResultCodesEnum, ResultCodeForCaptcha } from '../api/api.ts';
let initialState = {
id: null as number | null,
email: null as string | null,
login: null as string | null,
isAuth: false as boolean,
captchaUrl: null as string | null
};
const authReducer = (state = initialState, action: ActionTypes): InitialStateType => {
switch (action.type) {
case 'SN/AUTH/SET_USER_DATA':
case 'SN/AUTH/GET_CAPTCHA_URL_SUCCES':
return {
...state,
...action.payload,
}
default:
return state;
}
}
export const actions = {
setAuthUserData: (userId: number | null, email: string | null, login: string | null, isAuth: boolean) => ({
type: 'SN/AUTH/SET_USER_DATA', payload: { userId, email, login, isAuth }
} as const),
getCaptchaUrlSuccess: (captchaUrl: string) => ({ type: 'SN/AUTH/GET_CAPTCHA_URL_SUCCES', payload: { captchaUrl } } as const)
}
export const getAuthUserData = (): ThunkType => async (dispatch) => {
let meData = await authAPI.me();
if (meData.resultCode === ResultCodesEnum.Success) {
let { id, login, email } = meData.data;
dispatch(actions.setAuthUserData(id, email, login, true));
}
}
export const login = (email: string, password: string, rememberMe: boolean, captcha: string): ThunkType => async (dispatch) => {
let data = await authAPI.login(email, password, rememberMe, captcha);
if (data.resultCode === ResultCodesEnum.Success) {
dispatch(getAuthUserData());
} else {
if(data.resultCode === ResultCodeForCaptcha.CaptchaIsRequired){
dispatch(getCaptchaUrl());
}
let message = data.messages.length > 0 ? data.messages[0] : 'Some error';
dispatch(stopSubmit('login', {_error: message}));
}
}
export const logout = (): ThunkType => async (dispatch) => {
let response = await authAPI.logout()
if (response.data.resultCode === 0) {
dispatch(actions.setAuthUserData(null, null, null, false))
}
}
export const getCaptchaUrl = (): ThunkType => async (dispatch) => {
const data = await secutiryAPI.getCaptchaUrl()
const captchaUrl = data.url
dispatch(actions.getCaptchaUrlSuccess(captchaUrl))
}
export default authReducer;
export type InitialStateType = typeof initialState
type ActionTypes = InfernActionsTypes<typeof actions>
type ThunkType = BaseThunkType<ActionTypes | FormAction>
|
import { Commands, Container } from "@swipechain/core-cli";
import { Networks } from "@swipechain/crypto";
import Joi from "joi";
import { File, Git, NPM, Source } from "../source-providers";
/**
* @export
* @class Command
* @extends {Commands.Command}
*/
@Container.injectable()
export class Command extends Commands.Command {
/**
* The console command signature.
*
* @type {string}
* @memberof Command
*/
public signature: string = "plugin:install";
/**
* The console command description.
*
* @type {string}
* @memberof Command
*/
public description: string = "Installs a package, and any packages that it depends on.";
/**
* Configure the console command.
*
* @returns {void}
* @memberof Command
*/
public configure(): void {
this.definition
.setFlag("token", "The name of the token.", Joi.string().default("swipechain"))
.setFlag("network", "The name of the network.", Joi.string().valid(...Object.keys(Networks)))
.setArgument("package", "The name of the package.", Joi.string().required());
}
/**
* Execute the console command.
*
* @returns {Promise<void>}
* @memberof Command
*/
public async execute(): Promise<void> {
const pkg: string = this.getArgument("package");
try {
return await this.install(pkg);
} catch (error) {
throw new Error(error.message);
}
}
/**
* @private
* @param {string} pkg
* @returns {Promise<void>}
* @memberof Command
*/
private async install(pkg: string): Promise<void> {
for (const Instance of [File, Git, NPM]) {
const source: Source = new Instance({
data: this.app.getCorePath("data", "plugins"),
temp: this.app.getCorePath("temp", "plugins"),
});
if (await source.exists(pkg)) {
return source.install(pkg);
}
}
throw new Error(`The given package [${pkg}] is neither a git nor a npm package.`);
}
}
|
import 'package:bordered_text/bordered_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:netflix_clone/application/bloc/home_bloc.dart';
import 'package:netflix_clone/core/colors/colors.dart';
// import 'package:netflix_clone/application/bloc/home_bloc.dart';
import 'package:netflix_clone/core/common/constants.dart';
import 'package:netflix_clone/core/common/widgets/mainCardTile.dart';
import 'package:netflix_clone/core/common/widgets/subtitle_widget.dart';
import 'package:netflix_clone/core/string.dart';
import 'package:netflix_clone/presentation/home/widgets/main_background.dart';
final List imageUrlList = [
"https://www.themoviedb.org/t/p/w600_and_h900_bestv2/ekZobS8isE6mA53RAiGDG93hBxL.jpg",
"https://www.themoviedb.org/t/p/w600_and_h900_bestv2/lAXONuqg41NwUMuzMiFvicDET9Y.jpg",
"https://www.themoviedb.org/t/p/w220_and_h330_face/wFjboE0aFZNbVOF05fzrka9Fqyx.jpg",
"https://www.themoviedb.org/t/p/original/flLF4Oe4MTz6U6iqeLEULl6RCfu.jpg",
"https://www.themoviedb.org/t/p/w220_and_h330_face/rnheO8cFvCYcmZsDrBoabJbKLFE.jpg",
"https://www.themoviedb.org/t/p/w220_and_h330_face/7Bttz4hEspKlpU0Me57dkHNR3nf.jpg",
"https://www.themoviedb.org/t/p/original/fzANAOf0YlDsol1XDzSp6WPTUv3.jpg",
"https://www.themoviedb.org/t/p/original/j39IIKLYWsGzMepFE1xFBFbFsd3.jpg"
];
ValueNotifier<bool> scrollNotifier = ValueNotifier(true);
class ScreenHome extends StatelessWidget {
const ScreenHome({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((_) {
BlocProvider.of<HomeBloc>(context).add(const GetHomeScreenData());
});
return Scaffold(
body: SafeArea(
child: NotificationListener<UserScrollNotification>(
onNotification: (notification) {
final ScrollDirection direction = notification.direction;
if (direction == ScrollDirection.reverse) {
scrollNotifier.value = false;
} else if (direction == ScrollDirection.forward) {
scrollNotifier.value = true;
}
return true;
},
child: ValueListenableBuilder(
valueListenable: scrollNotifier,
builder: (context, value, _) {
return Stack(
children: [
BlocBuilder<HomeBloc, HomeState>(
builder: (context, state) {
if (state.isLoading) {
return const Center(
child: CircularProgressIndicator(
strokeWidth: 2,
),
);
}
if (state.hasError) {
return const Center(
child: Text(
'Error While Getting Data',
style: TextStyle(color: kwhiteColor),
),
);
}
if (state.top10TvShowsList.isEmpty) {
return const Center(
child: Text('No Data Available'),
);
}
// released past year
final _releasesPathYear = state.pastYearMovieList.map((e) {
return '$imageAppendUrl${e.posterPath}';
}).toList();
//trending now
final _trendingNow = state.trendingNowList.map((e) {
return '$imageAppendUrl${e.posterPath}';
}).toList();
//tense dramas
final _tenseDramas = state.tenseDramasList.map((e) {
return '$imageAppendUrl${e.posterPath}';
}).toList();
// south indian
final _southIndian = state.southIndianMovieList.map((e) {
return '$imageAppendUrl${e.posterPath}';
}).toList();
return ListView(
children: [
const MainBackgroundCard(),
kheight,
const SubTitleWidgetCustom(
title: 'Released In Past Year'),
ImageTileWidgetCustom(
imageUrl: imageUrlList[0],
posterPathList: _releasesPathYear,
),
kheight,
const SubTitleWidgetCustom(title: 'Trending Now'),
ImageTileWidgetCustom(
imageUrl: imageUrlList[1],
posterPathList: _trendingNow,
),
kheight,
const SubTitleWidgetCustom(
title: 'Top 10 TV Shows In India Today'),
ToptenImageWidget(
imageUrl: imageUrlList[4],
posterUrl: _releasesPathYear,
),
kheight,
const SubTitleWidgetCustom(title: 'Tense Dramas'),
ImageTileWidgetCustom(
imageUrl: imageUrlList[2],
posterPathList: _tenseDramas,
),
const SubTitleWidgetCustom(title: 'South Indian Cinema'),
ImageTileWidgetCustom(
imageUrl: imageUrlList[3],
posterPathList: _southIndian,
)
],
);
},
),
scrollNotifier.value ? const TopAppBar() : kheight
],
);
},
),
)));
}
}
class ToptenImageWidget extends StatelessWidget {
const ToptenImageWidget(
{Key? key, required this.imageUrl, required this.posterUrl})
: super(key: key);
final String imageUrl;
final List<String> posterUrl;
@override
Widget build(BuildContext context) {
return LimitedBox(
maxHeight: 220, //maxWidth: 150,
child: ListView(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
children: List.generate(
10,
(index) => ToptenImageTile(
imageurl: posterUrl[index],
index: index,
)),
),
);
}
}
// top 10 Custom image tile number + image //
class ToptenImageTile extends StatelessWidget {
const ToptenImageTile({Key? key, required this.index, required this.imageurl})
: super(key: key);
final int index;
final String imageurl;
@override
Widget build(BuildContext context) {
return Stack(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
),
child: Row(
children: [
kimageWidth,
MainCardTileWidgetCustom(customurl: imageurl),
],
),
),
Positioned(
bottom: 0,
child: BorderedText(
child: Text(
'${index + 1}',
style: const TextStyle(fontSize: 100, color: Colors.black),
),
strokeColor: Colors.white,
))
],
);
}
}
// normal list tile widget//
class ImageTileWidgetCustom extends StatelessWidget {
const ImageTileWidgetCustom(
{Key? key, required this.imageUrl, required this.posterPathList})
: super(key: key);
final String imageUrl;
final List<String> posterPathList;
@override
Widget build(BuildContext context) {
return LimitedBox(
maxHeight: 220,
child: ListView(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
children: List.generate(
posterPathList.length,
(index) => MainCardTileWidgetCustom(
customurl: posterPathList[index],
))),
);
}
}
|
import Text from './components/Text';
import './styles/App.css';
import Button from './components/Button';
import Input from './components/Input';
import {useState} from 'react';
function App() {
//State for name
const [name, setName] = useState('');
//State for age
const [age, setAge] = useState(0);
//State to show Name required
const [msgErrorName, setMsgErrorName] = useState('');
//State to show Name required
const [msgErrorAge, setErrorAge] = useState('');
//State to show Msg
const [welcomeMessage, setWelcomeMessage] = useState('');
const validForm = () => {
let valid=true;
setName(name.trim());
if(name.length===0 )
{
valid=false;
setMsgErrorName('Campo Obligatorio');
}
else
setMsgErrorName('');
if(age.toString().length===0 || parseInt(age)<=0)
{
valid=false;
setErrorAge('Campo Obligatorio y mayor que 0');
}
else
setErrorAge('');
if(valid)
if(age>=18)
setWelcomeMessage(`Bienvenido <strong>${name}</strong>, gracias por usar nuestra aplicación`);
else
setWelcomeMessage(`Hola <strong>${name}</strong>, eres muy joven para usar esta aplicación`);
else
setWelcomeMessage('');
};
return (
<div className="App">
<div className="form__container">
<Text renderAs="h1" content="Ingrese los Siguientes Datos"/>
<div className="flex__container p__LeftRight--3">
<Text renderAs="p" content="Nombre" />
<Input
type={"text"}
placeholder={"Ingrese Nombre"}
value={name}
onChange={(e) => setName(e.target.value)}
/>
<Text renderAs="p" content={msgErrorName} componentsProps={{className:"erroMessage"}}/>
<Text renderAs="p" content="Edad" />
<Input
type={"number"}
minValue="1"
placeholder={"Ingrese Edad"}
value={age}
onChange={(e) => setAge(e.target.value)}
/>
<Text renderAs="p" content={msgErrorAge} componentsProps={{className:"erroMessage"}}/>
</div>
<Button label="Mostrar Mensaje" onClick={validForm}/>
<Text renderAs="span" content={welcomeMessage}
componentsProps={{id:"idMsg", style: { display: welcomeMessage ? 'block' : 'none' }}}
/>
</div>
</div>
);
}
export default App;
|
install.packages("readxl")
library(readxl)
estimation <- read_excel("BBBCData.xlsx", sheet = "Estimation Sample")
log_reg = glm(Choice ~ Gender + Amt_purchased + Frequency +
Last_Purchase + First_purchase + P_Child + P_Youth + P_Cook +
P_DIY + P_Art,
data = estimation, family = binomial)
summary(log_reg)$coef
install.packages("mfx")
library(mfx)
mfx <- logitmfx(Choice ~ Gender + Amt_purchased + Frequency +
Last_Purchase+ First_purchase + P_Child + P_Youth + P_Cook +
P_DIY + P_Art,
data = estimation)
mfx$mfxest
library(dplyr)
estimation <- estimation %>% mutate(decile = ntile(Last_Purchase, 10))
table(estimation$Last_Purchase)
estimation$R_decile = .bincode(estimation$Last_Purchase,
quantile(estimation$Last_Purchase, probs = seq(0, 1, 0.1),
right = TRUE, include.lowest = TRUE))
estimation$R_decile = .bincode(estimation$Last_Purchase,
quantile(estimation$Last_Purchase, probs = seq(0, 1, 0.1)),
right = TRUE, include.lowest = TRUE)
estimation$R_decile = 11 - estimation$R_decile
table(estimation$R_decile)
estimation %>% group_by(decile) %>% summarize(response_rate = mean(Choice))
estimation %>% group_by(R_decile) %>% summarize(response_rate = mean(Choice))
estimation$probabilities = predict(log_reg, type = "response")
validation <- read_excel("BBBCData.xlsx", sheet = "Validation Sample")
validation$probabilities = predict(log_reg, newdata = validation, type = "response")
validation$pred_choice = ifelse(validation$probabilities >= 0.5, TRUE, FALSE)
table(validation$Choice, validation$pred_choice)
estimation$prob_decile = .bincode(estimation$probabilities,
quantile(estimation$probabilities, probs = seq(0, 1, 0.1)),
right = TRUE, include.lowest = TRUE)
validation$prob_decile = .bincode(validation$probabilities,
quantile(validation$probabilities, probs = seq(0, 1, 0.1)),
right = TRUE, include.lowest = TRUE)
validation$prob_decile = 11 - validation$prob_decile
table(validation$prob_decile)
tapply(validation$Choice,validation$prob_decile,sum)
tapply(validation$Choice,validation$prob_decile,mean)
validation$R_decile = .bincode(validation$Last_Purchase,
quantile(estimation$Last_Purchase,
probs = seq(0, 1, 0.1), na.rm = TRUE),
right = TRUE, include.lowest = TRUE)
validation$R_decile = 11 - validation$R_decile
tapply(validation$Choice,validation$R_decile,sum)
table(validation$R_decile)
|
package academy.user
import academy.user.role.UserRole
import org.apache.commons.lang3.StringUtils
import org.springframework.security.core.GrantedAuthority
import org.springframework.security.core.authority.SimpleGrantedAuthority
class AcademyUser {
String name
String surname
String email
Date createdOn
Date dateOfBirth
String phoneNumber
String location
UserType userType
EnglishLevel englishLevel
boolean enabled
static mapping = {
autowire true
}
static constraints = {
email(blank: false, email: true, validator: { value, user ->
String login = value.trim()
def notUnique
if (AcademyUser.findAllByEmail(login).find { it.id != user.id }) {
notUnique = ['User.email.unique']
}
if (notUnique) {
return notUnique
}
true
})
name blank: false
surname blank: false
createdOn nullable: false
userType nullable: false
phoneNumber nullable: true
dateOfBirth nullable: true
location nullable: true
englishLevel nullable: true
}
String fullname() {
name + " " + surname
}
Collection<GrantedAuthority> authorities() {
UserRole.findAllByUser(this).collect {
new SimpleGrantedAuthority(it.role.authority)
}
}
def beforeInsert() {
capitalizeName()
}
protected void capitalizeName() {
name = StringUtils.capitalize(name)
surname = StringUtils.capitalize(surname)
}
}
|
/*
* 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.spark.sql.execution.datasources.v2
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.{Expression, RowOrdering, SortOrder}
import org.apache.spark.sql.catalyst.plans.physical
import org.apache.spark.sql.catalyst.plans.physical.KeyGroupedPartitioning
import org.apache.spark.sql.catalyst.util.{truncatedString, InternalRowComparableWrapper}
import org.apache.spark.sql.connector.read.{HasPartitionKey, InputPartition, PartitionReaderFactory, Scan}
import org.apache.spark.sql.execution.{ExplainUtils, LeafExecNode, SQLExecution}
import org.apache.spark.sql.execution.metric.SQLMetrics
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.connector.SupportsMetadata
import org.apache.spark.sql.vectorized.ColumnarBatch
import org.apache.spark.util.ArrayImplicits._
import org.apache.spark.util.Utils
trait DataSourceV2ScanExecBase extends LeafExecNode {
lazy val customMetrics = scan.supportedCustomMetrics().map { customMetric =>
customMetric.name() -> SQLMetrics.createV2CustomMetric(sparkContext, customMetric)
}.toMap
override lazy val metrics = {
Map("numOutputRows" -> SQLMetrics.createMetric(sparkContext, "number of output rows")) ++
customMetrics
}
def scan: Scan
def readerFactory: PartitionReaderFactory
/** Optional partitioning expressions provided by the V2 data sources, through
* `SupportsReportPartitioning` */
def keyGroupedPartitioning: Option[Seq[Expression]]
/** Optional ordering expressions provided by the V2 data sources, through
* `SupportsReportOrdering` */
def ordering: Option[Seq[SortOrder]]
protected def inputPartitions: Seq[InputPartition]
override def simpleString(maxFields: Int): String = {
val result =
s"$nodeName${truncatedString(output, "[", ", ", "]", maxFields)} ${scan.description()}"
redact(result)
}
def partitions: Seq[Seq[InputPartition]] = {
groupedPartitions.map(_.groupedParts.map(_.parts)).getOrElse(inputPartitions.map(Seq(_)))
}
/**
* Shorthand for calling redact() without specifying redacting rules
*/
protected def redact(text: String): String = {
Utils.redact(session.sessionState.conf.stringRedactionPattern, text)
}
override def verboseStringWithOperatorId(): String = {
val metaDataStr = scan match {
case s: SupportsMetadata =>
s.getMetaData().toSeq.sorted.flatMap {
case (_, value) if value.isEmpty || value.equals("[]") => None
case (key, value) => Some(s"$key: ${redact(value)}")
case _ => None
}
case _ =>
Seq(scan.description())
}
s"""
|$formattedNodeName
|${ExplainUtils.generateFieldString("Output", output)}
|${metaDataStr.mkString("\n")}
|""".stripMargin
}
override def outputPartitioning: physical.Partitioning = {
keyGroupedPartitioning match {
case Some(exprs) if KeyGroupedPartitioning.supportsExpressions(exprs) =>
groupedPartitions
.map { keyGroupedPartsInfo =>
val keyGroupedParts = keyGroupedPartsInfo.groupedParts
KeyGroupedPartitioning(exprs, keyGroupedParts.size, keyGroupedParts.map(_.value),
keyGroupedPartsInfo.originalParts.map(_.partitionKey()))
}
.getOrElse(super.outputPartitioning)
case _ =>
super.outputPartitioning
}
}
@transient lazy val groupedPartitions: Option[KeyGroupedPartitionInfo] = {
// Early check if we actually need to materialize the input partitions.
keyGroupedPartitioning match {
case Some(_) => groupPartitions(inputPartitions)
case _ => None
}
}
/**
* Group partition values for all the input partitions. This returns `Some` iff:
* - [[SQLConf.V2_BUCKETING_ENABLED]] is turned on
* - all input partitions implement [[HasPartitionKey]]
* - `keyGroupedPartitioning` is set
*
* The result, if defined, is a [[KeyGroupedPartitionInfo]] which contains a list of
* [[KeyGroupedPartition]], as well as a list of partition values from the original input splits,
* sorted according to the partition keys in ascending order.
*
* A non-empty result means each partition is clustered on a single key and therefore eligible
* for further optimizations to eliminate shuffling in some operations such as join and aggregate.
*/
def groupPartitions(inputPartitions: Seq[InputPartition]): Option[KeyGroupedPartitionInfo] = {
if (!SQLConf.get.v2BucketingEnabled) return None
keyGroupedPartitioning.flatMap { expressions =>
val results = inputPartitions.takeWhile {
case _: HasPartitionKey => true
case _ => false
}.map(p => (p.asInstanceOf[HasPartitionKey].partitionKey(), p.asInstanceOf[HasPartitionKey]))
if (results.length != inputPartitions.length || inputPartitions.isEmpty) {
// Not all of the `InputPartitions` implements `HasPartitionKey`, therefore skip here.
None
} else {
// also sort the input partitions according to their partition key order. This ensures
// a canonical order from both sides of a bucketed join, for example.
val partitionDataTypes = expressions.map(_.dataType)
val rowOrdering = RowOrdering.createNaturalAscendingOrdering(partitionDataTypes)
val sortedKeyToPartitions = results.sorted(rowOrdering.on((t: (InternalRow, _)) => t._1))
val sortedGroupedPartitions = sortedKeyToPartitions
.map(t => (InternalRowComparableWrapper(t._1, expressions), t._2))
.groupBy(_._1)
.toSeq
.map { case (key, s) => KeyGroupedPartition(key.row, s.map(_._2)) }
.sorted(rowOrdering.on((k: KeyGroupedPartition) => k.value))
Some(KeyGroupedPartitionInfo(sortedGroupedPartitions, sortedKeyToPartitions.map(_._2)))
}
}
}
override def outputOrdering: Seq[SortOrder] = {
// when multiple partitions are grouped together, ordering inside partitions is not preserved
val partitioningPreservesOrdering = groupedPartitions
.forall(_.groupedParts.forall(_.parts.length <= 1))
ordering.filter(_ => partitioningPreservesOrdering).getOrElse(super.outputOrdering)
}
override def supportsColumnar: Boolean = {
scan.columnarSupportMode() match {
case Scan.ColumnarSupportMode.PARTITION_DEFINED =>
require(
inputPartitions.forall(readerFactory.supportColumnarReads) ||
!inputPartitions.exists(readerFactory.supportColumnarReads),
"Cannot mix row-based and columnar input partitions.")
inputPartitions.exists(readerFactory.supportColumnarReads)
case Scan.ColumnarSupportMode.SUPPORTED => true
case Scan.ColumnarSupportMode.UNSUPPORTED => false
}
}
def inputRDD: RDD[InternalRow]
def inputRDDs(): Seq[RDD[InternalRow]] = Seq(inputRDD)
override def doExecute(): RDD[InternalRow] = {
val numOutputRows = longMetric("numOutputRows")
inputRDD.map { r =>
numOutputRows += 1
r
}
}
protected def postDriverMetrics(): Unit = {
val driveSQLMetrics = scan.reportDriverMetrics().map(customTaskMetric => {
val metric = metrics(customTaskMetric.name())
metric.set(customTaskMetric.value())
metric
})
val executionId = sparkContext.getLocalProperty(SQLExecution.EXECUTION_ID_KEY)
SQLMetrics.postDriverMetricUpdates(sparkContext, executionId,
driveSQLMetrics.toImmutableArraySeq)
}
override def doExecuteColumnar(): RDD[ColumnarBatch] = {
val numOutputRows = longMetric("numOutputRows")
inputRDD.asInstanceOf[RDD[ColumnarBatch]].map { b =>
numOutputRows += b.numRows()
b
}
}
}
/**
* A key-grouped Spark partition, which could consist of multiple input splits
*
* @param value the partition value shared by all the input splits
* @param parts the input splits that are grouped into a single Spark partition
*/
private[v2] case class KeyGroupedPartition(value: InternalRow, parts: Seq[InputPartition])
/**
* Information about key-grouped partitions, which contains a list of grouped partitions as well
* as the original input partitions before the grouping.
*/
private[v2] case class KeyGroupedPartitionInfo(
groupedParts: Seq[KeyGroupedPartition],
originalParts: Seq[HasPartitionKey])
|
(ns dujour.migrations
(:require [clojure.java.jdbc :as jdbc]
[clojure.java.jdbc.sql :as sql]
[dujour.db :refer :all]
[ragtime.core :refer :all]
[ragtime.sql.database :refer :all]
))
(defn clear-database!
[database]
(let [ddl-drop-tables
["DROP TABLE IF EXISTS params CASCADE"
"DROP TABLE IF EXISTS checkins CASCADE"
"DROP TABLE IF EXISTS releases CASCADE"]]
(apply jdbc/db-do-commands database true ddl-drop-tables)))
(defn init-database!
[{:keys [db-type] :as database}]
(let [checkin_id-sql
(case db-type
"postgresql" "SERIAL PRIMARY KEY"
"hsqldb" "INTEGER GENERATED BY DEFAULT AS IDENTITY (START WITH 0) PRIMARY KEY")
ddl-create-tables
["CREATE TABLE releases
(product TEXT,
version TEXT, release_date TIMESTAMP,
link TEXT,
message TEXT,
PRIMARY KEY (product, version))",
(format "CREATE TABLE checkins
(checkin_id %s,
product TEXT,
version TEXT,
timestamp TIMESTAMP,
ip TEXT,
FOREIGN KEY (product, version) REFERENCES releases (product, version) ON DELETE CASCADE)"
checkin_id-sql),
"CREATE TABLE params
(checkin_id INTEGER REFERENCES checkins(checkin_id) ON DELETE CASCADE,
param TEXT,
value TEXT,
PRIMARY KEY (checkin_id, param))",
"CREATE INDEX checkins_timestamp ON checkins (timestamp)",
"CREATE INDEX checkins_ip ON checkins (ip)"]]
(apply jdbc/db-do-commands database true ddl-create-tables)))
(def init-dujour-db
{:id "init-dujour-db"
:up init-database!
:down clear-database!})
(defn remove-users-and-products!
[database]
(let [ddl-drop-tables
["DROP TABLE IF EXISTS users CASCADE"
"DROP TABLE IF EXISTS products CASCADE"]]
(apply jdbc/db-do-commands database true ddl-drop-tables)))
(defn add-users-and-products!
[database]
(let [ddl-commands
["CREATE TABLE users
(ip TEXT PRIMARY KEY)"
"CREATE TABLE products
(product TEXT PRIMARY KEY)"
"INSERT INTO users SELECT DISTINCT ip FROM checkins"
"INSERT INTO products SELECT DISTINCT product FROM releases"
"ALTER TABLE checkins ADD FOREIGN KEY (ip) REFERENCES users (ip) ON DELETE CASCADE"
"ALTER TABLE releases ADD FOREIGN KEY (product) REFERENCES products (product) ON DELETE CASCADE"]]
(apply jdbc/db-do-commands database true ddl-commands)))
(def add-users-and-products
{:id "add-users-and-products"
:up add-users-and-products!
:down remove-users-and-products!})
(defn migrate-db!
"Applies a list of migrations using a given strategy from ragtime
:apply-new, :raise-error (default) or :rebase"
[database]
(let [migrations [init-dujour-db
add-users-and-products]]
(migrate-all (map->SqlDatabase database) migrations)))
|
import { ReactNode } from "react";
import { Color } from "../types/props";
export default function Button({ label, name, color = 'indigo', loading = false, onClick }: { label: string | ReactNode, name: string, color?: Color, loading?: boolean, onClick: () => void }) {
const colors = {
indigo: 'text-slate-100 bg-indigo-500 hover:bg-indigo-600 active:bg-indigo-700 focus:ring-indigo-300',
blue: 'text-slate-100 bg-blue-500 hover:bg-blue-600 active:bg-blue-700 focus:ring-blue-300',
grey: 'text-slate-100 bg-slate-500 hover:bg-slate-600 active:bg-slate-700 focus:ring-slate-300',
}
const colorClass = colors[color];
return (
<button
className={`${colorClass} flex items-center justify-center py-2 px-4 my-2 w-full h-10 text-sm font-medium rounded-md shadow-md focus:outline-none focus:ring transition ease-in-out duration-150`}
name={name}
onClick={onClick}
>
{
loading ?
<span className="inline-flex">
<svg className="animate-spin -ml-1 mr-3 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>
Loading...
</span>
:
label
}
</button>);
}
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
contract USDCBankV1 is Initializable, PausableUpgradeable, AccessControlUpgradeable {
bytes32 public constant DISTRIBUTOR_ROLE = keccak256("DISTRIBUTOR_ROLE");
ERC20Burnable public erc20;
mapping(address => uint256) public claimables;
struct Reward {
address to;
uint256 amount;
}
event Swap(address indexed _address, uint256 _amount);
event Claim(address indexed _address, uint256 _amount);
event Airdrop(address indexed _address, uint256 _amount);
function initialize(
address erc20Address
) public initializer {
__Pausable_init();
__AccessControl_init();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
erc20 = ERC20Burnable(erc20Address);
}
/**
* dev Swap function for exchanging USDCToken to karma point
*/
function swap(uint256 amount) external whenNotPaused {
erc20.transferFrom(msg.sender, address(this), amount);
emit Swap(msg.sender, amount);
}
/**
* dev Claim function for user to claim its claimable
*/
function claim() external whenNotPaused {
uint256 claimable = claimables[msg.sender];
require(claimable > 0, "Zero claimable");
erc20.transfer(msg.sender, claimable);
claimables[msg.sender] = 0;
emit Claim(msg.sender, claimable);
}
/**
* dev Setter for the claimables assigned to each users.
*/
function addClaimables(Reward[] calldata items) external onlyRole(DISTRIBUTOR_ROLE) {
for (uint256 i = 0; i < items.length; i++) {
claimables[items[i].to] += items[i].amount;
}
}
/**
* dev Removes claimable assigned to each users.
* Only use this function when claimables are set incorrectly.
*/
function removeClaimables(address[] calldata addresses) external onlyRole(DISTRIBUTOR_ROLE) {
for (uint256 i = 0; i < addresses.length; i++) {
claimables[addresses[i]] = 0;
}
}
/**
* dev Airdrop rewards to each users
*/
function airdrop(Reward[] calldata items) external onlyRole(DISTRIBUTOR_ROLE) {
for (uint256 i = 0; i < items.length; i++) {
erc20.transfer(items[i].to, items[i].amount);
emit Airdrop(items[i].to, items[i].amount);
}
}
/**
* dev Emergency withdraw in case of migration
*/
function withdraw() external onlyRole(DEFAULT_ADMIN_ROLE) {
erc20.transfer(msg.sender, erc20.balanceOf(address(this)));
}
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
}
|
package com.mca.application.service;
import com.mca.application.services.SagaVideoGameService;
import com.mca.infrastructure.adapters.out.persistence.SagaVideoGamePersistenceAdapter;
import com.mca.infrastructure.adapters.out.persistence.entities.SagaEntity;
import com.mca.infrastructure.model.Saga;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class SagaVideoGameServiceTest {
@Mock
private SagaVideoGamePersistenceAdapter sagaVideoGamePersistenceAdapter;
@InjectMocks
private SagaVideoGameService sagaVideoGameService;
@BeforeEach
void setUp(){
this.sagaVideoGameService = new SagaVideoGameService(sagaVideoGamePersistenceAdapter);
}
@Test
@DisplayName("getListSagasByGameId")
void getListSagasByGameId(){
List<Saga> listSagas = new ArrayList<>();
Saga saga = Saga.builder().id(1).title("Whispers").relevance(10).build();
listSagas.add(saga);
ResponseEntity<?> responseTest = ResponseEntity.ok(listSagas);
doReturn(responseTest).when(this.sagaVideoGamePersistenceAdapter).getListSagasByGameId(Mockito.anyInt());
ResponseEntity<?> response = sagaVideoGameService.getListSagasByGameId(1);
Assertions.assertEquals(HttpStatus.OK, response.getStatusCode());
List<Saga> responseBody = (List<Saga>) response.getBody();
Assertions.assertEquals(listSagas.get(0).getId(), responseBody.get(0).getId());
}
}
|
//* libraries
import { useState } from "react";
import { Typography, Button, Box, Rating, useMediaQuery } from "@mui/material";
import PropTypes from "prop-types";
//* styles
import { productItemStyles as styles } from "./productItem.styles";
export const ProductItem = ({
imageUrl,
installments,
listPrice,
price,
productName,
stars,
increment,
}) => {
const is640px = useMediaQuery("(max-width:640px)");
const [isBtnShown, setIsBtnShown] = useState(false);
const onMouseOver = () => setIsBtnShown(true);
const onMouseLeave = () => setIsBtnShown(false);
return (
<Box sx={styles.box}>
{/*//? Product image */}
<Box sx={styles.boxProduct}>
<Box
aria-label="productImg"
component="img"
src={imageUrl}
alt={productName}
/>
{listPrice && (
<Box sx={styles.boxTriangle}>
<Typography sx={styles.typoOff}>OFF</Typography>
</Box>
)}
</Box>
{/*//? Product details */}
<Box
sx={styles.boxData}
onMouseOver={onMouseOver}
onMouseLeave={onMouseLeave}
>
<Typography sx={styles.typoName}>{productName}</Typography>
<Rating
aria-label="rating"
name="read-only"
value={stars}
readOnly
sx={styles.rating}
/>
{listPrice && (
<Typography
sx={styles.typoListPrice}
>{`de $ ${listPrice}`}</Typography>
)}
<Typography sx={styles.typoPrice}>{`por $ ${price}`}</Typography>
{installments[0] && (
<Typography
sx={styles.typoQuantity}
>{`o en ${installments[0]?.quantity}x de R $ ${installments[0]?.value}`}</Typography>
)}
{(isBtnShown || is640px) && (
<Button sx={styles.button} onClick={() => increment()}>
<Typography sx={styles.typoButton}>COMPRAR</Typography>
</Button>
)}
</Box>
</Box>
);
};
//? Props validations
ProductItem.propTypes = {
imageUrl: PropTypes.string.isRequired,
installments: PropTypes.arrayOf(
PropTypes.shape({
quantity: PropTypes.number,
value: PropTypes.number,
})
).isRequired,
listPrice: PropTypes.number,
price: PropTypes.number.isRequired,
productName: PropTypes.string.isRequired,
stars: PropTypes.number.isRequired,
increment: PropTypes.func.isRequired,
};
|
from passlib.context import CryptContext
from sqlalchemy import Boolean, Column, Integer, String, select
from sqlalchemy.orm import Session, relationship
from app.db.session import Base
from .profile import Profile
from app.helper.exception import (
EmailConflictException,
PasswordInvalidException,
UserNotFoundException,
)
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
class User(Base):
__tablename__ = "users"
seq = Column(Integer, primary_key=True, autoincrement=True, comment="시퀀스")
email = Column(String(128), unique=True, comment="이메일")
password = Column(String(256), comment="비밀번호")
is_active = Column(Boolean, default=True, comment="활성화 여부")
profile = relationship(Profile, back_populates="user")
@staticmethod
def create(db: Session, email: str, password: str) -> None:
user = db.scalar(select(User).where(User.email == email))
if user:
raise EmailConflictException
if len(password) < 6:
raise PasswordInvalidException
user = User(email=email, password=pwd_context.hash(password))
db.add(user)
db.commit()
return None
@staticmethod
def resset_password(db: Session, email: str, password: str):
user = db.scalar(select(User).where(User.email == email))
if not user:
raise UserNotFoundException
db.query(User).filter(User.email == email).update(
{"password": pwd_context.hash(password)}
)
db.commit()
db.flush()
|
library(shiny)
library(reticulate)
library(png)
# Activate the Python environment
use_python("~/miniconda3/envs/r-reticulate/bin/python")
# Define the paths to the Python scripts
map_path <- "map.py"
migrate_path <- "migrate.py"
agri_path <- "agri.py"
clear_path <- "clear.py"
weather_api <- "weatherapi.py"
# Define the UI
ui <- fluidPage(
tags$head(
tags$style(HTML("
/* Custom CSS to style the UI */
.btn-primary {
background-color: #5cb85c;
border-color: #4cae4c;
}
.btn-primary:hover {
background-color: #449d44;
border-color: #398439;
}
.btn-primary:active, .btn-primary.active {
background-color: #449d44;
border-color: #398439;
}
.nav-tabs > li > a:hover {
border-color: #5cb85c;
}
.nav-tabs > li.active > a, .nav-tabs > li.active > a:hover, .nav-tabs > li.active > a:focus {
background-color: #5cb85c;
border-color: #5cb85c;
}
.nav-tabs > li > a {
color: #5cb85c;
}
.navbar-default {
background-color: #f5f5f5;
border-color: #e7e7e7;
}
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
background-color: #e7e7e7;
}
.navbar-default .navbar-brand {
color: #5cb85c;
}
"))
),
navbarPage(
"AgriVision",
tabPanel(
"Calculate Green Area",
textInput("loc", "Enter location"),
dateInput("date_pred", "Enter date for prediction"),
sidebarLayout(
sidebarPanel(
actionButton("open_maps", "Open Maps"),
br(),
actionButton("migrate_screenshots", "Migrate Screenshots"),
br(),
actionButton("calculate_area", "Calculate Green Area", class = "btn-primary"),
br(),
actionButton("clear_images", "Clear Images"),
br(),
actionButton("clear_graph", "Clear Plots", class = "btn-danger"),
br(),
actionButton("run_api", "Find details"),
),
mainPanel(
tabsetPanel(
tabPanel("Mask", plotOutput("mask_plot")),
tabPanel("Original", plotOutput("original_plot")),
tabPanel("Result", plotOutput("res_plot")),
tabPanel("Location",textOutput("Location_output")),
tabPanel("Attributes",textOutput("Attributes_output"))
)
)
)
),
tabPanel(
"About",
tags$div(
style = "padding: 20px;",
tags$h3("AgriVision"),
tags$p(
"AgriVision is a tool designed to calculate the green cultivatable land in a satellite image using Python and R."
),
tags$p(
"The tool consists of several Python scripts that use OpenCV to preprocess and analyze the image, and R Shiny for the user interface."
),
tags$p(
"This tool was created as part of a project for the Summer Research Internship at VIT Chennai."
),
tags$p(
"Developed by Abdul Aziz A.B and Aman Gupta."
)
)
)
)
)
source_python('weatherapi.py')
# Define the server
server <- function(input, output) {
# Function to run a Python script
run_python_script <- function(script_path) {
py_run_file(script_path, convert = TRUE)
}
# Function to plot an image
plot_image <- function(image_path) {
img <- readPNG(image_path)
plot(0, 0, type = "n", xlim = c(0, ncol(img)), ylim = c(0, nrow(img)),
xlab = "", ylab = "")
rasterImage(img, 0, 0, ncol(img), nrow(img))
}
# Open Maps button
observeEvent(input$open_maps, {
run_python_script(map_path)
})
#to show location details
output$Location_output <- renderText({
if (file.size("media/location.txt")>0){
Location_file_read <- read.delim("media/location.txt", header = TRUE, sep = "\n") # nolint
paste(toString(Location_file_read))
}
})
#to show climate attributes
output$Attributes_output <- renderText({
if (file.size("media/attributes.txt")>0){
Attribute_file_read <- read.delim("media/attributes.txt", header = TRUE, sep = "\n") # nolint
paste(toString(Attribute_file_read))
}
})
#run weather api button
observeEvent(input$run_api, {
value=input$loc
date=input$date_pred
v=test_weather(value,date)
#run_python_script(weather_api)
})
# Migrate Screenshots button
observeEvent(input$migrate_screenshots, {
run_python_script(migrate_path)
})
# Calculate Area button
observeEvent(input$calculate_area, {
run_python_script(agri_path)
output$mask_plot <- renderPlot({ plot_image("mask.png") })
output$original_plot <- renderPlot({ plot_image("original.png") })
output$res_plot <- renderPlot({ plot_image("result.png") })
})
observeEvent(input$clear_images, {
# Get a list of all the files in the directory
files <- list.files("working images")
# Remove each file one by one
for (file in files) {
file.remove(paste0("working images", file))
}
# Clear the image plots
output$mask_plot <- renderPlot(NULL)
output$original_plot <- renderPlot(NULL)
output$res_plot <- renderPlot(NULL)
})
observeEvent(input$clear_graph, {
# Clear the image plots
output$mask_plot <- renderPlot(NULL)
output$original_plot <- renderPlot(NULL)
output$res_plot <- renderPlot(NULL)
run_python_script(clear_path)
})
}
shinyApp(ui = ui, server = server)
|
'use client'
import React, { useState } from 'react';
const ThemeContext = React.createContext()
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light')
const toggleTheme = () => {
setTheme((theme) => {
// if (theme === 'light') {
// return 'dark'
// } else {
// return 'light'
// }
return theme === 'light' ? 'dark' : 'light'
})
}
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
{children}
</ThemeContext.Provider>
)
}
export { ThemeProvider, ThemeContext }
|
/**
*
* This file is part of Disco.
*
* Disco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Disco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Disco. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.diversify.disco.experiments.commons;
import eu.diversify.disco.experiments.commons.codecs.Codecs;
import eu.diversify.disco.experiments.commons.data.DataSet;
import eu.diversify.disco.experiments.commons.errors.RScriptNotFound;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.yaml.snakeyaml.Yaml;
/**
* Run a experiment identified by the class of its setup
*
* @author Franck Chauvel
* @since 0.1
*/
public class Runner {
private final static String VIEW_R = "view.r";
private final static String R_SCRIPT = "RScript";
private final static String RESULTS_EXTENSION = ".csv";
private final static String ABORT_COMMAND = "!abort";
private final static String DISCLAIMER = "Disco v0.1\n"
+ "Copyright (C) 2013 SINTEF ICT\n\n"
+ "License LGPLv3+: GNU LGPL version 3 or later <http://gnu.org/licenses/lgpl.html>\n"
+ "This is free software: you are free to change and redistribute it.\n"
+ "There is NO WARRANTY, to the extent permitted by law.\n";
private final static String CLOSING_MESSAGE = "That's all folks!";
private final static String DEFAULT_SETUP_FILE = "setup.yml";
/**
* To run an experiment, we first load the setup file, build the associated
* experiment, run it, serialise the results and generate their
* visualisation.
*
* @param setupClass the class encapsulating the setup of the experiment
*
* @param setupFile the location of file containing the actual setup
*/
public void run(Class setupClass, String setupFile) {
System.out.println(DISCLAIMER);
Setup setup = loadExperimentSetup(setupClass, setupFile);
Experiment experiment = setup.buildExperiment();
saveResults(experiment.run());
generateVisualisations();
System.out.println(CLOSING_MESSAGE);
}
/**
* Run the first setup file found within the arguments list or the default
* one if none is found.
*
* @param setupClass the Class of the setup
* @param commandLineArguments the command line arguments
*/
public void run(Class setupClass, String... commandLineArguments) {
System.out.println(DISCLAIMER);
List<String> setupFiles = extractSetupFiles(commandLineArguments);
run(setupClass, setupFiles.get(0));
/*
* TODO: Should ideally run all the given setup files. So far it run
* only the first one as in the following
*
* for (String setupFile : setupFiles) { run(setupClass, setupFile); }
*
*/
System.out.println(CLOSING_MESSAGE);
}
/**
* Extract the setup files specified in the command line arguments. If none
* are specified, return a list containing only de the default setup file.
*
* @param args the commands line arguments
* @return the list of setup file to run
*/
List<String> extractSetupFiles(String[] args) {
ArrayList<String> setupFiles = new ArrayList<String>();
for (String arg : args) {
if (isSetupFile(arg)) {
setupFiles.add(arg);
}
}
if (setupFiles.isEmpty()) {
setupFiles.add(DEFAULT_SETUP_FILE);
}
return setupFiles;
}
private boolean isSetupFile(String text) {
return text.matches("[^\\.]*\\.(yaml|yml)$");
}
/**
* To generate the the visualisation we call the RScript application,
* assuming their is a 'view.r' script available in the current directory.
*/
private void generateVisualisations() {
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec(String.format("%s %s", R_SCRIPT, VIEW_R));
final int errorCode = process.waitFor();
if (errorCode != 0) {
System.out.println("Error: R returned code " + errorCode);
}
} catch (IOException ex) {
System.out.println("ERROR: Unable to generate visualisation using R. Is R properly installed?'");
throw new RScriptNotFound();
} catch (InterruptedException ex) {
System.out.println("Error while generating the visualisations.");
System.out.println(" -> " + ex.getMessage());
}
}
/**
* To build the results of the experiment, we create a codecs and request
* the serialisation in CSV, for each dataset.
*
* @param results the collections of results to serialise
*/
private void saveResults(Collection<DataSet> results) {
Codecs codecs = new Codecs();
for (DataSet result : results) {
String fileName = result.getName() + RESULTS_EXTENSION;
try {
codecs.saveAs(result, fileName);
} catch (FileNotFoundException ex) {
System.out.println("ERROR: Unable to write or create ' " + fileName + "'");
System.out.println(" -> " + ex.getMessage());
} catch (IOException ex) {
System.out.println("ERROR: Unable to write or create ' " + fileName + "'");
}
}
}
/**
* To load the setup file, we create a YAML parser and use it create the
* setup object. If the given file does not exist, we prompt the user for
* another, as long as we cannot read the given file.
*
* @param setupClass the class of setup object to build
* @param setupFile the file to load
*
* @return the resulting setup object
*/
private Setup loadExperimentSetup(Class setupClass, String setupFile) {
final Yaml yaml = new Yaml();
Setup setup = null;
boolean abortRequested = false;
while (setup == null && !abortRequested) {
try {
setup = (Setup) yaml.loadAs(new FileInputStream(setupFile), setupClass);
} catch (FileNotFoundException ex) {
System.out.println("ERROR: Unable to locate the setup file '" + setupFile + "'");
System.out.println(" -> " + ex.getMessage());
setupFile = promptForSetupFile().trim();
if (setupFile.equals(ABORT_COMMAND)) {
abortRequested = true;
}
}
}
return setup;
}
/**
* Prompt the user for a setup file to read or to abort the experiment
*
* @return the string inputed by the user
*/
private String promptForSetupFile() {
BufferedReader commandLine = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the path to the setup file: ('" + ABORT_COMMAND + "' to abort) ");
String answer;
try {
answer = commandLine.readLine();
} catch (IOException ex) {
System.out.println("I/O ERROR while reading the command line. Quiting");
answer = ABORT_COMMAND;
}
return answer;
}
}
|
import { useState } from 'react'
import { Alert } from 'react-native'
import { useNavigation } from '@react-navigation/native'
import firestore from '@react-native-firebase/firestore'
import { VStack } from 'native-base'
import { Header } from '../components/Header'
import { Input } from '../components/Input'
import { Button } from '../components/Button'
export function Register() {
const [isLoading, setIsLoading] = useState(false)
const [patrimony, setPatrimony] = useState('')
const [description, setDescription] = useState('')
const navigation = useNavigation()
function handleNewOrderRegister() {
if (!patrimony || !description) {
//validação caso os campos estejam preenchidos
return Alert.alert('Solicitar', 'Preencha todos os campos.')
}
setIsLoading(true)
firestore() //banco de dados utilizado importado de '@react-native-firebase/firestore'
.collection('orders') //entre na coleção e caso não haja crei ela
.add({
//crie o documento ou dados
patrimony, //conteudo digitado no campo de patrimonio
description, //conteudo digitado no campo de descrição
status: 'open', //conteudo vem como padrão em andamento => "open"
created_at: firestore.FieldValue.serverTimestamp() //conteudo de data atual do servidor importado do firebase
})
.then(() => {
//caso inserção seja sucesso
Alert.alert('Solicitação', 'Sua solicitação foi criada com sucesso.')
navigation.goBack()
})
.catch(err => {
//caso inserção seja fracasso
console.log(err)
setIsLoading(false)
return Alert.alert(
'Solicitação',
'Não foi possivel criar sua solicitação.'
)
})
}
return (
<VStack flex={1} p={6} bg="gray.600">
<Header title="Nova solicitação" />
<Input
onChangeText={setPatrimony}
placeholder="Número do patrimônio"
mt={4}
/>
<Input
onChangeText={setDescription}
placeholder="Descrição do problema"
flex={1}
mt={5}
multiline
textAlignVertical="top"
/>
<Button
title="Cadastrar"
mt={5}
isLoading={isLoading}
onPress={handleNewOrderRegister}
/>
</VStack>
)
}
|
/**
* @param {number} k
*/
var MyCircularQueue = function(k) {
this.queue = [];
this.maxSize = k;
this.currentSize = 0;
this.front = 0;
this.rear = -1;
};
/**
* @param {number} value
* @return {boolean}
*/
MyCircularQueue.prototype.enQueue = function(value) {
if (this.currentSize >= this.maxSize) return false;
this.rear = (++this.rear) % this.maxSize;
// 원형 큐이므로 push를 하지않고 인덱스를 지정해준다
this.queue[this.rear] = value;
this.currentSize++;
return true;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.deQueue = function() {
if (this.currentSize === 0) return false;
this.front = (++this.front) % this.maxSize;
this.currentSize--;
return true;
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Front = function() {
return this.currentSize === 0 ? -1 : this.queue[this.front];
};
/**
* @return {number}
*/
MyCircularQueue.prototype.Rear = function() {
return this.currentSize === 0 ? -1 : this.queue[this.rear];
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isEmpty = function() {
return this.currentSize === 0;
};
/**
* @return {boolean}
*/
MyCircularQueue.prototype.isFull = function() {
return this.currentSize === this.maxSize;
};
/**
* Your MyCircularQueue object will be instantiated and called as such:
* var obj = new MyCircularQueue(k)
* var param_1 = obj.enQueue(value)
* var param_2 = obj.deQueue()
* var param_3 = obj.Front()
* var param_4 = obj.Rear()
* var param_5 = obj.isEmpty()
* var param_6 = obj.isFull()
*/
|
import { EthereumAuthProvider, useViewerConnection } from "@self.id/framework";
// A simple button to initiate the connection flow. A Provider must be present at a higher level
// in the component tree for the `useViewerConnection()` hook to work.
function ConnectButton() {
const [connection, connect, disconnect] = useViewerConnection();
return connection.status === "connected" ? (
<button
onClick={() => {
disconnect();
}}
>
Disconnect ({connection.selfID.id})
</button>
) : "ethereum" in window ? (
<button
disabled={connection.status === "connecting"}
onClick={async () => {
const accounts = await window.ethereum.request({
method: "eth_requestAccounts",
});
await connect(
new EthereumAuthProvider(window.ethereum, accounts[0])
);
}}
>
Connect
</button>
) : (
<p>
An injected Ethereum provider such as{" "}
<a href="https://metamask.io/">MetaMask</a> is needed to
authenticate.
</p>
);
}
export default ConnectButton;
|
/*
* Copyright (c) 2006-2007 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: Thumbnail object
*
*/
#ifndef THUMBNAILDATA_H
#define THUMBNAILDATA_H
#include <e32std.h>
class CFbsBitmap;
/**
* Thumbnail object.
*
* @since S60 S60 v5.0
*/
NONSHARABLE_CLASS( MThumbnailData )
{
public:
/**
* Get a pointer to a CFbsBitmap containing the thumbnail image. Ownership
* of the object is not transferred (i.e. client must not delete the
* pointer).
*
* @since S60 v5.0
* @return Pointer to a bitmap representing the thumbnail or NULL if
* thumbnail pointer is not available or it has been detached.
*/
virtual CFbsBitmap* Bitmap() = 0;
/**
* Get a pointer to a CFbsBitmap containing the thumbnail image. Ownership
* of the object is transferred to the caller. Client must delete the
* bitmap after it is done processing it.
*
* @since S60 v5.0
* @return Pointer to a bitmap representing the thumbnail or NULL if
* thumbnail pointer is not available or it has been detached.
* Caller assumes ownership of the bitmap.
*/
virtual CFbsBitmap* DetachBitmap() = 0;
/**
* Get client data structure.
*
* @since S60 v5.0
* @return A pointer for client data specified as a parameter for
* GetThumbnailL() or NULL if not specified.
*/
virtual TAny* ClientData() = 0;
};
#endif // THUMBNAILDATA_H
|
//! # Utility Functions for Kernel Operations
//!
//! This module provides various utility functions essential for kernel operations,
//! including string manipulation, reading real-time clock data from CMOS, and performing hex dumps.
//! These functions are for handling shell input, displaying system time, and debugging.
use crate::shell::prints::PrintStackMode;
use crate::shell::{builtins::MAX_LINE_LENGTH, history::Line};
use crate::utils::io::{inb, outb};
use core::arch::asm;
const CMOS_ADDRESS: u16 = 0x70;
const CMOS_DATA: u16 = 0x71;
/// Compares two arrays of bytes.
pub fn array_cmp(a: &Line, b: &Line) -> bool {
a.iter().zip(b.iter()).all(|(&x, &y)| x == y)
}
/// Converts an array of bytes to a string slice.
pub fn array_to_str(arr: &Line) -> &str {
let len = arr.iter().position(|&c| c == 0).unwrap_or(arr.len());
core::str::from_utf8(&arr[..len]).unwrap_or_default()
}
/// Converts a string slice to an array of bytes.
pub fn str_to_array(s: &str) -> Line {
let mut line = [0; MAX_LINE_LENGTH];
for (i, c) in s.bytes().enumerate() {
line[i] = c;
}
line
}
/// Converts a Binary-Coded Decimal (BCD) to a binary representation.
pub fn bcd_to_binary(bcd: u8) -> u8 {
((bcd & 0xf0) >> 4) * 10 + (bcd & 0x0f)
}
/// Reads data from a CMOS register.
///
/// The CMOS is a special chip that stores real-time clock data, such as the current time and date.
/// The CMOS is accessed through I/O ports 0x70 and 0x71. The first port is used to specify the
/// register to read from, and the second port is used to read the data from the register.
///
/// # Safety
///
/// Directly accesses I/O ports, which can cause undefined behavior if misused.
pub fn read_cmos(register: u8) -> u8 {
unsafe {
outb(CMOS_ADDRESS, register);
inb(CMOS_DATA)
}
}
/// Retrieves the current real-time clock time from CMOS.
pub fn get_rtc_time() -> (u8, u8, u8) {
let seconds = bcd_to_binary(read_cmos(0x00));
let minutes = bcd_to_binary(read_cmos(0x02));
let hours = bcd_to_binary(read_cmos(0x04));
(hours, minutes, seconds)
}
/// Retrieves the current real-time clock date from CMOS.
pub fn get_rtc_date() -> (u8, u8, u8) {
let year = bcd_to_binary(read_cmos(0x09));
let month = bcd_to_binary(read_cmos(0x08));
let day = bcd_to_binary(read_cmos(0x07));
(year, month, day)
}
/// Halts the CPU until the next external interrupt.
#[inline]
pub fn hlt() {
unsafe {
asm!("hlt", options(nomem, nostack, preserves_flags));
}
}
/// Performs a hex dump starting from a given memory address.
pub fn hexdump(mut address: usize, limit: usize, mode: PrintStackMode) {
if limit == 0 {
return;
}
let bytes = unsafe { core::slice::from_raw_parts(address as *const u8, limit) };
for (i, &byte) in bytes.iter().enumerate() {
if i % 16 == 0 {
if i != 0 {
print_hex_line(address - 16, 16, mode);
match mode {
PrintStackMode::Vga => println!(""),
PrintStackMode::Serial => println_serial!(""),
}
}
match mode {
PrintStackMode::Vga => print!("{:08x} ", address),
PrintStackMode::Serial => print_serial!("{:08x} ", address),
}
}
if i % 8 == 0 {
match mode {
PrintStackMode::Vga => print!(" "),
PrintStackMode::Serial => print_serial!(" "),
}
}
match mode {
PrintStackMode::Vga => print!("{:02x} ", byte),
PrintStackMode::Serial => print_serial!("{:02x} ", byte),
}
address += 1;
}
let remaining = limit % 16;
if remaining > 0 {
// Pad the last line if necessary
let padding = 16 - remaining;
for _ in 0..padding {
match mode {
PrintStackMode::Vga => print!(" "),
PrintStackMode::Serial => print_serial!(" "),
}
}
if padding > 7 {
match mode {
PrintStackMode::Vga => print!(" "),
PrintStackMode::Serial => print_serial!(" "),
}
}
print_hex_line(address - remaining, remaining, mode);
} else {
print_hex_line(address - 16, 16, mode);
}
match mode {
PrintStackMode::Vga => println!(""),
PrintStackMode::Serial => println_serial!(""),
}
}
/// Helper function for printing a line in hex dump format.
fn print_hex_line(address: usize, count: usize, mode: PrintStackMode) {
let bytes = unsafe { core::slice::from_raw_parts(address as *const u8, count) };
match mode {
PrintStackMode::Vga => print!(" "),
PrintStackMode::Serial => print_serial!(" "),
}
// Print ASCII representation
for i in 0..count {
let ch = if bytes[i] >= 0x20 && bytes[i] <= 0x7e {
bytes[i] as char
} else {
'.'
};
match mode {
PrintStackMode::Vga => print!("{}", ch),
PrintStackMode::Serial => print_serial!("{}", ch),
}
}
}
|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.
*/
package com.android.inputmethod.latin;
import com.android.inputmethod.latin.LatinIMEUtil.RingCharBuffer;
import com.android.inputmethod.voice.FieldContext;
import com.android.inputmethod.voice.SettingsUtil;
import com.android.inputmethod.voice.VoiceInput;
import org.xmlpull.v1.XmlPullParserException;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.inputmethodservice.InputMethodService;
import android.inputmethodservice.Keyboard;
import android.media.AudioManager;
import android.os.Debug;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.speech.SpeechRecognizer;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Input method implementation for Qwerty'ish keyboard.
*/
public class LatinIME extends InputMethodService
implements LatinKeyboardBaseView.OnKeyboardActionListener,
VoiceInput.UiListener,
SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "LatinIME";
private static final boolean PERF_DEBUG = false;
static final boolean DEBUG = false;
static final boolean TRACE = false;
static final boolean VOICE_INSTALLED = true;
static final boolean ENABLE_VOICE_BUTTON = true;
private static final String PREF_VIBRATE_ON = "vibrate_on";
private static final String PREF_SOUND_ON = "sound_on";
private static final String PREF_POPUP_ON = "popup_on";
private static final String PREF_AUTO_CAP = "auto_cap";
private static final String PREF_QUICK_FIXES = "quick_fixes";
private static final String PREF_SHOW_SUGGESTIONS = "show_suggestions";
private static final String PREF_AUTO_COMPLETE = "auto_complete";
//private static final String PREF_BIGRAM_SUGGESTIONS = "bigram_suggestion";
private static final String PREF_VOICE_MODE = "voice_mode";
// Whether or not the user has used voice input before (and thus, whether to show the
// first-run warning dialog or not).
private static final String PREF_HAS_USED_VOICE_INPUT = "has_used_voice_input";
// Whether or not the user has used voice input from an unsupported locale UI before.
// For example, the user has a Chinese UI but activates voice input.
private static final String PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE =
"has_used_voice_input_unsupported_locale";
// A list of locales which are supported by default for voice input, unless we get a
// different list from Gservices.
public static final String DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES =
"en " +
"en_US " +
"en_GB " +
"en_AU " +
"en_CA " +
"en_IE " +
"en_IN " +
"en_NZ " +
"en_SG " +
"en_ZA ";
// The private IME option used to indicate that no microphone should be shown for a
// given text field. For instance this is specified by the search dialog when the
// dialog is already showing a voice search button.
private static final String IME_OPTION_NO_MICROPHONE = "nm";
public static final String PREF_SELECTED_LANGUAGES = "selected_languages";
public static final String PREF_INPUT_LANGUAGE = "input_language";
private static final String PREF_RECORRECTION_ENABLED = "recorrection_enabled";
private static final int MSG_UPDATE_SUGGESTIONS = 0;
private static final int MSG_START_TUTORIAL = 1;
private static final int MSG_UPDATE_SHIFT_STATE = 2;
private static final int MSG_VOICE_RESULTS = 3;
private static final int MSG_UPDATE_OLD_SUGGESTIONS = 4;
// How many continuous deletes at which to start deleting at a higher speed.
private static final int DELETE_ACCELERATE_AT = 20;
// Key events coming any faster than this are long-presses.
private static final int QUICK_PRESS = 200;
static final int KEYCODE_ENTER = '\n';
static final int KEYCODE_SPACE = ' ';
static final int KEYCODE_PERIOD = '.';
// Contextual menu positions
private static final int POS_METHOD = 0;
private static final int POS_SETTINGS = 1;
//private LatinKeyboardView mInputView;
private LinearLayout mCandidateViewContainer;
private CandidateView mCandidateView;
private Suggest mSuggest;
private CompletionInfo[] mCompletions;
private AlertDialog mOptionsDialog;
private AlertDialog mVoiceWarningDialog;
/* package */ KeyboardSwitcher mKeyboardSwitcher;
private UserDictionary mUserDictionary;
private UserBigramDictionary mUserBigramDictionary;
private ContactsDictionary mContactsDictionary;
private AutoDictionary mAutoDictionary;
private Hints mHints;
private Resources mResources;
private String mInputLocale;
private String mSystemLocale;
private LanguageSwitcher mLanguageSwitcher;
private StringBuilder mComposing = new StringBuilder();
private WordComposer mWord = new WordComposer();
private int mCommittedLength;
private boolean mPredicting;
private boolean mRecognizing;
private boolean mAfterVoiceInput;
private boolean mImmediatelyAfterVoiceInput;
private boolean mShowingVoiceSuggestions;
private boolean mVoiceInputHighlighted;
private boolean mEnableVoiceButton;
private CharSequence mBestWord;
private boolean mPredictionOn;
private boolean mCompletionOn;
private boolean mHasDictionary;
private boolean mAutoSpace;
private boolean mJustAddedAutoSpace;
private boolean mAutoCorrectEnabled;
private boolean mReCorrectionEnabled;
// Bigram Suggestion is disabled in this version.
private final boolean mBigramSuggestionEnabled = false;
private boolean mAutoCorrectOn;
// TODO move this state variable outside LatinIME
private boolean mCapsLock;
private boolean mPasswordText;
private boolean mVibrateOn;
private boolean mSoundOn;
private boolean mPopupOn;
private boolean mAutoCap;
private boolean mQuickFixes;
private boolean mHasUsedVoiceInput;
private boolean mHasUsedVoiceInputUnsupportedLocale;
private boolean mLocaleSupportedForVoiceInput;
private boolean mShowSuggestions;
private boolean mIsShowingHint;
private int mCorrectionMode;
private boolean mEnableVoice = true;
private boolean mVoiceOnPrimary;
private int mOrientation;
private List<CharSequence> mSuggestPuncList;
// Keep track of the last selection range to decide if we need to show word alternatives
private int mLastSelectionStart;
private int mLastSelectionEnd;
// Input type is such that we should not auto-correct
private boolean mInputTypeNoAutoCorrect;
// Indicates whether the suggestion strip is to be on in landscape
private boolean mJustAccepted;
private CharSequence mJustRevertedSeparator;
private int mDeleteCount;
private long mLastKeyTime;
// Modifier keys state
private ModifierKeyState mShiftKeyState = new ModifierKeyState();
private ModifierKeyState mSymbolKeyState = new ModifierKeyState();
private Tutorial mTutorial;
private AudioManager mAudioManager;
// Align sound effect volume on music volume
private final float FX_VOLUME = -1.0f;
private boolean mSilentMode;
/* package */ String mWordSeparators;
private String mSentenceSeparators;
private String mSuggestPuncs;
private VoiceInput mVoiceInput;
private VoiceResults mVoiceResults = new VoiceResults();
private boolean mConfigurationChanging;
// Keeps track of most recently inserted text (multi-character key) for reverting
private CharSequence mEnteredText;
private boolean mRefreshKeyboardRequired;
// For each word, a list of potential replacements, usually from voice.
private Map<String, List<CharSequence>> mWordToSuggestions =
new HashMap<String, List<CharSequence>>();
private ArrayList<WordAlternatives> mWordHistory = new ArrayList<WordAlternatives>();
private class VoiceResults {
List<String> candidates;
Map<String, List<CharSequence>> alternatives;
}
public abstract static class WordAlternatives {
protected CharSequence mChosenWord;
public WordAlternatives() {
// Nothing
}
public WordAlternatives(CharSequence chosenWord) {
mChosenWord = chosenWord;
}
@Override
public int hashCode() {
return mChosenWord.hashCode();
}
public abstract CharSequence getOriginalWord();
public CharSequence getChosenWord() {
return mChosenWord;
}
public abstract List<CharSequence> getAlternatives();
}
public class TypedWordAlternatives extends WordAlternatives {
private WordComposer word;
public TypedWordAlternatives() {
// Nothing
}
public TypedWordAlternatives(CharSequence chosenWord, WordComposer wordComposer) {
super(chosenWord);
word = wordComposer;
}
@Override
public CharSequence getOriginalWord() {
return word.getTypedWord();
}
@Override
public List<CharSequence> getAlternatives() {
return getTypedSuggestions(word);
}
}
/* package */ Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_SUGGESTIONS:
updateSuggestions();
break;
case MSG_UPDATE_OLD_SUGGESTIONS:
setOldSuggestions();
break;
case MSG_START_TUTORIAL:
if (mTutorial == null) {
if (mKeyboardSwitcher.getInputView().isShown()) {
mTutorial = new Tutorial(
LatinIME.this, mKeyboardSwitcher.getInputView());
mTutorial.start();
} else {
// Try again soon if the view is not yet showing
sendMessageDelayed(obtainMessage(MSG_START_TUTORIAL), 100);
}
}
break;
case MSG_UPDATE_SHIFT_STATE:
updateShiftKeyState(getCurrentInputEditorInfo());
break;
case MSG_VOICE_RESULTS:
handleVoiceResults();
break;
}
}
};
@Override
public void onCreate() {
LatinImeLogger.init(this);
KeyboardSwitcher.init(this);
super.onCreate();
//setStatusIcon(R.drawable.ime_qwerty);
mResources = getResources();
final Configuration conf = mResources.getConfiguration();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mLanguageSwitcher = new LanguageSwitcher(this);
mLanguageSwitcher.loadLocales(prefs);
mKeyboardSwitcher = KeyboardSwitcher.getInstance();
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
mSystemLocale = conf.locale.toString();
mLanguageSwitcher.setSystemLocale(conf.locale);
String inputLanguage = mLanguageSwitcher.getInputLanguage();
if (inputLanguage == null) {
inputLanguage = conf.locale.toString();
}
mReCorrectionEnabled = prefs.getBoolean(PREF_RECORRECTION_ENABLED,
getResources().getBoolean(R.bool.default_recorrection_enabled));
LatinIMEUtil.GCUtils.getInstance().reset();
boolean tryGC = true;
for (int i = 0; i < LatinIMEUtil.GCUtils.GC_TRY_LOOP_MAX && tryGC; ++i) {
try {
initSuggest(inputLanguage);
tryGC = false;
} catch (OutOfMemoryError e) {
tryGC = LatinIMEUtil.GCUtils.getInstance().tryGCOrWait(inputLanguage, e);
}
}
mOrientation = conf.orientation;
initSuggestPuncList();
// register to receive ringer mode changes for silent mode
IntentFilter filter = new IntentFilter(AudioManager.RINGER_MODE_CHANGED_ACTION);
registerReceiver(mReceiver, filter);
if (VOICE_INSTALLED) {
mVoiceInput = new VoiceInput(this, this);
mHints = new Hints(this, new Hints.Display() {
public void showHint(int viewResource) {
LayoutInflater inflater = (LayoutInflater) getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(viewResource, null);
setCandidatesView(view);
setCandidatesViewShown(true);
mIsShowingHint = true;
}
});
}
prefs.registerOnSharedPreferenceChangeListener(this);
}
/**
* Loads a dictionary or multiple separated dictionary
* @return returns array of dictionary resource ids
*/
/* package */ static int[] getDictionary(Resources res) {
String packageName = LatinIME.class.getPackage().getName();
XmlResourceParser xrp = res.getXml(R.xml.dictionary);
ArrayList<Integer> dictionaries = new ArrayList<Integer>();
try {
int current = xrp.getEventType();
while (current != XmlResourceParser.END_DOCUMENT) {
if (current == XmlResourceParser.START_TAG) {
String tag = xrp.getName();
if (tag != null) {
if (tag.equals("part")) {
String dictFileName = xrp.getAttributeValue(null, "name");
dictionaries.add(res.getIdentifier(dictFileName, "raw", packageName));
}
}
}
xrp.next();
current = xrp.getEventType();
}
} catch (XmlPullParserException e) {
Log.e(TAG, "Dictionary XML parsing failure");
} catch (IOException e) {
Log.e(TAG, "Dictionary XML IOException");
}
int count = dictionaries.size();
int[] dict = new int[count];
for (int i = 0; i < count; i++) {
dict[i] = dictionaries.get(i);
}
return dict;
}
private void initSuggest(String locale) {
mInputLocale = locale;
Resources orig = getResources();
Configuration conf = orig.getConfiguration();
Locale saveLocale = conf.locale;
conf.locale = new Locale(locale);
orig.updateConfiguration(conf, orig.getDisplayMetrics());
if (mSuggest != null) {
mSuggest.close();
}
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true);
int[] dictionaries = getDictionary(orig);
mSuggest = new Suggest(this, dictionaries);
updateAutoTextEnabled(saveLocale);
if (mUserDictionary != null) mUserDictionary.close();
mUserDictionary = new UserDictionary(this, mInputLocale);
if (mContactsDictionary == null) {
mContactsDictionary = new ContactsDictionary(this, Suggest.DIC_CONTACTS);
}
if (mAutoDictionary != null) {
mAutoDictionary.close();
}
mAutoDictionary = new AutoDictionary(this, this, mInputLocale, Suggest.DIC_AUTO);
if (mUserBigramDictionary != null) {
mUserBigramDictionary.close();
}
mUserBigramDictionary = new UserBigramDictionary(this, this, mInputLocale,
Suggest.DIC_USER);
mSuggest.setUserBigramDictionary(mUserBigramDictionary);
mSuggest.setUserDictionary(mUserDictionary);
mSuggest.setContactsDictionary(mContactsDictionary);
mSuggest.setAutoDictionary(mAutoDictionary);
updateCorrectionMode();
mWordSeparators = mResources.getString(R.string.word_separators);
mSentenceSeparators = mResources.getString(R.string.sentence_separators);
conf.locale = saveLocale;
orig.updateConfiguration(conf, orig.getDisplayMetrics());
}
@Override
public void onDestroy() {
if (mUserDictionary != null) {
mUserDictionary.close();
}
if (mContactsDictionary != null) {
mContactsDictionary.close();
}
unregisterReceiver(mReceiver);
if (VOICE_INSTALLED && mVoiceInput != null) {
mVoiceInput.destroy();
}
LatinImeLogger.commit();
LatinImeLogger.onDestroy();
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration conf) {
// If the system locale changes and is different from the saved
// locale (mSystemLocale), then reload the input locale list from the
// latin ime settings (shared prefs) and reset the input locale
// to the first one.
final String systemLocale = conf.locale.toString();
if (!TextUtils.equals(systemLocale, mSystemLocale)) {
mSystemLocale = systemLocale;
if (mLanguageSwitcher != null) {
mLanguageSwitcher.loadLocales(
PreferenceManager.getDefaultSharedPreferences(this));
mLanguageSwitcher.setSystemLocale(conf.locale);
toggleLanguage(true, true);
} else {
reloadKeyboards();
}
}
// If orientation changed while predicting, commit the change
if (conf.orientation != mOrientation) {
InputConnection ic = getCurrentInputConnection();
commitTyped(ic);
if (ic != null) ic.finishComposingText(); // For voice input
mOrientation = conf.orientation;
reloadKeyboards();
}
mConfigurationChanging = true;
super.onConfigurationChanged(conf);
if (mRecognizing) {
switchToRecognitionStatusView();
}
mConfigurationChanging = false;
}
@Override
public View onCreateInputView() {
mKeyboardSwitcher.recreateInputView();
mKeyboardSwitcher.makeKeyboards(true);
mKeyboardSwitcher.setKeyboardMode(
KeyboardSwitcher.MODE_TEXT, 0,
shouldShowVoiceButton(makeFieldContext(), getCurrentInputEditorInfo()));
return mKeyboardSwitcher.getInputView();
}
@Override
public View onCreateCandidatesView() {
mKeyboardSwitcher.makeKeyboards(true);
mCandidateViewContainer = (LinearLayout) getLayoutInflater().inflate(
R.layout.candidates, null);
mCandidateView = (CandidateView) mCandidateViewContainer.findViewById(R.id.candidates);
mCandidateView.setService(this);
setCandidatesViewShown(true);
return mCandidateViewContainer;
}
@Override
public void onStartInputView(EditorInfo attribute, boolean restarting) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
// In landscape mode, this method gets called without the input view being created.
if (inputView == null) {
return;
}
if (mRefreshKeyboardRequired) {
mRefreshKeyboardRequired = false;
toggleLanguage(true, true);
}
mKeyboardSwitcher.makeKeyboards(false);
TextEntryState.newSession(this);
// Most such things we decide below in the switch statement, but we need to know
// now whether this is a password text field, because we need to know now (before
// the switch statement) whether we want to enable the voice button.
mPasswordText = false;
int variation = attribute.inputType & EditorInfo.TYPE_MASK_VARIATION;
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
mPasswordText = true;
}
mEnableVoiceButton = shouldShowVoiceButton(makeFieldContext(), attribute);
final boolean enableVoiceButton = mEnableVoiceButton && mEnableVoice;
mAfterVoiceInput = false;
mImmediatelyAfterVoiceInput = false;
mShowingVoiceSuggestions = false;
mVoiceInputHighlighted = false;
mInputTypeNoAutoCorrect = false;
mPredictionOn = false;
mCompletionOn = false;
mCompletions = null;
mCapsLock = false;
mEnteredText = null;
switch (attribute.inputType & EditorInfo.TYPE_MASK_CLASS) {
case EditorInfo.TYPE_CLASS_NUMBER:
case EditorInfo.TYPE_CLASS_DATETIME:
// fall through
// NOTE: For now, we use the phone keyboard for NUMBER and DATETIME until we get
// a dedicated number entry keypad.
// TODO: Use a dedicated number entry keypad here when we get one.
case EditorInfo.TYPE_CLASS_PHONE:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_PHONE,
attribute.imeOptions, enableVoiceButton);
break;
case EditorInfo.TYPE_CLASS_TEXT:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
//startPrediction();
mPredictionOn = true;
// Make sure that passwords are not displayed in candidate view
if (variation == EditorInfo.TYPE_TEXT_VARIATION_PASSWORD ||
variation == EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD ) {
mPredictionOn = false;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS
|| variation == EditorInfo.TYPE_TEXT_VARIATION_PERSON_NAME) {
mAutoSpace = false;
} else {
mAutoSpace = true;
}
if (variation == EditorInfo.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_EMAIL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_URI) {
mPredictionOn = false;
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_URL,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_SHORT_MESSAGE) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_IM,
attribute.imeOptions, enableVoiceButton);
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_FILTER) {
mPredictionOn = false;
} else if (variation == EditorInfo.TYPE_TEXT_VARIATION_WEB_EDIT_TEXT) {
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_WEB,
attribute.imeOptions, enableVoiceButton);
// If it's a browser edit field and auto correct is not ON explicitly, then
// disable auto correction, but keep suggestions on.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0) {
mInputTypeNoAutoCorrect = true;
}
}
// If NO_SUGGESTIONS is set, don't do prediction.
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_NO_SUGGESTIONS) != 0) {
mPredictionOn = false;
mInputTypeNoAutoCorrect = true;
}
// If it's not multiline and the autoCorrect flag is not set, then don't correct
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_CORRECT) == 0 &&
(attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_MULTI_LINE) == 0) {
mInputTypeNoAutoCorrect = true;
}
if ((attribute.inputType & EditorInfo.TYPE_TEXT_FLAG_AUTO_COMPLETE) != 0) {
mPredictionOn = false;
mCompletionOn = isFullscreenMode();
}
break;
default:
mKeyboardSwitcher.setKeyboardMode(KeyboardSwitcher.MODE_TEXT,
attribute.imeOptions, enableVoiceButton);
}
inputView.closing();
mComposing.setLength(0);
mPredicting = false;
mDeleteCount = 0;
mJustAddedAutoSpace = false;
loadSettings();
updateShiftKeyState(attribute);
setCandidatesViewShownInternal(isCandidateStripVisible() || mCompletionOn,
false /* needsInputViewShown */ );
updateSuggestions();
// If the dictionary is not big enough, don't auto correct
mHasDictionary = mSuggest.hasMainDictionary();
updateCorrectionMode();
inputView.setPreviewEnabled(mPopupOn);
inputView.setProximityCorrectionEnabled(true);
mPredictionOn = mPredictionOn && (mCorrectionMode > 0 || mShowSuggestions);
// If we just entered a text field, maybe it has some old text that requires correction
checkReCorrectionOnStart();
checkTutorial(attribute.privateImeOptions);
if (TRACE) Debug.startMethodTracing("/data/trace/latinime");
}
private void checkReCorrectionOnStart() {
if (mReCorrectionEnabled && isPredictionOn()) {
// First get the cursor position. This is required by setOldSuggestions(), so that
// it can pass the correct range to setComposingRegion(). At this point, we don't
// have valid values for mLastSelectionStart/Stop because onUpdateSelection() has
// not been called yet.
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ExtractedTextRequest etr = new ExtractedTextRequest();
etr.token = 0; // anything is fine here
ExtractedText et = ic.getExtractedText(etr, 0);
if (et == null) return;
mLastSelectionStart = et.startOffset + et.selectionStart;
mLastSelectionEnd = et.startOffset + et.selectionEnd;
// Then look for possible corrections in a delayed fashion
if (!TextUtils.isEmpty(et.text) && isCursorTouchingWord()) {
postUpdateOldSuggestions();
}
}
}
@Override
public void onFinishInput() {
super.onFinishInput();
LatinImeLogger.commit();
onAutoCompletionStateChanged(false);
if (VOICE_INSTALLED && !mConfigurationChanging) {
if (mAfterVoiceInput) {
mVoiceInput.flushAllTextModificationCounters();
mVoiceInput.logInputEnded();
}
mVoiceInput.flushLogs();
mVoiceInput.cancel();
}
if (mKeyboardSwitcher.getInputView() != null) {
mKeyboardSwitcher.getInputView().closing();
}
if (mAutoDictionary != null) mAutoDictionary.flushPendingWrites();
if (mUserBigramDictionary != null) mUserBigramDictionary.flushPendingWrites();
}
@Override
public void onFinishInputView(boolean finishingInput) {
super.onFinishInputView(finishingInput);
// Remove penging messages related to update suggestions
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
mHandler.removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
}
@Override
public void onUpdateExtractedText(int token, ExtractedText text) {
super.onUpdateExtractedText(token, text);
InputConnection ic = getCurrentInputConnection();
if (!mImmediatelyAfterVoiceInput && mAfterVoiceInput && ic != null) {
if (mHints.showPunctuationHintIfNecessary(ic)) {
mVoiceInput.logPunctuationHintDisplayed();
}
}
mImmediatelyAfterVoiceInput = false;
}
@Override
public void onUpdateSelection(int oldSelStart, int oldSelEnd,
int newSelStart, int newSelEnd,
int candidatesStart, int candidatesEnd) {
super.onUpdateSelection(oldSelStart, oldSelEnd, newSelStart, newSelEnd,
candidatesStart, candidatesEnd);
if (DEBUG) {
Log.i(TAG, "onUpdateSelection: oss=" + oldSelStart
+ ", ose=" + oldSelEnd
+ ", nss=" + newSelStart
+ ", nse=" + newSelEnd
+ ", cs=" + candidatesStart
+ ", ce=" + candidatesEnd);
}
if (mAfterVoiceInput) {
mVoiceInput.setCursorPos(newSelEnd);
mVoiceInput.setSelectionSpan(newSelEnd - newSelStart);
}
// If the current selection in the text view changes, we should
// clear whatever candidate text we have.
if ((((mComposing.length() > 0 && mPredicting) || mVoiceInputHighlighted)
&& (newSelStart != candidatesEnd
|| newSelEnd != candidatesEnd)
&& mLastSelectionStart != newSelStart)) {
mComposing.setLength(0);
mPredicting = false;
postUpdateSuggestions();
TextEntryState.reset();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.finishComposingText();
}
mVoiceInputHighlighted = false;
} else if (!mPredicting && !mJustAccepted) {
switch (TextEntryState.getState()) {
case ACCEPTED_DEFAULT:
TextEntryState.reset();
// fall through
case SPACE_AFTER_PICKED:
mJustAddedAutoSpace = false; // The user moved the cursor.
break;
}
}
mJustAccepted = false;
postUpdateShiftKeyState();
// Make a note of the cursor position
mLastSelectionStart = newSelStart;
mLastSelectionEnd = newSelEnd;
if (mReCorrectionEnabled) {
// Don't look for corrections if the keyboard is not visible
if (mKeyboardSwitcher != null && mKeyboardSwitcher.getInputView() != null
&& mKeyboardSwitcher.getInputView().isShown()) {
// Check if we should go in or out of correction mode.
if (isPredictionOn()
&& mJustRevertedSeparator == null
&& (candidatesStart == candidatesEnd || newSelStart != oldSelStart
|| TextEntryState.isCorrecting())
&& (newSelStart < newSelEnd - 1 || (!mPredicting))
&& !mVoiceInputHighlighted) {
if (isCursorTouchingWord() || mLastSelectionStart < mLastSelectionEnd) {
postUpdateOldSuggestions();
} else {
abortCorrection(false);
// Show the punctuation suggestions list if the current one is not
// and if not showing "Touch again to save".
if (mCandidateView != null
&& !mSuggestPuncList.equals(mCandidateView.getSuggestions())
&& !mCandidateView.isShowingAddToDictionaryHint()) {
setNextSuggestions();
}
}
}
}
}
}
/**
* This is called when the user has clicked on the extracted text view,
* when running in fullscreen mode. The default implementation hides
* the candidates view when this happens, but only if the extracted text
* editor has a vertical scroll bar because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedTextClicked() {
if (mReCorrectionEnabled && isPredictionOn()) return;
super.onExtractedTextClicked();
}
/**
* This is called when the user has performed a cursor movement in the
* extracted text view, when it is running in fullscreen mode. The default
* implementation hides the candidates view when a vertical movement
* happens, but only if the extracted text editor has a vertical scroll bar
* because its text doesn't fit.
* Here we override the behavior due to the possibility that a re-correction could
* cause the candidate strip to disappear and re-appear.
*/
@Override
public void onExtractedCursorMovement(int dx, int dy) {
if (mReCorrectionEnabled && isPredictionOn()) return;
super.onExtractedCursorMovement(dx, dy);
}
@Override
public void hideWindow() {
LatinImeLogger.commit();
onAutoCompletionStateChanged(false);
if (TRACE) Debug.stopMethodTracing();
if (mOptionsDialog != null && mOptionsDialog.isShowing()) {
mOptionsDialog.dismiss();
mOptionsDialog = null;
}
if (!mConfigurationChanging) {
if (mAfterVoiceInput) mVoiceInput.logInputEnded();
if (mVoiceWarningDialog != null && mVoiceWarningDialog.isShowing()) {
mVoiceInput.logKeyboardWarningDialogDismissed();
mVoiceWarningDialog.dismiss();
mVoiceWarningDialog = null;
}
if (VOICE_INSTALLED & mRecognizing) {
mVoiceInput.cancel();
}
}
mWordToSuggestions.clear();
mWordHistory.clear();
super.hideWindow();
TextEntryState.endSession();
}
@Override
public void onDisplayCompletions(CompletionInfo[] completions) {
if (DEBUG) {
Log.i("foo", "Received completions:");
for (int i=0; i<(completions != null ? completions.length : 0); i++) {
Log.i("foo", " #" + i + ": " + completions[i]);
}
}
if (mCompletionOn) {
mCompletions = completions;
if (completions == null) {
clearSuggestions();
return;
}
List<CharSequence> stringList = new ArrayList<CharSequence>();
for (int i=0; i<(completions != null ? completions.length : 0); i++) {
CompletionInfo ci = completions[i];
if (ci != null) stringList.add(ci.getText());
}
// When in fullscreen mode, show completions generated by the application
setSuggestions(stringList, true, true, true);
mBestWord = null;
setCandidatesViewShown(true);
}
}
private void setCandidatesViewShownInternal(boolean shown, boolean needsInputViewShown) {
// TODO: Remove this if we support candidates with hard keyboard
if (onEvaluateInputViewShown()) {
super.setCandidatesViewShown(shown && mKeyboardSwitcher.getInputView() != null
&& (needsInputViewShown ? mKeyboardSwitcher.getInputView().isShown() : true));
}
}
@Override
public void setCandidatesViewShown(boolean shown) {
setCandidatesViewShownInternal(shown, true /* needsInputViewShown */ );
}
@Override
public void onComputeInsets(InputMethodService.Insets outInsets) {
super.onComputeInsets(outInsets);
if (!isFullscreenMode()) {
outInsets.contentTopInsets = outInsets.visibleTopInsets;
}
}
@Override
public boolean onEvaluateFullscreenMode() {
DisplayMetrics dm = getResources().getDisplayMetrics();
float displayHeight = dm.heightPixels;
// If the display is more than X inches high, don't go to fullscreen mode
float dimen = getResources().getDimension(R.dimen.max_height_for_fullscreen);
if (displayHeight > dimen) {
return false;
} else {
return super.onEvaluateFullscreenMode();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (event.getRepeatCount() == 0 && mKeyboardSwitcher.getInputView() != null) {
if (mKeyboardSwitcher.getInputView().handleBack()) {
return true;
} else if (mTutorial != null) {
mTutorial.close();
mTutorial = null;
}
}
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_RIGHT:
// If tutorial is visible, don't allow dpad to work
if (mTutorial != null) {
return true;
}
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
// Enable shift key and DPAD to do selections
if (inputView != null && inputView.isShown()
&& inputView.isShifted()) {
event = new KeyEvent(event.getDownTime(), event.getEventTime(),
event.getAction(), event.getKeyCode(), event.getRepeatCount(),
event.getDeviceId(), event.getScanCode(),
KeyEvent.META_SHIFT_LEFT_ON | KeyEvent.META_SHIFT_ON);
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.sendKeyEvent(event);
return true;
}
break;
}
return super.onKeyUp(keyCode, event);
}
private void revertVoiceInput() {
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.commitText("", 1);
updateSuggestions();
mVoiceInputHighlighted = false;
}
private void commitVoiceInput() {
InputConnection ic = getCurrentInputConnection();
if (ic != null) ic.finishComposingText();
updateSuggestions();
mVoiceInputHighlighted = false;
}
private void reloadKeyboards() {
mKeyboardSwitcher.setLanguageSwitcher(mLanguageSwitcher);
if (mKeyboardSwitcher.getInputView() != null
&& mKeyboardSwitcher.getKeyboardMode() != KeyboardSwitcher.MODE_NONE) {
mKeyboardSwitcher.setVoiceMode(mEnableVoice && mEnableVoiceButton, mVoiceOnPrimary);
}
mKeyboardSwitcher.makeKeyboards(true);
}
private void commitTyped(InputConnection inputConnection) {
if (mPredicting) {
mPredicting = false;
if (mComposing.length() > 0) {
if (inputConnection != null) {
inputConnection.commitText(mComposing, 1);
}
mCommittedLength = mComposing.length();
TextEntryState.acceptedTyped(mComposing);
addToDictionaries(mComposing, AutoDictionary.FREQUENCY_FOR_TYPED);
}
updateSuggestions();
}
}
private void postUpdateShiftKeyState() {
mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
// TODO: Should remove this 300ms delay?
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SHIFT_STATE), 300);
}
public void updateShiftKeyState(EditorInfo attr) {
InputConnection ic = getCurrentInputConnection();
if (ic != null && attr != null && mKeyboardSwitcher.isAlphabetMode()) {
mKeyboardSwitcher.setShifted(mShiftKeyState.isMomentary() || mCapsLock
|| getCursorCapsMode(ic, attr) != 0);
}
}
private int getCursorCapsMode(InputConnection ic, EditorInfo attr) {
int caps = 0;
EditorInfo ei = getCurrentInputEditorInfo();
if (mAutoCap && ei != null && ei.inputType != EditorInfo.TYPE_NULL) {
caps = ic.getCursorCapsMode(attr.inputType);
}
return caps;
}
private void swapPunctuationAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastTwo = ic.getTextBeforeCursor(2, 0);
if (lastTwo != null && lastTwo.length() == 2
&& lastTwo.charAt(0) == KEYCODE_SPACE && isSentenceSeparator(lastTwo.charAt(1))) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(lastTwo.charAt(1) + " ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void reswapPeriodAndSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& lastThree.charAt(0) == KEYCODE_PERIOD
&& lastThree.charAt(1) == KEYCODE_SPACE
&& lastThree.charAt(2) == KEYCODE_PERIOD) {
ic.beginBatchEdit();
ic.deleteSurroundingText(3, 0);
ic.commitText(" ..", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
}
}
private void doubleSpace() {
//if (!mAutoPunctuate) return;
if (mCorrectionMode == Suggest.CORRECTION_NONE) return;
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastThree = ic.getTextBeforeCursor(3, 0);
if (lastThree != null && lastThree.length() == 3
&& Character.isLetterOrDigit(lastThree.charAt(0))
&& lastThree.charAt(1) == KEYCODE_SPACE && lastThree.charAt(2) == KEYCODE_SPACE) {
ic.beginBatchEdit();
ic.deleteSurroundingText(2, 0);
ic.commitText(". ", 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mJustAddedAutoSpace = true;
}
}
private void maybeRemovePreviousPeriod(CharSequence text) {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
// When the text's first character is '.', remove the previous period
// if there is one.
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == KEYCODE_PERIOD
&& text.charAt(0) == KEYCODE_PERIOD) {
ic.deleteSurroundingText(1, 0);
}
}
private void removeTrailingSpace() {
final InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
CharSequence lastOne = ic.getTextBeforeCursor(1, 0);
if (lastOne != null && lastOne.length() == 1
&& lastOne.charAt(0) == KEYCODE_SPACE) {
ic.deleteSurroundingText(1, 0);
}
}
public boolean addWordToDictionary(String word) {
mUserDictionary.addWord(word, 128);
// Suggestion strip should be updated after the operation of adding word to the
// user dictionary
postUpdateSuggestions();
return true;
}
private boolean isAlphabet(int code) {
if (Character.isLetter(code)) {
return true;
} else {
return false;
}
}
private void showInputMethodPicker() {
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showInputMethodPicker();
}
private void onOptionKeyPressed() {
if (!isShowingOptionDialog()) {
if (LatinIMEUtil.hasMultipleEnabledIMEs(this)) {
showOptionsMenu();
} else {
launchSettings();
}
}
}
private void onOptionKeyLongPressed() {
if (!isShowingOptionDialog()) {
if (LatinIMEUtil.hasMultipleEnabledIMEs(this)) {
showInputMethodPicker();
} else {
launchSettings();
}
}
}
private boolean isShowingOptionDialog() {
return mOptionsDialog != null && mOptionsDialog.isShowing();
}
// Implementation of KeyboardViewListener
public void onKey(int primaryCode, int[] keyCodes, int x, int y) {
long when = SystemClock.uptimeMillis();
if (primaryCode != Keyboard.KEYCODE_DELETE ||
when > mLastKeyTime + QUICK_PRESS) {
mDeleteCount = 0;
}
mLastKeyTime = when;
final boolean distinctMultiTouch = mKeyboardSwitcher.hasDistinctMultitouch();
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
handleBackspace();
mDeleteCount++;
LatinImeLogger.logOnDelete();
break;
case Keyboard.KEYCODE_SHIFT:
// Shift key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch)
handleShift();
break;
case Keyboard.KEYCODE_MODE_CHANGE:
// Symbol key is handled in onPress() when device has distinct multi-touch panel.
if (!distinctMultiTouch)
changeKeyboardMode();
break;
case Keyboard.KEYCODE_CANCEL:
if (!isShowingOptionDialog()) {
handleClose();
}
break;
case LatinKeyboardView.KEYCODE_OPTIONS:
onOptionKeyPressed();
break;
case LatinKeyboardView.KEYCODE_OPTIONS_LONGPRESS:
onOptionKeyLongPressed();
break;
case LatinKeyboardView.KEYCODE_NEXT_LANGUAGE:
toggleLanguage(false, true);
break;
case LatinKeyboardView.KEYCODE_PREV_LANGUAGE:
toggleLanguage(false, false);
break;
case LatinKeyboardView.KEYCODE_VOICE:
if (VOICE_INSTALLED) {
startListening(false /* was a button press, was not a swipe */);
}
break;
case 9 /*Tab*/:
sendDownUpKeyEvents(KeyEvent.KEYCODE_TAB);
break;
default:
if (primaryCode != KEYCODE_ENTER) {
mJustAddedAutoSpace = false;
}
RingCharBuffer.getInstance().push((char)primaryCode, x, y);
LatinImeLogger.logOnInputChar();
if (isWordSeparator(primaryCode)) {
handleSeparator(primaryCode);
} else {
handleCharacter(primaryCode, keyCodes);
}
// Cancel the just reverted state
mJustRevertedSeparator = null;
}
mKeyboardSwitcher.onKey(primaryCode);
// Reset after any single keystroke
mEnteredText = null;
}
public void onText(CharSequence text) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
abortCorrection(false);
ic.beginBatchEdit();
if (mPredicting) {
commitTyped(ic);
}
maybeRemovePreviousPeriod(text);
ic.commitText(text, 1);
ic.endBatchEdit();
updateShiftKeyState(getCurrentInputEditorInfo());
mKeyboardSwitcher.onKey(0); // dummy key code.
mJustRevertedSeparator = null;
mJustAddedAutoSpace = false;
mEnteredText = text;
}
public void onCancel() {
// User released a finger outside any key
mKeyboardSwitcher.onCancelInput();
}
private void handleBackspace() {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
mVoiceInput.incrementTextModificationDeleteCount(
mVoiceResults.candidates.get(0).toString().length());
revertVoiceInput();
return;
}
boolean deleteChar = false;
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
ic.beginBatchEdit();
if (mAfterVoiceInput) {
// Don't log delete if the user is pressing delete at
// the beginning of the text box (hence not deleting anything)
if (mVoiceInput.getCursorPos() > 0) {
// If anything was selected before the delete was pressed, increment the
// delete count by the length of the selection
int deleteLen = mVoiceInput.getSelectionSpan() > 0 ?
mVoiceInput.getSelectionSpan() : 1;
mVoiceInput.incrementTextModificationDeleteCount(deleteLen);
}
}
if (mPredicting) {
final int length = mComposing.length();
if (length > 0) {
mComposing.delete(length - 1, length);
mWord.deleteLast();
ic.setComposingText(mComposing, 1);
if (mComposing.length() == 0) {
mPredicting = false;
}
postUpdateSuggestions();
} else {
ic.deleteSurroundingText(1, 0);
}
} else {
deleteChar = true;
}
postUpdateShiftKeyState();
TextEntryState.backspace();
if (TextEntryState.getState() == TextEntryState.State.UNDO_COMMIT) {
revertLastWord(deleteChar);
ic.endBatchEdit();
return;
} else if (mEnteredText != null && sameAsTextBeforeCursor(ic, mEnteredText)) {
ic.deleteSurroundingText(mEnteredText.length(), 0);
} else if (deleteChar) {
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
// Go back to the suggestion mode if the user canceled the
// "Touch again to save".
// NOTE: In gerenal, we don't revert the word when backspacing
// from a manual suggestion pick. We deliberately chose a
// different behavior only in the case of picking the first
// suggestion (typed word). It's intentional to have made this
// inconsistent with backspacing after selecting other suggestions.
revertLastWord(deleteChar);
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
if (mDeleteCount > DELETE_ACCELERATE_AT) {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
}
}
}
mJustRevertedSeparator = null;
ic.endBatchEdit();
}
private void resetShift() {
handleShiftInternal(true);
}
private void handleShift() {
handleShiftInternal(false);
}
private void handleShiftInternal(boolean forceNormal) {
mHandler.removeMessages(MSG_UPDATE_SHIFT_STATE);
KeyboardSwitcher switcher = mKeyboardSwitcher;
LatinKeyboardView inputView = switcher.getInputView();
if (switcher.isAlphabetMode()) {
if (mCapsLock || forceNormal) {
mCapsLock = false;
switcher.setShifted(false);
} else if (inputView != null) {
if (inputView.isShifted()) {
mCapsLock = true;
switcher.setShiftLocked(true);
} else {
switcher.setShifted(true);
}
}
} else {
switcher.toggleShift();
}
}
private void abortCorrection(boolean force) {
if (force || TextEntryState.isCorrecting()) {
getCurrentInputConnection().finishComposingText();
clearSuggestions();
}
}
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
if (mAfterVoiceInput) {
// Assume input length is 1. This assumption fails for smiley face insertions.
mVoiceInput.incrementTextModificationInsertCount(1);
}
if (mLastSelectionStart == mLastSelectionEnd && TextEntryState.isCorrecting()) {
abortCorrection(false);
}
if (isAlphabet(primaryCode) && isPredictionOn() && !isCursorTouchingWord()) {
if (!mPredicting) {
mPredicting = true;
mComposing.setLength(0);
saveWordInHistory(mBestWord);
mWord.reset();
}
}
if (mKeyboardSwitcher.getInputView().isShifted()) {
if (keyCodes == null || keyCodes[0] < Character.MIN_CODE_POINT
|| keyCodes[0] > Character.MAX_CODE_POINT) {
return;
}
primaryCode = keyCodes[0];
if (mKeyboardSwitcher.isAlphabetMode() && Character.isLowerCase(primaryCode)) {
int upperCaseCode = Character.toUpperCase(primaryCode);
if (upperCaseCode != primaryCode) {
primaryCode = upperCaseCode;
} else {
// Some keys, such as [eszett], have upper case as multi-characters.
String upperCase = new String(new int[] {primaryCode}, 0, 1).toUpperCase();
onText(upperCase);
return;
}
}
}
if (mPredicting) {
if (mKeyboardSwitcher.getInputView().isShifted()
&& mKeyboardSwitcher.isAlphabetMode()
&& mComposing.length() == 0) {
mWord.setFirstCharCapitalized(true);
}
mComposing.append((char) primaryCode);
mWord.add(primaryCode, keyCodes);
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
// If it's the first letter, make note of auto-caps state
if (mWord.size() == 1) {
mWord.setAutoCapitalized(
getCursorCapsMode(ic, getCurrentInputEditorInfo()) != 0);
}
ic.setComposingText(mComposing, 1);
}
postUpdateSuggestions();
} else {
sendKeyChar((char)primaryCode);
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (LatinIME.PERF_DEBUG) measureCps();
TextEntryState.typedCharacter((char) primaryCode, isWordSeparator(primaryCode));
}
private void handleSeparator(int primaryCode) {
if (VOICE_INSTALLED && mVoiceInputHighlighted) {
commitVoiceInput();
}
if (mAfterVoiceInput){
// Assume input length is 1. This assumption fails for smiley face insertions.
mVoiceInput.incrementTextModificationInsertPunctuationCount(1);
}
// Should dismiss the "Touch again to save" message when handling separator
if (mCandidateView != null && mCandidateView.dismissAddToDictionaryHint()) {
postUpdateSuggestions();
}
boolean pickedDefault = false;
// Handle separator
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
abortCorrection(false);
}
if (mPredicting) {
// In certain languages where single quote is a separator, it's better
// not to auto correct, but accept the typed word. For instance,
// in Italian dov' should not be expanded to dove' because the elision
// requires the last vowel to be removed.
if (mAutoCorrectOn && primaryCode != '\'' &&
(mJustRevertedSeparator == null
|| mJustRevertedSeparator.length() == 0
|| mJustRevertedSeparator.charAt(0) != primaryCode)) {
pickedDefault = pickDefaultSuggestion();
// Picked the suggestion by the space key. We consider this
// as "added an auto space".
if (primaryCode == KEYCODE_SPACE) {
mJustAddedAutoSpace = true;
}
} else {
commitTyped(ic);
}
}
if (mJustAddedAutoSpace && primaryCode == KEYCODE_ENTER) {
removeTrailingSpace();
mJustAddedAutoSpace = false;
}
sendKeyChar((char)primaryCode);
// Handle the case of ". ." -> " .." with auto-space if necessary
// before changing the TextEntryState.
if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED
&& primaryCode == KEYCODE_PERIOD) {
reswapPeriodAndSpace();
}
TextEntryState.typedCharacter((char) primaryCode, true);
if (TextEntryState.getState() == TextEntryState.State.PUNCTUATION_AFTER_ACCEPTED
&& primaryCode != KEYCODE_ENTER) {
swapPunctuationAndSpace();
} else if (isPredictionOn() && primaryCode == KEYCODE_SPACE) {
doubleSpace();
}
if (pickedDefault) {
TextEntryState.backToAcceptedDefault(mWord.getTypedWord());
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
}
private void handleClose() {
commitTyped(getCurrentInputConnection());
if (VOICE_INSTALLED & mRecognizing) {
mVoiceInput.cancel();
}
requestHideSelf(0);
if (mKeyboardSwitcher != null) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (inputView != null) {
inputView.closing();
}
}
TextEntryState.endSession();
}
private void saveWordInHistory(CharSequence result) {
if (mWord.size() <= 1) {
mWord.reset();
return;
}
// Skip if result is null. It happens in some edge case.
if (TextUtils.isEmpty(result)) {
return;
}
// Make a copy of the CharSequence, since it is/could be a mutable CharSequence
final String resultCopy = result.toString();
TypedWordAlternatives entry = new TypedWordAlternatives(resultCopy,
new WordComposer(mWord));
mWordHistory.add(entry);
}
private void postUpdateSuggestions() {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_SUGGESTIONS), 100);
}
private void postUpdateOldSuggestions() {
mHandler.removeMessages(MSG_UPDATE_OLD_SUGGESTIONS);
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_UPDATE_OLD_SUGGESTIONS), 300);
}
private boolean isPredictionOn() {
return mPredictionOn;
}
private boolean isCandidateStripVisible() {
return isPredictionOn() && mShowSuggestions;
}
public void onCancelVoice() {
if (mRecognizing) {
switchToKeyboardView();
}
}
private void switchToKeyboardView() {
mHandler.post(new Runnable() {
public void run() {
mRecognizing = false;
if (mKeyboardSwitcher.getInputView() != null) {
setInputView(mKeyboardSwitcher.getInputView());
}
setCandidatesViewShown(true);
updateInputViewShown();
postUpdateSuggestions();
}});
}
private void switchToRecognitionStatusView() {
final boolean configChanged = mConfigurationChanging;
mHandler.post(new Runnable() {
public void run() {
setCandidatesViewShown(false);
mRecognizing = true;
View v = mVoiceInput.getView();
ViewParent p = v.getParent();
if (p != null && p instanceof ViewGroup) {
((ViewGroup)v.getParent()).removeView(v);
}
setInputView(v);
updateInputViewShown();
if (configChanged) {
mVoiceInput.onConfigurationChanged();
}
}});
}
private void startListening(boolean swipe) {
if (!mHasUsedVoiceInput ||
(!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale)) {
// Calls reallyStartListening if user clicks OK, does nothing if user clicks Cancel.
showVoiceWarningDialog(swipe);
} else {
reallyStartListening(swipe);
}
}
private void reallyStartListening(boolean swipe) {
if (!mHasUsedVoiceInput) {
// The user has started a voice input, so remember that in the
// future (so we don't show the warning dialog after the first run).
SharedPreferences.Editor editor =
PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(PREF_HAS_USED_VOICE_INPUT, true);
SharedPreferencesCompat.apply(editor);
mHasUsedVoiceInput = true;
}
if (!mLocaleSupportedForVoiceInput && !mHasUsedVoiceInputUnsupportedLocale) {
// The user has started a voice input from an unsupported locale, so remember that
// in the future (so we don't show the warning dialog the next time they do this).
SharedPreferences.Editor editor =
PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.putBoolean(PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, true);
SharedPreferencesCompat.apply(editor);
mHasUsedVoiceInputUnsupportedLocale = true;
}
// Clear N-best suggestions
clearSuggestions();
FieldContext context = new FieldContext(
getCurrentInputConnection(),
getCurrentInputEditorInfo(),
mLanguageSwitcher.getInputLanguage(),
mLanguageSwitcher.getEnabledLanguages());
mVoiceInput.startListening(context, swipe);
switchToRecognitionStatusView();
}
private void showVoiceWarningDialog(final boolean swipe) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_mic_dialog);
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mVoiceInput.logKeyboardWarningDialogOk();
reallyStartListening(swipe);
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mVoiceInput.logKeyboardWarningDialogCancel();
}
});
if (mLocaleSupportedForVoiceInput) {
String message = getString(R.string.voice_warning_may_not_understand) + "\n\n" +
getString(R.string.voice_warning_how_to_turn_off);
builder.setMessage(message);
} else {
String message = getString(R.string.voice_warning_locale_not_supported) + "\n\n" +
getString(R.string.voice_warning_may_not_understand) + "\n\n" +
getString(R.string.voice_warning_how_to_turn_off);
builder.setMessage(message);
}
builder.setTitle(R.string.voice_warning_title);
mVoiceWarningDialog = builder.create();
Window window = mVoiceWarningDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mKeyboardSwitcher.getInputView().getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mVoiceInput.logKeyboardWarningDialogShown();
mVoiceWarningDialog.show();
}
public void onVoiceResults(List<String> candidates,
Map<String, List<CharSequence>> alternatives) {
if (!mRecognizing) {
return;
}
mVoiceResults.candidates = candidates;
mVoiceResults.alternatives = alternatives;
mHandler.sendMessage(mHandler.obtainMessage(MSG_VOICE_RESULTS));
}
private void handleVoiceResults() {
mAfterVoiceInput = true;
mImmediatelyAfterVoiceInput = true;
InputConnection ic = getCurrentInputConnection();
if (!isFullscreenMode()) {
// Start listening for updates to the text from typing, etc.
if (ic != null) {
ExtractedTextRequest req = new ExtractedTextRequest();
ic.getExtractedText(req, InputConnection.GET_EXTRACTED_TEXT_MONITOR);
}
}
vibrate();
switchToKeyboardView();
final List<CharSequence> nBest = new ArrayList<CharSequence>();
boolean capitalizeFirstWord = preferCapitalization()
|| (mKeyboardSwitcher.isAlphabetMode()
&& mKeyboardSwitcher.getInputView().isShifted());
for (String c : mVoiceResults.candidates) {
if (capitalizeFirstWord) {
c = Character.toUpperCase(c.charAt(0)) + c.substring(1, c.length());
}
nBest.add(c);
}
if (nBest.size() == 0) {
return;
}
String bestResult = nBest.get(0).toString();
mVoiceInput.logVoiceInputDelivered(bestResult.length());
mHints.registerVoiceResult(bestResult);
if (ic != null) ic.beginBatchEdit(); // To avoid extra updates on committing older text
commitTyped(ic);
EditingUtil.appendText(ic, bestResult);
if (ic != null) ic.endBatchEdit();
mVoiceInputHighlighted = true;
mWordToSuggestions.putAll(mVoiceResults.alternatives);
}
private void clearSuggestions() {
setSuggestions(null, false, false, false);
}
private void setSuggestions(
List<CharSequence> suggestions,
boolean completions,
boolean typedWordValid,
boolean haveMinimalSuggestion) {
if (mIsShowingHint) {
setCandidatesView(mCandidateViewContainer);
mIsShowingHint = false;
}
if (mCandidateView != null) {
mCandidateView.setSuggestions(
suggestions, completions, typedWordValid, haveMinimalSuggestion);
}
}
private void updateSuggestions() {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null);
// Check if we have a suggestion engine attached.
if ((mSuggest == null || !isPredictionOn()) && !mVoiceInputHighlighted) {
return;
}
if (!mPredicting) {
setNextSuggestions();
return;
}
showSuggestions(mWord);
}
private List<CharSequence> getTypedSuggestions(WordComposer word) {
List<CharSequence> stringList = mSuggest.getSuggestions(
mKeyboardSwitcher.getInputView(), word, false, null);
return stringList;
}
private void showCorrections(WordAlternatives alternatives) {
List<CharSequence> stringList = alternatives.getAlternatives();
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()).setPreferredLetters(null);
showSuggestions(stringList, alternatives.getOriginalWord(), false, false);
}
private void showSuggestions(WordComposer word) {
// long startTime = System.currentTimeMillis(); // TIME MEASUREMENT!
// TODO Maybe need better way of retrieving previous word
CharSequence prevWord = EditingUtil.getPreviousWord(getCurrentInputConnection(),
mWordSeparators);
List<CharSequence> stringList = mSuggest.getSuggestions(
mKeyboardSwitcher.getInputView(), word, false, prevWord);
// long stopTime = System.currentTimeMillis(); // TIME MEASUREMENT!
// Log.d("LatinIME","Suggest Total Time - " + (stopTime - startTime));
int[] nextLettersFrequencies = mSuggest.getNextLettersFrequencies();
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()).setPreferredLetters(
nextLettersFrequencies);
boolean correctionAvailable = !mInputTypeNoAutoCorrect && mSuggest.hasMinimalCorrection();
//|| mCorrectionMode == mSuggest.CORRECTION_FULL;
CharSequence typedWord = word.getTypedWord();
// If we're in basic correct
boolean typedWordValid = mSuggest.isValidWord(typedWord) ||
(preferCapitalization()
&& mSuggest.isValidWord(typedWord.toString().toLowerCase()));
if (mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM) {
correctionAvailable |= typedWordValid;
}
// Don't auto-correct words with multiple capital letter
correctionAvailable &= !word.isMostlyCaps();
correctionAvailable &= !TextEntryState.isCorrecting();
showSuggestions(stringList, typedWord, typedWordValid, correctionAvailable);
}
private void showSuggestions(List<CharSequence> stringList, CharSequence typedWord,
boolean typedWordValid, boolean correctionAvailable) {
setSuggestions(stringList, false, typedWordValid, correctionAvailable);
if (stringList.size() > 0) {
if (correctionAvailable && !typedWordValid && stringList.size() > 1) {
mBestWord = stringList.get(1);
} else {
mBestWord = typedWord;
}
} else {
mBestWord = null;
}
setCandidatesViewShown(isCandidateStripVisible() || mCompletionOn);
}
private boolean pickDefaultSuggestion() {
// Complete any pending candidate query first
if (mHandler.hasMessages(MSG_UPDATE_SUGGESTIONS)) {
mHandler.removeMessages(MSG_UPDATE_SUGGESTIONS);
updateSuggestions();
}
if (mBestWord != null && mBestWord.length() > 0) {
TextEntryState.acceptedDefault(mWord.getTypedWord(), mBestWord);
mJustAccepted = true;
pickSuggestion(mBestWord, false);
// Add the word to the auto dictionary if it's not a known word
addToDictionaries(mBestWord, AutoDictionary.FREQUENCY_FOR_TYPED);
return true;
}
return false;
}
public void pickSuggestionManually(int index, CharSequence suggestion) {
List<CharSequence> suggestions = mCandidateView.getSuggestions();
if (mAfterVoiceInput && mShowingVoiceSuggestions) {
mVoiceInput.flushAllTextModificationCounters();
// send this intent AFTER logging any prior aggregated edits.
mVoiceInput.logTextModifiedByChooseSuggestion(suggestion.toString(), index,
mWordSeparators,
getCurrentInputConnection());
}
final boolean correcting = TextEntryState.isCorrecting();
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
ic.beginBatchEdit();
}
if (mCompletionOn && mCompletions != null && index >= 0
&& index < mCompletions.length) {
CompletionInfo ci = mCompletions[index];
if (ic != null) {
ic.commitCompletion(ci);
}
mCommittedLength = suggestion.length();
if (mCandidateView != null) {
mCandidateView.clear();
}
updateShiftKeyState(getCurrentInputEditorInfo());
if (ic != null) {
ic.endBatchEdit();
}
return;
}
// If this is a punctuation, apply it through the normal key press
if (suggestion.length() == 1 && (isWordSeparator(suggestion.charAt(0))
|| isSuggestedPunctuation(suggestion.charAt(0)))) {
// Word separators are suggested before the user inputs something.
// So, LatinImeLogger logs "" as a user's input.
LatinImeLogger.logOnManualSuggestion(
"", suggestion.toString(), index, suggestions);
final char primaryCode = suggestion.charAt(0);
onKey(primaryCode, new int[]{primaryCode}, LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE,
LatinKeyboardBaseView.NOT_A_TOUCH_COORDINATE);
if (ic != null) {
ic.endBatchEdit();
}
return;
}
mJustAccepted = true;
pickSuggestion(suggestion, correcting);
// Add the word to the auto dictionary if it's not a known word
if (index == 0) {
addToDictionaries(suggestion, AutoDictionary.FREQUENCY_FOR_PICKED);
} else {
addToBigramDictionary(suggestion, 1);
}
LatinImeLogger.logOnManualSuggestion(mComposing.toString(), suggestion.toString(),
index, suggestions);
TextEntryState.acceptedSuggestion(mComposing.toString(), suggestion);
// Follow it with a space
if (mAutoSpace && !correcting) {
sendSpace();
mJustAddedAutoSpace = true;
}
final boolean showingAddToDictionaryHint = index == 0 && mCorrectionMode > 0
&& !mSuggest.isValidWord(suggestion)
&& !mSuggest.isValidWord(suggestion.toString().toLowerCase());
if (!correcting) {
// Fool the state watcher so that a subsequent backspace will not do a revert, unless
// we just did a correction, in which case we need to stay in
// TextEntryState.State.PICKED_SUGGESTION state.
TextEntryState.typedCharacter((char) KEYCODE_SPACE, true);
setNextSuggestions();
} else if (!showingAddToDictionaryHint) {
// If we're not showing the "Touch again to save", then show corrections again.
// In case the cursor position doesn't change, make sure we show the suggestions again.
clearSuggestions();
postUpdateOldSuggestions();
}
if (showingAddToDictionaryHint) {
mCandidateView.showAddToDictionaryHint(suggestion);
}
if (ic != null) {
ic.endBatchEdit();
}
}
private void rememberReplacedWord(CharSequence suggestion) {
if (mShowingVoiceSuggestions) {
// Retain the replaced word in the alternatives array.
EditingUtil.Range range = new EditingUtil.Range();
String wordToBeReplaced = EditingUtil.getWordAtCursor(getCurrentInputConnection(),
mWordSeparators, range);
if (!mWordToSuggestions.containsKey(wordToBeReplaced)) {
wordToBeReplaced = wordToBeReplaced.toLowerCase();
}
if (mWordToSuggestions.containsKey(wordToBeReplaced)) {
List<CharSequence> suggestions = mWordToSuggestions.get(wordToBeReplaced);
if (suggestions.contains(suggestion)) {
suggestions.remove(suggestion);
}
suggestions.add(wordToBeReplaced);
mWordToSuggestions.remove(wordToBeReplaced);
mWordToSuggestions.put(suggestion.toString(), suggestions);
}
}
}
/**
* Commits the chosen word to the text field and saves it for later
* retrieval.
* @param suggestion the suggestion picked by the user to be committed to
* the text field
* @param correcting whether this is due to a correction of an existing
* word.
*/
private void pickSuggestion(CharSequence suggestion, boolean correcting) {
LatinKeyboardView inputView = mKeyboardSwitcher.getInputView();
if (mCapsLock) {
suggestion = suggestion.toString().toUpperCase();
} else if (preferCapitalization()
|| (mKeyboardSwitcher.isAlphabetMode()
&& inputView.isShifted())) {
suggestion = suggestion.toString().toUpperCase().charAt(0)
+ suggestion.subSequence(1, suggestion.length()).toString();
}
InputConnection ic = getCurrentInputConnection();
if (ic != null) {
rememberReplacedWord(suggestion);
ic.commitText(suggestion, 1);
}
saveWordInHistory(suggestion);
mPredicting = false;
mCommittedLength = suggestion.length();
((LatinKeyboard) inputView.getKeyboard()).setPreferredLetters(null);
// If we just corrected a word, then don't show punctuations
if (!correcting) {
setNextSuggestions();
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
/**
* Tries to apply any voice alternatives for the word if this was a spoken word and
* there are voice alternatives.
* @param touching The word that the cursor is touching, with position information
* @return true if an alternative was found, false otherwise.
*/
private boolean applyVoiceAlternatives(EditingUtil.SelectedWord touching) {
// Search for result in spoken word alternatives
String selectedWord = touching.word.toString().trim();
if (!mWordToSuggestions.containsKey(selectedWord)) {
selectedWord = selectedWord.toLowerCase();
}
if (mWordToSuggestions.containsKey(selectedWord)) {
mShowingVoiceSuggestions = true;
List<CharSequence> suggestions = mWordToSuggestions.get(selectedWord);
// If the first letter of touching is capitalized, make all the suggestions
// start with a capital letter.
if (Character.isUpperCase(touching.word.charAt(0))) {
for (int i = 0; i < suggestions.size(); i++) {
String origSugg = (String) suggestions.get(i);
String capsSugg = origSugg.toUpperCase().charAt(0)
+ origSugg.subSequence(1, origSugg.length()).toString();
suggestions.set(i, capsSugg);
}
}
setSuggestions(suggestions, false, true, true);
setCandidatesViewShown(true);
return true;
}
return false;
}
/**
* Tries to apply any typed alternatives for the word if we have any cached alternatives,
* otherwise tries to find new corrections and completions for the word.
* @param touching The word that the cursor is touching, with position information
* @return true if an alternative was found, false otherwise.
*/
private boolean applyTypedAlternatives(EditingUtil.SelectedWord touching) {
// If we didn't find a match, search for result in typed word history
WordComposer foundWord = null;
WordAlternatives alternatives = null;
for (WordAlternatives entry : mWordHistory) {
if (TextUtils.equals(entry.getChosenWord(), touching.word)) {
if (entry instanceof TypedWordAlternatives) {
foundWord = ((TypedWordAlternatives) entry).word;
}
alternatives = entry;
break;
}
}
// If we didn't find a match, at least suggest completions
if (foundWord == null
&& (mSuggest.isValidWord(touching.word)
|| mSuggest.isValidWord(touching.word.toString().toLowerCase()))) {
foundWord = new WordComposer();
for (int i = 0; i < touching.word.length(); i++) {
foundWord.add(touching.word.charAt(i), new int[] {
touching.word.charAt(i)
});
}
foundWord.setFirstCharCapitalized(Character.isUpperCase(touching.word.charAt(0)));
}
// Found a match, show suggestions
if (foundWord != null || alternatives != null) {
if (alternatives == null) {
alternatives = new TypedWordAlternatives(touching.word, foundWord);
}
showCorrections(alternatives);
if (foundWord != null) {
mWord = new WordComposer(foundWord);
} else {
mWord.reset();
}
return true;
}
return false;
}
private void setOldSuggestions() {
mShowingVoiceSuggestions = false;
if (mCandidateView != null && mCandidateView.isShowingAddToDictionaryHint()) {
return;
}
InputConnection ic = getCurrentInputConnection();
if (ic == null) return;
if (!mPredicting) {
// Extract the selected or touching text
EditingUtil.SelectedWord touching = EditingUtil.getWordAtCursorOrSelection(ic,
mLastSelectionStart, mLastSelectionEnd, mWordSeparators);
if (touching != null && touching.word.length() > 1) {
ic.beginBatchEdit();
if (!applyVoiceAlternatives(touching) && !applyTypedAlternatives(touching)) {
abortCorrection(true);
} else {
TextEntryState.selectedForCorrection();
EditingUtil.underlineWord(ic, touching);
}
ic.endBatchEdit();
} else {
abortCorrection(true);
setNextSuggestions(); // Show the punctuation suggestions list
}
} else {
abortCorrection(true);
}
}
private void setNextSuggestions() {
setSuggestions(mSuggestPuncList, false, false, false);
}
private void addToDictionaries(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, false);
}
private void addToBigramDictionary(CharSequence suggestion, int frequencyDelta) {
checkAddToDictionary(suggestion, frequencyDelta, true);
}
/**
* Adds to the UserBigramDictionary and/or AutoDictionary
* @param addToBigramDictionary true if it should be added to bigram dictionary if possible
*/
private void checkAddToDictionary(CharSequence suggestion, int frequencyDelta,
boolean addToBigramDictionary) {
if (suggestion == null || suggestion.length() < 1) return;
// Only auto-add to dictionary if auto-correct is ON. Otherwise we'll be
// adding words in situations where the user or application really didn't
// want corrections enabled or learned.
if (!(mCorrectionMode == Suggest.CORRECTION_FULL
|| mCorrectionMode == Suggest.CORRECTION_FULL_BIGRAM)) {
return;
}
if (suggestion != null) {
if (!addToBigramDictionary && mAutoDictionary.isValidWord(suggestion)
|| (!mSuggest.isValidWord(suggestion.toString())
&& !mSuggest.isValidWord(suggestion.toString().toLowerCase()))) {
mAutoDictionary.addWord(suggestion.toString(), frequencyDelta);
}
if (mUserBigramDictionary != null) {
CharSequence prevWord = EditingUtil.getPreviousWord(getCurrentInputConnection(),
mSentenceSeparators);
if (!TextUtils.isEmpty(prevWord)) {
mUserBigramDictionary.addBigrams(prevWord.toString(), suggestion.toString());
}
}
}
}
private boolean isCursorTouchingWord() {
InputConnection ic = getCurrentInputConnection();
if (ic == null) return false;
CharSequence toLeft = ic.getTextBeforeCursor(1, 0);
CharSequence toRight = ic.getTextAfterCursor(1, 0);
if (!TextUtils.isEmpty(toLeft)
&& !isWordSeparator(toLeft.charAt(0))
&& !isSuggestedPunctuation(toLeft.charAt(0))) {
return true;
}
if (!TextUtils.isEmpty(toRight)
&& !isWordSeparator(toRight.charAt(0))
&& !isSuggestedPunctuation(toRight.charAt(0))) {
return true;
}
return false;
}
private boolean sameAsTextBeforeCursor(InputConnection ic, CharSequence text) {
CharSequence beforeText = ic.getTextBeforeCursor(text.length(), 0);
return TextUtils.equals(text, beforeText);
}
public void revertLastWord(boolean deleteChar) {
final int length = mComposing.length();
if (!mPredicting && length > 0) {
final InputConnection ic = getCurrentInputConnection();
mPredicting = true;
mJustRevertedSeparator = ic.getTextBeforeCursor(1, 0);
if (deleteChar) ic.deleteSurroundingText(1, 0);
int toDelete = mCommittedLength;
CharSequence toTheLeft = ic.getTextBeforeCursor(mCommittedLength, 0);
if (toTheLeft != null && toTheLeft.length() > 0
&& isWordSeparator(toTheLeft.charAt(0))) {
toDelete--;
}
ic.deleteSurroundingText(toDelete, 0);
ic.setComposingText(mComposing, 1);
TextEntryState.backspace();
postUpdateSuggestions();
} else {
sendDownUpKeyEvents(KeyEvent.KEYCODE_DEL);
mJustRevertedSeparator = null;
}
}
protected String getWordSeparators() {
return mWordSeparators;
}
public boolean isWordSeparator(int code) {
String separators = getWordSeparators();
return separators.contains(String.valueOf((char)code));
}
private boolean isSentenceSeparator(int code) {
return mSentenceSeparators.contains(String.valueOf((char)code));
}
private void sendSpace() {
sendKeyChar((char)KEYCODE_SPACE);
updateShiftKeyState(getCurrentInputEditorInfo());
//onKey(KEY_SPACE[0], KEY_SPACE);
}
public boolean preferCapitalization() {
return mWord.isFirstCharCapitalized();
}
private void toggleLanguage(boolean reset, boolean next) {
if (reset) {
mLanguageSwitcher.reset();
} else {
if (next) {
mLanguageSwitcher.next();
} else {
mLanguageSwitcher.prev();
}
}
int currentKeyboardMode = mKeyboardSwitcher.getKeyboardMode();
reloadKeyboards();
mKeyboardSwitcher.makeKeyboards(true);
mKeyboardSwitcher.setKeyboardMode(currentKeyboardMode, 0,
mEnableVoiceButton && mEnableVoice);
initSuggest(mLanguageSwitcher.getInputLanguage());
mLanguageSwitcher.persist();
updateShiftKeyState(getCurrentInputEditorInfo());
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PREF_SELECTED_LANGUAGES.equals(key)) {
mLanguageSwitcher.loadLocales(sharedPreferences);
mRefreshKeyboardRequired = true;
} else if (PREF_RECORRECTION_ENABLED.equals(key)) {
mReCorrectionEnabled = sharedPreferences.getBoolean(PREF_RECORRECTION_ENABLED,
getResources().getBoolean(R.bool.default_recorrection_enabled));
}
}
public void swipeRight() {
if (LatinKeyboardView.DEBUG_AUTO_PLAY) {
ClipboardManager cm = ((ClipboardManager)getSystemService(CLIPBOARD_SERVICE));
CharSequence text = cm.getText();
if (!TextUtils.isEmpty(text)) {
mKeyboardSwitcher.getInputView().startPlaying(text.toString());
}
}
}
public void swipeLeft() {
}
public void swipeDown() {
handleClose();
}
public void swipeUp() {
//launchSettings();
}
public void onPress(int primaryCode) {
if (mKeyboardSwitcher.isVibrateAndSoundFeedbackRequired()) {
vibrate();
playKeyClick(primaryCode);
}
final boolean distinctMultiTouch = mKeyboardSwitcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) {
mShiftKeyState.onPress();
handleShift();
} else if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {
changeKeyboardMode();
mSymbolKeyState.onPress();
mKeyboardSwitcher.setAutoModeSwitchStateMomentary();
} else {
mShiftKeyState.onOtherKeyPressed();
mSymbolKeyState.onOtherKeyPressed();
}
}
public void onRelease(int primaryCode) {
// Reset any drag flags in the keyboard
((LatinKeyboard) mKeyboardSwitcher.getInputView().getKeyboard()).keyReleased();
//vibrate();
final boolean distinctMultiTouch = mKeyboardSwitcher.hasDistinctMultitouch();
if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_SHIFT) {
if (mShiftKeyState.isMomentary())
resetShift();
mShiftKeyState.onRelease();
} else if (distinctMultiTouch && primaryCode == Keyboard.KEYCODE_MODE_CHANGE) {
// Snap back to the previous keyboard mode if the user chords the mode change key and
// other key, then released the mode change key.
if (mKeyboardSwitcher.isInChordingAutoModeSwitchState())
changeKeyboardMode();
mSymbolKeyState.onRelease();
}
}
private FieldContext makeFieldContext() {
return new FieldContext(
getCurrentInputConnection(),
getCurrentInputEditorInfo(),
mLanguageSwitcher.getInputLanguage(),
mLanguageSwitcher.getEnabledLanguages());
}
private boolean fieldCanDoVoice(FieldContext fieldContext) {
return !mPasswordText
&& mVoiceInput != null
&& !mVoiceInput.isBlacklistedField(fieldContext);
}
private boolean shouldShowVoiceButton(FieldContext fieldContext, EditorInfo attribute) {
return ENABLE_VOICE_BUTTON && fieldCanDoVoice(fieldContext)
&& !(attribute != null
&& IME_OPTION_NO_MICROPHONE.equals(attribute.privateImeOptions))
&& SpeechRecognizer.isRecognitionAvailable(this);
}
// receive ringer mode changes to detect silent mode
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
updateRingerMode();
}
};
// update flags for silent mode
private void updateRingerMode() {
if (mAudioManager == null) {
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
if (mAudioManager != null) {
mSilentMode = (mAudioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL);
}
}
private void playKeyClick(int primaryCode) {
// if mAudioManager is null, we don't have the ringer state yet
// mAudioManager will be set by updateRingerMode
if (mAudioManager == null) {
if (mKeyboardSwitcher.getInputView() != null) {
updateRingerMode();
}
}
if (mSoundOn && !mSilentMode) {
// FIXME: Volume and enable should come from UI settings
// FIXME: These should be triggered after auto-repeat logic
int sound = AudioManager.FX_KEYPRESS_STANDARD;
switch (primaryCode) {
case Keyboard.KEYCODE_DELETE:
sound = AudioManager.FX_KEYPRESS_DELETE;
break;
case KEYCODE_ENTER:
sound = AudioManager.FX_KEYPRESS_RETURN;
break;
case KEYCODE_SPACE:
sound = AudioManager.FX_KEYPRESS_SPACEBAR;
break;
}
mAudioManager.playSoundEffect(sound, FX_VOLUME);
}
}
private void vibrate() {
if (!mVibrateOn) {
return;
}
if (mKeyboardSwitcher.getInputView() != null) {
mKeyboardSwitcher.getInputView().performHapticFeedback(
HapticFeedbackConstants.KEYBOARD_TAP,
HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
}
}
private void checkTutorial(String privateImeOptions) {
if (privateImeOptions == null) return;
if (privateImeOptions.equals("com.android.setupwizard:ShowTutorial")) {
if (mTutorial == null) startTutorial();
} else if (privateImeOptions.equals("com.android.setupwizard:HideTutorial")) {
if (mTutorial != null) {
if (mTutorial.close()) {
mTutorial = null;
}
}
}
}
private void startTutorial() {
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_START_TUTORIAL), 500);
}
/* package */ void tutorialDone() {
mTutorial = null;
}
/* package */ void promoteToUserDictionary(String word, int frequency) {
if (mUserDictionary.isValidWord(word)) return;
mUserDictionary.addWord(word, frequency);
}
/* package */ WordComposer getCurrentWord() {
return mWord;
}
/* package */ boolean getPopupOn() {
return mPopupOn;
}
private void updateCorrectionMode() {
mHasDictionary = mSuggest != null ? mSuggest.hasMainDictionary() : false;
mAutoCorrectOn = (mAutoCorrectEnabled || mQuickFixes)
&& !mInputTypeNoAutoCorrect && mHasDictionary;
mCorrectionMode = (mAutoCorrectOn && mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL
: (mAutoCorrectOn ? Suggest.CORRECTION_BASIC : Suggest.CORRECTION_NONE);
mCorrectionMode = (mBigramSuggestionEnabled && mAutoCorrectOn && mAutoCorrectEnabled)
? Suggest.CORRECTION_FULL_BIGRAM : mCorrectionMode;
if (mSuggest != null) {
mSuggest.setCorrectionMode(mCorrectionMode);
}
}
private void updateAutoTextEnabled(Locale systemLocale) {
if (mSuggest == null) return;
boolean different =
!systemLocale.getLanguage().equalsIgnoreCase(mInputLocale.substring(0, 2));
mSuggest.setAutoTextEnabled(!different && mQuickFixes);
}
protected void launchSettings() {
launchSettings(LatinIMESettings.class);
}
public void launchDebugSettings() {
launchSettings(LatinIMEDebugSettings.class);
}
protected void launchSettings (Class<? extends PreferenceActivity> settingsClass) {
handleClose();
Intent intent = new Intent();
intent.setClass(LatinIME.this, settingsClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void loadSettings() {
// Get the settings preferences
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
mVibrateOn = sp.getBoolean(PREF_VIBRATE_ON, false);
mSoundOn = sp.getBoolean(PREF_SOUND_ON, false);
mPopupOn = sp.getBoolean(PREF_POPUP_ON,
mResources.getBoolean(R.bool.default_popup_preview));
mAutoCap = sp.getBoolean(PREF_AUTO_CAP, true);
mQuickFixes = sp.getBoolean(PREF_QUICK_FIXES, true);
mHasUsedVoiceInput = sp.getBoolean(PREF_HAS_USED_VOICE_INPUT, false);
mHasUsedVoiceInputUnsupportedLocale =
sp.getBoolean(PREF_HAS_USED_VOICE_INPUT_UNSUPPORTED_LOCALE, false);
// Get the current list of supported locales and check the current locale against that
// list. We cache this value so as not to check it every time the user starts a voice
// input. Because this method is called by onStartInputView, this should mean that as
// long as the locale doesn't change while the user is keeping the IME open, the
// value should never be stale.
String supportedLocalesString = SettingsUtil.getSettingsString(
getContentResolver(),
SettingsUtil.LATIN_IME_VOICE_INPUT_SUPPORTED_LOCALES,
DEFAULT_VOICE_INPUT_SUPPORTED_LOCALES);
ArrayList<String> voiceInputSupportedLocales =
newArrayList(supportedLocalesString.split("\\s+"));
mLocaleSupportedForVoiceInput = voiceInputSupportedLocales.contains(mInputLocale);
mShowSuggestions = sp.getBoolean(PREF_SHOW_SUGGESTIONS, true);
if (VOICE_INSTALLED) {
final String voiceMode = sp.getString(PREF_VOICE_MODE,
getString(R.string.voice_mode_main));
boolean enableVoice = !voiceMode.equals(getString(R.string.voice_mode_off))
&& mEnableVoiceButton;
boolean voiceOnPrimary = voiceMode.equals(getString(R.string.voice_mode_main));
if (mKeyboardSwitcher != null &&
(enableVoice != mEnableVoice || voiceOnPrimary != mVoiceOnPrimary)) {
mKeyboardSwitcher.setVoiceMode(enableVoice, voiceOnPrimary);
}
mEnableVoice = enableVoice;
mVoiceOnPrimary = voiceOnPrimary;
}
mAutoCorrectEnabled = sp.getBoolean(PREF_AUTO_COMPLETE,
mResources.getBoolean(R.bool.enable_autocorrect)) & mShowSuggestions;
//mBigramSuggestionEnabled = sp.getBoolean(
// PREF_BIGRAM_SUGGESTIONS, true) & mShowSuggestions;
updateCorrectionMode();
updateAutoTextEnabled(mResources.getConfiguration().locale);
mLanguageSwitcher.loadLocales(sp);
}
private void initSuggestPuncList() {
mSuggestPuncList = new ArrayList<CharSequence>();
mSuggestPuncs = mResources.getString(R.string.suggested_punctuations);
if (mSuggestPuncs != null) {
for (int i = 0; i < mSuggestPuncs.length(); i++) {
mSuggestPuncList.add(mSuggestPuncs.subSequence(i, i + 1));
}
}
}
private boolean isSuggestedPunctuation(int code) {
return mSuggestPuncs.contains(String.valueOf((char)code));
}
private void showOptionsMenu() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setIcon(R.drawable.ic_dialog_keyboard);
builder.setNegativeButton(android.R.string.cancel, null);
CharSequence itemSettings = getString(R.string.english_ime_settings);
CharSequence itemInputMethod = getString(R.string.selectInputMethod);
builder.setItems(new CharSequence[] {
itemInputMethod, itemSettings},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface di, int position) {
di.dismiss();
switch (position) {
case POS_SETTINGS:
launchSettings();
break;
case POS_METHOD:
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.showInputMethodPicker();
break;
}
}
});
builder.setTitle(mResources.getString(R.string.english_ime_input_options));
mOptionsDialog = builder.create();
Window window = mOptionsDialog.getWindow();
WindowManager.LayoutParams lp = window.getAttributes();
lp.token = mKeyboardSwitcher.getInputView().getWindowToken();
lp.type = WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG;
window.setAttributes(lp);
window.addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
mOptionsDialog.show();
}
public void changeKeyboardMode() {
mKeyboardSwitcher.toggleSymbols();
if (mCapsLock && mKeyboardSwitcher.isAlphabetMode()) {
mKeyboardSwitcher.setShiftLocked(mCapsLock);
}
updateShiftKeyState(getCurrentInputEditorInfo());
}
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
@Override
protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
super.dump(fd, fout, args);
final Printer p = new PrintWriterPrinter(fout);
p.println("LatinIME state :");
p.println(" Keyboard mode = " + mKeyboardSwitcher.getKeyboardMode());
p.println(" mCapsLock=" + mCapsLock);
p.println(" mComposing=" + mComposing.toString());
p.println(" mPredictionOn=" + mPredictionOn);
p.println(" mCorrectionMode=" + mCorrectionMode);
p.println(" mPredicting=" + mPredicting);
p.println(" mAutoCorrectOn=" + mAutoCorrectOn);
p.println(" mAutoSpace=" + mAutoSpace);
p.println(" mCompletionOn=" + mCompletionOn);
p.println(" TextEntryState.state=" + TextEntryState.getState());
p.println(" mSoundOn=" + mSoundOn);
p.println(" mVibrateOn=" + mVibrateOn);
p.println(" mPopupOn=" + mPopupOn);
}
// Characters per second measurement
private long mLastCpsTime;
private static final int CPS_BUFFER_SIZE = 16;
private long[] mCpsIntervals = new long[CPS_BUFFER_SIZE];
private int mCpsIndex;
private void measureCps() {
long now = System.currentTimeMillis();
if (mLastCpsTime == 0) mLastCpsTime = now - 100; // Initial
mCpsIntervals[mCpsIndex] = now - mLastCpsTime;
mLastCpsTime = now;
mCpsIndex = (mCpsIndex + 1) % CPS_BUFFER_SIZE;
long total = 0;
for (int i = 0; i < CPS_BUFFER_SIZE; i++) total += mCpsIntervals[i];
System.out.println("CPS = " + ((CPS_BUFFER_SIZE * 1000f) / total));
}
public void onAutoCompletionStateChanged(boolean isAutoCompletion) {
mKeyboardSwitcher.onAutoCompletionStateChanged(isAutoCompletion);
}
}
|
package com.kate.listeners;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.kate.util.DBConnectionManager;
/*AppContextListener är en ServletContextListener som har två
metoder. Den ena körs innan uppstart och den andra precis innan
nedstängning av appen. Här skapar och stänger vi vår databasanslutning
*/
@WebListener
public class AppContextListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext ctx = servletContextEvent.getServletContext();
/*
data to initialise database connection
dbURL, dbUser and dbpassword are all parameter
that has been defined in web.xml
*/
String dbURL = ctx.getInitParameter("dbURL");
String user = ctx.getInitParameter("dbUser");
String pwd = ctx.getInitParameter("dbPassword");
try{
// get database connection
DBConnectionManager connectionManager = new DBConnectionManager(dbURL, user, pwd);
ctx.setAttribute("DBConnection", connectionManager.getConnection());
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
Connection con = (Connection) servletContextEvent.getServletContext().getAttribute("DBConnection");
try{
con.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
|
import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import styled from "styled-components";
import LoginModal from "../login/login";
const HeroCarouselContainer = styled.div`
position: relative;
width: 100%;
max-width: 1200px;
height: 400px;
margin: 0 auto;
`;
const SlideImageWrapper = styled.div`
height: 100%;
img {
width: 100%;
height: 100%;
object-fit: cover;
}
`;
const OverlayContent = styled.div`
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
color: #fff;
z-index: 1;
`;
const CtaButton = styled.button`
background-color: #007bff;
color: #fff;
font-size: 1.5rem;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.2s;
&:hover {
background-color: #0056b3;
}
`;
const HeroCarousel = () => {
const settings = {
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 3000,
};
const [isModalOpen, setIsModalOpen] = React.useState(false);
const handleOpenModal = () => {
setIsModalOpen(true);
};
const handleCloseModal = () => {
setIsModalOpen(false);
};
return (
<HeroCarouselContainer>
<Slider {...settings}>
<div>
<SlideImageWrapper>
<img
src="https://images.unsplash.com/photo-1495202337139-e865ed70fcd4"
alt="Slide 1"
/>
</SlideImageWrapper>
</div>
<div>
<SlideImageWrapper>
<img
src="https://images.unsplash.com/photo-1518355077561-4af7abce973d"
alt="Slide 1"
/>
</SlideImageWrapper>
</div>
<div>
<SlideImageWrapper>
<img
src="https://images.unsplash.com/photo-1451153378752-16ef2b36ad05"
alt="Slide 1"
/>
</SlideImageWrapper>
</div>
{/* Add more slides with SlideImageWrapper */}
</Slider>
<OverlayContent>
<h1 style={{ color: "#333", marginBottom: ".5rem" }}>
Welcome to Our Rental Service
</h1>
<p style={{ color: "#333", marginBottom: ".5rem" }}>
Find the perfect rental property for you!
</p>
{/* Include your CTA button component here */}
<CtaButton onClick={handleOpenModal}>Let's Get Stated</CtaButton>
</OverlayContent>
<LoginModal show={isModalOpen} onClose={handleCloseModal} />
</HeroCarouselContainer>
);
};
export default HeroCarousel;
|
package hylo
import scala.collection.mutable
/** An array of bit values represented as Booleans, where `true` indicates that the bit is on. */
final class BitArray private (
private var _bits: HyArray[Int],
private var _count: Int
) {
/** Returns `true` iff `this` is empty. */
def isEmpty: Boolean =
_count == 0
/** Returns the number of elements in `this`. */
def count: Int =
_count
/** The number of bits that the array can contain before allocating new storage. */
def capacity: Int =
_bits.capacity << 5
/** Reserves enough storage to store `n` elements in `this`. */
def reserveCapacity(n: Int, assumeUniqueness: Boolean = false): BitArray =
if (n == 0) {
this
} else {
val k = 1 + ((n - 1) >> 5)
if (assumeUniqueness) {
_bits = _bits.reserveCapacity(k, assumeUniqueness)
this
} else {
new BitArray(_bits.reserveCapacity(k), _count)
}
}
/** Adds a new element at the end of the array. */
def append(bit: Boolean, assumeUniqueness: Boolean = false): BitArray =
val result = if assumeUniqueness && (count < capacity) then this else copy(count + 1)
val p = BitArray.Position(count)
if (p.bucket >= _bits.count) {
result._bits = _bits.append(if bit then 1 else 0)
} else {
result.setValue(bit, p)
}
result._count += 1
result
/** Removes and returns the last element, or returns `None` if the array is empty. */
def popLast(assumeUniqueness: Boolean = false): (BitArray, Option[Boolean]) =
if (isEmpty) {
(this, None)
} else {
val result = if assumeUniqueness then this else copy()
val bit = result.at(BitArray.Position(count))
result._count -= 1
(result, Some(bit))
}
/** Removes all elements in the array, keeping allocated storage iff `keepStorage` is true. */
def removeAll(
keepStorage: Boolean = false,
assumeUniqueness: Boolean = false
): BitArray =
if (isEmpty) {
this
} else if (keepStorage) {
val result = if assumeUniqueness then this else copy()
result._bits.removeAll(keepStorage, assumeUniqueness = true)
result._count = 0
result
} else {
BitArray()
}
/** Returns `true` iff all elements in `this` are `false`. */
def allFalse: Boolean =
if (isEmpty) {
true
} else {
val k = (count - 1) >> 5
def loop(i: Int): Boolean =
if (i == k) {
val m = (1 << (count & 31)) - 1
(_bits.at(k) & m) == 0
} else if (_bits.at(i) != 0) {
false
} else {
loop(i + 1)
}
loop(0)
}
/** Returns `true` iff all elements in `this` are `true`. */
def allTrue: Boolean =
if (isEmpty) {
true
} else {
val k = (count - 1) >> 5
def loop(i: Int): Boolean =
if (i == k) {
val m = (1 << (count & 31)) - 1
(_bits.at(k) & m) == m
} else if (_bits.at(i) != ~0) {
false
} else {
loop(i + 1)
}
loop(0)
}
/** Returns the bitwise OR of `this` and `other`. */
def | (other: BitArray): BitArray =
val result = copy()
result.applyBitwise(other, _ | _, assumeUniqueness = true)
/** Returns the bitwise AND of `this` and `other`. */
def & (other: BitArray): BitArray =
val result = copy()
result.applyBitwise(other, _ & _, assumeUniqueness = true)
/** Returns the bitwise XOR of `this` and `other`. */
def ^ (other: BitArray): BitArray =
val result = copy()
result.applyBitwise(other, _ ^ _, assumeUniqueness = true)
/** Assigns each bits in `this` to the result of `operation` applied on those bits and their
* corresponding bits in `other`.
*
* @requires
* `self.count == other.count`.
*/
private def applyBitwise(
other: BitArray,
operation: (Int, Int) => Int,
assumeUniqueness: Boolean = false
): BitArray =
require(this.count == other.count)
if (isEmpty) {
this
} else {
val result = if assumeUniqueness then this else copy()
var u = assumeUniqueness
val k = (count - 1) >> 5
for (i <- 0 until k) {
result._bits = result._bits.modifyAt(
i, (n) => operation(n, other._bits.at(n)),
assumeUniqueness = u
)
u = true
}
val m = (1 << (count & 31)) - 1
result._bits = result._bits.modifyAt(
k, (n) => operation(n & m, other._bits.at(k) & m),
assumeUniqueness = u
)
result
}
/** Returns the position of `this`'s first element', or `endPosition` if `this` is empty.
*
* @complexity
* O(1).
*/
def startPosition: BitArray.Position =
BitArray.Position(0)
/** Returns the "past the end" position in `this`, that is, the position immediately after the
* last element in `this`.
*
* @complexity
* O(1).
*/
def endPosition: BitArray.Position =
BitArray.Position(count)
/** Returns the position immediately after `p`.
*
* @requires
* `p` is a valid position in `self` different from `endPosition`.
* @complexity
* O(1).
*/
def positionAfter(p: BitArray.Position): BitArray.Position =
if (p.offsetInBucket == 63) {
BitArray.Position(p.bucket + 1, 0)
} else {
BitArray.Position(p.bucket, p.offsetInBucket + 1)
}
/** Accesses the element at `p`.
*
* @requires
* `p` is a valid position in `self` different from `endPosition`.
* @complexity
* O(1).
*/
def at(p: BitArray.Position): Boolean =
val m = 1 << p.offsetInBucket
val b: Int = _bits.at(p.bucket)
(b & m) == m
/** Accesses the `i`-th element of `this`.
*
* @requires
* `i` is greater than or equal to 0, and less than `count`.
* @complexity
* O(1).
*/
def atIndex(i: Int): Boolean =
at(BitArray.Position(i))
/** Calls `transform` on the element at `p` to update its value.
*
* @requires
* `p` is a valid position in `self` different from `endPosition`.
* @complexity
* O(1).
*/
def modifyAt(
p: BitArray.Position,
transform: (Boolean) => Boolean,
assumeUniqueness: Boolean = false
): BitArray =
val result = if assumeUniqueness then this else copy()
result.setValue(transform(result.at(p)), p)
result
/** Calls `transform` on `i`-th element of `this` to update its value.
*
* @requires
* `i` is greater than or equal to 0, and less than `count`.
* @complexity
* O(1).
*/
def modifyAtIndex(
i: Int,
transform: (Boolean) => Boolean,
assumeUniqueness: Boolean = false
): BitArray =
modifyAt(BitArray.Position(i), transform, assumeUniqueness)
/** Returns an independent copy of `this`. */
def copy(minimumCapacity: Int = 0): BitArray =
if (minimumCapacity > capacity) {
// If the requested capacity on the copy is greater than what we have, `reserveCapacity` will
// create an independent value.
reserveCapacity(minimumCapacity)
} else {
val k = 1 + ((minimumCapacity - 1) >> 5)
val newBits = _bits.copy(k)
new BitArray(newBits, _count)
}
/** Returns a textual description of `this`. */
override def toString: String =
_bits.toString
/** Sets the value `b` for the bit at position `p`.
*
* @requires
* `this` is uniquely referenced and `p` is a valid position in `this`.
*/
private def setValue(b: Boolean, p: BitArray.Position): Unit =
val m = 1 << p.offsetInBucket
_bits = _bits.modifyAt(
p.bucket,
(e) => if b then e | m else e & ~m,
assumeUniqueness = true
)
}
object BitArray {
/** A position in a `BitArray`.
*
* @param bucket
* The bucket containing `this`.
* @param offsetInBucket
* The offset of `this` in its containing bucket.
*/
final class Position(
private[BitArray] val bucket: Int,
private[BitArray] val offsetInBucket: Int
) {
/** Creates a position from an index. */
private[BitArray] def this(index: Int) =
this(index >> 5, index & 31)
/** Returns the index corresponding to this position. */
private def index: Int =
(bucket >> 5) + offsetInBucket
/** Returns a copy of `this`. */
def copy(): Position =
new Position(bucket, offsetInBucket)
/** Returns `true` iff `this` and `other` have an equivalent value. */
def eq(other: Position): Boolean =
(this.bucket == other.bucket) && (this.offsetInBucket == other.offsetInBucket)
/** Hashes the salient parts of `self` into `hasher`. */
def hashInto(hasher: Hasher): Hasher =
hasher.combine(bucket)
hasher.combine(offsetInBucket)
}
/** Creates an array with the given `bits`. */
def apply[T](bits: Boolean*): BitArray =
var result = new BitArray(HyArray[Int](), 0)
for (b <- bits) result = result.append(b, assumeUniqueness = true)
result
}
given bitArrayPositionIsValue: Value[BitArray.Position] with {
extension (self: BitArray.Position) {
def copy(): BitArray.Position =
self.copy()
def eq(other: BitArray.Position): Boolean =
self.eq(other)
def hashInto(hasher: Hasher): Hasher =
self.hashInto(hasher)
}
}
given bitArrayIsCollection: Collection[BitArray] with {
type Element = Boolean
type Position = BitArray.Position
extension (self: BitArray) {
override def count: Int =
self.count
def startPosition: BitArray.Position =
self.startPosition
def endPosition: BitArray.Position =
self.endPosition
def positionAfter(p: BitArray.Position): BitArray.Position =
self.positionAfter(p)
def at(p: BitArray.Position): Boolean =
self.at(p)
}
}
given bitArrayIsStringConvertible: StringConvertible[BitArray] with {
extension (self: BitArray)
override def description: String =
var contents = mutable.StringBuilder()
self.forEach((e) => { contents += (if e then '1' else '0'); true })
contents.mkString
}
|
import { Button, cn, IconButton } from '@stump/components'
import { ArrowLeft, ArrowRight, DotsThree } from 'phosphor-react'
import { useMemo } from 'react'
import { useWindowSize } from 'rooks'
import { usePagination } from '../../hooks/usePagination'
import PagePopoverForm from '../PagePopoverForm'
import { PaginationProps } from '../Pagination'
type TablePaginationProps = Omit<PaginationProps, 'position'> & {
onPageChange: (page: number) => void
isZeroBasedPagination?: boolean
}
export default function TablePagination({
pages,
currentPage,
onPageChange,
isZeroBasedPagination,
}: TablePaginationProps) {
const { innerWidth: screenWidth } = useWindowSize()
const numbersToShow = useMemo(() => {
if (screenWidth != null) {
if (screenWidth < 768) {
return 5
}
if (screenWidth < 992) {
return 7
}
}
return 10
}, [screenWidth])
const { pageRange } = usePagination({ currentPage, numbersToShow, totalPages: pages })
return (
<div className="flex items-center gap-1">
<IconButton disabled={currentPage <= 1} onClick={() => onPageChange(currentPage - 1)}>
<ArrowLeft />
</IconButton>
{pageRange.map((page, i) => {
if (typeof page === 'number') {
return (
<PaginationNumber
key={`${i}, pagination-${page}`}
isActive={page === currentPage}
onClick={() => onPageChange(page)}
page={page}
/>
)
}
return (
<PagePopoverForm
currentPage={currentPage}
pos={i}
key={`${i}, pagination-${page}`}
totalPages={pages}
onPageChange={onPageChange}
trigger={
<Button>
<DotsThree />
</Button>
}
/>
)
})}
<IconButton disabled={currentPage >= pages} onClick={() => onPageChange(currentPage + 1)}>
<ArrowRight />
</IconButton>
</div>
)
}
interface PaginationNumberProps {
page: number
isActive: boolean
onClick: () => void
}
// TODO: style
function PaginationNumber({ onClick, page, isActive }: PaginationNumberProps) {
return (
<IconButton
size="xs"
onClick={onClick}
variant="ghost"
className={cn('h-5 w-5', isActive ? '!text-brand' : '')}
>
{page}
</IconButton>
)
}
|
import {EventEmitter} from 'events';
export const eventEmiter = new EventEmitter();
export enum CallType {
call = 'call', // 调用
callBack = 'callBack', // 回调
}
declare global {
interface Window {
ReactNativeWebView: any
}
}
export const defaultChannelName = 'ReactNativeWebView'; // 默认渠道名称
export interface MethodArgs {
channelName?: string; // 渠道名称,默认'ReactNativeWebView',一般都使用同一个渠道,不同业务或者应用可以使用不同的渠道名,避免通信污染
methodType?: CallType; // 当前是调用还是响应调用即【回调】
methodName: string; // 方法名称,用户自定义,一般是一个有意义并且唯一的字符串
data?: any; // 传输的数据,any类型
}
export interface MethodCallArgs extends MethodArgs {
timeStr: string; // 时间戳
sourceMethodName: string; // 保留原始方法名
successKey: string; // 成功回调的key值
errorKey: string; // 失败回调的key值
}
// H5初始化监听
export const useH5AddListener = (bridgeH5Api: any = {}) => {
// 可以传进来一个meargeApi进来
const messageFn = event => {
try {
let dataSource = event?.data;
if (dataSource && dataSource !== 'undefined') {
const messageData: MethodCallArgs = dataSource && JSON.parse(dataSource) || {};
const {
channelName,
methodType,
methodName,
data,
sourceMethodName,
successKey,
errorKey,
} = messageData;
if (channelName === defaultChannelName) {
if (methodType === CallType.callBack) {
// react native 回调到H5
eventEmiter.emit(methodName, data);
eventEmiter.off(successKey, () => {});
eventEmiter.off(errorKey, () => {});
} else if (methodType === CallType.call) {
// react native 调用H5的方法
if (
bridgeH5Api.hasOwnProperty(sourceMethodName) &&
typeof bridgeH5Api[sourceMethodName] === 'function'
) {
bridgeH5Api[sourceMethodName](data)
.then((res: any) => {
const successObj = {
...messageData,
data: res,
methodType: CallType.callBack,
methodName: successKey,
};
window?.ReactNativeWebView?.postMessage(
JSON.stringify(successObj),
);
})
.catch(err => {
const errObj = {
...messageData,
data: err,
methodType: CallType.callBack,
methodName: errorKey,
};
window?.ReactNativeWebView?.postMessage(
JSON.stringify(errObj),
);
});
}
}
}
}
} catch (error) {
console.error(error);
}
};
window?.addEventListener('message', messageFn, {
capture: true,
passive: true,
});
window.addEventListener('beforeunload', ()=>{
window?.removeEventListener('message', messageFn);
});
};
export interface useReactNativeAddListenerArgs {
bridgeReactNativeApi: any;
webViewRef: any;
event: any;
}
export const useReactNativeAddListener = (
messageProps: useReactNativeAddListenerArgs,
) => {
const {bridgeReactNativeApi, webViewRef, event} = messageProps;
const dataSource = event?.nativeEvent?.data;
try {
if (dataSource && dataSource !== 'undefined') {
const messageData: MethodCallArgs = dataSource && JSON.parse(dataSource) || {};
const {
channelName,
methodType,
methodName,
data,
sourceMethodName,
successKey,
errorKey,
} = messageData;
if (channelName === defaultChannelName) {
if (methodType === CallType.callBack) {
// H5 回调到react native
eventEmiter.emit(methodName, data);
eventEmiter.off(successKey, () => {});
eventEmiter.off(errorKey, () => {});
} else if (methodType === CallType.call) {
// H5调用react native的方法
if (
bridgeReactNativeApi.hasOwnProperty(sourceMethodName) &&
typeof bridgeReactNativeApi[sourceMethodName] === 'function'
) {
bridgeReactNativeApi[sourceMethodName](data)
.then((res: any) => {
const successObj = {
...messageData,
data: res,
methodType: CallType.callBack,
methodName: successKey,
};
webViewRef?.current?.postMessage(JSON.stringify(successObj), '*');
})
.catch(err => {
const errObj = {
...messageData,
data: err,
methodType: CallType.callBack,
methodName: errorKey,
};
webViewRef?.current?.postMessage(JSON.stringify(errObj), '*');
});
}
}
}
}
} catch (error) {
console.error(error);
}
};
// 统一封装H5调用react native 及回调返回,通过promise的方式
export const h5CallreactNative = (dataParms: MethodArgs) => {
return new Promise((resolve, reject) => {
const {
channelName = defaultChannelName,
methodType = CallType.call,
methodName = 'methodName',
data = '',
} = dataParms;
const timeStr = `${new Date().getTime()}`;
const successKey = `${methodName}_${timeStr}_success`;
const errorKey = `${methodName}_${timeStr}_error`;
const obj: MethodCallArgs = {
channelName,
methodType,
methodName,
sourceMethodName: methodName,
data,
timeStr,
successKey,
errorKey,
};
// 挂载成功的回调
eventEmiter.on(successKey, res => {
resolve(res);
});
// 挂载失败的回调
eventEmiter.on(errorKey, err => {
reject(err);
});
window?.ReactNativeWebView?.postMessage(JSON.stringify(obj));
});
};
export interface reactNativeCallH5Args {
dataParms: MethodArgs;
webViewRef: any;
}
// 统一封装react native调用H5及回调返回,通过promise的方式
export const reactNativeCallH5 = (
reactNativeCallH5Props: reactNativeCallH5Args,
) => {
const {dataParms, webViewRef} = reactNativeCallH5Props;
return new Promise((resolve, reject) => {
const {
channelName = defaultChannelName,
methodType = CallType.call,
methodName = 'methodName',
data = '',
} = dataParms;
const timeStr = `${new Date().getTime()}`;
const successKey = `${methodName}_${timeStr}_success`;
const errorKey = `${methodName}_${timeStr}_error`;
const obj: MethodCallArgs = {
channelName,
methodType,
methodName,
sourceMethodName: methodName,
data,
timeStr,
successKey,
errorKey,
};
// 挂载成功的回调
eventEmiter.on(successKey, res => {
resolve(res);
});
// 挂载失败的回调
eventEmiter.on(errorKey, err => {
reject(err);
});
webViewRef?.current?.postMessage(JSON.stringify(obj), '*');
});
};
|
import { Repository, SelectQueryBuilder } from 'typeorm';
import BaseService from '../../core/base-service';
import Goods from '../../model/entity/goods';
import GoodsTag from '../../model/entity/goods-tag';
import { GoodsQuery, GoodsResult } from '../../common/QueryInterface';
export default class GoodsService extends BaseService {
// -------------------------------------------------------------------------
// Public Properties
// -------------------------------------------------------------------------
// - 商品__实体
readonly Goods: Repository<Goods>;
// - 商品标签__实体
readonly GoodsTag: Repository<GoodsTag>;
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(ctx) {
super(ctx);
this.Goods = this.conn.getRepository(Goods);
this.GoodsTag = this.conn.getRepository(GoodsTag);
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
// - 获得所有的商品
async queryAll({
page = 1,
rows = 20,
disabledPage = false,
isOnline = 'all',
goodsNo = '',
goodsName }: GoodsQuery): Promise<GoodsResult> {
const where1: string = +goodsNo ? `G.goodsNo LIKE '%${goodsNo}%'` : '1 = 1';
const where2: string = goodsName ? `G.goodsName LIKE '%${goodsName}%'` : '1 = 1';
const where3: string = +isOnline === 1
? `G.isOnline = ${isOnline}`
: +isOnline === 0
? 'G.isOnline != 1'
: '1 = 1';
let query: SelectQueryBuilder<Goods> = this.Goods
.createQueryBuilder('G')
.where('ISNULL(G.deletedAt)')
.andWhere(where1)
.andWhere(where2)
.andWhere(where3)
.orderBy('G.updatedAt', 'DESC');
const total: number = await query.getCount();
if (!disabledPage) {
query = query
.skip((page - 1) * rows)
.take(rows);
}
const list: Goods[] = await query
.leftJoinAndSelect('G.categorys', 'GC')
.leftJoinAndSelect('G.tags', 'T')
.getMany();
return { list, total };
}
// - 查询单个商品信息
async queryOne(goodsNo: string): Promise<Goods> {
return await this.Goods
.createQueryBuilder('G')
.where('G.goodsNo = :goodsNo', { goodsNo })
.leftJoin('G.goodsDesc', 'GD')
.leftJoin('GD.tags', 'T')
.getOne() || this.Goods.create();
}
// - 删除一个商品
async deleteOne(rowData: Partial<Goods>): Promise<void> {
try {
await this.Goods.save({ ...rowData, deletedAt: new Date() });
} catch (err) {
this.error(err);
}
}
// - 根据id查找
async findById(id: number): Promise<Goods> {
return await this.Goods.findOne(id) || this.Goods.create();
}
// - 保存一个商品
async saveOne(rowData: Partial<Goods>): Promise<void> {
try {
await this.Goods.save(this.Goods.create(rowData));
} catch (err) {
this.error(err);
}
}
// - 创建新标签
async createTags(id: number, tags: string[]): Promise<void> {
let temp: GoodsTag[] = [];
try {
// - 先删除该商品之前存在的标签
await this.GoodsTag.delete({ goods: { id } })
for (const tagName of tags) {
temp.push(this.GoodsTag.create({ goods: { id }, tagName }));
}
// - 然后在保存新标签
this.GoodsTag.save(temp);
} catch (err) {
this.error(err);
}
}
// - 获得最大的商品编号
async getMaxGoodsNo(goodsNoPrefix: string): Promise<string> {
let maxNo: number = await this.Goods
.createQueryBuilder('G')
.where(`G.goodsNo LIKE :goodsNoPrefix '%'`, { goodsNoPrefix })
.getCount();
return goodsNoPrefix + this.ctx.helper.prefixZero(++maxNo, 4);
}
}
|
import numpy
import theano
import theano.tensor as T
import argparse
import mnist
"""HYPERPARAMS"""
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", type = int, default = 600, help = 'Size of the minibatch')
parser.add_argument("--n_iter", type = int, default = 50000)
parser.add_argument("--init_scale", type = float, default = 1e-6, help = 'Weights init scale')
parser.add_argument("--lr", type = float, default = 0.13, help= 'Learning Rate')
hparams = parser.parse_args()
print hparams
"""DATASET"""
dataset = mnist.MNIST()
"""PARAMS"""
n_in = 28*28
n_out = 10
# initialize the weights W as a matrix of shape (n_in, n_out)
W = theano.shared(
value=numpy.random.normal(scale=hparams.init_scale,size=(n_in, n_out)).astype(theano.config.floatX),
name='W'
)
# initialize the biases b as a vector of n_out 0s
b = theano.shared(
value=numpy.zeros((n_out,),dtype=theano.config.floatX),
name='b'
)
params = [W, b] # Lista de todos los parametros del modelo
"""MODEL"""
X = T.matrix('X') # data, presented as rasterized images
model_prob = T.nnet.softmax(T.dot(X, W) + b)
model_out = T.argmax(model_prob, axis=1)
"""LOSS"""
y = T.vector('y',dtype='int32')
loss = T.nnet.categorical_crossentropy(model_prob, y).mean()
"""OPTIMIZER"""
# SGD
# compute the gradient of cost with respect to theta = (W,b)
g_W = T.grad(cost=loss, wrt=W)
g_b = T.grad(cost=loss, wrt=b)
# specify how to update the parameters of the model as a list of
# (variable, update expression) pairs.
updates = [(W, W - hparams.lr * g_W),
(b, b - hparams.lr * g_b)]
"""TRAINING STEP FUNCTION"""
train_model = theano.function(
inputs=[X,y],
outputs=loss,
updates=updates
)
"""MONITOR FUNCTIONS"""
valid_model = theano.function(
inputs=[X,y],
outputs=loss,
updates=None
)
predict = theano.function(
inputs=[X],
outputs=model_out,
updates=None
)
"""TRANING MAIN LOOP"""
mon_frec = 1000
for it in xrange(hparams.n_iter):
X_train, y_train = dataset.get_train_batch(hparams.batch_size)
train_loss = train_model(X_train,y_train)
"""MONITOR"""
if it % mon_frec == 0:
X_valid, y_valid = dataset.get_valid_batch(hparams.batch_size)
valid_loss = valid_model(X_valid,y_valid)
y_pred = predict(X_valid)
valid_error = (y_pred != y_valid).mean()
y_pred = predict(X_train)
train_error = (y_pred != y_train).mean()
print it, train_loss, valid_loss, train_error, valid_error
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Gsharp;
using System.Threading;
using System.IO;
namespace Geo_Wall_E
{
public partial class Work : Form
{
public Work()
{
InitializeComponent();
}
private List<IFigure> Figures = new List<IFigure>();
#region Run Code
private void Button1_Click(object sender, EventArgs e)
{
ErrorShow.Text = "";
if (textBox1.Text == "") return;
//Reinicia el lienzo
lienzo.Refresh();
//Guarda la informacion del TextBox donde se escribe el codigo
string code = textBox1.Text;
//Hacemos una nueva lista
Figures = new List<IFigure>();
//Inicia el proceso de Tokenizacion, Parseo y Chequeo Semantico del codigo
try
{
SyntaxTree syntax = CallLogic.CallLogic.WorkWithCode(code);
foreach(var item in syntax.Program)
{
if(item is DrawStatement)
{
var test = (DrawStatement)item;
test.DrawThis += DrawFigure;
}
item.Execute();
Thread.Sleep(100);
}
}
catch(Exception E)
{
ErrorShow.Text = E.Message;
}
}
private void DebugButton_Click(object sender, EventArgs e)
{
int lines = 0;
string codeToDebug = "";
string temp = textBox1.Text;
if (numberDegub.Text != "")
{
lines = int.Parse(numberDegub.Text);
}
if (lines > 0 && lines < textBox1.Lines.Length)
{
for (int i = 0; i <= lines - 1; i++)
{
codeToDebug += textBox1.Lines[i] + "\n";
}
textBox1.Text = codeToDebug;
}
Button1_Click(sender, e);
textBox1.Text = temp;
}
#endregion
#region Save and Load
//Boton para Salvar Proyectos
private void Button2_Click(object sender, EventArgs e)
{
if(saveFileArchive.ShowDialog() == DialogResult.OK)
{
string path = saveFileArchive.FileName;
string code = textBox1.Text;
StreamWriter streamWriter = File.CreateText(path);
streamWriter.Write(code);
streamWriter.Flush();
streamWriter.Close();
}
}
//Boton para Cargar Proyectos
private void Button3_Click(object sender, EventArgs e)
{
if(openFile.ShowDialog() == DialogResult.OK)
{
string path = openFile.FileName;
string import = File.ReadAllText(path);
textBox1.Text = textBox1.Text + "\n" + import;
}
}
#endregion
#region Draw Section
public void DrawFigure(IFigure figure, string color)
{
/*Este método es el encargado de dibujar las figuras, llamando al método correspondiente.
Utiliza herramientas de Windows Form, el lector podrá darse cuenta de que hace cada método
solamente leyendo el codigo*/
Graphics graphics = lienzo.CreateGraphics();
Color actualColor = GetColor(color);
/*Antes de agregar una figura a la lista preguntar si no existe ninguna con su mismo nombre
Esta línea ayuda a la hora de trasladar las figuras en el lienzo*/
if (!(Figures.Any(x => x.Name == figure.Name))) { Figures.Add(figure); }
FigureType thisType = figure.GetFigureType();
//Chequear el tipo de figura para llamar al metodo correspondientes
if (thisType == FigureType.Point)
{
Gsharp.Point p1 = (Gsharp.Point)figure;
MyDrawPoint(p1, graphics);
return;
}
if (thisType == FigureType.Circle)
{
Circle c1 = (Circle)figure;
MyDrawCircle(c1, graphics, actualColor);
return;
}
if (thisType == FigureType.Segment)
{
Segment l1 = (Segment)figure;
MyDrawSegment(l1, graphics, actualColor);
return;
}
if (thisType == FigureType.Line)
{
Line l1 = (Line)figure;
MyDrawLine(l1, graphics, actualColor);
return;
}
if (thisType == FigureType.Ray)
{
Ray l1 = (Ray)figure;
MyDrawRay(l1, graphics, actualColor);
return;
}
if (thisType == FigureType.Arc)
{
Arc a1 = (Arc)figure;
MyDrawArc(a1, graphics, actualColor);
return;
}
}
//Draw point
private void MyDrawPoint(Gsharp.Point point, Graphics graphics)
{
graphics.FillEllipse(Brushes.Black, point.X - 3, point.Y - 3, 6, 6);
graphics.DrawString(point.Name, new Font("Arial", 10), Brushes.Black, point.X, point.Y);
}
//Draw Circle
private void MyDrawCircle(Circle circle, Graphics graphics, Color color)
{
graphics.DrawEllipse(new Pen(color), circle.Center.X - circle.Ratio, circle.Center.Y - circle.Ratio, (float)circle.Ratio * 2, (float)circle.Ratio * 2);
graphics.FillEllipse(Brushes.Black, circle.Center.X - 3, circle.Center.Y - 3, 6, 6);
}
//Draw Segment
private void MyDrawSegment(Segment line, Graphics graphics, Color color)
{
graphics.DrawLine(new Pen(color), line.p1.X, line.p1.Y, line.p2.X, line.p2.Y);
graphics.FillEllipse(Brushes.Black, line.p1.X - 3, line.p1.Y - 3, 6, 6);
graphics.FillEllipse(Brushes.Black, line.p2.X - 3, line.p2.Y - 3, 6, 6);
}
//Draw Line
private void MyDrawLine(Line line, Graphics graphics, Color color)
{
//Para dibujar una linea (recta en geometria) se usa la ecuación de la recta, para determinar
//los interceptos con el ancho y alto del lienzo, conociendo los dos puntos por los que la recta pasa
float m = line.GetPendiente();
float n = line.p1.Y - m * line.p1.X;
(Gsharp.Point, Gsharp.Point) interceps = GetIntersepts(m, n);
graphics.DrawLine(new Pen(color), interceps.Item1.X, interceps.Item1.Y, interceps.Item2.X, interceps.Item2.Y);
graphics.FillEllipse(Brushes.Black, line.p1.X - 3, line.p1.Y - 3, 6, 6);
graphics.FillEllipse(Brushes.Black, line.p2.X - 3, line.p2.Y - 3, 6, 6);
}
//Draw Ray
private void MyDrawRay(Ray line, Graphics graphics, Color color)
{
//Cuando conoce el punto inicial del rayo, halla los interceptos con los extremos del lienzo
//Mediante el uso del Vector Director y de la ecuacion de la recta se obtiene el sentido
//del rayo y bueno, luego se pinta
graphics.DrawLine(new Pen(color), line.p1.X, line.p1.Y, line.p2.X, line.p2.Y);
float m = line.GetPendiente();
float n = line.p1.Y - m * line.p1.X;
(Gsharp.Point, Gsharp.Point) interceps = GetIntersepts(m, n);
//Vector Director de la recta que pasa por los puntos del rayo
(float, float) vector1 = (line.p2.X - line.p1.X, line.p2.Y - line.p2.X);
//Vector Director del primer punto del rayo con respecto al intercepto mas a la izquierda
(float, float) vector2 = (interceps.Item1.X - line.p1.X, interceps.Item1.Y - line.p1.Y);
//Vector Director del primer punto del rayo con respecto al intercepto mas a la derecha
(float, float) vector3 = (interceps.Item2.X - line.p1.X, interceps.Item2.Y - line.p1.Y);
//Verficar si el sentido del rayo es el mismo que el sentido de la izquierda
if (vector1.Item1 > 0 && vector2.Item1 > 0 || vector1.Item1 < 0 && vector2.Item1 < 0)
{
graphics.DrawLine(new Pen(color), line.p1.X, line.p1.Y, interceps.Item1.X, interceps.Item1.Y);
}
//Verificar si el sentido del rayo es el mismo que el sentido de la derecha
else if (vector1.Item1 > 0 && vector3.Item1 > 0 || vector1.Item1 < 0 && vector3.Item1 < 0)
{
graphics.DrawLine(new Pen(color), line.p1.X, line.p1.Y, interceps.Item2.X, interceps.Item2.Y);
}
graphics.FillEllipse(Brushes.Black, line.p1.X - 3, line.p1.Y - 3, 6, 6);
graphics.FillEllipse(Brushes.Black, line.p2.X - 3, line.p2.Y - 3, 6, 6);
}
private void MyDrawArc(Arc arc, Graphics graphics, Color color)
{
graphics.FillEllipse(Brushes.Black, arc.origin.X - 3, arc.origin.Y - 3, 6, 6);
graphics.FillEllipse(Brushes.Black, arc.first.X - 3, arc.first.Y - 3, 6, 6);
graphics.FillEllipse(Brushes.Black, arc.second.X - 3, arc.second.Y - 3, 6, 6);
float startAngle = GetAngle(arc.origin, arc.second);
float endAngle = GetAngle(arc.origin, arc.first);
float possitiveStart = Math.Sign(startAngle) * startAngle;
float possitiveEnd = Math.Sign(endAngle) * endAngle;
float sweepAngle = 0;
if (Math.Sign(startAngle) == Math.Sign(endAngle))
{
if (startAngle < 0)
sweepAngle = possitiveStart > possitiveEnd ? possitiveStart - possitiveEnd : 360 - possitiveEnd + possitiveStart;
else
sweepAngle = possitiveStart > possitiveEnd ? 360 - possitiveStart + possitiveEnd : possitiveEnd - possitiveStart;
}
else
{
sweepAngle = Math.Sign(endAngle) > 0 ? possitiveEnd + possitiveStart : 360 - possitiveEnd - possitiveStart;
}
graphics.DrawArc(new Pen(color), arc.origin.X - arc.measure, arc.origin.Y - arc.measure, arc.measure * 2, arc.measure * 2, startAngle, sweepAngle);
}
private Color GetColor(string color)
{
switch (color)
{
case "red" : return Color.Red;
case "blue" : return Color.Blue;
case "yellow" : return Color.Yellow;
case "green" : return Color.Green;
case "cyan" : return Color.Cyan;
case "magenta" : return Color.Magenta;
case "white" : return Color.White;
case "gray" : return Color.Gray;
default: return Color.Black;
}
}
#endregion
#region Geometric Concepts
private float GetPendiente(Gsharp.Point p1, Gsharp.Point p2)
{
return ((p2.Y - p1.Y) / (p2.X - p1.X));
}
private (Gsharp.Point, Gsharp.Point) GetIntersepts(float m, float n)
{
float intercepUP = -(n / m);
if(intercepUP < 0)
{
return(new Gsharp.Point(0, n, ""), new Gsharp.Point((lienzo.Height - 1 - n) / m, lienzo.Height - 1, ""));
}
if(n < 0)
{
return (new Gsharp.Point(intercepUP, 0, ""), new Gsharp.Point(lienzo.Width - 1, m * lienzo.Width - 1 + n, ""));
}
return (new Gsharp.Point(intercepUP, 0, ""), new Gsharp.Point(0, n, ""));
}
private float GetAngle(Gsharp.Point p1, Gsharp.Point p2)
{
float m = GetPendiente(p1, p2);
float angle = (float)(Math.Atan(m) * 180 / Math.PI);
if (m >= 0)
{
angle = p1.Y > p2.Y ? -180 + angle : angle;
}
else
{
angle = p1.Y > p2.Y ? angle : 180 + angle;
}
return angle;
}
#endregion
#region Traslate Figures
private void Traslation(int X, int Y)
{
List<IFigure> traslates = new List<IFigure>();
lienzo.Refresh();
foreach (var item in Figures)
{
IFigure traslate = item.Traslate(X,Y);
DrawFigure(traslate, CompilatorTools.ColorPool.Peek());
traslates.Add(traslate);
}
Figures = traslates;
}
private void Up_Click(object sender, EventArgs e)
{
Traslation(0, -10);
}
private void Left_Click(object sender, EventArgs e)
{
Traslation(-10, 0);
}
private void PictureBox1_Click(object sender, EventArgs e)
{
Traslation(0, 10);
}
private void PictureBox4_Click(object sender, EventArgs e)
{
Traslation(10, 0);
}
#endregion
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
//if(e.KeyValue == (int)Keys.Enter || e.KeyValue == (int)Keys.Back)
{
lineCounter.Text = "";
for(int i = 1; i <= textBox1.Lines.Length; i++)
{
lineCounter.Text += i + "\r\n";
}
}
}
}
}
|
package adivinanzadenumero_ej5;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class AdivinanzaDeNumero_Ej5 {
public static void main(String[] args) {
/*
Escribir un programa en Java que juegue con el usuario a adivinar un número. La computadora
debe generar un número aleatorio entre 1 y 500, y el usuario tiene que intentar adivinarlo. Para
ello, cada vez que el usuario introduce un valor, la computadora debe decirle al usuario si el
número que tiene que adivinar es mayor o menor que el que ha introducido el usuario. Cuando
consiga adivinarlo, debe indicárselo e imprimir en pantalla el número de veces que el usuario
ha intentado adivinar el número. Si el usuario introduce algo que no es un número, se debe
controlar esa excepción e indicarlo por pantalla. En este último caso también se debe contar el
carácter fallido como un intento.
*/
//importar Scanner
Scanner leer = new Scanner(System.in).useDelimiter("\n");
//generar y asignar numero aleatorio
Random random = new Random();
int numeroSecreto = random.nextInt(500) + 1;
int numeroIngresado = 0;
//bucle do while para seguir pidiendo un numero y evaluando con try-catch
do {
//pedir el valor y asignarlo a una variable --> aca hacemos el try catch (InputMismatchException?)
System.out.println("Ingresa un nuemero para adivinar");
try {
numeroIngresado = leer.nextInt();
//informar al usuario si el valor es mayor o menor (if)
if (numeroIngresado != 0) {
if (numeroIngresado < numeroSecreto) {
System.out.println("El valor secreto es un numero mas grande!");
} else {
System.out.println("El valor secreto es un numero mas pequeno!");
}
}
} catch (InputMismatchException e) {
System.out.println("Se ha encontrado un error; " + e.getMessage());
System.out.println(e.toString());
leer.next();
}
} while (numeroSecreto != numeroIngresado);//aca va numeroSecreto != numeroIngresado
}
}
|
-------------------------------------------------------------------------------
--- ANSIFILTER MANUAL - Version 1.4 ------------------------- August 2010 ---
-------------------------------------------------------------------------------
OSI Certified Open Source Software
-------------------------------------------------------------------------------
Ansifilter handles text files containing ANSI terminal escape codes.
The command sequences may be stripped or be interpreted to generate formatted
output (HTML, RTF, TeX, LaTeX).
CONTENT:
-------------------------------------------------------------------------------
1. Quick introduction
2. Platforms
3. Features
4. Contact
1. Quick introduction
-------------------------------------------------------------------------------
File handling:
-i, --input=<file> Input file (optional)
-o, --output=<file> Output file (optional)
-t, --tail Continue reading after end-of-file (like tail -f)
Use system tail if available
Output text formats:
-T, --text (default) Output text
-H, --html Output HTML
-L, --latex Output LaTeX
-P, --tex Output Plain TeX
-R, --rtf Output RTF
Formatted text options:
-d, --doc-title Set HTML/LaTeX document title
-e, --encoding Set HTML encoding (must match input file encoding)
-F, --font=<font> Set HTML/RTF font face
-s, --font-size=<fs> Set HTML/RTF font size
-f, --fragment Omit HTML header and footer
-p, --plain Ignore formatting information
Other options:
-h, --help Print help
-v, --version Print version and license info
Examples:
ansifilter -i text_with_ansi.txt -o text_without_ansi.txt
ansifilter -i text_with_ansi.txt -o output.html --html
ansifilter *.txt
tail -f server.log | ansifilter
The GUI version (ansifilter-gui) also accepts the first command line argument
as input file name.
2. Platforms
-------------------------------------------------------------------------------
Ansifilter is currently available for Linux and Win32 platforms.
3. Features
-------------------------------------------------------------------------------
Supported control sequences:
ESC [ * m
ESC ] * ND
ESC ] Ps ND string NP
Supported commands:
Formatting: Bold, Underline, Italic, Blink
Colors: Black, Red, Green, Yellow, Blue, Magenta, Cyan, White
xterm 256 color modes
Other: Conceal/Reveal, Image positive/negative
All commands which issue the listed formatting options are supported.
Some options like Blink are not supported by all output formats (like RTF).
4. Contact
-------------------------------------------------------------------------------
Andre Simon
[email protected]
http://www.andre-simon.de/
http://wiki.andre-simon.de/
|
//
// DatePickerField.swift
//
//
// Created by Irshad Ahmad on 06/05/22.
//
//
// 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
public class DatePickerField: UITextField {
private let datePicker = UIDatePicker()
public var dateFormat = "MM/dd/yyyy"
public var dateChanged: ((Date) -> Void)?
public var mode: UIDatePicker.Mode = .date {
didSet {
self.setupPickerView()
}
}
public var minimumDate = Date(){
didSet {
self.setupPickerView()
}
}
public var selectedDate = Date(){
didSet {
self.setupPickerView()
}
}
public var maximumDate: Date?{
didSet {
self.setupPickerView()
}
}
public override func awakeFromNib() {
super.awakeFromNib()
createDatePicker()
setupToolBar()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func createDatePicker() {
if #available(iOS 13.4, *) {
datePicker.preferredDatePickerStyle = .wheels
}
datePicker.addTarget(self, action: #selector(pickerDidChange(_:)), for: .valueChanged)
self.inputView = datePicker
setupPickerView()
}
private func setupPickerView() {
datePicker.datePickerMode = mode
datePicker.date = selectedDate
datePicker.minimumDate = minimumDate
datePicker.maximumDate = maximumDate
}
private func setupToolBar() {
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor.systemBlue
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(textDidEndEditing))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolBar.setItems([spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
self.inputAccessoryView = toolBar
}
@objc private func pickerDidChange(_ picker: UIDatePicker) {
self.text = picker.date.string(withFormat: dateFormat)
}
@objc private func textDidEndEditing() {
dateChanged?(datePicker.date)
self.text = datePicker.date.string(withFormat: dateFormat)
self.resignFirstResponder()
}
}
|
<template>
<div :class="className" :style="{height:height,width:width}"/>
</template>
<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
const animationDuration = 6000
export default {
props: {
className: {
type: String,
default: 'chart'
},
width: {
type: String,
default: '100%'
},
height: {
type: String,
default: '300px'
},
state: {
type: Object,
required: true
}
},
data() {
return {
chart: null
}
},
watch: {
state: {
deep: true,
handler(val) {
this.setOptions(val)
}
}
},
mounted() {
this.initChart()
this.__resizeHandler = debounce(() => {
if (this.chart) {
this.chart.resize()
}
}, 100)
window.addEventListener('resize', this.__resizeHandler)
},
beforeDestroy() {
if (!this.chart) {
return
}
window.removeEventListener('resize', this.__resizeHandler)
this.chart.dispose()
this.chart = null
},
methods: {
initChart() {
this.chart = echarts.init(this.$el, 'macarons')
},
setOptions({ dayData,eviData,stealData } = {}) {
this.chart.setOption({
tooltip: {
trigger: 'axis',
axisPointer: { // 坐标轴指示器,坐标轴触发有效
type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
grid: {
top: 10,
left: '2%',
right: '2%',
bottom: '3%',
containLabel: true
},
xAxis: [{
type: 'category',
data: dayData,
axisTick: {
alignWithLabel: true
}
}],
yAxis: [{
type: 'value',
axisTick: {
show: false
}
}],
series: [{
name: '盗窃案',
type: 'bar',
stack: 'vistors',
barWidth: '60%',
data: stealData,
animationDuration
},{
name: '现勘数',
type: 'bar',
stack: 'vistors',
barWidth: '60%',
data: eviData,
animationDuration
},]
})
}
}
}
</script>
|
Use Case: High Performance Computing software for MPI (Message Passing Interface) applications
Code details and examples:
MVAPICH2 is an MPI library designed for high-performance computing. Here is an example of running a simple MPI application using MVAPICH2:
1. Sample MPI application (hello.c):
```c
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[]) {
int rank, size;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
printf("Hello world from rank %d out of %d\n", rank, size);
MPI_Finalize();
return 0;
}
```
2. Compiling the MPI application:
```bash
mpicc -o hello hello.c
```
3. Running the MPI application using MVAPICH2:
```bash
mpirun -np 4 ./hello
```
This will run the "hello" MPI application with 4 processes.
Note: The actual command to run MPI applications may vary depending on your MPI installation and system configuration.
|
import React, { useState } from 'react';
import { Tilt } from 'react-tilt';
import { motion, spring } from 'framer-motion';
import { styles } from '../styles';
import { github, web } from '../assets';
import { SectionWrapper } from '../hoc';
import { projects } from '../constants';
import { fadeIn, textVariant } from '../utils/motion';
/* const ProjectCard = ({ project}) => {
console.log('Coming from Project Card', project);
return (
<div>
<h1>{projects.name}</h1>
<p> My Projects </p>
</div>
)
} */
const ProjectCard = ({ index, name, description, tags, image, source_code_link, website_link }) => {
console.log('projects', projects);
console.log(index)
return (
<motion.div>
<Tilt options={{ max: 45, scale: 1, speed: 450 }}
className="bg-tertiary p-5 rounded-2xl sm:w-[360PX] w-full ">
<div className='relative w-full h-[230px] '>
<img
src={image}
alt={name}
className="w-full h-full object-cover rounded-2xl"
/>
<div className="absolute inset-0 flex justify-end m-3 card-img_hover">
<div
onClick={() => window.open(source_code_link, "_blank")}
className='black-gradient w-10 h-10 rounded-full flex justify-center items-center cursor-pointer'
>
<img
src={github}
alt="github"
className="w-1/2 h-1/2 object-contain"
/>
</div>
<div
onClick={() => window.open(website_link, "_blank")}
className='black-gradient w-10 h-10 rounded-full flex justify-center items-center cursor-pointer'
>
<img
src={web}
alt="web"
className="w-1/2 h-1/2 object-contain"
/>
</div>
</div>
</div>
<div className="mt-5">
<h3 className='text-white font-bold text-[22px]'>{name}</h3>
<p className="mt-2 text-secondary text-[14px]">
{description.length > 175 ? description.substring(0, 175) + "..." : description}
</p>
</div>
<div className="mt-4 flex flex-wrap gap-2">
{tags.map((tag) => (
<p key={tag.name} className={`text-[14px] ${tag.color}`}>
#{tag.name}
</p>
))}
</div>
</Tilt>
</motion.div>
)
}
const Works = () => {
const [loadmore, setLoadmore] = useState(false)
const loadMore = () => {
setLoadmore(true)
setDisplayData(projects);
console.log("Loading clicked")
}
console.log("current load more state:", loadmore)
const [displayData, setDisplayData ] = useState(projects.slice(0, 3))
// const displayData = loadmore ? projects : projects.slice(0, 3) //display only 3 data
console.log(displayData, 'this is coming from works')
//console.log(typeof displayData)
console.log('Data from Projects', projects)
return (
<>
<motion.div variants={textVariant()}>
<p className={`${styles.sectionSubText} `}>A Journey Through My Projects</p>
<h2 className={`${styles.sectionHeadText}`}>Code Chronicles.</h2>
</motion.div>
<div className='w-full flex'>
<motion.p
variants={fadeIn("", "", 0.1, 1)}
className='mt-3 text-secondary text-[17px] max-w-3xl leading-[30px]'
>
Welcome to - A Journey Through My Projects - You will find a selection
of my work right here, each representing the passion and commitment I
put into it. Each project highlights particular difficulties overcame
and abilities improved. They show off my skills on their own, but
when combined, they show how far I've come as a professional.
I encourage you to look over these achievements, which show my dedication
to lifelong learning and the pursuit of excellence.
</motion.p>
</div>
<div className='mt-20 flex flex-wrap gap-7'>
{/* {projects.map((project, index) => (
<ProjectCard key={`project-${index}`} index={index} {...project} />
))} */}
{displayData.map((project, index) => {
console.log(`Rendering project at index ${index}:`, project);
console.log(project, 'from displayData map')
//return <ProjectCard index={index} project={project} />
return <ProjectCard key={`project-${index}`} index={index} {...project} />
})}
</div>
<div className='mt-10 gap-5 flex flex-col items-center'>
<button className="violet-gradient uppercase text-xs hover:bg-blue-500 text-white py-2 px-2 border-b-4 border-blue-700 hover:border-blue-400 rounded" onClick={loadMore} >
Load More Projects
</button>
</div>
</>
)
}
export default SectionWrapper(Works, "portfolio")
|
Availability:Public
Title:Struct Variables in Blueprints
Crumbs: %ROOT%, Engine, Engine/Blueprints, Engine/Blueprints/Scripting
Description: Blueprint struct variables allow you to store different data types that contain related information together.
version: 4.12
skilllevel:Intermediate
Parent:Engine/Blueprints/Scripting
tag:Arrays and Structures
type:overview
tags:Blueprints
[TOC]
A struct is a collection of different types of data that are related and held together for easy access. You've probably used simple structs in Blueprints already, as
Vectors, Rotators, and Transforms are all struct variables. For example, a Vector struct holds an X float, a Y float, and a Z float variable that are related to each other.
Structs can also nest their data. A Transform struct holds Location (a Vector struct), Rotation (a Rotator struct), and Scale (a Vector struct) data about an Actor.
## Creating Structs
You add a struct variable to your Blueprint in the same way you add any other [Blueprint variable](Engine/Blueprints/UserGuide/Variables). Simple structs, like Vectors, Rotators, and Transforms, are listed in the top section of the variable type dropdown menu.

There is also a **Structure** section of the dropdown menu, where you can find all struct variables currently available to your Blueprint.

## Accessing Struct Information
Because structs work by bundling data together, you also need to work on accessing those smaller chunks of information. You can do that through a few different methods:
### Splitting Struct Pins
If you want to be able to access the individual variables in a struct on a single node, splitting struct pins can be a helpful tool.
To split a struct pin, right-click on the pin and select **Split Struct Pin**.

This exposes all of the variables contained within the struct as individual pins on the node, allowing you to enter values or manipulate them independently.

To undo a **Split Struct Pin**, right-click on any of the new pins and select **Recombine Struct Pin**.

You can split and recombine both input and output struct pins.
### Breaking Structs
Often, taking apart a struct into its individual parts will be gameplay logic you repeat in a function or macro. Using a **Break Struct** node allows you to replicate that behavior throughout your Blueprint graph easily.
To create a **Break Struct** node, drag off of a struct output pin and select **Break [Struct Name]** from the context menu.

The **Break Struct** node will have a different name and different output pins depending on the struct you use, but overall will break the struct into its individual parts.

For example, if you always want to work with the **Impact Point**, **Hit Component**, and **Hit Bone Name** of a **Hit Result**, you can have a **Break Hit Result** node inside a function that means that you can just input **Hit Result**
as a function input, and always have those three data pieces separated out inside the function.

### Making Structs
Much like you can break a struct into its individual pieces of data, you can make a struct out of the right data as well.
To create a **Make Struct** node, drag off of a struct input pin and select **Make [Struct Name]** from the context menu.

The **Make Struct** node will have a different name and different input pins depending on the struct you use, but overall will enable you to build a struct out of all the data it contains.

### Setting Members in Structs
Sometimes, structs can contain a lot of data, and you only want to change a few elements out of that set. Setting members in a struct enables you to be very specific about what data you change, without having to wire up all the
data pins that are remaining constant.

To change which members are available through the **Set Members in Struct** node, select the node. In the **Details** panel, there are checkboxes for each possible member to expose as a pin on the node. Member variables that are not exposed
will not be changed by the **Set Members in Struct** node.

|
from bs4 import BeautifulSoup, NavigableString
import urllib.request
import sys
import re
import os
class WebnovelDownloader(object):
# Get list of chapter urls
def get_chapter_urls(self) -> list[str]:
return []
def extract_chapter_title(self, chapter_soup) -> str:
return ""
def extract_chapter_content(self, chapter_soup, chapter_url:str) -> str:
return ""
# override this if a single url has multiple chapters in it
def get_soups(self,chapter_url) -> list:
return [get_soup(chapter_url)]
def setup_download(self, url_batch_size=50):
self.url_offset=0
self.downloaded_chapters=0
self.url_batch_size=url_batch_size
# TODO: setup download dir
self.file_dir = "chapters"
i=4
while os.path.exists(f"{self.file_dir}-{i}"):
i+=1
self.file_dir = f"{self.file_dir}-{i}"
os.mkdir(self.file_dir)
print(f"Saving in {self.file_dir}/")
def download(self,num=-1,url_batch_size=50):
if num>0:
url_batch_size = min(num,url_batch_size)
self.setup_download(url_batch_size)
while not self.done_downloading():
self.download_batch()
if num>0:
if self.downloaded_chapters>=num:
return
if num - self.url_offset < self.url_batch_size:
self.url_batch_size = num - self.url_offset
def done_downloading(self) -> bool:
return self.url_offset >= len(self.get_chapter_urls())
def download_batch(self) -> int:
"""Downloads the next batch of chapters
"""
if self.url_batch_size <= 0:
print("Must call setup_download with positive batch size first")
return
urls = self.get_chapter_urls()[self.url_offset:self.url_offset+self.url_batch_size]
for chapter_url in urls:
for chapter_soup in self.get_soups(chapter_url):
try:
self.save_chapter(chapter_soup, chapter_url, self.downloaded_chapters)
except IndexError as err: # Exception
print(f"Unable to download chapter at: {chapter_url}")
print(err)
self.downloaded_chapters+=1
if (self.downloaded_chapters) % 50 == 0:
print(f"... so far, tried {self.downloaded_chapters} chapter urls...")
self.url_offset+=1
def save_chapter(self, chapter_soup, chapter_url, chapter_i:int):
try:
title = self.extract_chapter_title(chapter_soup)
content = self.extract_chapter_content(chapter_soup, chapter_url)
except:
print(f"Unable to parse chapter at {chapter_url}")
err_file = f"{self.file_dir}/err/chapter-{chapter_i+1:06}.xhtml"
print(f"Attempting to write it to {err_file}")
if not os.path.exists(f"{self.file_dir}/err"):
os.mkdir(f"{self.file_dir}/err")
with open(err_file, "w", encoding="utf8") as file:
file.write(chapter_soup.prettify())
return
with open(f"{self.file_dir}/chapter-{chapter_i+1:06}.xhtml", "w", encoding="utf8") as file:
file.write("<?xml version='1.0' encoding='utf-8'?>\n")
file.write('<html xmlns="http://www.w3.org/1999/xhtml">\n')
file.write(f"<head>\n<title>{title}</title>\n</head>\n")
file.write(f"<body>\n<h1>{title}</h1>\n{content}\n</body>\n</html>")
class ParameterizedDownloader(WebnovelDownloader):
# Constructor
def __init__(self, toc_url:str, toc_selector:str, chapter_text_selector:str, include_toc:bool):
"""Encapsulates toc-like downloading options.
@toc_url: E.g. https://shanastoryteller.tumblr.com/post/724074957212172288/happy-pride-fem-mxy-wwx-pls
@toc_selector: e.g. ".captext a"
@chapter_text_selector: e.g. .captext
"""
self.toc_url = toc_url
self.toc_selector = toc_selector
self.chapter_text_selector = chapter_text_selector
self.chapter_urls = []
self.chapter_number = 0
self.include_toc = include_toc
def get_chapter_urls(self) -> list[str]:
# cache this so we don't need to do num_toc_pages web requests every time
if self.chapter_urls == []:
self.chapter_urls = get_chapter_urls_from_toc(self.toc_url,self.toc_selector)
if self.include_toc:
self.chapter_urls = self.chapter_urls + [self.toc_url]
return self.chapter_urls
def extract_chapter_title(self, chapter_soup):
self.chapter_number += 1
return f"Chapter {self.chapter_number}"
def extract_chapter_content(self, chapter_soup, chapter_url:str):
content = '\n'.join(
f"{clean(x, chapter_url).prettify()}" for x in chapter_soup.select(self.chapter_text_selector, limit=1))
return content
# table of contents:
# https://novelfull.com/reincarnation-of-the-strongest-sword-god.html
# https://novelfull.com/reincarnation-of-the-strongest-sword-god.html?page=2
# ...
# https://novelfull.com/reincarnation-of-the-strongest-sword-god.html?page=64
# "a" descendents of "list-chapter" will contain links to chapters
#
# per chapter:
# title: .chapter-title
# content: #chapter-content
class NovelfullDownloader(WebnovelDownloader):
# Constructor
def __init__(self, toc_url:str, num_toc_pages:int):
"""Encapsulates novelfull.com-specific downloading options.
@toc_url: E.g. https://novelfull.com/reincarnation-of-the-strongest-sword-god.html
@num_toc_pages: e.g. 65
"""
self.toc_url = toc_url
self.num_toc_pages = num_toc_pages
self.chapter_urls = []
def get_chapter_urls(self) -> list[str]:
# cache this so we don't need to do num_toc_pages web requests every time
if self.chapter_urls == []:
chapter_urls = []
for toc_url in [f"{self.toc_url}?page={x}" for x in range(1,self.num_toc_pages+1)]:
chapter_urls.extend(get_chapter_urls_from_toc(toc_url,".list-chapter a"))
self.chapter_urls = chapter_urls
return self.chapter_urls
# For https://novelfull.com/reincarnation-of-the-strongest-sword-god.html
def extract_chapter_title(self, chapter_soup):
return chapter_soup.select(".chapter-title", limit=1)[0].text
# For https://novelfull.com/reincarnation-of-the-strongest-sword-god.html
def extract_chapter_content(self, chapter_soup, chapter_url:str):
content = '\n'.join(
f"{clean(x, chapter_url).prettify()}" for x in chapter_soup.select("#chapter-content"))
return content
# chapter urls:
# https://www.wuxiaworld.eu/chapter/the-e-sports-circles-toxic-assembly-camp-# for 1-216, -106
# chapter text: Array.from(document.querySelectorAll("#chapterText")).map(div => div.innerHTML)
class WuxiaWorldEuDownloader(WebnovelDownloader):
# Constructor
def __init__(self, base_chapter_url:str, chapters:int):
"""Encapsulates www.wuxiaworld.eu-specific downloading options.
@base_chapter_url: E.g. https://www.wuxiaworld.eu/chapter/the-e-sports-circles-toxic-assembly-camp-
@chapters: number of chapters, e.g. 216)
"""
# https://www.wuxiaworld.eu/novel/the-e-sports-circles-toxic-assembly-camp
# to:
# https://www.wuxiaworld.eu/chapter/the-e-sports-circles-toxic-assembly-camp-
if "www.wuxiaworld.eu/novel/" in base_chapter_url:
base_chapter_url = f"{base_chapter_url.replace('/novel/','/chapter/')}-"
self.base_chapter_url = base_chapter_url
self.chapters = chapters
def get_chapter_urls(self) -> list[str]:
# chapters are at:
# https://www.wuxiaworld.eu/chapter/the-e-sports-circles-toxic-assembly-camp-#
# so base url is:
# https://www.wuxiaworld.eu/chapter/the-e-sports-circles-toxic-assembly-camp-
return [f"{self.base_chapter_url}{x}" for x in range(1,self.chapters+1)]
def extract_chapter_title(self,chapter_soup) -> str:
return chapter_soup.select("h1", limit=1)[0].text
def extract_chapter_content(self,chapter_soup, chapter_url:str) -> str:
# for some reason all the chapter paragraphs are actually divs with id #chapterText
content = '\n'.join(
f"{clean(x, chapter_url).prettify()}" for x in chapter_soup.select("#chapterText"))
content = re.sub("<div[^>]*>", "<p>", content).replace("</div>","</p>")
content = re.sub("<p>\s*</p>", "", content)
return content
def canonical(orig_url:str, relative_url:str) -> str:
m = re.search(r'https?://.*', relative_url)
if m:
return relative_url
m = re.search(r'https?://[^/]*', orig_url)
return f"{m.group(0)}{relative_url}"
def get_soup(url:str) -> BeautifulSoup:
# this sets a non-robot user agent so we don't get blocked
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
headers = {'User-Agent': user_agent, }
request = urllib.request.Request(
url, None, headers) # The assembled request
response = urllib.request.urlopen(request)
return BeautifulSoup(response.read(), "lxml")
def remove_style_attribute(element):
if isinstance(element, NavigableString):
return
if element.has_attr('style'):
element['data-orig-style'] = element['style']
del element['style']
def clean(content, orig_url):
# remove ads, scripts, and styles
for data in content.select('script, style, .ads, .adsbygoogle'):
data.decompose()
# remove styles specified as attributes
remove_style_attribute(content)
for descendant in content.descendants:
remove_style_attribute(descendant)
# totally empty filler elements (and their otherwise empty parents)
# can go bye bye
for data in content.select('div, p, span'):
# (no text or child elements)
while data.text.strip() == "" and len(data.find_all()) == 0:
parent = data.parent
data.decompose()
data = parent
# technically if it's linking to another chapter or something it makes
# more sense to link within the epub, but eh.
for data in content.select('[href]'):
# this is a half-assed attempt to not break footnotes
if not data["href"].startswith('#'):
data["href"] = canonical(orig_url, data["href"])
return content
def get_chapter_urls_from_toc(toc_url:str, chapter_url_selector:str) -> list[str]:
soup = get_soup(toc_url)
return [canonical(toc_url, x["href"]) for x in soup.select(chapter_url_selector)]
print('Usage:\npython webnovel-downloader.py <url> <number of chapters/toc pages; defaults to 1> <num chapters to download; defaults to 1; set to "all" to override>\n')
url = sys.argv[1]
if not url.startswith("http"):
sys.exit()
else:
print(f"Fetching novel from: {url}")
num = 1
if len(sys.argv)>=3:
num = int(sys.argv[2])
restrict_downloads = True
download_num = 1
if len(sys.argv)>=4:
try:
download_num = int(sys.argv[3])
except ValueError:
restrict_downloads = False
downloader = None
if "www.wuxiaworld.eu" in url:
downloader = WuxiaWorldEuDownloader(url,num)
elif "novelfull.com" in url:
downloader = NovelfullDownloader(url,num)
elif "tumblr" in url:
downloader = ParameterizedDownloader(url,".captext a",".captext",True)
else:
print("unsupported url host; please implement a WebnovelDownloader to handle parsing")
if downloader is not None:
if restrict_downloads:
downloader.download(download_num)
else:
downloader.download()
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import allReducers from './reducers'
import {Provider} from 'react-redux'
import {persistStore, autoRehydrate} from 'redux-persist'
import { PersistGate } from 'redux-persist/integration/react';
const store = createStore(
allReducers,
// applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
const persistor = persistStore(store)
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate persistor={persistor}>
<App />
</PersistGate>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
|
import React, { useState } from "react";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
const Login = () => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleLogin = () => {
if (!username || !password) {
console.error("Make sure to fill both fields!");
toast.error("Login failed. Input username and password.");
return;
}
// API request
fetch("http://localhost:3001/Login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username, password }),
})
.then((response) => {
if (response.status === 200) {
toast.success("Login successful.");
setUsername("");
setPassword("");
} else if (response.status === 401) {
toast.error("Login failed, wrong credentials.");
} else {
toast.error("Login failed. Please try again after some time.");
}
})
.catch((error) => {
console.error("Login error: ", error);
toast.error("Login error. Please try again after some time.");
});
};
return (
<div>
<h3>Login</h3>
<form>
<label>
Username:
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
</label>
<br />
<label>
Password:
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</label>
<br />
<button type="button" onClick={handleLogin}>
Login
</button>
</form>
<ToastContainer />
</div>
);
};
export default Login;
|
<template>
<a-card title="项目" :bordered="false" size="medium" style="overflow: hidden">
<a-card-grid :style="{ width: '33.33%' }" v-for="(item, index) in list" :key="item.name" class="card-grid-item">
<a-card :bordered="false" hoverable :class="'animated-fade-up-' + index">
<div class="head">
<GiSvgIcon :size="30" :name="item.icon"></GiSvgIcon>
<span>{{ item.name }}</span>
</div>
<p class="text">{{ item.text }}</p>
<p class="desc">{{ item.time }}</p>
</a-card>
</a-card-grid>
</a-card>
</template>
<script setup lang="ts">
const list = [
{
name: 'Github',
text: '是一个面向开源及私有软件项目的托管平台',
time: '开源君 2021-07-04',
icon: 'item-github'
},
{
name: 'Vue',
text: '渐进式 JavaScript 框架',
time: '学不动也要学 2021-07-04',
icon: 'item-vue'
},
{
name: 'Html5',
text: 'HTML5是互联网的下一代标准',
time: '撸码也是一种艺术 2021-04-01',
icon: 'item-html5'
},
{
name: 'Angular',
src: '../../assets/images/home/angular.png',
text: '现代 Web 开发平台 百万粉丝热捧',
time: '铁粉君 2021-07-04',
icon: 'item-angular'
},
{
name: 'React',
text: '用于构建用户界面的 JavaScript 库',
time: '技术牛 2021-07-04',
icon: 'item-react'
},
{
name: 'Js',
text: '路是走出来的 而不是空想出来的',
time: '架构组 2021-07-04',
icon: 'item-js'
}
]
</script>
<style lang="scss" scoped>
:deep(.arco-card-header) {
border: none;
}
.head {
display: flex;
align-items: center;
span {
margin-left: 10px;
font-size: 1.125rem;
line-height: 1.75rem;
color: var(--color-text-2);
}
}
.text {
margin-top: 10px;
line-height: 1.4;
height: 50px;
color: var(--color-text-3);
}
.desc {
font-size: 12px;
color: var(--color-text-3);
}
</style>
|
import {useState} from 'react'
import { StyleSheet, Text, View, StatusBar, TextInput, Platform, Pressable,ScrollView, ActivityIndicator, Alert, Keyboard } from "react-native";
import{MaterialIcons} from '@expo/vector-icons'
import Slider from '@react-native-community/slider'
const StatusBarHeight = StatusBar.currentHeight
const KEY_GPT ='SUA CHAVE AQUI';
export default function App(){
const[city, setCity] = useState("");
const[day, setDay] = useState(1);
const [loading, setLoading] = useState (false);
const [travel, setTravel] = useState("");
async function handleGenerate(){
if(city === ""){
Alert.alert("Atenção","Preencha a cidade destino")
return;
}
setTravel("")
setLoading(true);
Keyboard.dismiss();
const prompt = 'Crie um roteiro para um viagem de exatos ${day.toFixed(0)} dias na cidade de ${city}, busque por pontos turisticos, locais mais visitados com uma boa recomendação, seja preciso nos dias de estadia fornecidos e limite o roteiro apenas na cidade fornecida. Forneça em topicos com nome do local onde ir em cada dia.'
fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers:{
"Content-Type": "application/json",
Authorization: ` Bearer ${KEY_GPT} `
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages:[
{
role: 'user',
content: prompt
}
],
temperature: 0.20,
max_tokens: 500,
top_p: 1,
})
})
.then(response => response.json())
.then((data) => {
if (data && data.choices && data.choices.length > 0 && data.choices[0].message && data.choices[0].message.content) {
console.log(data.choices[0].message.content);
setTravel(data.choices[0].message.content);
} else {
console.log('Resposta inválida da API OpenAI');
}
})
.catch((error) => {
console.log('Erro na requisição:', error);
Alert.alert('Erro', 'Ocorreu um problema ao processar a solicitação.');
})
.finally(()=>{
setLoading(false);
})
}
return(
<View style={styles.container}>
<StatusBar barStyle="dark content" translucent={true} backgroundColor="#F1F1F1"/>
<Text style={styles.heading}>Roteiro de viagem</Text>
<View style={styles.form}>
<Text style={styles.label}>Destino</Text>
<TextInput
placeholder="Teresina, PI"
style={styles.imput}
values={city}
onChangeText={(text) => setCity(text)}
/>
<Text>Tempo de Estadia: <Text style={styles.day}> {day.toFixed(0)} </Text>Dias</Text>
<Slider
minimumValue={1}
maximumValue={30}
minimumTrackTintColor="#009688"
maximumTrackTintColor="#000000"
value={day}
onValueChange={(value) => setDay (value)}
/>
</View>
<Pressable style={styles.button} onPress={handleGenerate}>
<Text style={styles.buttonText}>Gerar Roteiro</Text>
<MaterialIcons name="travel-explore" size={24} color={"#fff"}/>
</Pressable>
<ScrollView style={styles.containerScroll} showsVerticalScrollIndicator={false}>
{loading &&( <View style={styles.content}>
<Text style={styles.title}>Carregando roteiro...</Text>
<ActivityIndicator color="#000" size ="large"/>
</View>)}
{travel &&(
<View style={styles.content}>
<Text style={styles.title}>Roteiro da viagem</Text>
<Text>{travel}</Text>
</View>
)}
</ScrollView>
</View>
);
}
const styles= StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#d3d3d3",
alignItems:'center',
paddingTop:20,
},
heading:{
fontSize:32,
fontWeight:'bold',
paddingTop:Platform.OS == 'android' ? StatusBar: 34
},
form:{
backgroundColor:'#fff',
width:'90%',
borderRadius: 8,
padding: 16,
marginTop:16,
marginBottom:8,
},
label:{
fontWeight:'bold',
fontSize: 18,
marginBottom: 8,
},
imput:{
borderWidth:1,
borderRadius: 4,
borderColor:'#94a3b8',
padding: 8,
fontSize: 16,
marginBottom: 16,
},
day:{
backgroundColor: '#f1f1f1',
},
button:{
backgroundColor:'#ff5656',
width: '90%',
borderRadius: 8,
flexDirection:'row',
padding: 14,
justifyContent:'center',
alignItems:'center',
gap:8,
},
buttonText:{
fontSize: 18,
color: '#fff',
fontWeight: 'bold',
},
content:{
backgroundColor:'#fff',
padding: 16,
width:'100%',
marginTop: 16,
borderRadius: 8,
},
title:{
fontSize: 18,
fontWeight:'bold',
textAlign: 'center',
marginBottom: 14,
},
containerScroll:{
width: '90%',
marginTop: 8,
},
});
|
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Explorer</title>
<link th:href="@{styles/main.css}" rel="stylesheet" />
</head>
<body>
<!--Надпись текущий каталог-->
<p th:if="${not explorer.isDisk}" th:text="'Текущий каталог: ' + ${explorer.dir.getName}"></p>
<p th:if="${explorer.isDisk}" th:text="'Этот компьютер'"></p>
<!--Кнопка назад-->
<form th:if="${not explorer.isRoot and not explorer.isDisk}" method="post" th:action="@{/(param=${explorer.dir.getParent})}" class="inline">
<button type="submit" class="backbtn">▲</button>
</form>
<form th:if="${explorer.isRoot and not explorer.isDisk}" method="post" th:action="@{/(param=root)}" class="inline">
<button type="submit" class="backbtn">▲</button>
</form>
<!--Абсолютный путь-->
<div th:if="${not explorer.isDisk}" th:text="${explorer.dir.getAbsolutePath}" class="inline"></div>
<div th:if="${explorer.isDisk}" th:text="'Устройства и диски'" class="inline"></div>
<!--Таблица файлов-->
<table>
<!--Заголовки-->
<thead>
<td class="icon">Имя</td>
<td class="name"></td>
<td class="date">Дата изменения</td>
<td class="type">Тип</td>
<td class="sizelable">Размер</td>
</thead>
<tr th:each="file: ${explorer.filesData}" class="content">
<td th:text="${file.isDirectory}? '📁' : '📄' " class="icon"></td>
<!--Кнопка, если папка-->
<td th:if="${file.isDirectory}" class="name">
<form method="post" th:action="@{/(param=${file.path})}">
<button th:if="${not explorer.isDisk}" type="submit" th:text="${file.name}"></button>
<button th:if="${explorer.isDisk}" type="submit" th:text="${file.path}"></button>
</form>
</td>
<!--Название файла, если не кнопка-->
<td th:if="${not file.isDirectory}" th:text="${file.name}" class="name"></td>
<!--Дата изменения-->
<td th:text="${file.lastModified}" class="date"></td>
<!--Тип-->
<td th:text="${file.type}" class="type"></td>
<!--Размер-->
<td th:text="${not file.isDirectory}? ${file.size}" class="size"></td>
</tr>
</table>
</body>
</html>
|
import React, { FC, useContext } from 'react'
import Modal from '@/components/01_atoms/Modal'
import DotPulse from '@/components/01_atoms/DotPulse'
import { Button } from '@mui/material'
import Container from '@mui/material/Container'
import { ContainerProps, WithChildren } from 'types'
import * as styles from './styles'
import { connect } from '@/components/hoc'
import { Context } from '@/components/05_layouts/HtmlSkeleton'
import MainService from '@/services/main'
import * as _ from 'lodash'
/** ReceiveCallModalProps Props */
export type ReceiveCallModalProps = WithChildren
/** Presenter Props */
export type PresenterProps = ReceiveCallModalProps & {
main
isOpen
connectionId
name
photo
}
/** Presenter Component */
const ReceiveCallModalPresenter: FC<PresenterProps> = ({
main,
isOpen,
connectionId,
name,
photo,
...props
}) => (
<>
<Modal isOpen={isOpen} hideCloseBtn={true}>
<Container component="main">
<div className={styles.notion}>
<div className="myHeadPhoto">
<img src={photo} alt="" />
</div>
<div className="myName">{name}</div>
<div className="btn">
<Button
color="secondary"
onClick={(e) => main.video.sendRejectCall(connectionId)}
type="submit"
variant="contained"
>
また後で
</Button>
<Button
color="primary"
onClick={(e) => main.video.sendAcceptCall(connectionId)}
type="submit"
variant="contained"
>
いいよ!
</Button>
</div>
<div className="loading">
<div className="snippet" data-title=".dot-pulse">
<div className="stage">
<DotPulse />
</div>
</div>
</div>
</div>
</Container>
</Modal>
</>
)
/** Container Component */
const ReceiveCallModalContainer: React.FC<
ContainerProps<ReceiveCallModalProps, PresenterProps>
> = ({ presenter, children, ...props }) => {
const main = useContext<MainService | null>(Context)
if (!main) return <></>
if (_.size(main.video.members) === 0) return <></>
const isOpen = main.video.nowCallReceiving
const { connectionId, name, photo } = main.video.members[0]
return presenter({
children,
main,
isOpen,
connectionId,
name,
photo,
...props,
})
}
export default connect<ReceiveCallModalProps, PresenterProps>(
'ReceiveCallModal',
ReceiveCallModalPresenter,
ReceiveCallModalContainer
)
|
import React from "react";
import './style.css';
import Title, { TitleSize } from "../../UI/title/title";
import Switch from "../switch/switch";
import Button, { buttonsFunction, buttonsTypes } from "../../UI/button/Button";
function OrderModal ({transports}) {
return (
<div className="order-modal">
<form className="order-modal__form" action="/">
<Title size={TitleSize.SMALL}>Send a parcel</Title>
<span class="tooltip">
<button class="tooltip-toggle" type="button" aria-labelledby="tooltip-label-date">
<svg className="tooltip-toggle__image" width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<g id="i">
<circle id="pad" cx="12" cy="12" r="12"/>
<g id="i_2">
<path d="M11 11C11 10.4477 11.4477 10 12 10C12.5523 10 13 10.4477 13 11V17C13 17.5523 12.5523 18 12 18C11.4477 18 11 17.5523 11 17V11Z" fill="white"/>
<path d="M11 7C11 6.44772 11.4477 6 12 6C12.5523 6 13 6.44772 13 7C13 7.55228 12.5523 8 12 8C11.4477 8 11 7.55228 11 7Z" fill="white"/>
</g>
</g>
</svg>
</button>
<span class="tooltip-text" role="tooltip" id="tooltip-label-date">A commission is a piece of work that someone is asked to do and is paid for.</span>
</span>
<ul className="order-modal__list">
{
transports.map((transport, i) => (
<li className="order-modal__item" key={i}>
<Switch {...transport}/>
</li>
))
}
</ul>
<div className="order-modal__inputs">
<label className="order-modal__label order-modal__label--pickup" htmlFor="pickup-location">
pickup location
<input name="pickup-location" className="order-modal__input order-modal__input--pickup" type="text" placeholder="location" />
</label>
<label className="order-modal__label order-modal__label--drop" htmlFor="drop-location">
drop location
<input name="drop-location" className="order-modal__input order-modal__input--drop" type="text" placeholder="502 86th St, Brooklyn, NY 11209" />
</label>
</div>
<Button className={buttonsFunction.SUBMIT} type={buttonsTypes.SUBMIT}>Order</Button>
<Button className={buttonsFunction.RESET} type={buttonsTypes.RESET}>Clear All</Button>
</form>
</div>
)
}
export default OrderModal;
|
# Index Syntax
Move provides syntax attributes to allow you to define operations that look and feel like native
move code, lowering these operations into your user-provided definitions.
Our first syntax method, `index`, allows you to define a group of operations that can be used as
custom index accessors for your datatypes, such as accessing a matrix element as `m[i,j]`, by
annotating functions that should be used for these index operations. Moreover, these definitions are
bespoke per-type and available implicitly for any programmer using your type.
## Overview and Summary
To start, consider a `Matrix` type that uses a vector of vectors to represent its values. You can
write a small library using `index` syntax annotations on the `borrow` and `borrow_mut` functions as
follows:
```
module matrix {
public struct Matrix<T> { v: vector<vector<T>> }
#[syntax(index)]
public fun borrow<T>(s: &Matrix<T>, i: u64, j: u64): &T {
borrow(borrow(s.v, i), j)
}
#[syntax(index)]
public fun borrow_mut<T>(s: &mut Matrix<T>, i: u64, j: u64): &mut T {
borrow_mut(borrow_mut(s.v, i), j)
}
public fun make_matrix<T>(v: vector<vector<T>>): Matrix<T> {
Matrix { v }
}
}
```
Now anyone using this `Matrix` type has access to index syntax for it:
```
let v0 = vector<u64>[1, 0, 0];
let v1 = vector<u64>[0, 1, 0];
let v2 = vector<u64>[0, 0, 1];
let v = vector<vector<u64>>[v0, v1, v2];
let mut m = matrix::make_matrix(v);
let mut i = 0;
while (i < 3) {
let mut j = 0;
while (j < 3) {
if (i == j) {
assert!(m[i, j] == 1, i);
} else {
assert!(m[i, j] == 0, i + 10);
};
*(&mut m[i,j]) = 2;
j = j + 1;
};
i = i + 1;
}
```
## Usage
As the example indicates, if you define a datatype and an associated index syntax method, anyone can
invoke that method by writing index syntax on a value of that type:
```move
let mat = matrix::make_matrix(...);
let m_0_0 = mat[0, 0];
```
During compilation, the compiler translates these into the appropriate function invocations based on
the position and mutable usage of the expression:
````move
let mut mat = matrix::make_matrix(...);
let m_0_0 = mat[0, 0];
// translates to copy matrix::borrow(&mat, 0, 0)
let m_0_0 = &mat[0, 0];
// translates to matrix::borrow(&mat, 0, 0)
let m_0_0 = &mut mat[0, 0];
// translates to matrix::borrow_mut(&mut mat, 0, 0)
``
You can also intermix index expressions with field accesses:
```move
public struct V { v: vector<u64> }
public struct Vs { vs: vector<V> }
fun borrow_first(input: &Vs): &u64 {
input.vs[0].v[0]
// translates to vector::borrow(vector::borrow(input.vs, 0).v, 0)
}
````
### Index Functions Take Flexible Arguments
Note that, aside from the definition and type limitations described in the rest of this chapter,
Move places no restrictions on the values your index syntax method takes as parameters. This allows
you to implement intricate programmatic behavior when defining index syntax, such as a data
structure that takes a default value if the index is out of bounds:
```
#[syntax(index)]
public fun borrow_or_set<Key: copy, Value: drop>(
input: &mut MTable<Key, Value>,
key: &Key,
default: Value
): &mut Value {
if (contains(input, *key)) {
borrow(input, key)
} else {
insert(input, *key, default)
borrow(input, key)
}
}
```
Now, when you index into `MTable`, you must also provide a default value:
```
let string_key: String = ...;
let mut table: MTable<String, u64> = m_table::make_table();
let entry: &mut u64 = &mut table[string_key, 0];
```
This sort of extensible power allows you to write precise index interfaces for your types,
concretely enforcing bespoke behavior.
## Defining Index Syntax Functions
This powerful syntax form allows all of your user-defined datatypes to behave in this way, assuming
your definitions adhere to the following rules:
1. The `#[syntax(index)]` attribute is added to the designated functions defined in the same module
as the subject type.
1. The designated functions have `public` visibility.
1. The functions take a reference type as its subject type (its first argument) and returns a
matching references type (`mut` if the subject was `mut`).
1. Each type has only a single mutable and single immutable definition.
1. Immutable and mutable versions have type agreement:
- The subject types match, differing only in mutability.
- The return types match the mutability of their subject types.
- Type parameters, if present, have identical constraints between both versions.
- All parameters beyond the subject type are identical.
The following content and additional examples describe these rules in greater detail.
### Declaration
To declare an index syntax method, add the `#[syntax(index)]` attribute above the relevant function
definition in the same module as the subject type's definition. This signals to the compiler that
the function is an index accessor for the specified type.
#### Immutable Accessor
The immutable index syntax method is defined for read-only access. It takes an immutable reference
of the subject type and returns an immutable reference to the element type. The `borrow` function
defined in `std::vector` is an example of this:
```move
#[syntax(index)]
public fun borrow<Element>(v: &vector<Element>, i: u64): &Element {
// implementation
}
```
#### Mutable Accessor
The mutable index syntax method is the dual of the immutable one, allowing for both read and write
operations. It takes a mutable reference of the subject type and returns a mutable reference to the
element type. The `borrow_mut` function defined in `std::vector` is an example of this:
```move
#[syntax(index)]
public fun borrow_mut<Element>(v: &mut vector<Element>, i: u64): &mut Element {
// implementation
}
```
#### Visibility
To ensure that indexing functions are available anywhere the type is used, all index syntax methods
must have public visibility. This ensures ergonomic usage of indexing across modules and packages in
Move.
#### No Duplicates
In addition to the above requirements, we restrict each subject base type to defining a single index
syntax method for immutable references and a single index syntax method for mutable references. For
example, you cannot define a specialized version for a polymorphic type:
```move
#[syntax(index)]
public fun borrow_matrix_u64(s: &Matrix<u64>, i: u64, j: u64): &u64 { ... }
#[syntax(index)]
public fun borrow_matrix<T>(s: &Matrix<T>, i: u64, j: u64): &T { ... }
// ERROR! Matrix already has a definition
// for its immutable index syntax method
```
This ensures that you can always tell which method is being invoked, without the need to inspect
type instantiation.
### Type Constraints
By default, an index syntax method has the following type constraints:
**Its subject type (first argument) must be a reference to a single type defined in the same module
as the marked function.** This means that you cannot define index syntax methods for tuples, type
parameters, or values:
```move
#[syntax(index)]
public fun borrow_fst(x: &(u64, u64), ...): &u64 { ... }
// ERROR because the subject type is a tuple
#[syntax(index)]
public fun borrow_tyarg<T>(x: &T, ...): &T { ... }
// ERROR because the subject type is a type parameter
#[syntax(index)]
public fun borrow_value(x: Matrix<u64>, ...): &u64 { ... }
// ERROR because x is not a reference
```
**The subject type must match mutability with the return type.** This restriction allows you to
clarify the expected behavior when borrowing an indexed expression as `&vec[i]` versus
`&mut vec[i]`. The Move compiler uses the mutability marker to determine which borrow form to call
to produce a reference of the appropriate mutability. As a result, we disallow index syntax methods
whose subject and return mutability differ:
```move
#[syntax(index)]
public fun borrow_imm(x: &mut Matrix<u64>, ...): &u64 { ... }
// ERROR! incompatible mutability
```
### Type Compatibility
When defining an immutable and mutable index syntax method pair, they are subject to a number of
compatibility constraints:
1. They must take the same number of type parameters, those type parameters must have the same
constraints.
1. Type parameters must be used the same _by position_, not name.
1. Their subject types must match exactly except for the mutability.
1. Their return types must match exactly except for the mutability.
1. All other parameter types must match exactly.
These constraints are to ensure that index syntax behaves identically regardless of being in a
mutable or immutable position.
To illustrate some of these errors, recall the previous `Matrix` definition:
```move
#[syntax(index)]
public fun borrow<T>(s: &Matrix<T>, i: u64, j: u64): &T {
borrow(borrow(s.v, i), j)
}
```
All of the following are type-incompatible definitions of the mutable version:
```move
#[syntax(index)]
public fun borrow_mut<T: drop>(s: &mut Matrix<T>, i: u64, j: u64): &mut T { ... }
// ERROR! `T` has `drop` here, but no in the immutable version
#[syntax(index)]
public fun borrow_mut(s: &mut Matrix<u64>, i: u64, j: u64): &mut u64 { ... }
// ERROR! This takes a different number of type parameters
#[syntax(index)]
public fun borrow_mut<T, U>(s: &mut Matrix<U>, i: u64, j: u64): &mut U { ... }
// ERROR! This takes a different number of type parameters
#[syntax(index)]
public fun borrow_mut<T, U>(s: &mut Matrix<U>, i_j: (u64, u64)): &mut U { ... }
// ERROR! This takes a different number of arguments
#[syntax(index)]
public fun borrow_mut<T, U>(s: &mut Matrix<U>, i: u64, j: u32): &mut U { ... }
// ERROR! `j` is a different type
```
Again, the goal here is to make the usage across the immutable and mutable versions consistent. This
allows index syntax methods to work without changing out the behavior or constraints based on
mutable versus immutable usage, ultimately ensuring a consistent interface to program against.
|
import { beforeEach, describe, expect, test, vi } from 'vitest'
import { fireEvent, render } from '@testing-library/vue'
import { setActivePinia, createPinia } from 'pinia'
import { waitPerfectly } from '../setup'
import Form from '~/pages/formScript.vue'
vi.useFakeTimers()
const mockPush = vi.fn()
vi.mock('vue-router', () => ({
useRouter: () => ({
push: mockPush
})
}))
describe('Form', () => {
beforeEach(() => {
setActivePinia(createPinia())
})
describe('画面初期状態の確認', () => {
test('ページが描画されていること', () => {
// Arrange
const { container } = render(Form)
// textContentは前後に空白を付与したテキストを返却するのでtrimで空白を除去する必要があります
const title = container.querySelector('[data-testid="page-title"]')?.textContent?.trim()
// Assert
expect(title).toBe('Login')
})
test('送信ボタンが非活性であること', async () => {
// Arrange
const { container } = render(Form)
// render直後はHTMLButtonElement.disabledが常にfalseを返すため、flushPromisesを呼び出して正常な値に更新する必要があります。
await waitPerfectly()
const isDisabled = (container.querySelector('[data-testid="submit-btn"]') as HTMLButtonElement).disabled
// Assert
expect(isDisabled).toBeTruthy()
})
})
describe('vee-validateの動作確認', () => {
test.each([
['email'],
['password']
])(
'%sが入力必須の項目であること',
async (
inputName
) => {
// Arrange
const { container } = render(Form)
const inputElement = container.querySelector(`[data-testid="input-${inputName}"]`) as HTMLInputElement
// Act
await fireEvent.update(inputElement, '')
await waitPerfectly()
const errorMsg = container.querySelector(`[data-testid="${inputName}-error-msg"]`)?.textContent
// Assert
expect(errorMsg).toBe(`${inputName}は必須項目です`)
})
test('emailの入力は有効なメールアドレス形式であること', async () => {
// Arrange
const { container } = render(Form)
const inputElement = container.querySelector('[data-testid="input-email"]') as HTMLInputElement
// Act
await fireEvent.update(inputElement, 'abc')
await waitPerfectly()
const errorMsgInputInvalidValue = container.querySelector('[data-testid="email-error-msg"]')?.textContent
await fireEvent.update(inputElement, '[email protected]')
await waitPerfectly()
const errorMsgInputValidValue = container.querySelector('[data-testid="email-error-msg"]')?.textContent
// Assert
expect(errorMsgInputInvalidValue).toBe('emailは有効なメールアドレスではありません')
expect(errorMsgInputValidValue).toBeFalsy()
})
test('すべての項目へ有効な値を入力した場合は、送信ボタンが活性になること', async () => {
// Arrange
const { container } = render(Form)
// render直後はHTMLButtonElement.disabledが常にfalseを返すため、flushPromisesを呼び出して正常な値に更新する必要があります。
await waitPerfectly()
// Act
const emailInputElement = container.querySelector('[data-testid="input-email"]') as HTMLInputElement
await fireEvent.update(emailInputElement, '[email protected]')
await waitPerfectly()
const passwordInputElement = container.querySelector('[data-testid="input-password"]') as HTMLInputElement
await fireEvent.update(passwordInputElement, '123')
await waitPerfectly()
const submitElement = container.querySelector('[data-testid="submit-btn"]') as HTMLButtonElement
await fireEvent.click(submitElement)
await waitPerfectly()
// Assert
expect(submitElement.disabled).toBeFalsy()
})
test('送信ボタンを押下した場合は、送信処理が実行されること', async () => {
const submitFn = vi.fn()
// Arrange
const { container } = render(Form, { global: { mocks: { submit: submitFn } } })
const emailInputElement = container.querySelector('[data-testid="input-email"]') as HTMLInputElement
await fireEvent.update(emailInputElement, '[email protected]')
await waitPerfectly()
const passwordInputElement = container.querySelector('[data-testid="input-password"]') as HTMLInputElement
await fireEvent.update(passwordInputElement, '123')
await waitPerfectly()
// Act
await fireEvent.click((container.querySelector('[data-testid="submit-btn"]') as HTMLButtonElement))
await waitPerfectly()
// Assert
expect(submitFn).toHaveBeenCalledOnce()
expect(mockPush).toHaveBeenCalledWith('/myPage')
})
})
})
|
# Copyright (C) 2020 Greenbone Networks GmbH
# Some text descriptions might be excerpted from (a) referenced
# source(s), and are Copyright (C) by the respective right holder(s).
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
# 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
if(description)
{
script_oid("1.3.6.1.4.1.25623.1.0.853407");
script_version("2020-09-11T10:38:07+0000");
script_cve_id("CVE-2020-8231");
script_tag(name:"cvss_base", value:"5.0");
script_tag(name:"cvss_base_vector", value:"AV:N/AC:L/Au:N/C:P/I:N/A:N");
script_tag(name:"last_modification", value:"2020-09-11 10:38:07 +0000 (Fri, 11 Sep 2020)");
script_tag(name:"creation_date", value:"2020-09-06 03:00:45 +0000 (Sun, 06 Sep 2020)");
script_name("openSUSE: Security Advisory for curl (openSUSE-SU-2020:1345-1)");
script_category(ACT_GATHER_INFO);
script_copyright("Copyright (C) 2020 Greenbone Networks GmbH");
script_family("SuSE Local Security Checks");
script_dependencies("gather-package-list.nasl");
script_mandatory_keys("ssh/login/suse", "ssh/login/rpms", re:"ssh/login/release=openSUSELeap15\.1");
script_xref(name:"openSUSE-SU", value:"2020:1345-1");
script_xref(name:"URL", value:"http://lists.opensuse.org/opensuse-security-announce/2020-09/msg00011.html");
script_tag(name:"summary", value:"The remote host is missing an update for the 'curl'
package(s) announced via the openSUSE-SU-2020:1345-1 advisory.");
script_tag(name:"vuldetect", value:"Checks if a vulnerable package version is present on the target host.");
script_tag(name:"insight", value:"This update for curl fixes the following issues:
- An application that performs multiple requests with libcurl's multi API
and sets the 'CURLOPT_CONNECT_ONLY' option, might in rare circumstances
experience that when subsequently using the setup connect-only transfer,
libcurl will pick and use the wrong connection and instead pick another
one the application has created since then. [bsc#1175109, CVE-2020-8231]
This update was imported from the SUSE:SLE-15:Update update project.
Patch Instructions:
To install this openSUSE Security Update use the SUSE recommended
installation methods
like YaST online_update or 'zypper patch'.
Alternatively you can run the command listed for your product:
- openSUSE Leap 15.1:
zypper in -t patch openSUSE-2020-1345=1");
script_tag(name:"affected", value:"'curl' package(s) on openSUSE Leap 15.1.");
script_tag(name:"solution", value:"Please install the updated package(s).");
script_tag(name:"solution_type", value:"VendorFix");
script_tag(name:"qod_type", value:"package");
exit(0);
}
include("revisions-lib.inc");
include("pkg-lib-rpm.inc");
release = rpm_get_ssh_release();
if(!release)
exit(0);
res = "";
report = "";
if(release == "openSUSELeap15.1") {
if(!isnull(res = isrpmvuln(pkg:"curl", rpm:"curl~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"curl-debuginfo", rpm:"curl-debuginfo~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"curl-debugsource", rpm:"curl-debugsource~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"curl-mini", rpm:"curl-mini~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"curl-mini-debuginfo", rpm:"curl-mini-debuginfo~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"curl-mini-debugsource", rpm:"curl-mini-debugsource~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"libcurl-devel", rpm:"libcurl-devel~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"libcurl-mini-devel", rpm:"libcurl-mini-devel~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"libcurl4", rpm:"libcurl4~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"libcurl4-debuginfo", rpm:"libcurl4-debuginfo~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"libcurl4-mini", rpm:"libcurl4-mini~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"libcurl4-mini-debuginfo", rpm:"libcurl4-mini-debuginfo~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"libcurl-devel-32bit", rpm:"libcurl-devel-32bit~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"libcurl4-32bit", rpm:"libcurl4-32bit~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(!isnull(res = isrpmvuln(pkg:"libcurl4-32bit-debuginfo", rpm:"libcurl4-32bit-debuginfo~7.60.0~lp151.5.15.1", rls:"openSUSELeap15.1"))) {
report += res;
}
if(report != "") {
security_message(data:report);
} else if(__pkg_match) {
exit(99);
}
exit(0);
}
exit(0);
|
<?php
/**
* This file is part of the PINAX framework.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Class pinax_components_LoginBox
*/
class pinax_components_LoginBox extends pinax_components_Component
{
var $_error = NULL;
/**
* Init
*
* @return void
* @access public
*/
function init()
{
$this->defineAttribute('accessPageId', false, NULL, COMPONENT_TYPE_STRING);
$this->defineAttribute('allowGroups', false, '', COMPONENT_TYPE_STRING);
$this->defineAttribute('askPasswordLabel', false, '', COMPONENT_TYPE_STRING);
$this->defineAttribute('askPasswordUrl', false, '', COMPONENT_TYPE_STRING);
$this->defineAttribute('backend', false, false, COMPONENT_TYPE_BOOLEAN);
$this->defineAttribute('confirmLabel', false, '', COMPONENT_TYPE_STRING);
$this->defineAttribute('cssClass', false, '', COMPONENT_TYPE_STRING);
$this->defineAttribute('errorLabel', false, __T('PNX_LOGIN_ERROR'), COMPONENT_TYPE_STRING);
$this->defineAttribute('userLabel', false, __T('PNX_USER_LOGINID'), COMPONENT_TYPE_STRING);
$this->defineAttribute('userField', false, 'loginuser', COMPONENT_TYPE_STRING);
$this->defineAttribute('passwordLabel', false, __T('PNX_USER_PASSWORD'), COMPONENT_TYPE_STRING);
$this->defineAttribute('passwordField', false, 'loginpsw', COMPONENT_TYPE_STRING);
$this->defineAttribute('languageLabel', false, __T('PNX_LANGUAGE'), COMPONENT_TYPE_STRING);
$this->defineAttribute('languageField', false, 'loginlanguage', COMPONENT_TYPE_STRING);
$this->defineAttribute('registrationUrl', false, '', COMPONENT_TYPE_STRING);
$this->defineAttribute('registrationLabel', false, '', COMPONENT_TYPE_STRING);
$this->defineAttribute('rememberLabel', false, __T('PNX_LOGIN_REMEMBER'), COMPONENT_TYPE_STRING);
$this->defineAttribute('rememberField', false, 'remember', COMPONENT_TYPE_STRING);
$this->defineAttribute('title', false, '', COMPONENT_TYPE_STRING);
parent::init();
}
function process()
{
$this->_content = array();
$this->_content['errorLabel'] = '';
// check if the user is already logged
$backend = $this->getAttribute('backend');
$allowGroups = $this->getAttribute('allowGroups')!='' ? explode(',', $this->getAttribute('allowGroups')) : array();
if ($this->_user->isLogged()) {
if (($backend && !$this->_user->backEndAccess) ||
(count($allowGroups) && !in_array($this->_user->groupId, $allowGroups))) {
$this->_content['errorLabel'] = pinax_locale_Locale::get('LOGGER_INSUFFICIENT_GROUP_LEVEL');
} else {
$this->setAttribute('visible', false);
$this->redirectAfterLogin();
return;
}
}
$submitId = 'submit_'.$this->getId();
$this->_content['id'] = $this->getId();
$this->_content['submitName'] = $submitId;
$this->_content['cssClass'] = $this->getAttribute('cssClass');
$this->_content['userLabel'] = $this->getAttribute('userLabel');
$this->_content['userField'] = $this->getAttribute('userField');
$this->_content['passwordLabel'] = $this->getAttribute('passwordLabel');
$this->_content['passwordField'] = $this->getAttribute('passwordField');
$this->_content['registrationPage'] = $this->getAttribute('registrationPage');
$this->_content['registrationLabel'] = $this->getAttribute('registrationLabel');
$this->_content['confirmLabel'] = $this->getAttribute('confirmLabel');
$this->_content['rememberLabel'] = $this->getAttribute('rememberLabel');
$this->_content['askPasswordLabel'] = $this->getAttribute('askPasswordLabel');
$this->_content['title'] = $this->getAttributeString('title');
$this->_content['__url__'] = pinax_helpers_Link::makeURL($this->getAttribute('registrationUrl'));
$this->_content['askPasswordUrl'] = pinax_helpers_Link::makeURL($this->getAttribute('askPasswordUrl'));
if (__Request::exists($this->_content['userField']) || __Request::exists($this->_content['passwordField'])) {
$authClass = pinax_ObjectFactory::createObject(__Config::get('pinax.authentication'));
if ($authClass) {
try {
$authClass->setAllowGroups($allowGroups);
$authClass->setOnlyBackendUser($backend);
$authClass->setUserLanguage(__Request::get($this->getAttribute('languageField')));
$authClass->loginFromRequest($this->getAttribute('userField'), $this->getAttribute('passwordField'), $this->getAttribute('rememberField'), true);
$this->redirectAfterLogin();
} catch(pinax_authentication_AuthenticationException $e) {
switch ($e->getCode()) {
case pinax_authentication_AuthenticationException::EMPTY_LOGINID_OR_PASSWORD:
case pinax_authentication_AuthenticationException::WRONG_LOGINID_OR_PASSWORD:
$this->_content['errorLabel'] = $this->getAttribute('errorLabel');
break;
case pinax_authentication_AuthenticationException::USER_NOT_ACTIVE:
$this->_content['errorLabel'] = pinax_locale_Locale::get('PNX_LOGIN_DISABLED');
break;
case pinax_authentication_AuthenticationException::ACCESS_NOT_ALLOWED:
$this->_content['errorLabel'] = pinax_locale_Locale::get('LOGGER_INSUFFICIENT_GROUP_LEVEL');
break;
}
}
} else {
// TODO mostrare errore
$this->_content['errorLabel'] = __Config::get('pinax.authentication');
}
} else {
if (!$this->_content['errorLabel']) {
$this->_content['errorLabel'] = __Session::get('pinax.loginError', '');
__Session::remove('pinax.loginError');
}
}
}
protected function redirectAfterLogin()
{
$destPage = '';
$accessPageId = $this->getAttribute('accessPageId');
if ( $accessPageId && $accessPageId != $this->_application->getPageId() ) {
$accessPageId = $this->getAttribute('accessPageId');
$redirectUrl = __Routing::exists($accessPageId) ? __Routing::makeUrl($accessPageId) : pinax_helpers_Link::makeUrl('link', array('pageId' => $accessPageId));
$destPage = strpos($accessPageId, 'http')!==false ? $accessPageId : $redirectUrl;
}
$url = __Session::get('pinax.loginUrl', $destPage);
if ($url) {
__Session::remove('pinax.loginUrl' );
pinax_helpers_Navigation::gotoUrl($url);
}
}
}
if (!class_exists('pinax_components_LoginBox_render'))
{
class pinax_components_LoginBox_render extends pinax_components_render_Render
{
function getDefaultSkin()
{
$skin = <<<EOD
<div tal:attributes="id Component/id; class Component/cssClass">
<h3 tal:content="Component/title" />
<div>
<form id="" method="post" action="" tal:attributes="id Component/id">
<p class="error" tal:condition="Component/errorLabel" tal:content="structure Component/errorLabel"></p>
<label tal:attributes="for Component/userField" tal:content="structure Component/userLabel" /><br />
<input type="text" class="text" tal:attributes="id Component/userField; name Component/userField"/><br />
<label tal:attributes="for Component/passwordField" tal:content="structure Component/passwordLabel" /><br />
<input type="password" class="text" tal:attributes="id Component/passwordField; name Component/passwordField"/><br />
<table>
<tr>
<td><input name="remember" id="remember" value="1" type="checkbox" /><label for="remember" tal:content="structure Component/rememberLabel" /></td>
<td class="submitButton"><input type="submit" class="submitButton" tal:attributes="name Component/submitName;value Component/confirmLabel"/></td>
</tr>
</table>
<a class="link" tal:attributes="href Component/__url__" tal:content="structure Component/registrationLabel"></a><br />
<a class="link" tal:attributes="href Component/askPasswordUrl" tal:content="structure Component/askPasswordLabel"></a>
</form>
</div>
</div>
EOD;
return $skin;
}
}
}
|
import React, {
PropsWithChildren,
useState,
ChangeEvent,
forwardRef,
useImperativeHandle,
useRef,
} from 'react';
import clsx from 'clsx';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
import Typography from '@material-ui/core/Typography/Typography';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
//import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import { PanelProps, PanelHandle } from './panel-types';
import { useStyles } from './panel-styles';
import { useEventCallback } from 'utils/event-callback-hook';
import { composeRefs } from 'utils/compose-refs';
export const Panel = forwardRef<PanelHandle, PropsWithChildren<PanelProps>>(
function Panel(
{
children,
label,
summary,
expandable = false,
defaultExpanded = true,
sideBorder = false,
className,
fitHeight,
},
ref
) {
const {
root,
fullHeight,
summaryRoot,
summaryFixed,
detailsRoot,
detailRootWithSideBorder,
labelRoot,
summaryContent,
summaryRootWithBorder,
sumaryFullHeight,
formPanelSummary,
} = useStyles();
const anchorRef = useRef<PanelHandle>(null);
const composedRef = composeRefs(ref, anchorRef);
const [expanded, setExpanded] = useState(defaultExpanded);
useImperativeHandle(ref, () => ({
setExpanded,
scrollIntoView: () => {
anchorRef.current?.scrollIntoView();
},
}));
const handleChange = useEventCallback(
(event: ChangeEvent<any>, expanded) => {
if (expandable) {
setExpanded(expanded);
}
}
);
return (
<ExpansionPanel
className={className}
classes={{ root: clsx(root, { [fullHeight]: fitHeight }) }}
square={true}
expanded={expanded}
onChange={handleChange}
innerRef={composedRef}
TransitionProps={{
style: fitHeight
? {
flex: '1 1 auto',
overflowY: 'auto',
}
: undefined,
}}
>
<ExpansionPanelSummary
classes={{
root: clsx(summaryRoot, {
[summaryFixed]: !expandable,
[summaryRootWithBorder]: sideBorder,
[sumaryFullHeight]: fitHeight,
}),
content: summaryContent,
}}
expandIcon={expandable ? <ExpandMoreIcon /> : undefined}
>
<Typography classes={{ root: labelRoot }} variant="h6">
{label}
</Typography>
{summary && (
<Typography component="div" className={formPanelSummary}>
{summary}
</Typography>
)}
</ExpansionPanelSummary>
<ExpansionPanelDetails
classes={{
root: clsx(detailsRoot, {
[detailRootWithSideBorder]: sideBorder,
}),
}}
>
{children}
</ExpansionPanelDetails>
</ExpansionPanel>
);
}
);
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {Routes, RouterModule} from '@angular/router';
import { AppComponent } from './app.component';
import { HeroesListComponent } from './heroes-list/heroes-list.component';
import { AlexisPoluxComponent } from './alexis-polux/alexis-polux.component';
import { FafnirRannComponent } from './fafnir-rann/fafnir-rann.component';
import { SigismundComponent } from './sigismund/sigismund.component';
import { TorGaradonComponent } from './tor-garadon/tor-garadon.component';
import { DornComponent } from './dorn/dorn.component';
const appRoutes: Routes = [
{
path: 'alexis-polux',
component: AlexisPoluxComponent
},
{
path: 'fafnir-rann',
component: FafnirRannComponent
},
{
path: 'sigismund',
component: SigismundComponent
},
{
path: 'tor-garadon',
component: TorGaradonComponent
},
{
path: 'dorn',
component: DornComponent
},
{
path: 'home',
component: HeroesListComponent
},
];
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forRoot(appRoutes),
],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
import { FC } from "react"
import { useState } from "react"
import {
Box,
Button,
FormControl,
FormLabel,
Input,
NumberDecrementStepper,
NumberIncrementStepper,
NumberInput,
NumberInputField,
NumberInputStepper,
Textarea,
Switch,
} from "@chakra-ui/react"
import { useWorkspace } from "../context/Anchor"
import { useWallet } from "@solana/wallet-adapter-react"
import { findProgramAddressSync } from "@project-serum/anchor/dist/cjs/utils/pubkey"
import { getAssociatedTokenAddressSync } from "@solana/spl-token"
import * as anchor from "@project-serum/anchor"
import InstructionNamespaceFactory from "@project-serum/anchor/dist/cjs/program/namespace/instruction"
export const Form: FC = () => {
const [title, setTitle] = useState("")
const [rating, setRating] = useState(0)
const [description, setDescription] = useState("")
const [toggle, setToggle] = useState(true)
const workspace = useWorkspace()
const { publicKey, sendTransaction } = useWallet()
const handleSubmit = async (event: any) => {
event.preventDefault()
if (!publicKey || !workspace.program || !workspace.connection) {
alert("Please connect your wallet")
return
}
const [mintPda] = findProgramAddressSync(
[Buffer.from("mint")],
workspace.program.programId
)
const tokenAddress = getAssociatedTokenAddressSync(mintPda, publicKey)
const transaction = new anchor.web3.Transaction()
if (toggle) {
const ix = await workspace.program.methods
.addMovieReview(title, description, rating)
.accounts({
tokenAccount: tokenAddress,
})
.instruction()
transaction.add(ix)
} else {
const ix = await workspace.program.methods
.updateMovieReview(title, description, rating)
.instruction()
transaction.add(ix)
}
try {
let signature = await sendTransaction(transaction, workspace.connection)
console.log(
`Transaction submitted: https://explorer.solana.com/tx/${signature}?cluster=devnet`
)
} catch (e) {
console.log("Error:", JSON.stringify(e))
alert(JSON.stringify(e))
}
}
return (
<Box
p={4}
display={{ md: "flex" }}
maxWidth="32rem"
borderWidth={1}
margin={2}
justifyContent="center"
>
<form onSubmit={handleSubmit}>
<FormControl isRequired>
<FormLabel color="gray.200">Movie Title</FormLabel>
<Input
id="title"
color="gray.400"
onChange={(event) => setTitle(event.currentTarget.value)}
/>
</FormControl>
<FormControl isRequired>
<FormLabel color="gray.200">Add your review</FormLabel>
<Textarea
id="review"
color="gray.400"
onChange={(event) => setDescription(event.currentTarget.value)}
/>
</FormControl>
<FormControl isRequired>
<FormLabel color="gray.200">Rating</FormLabel>
<NumberInput
max={5}
min={1}
onChange={(valueString) => setRating(parseInt(valueString))}
>
<NumberInputField id="amount" color="gray.400" />
<NumberInputStepper color="gray.400">
<NumberIncrementStepper />
<NumberDecrementStepper />
</NumberInputStepper>
</NumberInput>
</FormControl>
<FormControl display="center" alignItems="center">
<FormLabel color="gray.100" mt={2}>
Update
</FormLabel>
<Switch
id="update"
onChange={(event) => setToggle((prevCheck) => !prevCheck)}
/>
</FormControl>
<Button width="full" mt={4} type="submit">
Submit Review
</Button>
</form>
</Box>
)
}
|
<script>
// NOTE! For the first iteration, we are simply copying the implementation of Assignees
// It will soon be overhauled in Issue https://gitlab.com/gitlab-org/gitlab/-/issues/233736
import { __, sprintf } from '~/locale';
import ReviewerAvatarLink from './reviewer_avatar_link.vue';
const DEFAULT_RENDER_COUNT = 5;
export default {
components: {
ReviewerAvatarLink,
},
props: {
users: {
type: Array,
required: true,
},
rootPath: {
type: String,
required: true,
},
issuableType: {
type: String,
required: false,
default: 'issue',
},
},
data() {
return {
showLess: true,
};
},
computed: {
firstUser() {
return this.users[0];
},
hasOneUser() {
return this.users.length === 1;
},
hiddenReviewersLabel() {
const { numberOfHiddenReviewers } = this;
return sprintf(__('+ %{numberOfHiddenReviewers} more'), { numberOfHiddenReviewers });
},
renderShowMoreSection() {
return this.users.length > DEFAULT_RENDER_COUNT;
},
numberOfHiddenReviewers() {
return this.users.length - DEFAULT_RENDER_COUNT;
},
uncollapsedUsers() {
const uncollapsedLength = this.showLess
? Math.min(this.users.length, DEFAULT_RENDER_COUNT)
: this.users.length;
return this.showLess ? this.users.slice(0, uncollapsedLength) : this.users;
},
username() {
return `@${this.firstUser.username}`;
},
},
methods: {
toggleShowLess() {
this.showLess = !this.showLess;
},
},
};
</script>
<template>
<reviewer-avatar-link
v-if="hasOneUser"
#default="{ user }"
tooltip-placement="left"
:tooltip-has-name="false"
:user="firstUser"
:root-path="rootPath"
:issuable-type="issuableType"
>
<div class="gl-ml-3 gl-line-height-normal">
<div class="author">{{ user.name }}</div>
<div class="username">{{ username }}</div>
</div>
</reviewer-avatar-link>
<div v-else>
<div class="user-list">
<div v-for="user in uncollapsedUsers" :key="user.id" class="user-item">
<reviewer-avatar-link :user="user" :root-path="rootPath" :issuable-type="issuableType" />
</div>
</div>
<div v-if="renderShowMoreSection" class="user-list-more">
<button
type="button"
class="btn-link"
data-qa-selector="more_reviewers_link"
@click="toggleShowLess"
>
<template v-if="showLess">
{{ hiddenReviewersLabel }}
</template>
<template v-else>{{ __('- show less') }}</template>
</button>
</div>
</div>
</template>
|
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>css3</title>
<style>
body { font:15px "나눔고딕"; color:#777; }
#box1 { position:absolute; left:50px; top:50px; width:200px;height:200px; background:#FCC}
#box2 { position: absolute; left: 150px; top: 120px; width: 200px; height: 200px; background:#F6C;
-ms-opacity: 0.3;
-webkit-opacity: 0.3;
-moz-opacity: 0.3;
-o-opacity: 0.3;
opacity: 0.3;
}
/*
벤더 프리픽스 :
W3C권고 전 CSS3의 사양을 웹브라우저 제조업체가 지원하는 경우
셀렉터 앞에 웹브라우저별로 서로 다른 접두사(프리픽스,Prefix)를 붙일것을 권장.
이를 '벤더 프리픽스'라고 한다
익스플로러 -ms-
파이어폭스 -moz-
크롬,사파리,오페라 -webkit-
오페라 구버전 -o-
*/
/* CSS3의 브라우져 지원 범위를 확인할 수 있는 사이트
http://www.w3schools.com/cssref/css3_browsersupport.asp */
</style>
<!-- <script src="http://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script> -->
<!-- css3의 벤더프리픽스를 자동으로 붙여주는 자바스크립트
단, css를 외부로 저장해야 적용이되며, 로컬에서는 확인이 안되므로
서버에 올려서 확인해야합니다. -->
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
</body>
</html>
|
public with sharing class LDC_LocationService {
@TestVisible private Decimal lat {get; set;}
@TestVisible private Decimal lng {get; set;}
public LDC_LocationService(Id sObjectId) {
if (sObjectId != null) {
getLatLngFromObject(sObjectId);
} else {
//throw new Exception('Invalid object Id');
}
System.debug('LDC is ObjectId from LDC_LocationService: ' + this.lat + ',' + this.lng);
}
public LDC_LocationService(String lat, String lng) {
this.lat = decimal.valueOf(lat);
this.lng = decimal.valueOf(lng);
System.debug('LDC is lat,lng from LDC_LocationService: ' + this.lat + ',' + this.lng);
}
public LDC_LocationService(String city) {
getLatLngFromCity(city);
System.debug('LDC is city from LDC_LocationService: ' + this.lat + ',' + this.lng);
}
private void getLatLngFromObject(Id sObjectId){
String sObjectName = null;
sObjectName = getSObjectType(sObjectId);
if(sObjectName == 'Account') {
getLatLngFromAccount(sObjectId);
} else if(sObjectName == 'Contact') {
getLatLngFromContact(sObjectId);
} else {
//throw new Exception('Invalid object type');
}
}
private String getSObjectType(Id sObjectId) {
String sObjectName = sObjectId?.getSObjectType().getDescribe().getName();
System.debug('sObjectName:'+ sObjectName);
return sObjectName;
}
private void getLatLngFromAccount(Id accountId) {
Account acc = [SELECT BillingLatitude, BillingLongitude FROM Account WHERE Id = :accountId][0];
this.lat = acc.BillingLatitude;
this.lng = acc.BillingLongitude;
}
private void getLatLngFromContact(Id contactId) {
Contact contact = [SELECT MailingLatitude, MailingLongitude FROM Contact WHERE Id = :contactId][0];
this.lat = contact.MailingLatitude;
this.lng = contact.MailingLongitude;
}
private void getLatLngFromCity(String city) {
System.debug('LDC is city from getLatLngFromCity:'+ city);
// TODO: Get lat/lng from city with Webservice
this.lat = decimal.valueOf('40.7127837');
this.lng = decimal.valueOf('-74.0059413');
}
public Decimal getLat(){
return this.lat;
}
public Decimal getLng(){
return this.lng;
}
}
|
```markdown
# Compliance Seeker
Compliance Seeker is a web application designed to test websites for cross-border data transfer compliance. The application checks if websites transfer personal data outside of the EU without adequate safeguards, and looks for instances where data is sent to countries without an adequate level of data protection or without the use of appropriate mechanisms such as Standard Contractual Clauses or Binding Corporate Rules.
## Setup
### Prerequisites
- Node.js (v14.x or later recommended)
- npm (v6.x or later recommended)
### Installing Dependencies
1. Navigate to the project root directory.
```bash
cd path/to/compliance-seeker
```
2. Install the necessary dependencies.
```bash
npm install
```
## Running the Application
1. Navigate to the project root directory if you are not already there.
```bash
cd path/to/compliance-seeker
```
2. Start the Next.js development server.
```bash
npm run dev
```
The application should now be running on [http://localhost:3000](http://localhost:3000). You can access it in your web browser.
## Starting the Backend Server
1. Navigate to the `backend` directory from the project root.
```bash
cd backend
```
2. Install the necessary dependencies if you haven't already.
```bash
npm install
```
3. Start the backend server.
```bash
node server.mjs
```
- Alternatively, if you have set up a script in your `package.json` to start the server, you can use that instead. For example, if you have a script named `start`, you would run:
```bash
npm start
```
Now the backend server should be running on [http://localhost:3001](http://localhost:3001). It's ready to handle requests from the frontend part of the Compliance Seeker application.
## Contributing
Please read the [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to the project.
## License
This project is licensed under the MIT License. See the [LICENSE.md](LICENSE.md) file for details.
```
|
/*
* Copyright (c) 2020-2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @addtogroup Display
* @{
*
* @brief Defines driver functions of the display module.
*
* This module provides driver functions for the graphics subsystem, including graphics layer management,
* device control, graphics hardware acceleration, display memory management, and callbacks.
*
* @since 1.0
* @version 2.0
*/
/**
* @file display_gfx.h
*
* @brief Declares the driver functions for implementing hardware acceleration.
*
* @since 1.0
* @version 1.0
*/
#ifndef DISPLAY_GFX_H
#define DISPLAY_GFX_H
#include "display_type.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Defines pointers to the hardware acceleration driver functions.
*/
typedef struct {
/**
* @brief Initializes hardware acceleration.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @see DeinitGfx
* @since 1.0
* @version 1.0
*/
int32_t (*InitGfx)(void);
/**
* @brief Deinitializes hardware acceleration.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @see InitGfx
* @since 1.0
* @version 1.0
*/
int32_t (*DeinitGfx)(void);
/**
* @brief Fills a rectangle with a given color on the canvas.
*
* @param surface Indicates the pointer to the canvas.
* @param rect Indicates the pointer to the rectangle to fill.
* @param color Indicates the color to fill.
* @param opt Indicates the pointer to the hardware acceleration option.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @since 1.0
* @version 1.0
*/
int32_t (*FillRect)(ISurface *surface, IRect *rect, uint32_t color, GfxOpt *opt);
/**
* @brief Draws a rectangle with a given color on the canvas.
*
* @param surface Indicates the pointer to the canvas.
* @param rect Indicates the pointer to the rectangle to draw.
* @param color Indicates the color to draw.
* @param opt Indicates the pointer to the hardware acceleration option.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @since 1.0
* @version 1.0
*/
int32_t (*DrawRectangle)(ISurface *surface, Rectangle *rect, uint32_t color, GfxOpt *opt);
/**
* @brief Draws a straight line with a given color on the canvas.
*
* @param surface Indicates the pointer to the canvas.
* @param line Indicates the pointer to the line to draw.
* @param opt Indicates the pointer to the hardware acceleration option.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @since 1.0
* @version 1.0
*/
int32_t (*DrawLine)(ISurface *surface, ILine *line, GfxOpt *opt);
/**
* @brief Draws a circle with a specified center and radius on the canvas using a given color.
*
* @param surface Indicates the pointer to the canvas.
* @param circle Indicates the pointer to the circle to draw.
* @param opt Indicates the pointer to the hardware acceleration option.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @since 1.0
* @version 1.0
*/
int32_t (*DrawCircle)(ISurface *surface, ICircle *circle, GfxOpt *opt);
/**
* @brief Blits bitmaps.
*
* During bit blit, color space conversion (CSC), scaling, and rotation can be implemented.
*
* @param srcSurface Indicates the pointer to the source bitmap.
* @param srcRect Indicates the pointer to the rectangle of the source bitmap.
* @param dstSurface Indicates the pointer to the destination bitmap.
* @param dstRect Indicates the pointer to the rectangle of the destination bitmap.
* @param opt Indicates the pointer to the hardware acceleration option.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @since 1.0
* @version 1.0
*/
int32_t (*Blit)(ISurface *srcSurface, IRect *srcRect, ISurface *dstSurface, IRect *dstRect, GfxOpt *opt);
/**
* @brief Synchronizes hardware acceleration when it is used to draw and blit bitmaps.
*
* This function blocks the process until hardware acceleration is complete.
*
* @param timeOut Indicates the timeout duration for hardware acceleration synchronization. The value <b>0</b>
* indicates no timeout, so the process waits until hardware acceleration is complete.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @since 1.0
* @version 1.0
*/
int32_t (*Sync)(int32_t timeOut);
} GfxFuncs;
/**
* @brief Initializes the hardware acceleration module to obtain the pointer to functions for hardware acceleration
* operations.
*
* @param funcs Indicates the double pointer to functions for hardware acceleration operations. Memory is allocated
* automatically when you initiate the hardware acceleration module, so you can simply use the pointer to gain access
* to the functions.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @since 1.0
* @version 1.0
*/
int32_t GfxInitialize(GfxFuncs **funcs);
/**
* @brief Deinitializes the hardware acceleration module to release the pointer to functions for hardware
* acceleration operations.
*
* @param funcs Indicates the pointer to the functions for hardware acceleration operations.
*
* @return Returns <b>0</b> if the operation is successful; returns an error code defined in {@link DispErrCode}
* otherwise.
* @since 1.0
* @version 1.0
*/
int32_t GfxUninitialize(GfxFuncs *funcs);
#ifdef __cplusplus
}
#endif
#endif
/** @} */
|
<template>
<q-card>
<q-card-section v-if="achievements.length === 0" class="column items-center">
<div class="text-h6">Achievements</div>
<div class="text-subtitle2">Your achievements will be displayed here</div>
</q-card-section>
<q-card-section v-else class="column items-center" horizontal>
<q-card-section
v-for="(achievement) in achievements"
:key="achievement.title"
align="center"
>
<q-avatar>
<img :src="`/${achievement.image}`"/>
</q-avatar>
<h6>"{{achievement.title}}"<br/>{{achievement.body}}</h6>
</q-card-section>
</q-card-section>
</q-card>
</template>
<script lang="ts" setup>
import { useAuthStore } from 'src/stores/auth.store';
import { useMatchHistoryStore, UserMatchesHistory } from 'src/stores/history.store';
import { useSocialStore } from 'src/stores/social.store';
import {
computed, ComputedRef, defineComponent, PropType,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
const his = useMatchHistoryStore(); his.fetchUserMatchesHistory();
const auth = useAuthStore(); auth.fetchConnectedUsers();
const soc = useSocialStore(); soc.fetchRelationships();
const $route = useRoute(); const router = useRouter();
const props = defineProps({
userId: {
type: Number, default: -1,
},
name: {
type: String, default: '',
},
userMatches: {
type: Object as PropType<UserMatchesHistory>, defaut: undefined,
},
});
defineComponent({ name: 'AchievementsCard' });
interface Achievement {
title: string;
body: string;
image: string;
}
const achievements: ComputedRef<Achievement[]> = computed(() => {
const arr: Achievement[] = [];
if (props.userMatches?.stats && props.userMatches.stats.wins > 0) {
arr.push({
title: 'I did it !', body: 'win a game', image: 'happy1.png',
});
}
if (props.userMatches?.stats && props.userMatches.stats.wins > 2) {
arr.push({
title: 'PongChamp', body: 'win 3 games', image: 'happy2.png',
});
}
if (props.userMatches?.stats && props.userMatches.stats.losses > 0) {
arr.push({
title: 'I did it...', body: 'lose a game', image: 'sad1.png',
});
}
if (props.userMatches?.stats && props.userMatches.stats.losses > 2) {
arr.push({
title: 'Oops I did it again', body: 'lose 3 games', image: 'sad2.png',
});
}
return arr;
});
// console.log('achievements = ', achievements);
const emit = defineEmits(['click']);
</script>
|
#!/usr/bin/python3
"""Defines unittests for models/amenity.py."""
import unittest
import os
from datetime import datetime
from time import sleep
from models.amenity import Amenity
class TestAmenityMethods(unittest.TestCase):
"""Test cases for the Amenity class."""
@classmethod
def setUpClass(cls):
try:
os.rename("file.json", "tmp")
except IOError:
pass
@classmethod
def tearDownClass(cls):
try:
os.remove("file.json")
except IOError:
pass
try:
os.rename("tmp", "file.json")
except IOError:
pass
def setUp(self):
self.amenity = Amenity()
def test_type_ins(self):
self.assertIsInstance(self.amenity, Amenity)
def test_id_str(self):
self.assertIsInstance(self.amenity.id, str)
def test__dateti_created_at(self):
self.assertIsInstance(self.amenity.created_at, datetime)
def test_dateti_updated_at(self):
self.assertIsInstance(self.amenity.updated_at, datetime)
def test_attr_name(self):
self.assertEqual(str, type(Amenity.name))
def test_ids_is_unique(self):
another_amenity = Amenity()
self.assertNotEqual(self.amenity.id, another_amenity.id)
def test_ord_created_at(self):
sleep(0.05)
another_amenity = Amenity()
self.assertLess(self.amenity.created_at, another_amenity.created_at)
def test_ord_updated_at(self):
sleep(0.05)
another_amenity = Amenity()
self.assertLess(self.amenity.updated_at, another_amenity.updated_at)
def test_repre_of_str(self):
tym = datetime.today()
tym_repr = repr(tym)
self.amenity.id = "527"
self.amenity.created_at = self.amenity.updated_at = tym
expected_str = (
f"[Amenity] (527) {{'id': '527', "
f"'created_at': {repr(tym)}, 'updated_at': {repr(tym)}}}"
)
self.assertEqual(str(self.amenity), expected_str)
def test_inst_kwargs(self):
tym = datetime.today()
tym_iso = tym.isoformat()
amenity = Amenity(id="400", created_at=tym_iso, updated_at=tym_iso)
self.assertEqual(amenity.id, "400")
self.assertEqual(amenity.created_at, tym)
self.assertEqual(amenity.updated_at, tym)
def test_inst_None_kwargs(self):
with self.assertRaises(TypeError):
Amenity(id=None, created_at=None, updated_at=None)
def test_save(self):
sleep(0.05)
first_updated_at = self.amenity.updated_at
self.amenity.save()
self.assertLess(first_updated_at, self.amenity.updated_at)
def test__saves_updated_multiple(self):
sleep(0.05)
first_updated_at = self.amenity.updated_at
self.amenity.save()
second_updated_at = self.amenity.updated_at
self.assertLess(first_updated_at, second_updated_at)
self.amenity.save()
self.assertLess(second_updated_at, self.amenity.updated_at)
def test_argument_saves(self):
with self.assertRaises(TypeError):
self.amenity.save(None)
def test_save_file_upda(self):
self.amenity.save()
amid = "Amenity." + self.amenity.id
with open("file.json", "r") as file:
self.assertIn(amid, file.read())
def test_type_dict(self):
self.assertIsInstance(self.amenity.to_dict(), dict)
def test_cont_keys_dict(self):
amenity_dict = self.amenity.to_dict()
self.assertIn("id", amenity_dict)
self.assertIn("created_at", amenity_dict)
self.assertIn("updated_at", amenity_dict)
self.assertIn("__class__", amenity_dict)
def test__dict_added_attri_contains(self):
self.amenity.middle_name = "abc"
self.amenity.my_number = 70
self.assertEqual("abc", self.amenity.middle_name)
self.assertIn("my_number", self.amenity.to_dict())
def test_attributes_strs_dict_dateti(self):
am_dict = self.amenity.to_dict()
self.assertIsInstance(am_dict["id"], str)
self.assertIsInstance(am_dict["created_at"], str)
self.assertIsInstance(am_dict["updated_at"], str)
def test__output_dict(self):
tym = datetime.today()
self.amenity.id = "875652"
self.amenity.created_at = self.amenity.updated_at = tym
expected_dict = {
'id': '875652',
'__class__': 'Amenity',
'created_at': tym.isoformat(),
'updated_at': tym.isoformat(),
}
self.assertDictEqual(self.amenity.to_dict(), expected_dict)
def test_under_dict_contrast(self):
self.assertNotEqual(self.amenity.to_dict(), self.amenity.__dict__)
def test__argument_dict(self):
with self.assertRaises(TypeError):
self.amenity.to_dict(None)
if __name__ == "__main__":
unittest.main()
|
import { TestBed } from '@angular/core/testing';
import { HttpService } from './http.service';
import { UserService } from './user.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { environment } from 'src/environments/environment';
import { User } from '../shared/models/user';
import { of } from 'rxjs';
describe('UserService', () => {
let service: UserService;
let mockHttpService: HttpService;
let httpTestingController: HttpTestingController;
const mockUser: User = new User();
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
});
service = TestBed.inject(UserService);
mockHttpService = TestBed.inject(HttpService);
httpTestingController = TestBed.inject(HttpTestingController);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('returns data when inviteUser() is successful', () => {
service.inviteUser(mockUser).subscribe(response => {
expect(response).toEqual('Registered');
});
const req = httpTestingController.expectOne(environment.inviteUrl);
expect(req.request.method).toBe("POST");
req.flush('Registered');
httpTestingController.verify();
});
});
|
import { Injectable } from '@angular/core';
import { Camera, CameraResultType, CameraSource, Photo } from '@capacitor/camera';
import { Filesystem, Directory } from '@capacitor/filesystem';
import { Storage } from '@capacitor/storage';
import { Platform } from '@ionic/angular';
import { Capacitor } from '@capacitor/core';
@Injectable({
providedIn: 'root'
})
export class PhotoService {
public photos: UserPhoto[] = [];
private PHOTO_STORAGE: string = 'photos';
private platform: Platform;
public savedFile;
public imgfile;
constructor(platform: Platform) {
this.platform = platform;
}
public async addNewToGallery(): Promise<Photo> {
try{
// Take a photo
const capturedPhoto = await Camera.getPhoto({
resultType: CameraResultType.Uri,
source: CameraSource.Camera,
quality: 100
});
// Save the picture and add it to photo collection
const savedImageFile = await this.savePicture(capturedPhoto);
// Add new photo to Photos array
this.photos.unshift(savedImageFile);
Storage.set({
key: this.PHOTO_STORAGE,
value: JSON.stringify(this.photos),
});
return capturedPhoto;
}
catch(e){
console.log('no photo');
}
}
public async getFromGallery() : Promise<Photo> {
// Take a photo
const existingPhoto = await Camera.getPhoto({
resultType: CameraResultType.Uri, // file-based data; provides best performance
source: CameraSource.Prompt, // automatically take a new photo with the camera
quality: 100, // highest quality (0 to 100)
});
return existingPhoto;
}
public async loadSaved() {
// Retrieve cached photo array data
const photoList = await Storage.get({ key: this.PHOTO_STORAGE });
this.photos = JSON.parse(photoList.value) || [];
// If running on the web...
if (!this.platform.is('hybrid')) {
for (let photo of this.photos) {
// Read each saved photo's data from the Filesystem
const readFile = await Filesystem.readFile({
path: photo.filepath,
directory: Directory.Data,
});
// Web platform only: Load the photo as base64 data
photo.webviewPath = `data:image/jpeg;base64,${readFile.data}`;
}
}
}
// Save picture to file on device
private async savePicture(camphoto: Photo) {
// Convert photo to base64 format, required by Filesystem API to save
const base64Data = await this.readAsBase64(camphoto);
// Write the file to the data directory
const fileName = new Date().getTime() + '.jpeg';
this.savedFile = await Filesystem.writeFile({
path: fileName,
data: base64Data,
directory: Directory.Data
});
if (this.platform.is('hybrid')) {
// Display the new image by rewriting the 'file://' path to HTTP
// Details: https://ionicframework.com/docs/building/webview#file-protocol
return {
filepath: this.savedFile.uri,
webviewPath: Capacitor.convertFileSrc(this.savedFile.uri),
};
}
else {
// Use webPath to display the new image instead of base64 since it's
// already loaded into memory
return {
filepath: fileName,
webviewPath: camphoto.webPath
};
}
}
//write photo to file type
// public async photoToFile(camphoto: Photo) {
// const fileContents = new Buffer(attachmentResponse.data.data, 'base64')
// fs.writeFile(part.filename, fileContents, (err) => {
// if (err) return console.error(err)
// console.log('file saved to ', part.filename)
// })
// // "hybrid" will detect Cordova or Capacitor
// if (this.platform.is('hybrid')) {
// // Read the file into base64 format
// const file = await Filesystem.readFile({
// path: camphoto.path
// });
// return file.data;
// }
// else {
// // Fetch the photo, read as a blob, then convert to base64 format
// const response = await fetch(camphoto.webPath);
// const blob = await response.blob();
// return await this.convertBlobToBase64(blob) as string;
// }
// }
public async readAsBase64(camphoto: Photo) {
// "hybrid" will detect Cordova or Capacitor
if (this.platform.is('hybrid')) {
// Read the file into base64 format
const file = await Filesystem.readFile({
path: camphoto.path
});
return file.data;
}
else {
// Fetch the photo, read as a blob, then convert to base64 format
const response = await fetch(camphoto.webPath);
const blob = await response.blob();
this.imgfile = new File([blob], 'image.jpg', {type: blob.type});
return await this.convertBlobToBase64(blob) as string;
}
}
public async deletePicture(photo: UserPhoto, position: number) {
// Remove this photo from the Photos reference data array
this.photos.splice(position, 1);
// Update photos array cache by overwriting the existing photo array
Storage.set({
key: this.PHOTO_STORAGE,
value: JSON.stringify(this.photos)
});
// delete photo file from filesystem
const filename = photo.filepath.substr(photo.filepath.lastIndexOf('/') + 1);
await Filesystem.deleteFile({
path: filename,
directory: Directory.Data
});
}
convertBlobToBase64 = (blob: Blob) => new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
}
export interface UserPhoto {
filepath: string;
webviewPath: string;
}
|
# Test Yourself (Multipart) 5.2
# Let's return to the example involving SAT scores where we took independent
# simple random samples of 5 students who took the in school SAT prep course,
# 5 students who had private SAT prep instruction,
# and 5 students who did not take any SAT prep course.
# Their SAT scores on the math portion are below as are some descriptive statistics by group.
# Fill in the ANOVA table below using the values calculated earlier:
# Set up the hypotheses and select the alpha level
# H0:μIn-School = μPrivate = μNone (All underlying population means are equal)
# H1:μIn-School = μPrivate = μNone (Not all of the underlying population means are equal)
# α = 0.01
# Select the appropriate test statistic
MSB <- 195
MSW <- 333.33
# F = MSB/MSW
# State the decision rule
(test_f_stat <- qf(.99, df1=2, df2=12)) # alpha of 0.01
# Reject H0 if F ≥ 6.926608. Otherwise, do not reject
# Compute the test statistic
# Test Statistic - F Value
(F <- MSB/MSW)
F >= test_f_stat
# Conclusion
# Do not reject H0 since 0.59 is not ≥ 6.93
# We do not have evidence at the α=0.01 level that there is a difference
# in mean SAT scores by type of SAT preparation (here, p =0.57
# as calculated using a software program).
###########################################################################
###########################################################################
###########################################################################
# The global F test above is used to test whether there are differences between the underlying
# group means. If the global F
# test indicates that there are group differences (if the null hypothesis is rejected),
# then it is often of interest to take the additional steps needed to determine which of the population
# group means are different.
# To determine where the differences lie, we perform testing on each pairwise comparison of interest.
# In order to test if μi=μj, for example, we use a t-statistic. Below is a problem with an example.
# Test Yourself (Multipart) 5.3
# Use the raw data and the ANOVA table below to test whether the mean distance of Callaway
# brand balls is different from the mean distance of Nike brand golf balls.
# Formally set up this test and use α=0.05
# α = 0.05
# Set up the hypotheses and select the alpha level
# H0:μCallaway = μNike
# H1:μCallaway ≠ μNike
# State the decision rule
# Two tailed t-test
# Find T
(a = 0.05/2)
(test_stat <- abs(qt(a, df=12)))
# OR
# Find T
(alpha <- 0.05)
(t.critical <- qt(1-(alpha/2), df=12))
# Decision Rule: Reject H0 if t ≥ 2.18 or if t ≤ −2.179
# Compute Test Statistic
(t <- (285 - 260)/sqrt(62.5 * (1/5 + 1/5)))
pairwise.t.test(distance, brand, p.adj="none")
# Conclusion: If TRUE then we reject H0 else accept H1 the alternative
t >= test_stat
# Reject H0 since 5 > 2.178813. We have significant evidence at the alpha 0.05 level that μCallaway ≠ μNike
(Upper <- (285 - 260)+2.18*sqrt(62.5 * (1/5 + 1/5)))
(Lower <- (285 - 260)+2.18*sqrt(62.5 * (1/5 + 1/5)))
# We are 95% confident that the true increase in distance for Callaway is between 14.1 yards & 35.9 yards
# Family Wise Error Rate (FWER)
alpha <- 0.01
num_tests <- 10
(FWER <- abs(1 -(1 - alpha)^num_tests)*100)
# Correct alpha level with Bonferoni Test
(bonferoni_corrected_alpha <- alpha/num_tests)
# Now rerun with new alpha
(FWER <- abs(1 - (1 - bonferoni_corrected_alpha)^num_tests))
t.test(Participants,conf.level=0.90)
t.test(97.5, 12)
### ### ### ### ### ###
### QUIZ 5 PROBLEMS ###
### ### ### ### ### ###
# Question #3
qf(.95, df1 = 8, df2 = 198)
9*(9-1)/2
|
import React, { FC } from "react";
import DatePicker from "react-datepicker";
import Select from "react-select";
import { Input, Label, Row, Col, Button } from "reactstrap";
import { Formik } from "formik";
import * as yup from "yup";
import { DefaultOption, Task } from "../../../interfaces/task";
import { CustomDatePicker } from "../../../components/CustomDatePicker";
import ErrorHandler from "../../../components/ErrorHandler";
let piorityOptions: DefaultOption[] = [
{ value: "normal", label: "Normal" },
{ value: "low", label: "Low" },
{ value: "high", label: "High" },
];
interface Props {
task: Task;
onSave: (task: Task) => void;
}
let currentDate = new Date();
currentDate.setDate(currentDate.getDate() - 1);
const schema = yup.object({
title: yup.string().required("Title is required"),
startDate: yup.date().min(currentDate, "Due date not less than current date"),
});
const TaskForm: FC<Props> = ({ task, onSave }) => {
return (
<Formik
initialValues={task}
validationSchema={schema}
onSubmit={(values, actions) => {
onSave(values);
actions.resetForm();
}}
>
{(formikProps) => {
const { values, touched, errors, handleSubmit } = formikProps;
return (
<div>
{!!task && !task.id && (
<Label className="label-task">New Task</Label>
)}
<Label for="Description" className="label-custom mt-3">
Title
</Label>
<Input
value={values.title}
placeholder="Add new task..."
onChange={(e) => {
formikProps.setFieldValue("title", e.target.value);
}}
/>
{touched.title && errors.title && (
<ErrorHandler text={errors.title as string} />
)}
<Label for="Description" className="label-custom mt-3">
Description
</Label>
<Input
type="textarea"
name="text"
className="description"
id="Description"
value={values.description}
onChange={(e) => {
formikProps.setFieldValue("description", e.target.value);
}}
/>
<Row>
<Col xs={6}>
<Label for="Description" className="label-custom mt-3">
Due Date
</Label>
<DatePicker
selected={values.startDate}
onChange={(date: Date) => {
formikProps.setFieldValue("startDate", date);
}}
customInput={<CustomDatePicker ref={null} />}
/>
{touched.startDate && errors.startDate && (
<ErrorHandler text={errors.startDate as string} />
)}
</Col>
<Col xs={6}>
<Label for="Description" className="label-custom mt-3">
Piority
</Label>
<Select
value={values.piority}
onChange={(value) => {
formikProps.setFieldValue("piority", value);
}}
options={piorityOptions}
/>
</Col>
</Row>
<Button className="btn-add" onClick={() => handleSubmit()}>
{!!task && !task.id ? "Add" : "Update"}
</Button>
</div>
);
}}
</Formik>
);
};
export default TaskForm;
|
/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
/**
* Language Select Dropdown
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect, useSelector } from "react-redux";
import { DropdownToggle, DropdownMenu, Dropdown } from "reactstrap";
import { Scrollbars } from "react-custom-scrollbars";
import { useRemember } from "react-remember";
import Tooltip from "@material-ui/core/Tooltip";
// actions
import { setLanguage, rtlLayoutAction } from "Actions";
import { FormattedMessage } from "react-intl";
class LanguageProvider extends Component {
constructor(props) {
super(props);
this.state = {
langDropdownOpen: false,
};
}
// function to toggle dropdown menu
toggle = () => {
this.setState({
langDropdownOpen: !this.state.langDropdownOpen,
});
};
// on change language
onChangeLanguage = (lang) => {
this.setState({ langDropdownOpen: false });
this.props.setLanguage(lang);
localStorage.setItem("locale", JSON.stringify(lang));
if (lang.locale === "ar" || lang.locale === "he") {
this.rtlLayoutHanlder(true);
} else {
this.rtlLayoutHanlder(false);
}
};
/**
* Rtl Layout Event Hanlder
* Use to Enable rtl Layout
* @param {*object} event
*/
rtlLayoutHanlder = (isTrue) => {
const root = document.getElementsByTagName("html")[0];
if (isTrue) {
root.setAttribute("dir", "rtl");
document.body.classList.add("rtl");
} else {
root.setAttribute("dir", "ltr");
document.body.classList.remove("rtl");
}
this.props.rtlLayoutAction(isTrue);
};
render() {
const { locale } = this.props;
return (
<Dropdown
nav
className="list-inline-item language-dropdown tour-step-5"
isOpen={this.state.langDropdownOpen}
toggle={this.toggle}
>
<DropdownToggle caret nav className="header-icon language-icon">
<Tooltip title="Languages" placement="bottom">
<img
src={require(`Assets/flag-icons/${locale.icon}.png`)}
className="mr-10"
width="25"
height="16"
alt="lang-icon"
/>
</Tooltip>
</DropdownToggle>
<DropdownMenu>
<div className="dropdown-content">
<div className="dropdown-top d-flex justify-content-between rounded-top bg-primary">
<span className="text-white font-weight-bold">
<FormattedMessage id="languages" />
</span>
</div>
<Scrollbars className="rct-scroll" autoHeight autoHeightMin={100} autoHeightMax={280}>
<LanguagesSelection onChangeLanguage={this.onChangeLanguage} />
</Scrollbars>
</div>
</DropdownMenu>
</Dropdown>
);
}
}
LanguageProvider.propTypes = {
locale: PropTypes.object,
rtlLayoutAction: PropTypes.func,
setLanguage: PropTypes.func,
};
// map state to props
const mapStateToProps = ({ settings }) => settings;
export default connect(mapStateToProps, {
setLanguage,
rtlLayoutAction,
})(LanguageProvider);
const LanguagesSelection = ({ onChangeLanguage }) => {
const [, remember] = useRemember();
const { settings } = useSelector((state) => state);
const { languages } = settings;
return (
<ul className="list-unstyled mb-0 dropdown-list d-flex">
{languages.map((language, key) => (
<li
key={JSON.stringify(key)}
onKeyDown={() => onChangeLanguage(language)}
onClick={() => {
onChangeLanguage(language);
remember({ locale: language.locale });
}}
>
<a href="#" onClick={(e) => e.preventDefault()}>
<img
src={require(`Assets/flag-icons/${language.icon}.png`)}
className="mr-10"
width="25"
height="16"
alt="lang-icon"
/>
<FormattedMessage id={language.name} />
</a>
</li>
))}
</ul>
);
};
LanguagesSelection.propTypes = {
onChangeLanguage: PropTypes.func,
};
|
package com.example.alleywayalliancelms.service;
import com.example.alleywayalliancelms.exception.BookNotFoundException;
import com.example.alleywayalliancelms.model.Book;
import com.example.alleywayalliancelms.model.PatronAccount;
import com.example.alleywayalliancelms.model.Role;
import com.example.alleywayalliancelms.repository.PatronAccountRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.*;
@Slf4j
@Service
@RequiredArgsConstructor
public class PatronAccountService implements UserDetailsService {
private final PatronAccountRepository patronAccountRepository;
private final BookService bookService;
private final CheckoutService checkoutService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
PatronAccount patronAccount = patronAccountRepository.getPatronAccountByEmail(username);
if (patronAccount == null) {
throw new UsernameNotFoundException("User not found");
}
return new User(patronAccount.getEmail(),
patronAccount.getPassword(),
patronAccount.isEnabled(),
true,
true,
true,
patronAccount.getAuthorities());
}
public List<PatronAccount> getAllAccountsWithSortedCheckouts() {
List<PatronAccount> allAccounts = patronAccountRepository.findAll();
for (PatronAccount el : allAccounts) {
el.setCheckouts(checkoutService.checkActiveCheckoutsForUser(el, false));
}
return allAccounts;
}
public PatronAccount updateAccountInformation(String email, PatronAccount patronAccountForm) {
PatronAccount patronAccount = patronAccountRepository.getPatronAccountByEmail(email);
patronAccount.setFirstName(patronAccountForm.getFirstName());
patronAccount.setEmail(patronAccountForm.getEmail());
patronAccount.setSurename(patronAccountForm.getSurename());
return patronAccountRepository.save(patronAccount);
}
public PatronAccount getAccountByEmail(String email) {
return patronAccountRepository.getPatronAccountByEmail(email);
}
public PatronAccount findPatronAccountById(String id) {
Optional<PatronAccount> patronAccountFromDb = patronAccountRepository.findById(id);
return patronAccountFromDb.orElse(new PatronAccount());
}
public void saveBookToWaitList(Long bookId, String email) throws BookNotFoundException {
PatronAccount patronAccountFromDb = patronAccountRepository.getPatronAccountByEmail(email);
Book book = bookService.getBookById(bookId);
Set<Book> bookSet = new HashSet<>(patronAccountFromDb.getBooks());
bookSet.add(book);
patronAccountFromDb.setBooks(bookSet);
patronAccountRepository.save(patronAccountFromDb);
}
public boolean checkIfBookAlreadyInWaitlist(Long bookId, String email) {
PatronAccount patronAccountFromDb = patronAccountRepository.getPatronAccountByEmail(email);
for (Book el : patronAccountFromDb.getBooks()) {
if (bookId.equals(el.getId())) {
return true;
}
}
return false;
}
public boolean savePatronAccount(PatronAccount patronAccount) {
PatronAccount patronAccountFromDb = patronAccountRepository.getPatronAccountByEmail(patronAccount.getEmail());
if (patronAccountFromDb != null) {
return false;
}
patronAccount.setRole(1L);
patronAccount.setStatus(true);
patronAccount.setRoles(Collections.singleton(new Role(1L, "ROLE_USER")));
patronAccount.setPassword(bCryptPasswordEncoder.encode(patronAccount.getPassword()));
patronAccountRepository.save(patronAccount);
return true;
}
public boolean deletePatronAccount(String id) {
if (patronAccountRepository.findById(id).isPresent()) {
patronAccountRepository.deleteById(id);
return true;
}
return false;
}
}
|
# Petals Chat
A chatbot [web app](https://chat.petals.dev) + HTTP and WebSocket endpoints for LLM inference with the [Petals](https://petals.dev) client
## Interactive Chat
<div align="center">
<img src="https://i.imgur.com/QVTzc6u.png" width="600px">
</div>
You can try it out [here](https://chat.petals.dev) or run the backend on your server using these commands:
```bash
git clone https://github.com/petals-infra/chat.petals.dev.git
cd chat.petals.dev
pip install -r requirements.txt
flask run --host=0.0.0.0 --port=5000
```
In production, we recommend using gunicorn instead of the Flask dev server:
```bash
gunicorn app:app --bind 0.0.0.0:5000 --worker-class gthread --threads 100 --timeout 1000
```
The chat uses the WebSocket API under the hood.
## APIs
The backend provides two APIs endpoints:
- [WebSocket API](#websocket-api-apiv2generate) (`/api/v2/generate`, recommended)
- [HTTP API](#http-api-apiv1) (`/api/v1/...`)
Please use the WebSocket API when possible - it is much faster, more powerful, and consumes less resources.
If you develop your own web app, you can use our endpoint at `https://chat.petals.dev/api/...` for research and development, then set up your own backend for production using the commands above.
> **Note:** We do not recommend using the endpoint at `https://chat.petals.dev/api/...` in production. It has a limited throughput, and we may pause or stop it any time.
### Backend's system requirements
- If you use a CPU-only server, you need enough RAM to fit embeddings for all models (see the table below).
If your CPU supports AVX512, the embeddings will be loaded in 16-bit, otherwise they will be loaded in 32-bit (= 2x more memory).
This is because multiplying 16-bit weights without AVX512 is slow and may introduce a slowdown of 1-2 sec/token.
AVX512 support is available on late Intel Xeon CPUs
(e.g., on [DigitalOcean](https://digitalocean.com) droplets with a dedicated CPU).
- If you use a GPU server, you need enough GPU memory to fit the embeddings for all models.
The embeddings will be loaded in 16-bit.
- You don't have to serve all models. If you don't have enough memory, remove some models in [config.py](config.py).
| Model family | Embeds in 16-bit | Embeds in 32-bit |
| --- | --- | --- |
| LLaMA 2 (70B, 70B-Chat), LLaMA-65B, Guanaco-65B | 1.05 GB | 2.1 GB |
| BLOOM-176B, BLOOMZ-176B | 7.19 GB | 14.38 GB |
## WebSocket API (`/api/v2/generate`)
This API implies that you open a WebSocket connection and exchange JSON-encoded requests and responses.
This may be done from any programming language, see the example on Javascript:
```javascript
const ws = new WebSocket(`wss://chat.petals.dev/api/v2/generate`);
ws.onopen = () => {
ws.send(JSON.stringify({type: "open_inference_session", max_length: 1024}));
ws.onmessage = event => {
const response = JSON.parse(event.data);
// TODO: Your code here
};
};
```
The requests must follow this protocol:
### open_inference_session
The first request must be of type **open_inference_session** and include the `max_length` parameter (int, required)
and, optionally, the `model` (str) parameter (default: `config.DEFAULT_MODEL_NAME`).
The inference session created by this request is unique to this WebSocket connection and cannot be reused in other connections.
It is closed automatically when the connection is closed.
Request:
```javascript
{type: "open_inference_session", max_length: 1024}
```
Response:
```javascript
{ok: true} // If successful
{ok: false, traceback: "..."} // If failed
```
### generate
The next requests must be of type **generate** and include the same parameters as in the [/api/v1/generate HTTP API](#post-apiv1generate).
In contrast to HTTP API, you can use this API in streaming fashion, generating a response token-by-token and accepting intermediate prompts from a user
(e.g., to make a chatbot).
A new feature of the WebSocket API is the `stop_sequence` parameter (str, optional). If you set it, the server will continue generation with the same parameters unless it generates the `stop_sequence`, so you may get multiple responses without having to send the request again and wait for the round trip's latency.
Intermediate responses contain the field `stop: false`, and the last response contains `stop: true`. For example, you can set `max_new_tokens: 1` and receive tokens one by one, as soon as they are generated. Check out the chat's [frontend code](static/chat.js) for a detailed example of how to do that.
Request:
```javascript
{type: "generate", "inputs": "A cat in French is \"", "max_new_tokens": 3}
```
Response (one or multiple):
```javascript
{ok: true, outputs: "chat\".", stop: true} // If successful
{ok: false, traceback: "..."} // If failed
```
## HTTP API (`/api/v1/...`)
### POST /api/v1/generate
Parameters:
- **model** (str, optional) - Model name. Default: `config.DEFAULT_MODEL_NAME`.
- **inputs** (str, optional) - New user inputs. May be omitted if you continue generation in an inference session (see below).
- **do_sample** (bool, optional) - If `0` (default), runs greedy generation. If `1`, performs sampling with parameters below.
- **temperature** (float, optional)
- **top_k** (int, optional)
- **top_p** (float, optional)
- **max_length** (int) - Max length of generated text (including prefix) in tokens.
- **max_new_tokens** (int) - Max number of newly generated tokens (excluding prefix).
Notes:
- You need to specify either `max_length` or `max_new_tokens`.
- If you'd like to solve downstream tasks in the zero-shot mode, start with `do_sample=0` (default).
- If you'd like to make a chat bot or write a long text, start with `do_sample=1, temperature=0.75, top_p=0.9` (tuning these params may help).
Returns (JSON):
- **ok** (bool)
- **outputs** (str)
- **traceback** (str) - the Python traceback if `ok == False`
|
import { useContext } from "react";
import { Link, useHistory } from "react-router-dom";
import AuthContext from "../../store of browser provider/auth-context";
import classes from "./MainNavigation.module.css";
const MainNavigation = () => {
const authCtx = useContext(AuthContext);
const history = useHistory();
const isLoggedIn = authCtx.isLoggedIn;
const logoutHandler = () => {
authCtx.logout();
localStorage.clear();
history.replace("/");
};
return (
<header className={classes.header}>
<Link to="/">
<div className={classes.logo}>Wallet and Note</div>
</Link>
<nav>
<ul>
{isLoggedIn && (
<li>
<Link to="/choosePage">{authCtx.userData.email} </Link>
</li>
)}
{!isLoggedIn && (
<li>
<Link to="/auth">Login</Link>
</li>
)}
{isLoggedIn && (
<li>
<Link to="/choosePage">Main Page</Link>
</li>
)}
{isLoggedIn && (
<li>
<button onClick={logoutHandler}>Logout</button>
</li>
)}
</ul>
</nav>
</header>
);
};
export default MainNavigation;
|
/* tslint:disable max-line-length */
import { TestBed, getTestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestPaperUserService } from 'app/entities/test-paper-user/test-paper-user.service';
import { TestPaperUser } from 'app/shared/model/test-paper-user.model';
import { SERVER_API_URL } from 'app/app.constants';
describe('Service Tests', () => {
describe('TestPaperUser Service', () => {
let injector: TestBed;
let service: TestPaperUserService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
injector = getTestBed();
service = injector.get(TestPaperUserService);
httpMock = injector.get(HttpTestingController);
});
describe('Service methods', () => {
it('should call correct URL', () => {
service.find(123).subscribe(() => {});
const req = httpMock.expectOne({ method: 'GET' });
const resourceUrl = SERVER_API_URL + 'api/test-paper-users';
expect(req.request.url).toEqual(resourceUrl + '/' + 123);
});
it('should create a TestPaperUser', () => {
service.create(new TestPaperUser(null)).subscribe(received => {
expect(received.body.id).toEqual(null);
});
const req = httpMock.expectOne({ method: 'POST' });
req.flush({ id: null });
});
it('should update a TestPaperUser', () => {
service.update(new TestPaperUser(123)).subscribe(received => {
expect(received.body.id).toEqual(123);
});
const req = httpMock.expectOne({ method: 'PUT' });
req.flush({ id: 123 });
});
it('should return a TestPaperUser', () => {
service.find(123).subscribe(received => {
expect(received.body.id).toEqual(123);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush({ id: 123 });
});
it('should return a list of TestPaperUser', () => {
service.query(null).subscribe(received => {
expect(received.body[0].id).toEqual(123);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush([new TestPaperUser(123)]);
});
it('should delete a TestPaperUser', () => {
service.delete(123).subscribe(received => {
expect(received.url).toContain('/' + 123);
});
const req = httpMock.expectOne({ method: 'DELETE' });
req.flush(null);
});
it('should propagate not found response', () => {
service.find(123).subscribe(null, (_error: any) => {
expect(_error.status).toEqual(404);
});
const req = httpMock.expectOne({ method: 'GET' });
req.flush('Invalid request parameters', {
status: 404,
statusText: 'Bad Request'
});
});
});
afterEach(() => {
httpMock.verify();
});
});
});
|
import { Global, Module } from '@nestjs/common'
import { GraphQLModule } from '@nestjs/graphql'
import { join } from 'path'
import { UserModule } from './user/user.module'
import { TypeOrmModule } from '@nestjs/typeorm'
import { User } from './user/user'
import { Policy } from './policy/policy'
import { Index } from './index'
import { LegislationEvent } from './events/legislation/legislation-event'
import { NamedEntity } from './entities/named-entity'
import { Category } from './category/category'
import { PolicyModule } from './policy/policy.module'
import { CategoryModule } from './category/category.module'
import { LegislationEventModule } from './events/legislation/legislation-event.module'
import { IndexModule } from './index/index.module'
import { NamedEntityModule } from './entities/named-entity.module'
export const AppModule = (dbURL: string): any => {
@Global()
@Module({
imports: [
UserModule,
TypeOrmModule.forRoot({
type: 'postgres',
url: dbURL,
entities: [
User,
Policy,
Index,
LegislationEvent,
NamedEntity,
Category,
],
synchronize: true,
}),
GraphQLModule.forRoot({
playground: true,
introspection: true,
autoSchemaFile: join(process.cwd() + 'src/schema.gql'),
sortSchema: true,
}),
PolicyModule,
CategoryModule,
LegislationEventModule,
IndexModule,
NamedEntityModule,
],
controllers: [],
providers: [],
})
abstract class BaseAppModule {}
return BaseAppModule
}
|
import 'package:flutter/material.dart';
class ResultWidget extends StatelessWidget implements PreferredSizeWidget {
final bool? won;
final Function() onRestart;
const ResultWidget({
required this.won,
required this.onRestart,
super.key,
});
Color _getColor() {
switch (won) {
case null:
return Colors.yellow;
case true:
return Colors.green[300]!;
default:
return Colors.red[300]!;
}
}
IconData _getIcon() {
switch (won) {
case null:
return Icons.sentiment_satisfied;
case true:
return Icons.sentiment_very_satisfied;
default:
return Icons.sentiment_very_dissatisfied;
}
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.grey,
child: SafeArea(
child: Container(
padding: const EdgeInsets.all(10),
child: CircleAvatar(
backgroundColor: _getColor(),
child: IconButton(
padding: const EdgeInsets.all(0),
onPressed: onRestart,
icon: Icon(
_getIcon(),
color: Colors.black,
size: 35,
),
),
),
)),
);
}
@override
Size get preferredSize => const Size.fromHeight(120);
}
|
import { useEffect, useState } from "react"
import { Spinner } from "react-bootstrap"
import { useParams } from "react-router-dom"
import { pedirDatos } from "../../mock/pedirDatos"
import { ItemDetail } from "../ItemDetail/ItemDetail"
export const ItemDetailContainer = () => {
const [item, setItem] = useState(null)
const [loading, setLoading] = useState(true)
const { itemId } = useParams()
useEffect(() => {
setLoading(true)
pedirDatos()
.then((resp) => {
setItem( resp.find((item) => item.id === Number(itemId)) )
})
.catch((error) => {
console.log('ERROR', error)
})
.finally(() => {
setLoading(false)
})
}, [itemId])
return (
<section className="container my-5">
{
loading
? <Spinner animation="border" role="status">
<span className="visually-hidden">Loading...</span>
</Spinner>
: <ItemDetail item={item}/>
}
</section>
)
}
|
import React from 'react';
import { FaGithub, FaLinkedin } from 'react-icons/fa';
import { HiOutlineMail } from 'react-icons/hi';
import { AiFillTwitterCircle } from 'react-icons/ai';
function SocialConnections() {
const socials = [
{
id: 1,
child: (
<>
{<FaLinkedin size={30} />}
</>
),
href: "https://www.linkedin.com/in/aditya-singh-76065422b/",
styles: "rounded-tl-md rounded-bl-md"
},
{
id: 2,
child: (
<>
{<FaGithub size={30} />}
</>
),
href: "https://github.com/AdityaSingh-02",
},
{
id: 3,
child: (
<>
{<HiOutlineMail size={30} />}
</>
),
href: "mailto:[email protected]",
},
{
id: 4,
child: (
<>
{<AiFillTwitterCircle size={35} />}
</>
),
href: "https://twitter.com/Go_D_Aditya",
styles: "rounded-tr-md rounded-br-md"
}
];
return (
<>
<div className='hidden lg:flex flex-col text-white top-[90%] left-[50%] right-[50%] absolute'>
<ul className='flex flex-row justify-center '>
{socials.map(({ id, child, href, styles }) => (
<li key={id} className={`${"flex justify-between items-center w-14 h-14 px-4 shadow-gray-700 hover: duration-500 hover:my-2 hover:shadow-none "} + " " + ${styles}`} >
<a href={href} className='flex justify-between items-center w-full'>
{child}
</a>
</li>
))}
</ul>
</div>
</>
)
}
export default SocialConnections;
|
package com.example.spring_batchstudy.validatoedParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobScope;
import org.springframework.batch.core.job.builder.JobBuilder;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
@Slf4j
@Configuration
public class ValidatedParamJobConfig {
@Bean
public Job ValidatedParamJob(JobRepository jobRepository, Step ValidatedParamStep1) {
return new JobBuilder("validatedParamJob", jobRepository)
.validator(new FileValidator())
.start(ValidatedParamStep1)
.build();
}
@Bean
public Step ValidatedParamStep1(JobRepository jobRepository, Tasklet ValidatedParamTasklet, PlatformTransactionManager platformTransactionManager){
return new StepBuilder("validatedParamStep1", jobRepository)
.tasklet(ValidatedParamTasklet, platformTransactionManager).build();
}
@JobScope
public Tasklet ValidatedParamTasklet(@Value("#{jobParameters['fileName']}") String fileName){
return (contribution, chunkContext) -> {
log.info(fileName);
log.info("hello-ValidatedParam");
return RepeatStatus.FINISHED; // 종료 상태 반환
};
} }
// 스프링 배치 4.xx 버전일때
// @Configuration
// @EnableBatchProcessing
//public class HelloWorldJobConfig {
//
// @Autowired
// private JobBuilderFactory jobBuilderFactory;
// @Autowired
// private StepBuilderFactory stepBuilderFactory;
//
// @Bean
// public Job ValidatedParamJob(){
// return jobBuilderFactory.get("hello")
// .incrementer(new RunIdIncrementer())
// .start(ValidatedParamStep())
// .build();
// }
// @Bean
// @JobScope
// public Step ValidatedParamStep() {
// return stepBuilderFactory.get("ValidatedParamStep")
// .tasklet(ValidatedParamTasklet())
// .build();
// }
//
// @Bean
// @StepScope
// public Tasklet ValidatedParamTasklet() {
// return new Tasklet() {
// @Override
// public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
// System.out.println("hello");
// return RepeatStatus.FINISHED;
// }
// };
// }
|
function getFormattedFileSize(fileSize: number): string {
let prefix: number;
let suffix: string;
const KILOBYTE_SIZE = 1000;
const MEGABYTE_SIZE = 1000 * 1000;
const GIGABYTE_SIZE = 1000 * 1000 * 1000;
if (fileSize < KILOBYTE_SIZE) {
prefix = fileSize;
suffix = 'bytes';
}
else if (fileSize < MEGABYTE_SIZE) {
prefix = fileSize / KILOBYTE_SIZE;
suffix = 'KB';
}
else if (fileSize < GIGABYTE_SIZE) {
prefix = fileSize / MEGABYTE_SIZE;
suffix = 'MB';
}
else {
prefix = fileSize / GIGABYTE_SIZE;
suffix = 'GB';
}
return `${prefix.toPrecision(3)} ${suffix}`;
}
export const FileSizeHelper = {
getFormattedFileSize,
}
|
import { QueryClient, useMutation } from '@tanstack/react-query';
import { ToastContents } from '@/components/atoms';
import { User } from '@/types/users';
import { unfollowUser } from '../../api/user';
export type UseUnfollowMutationProps = {
queryClient: QueryClient;
authUser?: Pick<User, 'id'> & Partial<User>;
openToast: (contents: ToastContents) => void;
};
export const useUnfollowMutation = ({
queryClient,
authUser,
openToast,
}: UseUnfollowMutationProps) => {
const mutation = useMutation({
mutationFn: ({ username }: Pick<User, 'username'>) =>
unfollowUser(username),
onError: (error) => {
openToast({
title: 'Oops!',
description:
error instanceof Error
? error.message
: `Something went wrong attempting to unfollow the user`,
});
return error;
},
onSuccess: (_, { username }) => {
// refetch the user to refresh stats
queryClient.invalidateQueries(['users', username]);
// refetch the user's followers to add auth user
queryClient.invalidateQueries(['followers', username]);
if (authUser?.username) {
// refetch auth user's profile page to refresh stats
queryClient.invalidateQueries(['users', authUser.username]);
// refetch auth user's followers list (when auth follows back a user in the list)
queryClient.invalidateQueries(['followers', authUser.username]);
// refetch auth user's following list to add user
queryClient.invalidateQueries(['following', authUser.username]);
}
// update auth user's following status
queryClient.invalidateQueries(['isAuthFollowingUser', username]);
// update auth user's list of users they are following
queryClient.invalidateQueries(['followingIds']);
openToast({
title: 'Success!',
description: `You are no longer following @${username}`,
});
},
});
return mutation;
};
|
#include "main.h"
/**
* _strlen - function that returns the length of a string.
*
* @s: pointer to an string
* Return: int
*/
int _strlen(char *s)
{
int len = 0;
while (*s != '\0')
{
len++;
s++;
}
return (len);
}
|
import React, { useRef, useState, useEffect } from "react";
import { Canvas } from "@react-three/fiber";
import { Environment } from "@react-three/drei";
import { Suspense } from "react";
import Loader from "./Loader";
import { Model as Marble } from "./3d/Marble";
import { Sparkles } from "@react-three/drei";
import DialogueBox from "./DialogueBox";
import { gsap } from "gsap";
import SplitType from "split-type";
export default function Scene() {
useEffect(() => {
const ourText = new SplitType(".anim-text", { types: "chars" });
const chars = ourText.chars;
gsap.fromTo(
chars,
{
y: 100,
opacity: 0,
},
{
y: 0,
opacity: 1,
stagger: 0.05,
duration: 2,
ease: "power4.out",
}
);
}, []);
return (
<div className='relative max-h-screen max-w-screen h-screen w-screen overflow-hidden '>
<Canvas shadows className='z-2'>
<ambientLight intensity={3} color={"#3F2305"} />
<Suspense fallback={<Loader />}>
<Marble />
<Environment files='/env/studio_small_03_1k.hdr' />
</Suspense>
<Sparkles
count={100}
scale={10}
size={5}
speed={0.6}
color={"#B4B4B8"}
/>
</Canvas>
<div className='flex justify-center flex-col absolute bottom-[20%] left-5 items-start w-[30rem] '>
<h1 className='md:text-[4.5rem] tinos-bold text-[2.5rem] font-thin text-black leading-[5rem] anim-text'>
SOUND
</h1>
<h1 className='md:text-[4.5rem] tinos-bold text-[2.5rem] font-thin text-black leading-[5rem] anim-text'>
EXPERIENCE
</h1>
</div>
</div>
);
}
|
import SwiftUI
struct HubsSection: View {
@Environment(\.managedObjectContext) private var moc
let trip: Trip
@State var showHubAddition = false
@State var hubDetail: Hub? = nil
@FetchRequest private var hubs: FetchedResults<Hub>
init(trip: Trip) {
self.trip = trip
_hubs = FetchRequest(
entity: Hub.entity(),
sortDescriptors: [
NSSortDescriptor(keyPath: \Hub.addedAt, ascending: true)
],
predicate: NSPredicate(format: "trip == %@", trip)
)
}
private func addHub(_ hub: Hub) {
showHubAddition = false
hub.trip = trip
do {
try moc.save()
} catch {
print(error)
}
}
private func handleDelete(_ indexSet: IndexSet) {
indexSet
.map { hubs[$0] }
.forEach { hub in
moc.delete(hub)
}
do {
try moc.save()
} catch {
print(error)
// TODO: handle error
}
}
var body: some View {
Section {
ListSectionHeader(title: "Hotels or stays") { showHubAddition = true }
.padding(.horizontal)
.padding(.bottom, 8)
ForEach(hubs) { hub in
Button {
hubDetail = hub
} label: {
HStack {
VStack(alignment: .leading) {
Text(hub.name!)
Text(hub.address ?? "")
.foregroundColor(.secondary)
.font(.caption)
}
Spacer()
Image(systemName: "chevron.forward")
.foregroundColor(.blue)
.font(.title3)
}.padding(.trailing)
}
.listRowSeparator(.visible)
.padding(.leading)
}
.onDelete(perform: handleDelete)
}
.listRowSeparator(.hidden)
.listRowInsets(EdgeInsets())
.sheet(isPresented: $showHubAddition) {
HubSearch(trip: trip, onHubPicked: addHub) { showHubAddition = false }
.environment(\.managedObjectContext, moc)
}
.sheet(item: $hubDetail) { hub in
HubDetails(hub: hub) {
hubDetail = nil
}
}
}
}
struct Hubs_Previews: PreviewProvider {
static let moc = PersistenceController.preview.container.viewContext
static var previews: some View {
let trip = Trip(context: moc)
let hub = Hub(context: moc)
hub.name = "Test"
hub.trip = trip
return SwiftUI.List {
HubsSection(
trip: trip
)
}
.listStyle(.plain)
.environment(\.managedObjectContext, moc)
.previewLayout(.sizeThatFits)
}
}
|
package com.athimue.data.network.dto.searchArtist
import com.athimue.data.network.dto.album.*
import com.athimue.domain.model.Artist
import com.google.gson.annotations.SerializedName
data class SearchArtistDto(
@SerializedName("id") val id: Long,
@SerializedName("name") val name: String,
@SerializedName("link") val link: String,
@SerializedName("picture") val picture: String,
@SerializedName("picture_small") val pictureSmall: String,
@SerializedName("picture_medium") val pictureMedium: String,
@SerializedName("picture_big") val pictureBig: String,
@SerializedName("picture_xl") val pictureXl: String,
@SerializedName("nb_album") val nbAlbum: Int,
@SerializedName("nb_fan") val nbFan: Int,
@SerializedName("radio") val radio: Boolean,
@SerializedName("tracklist") val tracklist: String,
@SerializedName("type") val type: String
)
fun SearchArtistDto.toArtist() = Artist(
id = id,
name = name,
link = link,
cover = pictureXl,
nbAlbum = nbAlbum,
nbFan = nbFan
)
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/reset.css">
<style>
.nav { width: 1000px; }
.nav .gnb { font-size: 0; }
.nav .gnb li {display: inline-block; }
.nav .gnb li a {
display: block;
width: 104px;
height: 37px;
font-size: 16px;
background-repeat: no-repeat;
background-position: 0 0;
background-image: url(images/nav.png);
/* 접근성 */
text-indent: -9999em;
overflow: hidden;
}
.nav .gnb li:nth-child(1) a {}
.nav .gnb li:nth-child(2) a {
background-position: -103px 0;
}
.nav .gnb li:nth-child(3) a {
background-position: -206px 0;
}
.nav .gnb li:nth-child(4) a {
background-position: -309px 0;
}
/* :hover - 마우스 올렸을때 (많이 사용) :모든태그 사용가능 */
.nav .gnb li a:hover {
background-position-y:-38px ;
}
/* 눌렀을때 - 중요하지 않음 */
.nav .gnb li a:active {
background-position-y:-76px ;
}
</style>
</head>
<body>
<!-- nav.nav>ul.gnb>li*8>a[href="#"] -->
<nav class="nav">
<ul class="gnb">
<li><a href="#">홈</a></li>
<li><a href="#">Store</a></li>
<li><a href="#">Mac</a></li>
<li><a href="#">iPod</a></li>
<li><a href="#">iPhone</a></li>
<li><a href="#">iPad</a></li>
<li><a href="#">iTunes</a></li>
<li><a href="#">Support</a></li>
</ul>
</nav>
<pre>
------------------
스프라이트( sprite) 배경 이미지 적용예시
수업용
</pre>
</body>
</html>
|
import React, { useState } from 'react';
import VaultProIcon from '@mui/icons-material/Brightness5Outlined';
import WithdrawIcon from '@mui/icons-material/CreditCardRounded';
import CurrencyExchangeRoundedIcon from '@mui/icons-material/CurrencyExchangeRounded';
import DepositIcon from '@mui/icons-material/SavingsOutlined';
import BCSwapIcon from '@mui/icons-material/SwapCallsRounded';
import { Box, Typography } from '@mui/material';
import Button from '@mui/material/Button';
import { WALLET_TAB_KEY } from '../../constants';
import Dialog from '../Dialog';
import BCSwap from './components/BCSwap';
import Deposit from './components/Deposit';
import VaultPro from './components/VaultPro';
import Withdraw from './components/Withdraw';
import { WalletBody, WalletTabList, WalletFooter } from './styles';
import WalletTabItem from './WalletTabItem';
import { ACTIVE_COLOR } from 'src/themes/colors';
const walletTabs = [
{
key: WALLET_TAB_KEY.DEPOSIT,
label: 'Deposit',
icon: <DepositIcon />,
},
{
key: WALLET_TAB_KEY.BSCSWAP,
label: 'BCSwap',
icon: <BCSwapIcon />,
},
{
key: WALLET_TAB_KEY.VAULT_PRO,
label: 'Vault Pro',
icon: <VaultProIcon />,
},
{
key: WALLET_TAB_KEY.WITHDRAW,
label: 'Withdraw',
icon: <WithdrawIcon />,
},
];
interface WalletDialogProps {
isOpen: boolean;
handleClose: () => void;
}
const WalletDialog = ({ isOpen, handleClose }: WalletDialogProps) => {
const [selectedWalletTab, setSelectedWalletTab] = useState(walletTabs[0]);
const handleSelectTab = (selectedTab) => {
setSelectedWalletTab(selectedTab);
};
return (
<Dialog
title="Wallet"
isOpen={isOpen}
handleClose={handleClose}
dialogHeaderChild={
<Button
startIcon={
<CurrencyExchangeRoundedIcon style={{ fontSize: '14px' }} />
}
sx={{ color: 'text.primary', top: '-50%' }}
>
Transactions
</Button>
}
hasCloseBtn
>
<Box>
<WalletTabList>
{walletTabs.map((walletTab) => (
<WalletTabItem
key={walletTab.key}
isActive={walletTab.key === selectedWalletTab.key}
handleSelectTab={() => handleSelectTab(walletTab)}
icon={walletTab.icon}
label={walletTab.label}
/>
))}
</WalletTabList>
</Box>
<WalletBody>
{selectedWalletTab.key === WALLET_TAB_KEY.DEPOSIT && <Deposit />}
{selectedWalletTab.key === WALLET_TAB_KEY.BSCSWAP && <BCSwap />}
{selectedWalletTab.key === WALLET_TAB_KEY.VAULT_PRO && <VaultPro />}
{selectedWalletTab.key === WALLET_TAB_KEY.WITHDRAW && <Withdraw />}
</WalletBody>
<WalletFooter>
<div className="footer-box">
<Typography>To secure your assets, please</Typography>
<Typography
sx={{ color: ACTIVE_COLOR, fontWeight: 600, marginLeft: '5px' }}
>
Enable 2FA
</Typography>
</div>
</WalletFooter>
</Dialog>
);
};
export default WalletDialog;
|
import { useContext, useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import range from 'lodash/range'
import isEmpty from 'lodash/isEmpty'
import useMediaQuery from '@mui/material/useMediaQuery'
import CircularProgress from '@mui/material/CircularProgress'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import { ThemeContext } from 'styled-components'
import { fetchImages, watchImages, stopWatchingImages } from 'actions'
import { StoreState } from 'types'
import { getSortedImageIds, isFetchingImages } from 'selectors'
import StyledImagesList from './ImagesList.styled'
import ImageFiller from './ImageFiller'
import ImageCard from './ImageCard'
import ImagesFetcher from './ImagesFetcher'
const PER_COLUMN = 3
export default function ImagesList() {
const dispatch = useDispatch()
const theme = useContext(ThemeContext)
const xl = useMediaQuery(theme.breakpoints.up('xl'))
const lg = useMediaQuery(theme.breakpoints.up('lg'))
const md = useMediaQuery(theme.breakpoints.up('md'))
const sm = useMediaQuery(theme.breakpoints.up('sm'))
const perRow = xl ? 5 : lg ? 4 : md ? 3 : sm ? 2 : 1
const { imageIds, isFetching } = useSelector((s: StoreState) => ({
imageIds: getSortedImageIds(s),
isFetching: isFetchingImages(s)
}))
const [missingEnd, setMissingEnd] = useState<number>(0)
const missingStart =
(perRow - ((imageIds.length + missingEnd) % perRow)) % perRow
const fetch = () => {
dispatch(stopWatchingImages())
dispatch(fetchImages({ limit: perRow * 10 }))
dispatch(watchImages())
}
useEffect(() => {
fetch()
}, [])
useEffect(() => {
setMissingEnd(0)
}, [perRow])
const renderFiller = (i: number) => (
<ImageFiller key={i} perRow={perRow} perColumn={PER_COLUMN} />
)
const renderImage = (id: number) =>
id && (
<ImageCard key={id} imageId={id} perRow={perRow} perColumn={PER_COLUMN} />
)
return (
<StyledImagesList>
{isEmpty(imageIds) ? (
isFetching ? (
<div className="loading">
<CircularProgress color="primary" size={45} thickness={5} />
</div>
) : (
<div className="error">
<Typography>Failed to fetch images</Typography>
<Button variant="contained" onClick={fetch}>
Retry
</Button>
</div>
)
) : (
<>
<ul className="images-list">
{range(missingStart).map(renderFiller)}
{imageIds.map(renderImage)}
</ul>
<ImagesFetcher perRow={perRow} setMissingEnd={setMissingEnd} />
</>
)}
</StyledImagesList>
)
}
|
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MovieList.Data;
using MovieList.Models;
namespace MovieList.Controllers
{
[Authorize (Roles = "User")]
public class ListController : Controller
{
private readonly MovieListContext _context;
public ListController(MovieListContext context)
{
_context = context;
}
// GET: List
public async Task<IActionResult> Index()
{
string? userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId == null)
{
return NotFound();
}
var query = _context.ListItem.Where(m => m.IdentityUserId == userId);
var list = query.Select(m => new ListIndexViewModel
{
Id = m.Id,
Title = m.Movie.Title,
ReleaseYear = m.Movie.ReleaseYear,
Genre = m.Movie.Genre,
Note = m.Note
});
return View(await list.ToListAsync());
}
// GET: List/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var listItem = await _context.ListItem
.FirstOrDefaultAsync(m => m.Id == id);
if (listItem == null)
{
return NotFound();
}
return View(listItem);
}
// GET: List/Create
public IActionResult Create(int id)
{
ViewData["MovieId"] = id;
ViewData["MovieTitle"] = _context.Movie.Find(id)?.Title;
return View();
}
// POST: List/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("MovieId, Note")] ListItem listItem)
{
ModelState.Clear();
string? userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
if (userId == null)
{
return NotFound();
}
listItem.IdentityUserId = userId;
listItem.IdentityUser = (await _context.Users.FindAsync(userId))!;
Movie? movie = _context.Movie.Find(listItem.MovieId);
if(movie == null)
{
return NotFound();
}
listItem.Movie = movie;
if (TryValidateModel(listItem))
{
_context.Add(listItem);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(listItem);
}
// GET: List/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var listItem = await _context.ListItem.FindAsync(id);
if (listItem == null)
{
return NotFound();
}
return View(listItem);
}
// POST: List/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,MovieId,IdentityUserId,Note")] ListItem listItem)
{
ModelState.Clear();
if (id != listItem.Id)
{
return NotFound();
}
listItem.IdentityUser = (await _context.Users.FindAsync(listItem.IdentityUserId))!;
Movie? movie = _context.Movie.Find(listItem.MovieId);
if(movie == null)
{
return NotFound();
}
listItem.Movie = movie;
if (TryValidateModel(listItem))
{
try
{
_context.Update(listItem);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ListItemExists(listItem.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(listItem);
}
// GET: List/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var listItem = await _context.ListItem
.FirstOrDefaultAsync(m => m.Id == id);
if (listItem == null)
{
return NotFound();
}
return View(listItem);
}
// POST: List/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var listItem = await _context.ListItem.FindAsync(id);
if (listItem != null)
{
_context.ListItem.Remove(listItem);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool ListItemExists(int id)
{
return _context.ListItem.Any(e => e.Id == id);
}
}
}
|
#!/usr/bin/env python3
import os
import re
import shutil
import sys
# There are three different file type modules:
# filemagic: ubuntu 16.04
# filetype: windows
# magic: ubuntu 18.04
# so try them all, and use whichever one is installed.
mime_module = None
try:
import filetype
mime_module = 'filetype'
except:
import magic
try:
# ubuntu 18.04 uses new magic
mymime = magic.Magic(mime=True)
mime_module = 'magic'
except:
# ubuntu 16.04 uses old filemagic
# https://stackoverflow.com/questions/25286176/how-to-use-python-magic-5-19-1
mymime = magic.open(magic.MAGIC_MIME)
mymime.load()
mime_module = 'filemagic'
def mime_is_text_file(fname):
if mime_module == 'magic':
type = mymime.from_file(fname)
return (type != None and type.startswith('text'))
elif mime_module == 'filemagic':
type = mymime.file(fname)
return (type != None and type.startswith('text'))
elif mime_module == 'filetype':
kind = filetype.guess(fname)
# filetype doesn't support text file types! But it does detect
# images and archives, which is probably enough; if it's not one
# of those, it's prolly text.
return (kind == None or kind.mime.startswith('text'))
else:
print("Sorry, no mime classifier available.")
sys.exit(1)
def usage():
message(
"""
Expand one yovo sample in an obi-like manner (but with an extra level of templating).
First argument is the output directory.
Remaining arguments are the template directories, least to most specific.
For example,
expand-sample btmp/libNoodoo/samples/generated/bubbles samples/obi-template libNoodoo/obi-template libNoodoo/bubbles
creates
btmp/libNoodoo/samples/generated/bubbles
containing all the files for that sample, with variables expanded.
This script is generated from expand-sample.in at yovo configure
time to bake in variable values.
""")
if len(sys.argv) < 4:
print("Usage: expand-sample outdir indir...")
sys.exit(1)
# Strip trailing slashes, if any
outdir = os.path.normpath(sys.argv[1])
templates = [os.path.normpath(arg) for arg in sys.argv[2:]]
# Values from meson or cmake, expanded by configure_file
cdata = {
'yobuild': '@YOBUILD@',
'G_SPEAK_HOME': '@prefix@',
'ASAN': '@ASAN@',
'TSAN': '@TSAN@',
'COVERAGE': '@COVERAGE@',
'MAJOR_VERSION': '@MAJOR_VERSION@',
'MINOR_VERSION': '@MINOR_VERSION@',
}
# Compute a few
cdata['project_name'] = os.path.basename(templates[-1])
print('project_name = ' + cdata['project_name'])
cdata['YOVERSION'] = re.sub(r'^.*[^0-9]','',cdata['yobuild'])
cdata['yobuild_major'] = cdata['YOVERSION']
cdata['NOSLASH_YOBUILD'] = cdata['yobuild'][1:]
cdata['NOSLASH_G_SPEAK_HOME'] = cdata['G_SPEAK_HOME'][1:]
cdata['G_SPEAK_XY'] = cdata['MAJOR_VERSION'] + '.' + cdata['MINOR_VERSION']
# blarg
cdata['g_speak_version'] = cdata['G_SPEAK_XY']
# Walk through the templates
map = {}
for top in templates:
skip = len(top + os.sep)
for root, dirs, files in os.walk(top):
for file in files:
p = os.path.join(root, file)[skip:]
map[p] = top
# Expand the chosen input files
for key in sorted(map.keys()):
# Expand filenames a bit, too. Quote PROJECT to protect it from expansion by configure_file!
xkey = re.sub('@' + 'PROJECT@', cdata['project_name'], key)
xkey = re.sub('@' + 'G_SPEAK_XY@', cdata['project_name'], xkey)
iname = os.path.join(map[key], key)
oname = os.path.join(outdir, xkey)
# Create output directory if missing
os.makedirs(os.path.dirname(oname), mode=0o755, exist_ok=True)
if mime_is_text_file(iname):
try:
# Open input and output file
with open(iname, "r") as ifile:
# On Windows, avoid outputing CR's
with open(oname, "w", newline='\n') as ofile:
# Read
lines = ifile.readlines()
# Expand
for key in cdata.keys():
pat = r'{{' + key + r'}}'
lines = [line.replace(pat, cdata[key]) for line in lines]
# Write
ofile.writelines(lines)
# Success! Continue on to next file.
continue
except:
# fall through to copyfile
pass
shutil.copyfile(iname, oname)
|
class TasksController < ApplicationController
def index
@tasks = Task.all
end
def show
@task = Task.find(params[:id])
end
def new
@task = Task.new
end
def create
@task = Task.new(set_task)
@task.save
redirect_to tasks_path(@task)
end
def edit
@task = Task.find(params[:id])
end
def update
@task.update(set_task)
redirect_to task_path(@task)
end
def destroy
@task.destroy
redirect_to tasks_path
end
def find_task
@task = Task.find(params[:id])
end
def set_task
params.require(:task).permit(:title, :details, :completed)
end
end
|
from ev_comm.model.battery_state import BatteryState
from ev_comm.model.charging_state import ChargingState
from ev_comm.model.environment_state import EnvironmentState
from ev_comm.model.position_state import PositionState
from datetime import datetime
class CarState:
def load_from_psacc_response(self, response):
self.battery = BatteryState(
response["energy"][0]["level"],
response["energy"][0]["autonomy"],
ChargingState(
response["energy"][0]["charging"]["charging_mode"],
response["energy"][0]["charging"]["charging_rate"],
response["energy"][0]["charging"]["plugged"],
response["energy"][0]["charging"]["remaining_time"],
response["energy"][0]["charging"]["status"],
),
response["energy"][0]["updated_at"]
)
self.environment = EnvironmentState(
response["environment"]["air"]["temp"],
response["environment"]["luminosity"]["day"]
)
self.position_state = PositionState(
response["last_position"]["geometry"]["coordinates"][0],
response["last_position"]["geometry"]["coordinates"][1],
response["last_position"]["geometry"]["coordinates"][2],
response["last_position"]["properties"]["updated_at"]
)
self.odometer = response["timed_odometer"]["mileage"],
self.ignition = response["ignition"]["type"]
self.timestamp = datetime.timestamp(datetime.now())
def to_dict(self):
return {
"battery": self.battery.to_dict(),
"environment": self.environment.to_dict(),
"odometer": self.odometer,
"ignition": self.ignition,
"position": self.position_state.to_dict(),
"timestamp": self.timestamp
}
|
import ch from 'chalk';
import exists from 'command-exists-promise';
import { spawn } from 'node:child_process';
import { EventEmitter } from 'node:events';
/*
* Automatically find and open one of NeoVim, Vim, or Vi, the hardest editors to close
*/
class Vim extends EventEmitter {
vim;
editor;
constructor() {
super();
this.vim = null;
this.editor = false;
}
async init() {
const viExists = await exists('vi');
const vimExists = await exists('vim');
const nvimExists = await exists('nvim');
if (nvimExists) {
console.log(ch.cyan('Vim: Using NeoVim'));
this.editor = 'nvim';
} else if (vimExists) {
console.log(ch.cyan('Vim: Using Vim'));
this.editor = 'vim';
} else if (viExists) {
console.log(ch.yellow('Vim: Falling back onto Vi'));
this.editor = 'vi';
} else {
throw new Error('Vim/NeoVim not found');
}
}
start(file) {
if (!this.editor) throw new Error('Editor not selected');
this.vim = spawn(this.editor, [file], {
stdio: 'inherit'
});
this.vim.on('close', code => {
this.emit('close', code);
});
}
quit() {
if (this.vim === null) throw new Error('Vim not started');
this.vim.kill();
}
waitForClose() {
if (this.vim === null) throw new Error('Vim not started');
return new Promise((r, j) => {
this.on('close', r);
this.vim.on('error', j);
});
}
}
export default Vim;
|
import os from "os";
import fs from "fs";
import url from "url";
import path from "path";
import BuildVitePressTemplate from "./vitepress-template-builder.js";
import { Console } from "@mekstuff/logreport";
import { DocDocsConfiguration } from "../configuration.js";
/**
* Returns the `.dcodocs` root path. `./~/.docdocs`
*
* Creates it if it doesn't exists already
*/
export function GetDocDocsRootDirectory(): string {
const DDRPath = path.join(os.homedir(), ".docdocs");
if (!fs.existsSync(DDRPath)) {
try {
fs.mkdirSync(DDRPath, { recursive: true });
} catch (err) {
Console.error(`Could not create root directory: ${err}`);
process.exit(1);
}
}
return DDRPath;
}
/**
* Returns the `.docdocs/cache` root path.
*
* Creates it if it doesn't exists already
*/
export function GetDocDocsRootCacheDirectory(): string {
const CachePath = path.join(GetDocDocsRootDirectory(), "cache");
if (!fs.existsSync(CachePath)) {
try {
fs.mkdirSync(CachePath, { recursive: true });
} catch (err) {
Console.error(`Could not create root cache directory: ${err}`);
process.exit(1);
}
}
return CachePath;
}
/**
* Gets the version of vitepress that is used in a cached project
*/
export function GetVitePressVersionOfCachedProject(
directory: string
): string | undefined {
try {
const pj = JSON.parse(
fs.readFileSync(path.join(directory, "package.json"), "utf-8")
);
return pj.version;
} catch {
return;
}
}
/**
* Removes all unrelated files from the cache/project directory
*/
export function RemoveUnrelatedFilesFromDocsCacheProject(directory: string) {
const IgnoreFiles = [
"index.md",
".vitepress",
"api",
"node_modules",
"package.json",
"yarn.lock",
"package-lock.json",
"pnpm-lock.yaml",
"bun.lockb",
".docdocs-vite-theme-info.json",
];
if (fs.existsSync(directory)) {
fs.readdirSync(directory).forEach((x) => {
if (IgnoreFiles.indexOf(path.parse(x).base) === -1) {
try {
fs.rmSync(path.join(directory, x), { force: true, recursive: true });
} catch (err) {
Console.warn(err);
}
}
});
}
}
/**
* Returns the path of the project if it exists in the cache directory
*/
export function GetDocsDocsCacheProject(name: string): string | undefined {
name = name.replace(/\//g, "--");
const p = path.join(GetDocDocsRootCacheDirectory(), name);
if (fs.existsSync(p)) {
return p;
}
return undefined;
}
/**
* Builds a new project in cache
*/
export function CreateNewDocDocsCacheProject(
name: string,
ignoreCache?: boolean
): string {
name = name.replace(/\//g, "--");
const p = path.join(GetDocDocsRootCacheDirectory(), name);
if (fs.existsSync(p)) {
if (!ignoreCache) {
return p;
}
}
try {
fs.rmSync(p, { force: true });
fs.mkdirSync(p, { recursive: true });
BuildVitePressTemplate(p);
} catch (err) {
Console.error(err);
}
return p;
}
/**
* Returns the `docdocs.config.[ext]` joined to the given dir
*/
export function GetDocDocsConfigDir(cwd?: string) {
return path.join(cwd ? cwd : process.cwd(), "docdocs.config.js");
}
/**
* To remove the caching of the `docdocs.config.[ext]` file, add this index on each import query param then
* increment it.
*
* NOTE: This method may cause memory leaks potentially if each imported module is kept and not garbage collected.
* Deleting the path from require.cache using `{ createRequire }` does not seem to work, this will be a preferred methid,
* but will have to look into why it doesn't work in this case.
*/
let DocDocsConfigImportIndex = 0;
let CurrentDocDocsConfig: DocDocsConfiguration | undefined;
/**
* Loads the `docdoc.config.[ext]` file and stores it in a variable
*
* We opt to using this to prevent having to make every function `async` with `GetDocDocsConfig`. So instead we Load the config
* on start or whenever file changes (for dev mode)
*/
export async function LoadDocDocsConfig(): Promise<DocDocsConfiguration> {
const p = GetDocDocsConfigDir(process.cwd());
if (!fs.existsSync(p)) {
Console.error(`file was not found: "${p}".`);
process.exit(1);
}
const importpath = url.pathToFileURL(p).toString();
try {
const res = await import(
importpath + `?cache-index=${DocDocsConfigImportIndex}`
);
DocDocsConfigImportIndex++;
const def = res.default as DocDocsConfiguration;
if (typeof def !== "object") {
throw `default value of module is not an object. Did you export default Config?`;
}
CurrentDocDocsConfig = def;
return def;
} catch (err) {
Console.error(err);
process.exit(1);
}
}
/**
* Reads the `docdocs.config.[ext]` file
*/
export function GetDocDocsConfig(): DocDocsConfiguration {
if (!CurrentDocDocsConfig) {
Console.error("Config was not loaded prior to `GetDocDocsConfig` call.");
process.exit(1);
}
return CurrentDocDocsConfig;
/*
const p = GetDocDocsConfigDir(cwd);
if (!fs.existsSync(p)) {
Console.error(`file was not found: "${p}".`);
process.exit(1);
}
const importpath = url.pathToFileURL(p).toString();
return import(importpath + `?cache-index=${DocDocsConfigImportIndex}`).then(
(res) => {
DocDocsConfigImportIndex++;
const def = res.default as DocDocsConfiguration;
if (typeof def !== "object") {
throw `default value of module is not an object. Did you export default Config?`;
}
return def;
}
);
*/
}
/**
* Creates the api route if it doesn't exist and adds the route to the vite config.
*/
function CreateApiRoute(directory: string): string {
const ApiRoutePath = path.join(directory, "api");
if (!fs.existsSync(ApiRoutePath)) {
fs.mkdirSync(ApiRoutePath);
}
return ApiRoutePath;
}
/**
* Creates a sub route under the api route.
*/
function CreateSubApiRoute(directory: string, RouteName: string): string {
const TargetRoute = path.join(CreateApiRoute(directory), RouteName);
if (!fs.existsSync(TargetRoute)) {
fs.mkdirSync(TargetRoute);
}
return TargetRoute;
}
export type SupportedApiRoutes =
| "class"
| "function"
| "module"
| "interface"
| "type";
/**
* Gets the sub api route, returns undefined if it doesn't exists.
*/
export function GetSubApiRoute(
directory: string,
route: SupportedApiRoutes
): string | undefined {
const SubApiRoutePath = path.join(directory, "api", route);
if (fs.existsSync(SubApiRoutePath)) {
return SubApiRoutePath;
}
}
/**
* Adds to api route.
*
* NOTE: file names and extensions are converted `toLowerCase()`. so when routing make sure to use the `toLowerCase()` on the file.
*/
export function AddToApiRoute(
directory: string,
route: SupportedApiRoutes,
fileName: string,
fileExtension: ".md",
source: string
) {
const TargetRoute = CreateSubApiRoute(directory, route);
/**
* Api Routes need deeper outline than default, e.g class.properties.property will be displayed instead of class.properties.
*/
source = `---\noutline: [2,3]\n---\n` + source;
fs.writeFileSync(
path.join(
TargetRoute,
fileName.toLowerCase() + fileExtension.toLocaleLowerCase()
),
source,
"utf-8"
);
}
|
<?php
/**
* Custom template tags for this theme
*
* Eventually, some of the functionality here could be replaced by core features.
*
* @package klean_blog
*/
/**
* Auto add more links.
*
* @package klean_blog
* @since 1.0
*/
function klean_blog_content_more() {
/* translators: link read more. */
$text = wp_kses_post( sprintf( __( 'Continue reading ➞ %s', 'klean-blog' ), '<span class="screen-reader-text">' . get_the_title() . '</span>' ) );
$more = sprintf( '<div class="link-more"><a href="%s#more-%d" class="more-link">%s</a></div>', esc_url( get_permalink() ), get_the_ID(), $text );
return $more;
}
add_filter( 'the_content_more_link', 'klean_blog_content_more' );
/**
* Auto add more links.
*
* @package klean_blog
* @since 1.0
*/
function klean_blog_excerpt_more_link( $excerpt ) {
$excerpt .= klean_blog_content_more();
return $excerpt;
}
add_filter( 'the_excerpt', 'klean_blog_excerpt_more_link', 21 );
/**
* Change the archive title for category page.
*
* @package klean_blog
* @since 1.0
*/
function klean_blog_category_title( $title ) {
if ( is_category() ) {
$title = single_cat_title( '', false );
}
return $title;
}
add_filter( 'get_the_archive_title', 'klean_blog_category_title' );
/**
* Prints HTML with meta information for the current post-date/time and categories, tags..
*/
function klean_blog_posted_on( $meta = array() ) {
$default_meta = array(
'post_date' => 1,
'author' => 1,
'tag' => 1,
'comment' => 1,
);
if( !empty($meta) && is_array($meta) ) {
foreach ($default_meta as $meta_key => $meta_val) {
$val = in_array($meta_key, $meta) ? 1 : 0;
$result_meta[$meta_key] = $val;
}
}
$result_meta = !empty($result_meta) ? $result_meta : $default_meta;
extract( $result_meta, EXTR_SKIP );
if( is_home() ) {
$post_date = klean_blog_get_theme_mod( 'blog_show_date' );
$author = klean_blog_get_theme_mod( 'blog_show_author' );
$tag = klean_blog_get_theme_mod( 'blog_show_tags' );
} elseif( is_category() ) {
$post_date = klean_blog_get_theme_mod( 'cat_show_date' );
$author = klean_blog_get_theme_mod( 'cat_show_author' );
$tag = klean_blog_get_theme_mod( 'cat_show_tags' );
}
// Post Date
if( $post_date ) {
$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
}
$time_string = sprintf( $time_string,
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() ),
esc_attr( get_the_modified_date( 'c' ) ),
esc_html( get_the_modified_date() )
);
$posted_on = '<a href="' . esc_url( get_permalink() ) . '" rel="bookmark">' . $time_string . '</a>';
echo '<span class="posted-on"><i class="fa fa-clock-o"></i>' . $posted_on . '</span>'; // WPCS: XSS OK.
}
// Post Author
if( $author ) {
$byline = '<span class="author vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ) . '">' . esc_html( get_the_author() ) . '</a></span>';
echo '<span class="byline"><i class="fa fa-user"></i> ' . $byline . '</span>';
}
// Hide category and tag text for pages.
if ( $tag && 'post' === get_post_type() ) {
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list( '', esc_html__( ', ', 'klean-blog' ) );
if ( $tags_list ) {
echo '<span class="tags-links"><i class="fa fa-tags"></i>' . $tags_list . '</span>'; // WPCS: XSS OK.
}
}
if ( $comment && ! post_password_required() && ( comments_open() || get_comments_number() ) ) {
echo '<span class="comments-link"><i class="fa fa-comments-o"></i>';
/* translators: %s: post title */
comments_popup_link( sprintf( wp_kses( __( 'Leave a Comment<span class="screen-reader-text"> on %s</span>', 'klean-blog' ), array(
'span' => array(
'class' => array(),
),
) ), get_the_title() ) );
echo '</span>';
}
}
/**
* Prints HTML with meta information for the current post-date/time and categories, tags..
*/
function klean_blog_posted_on_cat() {
$category = '';
if( is_home() ) {
$category = klean_blog_get_theme_mod( 'blog_show_cat' );
} elseif( is_category() ) {
$category = klean_blog_get_theme_mod( 'cat_show_cat' );
}
// Post Category
if( $category ) {
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( esc_html__( ' ', 'klean-blog' ) );
if ( $categories_list ) {
printf( '<span class="cat-links">%2$s</span>', esc_html__( 'Categories', 'klean-blog' ), $categories_list ); // WPCS: XSS OK.
}
} else {
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( esc_html__( ' ', 'klean-blog' ) );
if ( $categories_list ) {
printf( '<span class="cat-links">%2$s</span>', esc_html__( 'Categories', 'klean-blog' ), $categories_list ); // WPCS: XSS OK.
}
}
}
/**
* Prints HTML with meta information for the categories, tags and comments.
*/
function klean_blog_entry_footer() {
edit_post_link(
sprintf(
/* translators: %s: Name of current post */
esc_html__( 'Edit %s', 'klean-blog' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
),
'<span class="edit-link">',
'</span>'
);
}
/**
* Change the tag could args
*
* @param array $args Widget parameters.
*
* @return mixed
*/
function klean_blog_tag_cloud_args( $args ) {
$args['largest'] = 1; // Largest tag.
$args['smallest'] = 1; // Smallest tag.
$args['unit'] = 'rem'; // Tag font unit.
return $args;
}
add_filter( 'widget_tag_cloud_args', 'klean_blog_tag_cloud_args' );
if ( ! function_exists( 'klean_blog_comment_nav' ) ) :
/**
* Display navigation to next/previous comments when applicable.
*
* @since Twenty Fifteen 1.0
*/
function klean_blog_comment_nav() {
// Are there comments to navigate through?
if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) :
?>
<nav class="navigation comment-navigation" role="navigation">
<h2 class="screen-reader-text"><?php _e( 'Comment navigation', 'klean-blog' ); ?></h2>
<div class="nav-links">
<?php
if ( $prev_link = get_previous_comments_link( __( 'Older Comments', 'klean-blog' ) ) ) :
printf( '<div class="nav-previous">%s</div>', $prev_link );
endif;
if ( $next_link = get_next_comments_link( __( 'Newer Comments', 'klean-blog' ) ) ) :
printf( '<div class="nav-next">%s</div>', $next_link );
endif;
?>
</div><!-- .nav-links -->
</nav><!-- .comment-navigation -->
<?php
endif;
}
endif;
// Remove Wocommerce Wrapper
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);
/**
* Function to start WooCommece wrapper
*
* @package klean_blog
* @since 1.0
*/
function klean_blog_theme_wrapper_start() {
echo '<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">';
}
add_action('woocommerce_before_main_content', 'klean_blog_theme_wrapper_start', 10);
/**
* Function to end WooCommece wrapper
*
* @package klean_blog
* @since 1.0
*/
function klean_blog_theme_wrapper_end() {
echo '</main></div>';
}
add_action('woocommerce_after_main_content', 'klean_blog_theme_wrapper_end', 10);
|
import opuslib
import torch
import numpy as np
class OpusCodec():
"""
Runs Opus compression with the same parameters used on each of the robots
"""
def __init__(self, channels, sr, frame_width=0.02) -> None:
self.channels = channels
# Initialize encoder
self.encoder = opuslib.api.encoder.create_state(sr, channels, opuslib.APPLICATION_RESTRICTED_LOWDELAY)
# Parameters used on robots to do compression
opuslib.api.encoder.encoder_ctl(
self.encoder, opuslib.api.ctl.set_bitrate, 32000)
opuslib.api.encoder.encoder_ctl(
self.encoder, opuslib.api.ctl.set_complexity, 0)
opuslib.api.encoder.encoder_ctl(
self.encoder, opuslib.api.ctl.set_inband_fec, 0)
opuslib.api.encoder.encoder_ctl(
self.encoder, opuslib.api.ctl.set_packet_loss_perc, 0)
opuslib.api.encoder.encoder_ctl(
self.encoder, opuslib.api.ctl.set_dtx, 0)
opuslib.api.encoder.encoder_ctl(
self.encoder, opuslib.api.ctl.set_lsb_depth, 16)
# Create decoder
self.decoder = opuslib.api.decoder.create_state(sr, channels)
# Initialize frame size
self.frame_size = int(round(sr * frame_width))
def apply(self, audio: torch.FloatTensor) -> torch.Tensor:
# Reset encoder state
opuslib.api.encoder.encoder_ctl(self.encoder, opuslib.api.ctl.reset_state)
# Reset decoder state
opuslib.api.decoder.decoder_ctl(self.decoder, opuslib.api.ctl.reset_state)
# Convert float tensor to int16 and then to bytes
audio = (audio * (2 ** 15 - 1)).short().numpy().tobytes()
# Go over and encoder byte array into frames and add encoded frames to list
bchunks = []
for i in range(0, len(audio), 2 * self.frame_size):
encoded = opuslib.api.encoder.encode(self.encoder,
audio[i: i + 2 * self.frame_size],
self.frame_size,
2 * self.frame_size)
bchunks.append(encoded)
# Decode chunks into audio waveform as bytes
output = b''
for bchunk in bchunks:
dec = opuslib.api.decoder.decode(self.decoder,
bchunk,
len(bchunk),
1500,
False,
self.channels)
output += dec
# Convert bytes back to int16 and then back to float
output = torch.from_numpy(np.frombuffer(output, dtype=np.int16) / (2 ** 15 - 1))
return output
|
year_slider <- function(ns, ...) {
shiny::sliderInput(
ns("year"),
"Jahr",
min = min(.GlobalEnv$df_base$year),
max = max(.GlobalEnv$df_base$year),
value = ...,
step = 1,
round = TRUE,
sep = ""
)
}
canton_selector <- function(ns) {
shiny::selectInput(
ns("canton_selection"),
"Kanton hervorheben",
choices = unique(.GlobalEnv$df_cantons$canton),
selected = NULL,
multiple = TRUE
)
}
level_selector <- function(ns) {
shiny::selectInput(
ns("level"),
"Level",
choices = c("can", "mun"),
selected = "can"
)
}
cat1_selector <- function(ns) {
shiny::selectInput(
ns("cat1"),
"Oberkategorie",
choices = c("Einnahmen" = "rev",
"Ausgaben" = "exp",
"Bilanz" = "balance"),
# choices = unique(.GlobalEnv$df_base$cat1),
selected = "rev"
)
}
cat2_selector <- function(ns) {
shiny::selectInput(
ns("cat2"),
"Unterkategorie",
choices = NULL
)
}
unit_selector <- function(ns) {
shiny::selectInput(
ns("unit"),
"Einheit",
# choices = unique(.GlobalEnv$df_base$unit),
choices = c("Pro Kopf (CHF)" = "pc_chf",
"Total (Mio. CHF)" = "agg_miochf"),
selected = "pc_chf"
)
}
# Updates -----------------------------------------------------------------
#' Title
#'
#' @param session Internal shiny variable
#' @param input List, storing user inputs
#'
#' @importFrom magrittr %>%
#'
#' @noRd
update_cat2_selector <- function(session, input) {
shiny::updateSelectInput(
session, inputId = "cat2",
choices = .GlobalEnv$df_var_structure %>%
# dplyr::filter(federal_level == input$level) %>%
dplyr::filter(cat1 == input$cat1) %>%
dplyr::filter(unit == shiny::isolate(input$unit)) %>%
dplyr::pull(cat2) %>%
# Get labels to display
purrr::set_names(get(paste0("v_", input$cat1, "_name_mapping")))
)
}
|
<script lang="ts">
import type { Post } from '$lib/@types/Posts';
import { locale, t } from '$lib/i18n';
import { createEventDispatcher } from 'svelte';
import SvelteExMarkdown from 'svelte-exmarkdown';
export let post: Post;
export let preview = false;
const dispatch = createEventDispatcher();
function tagClick(e: Event) {
if (e.type === 'click' || (e.type === 'keydown' && (e as KeyboardEvent).key === 'Enter')) {
if (e.target instanceof HTMLElement) {
dispatch('tagClick', e.target.innerText);
}
}
}
$: md = preview
? post.content.split('<!-- more -->')[0]
: post.content.replace(/<!-- more -->/g, '');
</script>
<section class="post">
<h1>{post.title}</h1>
{#if post.date}
<span class="date">{new Date(post.date).toLocaleDateString(locale.get())}</span>
{/if}
<span class="content">
<SvelteExMarkdown {md} />
</span>
{#if preview}
<a href={`/blog/${post.slug}`} class="readMore">{$t('common.blog.readMore')}</a>
{/if}
{#if post.tags && post.tags.length > 0}
<h2>{$t('common.blog.tags')}</h2>
<ul>
{#each post.tags as tag}
<li on:click={tagClick} on:keydown={tagClick}>{tag}</li>
{/each}
</ul>
{/if}
</section>
<style lang="scss">
.post {
@apply border border-gray-300 rounded-lg p-4 my-2;
h1 {
@apply text-2xl font-bold;
}
.date {
@apply text-gray-600;
}
}
.content {
@apply block my-3;
:global(h2) {
@apply text-xl font-bold;
}
}
li {
@apply text-blue-600 underline hover:text-blue-700 hover:no-underline cursor-pointer;
}
.readMore {
@apply block my-3 text-white bg-blue-600 rounded-lg p-2 w-fit hover:bg-blue-900;
}
</style>
|
#include <Servo.h>
// Arduino pin assignment
#define PIN_POTENTIOMETER 3 // Potentiometer at Pin A3
#define PIN_IR 0
#define PIN_LED 9
#define PIN_SERVO 10
#define _DUTY_MIN 553 // servo full clock-wise position (0 degree)
#define _DUTY_NEU 1476 // servo neutral position (90 degree)
#define _DUTY_MAX 2399 // servo full counter-clockwise position (180 degree)
#define DIST_MIN 100.0
#define DIST_MAX 250.0
#define _EMA_ALPHA 0.1
#define LOOP_INTERVAL 20 // Loop Interval (unit: msec)
Servo myservo;
unsigned long last_loop_time; // unit: msec
float dist_ema, dist_prev = 0;
void setup()
{
pinMode(PIN_LED, OUTPUT);
myservo.attach(PIN_SERVO);
myservo.writeMicroseconds(_DUTY_NEU);
Serial.begin(2000000);
}
void loop()
{
unsigned long time_curr = millis();
int a_value, duty;
float dist;
// wait until next event time
if (time_curr < (last_loop_time + LOOP_INTERVAL))
return;
last_loop_time += LOOP_INTERVAL;
// Remove Next line !!!
// a_value = analogRead(PIN_POTENTIOMETER);
// Read IR Sensor value !!!
a_value = analogRead(PIN_IR);
// Convert IR sensor value into distance !!!
dist = (6762.0/(a_value-9)-4.0)*10.0 - 60.0;
// we need distance range filter here !!!
if (dist >= DIST_MIN && dist <= DIST_MAX) {
digitalWrite(PIN_LED, 0);
dist_prev = dist;
} else {
digitalWrite(PIN_LED, 1);
dist = dist_prev;
}
// we need EMA filter here !!!
dist_ema = (_EMA_ALPHA*dist) + ((1-_EMA_ALPHA)*dist_ema);
// map distance into duty
duty = _DUTY_MIN + ((dist_ema - 100.0) / 150.0) * (_DUTY_MAX - _DUTY_MIN);
// duty = map(a_value, 0, 1023, _DUTY_MIN, _DUTY_MAX);
myservo.writeMicroseconds(duty);
// print IR sensor value, distnace, duty !!!
Serial.print("MIN:"); Serial.print(DIST_MIN);
Serial.print(",IR:"); Serial.print(a_value);
Serial.print(",dist:"); Serial.print(dist);
Serial.print(",ema:"); Serial.print(dist_ema);
Serial.print(",servo:"); Serial.print(duty);
Serial.print(",MAX:"); Serial.print(DIST_MAX);
Serial.println("");
// Serial.print("ADC Read: "); Serial.print(a_value);
// Serial.print(" = ");
// Serial.print((a_value / 1024.0) * 5.0);
// Serial.print(" Volt => Duty : ");
// Serial.print(duty);
// Serial.println("usec");
}
|
# For this challenge, write a smart contract that uses view, pure, and payable functions. Ensure that the functions are accessible within the contract and derived contracts as well.
pragma solidity ^0.8.0;
contract FunctionExample {
function viewFunction() public view returns (uint256) {
// Function implementation
return 42;
}
function pureFunction(uint256 a, uint256 b) public pure returns (uint256) {
// Function implementation
return a + b;
}
function payableFunction() public payable {
// Function implementation
}
}
contract DerivedContract is FunctionExample {
function derivedFunction() public view returns (uint256) {
// Function implementation
return viewFunction();
}
}
|
import { get } from "lodash";
import { MANUFACTURER } from "src/constants";
import { CategoryFilterState } from "src/state/categoryFiltersState";
import { SearchFilterState } from "src/state/searchFilterState";
import { FilterOperator, Watch } from "src/types";
import { normalizeString } from "src/utils/normalizeString";
interface FilterWatches {
watches: Watch[];
searchFilter: SearchFilterState;
categoryFilters: CategoryFilterState[];
}
export const filterWatches = ({
watches,
searchFilter,
categoryFilters,
}: FilterWatches) => {
let result = watches;
// Search filter
result = result.filter(
(watch) =>
normalizeString(MANUFACTURER[watch.manufacturer]).includes(
searchFilter.searchString
) ||
normalizeString(watch.model).includes(searchFilter.searchString) ||
normalizeString(watch.reference).includes(searchFilter.searchString)
);
// Category filters
categoryFilters
.filter((categoryFilter) => categoryFilter.activeFilterOptions.length)
.forEach((categoryFilter) => {
result = result.filter((watch) => {
const accessorResult = get(watch, categoryFilter.accessor);
console.log(accessorResult);
if (accessorResult === null) {
return false;
}
if (typeof accessorResult === "string") {
return categoryFilter.activeFilterOptions.includes(accessorResult);
} else if (typeof accessorResult === "number") {
return categoryFilter.activeFilterOptions.includes(
Math.floor(accessorResult).toString()
);
} else if (typeof accessorResult === "object") {
console.log("bingo");
return categoryFilter.operator === FilterOperator.Or
? categoryFilter.activeFilterOptions.some((item) =>
accessorResult.includes(item)
)
: categoryFilter.activeFilterOptions.every((item) =>
accessorResult.includes(item)
);
} else {
throw new Error("Unexpected accessor result");
}
});
});
return result;
};
|
import streamlit as st
import pickle
import string
import nltk
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()
def transform_text(text):
text = text.lower()
text = nltk.word_tokenize(text)
y = []
for word in text:
if word.isalnum():
y.append(word)
text = y[:]
y.clear()
for word in text:
if word not in stopwords.words('english') and word not in string.punctuation:
y.append(word)
text = y[:]
y.clear()
for word in text:
y.append(ps.stem(word))
return " ".join(y)
tfidf = pickle.load(open('vectorizer.pkl', 'rb'))
model = pickle.load(open('model.pkl', 'rb'))
st.title("SMS SPAM VS HAM CLASSIFIER")
input_sms = st.text_input("Enter your SMS")
if st.button('SPAM OR HAM'):
# 1. preprocess
transformed_sms = transform_text(input_sms)
# 2. vectorize
vector_input = tfidf.transform([transformed_sms])
# 3. predict
result = model.predict(vector_input)[0]
# 4. Display
if result == 1:
st.header("SPAM")
else:
st.header("HAM")
|
# AverageProbabilitiesMetric
*Back to [[SimpleMetrics]] page.*
## AverageProbabilitiesMetric
[[include:simple_metric_AverageProbabilitiesMetric_type]]
### General description
A metric for averaging multiple `PerResidueProbabilitiesMetrics`.
### Details
Like other `PerResidueProbabilitiesMetrics` the probabilities can be output as logits in a psi-blast style PSSM using the [[SaveProbabilitiesMetricMover]], and used as input for the [[FavorSequenceProfileMover]]. This metric alone does not require compilation with `extras=tensorflow,pytorch` but the model predictions that are typically input do. See [[Building Rosetta with TensorFlow and PyTorch]] for the compilation setup.
### Example
In this example we predict the amino acid probabilities for chain A of our protein using ProteinMPNN and ESM, average both predictions and use the average probabilities to calculate a single score for our protein.
```xml
<ROSETTASCRIPTS>
<RESIDUE_SELECTORS>
<Chain name="res" chains="A" />
</RESIDUE_SELECTORS>
<SIMPLE_METRICS>
----------------- Define models to use -----------------------------
<ProteinMPNNProbabilitiesMetric name="mpnn" residue_selector="res"/>
<PerResidueEsmProbabilitiesMetric name="esm" residue_selector="res" model="esm2_t33_650M_UR50D"/>
----------------- Average the probabilities ------------------------
<AverageProbabilitiesMetric name="avg" metrics="mpnn,esm"/>
----------------- Analyze predictions without re-calculation -------
<PseudoPerplexityMetric name="perplex" metric="avg" use_cached_data="true"/>
</SIMPLE_METRICS>
<FILTERS>
</FILTERS>
<MOVERS>
<RunSimpleMetrics name="predictions" metrics="avg"/>
<RunSimpleMetrics name="analysis" metrics="perplex"/>
</MOVERS>
<PROTOCOLS>
<Add mover_name="predictions"/>
<Add mover_name="analysis"/>
</PROTOCOLS>
</ROSETTASCRIPTS>
```
### Reference
The implementation in Rosetta is currently unpublished.
##See Also
* [[PseudoPerplexityMetric]]: Calculate the pseudo-perplexity score for any PerResidueProbabilitiesMetric
* [[RunSimpleMetrics]]: Run a set of SimpleMetrics and output data to the scorefile
* [[PerResidueEsmProbabilitiesMetric]]: Predict probabilities using the ESM language model family
* [[SimpleMetricFeatures]]: Run [[Features | Features-reporter-overview]] on a set of SimpleMetrics
* [[SimpleMetrics]]: Available SimpleMetrics
* [[Mover|Movers-RosettaScripts]]: Available Movers
* [[I want to do x]]: Guide to choosing a mover
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.