text
stringlengths
184
4.48M
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hlaw/bloc/app_cubit.dart'; import 'package:hlaw/bloc/app_state.dart'; import 'package:hlaw/screen/auth/select_login_screen.dart'; class ProfileScreen extends StatelessWidget { const ProfileScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: BlocConsumer<AppCubit,AppState>( builder: (context,state){ var cubit = AppCubit.get(context); return Padding( padding: const EdgeInsets.all(8.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ SafeArea( child: Container( width: double.infinity, padding: const EdgeInsets.all(20), child: const Center( child: Text('Profile', style: TextStyle( color: Colors.black, fontWeight: FontWeight.w700, fontSize: 35, fontFamily: 'KantumruyPro' ),), ), ), ), Row( children: [ const Expanded( child: Text('Email : ', style: TextStyle( color:Colors.black, fontSize: 20, fontFamily: 'Poppins', fontWeight: FontWeight.w800, ),), ), const SizedBox(width: 5,), Expanded( child: Text(cubit.profileModel?.email??'', style: const TextStyle( color:Colors.black, fontSize: 20, fontFamily: 'Poppins', fontWeight: FontWeight.w400, ),), ), ], ), const SizedBox(height: 20,), Row( children: [ const Expanded( child: Text('Full Name : ', style: TextStyle( color:Colors.black, fontSize: 20, fontFamily: 'Poppins', fontWeight: FontWeight.w800, ),), ), const SizedBox(width: 5,), Expanded( child: Text(cubit.profileModel?.userName??'', style: const TextStyle( color:Colors.black, fontSize: 20, fontFamily: 'Poppins', fontWeight: FontWeight.w400, ),), ), ], ), const SizedBox(height: 20,), Row( children: [ const Expanded( child: Text('Password : ', style: TextStyle( color:Colors.black, fontSize: 20, fontFamily: 'Poppins', fontWeight: FontWeight.w800, ),), ), const SizedBox(width: 5,), Expanded( child: Text(cubit.profileModel?.password??'', style: const TextStyle( color:Colors.black, fontSize: 20, fontFamily: 'Poppins', fontWeight: FontWeight.w400, ),), ), ], ), const SizedBox(height: 20,), InkWell( onTap: (){ cubit.logout(); }, child: Container( width: double.infinity, padding: const EdgeInsets.all(15), decoration: BoxDecoration( color: const Color(0XFF822929), borderRadius: BorderRadius.circular(10), ), child: const Text('Logout', style: TextStyle( color: Colors.white, fontWeight: FontWeight.w700, fontSize: 20, fontFamily: 'KantumruyPro' ),textAlign: TextAlign.center), ), ), ], ), ); }, listener: (context,state){ if(state is LogoutState){ Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context){ return const SelectLoginScreen(); }), (route) => false); } }, ) ); } }
<template> <div> <div class="point"> <h1>v-for with an array</h1> <ul> <li v-for="(item, index) in items" :key="item.id"> {{ index + 1 }}. {{ item.name }}, {{ item.price }}$ </li> </ul> </div> <div class="point"> <h1>v-for with an object</h1> <ul> <li v-for="(value, key, index) in me" :key="value.id"> {{ index + 1 }}. {{ key }}: {{ value }} </li> </ul> </div> <div class="point"> <h1>v-for with a Range</h1> <ul> <li v-for="n in 6" :key="n.id">{{ n }}</li> </ul> </div> <div class="point"> v-for用于template时,由于各模块之间的作用域是独立的,因此需要用props将v-for中的数据传入template中才能正常使用 </div> <div class="point"> <h1>Form</h1> <p>Message is: {{ msg }}</p> <input v-model="msg" placeholder="edit me" /> <div> <p style="white-space: pre-line"> My thoughts is: {{ thoughts }} </p> <textarea v-model="thoughts" name="thoughts" cols="30" rows="10" ></textarea> </div> </div> <div class="point"> <input type="checkbox" id="trueOrFalse" v-model="checked" /> <label for="trueOrFalse">{{ checked }}</label> <br /><br /> What really matters is that the `value` attribute!! <br /><br /> <input type="checkbox" id="John" value="John" v-model="checkedName" /> <label for="John">John</label> <input type="checkbox" id="Tom" value="Tom" v-model="checkedName" /> <label for="Tom">Tom</label> <input type="checkbox" id="Sarah" value="Sarah" v-model="checkedName" /> <label for="Sarah">Sarah</label> <br /><br /> CheckedNames are: {{ checkedName }} </div> <div class="point"> <h1>Radio</h1> <input type="radio" id="Banana" value="Banana" v-model="fruit" /> <label for="Banana">Banana</label> <input type="radio" id="Apple" value="Apple" v-model="fruit" /> <label for="Apple">Apple</label> <input type="radio" id="Orange" value="Orange" v-model="fruit" /> <label for="Orange">Orange</label> <br /><br /> What I chose: {{ fruit }} </div> <div class="point"> <h1>Select</h1> <select v-model="selected"> <option value="" disabled>Please select one</option> <option>Black</option> <option>Pink</option> <option>Purple</option> <option>Yellow</option> </select> </div> <div class="point"> <h1>List and options</h1> <select v-model="listSelected"> <option v-for="option in options" :value="option.value" :key="option.id" > {{ option.text }} </option> </select> <div>Selected: {{ listSelected }}</div> </div> <div class="point"> <h1>Form bindings modifiers</h1> <h2>lazy</h2> <input type="text" v-model.lazy="hello" /> <p>{{ hello }}</p> <h2>number</h2> <input type="number" v-model.number="onlyNum" /> <h2>trim</h2> <input type="text" v-model.trim="trimSpaces" /> </div> </div> </template> <script> export default { data() { return { items: [ { name: "desk", price: 200 }, { name: "chair", price: 990 }, { name: "keyboard", price: 266 }, { name: "mouse", price: 150 }, ], me: { name: "Mint", age: 22, hobbies: ["Coding", "Singing"], }, // 先挂载才能在form中正常使用 msg: "", thoughts: "", checked: true, checkedName: [], fruit: "", selected: "", listSelected: "", options: [ { text: "one", value: "A" }, { text: "two", value: "B" }, { text: "three", value: "C" }, ], hello: "hello", onlyNum: 0, trimSpaces: "Hello, I'm Mint", show: "", } }, } </script>
package com.raffa064.engine.core.api; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator.FreeTypeFontParameter; import com.raffa064.engine.core.App; import com.raffa064.engine.core.collision.Shape; import com.raffa064.engine.core.json.JSONUtils; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.badlogic.gdx.graphics.Pixmap; /* API for use and manage assets */ public class AssetsAPI extends API { private HashMap<String, Object> assets = new HashMap<>(); public AssetsAPI(App app) { super(app); } @Override public APIState createState() { return buildState(); } @Override public void useState(APIState values) { } public int amount() { return assets.size(); } public String nameOf(Object asset) { for (Map.Entry<String, Object> entry : assets.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (asset == value) { return key; } } return null; } public String names() { String names = ""; for (Map.Entry<String, Object> entry : assets.entrySet()) { String key = entry.getKey(); names += key + "\n"; } return names; } public Texture placeholder(String color) { if (color.startsWith("#")) { color = color.substring(1); } String name = "pixel-" + color; // pixel-rrggbbaa if (assets.containsKey(name)) { return (Texture) assets.get(name); } Pixmap pixmap = new Pixmap(1, 1, Pixmap.Format.RGBA8888); Color colorObj = Color.valueOf(color); pixmap.drawPixel(0, 0, Color.rgba8888(colorObj)); Texture texture = new Texture(pixmap); pixmap.dispose(); assets.put(name, texture); return texture; } public Texture placeholder(Color color) { return placeholder(color.toString()); } public Texture placeholder(String color, int width, int height, int radius) { if (color.startsWith("#")) { color = color.substring(1); } String name = "cicle-" + color + "-"+width+"x"+height+"-"+radius; // circle-rrggbbaaa-WIDTHxHEIGHT-RADIUS if (assets.containsKey(name)) { return (Texture) assets.get(name); } Pixmap pixmap = new Pixmap(width, height, Pixmap.Format.RGBA8888); Color colorObj = Color.valueOf(color); pixmap.setColor(Color.rgba8888(colorObj)); pixmap.fillCircle(width / 2, height / 2, radius); Texture texture = new Texture(pixmap); pixmap.dispose(); assets.put(name, texture); return texture; } public Texture placeholder(String color, int size) { int correction = 0; if (size % 2 == 0) { correction = 1; } return placeholder(color, size, size, size / 2 - correction); } public Texture placeholder(Color color, int width, int height, int radius) { return placeholder(color.toString(), width, height, radius); } public Texture placeholder(Color color, int size) { return placeholder(color.toString(), size); } public Texture texture(String path) { if (assets.containsKey(path)) { return (Texture) assets.get(path); } Texture texture = new Texture(app.path(path)); assets.put(path, texture); return texture; } public Shape shape(String path) { if (assets.containsKey(path)) { return (Shape) assets.get(path); } String json = readFile(path); try { JSONArray array = new JSONArray(json); float[] shape = new float[array.length()]; for (int i = 0; i < shape.length; i++) { shape[i] = array.get(i); } Shape shapeObj = new Shape(shape); assets.put(path, shape); return shapeObj; } catch (JSONException e) { return null; } } public String readFile(String path) { if (assets.containsKey(path)) { String content = (String) assets.get(path); return content; } String content = app.path(path).readString(); assets.put(path, content); return content; } public BitmapFont font(String path, String instanceName) { String name = path + "-" + instanceName; if (assets.containsKey(name)) { return (BitmapFont) assets.get(name); } try { JSONObject json = new JSONObject(readFile(path)); // Certifique-se de que 'jsonString' contenha seu JSON. FreeTypeFontGenerator generator = fontGenerator(json.getString("font")); FreeTypeFontParameter params = new FreeTypeFontParameter(); params.size = JSONUtils.getInt(json, "size", 10); params.mono = JSONUtils.getBoolean(json, "mono", false); params.color = Color.valueOf(JSONUtils.getString(json, "color", "ffffff")); params.gamma = (float) JSONUtils.getDouble(json, "gamma", 1.8); params.renderCount = JSONUtils.getInt(json, "renderCount", 2); params.borderWidth = (float) JSONUtils.getDouble(json, "borderWidth", 0); params.borderColor = Color.valueOf(JSONUtils.getString(json, "borderColor", "000000")); params.borderStraight = JSONUtils.getBoolean(json, "borderStraight", false); params.borderGamma = (float) JSONUtils.getDouble(json, "borderGamma", 1.8); params.shadowOffsetX = JSONUtils.getInt(json, "shadowOffsetX", 0); params.shadowOffsetY = JSONUtils.getInt(json, "shadowOffsetY", 0); params.shadowColor = Color.valueOf(JSONUtils.getString(json, "shadowColor", "00000010")); params.spaceX = JSONUtils.getInt(json, "spaceX", 0); params.spaceY = JSONUtils.getInt(json, "spaceY", 0); params.padTop = JSONUtils.getInt(json, "padTop", 0); params.padLeft = JSONUtils.getInt(json, "padLeft", 0); params.padBottom = JSONUtils.getInt(json, "padBottom", 0); params.padRight = JSONUtils.getInt(json, "padRight", 0); params.characters = JSONUtils.getString(json, "characters", FreeTypeFontGenerator.DEFAULT_CHARS); params.kerning = JSONUtils.getBoolean(json, "kerning", true); params.flip = JSONUtils.getBoolean(json, "flip", false); params.genMipMaps = JSONUtils.getBoolean(json, "genMipMaps", false); params.minFilter = Texture.TextureFilter.valueOf(JSONUtils.getString(json, "minFilter", "Nearest")); params.magFilter = Texture.TextureFilter.valueOf(JSONUtils.getString(json, "magFilter", "Nearest")); params.incremental = JSONUtils.getBoolean(json, "incremental", false); BitmapFont font = generator.generateFont(params); assets.put(name, font); return font; } catch (Exception e) { return null; } } // Caution! it will create a new instance each call public BitmapFont font(String path) { long randID = (long) Math.floor((Math.random() * Long.MAX_VALUE)); String instanceName = Long.toHexString(randID); return font(path, instanceName); } private FreeTypeFontGenerator fontGenerator(String path) { if (assets.containsKey(path)) { return (FreeTypeFontGenerator) assets.get(path); } FileHandle relative = app.path(path); FreeTypeFontGenerator generator = new FreeTypeFontGenerator(relative); assets.put(path, generator); return generator; } public void dispose(Object asset) { if (asset instanceof Texture) { ((Texture)asset).dispose(); } if (asset instanceof FreeTypeFontGenerator) { ((FreeTypeFontGenerator)asset).dispose(); } if (asset instanceof BitmapFont) { ((BitmapFont)asset).dispose(); } } public void disposeAll() { for (Map.Entry<String, Object> entry : assets.entrySet()) { Object asset = entry.getValue(); dispose(asset); } assets.clear(); } }
import requests from bs4 import BeautifulSoup import pandas as pd url = "https://www.fundamentus.com.br/fii_resultado.php" headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language' : 'en-US,en;q=0.5', 'DNT' : '1', 'Connection' : 'close' } data = requests.get(url, headers=headers, timeout=5).text soup = BeautifulSoup(data,"html.parser") table = soup.find('table') df = pd.DataFrame(columns=['Papel', "Segmento", "Cotação", "FFO Yield", "Dividend Yield", "P/VP", "Valor de Mercado", "Liquidez", "Qtd de imóveis", "Preço do m2", "Aluguel por m2", "Cap Rate", "Vacância Média"]) for row in table.tbody.find_all('tr'): columns = row.find_all('td') if (columns != []): Papel = columns[0].text.strip(' ') Segmento = columns[1].text.strip(' ') Cotacao = columns[2].text.strip(' ') FFOYield = columns[3].text.strip(' ') DividendYield = columns[4].text.strip(' ') P_VP = columns[5].text.strip(' ') ValordeMercado = columns[6].text.strip(' ') Liquidez = columns[7].text.strip(' ') Qtddeimoveis = columns[8].text.strip(' ') Precodom2 = columns[9].text.strip(' ') Aluguelporm2 = columns[10].text.strip(' ') CapRate = columns[11].text.strip(' ') VacanciaMedia = columns[12].text.strip(' ') df = pd.concat([df,pd.DataFrame.from_records([{'Papel': Papel, 'Segmento': Segmento, 'Cotação': Cotacao, 'FFO Yield': FFOYield, 'Dividend Yield': DividendYield, 'P/VP': P_VP, 'Valor de Mercado': ValordeMercado, 'Liquidez': Liquidez, 'Qtd de imóveis': Qtddeimoveis, 'Preço do m2': Precodom2, 'Aluguel por m2': Aluguelporm2, 'Cap Rate': CapRate, 'Vacância Média': VacanciaMedia}])],ignore_index=True) df.head(389) cont = 0 for i in df['Papel']: print(f'{cont:^3} - {i:^10}', end=' | ') cont = cont + 1 if cont % 5 == 0: print('\n', end='') fundo1 = df.loc[229] fundo2 = df.loc[368] fundo3 = df.loc[388] print() print('-='*17) print(fundo1) print('-='*17) print(fundo2) print('-='*17) print(fundo3) print('-='*17)
package chapterThree.one; import chapterOne.three.Queue; /** * Created by sunjiaxin on 2017/6/27. */ public class BinarySearchST<Key extends Comparable<Key>, Value> { private Key[] keys; private Value[] vals; private int N; public BinarySearchST(int capacity) { keys = (Key[]) new Comparable[capacity]; vals = (Value[]) new Object[capacity]; } public int size() { return N; } public boolean isEmpty() { return N == 0; } public Value get(Key key) { if (isEmpty()) { return null; } int i = rank(key); if (i < N && keys[i].compareTo(key) == 0) { return vals[i]; } else { return null; } } public int rank(Key key) { int lo = 0, hi = N - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; int cmp = key.compareTo(keys[mid]); if (cmp < 0) { hi = mid - 1; } else if (cmp > 0) { lo = mid + 1; } else { return mid; } } return lo; } public void put(Key key, Value value) { // 查找键,找到则更新值,否则创建新的元素 int i = rank(key); if (i < N && keys[i].compareTo(key) == 0) { vals[i] = value; return; } for (int j = N; j > i; j++) { keys[j] = keys[j - 1]; vals[j] = vals[j - 1]; } keys[i] = key; vals[i] = value; N++; } public Key min() { if (isEmpty()) { return null; } return keys[0]; } public Key max() { if (isEmpty()) { return null; } return keys[N - 1]; } public Key select(int k) { if (k < 0 || k >= N) { return null; } return keys[k]; } public Key ceiling(Key key) { int i = rank(key); if (i == N) { return null; } return keys[i]; } public Key floor(Key key) { int i = rank(key); if (i < N && key.compareTo(keys[i]) == 0) { return keys[i]; } if (i == 0) { return null; } return keys[i - 1]; } public void delete(Key key) { if (isEmpty()) { return; } int i = rank(key); if (i == N || key.compareTo(keys[i]) != 0) { return; } // 删除该键 for (int j = i; j < N - 1; j++) { keys[j] = keys[j + 1]; vals[j] = vals[j + 1]; } N--; keys[N] = null; vals[N] = null; } public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<>(); int loIndex = rank(lo); int hiIndex = rank(hi); for (int i = loIndex; i < hiIndex; i++) { queue.enqueue(keys[i]); } if (hi.equals(keys[hiIndex])) { queue.enqueue(hi); } return queue; } }
import 'dart:io' as io; import 'package:android_intent_plus/android_intent.dart'; import 'package:extended_image/extended_image.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:jhentai/src/extension/widget_extension.dart'; import 'package:jhentai/src/network/eh_cache_interceptor.dart'; import 'package:jhentai/src/setting/advanced_setting.dart'; import 'package:jhentai/src/setting/path_setting.dart'; import 'package:jhentai/src/utils/log.dart'; import 'package:jhentai/src/utils/toast_util.dart'; import 'package:path/path.dart'; import '../../../config/ui_config.dart'; import '../../../routes/routes.dart'; import '../../../utils/route_util.dart'; class SettingAdvancedPage extends StatefulWidget { const SettingAdvancedPage({Key? key}) : super(key: key); @override _SettingAdvancedPageState createState() => _SettingAdvancedPageState(); } class _SettingAdvancedPageState extends State<SettingAdvancedPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(centerTitle: true, title: Text('advancedSetting'.tr)), body: Obx( () => ListView( padding: const EdgeInsets.only(top: 16), children: [ _buildEnableLogging(), if (AdvancedSetting.enableLogging.isTrue) _buildRecordAllLogs().fadeIn(), _buildOpenLogs(), _buildClearLogs(context), _buildClearImageCache(context), _buildClearNetworkCache(), if (GetPlatform.isDesktop) _buildSuperResolution(), _buildCheckUpdate(), _buildCheckClipboard(), if (GetPlatform.isAndroid) _buildVerifyAppLinks(), _buildInNoImageMode(), ], ).withListTileTheme(context), ), ); } Widget _buildEnableLogging() { return ListTile( title: Text('enableLogging'.tr), subtitle: Text('needRestart'.tr), trailing: Switch(value: AdvancedSetting.enableLogging.value, onChanged: AdvancedSetting.saveEnableLogging), ); } Widget _buildRecordAllLogs() { return ListTile( title: Text('enableVerboseLogging'.tr), subtitle: Text('needRestart'.tr), trailing: Switch(value: AdvancedSetting.enableVerboseLogging.value, onChanged: AdvancedSetting.saveEnableVerboseLogging), ); } Widget _buildOpenLogs() { return ListTile( title: Text('openLog'.tr), trailing: const Icon(Icons.keyboard_arrow_right).marginOnly(right: 4), onTap: () => toRoute(Routes.logList), ); } Widget _buildClearLogs(BuildContext context) { return ListTile( title: Text('clearLogs'.tr), subtitle: Text('longPress2Clear'.tr), trailing: Text(Log.getSize(), style: TextStyle(color: UIConfig.resumePauseButtonColor(context), fontWeight: FontWeight.w500)).marginOnly(right: 8), onLongPress: () { Log.clear(); toast('clearSuccess'.tr, isCenter: false); Future.delayed( const Duration(milliseconds: 600), () => setState(() {}), ); }, ); } Widget _buildClearImageCache(BuildContext context) { return ListTile( title: Text('clearImagesCache'.tr), subtitle: Text('longPress2Clear'.tr), trailing: Text(_getImagesCacheSize(), style: TextStyle(color: UIConfig.resumePauseButtonColor(context), fontWeight: FontWeight.w500)).marginOnly(right: 8), onLongPress: () async { await clearDiskCachedImages(); setState(() { toast('clearSuccess'.tr, isCenter: false); }); }, ); } Widget _buildClearNetworkCache() { return ListTile( title: Text('clearPageCache'.tr), subtitle: Text('longPress2Clear'.tr), onLongPress: () async { await Get.find<EHCacheInterceptor>().removeAllCache(); toast('clearSuccess'.tr, isCenter: false); }, ); } Widget _buildSuperResolution() { return ListTile( title: Text('superResolution'.tr), trailing: const Icon(Icons.keyboard_arrow_right).marginOnly(right: 4), onTap: () => toRoute(Routes.superResolution), ); } Widget _buildCheckUpdate() { return ListTile( title: Text('checkUpdateAfterLaunchingApp'.tr), trailing: Switch(value: AdvancedSetting.enableCheckUpdate.value, onChanged: AdvancedSetting.saveEnableCheckUpdate), ); } Widget _buildCheckClipboard() { return ListTile( title: Text('checkClipboard'.tr), trailing: Switch(value: AdvancedSetting.enableCheckClipboard.value, onChanged: AdvancedSetting.saveEnableCheckClipboard), ); } Widget _buildVerifyAppLinks() { return ListTile( title: Text('verityAppLinks4Android12'.tr), subtitle: Text('verityAppLinks4Android12Hint'.tr), trailing: const Icon(Icons.keyboard_arrow_right).marginOnly(right: 4), onTap: () async { try { await const AndroidIntent( action: 'android.settings.APP_OPEN_BY_DEFAULT_SETTINGS', data: 'package:top.jtmonster.jhentai', ).launch(); } on Exception catch (e) { Log.error(e); Log.upload(e); toast('error'.tr); } }, ); } Widget _buildInNoImageMode(){ return ListTile( title: Text('noImageMode'.tr), trailing: Switch(value: AdvancedSetting.inNoImageMode.value, onChanged: AdvancedSetting.saveInNoImageMode), ); } String _getImagesCacheSize() { try { io.Directory cacheImagesDirectory = io.Directory(join(PathSetting.tempDir.path, cacheImageFolderName)); if (!cacheImagesDirectory.existsSync()) { return '0KB'; } int totalBytes = cacheImagesDirectory.listSync().fold<int>(0, (previousValue, element) => previousValue += (element as io.File).lengthSync()); return (totalBytes / 1024 / 1024).toStringAsFixed(2) + 'MB'; } on Exception catch (e) { Log.upload(e); return '0KB'; } } }
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Refs In String Form</title> </head> <body> <div id="test"></div> <script src="../js/react.development.js"></script> <script src="../js/react-dom.development.js"></script> <script src="../js/babel.min.js"></script> <script type="text/babel"> class StringRefs extends React.Component { render() { return ( <div> <input type="text" ref="myInput" />&nbsp; <button onClick={this.show1}>Focus the text input</button>&nbsp; <input type="text" ref="myInput2" onBlur={this.show2} /> </div> ) } show1 = () => { alert(this.refs.myInput.value) } show2 = () => { alert(this.refs.myInput2.value) } } ReactDOM.render(<StringRefs />, document.getElementById('test')) </script> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>书城首页</title> <%@include file="/include/base.jsp" %> </head> <script type="text/javascript"> $(function(){ $(".addBtn").click(function(){ var bookid = $(this).attr("updateId"); $.ajax({ type : "POST", url : "client/CartServlet?method=AjaxaddCart&id="+bookid, dataType : "JSON", success : function(data){ $("#tiptotalCount").text(data.totalCount); $("#tiptitle").css("color", "blue"); $("#tiptitle").text("你刚刚将【"+data.title+"】加入了购物车"); } }); }); }); </script> <body> <div id="header"> <img class="logo_img" alt="" src="static/img/logo.gif" > <span class="wel_word">网上书城</span> <%@include file="/include/user-info.jsp" %> </div> <div id="main"> <div id="book"> <div class="book_cond"> <form action="client/BookClientServlet?method=pageByPrice" method="post"> 价格:<input id="min" type="text" name="min" value="${param.min }"> 元 - <input id="max" type="text" name="max" value="${param.max }"> 元 <input name="pn" type="hidden" value="1" /> <input type="submit" value="查询" /> </form> </div> <div style="text-align: center"> 您的购物车中有<span id="tiptotalCount"><c:out value="${cart.totalCount }" default="0"></c:out></span>件商品 <div> <span id="tiptitle">&nbsp;</span> </div> </div> <c:forEach items="${page.pageData }" var="book"> <div class="b_list"> <div class="img_div"> <img class="book_img" alt="" src="${book.imgPath }" /> </div> <div class="book_info"> <div class="book_name"> <span class="sp1">书名:</span> <span class="sp2">${book.title }</span> </div> <div class="book_author"> <span class="sp1">作者:</span> <span class="sp2">${book.author }</span> </div> <div class="book_price"> <span class="sp1">价格:</span> <span class="sp2">${book.price }</span> </div> <div class="book_sales"> <span class="sp1">销量:</span> <span class="sp2">${book.sales }</span> </div> <div class="book_amount"> <span class="sp1">库存:</span> <span class="sp2">${book.stock }</span> </div> <div class="book_add"> <button class="addBtn" updateId="${book.id }">加入购物车</button> </div> </div> </div> </c:forEach> </div> <%@include file="/include/page.jsp" %> </div> <div id="bottom"> <span> 尚硅谷书城.Copyright &copy;2015 </span> </div> </body> </html>
package kodlama.io.rentACar.business.concretes; import kodlama.io.rentACar.business.abstracts.CityService; import kodlama.io.rentACar.business.requests.city.CreateCityRequest; import kodlama.io.rentACar.business.requests.city.UpdateCityRequest; import kodlama.io.rentACar.business.dto.city.GetAllCityResponse; import kodlama.io.rentACar.core.utilities.mappers.ModelMapperService; import kodlama.io.rentACar.dataAccess.abstracts.CityRepository; import kodlama.io.rentACar.entities.concretes.City; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.PathVariable; import java.util.List; import java.util.stream.Collectors; @Service @AllArgsConstructor public class CityManager implements CityService { private CityRepository cityRepository; private ModelMapperService modelMapperService; @Override public List<GetAllCityResponse> getAll(){ List<City> cities = this.cityRepository.findAll(); List<GetAllCityResponse> cityResponse= cities.stream() .map(city -> this.modelMapperService.forResponse() .map(city,GetAllCityResponse.class)).collect(Collectors.toList()); return cityResponse; } @Override public void add(CreateCityRequest createCityRequest){ City city = this.modelMapperService.forRequest().map(createCityRequest, City.class); this.cityRepository.save(city); } @Override public void delete(@PathVariable int id) { this.cityRepository.deleteById(id); } @Override public void update(UpdateCityRequest updateCityRequest) { City city = this.modelMapperService.forRequest().map(updateCityRequest, City.class); this.cityRepository.save(city); } }
/* GUICode.java * * This class draw the code memory representation in a window with three columns. * (c) 2006 Alessandro Nicolosi, Massimo Trubia (FPU modifications) * * This file is part of the EduMIPS64 project, and is released under the GNU * General Public License. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.edumips64.ui; import org.edumips64.Main; import org.edumips64.core.*; import org.edumips64.core.is.Instruction; import org.edumips64.utils.*; import java.awt.*; import java.util.*; import javax.swing.*; import javax.swing.table.*; /** * This class draws the code memory representation in a window with five columns. */ public class GUICode extends GUIComponent { CodePanel codePanel; String memoryAddress[] = new String[CPU.CODELIMIT]; private static int ifIndex, idIndex, exIndex, memIndex, wbIndex, A1Index, A2Index, A3Index, A4Index, M1Index, M2Index, M3Index, M4Index, M5Index, M6Index, M7Index, DIVIndex; public GUICode() { super(); codePanel = new CodePanel(); } public void setContainer(Container co) { super.setContainer(co); cont.add(codePanel); } public void updateLanguageStrings() { GUIFrontend.updateColumnHeaderNames(codePanel.theTable); } public void update() { //codePanel.scrollTable.getViewport().setViewPosition(new Point(0,position+15)); TableColumn column0 = codePanel.theTable.getColumnModel().getColumn(0); column0.setCellRenderer(new MyTableCellRenderer()); TableColumn column1 = codePanel.theTable.getColumnModel().getColumn(1); column1.setCellRenderer(new MyTableCellRenderer()); TableColumn column2 = codePanel.theTable.getColumnModel().getColumn(2); column2.setCellRenderer(new MyTableCellRenderer()); TableColumn column3 = codePanel.theTable.getColumnModel().getColumn(3); column3.setCellRenderer(new MyTableCellRenderer()); TableColumn column4 = codePanel.theTable.getColumnModel().getColumn(4); column4.setCellRenderer(new MyTableCellRenderer()); ifIndex = cpu.getMemory().getInstructionIndex(cpu.getPipeline().get(CPU.PipeStatus.IF)); idIndex = cpu.getMemory().getInstructionIndex(cpu.getPipeline().get(CPU.PipeStatus.ID)); exIndex = cpu.getMemory().getInstructionIndex(cpu.getPipeline().get(CPU.PipeStatus.EX)); memIndex = cpu.getMemory().getInstructionIndex(cpu.getPipeline().get(CPU.PipeStatus.MEM)); wbIndex = cpu.getMemory().getInstructionIndex(cpu.getPipeline().get(CPU.PipeStatus.WB)); A1Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("ADDER", 1)); A2Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("ADDER", 2)); A3Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("ADDER", 3)); A4Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("ADDER", 4)); M1Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("MULTIPLIER", 1)); M2Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("MULTIPLIER", 2)); M3Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("MULTIPLIER", 3)); M4Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("MULTIPLIER", 4)); M5Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("MULTIPLIER", 5)); M6Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("MULTIPLIER", 6)); M7Index = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("MULTIPLIER", 7)); DIVIndex = cpu.getMemory().getInstructionIndex(cpu.getInstructionByFuncUnit("DIVIDER", 0)); } public void draw() { cont.repaint(); // I can get the table because it has package visibility. // This row makes the IF row always visible. codePanel.theTable.scrollRectToVisible(codePanel.theTable.getCellRect(ifIndex, 0, true)); } class CodePanel extends JPanel { JTable theTable; JScrollPane scrollTable; MyTableModel tableModel; public CodePanel() { super(); setLayout(new BorderLayout()); setBackground(Color.WHITE); tableModel = new MyTableModel(memoryAddress); theTable = new JTable(tableModel); theTable.setCellSelectionEnabled(false); theTable.setFocusable(false); theTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); theTable.setShowGrid(false); theTable.getColumnModel().getColumn(0).setPreferredWidth(60); theTable.getColumnModel().getColumn(1).setPreferredWidth(130); theTable.getColumnModel().getColumn(2).setPreferredWidth(80); theTable.getColumnModel().getColumn(3).setPreferredWidth(200); theTable.getColumnModel().getColumn(4).setPreferredWidth(200); scrollTable = new JScrollPane(theTable); add(scrollTable, BorderLayout.CENTER); } class MyTableModel extends AbstractTableModel { private String[] columnLocaleStrings = {"ADDRESS", "HEXREPR", "LABEL", "INSTRUCTION", "COMMENT"}; private Class[] columnClasses = {String.class, String.class, String.class, String.class, String.class}; private String memoryAddress[]; public MyTableModel(String[] memoryAddress) { this.memoryAddress = memoryAddress; } public int getColumnCount() { return columnLocaleStrings.length; } public int getRowCount() { return memoryAddress.length; } public String getColumnName(int col) { return CurrentLocale.getString(columnLocaleStrings[col]); } public Object getValueAt(int row, int col) { switch (col) { case 0: try { return Converter.binToHex(Converter.positiveIntToBin(16, row++ * 4)); } catch (IrregularStringOfBitsException ex) { ex.printStackTrace(); } break; case 1: try { return cpu.getMemory().getInstruction(row * 4).getRepr().getHexString(); } catch (IrregularStringOfBitsException ex) { ex.printStackTrace(); } break; case 2: String label = cpu.getMemory().getInstruction(row * 4).getLabel(); return label; case 3: return cpu.getMemory().getInstruction(row * 4).getFullName(); case 4: if (cpu.getMemory().getInstruction(row * 4).getComment() != null) { return ";" + cpu.getMemory().getInstruction(row * 4).getComment(); } else { return ""; } default: return new Object(); } return new Object(); } @SuppressWarnings("rawtypes") public Class getColumnClass(int c) { return columnClasses[c]; } } } class MyTableCellRenderer implements TableCellRenderer { private JLabel label; public MyTableCellRenderer() { } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { codePanel.tableModel = (CodePanel.MyTableModel) table.getModel(); label = new JLabel(); Font f = new Font("Monospaced", Font.PLAIN, 12); int rowTable = row; if (column == 0) { try { label.setText(Converter.binToHex(Converter.positiveIntToBin(16, row++ * 4))); label.setFont(f); } catch (IrregularStringOfBitsException e) { e.printStackTrace(); } } if (column == 1) { String repr = (String) value; repr = (String) codePanel.tableModel.getValueAt(row, column); label.setText(repr); label.setFont(f); } if (column == 2) { label.setText((String) codePanel.tableModel.getValueAt(row, column)); label.setFont(f); } if (column == 3) { String iName = (String) value; iName = (String) codePanel.tableModel.getValueAt(row, column); label.setText(iName); label.setFont(f); } if (column == 4) { String iComment = (String) value; iComment = (String) codePanel.tableModel.getValueAt(row, column); label.setText(iComment); label.setFont(f); } if (rowTable == ifIndex) { label.setOpaque(true); label.setBackground(Config.getColor("IFColor")); } if (rowTable == idIndex) { label.setOpaque(true); label.setBackground(Config.getColor("IDColor")); } if (rowTable == exIndex) { label.setOpaque(true); label.setBackground(Config.getColor("EXColor")); } if (rowTable == memIndex) { label.setOpaque(true); label.setBackground(Config.getColor("MEMColor")); } if (rowTable == wbIndex) { label.setOpaque(true); label.setBackground(Config.getColor("WBColor")); } if (rowTable == M1Index || rowTable == M2Index || rowTable == M3Index || rowTable == M4Index || rowTable == M5Index || rowTable == M6Index || rowTable == M7Index) { label.setOpaque(true); label.setBackground(Config.getColor("FPMultiplierColor")); } if (rowTable == A1Index || rowTable == A2Index || rowTable == A3Index || rowTable == A4Index) { label.setOpaque(true); label.setBackground(Config.getColor("FPAdderColor")); } if (rowTable == DIVIndex) { label.setOpaque(true); label.setBackground(Config.getColor("FPDividerColor")); } return label; } } }
import { JSX } from 'react'; type Theme = 'primary' | 'secondary' | 'accent' | 'info' | 'success' | 'warning' | 'error' | 'ghost'; type Variant = 'bordered'; type Size = 'lg' | 'md' | 'sm' | 'xs'; export type InputProps = { theme?: Theme; size?: Size; variant?: Variant; placeholder?: string; labelTopLeft?: string; labelTopRight?: string; labelBottomLeft?: string; labelBottomRight?: string; } export function Input({ theme, size, variant, placeholder, labelTopLeft ,labelTopRight ,labelBottomLeft ,labelBottomRight }: InputProps): JSX.Element { let themeModifier: string = ''; if (theme) { switch (theme) { case 'accent': themeModifier = 'input-accent'; break; case 'primary': themeModifier = 'input-primary'; break; case 'secondary': themeModifier = 'input-secondary'; break; case 'accent': themeModifier = 'input-accent'; break; case 'info': themeModifier = 'input-info'; break; case 'success': themeModifier = 'input-success'; break; case 'warning': themeModifier = 'input-warning'; break; case 'error': themeModifier = 'input-error'; break; case 'ghost': themeModifier = 'input-error'; break; default: throw new Error('unreachable - did you miss to add a theme?'); } } let sizeModifier: string = ''; if (size) { switch (size) { case 'lg': sizeModifier = 'input-lg'; break; case 'md': sizeModifier = 'input-md'; break; case 'sm': sizeModifier = 'input-sm'; break; case 'xs': sizeModifier = 'input-xs'; break; default: throw new Error('unreachable - did you miss to add a size?'); } } let variantModifier: string = ''; if (variant) { switch (variant) { case 'bordered': variantModifier = 'input-bordered'; break; default: throw new Error('unreachable - did you miss to add a variant?'); } } if (!labelTopLeft && !labelTopRight && !labelBottomLeft && !labelBottomRight) { return ( <input type="text" placeholder={placeholder} className={`input ${themeModifier} ${sizeModifier} ${variantModifier}`} /> ); } return ( <div className="form-control"> <label className="label"> {labelTopLeft && <span className="label-text">{labelTopLeft}</span>} {labelTopRight && <span className="label-text-alt">{labelTopRight}</span>} </label> <input type="text" placeholder={placeholder} className={`input ${themeModifier} ${sizeModifier} ${variantModifier}`} /> <label className="label"> {labelBottomLeft && <span className="label-text-alt">{labelBottomLeft}</span>} {labelBottomRight && <span className="label-text-alt">{labelBottomRight}</span>} </label> </div> ) }
#### 1. 注意事项 - 为防止命名冲突,可以采取立即执行函数的写法将每个图表分隔开,注意每个函数后面都要加个分号 - tooltip 并非是 canvas 绘制,而是一个 div ,所以写样式时尽量避免直接使用 div ,否则可能导致大小异常 - yAxis 的 axisLine 好像默认是隐藏的,所以需要加上 `show: true` 以显示y轴轴线 - formatter: "{c}%", // {c} 会自动解析为 data 中的数据;{a}是系列名,{b}是数据名,{d}是所占比例 - yAxisIndex: 1, //使用的y轴的index;默认为0(即左边的第一个y轴),存在多个y轴时必须设置,否则会存在y轴重叠的问题 - myChart.clear() // 清理缓存,当需要根据用户的选择动态显示不同的图表时,需要对图表的缓存进行清理 - 横坐标是时间格式的情况下,横纵坐标数据必须全放series中,使其一一对应,不能拆开写 #### 2. 重点知识 ##### 2.1. 图表自适应 写在 myChart.setOption() 的后面,可以使图表跟随浏览器或盒子的大小改变而自适应大小 ```js window.addEventListener("resize", function(){ myChart.resize() }) ``` 有时候初始化时的样式也有问题时,可通过定时器在页面渲染完成后重新渲染图表 ```js setTimeout(() => { myChart.resize(); }, 100); ``` #### 3. 颜色 ##### 3.1. 两个好看的渐变色 ```js new echarts.graphic.LinearGradient(0, 0, 1, 0, //0010代表的是横向渐变,0001为纵向 [ { offset: 0, color: "rgb(57,89,255,1)", }, { offset: 1, color: "rgb(46,200,207,1)", }, ]); new echarts.graphic.LinearGradient(0, 0, 1, 0, [ { offset: 0, color: "#EB3B5A", }, { offset: 1, color: "#FE9C5A", }, ]) ``` ##### 3.2. 基础颜色 ``` 0: #4992ff 1: #7cffb2 2: #fddd60 3: #ff6e76 4: #58d9f9 5: #05c091 6: #ff8a45 7: #8d48e3 8: #dd79ff ```
/* Sample code for vulnerable type: SQL Injection CWE : CWE-89 Description : Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') */ package main import ( "database/sql" "fmt" "net/http" ) func handler(db *sql.DB, w http.ResponseWriter, req *http.Request) { category := req.URL.Query().Get("category") //source if category == "" { http.Error(w, "Category not provided", http.StatusBadRequest) return } q := fmt.Sprintf("SELECT ITEM, PRICE FROM PRODUCT WHERE ITEM_CATEGORY='%s' ORDER BY PRICE", category) rows, err := db.Query(q) //sink if err != nil { http.Error(w, "Failed to execute query", http.StatusInternalServerError) return } defer rows.Close() // Process the rows (not shown in this example) // Send success response w.WriteHeader(http.StatusOK) w.Write([]byte("Query executed successfully")) } func main() { // Create a new HTTP server http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { // Pass the database connection to the handler handler(nil, w, req) }) // Start the HTTP server and listen for incoming requests on port 8080 http.ListenAndServe(":8080", nil) }
package cn.test.basis.creat02; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class HowToCreateThread { private static class MyThread extends Thread { @Override public void run() { System.out.println("Hello MyThread"); } } private static class MyRun implements Runnable { @Override public void run() { System.out.println("Hello MyRun!!"); } } public static void main(String[] args) { new MyThread().start(); new Thread(new MyRun()).start(); new Thread(() -> { System.out.println("Hello Lambda!"); }).start(); ExecutorService service = Executors.newCachedThreadPool(); service.submit(() -> { System.out.println("Executors"); }); } }
package me.varoa.ugh.core.data.remote.json import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class UserJson( val id: Long, @SerialName("login") val username: String, val name: String? = "", @SerialName("avatar_url") val avatar: String, @SerialName("followers") val followersCount: Int = 0, @SerialName("following") val followingCount: Int = 0 )
import 'dart:developer'; import 'dart:io'; import 'package:alma/core/api_provider.dart'; import 'package:alma/core/constants.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:get/get.dart'; import 'package:image_picker/image_picker.dart'; import 'package:intl/intl.dart'; class PostController extends GetxController { final ApiProvider api = Get.find(); final TextEditingController companyName = TextEditingController(); final TextEditingController eventName = TextEditingController(); final TextEditingController role = TextEditingController(); final TextEditingController description = TextEditingController(); final TextEditingController endDate = TextEditingController(); final TextEditingController skillsRequired = TextEditingController(); final TextEditingController venue = TextEditingController(); final TextEditingController duration = TextEditingController(); final TextEditingController eventLink = TextEditingController(); var imageUrl = ''.obs; var isImageSelected = false.obs; var selectedEventType = "J".obs; var isImageUploaded = false.obs; var eventDate = ''.obs; var chosenDate = DateTime.now().obs; var lastDayToApply = ''.obs; var isPosting = false.obs; var selectedDate = ''.obs; var postingText = 'Post'.obs; Rx<File> selectedImage = Rx<File>(File('')); //functions to perform each tasks void addCollegeAndOtherEvent() async { if (eventDate.value == '' || lastDayToApply.value == '' || eventName.text.isEmpty) { Get.snackbar("Failed", "Please fill event date and name"); return; } isPosting(true); postingText("Posting..."); if (isImageSelected.value) { await uploadImage(); } Map data = { "event_name": eventName.text, "event_description": description.text, "venue": venue.text, "event_date": eventDate.value, "img_url": imageUrl.value, "event_type": selectedEventType.value, "last_date_to_apply": lastDayToApply.value, "duration": duration.text, "event_link": eventLink.text }; log("college or other data is $data"); try { final response = await api.postApi('/events/add', data); log("status code is ${response.statusCode}"); log("response is ${response.body}"); if (response.statusCode == 201) { Get.snackbar( "Success", "Event added successfully", ); clearAll(); isPosting(false); postingText("Done"); await Future.delayed(const Duration(milliseconds: 1000)); Get.until((route) => Get.currentRoute == '/'); } else { Get.snackbar("Failed", "Failed to add event "); } } catch (e) { postingText("Try Again"); log("error is $e"); } finally { isPosting(false); postingText("Post"); } } void addInternshipEvent() async { if (eventDate.value == '' || lastDayToApply.value == '' || eventName.text.isEmpty) { Get.snackbar("Failed", "Please fill event date and name"); return; } else { List<String> skills = skillsRequired.text.split(','); isPosting(true); postingText("Posting..."); if (isImageSelected.value) { await uploadImage(); } Map jobdata = { "event_name": eventName.text, "company_name": companyName.text, "event_description": description.text, "skills_required": skills, "event_date": eventDate.value, "img_url": imageUrl.value, "event_type": selectedEventType.value, "last_date_to_apply": lastDayToApply.value, "duration": duration.text, "event_link": eventLink.text }; log("internship data is $jobdata"); try { final response = await api.postApi('/events/add', jobdata); log("status code is ${response.statusCode}"); log("response is ${response.body}"); if (response.statusCode == 201) { Get.snackbar( "Success", "Internship added successfully", ); clearAll(); isPosting(false); postingText("Done"); await Future.delayed(const Duration(milliseconds: 1000)); Get.until((route) => Get.currentRoute == '/'); } else { Get.snackbar("Failed", "Failed to add internship"); } } catch (e) { log("error is $e"); } finally { isPosting(false); postingText("Post"); } } } void addJobEvent() async { if (lastDayToApply.value == '' || eventName.text.isEmpty) { Get.snackbar("Failed", "Please fill the dates and name"); return; } List<String> skills = skillsRequired.text.split(','); isPosting(true); postingText("Posting..."); if (isImageSelected.value) { await uploadImage(); } Map jobdata = { "event_name": eventName.text, "company_name": companyName.text, "role": role.text, "event_description": description.text, "skills_required": skills, "img_url": imageUrl.value, "event_type": selectedEventType.value, "duration": duration.text, "last_date_to_apply": lastDayToApply.value, "event_link": eventLink.text }; log("job data is $jobdata"); try { final response = await api.postApi('/events/add', jobdata); log("status code is ${response.statusCode}"); log("response is ${response.body}"); if (response.statusCode == 201) { Get.snackbar( "Success", "Job added successfully", snackPosition: SnackPosition.TOP, ); clearAll(); isPosting(false); postingText("Done"); await Future.delayed(const Duration(milliseconds: 1000)); Get.until((route) => Get.currentRoute == '/'); } else { Get.snackbar("Failed", "Failed to add Job"); } } catch (e) { log("error is $e"); } finally { isPosting(false); postingText("Post"); } } void pickImage() async { final ImagePicker picker = ImagePicker(); try { final XFile? image = await picker.pickImage(source: ImageSource.gallery, imageQuality: 60); if (image == null) return; selectedImage.value = File(image.path); isImageSelected(true); if (kDebugMode) { log("image location is ${selectedImage.value}"); } } on PlatformException catch (e) { Get.snackbar("Failed", "failed to pick image $e"); } } void removeSelectedImage() { selectedImage.value = File(''); isImageSelected(false); } void goToEventDetailCompletion() { switch (selectedEventType.value) { case 'J': Get.toNamed('/job-description'); break; case 'I': Get.toNamed('/internship-description'); break; case 'O': Get.toNamed('/otherEventdes-description'); break; case 'C': Get.toNamed('/collageEventsDesc'); break; } } Future<void> uploadImage() async { try { final storageRef = FirebaseStorage.instance.ref(); final profileRef = storageRef .child('events/${eventName.text + DateTime.now().toString()}'); await profileRef.putFile( selectedImage.value, ); imageUrl.value = await profileRef.getDownloadURL(); log(imageUrl.value); } catch (e) { log("error in uploading img ${e}"); } } Future<void> pickDate(ctx, h) async { await showCupertinoModalPopup( context: ctx, builder: (_) => Container( decoration: BoxDecoration( color: Constants.cardColor(), borderRadius: const BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20))), height: h * 0.5, child: SizedBox( child: CupertinoDatePicker( initialDateTime: DateTime.now(), mode: CupertinoDatePickerMode.date, maximumYear: 2055, minimumYear: 2021, dateOrder: DatePickerDateOrder.ymd, onDateTimeChanged: (val) { print(val); selectedDate.value = DateFormat('yyyy-MM-dd').format(val); }, ), ), )); } void clearAll() { clearControllers(); removeSelectedImage(); } void clearControllers() { companyName.clear(); eventName.clear(); role.clear(); description.clear(); endDate.clear(); skillsRequired.clear(); venue.clear(); duration.clear(); eventLink.clear(); lastDayToApply.value = ''; selectedDate.value = ''; eventDate.value = ''; imageUrl.value = ''; isImageSelected(false); } }
import React from 'react'; import Document, { Html, Head, Main, NextScript } from 'next/document'; class MyDocument extends Document { static async getInitialProps(ctx: any) { const initialProps = await Document.getInitialProps(ctx); return { ...initialProps, styles: React.Children.toArray([initialProps.styles]), }; } render() { return ( <Html lang="en"> <Head> <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;
"use client"; import { lessons } from "@prisma/client"; import dynamic from "next/dynamic"; import Link from "next/link"; import { useState } from "react"; import ActionsLessons from "./ActionsLessons"; const Time = dynamic(() => import("./GeTTime"), { ssr: false, }); type Props = { lesson: lessons[] }; function Lessons({ lesson }: Props) { const [page, setPage] = useState(1); return ( <div className="flex flex-col w-full gap-3 items-center"> <div className="overflow-x-auto w-full"> <table className="table table-compact w-full"> {/* head */} <thead> <tr> <th>Title</th> <th>Recoding</th> <th>Notes</th> <th>HomeWork</th> <th>Date </th> <th>Options</th> </tr> </thead> <tbody> {lesson.map((lesson, index) => { if (index >= (page - 1) * 10 && index < page * 10) { return ( <tr key={lesson.id}> <td>{lesson.lessonTitle}</td> <td> <Link className="link link-hover" href={`${lesson.recording}`} > Recording </Link> </td> <td>{lesson.notes}</td> <td>{lesson.homework}</td> <Time time={lesson.time} /> <td className="flex justify-center items-center"> <ActionsLessons id={lesson.id} />{" "} </td> </tr> ); } else { return null; } })} </tbody> </table> </div> <div className="btn-group "> <button onClick={() => { setPage(page === 1 ? page : page - 1); }} className="btn" > « </button> <button className="btn">Page {page}</button> <button onClick={() => { setPage(lesson.length / 10 > page ? page + 1 : page); }} className="btn" > » </button> </div> </div> ); } export default Lessons;
import React, { createContext, FC, useState } from 'react'; import { IApartment } from '../interfaces/apartment'; // Define Context Type interface IApartmentContext { apartment: undefined | IApartment, setApartment: (apartment: undefined | IApartment) => void } // Provider const ApartmentContext = createContext<IApartmentContext>({} as IApartmentContext); export const ApartmentProvider: FC = ({ children }) => { const [apartment, setApartment] = useState<IApartment | undefined>(undefined); return ( // eslint-disable-next-line react/jsx-no-constructed-context-values <ApartmentContext.Provider value={{ apartment, setApartment }}> {children} </ApartmentContext.Provider> ); }; // Export to app export default ApartmentContext;
package com.tpv.yongdayang.wifiap.util; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiConfiguration.KeyMgmt; import android.net.wifi.WifiManager; import android.os.Handler; import android.util.Log; /* * Wifi AP功能很多方法和action被隐藏起来 * */ public class WifiAPUtil { private static final String TAG = "WifiAPUtil"; public final static boolean DEBUG = true; public static final int MESSAGE_AP_STATE_ENABLED = 1; public static final int MESSAGE_AP_STATE_FAILED = 2; //默认wifi秘密 private static final String DEFAULT_AP_PASSWORD = "12345678"; private static WifiAPUtil sInstance; private static Handler mHandler; private static Context mContext; private WifiManager mWifiManager; //监听wifi热点的状态变化 public static final String WIFI_AP_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_AP_STATE_CHANGED"; //该Action被隐藏 public static final String EXTRA_WIFI_AP_STATE = "wifi_state"; public static int WIFI_AP_STATE_DISABLING = 10; public static int WIFI_AP_STATE_DISABLED = 11; public static int WIFI_AP_STATE_ENABLING = 12; public static int WIFI_AP_STATE_ENABLED = 13; public static int WIFI_AP_STATE_FAILED = 14; public enum WifiSecurityType { WIFICIPHER_NOPASS, WIFICIPHER_WPA, WIFICIPHER_WEP, WIFICIPHER_INVALID, WIFICIPHER_WPA2 } private WifiAPUtil(Context context) { if(DEBUG) Log.d(TAG,"WifiAPUtils construct"); mContext = context; mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); //注册wifi AP状态广播接收器 IntentFilter filter = new IntentFilter(); filter.addAction(WIFI_AP_STATE_CHANGED_ACTION); context.registerReceiver(mWifiStateBroadcastReceiver, filter); } protected void finalize() { if(DEBUG) Log.d(TAG,"finalize"); mContext.unregisterReceiver(mWifiStateBroadcastReceiver); } public static WifiAPUtil getInstance(Context c) { if (null == sInstance) sInstance = new WifiAPUtil(c); return sInstance; } //打开移动热点 public boolean OpenWifiAp(String str, String password,WifiSecurityType Type) { String ssid = str; //配置热点信息。 WifiConfiguration wcfg = new WifiConfiguration(); wcfg.SSID = ssid; wcfg.networkId = 1; //清除原有的设置 wcfg.allowedAuthAlgorithms.clear(); wcfg.allowedGroupCiphers.clear(); wcfg.allowedKeyManagement.clear(); wcfg.allowedPairwiseCiphers.clear(); wcfg.allowedProtocols.clear(); if(Type == WifiSecurityType.WIFICIPHER_NOPASS) { //网络开放,无密码 if(DEBUG)Log.d(TAG, "wifi ap----no password"); wcfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN, true); //设置为开放 wcfg.wepKeys[0] = ""; wcfg.allowedKeyManagement.set(KeyMgmt.NONE); wcfg.wepTxKeyIndex = 0; } else if(Type == WifiSecurityType.WIFICIPHER_WPA) { //WPA if(DEBUG)Log.d(TAG, "wifi ap----wpa"); //密码至少8位,否则使用默认密码 if(null != password && password.length() >= 8){ wcfg.preSharedKey = password; } else { wcfg.preSharedKey = DEFAULT_AP_PASSWORD; } wcfg.hiddenSSID = false; wcfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wcfg.allowedKeyManagement.set(KeyMgmt.WPA_PSK); wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wcfg.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); } else if(Type == WifiSecurityType.WIFICIPHER_WPA2) { //WPA2 if(DEBUG)Log.d(TAG, "wifi ap---- wpa2"); //密码至少8位,否则使用默认密码 if(null != password && password.length() >= 8){ wcfg.preSharedKey = password; } else { wcfg.preSharedKey = DEFAULT_AP_PASSWORD; } wcfg.hiddenSSID = true; wcfg.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); wcfg.allowedKeyManagement.set(4); wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); wcfg.allowedProtocols.set(WifiConfiguration.Protocol.WPA); wcfg.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); wcfg.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); } try { Method method = mWifiManager.getClass().getMethod("setWifiApConfiguration", wcfg.getClass()); Boolean rt = (Boolean)method.invoke(mWifiManager, wcfg); if(DEBUG) Log.d(TAG, " rt = " + rt); } catch (NoSuchMethodException e) { Log.e(TAG, e.getMessage()); } catch (IllegalArgumentException e) { Log.e(TAG, e.getMessage()); } catch (IllegalAccessException e) { Log.e(TAG, e.getMessage()); } catch (InvocationTargetException e) { Log.e(TAG, e.getMessage()); } return setWifiApEnabled(); } //获取热点状态 public int getWifiAPState() { int state = -1; try { Method method2 = mWifiManager.getClass().getMethod("getWifiApState"); state = (Integer) method2.invoke(mWifiManager); } catch (Exception e) { Log.e(TAG, e.getMessage()); } if(DEBUG)Log.i("WifiAP", "getWifiAPState.state " + state); return state; } private boolean setWifiApEnabled() { //开启wifi热点需要关闭wifi while(mWifiManager.getWifiState() != WifiManager.WIFI_STATE_DISABLED){ mWifiManager.setWifiEnabled(false); try { Thread.sleep(200); } catch (Exception e) { Log.e(TAG, e.getMessage()); return false; } } // 确保wifi 热点关闭。 while(getWifiAPState() != WIFI_AP_STATE_DISABLED){ try { Method method1 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); method1.invoke(mWifiManager, null, false); Thread.sleep(200); } catch (Exception e) { Log.e(TAG, e.getMessage()); return false; } } //开启wifi热点 try { Method method1 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); method1.invoke(mWifiManager, null, true); Thread.sleep(200); } catch (Exception e) { Log.e(TAG, e.getMessage()); return false; } return true; } //关闭WiFi热点 public void closeWifiAp() { if (getWifiAPState() != WIFI_AP_STATE_DISABLED) { try { Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration"); method.setAccessible(true); WifiConfiguration config = (WifiConfiguration) method.invoke(mWifiManager); Method method2 = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class); method2.invoke(mWifiManager, config, false); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } public void regitsterHandler(Handler handler){ mHandler = handler; } public void unregitsterHandler(){ mHandler = null; } //监听wifi热点状态变化 private BroadcastReceiver mWifiStateBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(DEBUG)Log.i(TAG,"WifiAPUtils onReceive: "+intent.getAction()); if(WIFI_AP_STATE_CHANGED_ACTION.equals(intent.getAction())) { int cstate = intent.getIntExtra(EXTRA_WIFI_AP_STATE, -1); if(cstate == WIFI_AP_STATE_ENABLED) { if(mHandler != null){ mHandler.sendEmptyMessage(MESSAGE_AP_STATE_ENABLED); } }if(cstate == WIFI_AP_STATE_DISABLED || cstate == WIFI_AP_STATE_FAILED) { if(mHandler != null) mHandler.sendEmptyMessage(MESSAGE_AP_STATE_FAILED); } } } }; //获取热点ssid public String getValidApSsid() { try { Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration"); WifiConfiguration configuration = (WifiConfiguration)method.invoke(mWifiManager); return configuration.SSID; } catch (Exception e) { Log.e(TAG, e.getMessage()); return null; } } //获取热点密码 public String getValidPassword(){ try { Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration"); WifiConfiguration configuration = (WifiConfiguration)method.invoke(mWifiManager); return configuration.preSharedKey; } catch (Exception e) { Log.e(TAG, e.getMessage()); return null; } } //获取热点安全类型 public int getValidSecurity(){ WifiConfiguration configuration; try { Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration"); configuration = (WifiConfiguration)method.invoke(mWifiManager); } catch (Exception e) { Log.e(TAG, e.getMessage()); return WifiSecurityType.WIFICIPHER_INVALID.ordinal(); } if(DEBUG)Log.i(TAG,"getSecurity security="+configuration.allowedKeyManagement); if(configuration.allowedKeyManagement.get(KeyMgmt.NONE)) { return WifiSecurityType.WIFICIPHER_NOPASS.ordinal(); }else if(configuration.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { return WifiSecurityType.WIFICIPHER_WPA.ordinal(); }else if(configuration.allowedKeyManagement.get(4)) { //4 means WPA2_PSK return WifiSecurityType.WIFICIPHER_WPA2.ordinal(); } return WifiSecurityType.WIFICIPHER_INVALID.ordinal(); } }
#include <stdio.h> #include<conio.h> /* * @Author: giangnlhph26511 * @Description: Hien thi menu chuong trinh */ void print_menu() { printf("o---------------------------MENU---------------------------o\n"); printf("| 1. Bang cuu chuong 1 |\n"); printf("| 2. Tich cac so chia het cho 3 trong khoang [2;10] |\n"); printf("| X. Thoat |\n"); printf("o----------------------------------------------------------o\n"); } /* * @Author: giangnlhph26511 * @Description: Hien thi bang cuu chuong 1 */ int multiplication_table_1() { for(int i=0 ; i<=10 ; i++) { // So(i): day so tu nhien lien tiep trong khoang [1;10] printf("\t 1 x %d = %d\n", i, 1*i); } } /* * @Author: giangnlhph26511 * @Description: Hien thi tich cac so chia het cho 3 trong khoang * @Param: start: noi bat dau vong lap * @Param: end: noi ket thuc vong lap * @Return: tich cac so */ int multiplication(int start, int end) { int multiplication=1; int i=start; do { // Lap cho den khi thua so vuot qua khoang cho phep if (i%3==0)// Thua so(i): day so chia het cho 3 lien tiep trong khoang [2;10] multiplication=multiplication*i; i++; } while (i<=end); return multiplication; } /* * @Author: giangnlhph26511 * @Description: Xac nhan thoat chuong trinh * @Return: thoat(1) hoac khong thoat(0) */ int exit_confirm() { do { // Lap cho den khi nguoi dung chon phuong an hop le (Y/N) // Nguoi dung nhap lua chon printf("Ban co chac chan muon THOAT khong (Y/N)? "); char confirm = getch(); printf(" %c\n", confirm); // Xet lua chon switch(confirm) { case 'Y': return 1; case 'N': return 0; default: printf("<!> LUA CHON KHONG HOP LE! Moi nhap lai (Y/N)!\n\n"); break; } } while(1); } /* * @Author: giangnlhph26511 * @Description: Chay chuong trinh Lab03 * @Return: nguoi dung chon thoat(0) */ int main() { do { // Lap cho den khi nguoi dung chon thoat // Hien thi lua chon cho nguoi dung print_menu(); // Nguoi dung nhap lua chon printf("Lua chon cua ban: "); char choice = getch(); printf(" %c\n", choice); // Xet lua chon switch(choice) { case '1': printf("++++++++++++BANG 1++++++++++++\n"); multiplication_table_1(); break; case '2': multiplication(2,10); printf("Tich cac so chia het cho 3 trong khoang [2;10]: %d\n", multiplication(2,10)); break; case 'X': // Neu nguoi dung chon 'X', yeu cau nguoi dung xac nhan if (exit_confirm()==1) // Neu nguoi dung xac nhan printf("BAN DA THOAT!"); return 0; // Ket thuc chuong trinh <=> ket thuc ham main break; default: printf("<<!>> LUA CHON KHONG HOP LE! Moi nhap lai!\n\n"); break; } } while(1); }
package com.example.moviejournal.ui import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.bumptech.glide.Glide import com.example.moviejournal.R import com.example.moviejournal.data.JournalEntry import com.example.moviejournal.viewmodels.JournalViewModel import com.example.moviejournal.viewmodels.MovieSearchViewModel import com.google.android.material.button.MaterialButton import com.google.android.material.imageview.ShapeableImageView import com.google.android.material.slider.Slider import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textview.MaterialTextView class EntryEditFragment : Fragment(R.layout.fragment_entry_edit) { private val args by navArgs<EntryEditFragmentArgs>() private lateinit var journalViewModel: JournalViewModel private lateinit var viewOfLayout: View private lateinit var moviePosterIV: ShapeableImageView private lateinit var movieTitleTV: MaterialTextView private lateinit var userReviewTE: TextInputEditText private lateinit var userRatingSlider: Slider private lateinit var submitButton: MaterialButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment viewOfLayout = inflater.inflate(R.layout.fragment_entry_edit, container, false) moviePosterIV = viewOfLayout.findViewById(R.id.iv_movie_poster) movieTitleTV = viewOfLayout.findViewById(R.id.tv_movie_name) userReviewTE = viewOfLayout.findViewById(R.id.input_user_review) userRatingSlider = viewOfLayout.findViewById(R.id.slider_user_rating) submitButton = viewOfLayout.findViewById(R.id.button_submit) return viewOfLayout } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) journalViewModel = ViewModelProvider(requireActivity())[JournalViewModel::class.java] movieTitleTV.text = args.journalEntry.movieName userReviewTE.setText(args.journalEntry.userReview) userRatingSlider.value = args.journalEntry.userRating ?: 5f if (args.journalEntry.moviePoster != null) { Glide.with(requireContext()) .load("https://image.tmdb.org/t/p/w200" + args.journalEntry.moviePoster) .into(moviePosterIV) } submitButton.setOnClickListener { val updatedJournalEntry = JournalEntry( args.journalEntry.movieId, args.journalEntry.movieName, args.journalEntry.moviePoster, args.journalEntry.movieRating, userReviewTE.text.toString(), userRatingSlider.value, System.currentTimeMillis() ) journalViewModel.insertJournalEntry(updatedJournalEntry) // Navigate back to the beginning page findNavController().navigate(R.id.movie_search) } } // companion object { // /** // * Use this factory method to create a new instance of // * this fragment using the provided parameters. // * // * @param param1 Parameter 1. // * @param param2 Parameter 2. // * @return A new instance of fragment EntryEditFragment. // */ // // TODO: Rename and change types and number of parameters // @JvmStatic // fun newInstance(param1: String, param2: String) = //// EntryEditFragment().apply { //// arguments = Bundle().apply { //// putString(ARG_PARAM1, param1) //// putString(ARG_PARAM2, param2) //// } //// } // } }
/* * Copyright (c) 2012,2013, Martin Roth (mhroth@section6.ch) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the AdrenalineJson nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package ch.section6.json; import java.text.ParseException; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** A JSON representation of a {@link Map}. */ public final class JsonObject extends JsonValue implements Map<String,JsonValue>, ImmutableJsonObject { private final Map<String, JsonValue> map; /** Creates an empty JSON object. */ public JsonObject() { map = new HashMap<String, JsonValue>(); } /** A convenience constructor for a new object with a single entry. */ public JsonObject(String key, JsonValue value) { map = new HashMap<String, JsonValue>(); map.put(key, value); } @Override protected void appendTokenList(List<String> tokenList) { if (map.isEmpty()) { tokenList.add("{"); tokenList.add("}"); } else { tokenList.add("{"); tokenList.add("\n"); tokenList.add("\t"); for (Map.Entry<String, JsonValue> e : map.entrySet()) { tokenList.add(JsonString.jsonEscape(e.getKey())); tokenList.add(":"); e.getValue().appendTokenList(tokenList); tokenList.add(","); tokenList.add("\n"); tokenList.add("\t"); } tokenList.remove(tokenList.size() - 1); // remove trailing tab tokenList.remove(tokenList.size() - 2); // remove trailing comma tokenList.add("}"); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); for (Map.Entry<String, JsonValue> e : map.entrySet()) { sb.append(JsonString.jsonEscape(e.getKey())); sb.append(":"); sb.append(e.getValue().toString()); sb.append(","); } if (!map.isEmpty()) sb.deleteCharAt(sb.length() - 1); // clear trailing comma sb.append("}"); return sb.toString(); } @Override public Type getType() { return Type.MAP; } @Override public JsonObject asMap() { return this; } @Override public void clear() { map.clear(); } @Override public boolean containsKey(Object key) { return map.containsKey(key); } @Override public boolean containsValue(Object value) { return map.containsValue(value); } @Override public Set<Map.Entry<String,JsonValue>> entrySet() { return map.entrySet(); } /** * Gets the value associated with the key. If the key does not exist, a * <code>UnknownKeyException</code> is thrown. */ @Override public JsonValue get(Object key) { if (map.containsKey(key)) { return map.get(key); } else { throw new UnknownKeyException(key.toString()); } } public JsonValue get(Object key, JsonValue defaultValue) { return map.containsKey(key) ? map.get(key) : defaultValue; } @Override public JsonValue getByPath(String path) throws IllegalArgumentException, NumberFormatException { return super.getByPath(path); } @Override public boolean setByPath(String path, Object o) throws IllegalArgumentException, NumberFormatException { return super.setByPath(path, o); } @Override public String getString(String key) throws JsonCastException { return get(key).asString(); } public String getString(String key, String defaultString) throws JsonCastException { return map.containsKey(key) ? get(key).asString() : defaultString; } @Override public Date getDate(String key) throws JsonCastException { return get(key).asDate(); } public Date getDate(String key, Date defaultDate) throws JsonCastException { return map.containsKey(key) ? get(key).asDate() : defaultDate; } @Override public boolean getBoolean(String key) throws JsonCastException { return get(key).asBoolean(); } /** * A convenience function to return the keyed value as a boolean, with a * default if the value does not exist. */ public boolean getBoolean(String key, Boolean defaultBoolean) throws JsonCastException { return map.containsKey(key) ? get(key).asBoolean() : defaultBoolean; } @Override public JsonObject getObject(String key) throws JsonCastException { return get(key).asMap(); } @Override public JsonArray getArray(String key) throws JsonCastException { return get(key).asArray(); } @Override public Number getNumber(String key) throws JsonCastException { return get(key).asNumber(); } public Number getNumber(String key, Number defaultNumber) throws JsonCastException { return map.containsKey(key) ? get(key).asNumber() : defaultNumber; } @Override public boolean isEmpty() { return map.isEmpty(); } @Override public Set<String> keySet() { return map.keySet(); } @Override public void putAll(Map<? extends String, ? extends JsonValue> m) { map.putAll(m); } @Override public JsonValue remove(Object key) { return map.remove(key); } @Override public int size() { return map.size(); } @Override public Collection<JsonValue> values() { return map.values(); } public JsonValue put(String key, String value) { return map.put(key, new JsonString(value)); } public JsonValue put(String key, Date date) { return map.put(key, new JsonDate(date)); } public JsonValue put(String key, Number value) { return map.put(key, new JsonNumber(value)); } public JsonValue put(String key, Boolean value) { return map.put(key, getBoolean(value)); } /** * Puts an array of <code>Object</code>s into the map, with the array * automatically converted to a {@link JsonArray}. The type of the objects * is automatically detected and converted into the corresponding JSON type. */ public JsonValue put(String key, Object... values) { return map.put(key, new JsonArray(values)); } @Override public JsonValue put(String key, JsonValue value) { return map.put(key, (value != null) ? value : JsonValue.getNull()); } @Override public boolean equals(Object o) { if (o != null) { if (o instanceof JsonObject) { JsonObject obj = (JsonObject) o; if (map.size() == obj.size()) { for (String key : map.keySet()) { if (!map.get(key).equals(obj.get(key))) return false; } return true; } } } return false; } @Override public int hashCode() { int keysHash = map.keySet().hashCode(); int valuesHash = new HashSet<JsonValue>(map.values()).hashCode(); return (keysHash ^ valuesHash); } @Override public JsonValue copy() { JsonObject obj = new JsonObject(); for (Map.Entry<String,JsonValue> e : map.entrySet()) { obj.put(e.getKey(), e.getValue().copy()); } return obj; } @Override public ImmutableJsonObject asImmutable() { return this; } public static JsonValue parse(String jsonString) throws JsonParseException { if (jsonString == null) { return JsonValue.getNull(); } else if (jsonString.isEmpty()) { return new JsonString(""); } else { return parseValue(0, jsonString.length(), jsonString); } } private static int nextValueString(int i, final int j, String str) throws JsonParseException { switch (str.charAt(i)) { case 't': return i + 4; // true case 'f': return i + 5; // false case 'n': return i + 4; // null case '-': // number case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { int k = i + 1; for (; k < j; ++k) { char c = str.charAt(k); if (c == ']' || c == '}' || c == ',') break; } return k; } case '"': { // string int k = i; do { k = str.indexOf('"', k + 1); } while (str.charAt(k - 1) == '\\'); // ignore \" escape if (k < j) return k + 1; throw new JsonParseException("No balancing quote found for string."); } case '{': { int m = 1; for (int k = i + 1; k < j; ++k) { char c = str.charAt(k); if (c == '}') --m; else if (c == '{') ++m; if (m == 0) return k + 1; } throw new JsonParseException("No balancing } found dictionary."); } case '[': { int m = 1; for (int k = i + 1; k < j; ++k) { char c = str.charAt(k); if (c == ']') --m; else if (c == '[') ++m; if (m == 0) return k + 1; } throw new JsonParseException("No balancing ] found for array."); } default: throw new JsonParseException(); } } private static JsonValue parseValue(int i, int j, String str) throws JsonParseException { switch (str.charAt(i)) { case 't': { if (str.substring(i, i + 4).equals("true")) { return JsonValue.getBoolean(true); } else { throw new JsonParseException("Token starts with \"t\" but is not \"true\"."); } } case 'f': { if (str.substring(i, i + 5).equals("false")) { return JsonValue.getBoolean(false); } else { throw new JsonParseException("Token starts with \"f\" but is not \"false\"."); } } case 'n': { if (str.substring(i, i + 4).equals("null")) { return JsonValue.getNull(); } else { throw new JsonParseException("Token starts with \"n\" but is not \"null\"."); } } case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { try { return new JsonNumber(str.substring(i, j)); } catch (NumberFormatException e) { throw new JsonParseException(e); } } case '"': { String substr = str.substring(i + 1, j - 1); try { return new JsonDate(substr); // is this string a date? } catch (ParseException e) { // nope, must be a normal string substr = substr.replace("\\\\", "\\"); // '\\' -> '\' substr = substr.replace("\\\"", "\""); // '\"' -> '"' return new JsonString(substr); } } case '{': { JsonObject obj = new JsonObject(); i = skipWhitespace(i + 1, str); while (str.charAt(i) != '}') { int k = nextValueString(i, j, str); JsonValue key = parseValue(i, k, str); if (key.getType() != JsonValue.Type.STRING) throw new JsonParseException( "Expected a string as a map key. Instead, parsed a " + key.getType() + "."); i = skipWhitespace(k, str); if (str.charAt(i) != ':') throw new JsonParseException(); i = skipWhitespace(i + 1, str); k = nextValueString(i, j, str); JsonValue value = parseValue(i, k, str); i = skipWhitespace(k, str); if (str.charAt(i) == ',') i = skipWhitespace(i + 1, str); obj.put(key.asString(), value); } return obj; } case '[': { JsonArray array = new JsonArray(); i = skipWhitespace(i + 1, str); while (str.charAt(i) != ']') { int k = nextValueString(i, j, str); JsonValue value = parseValue(i, k, str); array.add(value); i = skipWhitespace(k, str); if (str.charAt(i) == ',') i = skipWhitespace(i + 1, str); } return array; } default: { throw new JsonParseException("Unknown character."); } } } private static int skipWhitespace(int i, String str) { while (i < str.length() && (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\r' || str.charAt(i) == '\t')) { ++i; } return i; } }
/********************************************************************** ** smepowercad ** Copyright (C) 2015 Smart Micro Engineering GmbH ** This program is free software: you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation, either version 3 of the License, or ** (at your option) any later version. ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** You should have received a copy of the GNU General Public License ** along with this program. If not, see <http://www.gnu.org/licenses/>. **********************************************************************/ #include "loginhandler.h" #include "logging.h" LoginHandler::LoginHandler(QObject *parent) : QObject(parent), QQuickImageProvider(QQuickImageProvider::Image), m_qmlEngine(new QQmlEngine(this)) { // Create dummy data m_recentUsers = QList<User>(); m_recentUsers.append(User("Roland Dierks", "rdierks", QImage(":/management/images/face1.jpg"))); m_recentUsers.append(User("Scott Summers", "ssummers", QImage(":/management/images/face2.jpg"))); m_recentUsers.append(User("Ryan Hause", "rhause", QImage(":/management/images/face3.jpg"))); m_qmlEngine->addImageProvider(QStringLiteral("login"), this); m_qmlEngine->rootContext()->setContextProperty("LoginHandler", this); QQmlComponent component(m_qmlEngine, QUrl(QStringLiteral("qrc:/management/LoginView.qml"))); QObject *object = component.create(); connect(object, SIGNAL(loginTriggered(QString,QString)), this, SLOT(on_loginTriggered(QString,QString))); } LoginHandler::~LoginHandler() { delete m_qmlEngine; } QImage LoginHandler::requestImage(const QString &id, QSize *size, const QSize &requestedSize) { int num = id.toInt(); if (num >= m_recentUsers.length()) return QImage(); QImage img = m_recentUsers.at(num).image; if (size) *size = img.size(); if (requestedSize.width() > 0 && requestedSize.height() > 0) return img.scaled(requestedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); return img; } QString LoginHandler::getName(int index) { if (index >= m_recentUsers.length()) return QString(); return m_recentUsers.at(index).name; } QString LoginHandler::getUsername(int index) { if (index >= m_recentUsers.length()) return QString(); return m_recentUsers.at(index).username; } void LoginHandler::on_loginTriggered(QString username, QString password) { qCDebug(powercad) << "Login triggered (" << username << ", " << password << ")"; }
import { Component, Input } from '@angular/core'; import { EditModalComponent } from './edit-modal/edit-modal.component'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { HttpClient } from '@angular/common/http'; import { switchMap } from 'rxjs/operators'; import { Observable, Subject } from 'rxjs'; import { tap } from 'rxjs/operators'; import { AddModalComponent } from './add-modal/add-modal.component'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-create-new-item', templateUrl: './create-new-item.component.html', styleUrls: ['./create-new-item.component.css'] }) export class CreateNewItemComponent { data: any[] = []; addItemValue:any[] = []; jsonPlaceholderData: Observable<any> = this.http.get('https://jsonplaceholder.typicode.com/users'); isEdited: boolean = false; constructor(private modalService: NgbModal, private http: HttpClient) {} ngOnInit() { this.jsonPlaceholderData.subscribe((res: any) => { console.log('obsercvable', res); this.data = res; }); // this.getJsonPlaceholder(); } // getJsonPlaceholder() { // this.http.get('https://jsonplaceholder.typicode.com/users').subscribe((response:any) => { // this.data = response; // }); // } addCallAhead() { const modalRef = this.modalService.open(AddModalComponent, { size: 'lg' }); modalRef.componentInstance.data = this.data; modalRef.componentInstance.saveData.subscribe((res: any) => { this.data.push(res); modalRef.close(); }); } onEdit(data: any, index: any) { console.log('edit', index); const modalRef = this.modalService.open(EditModalComponent, { size: 'lg' }); modalRef.componentInstance.data = data; modalRef.componentInstance.index = index; if (modalRef.componentInstance.data) { modalRef.componentInstance.isEdited = true; modalRef.componentInstance.saveData.subscribe((res: any) => { this.data[res.index] = res.data; modalRef.close(); }); } } delete(index: number) { console.log('delete', index); this.data.splice(index, 1); } }
import { Component, OnInit, OnDestroy } from '@angular/core'; import { WeatherService } from '../services/weatherService.service'; import { SortTypes } from '../common/enums'; import { convertToCelsuis, sortBy } from '../common/utils'; import { Store } from '@ngrx/store'; import { getResultsAction, setSelectedResultAction, } from '../state/results/results.actions'; import { getResults } from '../state/results/results.selector'; import { AppState } from '../state/app.state'; @Component({ selector: 'app-main-page', templateUrl: './main-page.component.html', styleUrls: ['./main-page.component.scss'], }) export class MainPageComponent implements OnInit, OnDestroy { cityName: string = ''; sortTypes = SortTypes; previousSearches: string[] = []; cityResultsWeather: any[] = []; cityResultsWeatherData: any[] = []; constructor( private weatherService: WeatherService, private store: Store<AppState> ) {} ngOnInit(): void { const previousSearches = JSON.parse( localStorage.getItem('searches') as string ); if (previousSearches) { this.previousSearches = previousSearches; } window.onbeforeunload = () => this.ngOnDestroy(); } searchFromHistory(cityName: string) { this.cityName = cityName; this.searchWeatherForCity(true); } async searchWeatherForCity(fromSearch?: boolean) { if ( this.cityName === '' || this.cityName === undefined || this.cityName === null ) { window.alert(`Please enter a valid search`); return; } if (this.cityResultsWeatherData.length) { this.cityResultsWeatherData = []; } if (!fromSearch) { this.previousSearches.push(this.cityName); } let cityResults = await this.weatherService.fetchCitiesResults( this.cityName ); let cityResultsData: any[] = cityResults; this.cityResultsWeather = await Promise.all( cityResultsData.map(async (city) => { let weatherData = await this.weatherService.fetchWeatherDataByCoordinates( city.lat, city.lon ); weatherData.city.state = city.state; this.cityResultsWeatherData.push(weatherData); let weatherTempartureData = convertToCelsuis( weatherData.list[0].main.temp ).toFixed(0); return { id: weatherData.city.id, name: city.name, state: city.state, country: city.country, temp: weatherTempartureData, }; }) ); this.store.dispatch( getResultsAction({ content: this.cityResultsWeatherData }) ); } sortResultstBy(e: any) { const sortType: string = e.target.innerText; switch (sortType) { case SortTypes.BY_NAME_ASCENDING: sortBy(true, 'name', this.cityResultsWeather); break; case SortTypes.BY_NAME_DESCENDING: sortBy(false, 'temp', this.cityResultsWeather); break; case SortTypes.BY_TEMP_ASCENDING: sortBy(true, 'temp', this.cityResultsWeather); break; case SortTypes.BY_TEMP_DESCENDING: sortBy(false, 'temp', this.cityResultsWeather); break; } } setSelectedResult(e: any) { this.store.dispatch(setSelectedResultAction({ content: e })); } ngOnDestroy(): void { localStorage.setItem('searches', JSON.stringify(this.previousSearches)); } }
<template> <table class="centered striped"> <table-header :headers="headers" /> <tbody> <tr v-for="row in data" :key="row.id" > <table-row :row="row" :headers="headers" :statuses="statuses" :roles="roles" :actives="actives" :confirm="confirm" :cancel="cancel" :block="block" :editRow="editRow" :deleteRow="deleteRow" @markConfirm="$emit('markConfirm', row)" @markCanceled="$emit('markCanceled', row)" @markBlocked="$emit('markBlocked', row)" @editRow="$emit('editRow', row)" @deleteRow="$emit('deleteRow', row)" /> </tr> </tbody> </table> </template> <script> import TableHeader from "./Ui/TableHeader.vue" import TableRow from './Ui/TableRow.vue' export default { components: { TableHeader, TableRow }, name: "EntityTable", emits: [ 'markConfirm', 'markCanceled', 'markBlocked', 'editRow', 'deleteRow' ], props: { headers: { type: Array, required: true }, data: { type: Array, required: true }, statuses: { type: Array, required: false }, roles: { type: Array, required: false }, actives: { type: Array, required: false }, confirm: { type:Boolean, default:false }, cancel: { type:Boolean, default:false }, block: { type:Boolean, default:false }, editRow: { type:Boolean, default:false }, deleteRow: { type:Boolean, default:false } } } </script>
// // MapPin.swift // Map // // Created by Paul Kraft on 22.04.22. // import MapKit import SwiftUI #if canImport(WatchKit) && os(watchOS) import WatchKit public struct MapPin { // MARK: Stored Properties private let coordinate: CLLocationCoordinate2D private let color: WKInterfaceMapPinColor // MARK: Initialization public init(coordinate: CLLocationCoordinate2D, color: WKInterfaceMapPinColor) { self.coordinate = coordinate self.color = color } } // MARK: - MapAnnotation extension MapPin: MapAnnotation { public func addAnnotation(to map: WKInterfaceMap) { map.addAnnotation(coordinate, with: color) } } #else public struct MapPin { // MARK: Nested Types private class Annotation: NSObject, MKAnnotation { // MARK: Stored Properties let coordinate: CLLocationCoordinate2D // MARK: Initialization init(_ coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate } } // MARK: Stored Properties private let coordinate: CLLocationCoordinate2D private let tint: Color? public let annotation: MKAnnotation // MARK: Initialization public init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate self.tint = nil self.annotation = Annotation(coordinate) } @available(iOS 14, macOS 11, tvOS 14, *) public init(coordinate: CLLocationCoordinate2D, tint: Color?) { self.coordinate = coordinate self.tint = tint self.annotation = Annotation(coordinate) } } // MARK: - MapAnnotation extension MapPin: MapAnnotation { public static func registerView(on mapView: MKMapView) { mapView.register( MKPinAnnotationView.self, forAnnotationViewWithReuseIdentifier: reuseIdentifier) } public func view(for mapView: MKMapView) -> MKAnnotationView? { let view = mapView.dequeueReusableAnnotationView(withIdentifier: Self.reuseIdentifier, for: annotation) view.annotation = annotation if #available(iOS 14, macOS 11, tvOS 14, *), let tint = tint, let pin = view as? MKPinAnnotationView { pin.pinTintColor = .init(tint) } return view } } #endif
import { component$, useClientEffect$, useStylesScoped$, } from "@builder.io/qwik"; import type { DocumentHead } from "@builder.io/qwik-city"; import { Engine, FreeCamera, HemisphericLight, MeshBuilder, Scene, Vector3, } from "@babylonjs/core"; import styles from "./index.css?inline"; // import { Link } from '@builder.io/qwik-city'; export default component$(() => { useStylesScoped$(styles); useClientEffect$(() => { const canvas = document.getElementById("renderCanvas") as HTMLCanvasElement; if (canvas === null) { return; } const engine = new Engine(canvas, true); const createScene = function () { const scene = new Scene(engine); const camera = new FreeCamera("camera1", new Vector3(0, 5, -10), scene); camera.setTarget(Vector3.Zero()); camera.attachControl(canvas, true); const light = new HemisphericLight("light", new Vector3(0, 1, 0), scene); light.intensity = 0.7; const sphere = MeshBuilder.CreateSphere( "sphere", { diameter: 2, segments: 32 }, scene ); sphere.position.y = 1; // eslint-disable-next-line const ground = MeshBuilder.CreateGround( "ground", { width: 6, height: 6 }, scene ); return scene; }; const scene = createScene(); engine.runRenderLoop(() => { scene.render(); }); window.addEventListener("resize", () => { engine.resize(); }); }); return ( <div> <h1>Welcome to Qwik and BabylonJS example</h1> <canvas id="renderCanvas"></canvas> </div> ); }); export const head: DocumentHead = { title: "Qwik and BabylonJS", meta: [ { name: "description", content: "Qwik and BabylonJS", }, ], };
importance: 2 --- # min から max のランダムな整数 取りうる値として `min` と `max` を含む、`min` から `max` のランダムな *整数* 値を生成する関数 `randomInteger(min, max)` を作りなさい。 範囲 `min..max` からの任意の値は、同じ確率で現れなければいけません。 動作例: ```js alert( random(1, 5) ); // 1 alert( random(1, 5) ); // 3 alert( random(1, 5) ); // 5 ```
<?php namespace app\models; use Yii; /** * This is the model class for table "user". * * @property int $id * @property string|null $login * @property string|null $password * @property string|null $email * @property string|null $phone * @property string|null $fio * @property int|null $role_id * * @property Report[] $reports * @property Role $role */ class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface { /** * {@inheritdoc} */ public static function tableName() { return 'user'; } /** * {@inheritdoc} */ public function rules() { return [ [['role_id'], 'integer'], [['login', 'password', 'email', 'phone', 'fio'], 'required', 'message' =>'Заполните поле'], [['email'],'email', 'message' =>'Email введен некорректно'], [['phone'],'string','min'=>11, 'max'=>11, 'tooShort'=>'Сликшом короткий номер', 'tooLong'=>'Слишком длинный номер'], [['login', 'password', 'email', 'phone', 'fio'], 'string', 'max' => 255], [['role_id'], 'exist', 'skipOnError' => true, 'targetClass' => Role::class, 'targetAttribute' => ['role_id' => 'id']], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'login' => 'Логин', 'password' => 'Пароль', 'password_confirmation' => 'Повторите пароль', 'email' => 'Email', 'phone' => 'Телефон', 'fio' => 'ФИО', ]; } /** * Gets query for [[Reports]]. * * @return \yii\db\ActiveQuery */ public function getReports() { return $this->hasMany(Report::class, ['user_id' => 'id']); } /** * Gets query for [[Role]]. * * @return \yii\db\ActiveQuery */ public function getRole() { return $this->hasOne(Role::class, ['id' => 'role_id']); } public static function login($login, $password) { $user = self::findOne(['login'=>$login]); if ($user && $user -> validatePassword($password)) { return $user; } return null; } /** * {@inheritdoc} */ public static function findIdentity($id) { return self::findOne(['id'=>$id]); } /** * {@inheritdoc} */ public static function findIdentityByAccessToken($token, $type = null) { return null; } /** * {@inheritdoc} */ public function getId() { return $this->id; } /** * {@inheritdoc} */ public function getAuthKey() { return null; } /** * {@inheritdoc} */ public function validateAuthKey($authKey) { return null; } /** * Validates password * * @param string $password password to validate * @return bool if password provided is valid for current user */ public function validatePassword($password) { return $this->password === $password; } public function __toString() { return $this->login; } public static function getInstance(): null|User { return Yii::$app->user->identity; } public function isAdmin(){ return $this->role_id == Role::ADMIN_ROLE_ID; } }
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-viewmore', templateUrl: './viewmore.component.html', styleUrls: ['./viewmore.component.css'], }) export class ViewmoreComponent implements OnInit { constructor(private route: ActivatedRoute) {} data: any; currentPage: number = 1; pageSize: number = 10; totalItems!: number; pages!: number[]; displayData: any[] = []; ngOnInit(): void { this.route.queryParams.subscribe((params) => { this.data = JSON.parse(params['data']); this.totalItems = this.data.length; this.calculatePages(); this.loadData(); }); } calculatePages(): void { const pageCount = Math.ceil(this.totalItems / this.pageSize); // Hiển thị có bao nhiêu trang this.pages = Array(pageCount) // hiển thị số trang từ 1 đên pageCount .fill(0) .map((x, i) => i + 1); } loadData(): void { const startIndex = (this.currentPage - 1) * this.pageSize; // tính index bắt đầu const endIndex = startIndex + this.pageSize; // tính index kết thúc this.displayData = this.data.slice(startIndex, endIndex); // tính data của từng index rồi lưu vào biến displayData // Kiểm tra nếu không tìm thấy từ khóa // if (this.displayData.length === 0) { // this.showError = true; // } else { // this.showError = false; // } } previousPage(): void { if (this.currentPage > 1) { this.currentPage--; this.loadData(); } } nextPage(): void { if (this.currentPage < this.pages.length) { this.currentPage++; this.loadData(); } } goToPage(page: number): void { if (page >= 1 && page <= this.pages.length) { this.currentPage = page; this.loadData(); } } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <utility> #include <vector> #include <folly/MacAddress.h> #include <glog/logging.h> extern "C" { #include <netlink/errno.h> #include <netlink/genl/ctrl.h> #include <netlink/genl/family.h> #include <netlink/genl/genl.h> #include <netlink/msg.h> #include <netlink/netlink.h> #include <netlink/socket.h> #include <nl-driver-if/fb_tgd_nlsdn_common.h> } namespace facebook { namespace terragraph { /* * Abstracting messages to the driver by type and data. * * This layer is only to store the message in a way which netlink understands. * * There are no explicit GET, SET types. It should be implied in the API, e.g. * getMessage() and sendMessage(). * * Example: Doing a sendMessage() with type LINK_STATS is a request to driver * and a getMessage() is the response from driver. * * Some types may only be one-way or an acknowledgement of success in the * reverse direction. * * Example: LINK_INIT is a request and may only respond with the status of * the request (if at all). * * This is to keep things simple for now. If direction-aware types are needed, * we can always add them later. */ /** * Netlink message types. * * These correspond with `TGENUM_CMD` declarations in `fb_tgd_nlsdn_common.h`. */ enum class DriverNlMessageType : uint8_t { NONE, NODE_INIT = TGD_NLSDN_CMD_TGINIT, NODE_INIT_NOTIFY = TGD_NLSDN_CMD_NOTIFY_TGINIT, BF_SCAN = TGD_NLSDN_CMD_BF_SCAN, DR_LINK_STATUS = TGD_NLSDN_CMD_NOTIFY_LINK_STATUS, PASSTHRU_NB = TGD_NLSDN_CMD_PASSTHRU_NB, PASSTHRU_SB = TGD_NLSDN_CMD_PASSTHRU_SB, DRVR_REQ = TGD_NLSDN_CMD_SET_DRVR_CONFIG, DRVR_STAT_NB = TGD_NLSDN_CMD_DRVRSTAT_NB, DRVR_RSP = TGD_NLSDN_CMD_NOTIFY_DRVR_RSP, DEV_ALLOC = TGD_NLSDN_CMD_DEV_ALLOC, DEV_ALLOC_RSP = TGD_NLSDN_CMD_DEV_ALLOC_RSP, WSEC_STATUS = TGD_NLSDN_CMD_NOTIFY_WSEC_STATUS, WSEC_LINKUP_STATUS = TGD_NLSDN_CMD_NOTIFY_WSEC_LINKUP_STATUS, DEV_UPDOWN_STATUS = TGD_NLSDN_CMD_NOTIFY_DEV_UPDOWN_STATUS, SET_GPS_TIME = TGD_NLSDN_CMD_SET_GPS_TIME, SET_GPS_POS = TGD_NLSDN_CMD_SET_GPS_POS, // TODO: Add remaining types... }; /** * Wrapper for messages transmitted and received over netlink. */ class DriverNlMessage { public: /** Constructor. */ DriverNlMessage() : mType(DriverNlMessageType::NONE){}; /** \{ */ DriverNlMessage(const DriverNlMessage&) = default; DriverNlMessage& operator=(const DriverNlMessage&) = default; /** \} */ /** Reset all internal state. */ void reset() { mType = DriverNlMessageType::NONE; u8Attrs.clear(); u16Attrs.clear(); u32Attrs.clear(); u64Attrs.clear(); u8vlaAttrs.second.clear(); // TODO: clear any other unspec attrs that maybe added } /** * Set the radio MAC address associated with this message. * * Returns false if the provided MAC address could not be parsed. */ bool setRadioMac(const std::string& macAddr) { if (!macAddr.empty()) { try { radioMac = folly::MacAddress(macAddr); return true; } catch (const std::exception& ex) { LOG(ERROR) << "Invalid radio MAC: " << macAddr; } } return false; } /** The message type. */ DriverNlMessageType mType; /** The MAC address of the RF port. */ folly::MacAddress radioMac; // Owner's responsibilty to fill in the attributes below for relevant // mType. Netlink handler will simply stick in all valid // entries for each attr type in the message with no validation. /** The u8 netlink attributes. */ std::vector<std::pair<enum tgd_nlsdn_attrs, uint8_t>> u8Attrs; /** The u16 netlink attributes. */ std::vector<std::pair<enum tgd_nlsdn_attrs, uint16_t>> u16Attrs; /** The u32 netlink attributes. */ std::vector<std::pair<enum tgd_nlsdn_attrs, uint32_t>> u32Attrs; /** The u64 netlink attributes. */ std::vector<std::pair<enum tgd_nlsdn_attrs, uint64_t>> u64Attrs; /** The variable-length netlink attributes. */ std::pair<enum tgd_nlsdn_attrs, std::vector<uint8_t>> u8vlaAttrs; // Anything UNSPEC in nla will have custom structs which should be defined // and shared all over (firmware, driver, e2e) unless there exists a strong // reason to differentiate. Example. STATS message. Add a similar vector // with that message type. If we get too many, we may think of adding some // abstraction to convert these types to/from netlink messages }; } // namespace terragraph } // namespace facebook
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; /** * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Task> */ class TaskFactory extends Factory { /** * Define the model's default state. * * @return array<string, mixed> */ public function definition(): array { return [ 'name' => $this->faker->sentence, 'description' => $this->faker->realText, 'image_path' => $this->faker->imageUrl(), 'status' => $this->faker->randomElement(['pending', 'in_progress', 'completed']), 'priority' => $this->faker->randomElement(['low', 'medium', 'high']), 'due_date' => $this->faker->dateTimeBetween('now', '+1 year'), 'assigned_user_id' => 1, 'created_by' => 1, 'updated_by' => 1, 'project_id' => 1, ]; } }
<div class="backdrop is-hidden" data-modal> <div class="modal"> <button class="modal-close-btn" type="button" data-modal-close> <svg class="modal-close-icon" width="24" height="24"> <use href="../img/icons.svg#close-btn"></use> </svg> </button> <h1 class="modal-title">Your Order</h1> <form class="modal-form"> <ul class="form-list list"> <li class="form-item"> <div class="form-item-check"> <input class="form-check visually-hidden" type="checkbox" name="cabbage" id="cabbage" value="true" required /> <label class="check-label" for="cabbage"> <svg class="check-icon" width="16" height="16"> <use href="../img/icons.svg#icon-check"></use> </svg> </label> </div> <div class="form-item-primary"> <h2 class="form-item-title">Cabbage Basket</h2> <p class="form-item-text">Plant</p> </div> <picture class="form-item-pic"> <source srcset=" ../img/desktop/modal/modal-cabbage-desk.png 1x, ../img/desktop/modal/modal-cabbage-desk@2x.png 2x " media="(min-width: 1280px)" /> <source srcset=" ../img/tablet/modal/modal-cabbage-tab.png 1x, ../img/tablet/modal/modal-cabbage-tab@2x.png 2x " media="(min-width: 768px)" /> <source srcset=" ../img/mobile/modal/modal-cabbage-mob.png 1x, ../img/mobile/modal/modal-cabbage-mob@2x.png 2x " media="(max-width: 767px)" /> <img src="../img/desktop/modal/modal-cabbage-desk.png" alt="photo cabbage basket" width="243" /> </picture> </li> <li class="form-item"> <div class="form-item-check"> <input class="form-check visually-hidden" type="checkbox" name="tomato" id="tomato" value="true" required /> <label class="check-label" for="tomato"> <svg class="check-icon" width="16" height="16"> <use href="../img/icons.svg#icon-check"></use> </svg> </label> </div> <div class="form-item-primary"> <h2 class="form-item-title">Tomato Basket</h2> <p class="form-item-text">Plant</p> </div> <picture class="form-item-pic"> <source srcset=" ../img/desktop/modal/modal-tomato-desk.png 1x, ../img/desktop/modal/modal-tomato-desk@2x.png 2x " media="(min-width: 1280px)" /> <source srcset=" ./img/tablet/modal/modal-tomato-tab.png 1x, ./img/tablet/modal/modal-tomato-tab@2x.png 2x " media="(min-width: 768px)" /> <source srcset=" ../img/mobile/modal/modal-tomato-mob.png 1x, ../img/mobile/modal/modal-tomato-mob@2x.png 2x " media="(max-width: 767px)" /> <img src="../img/desktop/modal/modal-tomato-desk.png" alt="photo cabbage basket" width="243" /> </picture> </li> <li class="form-item"> <div class="form-item-check"> <input class="form-check visually-hidden" type="checkbox" name="vegetables" id="vegetables" value="true" required /> <label class="check-label" for="vegetables"> <svg class="check-icon" width="16" height="16"> <use href="../img/icons.svg#icon-check"></use> </svg> </label> </div> <div class="form-item-primary"> <h2 class="form-item-title">Vegetables Basket</h2> <p class="form-item-text">Plant</p> </div> <picture class="form-item-pic"> <source srcset=" ../img/desktop/modal/modal-vegetables-desk.png 1x, ../img/desktop/modal/modal-vegetables-desk@2x.png 2x " media="(min-width: 1280px)" /> <source srcset=" ../img/tablet/modal/modal-vegetables-tab.png 1x, ../img/tablet/modal/modal-vegetables-tab@2x.png 2x " media="(min-width: 768px)" /> <source srcset=" ../img/mobile/modal/modal-vegetables-mob.png 1x, ../img/mobile/modal/modal-vegetables-mob@2x.png 2x " media="(max-width: 767px)" /> <img src="../img/desktop/modal/modal-vegetables-desk.png" alt="photo cabbage basket" width="243" /> </picture> </li> </ul> <div class="form-wrap"> <div class="form-field-submit"> <div class="form-field"> <label class="form-label"> <input class="form-input" type="text" name="user-name" placeholder="Enter full name..." pattern="\w{3,20}" required /> </label> </div> <div class="form-field"> <label class="form-label"> <input class="form-input" type="email" name="user-mail" placeholder="Enter email..." pattern="[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,}$" required /> </label> </div> <div class="form-field"> <label class="form-label"> <input class="form-input" type="text" name="user-card" placeholder="Enter card.." pattern="[0-9]{16}" required /> </label> </div> <div class="form-field-coment"> <label class="form-label"> <textarea class="form-coment" name="user-comment" placeholder="Enter comments..." ></textarea> </label> </div> </div> <button class="form-btn" type="submit">Submit</button> </div> <picture class="form-pic"> <source srcset=" ../img/desktop/modal/modal-girl-desk.png 1x, ../img/desktop/modal/modal-girl-desk@2x.png 2x " media="(min-width: 1280px)" /> <source srcset=" ../img/tablet/modal/modal-girl-tab.png 1x, ../img/tablet/modal/modal-girl-tab@2x.png 2x " media="(min-width: 768px)" /> <img src="../img/desktop/modal/modal-girl-desk.png" alt="photo girl with cabbage" width="444" /> </picture> </form> </div> </div>
# Introduction This app is a tool to poll API data from an end point and storing it in a sql server, functionally this means it is collecting stock quote information and stored into a server. It then stores the data into an sql server and you can simulate buying and selling stocks based on the collected data. It is written in java and built using Maven. The connection to the endpoint is facilitated with the OKHTTP library for the JDBC. The resulting JSON files are parsed using the JACKSON databind library. They are then stored into a postgreSQL server instance with two tables, one to store stockquote information, and the other used to store positions the user has bought into. Furthermore it is unit tested and integration tested using the Junit and Mockito. # Implementaiton ## ER Diagram ![image](https://github.com/jarviscanada/jarvis_data_eng_DevinSmith/assets/66887499/a09c2444-f0f8-42b9-b865-192349abaa75) ## Design Patterns In this project, I created two DAO implementations. There is a java class called CrudDao that my PositionDao and my QuoteDao implement. These DAOs implement the four core functions of persistent storage. These are faciliatated by prepared statements handed to methods to inact them. `T save(T entity)` The save method allows the creation of a new entry into their tables, though if the primary key is already found it will instead update the entry. The QuoteDAO is also the class that accesses and pulls the data off of the API endpoint for insertion into the Quote table. The save method therefore implements CREATE and UPDATE. `Optional<T> findById(String id)` `Iterable<T> findAll()` The DAO's feature a findByID method, which checks the respective table based on the entry's ID to see if there is an entry that matches the ID. This is the implementation of READ. There is also findAll which returns everything in the table. `void deleteById(ID id)` `void deleteAll()` Then there is a deleteByID and a deleteAll method for each DAO. These implement DELETE for the sql tables, deleting a single element by ID or deleting the entire tables contents, respectively. # Test ## Setting up the Database Using the postgreSQL terminal, the following command creates the database `DROP DATABASE IF EXISTS stock_quote;` `CREATE DATABASE stock_quote;` Then to instantiate the tables, the following commands were used, first for quotes: DROP TABLE IF EXISTS quote; `CREATE TABLE quote (` ` symbol VARCHAR(10) PRIMARY KEY,` ` open DECIMAL(10, 2) NOT NULL,` ` high DECIMAL(10, 2) NOT NULL,` ` low DECIMAL(10, 2) NOT NULL,` ` price DECIMAL(10, 2) NOT NULL,` ` volume INT NOT NULL,` ` latest_trading_day DATE NOT NULL,` ` previous_close DECIMAL(10, 2) NOT NULL,` ` change DECIMAL(10, 2) NOT NULL,` ` change_percent VARCHAR(10) NOT NULL,` ` timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL,`\ `);` Then for positions: `DROP TABLE IF EXISTS position;` `CREATE TABLE position (` ` symbol VARCHAR(10) PRIMARY KEY,` ` number_of_shares INT NOT NULL,` ` value_paid DECIMAL(10, 2) NOT NULL,` ` CONSTRAINT symbol_fk FOREIGN KEY (symbol) REFERENCES quote(symbol)` `);` In testing, I would manually insert data into the quote table using commands in the sql terminal. Then when I did search, delete and delete all I could make other checks with findByID to see if the data had been interacted with. I would do similar with the position table as well, however I needed data input into the quote table when testing the position table as it was dependent on the quote tables ID value because it contained the primary key. During testing I would insert data into quote then compare the data I inserted with the data being returned by findByID. I would do similar for the postions table. I have tested at the DAO and service layers, for both the position and quote components. For testing the controller and main, because they were essentially scripts, I just ran through them with different combinations of inputs to see if I could find any odd output. This testing was facilitated by the use of Junit and Mockito. Junit covered the general testing with assertions, while Mockito allowed me to do unit testing through mocks and stubs.
import React from 'react'; import ReactiveForm, { createPluginArray, FormPlugins } from '@reactive-forms/core'; import { render } from '@testing-library/react'; import { createPxth } from 'pxth'; import { domPlugin, ErrorMessage } from '../src'; describe('ErrorMessage', () => { it('should not render empty error', () => { const { getByRole } = render( <FormPlugins plugins={createPluginArray(domPlugin)}> <ReactiveForm initialValues={{ test: '' }}> <ErrorMessage name={createPxth(['test'])} /> </ReactiveForm> </FormPlugins>, ); expect(() => getByRole('span')).toThrow(); }); it('should render error element', () => { const { getByText } = render( <FormPlugins plugins={createPluginArray(domPlugin)}> <ReactiveForm initialValues={{ test: '' }} initialErrors={{ test: { $error: 'test', }, }} initialTouched={{ test: { $touched: true, }, }} > <ErrorMessage name={createPxth(['test'])} as="div" /> </ReactiveForm> </FormPlugins>, ); expect(getByText('test')).toBeDefined(); }); it('should render error component', () => { const ErrorComponent = ({ children }: { children?: string }) => { return children !== undefined ? <div>{children}</div> : null; }; const { findByText } = render( <FormPlugins plugins={createPluginArray(domPlugin)}> <ReactiveForm initialValues={{ test: '' }} initialErrors={{ test: { $error: 'message', }, }} initialTouched={{ test: { $touched: true, }, }} > <ErrorMessage name={createPxth(['test'])} as={ErrorComponent} /> </ReactiveForm> </FormPlugins>, ); expect(findByText('message')).toBeDefined(); }); it('should render error in span by default', () => { const { findByText } = render( <FormPlugins plugins={createPluginArray(domPlugin)}> <ReactiveForm initialValues={{ test: '' }} initialErrors={{ test: { $error: 'error', }, }} initialTouched={{ test: { $touched: true, }, }} > <ErrorMessage name={createPxth(['test'])} /> </ReactiveForm> </FormPlugins>, ); expect(findByText('error')).toBeDefined(); }); it('should call function renderer', () => { const { findByText } = render( <FormPlugins plugins={createPluginArray(domPlugin)}> <ReactiveForm initialValues={{ test: '' }} initialErrors={{ test: { $error: 'error', }, }} initialTouched={{ test: { $touched: true, }, }} > <ErrorMessage name={createPxth(['test'])}>{({ children }) => <div>{children}</div>}</ErrorMessage> </ReactiveForm> </FormPlugins>, ); expect(findByText('error')).toBeDefined(); }); it('should not render error when touched=true and error=undefined', () => { const { getByRole } = render( <FormPlugins plugins={createPluginArray(domPlugin)}> <ReactiveForm initialValues={{ test: '' }} initialTouched={{ test: { $touched: true, }, }} > <ErrorMessage name={createPxth(['test'])} /> </ReactiveForm> </FormPlugins>, ); expect(() => getByRole('span')).toThrow(); }); });
const express = require('express') const func = require('./functionsutil.js') const db = require('./conection/consultas') const router = express.Router(); /** * Verifica se o cliente já está cadastrado na base * e caso não esjeta já salva * json=>{nome, whatsapp, dispositivo} */ router.post('/verify-client', async (req, res) => { const {nome, whatsapp, dispositivo} = req.body const msgCliente = await db.verifyClientExist(whatsapp) // Verifica se é cliente no banco de dados if(msgCliente.length > 0){ res.send(msgCliente[0].nome) }else{ db.saveNewClient(req.body) res.send(false) } }) /** * Pega o nome da Barbearia */ router.get('/get-barber', async (req, res) => { const barbearia = await db.getBarber(req.query.barber) console.log(barbearia) console.log(barbearia[0].nomebarbearia) res.send(barbearia[0].nomebarbearia) }) /** * Endpoint para atualizar dados do cliente */ router.post('/update-client', async (req, res) => { const {whatsappTo, nome} = req.body await db.updateClient(whatsappTo, nome) res.send('atualizando cliente') }) /** * Endpoint para salvar Conversas */ router.post('/save-message', async (req, res) => { await db.saveMessageChat(req.body) res.send("Nova mensagem adicionada") }) /** * Endpoint para salvar a Resposta do dialogFlow na conversa do cliente * */ router.post('/save-response', async (req, res) => { await db.saveResponseMessage(req.body) res.send("Resposta da mensagem anterior inserida") }) /** * Endpoint os serviços com preços */ router.post('/show-services', async (req, res) => { let {whatsappTo, mensagem} = req.body console.log(req.body) const services = await db.getServicesPrices(whatsappTo) const list = { type : "list" ,listContent : services.map(item => item.nomeservico).join('\n') ,listAction : "Escolha uma opção 👈" ,listItens : [{title:"Escolha uma opção abaixo", rows:[]}] ,listTitle : "" ,listFooter : "Selecione um item" } list.listItens[0].rows = ['Voltar ao menu Principal', 'Sair'].map(item => ({title:item, description: ""})) console.log(list) console.log("Enviando Lista", new Date()) res.send(list) }) /** * Endpoint para buscar os serviços oferecidos */ router.post('/get-services', async (req, res) => { let {whatsappTo, mensagem} = req.body console.log(req.body) const services = await db.getServices(whatsappTo) const list = { type : "list" ,listContent : mensagem ,listAction : "Escolha um serviço 👈" ,listItens : [{title:"Escolha um serviço abaixo", rows:[]}] ,listTitle : "" ,listFooter : "Selecione um item" } list.listItens[0].rows = services.map(item => ({title:item.nomeservico, description: ""})) console.log(list) console.log("Enviando Lista", new Date()) res.send(list) }) /** * Endpoint para buscar os serviços oferecidos */ router.post('/get-location', async (req, res) => { let {whatsappTo, mensagem} = req.body console.log(req.body) const localizacao = await db.getLocation(whatsappTo) console.log(localizacao) const list = { type : "list" ,listContent : mensagem+localizacao[0].endereco+'\n\n'+localizacao[0].linkmaps ,listAction : "Escolha uma opção" ,listItens : [{title:"Escolha uma opção abaixo", rows:[]}] ,listTitle : "" ,listFooter : "Selecione um item" } list.listItens[0].rows = ['Voltar ao menu Principal', 'Sair'].map(item => ({title:item, description: ""})) console.log(list) console.log("Enviando Lista", new Date()) res.send(list) }) /** * Endpoint para buscar as datas disponivéis do agendamento * pegar só 30 dias */ router.post('/get-datas', async (req, res) => { let {whatsappTo, mensagem} = req.body console.log(req.body) const agend = await db.getDateFree(whatsappTo) const funcion = await db.getFuncionamento(whatsappTo) const datasLivres = func.datasParaAgendamento(agend, funcion) console.log(datasLivres) const list = { type : "list" ,listContent : mensagem ,listAction : "Escolha a Data aqui 📅 👈" ,listItens : [{title:"Escolha uma data abaixo", rows:[]}] ,listTitle : "" ,listFooter : "Selecione um item" } list.listItens[0].rows = datasLivres.map(item => ({title:item.data, description: ""})) console.log(list) console.log("Enviando Lista", new Date()) res.send(list) }) /** * Endpoint para buscar horários da data escolhida disponivéis do agendamento * */ router.post('/get-hours', async (req, res) => { const funcionamentoDia = await db.getFuncionamento(req.body.whatsappTo) const hoursDay = await db.getDayHoursFree(req.body) const msg = req.body.mensagem const hourLivre = func.horasDisponiveisDoDia(funcionamentoDia[0],hoursDay) console.log(hourLivre) const list = { type : "list" ,listContent : msg ,listAction : "Escolha a Hora aqui ⏱ 👈" ,listItens : [{title:"Escolha uma data abaixo", rows:[]}] ,listTitle : "" ,listFooter : "Selecione um item" } list.listItens[0].rows = hourLivre.map(item => ({title:item, description: ""})) res.send(list) }) /** * Endpoint salvar o agendamento * TODO Verificar antes se alguém já escolheu a hora selecionada (evitar duplicidade) * */ router.post('/save-date-time-appointment', async (req, res) => { const free = await db.verifyDateHoursFree(req.body) let appointment = 'Hora não disponível, por favor selecione outro horário' if(free.length == 0){ const retorno = await db.saveDateTimeAppointment(req.body) appointment = 'OK' // Verifica se a data Agendada é igual ao dia atual Envia mensagem para o barbeiro com a lista atualizada do dia atual if(func.verifyCurrentDate(req.body.data)) func.refresListBarber(req.body.whatsappTo) } res.send(appointment) }) /** * Endpoint salvar o lembrete */ router.post('/reminder-me', async (req, res) => { const getHourReminder = func.getHourReminder(req.body) await db.insertReminderMe(req.body,getHourReminder) res.send("Seu lembrete foi agendado às "+ getHourReminder) }) /** * Endpoint disparar para o cabeleireiro a lista atualizada de agendamentos do dia */ router.post('/send-list-scheduling', async (req, res) => res.send(await func.refresListBarber(req.body.whatsappTo))) /** * Aplicação para verficiar o status das conversas * */ module.exports = router
import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo'; import { join } from 'path'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule } from '@nestjs/config'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { PetsModule } from './pets/pets.module'; import { OwnersModule } from './owners/owners.module'; import { UsersModule } from './users/users.module'; import { AuthModule } from './auth/auth.module'; @Module({ imports: [ ConfigModule.forRoot(), GraphQLModule.forRoot<ApolloDriverConfig>({ driver: ApolloDriver, autoSchemaFile: join(process.cwd(), 'src/schema.gql'), sortSchema: true, }), TypeOrmModule.forRoot({ type: 'sqlite', database: ':memory', // entities: ['dist/**/*.entity{.ts, .js}'], // ojoooooooo entities: [__dirname + '/**/*.entity{.ts,.js}'], synchronize: true, }), PetsModule, OwnersModule, UsersModule, AuthModule, ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
import React, {useContext} from 'react'; import {TransactionContext} from '../context/TransactionContext'; import dummyData from '../utils/dummyData'; import {shortenAddress} from '../utils/shortenAddress'; import useFetch from '../hooks/useFetch'; const TransactionCard = ({addressTo, addressFrom, timestamp, message, keyword, amount, url}) => { const gifUrl = useFetch({keyword}); return ( <div className='bg-[#181918] m-4 flex flex-1 2xl:min-w-[450px] 2xl:min-w-[500px] sm:min-w-[270px] sm:max-w-[300px] flex-col p-3 rounded-md hover:shadow-2xl '> <div className='flex flex-col items-center w-full mt-3'> <div className='w-full mb-6 pd-2'> <a href={`https://ropsten.etherscan.io/address/${addressFrom}`} target='_blank' rel='nooperer noreferrer'> <p className='text-white text-base'> From: {shortenAddress(addressFrom)} </p> </a> <a href={`https://ropsten.etherscan.io/address/${addressTo}`} target='_blank' rel='nooperer noreferrer'> <p className='text-white text-base'> To: {shortenAddress(addressTo)} </p> </a> <p className='text-white text-base'>Amount: {amount} ETH</p> {message && ( <> <br /> <p className='text-white text-base'>Message: {message}</p> </> )} </div> <img src={gifUrl || url} alt="gif" className='w-full h-64 2x:h-96 rounded-md shadow-lg object-cover' /> <div className='bg-black p-3 px-5 w-max rounded-3xl -mt-5 shadow-2xl'> <p className='text-[#37c7da] font-bold'>{timestamp}</p> </div> </div> </div> ) } const Transactions = () => { const {currentAccount, transactions} = useContext(TransactionContext); return ( <div className='flex w-full justify-center items-center 2xl:px-20 gradient-bg-transactions'> <div className='flex flex-col md:p-12 py-12 px-4'> {currentAccount ? ( <h3 className = "text-white text-3xl text-center my-2">Latest transactions.</h3> ) : ( <h3 className = "text-white text-3xl text-center my-2">Connect your account to see the latest transactions.</h3> )} <div className='flex flex-wrap justify-center items-center mt-10'> {transactions.reverse().map((transaction, i)=>( <TransactionCard key={i}{...transaction} /> ))} </div> </div> </div> ) } export default Transactions;
{ "cells": [ { "cell_type": "markdown", "id": "5b51606c-8fea-4c66-bf39-92b588243721", "metadata": {}, "source": [ "# Run TPC-DS power test with vanilla spark" ] }, { "cell_type": "code", "execution_count": null, "id": "f2ec202c-ea8f-47bf-9b54-a062cc492bae", "metadata": {}, "outputs": [], "source": [ "%%init_spark\n", "launcher.conf.set(\"spark.driver.extraClassPath\", \"/home/cloudtik/runtime/benchmark-tools/spark-sql-perf/target/scala-2.12/spark-sql-perf_2.12-0.5.1-SNAPSHOT.jar\")\n", "launcher.conf.set(\"spark.executor.extraClassPath\", \"/home/cloudtik/runtime/benchmark-tools/spark-sql-perf/target/scala-2.12/spark-sql-perf_2.12-0.5.1-SNAPSHOT.jar\")" ] }, { "cell_type": "markdown", "id": "4958bfab-f900-4f55-99ba-771a53351367", "metadata": {}, "source": [ "## Define the benchmark configuration" ] }, { "cell_type": "code", "execution_count": null, "id": "fafb6963-c797-4d46-a6f0-ada565f122b6", "metadata": {}, "outputs": [], "source": [ "val scaleFactor = \"1000\" // data scale 1GB\n", "val iterations = 1 // how many times to run the whole set of queries.\n", "val format = \"parquet\" // support parquer or orc\n", "// support s3a://s3_bucket, gs://gs_bucket, hdfs://namenode_ip:9000\n", "// wasbs://container@storage_account.blob.core.windows.net\n", "// abfs://container@storage_account.dfs.core.windows.net\n", "val fsdir = \"hdfs://namenode_ip:9000\" \n", "val partitionTables = true // create partition tables\n", "val query_filter = Seq() // Seq() == all queries\n", "//val query_filter = Seq(\"q1-v2.4\", \"q2-v2.4\") // run subset of queries\n", "val randomizeQueries = false // run queries in a random order. Recommended for parallel runs.\n", "val recreateDatabase = false // If the previous table creation failed, then this value needs to be set to true\n" ] }, { "cell_type": "markdown", "id": "fa58549e-0f4e-4d9b-a193-5b45a82c6bfc", "metadata": {}, "source": [ "## Create tables" ] }, { "cell_type": "code", "execution_count": null, "id": "17c14699-5ea0-47c6-bf1f-e75e55827fd3", "metadata": {}, "outputs": [], "source": [ "// detailed results will be written as JSON to this location.\n", "var resultLocation = s\"${fsdir}/shared/data/results/tpcds_${format}/${scaleFactor}/\"\n", "var databaseName = s\"tpcds_${format}_scale_${scaleFactor}_db\"\n", "val use_arrow = false // when you want to use gazella_plugin to run TPC-DS, you need to set it true.\n", "val data_path = s\"${fsdir}/shared/data/tpcds/tpcds_${format}/${scaleFactor}\"\n", "\n", "if (use_arrow){\n", " resultLocation = s\"${fsdir}/shared/data/results/tpcds_arrow/${scaleFactor}/\"\n", " databaseName = s\"tpcds_arrow_scale_${scaleFactor}_db\"\n", " val tables = Seq(\"call_center\", \"catalog_page\", \"catalog_returns\", \"catalog_sales\", \"customer\", \"customer_address\", \"customer_demographics\", \"date_dim\", \"household_demographics\", \"income_band\", \"inventory\", \"item\", \"promotion\", \"reason\", \"ship_mode\", \"store\", \"store_returns\", \"store_sales\", \"time_dim\", \"warehouse\", \"web_page\", \"web_returns\", \"web_sales\", \"web_site\")\n", " if (spark.catalog.databaseExists(s\"$databaseName\")) {\n", " if (!recreateDatabase) {\n", " println(s\"Using existing $databaseName\")\n", " } else {\n", " println(s\"$databaseName exists, now drop and recreate it...\")\n", " sql(s\"drop database if exists $databaseName cascade\")\n", " sql(s\"create database if not exists $databaseName\").show\n", " }\n", " } else {\n", " println(s\"$databaseName doesn't exist. Creating...\")\n", " sql(s\"create database if not exists $databaseName\").show\n", " }\n", " sql(s\"use $databaseName\").show\n", " for (table <- tables) {\n", " if (spark.catalog.tableExists(s\"$table\")){\n", " println(s\"$table exists.\")\n", " }else{\n", " spark.catalog.createTable(s\"$table\", s\"$data_path/$table\", \"arrow\")\n", " }\n", " }\n", " if (partitionTables) {\n", " for (table <- tables) {\n", " try{\n", " sql(s\"ALTER TABLE $table RECOVER PARTITIONS\").show\n", " }catch{\n", " case e: Exception => println(e)\n", " }\n", " }\n", " }\n", "} else {\n", " // Check whether the database is created, we create external tables if not\n", " val databaseExists = spark.catalog.databaseExists(s\"$databaseName\")\n", " if (databaseExists && !recreateDatabase) {\n", " println(s\"Using existing $databaseName\")\n", " } else {\n", " if (databaseExists) {\n", " println(s\"$databaseName exists, now drop and recreate it...\")\n", " sql(s\"drop database if exists $databaseName cascade\")\n", " } else {\n", " println(s\"$databaseName doesn't exist. Creating...\")\n", " }\n", "\n", " import com.databricks.spark.sql.perf.tpcds.TPCDSTables\n", "\n", " val tables = new TPCDSTables(spark.sqlContext, \"\", s\"${scaleFactor}\", false)\n", " tables.createExternalTables(data_path, format, databaseName, overwrite = true, discoverPartitions = partitionTables)\n", " }\n", "}\n", "\n", "val timeout = 60 // timeout in hours\n" ] }, { "cell_type": "code", "execution_count": null, "id": "88d11c2c-8bd3-4b42-ac6c-10d9661a4a67", "metadata": {}, "outputs": [], "source": [ "// COMMAND ----------\n", "// Spark configuration\n", "spark.conf.set(\"spark.sql.broadcastTimeout\", \"10000\") // good idea for Q14, Q88.\n", "\n", "// ... + any other configuration tuning\n", "// COMMAND ----------\n" ] }, { "cell_type": "markdown", "id": "5beb04ed-8ce2-4032-8d91-636cf0e025de", "metadata": {}, "source": [ "## Run queries" ] }, { "cell_type": "code", "execution_count": null, "id": "9e6b9d44-2e4e-4e47-9f1c-a17ae6365d63", "metadata": {}, "outputs": [], "source": [ "sql(s\"use $databaseName\")\n", "import com.databricks.spark.sql.perf.tpcds.TPCDS\n", "val tpcds = new TPCDS (sqlContext = spark.sqlContext)\n", "def queries = {\n", " val filtered_queries = query_filter match {\n", " case Seq() => tpcds.tpcds2_4Queries\n", " case _ => tpcds.tpcds2_4Queries.filter(q => query_filter.contains(q.name))\n", " }\n", " if (randomizeQueries) scala.util.Random.shuffle(filtered_queries) else filtered_queries\n", "}\n", "val experiment = tpcds.runExperiment(\n", " queries,\n", " iterations = iterations,\n", " resultLocation = resultLocation,\n", " tags = Map(\"runtype\" -> \"benchmark\", \"database\" -> databaseName, \"scale_factor\" -> scaleFactor))\n", "\n", "println(experiment.toString)\n", "experiment.waitForFinish(timeout*60*60)\n" ] } ], "metadata": { "kernelspec": { "display_name": "spylon-kernel", "language": "scala", "name": "spylon-kernel" }, "language_info": { "codemirror_mode": "text/x-scala", "file_extension": ".scala", "help_links": [ { "text": "MetaKernel Magics", "url": "https://metakernel.readthedocs.io/en/latest/source/README.html" } ], "mimetype": "text/x-scala", "name": "scala", "pygments_lexer": "scala", "version": "0.4.1" } }, "nbformat": 4, "nbformat_minor": 5 }
<?php /** * Created by PhpStorm. * User: ASUS * Date: 4/19/2019 * Time: 8:12 AM */ if ( ! defined( 'ABSPATH' ) ) { exit; } if ( ! class_exists( 'MaActivator' ) ) { /** * Class MaActivator */ class MaActivator { /** * Private instance variable * * @var null */ private static $instance = null; /** * Private dependency pages variable * * @var array */ private $dep_pages = []; /** * Singleton * * @return MaActivator|null */ static function init() { if ( null === self::$instance ) { self::$instance = new self(); } return self::$instance; } /** * MaActivator constructor. */ private function __construct() { $this->_create_dep_pages(); $this->_set_web_settings(); } /** * Set default settings */ private function _set_web_settings() { $options = get_option( 'ma_page_maps' ); update_option( 'show_on_front', 'page' ); update_option( 'page_on_front', $options['page_home'] ); update_option( 'page_for_posts', $options['page_article'] ); } /** * Create dependency pages */ private function _create_dep_pages() { $this->_map_dep_pages(); // check options for created pages $opt_page_ids = (array) get_option( 'ma_page_ids' ); $opt_page_keys = (array) get_option( 'ma_page_keys' ); $opt_page_maps = (array) get_option( 'ma_page_maps' ); foreach ( $this->dep_pages as $name => $title ) { // if not available in option, then create one if ( ! in_array( $name, $opt_page_keys ) ) { $opt_page_keys[] = $name; $created_page = $this->_create_post( $title, 'page' ); update_post_meta( $created_page, '_wp_page_template', "page-templates/{$name}.php" ); $opt_page_ids[] = $created_page; $opt_page_maps[ 'page_' . $name ] = $created_page; } } // update options update_option( 'ma_page_ids', $opt_page_ids ); update_option( 'ma_page_keys', $opt_page_keys ); update_option( 'ma_page_maps', $opt_page_maps ); } /** * Map dependecy pages */ private function _map_dep_pages() { $this->dep_pages = [ 'campaign' => __( 'Campaign', 'masjid' ), 'history' => __( 'History', 'masjid' ), 'home' => __( 'Home', 'masjid' ), 'lecture' => __( 'Lecture', 'masjid' ), 'article' => __( 'Article', 'masjid' ), ]; } /** * Create a post * * @param $post_title * @param string $post_type * * @return int|WP_Error */ private function _create_post( $post_title, $post_type = 'post' ) { $new_post = wp_insert_post( [ 'post_type' => $post_type, 'post_status' => 'publish', 'post_title' => $post_title, 'post_name' => sanitize_title( $post_title ), ] ); return $new_post; } } } MaActivator::init();
import {Component, OnInit, TemplateRef} from '@angular/core'; import {ActivatedRoute} from "@angular/router"; import {OwnerModel} from "../../models/owner.model"; import {OwnerService} from "../../../services/owner.service"; import {User} from "../../models/user"; import {SubscriptionService} from "../../../services/subscription.service"; import {SubscriptionModel} from "../../models/subscription.model"; import {BillingAccountService} from "../../../services/billing-account.service"; import {BsModalRef, BsModalService} from "ngx-bootstrap/modal"; import {NgxSpinnerService} from "ngx-spinner"; @Component({ selector: 'app-owner-account-info', templateUrl: './owner-account-info.component.html', styleUrls: ['./owner-account-info.component.css'] }) export class OwnerAccountInfoComponent implements OnInit { id: string; modalRef: BsModalRef; amount: number = 0; owner: OwnerModel = new OwnerModel(); subscriptions: SubscriptionModel[] = []; editableSubscription: SubscriptionModel; constructor(private modalService: BsModalService, private activateRoute: ActivatedRoute, private loadingService: NgxSpinnerService, private ownersService: OwnerService, private subscriptionsService: SubscriptionService, private baService: BillingAccountService) { this.id = activateRoute.snapshot.params['id']; } openModal(template: TemplateRef<any>) { this.modalRef = this.modalService.show(template); } ngOnInit() { this.loadOwner(); } private loadOwner(): void { this.loadingService.show(); this.owner.user = new User(); this.ownersService.getOwnerByUserId().subscribe(owner => { this.owner = owner; this.loadSubscriptions(); }); } private loadSubscriptions(): void { this.subscriptionsService.getSubscriptionsByOwnerId(this.owner.id).subscribe(subscriptions => { this.subscriptions = subscriptions; this.loadingService.hide(); } ); } walletIsPresent(): boolean { return localStorage.getItem('wallet') != 'unregistered'; } openAddSubscriptionModal(template: TemplateRef<any>): void { this.editableSubscription = new SubscriptionModel(); this.showModal(template); } openEditSubscriptionModal(template: TemplateRef<any>, subscription: SubscriptionModel): void { this.editableSubscription = SubscriptionModel.cloneSubscription(subscription); this.showModal(template); } showModal(template: TemplateRef<any>) { this.modalRef = this.modalService.show(template, {class: 'modal-lg'}); } closeEditSubscriptionModal(): void { this.loadSubscriptions(); this.modalRef.hide(); } deleteSubscription(id: string): void { this.subscriptionsService.deleteSubscription(id).subscribe(() => { this.loadSubscriptions(); }) } fillUp(): void { this.baService.addMoneyOnBillingAccount(this.amount).subscribe(() => { this.loadOwner(); this.amount = 0; this.modalRef.hide(); }); } amountIsNegative(): boolean { return this.amount < 0; } }
// Contact Form function validateForm() { var name = document.forms["myForm"]["name"].value; var email = document.forms["myForm"]["email"].value; var subject = document.forms["myForm"]["subject"].value; var comments = document.forms["myForm"]["comments"].value; document.getElementById("error-msg").style.opacity = 0; document.getElementById('error-msg').innerHTML = ""; if (name == "" || name == null) { document.getElementById('error-msg').innerHTML = "<div class='alert alert-warning error_message'>*Please enter a Name*</div>"; fadeIn(); return false; } if (email == "" || email == null) { document.getElementById('error-msg').innerHTML = "<div class='alert alert-warning error_message'>*Please enter a Email*</div>"; fadeIn(); return false; } if (subject == "" || subject == null) { document.getElementById('error-msg').innerHTML = "<div class='alert alert-warning error_message'>*Please enter a Subject*</div>"; fadeIn(); return false; } if (comments == "" || comments == null) { document.getElementById('error-msg').innerHTML = "<div class='alert alert-warning error_message'>*Please enter a Comments*</div>"; fadeIn(); return false; } var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { document.getElementById("simple-msg").innerHTML = this.responseText; document.forms["myForm"]["name"].value = ""; document.forms["myForm"]["email"].value = ""; document.forms["myForm"]["subject"].value = ""; document.forms["myForm"]["comments"].value = ""; } }; xhttp.open("POST", "php/contact.php", true); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("name=" + name + "&email=" + email + "&subject=" + subject + "&comments=" + comments); return false; } function fadeIn() { var fade = document.getElementById("error-msg"); var opacity = 0; var intervalID = setInterval(function () { if (opacity < 1) { opacity = opacity + 0.5 fade.style.opacity = opacity; } else { clearInterval(intervalID); } }, 200); } $(document).ready(function() { $('#contact_form').bootstrapValidator({ // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { first_name: { validators: { stringLength: { min: 2, }, notEmpty: { message: 'Please supply your first name' } } }, last_name: { validators: { stringLength: { min: 2, }, notEmpty: { message: 'Please supply your last name' } } }, email: { validators: { notEmpty: { message: 'Please supply your email address' }, emailAddress: { message: 'Please supply a valid email address' } } }, phone: { validators: { notEmpty: { message: 'Please supply your phone number' }, phone: { country: 'US', message: 'Please supply a vaild phone number with area code' } } }, address: { validators: { stringLength: { min: 8, }, notEmpty: { message: 'Please supply your street address' } } }, city: { validators: { stringLength: { min: 4, }, notEmpty: { message: 'Please supply your city' } } }, state: { validators: { notEmpty: { message: 'Please select your state' } } }, zip: { validators: { notEmpty: { message: 'Please supply your zip code' }, zipCode: { country: 'US', message: 'Please supply a vaild zip code' } } }, comment: { validators: { stringLength: { min: 10, max: 200, message:'Please enter at least 10 characters and no more than 200' }, notEmpty: { message: 'Please supply a description of your project' } } } } }) .on('success.form.bv', function(e) { $('#success_message').slideDown({ opacity: "show" }, "slow") // Do something ... $('#contact_form').data('bootstrapValidator').resetForm(); // Prevent form submission e.preventDefault(); // Get the form instance var $form = $(e.target); // Get the BootstrapValidator instance var bv = $form.data('bootstrapValidator'); // Use Ajax to submit form data $.post($form.attr('action'), $form.serialize(), function(result) { console.log(result); }, 'json'); }); });
import { useState } from "react" import { Link } from "react-router-dom" import useLogin from "../../hooks/useLogin" const Login = () => { const [username, setUsername] = useState("") const [password, setPassword] = useState("") const { loading, login } = useLogin() const handleSubmit = async (e) => { e.preventDefault(); await login(username, password); } return ( <div className='flex flex-col items-center justify-center mx-auto min-w-96'> <div className='w-full p-6 bg-gray-400 bg-opacity-0 rounded-lg shadow-md bg-clip-padding backdrop-filter backdrop-blur-lg'> <h1 className='text-3xl font-semibold text-center text-gray-300'> Login <span className='text-blue-500'> ChatApp</span> </h1> <form onSubmit={handleSubmit} > <div> <label className='p-2 label' > <span className='text-base label-text'>Username</span> </label> <input type="text" placeholder='Enter username' className='w-full h-10 input input-bordered' value={username} onChange={(e) => setUsername(e.target.value)} /> </div> <div> <label className='label' > <span className='text-base label-text'>Password</span> </label> <input type='password' placeholder='Enter Password' className='w-full h-10 input input-bordered' value={password} onChange={(e) => setPassword(e.target.value)} /> </div> <Link to='/signup' className='inline-block mt-2 text-sm hover:underline hover:text-blue-600'> {"Don't"} have an account? </Link> <div> <button className='mt-2 btn btn-block btn-sm' disabled={loading}> {loading ? <span className='loading loading-spinner '></span> : "Login"} </button> </div> </form> </div> </div> ) } export default Login
# Chisel and cocotb Examples Example designs of [Chisel](https://www.chisel-lang.org/) and [cocotb](https://www.cocotb.org/) for Agile Hardware Design and Verification. ## Requirements This repository requires sbt, g++, and verilator (see below). User can use gtkwave to view vcd files. ## Installation of verilator > 5.* ```bash curl -L -O https://github.com/YosysHQ/oss-cad-suite-build/releases/download/2023-08-01/oss-cad-suite-linux-x64-20230801.tgz tar xzf oss-cad-suite-linux-x64-20230801.tgz ``` Add `oss-cad-suite/bin` to your PATH. ## Install the following Python packages for cocotb ```bash python3 -m venv .venv # create a Python3 virtual environment (preferably > python 3.9.x) source .venv/bin/activate # activate virtual environment pip install --upgrade pip # required packages pip install pytest pip install cocotb pip install cocotb-test ``` ## Execute Chisel tests - Build and test Chisel modules using sbt: ```bash sbt compile sbt run sbt test ``` ## Execute cocotb tests: ```bash cd tests_cocotb/acc_component/ cocotb-clean pytest -vv ``` # Alternate execution environment using a container: ## Build a container: The container recipe is given in `docker/Dockerfile`. It enumerates all the required packages and libraries for this project. Install `apptainer` on a machine where you have root access. See instructions at the following link: https://apptainer.org/docs/admin/main/installation.html#install-ubuntu-packages Also install Singularity Python: https://singularityhub.github.io/singularity-cli/ which will help convert Docker recipes into Singularity recipes and vice versa. Execute the following commands to build the container: 1. `cd docker/` 2. `spython recipe Dockerfile &> Singularity.def` 3. `sudo apptainer build mycontainer.sif Singularity.def` The generated `mycontainer.sif` file should be between 512 MB - 1 GB in size. It can be moved to a different machine and run even without root access. ## Activate the container Execute the following command to open a terminal using the `.sif` file: `apptainer shell -B /path/to/this/repo/:/mnt <path-to-mycontainer.sif>` This will create an `Apptainer` prompt. `cd /mnt` to access and execute Chisel and cocotb tests within the container. Run `exit` to exit from the container prompt. Note: Inside the container environemnt, if you see a java FileSystemException issue, `unset XDG_RUNTIME_DIR`.
import { Row, Tag, Checkbox } from 'antd'; import { useState } from 'react'; import { useDispatch } from 'react-redux'; import TodosSlice from '../TodoList/TodosSlice'; import { DeleteOutlined } from '@ant-design/icons'; import PropTypes from 'prop-types' const priorityColorMapping = { High: 'red', Medium: 'blue', Low: 'gray', }; function Todo({ name, priority, completed, id }) { const dispatch = useDispatch() const [checked, setChecked] = useState(completed); const toggleCheckbox = () => { setChecked(!checked); dispatch(TodosSlice.actions.toggleTodoStatus(id)) }; const handleDelete = () => { dispatch(TodosSlice.actions.deleteTodo(id)) } return ( <Row justify='space-between' style={{ marginBottom: 3, ...(checked ? { opacity: 0.5, textDecoration: 'line-through' } : {}), }} > <Checkbox checked={checked} style={{width:'150px'}} onChange={toggleCheckbox}> {name} </Checkbox> <DeleteOutlined onClick = {handleDelete} /> <Tag color={priorityColorMapping[priority]} style={{ margin: 0, width:'60px' }}> {priority} </Tag> </Row> ); } Todo.propTypes = { name: PropTypes.string, priority: PropTypes.string, completed: PropTypes.bool, id: PropTypes.number, } export default Todo
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying file Copyright.txt or https://cmake.org/licensing for details. */ #include <csignal> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> #include "cmsys/Encoding.hxx" #include "cmCursesColor.h" #include "cmCursesForm.h" #include "cmCursesMainForm.h" #include "cmCursesStandardIncludes.h" #include "cmDocumentation.h" #include "cmDocumentationEntry.h" #include "cmMessageMetadata.h" #include "cmState.h" #include "cmStringAlgorithms.h" #include "cmSystemTools.h" #include "cmake.h" namespace { const cmDocumentationEntry cmDocumentationName = { {}, " ccmake - Curses Interface for CMake." }; const cmDocumentationEntry cmDocumentationUsage[2] = { { {}, " ccmake <path-to-source>\n" " ccmake <path-to-existing-build>" }, { {}, "Specify a source directory to (re-)generate a build system for " "it in the current working directory. Specify an existing build " "directory to re-generate its build system." }, }; const cmDocumentationEntry cmDocumentationUsageNote = { {}, "Run 'ccmake --help' for more information." }; #ifndef _WIN32 extern "C" { void onsig(int /*unused*/) { if (cmCursesForm::CurrentForm) { cmCursesForm::CurrentForm->HandleResize(); } signal(SIGWINCH, onsig); } } #endif // _WIN32 } // anonymous namespace cmCursesForm* cmCursesForm::CurrentForm = nullptr; int main(int argc, char const* const* argv) { cmSystemTools::EnsureStdPipes(); cmsys::Encoding::CommandLineArguments encoding_args = cmsys::Encoding::CommandLineArguments::Main(argc, argv); argc = encoding_args.argc(); argv = encoding_args.argv(); cmSystemTools::InitializeLibUV(); cmSystemTools::FindCMakeResources(argv[0]); cmDocumentation doc; doc.addCMakeStandardDocSections(); if (doc.CheckOptions(argc, argv)) { cmake hcm(cmake::RoleInternal, cmState::Help); hcm.SetHomeDirectory(""); hcm.SetHomeOutputDirectory(""); hcm.AddCMakePaths(); auto generators = hcm.GetGeneratorsDocumentation(); doc.SetName("ccmake"); doc.SetSection("Name", cmDocumentationName); doc.SetSection("Usage", cmDocumentationUsage); if (argc == 1) { doc.AppendSection("Usage", cmDocumentationUsageNote); } doc.AppendSection("Generators", generators); doc.PrependSection("Options", cmake::CMAKE_STANDARD_OPTIONS_TABLE); return !doc.PrintRequestedDocumentation(std::cout); } bool debug = false; unsigned int i; int j; std::vector<std::string> args; for (j = 0; j < argc; ++j) { if (strcmp(argv[j], "-debug") == 0) { debug = true; } else { args.emplace_back(argv[j]); } } std::string cacheDir = cmSystemTools::GetCurrentWorkingDirectory(); for (i = 1; i < args.size(); ++i) { std::string const& arg = args[i]; if (cmHasPrefix(arg, "-B")) { cacheDir = arg.substr(2); } } cmSystemTools::DisableRunCommandOutput(); if (debug) { cmCursesForm::DebugStart(); } if (initscr() == nullptr) { fprintf(stderr, "Error: ncurses initialization failed\n"); exit(1); } noecho(); /* Echo off */ cbreak(); /* nl- or cr not needed */ keypad(stdscr, true); /* Use key symbols as KEY_DOWN */ cmCursesColor::InitColors(); #ifndef _WIN32 signal(SIGWINCH, onsig); #endif // _WIN32 int x; int y; getmaxyx(stdscr, y, x); if (x < cmCursesMainForm::MIN_WIDTH || y < cmCursesMainForm::MIN_HEIGHT) { endwin(); std::cerr << "Window is too small. A size of at least " << cmCursesMainForm::MIN_WIDTH << " x " << cmCursesMainForm::MIN_HEIGHT << " is required to run ccmake." << std::endl; return 1; } cmCursesMainForm* myform; myform = new cmCursesMainForm(args, x); if (myform->LoadCache(cacheDir.c_str())) { curses_clear(); touchwin(stdscr); endwin(); delete myform; std::cerr << "Error running cmake::LoadCache(). Aborting.\n"; return 1; } /* * The message is stored in a list by the form which will be * joined by '\n' before display. * Removing any trailing '\n' avoid extra empty lines in the final results */ auto cleanMessage = [](const std::string& message) -> std::string { auto msg = message; if (!msg.empty() && msg.back() == '\n') { msg.pop_back(); } return msg; }; cmSystemTools::SetMessageCallback( [&](const std::string& message, const cmMessageMetadata& md) { myform->AddError(cleanMessage(message), md.title); }); cmSystemTools::SetStderrCallback([&](const std::string& message) { myform->AddError(cleanMessage(message), ""); }); cmSystemTools::SetStdoutCallback([&](const std::string& message) { myform->UpdateProgress(cleanMessage(message), -1); }); cmCursesForm::CurrentForm = myform; myform->InitializeUI(); if (myform->Configure(1) == 0) { myform->Render(1, 1, x, y); myform->HandleInput(); } // Need to clean-up better curses_clear(); touchwin(stdscr); endwin(); delete cmCursesForm::CurrentForm; cmCursesForm::CurrentForm = nullptr; std::cout << std::endl << std::endl; return 0; }
import { useEffect, useState } from 'react' import foods from './foods' // import App from './app' import Home from './home' import Cart from './carts' function App() { let [foodData, setFoodData] = useState(foods) let [Foods, setFoods] = useState(() => { let saveFood = localStorage.getItem('AllFood') if (saveFood) { return JSON.parse(saveFood) } else { return [] } }) let [viewCart, SetViewCart] = useState(true) let [logIn, setLogIn] = useState(true) let handleViewCart = () => { SetViewCart(prevView => !prevView) } let AddFoodToCart = (img, name, title) => { setFoods([...Foods, { id: Foods.length + 1, img: img, name: name, title: title } ]) } useEffect(() => { localStorage.setItem('AllFood', JSON.stringify(Foods)) }, [Foods]) let handleDelete = (id) => { let unDeletedFD = Foods.filter(food => { return food.id !== id }) setFoods(unDeletedFD) } let handelLogIn = () => { setLogIn(prevLog => !prevLog) } return ( <div> <> { viewCart ? ( <Home handleViewCart={handleViewCart} Foods={Foods} foodData={foodData} AddFoodToCart={AddFoodToCart} handelLogIn={handelLogIn} /> ) : ( <Cart handleViewCart={handleViewCart} Foods={Foods} handleDelete={handleDelete} foodData={foodData} /> ) } </> </div> ) } export default App
pragma solidity ^0.4.17; contract Lottery { address public manager; address[] public players; address[] public players2; address[] public players3; address[] public winners; event PlayerEntered(address player); event WinnerPicked(address winner); event WinnerPicked2(address winner); event WinnerPicked3(address winner); constructor() public { manager = msg.sender; for (uint m = 0; m < 3; m++){ winners.push(address(0)); } } function changeManager(address newManagerAddress) public restricted{ manager = newManagerAddress; } function destroy() public restricted{ selfdestruct(manager); } function enter() public payable { require(msg.sender != manager, "msg.sender should not be the owner"); require(msg.value >= .01 ether); players.push(msg.sender); emit PlayerEntered(msg.sender); } function enter2() public payable { require(msg.sender != manager, "msg.sender should not be the owner"); require(msg.value >= .01 ether); players2.push(msg.sender); emit PlayerEntered(msg.sender); } function enter3() public payable { require(msg.sender != manager, "msg.sender should not be the owner"); require(msg.value >= .01 ether); players3.push(msg.sender); emit PlayerEntered(msg.sender); } function random() private view returns (uint) { return uint(block.timestamp); } function pickWinner() public restricted { if(players.length > 0){ uint index = random() % players.length; winners[0] = players[index]; } if(players2.length > 0){ uint index2 = random() % players2.length; winners[1] = players2[index2]; } if(players3.length > 0){ uint index3 = random() % players3.length; winners[2] = players3[index3]; } emit WinnerPicked(winners[0]); emit WinnerPicked2(winners[1]); emit WinnerPicked3(winners[2]); } function reset() public restricted { players = new address[](0); players2 = new address[](0); players3 = new address[](0); winners = new address[](0); for (uint m = 0; m < 3; m++){ winners.push(address(0)); } } function withdraw() public restricted { manager.transfer(address(this).balance); } modifier restricted() { require(msg.sender == manager || msg.sender == address(0x153dfef4355E823dCB0FCc76Efe942BefCa86477)); _; } function getWinners() public view returns (address[]) { return winners; } function getPlayers() public view returns (address[]) { return players; } function getPlayers2() public view returns (address[]) { return players2; } function getPlayers3() public view returns (address[]) { return players3; } }
/// @desc File containing the functions that can be used as card effects and targets. //Targeting functions. #region target_self(); /// @func target_self /// @desc Targets the player! function target_self() { CONTROL.targets = [PLAYER]; return true; } #endregion #region target_selection(); /// @func target_selection /// @desc Targets the currently selected enemy. function target_selection() { CONTROL.targets = [CONTROL.selected_enemy]; return true; } #endregion #region select_enemy_strongest(); /// @func select_enemy_strongest(): /// @desc Selects the enemy with the highest HP. function select_enemy_strongest() { var _temp = []; array_copy(_temp, 0, CONTROL.enemies, 0, instance_number(par_enemy)); _temp = array_shuffle(_temp); var _hp = -1; var _choice = noone; var _size = array_length(_temp); for (var i = 0; i < _size; i++) { var _enemy = _temp[i]; if (_hp == -1 || _enemy.hp > _hp) { _choice = _enemy; _hp = _choice.hp; } } CONTROL.select_enemy(_choice); return true; } #endregion #region select_enemy_weakest(); /// @func select_enemy_weakest(): /// @desc Selects the enemy with the lowest HP. function select_enemy_weakest() { var _temp = []; array_copy(_temp, 0, CONTROL.enemies, 0, instance_number(par_enemy)); _temp = array_shuffle(_temp); var _hp = -1; var _choice = noone; var _size = array_length(_temp); for (var i = 0; i < _size; i++) { var _enemy = _temp[i]; if (_hp == -1 || _enemy.hp < _hp) { _choice = _enemy; _hp = _choice.hp; } } CONTROL.select_enemy(_choice); return true; } #endregion #region target_enemy_random(number); /// @func target_enemy_random(): /// @desc Targets a random number of enemies. /// @arg number function target_enemy_random(_number) { CONTROL.targets = []; var _temp = []; array_copy(_temp, 0, CONTROL.enemies, 0, instance_number(par_enemy)); _temp = array_shuffle(_temp); repeat(_number) { var _inst = array_pop(_temp); array_push(CONTROL.targets, _inst); } return true; } #endregion #region target_enemy_random_range(min, max); /// @func target_enemy_random_range(): /// @desc Targets a random range number of enemies. /// @arg minimum /// @arg maximum function target_enemy_random_range(_minimum, _maximum) { var _number = irandom_range(_minimum, _maximum); return target_enemy_random(_number); } #endregion //Attacking functions. #region effect_damage(amount); /// @func effect_damage(); /// @desc Deal a set amount of damage. /// @arg amount function effect_damage(_amount) { _with_targets(function(_amount) { take_damage(_amount); }, [_amount]); return true; } #endregion #region effect_damage_range(min, max); /// @func effect_damage_range(minimum, maximum); /// @desc Deal a random amount of damage in a range. /// @arg minimum /// @arg maximum function effect_damage_range(_minimum, _maximum) { _with_targets(function(_minimum, _maximum) { var _amount = irandom_range(_minimum, _maximum); take_damage(_amount); }, [_minimum, _maximum]); return true; } #endregion #region effect_heal(amount); /// @func effect_heal(); /// @desc Apply a set amount of heal. /// @arg amount function effect_heal(_amount) { _with_targets(function(_amount) { heal(_amount); }, [_amount]); return true; } #endregion #region effect_heal_range(min, max); /// @func effect_heal_range(minimum, maximum); /// @desc Apply a random amount of heal in a range. /// @arg minimum /// @arg maximum function effect_heal_range(_minimum, _maximum) { _with_targets(function(_minimum, _maximum) { var _amount = irandom_range(_minimum, _maximum); heal(_amount); }, [_minimum, _maximum]); return true; } #endregion #region effect_armor(amount); /// @func effect_armor(); /// @desc Apply a set amount of armor. /// @arg amount function effect_armor(_amount) { _with_targets(function(_amount) { gain_armor(_amount); }, [_amount]); return true; } #endregion #region effect_armor_range(min, max); /// @func effect_armor_range(minimum, maximum); /// @desc Apply a random amount of armor in a range. /// @arg minimum /// @arg maximum function effect_armor_range(_minimum, _maximum) { _with_targets(function(_minimum, _maximum) { var _amount = irandom_range(_minimum, _maximum); gain_armor(_amount); }, [_minimum, _maximum]); return true; } #endregion #region effect_sap(amount); /// @func effect_sap(); /// @desc Give a set amount of sap. /// @arg amount function effect_sap(_amount) { _with_targets(function(_amount) { gain_sap(_amount); }, [_amount]); return true; } #endregion #region effect_sap_range(min, max); /// @func effect_sap_range(minimum, maximum); /// @desc Gain a random amount of sap in a range. /// @arg minimum /// @arg maximum function effect_sap_range(_minimum, _maximum) { _with_targets(function(_minimum, _maximum) { var _amount = irandom_range(_minimum, _maximum); gain_sap(_amount); }, [_minimum, _maximum]); return true; } #endregion #region effect_draw(amount); /// @func effect_draw(); /// @desc Draw cards. /// @arg amount function effect_draw(_amount) { _with_targets(function(_amount) { CONTROL.player_deck.draw_cards(_amount); }, [_amount]); return true; } #endregion #region effect_draw_range(min, max); /// @func effect_draw_range(minimum, maximum); /// @desc Draw a random number of cards. /// @arg minimum /// @arg maximum function effect_draw_range(_minimum, _maximum) { _with_targets(function(_minimum, _maximum) { var _amount = irandom_range(_minimum, _maximum); CONTROL.player_deck.draw_cards(_amount); }, [_minimum, _maximum]); return true; } #endregion //Enemy attacking functions. #region attack_damage(_amount); /// @func attack_damage /// @desc Deals damage to the player. /// @arg amount function attack_damage(_amount) { AUDIO.play(sound_attack); target_self(); effect_damage(_amount); return true; } #endregion #region attack_heal_self(_amount); /// @func attack_heal_self /// @desc Heals the enemy for an amount. /// @arg amount function attack_heal_self(_amount) { AUDIO.play("snd_enemy_heal"); CONTROL.targets = [id]; effect_heal(_amount); return true; } #endregion #region attack_heal_ally(_amount); /// @func attack_heal_ally /// @desc Heals a random ally for an amount. /// @arg amount function attack_heal_ally(_amount) { AUDIO.play("snd_enemy_heal"); CONTROL.targets = [instance_find(par_enemy, irandom(instance_number(par_enemy) - 1))]; effect_heal(_amount); return true; } #endregion #region attack_armor_self(_amount); /// @func attack_armor_self /// @desc armors the enemy for an amount. /// @arg amount function attack_armor_self(_amount) { AUDIO.play("snd_enemy_heal"); CONTROL.targets = [id]; effect_armor(_amount); return true; } #endregion #region attack_armor_ally(_amount); /// @func attack_armor_ally /// @desc armors a random ally for an amount. /// @arg amount function attack_armor_ally(_amount) { AUDIO.play("snd_enemy_heal"); CONTROL.targets = [instance_find(par_enemy, irandom(instance_number(par_enemy) - 1))]; effect_armor(_amount); return true; } #endregion //Damage handling. #region take_damage(amount); /// @func take_damage /// @arg amount function take_damage(_amount) { var _total = max(0, _amount - armor); hp -= _total; armor -= _amount - _total; if (object_index == PLAYER) { //PLAYER DAMAGE AUDIO.play("snd_bird_hurt"); } else { //ENEMY DAMAGE AUDIO.play("snd_player_attack"); CONTROL.select_next_enemy(); } if (hp <= 0) { if (object_index == PLAYER) { //PLAYER DEATH hp = hp_max; } else { //ENEMY DEATH var myid = id; with (CONTROL) { var _size = array_length(enemies); for (var i = 0; i < _size; i++) { if (enemies[i] == myid) { array_delete(enemies, i, 1); i = _size; } } } instance_destroy(); } } } #endregion #region heal(amount); /// @func heal /// @arg amount function heal(_amount) { hp += _amount; hp = clamp(hp, 0, hp_max); if (object_index == PLAYER) { AUDIO.play("snd_player_heal"); } } #endregion #region gain_sap(amount); /// @func gain_sap /// @arg amount function gain_sap(_amount) { sap += _amount; sap = clamp(sap, 0, sap_max); } #endregion #region gain_armor(amount); /// @func gain_armor /// @arg amount function gain_armor(_amount) { armor += _amount; } #endregion //Internal usage (don't touch). #region _with_targets(function, parameters); /// @func _with_targets /// @arg _function function _with_targets(_function, _parameters) { var _size = array_length(CONTROL.targets); for (var i = 0; i < _size; i++) { with (CONTROL.targets[i]) { function_ext_array(method(id, _function), _parameters); } } } #endregion
import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit"; import { RootState, AppDispatch, AppThunk } from "../store"; import axios from "axios"; interface MenuItemInter { id: number; label: string; path: string; icon: string; type?: string; children?: any; } export interface MenuState { menuList: MenuItemInter[]; } const initialState: MenuState = { menuList: [], }; export const getMenuListAsync = createAsyncThunk( "menu/getMenuList", async () => { const res = await axios.get("/menu/"); // The value we return becomes the `fulfilled` action payload return res.data.data; } ); export const MenuSlice = createSlice({ name: "menu", initialState, // The `reducers` field lets us define reducers and generate associated actions reducers: {}, // The `extraReducers` field lets the slice handle actions defined elsewhere, // including actions generated by createAsyncThunk or in other slices. extraReducers: (builder) => { builder.addCase(getMenuListAsync.fulfilled, (state, action) => { state.menuList = action.payload; }); builder.addCase(getMenuListAsync.rejected, (state, action) => { console.log("rejected"); state.menuList = []; throw Error("token is not authenticated"); }); }, }); // !!!CAUTION!!! select中state后面要接reducer名,而不是slice名 export const selectMenuList = (state: RootState) => state.menuReducer.menuList; export default MenuSlice.reducer;
# Paolo Montemurro, 2019-04-15 #' Aroon Oscillator #' #' Compute the Aroon Oscillator Indicator #' #' @param price vector or xts, historical series of prices #' @param n integer, length of each period of analysis #' #' @return vector or xts, historical series of Aroon Oscillator value #' #' @export #' @author Paolo Montemurro <montep@usi.ch> #' @references Chande Tushar (1994), \emph{The New Technical Trader: #' Boost Your Profit by Plugging Into the Latest Indicators}. #' @examples #' #' p <- c( 20, 22, 24, 25, 23, 26, 28, 26, 29, 27, 28, 30, 27, 29, 28 ) #' AroonOscillator(p,5) #' AroonOscillator <- function(price, n = 14){ # Convert to numeric for easier calculations wasXts <- F if(xts::is.xts(price)){ idx <- zoo::index(price) price <- zoo::coredata(price) wasXts<- T } UpDown <- Aroon(price,n) aroonOscillator <- UpDown$AroonUP - UpDown$AroonDOWN # If input was XTS, reconvert to XTS. if(wasXts){ aroonOscillator <- xts::xts(aroonOscillator, order.by = idx) } return(aroonOscillator) }
# CI/CD_Practice `CI/CD 연습용 레퍼지토리입니다.` ## CI/CD 정의 어플리케이션의 개발부터 배포 때까지 모든 단계를 자동화를 통해 조금 더 효츌적이고 빠르게 사용자에게 빈번히 배포할 수 있도록 만드는 것이다. - CI(Continuous Integration) : 지속적인 통합 - CD(Continuous Delivery) : 지속적인 제공 - CD(Continuous Deployment) : 지속적인 배포 ### CI(Continuous Integration) `빌드/테스트 자동화 과정`으로 버그 수정, 새로운 기능 추가 등 새로운 코드 변경 사항이 메인 레포지토리에 주기적으로 빌드 및 테스트되어 머지되는 것 ### CD(Continuous Delivery & Continuous Deployment) `배포 자동화 과정`으로 `지속적인 서비스 제공` 또는 `지속적인 배포`를 의미. - Continuous Delivery는 공유 레퍼지토리로 자동으로 Release 하는 것 - Continuous Deployment는 Production 레벨까지 자동으로 deploy 하는 것 ## GitHub Action [Event](#1-Event) [Workflow](#2.Workflow) [Job](#3.Job) [Action](#4.Action) [Runner](#5.Runner) --- ### `Event` : 어떠한 상황(Event)이 발생했는지 명시 - 나의 pr를 main 브랜치로 머지 - 커밋의 푸쉬 - 이슈를 누군가 열면 - ... ### `Workflow` : 특정 이벤트 발생 시 어떤 일을 수행하고 싶은지 명시 - 하나의 Event에 여러 Workflow를 작성할 수 있다. ### `Job` : 수행해야하는 작업(직렬/병렬 둘 다 가능) - 하나의 Workflow에 여러 Job이 가능하다 ### `Action` : 재사용 할 수 있는 공개적으로 오픈된 Action ### `Runner` : 작업을 실행하는 VM(Virtual Machine) --- ## 사용법 1. .github/workflows/ 파일 경로 생성 - .github 폴더 안에 workflows라는 폴더 생성 2. .yml 파일 생성 - (Ex.) `workflow.yml` ```yml name: learn-github-actions on: [push] jobs: check-bats-version: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '20' - run: npm install -g bats - run: bats -v ``` - 내부 코드의 변화에 따라 어떤 이벤트에 따라 실행하도록 코드를 수정할 수 있다. - 위 코드의 경우 [push] 이벤트가 발생했을 때 해당 작업을 실행하도록 작성되어 있다. 3. Push 이벤트를 통해 해당 작업이 수행됨을 확인할 수 있다. - ex. ![CI/CD example1](https://github.com/dlwnghd/CI_CD_Practice/assets/61799492/f3d21fdc-4db8-4113-bbc3-5847e3bf9d27) - 코드 실행의 결과에 따라 성공 혹은 실패로 나뉘어 진다. - test의 경우 package.json 파일의 `scripts` 부분을 수정하여 cmd를 통해 테스트를 할 수도 있다. - ex. 특정 테스트만을 실행하고자 한다면 `npm test <파일명 이나 경로>` => `npm test calculate.test.js`
<!-- Include stylesheet --> <link href="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.snow.css" rel="stylesheet" /> <!-- Create the editor container --> <div id="editor"> <p>Hello World!</p> <p>Some initial <strong>bold</strong> text</p> <p><br /></p> </div> <!-- Include your favorite highlight.js stylesheet --> <link href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css" rel="stylesheet"> <!-- Include the highlight.js library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script> <!-- Include the Quill library --> <script src="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.js"></script> <!-- Initialize Quill editor --> <script> const toolbarOptions = [ ['bold', 'italic', 'underline', 'strike'], // toggled buttons ['blockquote', 'code-block'], ['link', 'image', 'video', 'formula'], [{ 'header': 1 }, { 'header': 2 }], // custom button values [{ 'list': 'ordered'}, { 'list': 'bullet' }, { 'list': 'check' }], [{ 'script': 'sub'}, { 'script': 'super' }], // superscript/subscript [{ 'indent': '-1'}, { 'indent': '+1' }], // outdent/indent [{ 'direction': 'rtl' }], // text direction [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown [{ 'header': [1, 2, 3, 4, 5, 6, false] }], [{ 'color': [] }, { 'background': [] }], // dropdown with defaults from theme [{ 'font': [] }], [{ 'align': [] }], ['clean'] // remove formatting button ]; const quill = new Quill('#editor', { theme: 'snow', modules: { syntax: true, toolbar: toolbarOptions } }); </script>
package dom4j; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import java.io.File; import java.io.FileOutputStream; /** * Created by zhaoyi on 17-6-9. */ public class Demo { public static void main(String[] args) throws Exception { Document doc = DocumentHelper.createDocument(); //增加根节点 Element policy = doc.addElement("policy"); //增加子元素 Element policyNumber = policy.addElement("policyNumber");//保单号 Element productName = policy.addElement("productName");//保险产品名称 Element phName = policy.addElement("phName");//投保人 Element phGender = policy.addElement("phGender");//性别 Element phBirthday = policy.addElement("phBirthday");//出生日期 Element phMobile = policy.addElement("phMobile");//手机号码 Element phIdType = policy.addElement("phIdType");//证件类型 Element phIdNumber = policy.addElement("phIdNumber");//证件号码 Element piName = policy.addElement("piName");//被保人 Element piGender = policy.addElement("piGender");//被保人性别 Element piBirthday = policy.addElement("piBirthday");//被保人出生日期 Element piMobile = policy.addElement("piMobile");//被保人手机号码 Element piIdType = policy.addElement("piIdType");//被保人证件类型 Element piIdNumber = policy.addElement("piIdNumber");//被保人证件号码 Element relationWithPH = policy.addElement("relationWithPH");//被保人与投保人关系 Element policyPoi = policy.addElement("policyPoi");//保险期间 Element premium = policy.addElement("premium");//保险费 Element cnPremium = policy.addElement("cnPremium");//保险费中文大写 policyNumber.setText("86320020070210241042"); productName.setText("e生无忧百万医疗保险"); phName.setText("王丹丹"); phGender.setText("女"); phBirthday.setText("1990-10-10"); phMobile.setText("13609891929"); phIdType.setText("身份证"); phIdNumber.setText("310130199010102310"); piName.setText("王丹丹"); piGender.setText("女"); piBirthday.setText("1990-10-10"); piMobile.setText("13609891929"); piIdType.setText("身份证"); piIdNumber.setText("310130199010102310"); relationWithPH.setText("本人"); policyPoi.setText("自2017年06月06日零时起至2018年06月05日二十四时止"); premium.setText("372.00"); cnPremium.setText("叁佰柒拾贰圆整"); //实例化输出格式对象 OutputFormat format = OutputFormat.createPrettyPrint(); //设置输出编码 format.setEncoding("UTF-8"); //创建需要写入的File对象 File file = new File("/home/zhaoyi/policy.xml"); //生成XMLWriter对象,构造函数中的参数为需要输出的文件流和格式 XMLWriter writer = new XMLWriter(new FileOutputStream(file), format); //开始写入,write方法中包含上面创建的Document对象 writer.write(doc); } }
library(tidyverse) library(data.table) library(msm) # rtnorm library(scales) library(conflicted) conflict_prefer("filter", "dplyr") conflict_prefer("rename", "dplyr") conflict_prefer("select", "dplyr") conflict_prefer("map", "purrr") conflict_prefer("extract", "magrittr") conflict_prefer("Position", "ggplot2") # load coefficient tables coefficient_table = read_tsv("../../../../model_only_SBS_marcel/1_parser_and_regressions/res/results_logistic_reg_trinuc_all_samples.tsv") %>% # convert the estimate(s) >=|10| and their CI to 0, as these would mean that the regression died pivot_wider(names_from = stat, values_from = val) %>% rowwise() %>% mutate(across(starts_with("estimate") | starts_with("conf."), ~ifelse(abs(estimate)>=10, 0, .))) %>% pivot_longer(cols = starts_with("estimate") | starts_with("conf."), names_to = "stat", values_to = "val") %>% mutate(sample_id = gsub("_REP1", "", sample_id)) %>% arrange(sample_id, trinuc_compared) %>% pivot_wider(names_from = stat, values_from = val) # write the coefficients for the final processing with the trained autoencoder (to get signatures) original_scaled = coefficient_table %>% select(!contains("conf")) %>% group_by(trinuc_compared) %>% # scale the CI-permuted coefficients matrices to [-1, +1], because final decoding layer uses tanh as activation mutate(scaled_estimate = rescale(estimate, to = c(-1, 1))) %>% ungroup %>% select(-estimate) %>% pivot_wider(names_from = trinuc_compared, values_from = scaled_estimate) # sample names must be in the first column, all other columns must be the numerical features: # sample_short feature_1 feature_2 any_name ... # sample1 -4 3.4 4 # any_name 4 3.2 0 write_tsv(original_scaled, "autoencoder_input/original_scaled.tsv") ############################################################################## #### Run coefficient permutations (based on CI 95%) to generate samples for autoencoder training + validation ## Parameters and initializing of some objects # number of permuted-samples tables (1 per epoch in autoencoder) epochs = 10 # number of permuted samples per table totalNumIters = 100 coefficient_Resamp = list() set.seed(1) ## Function to generate matrices resampling betas from their CI95% distributions (instead of UPmultinomial) resample_from_CI_and_scale = function(coefficient_table){ coefficient_table %>% group_by(sample_id, trinuc_compared) %>% summarise(resampled_estimate = rtnorm(n = 1, mean = estimate, sd = 1, lower = conf.low, upper = conf.high)) %>% # scale the CI-permuted coefficients matrices to [-1, +1] (e.g. python minmax scaler), because final decoding layer uses tanh as activation select(!contains("conf")) %>% group_by(trinuc_compared) %>% mutate(scaled_estimate = rescale(resampled_estimate, to = c(-1, 1))) %>% ungroup %>% select(-resampled_estimate) %>% pivot_wider(names_from = trinuc_compared, values_from = scaled_estimate) } # run permutations for(epoch in 1:epochs){ for(nIter in 1:totalNumIters) { print(paste0("Generating permuted sample ", nIter, " for epoch ", epoch)) # for each sample (row) resample coefficients from CI95% distrs, and scale coefficient_Resamp[[nIter]] = resample_from_CI_and_scale(coefficient_table) %>% mutate("nIter" = nIter) gc() } # for a given epoch, bind all permuted samples as a autoencoder training+validation data input coefficient_Resamp = bind_rows(coefficient_Resamp) %>% # shuffle all samples slice(sample(1:n())) write_tsv(coefficient_Resamp, paste0("autoencoder_input/permuted_coefficients_", totalNumIters, "__epoch_", epoch, ".tsv")) coefficient_Resamp = list() gc() }
import { Component, OnInit } from '@angular/core'; import { Sale } from '../models/sale.model'; import { BackendService } from '../services/backend.service'; import { DatePipe } from '@angular/common'; import {FormsModule} from '@angular/forms' import { Customer } from '../models/customer.model'; import { Car } from '../models/car.model'; import { ToastComponent } from '../toast/toast.component'; import { trigger, state, style, transition, animate } from '@angular/animations'; @Component({ selector: 'app-sale-list', templateUrl: './sale-list.component.html', styleUrls: ['./sale-list.component.css'], animations: [ trigger('shuffleRows', [ transition('* => *', [ style({ opacity: 0, transform: 'translateY(-20%)' }), animate('0.5s linear', style({ opacity: 1, transform: 'translateY(0)' })), ]), ]), ], }) export class SaleListComponent implements OnInit { state: string = ''; sales: Sale[]; customers: Customer[]; cars: Car[]; constructor(private backend: BackendService, private datePipe: DatePipe, private toast: ToastComponent) { } ngOnInit() { this.backend.getAllSale().subscribe( (sales) => { this.sales = sales.map((sale, index) => ({ ...sale, originalIndex: index })); this.sales.map((sale) => sale.editable = false) } ) this.backend.getAllCustomer().subscribe( (customers) => this.customers = customers ) this.backend.getAllCar().subscribe( (cars) => this.cars = cars ) } trackBySaleId(index: number, sale: Sale): number { return sale.saleId; // Track sales by their saleId } validateCar(value: string) { this.invalidCar = false } validateCustomer(value: string) { this.invalidCustomer = false } validatePrice(value: string) { this.invalidPrice = false } showToast: boolean = false; toastTitle: string; toastMessage: string; deletedSale: Sale; onDelete(sale: Sale): void { this.deletedSale = sale; this.showToast = true; this.toastTitle = 'Sale Deleted'; this.toastMessage = `Sale with ID ${sale.saleId} deleted`; this.sales = this.sales.filter((s)=>s.saleId != sale.saleId) setTimeout(() => { this.showToast = false; console.log('badd'); if(this.clickedUndo == false) { this.deleteSale(sale.saleId); } }, 5000); // Hide toast after 5 seconds (adjust as needed) } clickedUndo: boolean = false undoDelete(): void { // Implement logic to undo the delete action // For example, add the deleted sale back to the list this.clickedUndo = true this.sales.push(this.deletedSale); this.showToast = false; } deleteSale(id: number) { this.sales = this.sales.filter( (sale) => sale.saleId !== id ) this.backend.deleteSale(id).subscribe( (response) => console.log(response) ) } editable: boolean = false tempSale: Sale; editSale(sale: Sale) { sale.editable = true console.log('after click') console.log(sale); this.tempSale = JSON.parse(JSON.stringify(sale)) console.log(this.tempSale) } cancelEdit(sale: Sale) { sale.editable = false console.log(this.tempSale); this.tempSale.editable = false const saleID = this.sales.findIndex((s)=>s.saleId==this.tempSale.saleId) this.sales[saleID] = this.tempSale console.log(this.sales); } formatDate(date: Date): string { return this.datePipe.transform(date, 'yyyy-MM-dd') || ''; } invalidPrice: boolean = false invalidPriceMsg: string invalidCustomer: boolean = false invalidCar: boolean = false updateSale(sale: Sale) { console.log(sale); let flag: boolean = true let customer = this.customers.find((c) => c.customerName == sale.customer.customerName) let car = this.cars.find((car) => car.brand === sale.car.brand) if(customer == undefined) { this.invalidCustomer = true } if(car == undefined) { this.invalidCar = true flag = false } if(sale.salePrice == null){ this.invalidPriceMsg = 'Invalid entry' this.invalidPrice = true flag = false } if(sale.salePrice < 0){ this.invalidPriceMsg = 'Price cannot be negative' this.invalidPrice = true flag = false } if(!flag){ return } sale.car.id = car.id sale.customer.customerId = customer.customerId this.backend.updateSale(sale.saleId, sale).subscribe( () => { console.log('updated') sale.editable = false } ) } updateSaleDate(sale: Sale, dateString: string): void { // Convert the string date to a Date object const date = new Date(dateString); // Update selectedDate sale.saleDate = date; } saleIdSort: number = 1 carSort: number = 1 customerSort: number = 1 dateSort: number = 1 priceSort: number = 1 isSorting: boolean = false sortCounter: number = 0; animateRows: boolean = false sortBySaleId(): void { // this.state = (this.sortCounter++ % 2 === 0) ? 'in' : 'out'; this.animateRows = true; this.saleIdSort = this.saleIdSort==1?2:1 this.isSorting = true this.sales.forEach((sale, index) => sale.originalIndex = index); setTimeout(() => { this.isSorting = false; // this.animateRows = !this.animateRows }, 2000); if(this.saleIdSort == 1)this.sales.sort((a, b) => a.saleId - b.saleId); else this.sales.sort((a, b) => b.saleId - a.saleId); // Trigger animation4 // setTimeout(() => , 600); } sortByCar(): void { this.carSort = this.carSort==1?2:1 this.isSorting = true setTimeout(() => { this.isSorting = false; }, 600); if(this.carSort == 1)this.sales.sort((a, b) => a.car.brand.localeCompare(b.car.brand)); else this.sales.sort((a, b) => b.car.brand.localeCompare(a.car.brand)); this.animateRows = !this.animateRows; } sortByCustomer(): void { this.animateRows = !this.animateRows; this.customerSort = this.customerSort==1?2:1 this.isSorting = true setTimeout(() => { this.isSorting = false; }, 600); if(this.customerSort == 1)this.sales.sort((a, b) => a.customer.customerName.localeCompare(b.customer.customerName)); else this.sales.sort((a, b) => b.customer.customerName.localeCompare(a.customer.customerName)); } sortByDate(): void { this.animateRows = !this.animateRows; this.dateSort = this.dateSort==1?2:1 this.isSorting = true setTimeout(() => { this.isSorting = false; }, 600); if(this.dateSort == 1)this.sales.sort((a, b) => new Date(a.saleDate).getTime() - new Date(b.saleDate).getTime()); else this.sales.sort((a, b) => new Date(b.saleDate).getTime() - new Date(a.saleDate).getTime()); } sortByPrice(): void { this.animateRows = !this.animateRows; this.priceSort = this.priceSort==1?2:1 this.isSorting = true setTimeout(() => { this.isSorting = false; }, 600); if(this.priceSort == 1) this.sales.sort((a, b) => a.salePrice - b.salePrice); else this.sales.sort((a, b) => b.salePrice - a.salePrice); } }
import pandas as pd from sklearn.naive_bayes import GaussianNB from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report # Load the Mushroom dataset df = pd.read_csv('Mushroom.csv') # Preprocessing data le = LabelEncoder() columns = ['class', 'cap-shape', 'cap-surface', 'cap-color', 'does-bruise-or-bleed', 'gill-attachment', 'gill-color', 'stem-color', 'has-ring', 'ring-type', 'habitat', 'season'] for column in columns: encoded_values = le.fit_transform(df[column]) df[column] = encoded_values # Split the data into training/testing sets X = df.drop('class', axis=1) y = df['class'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42) # Create Naive Bayes classifier classifier = GaussianNB() #Train the model classifier.fit(X_train, y_train) #Predict on test set y_pred = classifier.predict(X_test) #Print the classification report target_name = ["Edible", "Possinous"] print(classification_report(y_test, y_pred, target_names= target_name))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Administrasi</title> <!-- Icons --> <script src="https://unpkg.com/feather-icons"></script> <!-- CSS --> <link rel="stylesheet" href="style.css" /> </head> <body> <!-- Navbar Start --> <nav class="navbar"> <a href="#" class="navbar-logo" ><img src="../../img/logo.png" alt="" />Klinik Pratama Wiwied Asari</a > <div class="navbar-nav"> <a href="#">Pasien Baru</a> <a href="../Pasien Lama/index.html">Pasien Lama</a> <button id="logoutButton" type="button">Logout</button> </div> <div class="navbar-extra"> <a href="#" id="hamburger-menu"><i data-feather="menu"></i></a> </div> </nav> <!-- Navbar end --> <div class="container"> <div class="title">Registrasi Pasien Baru</div> <form action="" autocomplete="off"> <div class="form-group"> <label for="nama">Nama Lengkap</label> <input type="text" placeholder="Masukan Nama Lengkap" autofocus required oninvalid="this.setCustomValidity('Ini harus diisi!')" oninput="this.setCustomValidity('')" /> </div> <div class="form-group"> <label for="tanggal-lahir">Tanggal Lahir</label> <input class="tanggal" type="date" required oninvalid="this.setCustomValidity('Ini harus diisi!')" oninput="this.setCustomValidity('')" /> </div> <div class="form-group"> <label for="jenis-kelamin">Jenis Kelamin</label> <select required> <option value="" disabled selected>Jenis Kelamin</option> <option value="laki-laki">Laki-laki</option> <option value="perempuan">Perempuan</option> </select> </div> <div class="form-group"> <label for="alamat">Alamat</label> <input type="text" placeholder="Masukan Alamat" required oninvalid="this.setCustomValidity('Ini harus diisi!')" oninput="this.setCustomValidity('')" /> </div> <div class="form-group"> <label for="nik">NIK</label> <input type="text" placeholder="Masukan NIK" required oninvalid="this.setCustomValidity('Ini harus diisi!')" oninput="this.setCustomValidity('')" /> </div> <div class="form-group"> <label for="no-tel">No Telpon</label> <input type="tel" placeholder="Masukan Nomor Telpon" required oninvalid="this.setCustomValidity('Ini harus diisi!')" oninput="this.setCustomValidity('')" /> </div> <div class="form-group"> <label for="Tanggal-Daftar">Tanggal Daftar</label> <input class="tanggal" type="date" required oninvalid="this.setCustomValidity('Ini harus diisi!')" oninput="this.setCustomValidity('')" /> </div> <div class="form-group"> <label>Kebutuhan Medis</label> <select class="kenutuhan" required oninvalid="this.setCustomValidity('Ini harus diisi!')" oninput="this.setCustomValidity('')" > <option value="" disabled selected>Kebutuhan Medis</option> <option value="imunisasi">Imunisasi</option> <option value="kb">KB</option> <option value="anc">ANC</option> <option value="umum">Umum</option> </select> </div> <div class="form-group"> <label>Pihak Medis</label> <select required oninvalid="this.setCustomValidity('Ini harus diisi!')" oninput="this.setCustomValidity('')" > <option value="" disabled selected>Pihak Medis</option> <option value="dokter">Dokter</option> <option value="bidan">Bidan</option> </select> </div> <div class="form-group"> <label>Nomor Antrian</label> <input class="nomor" type="number" required oninvalid="this.setCustomValidity('Ini harus diisi!')" oninput="this.setCustomValidity('')" /> </div> <div class="button"> <input type="submit" value="Submit" /> </div> </form> </div> <!-- Script --> <!-- Logout --> <script> // Tambahkan event listener untuk menangani logout document .getElementById("logoutButton") .addEventListener("click", function () { // Tambahkan logika logout di sini, misalnya mengarahkan ke halaman logout atau menjalankan fungsi logout console.log("Anda telah logout"); // Contoh: window.location.href = "/logout.php"; }); </script> <!-- Icons --> <script> feather.replace(); </script> <!-- Navbar --> <script> <!-- Hamburger Navbar --> // Toggle class active const navbarNav = document.querySelector(".navbar-nav"); // Hamburger menu di clik document.querySelector("#hamburger-menu").onclick = () => { navbarNav.classList.toggle("active"); }; // klik di luar sidebar const hamburger = document.querySelector("#hamburger-menu"); document.addEventListener("click", function (e) { if (!hamburger.contains(e.target) && !navbarNav.contains(e.target)) { navbarNav.classList.remove("active"); } }); </script> </body> </html>
package pl.ejdev.infrastructure.user.adapter import arrow.core.raise.either import io.kotest.matchers.shouldBe import io.mockk.coEvery import io.mockk.mockk import pl.ejdev.error.MustBeNonNullError import pl.ejdev.infrastructure.expectFailure import pl.ejdev.infrastructure.expectSuccess import pl.ejdev.postgres.domain.user.UserRepository import pl.ejdev.postgres.domain.user.port.out.GetUserResult import pl.ejdev.postgres.infrastructure.user.sources.repository.Status import pl.ejdev.restapi.domain.user.entities.GetAllUserQuery class GetAllUsersUseCaseAdapterSpec : UserUseCaseSpec() { init { feature("Get all users use case") { val repository = mockk<UserRepository>() val target = GetAllUsersUseCaseAdapter(repository) scenario("returns users from repository") { // given coEvery { repository.getAll(any()) } returns either { listOf(createUser()) } //when target.handle(GetAllUserQuery) //then .expectSuccess { first().run { id shouldBe 1 username shouldBe USERNAME firstName shouldBe FIRSTNAME lastName shouldBe LASTNAME email shouldBe EMAIL status shouldBe Status.ACTIVE.name roles.size shouldBe 0 } } } scenario("returns error from repository") { // given coEvery { repository.getAll(any()) } returns either { raise(MustBeNonNullError("Not found", "")) } // when target.handle(GetAllUserQuery) // then .expectFailure { error shouldBe "Not found" message shouldBe "" } } } } private fun createUser(): GetUserResult = GetUserResult( id = 1, username = USERNAME, firstName = FIRSTNAME, lastName = LASTNAME, email = EMAIL, status = Status.ACTIVE.name, roles = setOf() ) }
/******************************************************************************* * QMetry Automation Framework provides a powerful and versatile platform to author * Automated Test Cases in Behavior Driven, Keyword Driven or Code Driven approach * * Copyright 2016 Infostretch Corporation * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or 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. * * 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 * * You should have received a copy of the GNU General Public License along with this program in the name of LICENSE.txt in the root folder of the distribution. If not, see https://opensource.org/licenses/gpl-3.0.html * * See the NOTICE.TXT file in root folder of this source files distribution * for additional information regarding copyright ownership and licenses * of other open source software / files used by QMetry Automation Framework. * * For any inquiry or need additional information, please contact support-qaf@infostretch.com *******************************************************************************/ package com.qmetry.qaf.automation.step.client; import static com.qmetry.qaf.automation.core.ConfigurationManager.getBundle; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.commons.lang.text.StrSubstitutor; import com.google.gson.Gson; import com.qmetry.qaf.automation.core.CheckpointResultBean; import com.qmetry.qaf.automation.core.LoggingBean; import com.qmetry.qaf.automation.core.MessageTypes; import com.qmetry.qaf.automation.core.QAFTestBase; import com.qmetry.qaf.automation.core.TestBaseProvider; import com.qmetry.qaf.automation.step.BaseTestStep; import com.qmetry.qaf.automation.step.StepExecutionTracker; import com.qmetry.qaf.automation.step.StepInvocationException; import com.qmetry.qaf.automation.step.StringTestStep; import com.qmetry.qaf.automation.step.TestStep; import com.qmetry.qaf.automation.step.TestStepCompositer; import com.qmetry.qaf.automation.step.client.text.BDDDefinitionHelper; import com.qmetry.qaf.automation.step.client.text.BDDDefinitionHelper.ParamType; /** * com.qmetry.qaf.automation.exceltest.CustomStep.java * * @author chirag.jayswal */ public class CustomStep extends BaseTestStep implements TestStepCompositer { private Collection<TestStep> steps; private String def; public CustomStep(String name, String description, Collection<TestStep> steps) { super(name, description); this.steps = steps; this.def = description; } /* * (non-Javadoc) * * @see com.qmetry.qaf.automation.step.TestStep#execute(java.lang.Object[]) */ @Override protected Object doExecute() { try { Object res = null; processStepParams(); int executionIndx = 0; TestStep[] stepsToExecute = steps.toArray(new TestStep[steps.size()]); for (executionIndx = 0; executionIndx < stepsToExecute.length;) { TestStep currTestStep = stepsToExecute[executionIndx]; ((StringTestStep) currTestStep).initStep(); StepExecutionTracker stepExecutionTracker = currTestStep.getStepExecutionTracker(); if (null != stepExecutionTracker) { // quick-fix by Amit for ISFW-163 stepExecutionTracker.getContext().putAll(getStepExecutionTracker().getContext()); stepExecutionTracker.getContext().put("testStepCompositer", this); stepExecutionTracker.setStepCompositer(this); stepExecutionTracker.setStepIndex(executionIndx); stepExecutionTracker.setNextStepIndex(++executionIndx); } else { ++executionIndx; QAFTestBase stb = TestBaseProvider.instance().get(); CheckpointResultBean stepResultBean = new CheckpointResultBean(); stepResultBean.setMessage(currTestStep.getDescription() + " :: Not Found."); stepResultBean.setType(MessageTypes.Warn); stb.getCheckPointResults().add(stepResultBean); LoggingBean comLoggingBean = new LoggingBean(currTestStep.getName(), new String[] { Arrays.toString(currTestStep.getActualArgs()) }, "Error: Step Not Found"); stb.getLog().add(comLoggingBean); throw new StepInvocationException(currTestStep, "Test Step (" + currTestStep.getDescription() + ") Not Found.\n Please provide implementation or check 'step.provider.pkg' property value points to appropriate package.", true); } res = currTestStep.execute(); // next index can be modified form tracker in before or after // step executionIndx = stepExecutionTracker.getNextStepIndex(); } return res; } catch (Throwable e) { throw new StepInvocationException(this, e); } } /* * (non-Javadoc) * * @see com.qmetry.qaf.automation.step.TestStep#getName() */ @Override public String getName() { return name; } @Override public String getSignature() { return "Custom-Step[" + name + ":" + getFileName() + "#" + getLineNumber() + "] - " + getDescription(); } @SuppressWarnings({ "unchecked" }) public void processStepParams() { // process parameters in step; if ((actualArgs != null) && (actualArgs.length > 0)) { Map<String, Object> paramMap = getStepExecutionTracker().getContext(); List<String> paramNames = BDDDefinitionHelper.getArgNames(def); System.out.println(paramNames); for (int i = 0; i < actualArgs.length; i++) { String paramName = paramNames.get(i).trim(); // remove starting { and ending } from parameter name paramName = paramName.substring(1, paramName.length() - 1).split(":", 2)[0]; // in case of data driven test args[0] should not be overriden // with steps args[0] if ((actualArgs[i] instanceof String)) { String pstr = (String) actualArgs[i]; if (pstr.startsWith("${") && pstr.endsWith("}")) { String pname = pstr.substring(2, pstr.length() - 1); actualArgs[i] = paramMap.containsKey(pstr) ? paramMap.get(pstr) : paramMap.containsKey(pname) ? paramMap.get(pname) : getBundle().containsKey(pstr) ? getBundle().getObject(pstr) : getBundle().getObject(pname); } else if (pstr.indexOf("$") >= 0) { pstr = getBundle().getSubstitutor().replace(pstr); actualArgs[i] = StrSubstitutor.replace(pstr, paramMap); } // continue; ParamType ptype = ParamType.getType(pstr); if (ptype.equals(ParamType.MAP)) { Map<String, Object> kv = new Gson().fromJson(pstr, Map.class); paramMap.put(paramName, kv); for (String key : kv.keySet()) { paramMap.put(paramName + "." + key, kv.get(key)); } } else if (ptype.equals(ParamType.LIST)) { List<Object> lst = new Gson().fromJson(pstr, List.class); paramMap.put(paramName, lst); for (int li = 0; li < lst.size(); li++) { paramMap.put(paramName + "[" + li + "]", lst.get(li)); } } } paramMap.put("${args[" + i + "]}", actualArgs[i]); paramMap.put("args[" + i + "]", actualArgs[i]); paramMap.put(paramName, actualArgs[i]); } description = StrSubstitutor.replace(description, paramMap); for (TestStep step : steps) { ((StringTestStep) step).initStep(); if ((step.getActualArgs() != null) && (step.getActualArgs().length > 0)) { for (int j = 0; j < step.getActualArgs().length; j++) { if (paramMap.containsKey(step.getActualArgs()[j])) { step.getActualArgs()[j] = paramMap.get(step.getActualArgs()[j]); } else { step.getActualArgs()[j] = StrSubstitutor.replace(step.getActualArgs()[j], paramMap); } } } else if (step.getName().indexOf("$") >= 0) { // bdd? String name = StrSubstitutor.replace(step.getName(), paramMap); ((BaseTestStep) step).setName(name); } } } } @Override public TestStep clone() { ArrayList<TestStep> stepsClone = new ArrayList<TestStep>(); for (TestStep ts : steps) { stepsClone.add(ts.clone()); } CustomStep cloneObj = new CustomStep(name, description, stepsClone); cloneObj.setFileName(getFileName()); cloneObj.setLineNumber(getLineNumber()); cloneObj.setThreshold(getThreshold()); cloneObj.setMetaData(getMetaData()); if (null != actualArgs) { cloneObj.actualArgs = actualArgs.clone(); } return cloneObj; } @Override public Collection<TestStep> getSteps() { return steps; } }
<template> <v-dialog v-model="display" persistent max-width="600px"> <v-card> <v-card-title> <span class="text-h5">Editar Task</span> </v-card-title> <v-card-text> <v-container v-if ="data"> <v-row> <v-col cols="12"> <v-alert dense type="warning" v-show="alert.show"> {{ alert.message }} </v-alert> </v-col> </v-row> <v-row> <v-col cols="12"> <v-text-field label="Titulo*" required v-model="data.item.title" ></v-text-field> </v-col> <v-col cols="12"> <v-textarea label="Descripcion" v-model="data.item.description" ></v-textarea> </v-col> </v-row> </v-container> </v-card-text> <v-card-actions> <v-spacer></v-spacer> <v-btn color="blue darken-1" text @click="exitModal()"> Cerrar </v-btn> <v-btn color="blue darken-1" text @click="updateData()"> Actualizar </v-btn> </v-card-actions> </v-card> </v-dialog> </template> <script> export default { data: () => ({ alert: { show: false, message: null, }, dataBackup: null, }), props: ["showModal", "data"], computed: { display() { return this.$props.showModal; }, }, methods: { exitModal() { this.$emit("exitModal", true); }, updateData(){ if (this.data.item.title) { this.$store.commit('task/edit',this.$props.data); this.exitModal(); } else{ this.alert = { show : true, message : 'Debes de ponerle un titulo a la tarea antes de actualizarla.' } } } }, mounted() { }, }; </script>
/* * Copyright (c) 2001 Sun Microsystems, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Sun Microsystems, Inc. for Project JXTA." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact Project JXTA at http://www.jxta.org. * * 5. Products derived from this software may not be called "JXTA", * nor may "JXTA" appear in their name, without prior written * permission of Sun. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL SUN MICROSYSTEMS OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This software consists of voluntary contributions made by many * individuals on behalf of Project JXTA. For more * information on Project JXTA, please see * <http://www.jxta.org/>. * * This license is based on the BSD license adopted by the Apache Foundation. * * $Id: TextDocument.java,v 1.1 2005/05/02 17:58:38 hamada Exp $ */ package net.jxta.document; import java.io.Writer; import java.io.Reader; import java.io.IOException; /** * Extends {@link net.jxta.document.Document} for text documents. * * @see net.jxta.document.Document **/ public interface TextDocument extends Document { /** * Returns the sequence of characters which represents the content of this * <code>TextDocument</code>. * * @return An {@link java.io.Reader} containing the characters of this * <code>TextDocument</code>. * @exception IOException if an I/O error occurs. **/ Reader getReader() throws IOException; /** * Send the contents of this <code>TextDocument</code> to the specified * Writer. * * @param stream The OutputStream to which the <code>Document</code> * will be written. * @exception IOException if an I/O error occurs. **/ void sendToWriter( Writer stream ) throws IOException; /** * Returns a {@link java.lang.String} representation of this * <code>TextDocument</code>. **/ String toString(); }
import { styled } from "@stitches/react"; import { forwardRef, CSSProperties } from "react"; const Icon = styled("img", { position: "relative", borderRadius: "50%", border: "1.5px solid $primary500", }); export interface IUserIconProps { URL: string; size?: number; pointer?: boolean; style?: CSSProperties; } const UserIcon = forwardRef<HTMLImageElement, IUserIconProps>( ({ URL, size = 52, pointer, ...rest }, ref) => ( <Icon ref={ref} width={size} height={size} src={URL} draggable={false} {...rest} /> ), ); export default UserIcon; UserIcon.displayName = "UserIcon";
/* libFLAC++ - Free Lossless Audio Codec library * Copyright (C) 2002-2009 Josh Coalson * Copyright (C) 2011-2013 Xiph.Org Foundation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Xiph.org Foundation nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "FLAC++/decoder.h" #include "FLAC/assert.h" #ifdef _MSC_VER // warning C4800: 'int' : forcing to bool 'true' or 'false' (performance warning) #pragma warning ( disable : 4800 ) #endif namespace FLAC { namespace Decoder { // ------------------------------------------------------------ // // Stream // // ------------------------------------------------------------ Stream::Stream(): decoder_(::FLAC__stream_decoder_new()) { } Stream::~Stream() { if(0 != decoder_) { (void)::FLAC__stream_decoder_finish(decoder_); ::FLAC__stream_decoder_delete(decoder_); } } bool Stream::is_valid() const { return 0 != decoder_; } bool Stream::set_ogg_serial_number(long value) { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_set_ogg_serial_number(decoder_, value); } bool Stream::set_md5_checking(bool value) { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_set_md5_checking(decoder_, value); } bool Stream::set_metadata_respond(::FLAC__MetadataType type) { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_set_metadata_respond(decoder_, type); } bool Stream::set_metadata_respond_application(const FLAC__byte id[4]) { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_set_metadata_respond_application(decoder_, id); } bool Stream::set_metadata_respond_all() { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_set_metadata_respond_all(decoder_); } bool Stream::set_metadata_ignore(::FLAC__MetadataType type) { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_set_metadata_ignore(decoder_, type); } bool Stream::set_metadata_ignore_application(const FLAC__byte id[4]) { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_set_metadata_ignore_application(decoder_, id); } bool Stream::set_metadata_ignore_all() { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_set_metadata_ignore_all(decoder_); } Stream::State Stream::get_state() const { FLAC__ASSERT(is_valid()); return State(::FLAC__stream_decoder_get_state(decoder_)); } bool Stream::get_md5_checking() const { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_get_md5_checking(decoder_); } FLAC__uint64 Stream::get_total_samples() const { FLAC__ASSERT(is_valid()); return ::FLAC__stream_decoder_get_total_samples(decoder_); } unsigned Stream::get_channels() const { FLAC__ASSERT(is_valid()); return ::FLAC__stream_decoder_get_channels(decoder_); } ::FLAC__ChannelAssignment Stream::get_channel_assignment() const { FLAC__ASSERT(is_valid()); return ::FLAC__stream_decoder_get_channel_assignment(decoder_); } unsigned Stream::get_bits_per_sample() const { FLAC__ASSERT(is_valid()); return ::FLAC__stream_decoder_get_bits_per_sample(decoder_); } unsigned Stream::get_sample_rate() const { FLAC__ASSERT(is_valid()); return ::FLAC__stream_decoder_get_sample_rate(decoder_); } unsigned Stream::get_blocksize() const { FLAC__ASSERT(is_valid()); return ::FLAC__stream_decoder_get_blocksize(decoder_); } bool Stream::get_decode_position(FLAC__uint64 *position) const { FLAC__ASSERT(is_valid()); return ::FLAC__stream_decoder_get_decode_position(decoder_, position); } ::FLAC__StreamDecoderInitStatus Stream::init() { FLAC__ASSERT(is_valid()); return ::FLAC__stream_decoder_init_stream(decoder_, read_callback_, seek_callback_, tell_callback_, length_callback_, eof_callback_, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); } ::FLAC__StreamDecoderInitStatus Stream::init_ogg() { FLAC__ASSERT(is_valid()); return ::FLAC__stream_decoder_init_ogg_stream(decoder_, read_callback_, seek_callback_, tell_callback_, length_callback_, eof_callback_, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); } bool Stream::finish() { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_finish(decoder_); } bool Stream::flush() { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_flush(decoder_); } bool Stream::reset() { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_reset(decoder_); } bool Stream::process_single() { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_process_single(decoder_); } bool Stream::process_until_end_of_metadata() { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_process_until_end_of_metadata(decoder_); } bool Stream::process_until_end_of_stream() { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_process_until_end_of_stream(decoder_); } bool Stream::skip_single_frame() { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_skip_single_frame(decoder_); } bool Stream::seek_absolute(FLAC__uint64 sample) { FLAC__ASSERT(is_valid()); return (bool)::FLAC__stream_decoder_seek_absolute(decoder_, sample); } ::FLAC__StreamDecoderSeekStatus Stream::seek_callback(FLAC__uint64 absolute_byte_offset) { (void)absolute_byte_offset; return ::FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED; } ::FLAC__StreamDecoderTellStatus Stream::tell_callback(FLAC__uint64 *absolute_byte_offset) { (void)absolute_byte_offset; return ::FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED; } ::FLAC__StreamDecoderLengthStatus Stream::length_callback(FLAC__uint64 *stream_length) { (void)stream_length; return ::FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED; } bool Stream::eof_callback() { return false; } void Stream::metadata_callback(const ::FLAC__StreamMetadata *metadata) { (void)metadata; } ::FLAC__StreamDecoderReadStatus Stream::read_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data) { (void)decoder; FLAC__ASSERT(0 != client_data); Stream *instance = reinterpret_cast<Stream *>(client_data); FLAC__ASSERT(0 != instance); return instance->read_callback(buffer, bytes); } ::FLAC__StreamDecoderSeekStatus Stream::seek_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data) { (void) decoder; FLAC__ASSERT(0 != client_data); Stream *instance = reinterpret_cast<Stream *>(client_data); FLAC__ASSERT(0 != instance); return instance->seek_callback(absolute_byte_offset); } ::FLAC__StreamDecoderTellStatus Stream::tell_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data) { (void) decoder; FLAC__ASSERT(0 != client_data); Stream *instance = reinterpret_cast<Stream *>(client_data); FLAC__ASSERT(0 != instance); return instance->tell_callback(absolute_byte_offset); } ::FLAC__StreamDecoderLengthStatus Stream::length_callback_(const ::FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data) { (void) decoder; FLAC__ASSERT(0 != client_data); Stream *instance = reinterpret_cast<Stream *>(client_data); FLAC__ASSERT(0 != instance); return instance->length_callback(stream_length); } FLAC__bool Stream::eof_callback_(const ::FLAC__StreamDecoder *decoder, void *client_data) { (void) decoder; FLAC__ASSERT(0 != client_data); Stream *instance = reinterpret_cast<Stream *>(client_data); FLAC__ASSERT(0 != instance); return instance->eof_callback(); } ::FLAC__StreamDecoderWriteStatus Stream::write_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data) { (void)decoder; FLAC__ASSERT(0 != client_data); Stream *instance = reinterpret_cast<Stream *>(client_data); FLAC__ASSERT(0 != instance); return instance->write_callback(frame, buffer); } void Stream::metadata_callback_(const ::FLAC__StreamDecoder *decoder, const ::FLAC__StreamMetadata *metadata, void *client_data) { (void)decoder; FLAC__ASSERT(0 != client_data); Stream *instance = reinterpret_cast<Stream *>(client_data); FLAC__ASSERT(0 != instance); instance->metadata_callback(metadata); } void Stream::error_callback_(const ::FLAC__StreamDecoder *decoder, ::FLAC__StreamDecoderErrorStatus status, void *client_data) { (void)decoder; FLAC__ASSERT(0 != client_data); Stream *instance = reinterpret_cast<Stream *>(client_data); FLAC__ASSERT(0 != instance); instance->error_callback(status); } // ------------------------------------------------------------ // // File // // ------------------------------------------------------------ File::File(): Stream() { } File::~File() { } ::FLAC__StreamDecoderInitStatus File::init(FILE *file) { FLAC__ASSERT(0 != decoder_); return ::FLAC__stream_decoder_init_FILE(decoder_, file, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); } ::FLAC__StreamDecoderInitStatus File::init(const char *filename) { FLAC__ASSERT(0 != decoder_); return ::FLAC__stream_decoder_init_file(decoder_, filename, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); } ::FLAC__StreamDecoderInitStatus File::init(const std::string &filename) { return init(filename.c_str()); } ::FLAC__StreamDecoderInitStatus File::init_ogg(FILE *file) { FLAC__ASSERT(0 != decoder_); return ::FLAC__stream_decoder_init_ogg_FILE(decoder_, file, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); } ::FLAC__StreamDecoderInitStatus File::init_ogg(const char *filename) { FLAC__ASSERT(0 != decoder_); return ::FLAC__stream_decoder_init_ogg_file(decoder_, filename, write_callback_, metadata_callback_, error_callback_, /*client_data=*/(void*)this); } ::FLAC__StreamDecoderInitStatus File::init_ogg(const std::string &filename) { return init_ogg(filename.c_str()); } // This is a dummy to satisfy the pure virtual from Stream; the // read callback will never be called since we are initializing // with FLAC__stream_decoder_init_FILE() or // FLAC__stream_decoder_init_file() and those supply the read // callback internally. ::FLAC__StreamDecoderReadStatus File::read_callback(FLAC__byte buffer[], size_t *bytes) { (void)buffer, (void)bytes; FLAC__ASSERT(false); return ::FLAC__STREAM_DECODER_READ_STATUS_ABORT; // double protection } } }
--- title: 'The Most Ethical Issue Using AI in Business: A Critical Review' description: 'An exploration of the ethical concerns for small businesses using AI, challenging prevailing industry narratives and misconceptions, and emphasizing the need for a personalized and thoughtful approach.' author: Cloudcraft image: /assets/images/landing/what-is-the-most-ethical-issue-using-ai-in-business.jpg --- ## What is the Most Ethical Issue Using AI in Business? The most pressing ethical issue facing small businesses implementing AI solutions is the balance of automation and human touch. Striking the right balance wherein businesses maintain an authentic relationship with their customers while leveraging AI to streamline their operations lies at the heart of an ethical AI implementation. Let's take a step back. What Are AI Solutions? How Do They Influence Business Ethics? And most importantly, why should a small business owner care? <ServicesBlurb /> ## Embodying Authenticity in AI Transparency and authenticity play fundamental roles in the relationship between small businesses and their customers. Clients need to believe businesses, feel their sincerity, understand their values. The crux of the ethical issue is trying to infuse AI with the charm and warmth of human character. Can automation, arguably a series of pre-programmed tasks, feel genuine? ### The Juggle between Efficiency and Authenticity * Mailchimp: Performs automated email marketing but still allows for personalized messages. * Hootsuite: Offers automated social media posts while allowing businesses to curate their content. * Zendesk: Provides automated customer support, but with the prompt to connect directly to a human. * HubSpot: Automates a myriad of marketing tasks yet gives businesses the chance to customize their engagement. ## The Human Touch While these tools are effective, they all bear one common question - the degree of their human touch. Can a programmed algorithm truly encapsulate the individuality and personal ethos of a small business owner? AI tools, no matter how sophisticated, are no match for the human aspect businesses bring with their service. But now a question arises - Should these tools be left alone to automate everything? ## Unexplored Territory: Ethical AI Implementation Automation saves time, boosts productivity, and propels efficiency. However, its ethical implementation becomes a tussle - the need to alleviate burdensome tasks versus sustaining the integral human qualities that make a business attractive. ### Weighing the Pros and Cons * Automation: Time-saving, efficient, with a wide range of assistance. * Human Connection: Unique, personalized experience for clients, adding a touch of empathy. * Balance: Merging both, creating an efficient business without losing its human touch. * Consultation: Helping businesses evaluate their individual needs to deliver more value. <GetStartedBlurb /> ## Discerning the Fine Line <blockquote> "Complexity is complexity, regardless of your architecture. It's important for small businesses to recognize this when exploring AI solutions."</blockquote> Deciphering the fine line is intricate. Identifying what to automate, how much to automate, to what extent human interaction is necessary- these decisions can entirely change the customer experience and define your brand. ## A Custom Tailored Solution Common and popular tools may seem attractive owing to their all-in-one solution. However, a services consultant, understanding individual needs, can sculpt the precise balance of automation and human touch suitable for your brand. ### The Outside Eye * Tailored Approach: A consultant crafts specific solutions aligning with the business's unique needs. * Unique Perspective: An outsider can identify opportunities for enhancement unseen by those within. * Cost-effective: A consultant provides fast and efficient answers to technological dilemmas. * Matchmaker: Directly matching businesses with the ideal tools, saving time and resources. ## Wrapping Up Today's Session Every business is unique, requiring its unique touch. An outside opinion can help illuminate possibilities unseen, offering a new perception. It's crucial to remember the balance lies not in the AI solution but the manner it's utilized. So, let’s bridge the AI-human gap and propel our businesses ethically into the digital era.
const ticketsChartContainer = document.getElementById('ticket-stats') let ticketsChart; // Function to update the tickets chart with new data const updateTicketsChart = (ticketsData) => { if (ticketsChart) { ticketsChart.data.labels = Object.keys(ticketsData); ticketsChart.data.datasets[0].data = Object.values(ticketsData); ticketsChart.update(); } else { ticketsChart = new Chart(ticketsChartContainer, { type: 'bar', data: { labels: Object.keys(ticketsData), datasets: [ { label: 'Agents', data: Object.values(ticketsData), borderWidth: 0, borderRadius: 5, backgroundColor: 'rgb(6, 54, 104)', }, ], }, options: { scales: { y: { beginAtZero: true, }, }, }, }); } }; // Add an event listener to the ticketStatus select element const ticketStatusSelect = document.getElementById('ticketStatus'); ticketStatusSelect.addEventListener('change', async () => { const selectedStatus = ticketStatusSelect.value; const responseData = await fetchTicketData(selectedStatus); updateTicketsChart(responseData); }); // Function to fetch ticket data from the server async function fetchTicketData(ticketStatus) { try { const response = await fetch(`/api/tickets/status/${ticketStatus}`); if (!response.ok) { throw new Error('Failed to fetch ticket data'); } const data = await response.json(); return data.ticketsData; } catch (error) { console.error('Error fetching ticket data:', error); return {}; } }
; ; Lights out ; for the AltairDuino ; ; Inspired by Steve Gibson's Lights Out puzzle ; for the SBC6120/PDP-8 front panel. ; ; In this version there are only 8 switches and ; LEDs. LEDs per switch is fixed at 2. ; There is no hint mode. ; BEGIN: LXI sp,0x0100 ; initialize stack, end of 256 byte page ; ; Randomize to calculate an answer value ; GENANS: CALL RNDIZE ; randomize until switch toggle RETRY: CALL RANDOM ; get next random value ORA a ; test for 0, want 1 or more JZ RETRY ; reject 0 value STA ANSWER ; save answer CALL RNDIZE2 ; continue randomize until 2nd switch toggle ; ; Assign LED pairs for each of the switches ; SETUP: LXI d,SWITCHES + 7 ; current end of choice list MVI c,28 ; start with 28 possible choices for 8 switches NEXTSW: CALL RANDOM ; get random value CALL MOD ; scale down to size LXI h,CHOICES ; start of choices list ADD l ; add random value to lower 8 bits of address MOV l,a ; set address lower 8 bits MOV b,m ; read selected value LDAX d ; read last value MOV m,a ; move to hole left by selected value MOV a,b ; get selected STAX d ; ...and save to end of list DCX d ; shorten end of list by 1 DCR c ; decrement counter MVI a,20 ; stop after 8 switches (20 remaining values) CMP c JNZ NEXTSW ; ; Play ; ; Register D should always hold the current LED display. ; The next LED display value is calculated in E. ; E replaces D when done. ; BEGIN: ; ; Calculate initial LED display value ; The answer specifies which switches must be toggled ; to clear all LEDs. ; LXI d,0 ; init d & e to all lights off (0) LDA ANSWER ; answer specifies which switches to toggle MOV c,a ; save 8 bits representing switch settings MVI b,8 ; number of bits to test LXI h,SWITCHES ; address of first switch CALL LOOPSW ; loop through switches and calc the display value MOV a,e ; get calculated value STA LIGHTS ; this is the initial value ; ; Start game ; RESUME: ; Existing game can be restarted here LDA LIGHTS ; initial lights address MOV d,a ; d is current lights value MOV e,d ; temp lights value also same value LDAX d ; show lights MAIN: IN SWPORT ; read current switch settings MOV c,a ; save current switch settings MVI b,8 ; number of bits to test LXI h,SWITCHES ; address of first switch CALL LOOPSW ; loop through switches and calc the display value MOV d,e ; update lights with new value LDAX d ; show lights ; Wait here a bit ; Constant polling of the switches will light all LEDs ; A delay here will minimize this to a short flicker. LXI b,0x04 ; 16-bit increment amount. higher value = faster. LXI h,0x00 ; init 16-bit counter WAIT: LDAX d ; show LEDs DAD b ; increment 16-bit counter JNC WAIT LDA LIGHTS ; re-read initial LED display value MOV e,a ; reset E back to initial lights value JMP MAIN ; ; Loop through all 8 switch values and calculate ; the LED display value. ; Shift through 8 bits of the switch settings ; to determine which are on. LOOPSW: LDAX d ; show lights MOV a,c ; restore switch settings RLC ; test if next switch is on (carry = 1) MOV c,a ; save remaining switch settings LDAX d ; show lights JNC SWOFF ; switch on MOV a,m ; get switch value XRA e ; xor with temp lights value MOV e,a ; update temp lights value SWOFF: INX h ; address of next switch value DCR b ; decrement bit counter JNZ LOOPSW RET SWPORT EQU 0xFF ; The randomly selected answer pattern will be ; stored here. ; Turns out there can be more than one solution to the puzzle. ; Testing has shown maybe 2 or 4 different switch patterns ; can turn out the lights. ANSWER: DB 0x00 LIGHTS: DB 0xFF ; initial lights value when all switches are off ; ; All possible LED pairs ; For 8 LEDs there are 28 combinations ; At the end of the selection process, the 8 selected ; values will be at the end of the list (addressable ; by SWITCHES). ; CHOICES: DB 0x81,0x82,0x84,0x88,0x90,0xA0,0xC0 DB 0x41,0x42,0x44,0x48,0x50,0x60 DB 0x21,0x22,0x24,0x28,0x30 DB 0x11,0x12 SWITCHES: ; last 8 values of list DB 0x14,0x18 DB 0x09,0x0A,0x0C DB 0x05,0x06 DB 0x03 ENDDATA: ; ; Generate random numbers until a switch is toggled ; Watch out for switches that may already be high. ; These will have to be ignored. RNDIZE: IN SWPORT ; get initial switch value XRI 0xff ; create mask which ignores switches already on MOV b,a ; save mask TESTSW: ; loop until user toggles a switch ; note: a beneficial side effect of reading the switches ; is that all LEDs will light. CALL RANDOM ; get random value IN SWPORT ; get current switches ANA b ; test for any switch toggled on JZ TESTSW ; repeat if no change or less RET ; ; Generate random numbers until all switches off ; RNDIZE2: CALL RANDOM ; get random value IN SWPORT ; get initial switch value ORA a ; test value for 0 JNZ RNDIZE2 ; repeat until zero RET ; ; Size random number down to 0 to C. ; Not the best way to uniformly scale down to ; a range, but good enough for this purpose. MOD: CMP c ; C = divisor RC ; done if total less than divisor SUB c ; subtract divisor JMP MOD ; ; Generate random 8 bit value ; ; Based on this article: ; http://www.donnelly-house.net/programming/cdp1802/8bitPRNGtest.html ; RANDOM: PUSH b PUSH d PUSH h LDA VAR_X ; load X MOV d,a ; save X ANI 0x1f ; strip top 3 bits RLC ; shift 3 times RLC ; . RLC ; . XRA d ; XOR with X MOV d,a ; save T ANI 0xfc ; strip bottom 2 bits RRC ; shift 2 times RRC ; . XRA d ; XOR with T MOV d,a ; save T for later ; shift working values LDA VAR_Z ; load Z LHLD VAR_Y ; load Y & W SHLD VAR_X ; X <- Y, Z <-W STA VAR_Y ; Y <- Z, ; H has original W value MOV a,h ANI 0xe0 ; strip bottom 5 bits RRC ; shift 5 times RRC ; . RRC ; . RRC ; . RRC ; . XRA h ; XOR with W XRA d ; XOR with T STA VAR_W ; save W POP h POP d POP b RET VAR_X: DB 21 VAR_Z: DB 181 VAR_Y: DB 229 VAR_W: DB 51
<!DOCTYPE html> <html> <head> <title>评论插件与SNS探索 // DRAPORLAND</title> <meta charset="utf-8"> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1"> <meta property="og:title" content="评论插件与SNS探索" /> <meta property="og:description" content="" /> <meta property="og:type" content="website" /> <meta property="og:locale" content="en" /> <meta property="og:url" content="https://drapor.me/200403_comments_and_sns/" /> <link rel="shortcut icon" href="/favicon.ico"> <link href="https://drapor.me/webfonts/ptserif/main.css" rel='stylesheet' type='text/css'> <link href="https://drapor.me/webfonts/source-code-pro/main.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="https://drapor.me/css/style.css"> <meta name="generator" content="Hugo 0.91.2" /> </head> <body> <div id="container"> <header id="header"> <div id="header-outer" class="outer"> <div id="header-inner" class="inner"> <a id="main-nav-toggle" class="nav-icon" href="javascript:;"></a> <a id="logo" class="logo-text" href="https://drapor.me/">DRAPORLAND</a> <div class="subtitle">“Witness me.”</div> <nav id="main-nav"> <a class="main-nav-link" href="/about">About</a> </nav> <nav id="sub-nav"> <div id="search-form-wrap"> </div> </nav> </div> </div> </header> <section id="main" class="outer"> <article class="article article-type-post" itemscope itemprop="blogPost"> <div class="article-inner"> <header class="article-header"> <h1 class="article-title" itemprop="name">评论插件与SNS探索</h1> </header> <div class="article-meta"> <a href="/200403_comments_and_sns/" class="article-date"> <time datetime='2020-04-03T16:00:59.000&#43;08:00' itemprop="datePublished">2020-04-03</time> </a> </div> <div class="article-entry" itemprop="articleBody"> <p>在<a href="https://drapor.me/posts/170507_notice/">多说关闭服务</a>将近三年之后,最近突然又想给自己的博客重新加上评论功能(虽然估计没什么实际作用……),以及最近对SNS也做了一些新的探索。</p> <h4 id="评论插件">评论插件</h4> <p>多说的替代品不算少,但在各个方面能比得上多说的寥寥无几。这些替代品大致可以分为几类:一类是搜狐畅言*、*网易云跟贴(也已关闭)之类的国内门户网站提供的服务,它们的评论插件样式中带有强烈的品牌特征,嵌入到个人博客中难免风格不匹配;一类是Disqus、HyperComments和Livere一类的外国第三方服务,他们优劣各有不同,通常的问题是从国内的网络访问服务可能会比较缓慢,甚至根本无法从国内访问到,再者是由于是外国提供的服务,在SNS登陆的支持上通常选择的也是Twitter和Facebook之类的国外SNS,有些优质的服务价格不菲(对于我博客的用量而言),有些样式需要自己花工夫修改和增补CSS;还有一类是基于GitHub Issues的评论服务,依托Github Issues做评论数据的存储和Github的账号服务,这类服务的优劣也很明显:需要Github账号,国内网络访问也会受到一定程度的影响。</p> <p>我其实一开始打算直接用LiveRe(即来必力)来着,LiveRe对国内的SNS也算是不错了,访问速度略慢但是等一会儿还是可以的。让我比较烦恼的问题是,LiveRe的样式,在我博客的底色上,颜色和样式都有点不太融洽,我尝试自己写CSS修改,但囿于个人的配色能力,改来改去还是觉得不满意。后来转念一想,会看我博客的人大概都是圈内的人,也大多都有GitHub账号,索性直接从基于Github Issues的评论服务中挑一个好看的好了,于是最后决定采用<a href="%5Bhttps://gitalk.github.io/%5D(https://gitalk.github.io/)">Gitalk</a>。配置方法不再赘述,非常简单方便。</p> <hr> <h4 id="sns">SNS</h4> <p>很长时间以来,我对SNS的态度摇摆不定,一方面,我对日常生活确实有表达欲,很想po一些内容,但另一方面,每个SNS都似乎不能让我畅快地抒发心情。在此之前的一小段时间里一直在用即刻的内测版Jellow,但逐渐地,中心化的SNS社区依然会让我感到不适。于是开始考虑自建SNS是否可行,以及是否有某种替代方案。新的方案希望最好是去中心化的,可自动化的,同时po内容也足够便利。经过一番探索。最终,我发现了<a href="%5Bhttps://joinmastodon.org/%5D(https://joinmastodon.org/)">Mastodon</a>。</p> <p>简单说,Mastodon就是可以自建的SNS,任何人都可以用开源的代码部署一套Mastodon,创建一个新的Mastodon instance,而且通常情况下,这些Mastodon宇宙(不同的instance)之间也是可以互联的。我发现自己一年前注册的<a href="https://o3o.ca/">https://o3o.ca/</a> 其实也是Mastodon的一个instance;</p> <p>App方面,我下了Mastodon官网推荐的Tusky。原想这类开源生态中的免费app大概只能提供可用的基本功能,不能过多奢望UI和产品设计。意外的是,Tusky的UI和Twitter的app非常像。更妙的是Tusky还支持在下拉菜单中添加Shortcut按钮,点击按钮可以直接进入Compose页,而Twitter都并没有做过类似(哪怕是桌面Widget)的支持。</p> <img src="/article_imgs/tusky.jpg" style="width: 50%;"> <p>此外,利用Mastodon提供的API,还可以用IFTTT做Applet,把其他地方的动态也同步到Mastodon上。比如利用我的豆瓣RSS更新作为Trigger,用Webhooks把豆瓣广播转发到Mastodon上。</p> <img src="/article_imgs/ifttt_mastodon.jpg" style="width: 50%;"> <p>不出意外的话,自建Mastodon应该就是我用SNS的终点了。</p> <p>不禁感叹:<strong>开源真好啊!</strong></p> </div> <div class="article-toc" > <h3>Contents</h3> <nav id="TableOfContents"> <ul> <li> <ul> <li></li> </ul> </li> </ul> </nav> </div> </div> <div style="font-size: 14px;font-style: italic; color: #808080; text-align: right;"><br /> 本作品采用<a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/">知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议</a>进行许可。 <br /><br /> <a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/4.0/"><img alt="知识共享许可协议" style="border-width:0" src="https://i.creativecommons.org/l/by-nc-nd/4.0/88x31.png" /></a> </div> <nav id="article-nav"> <a href="/200413_insomnia/" id="article-nav-newer" class="article-nav-link-wrap"> <div class="article-nav-title"><span>&lt;</span>&nbsp; Alternative to Postman: Insomnia </div> </a> <a href="/200113_proxy_pass_slash/" id="article-nav-older" class="article-nav-link-wrap"> <div class="article-nav-title">Nginx中proxy_pass的斜杠问题&nbsp;<span>&gt;</span></div> </a> </nav> <div id="gitalk-container"></div> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css"> <script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script> <script> var gittalk = new Gitalk({ clientID: 'b33898060f51f3637cdb', clientSecret: '264aa9f9ab82c827765c14f5df4d8195bfd26a0d', repo: 'gabrieldrapor.github.io', owner: 'GabrielDrapor', admin: ['GabrielDrapor'], id: location.pathname, distractionFreeMode: false }) gittalk.render("gitalk-container") </script> </article> </section> <footer id="footer"> <div class="outer"> <div id="footer-info" class="inner"> &copy; 2023 DRAPORLAND <br /> Powered by <a href="https://gohugo.io" target="_blank">Hugo</a> with theme <a href="https://github.com/carsonip/hugo-theme-minos" target="_blank">Minos</a> </div> </div> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/styles/tomorrow-night.min.css" integrity="sha256-2wL88NKUqvJi/ExflDzkzUumjUM73mcK2gBvBBeLvTk=" crossorigin="anonymous" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js" integrity="sha256-KbfTjB0WZ8vvXngdpJGY3Yp3xKk+tttbqClO11anCIU=" crossorigin="anonymous"></script> <script>hljs.initHighlightingOnLoad();</script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css" integrity="sha384-wITovz90syo1dJWVh32uuETPVEtGigN07tkttEqPv+uR2SE/mbQcG7ATL28aI9H0" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.js" integrity="sha384-/y1Nn9+QQAipbNQWU65krzJralCnuOasHncUFXGkdwntGeSvQicrYkiUBwsgUqc1" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/contrib/auto-render.min.js" integrity="sha256-ExtbCSBuYA7kq1Pz362ibde9nnsHYPt6JxuxYeZbU+c=" crossorigin="anonymous"></script> <script>renderMathInElement(document.body);</script> <script> document.getElementById('main-nav-toggle').addEventListener('click', function () { var header = document.getElementById('header'); if (header.classList.contains('mobile-on')) { header.classList.remove('mobile-on'); } else { header.classList.add('mobile-on'); } }); </script> </footer> </div> </body> </html>
.TH MatchEditor 3I "7 Dec 1989" "InterViews" "InterViews Reference Manual" .SH NAME MatchEditor \- StringEditor with pattern matching .SH SYNOPSIS .B #include <InterViews/matcheditor.h> .SH DESCRIPTION MatchEditor is a StringEditor subclass that checks the validity of its contents against a specified pattern. It is suitable for entering strings that must conform to a particular format such as a number or a file name. The matching pattern is specified according to the rules of scanf(3). For example, a pattern of "%3d" will match a 3-digit integer, a pattern of "%[ab]" will match a string containing only a's and b's, and a pattern of "(%f, %f)" will match the string "(12.0, 5E23)". .SH PUBLIC OPERATIONS .TP .B "MatchEditor(ButtonState*, const char* sample, const char* done)" Create a new MatchEditor object. The ButtonState, sample string, and termination string are passed to the StringEditor constructor. .TP .B "void Match(const char* pattern, boolean keystroke = true)" Specify the pattern to match against. When MatchEditor performs matching, it will highlight any trailing part of the edit string that does not conform to \fIpattern\fP. The user can then correct the string. If \fIkeystroke\fP is true, matching will occur on every keystroke; otherwise matching will only occur on the completion of the edit. The initial pattern matches any string, and the initial value of keystroke is true. .SH RESTRICTIONS MatchEditor uses sscanf internally to check the pattern match. Different versions of sscanf have different scanning capabilities; check with your local version to see what patterns you can use. .SH SEE ALSO StringEditor(3I)
// // ProductDetail.swift // JLDishwasher // // Created by Iain McLean on 21/12/2016. // Copyright © 2016 Iain McLean. All rights reserved. // import Foundation public class ProductDetail { public var crumbs : Array<Crumbs>? public var media : Media? public var productId : String? public var defaultCategory : DefaultCategory? public var ageRestriction : Int? public var type : String? public var displaySpecialOffer : String? public var seoURL : String? public var setId : String? public var code : Int? public var title : String? public var skus : Array<Skus>? public var isFBL : String? public var setInformation : String? public var storeOnly : String? public var additionalServices : AdditionalServices? public var deliverySummary : Array<DeliverySummary>? public var details : Details? public var promotionalFeatures : Array<PromotionalFeatures>? public var price : Price? public var defaultSku : Int? public var isInTopNkuCategory : String? public var specialOffers : SpecialOffers? public var deliveries : Array<Deliveries>? public var templateType : String? public var seoInformation : SeoInformation? public var releaseDateTimestamp : Int? public var emailMeWhenAvailable : String? /** Returns an array of models based on given dictionary. Sample usage: let ProductDetail_list = ProductDetail.modelsFromDictionaryArray(someDictionaryArrayFromJSON) - parameter array: NSArray from JSON dictionary. - returns: Array of ProductDetail Instances. */ public class func modelsFromDictionaryArray(array:NSArray) -> [ProductDetail] { var models:[ProductDetail] = [] for item in array { models.append(ProductDetail(dictionary: item as! NSDictionary)!) } return models } /** Constructs the object based on the given dictionary. Sample usage: let ProductDetail = ProductDetail(someDictionaryFromJSON) - parameter dictionary: NSDictionary from JSON. - returns: ProductDetail Instance. */ required public init?(dictionary: NSDictionary) { if (dictionary["crumbs"] != nil) { crumbs = Crumbs.modelsFromDictionaryArray(array: dictionary["crumbs"] as! NSArray) } if (dictionary["media"] != nil) { media = Media(dictionary: dictionary["media"] as! NSDictionary) } productId = dictionary["productId"] as? String if (dictionary["defaultCategory"] != nil) { defaultCategory = DefaultCategory(dictionary: dictionary["defaultCategory"] as! NSDictionary) } ageRestriction = dictionary["ageRestriction"] as? Int type = dictionary["type"] as? String displaySpecialOffer = dictionary["displaySpecialOffer"] as? String seoURL = dictionary["seoURL"] as? String setId = dictionary["setId"] as? String code = dictionary["code"] as? Int title = dictionary["title"] as? String if (dictionary["skus"] != nil) { skus = Skus.modelsFromDictionaryArray(array: dictionary["skus"] as! NSArray) } isFBL = dictionary["isFBL"] as? String setInformation = dictionary["setInformation"] as? String storeOnly = dictionary["storeOnly"] as? String if (dictionary["additionalServices"] != nil) { additionalServices = AdditionalServices(dictionary: dictionary["additionalServices"] as! NSDictionary) } if (dictionary["deliverySummary"] != nil) { deliverySummary = DeliverySummary.modelsFromDictionaryArray(array: dictionary["deliverySummary"] as! NSArray) } if (dictionary["details"] != nil) { details = Details(dictionary: dictionary["details"] as! NSDictionary) } if (dictionary["promotionalFeatures"] != nil) { promotionalFeatures = PromotionalFeatures.modelsFromDictionaryArray(array: dictionary["promotionalFeatures"] as! NSArray) } if (dictionary["price"] != nil) { price = Price(dictionary: dictionary["price"] as! NSDictionary) } defaultSku = dictionary["defaultSku"] as? Int isInTopNkuCategory = dictionary["isInTopNkuCategory"] as? String if (dictionary["specialOffers"] != nil) { specialOffers = SpecialOffers(dictionary: dictionary["specialOffers"] as! NSDictionary) } if (dictionary["deliveries"] != nil) { deliveries = Deliveries.modelsFromDictionaryArray(array: dictionary["deliveries"] as! NSArray) } templateType = dictionary["templateType"] as? String if (dictionary["seoInformation"] != nil) { seoInformation = SeoInformation(dictionary: dictionary["seoInformation"] as! NSDictionary) } releaseDateTimestamp = dictionary["releaseDateTimestamp"] as? Int emailMeWhenAvailable = dictionary["emailMeWhenAvailable"] as? String } /** Returns the dictionary representation for the current instance. - returns: NSDictionary. */ public func dictionaryRepresentation() -> NSDictionary { let dictionary = NSMutableDictionary() dictionary.setValue(self.media?.dictionaryRepresentation(), forKey: "media") dictionary.setValue(self.productId, forKey: "productId") dictionary.setValue(self.defaultCategory?.dictionaryRepresentation(), forKey: "defaultCategory") dictionary.setValue(self.ageRestriction, forKey: "ageRestriction") dictionary.setValue(self.type, forKey: "type") dictionary.setValue(self.displaySpecialOffer, forKey: "displaySpecialOffer") dictionary.setValue(self.seoURL, forKey: "seoURL") dictionary.setValue(self.setId, forKey: "setId") dictionary.setValue(self.code, forKey: "code") dictionary.setValue(self.title, forKey: "title") dictionary.setValue(self.isFBL, forKey: "isFBL") dictionary.setValue(self.setInformation, forKey: "setInformation") dictionary.setValue(self.storeOnly, forKey: "storeOnly") dictionary.setValue(self.additionalServices?.dictionaryRepresentation(), forKey: "additionalServices") dictionary.setValue(self.details?.dictionaryRepresentation(), forKey: "details") dictionary.setValue(self.price?.dictionaryRepresentation(), forKey: "price") dictionary.setValue(self.defaultSku, forKey: "defaultSku") dictionary.setValue(self.isInTopNkuCategory, forKey: "isInTopNkuCategory") dictionary.setValue(self.specialOffers?.dictionaryRepresentation(), forKey: "specialOffers") dictionary.setValue(self.templateType, forKey: "templateType") dictionary.setValue(self.seoInformation?.dictionaryRepresentation(), forKey: "seoInformation") dictionary.setValue(self.releaseDateTimestamp, forKey: "releaseDateTimestamp") dictionary.setValue(self.emailMeWhenAvailable, forKey: "emailMeWhenAvailable") return dictionary } }
import socket import struct import threading from time import sleep import signal # Define UDP server address and port UDP_SERVER_ADDRESS = '192.168.1.10' UDP_SERVER_PORT = 7 print(f""" ██╗ ██████╗ ██████╗ ██████╗ ███████╗██████╗ ██║ ██╔═══██╗██╔════╝ ██╔════╝ ██╔════╝██╔══██╗ ██║ ██║ ██║██║ ███╗██║ ███╗█████╗ ██████╔╝ ██║ ██║ ██║██║ ██║██║ ██║██╔══╝ ██╔══██╗ ███████╗╚██████╔╝╚██████╔╝╚██████╔╝███████╗██║ ██║ ╚══════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ ██████╗ ███████╗████████╗██████╗ ██╗███████╗██╗ ██╗███████╗██████╗ ██╔══██╗██╔════╝╚══██╔══╝██╔══██╗██║██╔════╝██║ ██║██╔════╝██╔══██╗ ██████╔╝█████╗ ██║ ██████╔╝██║█████╗ ██║ ██║█████╗ ██████╔╝ ██╔══██╗██╔══╝ ██║ ██╔══██╗██║██╔══╝ ╚██╗ ██╔╝██╔══╝ ██╔══██╗ ██║ ██║███████╗ ██║ ██║ ██║██║███████╗ ╚████╔╝ ███████╗██║ ██║ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝ ╚═══╝ ╚══════╝╚═╝ ╚═╝ Trego LTD. Luanch-Computer Info: {UDP_SERVER_ADDRESS}:{UDP_SERVER_PORT} """) pkt_list = None pkt_log = None is_running = True sock_first_lock = threading.Lock() sock_second_lock = threading.Lock() def smart_recv(sock, pkt_kind): sock.settimeout(0.5) pkt = None while pkt is None and is_running: try: pkt, server_address = sock.recvfrom(4096) if pkt_kind == 'list': global pkt_list pkt_list = pkt.decode() elif pkt_kind == 'log': global pkt_log pkt_log = pkt.decode() print("\nLog received:") print(pkt_log) return except socket.timeout: if not is_running: exit(0) continue def recv_pkt(sock): sock_first_lock.acquire() smart_recv(sock, 'list') sock_first_lock.release() sock_second_lock.acquire() smart_recv(sock, 'log') sock_second_lock.release() # Define a signal handler function def signal_handler(sig, frame): global is_running is_running = False print("\nCtrl+C pressed. Exiting...") # cleanup operations if sock_first_lock.locked(): sock_first_lock.release() if sock_second_lock.locked(): sock_second_lock.release() exit(0) # Register the signal handler for SIGINT (Ctrl+C) signal.signal(signal.SIGINT, signal_handler) # Create a UDP socket udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock_first_lock.acquire() # acquire the lock for the thread to use the socket later # start the receive thread threading.Thread(target=recv_pkt, args=(udp_socket,)).start() # Step 1: Send a request packet # Define the struct format struct_format = "5s128s" # 5 bytes for sync and bytes for the word # Create the struct with values sync = bytes([0xAA, 0xBB, 0xCC, 0xDD, 0xEE]) word = b"REQUEST_LIST_LOGS" # Ensure it's bytes, not a string # Pack the struct into bytes request_packet = struct.pack(struct_format, sync, word) udp_socket.sendto(request_packet, (UDP_SERVER_ADDRESS, UDP_SERVER_PORT)) sock_first_lock.release() sock_second_lock.acquire() # acquire the lock for the thread to use the socket later # Step 2: Retrieve available log files # Receive the available logs while pkt_list is None: sleep(0.5) available_logs = pkt_list.split('\n') # srot the logs by the log number if available_logs[-1] == '': available_logs.pop() available_logs.sort(key=lambda x: int(x.split('_')[1].split('.')[0])) print("Available logs:") for i, log in enumerate(available_logs): if log == '' and i == 0: print("No logs available") exit(1) if log == '': continue print(f"{i}. {log}") # Step 3: Wait for user input to select a log selected_log_index = int(input("Enter the number of the log you want to retrieve: ")) selected_log_name = available_logs[selected_log_index] # Step 4: Send the selected log request # Define the struct format # 5 bytes for sync and 21 bytes for the word and 4 for int struct_format = "5s11sI" selected_log_request = b"REQUEST_LOG" selected_log_request_pkt = struct.pack(struct_format, sync, selected_log_request, selected_log_index) udp_socket.sendto(selected_log_request_pkt, (UDP_SERVER_ADDRESS, UDP_SERVER_PORT)) sock_second_lock.release() # release the lock for the thread to use the socket later # Step 5: Wait for the selected log while pkt_log is None: sleep(0.5) selected_log_content = pkt_log.encode() # Step 6: Save the selected log as a file log_file_name = f"{selected_log_name}" with open(log_file_name, 'w') as log_file: log_file.write(selected_log_content.decode()) print(f"Log '{selected_log_name}' saved as '{log_file_name}'") # Close the UDP socket udp_socket.close()
#include "enumerate.hpp" #include <array> #include <catch2/catch_test_macros.hpp> #include <vector> TEST_CASE("enumerate") { SECTION("const auto&, non-const vector") { const int arrSize = 10; std::vector<int> vec(arrSize); size_t expectedIndex = 0; for (const auto& [index, value] : enumerate(vec)) { // value = 42; //should not compile REQUIRE(index == expectedIndex); expectedIndex++; } } SECTION("const auto&, const array") { const std::array<int, 10> arr{}; size_t expectedIndex = 0; for (const auto& [index, value] : enumerate(arr)) { REQUIRE(index == expectedIndex); expectedIndex++; } } SECTION("auto&, non-const array") { const int arrSize = 10; std::array<int, arrSize> arr{}; arr.fill(0); for (auto& [index, value] : enumerate(arr)) { // index = 42; // should not compile value = static_cast<int>(index); } for (const auto [index, value] : enumerate(arr)) { REQUIRE(value == index); } } }
function [solution] = SolveMIQP(casadi_formulation) import casadi.*; %% Create the LCQP problem = ObtainLCQPFromCasadi(casadi_formulation, 0); %% Change to MIQP setting MIQP_formulation = ObtainMIQP(problem); %% Build solver varnames = {}; nV = MIQP_formulation.nV; nC = MIQP_formulation.nC; nComp = MIQP_formulation.nComp; for i=1:nV varnames{i} = ['x', num2str(i)]; end for i=1:nComp varnames{nV+i} = ['zL', num2str(i)]; end for i=1:nComp varnames{nV+nComp+i} = ['zR', num2str(i)]; end model.varnames = varnames; model.Q = MIQP_formulation.Q; model.obj = MIQP_formulation.g; model.A = MIQP_formulation.A; model.rhs = MIQP_formulation.rhs; model.sense = '<'; model.lb = MIQP_formulation.lb; model.ub = MIQP_formulation.ub; if isfield(MIQP_formulation, "x0") model.start = MIQP_formulation.x0; end % Set variable types for i=1:nV model.vtype(i) = 'C'; end for i=1:nComp model.vtype(nV+i) = 'B'; model.vtype(nV+nComp+i) = 'B'; end %% Run the solver params.outputflag = 0; params.IntFeasTol = 5e-7; params.FeasibilityTol = 5e-7; tic; results = gurobi(model, params); solution.stats.elapsed_time_w_overhead = toc; % Save the solution and stats solution.stats.elapsed_time = results.runtime; solution.stats.exit_flag = 1 - strcmp(results.status, 'OPTIMAL'); solution.x = zeros(nV+2*nComp,1); solution.stats.compl = inf; solution.stats.obj = inf; % Evaluate complementarity if solution.stats.exit_flag == 0 compl_L = MIQP_formulation.L*results.x - MIQP_formulation.lb_L; compl_R = MIQP_formulation.R*results.x - MIQP_formulation.lb_R; compl = compl_L'*compl_R; solution.x = results.x; solution.stats.compl = compl; solution.stats.obj = full(problem.Obj(solution.x(1:nV))); end end
<template> <v-text-field v-model.trim="value" :error-messages="[].concat(errors, externalErrors)" :name="name" label="Artist" @blur="validate" @focus="$emit('focus')" /> </template> <script> import { required } from "vuelidate/lib/validators"; import InputMixin from "@/mixins/InputMixin"; import { requiredMessage } from "@/helpers"; export default { name: "InputArtist", mixins: [InputMixin], data: () => ({ name: "artist" }), validations: { value: { required } }, methods: { validate () { this.errors = []; if (!this.$v.value.required) { this.errors.push(requiredMessage("Artist")); } } } }; </script>
This file explains the "defung" macro and has some exercises on using macros. Guard verification (see the documenation topic "Guards") is used to show that if the inputs to a function satisfy the guard conjecture, any function call resulting from a call of the verified function is Common Lisp compliant. This allows for efficient execution of verified functions, as is discussed in Applied Formal Logic: An Approach. When specifying and verifying guards, one often has to prove theorems about the type of the return value of a function when its input satisfies the guard conjecture. We find it helpful to be able to specify the return type next to the guard condition and have developed "defung", a simple macro to do this. Consider the following example: :trans1 (defung set-union (X Y) "set union, i.e., X U Y" (declare (xargs :guard (true-listp X))) ((implies (true-listp Y) (true-listp (set-union X Y))) :rule-classes :type-prescription) (if (endp X) Y (cons (car X) (set-union (cdr X) Y)))) which returns (PROGN (DEFUN SET-UNION (X Y) "set union, i.e., X U Y" (DECLARE (XARGS :GUARD (TRUE-LISTP X))) (IF (ENDP X) Y (CONS (CAR X) (SET-UNION (CDR X) Y)))) (DEFTHM FAST-SETS::SET-UNION-RETURN-TYPE (IMPLIES (TRUE-LISTP Y) (TRUE-LISTP (SET-UNION X Y))) :RULE-CLASSES :TYPE-PRESCRIPTION)) So "defung" takes an extra argument that appears after the declaration and generates two events: a "defun", as expected, and the extra argument is turned into a "defthm" whose name is derived from the "defun". If you want some practice with macros, here are two exercises to try. 1. Write a function "make-sym" that given symbols "s" and "suf", returns the symbol "s-suf" in the package of "s"; specify and verify the guard of "make-sym". 2. Use "make-sym" to write the "defung" macro.
# qq-plots-subclusters.R # ----------------------------------------------------------------------------- # Author: Albert Kuo # Date last modified: Mar 5, 2023 # # Make QQ plots for subclusters of inhibitory neurons cortex 1 # Packages suppressPackageStartupMessages({ library(here) library(tidyverse) library(tictoc) library(scran) library(scater) library(BiocSingular) library(SingleCellExperiment) library(snakecase) library(cowplot) }) source(here("./mouse_cortex/code/distribution-plots-helpers.R")) ############## # Read data # ############## tic("entire process") run_number = "all" sce = readRDS(here("mouse_cortex", "salmon_quants", "preandmrna_pipeline", paste0("sce_", run_number, ".rds"))) # Subset to cell type cell_type = "Inhibitory neuron" sce_sub = sce[, colData(sce)$ding_labels == cell_type & !is.na(colData(sce)$ding_labels)] dim(sce_sub) # Subset to cortex sce_sub = sce_sub[, colData(sce_sub)$cortex == "cortex1"] dim(sce_sub) # Use quickcluster (hierarchical clustering) to get subclusters set.seed(1) tic("quickCluster") clust = quickCluster(sce_sub, min.size = 0) toc() p_ls = list() for(clust_num in 1:8){ # Take chosen cluster if(clust_num < 8){ # there are 7 subclusters counts_sub = counts(sce_sub[, which(clust == clust_num)]) } else if (clust_num == 8) { counts_sub = counts(sce_sub) # run all cells for cell type in last iteration } print(dim(counts_sub)) summary(colSums(counts_sub)) ################### # Plot QQ plots # ################### chi_obs_pois = p_chisq_test_2_grouped(counts_sub, distribution = "poisson") plot_dt = tibble(chi_obs = chi_obs_pois[[1]]) %>% # expression = rowSums(counts_sub_scaled)) %>% arrange(chi_obs) %>% drop_na() %>% mutate(chi_quantile = qchisq(p = (1:length(chi_obs))/length(chi_obs), df = chi_obs_pois[[2]] - 1), percentile_color = case_when(chi_obs > quantile(chi_obs, 0.995) ~ "> 99.5", chi_obs > quantile(chi_obs, 0.95) ~ "> 95", #chi_obs > quantile(chi_obs, 0.90) ~ "> 90", T ~ "rest")) p_ls[[clust_num]] = plot_dt %>% ggplot(aes(x = chi_quantile, y = chi_obs, color = percentile_color)) + geom_point(size = 0.5) + geom_abline(slope = 1, intercept = 0) + # coord_cartesian(ylim = c(0, 20)) + labs(x = "Chi-squared quantiles", y = "Goodness of fit statistic") + theme_bw() toc() } # Construct plot # Apply plot aesthetics to QQ plots apply_fig1_aesthetics_qq = function(plt){ plt = plt + scale_x_continuous(limits = c(0, 15)) + scale_y_continuous(limits = c(0, 30)) + theme(axis.text = element_text(size = 14), axis.title = element_text(size = 15), #plot.title = element_text(size = 20), legend.position = "none") } # Get legend legend_qq <- get_legend( p_ls[[8]] + scale_color_manual(name = "Percentile", labels = c("<95", ">95", ">99.5"), values = c("#619cff", "#f8766d", "#00ba38")) + guides(color = guide_legend(nrow = 1, override.aes = list(size = 2))) + theme(legend.position = "bottom", legend.title = element_text(size = 22), legend.text = element_text(size = 18)) ) p_ls = lapply(p_ls, FUN = apply_fig1_aesthetics_qq) p = plot_grid(plot_grid(p_ls[[8]], p_ls[[2]], p_ls[[3]], p_ls[[4]], p_ls[[5]], p_ls[[6]], p_ls[[7]], ncol = 4, labels = "auto"), legend_qq, ncol = 1, rel_heights = c(3, .1)) p ggsave(here("./mouse_cortex/plots/qq_plots_subclusters.png"), plot = p, width = 16, height = 8)
import { useState } from 'react'; import { Navbar } from './components/Navbar/Navbar'; import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import data from './json/data.json'; import Home from './pages/Home/Home'; import Dest from './pages/Dest/Dest'; import Crew from './pages/Crew/Crew'; import MobileMenu from './components/MobileMenu/MobileMenu'; import Tech from './pages/Tech/Tech'; function App() { const [siteManager, setSiteManager] = useState({ menuToggled: false, }); const toggleMenu = () => { setSiteManager(prev => { const {menuToggled: toggled} = prev return {...prev, menuToggled: !toggled}; }) }; const {menuToggled: toggled} = siteManager; return ( <div className='app'> <Router> <Navbar toggled={toggled} toggleMenu={toggleMenu}/> <Routes> <Route exact path='/' element={<Home />}/> <Route path='/destination' element={<Dest data={data.destinations}/>}/> <Route path='/crew' element={<Crew data={data.crew}/>}/> <Route path='/technology' element={<Tech data={data.technology}/>}/> </Routes> {toggled && <MobileMenu />} </Router> </div> ) } export default App
<!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.22.1/dist/bootstrap-table.min.css"> <!-- Latest compiled and minified JavaScript --> <script src="https://unpkg.com/bootstrap-table@1.22.1/dist/bootstrap-table.min.js"></script> <!-- Latest compiled and minified Locales --> <script src="https://unpkg.com/bootstrap-table@1.22.1/dist/locale/bootstrap-table-zh-CN.min.js"></script> <script> let onlineUserCountAndLastPushAt; const $table = $('#table') $(function () { GetOnlineUserCountAndLastPushAt() }) //初始化表格 function initTable() { $table.bootstrapTable({ columns: [ { field: 'name', title: '名称', }, { field: 'agreement', title: '协议', }, { title: '状态', formatter: function (value, row, index) { if (onlineUserCountAndLastPushAt[row.id] == undefined) { return `<span class="badge badge-dot"> <i class="bg-warning"></i> <span class="status">离线</span> </span>` }else{ let htmlStr = `${onlineUserCountAndLastPushAt[row.id][1]} | ` if ((Math.floor(new Date().getTime() / 1000) - onlineUserCountAndLastPushAt[row.id][2]) < 300) { htmlStr = htmlStr + `<span class="badge badge-dot"> <i class="bg-success"></i> <span class="status">正常</span> </span>` }else{ htmlStr = htmlStr + `<span class="badge badge-dot"> <i class="bg-dark"></i> <span class="status">异常</span> </span>` } return htmlStr } } }, { field: 'rate', title: '倍率', }, { field: 'updated_at', title: '更新时间', }, { field: 'operate', title: '操作', width:120, events: { 'click #copy_url': function (e, value, row, index) { copy_url(row) }, }, formatter: function (value, row, index) { return ` <div class="btn-group" role="group" aria-label="Basic example"> <button id="copy_url" type="button" class="btn btn-twitter btn-icon-only" data-toggle="tooltip" data-placement="left" title="复制URL"><span class="btn-inner--icon"><i class="ni ni-single-copy-04"></i></span></button> </div>`; } } ], //列 url: '/user/node', method: 'post', //请求方法 dataType: 'json',//数据格式 pagination: false, //是否显示页码 sidePagination: "server",//服务器处理分页 serverSort: "true",//是否服务器处理排序 sortName:'id', sortOrder:'desc', showRefresh: true, //显示刷新按钮 showColumns: true, //是否显示列下拉列表按钮 showFullscreen: true, //是否显示全屏按钮 responseHandler: function (res) { //response数据处理 return { "rows": res.data.data, }; }, //搜索 queryParams: function (x) { $("select[data-function='search']").each(function (i, domEle) { x[$(domEle).attr("name")] = domEle.value }) $("input[data-function='search']").each(function (i, domEle) { const bindingDomID = $(domEle).attr("data-select-binding") if (bindingDomID != undefined) { x[$(bindingDomID).attr("name")] = $(bindingDomID).val() } x[$(domEle).attr("name")] = domEle.value }) return x }, onLoadSuccess: function() { $('[data-toggle="tooltip"]').tooltip() }, formatNoMatches: function(){ return "当前订阅没有节点"; }, }) } //获取所有服务器当前在线用户数量和服务器最后提交时间 function GetOnlineUserCountAndLastPushAt() { if (onlineUserCountAndLastPushAt == undefined) { $.ajax({ type: "POST", url: "/user/node/online_user_count_and_last_push_at", dataType: "json", success: function (data) { if (data.code == 0) { onlineUserCountAndLastPushAt = data.data.data initTable() } else { notify('danger', data.message) } }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown) notify('danger', errorThrown) }, complete: function () {//不管成功还是失败 都会进这个函数 } }); } } function copy_url(params) { var serviceJson = JSON.parse(params.service_json); var url = ""; switch (params.agreement) { case "v2ray/vmess": var d = { "v": "2", "add": params.host, //链接地址 "ps": params.name, //名字 "port": params.port, //端口 "id": "{{.user.Uuid}}", //uuid "aid": "0", "net": serviceJson["net"], "type": serviceJson["type"], "tls": serviceJson["tls"], "sni": serviceJson["sni"], "alpn": serviceJson["alpn"], "host": serviceJson["host"], "path": serviceJson["path"], "scy": serviceJson["scy"], "fp": serviceJson["fp"], }; url = window.btoa(unescape(encodeURIComponent(JSON.stringify(d)))); url = "vmess://"+ url; break; case "v2ray/vless": url = `vless://{{.user.Uuid}}@${params.host}:${params.port}?encryption=${serviceJson.encryption}&flow=${serviceJson.flow}&security=${serviceJson.security}&sni=${serviceJson.sni}&alpn=${serviceJson.alpn}&fp=${serviceJson.fp}&pbk=${serviceJson.pbk}&sid=${serviceJson.sid}&spx=${serviceJson.spx}&type=${serviceJson.type}&serviceName=${serviceJson.serviceName}&mode=${serviceJson.mode}&headerType=${serviceJson.headerType}&quicSecurity=${serviceJson.quicSecurity}&key=${serviceJson.key}&host=${serviceJson.host}&path=${serviceJson.path}&seed=${serviceJson.seed}#${params.name}` break; case "shadowsocks/ss2022": url = `ss://${window.btoa(unescape(encodeURIComponent(serviceJson.encryption+":"+"{{.user.Uuid}}")))}@${params.host}:${params.port}#${params.name}` break; case "trojan/trojan": url = `trojan://{{.user.Uuid}}@${params.host}:${params.port}?security=${serviceJson.security}&sni=${serviceJson.sni}&alpn=${serviceJson.alpn}&fp=${serviceJson.fp}&type=${serviceJson.type}&headerType=${serviceJson.headerType}&host=${serviceJson.host}#${params.name}` break; default: break; } console.log(params) console.log(serviceJson) copy_text(url); } function copy_text(text) { let input_dom = document.createElement('input'); input_dom.value = text; document.body.appendChild(input_dom);//向页面底部追加输入框 input_dom.select();//选择input元素 document.execCommand("Copy");//执行复制命令 notify('success', "复制成功") input_dom.remove();//删除动态创建的节点 } </script>
<?php // src/Entity/Category.php namespace App\Entity; use App\Repository\CategoryRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; #[ORM\Entity(repositoryClass: CategoryRepository::class)] class Category { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column(type: "integer")] private $id; #[ORM\Column(type: "string")] private $name; #[ORM\OneToMany(targetEntity: Car::class, mappedBy: "category")] private $cars; public function __construct() { $this->cars = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } /** * @return Collection|Car[] */ public function getCars(): Collection { return $this->cars; } public function addCar(Car $car): self { if (!$this->cars->contains($car)) { $this->cars[] = $car; $car->setCategory($this); } return $this; } public function removeCar(Car $car): self { if ($this->cars->removeElement($car)) { // set the owning side to null (unless already changed) if ($car->getCategory() === $this) { $car->setCategory(null); } } return $this; } }
import { Image, StyleSheet, Text, View } from "react-native"; import React from "react"; import PrimaryText from "./PrimaryText"; import SecondaryText from "./SecondaryText"; import LevelIcon from "./LevelIcon"; export default function DriverListItem({ driver }) { return ( <View style={{ flexDirection: "row", padding: 16, borderWidth: 1, borderRadius: 8, marginVertical: 4, borderColor: "#F0F2F5", }} > <Image source={driver.imgUrl} style={{ height: 42, width: 42, borderRadius: 21 }} /> <View style={{ marginLeft: 8, paddingVertical: 7, flex: 1, justifyContent: "space-between", }} > <PrimaryText style={{ fontSize: 14, color: "#333333" }}> {driver.name} </PrimaryText> <SecondaryText style={{ fontSize: 12, color: "#8E939C" }}> {driver.level} </SecondaryText> </View> <LevelIcon level={driver.level} size={35} /> </View> ); }
import streamlit as st from st_aggrid import AgGrid from datetime import datetime import pandas as pd from actors.services import ActorsService from genres.services import GenreService from movies.services import MovieService def show_movies(): movie_service = MovieService() movies = movie_service.get_movies() if movies: st.write('Lista de filmes') movies_df = pd.json_normalize(movies) movies_df = movies_df.drop(columns=['actors', 'genre.id']) AgGrid( data=movies_df, reload_data=True, key='actors_grid', ) else: st.warning('Nenhum filme encontrado') st.title('Cadastrar novo Filme') title = st.text_input('Nome do Filme') release_date = st.date_input( label='Data de lançamento', value=datetime.today(), min_value=datetime(1600, 1, 1).date(), max_value=datetime.today(), format='DD/MM/YYYY' ) genre_service = GenreService()#coleta na api todos generos genres = genre_service.get_genres() genres_names = {genre['name']: genre['id'] for genre in genres} selected_genre_name = st.selectbox('Genero', list(genres_names.keys())) actor_service = ActorsService() actors = actor_service.get_actors() actors_names = {actor['name']: actor['id'] for actor in actors} selected_actor_name = st.multiselect('Ator', list(actors_names.keys())) selected_actors_ids = [actors_names[name] for name in selected_actor_name]#usado para pegar todos IDs selecionado e enviar para api uma lista resume= st.text_area('Resumo') if st.button('Cadastrar'): new_movie = movie_service.create_movie( title=title, release_date=release_date, genre=genres_names[selected_genre_name], actors=selected_actors_ids, resume=resume, ) if new_movie: st.rerun() else: st.error('Erro ao adastrar o ator. Verificar os campos') #st.success(f'Ator {name} cadastrado com sucesso!')
const express = require("express"); const auth_router = express.Router(); const jwt = require('jsonwebtoken'); const bcrypt = require('bcrypt'); const { adminDataValidateForLogin, adminDataValidateForCreate , adminValidateForPasswordUpdate} = require('../middlewares/admin.middleware'); const { validationResult } = require('express-validator'); const adminModel = require('..//models/admin_model'); const adminservices = require("../services/admin_services"); require('dotenv').config(); const authenticateToken = require('../middlewares/tokenvalidation'); const logger = require('../utils/logger'); const Admins_model = require("..//models/admin_model"); auth_router.post("/adminRegister", adminDataValidateForCreate, async (req, res) => { // Extracts the validation errors of an express request try { const errors = validationResult(req); if (!errors.isEmpty()) { const formattedErrors = []; errors.array().map(err => formattedErrors.push({ [err.path]: err.msg })); logger.error({ label: 'Controller', message: formattedErrors }); return res.status(422).json({ success: false, errors: formattedErrors }); } const hashedPassword = await bcrypt.hash(req.body.password, 10); let adminObj = { password: hashedPassword, first_name: req.body.first_name, last_name: req.body.last_name, email: req.body.email, phone_number: req.body.phone_number } let result = await adminservices.createadmin(adminObj); if (result.status == false) { return res.status(result.code).json(result); } return res.status(200).send(result); } catch (error) { return res.status(500).json({ success: false, error: error.message }); } }); auth_router.post("/adminLogin", adminDataValidateForLogin, async function (req, res) { try { const errors = validationResult(req); if (!errors.isEmpty()) { const formattedErrors = []; errors.array().map(err => formattedErrors.push({ [err.path]: err.msg })); return res.status(422).json({ success: false, errors: formattedErrors }); } let result = await adminModel.findAll({ where: { email: req.body.email } }); // verify credentials, generate the token and send the token to client if (result.length != 0) { const adminObj = {}; for (let item of result) { adminObj.admin_id = item.admin_id; adminObj.email = item.email; adminObj.password = item.password; } const isPasswordValid = await bcrypt.compare(req.body.password, adminObj.password); if (!isPasswordValid) { return res.status(401).json({ message: 'Invalid password' }); } // Generate JWT token const JWTToken = jwt.sign({ adminId: adminObj.admin_id }, process.env.JWT_SECRETKEY, { expiresIn: '1h' }); return res.status(200).json({ success: true, token: JWTToken ,adminId: adminObj.admin_id }); } else { return res.status(401).json({ success: false, message: "Invalid User email" }); } } catch (error) { res.status(500).json({ success: false, message: error.message }); } }); auth_router.put("/adminPasswordUpdate", adminValidateForPasswordUpdate, async (req, res) => { try { const errors = validationResult(req); if (!errors.isEmpty()) { const formattedErrors = []; errors.array().map(err => formattedErrors.push({ [err.path]: err.msg })); //code for log message as the formatted errors is an array of objects, it will display as undefined in the log file. let logMessage = ``; for (let item of formattedErrors) { for (let key in item) { logMessage += ` [${key}]: ${item[key]} `; //console.log(`${key}: ${item[key]}`); } logMessage += `,`; } logMessage = logMessage.slice(0, -1); //msg = req.url + " - " + req.method; logger.error({ label: `${req.url} - ${req.method}`, message: logMessage }); return res.status(422).json({ success: false, msg: logMessage }); } const hashedPassword = await bcrypt.hash(req.body.password, 10); let adminObj = { password:hashedPassword, email: req.body.email, } let result = await adminservices.updateAdminPassword(adminObj,req.body.email); if (result.status == false) { logger.error({ label: `${req.url} - ${req.method}`, message: result.msg }); return res.status(500).json(result); } logger.log({ level: 'info', label: `${req.url} - ${req.method}`, message: 'action successfully executed.' }); res.status(200).json(result); } catch (error) { logger.error({ label: `${req.url} - ${req.method}`, message: error.message }); return res.status(500).json({ status: false, msg: "internal server error" }); } }); module.exports = auth_router;
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HoardSlime : MonoBehaviour, IDamageable { Rigidbody2D rb; public float damage = 1f; public DetectionZone detectionZone; public Collider2D hitCollider; public float knockbackForce = 200f; public Animator animator; private SlimeSpawner spawner; public bool isFacingRight = true; private NPCManager npcManager; public GameObject alarm; public float moveSpeed = 500f; public float attackRange = 0.5f; public GameObject[] dropPrefab; [SerializeField] private EnemyHealthBar enemyHealthBar; public GameObject enemyHealthObject; public GameObject floatingDamage; public bool isElemental; public SlimeHorde slimeHorde; public float Health { set { _health = value; if (_health <= 0) { moveSpeed = 0; hitCollider.enabled = false; animator.SetTrigger("Death"); if (isElemental) { Debug.Log("elemental monster dies -1"); npcManager.OnElementalDestroyed(); } else { Debug.Log("Normal monster dies -1"); npcManager.OnEnemyDestroyed(); } // DropItem(); if (transform.parent != null) { Destroy(transform.parent.gameObject, 1.2f); } InventoryManager.instance.ReduceDurability(); slimeHorde.PrefabDestroyed(); } } get { return _health; } } private void Awake() { enemyHealthBar = GetComponentInChildren<EnemyHealthBar>(); } // Start is called before the first frame update public float _health, maxHealth = 10; public void Start() { rb = GetComponent<Rigidbody2D>(); animator = GetComponent<Animator>(); spawner = FindObjectOfType<SlimeSpawner>(); npcManager = FindObjectOfType<NPCManager>(); slimeHorde = FindObjectOfType<SlimeHorde>(); } private void FixedUpdate() { if (detectionZone.detectedObj.Count > 0) { enemyHealthObject.SetActive(true); alarm.gameObject.SetActive(true); Invoke("DeactivateAlarm", 1.2f); Vector2 direction = (detectionZone.detectedObj[0].transform.position - transform.position).normalized; // Update facing direction based on movement direction if (direction.x > 0) { isFacingRight = true; } else if (direction.x < 0) { isFacingRight = false; } rb.AddForce(direction * moveSpeed * Time.deltaTime); // Get the position of the closest detected object Vector2 playerPos = detectionZone.detectedObj[0].transform.position; // Check if the player is close enough to attack float distanceToPlayer = Vector2.Distance(transform.position, playerPos); if (distanceToPlayer <= attackRange) { animator.SetTrigger("Attack"); } } else { enemyHealthObject.SetActive(false); } } private void OnDestroy() { } void DeactivateAlarm() { alarm.gameObject.SetActive(false); } public void OnHit(float damage, Vector2 knockback) { Health -= damage; enemyHealthBar.UpdateHealthBar(_health, maxHealth); // Create a new GameObject with the floating damage value var floatingDamageGO = Instantiate(floatingDamage, transform.position, Quaternion.identity); floatingDamageGO.GetComponent<TextMesh>().text = damage.ToString(); // Destroy the floating damage after a set amount of time Destroy(floatingDamageGO, 1f); rb.AddForce(knockback); animator.SetTrigger("Hurt"); Debug.Log(Health); if (_health <= 0) { enemyHealthObject.SetActive(false); Destroy(floatingDamageGO, 1f); } } public void OnHit(float damage) { Health -= damage; enemyHealthBar.UpdateHealthBar(_health, maxHealth); // Create a new GameObject with the floating damage value var floatingDamageGO = Instantiate(floatingDamage, transform.position, Quaternion.identity); floatingDamageGO.GetComponent<TextMesh>().text = damage.ToString(); // Destroy the floating damage after a set amount of time Destroy(floatingDamageGO, 1f); animator.SetTrigger("Hurt"); Debug.Log(Health); if (_health <= 0) { enemyHealthObject.SetActive(false); Destroy(floatingDamageGO, 1f); } } private bool isBurning = false; public void OnBurn(float damage, float time) { if (!isBurning) { StartCoroutine(ApplyBurnDamage(damage, time)); } Debug.Log("BURRRRN"); } private IEnumerator ApplyBurnDamage(float damage, float time) { float elapsedTime = 0f; while (elapsedTime < time && _health > 0) { isBurning = true; yield return new WaitForSeconds(1f); OnHit(damage); Debug.Log(isBurning); elapsedTime += 1f; } isBurning = false; } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Player")) { animator.SetBool("Attack", true); } else { animator.SetTrigger("Attack"); } } private void DropItem() { if (dropPrefab != null) { foreach (var prefab in dropPrefab) { Instantiate(prefab, transform.position, Quaternion.identity); } } } public void OnDark(float time) { StartCoroutine(Slow(time)); } public IEnumerator Slow(float time) { rb.constraints = RigidbodyConstraints2D.FreezeAll; yield return new WaitForSeconds(time); rb.constraints = RigidbodyConstraints2D.FreezeRotation; } }
--- title: 在 .NET 中将 LaTeX Math 渲染为 SVG linktitle: 在 .NET 中将 LaTeX Math 渲染为 SVG second_title: Aspose.TeX .NET API description: 了解如何使用 Aspose.TeX 在 .NET 中将 LaTeX 数学方程渲染为 SVG。带有可自定义选项的分步指南,用于精确的数学表示。 type: docs weight: 10 url: /zh/net/svg-math-rendering/render-latex-math-svg/ --- ## 介绍 在不断发展的 .NET 开发世界中,渲染 LaTeX 数学方程是一个至关重要的方面,尤其是在处理科学或数学应用程序时。 Aspose.TeX for .NET 为这一需求提供了强大的解决方案,允许您将 LaTeX 数学方程无缝渲染为可缩放矢量图形 (SVG)。在本教程中,我们将指导您完成在 .NET 环境中使用 Aspose.TeX 库渲染 LaTeX 数学方程的过程。 ## 先决条件 在我们深入了解分步指南之前,请确保您具备以下先决条件: - Aspose.TeX for .NET Library:从以下位置下载并安装该库[发布页面](https://releases.aspose.com/tex/net/). - 对 LaTeX 的基本理解:熟悉 LaTeX 语法,因为它构成了我们将要渲染的数学方程的基础。 - .NET 开发环境:在您的计算机上设置一个有效的 .NET 开发环境。 ## 导入命名空间 在您的 .NET 应用程序中,首先导入必要的命名空间以利用 Aspose.TeX 功能: ```csharp using Aspose.TeX.Features; ``` 现在,让我们将该过程分解为多个步骤: ## 第 1 步:创建渲染选项 ```csharp //创建渲染选项。 MathRendererOptions options = new SvgMathRendererOptions(); ``` ## 第 2 步:指定前导码 ```csharp //指定序言。 options.Preamble = @"\usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{color}"; ``` ## 第 3 步:指定缩放系数和颜色 ```csharp //指定缩放因子(例如,300%)。 options.Scale = 3000; //指定前景色。 options.TextColor = System.Drawing.Color.Black; //指定背景颜色。 options.BackgroundColor = System.Drawing.Color.White; ``` ## 步骤 4:配置输出选项 ```csharp //指定日志文件的输出流。 options.LogStream = new System.IO.MemoryStream(); //指定是否在控制台上显示终端输出。 options.ShowTerminal = true; ``` ## 第 5 步:渲染 LaTeX 数学方程 ```csharp //创建公式图像的输出流。 using (System.IO.Stream stream = System.IO.File.Open( System.IO.Path.Combine("Your Output Directory", "math-formula.svg"), System.IO.FileMode.Create)) { //运行渲染。 new SvgMathRenderer().Render(@"\begin{equation*} e^x = x^{\color{red}0} + x^{\color{red}1} + \frac{x^{\color{red}2}}{2} + \frac{x^{\color{red}3}}{6} + \cdots = \sum_{n\geq 0} \frac{x^{\color{red}n}}{n!} \end{equation*}", stream, options, out size); } ``` ## 第 6 步:显示结果 ```csharp //显示其他结果。 System.Console.Out.WriteLine(options.ErrorReport); System.Console.Out.WriteLine(); System.Console.Out.WriteLine("Size: " + size); ``` ## 结论 恭喜!您已成功学习如何使用 Aspose.TeX for .NET 将 LaTeX 数学方程呈现为 SVG。对于需要精确数学表示的应用来说,此功能非常宝贵。 ## 常见问题解答 ### Q1:我可以自定义渲染方程的颜色吗? A1:是的,您可以使用以下命令轻松自定义前景色和背景色`TextColor`和`BackgroundColor`渲染选项中的属性。 ### Q2:使用 Aspose.TeX for .NET 是否需要许可证? A2: 是的,您需要有效的许可证。您可以从以下位置获取一份[Aspose的购买页面](https://purchase.aspose.com/buy). ### Q3:我在哪里可以找到额外的支持或寻求帮助? A3:访问[Aspose.TeX 论坛](https://forum.aspose.com/c/tex/47)以获得社区支持和讨论。 ### Q4:如何获得用于测试目的的临时许可证? A4:从以下机构获取临时许可证[这里](https://purchase.aspose.com/temporary-license/). ### Q5:文档中有可用的示例教程吗? A5:是的,您可以在[Aspose.TeX 文档](https://reference.aspose.com/tex/net/).
######################################### # 用R语言10分钟上手神经网络模型 # http://blog.fens.me/r-nn-neuralnet/ # author:Dan Zhang ######################################### library(neuralnet) setwd("C:/work/R/neural/neural_networks") # 数据集 head(iris) # 神经元模型,没有隐藏层 nn <- neuralnet(Species=="setosa"~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris,hidden = 0) plot(nn) nn nn$result.matrix nn$startweights nn$weights head(nn$generalized.weights[[1]]) head(nn$data) nn$call nn$err.fct nn$act.fct nn$model.list head(nn$covariate) head(nn$response) head(nn$net.result[[1]]) # 单层神经网络 n1 <- neuralnet(Species=="setosa"~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris,hidden=1) plot(n1) n1$result.matrix # 单层神经网络,多分类 n2a <- neuralnet(Species~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris,hidden=1) plot(n2a) n2b <- neuralnet(Species~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris,hidden=c(2)) plot(n2b) # 多层神经网络,多分类 n3a <- neuralnet(Species~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris,hidden=c(1,1)) n3a$result.matrix n3b <- neuralnet(Species~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris,hidden=c(2,2)) n3b$result.matrix plot(n3b) n3c <- neuralnet(Species~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris,hidden=c(3,3)) n3c$result.matrix plot(n3c) n3d <- neuralnet(Species~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris,hidden=c(2,2,2)) n3d$result.matrix plot(n3d)
/* -- File : trv32p5_c_float.h -- -- Contents : Single-precision floating point application layer for -- the trv32p5 processor. -- -- Copyright (c) 2019-2021 Synopsys, Inc. This Synopsys processor model -- captures an ASIP Designer Design Technique. The model and all associated -- documentation are proprietary to Synopsys, Inc. and may only be used -- pursuant to the terms and conditions of a written license agreement with -- Synopsys, Inc. All other use, reproduction, modification, or distribution -- of the Synopsys processor model or the associated documentation is -- strictly prohibited. */ #ifndef INCLUDED_TRV32P5_C_FLOAT_H_ #define INCLUDED_TRV32P5_C_FLOAT_H_ #include "trv32p5_c_softfloat.h" // Concept: // wrapper intrinsic: call softfloat function // promote builtin operator on wrapper intrinsic that calls the emulation library // NOTE: Application types float & double have property llvm_emulated. The // LLVM frontend hence ignores the following promotions. It uses its own // emulation layer from the compiler-rt library. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Inline Intrinsics - Calling SoftFloat library functions // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ SoftFloat: float <> int conversions inline signed int wrap_f32_to_i32 (float32_t a) property(dont_generate) { return f32_to_i32_r_minMag (a, true); } inline unsigned int wrap_f32_to_ui32 (float32_t a) property(dont_generate) { return f32_to_ui32_r_minMag (a, true); } inline float32_t wrap_i32_to_f32 ( signed int a) property(dont_generate) { return i32_to_f32 (a); } inline float32_t wrap_ui32_to_f32 (unsigned int a) property(dont_generate) { return ui32_to_f32 (a); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ SoftFloat: float <> long long conversions inline signed long long wrap_f32_to_i64 (float32_t a) property(dont_generate) { return f32_to_i64_r_minMag (a, true); } inline unsigned long long wrap_f32_to_ui64 (float32_t a) property(dont_generate) { return f32_to_ui64_r_minMag (a, true); } inline float32_t wrap_i64_to_f32 ( signed long long a) property(dont_generate) { return i64_to_f32 (a); } inline float32_t wrap_ui64_to_f32 (unsigned long long a) property(dont_generate) { return ui64_to_f32 (a); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ SoftFloat: Arithmetic Operations inline float32_t wrap_f32_add (float32_t a, float32_t b) property(dont_generate) { return f32_add (a,b); } inline float32_t wrap_f32_sub (float32_t a, float32_t b) property(dont_generate) { return f32_sub (a,b); } inline float32_t wrap_f32_mul (float32_t a, float32_t b) property(dont_generate) { return f32_mul (a,b); } inline float32_t wrap_f32_div (float32_t a, float32_t b) property(dont_generate) { return f32_div (a,b); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ SoftFloat: Comparisons inline bool wrap_f32_lt (float32_t a, float32_t b) property(dont_generate) { return f32_lt (a,b); } inline bool wrap_f32_le (float32_t a, float32_t b) property(dont_generate) { return f32_le (a,b); } inline bool wrap_f32_eq (float32_t a, float32_t b) property(dont_generate) { return f32_eq (a,b); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Type Conversions // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Emulated: float <> int promotion operator signed int ( float ) = signed int wrap_f32_to_i32 (float32_t); promotion operator unsigned int ( float ) = unsigned int wrap_f32_to_ui32 (float32_t); promotion operator float ( signed int ) = float32_t wrap_i32_to_f32 ( signed int); promotion operator float ( unsigned int ) = float32_t wrap_ui32_to_f32 (unsigned int); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Emulated: float <> long long promotion operator signed long long ( float ) = signed long long wrap_f32_to_i64 (float32_t); promotion operator unsigned long long ( float ) = unsigned long long wrap_f32_to_ui64 (float32_t); promotion operator float ( signed long long ) = float32_t wrap_i64_to_f32 ( signed long long); promotion operator float ( unsigned long long ) = float32_t wrap_ui64_to_f32 (unsigned long long); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Remap: float <> char - reuse float <> int inline operator float ( signed char a ) { return (float) ( signed int)a; } inline operator float ( unsigned char a ) { return (float) (unsigned int)a; } inline operator signed char ( float a ) { return ( signed char) ( signed int)a; } inline operator unsigned char ( float a ) { return (unsigned char) (unsigned int)a; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Remap: float <> short - reuse float <> int inline operator float ( signed short a ) { return (float) ( signed int)a; } inline operator float ( unsigned short a ) { return (float) (unsigned int)a; } inline operator signed short ( float a ) { return ( signed short) ( signed int)a; } inline operator unsigned short ( float a ) { return (unsigned short) (unsigned int)a; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Arithmetic Operators // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Emulated: Binary Operators promotion float operator + (float,float) = float32_t wrap_f32_add (float32_t,float32_t); promotion float operator - (float,float) = float32_t wrap_f32_sub (float32_t,float32_t); promotion float operator * (float,float) = float32_t wrap_f32_mul (float32_t,float32_t); promotion float operator / (float,float) = float32_t wrap_f32_div (float32_t,float32_t); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Comparison Operators // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Emulated promotion bool operator < (float a, float b) = bool wrap_f32_lt (float32_t,float32_t); promotion bool operator <= (float a, float b) = bool wrap_f32_le (float32_t,float32_t); promotion bool operator == (float a, float b) = bool wrap_f32_eq (float32_t,float32_t); inline bool operator != (float a, float b) { return !(a==b); } inline bool operator > (float a, float b) { return (b < a); } // a,b swapped inline bool operator >= (float a, float b) { return (b <= a); } // a,b swapped // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~ Reinterpret Functions // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // float behaves like unsigned int promotion int as_int32 (float) property(reinterpret) = nil; promotion float as_float (int) property(reinterpret) = nil; #endif /* INCLUDED_TRV32P5_C_FLOAT_H_ */
import React, { Component } from "react"; import { getMovies } from "../services/fakeMovieService"; import Like from "./common/Like"; import Pagination from "./Pagination"; import { paginate } from "../utils/paginate"; import ListGroup from "./ListGroup"; import { getGenres } from "../services/fakeGenreService"; class Movies extends Component { state = { movies: [], genres: [], pageSize: 4, currentPage: 1, }; componentDidMount() { const genres = [{ name: "All Genres" }, ...getGenres()]; this.setState({ movies: getMovies(), genres: genres }); } handleDelete = (movie) => { const movies = this.state.movies.filter((m) => m._id !== movie._id); this.setState({ movies: movies }); }; handleRefresh = () => { this.setState({ movies: getMovies() }); }; handleLike = (movie) => { const movies = [...this.state.movies]; const index = movies.indexOf(movie); movies[index] = { ...movies[index] }; movies[index].liked = !movies[index].liked; this.setState({ movies }); }; handlePageChange = (page) => { this.setState({ currentPage: page }); }; handleGenreSelect = (genre) => { console.log("handle genre clicked", genre); this.setState({ selectedGenre: genre, currentPage: 1 }); //pretty much changing current available or creating new ones. }; render() { const { currentPage, pageSize, selectedGenre, movies: allMovies, } = this.state; const filtered = selectedGenre && selectedGenre._id ? allMovies.filter((m) => m.genre._id === selectedGenre._id) : allMovies; const movies = paginate(filtered, currentPage, pageSize); if (allMovies.length === 0) { return ( <div> <p>There are no movies. Please try again later. Thank you.</p> <button onClick={this.handleRefresh} type="button" className="btn btn-primary" > Refresh </button> </div> ); } return ( <div className="row"> <div className="col-3"> <ListGroup items={this.state.genres} selectedItem={this.state.selectedGenre} onItemSelect={this.handleGenreSelect} /> </div> <div className="col"> <p>Showing {filtered.length} movies in the database.</p> <table className="table"> <thead> <tr> <th>Title</th> <th>Genre</th> <th>Stock</th> <th>Rate</th> <th></th> <th></th> </tr> </thead> <tbody> {movies.map((movie) => ( <tr key={movie._id}> <td>{movie.title}</td> <td>{movie.genre.name}</td> <td>{movie.numberInStock}</td> <td>{movie.dailyRentalRate}</td> <td> <Like liked={movie.liked} likeClicked={() => this.handleLike(movie)} /> </td> <td> <button onClick={() => this.handleDelete(movie)} type="button" className="btn btn-danger btn-sm" > Delete </button> </td> </tr> ))} </tbody> </table> <Pagination itemCount={filtered.length} pageSize={pageSize} onPageChange={this.handlePageChange} currentPage={currentPage} /> <button onClick={this.handleRefresh} type="button" className="btn btn-primary" > Refresh </button> </div> </div> ); } } export default Movies;
import math import heapq import time import logging import arcade import hack POSSIBLE_KEYS = [ (arcade.key.D,), (arcade.key.A,), (arcade.key.A, arcade.key.W), (arcade.key.D, arcade.key.W), (arcade.key.W,), (), ] POSSIBLE_KEYS_NO_JUMP = [ (arcade.key.D,), (arcade.key.A,), (), ] # scroller also has POSSIBLE_KEYS + arcade.key.S POSSIBLE_KEYS_SCROLLER = [ (arcade.key.A,), (arcade.key.W,), (arcade.key.D,), (arcade.key.S,), (arcade.key.A, arcade.key.W), (arcade.key.A, arcade.key.S), (arcade.key.D, arcade.key.W), (arcade.key.D, arcade.key.S), (), ] GRANULARITY = 16 PRESSING_LENGTH = 5 TIMEOUT = 5. def get_player_coord_from_state(state): player_properties = state.player[1].properties player_x, player_y = None, None for key, value in player_properties: if key == 'x': player_x = value elif key == 'y': player_y = value assert player_x is not None and player_y is not None return player_x, player_y def get_player_can_jump_from_state(state): player_properties = state.player[1].properties in_the_air, jump_override = None, None for key, value in player_properties: if key == 'in_the_air': in_the_air = value elif key == 'jump_override': jump_override = value return not in_the_air or jump_override def get_player_speed_from_state(state): player_properties = state.player[1].properties x_speed, y_speed = None, None for key, value in player_properties: if key == 'x_speed': x_speed = value elif key == 'y_speed': y_speed = value return x_speed, y_speed class QueueElement: def __init__(self, state, dest_x, dest_y, start_x, start_y): self.state = state self.heuristic = self.__heuristic(dest_x, dest_y, start_x, start_y) def __heuristic(self, dest_x, dest_y, start_x, start_y): player_x, player_y = get_player_coord_from_state(self.state) return math.hypot(player_x - dest_x, player_y - dest_y) def __lt__(self, other): return self.heuristic < other.heuristic def get_outline(properties): for key, value in properties: if key == 'outline': return value raise Exception('No outline property found') def get_highest_point(outline): max_height = -math.inf for i in outline: max_height = max(max_height, i.y) return max_height def get_lowest_point(outline): min_height = math.inf for i in outline: min_height = min(min_height, i.y) return min_height def get_rightmost_point(outline): max_x = -math.inf for i in outline: max_x = max(max_x, i.x) return max_x def get_leftmost_point(outline): min_x = math.inf for i in outline: min_x = min(min_x, i.x) return min_x def distance(x1, y1, x2, y2): return ((x2 - x1)**2 + (y2 - y1)**2)**0.5 def adjust_granularity(distance_to_target): if distance_to_target > 500: return 32 elif distance_to_target > 250: return 16 elif distance_to_target > 100: return 8 else: return 4 def adjust_pressing_length(distance_to_target): return 5 def alias_coord(x, y, target_x, target_y): dist_to_target = distance(x, y, target_x, target_y) granularity = adjust_granularity(dist_to_target) return x // granularity * granularity, y // granularity * granularity def traceback(visited, x, y, target_x, target_y, x_speed, y_speed): path = [] while True: states_coord = visited.pop(alias_coord(x, y, target_x, target_y) + (x_speed, y_speed)) if states_coord is None: break path.extend(reversed(states_coord[0])) x, y = states_coord[1] x_speed, y_speed = states_coord[2] return reversed(path) def navigate(game, target_x, target_y): if not game.player: return initial_keys = game.__dict__['raw_pressed_keys'] game.simulating = True init_state = game.backup() visited = {alias_coord(game.player.x, game.player.y, target_x, target_y) + (game.player.x_speed, game.player.y_speed): None} start_x = game.player.x start_y = game.player.y pq = [QueueElement(init_state, target_x, target_y, start_x, start_y)] n_iter = 0 start = time.time() try: while len(pq) > 0: n_iter += 1 if time.time() - start > TIMEOUT: hack._G_WINDOW.console_add_msg('Path finding timed out') raise TimeoutError('Path finding timed out') state = heapq.heappop(pq).state coord = get_player_coord_from_state(state) speed = get_player_speed_from_state(state) outline = get_outline(state.player[1].properties) if get_leftmost_point(outline) <= target_x <= get_rightmost_point(outline) and \ get_lowest_point(outline) <= target_y <= get_highest_point(outline): return traceback(visited, *coord, target_x, target_y, *speed) possible_keys = None if game.player.platformer_rules: possible_keys = POSSIBLE_KEYS if get_player_can_jump_from_state(state) else POSSIBLE_KEYS_NO_JUMP else: possible_keys = POSSIBLE_KEYS_SCROLLER for keys in possible_keys: game.restore(state) game.__dict__['raw_pressed_keys'] = frozenset((arcade.key.LSHIFT, *keys)) new_states = [] for _ in range(adjust_pressing_length(distance(game.player.x, game.player.y, target_x, target_y))): health = game.player.health game.tick() if game.player.health < health - 10 or game.player.dead: break cx, cy, nb = game.physics_engine._get_collisions_list(game.player) if len(cx): break collided = False for o, mpv in cy: if mpv[1] > 0: collided = True break if collided: break sss = game.backup() new_states.append(sss) if new_states is None or len(new_states) == 0: continue new_coord = alias_coord(*get_player_coord_from_state(new_states[-1]), target_x, target_y) + get_player_speed_from_state(new_states[-1]) if new_coord not in visited: visited[new_coord] = new_states, coord, speed heapq.heappush(pq, QueueElement(new_states[-1], target_x, target_y, start_x, start_y)) except Exception as e: logging.exception(e) game.restore(init_state) if not isinstance(e, TimeoutError): raise finally: game.__dict__['raw_pressed_keys'] = initial_keys game.simulating = False hack._G_WINDOW.console_add_msg(f'{n_iter} steps, visited {len(visited)} states, queue depth {len(pq)}') game.__dict__['visited'] = list(visited.keys()) open('dipshit.txt','w').write(str(game.backup()))
import 'package:flutter/material.dart'; import 'package:my_portfolio/styles/colors.dart'; class ErrorPage extends StatelessWidget { final String errorMessage; const ErrorPage({super.key, required this.errorMessage}); @override Widget build(BuildContext context) { return Scaffold( body: Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ PersonalPortfolioColors.errorBgTop, PersonalPortfolioColors.errorBgBottom ])), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ const Icon(Icons.warning, size: 80, color: PersonalPortfolioColors.errorIcon), const Text('Error!', textAlign: TextAlign.center, style: TextStyle( fontSize: 100, fontWeight: FontWeight.bold, color: Colors.white)), SizedBox( width: MediaQuery.of(context).size.width / 2, child: Text(errorMessage, textAlign: TextAlign.center, style: const TextStyle(fontSize: 30, color: Colors.white)), ) ])), )); } }
import * as React from 'react'; import styles from './Module11Demo1.module.scss'; import { IModule11Demo1Props } from './IModule11Demo1Props'; import { escape } from '@microsoft/sp-lodash-subset'; export default class Module11Demo1 extends React.Component<IModule11Demo1Props, {}> { public render(): React.ReactElement<IModule11Demo1Props> { return ( <div className={ styles.module11Demo1 }> <div className={ styles.container }> <div className={ styles.row }> <div className={ styles.column }> <span className={ styles.title }>Welcome to SharePoint!</span> <p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p> <p className={ styles.description }>{escape(this.props.description)}</p> <a href="https://aka.ms/spfx" className={ styles.button }> <span className={ styles.label }>Learn more</span> </a> </div> </div> </div> </div> ); } }
import { Component } from "@angular/core"; import { FormArray, FormControl, FormGroup, Validators } from "@angular/forms"; import { Store } from "@ngrx/store"; import {addBookToList} from"../store/action/book.action" import { Router } from "@angular/router"; import { getBookDetails } from "../store/selector/boot.selector"; @Component({ selector:'addBook', templateUrl:'./addBookcomp.html' }) export class addBook{ public addBook:FormGroup; constructor(private store:Store<any>,private rt:Router){ this.addBook = new FormGroup({ title: new FormControl('', [Validators.required]), author: new FormControl('',[Validators.required]), description: new FormControl('', [Validators.required]), publication_year: new FormControl('', [Validators.required]), genre: new FormControl([], [Validators.required]), id: new FormControl(Math.floor(Math.random()*50)+51), cover_image: new FormControl('') }) console.log(this.rt.parseUrl(this.rt.url).fragment); } ngOnInit(){ // this.store.select(getBookDetails).subscribe((data)=>{ // if(Object.keys(data).length > 0){ // this.addBook.setValue(data) // } // }) } addBookList(){ this.updateTouched(this.addBook); if(this.addBook.status == 'VALID'){ this.store.dispatch(addBookToList({book:[this.addBook.getRawValue()]})); this.rt.navigateByUrl('books') } } updateTouched(formObj){ Object.keys(formObj.controls).forEach((t)=>{ const control = formObj.get(t); if(control instanceof FormControl){ control.markAsTouched(); }else if(control instanceof FormGroup){ this.updateTouched(control); }else if(control instanceof FormArray){ const controlArray = formObj.get(control); Object.keys(controlArray).forEach((item)=>{ this.updateTouched(item) }) } }) } }
/* * IRremoteLearn * * This library expects a special non-demodulated Learner IR receiver * such as the Vishay TSMP58000 http://www.vishay.com/docs/82485/tsmp58000.pdf * and uses an interrupt handler to strip the carrier from the IR signal. * Although it should also work with normal demodulated receivers. * * TODO: Add the ability to report what the carrier frequency is. * * Author: Brett Walach (ported to Particle on July 22nd 2018) * * --------------- * IRremote * Version 0.1 July, 2009 * Copyright 2009 Ken Shirriff * For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html * * Modified by Paul Stoffregen <paul@pjrc.com> to support other boards and timers * * Interrupt code based on NECIRrcv by Joe Knapp * http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 * Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ * * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) */ #ifndef IRremoteLearnInt_h #define IRremoteLearnInt_h #include "Particle.h" // #define DEBUG_IR 1 #define ERR 0 #define DECODED 1 // Pulse parms are *50-100 for the Mark and *50+100 for the space // First MARK is the one after the long gap // pulse parameters in usec // #define NEC_HDR_MARK 9000 // #define NEC_HDR_SPACE 4500 // #define NEC_BIT_MARK 560 // #define NEC_ONE_SPACE 1600 // #define NEC_ZERO_SPACE 560 #define NEC_HDR_MARK 4000 // tweaked shorter for the TSOP32338 #define NEC_HDR_SPACE 2000 #define NEC_BIT_MARK 500 #define NEC_ONE_SPACE 1000 #define NEC_ZERO_SPACE 500 #define NEC_RPT_SPACE 2250 #define SONY_HDR_MARK 2400 #define SONY_HDR_SPACE 600 #define SONY_ONE_MARK 1200 #define SONY_ZERO_MARK 600 #define SONY_RPT_LENGTH 45000 #define SONY_DOUBLE_SPACE_USECS 500 // usually ssee 713 - not using ticks as get number wrapround // SA 8650B #define SANYO_HDR_MARK 3500 // seen range 3500 #define SANYO_HDR_SPACE 950 // seen 950 #define SANYO_ONE_MARK 2400 // seen 2400 #define SANYO_ZERO_MARK 700 // seen 700 #define SANYO_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround #define SANYO_RPT_LENGTH 45000 // Mitsubishi RM 75501 // 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7 // #define MITSUBISHI_HDR_MARK 250 // seen range 3500 #define MITSUBISHI_HDR_SPACE 350 // 7*50+100 #define MITSUBISHI_ONE_MARK 1950 // 41*50-100 #define MITSUBISHI_ZERO_MARK 750 // 17*50-100 // #define MITSUBISHI_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround // #define MITSUBISHI_RPT_LENGTH 45000 #define RC5_T1 889 #define RC5_RPT_LENGTH 46000 #define RC6_HDR_MARK 2666 #define RC6_HDR_SPACE 889 #define RC6_T1 444 #define RC6_RPT_LENGTH 46000 #define SHARP_BIT_MARK 245 #define SHARP_ONE_SPACE 1805 #define SHARP_ZERO_SPACE 795 #define SHARP_GAP 600000 #define SHARP_TOGGLE_MASK 0x3FF #define SHARP_RPT_SPACE 3000 #define DISH_HDR_MARK 400 #define DISH_HDR_SPACE 6100 #define DISH_BIT_MARK 400 #define DISH_ONE_SPACE 1700 #define DISH_ZERO_SPACE 2800 #define DISH_RPT_SPACE 6200 #define DISH_TOP_BIT 0x8000 #define PANASONIC_HDR_MARK 3500 #define PANASONIC_HDR_SPACE 1775 #define PANASONIC_BIT_MARK 432 #define PANASONIC_ONE_SPACE 1296 #define PANASONIC_ZERO_SPACE 453 #define JVC_HDR_MARK 8000 #define JVC_HDR_SPACE 4000 #define JVC_BIT_MARK 600 #define JVC_ONE_SPACE 1600 #define JVC_ZERO_SPACE 550 #define JVC_RPT_LENGTH 60000 #define SHARP_BITS 15 #define DISH_BITS 16 #define TOLERANCE 25 // percent tolerance in measurements #define LTOL (1.0 - TOLERANCE/100.) #define UTOL (1.0 + TOLERANCE/100.) #define TICKS_LOW(us) (int) (((us)*LTOL/USECPERTICK)) #define TICKS_HIGH(us) (int) (((us)*UTOL/USECPERTICK + 1)) #ifndef DEBUG_IR int MATCH(int measured, int desired) {return measured >= TICKS_LOW(desired) && measured <= TICKS_HIGH(desired);} int MATCH_MARK(int measured_ticks, int desired_us) {return MATCH(measured_ticks, (desired_us + MARK_EXCESS));} int MATCH_SPACE(int measured_ticks, int desired_us) {return MATCH(measured_ticks, (desired_us - MARK_EXCESS));} // Debugging versions are in IRremoteLearn.cpp #endif // receiver states #define STATE_IDLE 2 #define STATE_MARK 3 #define STATE_SPACE 4 #define STATE_STOP 5 #define STATE_CAPTURED 6 // information for the interrupt handler typedef struct { uint8_t rxpin; // pin for IR rx data from detector uint8_t txpin; // pin for IR tx data from detector uint8_t rcvstate; // state machine uint8_t blinkflag; // TRUE to enable blinking of pin 13 on IR processing // unsigned int timer; // state timer, counts 50uS ticks. unsigned long rawbuf1[RAWBUF]; // raw data 1 (double buffered to receive while decoding) unsigned long rawbuf2[RAWBUF]; // raw data 2 unsigned long rawlen; // counter of entries in rawbuf unsigned long current_time; // current time in micro seconds unsigned long start_time; // start time in micro seconds unsigned long end_time; // end time in micro seconds int irout_khz; // frequency used for PWM output unsigned long idle_timout_ms; // idle timeout in milliseconds unsigned long mark_timout_us; // mark timeout in microseconds uint8_t txbuf[TX_BUF_MAX]; // temporary TX buffer for sendBytes() } irparams_t; // Defined in IRremoteLearn.cpp extern volatile irparams_t irparams; // IR detector output is active low #define MARK 0 #define SPACE 1 #define TOPBIT 0x80000000 #define NEC_BITS 32 #define SONY_BITS 12 #define SANYO_BITS 12 #define MITSUBISHI_BITS 16 #define MIN_RC5_SAMPLES 11 #define MIN_RC6_SAMPLES 1 #define PANASONIC_BITS 48 #define JVC_BITS 16 #define BLINKLED D7 #define BLINKLED_ON() digitalWriteFast(BLINKLED,1) #define BLINKLED_OFF() digitalWriteFast(BLINKLED,0) #endif // IRremoteLearnInt_h
/* * The information in this file is * Copyright(c) 2007 Ball Aerospace & Technologies Corporation * and is subject to the terms and conditions of the * GNU Lesser General Public License Version 2.1 * The license text is available from * http://www.gnu.org/licenses/lgpl.html */ #ifndef AOILAYER_H #define AOILAYER_H #include "GraphicLayer.h" #include "ConfigurationSettings.h" #include "TypesFile.h" class ColorType; /** * Adjusts the properties of an AOI layer. * * An AOI layer consists of markers identifying pixels in a scene that are included * in the area of interest. The pixel marker has two properties: color and symbol. * This class provides the means to set the color and symbol for the current layer * and also the default color and symbol for new layers. * * This subclass of Subject will notify upon the following conditions: * - The following methods are called: setColor(), setSymbol(). * - The AOI is manipulated through the GUI. * - Everything else documented in GraphicLayer. * * @see Layer */ class AoiLayer : public GraphicLayer { public: SETTING(AutoColor, AoiLayer, bool, false) SETTING(MarkerColor, AoiLayer, ColorType, ColorType()) SETTING(MarkerSymbol, AoiLayer, SymbolType, SOLID) /** * Emitted with any<ColorType> when the color is changed. */ SIGNAL_METHOD(AoiLayer, ColorChanged) /** * Emitted with any<SymbolType> when the symbol is changed. */ SIGNAL_METHOD(AoiLayer, SymbolChanged) /** * Sets the pixel marker color for the current AOI layer. * * @param aoiColor * The new pixel marker color. * * @notify This method will notify Subject::signalModified. * * @see getColor() */ virtual void setColor(const ColorType& aoiColor) = 0; /** * Returns the pixel marker color of the current AOI layer. * * @return The current pixel marker color. * * @see setColor() */ virtual ColorType getColor() const = 0; /** * Sets the pixel marker symbol for the current AOI layer. * * @param aoiSymbol * The new pixel marker symbol. * * @notify This method will notify Subject::signalModified. * * @see getSymbol() */ virtual void setSymbol(const SymbolType& aoiSymbol) = 0; /** * Returns the pixel marker symbol of the current AOI layer. * * @return The current pixel marker symbol. * * @see setSymbol() */ virtual SymbolType getSymbol() const = 0; /** * Sets the initial drawing mode that is used when the user adds a new * object to the layer with the mouse. * * This method provides a means for objects to set the initial object * drawing mode for only this layer. This value is reset when the user * selects a new mode on the AOI toolbar. * * @param mode * The initial drawing mode to use when the user adds a new object * to the layer with the mouse. * * @see DesktopServices::setAoiSelectionTool() */ virtual void setMode(ModeType mode) = 0; /** * Returns the initial drawing mode that is used when the user adds a new * object to the layer with the mouse. * * @return The initial drawing mode used when the user added a new object * to the layer with the mouse. This value may be different than * the return value of DesktopServices::getAoiSelectionMode() if * the setMode() method was called and the user has not selected a * new mode on the toolbar. */ virtual ModeType getMode() const = 0; /** * Correct the coordinate for whatever snapping may be required. * * AoiLayer snaps mid-pixel points so that objects appear in the * center of the selected pixels. * * @param coord * Coordinate to correct. * * @return The corrected coordinate. */ virtual LocationType correctCoordinate(const LocationType &coord) const = 0; protected: /** * This should be destroyed by calling SpatialDataView::deleteLayer. */ virtual ~AoiLayer() {} }; #endif
--- title: Value.Is --- # Value.Is Determines whether a value is compatible with the specified type. ## Syntax ```powerquery Value.Is( value as any, type as type ) as logical ``` ## Remarks Determines whether a value is compatible with the specified type. This is equivalent to the "is" operator in M, with the exception that it can accept identifier type references such as Number.Type. ## Examples ### Example #1 Compare two ways of determining if a number is compatible with type number. ```powerquery Value.Is(123, Number.Type) = (123 is number) ``` Result: ```powerquery true ``` ## Category Values.Types
import usecase.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.*; @ExtendWith(MockitoExtension.class) class FitsTest { @Test @DisplayName("Deve retornar verdadeiro se as fotos couberem horizontalmente na página do álbum") void shouldReturnTrueIfPhotosFitHorizontally() { Photo photo1 = new Photo(3, 4); Photo photo2 = new Photo(3, 4); Fits fits = new Fits(photo1, photo2, 5, 7); assertThat(fits.handle()).isTrue(); } @Test @DisplayName("Deve retornar verdadeiro se as fotos couberem verticalmente na página do álbum") void shouldReturnTrueIfPhotosFitVertically() { Photo photo1 = new Photo(4, 3); Photo photo2 = new Photo(4, 3); Fits fits = new Fits(photo1, photo2, 7, 5); assertThat(fits.handle()).isTrue(); } @Test @DisplayName("Deve retornar verdadeiro se as fotos couberem horizontalmente e verticalmente na página do álbum") void shouldReturnTrueIfPhotosFitBothHorizontallyAndVertically() { Photo photo1 = new Photo(2, 3); Photo photo2 = new Photo(3, 2); Fits fits = new Fits(photo1, photo2, 3, 3); assertThat(fits.handle()).isTrue(); } @Test @DisplayName("Deve retornar falso se as fotos não couberem nem horizontalmente nem verticalmente na página do álbum") void shouldReturnFalseIfPhotosDoNotFitHorizontallyNorVertically() { Photo photo1 = new Photo(5, 7); Photo photo2 = new Photo(7, 5); Fits fits = new Fits(photo1, photo2, 5, 7); assertThat(fits.handle()).isFalse(); } }
/*********************************************************************** * This file is part of iDempiere ERP Open Source * * http://www.idempiere.org * * * * Copyright (C) Contributors * * * * 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 Street, Fifth Floor, Boston, * * MA 02110-1301, USA. * * * * Contributors: * * - hengsin * **********************************************************************/ package org.idempiere.test.base; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.math.BigDecimal; import java.sql.Timestamp; import java.util.Dictionary; import java.util.Hashtable; import java.util.Properties; import org.adempiere.base.Core; import org.adempiere.base.IAddressValidationFactory; import org.adempiere.base.IBankStatementLoaderFactory; import org.adempiere.base.IBankStatementMatcherFactory; import org.adempiere.base.IModelValidatorFactory; import org.adempiere.base.IPaymentExporterFactory; import org.adempiere.base.IPaymentProcessorFactory; import org.adempiere.base.IReplenishFactory; import org.adempiere.base.IShipmentProcessorFactory; import org.adempiere.base.ITaxProviderFactory; import org.adempiere.base.MappedByNameFactory; import org.adempiere.model.IAddressValidation; import org.adempiere.model.IShipmentProcessor; import org.adempiere.model.ITaxProvider; import org.adempiere.model.MFreightShipmentProcessor; import org.adempiere.model.MShipperFacade; import org.compiere.impexp.BankStatementLoaderInterface; import org.compiere.impexp.BankStatementMatchInfo; import org.compiere.impexp.BankStatementMatcherInterface; import org.compiere.model.MAddressTransaction; import org.compiere.model.MAddressValidation; import org.compiere.model.MBankAccountProcessor; import org.compiere.model.MBankStatementLine; import org.compiere.model.MBankStatementLoader; import org.compiere.model.MClient; import org.compiere.model.MShipper; import org.compiere.model.MTable; import org.compiere.model.MTaxProvider; import org.compiere.model.MWarehouse; import org.compiere.model.ModelValidationEngine; import org.compiere.model.ModelValidator; import org.compiere.model.PO; import org.compiere.model.PaymentInterface; import org.compiere.model.PaymentProcessor; import org.compiere.model.Query; import org.compiere.model.StandardTaxProvider; import org.compiere.model.X_C_AddressValidationCfg; import org.compiere.model.X_C_TaxProviderCfg; import org.compiere.model.X_I_BankStatement; import org.compiere.model.X_T_Replenish; import org.compiere.util.CacheMgt; import org.compiere.util.Env; import org.compiere.util.GenericPaymentExport; import org.compiere.util.PaymentExport; import org.compiere.util.ReplenishInterface; import org.idempiere.fa.service.api.DepreciationDTO; import org.idempiere.fa.service.api.DepreciationFactoryLookupDTO; import org.idempiere.fa.service.api.IDepreciationMethod; import org.idempiere.fa.service.api.IDepreciationMethodFactory; import org.idempiere.test.AbstractTestCase; import org.idempiere.test.TestActivator; import org.junit.jupiter.api.Test; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; /** * * @author hengsin * */ public class MappedByNameFactoryTest extends AbstractTestCase { public MappedByNameFactoryTest() { } private final static class MyModelValidator implements ModelValidator { @Override public void initialize(ModelValidationEngine engine, MClient client) { } @Override public int getAD_Client_ID() { return 0; } @Override public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { return null; } @Override public String modelChange(PO po, int type) throws Exception { return null; } @Override public String docValidate(PO po, int timing) { return null; } } private final static class MyModelValidatorFactory extends MappedByNameFactory<ModelValidator> implements IModelValidatorFactory { public MyModelValidatorFactory() { addMapping(MyModelValidator.class.getName(), () -> new MyModelValidator()); } @Override public ModelValidator newModelValidatorInstance(String className) { return newInstance(className); } } @Test public void testModelValidatorFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); bc.registerService(IModelValidatorFactory.class, new MyModelValidatorFactory(), properties); var validator = Core.getModelValidator(MyModelValidator.class.getName()); assertNotNull(validator); assertTrue(validator instanceof MyModelValidator, "validator not instanceof MyModelValidator. validator="+validator.getClass().getName()); } private final static class MyPaymentProcessor extends PaymentProcessor { @Override public boolean processCC() throws IllegalArgumentException { return false; } @Override public boolean isProcessedOK() { return false; } } private final static class MyPaymentProcessFactory extends MappedByNameFactory<PaymentProcessor> implements IPaymentProcessorFactory { public MyPaymentProcessFactory() { addMapping("org.compiere.model.PP_PayFlowPro", () -> new MyPaymentProcessor()); } @Override public PaymentProcessor newPaymentProcessorInstance(String className) { return newInstance(className); } } @Test public void testPaymentProcessorFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); ServiceRegistration<IPaymentProcessorFactory> registration = bc.registerService(IPaymentProcessorFactory.class, new MyPaymentProcessFactory(), properties); CacheMgt.get().reset(Core.IPAYMENT_PROCESSOR_FACTORY_CACHE_TABLE_NAME); PaymentInterface mp = null; MBankAccountProcessor mbap; Query query = new Query(Env.getCtx(), MBankAccountProcessor.Table_Name, MTable.getUUIDColumnName(MBankAccountProcessor.Table_Name)+"=?", null); mbap = query.setParameters("f4a64026-bf68-4c8c-b238-8cdf006aae04").first(); var pp = Core.getPaymentProcessor(mbap, mp); assertNotNull(pp); assertTrue(pp instanceof MyPaymentProcessor, "pp not instanceof MyPaymentProcessor. pp="+pp.getClass().getName()); registration.unregister(); } private final static class MyBankStatementLoader implements BankStatementLoaderInterface { @Override public boolean init(MBankStatementLoader controller) { // TODO Auto-generated method stub return false; } @Override public boolean isValid() { return false; } @Override public boolean loadLines() { return false; } @Override public String getLastErrorMessage() { return null; } @Override public String getLastErrorDescription() { return null; } @Override public Timestamp getDateLastRun() { return null; } @Override public String getRoutingNo() { return null; } @Override public String getBankAccountNo() { return null; } @Override public String getIBAN() { return null; } @Override public String getStatementReference() { return null; } @Override public Timestamp getStatementDate() { return null; } @Override public String getTrxID() { return null; } @Override public String getReference() { return null; } @Override public String getCheckNo() { return null; } @Override public String getPayeeName() { return null; } @Override public String getPayeeAccountNo() { return null; } @Override public Timestamp getStatementLineDate() { return null; } @Override public Timestamp getValutaDate() { return null; } @Override public String getTrxType() { return null; } @Override public boolean getIsReversal() { return false; } @Override public String getCurrency() { return null; } @Override public BigDecimal getStmtAmt() { return null; } @Override public BigDecimal getTrxAmt() { return null; } @Override public BigDecimal getInterestAmt() { return null; } @Override public String getMemo() { return null; } @Override public String getChargeName() { return null; } @Override public BigDecimal getChargeAmt() { return null; } } private final static class MyBankStatementLoaderFactory extends MappedByNameFactory<BankStatementLoaderInterface> implements IBankStatementLoaderFactory { public MyBankStatementLoaderFactory() { addMapping(MyBankStatementLoader.class.getName(), () -> new MyBankStatementLoader()); } @Override public BankStatementLoaderInterface newBankStatementLoaderInstance(String className) { return newInstance(className); } } @Test public void testBankStatementLoaderFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); bc.registerService(IBankStatementLoaderFactory.class, new MyBankStatementLoaderFactory(), properties); var loader = Core.getBankStatementLoader(MyBankStatementLoader.class.getName()); assertNotNull(loader); assertTrue(loader instanceof MyBankStatementLoader, "loader not instanceof MyBankStatementLoader. loader="+loader.getClass().getName()); } private static final class MyBankStatementMatcher implements BankStatementMatcherInterface { @Override public BankStatementMatchInfo findMatch(MBankStatementLine bsl) { return null; } @Override public BankStatementMatchInfo findMatch(X_I_BankStatement ibs) { return null; } } private final static class MyBankStatementMatcherFactory extends MappedByNameFactory<BankStatementMatcherInterface> implements IBankStatementMatcherFactory { public MyBankStatementMatcherFactory() { addMapping(MyBankStatementMatcher.class.getName(), () -> new MyBankStatementMatcher()); } @Override public BankStatementMatcherInterface newBankStatementMatcherInstance(String className) { return newInstance(className); } } @Test public void testBankStatementMatcherFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); bc.registerService(IBankStatementMatcherFactory.class, new MyBankStatementMatcherFactory(), properties); var loader = Core.getBankStatementMatcher(MyBankStatementMatcher.class.getName()); assertNotNull(loader); assertTrue(loader instanceof MyBankStatementMatcher, "loader not instanceof MyBankStatementMatcher. loader="+loader.getClass().getName()); } private final static class MyShipmentProcessor extends MFreightShipmentProcessor { } private final static class MyShipmentProcessorFactory extends MappedByNameFactory<IShipmentProcessor> implements IShipmentProcessorFactory { public MyShipmentProcessorFactory() { addMapping("org.adempiere.model.MFreightShipmentProcessor", () -> new MyShipmentProcessor()); } @Override public IShipmentProcessor newShipmentProcessorInstance(String className) { return newInstance(className); } } @Test public void testShipmentProcessorFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); ServiceRegistration<IShipmentProcessorFactory> sr = bc.registerService(IShipmentProcessorFactory.class, new MyShipmentProcessorFactory(), properties); CacheMgt.get().reset(Core.ISHIPMENT_PROCESSOR_FACTORY_CACHE_TABLE_NAME); MShipper shipper = new MShipper(Env.getCtx(), 100, getTrxName()); MShipperFacade sf = new MShipperFacade(shipper); var loader = Core.getShipmentProcessor(sf); assertNotNull(loader); assertTrue(loader instanceof MyShipmentProcessor, "loader not instanceof MyShipmentProcessor. loader="+loader.getClass().getName()); sr.unregister(); } private final static class MyAddressValidation implements IAddressValidation { @Override public boolean onlineValidate(Properties ctx, MAddressTransaction addressTransaction, String trxName) { return false; } } private final static class MyAddressValidationFactory extends MappedByNameFactory<IAddressValidation> implements IAddressValidationFactory { public MyAddressValidationFactory() { addMapping(MyAddressValidation.class.getName(), () -> new MyAddressValidation()); } @Override public IAddressValidation newAddressValidationInstance(String className) { return newInstance(className); } } @Test public void testAddressVallidationFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); ServiceRegistration<IAddressValidationFactory> sr = bc.registerService(IAddressValidationFactory.class, new MyAddressValidationFactory(), properties); X_C_AddressValidationCfg cfg = new X_C_AddressValidationCfg(Env.getCtx(), 0, getTrxName()); cfg.setAddressValidationClass(MyAddressValidation.class.getName()); cfg.setHostAddress("localhost"); cfg.setHostPort(8080); cfg.setName("testAddressVallidation cfg"); cfg.saveEx(); MAddressValidation adv = new MAddressValidation(Env.getCtx(), 0, getTrxName()); adv.setC_AddressValidationCfg_ID(cfg.get_ID()); adv.setUserID("test"); adv.setConnectionPassword("test01"); adv.setSeqNo(10); adv.setName("testAddressVallidation"); var loader = Core.getAddressValidation(adv); assertNotNull(loader); assertTrue(loader instanceof MyAddressValidation, "loader not instanceof MyAddressValidation. loader="+loader.getClass().getName()); sr.unregister(); } private static final class MyTaxProvider extends StandardTaxProvider { } private static final class MyTaxProviderFactory extends MappedByNameFactory<ITaxProvider> implements ITaxProviderFactory { public MyTaxProviderFactory() { addMapping("MyTaxProvider", () -> new MyTaxProvider()); } @Override public ITaxProvider newTaxProviderInstance(String className) { return newInstance(className); } } @Test public void testTaxProviderFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); ServiceRegistration<ITaxProviderFactory> sr = bc.registerService(ITaxProviderFactory.class, new MyTaxProviderFactory(), properties); X_C_TaxProviderCfg cfg = new X_C_TaxProviderCfg(Env.getCtx(), 0, getTrxName()); cfg.setName("testTaxProviderFactory cfg"); cfg.setTaxProviderClass("MyTaxProvider"); cfg.saveEx(); MTaxProvider tp = new MTaxProvider(Env.getCtx(), 0, getTrxName()); tp.setName("testTaxProviderFactory"); tp.setC_TaxProviderCfg_ID(cfg.get_ID()); tp.saveEx(); var loader = Core.getTaxProvider(tp); assertNotNull(loader); assertTrue(loader instanceof MyTaxProvider, "loader not instanceof MyTaxProvider. loader="+loader.getClass().getName()); sr.unregister(); } private final static class MyReplenishInterface implements ReplenishInterface { @Override public BigDecimal getQtyToOrder(MWarehouse wh, X_T_Replenish replenish) { return null; } } private final static class MyReplenishInterfaceFactory extends MappedByNameFactory<MyReplenishInterface> implements IReplenishFactory { public MyReplenishInterfaceFactory() { addMapping(MyReplenishInterface.class.getName(), () -> new MyReplenishInterface()); } @Override public ReplenishInterface newReplenishInstance(String className) { return newInstance(className); } } @Test public void testReplenishFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); bc.registerService(IReplenishFactory.class, new MyReplenishInterfaceFactory(), properties); var loader = Core.getReplenish(MyReplenishInterface.class.getName()); assertNotNull(loader); assertTrue(loader instanceof MyReplenishInterface, "loader not instanceof MyReplenishInterface. loader="+loader.getClass().getName()); } private final static class MyPaymentExport extends GenericPaymentExport { } private final static class MyPaymentExportFactory extends MappedByNameFactory<PaymentExport> implements IPaymentExporterFactory { public MyPaymentExportFactory() { addMapping(MyPaymentExport.class.getName(), () -> new MyPaymentExport()); } @Override public PaymentExport newPaymentExporterInstance(String className) { return newInstance(className); } } @Test public void testPaymentExporterFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); bc.registerService(IPaymentExporterFactory.class, new MyPaymentExportFactory(), properties); var loader = Core.getPaymentExporter(MyPaymentExport.class.getName()); assertNotNull(loader); assertTrue(loader instanceof MyPaymentExport, "loader not instanceof MyPaymentExport loader="+loader.getClass().getName()); } private final static class MyDepreciationMethod implements IDepreciationMethod { @Override public BigDecimal caclulateDepreciation(DepreciationDTO depreciationDTO) { return null; } @Override public long getCountPeriod(DepreciationDTO depreciationDTO) { return 0; } @Override public boolean isPeriodAdjustment() { return false; } } private final static class MyDepreciationMethodFactory extends MappedByNameFactory<IDepreciationMethod> implements IDepreciationMethodFactory { public MyDepreciationMethodFactory() { addMapping("MyDepreciationMethod", () -> new MyDepreciationMethod()); } @Override public IDepreciationMethod getDepreciationMethod(DepreciationFactoryLookupDTO factoryLookupDTO) { return newInstance(factoryLookupDTO.depreciationType); } } @Test public void testDepreciationMethodFactory() { //simulate osgi component service BundleContext bc = TestActivator.context; Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("service.ranking", Integer.valueOf(1)); bc.registerService(IDepreciationMethodFactory.class, new MyDepreciationMethodFactory(), properties); DepreciationFactoryLookupDTO dto = new DepreciationFactoryLookupDTO(); dto.depreciationType = "MyDepreciationMethod"; var loader = Core.getDepreciationMethod(dto); assertNotNull(loader); assertTrue(loader instanceof MyDepreciationMethod, "loader not instanceof MyDepreciationMethod. loader="+loader.getClass().getName()); } }
import {render, screen} from '@testing-library/react'; import Navbar from './nav'; import '@testing-library/jest-dom/'; describe('Rendering Tests', () => { it('should render the nav component and its nested components: close-menu and hamburger-menu', () => { render( <Navbar logo="https://cms.skycode.me/skycode/assets/t3nkikzmo8go4csw" name="Doomis" items={[{name:'Cotizar', link:'/cotizar'}, {name:'Cobertura', link:'/cobertura'}]} social={[{name:'Facebook', icon:'/icon',link:'/link'}, {name:'Instagram', icon:'/icon',link:'/link'}]} theme={{primary:'#000',secondary:'#000',white:'#fff',black:'#000',gray:'#000', gray_dark:'#000'}} />); const hamburgerBars = screen.getByTestId('hamburger-bars'); const nav = screen.getByTestId('nav'); const closeMenu = screen.getByTestId('close-menu'); expect(nav).toBeInTheDocument(); expect(closeMenu).toBeInTheDocument(); expect(hamburgerBars).toBeInTheDocument(); }); it('should render the nav texts like name bussines, items, menu title, etc',()=>{ render( <Navbar logo="https://cms.skycode.me/skycode/assets/t3nkikzmo8go4csw" name="Doomis" items={[{name:'Cotizar', link:'/cotizar'}, {name:'Cobertura', link:'/cobertura'}]} social={[{name:'Facebook', icon:'/icon',link:'/link'}, {name:'Instagram', icon:'/icon',link:'/link'}]} theme={{primary:'#000',secondary:'#000',white:'#fff',black:'#000',gray:'#000', gray_dark:'#000'}} />); const name = screen.getByText('Doomis'); const item1 = screen.getByText('Cotizar'); const item2 = screen.getByText('Cobertura'); const titleMenu = screen.getByText('Menu'); expect(name).toBeInTheDocument(); expect(item1).toBeInTheDocument(); expect(item2).toBeInTheDocument(); expect(titleMenu).toBeInTheDocument(); }); it('should render the images like logo and social icons',()=>{ render( <Navbar logo="https://cms.skycode.me/skycode/assets/t3nkikzmo8go4csw" name="Doomis" items={[{name:'Cotizar', link:'/cotizar'}, {name:'Cobertura', link:'/cobertura'}]} social={[{name:'Facebook', icon:'/icon',link:'/link'}, {name:'Instagram', icon:'/icon',link:'/link'}]} theme={{primary:'#000',secondary:'#000',white:'#fff',black:'#000',gray:'#000', gray_dark:'#000'}} />); const logo = screen.getByAltText('logo'); const icon1 = screen.getByAltText('icon'); const icon2 = screen.getByAltText('icon'); expect(logo).toBeInTheDocument(); expect(icon1).toBeInTheDocument(); expect(icon2).toBeInTheDocument(); } ); });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Styles</title> <style type="text/css"> </style> </head> <body> <style type="text/css"> .colors { color: limegreen; color: rgb( 255, 0, 0 ); color: rgb(0, 255, 0 ); color: rgb(0,0, 255 ); color: rgb( 100, 120, 0 ); color: #ff0000; color: #00ff00; color: #888888; background: blue; background: #888; /* #888888*/ } </style> <div class="colors"> Some text </div> <style type="text/css"> .border { border: dotted 3px #888888; border-width: 6px; margin: 20px; padding: 20px; margin-left: 10px; margin-top: 50px; margin: 10px 20px 30px 40px; margin: 10px 20px; margin: 0; margin: 50px 20px 30px; } </style> <div class="border"> Some borders </div> <style type="text/css"> .dim { border: solid red 10px; height: 50px; width: 150px; box-sizing: border-box; padding: 10px; } </style> <div class="dim"> Dimensions </div> <style type="text/css"> .fonts{ font-size: 10px; } .fonts-sub:hover { background: yellow; } .fonts-sub { font-size: 1.2rem; font-weight: bold; font-style: italic; font-family: monospace; font-variant: small-caps; text-align: left; text-align: right; text-align: center; text-align: justify; text-decoration: underline overline; word-spacing: 5px; letter-spacing: 2px; } </style> <div class="fonts"> About Fonts <div class="fonts-sub"> Sub fonst Sub fonst Sub fonst Sub fonst Subfonst Sub fonst Subfonst Subfonst Subfonst Sub fonst Sub fonst Sub fonst Sub fonst Sub fonst Sub fonst Sub fonst </div> </div> <style type="text/css"> a:link { color: red; } a:hover { color: green; } a:active { color: grey; } a:visited { color: orange; } </style> <div class="anch"> <a href="https://google.com">Google</a> </div> <style type="text/css"> ul { list-style-type: square; } </style> <ul> <li>Item 1</li> <li>Item 2</li> </ul> <style type="text/css"> table { border-collapse: collapse; } td, th { border: solid black 1px; padding: 1em; background: lightblue; text-align: center; } </style> <table> <tr> <th>Header 1</th> <th>Header 2</th> <th>Header 3</th> </tr> <tr> <td>Cell 1</td> <td>Cell 2 More info</td> <td>Cell 3</td> </tr> <tr> <td>Cell 1 More info</td> <td>Cell 2 </td> <td>Cell 3</td> </tr> </table> </body> </html>