text
stringlengths
184
4.48M
#include <iostream> #include <memory> #include <utility> #include "DrawStrategy.h" #include "OpenGLCircleStrategy.h" #include "OpenGLSquareStrategy.h" #include "Circle.h" #include "Square.h" #include <vector> int main(int argc, char *argv[]) { using Shapes = std::vector<std::shared_ptr<Shape>>; Shapes shapes{}; shapes.emplace_back( std::make_unique<Circle>( 2.3, std::make_shared<OpenGLCircleStrategy>("Red") ) ); shapes.emplace_back( std::make_unique<Square>( 10.0, std::make_shared<OpenGLSquareStrategy>("Green") ) ); shapes.emplace_back( std::make_unique<Square>( 20.0, std::make_shared<OpenGLSquareStrategy>("Yellow") ) ); shapes.emplace_back( std::make_unique<Circle>( 4.1, std::make_shared<OpenGLCircleStrategy>("Black") ) ); for ( auto const& shape : shapes ) { shape->draw(); } return 0; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>introduction | Emmet</title> </head> <body> <!-- nav>ul>li --> <nav> <ul> <li></li> </ul> </nav> <nav class="menu"> <ul class="menu__list"> <li class="menu__link">Atributo</li> <li class="menu__link">Atributo</li> <li class="menu__link">Atributo</li> <li class="menu__link">Atributo</li> <li class="menu__link">Atributo</li> </ul> </nav> <!-- div+p+bq --> <div></div> <p></p> <blockquote></blockquote> <div class="container"></div> <p class="parrafo"></p>+ <blockquote class="cita"></blockquote> <!-- div+div>p>span+em^bq --> <div></div> <div> <p><span></span><em></em></p> <blockquote></blockquote> </div> <!-- div+div>p>span+em^^^bq --> <div></div> <div> <p><span></span><em></em></p> </div> <blockquote></blockquote> <!-- div+(div>p>span+em)+bq --> <div></div> <div> <p><span></span><em></em></p> </div> <blockquote></blockquote> <!-- div>(header>ul>li*2>a)+footer>p --> <div> <header> <ul> <li><a href=""></a></li> <li><a href=""></a></li> </ul> </header> <footer> <p></p> </footer> </div> <!-- (div>dl>(dt+dd)*3)+footer>p --> <div> <dl> <dt></dt> <dd></dd> <dt></dt> <dd></dd> <dt></dt> <dd></dd> </dl> </div> <footer> <p></p> </footer> <!-- div#footer.class1.class2.class3 --> <div id="footer" class="class1 class2 class3"></div> <!-- footer.footer.footer--modifier>nav.menu>ul.menu__list>(li.menu__link>a{atributo $})*3 --> <footer class="footer footer--modifier"> <nav class="menu"> <ul class="menu__list"> <li class="menu__link"><a href="">atributo 1</a></li> <li class="menu__link"><a href="">atributo 2</a></li> <li class="menu__link"><a href="">atributo 3</a></li> </ul> </nav> </footer> <!-- td[title="Hello world!" colspan=3] --> <td title="Hello world!" colspan="3"></td> <!-- ul>li.item$$$*5 --> <ul> <li class="item001"></li> <li class="item002"></li> <li class="item003"></li> <li class="item004"></li> <li class="item005"></li> </ul> <!-- ul>li.item$@-*5 --> <ul> <li class="item5"></li> <li class="item4"></li> <li class="item3"></li> <li class="item2"></li> <li class="item1"></li> </ul> <!-- ul>li.item$@3*5 --> <ul> <li class="item3"></li> <li class="item4"></li> <li class="item5"></li> <li class="item6"></li> <li class="item7"></li> </ul> <!-- a{Click me} --> <a href="">Click me</a> <!-- td[title="Hello world!" colspan=3] --> <td title="Hello world!" colspan="3"></td> <!-- nav.menuNav>ul>li.menuNav-item*8>a{Apartado $} --> <nav class="menuNav"> <ul> <li class="menuNav-item"><a href="">Apartado 1</a></li> <li class="menuNav-item"><a href="">Apartado 2</a></li> <li class="menuNav-item"><a href="">Apartado 3</a></li> <li class="menuNav-item"><a href="">Apartado 4</a></li> <li class="menuNav-item"><a href="">Apartado 5</a></li> <li class="menuNav-item"><a href="">Apartado 6</a></li> <li class="menuNav-item"><a href="">Apartado 7</a></li> <li class="menuNav-item"><a href="">Apartado 8</a></li> </ul> </nav> </body> </html>
from django.db import models from data_maintenance.models import Store,Member # Create your models here. class Goods(models.Model): gid = models.CharField("商品編號", max_length=30,primary_key=True) type = models.CharField("食物類型", max_length=30) sid = models.ForeignKey(Store, on_delete=models.CASCADE) name = models.CharField("商品名稱", max_length=30) intro = models.CharField("商品簡介", max_length=50, null=True) quantity = models.CharField("商品數量", default="1", null=False, max_length=10) food_pic = models.ImageField("商品照片", upload_to='good', null=True) price = models.CharField("價格", default="50", null=False, max_length=10) ingredient = models.CharField("食物使用成分", max_length=200) allergen = models.CharField("過敏原成分", max_length=200) status = models.BooleanField('是否供應',default=True) def __str__(self): return "編號:{},名稱:{}".format(self.gid,self.name) def food_pic_url(self): """用於將照片儲存""" if self.food_pic and hasattr(self.food_pic,'url'): return self.food_pic.url # USERNAME_FIELD = "gid" class Evaluate(models.Model): evaid = models.CharField("留言編號",max_length=30,primary_key=True) sid = models.ForeignKey(Store, on_delete=models.CASCADE,null=True) uid = models.ForeignKey(Member, on_delete=models.CASCADE,null=True) star = models.IntegerField('分數') explain = models.CharField("心得或改進",max_length=100,blank=True,null=True) date = models.DateField('填寫時間',auto_now_add=True,null=True) def __str__(self): return "編號:{},店家:{},分數:{}".format(self.evaid,self.sid,self.star)
import { preventUndefined, isUndefinedPrevented, undefinedlessFunction, recursivelyUnprevent, preventUnusedProperties, typesafe, errorIfUndefined, } from './index.mjs' ; import { schema } from 'vanilla-schema-validator'; import assert from 'node:assert/strict'; // import { test, describe, it, before, after } from 'node:test' ; describe('test of test', ()=>{ it('as 1',()=>{ assert.throws( ()=>{ throw new Error( 'foo' ); }, Error,'foo' ); }); it('as 2', ()=>{ assert.equal( 'foo', 'foo' ); }); it( 'as 3', ()=>{ assert.throws( ()=>{ throw new ReferenceError( 'aaa\naaa' ); }, ReferenceError, 'aaa\naaa' ); }); }); // let count = 0; // const s_test=(name,fn )=>{ // // if ( ++count < 17 ) { // // return test( name.replaceAll(/[^\x00-\x7F]/gm, " "), fn ); // // } // // return test( name.replaceAll(/[^\x00-\x7F]/gm, " "), fn ); // return test( name, fn ); // }; test( 'basic test', ()=>{ const __foo = { hello : { world : { foo : { bar : { muz : "HELLO", }, } } } }; assert.throws(()=> preventUndefined( __foo ).hello.world.foo.bar.buz ); }); test( 'test1 - Check if preventUndefined() can work with destructuring' , ()=>{ assert.throws(()=>{ const obj = preventUndefined({ foo : 'foo', bar : 'bar', }); // console.log({obj}) ; const { foo = 'foo', bar = 'bar', bum = 'uh oh!', } = obj; }, ReferenceError ); }); test( 'test2 - Check if it works with Array' , ()=>{ assert.throws(()=>{ const obj = preventUndefined({ arr : [1,2,3], })[4]; }, ReferenceError ); }); test( 'test3 - Accessing a nesting object with a path' , ()=>{ assert.throws(()=>{ const obj = preventUndefined({ hello : 'hello', world : 'world', foo : { hello : 'hello', world : 'world', bar : { hello : 'hello', world : 'world', baz : { }, } } }); console.log( obj.foo.bar.baz.bum ); }, ReferenceError ); }); const obj = { hello : 'hello', world : 'world', foo : { hello : 'hello', world : 'world', bar : { hello : 'hello', world : 'world', baz : { boo : '' }, } } }; function hello0(obj0,obj1) { return ( obj0.foo.bar.baz.bum ); } function hello1(obj0,obj1) { return ( obj1.foo.bar.baz.bum ); } test( 'Wrapping function (arg0) ... 1' , ()=>{ assert.throws(()=>{ try { console.log( undefinedlessFunction( hello0 )( obj, obj ) ); } catch (e) { throw e; } }, ReferenceError ); }); test( 'Wrapping function (arg0) ... 2' , ()=>{ assert.throws(()=>{ try { console.log( undefinedlessFunction( hello1 )( obj, obj ) ); } catch (e) { throw e; } }, ReferenceError ); }); test( 'Wrapping function (arg0) ... 3' , ()=>{ const result = undefinedlessFunction( function(hello) { return { hello, foo : 'bar', }; })(); assert.throws( ()=>result.barr ); }); test( 'check ignore list `then` (for `Promise`)' , ()=>{ assert.doesNotReject( Promise.resolve( preventUndefined({hello:1})) ); }); test( 'check ignore list `toPostgres` (for `node-postgres`)' , ()=>{ const __foo = { hello : { hello : true, } }; assert.doesNotThrow(()=> preventUndefined( __foo ).hello.toPostgres === true ); }); test( 'check ignore list `Symbol.search`' , ()=>{ const __foo = { hello : { [Symbol.search]: true, } }; assert.doesNotThrow(()=> preventUndefined( __foo ).hello[Symbol.search]===true ); }); test( 'check ignore list `$$typeof` (for React.js)' , ()=>{ const __foo = { hello : { [Symbol.search]: true, } }; assert.doesNotThrow(()=> preventUndefined( __foo ).hello['$$typeof'] === true ); }); test( 'check ignore list `toPostgres` (for `node-postgres`)' , ()=>{ const __foo = { hello : { [Symbol.search]: true, } }; assert.doesNotThrow(()=> preventUndefined( __foo ).hello['toPostgres'] === true ); }); test( 'check ignore list `@@iterator` (for `React.js`)' , ()=>{ const __foo = { hello : { ['@@iterator']: true, } }; assert.doesNotThrow(()=> preventUndefined( __foo ).hello['@@iterator'] === true ); }); test( 'errorIfUndefined 1' , ()=>{ assert.throws(()=>{ try{ (( { hello = errorIfUndefined('hello'), } )=>'result')( { hello_TYPO: 'hello', } ) } catch (e){ throw e; } }, ReferenceError); }); test( 'errorIfUndefined 2' , ()=>{ const o = preventUndefined({ a : preventUndefined({ b: 'hello', }), }); const o2 = recursivelyUnprevent( o ); assert.throws(()=>o2.hello.foo.bar ); assert.doesNotThrow(()=>o2.NONEXISTENT ); assert.doesNotThrow(()=>o2.a.NONEXISTENT ); assert.doesNotThrow(()=>o2.a.b ); assert.doesNotThrow(()=>o2.a.b.c ); assert.doesNotThrow(()=>o2.a.b.c ); }); // // SKIPPED DUE TO PROBABLY NODE:TEST BUG // https://github.com/nodejs/node/issues/46508 // describe( 'preventUnusedProperties', ()=>{ it( 'preventUnusedProperties' , ()=>{ const o = preventUndefined({ a:1, b:2, }); assert.throws( ()=>{ preventUnusedProperties(o) }, ReferenceError, 'the fields [a,b] were not referred in\n{\n "a": 1,\n "b": 2\n}' ); console.log( o.a ); assert.throws( ()=>{ preventUnusedProperties(o) }, ReferenceError, 'the field [b] was not referred in\n{\n "a": 1,\n "b": 2\n}' ); console.log( o.b ); assert.doesNotThrow(()=>{ preventUnusedProperties(o) } ); }); it( 'preventUnusedProperties for an array' , ()=>{ const o = preventUndefined(["foo","bar","bum"]); assert.throws(()=>{ preventUnusedProperties(o) }, ReferenceError, 'the fields [0,1,2] were not referred in\n[\n "foo",\n "bar",\n "bum"\n]' ); console.log( o[0] ); assert.throws(()=>{ preventUnusedProperties(o) }, ReferenceError, 'the fields [1,2] were not referred in\n[\n "foo",\n "bar",\n "bum"\n]' ); console.log( o[1] ); assert.throws(()=>{ preventUnusedProperties(o) }, ReferenceError, 'the field [2] was not referred in\n[\n "foo",\n "bar",\n "bum"\n]' ); console.log( o[2] ); assert.doesNotThrow(()=>{ preventUnusedProperties(o) }); }); }); test( 'sample' , ()=>{ assert.throws( ()=>{ function someFunc(args){ // Apply preventUndefined() on the `args` before destructuring it. args = preventUndefined(args); const {foo,bar} = args; // After destructured the `args` object, call `preventUnusedProperties()` preventUnusedProperties(args); console.log("foo:",foo); console.log("bar:",bar); } var foo = 'foo'; var bar = 'bar'; var baz = 'baz'; someFunc({foo,bar,baz}); }, ReferenceError, 'the field [baz] was not referred in\n{\n "foo": "foo",\n "bar": "bar",\n "baz": "baz"\n}' ); }); test( 'validator No.1 setting a bad value' , ()=>{ assert.throws(()=>{ const validator = (o)=>{ if ( o?.hello === 'yes' ) { return true; } else { return false; } }; const obj = preventUndefined({ hello:'yes', }, validator ); obj.hello = 'A BAD VALUE'; },ReferenceError); }); test( 'validator No.2 setting a correct value' , ()=>{ assert.doesNotThrow(()=>{ const validator = (o)=>{ if ( o?.hello === 'yes' ) { return true; } else { return false; } }; const obj = preventUndefined({ hello:'yes', }, validator ); obj.hello = 'yes'; }, ReferenceError); }); test( 'validator No.3 the entry time validation' , ()=>{ assert.throws(()=>{ const validator = (o)=>{ if ( o?.hello === 'yes' ) { return true; } else { return false; } }; const obj = preventUndefined({ hello:'aa', }, validator ); }, ReferenceError); }); test( 'validator No.4 the entry time validation' , ()=>{ assert.doesNotThrow(()=>{ const validator = (o)=>{ if ( o?.hello === 'yes' ) { return true; } else { return false; } }; const obj = preventUndefined({ hello:'yes', }, validator ); }, ReferenceError); }); test( 'validator No.5 check detecting modifying a nested property' , ()=>{ assert.throws(()=>{ const validator = (o)=>{ if ( o?.hello?.foo?.bar?.value === 'yes' ) { return true; } else { return false; } }; const obj = preventUndefined({ hello: { foo : { bar : { value : 'yes', }, }, }, }, validator ); obj.hello.foo.bar.value = 'a wrong value'; }, ReferenceError); }); test( 'validator No.6 check detecting modifying a nested property to a valid value' , ()=>{ assert.doesNotThrow(()=>{ const validator = (o)=>{ if ( o?.hello?.foo?.bar?.value === 'yes' ) { return true; } else { return false; } }; const obj = preventUndefined({ hello: { foo : { bar : { value : 'yes', }, }, }, }, validator ); obj.hello.foo.bar.value = 'yes'; }, ReferenceError); }); test( 'validator No.7 check detecting deleting a nested property' , ()=>{ assert.throws(()=>{ const validator = (o)=>{ if ( o?.hello?.foo?.bar?.value === 'yes' ) { return true; } else { return false; } }; const obj = preventUndefined({ hello: { foo : { bar : { value : 'yes', }, }, }, }, validator ); Object.defineProperty( obj.hello.foo.bar,'value', { value:'a bad value', }); }, ReferenceError); }); test( 'validator No.8 check detecting deleting a nested property' , ()=>{ assert.throws(()=>{ const validator = (o)=>{ if ( o?.hello?.foo?.bar?.value === 'yes' ) { return true; } else { return false; } }; const obj = preventUndefined({ hello: { foo : { bar : { value : 'yes', }, }, }, }, validator ); delete obj.hello.foo.bar.value; }, ReferenceError); }); test( 'validator No.9 check detecting throwing inside the validator' , ()=>{ assert.throws(()=>{ const validator = (o)=>{ if ( o?.hello?.foo?.bar?.value === 'yes' ) { return true; } else { return false; } }; const obj = preventUndefined({ HELLO: { FOO : { BAR : { value : 'yes', }, }, }, }, validator ); }, ReferenceError); }); function cropStacktrace(e) { const result = /\[stacktrace\]/g.exec( e.message ); // console.log( result ); if ( result && 0<=result.index ) { e.message = e.message.substring( 0, result.index ).trim(); } // console.log(e.message); return e; } function protectByCroppingStacktrace(f){ return ()=>{ try{ f(); } catch(e){ throw cropStacktrace(e); } }; } test( 'sample' , ()=>{ assert.throws( protectByCroppingStacktrace(()=>{ const validator = (o)=>typeof o?.foo?.bar?.value === 'number'; const obj = preventUndefined({ foo : { bar : { value : 100, }, } },validator); obj.foo.bar.value = 'BUMMER! NOT A NUMBER'; }), ReferenceError, ` [prevent-undefined] detected defining an invalid property value to obj.foo.bar.value on { "foo": { "bar": { "value": "BUMMER! NOT A NUMBER" } } } validator (o)=>typeof o?.foo?.bar?.value === 'number' `.trim()); }); test( 'typesafe' , ()=>{ assert.throws( protectByCroppingStacktrace(()=>{ const validator = (o)=>typeof o?.foo?.bar?.value === 'number'; const obj = typesafe(validator, { foo : { bar : { value : 100, }, } }); obj.foo.bar.value = 'BUMMER! NOT A NUMBER'; }), ReferenceError, (` [prevent-undefined] detected defining an invalid property value to obj.foo.bar.value on { "foo": { "bar": { "value": "BUMMER! NOT A NUMBER" } } } validator (o)=>typeof o?.foo?.bar?.value === 'number' `.trim())); }); test( 'typesafe No.2 an Example' , ()=>{ assert.throws( protectByCroppingStacktrace(()=>{ const t_user = o=>(typeof o?.name === 'string') && (typeof o?.age ==='number'); function check_user({user}) { user = typesafe( t_user, user ); // Setting a wrong value causes throwing an error. user.name = false; return user; } check_user({ user:{ name : 'John', age : 23 } }); }), ReferenceError,(` [prevent-undefined] detected defining an invalid property value to obj.name on { "name": false, "age": 23 } validator o=>(typeof o?.name === 'string') && (typeof o?.age ==='number') `.trim())); }); describe('onError',()=>{ it( 'as onError test No.1' , ()=>{ return new Promise((resolve,reject)=>{ let flag = null; let err = null; const validator = o=>(typeof o?.name === 'string') && (typeof o?.age ==='number'); const onError = ()=>{ flag = true; }; function check_user({user}) { user = preventUndefined( user, { validator, onError }); // Setting a wrong value causes throwing an error. user.name = false; return user; } try{ check_user({ user:{ name : 'John', age : 23 } }); } catch(e){ err = e; } setTimeout( ()=>{ if ( ( flag === true ) && ( err !=null ) && ( 0<= err.message.indexOf( '[prevent-undefined]' ) ) ) { resolve(); } else { reject(); } }, 200 ); }); }); it( 'as onError test No.2' , ()=>{ return new Promise((resolve,reject)=>{ let flag = null; let err = null; const validator = o=>(typeof o?.name === 'string') && (typeof o?.age ==='number'); const onError = ()=>{ flag = true; }; function check_user({user}) { user = preventUndefined( user, { validator, onError }); // Setting a wrong value causes throwing an error. const val = user.WRONG_PROP; return user; } try{ check_user({ user:{ name : 'John', age : 23 } }); } catch(e){ err = e; } setTimeout( ()=>{ if ( ( flag === true ) && ( err !=null ) && ( 0<= err.message.indexOf( '[prevent-undefined]' ) ) ) { resolve(); } else { reject(`flag=${flag} err=${err}`); } }, 200 ); }); }); }); /* * TODO test all properties of the argument of `onError()` */ // test( 'onError example', ()=>{ // const obj = preventUndefined({ // foo: 'foo', // bar: 'bar', // }, { // onError: (info)=>{ // console.log( 'called ' + info.propPath ); // } // }); // // console.log( obj.wrongProp ); // // }); test( 'automatic unprevent for functions', ()=>{ const o = preventUndefined({ foo : { bar : { func : function foo_bar_func() { return isUndefinedPrevented( this ); }, }, }, }); console.log( o.foo.bar ); console.log( o.foo.bar.func ); assert.equal( o.foo.bar.func() , false ); }); test( 'automatically unprevent for functions', ()=>{ const o = preventUndefined({ foo : { bar : { func : function foo_bar_func() { console.log( `this[Symbol.for('__IS_PREVENTED_UNDEFINED__')]`, this[Symbol.for('__IS_PREVENTED_UNDEFINED__')] , ' ^^^ should be undefined ^^^' , ); return !! this[Symbol.for('__IS_PREVENTED_UNDEFINED__')]; }, }, }, }); console.log( o.foo.bar ); console.log( o.foo.bar.func ); assert.equal( o.foo.bar.func() , false ); }); // ADDED ON (Thu, 05 Jan 2023 14:18:29 +0900) test( 'non-writable and non-configurable ', ()=>{ const target ={}; const test_content = { foo : { bar : { func : function fooo_bar_func() { return 'foo_bar'; } } } }; Object.defineProperty( target ,'hello', { value : test_content, writable : false, configurable : false, }); const obj = preventUndefined( target ); assert.equal( obj.hello.foo.bar.func() , 'foo_bar' ); }); // ADDED ON (Thu, 05 Jan 2023 15:12:03 +0900) ignore function.prototype test( 'ignore functions in order to (mostly) unprevent `prototype` ', ()=>{ function target() { } const obj = preventUndefined( target ); assert.equal( !! obj.prototype[ Symbol.for('__IS_PREVENTED_UNDEFINED__') ] , false ); }); { const obj = { foo: { bar : { baz :{ data:1 }, }, }, }; test( 'maxRecursiveLevel ... base ', ()=>{ const po = preventUndefined( obj ); assert.equal( isUndefinedPrevented( po.foo ), true ); assert.equal( isUndefinedPrevented( po.foo.bar ), true ); assert.equal( isUndefinedPrevented( po.foo.bar.baz ), true ); }); test( 'maxRecursiveLevel ...0 ', ()=>{ const po = preventUndefined( obj, {maxRecursiveLevel:0 } ); assert.equal( isUndefinedPrevented( po ), false ); assert.equal( isUndefinedPrevented( po.foo ), false ); assert.equal( isUndefinedPrevented( po.foo.bar ), false ); assert.equal( isUndefinedPrevented( po.foo.bar.baz ), false ); }); test( 'maxRecursiveLevel ...1 ', ()=>{ const po = preventUndefined( obj, {maxRecursiveLevel:1 } ); assert.equal( isUndefinedPrevented( po ), true ); assert.equal( isUndefinedPrevented( po.foo ), false ); assert.equal( isUndefinedPrevented( po.foo.bar ), false ); assert.equal( isUndefinedPrevented( po.foo.bar.baz ), false ); }); test( 'maxRecursiveLevel ...2 ', ()=>{ const po = preventUndefined( obj, {maxRecursiveLevel:2 } ); assert.equal( isUndefinedPrevented( po ), true ); assert.equal( isUndefinedPrevented( po.foo ), true ); assert.equal( isUndefinedPrevented( po.foo.bar ), false ); assert.equal( isUndefinedPrevented( po.foo.bar.baz ), false ); }); test( 'maxRecursiveLevel ...3 ', ()=>{ const po = preventUndefined( obj, {maxRecursiveLevel:3 } ); assert.equal( isUndefinedPrevented( po ), true ); assert.equal( isUndefinedPrevented( po.foo ), true ); assert.equal( isUndefinedPrevented( po.foo.bar ), true ); assert.equal( isUndefinedPrevented( po.foo.bar.baz ), false ); }); } // { // const __IS_PREVENTED_UNDEFINED__ = Symbol.for( '__IS_PREVENTED_UNDEFINED__' ); // // test( 'inherit proxy class test 1', ()=>{ // /* // * Check if it works properly even if the parent class of a class is // * protected by preventUndefined(). // */ // class A { // constructor() { // this.a=1; // } // static getClassName() { // return this.name; // } // } // // assert.equal( A.getClassName() , 'A' ); // // const PA = preventUndefined( A ); // // assert.equal( PA.getClassName() , 'A' ); // // class PB extends PA { // constructor(){ // super(); // } // } // // console.log( isUndefinedPrevented( A ) ); // console.log( isUndefinedPrevented( PA ) ); // // // assert.equal( isUndefinedPrevented( A ) ,false); // assert.equal( isUndefinedPrevented( PA ) ,true); // assert.equal( isUndefinedPrevented( PB ) ,false); // // // This value `true` comes from A class. There is no way to intercept // // accessing fields to get own values of objects in JavaScript. // assert.equal( PB[ __IS_PREVENTED_UNDEFINED__ ] , true ); // // assert.equal( isUndefinedPrevented( PB ) , false ); // // assert.equal( PB.getClassName() , 'PB' ); // }); // } // test( 'test 2', ()=>{ const arr = preventUndefined( [3,2,1,0] ); assert.doesNotThrow( ()=>{ const arr2= [ ...arr ]; console.log(arr2); }); }); test( 'not to accept a validator factory as a validator', ()=>{ assert.throws( ()=>{ try { preventUndefined( [3,2,1,0] , ()=>()=>true ); } catch ( e ) { throw e; } }, TypeError , ( 'Your validator returned a function. Check your code. ' + 'The bet is, you forgot to invoke your validator factory.') ); assert.doesNotThrow( ()=>{ try { preventUndefined( [3,2,1,0] , ()=>true ); } catch ( e ) { console.error(e); throw e; } } ); }); test( 'test array ', ()=>{ const arr = preventUndefined( [0,1,2,[0,1,2]] ); assert.throws( ()=>{ console.log( arr[3][4] ); }); }); describe('new message', ()=>{ it( 'as 1', ()=>{ const __foo = { hello : { world : { foo : { bar : { baz : "HELLO", }, } } } }; try { preventUndefined( __foo ).hello.world.foo.bar.BAZ } catch ( e ){ console.error( 'as 1', e ); } }); it( 'as 2', ()=>{ const __foo = { hello : { world : { foo : { bar : { baz : "HELLO", }, } } } }; schema.define` foo1 : object( hello : object( world : object( foo : object( bar : object( baz : string()))))), foo2 : object( hello : object( world : object( foo : object( bar : object( baz : number()))))), `; try { preventUndefined( __foo, schema.foo2() ); } catch ( e ){ console.error( 'as 2', e ); } }); });
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; import 'package:flutter_ecommerce_app/provider/cart.dart'; import 'package:flutter_ecommerce_app/shared/appbar.dart'; import 'package:provider/provider.dart'; class CheckOut extends StatelessWidget { const CheckOut({super.key}); @override Widget build(BuildContext context) { final cartt = Provider.of<Cart>(context); return SafeArea( child: Scaffold( appBar: AppBar( iconTheme: const IconThemeData(color: Colors.white), backgroundColor: const Color.fromARGB(255, 76, 141, 95), title: Text( "Check Out", style: TextStyle(color: Colors.white), ), actions: [Productss()], ), body: Column( children: [ SingleChildScrollView( child: SizedBox( height: 500, child: ListView.builder( padding: const EdgeInsets.all(8), itemCount: cartt.selectedProducts.length, itemBuilder: (BuildContext context, int index) { return Card( child: ListTile( subtitle: Text( "${cartt.selectedProducts[index].price} - ${cartt.selectedProducts[index].location}"), leading: CircleAvatar( backgroundImage: AssetImage( cartt.selectedProducts[index].imgPath), ), title: Text(cartt.selectedProducts[index].name), trailing: IconButton( onPressed: () { cartt.delete(cartt.selectedProducts[index]); }, icon: Icon(Icons.remove)), ), ); }), ), ), SizedBox( height: 30, ), ElevatedButton( onPressed: () {}, style: ButtonStyle( backgroundColor: MaterialStateProperty.all( Color.fromARGB(255, 73, 179, 105)), padding: MaterialStateProperty.all(EdgeInsets.all(12)), shape: MaterialStateProperty.all(RoundedRectangleBorder( borderRadius: BorderRadius.circular(12))), ), child: Text( "Pay \$${cartt.price}", style: TextStyle(fontSize: 19, color: Colors.white), ), ), ], ), ), ); } }
using System; using System.Collections; using UnityEngine; using UnityEngine.Serialization; /// <summary> /// Projectile is a child class from attack and it is to represent the moving sprite attacks. /// Author: Tedrik "Teddy" Dumam-Ag (A01329707) /// Date: April 13 2024 /// Source: Applied C# and Unity Skills /// </summary> public abstract class Projectile : Attack { // Parent's position. private Vector2 _parent; // Target's position. protected Vector2 Target; // Establish a wait before destroying. private readonly WaitForSeconds _destroyDelay = new(1); // Projectile's animator. protected Animator Animator; // Projectile type as a string. [SerializeField] private string projectileType; // Get the projectile type. public string ProjectileType => projectileType; // How far should the projectile go. [FormerlySerializedAs("_rangeFloat")] [SerializeField] private float rangeFloat; // Sets all local values and adds a force in order to move the projectile from the player protected override void Init() { var currTransform = transform; _parent = currTransform.position; Animator = GetComponent<Animator>(); Target = GetTargetPosition(); SetRotation(); GetComponent<Rigidbody2D>().AddForce( Target.normalized * rangeFloat, ForceMode2D.Impulse ); // Start destroying self because they are very fragile when they spawn. StartCoroutine(DestroySelf()); } /// <summary> /// Set the rotation of the projectile. /// </summary> protected abstract void SetRotation(); protected override void BeforeAddingImplodeForce() { CheckBounds(); } protected override Vector2 GetStartingPosition() { return transform.position; } /// <summary> /// Enables impact status and destroy itself. /// </summary> protected virtual void CheckBounds() {} /// <summary> /// Get the target's position. /// </summary> /// <returns>Vector2, the distance of target minus parent, otherwise parent object.</returns> private Vector2 GetTargetPosition() { Vector2 to; if (ParentObject.CompareTag("Player") ) { if (Player.ChosenClass.Name == "Melee") { // Melee to.x = ParentObject.transform.localScale.x; to.y = 0; return to; } else { // Archer or Mage Vector3 temp = GameObject.FindWithTag("MainCamera").GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition); to.x = temp.x; to.y = temp.y; Vector2 diff = to - _parent; if (diff.x < 0) ParentObject.transform.localScale = new Vector3(-1, ParentObject.transform.localScale.y, 1); else ParentObject.transform.localScale = new Vector3(1, ParentObject.transform.localScale.y, 1); return diff; } } else { // Creature Vector3 temp = GameObject.FindWithTag("Player").transform.position; to.x = temp.x; to.y = temp.y; return to - _parent; } // try // test after testing the above // { // // TODO: NOAH'S MELEE IDEA IS PLACED HERE (REMOVE #TODO ONCE WRITTEN HERE) // Vector2 to = ParentObject.CompareTag("Player") ? // GameObject.FindWithTag("MainCamera").GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition) // : GameObject.FindWithTag("Player").transform.position; // return to - _parent; // } // catch (NullReferenceException) // { // BeforeDestroy(); // } // return _parent; } /// <summary> /// Perform a task before being destroyed. /// </summary> protected virtual void BeforeDestroy() {} /// <summary> /// Wait for one second and do task before destroying. /// </summary> /// <returns></returns> private IEnumerator DestroySelf() { yield return _destroyDelay; BeforeDestroy(); } protected override int GetAttackTypeDamage() { return Player.ChosenClass.Weapon.PerformAttackType(projectileType); } }
export interface NFLTeamStandingsI { wins: number losses: number ties: number winPercentage: number homeRecord: string visitorRecord: string divisionRecord: string conferenceRecord: string pointsFor: number pointsAgainst: number pointsDifferential: number currentStreak: string overallRecord: string } export interface NFLStatsOffenseDefenseI { totalYards: number yardsPerGame: number totalPassingYards: number passingYardsPerGame: number totalRushingYards: number rushingYardsPerGame: number totalPoints: number pointsPerGame: number } interface NFLSpecialTeamsI { kickTotalYards: number kickLong: number kickTouchdowns: number kickAttempts: number averageYardsPerKick: number puntTotalYards: number puntLong: number puntTouchdowns: number puntAttempts: number averageYardsPerPunt: number fairCatches: number } interface NFLTurnoversI { ratio: number takeawayInterceptions: number takeawayFumbles: number takeawayTotal: number giveawayInterceptions: number giveawayFumbles: number giveawayTotal: number } export interface NFLTeamI { name: string code: string standings: NFLTeamStandingsI, stats: { offense: NFLStatsOffenseDefenseI defense: NFLStatsOffenseDefenseI specialTeams: NFLSpecialTeamsI turnovers: NFLTurnoversI } } export interface SetTeamsStandingsI { [key: string]: { name: string code: string standings: NFLTeamStandingsI } } export interface SetTeamsOffenseI { [key: string]: { name: string offense: NFLStatsOffenseDefenseI } } export interface SetTeamsDefenseI { [key: string]: { name: string defense: NFLStatsOffenseDefenseI } } export interface SetSpecialTeamsI { [key: string]: { name: string specialTeams: NFLSpecialTeamsI } } export interface SetTurnoversI { [key: string]: { name: string turnovers: NFLTurnoversI } } export interface SetNFLTeamsI { [key: string]: { name: string code: string standings: NFLTeamStandingsI, stats: { offense: NFLStatsOffenseDefenseI defense: NFLStatsOffenseDefenseI specialTeams: NFLSpecialTeamsI turnovers: NFLTurnoversI } } }
console.log(document) const myMessage = document.querySelector('.myMessage'); console.log(myMessage); const theMessageButton = document.querySelector('.theMessageButton'); theMessageButton.addEventListener('click', function() { myMessage.innerText = 'Button pressed' setTimeout(function(){ myMessage.innerText = 'Press a button or enter a number' }, 5000 ) }); const clearButton = document.querySelector('.clearButton'); clearButton.addEventListener('click', function() { myMessage.innerText = '' setTimeout(function(){ myMessage.innerText = 'Press a button or enter a number' }, 3000 ) }); const inputBox = document.querySelector('.theInputValue'); theMessageButton.addEventListener('click', function() { myMessage.innerText = inputBox.value }); theMessageButton.addEventListener('click', function() { if (inputBox.value.trim().length > 0) { myMessage.innerText = inputBox.value; } }); myMessage.addEventListener('click', function() { myMessage.classList.toggle('darkmode') }) const fruits = ['Apples', 'Pears', 'Oranges', 'Grapes', 'Bananas']; const fruitList = document.querySelector(".fruits"); for(let i=0;i<fruits.length;i++){ const fruit = fruits[i]; const li = document.createElement('li'); li.innerText = fruit; fruitList.appendChild(li); }
--- title: userExperienceAnalyticsBatteryHealthModelPerformance 资源类型 description: 用户体验分析电池运行状况模型性能实体包含其组织中所有唯一设备模型的电池相关信息。 author: dougeby localization_priority: Normal ms.prod: intune doc_type: resourcePageType ms.openlocfilehash: 010b4498a8b725519636a727e0fada648c3a2b69 ms.sourcegitcommit: 435d70e7adb27e6cedaf485ebfdab7c3ef9ffacf ms.translationtype: MT ms.contentlocale: zh-CN ms.lasthandoff: 06/02/2022 ms.locfileid: "65857426" --- # <a name="userexperienceanalyticsbatteryhealthmodelperformance-resource-type"></a>userExperienceAnalyticsBatteryHealthModelPerformance 资源类型 命名空间:microsoft.graph > **重要:**/beta 版本下的 Microsoft Graph API 可能会发生更改;不支持生产使用。 > **注意:** 适用于 Intune 的 Microsoft Graph API 需要适用于租户的 [活动 Intune 许可证](https://go.microsoft.com/fwlink/?linkid=839381)。 用户体验分析电池运行状况模型性能实体包含其组织中所有唯一设备模型的电池相关信息。 ## <a name="methods"></a>方法 |方法|返回类型|说明| |:---|:---|:---| |[列出 userExperienceAnalyticsBatteryHealthModelPerformances](../api/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance-list.md)|[userExperienceAnalyticsBatteryHealthModelPerformance](../resources/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance.md) 集合|列出 [userExperienceAnalyticsBatteryHealthModelPerformance](../resources/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance.md) 对象的属性和关系。| |[获取 userExperienceAnalyticsBatteryHealthModelPerformance](../api/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance-get.md)|[userExperienceAnalyticsBatteryHealthModelPerformance](../resources/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance.md)|读取 [userExperienceAnalyticsBatteryHealthModelPerformance](../resources/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance.md) 对象的属性和关系。| |[创建 userExperienceAnalyticsBatteryHealthModelPerformance](../api/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance-create.md)|[userExperienceAnalyticsBatteryHealthModelPerformance](../resources/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance.md)|创建新的 [userExperienceAnalyticsBatteryHealthModelPerformance](../resources/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance.md) 对象。| |[删除 userExperienceAnalyticsBatteryHealthModelPerformance](../api/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance-delete.md)|None|删除 [userExperienceAnalyticsBatteryHealthModelPerformance](../resources/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance.md)。| |[更新 userExperienceAnalyticsBatteryHealthModelPerformance](../api/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance-update.md)|[userExperienceAnalyticsBatteryHealthModelPerformance](../resources/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance.md)|更新 [userExperienceAnalyticsBatteryHealthModelPerformance 对象的](../resources/intune-devices-userexperienceanalyticsbatteryhealthmodelperformance.md) 属性。| ## <a name="properties"></a>属性 |属性|类型|说明| |:---|:---|:---| |id|String|用户体验分析电池运行状况模型性能对象的唯一标识符。| |activeDevices|Int32|该模型的活动设备数。 有效值 -2147483648 2147483647| |model|String|设备的模型名称。| |manufacturer|String|设备制造商的名称。| |averageMaxCapacityPercentage|Int32|给定模型的所有设备的最大容量的平均值。 最大容量度量设备电池的全费与设计容量。 有效值 -2147483648 2147483647| |averageEstimatedRuntimeInMinutes|Int32|给定模型的所有设备的全费估计运行时的平均值。 以分钟为单位。 有效值 -2147483648 2147483647| |averageBatteryAgeInDays|Int32|租户中给定模型的所有设备的电池使用时间平均值。 单位(以天为单位)。 有效值 -2147483648 2147483647| |modelBatteryHealthScore|Int32|模型最大容量分数和运行时估计分数的加权平均值。 值范围为 0-100。 有效值 -2147483648 2147483647| ## <a name="relationships"></a>关系 无 ## <a name="json-representation"></a>JSON 表示形式 下面是资源的 JSON 表示形式。 <!-- { "blockType": "resource", "keyProperty": "id", "@odata.type": "microsoft.graph.userExperienceAnalyticsBatteryHealthModelPerformance" } --> ``` json { "@odata.type": "#microsoft.graph.userExperienceAnalyticsBatteryHealthModelPerformance", "id": "String (identifier)", "activeDevices": 1024, "model": "String", "manufacturer": "String", "averageMaxCapacityPercentage": 1024, "averageEstimatedRuntimeInMinutes": 1024, "averageBatteryAgeInDays": 1024, "modelBatteryHealthScore": 1024 } ```
<?php namespace App\Http\Controllers\Foreign; use App\Http\Requests\ProfileUpdateRequest; use App\Models\HobbyCategory; use App\Models\JapanRegion; use App\Models\JapanLocation; use App\Models\Country; use App\Models\ForeignVisitor; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Redirect; use Inertia\Inertia; use Inertia\Response; use Cloudinary; use App\Http\Controllers\Controller; class ForeignProfileController extends Controller { /** * Display the user's profile form. */ public function edit(Request $request,HobbyCategory $hobby_category,ForeignVisitor $foreign_visitor, JapanRegion $japan_region, JapanLocation $japan_location, Country $country): Response { return Inertia::render('ForeignProfile/Edit', [ 'mustVerifyEmail' => $request->user() instanceof MustVerifyEmail, 'status' => session('status'), 'hobby_categories' => $hobby_category->get(), 'japan_regions' => $japan_region->get(), 'japan_locations' => $japan_location->get(), 'countries' => $country->get(), 'foreign' => $foreign_visitor->where('user_id',Auth::id())->first(), ]); } /** * Update the user's profile information. */ public function update(ProfileUpdateRequest $request,ForeignVisitor $foreign_visitor): RedirectResponse { // dd($request->all()); $request->user()->fill($request->validated()); if ($request->user()->isDirty('email')) { $request->user()->email_verified_at = null; } if($request->file('image_url') != null){ $image_url = Cloudinary::upload($request->file('image_url')->getRealPath())->getSecurePath(); $request->user()->image_url=$image_url; } $request->user()->save(); $input["user_id"]=Auth::id(); $input["register_location_id"]=$request["register_location_id"]; $input["stay_location_id"]=$request["stay_location_id"]; $input["start_of_stay"]=$request["start_of_stay"]; $input["end_of_stay"]=$request["end_of_stay"]; $input["reason"]=$request["reason"]; $foreign=$foreign_visitor->where('user_id',Auth::id())->first(); $foreign->fill($input)->save(); return Redirect::route('foreign.profile.edit'); } /** * Delete the user's account. */ public function destroy(Request $request): RedirectResponse { $request->validate([ 'password' => ['required', 'current-password'], ]); $user = $request->user(); Auth::logout(); $user->delete(); $request->session()->invalidate(); $request->session()->regenerateToken(); return Redirect::to('/'); } }
NAME RT::Extension::SMSNotify - Send SMS notifications from RT via SMS::Send SYNOPSIS You don't generally use this module directly from your own code, it's an RT extension. See "CONFIGURATION" DESCRIPTION Use RT::Extension::SMSNotify to send text message notifications to mobile phones when events occur in RT, or via RT Crontool to do time-based alerting for things like SLA warnings. Useful in conjunction with the RT::Extension::SLA module. SMSes are sent using the SMS::Send module; this has been tested with SMS::Send::RedOxygen. You will need an SMS::Send driver module installed to use the SMSNotify extension. Writing them is easy if you can't find one for your provider. Most SMS providers only offer asynchronous non-guranteed delivery and there's no provision for asynchronous delivery status notification in the SMS::Send API. If a text message isn't immediately rejected by the provider this plugin will report that the message was dispatched successfully. SMSNotify can make no guarantees about whether the message was delivered. If you need reliable, guaranteed-delivery messaging you should look elsewhere - but remember that no message is truly received until a human has read and acknowledged it. If SMSes fail to send the resulting exception is reported to the address by default. You can provide your own error reporting function to override it; see CONFIGURATION below. INSTALLATION Install RT::Extension::SMSNotify using CPAN or using the usual: perl Makefile.PL make sudo make install process. This extension can optionally install some scrip actions in your RT database. If you do not install them, you can't create scrips via the RT web UI, but you can still use "RT::Action::SMSNotify" via "rt-crontool" etc. You can add scripactions manually if you prefer, or run: make initdb as a user that has read permission to your "RT_SiteConfig.pm". Do not run "make initdb" multiple times; this will result in duplicate entries in your RT database. If you have created duplicates you can carefully delete the duplicates manually. Alternately, delete all scrips that use the actions then delete them all from your database's "scripactions" table with something like: DELETE FROM scripactions WHERE name LIKE '[SMSNotify]%'; and add them back in by running "make initdb" *once*. CONFIGURATION # Add the plugin to your RT_SiteConfig.pm's plugin list. (Append to any existing # @Plugins setting rather than adding a new one). Set(@Plugins, qw(RT::Extension::SMSNotify)); # In RT_SiteConfig.pm, add entries for your SMS::Send provider and its setup # argument hash, eg: Set($SMSNotifyProvider, 'RedOxygen'); Set($SMSNotifyArguments, { _accountid => 'XXXXXXXXXXX' _email => 'xxxxx@xxxxxxxxxxxxxxx', _password => 'xxxxxxxx' }); # Then use RT-crontool to invoke the action or register it in the RT DB and use # it in scrips. $SMSNotifyProvider The $SMSNotifyProvider parameter must be set to the name of an installed "SMS::Send" module as a string, without the "SMS::Send" qualifier. For example, to use SMS::Send::RedOxygen you'd use: Set($SMSNotifyProvider, 'RedOxygen'); $SMSNotifyArguments The $SMSNotifyArguments parameter must be set to a hash reference with the parameters the SMS:Send driver expects. The exact parameters will vary from driver to driver. The sample given in "CONFIGURATION" shows settings for "SMS::Send::RedSMS". $SMSNotifyGetPhoneForUserFn This config-overridable method is useful for filtering users to limit the recipients of a message. For example, you might want to return a user's phone number only when their local time is between 08:00 and 17:00. If set, this variable must be either a function reference or a string that names a module with a function named GetPhoneForUser. In either case the variable is set in RT_SiteConfig.pm. If defined this function must take an RT::User as the 1st argument and returns a phone number as a string. The default implementation looks up the RT::User's PagerPhone attribute, which is shown as Pager in the RT UI, but you can replace this with an LDAP query or whatever you want. Two additional arguments are passed: the Ticket being operated on or undef if no ticket, and a user-defined hint extracted from the action argument if found as documented in SMS::Action::SMSNotify. Return undef or the empty string if no phone number exists for a user. More than one phone number may be returned by returning an array (not an arrayref); all of them will be notified. To set it as an anonymous function reference: Set($SMSNotifyGetPhoneForUserFn, sub { my ($user, $ticket, $hint) = @_; return $user->PagerPhone; }); Alternately and preferably if the above code were put in a function named GetPhoneForUser in a module named 'My::Module' with a matching 'package' declaration the configuration would be: Set($SMSNotifyGetPhoneForUserFn, 'My::Module'); Note that this method has full access to the RT system so write it carefully and don't trust user-supplied code. $SMSNotifyErrorAlertFn This config-overridable method lets you change this extension's error reporting for when SMSes fail to send. You might want this if you're using a pre-paid service and want to alert when you're out of credit, for example. It works like $SMSNotifyGetPhoneForUserFn in that it can be set to a function reference or to the string name of a module with a function named 'ErrorAlert'. The function (whether in a module or a func ref) must accept four arguments: * The SMS::Send result code (non-zero) * The SMS::Send error message * The destination phone number * The destination RT::User or undef if none The default implementation sends an email to the rt owner address. Use with rt-crontool This is an example of RT::Extension::SMSNotify use with rt-crontool in /etc/crontab format. The example presumes the existence of a template named 'SLA Alert SMS' and assumes that your local RT user is named 'requesttracker4'. There must be a user in the RT database with 'gecos' set to the local RT user Cron uses. The action argument specifies that notifications should be sent to all ticket AdminCc users/groups and queue AdminCc watchers. Action arguments are documented in RT::Action::SMSNotify. The search filter is a TicketSQL expression. You can use the RT query builder to generate TicketSQL, but it's very limited so you will usually want to write your own. You can test it by pasting it into the Advanced search in RT. This search sends SMSes for any ticket with a due date set that's due 24-25 mins, 11-12 mins, or 3-5 mins from now. Since it runs every minute ("*/1"; could just be written as "*") this will generate one message for each of the first time ranges and two for the 2nd. The crontab entry: */1 * * * * requesttracker4 rt-crontool --transaction last --search RT::Search::FromSQL --search-arg "(Status='new' OR Status='open') AND (Due > 'Jan 1, 1970') AND ((Due < '25 minutes' AND Due >= '24 minutes') OR (Due < '12 minutes' AND Due >= '11 minutes') OR (Due < '5 minutes' AND Due >= '3 minutes'))" --action RT::Action::SMSNotify --action-arg "TicketAdminCc,QueueAdminCc" --template 'SLA Alert SMS' If you want to test sending messages from cron use a simple search for ticket ID, eg: rt-crontool --search RT::Search::FromSQL --search-arg 'Id = 1033' --action RT::Action::SMSNotify --action-arg "TicketAdminCc,QueueAdminCc" --template 'SLA Alert SMS' or to send direct to a specified phone number: rt-crontool --search RT::Search::FromSQL --search-arg 'Id = 1033' --action RT::Action::SMSNotify --action-arg "p:+1234123132" --template 'SLA Alert SMS' Unlike email templates, your SMS templates don't need a header. RT will complain if you don't leave the first line blank in your template as it thinks you still need headers. Your template may use the following variables: Argument The argument to this invocation of RT::Extension::SMSNotify TicketObj The ticket object (undef if none) this action is acting on TransactionObj The current transaction PhoneNumber The phone number this template invocation will be sent to UserObj The RT::User whose pager number this is, or undef if it was supplied by other means like the argument. The template is executed once per SMS. If a user has more than one phone number it'll be executed once per phone number so you'll see the same UserObj more than once. Remember that UserObj can be "undef". For example, a template for due date alerting could be: RT alert: {$Ticket->SubjectTag} is due in { $Ticket->DueObj->AgeAsString() } AUTHOR Craig Ringer <craig@2ndquadrant.com> Copyright 2013 Craig Ringer This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of the license can be found in the LICENSE file included with this module. POD ERRORS Hey! The above document had some coding errors, which are explained below: Around line 189: Unknown directive: =head Around line 216: Unknown directive: =COPYRIGHT
import PropTypes from "prop-types"; import { useState } from "react"; export default function ProductCard({ data = {}, handleAddToCart = () => {}, handleRemoveFromCart = () => {}, isAddedToCart = false, }) { const [isHovered, setIsHovered] = useState(false); function renderRatings(rating = 0) { let ratingsNode = []; for (let i = 0; i < rating; i++) { ratingsNode.push(<div className="bi-star-fill"></div>); } return ratingsNode; } return ( <div className="col-md-3 mb-5 cards" onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)} style={{ transform: isHovered ? "scale(1.05)" : "scale(1)", transition: "transform 0.4s ease", }} > <div className="card h-100"> <div className="badge bg-dark text-white position-absolute" style={{ top: "0.5rem", right: "0.5rem" }} > Sale </div> <img className="card-img-top" src={data.image} alt="..." /> <div className="card-body p-4"> <div className="text-center"> <h5 className="fw-bolder">{data.name}</h5> <div className="d-flex justify-content-center small text-warning mb-2"> {renderRatings(data.rating)} </div> <span className="text-muted text-decoration-line-through"> ${data.normalCost} </span> ${data.actualCost} </div> </div> <div className="card-footer p-4 pt-0 border-top-0 bg-transparent"> <div className="text-center"> <button className="btn btn-outline-dark mt-auto" onClick={() => { if (isAddedToCart) { handleRemoveFromCart(data); } else { handleAddToCart(data); } }} > {isAddedToCart ? "Remove from cart" : "Add to cart"} </button> </div> </div> </div> </div> ); } ProductCard.propTypes = { data: PropTypes.object, handleAddToCart: PropTypes.func, handleRemoveFromCart: PropTypes.func, isAddedToCart: PropTypes.bool, };
import { Color3, Mesh, MeshBuilder, NodeMaterial, PointLight, Scene, ShadowDepthWrapper, ShadowGenerator, Sound, Vector3 } from "@babylonjs/core"; import {Area} from "amazer"; import {Game, State} from "./game"; import FireBallSound from "./assets/sounds/flames.mp3" export class FireBall { private readonly mesh: Mesh; private moveDirection: string; private collider: Mesh; private sound: Sound; constructor(private scene: Scene, private maze: Area, position: Vector3, private game: Game) { this.mesh = MeshBuilder.CreateSphere("fireball", { diameter: 3, segments: 32 }); this.mesh.position = position; this.moveDirection = 'up'; this.collider = new Mesh('fireball collider', scene); this.collider.visibility = 0; scene.registerBeforeRender(() => this.move()); const fireBallLight = new PointLight("pointLight", new Vector3(0, 0, 0), scene); fireBallLight.range = 5; fireBallLight.intensity = 3; fireBallLight.diffuse = new Color3(1, 0, 0); fireBallLight.specular = new Color3(1, 1, 0); fireBallLight.parent = this.mesh; this.sound = new Sound("fireball sound", FireBallSound, scene, null, { loop: true, volume: 0.5, spatialSound: true // maxDistance: 60, // refDistance: 20 }); this.sound.attachToMesh(this.mesh); } private move() { if (this.game.getState() === State.GAME) { if (!this.sound.isPlaying) { this.sound.play(); } let moveDirection = this.moveDirection; const isCloseToDirectionChange = (Math.round(this.mesh.position.z) % 5 === 0 && (Math.abs(Math.round(this.mesh.position.z) - this.mesh.position.z)) < 0.02) && (Math.round(this.mesh.position.x) % 5 === 0 && (Math.abs(Math.round(this.mesh.position.x) - this.mesh.position.x)) < 0.02) if (isCloseToDirectionChange) { this.mesh.position.x = Math.round(this.mesh.position.x); this.mesh.position.z = Math.round(this.mesh.position.z); const mazeX = (this.mesh.position.x + 100) / 5; const mazeY = (this.mesh.position.z + 90) / 5; const maze = this.maze; const moveDirections: string[] = []; if (moveDirection === 'up') { if (maze.tiles[mazeX][mazeY + 1].name === 'Floor') { moveDirections.push('up'); } if (maze.tiles[mazeX + 1][mazeY].name === 'Floor') { moveDirections.push('right'); } if (maze.tiles[mazeX - 1][mazeY].name === 'Floor') { moveDirections.push('left'); } if (moveDirections.length === 0 && maze.tiles[mazeX][mazeY + 1].name === 'Wall') { moveDirections.push('down'); } } else if (moveDirection === 'down') { if (maze.tiles[mazeX][mazeY - 1].name === 'Floor') { moveDirections.push('down'); } if (maze.tiles[mazeX + 1][mazeY].name === 'Floor') { moveDirections.push('right'); } if (maze.tiles[mazeX - 1][mazeY].name === 'Floor') { moveDirections.push('left'); } if (moveDirections.length === 0 && maze.tiles[mazeX][mazeY - 1].name === 'Wall') { moveDirections.push('up'); } } else if (moveDirection === 'right') { if (maze.tiles[mazeX + 1][mazeY].name === 'Floor') { moveDirections.push('right'); } if (maze.tiles[mazeX][mazeY + 1].name === 'Floor') { moveDirections.push('up'); } if (maze.tiles[mazeX][mazeY - 1].name === 'Floor') { moveDirections.push('down'); } if (moveDirections.length === 0 && maze.tiles[mazeX + 1][mazeY].name === 'Wall') { moveDirections.push('left'); } } else if (moveDirection === 'left') { if (maze.tiles[mazeX - 1][mazeY].name === 'Floor') { moveDirections.push('left'); } if (maze.tiles[mazeX][mazeY + 1].name === 'Floor') { moveDirections.push('up'); } if (maze.tiles[mazeX][mazeY - 1].name === 'Floor') { moveDirections.push('down'); } if (moveDirections.length === 0 && maze.tiles[mazeX - 1][mazeY].name === 'Wall') { moveDirections.push('right'); } } if (moveDirections.length > 0) { const rand = Math.floor(Math.random() * moveDirections.length) moveDirection = moveDirections[rand]; } } let moveVector = new Vector3(0, 0, 0); const speed = 0.1; if (moveDirection === 'up') { moveVector = new Vector3(0, 0, speed); } else if (moveDirection === 'right') { moveVector = new Vector3(speed, 0, 0); } else if (moveDirection === 'down') { moveVector = new Vector3(0, 0, -speed); } else if (moveDirection === 'left') { moveVector = new Vector3(-speed, 0, 0); } this.moveDirection = moveDirection; this.mesh.moveWithCollisions(moveVector); if (this.game.getState() === State.GAME && this.scene.activeCamera) { this.collider.position.x = this.scene.activeCamera.position.x; this.collider.position.z = this.scene.activeCamera.position.z; this.collider.position.y = 2; if (this.mesh.intersectsMesh(this.collider)) { this.game.lose(this.scene); } } } else { if (this.sound.isPlaying) { this.sound.stop(); } } } getMesh(): Mesh { return this.mesh; } static createFireballs(maze: Area, mazeCellSize: number, shadowGenerator: ShadowGenerator, scene: Scene, game: Game): void { NodeMaterial.ParseFromFileAsync('fireballMaterial', './assets/material/fireballMaterial.json', scene) .then((nodeMaterial) => { let fireBallCount = 0; while (fireBallCount < 5) { const x = Math.floor(maze.width * Math.random()); const y = Math.floor(maze.height * Math.random()); if (maze.tiles[x][y].name === 'Floor') { const fireBall = new FireBall(scene, maze, new Vector3(x * mazeCellSize - 100, 2, y * mazeCellSize - 90), game) shadowGenerator.addShadowCaster(fireBall.getMesh()); fireBall.mesh.material = nodeMaterial; fireBall.mesh.material.shadowDepthWrapper = new ShadowDepthWrapper(nodeMaterial, scene); fireBallCount += 1; } } }); } }
<div class="form-component login-container"> <div class="inner-container"> <div class="form-container"> <h2>Login</h2> <form [formGroup]="loginForm" (submit)="login()"> <div class="credentials"> <div> <mat-form-field appearance="outline"> <mat-label>Username</mat-label> <input matInput formControlName="username" type="text" [(ngModel)]="credentials.username"> </mat-form-field> <div class="error"> <small class="text-danger" *ngIf="loginForm.get('username')?.invalid && loginForm.get('username')?.errors && (loginForm.get('username')?.dirty || loginForm.get('username')?.touched)"> This field is required. </small> </div> </div> <div> <mat-form-field appearance="outline"> <mat-label>Password</mat-label> <input matInput formControlName="password" type="password" [(ngModel)]="credentials.password"> </mat-form-field> <div class="error"> <small class="text-danger" *ngIf="loginForm.get('password')?.invalid && loginForm.get('password')?.errors && (loginForm.get('password')?.dirty || loginForm.get('password')?.touched)"> This field is required. </small> </div> </div> </div> <div class="buttons"> <div class="button-wrapper member-btn"> <button type="submit" mat-raised-button [disabled]="loginForm.invalid">Login</button> </div> <div class="button-wrapper guest-btn"> <button mat-raised-button (click)="login(true)">Login as guest</button> </div> </div> </form> <div class="footer"> <span>Not a member? </span><span class="create-account-link" (click)="createAccount()">Create Account</span> </div> </div> </div> </div>
import { MapBase } from '../map-base'; import { Point } from "../entity/Point"; import { GeoUtil } from "../geo-util"; declare var ol: any; export class MapWrap { /** setFitViewByFeatures */ public static setFitViewByFeatures(data: { map: MapBase, features: Array<any>, padding: [number, number, number, number], }): void { if (data.features == null || data.features.length == 0) { return; } let shapes: Array<any> = []; for (let i = 0; i < data.features.length; i++) { let g = data.features[i].getGeometry(); if (g != null) { shapes.push(g); } } this.setFitViewByShapes({ map: data.map, shapes: shapes, padding: data.padding, }) } /** setFitViewByShapes */ public static setFitViewByShapes(data: { map: MapBase, shapes: Array<any>, padding: [number, number, number, number], }): void { if (data.shapes == null || data.shapes.length == 0) { return; } let points = { minS: new Array<Point>(), maxS: new Array<Point>(), }; for (let i = 0; i < data.shapes.length; i++) { switch (data.shapes[i].constructor) { case ol.geom.LineString: { let shape = data.shapes[i]; let coord = shape.getCoordinates(); let minX = 0, minY = 0, maxX = 0, maxY = 0; for (let n = 0; n < coord.length; n++) { minX = minX ? (minX > coord[n][0] ? coord[n][0] : minX) : coord[n][0]; minY = minY ? (minY > coord[n][1] ? coord[n][1] : minY) : coord[n][1]; maxX = maxX ? (maxX < coord[n][0] ? coord[n][0] : maxX) : coord[n][0]; maxY = maxY ? (maxY < coord[n][1] ? coord[n][1] : maxY) : coord[n][1]; } points.minS.push(new Point(minX, minY)); points.maxS.push(new Point(maxX, maxY)); break; } case ol.geom.Polygon: { let shape = data.shapes[i]; let coords = shape.getCoordinates(); for (let h = 0; h < coords.length; h++) { let coord = coords[h]; let minX = 0, minY = 0, maxX = 0, maxY = 0; for (let n = 0; n < coord.length; n++) { minX = minX ? (minX > coord[n][0] ? coord[n][0] : minX) : coord[n][0]; minY = minY ? (minY > coord[n][1] ? coord[n][1] : minY) : coord[n][1]; maxX = maxX ? (maxX < coord[n][0] ? coord[n][0] : maxX) : coord[n][0]; maxY = maxY ? (maxY < coord[n][1] ? coord[n][1] : maxY) : coord[n][1]; } points.minS.push(new Point(minX, minY)); points.maxS.push(new Point(maxX, maxY)); } break; } case ol.geom.Circle: { let shape = data.shapes[i]; let m_center = shape.getCenter(); let center = GeoUtil.Mercator_To_LngLat(new Point(m_center[0], m_center[1])); let radius = shape.getRadius(); let distance = Math.sqrt(2 * Math.pow(radius, 2)); let bottomLeft = GeoUtil.destinationVincenty(center, 225, distance); let topRight = GeoUtil.destinationVincenty(center, 45, distance); points.minS.push(GeoUtil.LngLat_To_Mercator(bottomLeft)); points.maxS.push(GeoUtil.LngLat_To_Mercator(topRight)); break; } default: break; } } let minX = 0, minY = 0, maxX = 0, maxY = 0; for (let i = 0; i < points.minS.length; i++) { minX = minX ? (minX > points.minS[i].lng ? points.minS[i].lng : minX) : points.minS[i].lng; minY = minY ? (minY > points.minS[i].lat ? points.minS[i].lat : minY) : points.minS[i].lat; } for (let i = 0; i < points.maxS.length; i++) { maxX = maxX ? (maxX < points.maxS[i].lng ? points.maxS[i].lng : maxX) : points.maxS[i].lng; maxY = maxY ? (maxY < points.maxS[i].lat ? points.maxS[i].lat : maxY) : points.maxS[i].lat; } let ext: number[] = [minX, minY, maxX, maxY]; let view = data.map.getOlMap().getView(); let size = data.map.getOlMap().getSize(); if (size != null) { if (size[0] < 100) { size[0] = 100; } if (size[1] < 100) { size[1] = 100; } } view.fit(ext, { nearest: false, padding: data.padding, size: size, }) } /** setFitView */ public static setFitView(data: { map: MapBase, extent: { bottomLeft: Point, topRight: Point }, padding: [number, number, number, number], }): void { let view = data.map.getOlMap().getView(); let m_bottomLeft = GeoUtil.LngLat_To_Mercator(data.extent.bottomLeft); let m_topRight = GeoUtil.LngLat_To_Mercator(data.extent.topRight); let ext: number[] = [m_bottomLeft.lng, m_bottomLeft.lat, m_topRight.lng, m_topRight.lat]; view.fit(ext, { nearest: false, padding: data.padding, }) } /** 地图添加Overlay */ public static addOverlay(map: MapBase, overlay: any): void { map.getOlMap().addOverlay(overlay); } /** 地图添加Overlay(多个) */ public static addOverlays(map: MapBase, overlays: Array<any>): void { for (let i = 0; i < overlays.length; i++) { map.getOlMap().addOverlay(overlays[i]); } } /** 地图移除Overlay */ public static removeOverlay(map: MapBase, overlay: any): void { map.getOlMap().removeOverlay(overlay); } /** 地图移除Overlay(多个) */ public static removeOverlays(map: MapBase, overlays: Array<any>): void { for (let i = 0; i < overlays.length; i++) { map.getOlMap().removeOverlay(overlays[i]); } } /** 地图清空Overlay */ public static removeAllOverlays(map: MapBase): void { let overlays = map.getOlMap().getOverlays().getArray(); this.removeOverlays(map, overlays); } /** 图层添加Feature */ public static addFeature(map: MapBase, name: string, feature: any): void { let source = map.getLayerByName(name).getSource(); if (!source.hasFeature(feature)) { source.addFeature(feature); } } /** 图层添加Feature(多个) */ public static addFeatures(map: MapBase, name: string, features: Array<any>): void { let source = map.getLayerByName(name).getSource(); for (let i = 0; i < features.length; i++) { if (!source.hasFeature(features[i])) { source.addFeature(features[i]); } } } /** 图层移除Feature */ public static removeFeature(map: MapBase, name: string, feature: any): void { let source = map.getLayerByName(name).getSource(); if (source.hasFeature(feature)) { source.removeFeature(feature); } } /** 图层移除Feature(多个) */ public static removeFeatures(map: MapBase, name: string, features: Array<any>): void { let source = map.getLayerByName(name).getSource(); for (let i = 0; i < features.length; i++) { if (source.hasFeature(features[i])) { source.removeFeature(features[i]); } } } /** 图层清空Feature */ public static removeAllFeatures(map: MapBase, name: string): void { let source = map.getLayerByName(name).getSource(); source.clear(); } }
import {BiSolidMoon, BiSolidSun, BiSolidCircle} from 'react-icons/bi'; import {useEffect, useState} from "react"; const DarkModeSwitcher = () => { const [darkMode, setDarkMode] = useState(true); useEffect(() => { const isUsingDarkMode = JSON.parse(localStorage.getItem('darkMode')); if (isUsingDarkMode === null) { localStorage.setItem('darkMode', JSON.stringify(true)); } else { enableDarkMode(isUsingDarkMode); } }, []) const enableDarkMode = (enable) => { setDarkMode(enable); localStorage.setItem('darkMode', JSON.stringify(enable)); const root = window.document.documentElement; if (enable) { root.classList.add('dark'); } else { root.classList.remove('dark'); } } return ( <button onClick={() => {enableDarkMode(!darkMode)}} aria-label="Toggle Dark Mode" className="flex gap-[1rem] p-[0.25rem] rounded-full theme-inverted text-xl md:text-4xl"> <BiSolidCircle className={ `absolute transition-transform duration-500 ${darkMode ? 'translate-x-0' : 'translate-x-[3.25rem]'}` }/> <BiSolidSun/> <BiSolidMoon/> </button> ); } export default DarkModeSwitcher;
{{fbdoc item="title" value="LINE INPUT"}}---- Reads one line of input from the keyboard {{fbdoc item="syntax"}}## **Line Input** [;] [//promptstring// {;|,} ] //stringvariable// ## {{fbdoc item="param"}} ##//promptstring//## prompt to display before waiting for input ##//stringvariable//## variable to receive the line of text {{fbdoc item="desc"}} Reads a line of text from the keyboard and stores it in a string variable. {{fbdoc item="ex"}} {{fbdoc item="filename" value="examples/manual/console/lineinput.bas"}}%%(freebasic) dim x as string line input "Enter a line:", x print "You entered '"; x; "'" %% {{fbdoc item="diff"}} - QBASIC only allowed literal strings for the prompt text. FreeBASIC allows any variable or constant string expression. {{fbdoc item="see"}} - ##[[KeyPgLineinputPp Line Input #]]## - ##[[KeyPgInput Input]]## {{fbdoc item="back" value="CatPgInput|User Input"}}
import { lighten } from 'polished'; import styled from 'styled-components'; import { adaptiveFont } from '@/utils/adaptiveFont'; export const ButtonWrapper = styled.button` width: 100%; padding: 19px 0; background-color: ${(props) => props.theme.bgSecondaryLight100}; border-radius: 76px; color: ${(props) => props.theme.textLight}; text-align: center; font-family: Roboto, sans-serif; font-size: ${adaptiveFont(18, 14)}; font-weight: 700; transition: all 200ms; cursor: pointer; &:not(:disabled):hover { box-shadow: 0 0 8px ${(props) => props.theme.bgSecondaryLight100}; background-color: ${(props) => lighten(0.1, props.theme.bgSecondaryLight100)}; } &:disabled { background-color: ${(props) => props.theme.bgSecondaryLight200}; box-shadow: 0 10px 20px 0 ${(props) => props.theme.shadow}; } @media (max-width: 768px) { padding: 15px 0; } `; export const PrimaryButton = styled(ButtonWrapper)` background-color: ${(props) => props.theme.bgSecondaryLight100}; `; export const SecondaryButton = styled(ButtonWrapper)` background-color: ${(props) => props.theme.bgSecondaryDark400}; color: ${(props) => props.theme.bgPrimary}; `; export const NeutralButton = styled(ButtonWrapper)` background-color: ${(props) => props.theme.bgPrimary}; border: 1px solid ${(props) => props.theme.border400}; color: ${(props) => props.theme.textDark500}; `;
import os import torch from OptiPrompt.code.models import Prober from OptiPrompt.code.utils import evaluate, load_data, batchify, get_relation_meta, load_vocab MAX_NUM_VECTORS = 10 def get_new_token(vid): assert(vid > 0 and vid <= MAX_NUM_VECTORS) return '[V%d]'%(vid) def convert_manual_to_dense(manual_template, model): def assign_embedding(new_token, token): """ assign the embedding of token to new_token """ id_a = model.tokenizer.convert_tokens_to_ids([new_token])[0] id_b = model.tokenizer.convert_tokens_to_ids([token])[0] with torch.no_grad(): model.base_model.embeddings.word_embeddings.weight[id_a] = model.base_model.embeddings.word_embeddings.weight[id_b].detach().clone() new_token_id = 0 template = [] for word in manual_template.split(): if word in ['[X]', '[Y]']: template.append(word) else: tokens = model.tokenizer.tokenize(' ' + word) for token in tokens: new_token_id += 1 template.append(get_new_token(new_token_id)) assign_embedding(get_new_token(new_token_id), token) return ' '.join(template) def prepare_for_dense_prompt(model): new_tokens = [get_new_token(i+1) for i in range(MAX_NUM_VECTORS)] model.tokenizer.add_tokens(new_tokens) model.mlm_model.resize_token_embeddings(len(model.tokenizer)) def init_template(args, model): if args.init_manual_template: relation = get_relation_meta(args) template = convert_manual_to_dense(relation['template'], model) else: template = '[X] ' + ' '.join(['[V%d]'%(i+1) for i in range(args.num_vectors)]) + ' [Y] .' return template def load_optiprompt(model, original_vocab_size, vs): # copy fine-tuned new_tokens to the pre-trained model with torch.no_grad(): model.base_model.embeddings.word_embeddings.weight[original_vocab_size:] = torch.Tensor(vs) class EvaluatePrompt: def __init__(self, args): args.model_name = args.tgt_model args.model_dir = None args.k = 5 args.eval_batch_size = 8 dev_data = os.path.join(args.data_path, args.relation, 'dev.jsonl') test_data = os.path.join(args.data_path, args.relation, 'test.jsonl') self.model = Prober(args) self.original_vocab_size = len(list(self.model.tokenizer.get_vocab())) prepare_for_dense_prompt(self.model) if args.common_vocab is not None: self.vocab_subset = load_vocab(args.common_vocab) self.filter_indices, self.index_list = self.model.init_indices_for_filter_logprobs(self.vocab_subset) else: self.filter_indices = None self.index_list = None template = init_template(args, self.model) self.valid_samples = load_data(dev_data, template, vocab_subset=self.vocab_subset, mask_token=self.model.MASK) self.valid_samples_batches, self.valid_sentences_batches = batchify(self.valid_samples, args.eval_batch_size) self.test_samples = load_data(test_data, template, vocab_subset=self.vocab_subset, mask_token=self.model.MASK) self.test_samples_batches, self.test_sentences_batches = batchify(self.test_samples, args.eval_batch_size) self.args = args def evaluate_valid(self, embeddings): load_optiprompt(self.model, self.original_vocab_size, embeddings) precision, _ = evaluate(self.model, self.valid_samples_batches, self.valid_sentences_batches, self.filter_indices, self.index_list) return precision def evaluate_test(self, embeddings): load_optiprompt(self.model, self.original_vocab_size, embeddings) precision, _ = evaluate(self.model, self.test_samples_batches, self.test_sentences_batches, self.filter_indices, self.index_list) return precision if __name__ == '__main__': EvaluatePrompt().evaluate()
'use client'; import { useState } from 'react'; import { Generator } from '@/components/generator'; import { Card, CardContent } from '@/components/ui/card'; import { Copyable } from '@/components/ui/copyable'; import { Separator } from '@/components/ui/separator'; import { TooltipProvider } from '@/components/ui/tooltip'; import { toast } from '@/components/ui/use-toast'; import { type AnimeGeneratorResult } from '@/generators/anime/result.interface'; import { type BibleGeneratorResult } from '@/generators/bible/result.interface'; import { type ElasticGeneratorResult } from '@/generators/elastic/result.interface'; import { type UuidGeneratorResult } from '@/generators/uuid/result.interface'; import { UuidGenerator } from '@/generators/uuid/uuid.generator'; import { cn } from '@/lib/utils'; interface GeneratorPanelProps { anime: AnimeGeneratorResult; bible: BibleGeneratorResult; elastic: ElasticGeneratorResult; uuid: UuidGeneratorResult; className?: string; } export function GeneratorPanel(props: GeneratorPanelProps) { const [state, setState] = useState(props); const updateState = (newState: Partial<GeneratorPanelProps>) => setState({ ...state, ...newState }); const regenerateRequest = async <R = unknown,>(generator: 'anime' | 'elastic' | 'bible'): Promise<R | null> => { try { const response = await fetch(`/api/generate/${generator}`); return await response.json(); } catch (error) { toast({ title: 'Uh oh! Something went wrong.', description: 'There was a problem with your request.', }); return null; } }; const regenerateAnime = async () => { const result = await regenerateRequest<AnimeGeneratorResult>('anime'); result && updateState({ anime: result }); }; const regenerateBible = async () => { const result = await regenerateRequest<BibleGeneratorResult>('bible'); result && updateState({ bible: result }); }; const regenerateElastic = async () => { const result = await regenerateRequest<ElasticGeneratorResult>('elastic'); result && updateState({ elastic: result }); }; const regenerateUuid = async () => { const result = await new UuidGenerator().generate(); updateState({ uuid: result }); }; return ( <Card className={cn(props.className)}> <CardContent className="p-4 space-y-4"> <TooltipProvider> <Generator title="anime" onRegenerate={regenerateAnime}> <Copyable disabled type="text" value={state.anime.firstName} /> <Copyable disabled type="text" value={state.anime.lastName} /> <Copyable disabled type="text" value={state.anime.fullName} /> </Generator> <Separator></Separator> <Generator title="bible" onRegenerate={regenerateBible}> <Copyable disabled type="text" value={state.bible.name} /> </Generator> <Separator></Separator> <Generator title="neutral" onRegenerate={regenerateElastic}> <Copyable disabled type="text" value={state.elastic.name} /> </Generator> <Separator></Separator> <Generator title="uuid" onRegenerate={regenerateUuid}> <Copyable disabled type="text" value={state.uuid.v4} /> <Copyable disabled type="text" value={state.uuid.short} /> </Generator> </TooltipProvider> </CardContent> </Card> ); }
import 'package:energise/constants/app_colors.dart'; import 'package:energise/widgets/ui/my_text/my_text.dart'; import 'package:flutter/material.dart'; class MyButton extends StatelessWidget { final String text; final Function onClick; final double? width; final Color? color; const MyButton({super.key, required this.text, required this.onClick, this.color, this.width}); @override Widget build(BuildContext context) { return InkWell( onTap: () { onClick(); }, child: Container( width: width, height: 70, decoration: BoxDecoration( borderRadius: BorderRadius.circular(18), color: color ?? AppColors.green, ), alignment: Alignment.center, child: MyText( text: text, textAlign: TextAlign.center, textColor: Colors.white, fontSize: 24, textVariant: TextVariants.bold, ), ), ); } }
import React, { useState } from 'react'; import { Dimensions, Pressable, StyleSheet, Text, View } from 'react-native'; import { Icon, Input, Button } from '@rneui/themed'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import { useNavigation } from '@react-navigation/native'; import axios from 'axios'; const height = Dimensions.get('screen').height; const width = Dimensions.get('screen').width; export default function Register() { const navigation = useNavigation(); const [email, setEmail] = useState(''); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [emailError, setEmailError] = useState(''); const [passwordError, setPasswordError] = useState(''); // const handleRegister = () => { // // Basic validation // if (!email || !username || !password || !confirmPassword) { // alert('Please fill in all the fields'); // return; // } // // You can add more specific validation here if needed // // If all validations pass, navigate to the next screen // navigation.navigate('Home'); // }; const validateInputs = () => { let isValid = true; // Email validation if (!email || !email.includes('@')) { setEmailError('Invalid email address'); isValid = false; } else { setEmailError(''); } // Password validation if (!password || password.length < 6) { setPasswordError('Password must be at least 6 characters'); isValid = false; } else { setPasswordError(''); } return isValid; }; const handleRegister = async () => { if (validateInputs()) { try { const response = await axios.post('http://192.168.157.210:5000/api/auth/register', { email, username, password, }); navigation.navigate('Login'); setEmail(''); setUsername(''); setPassword(''); setConfirmPassword(''); console.log('User Registered'); } catch (error) { console.error('Registration failed:', error); // Handle specific error cases if needed } } }; return ( <View style={styles.container}> <Text style={styles.text}>D CHAT</Text> <Input placeholder="Email" leftIcon={<Icon name="email" type="material" size={24} />} onChangeText={(text) => setEmail(text)} value={email} /> <Input placeholder="Username" leftIcon={<FontAwesome name="user" size={24} />} onChangeText={(text) => setUsername(text)} value={username} /> <Input placeholder="Password" secureTextEntry leftIcon={<FontAwesome name="lock" size={24} />} onChangeText={(text) => setPassword(text)} value={password} /> <Input placeholder="Confirm Password" secureTextEntry leftIcon={<FontAwesome name="lock" size={24} />} onChangeText={(text) => setConfirmPassword(text)} value={confirmPassword} /> <Pressable style={styles.btn} onPress={handleRegister}> <Text style={styles.btntext}>Register</Text> </Pressable> <Button title="Already have an account? Sign In" type="clear" onPress={() => { setUsername('') setEmail('') setPassword('') setConfirmPassword('') navigation.navigate('Login') }} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'white', }, text: { fontSize: 35, color: '#305F96', fontWeight: 'bold', }, btn: { height: 70, width: width / 2, backgroundColor: '#305F96', justifyContent: 'center', alignItems: 'center', borderRadius: 22, marginVertical: 10, }, btntext: { fontSize: 18, fontWeight: '700', color: 'white', }, });
import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_synthizer/flutter_synthizer.dart'; import 'screens/intro_screen.dart'; void main() { runApp(const MyApp()); } /// The top level app object. class MyApp extends StatelessWidget { /// Create an instance. const MyApp({super.key}); // This widget is the root of your application. @override Widget build(final BuildContext context) => ProviderScope( child: SynthizerScope( child: MaterialApp( title: 'Flutter Audio Games Example', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const IntroScreen(), ), ), ); }
# Django imports from django import forms from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ # Third party imports from ckeditor.widgets import CKEditorWidget # Local imports from .models import PostModel, CommentsModel class PostCreationForm(forms.ModelForm): class Meta: model = PostModel fields = ('category', 'title', 'body') widgets = { 'title': forms.TextInput( attrs={ 'class': 'form-control', 'label': 'Title must be unique from other posts that had been posted to the website', } ), 'body': CKEditorWidget( attrs={ 'class': 'form-control', } ), 'category': forms.Select( attrs={ 'class': 'form-select', 'style': 'width: 200px;' } ) } class AddCommentForm(forms.ModelForm): class Meta: model = CommentsModel fields = ('body',) widgets = { 'body': CKEditorWidget( attrs={ 'class': 'form-control', 'label': 'Comment' } ) }
package models; import com.fasterxml.jackson.annotation.JsonProperty; public class AnimeMangaIdBase extends AnimeMangaBase { private String[] english; @JsonProperty("english") public String[] getEnglish() { return english; } public void setEnglish(String[] english) { this.english = english; } private String[] japanese; @JsonProperty("japanese") public String[] getJapanese() { return japanese; } public void setJapanese(String[] japanese) { this.japanese = japanese; } private String[] synonyms; @JsonProperty("synonyms") public String[] getSynonyms() { return synonyms; } public void setSynonyms(String[] synonyms) { this.synonyms = synonyms; } private String licenseNameRu; @JsonProperty("license_name_ru") public String getLicenseNameRu() { return licenseNameRu; } public void setLicenseNameRu(String licenseNameRu) { this.licenseNameRu = licenseNameRu; } private String description; @JsonProperty("description") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } private String descriptionHtml; @JsonProperty("description_html") public String getDescriptionHtml() { return descriptionHtml; } public void setDescriptionHtml(String descriptionHtml) { this.descriptionHtml = descriptionHtml; } private String descriptionSource; @JsonProperty("description_source") public String getDescriptionSource() { return descriptionSource; } public void setDescriptionSource(String descriptionSource) { this.descriptionSource = descriptionSource; } private String franchise; @JsonProperty("franchise") public String getFranchise() { return franchise; } public void setFranchise(String franchise) { this.franchise = franchise; } private boolean favoured; @JsonProperty("favoured") public boolean isFavoured() { return favoured; } public void setFavoured(boolean favoured) { this.favoured = favoured; } private boolean anons; @JsonProperty("anons") public boolean isAnons() { return anons; } public void setAnons(boolean anons) { this.anons = anons; } private boolean ongoing; @JsonProperty("ongoing") public boolean isOngoing() { return ongoing; } public void setOngoing(boolean ongoing) { this.ongoing = ongoing; } private Genre[] genres; @JsonProperty("genres") public Genre[] getGenres() { return genres; } public void setGenres(Genre[] genres) { this.genres = genres; } }
import { Navigate, useNavigate, useParams } from 'react-router-dom'; import { getHeroById } from '../helpers'; import { useMemo } from 'react'; export const Hero = () => { // const params = useParams(); // hook creado por react-router que sirve para obtener los parámetros // console.log(params); const { id } = useParams(); // hook creado por react-router que sirve para obtener los parámetros const navegate = useNavigate(); // const hero = getHeroById(id); // no es eficiente const hero = useMemo( () => getHeroById(id), [id] ); // se usa el memo para que no se renderiza cada vez que un componente cambie. Solo cambiará cuando la dependencia, el id, cambie. Esto es mucho más eficiente // Tarea: hacer que el btn GoBack funcione ( no conseguida, no sabía que tenía que llamar al useNavegate) const onGoBack = () => { // return <Navigate to="/marvel"/> // como lo estaba haciendo navegate(-1); // esto lleva al usuario a la pag anterior, incluida sacarlo de la app }; if( !hero ) { // si no exsite un hero se redirecciona return <Navigate to="/marvel"/> } return ( <> <div className='row mt-5 animate__animated animate__fadeInDown'> <div className="col-4"> <img src={`/assets/heroes/${id}.jpg`} alt={ hero.superhero } className='img-thumbnail ' /> </div> <div className="col-8"> <h3>{hero.superhero} </h3> <ul className='list-group list-group-flush'> <li className='list-group-item'><b>Alter ego:</b> { hero.alter_ego } </li> <li className='list-group-item'><b>Publiser: </b> { hero.publisher } </li> <li className='list-group-item'><b>First Apparence: </b> { hero.first_appearance } </li> </ul> <h5 className='mt-3'>Characters </h5> <p>{hero.characters}</p> <hr /> <button className='btn btn-outline-secondary' onClick={ onGoBack } > Go back</button> </div> </div> </> ) }
// // SulfurIsotope.swift // // // Created by Evan Anderson on 5/13/23. // import Foundation import SwiftUnits // https://en.wikipedia.org/wiki/Isotopes_of_sulfur public enum SulfurIsotope : String, ChemicalElementIsotope { case sulfur_27 case sulfur_28 case sulfur_29 case sulfur_30 case sulfur_31 case sulfur_32 case sulfur_33 case sulfur_34 case sulfur_35 case sulfur_36 case sulfur_37 case sulfur_38 case sulfur_39 case sulfur_40 case sulfur_41 case sulfur_42 case sulfur_43 case sulfur_43_isomer_1 case sulfur_44 case sulfur_44_isomer_1 case sulfur_45 case sulfur_46 case sulfur_47 case sulfur_48 case sulfur_49 public var element : ChemicalElement { return ChemicalElement.sulfur } public var load_details : ChemicalElementDetails { switch self { case .sulfur_27: return ChemicalElementDetails(self, neutron_count: 11, standard_atomic_weight: "27.01828", decay_mode: AtomicDecayType.beta_plus, half_life: TimeUnit(prefix: UnitPrefix.milli, type: TimeUnitType.second, value: "15.5")) case .sulfur_28: return ChemicalElementDetails(self, neutron_count: 12, standard_atomic_weight: "28.00437", decay_mode: AtomicDecayType.beta_plus, half_life: TimeUnit(prefix: UnitPrefix.milli, type: TimeUnitType.second, value: "125")) case .sulfur_29: return ChemicalElementDetails(self, neutron_count: 13, standard_atomic_weight: "28.99661", decay_mode: AtomicDecayType.beta_plus, half_life: TimeUnit(prefix: UnitPrefix.milli, type: TimeUnitType.second, value: "188")) case .sulfur_30: return ChemicalElementDetails(self, neutron_count: 14, standard_atomic_weight: "29.98490677", decay_mode: AtomicDecayType.beta_plus, half_life: TimeUnit(type: TimeUnitType.second, value: "1.1759")) case .sulfur_31: return ChemicalElementDetails(self, neutron_count: 15, standard_atomic_weight: "30.97955701", decay_mode: AtomicDecayType.beta_plus, half_life: TimeUnit(type: TimeUnitType.second, value: "2.5534")) case .sulfur_32: return ChemicalElementDetails(self, neutron_count: 16, standard_atomic_weight: "31.9720711744") case .sulfur_33: return ChemicalElementDetails(self, neutron_count: 17, standard_atomic_weight: "32.9714589099") case .sulfur_34: return ChemicalElementDetails(self, neutron_count: 18, standard_atomic_weight: "33.96786701") case .sulfur_35: return ChemicalElementDetails(self, neutron_count: 19, standard_atomic_weight: "34.96903232", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(type: TimeUnitType.day, value: "87.37")) case .sulfur_36: return ChemicalElementDetails(self, neutron_count: 20, standard_atomic_weight: "35.96708070") case .sulfur_37: return ChemicalElementDetails(self, neutron_count: 21, standard_atomic_weight: "36.97112551", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(type: TimeUnitType.minute, value: "5.05")) case .sulfur_38: return ChemicalElementDetails(self, neutron_count: 22, standard_atomic_weight: "37.971163", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(type: TimeUnitType.minute, value: "170.3")) case .sulfur_39: return ChemicalElementDetails(self, neutron_count: 23, standard_atomic_weight: "38.97513", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(type: TimeUnitType.second, value: "11.5")) case .sulfur_40: return ChemicalElementDetails(self, neutron_count: 24, standard_atomic_weight: "39.975483", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(type: TimeUnitType.second, value: "8.8")) case .sulfur_41: return ChemicalElementDetails(self, neutron_count: 25, standard_atomic_weight: "40.979593", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(type: TimeUnitType.second, value: "1.99")) case .sulfur_42: return ChemicalElementDetails(self, neutron_count: 26, standard_atomic_weight: "41.981065", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(type: TimeUnitType.second, value: "1.016")) case .sulfur_43: return ChemicalElementDetails(self, neutron_count: 27, standard_atomic_weight: "42.986908", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(prefix: UnitPrefix.milli, type: TimeUnitType.second, value: "265")) case .sulfur_43_isomer_1: return ChemicalElementDetails(self, neutron_count: 27, standard_atomic_weight: "42.986908", decay_mode: AtomicDecayType.isomeric_transition, half_life: TimeUnit(prefix: UnitPrefix.nano, type: TimeUnitType.second, value: "415.0")) case .sulfur_44: return ChemicalElementDetails(self, neutron_count: 28, standard_atomic_weight: "43.990119", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(prefix: UnitPrefix.milli, type: TimeUnitType.second, value: "100")) case .sulfur_44_isomer_1: return ChemicalElementDetails(self, neutron_count: 28, standard_atomic_weight: "43.990119", decay_mode: AtomicDecayType.isomeric_transition, half_life: TimeUnit(prefix: UnitPrefix.micro, type: TimeUnitType.second, value: "2.619")) case .sulfur_45: return ChemicalElementDetails(self, neutron_count: 29, standard_atomic_weight: "44.99572", decay_mode: AtomicDecayType.beta_minus_neutron_emission(amount: 1), half_life: TimeUnit(prefix: UnitPrefix.milli, type: TimeUnitType.second, value: "68")) case .sulfur_46: return ChemicalElementDetails(self, neutron_count: 30, standard_atomic_weight: "46.00037", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(prefix: UnitPrefix.milli, type: TimeUnitType.second, value: "50")) case .sulfur_47: return ChemicalElementDetails(self, neutron_count: 31, standard_atomic_weight: "47.00791", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(prefix: UnitPrefix.nano, type: TimeUnitType.second, value: "201")) case .sulfur_48: return ChemicalElementDetails(self, neutron_count: 32, standard_atomic_weight: "48.01370", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: TimeUnit(prefix: UnitPrefix.nano, type: TimeUnitType.second, value: "201")) case .sulfur_49: return ChemicalElementDetails(self, neutron_count: 33, standard_atomic_weight: "49.02264", decay_mode: AtomicDecayType.beta_minus(amount: 1), half_life: nil) // TODO: fix } } }
use super::VariableExpression; use crate::{Compiler, CompilerError}; use compiler::Variable; #[derive(Debug, Clone, PartialEq)] pub struct BinaryExpression { pub left: VariableExpression, pub right: VariableExpression, pub exp_type: BinaryExpType, } #[derive(Clone, Debug, PartialEq, Eq)] pub enum BinaryExpType { // Logical And, Or, Eq, Ne, Gt, Ge, Lt, Le, // Arithmetic Add, Sub, Div, Mul, } impl BinaryExpression { pub fn binary_call< 'ctx, F: FnOnce( &Compiler<'ctx>, &Variable<'ctx>, &Variable<'ctx>, ) -> Result<Variable<'ctx>, CompilerError>, >( self, compiler: &mut Compiler<'ctx>, call: F, ) -> Result<Variable<'ctx>, CompilerError> { let var1 = self.left.compile_get_variable(compiler)?; let var2 = self.right.compile_get_variable(compiler)?; let ret = call(compiler, &var1, &var2)?; if var1.is_tmp() { var1.deallocate(compiler); } if var2.is_tmp() { var2.deallocate(compiler); } Ok(ret) } #[allow(clippy::too_many_lines)] pub fn compile<'ctx>( self, compiler: &mut Compiler<'ctx>, ) -> Result<Variable<'ctx>, CompilerError> { match self.exp_type { // Logical BinaryExpType::And => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .logical_and() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Or => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .logical_or() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Eq => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .logical_eq() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Ne => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .logical_ne() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Gt => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .logical_gt() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Ge => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .logical_ge() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Lt => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .logical_lt() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Le => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .logical_le() .call(compiler, var1, var2)) })?; Ok(ret) } // Arithmetic BinaryExpType::Add => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .arithmetic_addition() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Sub => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .arithmetic_substraction() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Mul => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .arithmetic_multiplication() .call(compiler, var1, var2)) })?; Ok(ret) } BinaryExpType::Div => { let ret = self.binary_call(compiler, |compiler, var1, var2| { Ok(compiler .predefined_functions() .arithmetic_division() .call(compiler, var1, var2)) })?; Ok(ret) } } } }
import { SaveOutlined, UploadOutlined } from "@mui/icons-material" import { Button, Grid, TextField, Typography, IconButton } from "@mui/material" import { ImageGallery } from "../components" import { useDispatch, useSelector } from "react-redux" import { useForm } from "../../hooks/useForm" import { useEffect, useMemo } from "react" import { setActiveNote } from "../../store/slices/journal/journalSlice" import { startDeleteNote, startSaveNote, startUploadingFiles } from "../../store/slices/journal/thunks" import Swal from "sweetalert2"; import { useRef } from "react" import { current } from "@reduxjs/toolkit" export const NoteView = () => { const dispatch = useDispatch(); const { active: note, messageSaved, isSaving } = useSelector(state => state.journal); const { title, body, date, onInputChange, formState } = useForm(note); const dateString = useMemo(() => { const newDate = new Date(date); return newDate.toUTCString(); }, [date]); const fileInputref = useRef() useEffect(() => { dispatch(setActiveNote(formState)); }, [formState, dispatch]); useEffect(() => { if (messageSaved.length > 0) { Swal.fire('Nota actualizada', messageSaved, 'success'); } }, [messageSaved]); const onSaveNote = () => { dispatch(startSaveNote()); } const onFileInputChange = ({ target }) => { if (target.files === 0) return; dispatch(startUploadingFiles(target.files)); } const onDelete = () => { dispatch(startDeleteNote()); } return ( <Grid container className="animate__animated animate__fadeIn animate__faster" direction={"row"} justifyContent={'space-between'} alignItems={'center'} sx={{ mb: 1 }}> <Typography fontSize={39} fontWeight={"light"}>{dateString}</Typography> <Grid item> <input type="file" multiple onChange={onFileInputChange} style={{ display: 'none' }} ref={fileInputref} /> <IconButton color="primary" disabled={isSaving} onClick={() => fileInputref.current.click()} > <UploadOutlined /> </IconButton> <Button color="primary" sx={{ padding: 2 }} disabled={isSaving} onClick={onSaveNote} > <SaveOutlined sx={{ fontSize: 30, mr: 1 }} /> Guardar </Button> </Grid> <Grid container > <TextField type="text" variant="filled" fullWidth placeholder="Ingrese un titulo" sx={{ border: 'none', mb: 1 }} value={title} name="title" onChange={onInputChange} /> <TextField type="text" variant="filled" fullWidth multiline placeholder="Que sucedio el dia de hoy" minRows={5} value={body} name="body" onChange={onInputChange} /> </Grid > <Grid container justifyContent={'end'} > <Button onClick={onDelete} color={"error"} sx={{ mt: 2 }} > Borrar </Button> </Grid> <ImageGallery images={note.imageUrls} /> </Grid> ) }
<!DOCTYPE html> <%@page import="java.net.URLDecoder"%> <%@ page pageEncoding="UTF-8" %> <%@ page contentType="text/html; charset=UTF-8" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <html lang="zh-cn"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width; initial-scale=0.8; user-scalable=0;" /> <title>统一登录认证系统</title> <link href="styles/css/font-awesome.css" type="text/css" rel="stylesheet" /> <link href="styles/css/css.css" type="text/css" rel="stylesheet" /> <script type="application/javascript" src="styles/js/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="styles/js/jquery.flexslider-min.js"></script> <script type="application/javascript" src="styles/js/index.js"></script> <script type="application/javascript" src="styles/js/md5.js"></script> <script language="javascript" type="text/javascript"> function encryptPwd(){ if (event.keyCode == 13){ dologin(); } }//end of encryPwd function dologin() { var inputPassword = document.getElementById("password").value; var onceCode = "MYXAPP_SALT_KEY"; var passwordMd5 = hex_md5(onceCode + hex_md5(inputPassword)); document.getElementById("password").value = passwordMd5; document.getElementById("username").value = trim(document .getElementById("username").value); }//end of dologin </script> </head> <script> $(function(){ <% String isframe = request.getParameter("isframe"); if(isframe!=null&&isframe!=""){ %> //只保留登录控件信息 $("body").html($("#miniLoginDiv").html()); <%} %> }); </script> <body> <div class="login"> <div class="login_nra"> <div class="login_tp"><img src="styles/images/login_tp.png"></div> <div id="miniLoginDiv" class="login_nr"> <div class="login_title"> <p>员工登录</p> </div> <form:form method="post" id="fm2" commandName="${commandName}" htmlEscape="true"> <div class="login_tr"> <ul> <span><form:errors path="*" id="msg" cssClass="errors" element="div" htmlEscape="false" /></span> <li><i class="icon-user"></i><form:input cssClass="required shuru" cssErrorClass="error" id="username" size="25" tabindex="2" accesskey="${userNameAccessKey}" path="username" autocomplete="off" htmlEscape="true" placeholder="请输入登录账号"/></li> <span><spring:message code="screen.welcome.label.netid.accesskey" var="userNameAccessKey" /></span> <li><i class="icon-lock"></i><form:password cssClass="required shuru" cssErrorClass="error" id="password" size="25" tabindex="3" path="password" accesskey="${passwordAccessKey}" htmlEscape="true" autocomplete="off" onkeydown="encryptPwd()"/></li> <span><spring:message code="screen.welcome.label.password.accesskey" var="passwordAccessKey" /></span> <li ><input id="rememberMe" name="rememberMe" tabindex="4" class="cbox" type="checkbox">下次自动登录</li> <li><input class="login_btn" name="submit" accesskey="l" value="登录" tabindex="5" type="submit" onclick="javascript:dologin();" /></li> </ul> <input type="hidden" name="lt" value="${loginTicket}" /> <input type="hidden" name="execution" value="${flowExecutionKey}" /> <input type="hidden" name="_eventId" value="submit" /> </div> </form:form> </div> </div> </div> </div> </body> </html>
import { Color4 } from '@dcl/sdk/math' import { adjustNonSetWidthsEvenDist, Table,TableCell, TableRow } from './tableTypes' import ReactEcs, { UiEntity, Position, UiBackgroundProps, Button } from '@dcl/sdk/react-ecs' import { getFakeDataSample, randomizeData } from './fakeData' import { CreateTableHeader, generateRows } from './uiTableComponents' import { UiBackground } from '@dcl/sdk/ecs' import { generateHudLeaderboardData } from './uiHudLeaderboard' const MODAL_WIDTH = 480 const MODAL_HEIGHT = 376 const TABLE_HEADER_FONT_SIZE = 27 const TABLE_CELL_FONT_SIZE = 23 const TABLE_ROW_HEIGHT = 40 const TABLE_ROW_MARGIN:Partial<Position> ={ top: '5px', left: '0px' } const TABLE_HEADER_MARGIN:Partial<Position> ={ top: '-50px', left: '0px', bottom: '10px' } const TABLE_ROW_UI_BG:UiBackgroundProps = { texture: {src: "images/rowLineImage.png"}, textureMode: 'stretch'} const TABLE_HEADER_UI_BG:UiBackgroundProps|undefined = undefined const TABLE_FONT_COLOR = Color4.White() const TABLE_HEADER_FONT_COLOR= Color4.White() const TABLE_WIDTH = 400 const TABLE_RANK_WIDTH = '20%' const TABLE_ICON_WIDTH = '25px' const header = new TableRow({ uiBackground:TABLE_HEADER_UI_BG, margin: TABLE_HEADER_MARGIN }); header.cells.push( new TableCell('text','Snowball Battle',{fontSize:TABLE_HEADER_FONT_SIZE,fontColor:TABLE_HEADER_FONT_COLOR})) adjustNonSetWidthsEvenDist(header.cells) const noDataRow = new TableRow({ height:TABLE_ROW_HEIGHT, margin:TABLE_ROW_MARGIN, uiBackground:TABLE_ROW_UI_BG, fontColor:Color4.Gray() }); noDataRow.cells.push( new TableCell('text','No Data To Display',{fontSize:TABLE_HEADER_FONT_SIZE,width:"100%",fontColor:Color4.Gray()})) const leaderboardTable = new Table( 'modal-leaderboard',header ) leaderboardTable.noDataRow = noDataRow export function generateModalLeaderboardData(){ leaderboardTable.rows = [] const randomizeFakeLeadboardData = getFakeDataSample() console.log("generateSampleData", randomizeFakeLeadboardData) for (let i = 0; i < randomizeFakeLeadboardData.length; i++) { const itm = randomizeFakeLeadboardData[i] const fontColor = itm.connStatus === 'connected' ? TABLE_FONT_COLOR : Color4.White() const row = new TableRow({ height:TABLE_ROW_HEIGHT, margin:TABLE_ROW_MARGIN, uiBackground:TABLE_ROW_UI_BG, fontColor:fontColor }) row.cells.push( new TableCell('text',itm.rank.toFixed(0),{fontSize:TABLE_CELL_FONT_SIZE,width:TABLE_RANK_WIDTH,fontColor:fontColor})) row.cells.push( new TableCell('image',itm.teamId === "blue" ? "images/krampus.png" : "images/santa.png", {innerWidth:TABLE_ICON_WIDTH, innerHeight:TABLE_ICON_WIDTH, width:TABLE_RANK_WIDTH} )) if(itm.userId != null && itm.userId != undefined && itm.userId != ""){ row.cells.push( new TableCell('avatar',itm.userId,{innerWidth:TABLE_ICON_WIDTH, innerHeight:TABLE_ICON_WIDTH, width:TABLE_RANK_WIDTH} )) } else { row.cells.push( new TableCell('image',"images/anonymous-player.png",{innerWidth:TABLE_ICON_WIDTH, innerHeight:TABLE_ICON_WIDTH, width:TABLE_RANK_WIDTH} )) } row.cells.push( new TableCell('text',itm.name + (itm.connStatus === 'connected' ? '' : '(*)'),{textAlign:'middle-left',fontSize:TABLE_CELL_FONT_SIZE,fontColor:fontColor})) row.cells.push( new TableCell('text',itm.score.toString(),{fontSize:TABLE_CELL_FONT_SIZE,fontColor:fontColor})) adjustNonSetWidthsEvenDist(row.cells) leaderboardTable.rows.push(row) } } generateModalLeaderboardData() export function toggleModalLeaderboard(val?:boolean):void{ console.log("clicked toggleModal",val,leaderboardTable.visible) if(val !== undefined){ leaderboardTable.visible = val }else{ leaderboardTable.visible = !leaderboardTable.visible } } export function createModalLeaderboardTable(){ const table = leaderboardTable return <UiEntity uiTransform={{ display:table.visible ? 'flex':'none', positionType: 'absolute' , width: MODAL_WIDTH, height: MODAL_HEIGHT, position: { left: '40%' } , flexDirection:'row', flexWrap:'wrap', alignSelf:'center' }} > <UiEntity //parent / modal decoration uiTransform={{ width: MODAL_WIDTH, height: MODAL_HEIGHT, display: 'flex', //position: { left: '50%' } , flexDirection:'column', //flexWrap:'wrap', //alignSelf:'center' }} uiBackground={{texture: {src: "images/leadboard.png"}, textureMode: 'stretch' }} > <UiEntity //start table uiTransform={{ width: TABLE_WIDTH, height: '90%', display: 'flex', position: { top: 75, left: 45 } , flexDirection:'column', flexWrap:'wrap' }} > <CreateTableHeader data={table.header} rowNum={0}/> {generateRows(table)} </UiEntity> <UiEntity //start table uiTransform={{ width: '100%', height: '50px', display: 'flex', flexDirection:'row', flexWrap:'wrap', alignSelf:'center', justifyContent:'center', padding: { bottom:'30px' }, }} > <Button variant='secondary' value='Shuffle' onMouseDown={()=>{ randomizeData(); generateModalLeaderboardData(); generateHudLeaderboardData() }} uiTransform={{ width: '100px', height: '40px', display: 'flex', alignSelf:'center', margin: { right:'20px' }, }} font='sans-serif' fontSize={20} ></Button> <Button variant='primary' value='Close' onMouseDown={()=>{toggleModalLeaderboard()}} uiTransform={{ width: '100px', height: '40px', display: 'flex', alignSelf:'center' }} font='sans-serif' fontSize={20} ></Button> </UiEntity> </UiEntity> </UiEntity> }
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { HomeComponent } from './home/home.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { MatToolbarModule } from '@angular/material/toolbar'; import { MatButtonModule } from '@angular/material/button'; import { MatSidenavModule} from '@angular/material/sidenav'; import { MatListModule } from '@angular/material/list'; import { AboutMeComponent } from './about-me/about-me.component'; import { ProjectsComponent } from './projects/projects.component'; import { ClassesComponent } from './classes/classes.component'; import {MatCardModule} from '@angular/material/card'; import { ProjectWidget } from './widgets/project.widget'; import { WorkExperienceComponent } from './work-experience/work-experience.component'; import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent, HomeComponent, AboutMeComponent, ProjectsComponent, ClassesComponent, ProjectWidget, WorkExperienceComponent ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatToolbarModule, MatButtonModule, MatSidenavModule, MatListModule, MatCardModule, HttpClientModule ], bootstrap: [AppComponent] }) export class AppModule { }
def shopping_cart(*args): max_products = {"Soup": 3, "Pizza": 4, "Dessert": 2} meals_and_products = {"Soup": [], "Pizza": [], "Dessert": []} for item in args: if item == "Stop": break name = item[0] product = item[1] if product not in meals_and_products[name] and len(meals_and_products[name]) < max_products[name]: meals_and_products[name].append(product) sorted_meals = {k: v for k, v in sorted(meals_and_products.items(), key=lambda x: (-len(x[1]), x[0]))} if not sorted_meals["Soup"] and not sorted_meals["Pizza"] and not sorted_meals["Dessert"]: return "No products in the cart!" result = "" for meal, products in sorted_meals.items(): if len(products) > 0: result += f"{meal}:\n" for prod in sorted(products): result += f" - {prod}\n" else: result += f"{meal}:\n" return result print(shopping_cart( ('Pizza', 'ham'), ('Soup', 'carrots'), ('Pizza', 'cheese'), ('Pizza', 'flour'), ('Dessert', 'milk'), ('Pizza', 'mushrooms'), ('Pizza', 'tomatoes'), 'Stop', )) print(shopping_cart( ('Pizza', 'ham'), ('Dessert', 'milk'), ('Pizza', 'ham'), 'Stop', )) print(shopping_cart( 'Stop', ('Pizza', 'ham'), ('Pizza', 'mushrooms'), ))
#!/usr/bin/env python3 """ Module for example how to scrape book info from Amazon web store https://www.amazon.com/Automate-Boring-Stuff-Python-Programming/dp/1593275994/ """ __author__ = "Petri Weckström" __version__ = "0.1.0" __license__ = "MIT" import bs4 import requests import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') # logging.disable(logging.CRITICAL) # This disable all logs as CRITICAL level is highest def main(): """ Main entry point of the app """ def getSamsungPrice(productUrl): logging.debug('Start of get Samsung price function') # some web page needs header information # headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', } # res = requests.get(Url, headers=headers) logging.debug('Open product URL') res = requests.get(productUrl) res.raise_for_status() # raise exception if request.get failed soup = bs4.BeautifulSoup(res.text, 'html.parser') # returns beautifulsoup object logging.debug('Get price element') priceElem = soup.select('#app > div > div.main > div > div > section > aside.product__main-view > div.main-view__info > div:nth-child(1) > div.price-tag > div > div.price-tag-prices > div > span') logging.debug('End of get Samsung price function') return priceElem[0].text.strip() # strip is used to trim white spaces and tabs out of the string price = getSamsungPrice('https://www.verkkokauppa.com/fi/product/36712/kjsdn/Samsung-C34J791-34-naytto?list=OZZQMqhQhX0hHyOqNQv6b55hZEhRwSEhUIZzZHEYsNxzF29') print('Todays price for the Samsung is: ' + price + 'e') if __name__ == "__main__": """ This is executed when run from the command line """ main()
<script setup> import CompanyLogo from "../components/CompanyLogo.vue"; import { ref, onMounted } from "vue"; import { changePassword, getCurrentAvatarId, getCurrentUsername, logout, isFirstLogin, } from "../services/user_service"; import router from "../router"; import InvalidInputMessage from "../components/InvalidInputMessage.vue"; import PasswordInput from "../components/PasswordInput.vue"; import CustomButton from "../components/CustomButton.vue"; const oldPasswordText = ref(""); const newPasswordText = ref(""); const confirmNewPassword = ref(""); const showErrorMessage = ref(false); const errorMessage = ref(""); const currentAvatarId = ref(-1); const passwordLength = ref(0); const containsEightCharacters = ref(false); const containsNumber = ref(false); const containsUppercase = ref(false); const containsSpecialCharacter = ref(false); const firstLogin = ref(false); currentAvatarId.value = getCurrentAvatarId(); const slideImages = [ "src/assets/img/avatars/avatar1.svg", "src/assets/img/avatars/avatar2.svg", "src/assets/img/avatars/avatar3.svg", "src/assets/img/avatars/avatar4.svg", "src/assets/img/avatars/avatar5.svg", "src/assets/img/avatars/avatar6.svg", "src/assets/img/avatars/avatar7.svg", ]; onMounted(() => { firstLogin.value = localStorage.getItem("isFirstLogin"); }); function submit() { if ( oldPasswordText.value && newPasswordText.value && confirmNewPassword.value ) { if (newPasswordText.value === confirmNewPassword.value) { let passwordFormatOK = true; const upperCaseRegex = /[A-Z]/; const specialCharacterRegex = /[#$^&*_@]/; if (newPasswordText.value.length < 8) { errorMessage.value = "The new password must contain at least 8 characters"; showErrorMessage.value = true; passwordFormatOK = false; } if (!upperCaseRegex.test(newPasswordText.value) && passwordFormatOK) { errorMessage.value = "The new password must contain at least one uppercase character"; showErrorMessage.value = true; passwordFormatOK = false; } if ( !specialCharacterRegex.test(newPasswordText.value) && passwordFormatOK ) { errorMessage.value = "The new password must contain at least one special character(#$^&*_@)"; showErrorMessage.value = true; passwordFormatOK = false; } if (passwordFormatOK) { changePassword({ username: getCurrentUsername(), oldPassword: oldPasswordText.value, newPassword: newPasswordText.value, }) .then((res) => { logout(); router.push("/login"); }) .catch((error) => { errorMessage.value = "Old password is incorrect"; showErrorMessage.value = true; }); } } else { errorMessage.value = "Passwords are not equal"; showErrorMessage.value = true; } } else { errorMessage.value = "All fields must be completed"; showErrorMessage.value = true; } } function handleOldPasswordTextChanged(password) { oldPasswordText.value = password; } function handleNewPasswordTextChanged(password) { newPasswordText.value = password; } function handleConfirmPasswordTextChanged(password) { confirmNewPassword.value = password; } function checkPassword() { passwordLength.value = newPasswordText.value.length; const format = /[!@#$%^&*()_+\-=\[\]{};':"\\,.<>\/?]/; containsEightCharacters.value = passwordLength.value > 7 ? true : false; containsNumber.value = /\d/.test(newPasswordText.value); containsUppercase.value = /[A-Z]/.test(newPasswordText.value); containsSpecialCharacter.value = format.test(newPasswordText.value); } </script> <template> <CompanyLogo /> <div class="wrapper"> <div class="container"> <h1 id="title"> <div class="big-text" id="name">AIMS</div> <div class="big-text">Change Password</div> </h1> <div id="profile-img"> <img :src="slideImages[currentAvatarId]" alt="avatar not found" style="height: auto; width: 8vw" /> </div> <InvalidInputMessage :message="errorMessage" :class="{ 'error-message-visible': showErrorMessage }" /> <div class="verification-container"> <ul> <li :class="{ is_valid: containsEightCharacters }">8 Characters</li> <li :class="{ is_valid: containsNumber }">Contains numbers</li> <li :class="{ is_valid: containsUppercase }">Contains Uppercase</li> <li :class="{ is_valid: containsSpecialCharacter }"> Contains Special Character </li> </ul> </div> <div> <PasswordInput :label="'Current password'" :value="oldPasswordText" @password-changed="handleOldPasswordTextChanged" @keyup="checkPassword" /> </div> <div> <PasswordInput :label="'New password'" :value="newPasswordText" @password-changed="handleNewPasswordTextChanged" @input="checkPassword" /> </div> <div> <PasswordInput :label="'Confirm password'" :value="confirmNewPassword" @password-changed="handleConfirmPasswordTextChanged" @enter-password="submit" /> </div> <div id="controls-container"> <button id="cancel" :disabled="!firstLogin" @click="router.push('/my')"> Cancel </button> <CustomButton id="submit" @click="submit">Submit</CustomButton> </div> </div> </div> </template> <style scoped> .container { min-width: 20vw; display: flex; flex-direction: column; justify-content: center; align-items: center; gap: 2vh; position: relative; margin-top: 10vh; background-color: #e9e9e9; padding: 20px; border-radius: 10px; } .wrapper { display: flex; align-items: center; justify-content: center; } .error-message-visible { opacity: 1; } .material-symbols-outlined { font-size: 10vh; } #cancel { display: flex; align-items: center; text-decoration: underline; background-color: transparent; border: none; } #cancel:hover { cursor: pointer; } input { padding: 5px; border: none; } #controls-container { display: flex; justify-content: space-between; gap: 20px; } #title { display: flex; flex-direction: column; align-items: center; } #name { color: var(--selected-color); } #submit { font-size: 15px; font-weight: 500; } .big-text { font-size: 30px; } #company-logo { position: relative; top: 20px; left: 5vw; } #user-icon { font-size: 70px; } a { color: black; } .verification-container { width: 10vw; margin-bottom: 10px; background-color: #e9e9e9; border-radius: 15px; padding: 10px; box-shadow: 2px 2px 5px 5px var(--sidebar-color); } ul { display: flex; justify-content: center; flex-direction: column; align-items: flex-start; margin: 0; padding: 0; list-style: none; color: red; } li:before { content: "X"; padding-right: 10px; } .is_valid { color: green; list-style: none; } ul .is_valid:before { content: "✓"; padding-right: 10px; } </style>
#!/usr/bin/python3 """ this module defines a name-printing function """ def say_my_name(first_name, last_name=""): """Print a name. Args: first_name (str): The first name to be printed. last_name (str): The last name to be printed. Raises: TypeError: If either of first_name or last_name are not strings. Returns: No return """ if type(first_name) is not str: raise TypeError("first_name must be a string") if type(last_name) is not str: raise TypeError("last_name must be a string") print("My name is", first_name, last_name)
#pragma once #include "MetaType.h" #include "ChainableTask.h" namespace api { /// @brief The result of an attempt to create an api command class enum class Result { Failed, Success, NotEnoughtData, UnknownCommand }; template <class Tools> class ApiCommandWithTools; /// @brief Basic class for api command's class class ApiCommandBase { public: virtual ~ApiCommandBase() {} /// @brief API command entry point /// @return Returns the coroutine for executing the command virtual task::CoroTask<String> ExecutionCommand() = 0; /// @brief Setting tools for heirs who need them /// @tparam Tools for working with api command /// @param Tools for working with api command template <class Tools> void SetTools(Tools &&tools) { if (ApiCommandWithTools<Tools> *p = dynamic_cast<ApiCommandWithTools<Tools> *>(this)) { p->SetTools(std::move(tools)); } } }; /// @brief Basic tools's struct /// @tparam Parser for raw data template <class Parser> struct DefaultTools { using ParserType = Parser; Parser mParser; }; /// @brief Basic class for api command's class with tools /// @tparam Tools for working with api command template <class Tools> class ApiCommandWithTools : public ApiCommandBase { public: virtual ~ApiCommandWithTools() {} inline void SetTools(Tools &&tools) { mTools = std::move(tools); } protected: Tools mTools; }; DECLARE_SHARED_PTR(ApiCommandBase) /// @brief API command parsing result struct ApiParseResult { Result code; ApiCommandBaseSharedPtr api_command; }; }
package com.main.ra.service.Impl; import com.main.ra.exception.BaseException; import com.main.ra.model.Enum.UserStatus; import com.main.ra.model.dto.UserDetailAdapter; import com.main.ra.model.dto.UserDto; import com.main.ra.model.dto.request.NewPasswordRequest; import com.main.ra.model.dto.request.SignUpRequest; import com.main.ra.model.dto.request.PageableRequest; import com.main.ra.model.dto.request.UserRequest; import com.main.ra.model.entity.AddressEntity; import com.main.ra.model.entity.RoleEntity; import com.main.ra.model.entity.UserEntity; import com.main.ra.repository.AddressRepository; import com.main.ra.repository.UserRepository; import com.main.ra.service.UserService; import com.main.ra.util.FileServiceImpl; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.domain.Page; import org.springframework.http.HttpStatus; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDate; @Service @Transactional public class UserServiceImpl implements UserService, UserDetailsService { @Value("${upload.User.location}") private String uploadFileLocation; @Autowired private UserRepository userRepository; @Autowired private UserRoleServiceImpl userRoleService; @Autowired private RoleServiceImpl roleService; @Autowired private MapperUtilServiceImpl mapper; @Autowired private final PasswordEncoder encoder; @Autowired private FileServiceImpl fileService; public UserServiceImpl(PasswordEncoder encoder) { this.encoder = encoder; } @Override public UserDetailAdapter loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity user = userRepository.findUserEntitiesByUserName(username).orElse(null); if (user != null){ UserDetailAdapter userAdapter = new UserDetailAdapter(); userAdapter.setUser(user); return userAdapter; } throw new UsernameNotFoundException("exception.UserNotFound"); } public UserEntity addUser(SignUpRequest req){ UserEntity existedUser = userRepository.findUserEntitiesByUserName(req.getUserName()).orElse(null); UserEntity phoneExistedUser = userRepository.findUserEntitiesByPhone(req.getPhone()).orElse(null); if (existedUser == null && phoneExistedUser == null){ UserEntity user = mapper.convertDTOToEntity(req, UserEntity.class); user.setPassword(encoder.encode(req.getPassword())); UserEntity userDB = userRepository.save(user); req.getRoles().forEach(r -> { RoleEntity role = roleService.findByRoleName(r); if (role != null){ userRoleService.addUserRole(userDB.getId(),role.getId()); } }); return userDB; } else if (existedUser != null){ throw new BaseException("exception.UserExisted",HttpStatus.BAD_REQUEST); } else { throw new BaseException("exception.PhoneExisted",HttpStatus.BAD_REQUEST); } } public UserEntity update(Long userId, UserRequest request){ UserEntity user = userRepository.findById(userId).orElse(null); if (user != null){ UserEntity updatedUser= mapper.updateToEntity(request,user); if (request.getFile().getSize() > 0){ String fileLocation = uploadFileLocation.concat("/userId_"+userId+"/"+ LocalDate.now()); String fileName = fileService.save(fileLocation,request.getFile()); updatedUser.setAvatar(fileName); } return userRepository.save(updatedUser); }else { throw new BaseException("exception.UserNotFound", HttpStatus.NOT_FOUND); } } public UserStatus switchStatus(Long userId){ UserEntity user = userRepository.findById(userId).orElse(null); if (user != null){ user.setStatus(!user.getStatus()); user = userRepository.save(user); if (user.getStatus()){ return UserStatus.ACTIVE; } else { return UserStatus.BLOCK; } } else { throw new BaseException("exception.UserNotFound",HttpStatus.NOT_FOUND); } } public boolean changePassword(Long userId, NewPasswordRequest request){ UserEntity user = userRepository.findById(userId).orElse(null); if (user != null){ if (encoder.matches(request.getOldPassword(), user.getPassword())){ user.setPassword(encoder.encode(request.getNewPassword())); userRepository.save(user); return true; }else { throw new BaseException("exception.PasswordIdNotSame",HttpStatus.FORBIDDEN); } }else { throw new BaseException("exception.UserNotFound",HttpStatus.NOT_FOUND); } } public Page<UserDto> findAllByUserName(String key, PageableRequest pageableRequest){ try{ String searchKey = "%".concat(key.concat("%")).replace(" ",""); return userRepository.findAllByUserNameLikeIgnoreCase(searchKey, pageableRequest) .map(u -> mapper.convertEntityToDTO(u, UserDto.class)); }catch (Exception e){ throw new BaseException("exception.pageable.PageNotFound",HttpStatus.FORBIDDEN); } } public UserEntity findByUsernameAndPassword(String userName, String password){ return userRepository.findUserEntitiesByUserNameAndPassword(userName,password).orElse(null); } public UserEntity findById(Long userId){ return userRepository.findById(userId).orElse(null); } public Page<UserDto> findAll(PageableRequest pageableRequest){ try{ return userRepository.findAll(pageableRequest).map(u -> mapper.convertEntityToDTO(u, UserDto.class)); }catch (Exception e){ throw new BaseException("exception.pageable.PageNotFound",HttpStatus.FORBIDDEN); } } }
<template> <div class="list"> <div class="item" v-for="(item,index) in problemStarList" :key="item.id" > <div class="icon-container"> <up-circle-outlined :class="['icon' ,{'active': index === 0}]" @click="upProblem(item,index)"/> <down-circle-outlined :class="['icon' ,{'active': index === problemStarList.length - 1}]" @click="downProblem(item,index)"/> </div> <span class="title">{{ item.problem.title }}</span> <div class="manage"> <span class="title" @click="editStarProblem(item)">编辑</span> <span class="title" @click="deleteStarProblem(item)">删除</span> </div> </div> </div> </template> <script lang="ts"> import {defineComponent, inject} from 'vue'; import {reqCancelStarProblem} from "@/api/problem/api"; import {message} from "ant-design-vue"; import {DownCircleOutlined, UpCircleOutlined} from "@ant-design/icons-vue"; export default defineComponent({ name: 'ModuleManageList', components: { UpCircleOutlined, DownCircleOutlined }, setup() { let problemStarList = inject("problemStarList") as any; let currentProblem = inject("currentProblem") as any; let isEdit = inject("isEdit") as any; const getStarProblemList = inject("getStarProblemList") as any; /** * @description: 上调 */ const upProblem = (item: any, index: number) => { if (index === 0) return; let temp = problemStarList.value[index]; problemStarList.value[index] = problemStarList.value[index - 1]; problemStarList.value[index - 1] = temp; }; /** * @description: 下调 */ const downProblem = (item: any, index: number) => { if (index === problemStarList.value.length) return; let temp = problemStarList.value[index]; problemStarList.value[index] = problemStarList.value[index + 1]; problemStarList.value[index + 1] = temp; }; /** * @description: 将调整更新至后端(改功能尚未实现) */ const deleteStarProblem = async (item: any) => { try { await reqCancelStarProblem(item.id); getStarProblemList(); message.success('删除成功!'); } catch { message.error('删除失败,请重试!'); } }; /** * @description: 重新编辑收藏问题 * @param item */ const editStarProblem = (item: any) => { if (item) { currentProblem.value = item; isEdit.value = true; } else { message.error('编辑不存在的问题,请刷新重试!'); } }; return { problemStarList, upProblem, downProblem, deleteStarProblem, editStarProblem, } } }) </script> <style scoped lang="scss"> .list { height: 420px; -webkit-border-radius: 2px; border-radius: 2px; border: 1px solid #e2e6ed; overflow-y: auto; .item { width: 100%; padding: 0 16px; border-bottom: 1px solid #e2e6ed; display: flex; height: 42px; align-items: center; .icon-container { width: 84px; .icon { color: #e2e6ed; font-size: 17px; margin-right: 10px; } :hover { color: #3398f0; } .active { opacity: 0; cursor: default; } } .title { width: 588px; overflow: hidden; white-space: nowrap; word-break: keep-all; -o-text-overflow: ellipsis; text-overflow: ellipsis; } .manage { width: 84px; .title { color: #1488ed; margin-right: 10px; cursor: pointer; } } } } </style>
// ignore_for_file: unnecessary_null_comparison import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:seller/globals/styles.dart'; import 'package:seller/providers/product_provider.dart'; import 'package:seller/screens/product_screen.dart'; import 'package:seller/services/firebase_services.dart'; import 'package:seller/widgets/category_list.dart'; class EditViewProduct extends StatefulWidget { final String productId; const EditViewProduct({super.key, required this.productId}); @override State<EditViewProduct> createState() => _EditViewProductState(); } class _EditViewProductState extends State<EditViewProduct> { final FirebaseServices _services = FirebaseServices(); final _formKey = GlobalKey<FormState>(); final ProductProvider _provider = ProductProvider(); final List<String> _collection = [ 'Featured Products', 'Best Selling', 'Recently Added' ]; String? dropdownValue; final _productName = TextEditingController(); final _unit = TextEditingController(); final _price = TextEditingController(); final _comparedPrice = TextEditingController(); final _description = TextEditingController(); final _stockQuantity = TextEditingController(); final _lowStockQuantity = TextEditingController(); final _categoryController = TextEditingController(); late DocumentSnapshot? doc; double discount = 0; late String image = ''; File? _image; bool _isLoading = true; bool _editing = true; @override void initState() { getProductDetails(); super.initState(); } Future<void> getProductDetails() async { await _services.products.doc(widget.productId).get().then((document) { if (document.exists) { setState(() { doc = document; _productName.text = document['productName']; _unit.text = document['unit']; _price.text = document['price'].toString(); _comparedPrice.text = document['comparedPrice'].toString(); _description.text = document['description'].toString(); _categoryController.text = document['category'].toString(); dropdownValue = document['collection'].toString(); _stockQuantity.text = document['stockQuantity'].toString(); _lowStockQuantity.text = document['lowStockQuantity'].toString(); image = document['productImage']; _isLoading = false; // Set loading to false when data is fetched try { // Parsing _price.text to double double price = double.parse(_price.text); print("Parsed price: $price (Type: ${price.runtimeType})"); // Validating and parsing _comparedPrice.text to double double? comparedPrice = double.tryParse(_comparedPrice.text); if (comparedPrice == null) { throw FormatException( "Invalid comparedPrice value: ${_comparedPrice.text}"); } print( "Parsed comparedPrice: $comparedPrice (Type: ${comparedPrice.runtimeType})"); // Handling case where original price and current price are equal if (price == comparedPrice) { discount = 0; // No discount if original price and current price are equal print("Prices are equal. Discount set to 0."); } else { // Calculating the amount saved double amountSaved = comparedPrice - price; print("Amount saved: $amountSaved"); // Calculating discount percentage if (comparedPrice != 0) { discount = (amountSaved / comparedPrice) * 100; print("Discount percentage: $discount%"); } else { discount = 0; print("Compared price is 0. Discount set to 0."); } } } catch (e) { print("Error parsing price or compared price: $e"); // Handle the error gracefully, perhaps by setting discount to 0 or showing an error message to the user discount = 0; } }); } }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: [ TextButton( onPressed: () { setState(() { _editing = false; }); }, child: Padding( padding: const EdgeInsets.only(right: 15.0), child: Text( 'Edit', style: TextStyle(color: GlobalStyles.green, fontSize: 16), ), ), ) ], ), bottomSheet: SizedBox( height: 60, child: Row( children: [ Expanded( child: InkWell( onTap: () { Navigator.pop(context); }, child: Container( color: Colors.red, child: const Center( child: Text( 'Cancel', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold), ), ), ), ), ), Expanded( child: AbsorbPointer( absorbing: _editing, child: InkWell( onTap: () { if (_formKey.currentState!.validate()) { if (_image != null) { _provider .uploadProductImage(_image!.path, _productName.text) .then((url) { if (url != null) { _provider.updateProductDeatils( context: context, productName: _productName.text, unit: _unit.text, price: double.parse(_price.text), comparedPrice: double.parse(_comparedPrice.text), description: _description.text, category: _categoryController.text, collection: dropdownValue, stockQuantity: int.parse(_stockQuantity.text), lowStockQuantity: int.parse(_lowStockQuantity.text), productId: widget.productId, image: image, ); _provider.showAlertDialog( context, 'Save Product', 'Product Details saved Successfully', ); } }); } else { _provider .updateProductDeatils( context: context, productName: _productName.text, unit: _unit.text, price: double.parse(_price.text), comparedPrice: double.parse(_comparedPrice.text), description: _description.text, category: _categoryController.text, collection: dropdownValue, stockQuantity: int.parse(_stockQuantity.text), lowStockQuantity: int.parse(_lowStockQuantity.text), productId: widget.productId, image: image, ) .then((_) { Navigator.pushNamed(context, ProductScreen.id); }); print('Image is not Changed'); _provider.showAlertDialog( context, 'Save Product', 'Product Details saved Successfully', ); } } }, child: Container( color: GlobalStyles.green, child: const Center( child: Text( 'Save', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold), ), ), ), ), ), ), ], ), ), body: _isLoading ? const Center(child: CircularProgressIndicator()) : doc != null ? _buildForm() : const Center(child: Text('Error: Product not found')), ); } Widget _buildForm() { return Form( key: _formKey, child: ListView( children: [ AbsorbPointer( absorbing: _editing, child: Column( children: [ SizedBox( width: GlobalStyles.screenWidth(context) - 20, height: GlobalStyles.screenHeight(context) * 0.8, child: SingleChildScrollView( child: Column( children: [ Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ const Text( 'Product Name: ', style: TextStyle(fontSize: 14), ), Expanded( child: TextFormField( controller: _productName, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold), decoration: const InputDecoration( contentPadding: EdgeInsets.only(left: 10, right: 10), border: InputBorder.none, ), ), ), ], ), Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ const Text( 'Unit: ', style: TextStyle(fontSize: 14), ), Expanded( child: TextFormField( controller: _unit, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold), decoration: const InputDecoration( contentPadding: EdgeInsets.only(left: 10, right: 10), border: InputBorder.none, ), ), ), ], ), Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ const Text( 'Price: ', style: TextStyle(fontSize: 14), ), Expanded( child: TextFormField( controller: _price, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold), decoration: const InputDecoration( prefixText: '₱ ', contentPadding: EdgeInsets.only(left: 10, right: 10), border: InputBorder.none, ), ), ), Container( decoration: const BoxDecoration(color: Colors.red), padding: const EdgeInsets.symmetric( horizontal: 10.0, vertical: 5.0), child: Text( '${discount.toStringAsFixed(0)} % OFF', style: const TextStyle(color: Colors.white), ), ), ], ), Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ const Text( 'Compared Price: ', style: TextStyle(fontSize: 14), ), Expanded( child: TextFormField( controller: _comparedPrice, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold), decoration: const InputDecoration( prefixText: '₱ ', contentPadding: EdgeInsets.only(left: 10, right: 10), border: InputBorder.none, ), ), ), ], ), Padding( padding: const EdgeInsets.all(8.0), child: InkWell( onTap: () { _provider.getProductImage().then((image) { setState(() { _image = image; }); }); }, child: _image != null ? Image.file( _image!, height: 300, ) : Image.network( image, height: 300, ), ), ), Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ const Text( 'About this Product: ', style: TextStyle( fontSize: 14, fontWeight: FontWeight.bold), ), Expanded( child: TextFormField( maxLines: null, keyboardType: TextInputType.multiline, controller: _description, style: const TextStyle( fontSize: 14, ), decoration: const InputDecoration( contentPadding: EdgeInsets.only(left: 10, right: 10), border: InputBorder.none, ), ), ), ], ), const SizedBox( height: 10, ), Row( children: [ const Text( 'Category: ', style: TextStyle(fontSize: 14), ), const SizedBox( width: 10, ), Expanded( child: GestureDetector( onTap: () { showDialog( context: context, builder: (BuildContext context) { return const CategoryList(); }, ).then((value) { setState(() { _categoryController.text = value; }); }); }, child: AbsorbPointer( absorbing: true, // Prevents user input on the text field child: TextFormField( controller: _categoryController, validator: (value) { if (value!.isEmpty) { return 'Select Product category'; } return null; }, decoration: InputDecoration( enabledBorder: const UnderlineInputBorder( borderSide: BorderSide(color: Colors.grey), ), suffixIcon: Visibility( visible: _editing ? false : true, child: IconButton( onPressed: () {}, // Empty onPressed to keep icon enabled icon: Icon( Icons.edit_outlined, color: GlobalStyles.green, ), ), ), ), ), ), ), ), ], ), Container( child: Row( children: [ const Text( 'Collection :', style: TextStyle( fontSize: 14, ), ), const SizedBox( width: 20, ), DropdownButton<String>( padding: const EdgeInsets.symmetric(vertical: 5), hint: const Padding( padding: EdgeInsets.symmetric( vertical: 10.0, horizontal: 20.0), child: Text( 'Select Collection', style: TextStyle(color: Colors.grey), ), ), value: dropdownValue, icon: const Icon(Icons.arrow_drop_down), onChanged: (String? value) { setState(() { dropdownValue = value; }); }, items: _collection.map((String value) { return DropdownMenuItem<String>( value: value, child: Text(value), ); }).toList(), ), ], ), ), Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ const Text( 'Stock Quantity: ', style: TextStyle(fontSize: 14), ), Expanded( child: TextFormField( controller: _stockQuantity, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold), decoration: const InputDecoration( contentPadding: EdgeInsets.only(left: 10, right: 10), border: InputBorder.none, ), ), ), ], ), Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [ const Text( 'Low Stock Quantity: ', style: TextStyle(fontSize: 14), ), Expanded( child: TextFormField( controller: _lowStockQuantity, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.bold), decoration: const InputDecoration( contentPadding: EdgeInsets.only(left: 10, right: 10), border: InputBorder.none, ), ), ), ], ), const SizedBox( height: 100, ) ], ), ), ), ], ), ), ], ), ); } }
package databaseproject; import java.util.concurrent.ExecutionException; import javax.swing.JOptionPane; import javax.swing.SwingWorker; //This class will extend the SwingWorker thread, which will allow //The action to be performed in a new thread to avoid performance issues //With the java swing class class AdminDeleteUserSwingWorker extends SwingWorker<Boolean, Void> { // Create two instance variables which will take the user to delete along // With the administratorfunctions instance being passed into it private String userToDelete; private AdministratorFunctions administratorFunctions; // Specific constructor will get the userToDelte and the administratorFunctions AdminDeleteUserSwingWorker(String userToDelete, AdministratorFunctions administratorFunctions) { this.userToDelete = userToDelete; this.administratorFunctions = administratorFunctions; } @Override protected Boolean doInBackground() throws Exception { // Perform the delete operation here return this.administratorFunctions.deleteUser(this.userToDelete); } @Override protected void done() { try { boolean success = get(); if (success) { JOptionPane.showMessageDialog(null, "User deleted successfully.", "Delete Confirmation", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Error deleting user.", "Error", JOptionPane.ERROR_MESSAGE); } } catch (InterruptedException | ExecutionException e) { JOptionPane.showMessageDialog(null, "Error deleting user.", "Error", JOptionPane.ERROR_MESSAGE); } } }
--- title: "How to deploy your next idea on Buildndeploy" date: 2023-07-11T13:03:44+05:30 draft: false image: "img/buildndeployBanner.png" tags: ["Deployment"] categories: ["Devops"] author: "Aryan Choudhary" authorDes: "Frontend Developer at Nurdsoft" authorImage: "img/aryan_choudhary.png" --- ## Introduction Deploying a Backend/Fronted app can be a daunting task, especially if you're not familiar with the process. There are a lot of different factors to consider, such as the choice of technology stack, the hosting provider, and the deployment methodology. There are a number of different SaaS products available that can help you deploy your backend and frontend. Some of the most popular options include: -Heroku -Netlify -AWS Elastic Beanstalk -Google App Engine If you're looking for a way to simplify the deployment process, then you should consider using [Buildndeploy](https://buildndeploy.co/), for rest of the blog we will be using short form BnD for [Buildndeploy](https://buildndeploy.co/). It is a Saas application that takes care of hosting/auto-deploying your application with the ease of just ```git push``` command so that you can focus on more important logics of your application rather then getting confused in the vast world of devops. ## Lets deploy 🚀 To get started we first need an application that we can deploy if you already have one you can simply use that, assuming that you are new to all this I am going to create a new React application and deploy that to [BnD](https://buildndeploy.co/). So there are two ways to do that, since [BnD](https://buildndeploy.co/) require some custom configured docker files either we can use build and deploy platform to create a github repo for us or we can create one by ourself and deploy that to [BnD](https://buildndeploy.co/) using github. Lets Explore with [BnD](https://buildndeploy.co/) first. ### Method 1 👾 Head on to [BnD](https://buildndeploy.co/) and your dashboard should look something like this: ![Alt text](img/homepageBnd.png "buildndeploy homepage") Now you have to select ```New Project``` button and select ```New Project``` option, you will be given two fields, enter the Name you would like in first field and select the framework whose boilerplate you want to generate. ( P.S. If you didn't find the framework you are looking for you can head to ```Method 2``` right away, since I am using Reactjs in this demo they already have support for that. ) ![Alt text](img/bndOptionsAutoGenCode.png "Autogen Repo") Along with Reactjs they have boilerplate support for Angular.js, Next.js, Golang and Node.js apps ( On time of writing this blog ). Don't worry your language will be here soon ![Alt text](https://media.giphy.com/media/zVnS1ngPv2me2ijImJ/giphy.gif "gif") Once you have successfully completed the process you will notice that in your github you have a repository with the same name that you gave to you app, on top of that your repo gets auto deployed on [BnD](https://buildndeploy.co/). Now you can clone your repo locally make some changes and push, voila !!!! just like that your code is auto deployed to the cloud. ![Alt text](img/noCloud.jpeg "No cloud") Your project's home page on [BnD](https://buildndeploy.co/) will look something like this depending on what framework you choose. ![Alt text](img/deploymentBnd.png "buildndeploy homepage") ### Method 2 🧑🏻‍💻 Head on to your teminal and create a new React application with the following command: ```bash $ npx create-react-app my-app ``` after it has finished its execution you will see this message refering that a new project has been initialized with name ```my-app```: ```bash $ Success! Created my-app at /Users/Username/my-app Inside that directory, you can run several commands: npm start Starts the development server. npm run build Bundles the app into static files for production. npm test Starts the test runner. npm run eject Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can’t go back! We suggest that you begin by typing: cd my-app npm start ``` Now the next step is you initialize a git repository in it so that you can import that into [BnD](https://buildndeploy.co/) and after that every time we push we get a fresh new build. Run the following command: ```bash $ cd my-app && git init ``` You can do desired changes to the application and then push it to the github, we are also going to add 2 more files to our frontend and that will help the platform to deploy our project. You can copy and paste the following files directly to root directory of the project which in my case is “my-app”: * nginx.conf: This is the default file that will take care of nginx configurations of your project. ```conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; #include /etc/nginx/conf.d/*.conf; server { listen 80; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } } } ``` * Dockerfile: this file will dockerize your application, it's inclusion is required as [BnD](https://buildndeploy.co/) uses it to deploy your application. ```Dockerfile FROM node WORKDIR /src COPY . ./ RUN npm install -f && npm run build FROM nginx:stable-alpine COPY --from=0 /src/dist /usr/share/nginx/html COPY nginx.conf /etc/nginx/nginx.conf EXPOSE 80 CMD ["nginx", "-g", "daemon off;"] ``` now we will commit and push the changes and head on to the [BnD](https://buildndeploy.co/) platform. After you have Signup on the platform you will see a page like this, I already happen to have a project deployed but if you are new user yours will look empty ( just like my brain sometimes 🥲 ) : ![Alt text](img/homepageBnd.png "buildndeploy homepage") click on ```New Project``` button and you will be presented with two options either you can “Create a New App” or you can “Use an Existing App”. Since we already had deployed our app on github we will choose ```Import Repository``` option and it will present us with a screen where we can choose which Repo to deploy : ![Alt text](img/deployBnd.png "buildndeploy homepage") from here we will search and choose our repo that we just pushed to, and it will take us to the part to configure our application: ![Alt text](img/projectConfigure.png "buildndeploy homepage") here you will have option to choose - Set you projcet name and choose its core language ( required for build commands ) - Set your build configurations, since we already have our docker file ready we can go ahead without editing any of these options - Set the port you want to expose your application to - Add environment variables that you might be using in your project. we have a simple fronted UI so, we don't need to add any of that as well - Choose custom domain, if you own any ( We can only add one custom domain at this time, it might change in the future ). Hit ```Save``` button at the top and it will start deployment and you will see a page like this one below: ![Alt text](img/deploymentBnd.png "buildndeploy homepage") once the ```running``` state changes to ```complete``` you can click and visit the marvelous 🥺 app that you just created by clicking the URL under ```Deployment```. ## Conclusion Coding is all about using the right tools that fits your need and this might be exactly what you are looking for to deploy your backend and fronted. Adios ✌🏻
<?php namespace Drupal\gutenberg\Controller; use Drupal\block_content\BlockContentInterface; use Drupal\block_content\Entity\BlockContent; use Drupal\Component\Serialization\Json; use Drupal\taxonomy\Entity\Term; use Drupal\Core\Access\AccessResult; use Drupal\Core\Controller\ControllerBase; use Drupal\Core\Session\AccountInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Drupal\Component\Utility\Html; /** * Returns responses for our blocks routes. */ class ReusableBlocksController extends ControllerBase { const HEADERS = [ 'Allow' => 'GET, POST, PUT, PATCH, DELETE', 'Access-Control-Allow-Methods' => 'OPTIONS, GET, POST, PUT, PATCH, DELETE', 'Access-Control-Allow-Credentials' => 'true', 'Access-Control-Allow-Headers' => 'Authorization, Content-Type', ]; /** * Returns JSON representing the loaded block/pattern categories. * * @param \Symfony\Component\HttpFoundation\Request $request * The request. * @param \Drupal\taxonomy\Entity\Term $category * The category taxonomy term. * * @return \Symfony\Component\HttpFoundation\JsonResponse * The JSON response. */ public function categoryLoad(Request $request, $category = NULL) { /* * TODO this should probably be paginated and lazy loaded in case a site * has hundreds of reusable blocks. */ $ids = \Drupal::entityQuery('taxonomy_term') ->condition('vid', 'pattern_categories') ->accessCheck(TRUE) ->execute(); $terms = Term::loadMultiple($ids); $result = []; /** @var \Drupal\block_content\BlockContentInterface[] $blocks */ foreach ($terms as $key => $term) { $result[] = [ 'id' => (int) $term->id(), 'slug' => Html::getClass($term->getName()), 'name' => $term->getName(), 'description' => $term->getDescription(), 'taxonomy' => 'wp_pattern_category', ]; } return new JsonResponse($result, Response::HTTP_OK, $this::HEADERS); } /** * Create pattern category taxonomy term. * * @param \Symfony\Component\HttpFoundation\Request $request * The request. * * @return \Symfony\Component\HttpFoundation\JsonResponse * The JSON response. * * @throws \Drupal\Core\Entity\EntityStorageException */ public function categoryCreate(Request $request) { $data = Json::decode($request->getContent()); // If term with same name already exists return 400 with data. $ids = \Drupal::entityQuery('taxonomy_term') ->condition('vid', 'pattern_categories') ->condition('name', $data['name']) ->accessCheck(TRUE) ->execute(); if (!empty($ids)) { return new JsonResponse([ 'code' => 'term_exists', 'message' => 'A term with the name provided already exists in this vocabulary.', 'data' => [ 'status' => 400, 'term_id' => (int) reset($ids), ], 'additional_data' => [(int) reset($ids), (int) reset($ids)], ], Response::HTTP_BAD_REQUEST, $this::HEADERS); } $term = Term::create([ 'name' => $data['name'], 'vid' => 'pattern_categories', ]); $term->save(); $headers = [ 'Allow' => 'GET, POST', 'Access-Control-Allow-Methods' => 'OPTIONS, GET, POST, PUT, PATCH, DELETE', ]; $response_code = Response::HTTP_CREATED; $result = [ 'id' => (int) $term->id(), 'count' => 0, 'slug' => Html::getClass($term->getName()), 'name' => $term->getName(), 'description' => $term->getDescription(), 'taxonomy' => 'wp_pattern_category', ]; return new JsonResponse($result, $response_code, $headers); } /** * Returns JSON representing the loaded blocks. * * @param \Symfony\Component\HttpFoundation\Request $request * The request. * @param string $block_id * The reusable block id. * * @return \Symfony\Component\HttpFoundation\JsonResponse * The JSON response. */ public function load(Request $request, $block_id = NULL) { if ($block_id && $block_id > 0) { $block = $this->loadBlockOrThrow($block_id); return new JsonResponse( $this->getBlockAttributes($block) + [ // Kind of a hack but accepted by Gutenberg ;) 'headers' => $this::HEADERS, ], Response::HTTP_OK, $this::HEADERS ); } /* * TODO this should probably be paginated and lazy loaded in case a site * has hundreds of reusable blocks. */ $ids = \Drupal::entityQuery('block_content') ->condition('type', 'reusable_block') ->accessCheck(TRUE) ->execute(); $blocks = BlockContent::loadMultiple($ids); $result = []; /** @var \Drupal\block_content\BlockContentInterface[] $blocks */ foreach ($blocks as $key => $block) { $result[] = $this->getBlockAttributes($block); } return new JsonResponse($result, Response::HTTP_OK, $this::HEADERS); } /** * Saves reusable block. * * @param \Symfony\Component\HttpFoundation\Request $request * The request. * @param string $block_id * The reusable block id. * * @return \Symfony\Component\HttpFoundation\JsonResponse * The JSON response. * * @throws \Drupal\Core\Entity\EntityStorageException */ public function save(Request $request, $block_id = NULL) { $updating_block = $block_id && $block_id > 0; $data = Json::decode($request->getContent()); if ($updating_block) { $block = $this->loadBlockOrThrow($block_id); if (!is_null($data['title'])) { $block->set('info', $data['title']); } if (!is_null($data['content'])) { $block->set('body', $data['content']); } } else { $block = BlockContent::create([ 'info' => $data['title'], 'type' => 'reusable_block', 'body' => [ 'value' => $data['content'], 'format' => 'plain_text', ], 'field_pattern_sync_status' => [ 'value' => $data['meta']['wp_pattern_sync_status'] == '' ? 'synced' : 'unsynced', ], 'field_pattern_category' => array_map(function ($tid) { return ['target_id' => $tid]; }, $data['wp_pattern_category']), ]); } $block->save(); $headers = [ 'Allow' => 'GET, POST', 'Access-Control-Allow-Methods' => 'OPTIONS, GET, POST, PUT, PATCH, DELETE', ]; if ($updating_block) { $response_code = Response::HTTP_OK; } else { $response_code = Response::HTTP_CREATED; } return new JsonResponse($this->getBlockAttributes($block), $response_code, $headers); } /** * Delete reusable block. * * @param \Symfony\Component\HttpFoundation\Request $request * The request. * @param string $block_id * The reusable block id. * * @return \Symfony\Component\HttpFoundation\JsonResponse * The JSON response. * * @throws \Drupal\Core\Entity\EntityStorageException */ public function delete(Request $request, $block_id = NULL) { $block = $this->loadBlockOrThrow($block_id); $block->delete(); return new JsonResponse([ 'id' => (int) $block_id, ]); } /** * Controller routes access callback. * * @param \Drupal\Core\Session\AccountInterface $account * Current user. * @param string $block_id * Block id from route parameter. * * @return \Drupal\Core\Access\AccessResult * Allowed access result if all conditions are met. */ public function access(AccountInterface $account, $block_id) { $block = BlockContent::load($block_id); // Check if the user has the proper permissions. $access = AccessResult::allowedIfHasPermission($account, 'use gutenberg'); if ($access->isAllowed()) { // Only throw the 404 if the user is allowed to access the route. // Avoids anonymous users scanning for a block's existence. if (!$block) { throw new NotFoundHttpException(); } } // Check if it's a reusable block. $access = $access->andIf(AccessResult::allowedIf($block && $block->bundle() === 'reusable_block')); // Add it as a cache dependency. $access->addCacheableDependency($block); return $access; } /** * Load a reusable block content entity or throw an HTTP exception. * * An HTTP exception is thrown if the block could not be loaded or it's not a * reusable block type. * * @param int $block_id * The block ID. * * @return \Drupal\block_content\BlockContentInterface * The block instance. */ protected function loadBlockOrThrow($block_id) { $block_id = (int) $block_id; if ($block_id > 0 && $block = BlockContent::load($block_id)) { /** @var \Drupal\block_content\BlockContentInterface $block */ if ($block->bundle() !== 'reusable_block') { // Avoid accidental/malicious manipulation of non reusable blocks in // this controller. throw new BadRequestHttpException("Block '$block_id' is not a reusable block."); } return $block; } throw new NotFoundHttpException("Block '$block_id' does not exist."); } /** * Get the block as a response array. * * @param \Drupal\block_content\BlockContentInterface $block * The block instance. * * @return array * The block response array. */ protected function getBlockAttributes(BlockContentInterface $block) { $terms = $block->get('field_pattern_category')->referencedEntities(); $categories = []; foreach ($terms as $term) { $categories[] = (int) $term->id(); } return [ 'name' => 'core/block/' . $block->id(), 'id' => (int) $block->id(), 'title' => [ 'raw' => (string) $block->get('info')->value, ], 'content' => [ 'block_version' => 1, 'raw' => (string) $block->get('body')->value, ], 'wp_pattern_category' => $categories, 'wp_pattern_sync_status' => $block->get('field_pattern_sync_status')->value == 'synced' ? '' : 'unsynced', 'type' => 'wp_block', 'status' => 'publish', 'slug' => 'reusable_block_' . $block->id(), ]; } }
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <learnopengl/shader_s.h> #include <learnopengl/filesystem.h> void frame_buffer_size_callback(GLFWwindow *window, int width, int height); void processInput(GLFWwindow *window); void initData(); int main() { // std::cout << "root " << logl_root << std::endl; // glfwInit函数来初始化GLFW glfwInit(); // 配置GLFW,告诉GLFW我们要使用的OpenGL版本是3.3 主版本号(Major)和次版本号(Minor) glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // GLFW我们使用的是核心模式(Core-profile) 我们只能使用OpenGL功能的一个子集 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // MAC OSX needs #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif GLFWwindow *window = glfwCreateWindow(800, 600, "QiangGL", NULL, NULL); if (window == NULL) { std::cout << "Fialed to create GLFW window" << std::endl; glfwTerminate(); // 终止 return -1; } glfwMakeContextCurrent(window); // 注册这个函数,告诉GLFW我们希望每当窗口调整大小的时候调用这个函数 glfwSetFramebufferSizeCallback(window, frame_buffer_size_callback); // GLAD if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // OpenGL渲染窗口的尺寸大小,即视口(Viewport) glViewport(0, 0, 800, 600); Shader ourShader(FileSystem::getPath("resources/shader/3_3_shader.vs").c_str(), FileSystem::getPath("resources/shader/3_3_shader.fs").c_str()); float vertices[] = { // 位置 // 颜色 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, // 右下 -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, // 左下 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 1.0f // 顶部 }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); // GL_STATIC_DRAW GL_DYNAMIC_DRAW GL_STREAM_DRAW // 顶点起步、顶点的大小、数据类型,是否希望被标准化(0,1),步长(3个顶点), 位置数据在缓冲中起始位置的偏移量(Offset) // 第二个参数指定顶点属性的大小。顶点属性是一个vec3,它由3个值组成,所以大小是3。 // glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void *)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void *)(3 * sizeof(float))); glEnableVertexAttribArray(1); // 可以安全地解除绑定 glBindBuffer(GL_ARRAY_BUFFER, 0); // 解除对 VAO 的绑定 glBindVertexArray(0); // 函数在我们每次循环的开始前检查一次GLFW是否被要求退出 while (!glfwWindowShouldClose(window)) { // 输入 processInput(window); // 执行渲染 。。。 glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); ourShader.use(); glBindVertexArray(VAO); glDrawArrays(GL_TRIANGLES, 0, 3); // 检查并调用事件,交换缓冲 // 函数会交换颜色缓冲(它是一个储存着GLFW窗口每一个像素颜色值的大缓冲),它在这一迭代中被用来绘制,并且将会作为输出显示在屏幕上 glfwSwapBuffers(window); // 函数检查有没有触发什么事件(比如键盘输入、鼠标移动等)、更新窗口状态,并调用对应的回调函数(可以通过回调方法手动设置)。 glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // 渲染循环结束后我们需要正确释放/删除之前的分配的所有资源 glfwTerminate(); return 0; } void frame_buffer_size_callback(GLFWwindow *window, int width, int height) { glViewport(0, 0, width, height); } void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } }
import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Observable } from 'rxjs'; import { RawMaterial } from '../../models/rawMaterial'; import { environment } from 'src/environments/environment'; import { PagedResult } from '../../models/pagedResult'; @Injectable({ providedIn: 'root' }) export class RawMaterialService { constructor(private httpClient: HttpClient) { } public Get(rawMaterialId: number): Observable<RawMaterial> { return this.httpClient.get<RawMaterial>(`${environment.apiUrl}/RawMaterial/${rawMaterialId}`); } public GetPaged(page: number, pageSize: number, name: string, sortDirection: number): Observable<PagedResult<RawMaterial>> { let params = new HttpParams(); if (name) params = params.append('name', name); params = params.append('direction', String(sortDirection)); return this.httpClient.get<PagedResult<RawMaterial>>(`${environment.apiUrl}/RawMaterial/${page}/${pageSize}`, { params: params }); } public Add(rawMaterial: RawMaterial): Observable<number> { return this.httpClient.post<number>(`${environment.apiUrl}/RawMaterial`, rawMaterial); } public Update(rawMaterial: RawMaterial): Observable<RawMaterial> { return this.httpClient.put<RawMaterial>(`${environment.apiUrl}/RawMaterial`, rawMaterial); } public GetAll(sortDirection: number): Observable<RawMaterial[]> { let params = new HttpParams(); params = params.append('direction', String(sortDirection)); return this.httpClient.get<RawMaterial[]>(`${environment.apiUrl}/RawMaterial`); } }
#include <iostream> /** Интерфейс Subject объявляет общие операции как для реального субъекта, так и для прокси. Пока клиент работает с RealSubject, используя этот интерфейс, вы сможете передавать ему прокси вместо реального субъекта. */ class Subject { public: virtual void Request() const = 0; }; /** Реальный объект содержит некоторую основную бизнес-логику. Обычно RealSubjects способны выполнять некоторую полезную работу, которая также может быть очень медленной или чувствительной - например, исправлять входные данные. Прокси-сервер может решить эти проблемы без каких-либо изменений в коде RealSubject. */ class RealSubject : public Subject { public: void Request() const override { std::cout << "RealSubject: Handling request.\n"; } }; /** Прокси имеет интерфейс, идентичный реальному субъекту. */ class Proxy : public Subject { /** * @var RealSubject */ private: RealSubject* real_subject_; bool CheckAccess() const { // Здесь должны быть какие-то реальные проверки. std::cout << "Proxy: Checking access prior to firing a real request.\n"; return true; } void LogAccess() const { std::cout << "Proxy: Logging the time of request.\n"; } /** Прокси поддерживает ссылку на объект класса RealSubject. Он может быть либо загружен с задержкой, либо передан прокси-серверу клиентом. */ public: Proxy(RealSubject* real_subject) : real_subject_(new RealSubject(*real_subject)) { } ~Proxy() { delete real_subject_; } /** Наиболее распространенными приложениями шаблона прокси-сервера являются отложенная загрузка, кэширование, управление доступом, ведение журнала и т.д. Прокси может выполнить одно из этих действий, а затем, в зависимости от результата, передать выполнение тому же методу в связанном объекте RealSubject. */ void Request() const override { if (this->CheckAccess()) { this->real_subject_->Request(); this->LogAccess(); } } }; /** Предполагается, что клиентский код работает со всеми объектами (как субъектами, так и прокси) через интерфейс Subject, чтобы поддерживать как реальные субъекты, так и прокси-серверы. Однако в реальной жизни клиенты в основном работают со своими реальными объектами напрямую. В этом случае, чтобы упростить реализацию шаблона, вы можете расширить свой прокси из класса реального субъекта. */ void ClientCode(const Subject& subject) { // ... subject.Request(); // ... } int main() { std::cout << "Клиент: Выполнение клиентского кода с реальным субъектом:\n"; RealSubject* real_subject = new RealSubject; ClientCode(*real_subject); std::cout << "\n"; std::cout << "Клиент: Выполнение того же клиентского кода с помощью прокси-сервера:\n"; Proxy* proxy = new Proxy(real_subject); ClientCode(*proxy); delete real_subject; delete proxy; return 0; }
{* *************************************************************************** Copyright (c) 2017 by Lloyd B. Park Handles various methods of logging This file is part of Lloyd's Free Pascal Libraries (LFPL). LFPL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. LFPL is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with LFPL. If not, see <http://www.gnu.org/licenses/>. *************************************************************************** *} unit lbp_Log; // Provides a common Log() function which can log to standard // out, a text file, or the syslog. // Currently defined INI variables are: // [KSULog] // // Minimum log level sent to the log. // LogLevel=Debug // // Possible Syslog levels, are in order: // // Debug, Info, Notice, Warning, Err, Crit, Alert, Emerg // // NOTE: Case is important!!! // Logging=yes // LogFile=/tmp/testrunonce.log // UseSysLog=false interface {$include lbp_standard_modes.inc} {$LONGSTRINGS ON} // Non-sized Strings are ANSI strings // SignalHandler for our timestamp when printing to a file or OUTPUT uses lbp_argv, {$ifndef windows} SystemLog, lbp_current_time, lbp_run_once, // IsDaemon function call {$endif} SysUtils, // FileExists() lbp_vararray, // Variable length arrays lbp_types, // int16 lbp_lists, lbp_ini_files; // ************************************************************************ const LOG_EMERG = 0; LOG_ALERT = 1; LOG_CRIT = 2; LOG_ERR = 3; LOG_WARNING = 4; LOG_NOTICE = 5; LOG_INFO = 6; LOG_DEBUG = 7; LogLevel: int16 = LOG_ERR; // Maximum log level we will use LogPrefix: string = ''; procedure Log( const Level: int16; const Msg: String); procedure Log( const Level: int16; const Msg: String; const Args: array of const); function HexDumpToList( var Buffer; Length: word): DoubleLinkedList; procedure LogHexDump( const Level: int16; var Buffer; Length: word; Prefix: string); procedure LogBoolean( const Level: int16; const Name: string; Value: boolean); type lbp_log_exception = class( lbp_exception); var LogCS: tRTLCriticalSection; // For the use of other units and programs // Not used internaly. // ************************************************************************ implementation const LogFileName: string = ''; LogFileAppend: boolean = false; DoLogging: boolean = true; // Output Log messages to OUTPUT. UseSyslog: boolean = false; // Output them to Syslog instead // of LogFile // stamp the event SyslogIsOpen: boolean = false; LogFileIsOpen: boolean = false; var LogFile: Text; CritSect: TRTLCriticalSection; // ************************************************************************ // * Log() - Send message to the log facility // ************************************************************************ procedure Log( const Level: int16; const Msg: String); begin if( DoLogging and (Level <= LogLevel)) then begin {$ifndef windows} EnterCriticalSection( CritSect); if( UseSyslog) then begin if( not SyslogIsOpen) then begin openlog( @LogPrefix[ 1], LOG_NOWAIT, LOG_DEBUG); end; syslog( Level, pchar( Msg), []); end else begin if( not CronIsRunning) then begin CurrentTime.Now(); // Set CurrentTime to the current time. end; writeln( LogFile, TimeStr(), ' ', Msg); Flush( LogFile); end; LeaveCriticalSection( CritSect); end; // if DoLogging {$endif} {$ifdef windows} writeln( LogFile, Msg); Flush( LogFile); end; {$endif} end; // Log() // ------------------------------------------------------------------------ procedure Log( const Level: int16; const Msg: String; const Args: array of const); begin Log( Level, Format( Msg, Args)); end; // LogF // ************************************************************************ // * HexDumpToList() - Creates a linked list of strings. Each string // * will hold a dump of up to 16 bytes of the Buffer. // ************************************************************************ function HexDumpToList( var Buffer; Length: word): DoubleLinkedList; var L: DoubleLinkedList; B: BigByteArrayPtr; S: StringPtr; HexValue: string; StrValue: string; i: word; HexIndex: shortint; StrIndex: shortint; Temp: byte; begin // This is just to stop the compiler warnings about uninitialized vars. S:= nil; HexValue:= ''; StrValue:= ''; L:= DoubleLinkedList.Create(); if( Length > 0) then begin B:= @Buffer; // Convert the array of bytes to a hex dump format // For each byte for i:= 0 to Length - 1 do begin Temp:= B^[ i]; // Create a new string for every 16 bytes if( (i mod 16) = 0) then begin if( i <> 0) then begin S^:= HexValue + ' ' + StrValue; end; // Initialize the arrays StrValue:= StringOfChar( '.', 16); HexValue:= StringOfChar( ' ', 16 * 3); HexIndex:= 1; StrIndex:= 1; new( S); L.Enqueue( S); end; // Add to the character string. if( Chr( Temp) in ['A'..'Z', 'a'..'z', '0'..'9', ' ']) then begin StrValue[ StrIndex]:= Chr( Temp); end; inc( StrIndex); // Handle the upper nibble Temp:= B^[ i] SHR 4; if( Temp > 9) then begin HexValue[ HexIndex]:= Chr( Temp + ord( 'a') - 10); end else begin HexValue[ HexIndex]:= Chr( Temp + ord( '0')); end; inc( HexIndex); // Handle the lower nibble Temp:= B^[ i] and 15; if( Temp > 9) then begin HexValue[ HexIndex]:= Chr( Temp + ord( 'a') - 10); end else begin HexValue[ HexIndex]:= Chr( Temp + ord( '0')); end; inc( HexIndex, 2); end; // For each byte S^:= HexValue + ' ' + StrValue; end; // If we passed a non-zero length. HexDumpToList:= L; end; // HexDumpToList(); // ************************************************************************ // * LogHexDump() - Dumps the hex representation of Length bytes from Buffer // * to Log. The first line is prefixed with Prefix and every // * other line is prefixed with Length( Prefix) spaces. // ************************************************************************ procedure LogHexDump( const Level: int16; var Buffer; Length: word; Prefix: string); var L: DoubleLinkedList; S: StringPtr; Spaces: String; begin EnterCriticalSection( CritSect); Spaces:= StringOfChar( ' ', System.Length( Prefix)); L:= HexDumpToList( Buffer, Length); // Output the first line if( not L.Empty()) then begin S:= StringPtr( L.Dequeue()); Log( Level, Prefix + S^); dispose( S); end; // Output any other lines. while( not L.Empty()) do begin S:= StringPtr( L.Dequeue()); Log( Level, Spaces + S^); dispose( S); end; L.Destroy(); LeaveCriticalSection( CritSect); end; // LogHexDump() // ************************************************************************ // * LogBoolean() // ************************************************************************ procedure LogBoolean( const Level: int16; const Name: string; Value: boolean); var ValueStr: string; begin if( Value) then begin ValueStr:= 'true'; end else begin ValueStr:= 'true'; end; Log( Level, Name + ' = ' + ValueStr); end; // LogBoolean() // ************************************************************************* // * StringToLogLevel() - Convert the string representation of a Log Level // * to a number. Returns a -1 on error! // ************************************************************************* function StringToLogLevel( S: string): int16; var Temp: string; begin Temp:= LowerCase( S); if( Temp = 'debug') then begin LogLevel:= LOG_DEBUG; end else if( Temp = 'info') then LogLevel:= LOG_INFO else if( Temp = 'notice') then LogLevel:= LOG_NOTICE else if( Temp = 'warning') then LogLevel:= LOG_WARNING else if( Temp = 'err') then LogLevel:= LOG_ERR else if( Temp = 'crit') then LogLevel:= LOG_CRIT else if( Temp = 'alert') then LogLevel:= LOG_ALERT else if( Temp = 'emerg') then LogLevel:= LOG_EMERG else result:= -1; end; // StringToLogLevel() // ************************************************************************* // * ReadLogLevel() - Reads the log level from the .ini file. // ************************************************************************* procedure ReadLogLevel( SectName: string); var TempS: String; TempL: int16; // Temporary Log Level begin TempS:= INI.ReadVariable( SectName, 'LogLevel', ''); TempL:= StringToLogLevel( TempS); If( TempL >= 0) then LogLevel:= TempL; end; // ReadLogLevel() // ************************************************************************* // * ParseArgV() - Parse the command line parameters // ************************************************************************* procedure ParseArgv(); var logconsole: boolean; logfile: boolean; logappend: boolean; logsyslog: boolean; LL: string; begin // If the user asked for no logging, then clear logging and exit if( ParamSet( 'no-log')) then begin LogFileName:= ''; LogFileAppend:= false; DoLogging:= false; UseSyslog:= false; exit; end; logconsole:= ParamSet( 'log-console'); logfile:= ParamSet( 'log-file'); logappend:= ParamSet( 'log-file-append'); logsyslog:= ParamSet( 'syslog'); if( logconsole) then begin if( logfile or logappend or logsyslog) then begin raise argv_exception.create( 'Only one log destination may be set!'); end; DoLogging:= true; LogFileAppend:= false; LogFileName:= ''; end else if( logfile) then begin if( logconsole or logappend or logsyslog) then begin raise argv_exception.create( 'Only one log destination may be set!'); end; DoLogging:= true; LogFileAppend:= false; ParseHelper( 'log-file', LogFileName); end else if( logappend) then begin if( logconsole or logfile or logsyslog) then begin raise argv_exception.create( 'Only one log destination may be set!'); end; DoLogging:= true; LogFileAppend:= true; ParseHelper( 'log-file-append', LogFileName); end else if( logsyslog) then begin if( logconsole or logfile or logappend) then begin raise argv_exception.create( 'Only one log destination may be set!'); end; DoLogging:= true; LogFileAppend:= false; UseSyslog:= true; LogFileName:= ''; end; if( ParamSet( 'log-level')) then begin ParseHelper( 'log-level', LL); case LL of 'debug': LogLevel:= LOG_DEBUG; 'info': LogLevel:= LOG_INFO; 'notice': LogLevel:= LOG_NOTICE; 'warning': LogLevel:= LOG_WARNING; 'err': LogLevel:= LOG_ERR; 'crit': LogLevel:= LOG_CRIT; 'alert': LogLevel:= LOG_ALERT; 'emerg': LogLevel:= LOG_EMERG; else begin raise lbp_log_exception.Create( 'An invalid --log-level was specified!'); end; end; // case end; // if log-level end; // ParseArgV // ************************************************************************* // * ReadINI() - Read the .ini file variables // ************************************************************************* procedure ReadINI(); var Sect1: string = 'lbpLog'; Sect2: string = 'KentLog'; begin if( INI <> nil) then begin // Logging variables using the new section name ReadLogLevel( Sect1); LogFileName:= INI.ReadVariable( Sect1, 'LogFile', LogFileName); LogfileAppend:= INI.ReadVariable( Sect1, 'LogFileAppend', LogFileAppend); DoLogging:= INI.ReadVariable( Sect1, 'Logging', true); // Logging variables using the old section name ReadLogLevel( Sect2); LogFileName:= INI.ReadVariable( Sect2, 'LogFile', LogFileName); LogfileAppend:= INI.ReadVariable( Sect2, 'LogFileAppend', LogFileAppend); DoLogging:= INI.ReadVariable( Sect2, 'Logging', DoLogging); {$ifndef windows} UseSyslog:= INI.ReadVariable( Sect1, 'UseSyslog', IsDaemon()); UseSyslog:= INI.ReadVariable( Sect2, 'UseSyslog', UseSyslog); {$endif} end; // if end; // ReadINI() // ************************************************************************* // * ReopenLog() - Reopen the log based on the current settings. // ************************************************************************* procedure ReopenLog(); begin if( LogFileIsOpen) then begin LogFileIsOpen:= false; Close( LogFile); end; {$ifndef windows} // Are we trying to log to standard out when we are a daemon? if( IsDaemon() and (not UseSysLog) and (LogFileName = '')) then begin DoLogging:= false; end; {$endif} // Don't do anything else unless we are logging. if( DoLogging) then begin {$ifndef windows} if( UseSyslog) then begin // Open the Syslog if needed if( not SyslogIsOpen) then begin SyslogIsOpen:= true; LogPrefix:= ProgramName + '[' + lbp_Run_Once.MyPIDStr + ']'; openlog( @LogPrefix[ 1], LOG_NOWAIT, LOG_DEBUG); end; end else begin // Not using syslog // Close the Syslog if needed if( SyslogIsOpen) then begin UseSysLog:= true; Log( LOG_DEBUG, 'Logging has been turned off. Closing Syslog.'); UseSysLog:= false; Closelog(); SyslogIsOpen:= false; end; {$endif} // Open the LogFile if( LogFileName <> '') then begin assign( LogFile, LogFileName); if( LogFileAppend and FileExists( LogFileName)) then begin append( LogFile); end else begin rewrite( LogFile); end; LogFileIsOpen:= true; end else begin LogFile:= OUTPUT; end; {$ifndef windows} end; // if UseSyslog {$endif} end; // if DoLogging end; // ReopenLog() // ************************************************************************* // * ReadVars() - Read INI and command line variables. Then open the log // ************************************************************************* procedure ReadVars(); begin ReadINI; ParseArgv; ReopenLog; end; // ReadVars(); // = Initialization and finalization // ************************************************************************ Initialization begin {$ifdef DEBUG_UNIT_INITIALIZATION} writeln( 'Initialization of lbp_log started.'); {$endif} InitCriticalSection( CritSect); InitCriticalSection( LogCS); // Add Usage messages AddUsage( ' ========== Logging options =========='); AddParam( ['no-log'], false, '', 'Disable logging'); AddParam( ['log-console'], false, '', 'Send log messages to the console.'); AddParam( ['log-file'], true , '', 'Send log messages to the passed file name.'); AddParam( ['log-file-append'], true , '', 'Like --log-file but append to an existing file'); AddParam( ['syslog'], false , '', 'Send log messages to syslog'); AddParam( ['log-level'], true, '', 'Set one of the log levels to one of ''debug'','); // ''Err'' is the default.'); AddUsage( ' ''info'', ''notice'', ''warning'', ''err'', ''crit'','); AddUsage( ' ''alert'', or ''emerg''. ''err'' is the default.'); AddUsage( ''); AddPostParseProcedure( @ReadVars); if( INI <> nil) then begin INI.ProcStack.Enqueue( @ReadVars); end; {$ifdef DEBUG_UNIT_INITIALIZATION} writeln( 'Initialization of lbp_log ended.'); {$endif} end; // ************************************************************************ finalization begin {$ifdef DEBUG_UNIT_INITIALIZATION} writeln( 'Finalization of lbp_log started.'); {$endif} {$ifndef windows} if( SyslogIsOpen) then begin CloseLog(); end; {$endif} if( LogFileIsOpen) then begin Close( LogFile); end; LogPrefix:= ''; LogFileName:= ''; DoneCriticalSection( CritSect); DoneCriticalSection( LogCS); {$ifdef DEBUG_UNIT_INITIALIZATION} writeln( 'Finalization of lbp_log ended.'); {$endif} end; // ************************************************************************ end. // lbp_Log
package main import ( "bufio" "fmt" "os" "strings" ) // 多组输入(不知道多少组) /* 每门课的成绩分为A、B、C、D、F五个等级,为了计算平均绩点,规定A、B、C、D、F分别代表4分、3分、2分、1分、0分。 输入 有多组测试样例。每组输入数据占一行,由一个或多个大写字母组成,字母之间由空格分隔。 输出 每组输出结果占一行。如果输入的大写字母都在集合{A,B,C,D,F}中,则输出对应的平均绩点,结果保留两位小数。否则,输出“Unknown”。 样例输入 A B C D F B F F C C A D C E F 样例输出 2.00 1.83 Unknown */ var ( scanner = bufio.NewScanner(os.Stdin) writer = bufio.NewWriter(os.Stdout) ) func main() { defer writer.Flush() m := map[string]int{"A": 4.0, "B": 3.0, "C": 2.0, "D": 1.0, "F": 0.0} for { boo := scanner.Scan() if boo == false { break } if err := scanner.Err(); err != nil { break } input := scanner.Text() keywordFrequency := make(map[string]int) keywords := strings.Fields(input) for _, keyword := range keywords { if keyword != "" { keywordFrequency[keyword]++ } } var sum float64 = 0 count := 0 flag := 1 for key, value := range keywordFrequency { if _, ok := m[key]; ok { count += value sum += float64((m[key] * value)) } else { flag = 0 } } if flag == 1 { fmt.Fprintf(writer, "%.2f\n", sum/float64(count)) } else { fmt.Fprintln(writer, "Unknown") } writer.Flush() } }
/* * Copyright 2012 SIB Visions GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * * History * * 11.10.2012 - [CB] - creation */ package com.sibvisions.rad.ui.vaadin.impl.component; import javax.rad.ui.IImage; import javax.rad.ui.component.ICheckBox; import javax.rad.ui.event.Key; import javax.rad.ui.event.UIActionEvent; import com.sibvisions.rad.ui.vaadin.ext.ui.AccessibilityUtil; import com.sibvisions.rad.ui.vaadin.ext.ui.client.CssExtensionAttribute; import com.vaadin.data.HasValue.ValueChangeEvent; import com.vaadin.data.HasValue.ValueChangeListener; import com.vaadin.ui.CheckBox; /** * The <code>VaadinCheckBox</code> class is the vaadin implementation of {@link ICheckBox}. * * @author Benedikt Cermak */ public class VaadinCheckBox extends AbstractVaadinCaptionComponent<CheckBox> implements ICheckBox, ValueChangeListener { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Class members //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** If the change event shoul be ignored. */ private boolean ignoreChangeEvent = false; /** The gap between the Image and the Text. **/ private int imageTextGap = 0; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Initialization //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * Creates a new instance of <code>VaadinCheckBox</code>. * * @see javax.rad.ui.component.ICheckBox */ public VaadinCheckBox() { super(new CheckBox()); addInternStyleName("jvxcheckbox"); resource.addValueChangeListener(this); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Interface Implementation //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * {@inheritDoc} */ public Key getAccelerator() { //Not supported return null; } /** * {@inheritDoc} */ public void setAccelerator(Key pAccelerator) { //Not supported } /** * {@inheritDoc} */ public int getImageTextGap() { return imageTextGap; } /** * {@inheritDoc} */ public void setImageTextGap(int pImageTextGap) { imageTextGap = pImageTextGap; CssExtensionAttribute cssAttribute = new CssExtensionAttribute("margin-right", imageTextGap + "px"); cssAttribute.setElementClassName("v-icon"); cssAttribute.setSearchDirection(CssExtensionAttribute.SEARCH_DOWN); getCssExtension().addAttribute(cssAttribute); } /** * {@inheritDoc} */ public void setVerticalTextPosition(int pVerticalPosition) { //Not supported } /** * {@inheritDoc} */ public int getVerticalTextPosition() { //Not supported return 0; } /** * {@inheritDoc} */ public void setHorizontalTextPosition(int pHorizontalPosition) { //Not supported } /** * {@inheritDoc} */ public int getHorizontalTextPosition() { //Not supported return 0; } /** * {@inheritDoc} */ public boolean isBorderOnMouseEntered() { //Not supported return false; } /** * {@inheritDoc} */ public void setBorderOnMouseEntered(boolean pBorderOnMouseEntered) { //Not supported } /** * {@inheritDoc} */ public void setBorderPainted(boolean pBorderPainted) { //Not supported } /** * {@inheritDoc} */ public boolean isBorderPainted() { //Not supported return false; } /** * {@inheritDoc} */ public void setMouseOverImage(IImage pImage) { //Not supported } /** * {@inheritDoc} */ public IImage getMouseOverImage() { //Not supported return null; } /** * {@inheritDoc} */ public void setPressedImage(IImage pImage) { //Not supported } /** * {@inheritDoc} */ public IImage getPressedImage() { //Not supported return null; } /** * {@inheritDoc} */ public void setDefaultButton(boolean pDefault) { //Not supported } /** * {@inheritDoc} */ public boolean isDefaultButton() { //Not supported return false; } /** * {@inheritDoc} */ public boolean isSelected() { return ((Boolean)resource.getValue()).booleanValue(); } /** * {@inheritDoc} */ public void setSelected(boolean pPressed) { ignoreChangeEvent = true; resource.setValue(Boolean.valueOf(pPressed)); AccessibilityUtil.setPressed(getAttributesExtension(), pPressed); ignoreChangeEvent = false; } /** * {@inheritDoc} */ public void valueChange(ValueChangeEvent pEvent) { if (!ignoreChangeEvent) { Boolean value = (Boolean)pEvent.getValue(); AccessibilityUtil.setPressed(getAttributesExtension(), value.booleanValue()); if (eventActionPerformed != null) { getFactory().synchronizedDispatchEvent(eventActionPerformed, new UIActionEvent(eventSource, UIActionEvent.ACTION_PERFORMED, System.currentTimeMillis(), 0, getActionCommand())); } } } } // VaadinCheckBox
package video.niuwei.com.myapplicationxiangmu.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.interfaces.DraweeController; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.imagepipeline.request.ImageRequest; import java.util.List; import video.niuwei.com.myapplicationxiangmu.R; import video.niuwei.com.myapplicationxiangmu.SousuoActivity; import video.niuwei.com.myapplicationxiangmu.bean.JBean; import video.niuwei.com.myapplicationxiangmu.bean.SBean; /** * Created by One Dream on 2017/11/29. */ public class MySousuoAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener{ private List<SBean.RetBean.ListBean> list; private Context context; public MySousuoAdapter(List<SBean.RetBean.ListBean> childList, SousuoActivity SousuoActivity ) { this.list=childList; this.context=SousuoActivity; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view=View.inflate(context,R.layout.sousuo_recy_layout,null); // View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.faxian_recy_layout, parent, false); MyHolder myHolder=new MyHolder(view); //将创建的View注册点击事件 view.setOnClickListener(this); return myHolder; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { ((MyHolder)holder).name.setText(list.get(position).getTitle()); ((MyHolder)holder).airtime.setText("上线日期:"+list.get(position).getAirTime()+""); ((MyHolder)holder).duration.setText("时长:"+list.get(position).getDuration()); ((MyHolder)holder).description.setText("简介:"+list.get(position).getDescription()); DraweeController controller = Fresco.newDraweeControllerBuilder() .setUri(list.get(position).getPic()) .setLowResImageRequest(ImageRequest.fromUri(list.get(position).getPic())) .setImageRequest(ImageRequest.fromUri(list.get(position).getPic())) .setOldController(((MyHolder)holder).sdv.getController()) .build(); ((MyHolder)holder).sdv.setController(controller); ((MyHolder)holder).description.setMaxLines(3); ((MyHolder)holder).description.setEllipsize(TextUtils.TruncateAt.END); //将position保存在itemView的Tag中,以便点击时进行获取 holder.itemView.setTag(position); } @Override public int getItemCount() { return list.size(); } @Override public void onClick(View v) { if (mOnItemClickListener != null) { //注意这里使用getTag方法获取position mOnItemClickListener.onItemClick(v,(int)v.getTag()); } } public void setOnItemClickListener(OnItemClickListener listener) { this.mOnItemClickListener = listener; } class MyHolder extends RecyclerView.ViewHolder{ private final TextView name; private final TextView airtime; private final TextView duration; private final TextView description; private final SimpleDraweeView sdv; public MyHolder(View itemView) { super(itemView); name = (TextView) itemView.findViewById(R.id.fx_name); airtime = (TextView)itemView.findViewById(R.id.airTime); duration = (TextView)itemView.findViewById(R.id.duration); description = (TextView)itemView.findViewById(R.id.description); sdv = itemView.findViewById(R.id.faxian_recy_sdv); } } private OnItemClickListener mOnItemClickListener = null; public static interface OnItemClickListener { void onItemClick(View view, int position); } }
# Configuring bot's responses Here is the process of creating a new configuration file with bot's responses. You can use the template to make things easier for youself. > The text structure should follow Markdown syntax. > To make a multiline answer, use symbol "`|`" Firstly, Create YAML file in`./configs/bot_locale/` directory. Let's configure some metadata: ```yaml language: English code: en ``` `language` - language name. It will be shown to user. `code` - language locale code. It is used to determine which language should be used for each user in default. ### Configuring settings: ```yaml start: message: | welcome message description: Start bot cancel: message: canceled description: Cancel current task help: message: | help message sample text description: Displays help message change_language: message: | change bots language to description: Change bot's interface language button1: "English" button2: "русский" ``` The general structure is: ```yaml command: message: command message description: command description button1: param1 value1: true_value1 button2: param2 value2: true_value2 ... buttonN: paramN valueN: true_valueN ``` `message` - Message which bot writes then configuring this setting. `description` - Command description in command list. `buttonN` - Shows button with this text. `valueN` - Send this string instead if user chooses this button. ### `general` and `errors` tab All keys in this section should exist in your config file. You can only change their values. Both tabs determine a message sent to user. Example: ```yaml general: success: Success! got_link: Processing youtube video... got_video: Processing video... transcribing: Transcribing video, please wait... processing: Processing text, please wait... caption: Here is your document document_caption: Here is your summary! startup: Bot started shutdown: Bot shutdown errors: critical: "Critical Error" bad_link: "Bad link" config_access: "Error: could not access config file with the provided keyword" composer: "Error in document generation" llm: "Error in text generation module" audio_model: "Error in transcription process" file_not_found: "Could not find file in the provided path" unknown_setting: "You chose a wrong setting, use keyboard next time or check configs" ```
use std::collections::HashMap; use axum::http::StatusCode; use axum::Json; use axum::routing::{get}; use axum_extra::headers::Cookie; use axum_extra::TypedHeader; use lib_base64::Base64; use serde::{Deserialize, Serialize}; use tracing::{error, info}; pub fn router() -> axum::Router { axum::Router::new() .route("/decode", get(day07_get)) .route("/bake", get(day07_get_task2)) } async fn day07_get(TypedHeader(cookie): TypedHeader<Cookie>) -> Result<String,StatusCode> { match cookie.get("recipe") { Some(recipe) => { recipe.to_string().decode().map_err(|_| StatusCode::BAD_REQUEST) } None => Err(StatusCode::BAD_REQUEST) } } #[derive(Deserialize, Debug)] struct BakeData{ recipe: HashMap<String, i64>, pantry: HashMap<String, i64>, } #[derive(Serialize, Debug)] struct BakeResult{ cookies: i64, pantry: HashMap<String, i64>, } impl BakeData { fn ingredients_available(&mut self) -> bool { let available = self.recipe.iter() .filter(|(ingredient, amount)| self.pantry.contains_key(ingredient as &str) && self.pantry.get(ingredient as &str).unwrap() >= amount) .count() == self.recipe.len(); if available { self.recipe.iter() .for_each(|(ingredient, amount)| { let current_amount = self.pantry.get(ingredient).unwrap(); self.pantry.insert(ingredient.to_string(), current_amount - amount); }); true } else { false } } fn bake(&mut self) -> BakeResult { let mut cookie_counter = 0; self.recipe.retain(|_, amount| *amount > 0i64); info!("Recipe after cleanup: {:?}", self.recipe); while self.ingredients_available() { cookie_counter += 1; } BakeResult { cookies: cookie_counter, pantry: self.pantry.clone(), } } } async fn day07_get_task2(TypedHeader(cookie): TypedHeader<Cookie>) -> Result<Json<BakeResult>,StatusCode> { info!("Got cookie: {:?}", cookie); let data = cookie.get("recipe") .and_then(|data| Some(data.to_string().decode())).ok_or(StatusCode::BAD_REQUEST)?.map_err(|_| StatusCode::BAD_REQUEST); info!("Got data: {:?}", data); let mut bake_data: BakeData = serde_json::from_str(&data.unwrap()).map_err(|e| { error!("Could not parse data: {}", e); StatusCode::BAD_REQUEST})?; info!("Got bake data: {:?}", bake_data); let bake_result = bake_data.bake(); info!("Bake result: {:?}", bake_result); Ok(Json(bake_result)) }
--- title: Using git bisect to find the one bad commit pubDate: 2023-10-26 tags: ['git'] isDraft: false isFeatured: true description: Commits may break things. But you might not notice it right away and push more commits. With git bisect you'll find the bad commit in no time. --- _Move fast and break things_. The official motto of Facebook until 2014 (it's now _move fast with stable infrastructure_). While developers try a lot locally, we tend to not commit a change if there are some obvious errors. But not all errors are obvious, which is a point where tests come in handy. And tests and test-driven development is great, but some errors still may slip through. Let's imagine: you're working on a large project, with separate teams of at least 5 devs, and suddenly production is down. The problem: the last commits were made pretty much simultaneously and there is no obvious way of telling which commit broke everything. Now it's up to you to play detective and find out where the error is coming from. ## Using the tools you're familiar with `git` is a very powerful tool, pretty much like a swiss army knife. And just like a typical swiss army knife, you will most likely use the same set of available tools and leave others aside without thinking about them too much. So, your first instinct may be to find the one file that caused the error. But (just for the fun of it) let's say the codebase is huge with over 10k files and although you are able to narrow it down to a certain section, there are still too many files to check manually. Maybe `git log` and/or `git blame` are great tools that could help. Especially if you have an idea of what the commit message might have been, `git log -S <string>` can go a long way. So, you spend a lot of time going through every file of every commit, look at all the changes that were made to track down the introduced error. In large projects, this will probably take a very long time. ## Binary search Before we get to the fastest way to find the culprit, we have to take a quick detour and talk about `binary search` with the typical use case when explaining this algorithm: finding the index of a certain value in a sorted array. The "standard" way of finding the index would be to start looking at the start of the array and traverse it one by one until you find the correct number or until you reach the end. This works, but with a asymptotic notation of `O(n)` it could take a very long time for very large arrays. A better way is `binary search`: check the middle value and compare it against the search value. If it's correct, great, you found it! If it's larger: repeat with the array now ending at the middle value. And if it's smaller, the array now starts at the middle value. ```ts const arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ]; const target = 13; ``` In this example, the first search would check against the number `11` and then continue in the right half of the array. It will keep going until it either finds the correct value (where it would return the index) or if the starting index is the same or larger than the ending index (where it would return `-1`). Here is a recursive implementation of the `binarySearch` in Typescript that works in `O(log n)`: ```ts function binarySearch( arr: number[], val: number, low: number, high: number, ): number { if (low >= high) { return -1; } const middle = Math.floor(low + (high - low) / 2); const middleVal = arr[middle]; if (middleVal === val) { return middle; } else if (middleVal > val) { return binarySearch(arr, val, low, middle); } else { return binarySearch(arr, val, middle + 1, high); } } ``` ## `git bisect` You might wonder, why this little detour? The commit history in git is not unlike a typical array ([JS array, that is](/blog/til-2)). You can now perform a binary search on the array with the last known "good" commit and the latest commit as a bad commit. And this is exactly what [`git bisect`](https://git-scm.com/docs/git-bisect) does: by defining a bad and a good commit, it narrows down the breaking commit by halving the array in every step. Let's try this: 1. Create a playground directory with git initialized: ```sh mkdir git-playground cd git-playground git init ``` 2. Run the following commands to add the first numbers of the fibonacci sequence to text file and commit after every number: ```sh echo fibonacci >> main.txt git add main.txt && git commit -m "Start with fibonacci sequence" echo 1 >> main.txt git add main.txt && git commit -m "add 1" echo 1 >> main.txt git add main.txt && git commit -m "add next 1" echo 2 >> main.txt git add main.txt && git commit -m "add 2" echo 3 >> main.txt git add main.txt && git commit -m "add 3" echo 5 >> main.txt git add main.txt && git commit -m "add 5" echo 9 >> main.txt git add main.txt && git commit -m "add 9" echo 13 >> main.txt git add main.txt && git commit -m "add 13" echo 21 >> main.txt git add main.txt && git commit -m "add 21" echo 34 >> main.txt git add main.txt && git commit -m "add 34" echo 55 >> main.txt git add main.txt && git commit -m "add 55" echo 89 >> main.txt git add main.txt && git commit -m "add 89" ``` 3. Take a look at the file and see that there is a mistake (it should be `8` instead of `9`): ```sh cat main.txt # fibonacci # 1 # 1 # 2 # 3 # 5 # 9 # 13 # 21 # 34 # 55 # 89 ``` 4. Start the bisect session with `git bisect start` 5. Since we know that the current version is wrong, call `git bisect bad`. This sets the current commit as the the end of the test array. 6. To set the start of the array, call `git bisect good <commit>`, you'll have to get the commit hash with `git log` before. 7. Now we get to the commit in the middle of the array. Call `cat main.txt` again and check if the output is correct: ```sh cat main.txt # fibonacci # 1 # 1 # 2 # 3 # 5 ``` 8. Looks good, tell git by calling `git bisect good`. Check the outcome: ```sh cat main.txt # fibonacci # 1 # 1 # 2 # 3 # 5 # 9 # 13 # 21 ``` 9. There's an error, so `git bisect bad`. 10. Repeat until git find the first bad commit. You'll end up with something like this: ```sh git bisect bad # 0b294c5b5e0cff6ea078133a03b961c9c13b31e8 is the first bad commit # commit 0b294c5b5e0cff6ea078133a03b961c9c13b31e8 ``` 11. You need to end the session with `git bisect reset`. ## Conclusion You now found the first bad commit! It's up to you what you will do with that information, but you saved a lot of time by following this approach. You could even start the session with one command if you follow the examples in the [git bisect docs](https://git-scm.com/docs/git-bisect#_examples). Owning a swiss army knife is great. Knowing how to use it is better. And now you know how to use a very useful tool in the swiss army knife that is git!
const { strictEqual, deepStrictEqual, ok } = require("assert"); const iconv = require("iconv-lite"); const { insertOrganisme } = require("../utils/fakeData"); const { startServer, generateAuthHeader } = require("../utils/testUtils"); const { dbCollection } = require("../../src/common/db/mongodb"); const assert = require("assert"); const { omitDeep } = require("../../src/common/utils/objectUtils"); const { sortBy, omit } = require("lodash"); const { DateTime } = require("luxon"); describe("organismesRoutes", () => { it("Vérifie qu'on peut lister des organismes", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", nature: "responsable_formateur", raison_sociale: "Centre de formation", _meta: { anomalies: [], date_import: new Date("2021-02-10T16:39:13.064Z"), date_dernier_import: new Date("2021-02-10T16:39:13.064Z"), }, }); const response = await httpClient.get("/api/v1/organismes"); strictEqual(response.status, 200); deepStrictEqual(response.data, { organismes: [ { siret: "11111111100001", raison_sociale: "Centre de formation", uai_potentiels: [], contacts: [], relations: [], lieux_de_formation: [], reseaux: [], nature: "responsable_formateur", diplomes: [], certifications: [], siege_social: true, etat_administratif: "actif", referentiels: ["test"], adresse: { geojson: { type: "Feature", geometry: { type: "Point", coordinates: [2.396444, 48.879706], }, properties: { score: 0.88, }, }, label: "31 rue des lilas Paris 75019", code_postal: "75001", code_insee: "75000", localite: "PARIS", departement: { code: "75", nom: "Paris", }, region: { code: "11", nom: "Île-de-France", }, academie: { code: "01", nom: "Paris", }, }, _meta: { anomalies: [], date_import: "2021-02-10T16:39:13.064Z", date_dernier_import: "2021-02-10T16:39:13.064Z", nouveau: false, }, }, ], pagination: { page: 1, resultats_par_page: 10, nombre_de_page: 1, total: 1, }, }); }); it("Vérifie qu'on peut rechercher des organismes à partir d'un UAI", async () => { const { httpClient } = await startServer(); await insertOrganisme(); await insertOrganisme({ uai: "0751234J" }); const response = await httpClient.get("/api/v1/organismes?uais=0751234J"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].uai, "0751234J"); }); it("Vérifie qu'on peut rechercher des organismes à partir de plusieurs UAI", async () => { const { httpClient } = await startServer(); await insertOrganisme(); await insertOrganisme({ uai: "0751234J" }); await insertOrganisme({ uai: "0751234X" }); const response = await httpClient.get("/api/v1/organismes?uais=0751234J,0751234X"); strictEqual(response.status, 200); const organismes = sortBy(response.data.organismes, (o) => o.uai); strictEqual(organismes.length, 2); strictEqual(organismes[0].uai, "0751234J"); strictEqual(organismes[1].uai, "0751234X"); }); it("Vérifie qu'on peut rechercher des organismes qui ont un UAI", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", uai: "0751234J" }); await insertOrganisme(); const response = await httpClient.get("/api/v1/organismes?uais=true"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes qui n'ont pas d'UAI", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", uai: "0751234J" }); await insertOrganisme({ siret: "22222222200002" }); const response = await httpClient.get("/api/v1/organismes?uais=false"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "22222222200002"); }); it("Vérifie qu'on peut rechercher des organismes à partir de leur nda", async () => { const { httpClient } = await startServer(); await insertOrganisme(); await insertOrganisme({ siret: "11111111100006", numero_declaration_activite: "12345678901" }); const response = await httpClient.get("/api/v1/organismes?numero_declaration_activite=12345678901"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes qui ont un nda", async () => { const { httpClient } = await startServer(); await insertOrganisme(); await insertOrganisme({ siret: "11111111100006", numero_declaration_activite: "12345678901" }); const response = await httpClient.get("/api/v1/organismes?numero_declaration_activite=true"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes qui n'ont pas de nda", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", numero_declaration_activite: "12345678901" }); await insertOrganisme({ siret: "22222222200002" }); const response = await httpClient.get("/api/v1/organismes?numero_declaration_activite=false"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "22222222200002"); }); it("Vérifie qu'on peut rechercher des organismes qualiopi", async () => { const { httpClient } = await startServer(); await insertOrganisme(); await insertOrganisme({ qualiopi: false }); await insertOrganisme({ siret: "11111111100006", qualiopi: true }); const response = await httpClient.get("/api/v1/organismes?qualiopi=true"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes qui ne sont pas qualiopi", async () => { const { httpClient } = await startServer(); await insertOrganisme({ qualiopi: true }); await insertOrganisme({ siret: "11111111100006", qualiopi: false }); const response = await httpClient.get("/api/v1/organismes?qualiopi=false"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes actifs", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", etat_administratif: "actif" }); await insertOrganisme({ etat_administratif: "fermé" }); const response = await httpClient.get("/api/v1/organismes?etat_administratif=actif"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes fermés", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", etat_administratif: "fermé" }); await insertOrganisme({ etat_administratif: "actif" }); const response = await httpClient.get("/api/v1/organismes?etat_administratif=fermé"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on calcule le meilleur UAI probable", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", uai_potentiels: [ { sources: ["sifa-ramsese"], uai: "0751234J", date_collecte: new Date(), }, { sources: ["other"], uai: "0751234X", date_collecte: new Date(), }, ], }); const response = await httpClient.get("/api/v1/organismes"); strictEqual(response.status, 200); strictEqual(response.data.organismes[0]._meta.uai_probable, "0751234J"); }); it("Vérifie qu'on peut rechercher des organismes qui un uai potentiel particulier", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", uai_potentiels: [ { sources: ["dummy"], uai: "0751234J", date_collecte: new Date(), }, ], }); await insertOrganisme({ siret: "22222222200002" }); const response = await httpClient.get("/api/v1/organismes?uai_potentiels=0751234J"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes avec plusieurs uai potentiels", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", uai_potentiels: [ { uai: "0751234J", sources: ["dummy"], date_collecte: new Date(), }, ], }); await insertOrganisme({ siret: "22222222200002", uai_potentiels: [ { uai: "0751234X", sources: ["dummy"], date_collecte: new Date(), }, ], }); await insertOrganisme({ siret: "33333333300003" }); const response = await httpClient.get("/api/v1/organismes?uai_potentiels=0751234J,0751234X"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 2); ok(response.data.organismes.find((o) => o.siret === "11111111100006")); ok(response.data.organismes.find((o) => o.siret === "22222222200002")); }); it("Vérifie qu'on peut rechercher des organismes qui ont des uais potentiels", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", uai_potentiels: [ { sources: ["dummy"], uai: "0751234J", date_collecte: new Date(), }, ], }); await insertOrganisme(); const response = await httpClient.get("/api/v1/organismes?uai_potentiels=true"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes qui n'ont pas uais potentiels", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", uai_potentiels: [ { sources: ["dummy"], uai: "0751234J", date_collecte: new Date(), }, ], }); await insertOrganisme({ siret: "22222222200002" }); const response = await httpClient.get("/api/v1/organismes?uai_potentiels=false"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "22222222200002"); }); it("Vérifie qu'on peut rechercher des organismes qui un type de relation", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", relations: [ { type: "responsable->formateur", siret: "33333333300003", label: "Organisme de formation", sources: ["aSource"], date_collecte: new Date(), referentiel: false, }, ], }); await insertOrganisme({ siret: "22222222200002" }); const response = await httpClient.get("/api/v1/organismes?relations=responsable->formateur"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes avec plusieurs type de relations", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", relations: [ { type: "responsable->formateur", siret: "33333333300003", label: "Organisme de formation", sources: ["aSource"], date_collecte: new Date(), referentiel: false, }, ], }); await insertOrganisme({ siret: "22222222200002", relations: [ { type: "formateur->responsable", siret: "44444444400004", label: "Organisme de formation", sources: ["aSource"], date_collecte: new Date(), referentiel: false, }, ], }); await insertOrganisme({ siret: "55555555500005" }); const response = await httpClient.get("/api/v1/organismes?relations=responsable->formateur,formateur->responsable"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 2); ok(response.data.organismes.find((o) => o.siret === "11111111100006")); ok(response.data.organismes.find((o) => o.siret === "22222222200002")); }); it("Vérifie qu'on peut rechercher des organismes qui ont des relations", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", relations: [ { type: "responsable->formateur", siret: "33333333300003", label: "Organisme de formation", sources: ["aSource"], date_collecte: new Date(), referentiel: false, }, ], }); await insertOrganisme(); const response = await httpClient.get("/api/v1/organismes?relations=true"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des organismes qui n'ont pas de relations", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", relations: [ { type: "responsable->formateur", siret: "33333333300003", label: "Organisme de formation", sources: ["aSource"], date_collecte: new Date(), referentiel: false, }, ], }); await insertOrganisme({ siret: "22222222200002" }); const response = await httpClient.get("/api/v1/organismes?relations=false"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "22222222200002"); }); it("Vérifie qu'on peut rechercher des organismes à partir d'un siret", async () => { const { httpClient } = await startServer(); await insertOrganisme(); await insertOrganisme({ siret: "11111111100001" }); const response = await httpClient.get("/api/v1/organismes?sirets=11111111100001"); strictEqual(response.status, 200); strictEqual(response.data.organismes[0].siret, "11111111100001"); }); it("Vérifie qu'on peut rechercher des organismes à partir de plusieurs sirets", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001" }); await insertOrganisme({ siret: "22222222200002" }); await insertOrganisme({ siret: "33333333300003" }); const response = await httpClient.get("/api/v1/organismes?sirets=11111111100001,22222222200002"); strictEqual(response.status, 200); const organismes = sortBy(response.data.organismes, (o) => o.siret); strictEqual(organismes.length, 2); strictEqual(organismes[0].siret, "11111111100001"); strictEqual(organismes[1].siret, "22222222200002"); }); it("Vérifie qu'on peut rechercher des organismes en fulltext (uai)", async () => { const { httpClient } = await startServer(); await insertOrganisme(); await insertOrganisme({ uai: "0010856A", }); const response = await httpClient.get("/api/v1/organismes?text=0010856A"); strictEqual(response.status, 200); strictEqual(response.data.organismes[0].uai, "0010856A"); }); it("Vérifie qu'on peut rechercher des organismes en fulltext (siret)", async () => { const { httpClient } = await startServer(); await insertOrganisme(); await insertOrganisme({ siret: "11111111100001", }); const response = await httpClient.get("/api/v1/organismes?text=11111111100001"); strictEqual(response.status, 200); strictEqual(response.data.organismes[0].siret, "11111111100001"); }); it("Vérifie qu'on peut rechercher des organismes à partir d'une académie", async () => { const { httpClient } = await startServer(); await Promise.all([ insertOrganisme({ siret: "11111111100001", adresse: { academie: { code: "01", nom: "Paris" }, }, }), insertOrganisme({ siret: "22222222200002", adresse: { academie: { code: "02", nom: "Aix-Marseille" }, }, }), ]); const response = await httpClient.get("/api/v1/organismes?academies=01"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100001"); }); it("Vérifie qu'on peut rechercher des organismes qui n'ont pas d'académie", async () => { const { httpClient } = await startServer(); await Promise.all([ insertOrganisme( { siret: "11111111100001", }, (o) => omit(o, ["adresse"]) ), insertOrganisme(), ]); const response = await httpClient.get("/api/v1/organismes?academies=false"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100001"); }); it("Vérifie qu'on peut rechercher des organismes qui ont une académie", async () => { const { httpClient } = await startServer(); await Promise.all([insertOrganisme({ siret: "11111111100001" }), insertOrganisme({}, (o) => omit(o, ["adresse"]))]); const response = await httpClient.get("/api/v1/organismes?academies=true"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100001"); }); it("Vérifie qu'on peut rechercher des organismes à partir de plusieurs académies", async () => { const { httpClient } = await startServer(); await Promise.all([ insertOrganisme({ siret: "11111111100001", adresse: { academie: { code: "01", nom: "Paris" }, }, }), insertOrganisme({ siret: "22222222200002", adresse: { academie: { code: "16", nom: "Toulouse" }, }, }), insertOrganisme({ siret: "33333333300003", adresse: { academie: { code: "02", nom: "Aix-Marseille" }, }, }), ]); const response = await httpClient.get("/api/v1/organismes?academies=01,16"); strictEqual(response.status, 200); const organismes = sortBy(response.data.organismes, (o) => o.siret); strictEqual(organismes.length, 2); strictEqual(organismes[0].siret, "11111111100001"); strictEqual(organismes[1].siret, "22222222200002"); }); it("Vérifie qu'on peut rechercher des organismes à partir d'une région", async () => { const { httpClient } = await startServer(); await Promise.all([ insertOrganisme({ siret: "11111111100001", adresse: { region: { code: "11", nom: "Île-de-France" }, }, }), insertOrganisme({ siret: "22222222200002", adresse: { region: { code: "93", nom: "Provence-Alpes-Côte d'Azur" }, }, }), ]); const response = await httpClient.get("/api/v1/organismes?regions=11"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100001"); }); it("Vérifie qu'on peut rechercher des organismes à partir de plusieurs régions", async () => { const { httpClient } = await startServer(); await Promise.all([ insertOrganisme({ siret: "11111111100001", adresse: { region: { code: "11", nom: "Île-de-France" }, }, }), insertOrganisme({ siret: "22222222200002", adresse: { region: { code: "76", nom: "Occitanie" }, }, }), insertOrganisme({ siret: "33333333300003", adresse: { region: { code: "93", nom: "Provence-Alpes-Côte d'Azur" }, }, }), ]); const response = await httpClient.get("/api/v1/organismes?regions=11,76"); strictEqual(response.status, 200); const organismes = sortBy(response.data.organismes, (o) => o.siret); strictEqual(organismes.length, 2); strictEqual(organismes[0].siret, "11111111100001"); strictEqual(organismes[1].siret, "22222222200002"); }); it("Vérifie qu'on peut rechercher des organismes à partir de leur département", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", adresse: { departement: { code: "75", nom: "Paris" }, }, }); await insertOrganisme({ siret: "22222222200002", adresse: { departement: { code: "11", nom: "Aude" }, }, }); const response = await httpClient.get("/api/v1/organismes?departements=11"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "22222222200002"); }); it("Vérifie qu'on peut rechercher des organismes à partir de plusieurs départements", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", adresse: { departement: { code: "75", nom: "Paris" }, }, }); await insertOrganisme({ siret: "22222222200002", adresse: { departement: { code: "11", nom: "Aude" }, }, }); const response = await httpClient.get("/api/v1/organismes?departements=11,75"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 2); }); it("Vérifie qu'on peut rechercher des organismes à partir d'une nature", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", nature: "responsable", }); await insertOrganisme({ siret: "22222222200002", nature: "formateur", }); const response = await httpClient.get("/api/v1/organismes?natures=formateur"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "22222222200002"); }); it("Vérifie qu'on peut rechercher des organismes responsable_formateur à partir de leur nature", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", nature: "responsable_formateur", }); await insertOrganisme({ siret: "22222222200002", nature: "formateur", }); const response = await httpClient.get("/api/v1/organismes?natures=responsable_formateur"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100001"); }); it("Vérifie qu'on peut rechercher des organismes à partir de plusieurs natures", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", nature: "responsable", }); await insertOrganisme({ siret: "22222222200002", nature: "responsable_formateur", }); await insertOrganisme({ siret: "333333333000003", nature: "formateur", }); const response = await httpClient.get("/api/v1/organismes?natures=formateur,responsable"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 2); ok(response.data.organismes.find((o) => o.siret === "11111111100001")); ok(response.data.organismes.find((o) => o.siret === "333333333000003")); }); it("Vérifie qu'on peut rechercher des organismes à partir d'un reseau", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", nature: "responsable", reseaux: [{ code: "reseau-1", label: "Reseau 1", sources: ["dummy"], date_collecte: new Date() }], }); await insertOrganisme({ siret: "22222222200002", nature: "formateur", }); const response = await httpClient.get("/api/v1/organismes?reseaux=reseau-1"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100001"); }); it("Vérifie qu'on peut rechercher des organismes à partir de plusieurs reseaux", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", reseaux: [{ code: "reseau-1", label: "Reseau 1", sources: ["dummy"], date_collecte: new Date() }], }); await insertOrganisme({ siret: "22222222200002", reseaux: [{ code: "reseau-2", label: "Reseau 2", sources: ["dummy"], date_collecte: new Date() }], }); await insertOrganisme({ siret: "333333333000003", nature: "formateur", }); const response = await httpClient.get("/api/v1/organismes?reseaux=reseau-1,reseau-2"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 2); ok(response.data.organismes.find((o) => o.siret === "11111111100001")); ok(response.data.organismes.find((o) => o.siret === "22222222200002")); }); it("Vérifie qu'on peut rechercher des organismes avec un référentiel dans lequel ils apparaissent", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", referentiels: ["ref1"], }); await insertOrganisme({ siret: "22222222200002", referentiels: ["ref2"], }); const response = await httpClient.get("/api/v1/organismes?referentiels=ref1"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); ok(response.data.organismes.find((o) => o.siret === "11111111100001")); }); it("Vérifie qu'on peut rechercher des organismes avec des référentiels dans lequel ils apparaissent", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", referentiels: ["ref1"], }); await insertOrganisme({ siret: "22222222200002", referentiels: ["ref2"], }); await insertOrganisme({ siret: "333333333000003", referentiels: ["ref3"], }); const response = await httpClient.get("/api/v1/organismes?referentiels=ref1,ref3"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 2); ok(response.data.organismes.find((o) => o.siret === "11111111100001")); ok(response.data.organismes.find((o) => o.siret === "333333333000003")); }); it("Vérifie qu'on peut rechercher des organismes qui n'apparaissent pas dans un référentiel", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", referentiels: ["ref1"], }); await insertOrganisme({ siret: "22222222200002", referentiels: ["ref2"], }); await insertOrganisme({ siret: "333333333000003", referentiels: ["ref3"], }); const response = await httpClient.get("/api/v1/organismes?referentiels=-ref2,ref1"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); ok(response.data.organismes.find((o) => o.siret === "11111111100001")); }); it("Vérifie qu'on peut limiter les champs renvoyés pour la liste des organismes", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", raison_sociale: "Centre de formation", _meta: { anomalies: [], date_import: new Date("2021-02-10T16:39:13.064Z"), }, }); const response = await httpClient.get("/api/v1/organismes?champs=siret,raison_sociale"); strictEqual(response.status, 200); deepStrictEqual(response.data, { organismes: [ { siret: "11111111100001", raison_sociale: "Centre de formation", }, ], pagination: { page: 1, resultats_par_page: 10, nombre_de_page: 1, total: 1, }, }); }); it("Vérifie qu'on peut peut limiter le nombre d'organisme par page", async () => { const { httpClient } = await startServer(); await Promise.all([ insertOrganisme({ siret: "11111111100001" }), insertOrganisme({ siret: "22222222200002" }), insertOrganisme({ siret: "33333333300008" }), ]); let response = await httpClient.get("/api/v1/organismes?items_par_page=1&page=1"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); response = await httpClient.get("/api/v1/organismes?items_par_page=1&page=2"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); }); it("Vérifie qu'on peut filtrer les organismes avec des anomalies", async () => { const { httpClient } = await startServer(); await Promise.all([ insertOrganisme({ siret: "11111111100001", _meta: { anomalies: [ { key: "123456", type: "dummy", sources: ["test"], job: "collect", date_collecte: new Date("2021-02-10T08:31:58.572Z"), }, ], }, }), insertOrganisme({ siret: "22222222200002", }), ]); let response = await httpClient.get("/api/v1/organismes?anomalies=true"); strictEqual(response.status, 200); strictEqual(response.data.organismes[0].siret, "11111111100001"); response = await httpClient.get("/api/v1/organismes?anomalies=false"); strictEqual(response.status, 200); strictEqual(response.data.organismes[0].siret, "22222222200002"); response = await httpClient.get("/api/v1/organismes"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 2); }); it("Vérifie qu'on peut trier les résultats (asc)", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", _meta: { anomalies: [], date_import: new Date("2021-02-10T16:39:13.064Z"), }, }); await insertOrganisme({ siret: "22222222200002", _meta: { anomalies: [], date_import: new Date("2020-02-10T16:39:13.064Z"), }, }); const response = await httpClient.get("/api/v1/organismes?ordre=asc"); strictEqual(response.status, 200); strictEqual(response.data.organismes[0].siret, "22222222200002"); strictEqual(response.data.organismes[1].siret, "11111111100001"); }); it("Vérifie qu'on peut trier les résultats (desc)", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", _meta: { anomalies: [], date_import: new Date("2021-02-10T16:39:13.064Z"), }, }); await insertOrganisme({ siret: "22222222200002", _meta: { anomalies: [], date_import: new Date("2020-02-10T16:39:13.064Z"), }, }); const response = await httpClient.get("/api/v1/organismes?ordre=desc"); strictEqual(response.status, 200); strictEqual(response.data.organismes[0].siret, "11111111100001"); strictEqual(response.data.organismes[1].siret, "22222222200002"); }); it("Vérifie que le service retourne une liste vide quand aucun organisme ne correspond", async () => { const { httpClient } = await startServer(); const response = await httpClient.get("/api/v1/organismes?text=XXX"); strictEqual(response.status, 200); deepStrictEqual(response.data, { organismes: [], pagination: { page: 1, resultats_par_page: 10, nombre_de_page: 1, total: 0, }, }); }); it("Vérifie que le service retourne une 400 quand les paramètres sont inconnus", async () => { const { httpClient } = await startServer(); const response = await httpClient.get("/api/v1/organismes?invalid=XXX"); strictEqual(response.status, 400); deepStrictEqual(response.data.details[0].path[0], "invalid"); }); it("Vérifie que le service retourne une 400 quand les paramètres sont invalides", async () => { const { httpClient } = await startServer(); const response = await httpClient.get("/api/v1/organismes?ordre=-1"); strictEqual(response.status, 400); deepStrictEqual(response.data.details[0].path[0], "ordre"); }); it("Vérifie qu'on peut obtenir un organisme", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", raison_sociale: "Centre de formation", _meta: { anomalies: [], date_import: new Date("2021-02-10T16:39:13.064Z"), date_dernier_import: new Date("2021-02-10T16:39:13.064Z"), }, }); const response = await httpClient.get("/api/v1/organismes/11111111100001"); strictEqual(response.status, 200); deepStrictEqual(response.data, { siret: "11111111100001", raison_sociale: "Centre de formation", nature: "inconnue", uai_potentiels: [], contacts: [], relations: [], reseaux: [], lieux_de_formation: [], diplomes: [], certifications: [], siege_social: true, etat_administratif: "actif", referentiels: ["test"], adresse: { geojson: { type: "Feature", geometry: { type: "Point", coordinates: [2.396444, 48.879706], }, properties: { score: 0.88, }, }, label: "31 rue des lilas Paris 75019", code_postal: "75001", code_insee: "75000", localite: "PARIS", departement: { code: "75", nom: "Paris", }, region: { code: "11", nom: "Île-de-France", }, academie: { code: "01", nom: "Paris", }, }, _meta: { anomalies: [], date_import: "2021-02-10T16:39:13.064Z", date_dernier_import: "2021-02-10T16:39:13.064Z", nouveau: false, }, }); }); it("Vérifie qu'on peut limiter les champs renvoyés pour un organisme", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", raison_sociale: "Centre de formation", _meta: { anomalies: [], date_import: new Date("2021-02-10T16:39:13.064Z"), }, }); const response = await httpClient.get("/api/v1/organismes/11111111100001?champs=siret,raison_sociale"); strictEqual(response.status, 200); deepStrictEqual(response.data, { siret: "11111111100001", raison_sociale: "Centre de formation", }); }); it("Vérifie qu'on renvoie une 404 si le siret n'est pas connu", async () => { const { httpClient } = await startServer(); const response = await httpClient.get("/api/v1/organismes/11111111100001"); strictEqual(response.status, 404); deepStrictEqual(response.data, { error: "Not Found", message: "Siret inconnu", statusCode: 404, }); }); it("Vérifie qu'on peut mettre à jour un organisme", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", uai: "0751234X", raison_sociale: "Centre de formation", adresse: { region: { code: "11", nom: "Île-de-France" }, }, }); const response = await httpClient.put( "/api/v1/organismes/11111111100001/setUAI", { uai: "0751234J" }, { headers: { ...generateAuthHeader("region", "11"), }, } ); strictEqual(response.status, 200); deepStrictEqual(response.data.siret, "11111111100001"); deepStrictEqual(response.data.uai, "0751234J"); deepStrictEqual( omitDeep(response.data, () => ["date_import", "date_dernier_import"]), { siret: "11111111100001", uai: "0751234J", nature: "inconnue", raison_sociale: "Centre de formation", uai_potentiels: [], contacts: [], relations: [], lieux_de_formation: [], reseaux: [], diplomes: [], certifications: [], siege_social: true, etat_administratif: "actif", referentiels: ["test"], adresse: { geojson: { type: "Feature", geometry: { type: "Point", coordinates: [2.396444, 48.879706], }, properties: { score: 0.88, }, }, label: "31 rue des lilas Paris 75019", code_postal: "75001", code_insee: "75000", localite: "PARIS", departement: { code: "75", nom: "Paris", }, region: { code: "11", nom: "Île-de-France", }, academie: { code: "01", nom: "Paris", }, }, _meta: { anomalies: [], nouveau: false, }, } ); const found = await dbCollection("organismes").findOne({ siret: "11111111100001" }); deepStrictEqual(found.uai, "0751234J"); const { date, ...modification } = await dbCollection("modifications").findOne({}, { projection: { _id: 0 } }); assert.ok(date); deepStrictEqual(modification, { siret: "11111111100001", auteur: "region-11", original: { uai: "0751234X", }, changements: { uai: "0751234J", }, }); }); it("Vérifie qu'on peut valider une UAI (academie)", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", raison_sociale: "Centre de formation", adresse: { academie: { code: "01", nom: "Paris" }, }, }); const response = await httpClient.put( "/api/v1/organismes/11111111100001/setUAI", { uai: "0751234J" }, { headers: { ...generateAuthHeader("academie", "01"), }, } ); strictEqual(response.status, 200); deepStrictEqual(response.data.siret, "11111111100001"); deepStrictEqual(response.data.uai, "0751234J"); }); it("Vérifie qu'on retourne une erreur si l'UAI est liée à un siret inconnu", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", raison_sociale: "Centre de formation", adresse: { region: { code: "11", nom: "Île-de-France" }, }, }); const response = await httpClient.put( "/api/v1/organismes/22222222200002/setUAI", { uai: "0751234J" }, { headers: { ...generateAuthHeader("region", "11"), }, } ); strictEqual(response.status, 400); }); it("Vérifie qu'on retourne une erreur si l'UAI est liée à un siret d'une autre région", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", raison_sociale: "Centre de formation", adresse: { region: { code: "76", nom: "Occitanie" }, }, }); const response = await httpClient.put( "/api/v1/organismes/22222222200002/setUAI", { uai: "0751234J" }, { headers: { ...generateAuthHeader("region", "76"), }, } ); strictEqual(response.status, 400); }); it("Vérifie qu'on retourne une erreur si l'UAI est liée à un siret d'une autre académie", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001", raison_sociale: "Centre de formation", adresse: { academie: { code: "01", nom: "Paris" }, }, }); const response = await httpClient.put( "/api/v1/organismes/22222222200002/setUAI", { uai: "0751234J" }, { headers: { ...generateAuthHeader("academie", "11"), }, } ); strictEqual(response.status, 400); }); it("Vérifie qu'on peut rechercher des nouveaux organismes", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", _meta: { date_import: new Date(), }, }); await insertOrganisme({ siret: "22222222200006", _meta: { date_import: DateTime.fromISO("1999-03-01").toJSDate(), }, }); const response = await httpClient.get("/api/v1/organismes?nouveaux=true"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "11111111100006"); }); it("Vérifie qu'on peut rechercher des anciens organismes", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", _meta: { date_import: new Date(), }, }); await insertOrganisme({ siret: "22222222200006", _meta: { date_import: DateTime.fromISO("1999-03-01").toJSDate(), }, }); const response = await httpClient.get("/api/v1/organismes?nouveaux=false"); strictEqual(response.status, 200); strictEqual(response.data.organismes.length, 1); strictEqual(response.data.organismes[0].siret, "22222222200006"); }); it("Vérifie qu'on peut obtenir les résultats au format CSV", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", raison_sociale: "Centre de formation", uai_potentiels: [ { sources: ["dummy"], uai: "0751234J", date_collecte: new Date(), }, { sources: ["sifa-ramsese"], uai: "0751234X", date_collecte: new Date(), }, ], _meta: { date_import: DateTime.fromISO("2022-03-20").toJSDate(), }, }); const response = await httpClient.get("/api/v1/organismes.csv"); strictEqual(response.status, 200); strictEqual( response.data, `Siret;UAI validée;Raison sociale;Enseigne;numero_declaration_activite;etat_administratif;Nature;Adresse;Académie;Région;Qualiopi;Réseaux;Nombre de relations;Nombre de lieux de formation;Date d'import;UAI probable;UAI potentielle 1;UAI potentielle 2;UAI potentielle 3;UAI potentielle 4;UAI potentielle 5;UAI potentielle 6;UAI potentielle 7;UAI potentielle 8;UAI potentielle 9;UAI potentielle 10;UAI potentielle 11;UAI potentielle 12;UAI potentielle 13;UAI potentielle 14;UAI potentielle 15;UAI potentielle 16;UAI potentielle 17;UAI potentielle 18;UAI potentielle 19;UAI potentielle 20;UAI potentielle 21;UAI potentielle 22;UAI potentielle 23;UAI potentielle 24;UAI potentielle 25;UAI potentielle 26;UAI potentielle 27;UAI potentielle 28;UAI potentielle 29;UAI potentielle 30;UAI potentielle 31;UAI potentielle 32;UAI potentielle 33;UAI potentielle 34;UAI potentielle 35;UAI potentielle 36;UAI potentielle 37;UAI potentielle 38;UAI potentielle 39;UAI potentielle 40;UAI potentielle 41;UAI potentielle 42;UAI potentielle 43;UAI potentielle 44;UAI potentielle 45;UAI potentielle 46;UAI potentielle 47;UAI potentielle 48;UAI potentielle 49;UAI potentielle 50;UAI potentielle 51;UAI potentielle 52;UAI potentielle 53;UAI potentielle 54;UAI potentielle 55;UAI potentielle 56;UAI potentielle 57;UAI potentielle 58;UAI potentielle 59;UAI potentielle 60 11111111100006;;Centre de formation;;;actif;inconnue;31 rue des lilas Paris 75019;Paris;Île-de-France;Non;;0;0;2022-03-20;0751234X;0751234J;0751234X;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ` ); }); it("Vérifie qu'on peut obtenir les résultats au format CSV (compatible XLS)", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100006", raison_sociale: "Centre de formation", uai_potentiels: [ { sources: ["dummy"], uai: "0751234J", date_collecte: new Date(), }, { sources: ["sifa-ramsese"], uai: "0751234X", date_collecte: new Date(), }, ], _meta: { date_import: DateTime.fromISO("2022-03-20").toJSDate(), }, }); const response = await httpClient.get("/api/v1/organismes.xls"); strictEqual(response.status, 200); const decoded = iconv.decode(response.data, "UTF-16"); assert.ok(decoded.indexOf('="Siret"\t') !== -1); }); it("Vérifie qu'on peut chercher des organismes via la méthode POST", async () => { const { httpClient } = await startServer(); await insertOrganisme({ siret: "11111111100001" }); await insertOrganisme({ siret: "22222222200006" }); const response = await httpClient.post("/api/v1/organismes", { sirets: "11111111100001", champs: "siret" }); strictEqual(response.status, 200); deepStrictEqual(response.data, { organismes: [{ siret: "11111111100001" }], pagination: { page: 1, resultats_par_page: 10, nombre_de_page: 1, total: 1, }, }); }); });
import React, { useState } from "react"; import Visibility from "@mui/icons-material/Visibility"; import VisibilityOff from "@mui/icons-material/VisibilityOff"; import styles from "../styles/login.module.scss"; import Box from "@mui/material/Box"; import IconButton from "@mui/material/IconButton"; import OutlinedInput from "@mui/material/OutlinedInput"; import InputLabel from "@mui/material/InputLabel"; import InputAdornment from "@mui/material/InputAdornment"; import FormControl from "@mui/material/FormControl"; import TextField from "@mui/material/TextField"; import { Button } from "@mui/material"; import PersonIcon from "@mui/icons-material/Person"; import { useFormik } from "formik"; import Stack from "@mui/material/Stack"; import Snackbar from "@mui/material/Snackbar"; import MuiAlert from "@mui/material/Alert"; import { baseurl } from "../utility/auth"; import { useRouter } from "next/router"; const Alert = React.forwardRef(function Alert(props, ref) { return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />; }); export default function Login() { const router = useRouter(); //login //---- snackbar--- const [open, setOpen] = React.useState(""); const handleSnackClick = () => { // setOpen(true); }; const handleSnackClose = (event, reason) => { if (reason === "clickaway") { return; } setOpen(false); }; //---snackbar-- const [values, setValues] = useState({ password: "", showPassword: false, }); // const handleChange = (prop) => (event) => { // setValues({ ...values, [prop]: event.target.value }); // }; const handleClickShowPassword = () => { setValues({ ...values, showPassword: !values.showPassword, }); }; const handleMouseDownPassword = (event) => { event.preventDefault(); }; // formik function const validate = (values) => { const errors = {}; if (values.email === "") { errors.email = "Enter Valid Email"; } if (values.password === "") { errors.password = "Enter valide password"; } return errors; }; const formik = useFormik({ initialValues: { email: "a1@yourdaily.com", password: "1234", }, validate, onSubmit: async (values) => { try { let result = await fetch(`${baseurl}/api/sm-login`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(values), }); if (result.status === 200) { let result2 = await result.json(); console.log(result2); localStorage.setItem("token", result2.Authorization); router.push("/dashboard"); } else { setOpen("Invalid Credentials"); } } catch (response) {} }, }); return ( <div className={styles.mainContainer}> <Stack spacing={2} sx={{ width: "100%" }}> <div className={styles.logo}> <img src="/assets/ydlogo.svg" alt="This is logo" /> </div> <div className={styles.container}> <div className={styles.imageContainer}> <img src="/assets/Illustrator 1.png" alt="This" /> </div> <div className={styles.card}> <div sx={{ minWidth: 275 }}> <div> <h2>LOGIN</h2> <p className={styles.pleaseLogin}> Please login to your account </p> </div> <Box sx={{ display: "flex", flexDirection: "column", flexWrap: "wrap", }} > <form className={styles.credentials} onSubmit={formik.handleSubmit} > <TextField label="User ID" id="outlined-start-adornment" name="email" value={formik.values.email} onChange={formik.handleChange} error={formik.touched.email && Boolean(formik.errors.email)} sx={{ m: 1, width: "25ch" }} InputProps={{ endAdornment: ( <InputAdornment position="end"> <PersonIcon /> </InputAdornment> ), }} variant="outlined" /> <FormControl sx={{ m: 1, width: "25ch" }} variant="outlined"> <InputLabel htmlFor="outlined-adornment-password"> Password </InputLabel> <OutlinedInput id="outlined-adornment-password" type={values.showPassword ? "text" : "password"} name="password" value={formik.values.password} onChange={formik.handleChange} error={ formik.touched.password && Boolean(formik.errors.password) } label="Password" // sx={{ m: 1, width: "25ch" }} endAdornment={ <InputAdornment position="end"> <IconButton aria-label="toggle password visibility" onClick={handleClickShowPassword} onMouseDown={handleMouseDownPassword} edge="end" > {values.showPassword ? ( <VisibilityOff /> ) : ( <Visibility /> )} </IconButton> </InputAdornment> } /> </FormControl> <div className={styles.loginbtnContainer}> <Button type="submit" className={styles.loginbutton} variant="contained" onClick={handleSnackClick} > Login </Button> </div> </form> <a href="#" className={styles.forgotpwd}> Forgot Password? </a> </Box> </div> </div> </div> <Snackbar open={!!open} anchorOrigin={{ vertical: "top", horizontal: "center" }} autoHideDuration={3000} onClose={handleSnackClose} > <Alert onClose={handleSnackClose} severity="error" sx={{ width: "100%" }} > {open} </Alert> </Snackbar> {/* <Alert severity="error">This is an error message!</Alert> */} {/* <Alert severity="success">This is a success message!</Alert> */} </Stack> </div> ); }
/** * Protocol description for the lightsync protocol * Authentication is done using TLS it is not included in the protobuf * protocol! **/ package light; enum ShareAction { ENTERING = 0; LEAVING = 1; } enum FileAction { CREATED = 0; UPDATED = 1; REMOVED = 2; } message ShareMessage { required string share_name = 1; required ShareAction action = 2; } message PeerMessage { required string peer_name = 1; //Contains the SHA1 hash of the peer's public key required string address = 2; //IP address as a string required string port = 3; //Port as a string repeated string shares = 4; //A list of shares for this peer } message FileMessage { required string filename = 1; required string share_name = 2; required bool folder = 3; required FileAction action = 4; optional bytes hash = 5; }
<?xml version="1.0" encoding="utf-8" ?> <!--vgl. CodeBehind, App.xaml, Resources/Styles/Colors.xaml--> <ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:sys="clr-namespace:System;assembly=System.Runtime" x:Class="MauiKurs.Resources_Styles" Title="Resources_Styles"> <!--Über die Ressourcen von App/Window/Container können für die entsprechende Range Daten zur Verfügung gestellt werden. Die Verbindung von Properties zu diesen Resourcen wird dann über eine StaticResource-Bindung hergestellt. Alternativ kann eine DynamicRessource-Bindung erstellt werden, wodurch die gebundene Property auf Veränderungen an der Ressource durch den CodeBehind reagiert.--> <VerticalStackLayout x:Name="Sly_Main"> <VerticalStackLayout.Resources> <!--Jede Ressource benötigt zur eindeutigen Identifizierung einen x:Key, welcher pro Resource-Eigenschaft einmalig sein muss. Kommt der gleiche Key in mehrfach vor, wird die Resource verwendent, welche näher am Verwender liegt.--> <x:Double x:Key="Dbl_FontSize">25.0</x:Double> <Color x:Key="Primary">#FFE4F6</Color> <!--Mit Styles konnen Sammlungen Propertes einzelner Controls und Container gebündelt vordefiniert werden. Erhält ein Style einen Key, erhalten alle derartigen Elemente, welche den Style in ihrer Style-Property angeben, diesen Style. Wenn ein Style keinen Key hat, wird er zum Standartlayout derartiger Elemente in der gewählten Range. Lokale Property-Werte haben Vorang vor den Styles.--> <Style TargetType="Label"> <Setter Property="FontSize" Value="20"/> <Setter Property="BackgroundColor" Value="LightGreen"/> <Setter Property="FontFamily" Value="Comic Sans MS"/> <Setter Property="TextColor" Value="Red"/> </Style> <Style TargetType="Label" x:Key="Sty_Lbl_01"> <Setter Property="FontSize" Value="{StaticResource Dbl_FontSize}"/> <Setter Property="BackgroundColor" Value="{StaticResource Gray300}"/> </Style> <!--Mittels der BaseOn-Property kann ein Style alles Propeties eines anderen Styles erben.--> <Style TargetType="Label" x:Key="Sty_Lbl_02" BasedOn="{StaticResource Sty_Lbl_01}"> <Setter Property="FontFamily" Value="Arial"/> </Style> </VerticalStackLayout.Resources> <DatePicker Date="{x:Static sys:DateTime.Now}"/> <!--Eine Anbindung an Ressourcen erfolgt entweder über eine StaticResource-Bindung, welche den Wert einmalig einholt--> <!--oder über eine DynamicResource-Bindung, welche permanent nach Veränderungen sucht und diese übernimmt--> <!--Die x:Static-Bindung ist ebenfalls eine statische Ressourcen-Bindung, welche für Anbindung an 'Nicht-XAML'-Ressourcen. Sie kann zum Beispiel (wie hier) für Bindungen C#-Konstanten verwendet werden--> <!--Dieses Label übernimmt den globalen Style--> <Label Text="HALLO" FontSize="{x:Static sys:Math.PI}"/> <Label Text="Moin Moin" FontSize="{StaticResource Dbl_FontSize}" BackgroundColor="{StaticResource Primary}"/> <Button Text="Change" x:Name="Btn_Change" Clicked="Btn_Change_Clicked" BackgroundColor="{DynamicResource Primary}"/> <Label Text="HALLO" TextColor="Blue"/> <Label Text="HALLO"/> <!--Dieses Label übernimmt den spezifischen Style--> <Label Text="HALLO" Style="{StaticResource Sty_Lbl_02}"/> <Label Text="HALLO" Style="{StaticResource Sty_Lbl_01}"/> </VerticalStackLayout> </ContentPage>
import os import time import pyfiglet import inquirer from yaspin import yaspin from colorama import just_fix_windows_console, Fore, Style class CLIUtils: """ This class contains utility functions for handling command-line interactions. """ def __init__(self) -> None: just_fix_windows_console() self.spinner = yaspin def display_title(self): title = pyfiglet.figlet_format("Image DC ++", font="big") print(Fore.RED + title + Style.RESET_ALL) def get_text_input(self, qname, qmsg): questions = [inquirer.Text(qname, qmsg)] answers = inquirer.prompt(questions) return answers[qname] def get_multi_choice_input(self, qname, qmsg, choices): questions = [ inquirer.List( qname, message=qmsg, choices=choices, ), ] answers = inquirer.prompt(questions) return answers[qname] def get_path(self, qname, qmsg): questions = [ inquirer.Path( qname, message=qmsg, path_type=inquirer.Path.ANY, ), ] answers = inquirer.prompt(questions) return os.path.abspath(answers[qname]) def get_selected_items(self, qname, qmsg, choices): questions = [ inquirer.Checkbox( qname, message=qmsg, choices=choices, ), ] answers = inquirer.prompt(questions) return answers[qname] def log_message(self, message): print("[-] LOG: " + message) def log_warning(self, message): print( "[" + Fore.YELLOW + "!" + Style.RESET_ALL + "] WARNING: " + message + Style.RESET_ALL ) def log_error(self, message): print( "[" + Fore.RED + "X" + Style.RESET_ALL + "]" + Fore.RED + " ERROR: " + message + Style.RESET_ALL ) self.wait(0.5) def wait(self, seconds=1): time.sleep(seconds)
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:p="http://primefaces.org/ui" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:f="http://xmlns.jcp.org/jsf/core"> <h:head> <title>Productos</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <h:outputStylesheet name="css/primeflex.min.css" /> <style type="text/css"> .product-item .product-item-content { border: 1px solid var(--surface-d); border-radius: 3px; margin: .3rem; text-align: center; padding: 2rem 0; } .product-item .product-image { width: 50%; box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23) } body { height: 400px; background-image: url("https://i.imgur.com/n8uEpN6.jpg"); background-size: cover; background-repeat:no-repeat; background-position: center center; } </style> </h:head> <h:body > <div class="p-grid"> <div class="p-col"></div> <div class="p-col"></div> <div class="p-col"><p:graphicImage name="Softwash.png" style="max-width: 640px;" library="img"/></div> <div class="p-col"></div> <div class="p-col"></div> </div> <ui:include src="barraMenu.xhtml"></ui:include> <br/> <div class="product card"> <h:form> <p:dataScroller value="#{dato.products}" var="product" chunkSize="10"> <f:facet name="loader"> <div class="p-text-center"> <p:commandButton type="button" value="More" icon="pi pi-refresh"/> </div> </f:facet> <div class="product"> <div class="product-list-item p-p-5"> <p:graphicImage name="demo/images/product/#{product.image}"/> <div class="product-list-detail"> <div class="product-name">#{product.name}</div> <div class="product-description">#{product.description}</div> <p:rating readonly="true" value="#{product.rating}"/> <i class="pi pi-tag product-category-icon"/><span class="product-category">#{product.category}</span> </div> <div class="product-list-action"> <h:outputText value="#{product.price}" styleClass="product-price"> <f:convertNumber currencySymbol="$" type="currency"/> </h:outputText> <p:commandButton value="Add To Cart" icon="pi pi-shopping-cart" disabled="#{product.inventoryStatus == 'OUTOFSTOCK'}"> </p:commandButton> <span class="product-badge status-#{product.inventoryStatus.name().toLowerCase()}">#{product.inventoryStatus.text}</span> </div> </div> </div> </p:dataScroller> </h:form> </div> </h:body> </html>
import React, {PropsWithChildren} from 'react'; import {StyleSheet, Text, TextStyle} from 'react-native'; import {TextTypes, Theme} from '../../constants/Types'; import {useTheme} from '../../context/theme/useTheme'; interface BaseCustomTextProps extends PropsWithChildren { title: string; type: TextTypes; style?: TextStyle; onPress?: () => void; bold?: boolean; numberOfLines?: number; } function BaseCustomText({ title, type, style, onPress, bold, numberOfLines, }: BaseCustomTextProps): JSX.Element { const {theme} = useTheme(); return ( <Text numberOfLines={numberOfLines} onPress={onPress} style={[ styles(theme)[type], bold && styles(theme).bold, styles(theme).text, style, ]}> {title} </Text> ); } export default BaseCustomText; const styles = (theme: Theme) => StyleSheet.create({ h1: { fontSize: theme.sizes.text.h1, color: theme.colors.text_color, }, h2: { fontSize: theme.sizes.text.h2, color: theme.colors.text_color, }, p1: { fontSize: theme.sizes.text.p1, color: theme.colors.text_color, }, p2: { fontSize: theme.sizes.text.p2, color: theme.colors.text_color, }, p3: { fontSize: theme.sizes.text.p3, color: theme.colors.text_color, }, p4: { fontSize: theme.sizes.text.p4, color: theme.colors.text_color, }, error: { fontSize: theme.sizes.text.p1, color: theme.colors.negative, }, bold: { fontWeight: 'bold', }, text: { lineHeight: 24, fontWeight: '200', textAlign: 'justify', }, });
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <string.h> // *** WRITE_END --> 1 , READ_END --> 0 , didn't define for ease // Define the student structure struct student { int roll; char name[100]; void *data_p; // void pointer , will point to the data_size field int data_size; }; // Function to fill up the student structures and send them to child process // parent process will execute void fill_and_send(int n, int pipe_write_fd) { struct student ss[100]; for (int i = 0; i < n; i++) { printf("Enter roll number for student %d: ", i + 1); scanf("%d", &ss[i].roll); printf("Enter name for student %d: ", i + 1); scanf("%s", ss[i].name); // Allocate memory for additional information // we will be giving department name for additional info printf("Enter size of department name (additional info) for student %d: ", i + 1); scanf("%d", &ss[i].data_size); // The malloc() function allocates size bytes and returns a pointer to the allocated memory ss[i].data_p = malloc(ss[i].data_size); if (ss[i].data_p == NULL) { perror("malloc failed , space not allocated"); exit(1); } printf("Enter department name (additional info) for student %d: ", i + 1); scanf("%s", (char *)ss[i].data_p); } // Write student structures to pipe write(pipe_write_fd, ss, sizeof(struct student) * n); } // Function to read student structures, sort them, and send back to parent process // child process will execute that void receive_sort_and_send(int n, int pipe_read_fd, int pipe_write_fd) { struct student ss[100]; // Read student structures from pipe read(pipe_read_fd, ss, sizeof(struct student) * n); // Sorting student structures based on roll number (using bubble sort) for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (ss[j].roll > ss[j + 1].roll) { // Swap struct student temp = ss[j]; ss[j] = ss[j + 1]; ss[j + 1] = temp; } } } // Write sorted student structures back to parent process write(pipe_write_fd, ss, sizeof(struct student) * n); } // Function to receive and print student structures // parent process(P1) executes it after receiving it from child (P2) void receive_and_print(int n, int pipe_read_fd) { struct student ss[100]; // Read sorted student structures from pipe read(pipe_read_fd, ss, sizeof(struct student) * n); // Print student information printf("Sorted student information:\n"); for (int i = 0; i < n; i++) { printf("Roll: %d, Name: %s, department Name (Add. Info): %s\n", ss[i].roll, ss[i].name, (char *)ss[i].data_p); // Free memory allocated for additional information free(ss[i].data_p); } } int main() { int n; // num of students printf("Enter the number of students: "); scanf("%d", &n); // SINCE WE NEED 2 PIPES int pipefd1[2], pipefd2[2]; if (pipe(pipefd1) == -1 || pipe(pipefd2) == -1) // i.e. <0 { perror("pipe not created"); exit(1); } // creating child process pid_t pid = fork(); if (pid == -1) // i.e. pid < 0 { perror("fork failed "); exit(1); } if (pid == 0) // Child process , which will tread from pipe1 , write in pipe2 { // closing unused ends of pipes ... close(pipefd1[1]); // Close write end of pipe 1 close(pipefd2[0]); // Close read end of pipe 2 receive_sort_and_send(n, pipefd1[0], pipefd2[1]); close(pipefd1[0]); close(pipefd2[1]); exit(1); } else // pid > 0 // Parent process which writes in pipe1 , reads from pipe2 { close(pipefd1[0]); // Close read end of pipe 1 close(pipefd2[1]); // Close write end of pipe 2 fill_and_send(n, pipefd1[1]); receive_and_print(n, pipefd2[0]); close(pipefd1[1]); close(pipefd2[0]); wait(NULL); // suspends execution until one of its child processes terminates exit(1); } return 0; }
import _ from 'lodash' import { fakerEN_GB as faker } from '@faker-js/faker' import { PATIENT_OUTCOME } from '../enums.js' import getChild from './child.js' import getResponse from './response.js' import { getYearGroup } from './year-group.js' /** * @typedef {object} Patient * @property {string} nhsNumber - NHS number * @property {string} address - Address * @property {object} yearGroup - Response method * @property {[import('./response.js').Response]} responses - Parent * @property {object} consent - Consent outcome * @property {string} outcome - Overall patient outcome * @property {object} [seen] - Seen offline * @property {object} triage - Triage outcome */ /** * @private * @param {object} options - Patient options * @returns {Patient} Patient record */ const _getPatient = (options) => { const { minYearGroup, maxYearGroup, type } = options const patient = getChild(minYearGroup, maxYearGroup) let responses = faker.helpers.multiple(getResponse(type, patient), { count: { min: 0, max: 3 } }) responses = _.uniqBy(responses, 'parentOrGuardian.relationship') // https://digital.nhs.uk/services/e-referral-service/document-library/synthetic-data-in-live-environments patient.nhsNumber = faker.helpers.replaceSymbolWithNumber('999#######') patient.yearGroup = getYearGroup(patient.dob) patient.responses = responses patient.consent = { events: [] } patient.outcome = PATIENT_OUTCOME.NO_OUTCOME_YET patient.seen = {} patient.triage = { events: [] } // Mark 50% of records as ready for triaged patient.__triageOutcome = faker.helpers.maybe(() => true, { probability: 0.5 }) return patient } export default (options) => { const patient = () => ({ ..._getPatient(options) }) return patient }
package com.momentodos.proyectoclases.service import com.momentodos.proyectoclases.model.DetailModel import com.momentodos.proyectoclases.repository.DetailRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.stereotype.Service import org.springframework.web.server.ResponseStatusException @Service class DetailService { @Autowired lateinit var modeloRepository: DetailRepository fun list ():List<DetailModel>{ return modeloRepository.findAll() } fun save(modelo: DetailModel): DetailModel { try{ modelo.price?.takeIf { it.trim().isNotEmpty()} ?:throw ResponseStatusException(HttpStatus.BAD_REQUEST, "La materia no debe ser nula") return modeloRepository.save(modelo) } catch (ex:Exception){ throw ResponseStatusException(HttpStatus.BAD_REQUEST,ex.message) } } fun update(modelo: DetailModel): DetailModel { try { modeloRepository.findById(modelo.id) ?: throw Exception("ID no existe") return modeloRepository.save(modelo) } catch (ex:Exception){ throw ResponseStatusException(HttpStatus.NOT_FOUND,ex.message) } } fun listById (id:Long?): DetailModel?{ return modeloRepository.findById(id) } fun delete (id: Long?):Boolean?{ try{ val response = modeloRepository.findById(id) ?: throw Exception("ID no disponible por hoy") modeloRepository.deleteById(id!!) return true } catch (ex:Exception){ throw ResponseStatusException(HttpStatus.NOT_FOUND,ex.message) } } fun updateName(modelo: DetailModel): DetailModel { try{ val response = modeloRepository.findById(modelo.id) ?: throw Exception("ID no existe") response.apply { id=modelo.id price=modelo.price } return modeloRepository.save(response) } catch (ex:Exception){ throw ResponseStatusException(HttpStatus.NOT_FOUND,ex.message) } } }
import { FC, useEffect, useState } from "react"; import { Controller, useForm } from "react-hook-form"; import { doc, updateDoc } from "firebase/firestore"; import { db } from "./../firebase"; import { CircularProgress, FormControl, FormHelperText, InputLabel, MenuItem, Select, Snackbar, TextField, } from "@mui/material"; import { UserAuth } from "../context/AuthContext"; const PersonalDetails: FC = () => { const handleSnackbarClose = () => { setSnackbarOpen(false); }; const { handleSubmit, setValue, control } = useForm({ defaultValues: { gender: "", age: 0, height: 0, weight: 0, bmi: 0, }, }); const [error, setError] = useState<string | null>(null); const [snackbarOpen, setSnackbarOpen] = useState(false); const [bmi, setBMI] = useState<number | null>(null); const [loading, setLoading] = useState(true); const { userData, user, fetchUserData } = UserAuth(); useEffect(() => { if (userData) { setValue("gender", userData.gender || ""); setValue("age", userData.age || 0); setValue("height", userData.height || 0); setValue("weight", userData.weight || 0); setBMI(userData.bmi || null); } setLoading(false); }, [userData, setValue]); const getWeightStatus = (bmi: number | null) => { if (bmi === null) return ""; if (bmi < 18.5) { return "Underweight"; } else if (bmi >= 18.5 && bmi < 25.0) { return "Healthy Weight"; } else if (bmi >= 25.0 && bmi < 30.0) { return "Overweight"; } else { return "Obesity"; } }; const onSubmit = async (data: any) => { try { if (userData && user) { const userDocRef = doc(db, "users", user.uid); try { // Calculate BMI const heightInMeters = data.height / 100; const bmiValue = data.weight / (heightInMeters * heightInMeters); // Update user details and BMI in FireStore await updateDoc(userDocRef, { gender: data.gender, age: data.age, height: data.height, weight: data.weight, bmi: bmiValue, }); setBMI(bmiValue); setError("User details updated successfully"); setSnackbarOpen(true); } catch (error) { setError("Error updating user details: " + error.message); setSnackbarOpen(true); } } setError("User data updated successfully."); setSnackbarOpen(true); } catch (error) { setError("Error updating user data: " + error.message); setSnackbarOpen(true); } finally { await fetchUserData(); } }; // Function to apply color based on weight status const getWeightStatusColor = (bmi: number | null) => { if (bmi === null) return ""; if (bmi < 18.5) { return "text-blue-500"; } else if (bmi >= 18.5 && bmi < 25.0) { return "text-green-500"; } else if (bmi >= 25.0 && bmi < 30.0) { return "text-yellow-500"; } else { return "text-red-500"; } }; const calculateBMI = (formData: any) => { const heightInMeters = formData.height / 100; const bmiValue = formData.weight / (heightInMeters * heightInMeters); setBMI(bmiValue); }; if (loading) { return ( <div className="flex h-20 flex-col items-center justify-center bg-white rounded-md"> <CircularProgress /> </div> ); } return ( <section className="gap-8"> {/* Personal Details Section */} <form className="gap-8 p-6 bg-white rounded-md shadow-md"> <div className="mb-6"> <Controller name="gender" control={control} rules={{ required: "Gender is required" }} render={({ field: { onChange, value }, fieldState: { invalid, error }, }) => ( <FormControl className="w-full" error={invalid}> <InputLabel id="gender-error-label">Gender</InputLabel> <Select labelId="gender-error-label" value={value} onChange={onChange} error={invalid} className="w-full" label="Gender" > <MenuItem value="male">Male</MenuItem> <MenuItem value="female">Female</MenuItem> <MenuItem value="other">Other</MenuItem> </Select> <FormHelperText>{error?.message}</FormHelperText> </FormControl> )} /> </div> <div className="mb-6"> <Controller name="age" control={control} rules={{ required: "Age is required", validate: (value) => value >= 1 || "Age must be greater or equal to 1", }} render={({ field: { onChange, value }, fieldState: { invalid, error }, }) => ( <TextField error={invalid} type="number" label="Age" onChange={onChange} value={value} helperText={error?.message} className="w-full" InputProps={{ inputProps: { min: 1 } }} /> )} /> </div> <div className="mb-6"> <Controller name="height" control={control} rules={{ required: "Height is required", validate: (value) => value > 40 || "Height must be greater than 40 cm", }} render={({ field: { onChange, value }, fieldState: { invalid, error }, }) => ( <TextField error={invalid} type="number" label="Height (cm)" onChange={onChange} value={value} helperText={error?.message} className="w-full" InputProps={{ inputProps: { min: 40 } }} /> )} /> </div> <div className="mb-6"> <Controller name="weight" control={control} rules={{ required: "Weight is required", validate: (value) => value > 10 || "Weight must be greater than 10 kg", }} render={({ field: { onChange, value }, fieldState: { invalid, error }, }) => ( <TextField error={invalid} type="number" label="Weight (kg)" onChange={onChange} value={value} helperText={error?.message} className="w-full" InputProps={{ inputProps: { min: 10 } }} /> )} /> </div> {bmi && ( <div className="mb-6"> <h3 className="text-xl font-semibold mb-3 text-gray-800"> Body Mass Index (BMI) </h3> <p className="text-2xl text-gray-800"> {bmi?.toFixed(1)} kg/m<sup>2</sup> </p> <p className={`text-gray-800 font-semibold ${getWeightStatusColor( bmi )}`} > {getWeightStatus(bmi)} </p> </div> )} <div> <button type="button" onClick={() => { handleSubmit((formData) => { onSubmit(formData); calculateBMI(formData); })(); }} className="w-full px-4 py-2 bg-blue-500 text-white rounded-md transition duration-300 hover:bg-blue-600" > Save Details </button> </div> </form> {/* Snackbar for displaying errors */} <Snackbar open={snackbarOpen} autoHideDuration={6000} onClose={handleSnackbarClose} message={error || ""} /> </section> ); }; export default PersonalDetails;
import { Component, OnInit } from '@angular/core'; import {HttpClient} from "@angular/common/http"; import {LoginInfo, LoginResponse} from "../../helpers/login-info"; import {MojCfg} from "../../moj-cfg"; import {AuthHelper} from "../../helpers/auth-helper"; import {Router} from "@angular/router"; import {FormBuilder, FormGroup, Validators} from "@angular/forms"; declare function porukaSuccess(a:string):any; declare function porukaError(a: string):any; declare function porukaInfo(a:string):any; declare function porukaWarning(a: string):any; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { constructor(private httpClient:HttpClient, private router: Router,private formBuilder:FormBuilder) { } loginForm!:FormGroup; loginInfo:LoginInfo=new LoginInfo(); ngOnInit(): void { if(AuthHelper.isLoggedIn()){ this.router.navigate(['app']); } this.loginForm=this.formBuilder.group({ username:['',Validators.required], password:['',Validators.required] }) } login() { if(this.loginForm.valid){ this.httpClient.post(MojCfg.adresa+"/KorisnickiNalog/Login",this.loginInfo) .subscribe((x:any)=>{ porukaSuccess('Uspješan login!') AuthHelper.setAuthInfo(x); if(x!=null) this.router.navigateByUrl("/app/home"); }) }else{ console.log("Login forma nije validna !!!"); porukaError('Unesite sve podatke!'); } setTimeout(()=>{ if(this.loginForm.valid&&AuthHelper.getAuthInfo().token=='') porukaError('Pogrešno korisnicko ime ili lozinka!'); },300); } }
<template> <div> <div v-if="isLoading" class="my-5"> <p class="text-center"> <BSpinner small /> </p> </div> <div v-else-if="!isLoading && logItems.length === 0" class="my-5"> <p>{{ $t('components.covidCaseOsirisLog.no_items') }}</p> </div> <div v-else> <h3 class="form-heading"> {{ $t('components.covidCaseOsirisLog.titles.main', { logId: caseOsirisNumber ?? 'nog niet bekend' }) }} </h3> <Card v-for="item in logItems" :key="item.uuid" class="log-item-container"> <div class="log-item"> <h4 class="note-title">{{ formattedTitle(item.status) }}</h4> <p class="note-description"> {{ $t('components.covidCaseOsirisLog.number', { osirisNumber: caseOsirisNumber?.toString() ?? 'nog niet bekend', }) }} </p> <div v-if="item.osirisValidationResponse?.errors?.length" data-testid="validation-response"> <p class="note-description"> {{ $t('components.covidCaseOsirisLog.errors') }} </p> <ul> <li v-for="error in item.osirisValidationResponse.errors">{{ error }}</li> </ul> </div> <div v-if="item.osirisValidationResponse?.warnings?.length" data-testid="validation-response"> <p class="note-description"> {{ $t('components.covidCaseOsirisLog.warnings') }} </p> <ul> <li v-for="warning in item.osirisValidationResponse.warnings">{{ warning }}</li> </ul> </div> <div v-if="item.osirisValidationResponse?.messages?.length" data-testid="validation-response"> <p class="note-description"> {{ $t('components.covidCaseOsirisLog.messages') }} </p> <ul> <li v-for="message in item.osirisValidationResponse.messages">{{ message }}</li> </ul> </div> <p class="time-stamp"> {{ formatDate(parseDate(item.time), 'd MMMM yyyy HH:mm') + formattedDescription(item) }} </p> </div> </Card> </div> </div> </template> <script lang="ts"> import useStatusAction, { isPending } from '@/store/useStatusAction'; import { caseApi } from '@dbco/portal-api'; import { computed, defineComponent, onMounted, ref } from 'vue'; import type { PropType } from 'vue'; import { useI18n } from 'vue-i18n-composable'; import type { OsirisLogItem } from '@dbco/portal-api/osiris.dto'; import { Card } from '@dbco/ui-library'; import type { TranslateResult } from 'vue-i18n'; import type { OsirisHistoryStatusV1 } from '@dbco/enum'; import { formatDate, parseDate } from '@/utils/date'; export default defineComponent({ props: { caseUuid: { type: String as PropType<string>, required: true }, caseOsirisNumber: { type: Number as PropType<number | null | undefined> }, }, components: { Card, }, setup(props) { let logItems = ref<OsirisLogItem[]>([]); const { t } = useI18n(); const { action: loadOsirisLog, status } = useStatusAction(async () => { const items = await caseApi.getOsirisLog(props.caseUuid); logItems.value = items; }); const formattedDescription = (item: OsirisLogItem): string => item.caseIsReopened ? ` - ${t('components.covidCaseOsirisLog.reopened')}` : ''; const formattedTitle = (status: OsirisHistoryStatusV1): TranslateResult => t(`components.covidCaseOsirisLog.titles.${status}`); onMounted(async () => { await loadOsirisLog(); }); const isLoading = computed(() => isPending(status.value)); return { formatDate, formattedDescription, formattedTitle, isLoading, loadOsirisLog, logItems, parseDate, t, }; }, }); </script> <style lang="scss" scoped> @import './resources/scss/_variables.scss'; .note-title { font-weight: 500; font-size: 16px; margin-bottom: 0.65rem; } .note-description { margin-bottom: $padding-xs; } .note-author { margin-bottom: 0.65rem; } .note-author { font-weight: 500; } .time-stamp { color: $dark-grey; margin-bottom: 0; } </style>
import React from "react"; import { Box, Typography } from "@mui/material"; import { AvatarIcon } from "../Avatar/Avatar"; interface ProfileInfoProps { name: string; email: string; createdAt: string; height: string; age: string; image: string; } export const ProfileInfo: React.FC<ProfileInfoProps> = ({ name, email, createdAt: createdAt, height, age, image, }) => { const formattedRegistrationDate = new Date(createdAt).toLocaleDateString('ru-RU', { day: '2-digit', month: '2-digit', year: 'numeric' }); return ( <Box sx={{ padding: 2, border: "1px solid #ccc", borderRadius: 4 }}> <Typography variant="h5" gutterBottom>Профиль пользователя</Typography> <Box sx={{ marginBottom: 1 }}> <AvatarIcon name={name} photo = {image} /> </Box> <Box sx={{ marginBottom: 1 }}> <Typography variant="subtitle1"><strong>Имя:</strong> {name}</Typography> </Box> <Box sx={{ marginBottom: 1 }}> <Typography variant="subtitle1"><strong>Email:</strong> {email}</Typography> </Box> <Box sx={{ marginBottom: 1 }}> <Typography variant="subtitle1"><strong>Дата регистрации:</strong> {formattedRegistrationDate}</Typography> </Box> <Box sx={{ marginBottom: 1 }}> <Typography variant="subtitle1"><strong>Рост:</strong> {height}</Typography> </Box> <Box> <Typography variant="subtitle1"><strong>Возраст:</strong> {age}</Typography> </Box> </Box> ); }
// Given an object, return a valid JSON string of that object. //You may assume the object only inludes strings, integers, arrays, objects, booleans, and null. The returned string should not include extra spaces. //The order of keys should be the same as the order returned by Object.keys(). // Please solve it without using the built-in JSON.stringify method. /** * @param {any} object * @return {string} */ var jsonStringify = function(object) { if (object === null) { return 'null'; } if (typeof object === 'boolean' || typeof object === 'number') { return object.toString(); } if (typeof object === 'string') { return '"' + object.replace(/"/g, '\\"') + '"'; } if (Array.isArray(object)) { const elements = object.map(jsonStringify); return '[' + elements.join(',') + ']'; } if (typeof object === 'object') { const keys = Object.keys(object); const pairs = keys.map(function(key) { const value = jsonStringify(object[key]); return '"' + key + '":' + value; }); return '{' + pairs.join(',') + '}'; } return ''; };
//https://hdlbits.01xz.net/wiki/Exams/2013_q2bfsm module top_module ( input clk, input resetn, // active-low synchronous reset input x, input y, output f, output g ); parameter A = 4'b0000, B = 4'b0001, C=4'b0010,D=4'b0011, E = 4'b0100, F = 4'b0101,G=4'b0110,H=4'b0111,I = 4'b1000; reg [3:0]state; reg [3:0]next_state; always @(*) begin case (state) A:next_state = B; B:next_state = I; C:next_state = x?C:D; D:next_state = x?E:I; I:next_state = x?C:I; E:next_state = y?G:F; F:next_state = y?G:H; G:next_state = G; H: next_state = H; default:next_state = A; endcase end always @(posedge clk ) begin if(!resetn) state <= A; else state <= next_state; end assign f=(state==B); assign g = (state==E || state==F || state ==G); endmodule
<template> <v-container> <v-row> <!-- <v-col> <div class="headline text-centers">Record Your Expense</div> </v-col> --> <v-col cols="12"> <v-text-field v-model="shop_name" label="Shop Name" outlined dense hide-details required ></v-text-field> </v-col> <v-col cols="12"> <v-text-field v-model="label" label="Label" outlined dense hide-details required ></v-text-field> </v-col> <v-col cols="12"> <v-text-field v-model="amount" label="Amount" type="number" outlined dense hide-details required ></v-text-field> </v-col> <v-col cols="12"> <DatePicker @date=" (e) => { date = e.date; } " /> </v-col> <v-col cols="12" class="error--text" v-if="errorResponse"> {{ errorResponse }} </v-col> <v-col cols="12"> <v-btn type="submit" color="primary" block @click="submit">Submit</v-btn> </v-col> </v-row> </v-container> </template> <script> export default { data() { return { dialog: false, shop_name: "", label: "", amount: "", date: null, errorResponse: null, data: [], }; }, async created() { // this.getData(); }, methods: { // async getData() { // this.data = await this.$axios.get(`https://backend.florencetech.online/api/expense`); // }, async submit() { try { const expenseData = { shop_name: this.shop_name, label: this.label, amount: this.amount, date: this.date, user_id: this.$auth.user.id, }; // Sending the expense data to the backend await this.$axios.post("expense", expenseData); alert("Expense has been recorded"); this.dialog = false; // Optionally, you can fetch updated data from the server or perform other actions } catch ({ response }) { this.errorResponse = response.data.message; // console.error("Error adding expense:", response.data.message); } }, }, }; </script>
import { StyleSheet, Text, View, Modal, Pressable, TextInput, ScrollView, TouchableOpacity,FlatList } from 'react-native' import React, { useState } from 'react' import { scale, verticalScale } from 'react-native-size-matters' import { theme } from '../../styles/stylesheet' import Search from '../search/Search' import { phoneData } from '../../../data/phonedata' import { Iconify } from 'react-native-iconify' export const CodeList = { Ethiopian: ({name,Flag,dial_code,code,setResult,setModalVisible} ) => { return (<TouchableOpacity onPress={() => {setResult({name,code,dial_code,Flag}); setModalVisible(false)}} key={name} style={{ width: "100%",flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginVertical: 8 }}> <View style={{ flexDirection: 'row' }}><Flag /><Text style={{ fontSize: 18 }}>{name}</Text></View> <Text>{dial_code}</Text></TouchableOpacity>) } } const PhoneCode = ({ modalVisible, setModalVisible, setResult }) => { const [searchfield, setSearchfield] = useState(""); const filteredphoneCodes = phoneData.filter((country) => { return country.name.toLowerCase().includes(searchfield.toLowerCase()); }); const onSearchChanges = (text) => { setSearchfield(text); }; return ( <Modal animationType="slide" transparent={true} visible={modalVisible} onRequestClose={() => { //Alert.alert('Modal has been closed.'); setModalVisible(!modalVisible); }}> <View style={styles.centeredView}> <View style={styles.modalView}> <Search value={searchfield} search={onSearchChanges} placeholder={'country name'} /> <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-around', width: '100%', paddingHorizontal:20,marginBottom: 100, }}> {/* <ScrollView><View style={{ marginBottom: 100, alignItems: 'center', width: "100%", paddingHorizontal: 30 }}> <View style={{ width: "100%"}}>{filteredphoneCodes.map(({ code, name, dial_code, Flag }) => <TouchableOpacity onPress={() => {setResult({name,code,dial_code,Flag}); setModalVisible(false)}} key={name} style={{ width: "100%",flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginVertical: 8 }}> <View style={{ flexDirection: 'row' }}><Flag /><Text style={{ fontSize: 18 }}>{name}</Text></View> <Text>{dial_code}</Text></TouchableOpacity>)}</View></View> </ScrollView> */} <FlatList showsVerticalScrollIndicator={false} data={filteredphoneCodes} numColumns={1} renderItem={({item}) => <TouchableOpacity onPress={() => {setResult(item); setModalVisible(false)}} style={{ width: "100%",flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginVertical: 8 }}> <View style={{ flexDirection: 'row' }}><item.Flag /><Text style={{ fontSize: 18 }}>{item.name}</Text></View> <Text>{item.dial_code}</Text></TouchableOpacity>} keyExtractor={(item) => item.name} /> </View> </View> </View> </Modal> ) } export default PhoneCode const styles = StyleSheet.create({ centeredView: { flex: 1, //justifyContent: 'center', alignItems: 'center', //marginTop: 22, //paddingHorizontal:scale(65), backgroundColor: 'rgba(135, 135, 135,0.3)', }, modalView: { flex: 1, marginHorizontal: scale(62), width: '100%', marginTop: 200, backgroundColor: 'white', borderRadius: 10, //height: 197, //justifyContent: 'center', //padding: 38, alignItems: 'center', shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 4, elevation: 5, }, button: { //backgroundColor: 'white', borderColor: theme.color.primary, borderWidth: 1, paddingHorizontal: 36.5, paddingVertical: 12, borderRadius: 10, elevation: 1, }, buttonOpen: { backgroundColor: theme.color.primary, }, buttonClose: { backgroundColor: "white", }, textStyle: { color: 'white', fontWeight: 'bold', textAlign: 'center', fontSize: 18, }, modalText: { marginBottom: 15, textAlign: 'center', fontSize: 22, color: 'black', }, btnInactive: { backgroundColor: 'white', borderColor: theme.color.primary, borderWidth: 1, paddingHorizontal: 36.5, paddingVertical: 12, borderRadius: 10, elevation: 1, }, });
<template> <NavBar/> <h1 class="page_category">Заказ</h1> <div class="block_content"> <div class="d-flex"> <form @submit.prevent class="align-self-start"> <div class="select_user"> <p>Выберите сотрудника:&nbsp</p> <select v-model="selectedUser"> <option v-for="user in users" v-bind:value="user.user_name">{{user.user_name}}</option> </select> </div> <div class="select_data"> <p>Выберите дату заказа:&nbsp</p> <input type="date" v-model="selectedDate"> </div> <div class="select_dish"> <p>Выберите блюдо:&nbsp</p> <select v-model="selectedDish" id="dish_item"> <option disabled value="">Выберите товар</option> <option v-for="dish in dishes" :key="dish.pk" :value="dish.dish_name"> {{ dish.dish_name }} </option> </select> <span v-if="selectedDish">&nbsp&nbsp{{ dishes.find(dish => dish.dish_name === selectedDish).dish_price }}₽</span> <div v-if="selectedDish" class="compound">Состав: <br/> {{ dishes.find(dish => dish.dish_name === selectedDish).dish_compose }}</div> </div> <button @click="addDishPost">Добавить блюдо</button> <div class="primary_button"> <button class="bg-primary text-white" v-if="this.dish_posts.length" @click="sendUsersChoice">Заказать</button> </div> </form> <div class="p-2" v-if="this.dish_posts.length"> <div class="dish_posts"> <div v-for="(dish, index) in dish_posts" :key="index"> <div class="dish"> <div class="dish_name"><h4>Название блюда: <br/> {{ dish.dish_name }}</h4></div> <div>Цена блюда: {{ dish.dish_price }}₽</div> <div class="dish_count"> <div>Кол-во: {{ dish.dish_count }}</div> <button class="count_button" @click="incrementCountDish(index)">+</button> <button class="count_button" @click="decrementCountDish(index)">-</button> </div> <div> <button class="bg-light text-dark" @click="deleteDishPost(index)">Удалить товар</button> </div> </div> </div> </div> </div> </div> </div> </template> <script> import NavBar from "@/Components/NavBar.vue"; import axios from "axios"; export default { data() { return { users: [], //users из API dishes: [], //dish из API selectedUser: null, // выбранный user из выпадающего списка selectedDish: null, // выбранное dish из выпадающего списка selectedDate: null, // выбранная дата из input'а с датой dish_posts: [], // список блюд }; }, mounted() { axios.get('http://127.0.0.1:8000/api/user_view/') .then(response => { this.users = response.data }) .catch(error => { console.log(error); }) axios.get('http://127.0.0.1:8000/api/dish_view/') .then(response => { this.dishes = response.data }) .catch(error => { console.log(error) }) }, components: {NavBar}, methods: { addDishPost() { if (this.selectedDish != null){ if (this.dish_posts.some(item => item.dish_name === this.selectedDish) === false) { this.dish_posts.push({ dish_name: this.dishes.find(item => item.dish_name === this.selectedDish)['dish_name'], dish_compose: this.dishes.find(item => item.dish_name === this.selectedDish)['dish_compose'], dish_price: this.dishes.find(item => item.dish_name === this.selectedDish)['dish_price'], pk: this.dishes.find(item => item.dish_name === this.selectedDish)['pk'], dish_count: 1, }) } else{ alert('Вы уже добавили этот товар') } }else{ alert('Вы не добавили блюдо') } }, deleteDishPost(index) { this.dish_posts.splice(index, 1) }, incrementCountDish(index) { this.dish_posts[index].dish_count += 1 }, decrementCountDish(index) { if (this.dish_posts[index].dish_count >= 2){ this.dish_posts[index].dish_count -= 1 } }, sendUsersChoice() { if (this.dish_posts.length > 0 && this.selectedUser != null && this.selectedDate != null){ axios.post('http://127.0.0.1:8000/api/put_users_choice/', { 'user_name': this.selectedUser, 'dish_list': this.dish_posts, 'order_date': this.selectedDate }) .then(response => { console.log(response) console.log('Все норм :)') }) .catch(error => { console.log(error) }) alert('Вы успешно оформили заказ :)') location.reload(); }else{ alert('Вы ввели не все данные.\nПожалуйста, проверьте форму на заполнение всех данных') } }, } }; </script> <style lang="scss" scoped> .dish_name{ white-space: nowrap; word-wrap: break-word; } .compound{ margin-top: 10px; width: 170px; height: auto; word-wrap: break-word; } .align-self-start{ border: 2px solid rgb(16, 127, 179); border-radius: 25px; padding: 15px; } .d-flex flex-row{ align-items: flex-start; } </style>
import 'package:animations/animations.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:mobile_chaseapp/utils/custom_platform.dart'; enum RouteTransition { defaultAnimation, fade, fadeThrough, fadeScale, none, slideVertically, } class CustomPageRouteBuilder { CustomPageRouteBuilder._(); static PageRoute<T> _route<T>({ required Widget Function(BuildContext) builder, String? name, Duration? transitionDuration, RouteTransition? transitionType, }) { final tType = transitionType ?? RouteTransition.defaultAnimation; if (tType == RouteTransition.defaultAnimation) { return MaterialPageRoute( builder: builder, settings: RouteSettings(name: name)); } return PageRouteBuilder<T>( transitionDuration: transitionDuration ?? const Duration(milliseconds: 300), pageBuilder: (context, _, __) => builder(context), settings: RouteSettings(name: name), transitionsBuilder: (context, animation, secondaryAnimation, child) { switch (tType) { case RouteTransition.fade: return FadeTransition(opacity: animation, child: child); case RouteTransition.fadeThrough: return FadeThroughTransition( animation: animation, secondaryAnimation: secondaryAnimation, child: child); case RouteTransition.fadeScale: return FadeScaleTransition(animation: animation, child: child); case RouteTransition.slideVertically: if (CustomPlatform.isIOS) { return CupertinoFullscreenDialogTransition( primaryRouteAnimation: animation, secondaryRouteAnimation: AlwaysStoppedAnimation(0), linearTransition: false, child: child); } return SharedAxisTransition( animation: animation, secondaryAnimation: secondaryAnimation, transitionType: SharedAxisTransitionType.vertical, child: child, ); default: return child; } }, ); } static PageRoute route<T>({ required Widget Function(BuildContext) builder, String? name, Duration? transitionDuration, RouteTransition? transitionType, }) { return CustomPageRouteBuilder._route<T>( name: name, builder: (ctx) { var widget = builder(ctx); return widget; }, transitionDuration: transitionDuration, transitionType: transitionType); } }
<?php /** * Mageplaza * * NOTICE OF LICENSE * * This source file is subject to the Mageplaza.com license that is * available through the world-wide-web at this URL: * https://www.mageplaza.com/LICENSE.txt * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade this extension to newer * version in the future. * * @category Mageplaza * @package Mageplaza_SpecialPromotions * @copyright Copyright (c) Mageplaza (http://www.mageplaza.com/) * @license https://www.mageplaza.com/LICENSE.txt */ namespace Mageplaza\SpecialPromotions\Model\Rule\Action\Discount; use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\SalesRule\Model\Rule\Action\Discount\DataFactory; use Magento\SalesRule\Model\Validator; use Mageplaza\SpecialPromotions\Helper\Data; /** * Class ToFixed * @package Mageplaza\SpecialPromotions\Model\Rule\Action\Discount */ class ToFixed extends \Magento\SalesRule\Model\Rule\Action\Discount\ToFixed { /** * @var Data */ protected $helper; /** * SpentXGetY constructor. * * @param Validator $validator * @param DataFactory $discountDataFactory * @param PriceCurrencyInterface $priceCurrency * @param Data $helper */ public function __construct( Validator $validator, DataFactory $discountDataFactory, PriceCurrencyInterface $priceCurrency, Data $helper ) { $this->helper = $helper; parent::__construct($validator, $discountDataFactory, $priceCurrency); } /** * @inheritDoc */ public function calculate($rule, $item, $qty) { if (!$this->helper->isEnabled($item->getStoreId())) { /** @var \Magento\SalesRule\Model\Rule\Action\Discount\Data $discountData */ $discountData = $this->discountFactory->create(); $discountData->setAmount(0); $discountData->setBaseAmount(0); return $discountData; } return parent::calculate($rule, $item, $qty); // TODO: Change the autogenerated stub } /** * @param float $qty * @param \Magento\SalesRule\Model\Rule $rule * * @return float */ public function fixQuantity($qty, $rule) { $step = $rule->getDiscountStep(); if ($step) { $qty = floor($qty / $step) * $step; } return $qty; } }
# Healthcare Pro ## Table of Contents - [Description](#description) - [Features](#features) - [Technologies Used](#technologies-used) - [Files and Folders](#files-and-folders) - [Manual Testing](#manual-testing) - [Usage](#usage) ## Description Healthcare Pro W is designed and developed to provide a robust platform for healthcare management. It leverages Django, HTML5, CSS3 (Bootstrap), and MySQL to offer a seamless experience for users. The platform includes robust authentication features and secure data management, ensuring that sensitive information is protected. ## Features - **User Authentication and Authorization:** Secure login functionality using unique email and password combinations. - **Patient Management:** Patients can view their appointment history and book appointments with registered doctors. - **Doctor Management:** Doctors can view and manage their schedules and appointments. - **Session-based Features:** Ensures that each doctor and patient can only view their own booking details or appointment schedules. - **Responsive Design:** Built with HTML5 and CSS3 (Bootstrap) for a responsive and user-friendly interface. - **Version Control:** Utilizes Git for version control, ensuring organized collaboration and tracking of changes. ## Technologies Used - **Backend:** Python, Django, MySQL - **Frontend:** HTML5, CSS3 (Bootstrap) - **Template Engine:** Jinja2 - **Database Management:** Django ORM (Object Relational Mapper) ## Files and Folders - **ClinicProject/:** - `settings.py`: Contains project settings such as database configuration, installed apps, static files configuration, etc. - `urls.py`: Main URL configuration for the project, including routing to app-level URLs. - **ClinicApp/ (Django App):** - `models.py`: Defines Django models for the application, including patients, doctors, appointments, etc. - `views.py`: Contains business logic for handling requests, rendering templates, processing forms, etc. - `urls.py`: App-level URL configuration for routing requests to appropriate view functions. - **static/:** Folder containing CSS files, images, JavaScript, or other static assets used in the application. - `style.css`: Custom CSS styles for the application. - `images/`: Folder containing image assets used in the application. - **templates/:** Folder containing HTML templates for rendering views and pages. - `base.html`: Base template containing common elements like header, footer, etc. - Other HTML files for specific pages or components. ## Manual Testing - **Register a New Account:** - Open the application in your web browser. - Click on the "Register" link to create a new account. - Enter your details and submit the form. - **Log In to Your Account:** - After registering, log in using your credentials. - Verify that you can successfully access your account dashboard. - **Book an Appointment:** - In your account dashboard, navigate to the "Book Appointment" section. - Select a doctor and choose an available time slot. - Enter the necessary details and submit the form. - **View Appointment History:** - Navigate to the "Appointment History" section to view past and upcoming appointments. - **Doctor Schedule Management:** - Doctors can log in and navigate to the "Manage Schedule" section to view and manage their appointments. ## Usage - **Run the Django development server:** ```bash python manage.py runserver
var yearData = [ { year: "2021", // 年份 data: [ [2994.6, 2305.5, 4908.9, 5379.0, 5274.6, 3823.1, 4650.1, 2207.0, 3519.6, 4002.8, 2441.7, 4492.4], [798.5, 652.3, 1215.5, 1285.0, 1267.8, 1104.6, 1305.6, 469.1, 918.6, 1008.1, 534.5, 1056.6], [2155.2, 1728.6, 3103.1, 3193.4, 3342.6, 3028.4, 3491.2, 1658.0, 2485.5, 2521.2, 1235.2, 2625.3], [264.8, 256.8, 622.7, 667.3, 623.4, 560.0, 691.6, 297.4, 500.7, 445.9, 209.5, 544.9] ] } ]; var myChart_left31 = echarts.init(document.querySelector(".line31 .chart")); var option_left31 = { color: ["#00f2f1", "#ed3f35", "#1adb3a", "#f5e90b"], toolbox: { show: true, top: '0px', left: 'right', feature: { mark: {show: true}, dataView: {show: true, readOnly: false}, restore: {show: true}, saveAsImage: {show: true} } }, tooltip: { trigger: "axis", axisPointer: { // 坐标轴指示器,坐标轴触发有效 type: "shadow" // 默认为直线,可选为:'line' | 'shadow' } }, legend: { // 如果series 对象有name 值,则 legend可以不用写data // 修改图例组件 文字颜色 textStyle: { color: "#111010" }, top:"30px", // 这个10% 必须加引号 left: 'center' }, // 修改图表的大小 grid: { left: "0%", top: "40px", right: "0%", bottom: "14%", containLabel: true }, xAxis: [ { type: "category", data: [ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月" ], axisTick: { alignWithLabel: true }, // 修改刻度标签 相关样式 axisLabel: { color: "rgba(0,0,0,.6) ", fontSize: "12" }, // 不显示x坐标轴的样式,不显示x坐标轴那条线 axisLine: { show: false } } ], yAxis: [ { type: "value", // 修改刻度标签 相关样式 axisLabel: { color: "rgba(0,0,0,.6) ", fontSize: 12 }, // y轴的线条改为了 2像素 axisLine: { lineStyle: { color: "rgba(0,0,0,.3)", width: 2 } }, // y轴分割线的颜色 splitLine: { lineStyle: { color: "rgba(0,0,0,.3)" } } } ], series: [ { name: "东部地区", type: "line", // true 可以让我们的折线显示带有弧度 smooth: true, // data: yearData[0].data[0] data:[] }, { name: "中部地区", type: "line", // true 可以让我们的折线显示带有弧度 smooth: true, // data: yearData[0].data[1] data:[] }, { name: "西部地区", type: "line", // true 可以让我们的折线显示带有弧度 smooth: true, // data: yearData[0].data[2] data:[] }, { name: "东北地区", type: "line", // true 可以让我们的折线显示带有弧度 smooth: true, // data: yearData[0].data[3] data:[] } ] }; // 3. 把配置项给实例对象 myChart_left31.setOption(option_left31); // 4. 让图表跟随屏幕自动的去适应 window.addEventListener("resize", function () { myChart_left31.resize(); });
/* * Copyright 2019 Adrian Bueno Olmedo - adrian.bueno.alum@iescamp.es. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.japo.java.app; import java.util.Locale; import java.util.Scanner; /** * * @author Adrián Bueno Olmedo <adrian.bueno.alum@iescamp.es> */ public final class App { // Constantes de clase public static final String MSG_USR = "Introduce un número por teclado: "; public static final String MSG_ERR = "Ha habido un error en el proceso de " + "introducción de un número"; // Definición de metodo, dentro de los metodos van los parametros entre () public static final double obtener(String msgUsr, String msgErr) { double numero = 0.0; boolean semaforo; do { Scanner scn = new Scanner(System.in, "Windows-1252") .useLocale(Locale.ENGLISH).useDelimiter("\\s+"); System.out.printf(msgUsr); try { numero = scn.nextDouble(); System.out.printf(Locale.ENGLISH, "Numero introducido ...: " + "%.2f%n", numero); semaforo = false; } catch (Exception e) { System.out.println(msgErr); semaforo = true; } } while (semaforo); return numero; } public final void launchApp() { System.out.println("INTRODUCCIÓN DE ENTERO"); /* Llamada de metodo, el orden importa, es decir, MSG_USR hace referencia a msgUsr en el metodo, y MSG_ERR hace referencia a msgErr, el nombre solo es para especificar el orden, si pusiera en la llamada el orden inverso MSG_USR haría referencia a msgErr y viceversa */ obtener(MSG_USR, MSG_ERR); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <script type="text/javascript"> /* 原型 */ var myMammal = { name:'Herb the Mammal', get_name:function(){ return this.name; }, says:function(){ return this.saying || ''; } }; var myCat = Object.create(myMammal); myCat.name = 'Henrietta'; myCat.saying = 'meow'; myCat.purr = function(n){ var i,s=''; for(i=0;i<n;i++){ if(s){ s+='-'; } s+='r'; } return s; }; myCat.get_name = function(){ return this.says+' '+this.name+' '+this.says; }; document.writeln(myCat.get_name()); var block = function(){ var oldScope = scope; scope = Object.create(scope); advance('{'); parse(scope); advance('}'); scope = oldScope; }; /* 函数化 */ //函数化构造器的伪码 // var constructor = function(spec,my){ // var that,其他的私有实例变量; // my = my || {}; // 把共享的变量和函数添加到my中 // that = 一个新对象 // 添加给that的特权方法 // return that; // }; var mammal = function(spec){ var that = {}; that.get_name = function(){ return spec.name; }; that.says = function(){ return spec.saying || ''; }; return that; }; var myMammal1 = mammal({name:'Herb'}); var cat = function(spec){ spec.saying = spec.saying || 'meow'; var that = mammal(spec); that.purr = function(n){ var i,s=''; for(i=0;i<n;i++){ if(s){ s+='-'; } s+='r'; } return s; }; that.get_name = function(){ return that.says()+' '+spec.name+' '+that.says(); }; return that; }; var myCat1 = cat({name:'Henrietta'}); document.writeln("<br/>"); document.writeln(myCat1.get_name()); document.writeln(myCat1.purr(10)); Function.prototype.method = function(name,func){ this.prototype[name] = func; return this; }; Object.method('superior',function(name){ var that = this, method = that[name]; return function() { return method.apply(that,arguments); }; }); var coolcat = function(spec){ var that = cat(spec), super_get_name = that.superior('get_name'); that.get_name = function(n){ return 'like '+super_get_name()+' baby'; }; return that; }; var myCoolCat = coolcat({name:'Bix'}); var name = myCoolCat.get_name(); document.writeln("<br/>"); document.writeln(name); /* 部件 */ var eventuality = function(that){ var registry = {}; that.fire = function(event){ var array, func, i, type = typeof event === 'string'?event:event.type; if(registry.hasOwnProperty(type)){ array = registry[type]; for(i=0;i<array.length;i++){ handler = array[i]; func = handler.method; if(typeof func === 'string'){ func = this[func]; } func.apply(this, handler.parameters || [event]); } } }; that.on = function(type,method,parameters){ var handler = { method:method, parameters:parameters }; if(registry.hasOwnProperty(type)){ registry[type].push(handler); }else{ registry[type] = [handler]; } return this; }; return that; }; //eventuality(that); // /** * 数组 */ /* 数组字面量 */ var empty = []; var numbers = ['zero','one','two','three','four','five','six','seven','eight','nine']; console.log(empty[1]); console.log(numbers[1]); console.log(empty.length); console.log(numbers.length); var numbers_object = {0:'zero',1:'one'}//对象字面量,与numbers类似 /* 数组方法 */ Array.method('reduce',function(f,value){ var i; for(i=0;i<this.length;i++){ value = f(this[i],value); } return value; }); var data = [4,8,15,16,23,42]; var add = function(a,b){ return a+b; }; var mult = function(a,b){ return a*b; }; var sum = data.reduce(add,0); var product = data.reduce(mult,1); console.log(sum); console.log(product); data.total = function(){ return this.reduce(add,0); } total = data.total(); console.log(total); /** * 正则表达式 */ var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z])(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/; var url = "http://www.ora.com:80/goodparts?q#fragment"; var result = parse_url.exec(url); var names = ['url','scheme','slash','host','port','path','query','hash']; var blanks = ' '; var i; // for(i=0;i<names.length;i++){ // document.writeln(names[i]+':'+blanks.substring(names[i].length),result[i]); // } </script> </body> </html>
package com.minidwep.springcloud.service; import cn.hutool.Hutool; import cn.hutool.core.util.IdUtil; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.omg.PortableInterceptor.INACTIVE; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.PathVariable; import java.util.UUID; import java.util.concurrent.TimeUnit; @Service public class PaymentService { public String paymentInfo_OK(Integer id){ return "线程池:"+Thread.currentThread().getName()+"paymentInfo_OK,id"+id+"\t"+"哈哈"; } @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = { @HystrixProperty(name ="execution.isolation.thread.timeoutInMilliseconds",value = "5000") }) public String paymentInfo_TimeOut(Integer id){ int timeNumber = 0; try { TimeUnit.SECONDS.sleep(timeNumber); } catch (InterruptedException e) { e.printStackTrace(); } // int age = 10/0; return "线程池:"+Thread.currentThread().getName()+"paymentInfo_TimeOut,id"+id+"\t" +"O(∩_∩)O哈哈~"+"耗时"+timeNumber+"秒"; } public String paymentInfo_TimeOutHandler(Integer id){ return "线程池:"+Thread.currentThread().getName()+"8001系统繁忙请稍后再试,id"+id+"\t" +"o(╥﹏╥)o"; } // 服务熔断 // 服务熔断 @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties ={ @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //是否开启断路器 @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"), //请求次数 @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "1000"), //时间窗口期 @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸 }) public String paymentCircuitBreaker(@PathVariable("id") Integer id) { if (id < 0) { throw new RuntimeException("******id 不能为负数"); } String serialNumber = IdUtil.simpleUUID(); return Thread.currentThread().getName()+"\t"+ "调用成功,流水号:" + serialNumber; } public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) { return "id 不能负数,请稍后再试,o(╥﹏╥)o id:" + id; } }
// // ContentView.swift // SwiftUI-Africa-IOS17 // // Created by Daniel Felipe on 18/02/24. // import SwiftUI struct ContentView: View { //MARK: - Properties let animals: [Animal] = Bundle.main.decode("animals.json") let haptics = UIImpactFeedbackGenerator(style: .medium) @State private var isGridViewActive: Bool = false @State private var gridLayout: [GridItem] = [GridItem(.flexible())] @State private var gridColumn: Int = 1 @State private var toolbarIcon: String = "square.grid.2x2" func gridSwitch() { gridLayout = Array(repeating: .init(.flexible()), count: gridLayout.count % 3 + 1) gridColumn = gridLayout.count print("Grid Number: \(gridColumn)") //toolbar Img switch gridColumn { case 1: toolbarIcon = "square.grid.2x2" case 2: toolbarIcon = "square.grid.3x2" case 3: toolbarIcon = "rectangle.grid.1x2" default: toolbarIcon = "square.grid.2x2" } } //MARK: - Body var body: some View { VStack { NavigationView { Group { if !isGridViewActive { List { CoverImageView() .frame(height: 300) .listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)) ForEach(animals) { animal in NavigationLink(destination: AnimalDetailView(animal: animal)){ AnimalListItemView(animal: animal) }//: Link .listRowBackground(Color.clear) }//: Loop CreditsView() .modifier(CenterModifier()) }//: List } else { ScrollView(.vertical, showsIndicators: false) { LazyVGrid(columns: gridLayout, alignment: .center, spacing: 10) { ForEach(animals) { animal in NavigationLink(destination: AnimalDetailView(animal: animal)){ AnimalGridItemView(animal: animal) }//: Link .listRowBackground(Color.clear) }//: Loop }//: LazyVGrid .padding(10) .animation(.easeIn) }// :ScrollView }//: Condition }//: Group .navigationTitle("Africa") .toolbarTitleDisplayMode(.large) .toolbar { ToolbarItem(placement: .topBarTrailing) { HStack { //List Button { print("List vies is activated") isGridViewActive = false haptics.impactOccurred() } label: { Image(systemName: "square.fill.text.grid.1x2") .font(.title2) .foregroundColor(isGridViewActive ? .primary : .accentColor) } //Grid Button { print("Grid vies is activated") isGridViewActive = true haptics.impactOccurred() gridSwitch() } label: { Image(systemName: toolbarIcon) .font(.title2) .foregroundColor(isGridViewActive ? .accentColor : .primary) } }//: HStack }//:ToolbarItem }//:Toolbar }//: Navigation } } } #Preview { ContentView() }
This program is a Python script that uses the LangChain library to create a Retrieval-Augmented Generation (RAG) model. RAG models combine a language model with a retrieval system to provide more relevant and factual responses to queries by retrieving relevant information from a knowledge base. Here's a breakdown of the code: Imports: The script imports the necessary libraries and modules, such as PromptTemplate and CTransformers from LangChain, Chroma for the vector store, HuggingFaceBgeEmbeddings for embeddings, and gradio for creating a user interface. Configuration: The script sets up the configuration for the language model (local_llm) and defines parameters like max_new_tokens, repetition_penalty, temperature, top_k, top_p, stream, and threads. Language Model Initialization: The script initializes the language model using CTransformers from LangChain and the specified configuration. Prompt Template: A prompt template is defined to format the context (retrieved information) and the user's question for the language model. Embeddings: The script sets up the embeddings using HuggingFaceBgeEmbeddings from the langchain_community library. Embeddings are used to convert the text data into vector representations for efficient retrieval. Vector Store: A Chroma vector store is loaded or created to store the embeddings and the corresponding text data. Retriever: The vector store is converted into a retriever using as_retriever method, which will be used to retrieve relevant information from the knowledge base. Sample Prompts: A list of sample prompts is provided for testing purposes. Gradio Interface: The script uses Gradio to create a user interface with a text input field for entering prompts. Response Generation: The get_response function is defined, which takes the user's input prompt, sets up the RetrievalQA chain from LangChain, retrieves relevant information from the knowledge base using the retriever, and generates a response using the language model. Utility Functions: The script includes utility functions for calculating the time difference between the start and end of the response generation process (calculate_time_difference) and parsing the JSON response from the language model (parse_json). Gradio Interface Launch: Finally, the script launches the Gradio interface, allowing users to enter prompts and receive responses from the RAG model. This program demonstrates how to combine a language model with a retrieval system using LangChain to create a question-answering application. The knowledge base used in this example is related to pet care, specifically for dogs. However, the program can be adapted to work with different knowledge bases and domains by modifying the data used for the vector store. The configuration parameters used in the config dictionary are specific to the CTransformers language model from LangChain. These parameters control various aspects of the model's behavior and output generation. Here's an explanation of each parameter: max_new_tokens (default: 1024): This parameter sets the maximum number of tokens (words or subwords) that the model can generate in its output. It helps to limit the length of the generated text and prevent the model from producing unnecessarily long responses. repetition_penalty (default: 1.1): This parameter controls the extent to which the model avoids repeating the same words or phrases in its output. A higher value discourages repetition, while a lower value allows for more repetition. Setting a value higher than 1.0 can help produce more diverse and coherent responses. temperature (default: 0.1): The temperature parameter controls the randomness or "creativity" of the model's output. A higher temperature (e.g., 0.8 or higher) will make the output more diverse and unpredictable, while a lower temperature (e.g., 0.1 or lower) will make the output more deterministic and focused on the most likely options. top_k (default: 50): This parameter determines the number of tokens with the highest probability that the model will consider for generating the next token. A lower value will make the output more deterministic, while a higher value will make it more diverse. top_p (default: 0.9): This parameter is an alternative to top_k and controls the cumulative probability mass of tokens to consider for generating the next token. A value of 0.9 means that the model will consider the most probable tokens until their cumulative probability reaches 0.9 and discard the remaining tokens. stream (default: True): This parameter specifies whether the model should generate its output in a streaming fashion (i.e., token by token) or generate the entire output at once. threads (default: int(os.cpu_count() / 2)): This parameter determines the number of parallel threads to use for generating the output. It is set to half of the available CPU cores, which can help improve performance on multi-core systems. These parameters are crucial for controlling the behavior of the language model and fine-tuning its output to suit the specific needs of your application. For example, if you want more focused and deterministic responses, you might use a lower temperature and higher repetition_penalty. If you want more diverse and creative responses, you might increase the temperature and adjust the top_k or top_p values. It's important to note that the optimal values for these parameters can vary depending on the specific language model, the task at hand, and the desired output characteristics. Experimentation and fine-tuning may be necessary to find the best configuration for your use case. This line of code initializes an instance of the CTransformers language model from the LangChain library. Let's break it down: pythonCopy codellm = CTransformers( model=local_llm, model_type="mistral", # lib="avx2", # for CPU use **config ) llm = CTransformers(...): This creates an instance of the CTransformers class and assigns it to the variable llm. CTransformers is a language model wrapper provided by LangChain that allows you to use various pre-trained language models, including those from Anthropic. model=local_llm: This parameter specifies the pre-trained language model to be used. In this case, local_llm is a variable that holds the path or identifier of the pre-trained model. It is set to "mistral-7b-openorca.gguf2.Q4_0.gguf" earlier in the code. model_type="mistral": This parameter indicates the type or architecture of the pre-trained model being used. In this case, it is set to "mistral", which is the name of the model family from Anthropic. # lib="avx2" # for CPU use: This is a commented-out line, which means it is not executed. If uncommented, it would specify the CPU instruction set to be used for running the model on a CPU. The "avx2" value stands for the "Advanced Vector Extensions 2" instruction set, which is commonly supported by modern CPUs. **config: This is a way to unpack the config dictionary, which contains various configuration parameters for the language model. The ** operator allows you to pass the key-value pairs of the dictionary as separate keyword arguments to the CTransformers constructor. The config dictionary is defined earlier in the code and contains parameters like max_new_tokens, repetition_penalty, temperature, top_k, top_p, stream, and threads. These parameters control various aspects of the language model's behavior, such as the maximum output length, repetition penalty, randomness, and parallelization. By passing **config to the CTransformers constructor, each key-value pair in the config dictionary is treated as a separate keyword argument. For example, max_new_tokens=1024 would be passed as a keyword argument to the constructor. In summary, this line of code initializes an instance of the CTransformers language model wrapper from LangChain, using the pre-trained "mistral-7b-openorca" model from Anthropic, and applies the specified configuration parameters from the config dictionary. The prompt_template is a string that defines the structure of the prompt that will be used to provide context and the question to the language model. It uses Python's formatted string literals (f-strings) to incorporate the context and question variables. Here's the prompt_template: pythonCopy codeprompt_template = """Use the following pieces of information to answer the user's question. If you don't know the answer, just say that you don't know, don't try to make up an answer. Context: {context} Question: {question} Only return the helpful answer below and nothing else. Helpful answer: """ Let's break it down: Instruction: The first line provides an instruction to the language model to use the provided context to answer the user's question. Handling unknown answers: The second line instructs the language model to say that it doesn't know the answer if it can't find a relevant answer in the context, instead of making up an answer. Context placeholder: {context} is a placeholder that will be replaced with the actual context information retrieved from the knowledge base. Question placeholder: {question} is a placeholder that will be replaced with the user's question or prompt. Output instruction: The next line instructs the language model to only return the helpful answer and nothing else. Answer prompt: The final line "Helpful answer:" serves as a prompt for the language model to begin generating the answer. When the PromptTemplate is instantiated with this template string, it creates a template object that can be called with the context and question values. pythonCopy codeprompt = PromptTemplate(template=prompt_template, input_variables=['context', 'question']) Later in the code, when the RetrievalQA chain is created, the prompt object is used to format the context and question for the language model: pythonCopy codeqa = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True, chain_type_kwargs={"prompt": prompt}, verbose=True ) The context is the relevant information retrieved from the knowledge base (in this case, the Chroma vector store) based on the user's question. The prompt template is used to combine the context and question into a formatted prompt that the language model can understand and generate an answer from. By using this prompt template, the language model is provided with the necessary context and question, along with instructions on how to use the context to answer the question and handle cases where it doesn't have enough information to provide a helpful answer. The 'context' is set by retrieving relevant information from the knowledge base (vector store) based on the user's question or prompt. In this code, the context is retrieved using the Chroma vector store and the retriever object, which is created from the vector store using as_retriever method: pythonCopy codeload_vector_store = Chroma(persist_directory="stores/pet_cosine", embedding_function=embeddings) retriever = load_vector_store.as_retriever(search_kwargs={"k": 1}) When the RetrievalQA chain is created, the retriever object is passed as an argument: pythonCopy codeqa = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True, chain_type_kwargs={"prompt": prompt}, verbose=True ) When the qa object is called with a user's question or prompt, it performs the following steps: The user's question is embedded into a vector representation using the specified embedding function (HuggingFaceBgeEmbeddings in this case). The retriever uses this vector representation to search for the most similar vectors in the vector store (knowledge base). The text data associated with the most similar vector(s) is retrieved and used as the context. The prompt template is applied to the retrieved context and the user's question to create the final prompt for the language model. The language model generates an answer based on this prompt, which includes the relevant context and the original question. So, the 'context' is dynamically retrieved from the knowledge base using vector similarity search, based on the user's input question. This context is then combined with the question in the prompt template and provided to the language model for generating the answer. By using a vector store and retriever, the system can efficiently search through a large knowledge base and retrieve the most relevant information to augment the language model's response, making it more factual and grounded in the provided context. +---------------------+ | User Input | | (Gradio UI) | +---------------------+ | v +---------------------+ | Get Response() | +----------+----------+ | v +---------------------+ | RetrievalQA | | Chain | +---------------------+ | v +---------------------+ | Retriever | +----------+----------+ | v +---------------------+ | Vector Store | | (Chroma) | +---------------------+ | v +---------------------+ | Knowledge | | Base | +---------------------+ | v +---------------------+ | Embeddings | | (HuggingFace) | +---------------------+ | v +---------------------+ | Language Model | | (CTransformers) | +---------------------+ | v +---------------------+ | Response | | (Gradio UI) | +---------------------+
use std::cell::RefCell; use std::rc::Rc; use colored::*; use super::{Interpreter, InterpreterError}; use crate::frontend::ast::{ASTNodeKind, ExpressionKind, StatementKind}; use crate::{environment::Env, values::RuntimeVal}; use frontend::parser::VarType; impl Interpreter { pub(super) fn resolve(&self, stmt: StatementKind, env: &mut Env) -> Result<RuntimeVal, InterpreterError> { match stmt { StatementKind::VarDeclaration { name, value, constant, var_type, } => { // We get declaration value let mut declaration_value = self.evaluate(value, env)?; // If this is structure that we assign, we create new members otherwise we point // to the other structure, like a pointer // TODO: test if let RuntimeVal::Structure { prototype, members } = declaration_value { declaration_value = RuntimeVal::Structure { prototype: prototype.clone(), members: Rc::new(RefCell::new(members.borrow().clone())) } } // We declare the variable env.declare_var(name, declaration_value, constant, var_type) .map_err(|e| InterpreterError::VarDeclaration(format!("{e}")))?; Ok(RuntimeVal::Null) } StatementKind::VarCommaDeclaration { declarations } => { for decl in declarations { self.resolve(decl, env)?; } Ok(RuntimeVal::Null) } StatementKind::StructDeclaration { name, members, functions, } => { env.declare_struct(name, members, functions) .map_err(|e| InterpreterError::StructDeclaration(format!("{e}")))?; Ok(RuntimeVal::Null) } // FIXME: put real type for return type StatementKind::FnDeclaration { name, args_and_type, body, return_stmt, return_type } => { env.declare_var( name.clone(), // Clone for closure capture for error RuntimeVal::Function { args_and_type, body, return_stmt, return_type }, true, VarType::Func, ) .map_err(|e| InterpreterError::FunctionDeclaration(name, e.to_string()))?; Ok(RuntimeVal::Null) } // TODO: Faire fonctionner la fonction de test err StatementKind::TestDeclaration { name, body } => { print!("Running test: {}...", name); let mut res: Vec<bool> = vec![]; // Tmp env let mut tmp_env = Env::new(Some(env)); // We check if this is a assert function that is called for node in body { let is_test = match &node { ASTNodeKind::Expression(ExpressionKind::FunctionCall { name, .. }) => { match &**name { "assert_eq" | "assert_neq" => true, _ => false, } } _ => false, }; // We interpret the node let run_val = self.interpret_node(node, &mut tmp_env); if is_test { match run_val { Ok(RuntimeVal::Bool(b)) => res.push(b), _ => res.push(false), } } // If not, if it is an error, we propagate it else { if let Err(e) = run_val { return Err(e); } } } // We check if there are only true result let final_res = res.into_iter().all(|x| x); // Result let final_text = match final_res { true => "Ok".green().bold(), false => "Ko".red().bold(), }; print!(" {}\n", final_text); Ok(RuntimeVal::Bool(final_res)) } } } } #[cfg(test)] mod tests { use crate::{ environment::{Env, EnvError}, interpreter::Interpreter, values::{RuntimeVal, StructMember, StructPrototype}, }; use frontend::parser::VarType; use crate::frontend::ast::{ASTNode, ASTNodeKind, ExpressionKind, StatementKind}; use std::rc::Rc; #[test] fn evaluate_var_declaration() { let interpr = Interpreter {}; let mut env = Env::new(None); env.declare_var("mass".into(), RuntimeVal::Real(120.), false, VarType::Real) .unwrap(); let var_name = String::from("position"); // We check that the var isn't yet declared assert!(matches!( env.lookup_var(&var_name), Err(EnvError::UndeclaredVar(_)) )); let var_decl = ASTNodeKind::Statement(StatementKind::VarDeclaration { name: var_name.clone(), value: ExpressionKind::RealLiteral { value: 45. }, constant: false, var_type: VarType::Any, }); let _ = interpr.execute_program(vec![ASTNode::new(var_decl, 0)], &mut env); // We should retreive it now assert_eq!(env.lookup_var(&var_name), Ok(&RuntimeVal::Real(45.))); } #[test] fn evaluate_var_declaration_already_declared() { let interpr = Interpreter {}; let var_name = String::from("mass"); let mut env = Env::new(None); env.declare_var(var_name.clone(), RuntimeVal::Real(120.), false, VarType::Any) .unwrap(); // We check that the var isn't yet declared assert!(env.lookup_var(&var_name).is_ok()); let var_decl = ASTNodeKind::Statement(StatementKind::VarDeclaration { name: var_name.clone(), value: ExpressionKind::RealLiteral { value: 45. }, constant: false, var_type: VarType::Any, }); let res = interpr.execute_program(vec![ASTNode::new(var_decl, 0)], &mut env); // We should retreive it now assert!(res.is_err()); } #[test] fn evaluate_var_assignment() { let interpr = Interpreter {}; let var_name = String::from("mass"); let var_name2 = String::from("gravity"); let mut env = Env::new(None); let var_decl = ASTNodeKind::Statement(StatementKind::VarDeclaration { name: var_name.clone(), value: ExpressionKind::RealLiteral { value: 45. }, constant: false, var_type: VarType::Any, }); let var_decl2 = ASTNodeKind::Statement(StatementKind::VarDeclaration { name: var_name2.clone(), value: ExpressionKind::RealLiteral { value: 20. }, constant: false, var_type: VarType::Any, }); let var_assign = ASTNodeKind::Expression(ExpressionKind::VarAssignment { assigne: Box::new(ExpressionKind::Identifier { symbol: var_name.clone(), }), value: Box::new(ExpressionKind::RealLiteral { value: 12. }), }); let var_assign_var = ASTNodeKind::Expression(ExpressionKind::VarAssignment { assigne: Box::new(ExpressionKind::Identifier { symbol: var_name2.clone(), }), value: Box::new(ExpressionKind::BinaryOp { left: Box::new(ExpressionKind::Identifier { symbol: var_name.clone(), }), right: Box::new(ExpressionKind::RealLiteral { value: 60. }), operator: '+'.to_string(), }), }); let _ = interpr.execute_program( vec![ ASTNode::new(var_decl, 0), ASTNode::new(var_decl2, 0), ASTNode::new(var_assign, 0), ASTNode::new(var_assign_var, 0), ], &mut env, ); // We should retreive it now assert_eq!( env.lookup_var(&var_name).unwrap(), &RuntimeVal::Real(12.) ); assert_eq!( env.lookup_var(&var_name2).unwrap(), &RuntimeVal::Real(72.) ); } #[test] fn evaluate_const_var_assignment() { let interpr = Interpreter {}; let var_name = String::from("mass"); let mut env = Env::new(None); let var_decl = ASTNodeKind::Statement(StatementKind::VarDeclaration { name: var_name.clone(), value: ExpressionKind::RealLiteral { value: 45. }, constant: true, var_type: VarType::Any, }); let var_assign = ASTNodeKind::Expression(ExpressionKind::VarAssignment { assigne: Box::new(ExpressionKind::Identifier { symbol: var_name.clone(), }), value: Box::new(ExpressionKind::RealLiteral { value: 12. }), }); let res = interpr.execute_program( vec![ASTNode::new(var_decl, 0), ASTNode::new(var_assign, 0)], &mut env, ); // We should retreive it now assert!(res.is_err()); } #[test] fn evaluate_struct_declaration() { let interpr = Interpreter {}; let mut env = Env::new(None); let name: String = "Planet".into(); let members = vec![("pos".into(), VarType::Any, false), ("radius".into(), VarType::Any, true)]; let constructor_args: Vec<(String, VarType)> = vec![ ("pos".into(), VarType::Any), ("x".into(), VarType::Any), ("radius".into(), VarType::Any), ("y".into(), VarType::Any), ]; let constructor = StatementKind::FnDeclaration { name: "new".into(), args_and_type: constructor_args.clone(), body: vec![], return_stmt: None, return_type: VarType::Void }; let struct_decl: ASTNodeKind = StatementKind::StructDeclaration { name: name.clone(), members, functions: vec![constructor], }.into(); interpr .execute_program(vec![ASTNode::new(struct_decl, 0)], &mut env) .expect("Error interpreting"); let members_expected: Vec<StructMember> = vec![ StructMember { name: "pos".into(), value: RuntimeVal::Null, constant: false, member_type: VarType::Any }, StructMember { name: "radius".into(), value: RuntimeVal::Null, constant: true, member_type: VarType::Any }, ]; // We should retreive it now assert_eq!( Rc::new(StructPrototype { name: name.clone(), members: members_expected, constructor: Some(RuntimeVal::Function { args_and_type: constructor_args, body: vec![], return_stmt: None, return_type: VarType::Void }), }), env.lookup_struct_prototype(&name) .expect("Error looking up structure proto") ); } #[test] fn evaluate_member_assignment_struct_decl() { let interpr = Interpreter {}; let mut env = Env::new(None); let name = String::from("Planet"); let constructor_args = vec![ ("pos".into(), VarType::Any), ("x".into(), VarType::Any), ("radius".into(), VarType::Any), ("y".into(), VarType::Any), ]; let constructor = StatementKind::FnDeclaration { name: "new".into(), args_and_type: constructor_args.clone(), body: vec![], return_stmt: None, return_type: VarType::Void }; let struct_decl: ASTNodeKind = StatementKind::StructDeclaration { name: name.clone(), members: vec![("pos".into(), VarType::Any, false), ("radius".into(), VarType::Any, true)], functions: vec![constructor], }.into(); let struct_create = ExpressionKind::FunctionCall { name: "Planet".into(), args: vec![ ExpressionKind::RealLiteral { value: 80. }, ExpressionKind::RealLiteral { value: 1. }, ExpressionKind::RealLiteral { value: 25. }, ExpressionKind::RealLiteral { value: 64. }, ] }; let var_decl = ASTNodeKind::Statement(StatementKind::VarDeclaration { name: "mars".into(), value: struct_create, constant: false, var_type: VarType::Struct("Planet".into()) }); let _ = interpr.execute_program( vec![ASTNode::new(struct_decl, 0), ASTNode::new(var_decl, 0)], &mut env, ); // We get the var let mars = env.lookup_var(&"mars".into()).expect("Error fetching mars"); if let RuntimeVal::Structure { members, .. } = mars { assert_eq!( members .borrow() .get(&String::from("pos")) .expect("Error getting member"), &RuntimeVal::Real(80.) ); assert_eq!( members .borrow() .get(&String::from("radius")) .expect("Error getting member"), &RuntimeVal::Real(25.) ); assert_eq!(members.borrow().get(&String::from("x")), None); assert_eq!(members.borrow().get(&String::from("y")), None); } else { assert!(false); } } }
import AggregateRoot from "../../../@shared/domain/entity/aggregate-root.interface"; import BaseEntity from "../../../@shared/domain/entity/base.entity"; import Id from "../../../@shared/domain/value-object/id.value-object"; import InvoiceItems from "./Invoice-items.entity"; import Address from "./value-object/address.value-object"; type InvoiceProps = { id?: Id; name: string; document: string; address: Address; items: InvoiceItems[]; createdAt?: Date; updatedAt?: Date; }; export default class Invoice extends BaseEntity implements AggregateRoot { _name: string; _document: string; _address: Address; _items: InvoiceItems[]; constructor(props: InvoiceProps) { super(props.id); this._name = props.name; this._document = props.document; this._address = props.address; this._items = props.items; this.updatedAt = props.updatedAt || new Date(); this.createdAt = props.createdAt || new Date(); this.validate(); } validate() { if (!this.name || this.name.length < 3) { this.addError("Nome inválido, deve ter no mínimo 3 caracteres"); } if (!this.document || this.document.length < 3) { this.addError("Documento inválido, deve ter no mínimo 3 caracteres"); } if (!this.address) { this.addError("Endereço inválido, deve ser informados"); } else if (!this.address.city || this.address.city.length < 2) { this.addError("Cidade inválida, deve ter no mínimo 2 caracteres"); } else if (!this.address.street || this.address.street.length < 3) { this.addError("Rua inválida, deve ter no mínimo 3 caracteres"); } else if (!this.address.number || this.address.number.length < 1) { this.addError("Número inválido, deve ter no mínimo 1 caracter"); } else if (!this.address.zipCode || this.address.zipCode.length < 8) { this.addError("CEP inválido"); } else if (!this.address.state || this.address.state.length < 2) { this.addError("Estado inválido"); } if (!this.items) { this.addError("Itens inválidos, deve ser informado 1 ou mais itens"); } else { this.items.forEach((item) => { if (item.hasErrors()) { this.getErros().push(...item.getErros()); } }); } } get total(): number { if (this.items) { let total = 0; this.items.forEach((i) => { total += i.price; }); return total; } } get name(): string { return this._name; } get document(): string { return this._document; } get address(): Address { return this._address; } get items(): InvoiceItems[] { return this._items; } }
# R SCRIPT # ------------------------------------------------------------------ # Author: Laura Grice # Date: 30th June 2020 # Title: 10f_ClusterStatsPlot.R # Goal: To plot a stacked bar plot and a heatmap for clustering vs. some condition of interest # Usage: Rscript 10f_ClusterStatsPlot.R {sampleID} {comparisonID} {cluster_col} {annotation_col} {seuratObj} {outdir} # WHERE: # sampleID and comparisonID are useful names used for saving the data # cluster_col and annotation_col are the column names for the clustering and some annotation of interest # ------------------------------------------------------------------ # ------------------------------------------------------------------ # INITIALISATION # ------------------------------------------------------------------ args <- commandArgs(trailingOnly=TRUE) if (length(args) != 6) { cat("ERROR: 6 arguments expected\n") cat("example: Rscript 10f_ClusterStatsPlot.R {sampleID} {comparisonID} {cluster_col} {annotation_col} {seuratObj} {outdir}\n") quit() } sampleID <- args[1] comparisonID <- args[2] cluster_col <- args[3] annotation_col <- args[4] df <- readRDS(args[5]) outdir <- args[6] # load packages #bioc_packages <- c() r_packages <- c("Seurat", "pheatmap", "ggplot2") ## function to load R packages baseRpkgTest <- function(x) { if (!suppressMessages(require(x,character.only = TRUE, quietly = T))) { install.packages(x,dep=TRUE, repos = "https://pbil.univ-lyon1.fr/CRAN/") if(!require(x,character.only = TRUE, quietly = T)) stop (paste0(x, "package not found")) } } # ## function to load bioconductor packages # biocondpkgTest <- function(x) { # if (!require(x,character.only = TRUE)) { # source("http://www.bioconductor.org/biocLite.R") # biocLite(x) # if(!require(x,character.only = TRUE)) stop (paste0(x, "bioconductor package not found")) # } # } # ## load packages # for (b_pkg in bioc_packages) { # biocondpkgTest(b_pkg) # } for (r_pkg in r_packages) { baseRpkgTest(r_pkg) } # checks if your outdir ends in / and adds one if not if (endsWith(outdir, "/") == FALSE) { outdir <- paste0(outdir, "/", sep="") } # ------------------------------------------------------------------ # MAKE PLOTS # ------------------------------------------------------------------ # Get the data plot <- DimPlot(df, group.by = cluster_col, split.by = annotation_col) # Plot 1: Stacked bar data <- as.data.frame(table(plot$data[,3:4])) colnames(data) <- c("cluster", "condition", "count") # Stacked + percent ggplot(data, aes(fill=condition, y=count, x=cluster)) + geom_bar(position="fill", stat="identity") ggsave(paste0(outdir, sampleID, "_", comparisonID, "_barplot.pdf")) # Plot 2: Heatmap mat <- as.matrix(table(plot$data[,3:4])) pheatmap(mat, scale = "row", filename = paste0(outdir, sampleID, "_", comparisonID, "_heatmap.pdf")) # ------------------------------------------------------------------ # SESSION INFO # ------------------------------------------------------------------ sink(paste0(outdir, sampleID, "_sessionInfo.txt")) sessionInfo() sink()
<!DOCTYPE html> <html> <head> <title>jQuery</title> <style> .cambiaColor{ height: 30px; font-size: 20px; font-weight: bold; border: 1px solid #000; cursor: default; } </style> </head> <body> <button id="boton">Haga clic aqui</button> <button id="cambiaColor">Cambia color</button> <a id="link" href="index.php">Inicio</a> <ul> <li class="cambiaColor">blue</li> <li class="cambiaColor">yellow</li> <li class="cambiaColor">red</li> </ul> <form> Nombre: <input type="text" name="nombre" > Apellido: <input type="text" name="apellido"> <select name ="option"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> <input type="submit" name=""> </form> <p id="texto"></p> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> <script> $(document).ready(function(){ //alert("Bienvenido"); }); $("#boton").click(function(){ alert("Bienvenido"); }); $("#cambiaColor").click(function(){ $("body").css("background-color","green"); }); $("#link").click(function (e){ e.preventDefault(); var url = $(this).attr("href"); alert(url); }); $(".cambiaColor").click(function(){ var color = $(this).text(); $("body").css("background-color",color); }); $("input[name='nombre']").change(function(){ var nombre = $(this).val(); $("#texto").text(nombre); }); $("select").change(function(){ var nombre = $(this).val(); $("#texto").text(nombre); }); $("form").submit(function(e){ e.preventDefault(); var datos = $(this).serialize(); alert(datos); }); </script> </body> </html>
import tkinter as tk from tkinter import filedialog, messagebox, simpledialog from PIL import Image, ImageTk import json class OnlineStoreApp: def __init__(self, root): self.root = root self.root.title("Онлайн магазин") self.users = self.load_users() self.current_user = None self.login_frame = self.create_login_frame() def load_users(self): try: with open('users.json', 'r') as file: return json.load(file) except FileNotFoundError: return [] def save_users(self): with open('users.json', 'w') as file: json.dump(self.users, file) def create_login_frame(self): frame = tk.Frame(self.root) frame.pack() self.login_label = tk.Label(frame, text="Введите имя пользователя:") self.login_label.pack(pady=10) self.login_entry = tk.Entry(frame) self.login_entry.pack(pady=10) self.login_button = tk.Button(frame, text="Войти", command=self.login) self.login_button.pack(pady=10) self.register_button = tk.Button(frame, text="Зарегистрироваться", command=self.register) self.register_button.pack(pady=10) return frame def add_item_to_cart(self, event): selected_item = self.catalogue_listbox.get(self.catalogue_listbox.curselection()) item_name, item_price = selected_item.split(" - ")[0], float(selected_item.split(" - ")[1][:-3]) new_product = {"name": item_name, "price": item_price} self.current_user["cart"].append(new_product) self.update_cart_listbox() self.save_users() def create_catalogue_frame(self): self.catalogue_frame = tk.Frame(self.root) self.catalogue_items = [ {"name": "Вода", "price": 12.0}, {"name": "Молоко", "price": 20.0}, {"name": "Кирпич", "price": 100.0}, {"name": "Карта сокровищ", "price": 250000.0}, {"name": "Пакет в пакете", "price": 2.0}, {"name": "Карандаш", "price": 10.0}, {"name": "Тетрадь", "price": 15.0}, {"name": "Ничего", "price": 0.0}, {"name": "Шоколадка", "price": 50.0}, {"name": "Орех", "price": 5.0}, ] self.scrollbar = tk.Scrollbar(self.catalogue_frame) self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y) self.catalogue_listbox = tk.Listbox(self.catalogue_frame, yscrollcommand=self.scrollbar.set) self.catalogue_listbox.pack(pady=10) self.scrollbar.config(command=self.catalogue_listbox.yview) for item in self.catalogue_items: self.catalogue_listbox.insert(tk.END, f"{item['name']} - {item['price']} ₽") self.catalogue_listbox.bind("<Double-Button-1>", self.add_item_to_cart) exit_button = tk.Button(self.catalogue_frame, text="Скрыть каталог", command=self.catalogue_frame.destroy) exit_button.pack(pady=10) return self.catalogue_frame def login(self): username = self.login_entry.get() for user in self.users: if user['name'] == username: self.current_user = user self.create_main_frame() self.login_frame.destroy() # Destroy the existing login frame return messagebox.showerror("Ошибка", "Пользователь не найден") def logout(self): self.current_user = None self.main_frame.destroy() self.login_frame.destroy() # Destroy the existing login frame self.login_frame = self.create_login_frame() # Create a new login frame self.login_frame.pack() self.catalogue_frame.destroy() self.profile_window.destroy() def register(self): username = simpledialog.askstring("Регистрация", "Введите ваше имя:") if username: new_user = {'name': username, 'cart': [], 'profile_picture': None} self.users.append(new_user) self.save_users() self.login_entry.delete(0, tk.END) self.login_entry.insert(tk.END, username) self.login() self.login_frame.destroy() def create_main_frame(self): self.login_frame.destroy() self.main_frame = tk.Frame(self.root) self.main_frame.pack() self.cart_listbox = tk.Listbox(self.main_frame, width=50) self.cart_listbox.pack(pady=10) def remove_item_from_cart(event): selected_index = self.cart_listbox.curselection() if selected_index: selected_index = selected_index[0] if selected_index >= 0 and selected_index < len(self.current_user['cart']): del self.current_user['cart'][selected_index] self.update_cart_listbox() self.save_users() self.cart_listbox.bind("<Double-Button-1>", remove_item_from_cart) self.add_to_cart_button = tk.Button(self.main_frame, text="Добавить в корзину", command=self.add_to_cart) self.add_to_cart_button.pack(pady=10) self.remove_from_cart_button = tk.Button(self.main_frame, text="Удалить из корзины", command=self.remove_from_cart) self.remove_from_cart_button.pack(pady=10) self.calculate_total_button = tk.Button(self.main_frame, text="Общая цена", command=self.calculate_total) self.calculate_total_button.pack(pady=10) self.catalogue_button = tk.Button(self.main_frame, text="Каталог", command=self.show_catalogue) self.catalogue_button.pack(pady=10) self.profile_button = tk.Button(self.main_frame, text="Профиль", command=self.open_or_update_profile) self.profile_button.pack(pady=10) self.logout_button = tk.Button(self.main_frame, text="Выйти", command=self.logout) self.logout_button.pack(pady=10) self.update_cart_listbox() def show_catalogue(self): self.catalogue_frame = self.create_catalogue_frame() self.catalogue_frame.pack() def add_to_cart(self): product_name = simpledialog.askstring("Добавить в корзину", "Введите название продукта:") product_price = simpledialog.askfloat("Добавить в корзину", "Введите цену продукта:") if product_name and product_price: new_product = {'name': product_name, 'price': product_price} self.current_user['cart'].append(new_product) self.update_cart_listbox() self.save_users() def remove_from_cart(self): if not self.current_user['cart']: messagebox.showinfo("Корзина пуста", "Ваша корзина пуста") return product_name = simpledialog.askstring("Удалить из корзины", "Введите название продукта для удаления:") if product_name: removed_product = None for product in self.current_user['cart']: if product['name'] == product_name: removed_product = product break if removed_product: self.current_user['cart'].remove(removed_product) self.update_cart_listbox() messagebox.showinfo("Удалено", f"{removed_product['name']} был удален из вашей корзины!") def calculate_total(self): total_price = sum(product['price'] for product in self.current_user['cart']) messagebox.showinfo("Общая цена", f"Общая стоимость вашей корзины: {total_price:.2f} ₽") def update_cart_listbox(self): self.cart_listbox.delete(0, tk.END) for item in self.current_user['cart']: self.cart_listbox.insert(tk.END, f"{item['name']} - {item['price']} ₽") def open_or_update_profile(self): if self.current_user: self.open_profile() else: messagebox.showerror("Ошибка", "Пожалуйста, войдите в свой профиль") def open_profile(self): self.profile_window = tk.Toplevel(self.root) self.profile_window.title(f"Ваш профиль, {self.current_user['name']}") self.name_label = tk.Label(self.profile_window, text="Имя: " + self.current_user['name'], font=('Helvetica', 14)) self.name_label.pack(pady=10) self.profile_picture_label = tk.Label(self.profile_window, text="Изображение профиля:") self.profile_picture_label.pack() self.update_profile_picture_label() change_name_button = tk.Button(self.profile_window, text="Изменить имя профиля", command=self.change_name) change_name_button.pack() upload_picture_button = tk.Button(self.profile_window, text="Загрузить фото", command=self.upload_picture) upload_picture_button.pack() delete_button = tk.Button(self.profile_window, text="Удалить профиль", command=self.delete_profile) delete_button.pack() close_button = tk.Button(self.profile_window, text="Закрыть", command=self.profile_window.destroy) close_button.pack() def delete_profile(self): if messagebox.askyesno("Удаление профиля", "Вы уверены, что хотите удалить свой профиль? Это действие необратимо."): self.users.remove(self.current_user) self.current_user = None self.save_users() self.profile_window.destroy() self.logout() def update_profile_window(self): self.name_label.config(text="Имя: " + self.current_user['name']) self.update_profile_picture_label() def update_profile_picture_label(self): if self.current_user['profile_picture']: image = Image.open(self.current_user['profile_picture']) image = image.resize((100, 100)) photo = ImageTk.PhotoImage(image) self.profile_picture_label.image = photo self.profile_picture_label.config(image=photo) self.profile_picture_label.pack() def change_name(self): new_name = simpledialog.askstring("Изменить имя профиля", "Введите ваше имя:") if new_name: if any(user['name'] == new_name for user in self.users if user != self.current_user): messagebox.showerror("Ошибка", "Имя занято. Пожалуйста, введите другое имя.") else: self.current_user['name'] = new_name self.update_profile_window() def upload_picture(self): file_path = filedialog.askopenfilename() if file_path: self.current_user['profile_picture'] = file_path self.update_profile_window() if __name__ == "__main__": root = tk.Tk() app = OnlineStoreApp(root) root.mainloop()
package com.PFA2.EduHousing.dto; import com.PFA2.EduHousing.model.Apartment; import com.PFA2.EduHousing.model.Favourites; import com.PFA2.EduHousing.model.Student; import com.fasterxml.jackson.annotation.JsonIgnore; import jakarta.persistence.Column; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import lombok.Builder; import lombok.Data; import java.util.stream.Collectors; @Data @Builder public class Favouritesdto { private Integer id; private String description; private Studentdto student; private Apartmentdto apartment; public static Favouritesdto fromEntity(Favourites favourites){ if(favourites==null){ return null; } return Favouritesdto.builder() .id(favourites.getId()) .description(favourites.getDescription()) .student( Studentdto.builder() .id(favourites.getStudent().getId()) .firstName(favourites.getStudent().getFirstName()) .lastName(favourites.getStudent().getLastName()) .email(favourites.getStudent().getEmail()) .build() ) .apartment( Apartmentdto.builder() .id(favourites.getApartment().getId()) .address(favourites.getApartment().getAddress()) .type(favourites.getApartment().getType()) .images(favourites.getApartment().getImageList().stream().map(ApartmentImagedto::fromEntity).collect(Collectors.toList())) .build() ) .build(); } public static Favourites toEntity(Favouritesdto favouritesdto){ if(favouritesdto==null){ return null; } Favourites favourites= new Favourites(); favourites.setId(favouritesdto.getId()); favourites.setDescription(favouritesdto.getDescription()); favourites.setStudent(Studentdto.toEntity(favouritesdto.getStudent())); favourites.setApartment(Apartmentdto.toEntity(favouritesdto.getApartment())); return favourites ; } }
import { BeforeUpdate, Column, Entity, PrimaryGeneratedColumn } from 'typeorm' /*enum Ticker { 'NASDAQ:CSCO', 'NASDAQ:SPLK', 'NASDAQ:NCNO' }*/ @Entity({ name: 'articles' }) export class ArticleEntity { @PrimaryGeneratedColumn() id: number @Column({ default: '' }) slug: string @Column({ unique: true }) title: string @Column() date: Date //При создании записи в БД значение будет присвоено автоматически @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' }) createdAt: Date @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' }) updatedAt: Date @Column('simple-array', { default: [] }) tagList: string[] @Column({ default: 0 }) favoritesCount: number @Column({ default: '' }) content: string @Column() tickers: string @Column() image: string @Column() link: string @Column() author: string @Column() site: string //Автоматическое заполнение поля при обновлении записи @BeforeUpdate() updateTimestamp() { this.updatedAt = new Date() } }
import React from 'react'; import { View, Text, TextStyle } from 'react-native'; import Icon from '../icon/icon.component'; import styles from './text.style'; type FlowType = 'row'|'row-reverse'|'column'|'column-reverse'; const stylesMapping: { [key in FlowType]: any } = { 'column': { containerFlow: 'column', iconMargin: 0, textMargin: 3 }, 'column-reverse': { containerFlow: 'column-reverse', iconMargin: 3 }, 'row': { containerFlow: 'row', // textFlex:1 }, 'row-reverse': { containerFlow: 'row-reverse', textFlex:1 } } interface iProps { text: string, icon?: string, fontSize?: number, reverse?: boolean, flow?: FlowType, color?: string, style?: TextStyle, bold?: boolean, numberOfLines?: number } const AppText:React.FC<iProps> = ({ text, icon, fontSize = 15, flow = 'row', color, style, bold = false, numberOfLines = 1 }) => { const inlineStyles = () => { const { containerFlow, textFlex, iconMargin, textMargin } = stylesMapping[flow]; const container = { flexDirection: containerFlow, } as TextStyle; const text = { fontSize, flex: textFlex, marginBottom: textMargin, color, fontWeight: bold ? '700' : '300', // width: '100%' } as TextStyle; const icon = { marginBottom: iconMargin } as TextStyle; return { container, text, icon } } const iconSize = () => { return fontSize + (fontSize * .35) } return ( <View style={[styles.container, inlineStyles().container, style]}> <Text style={[styles.text, inlineStyles().text]} numberOfLines={numberOfLines}> {text} </Text> { icon && <Icon color={color} name={icon as any} size={iconSize()} style={[styles.icon, inlineStyles().icon]} /> } </View> ); } export default AppText;
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ protected $redirectTo = RouteServiceProvider::HOME; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } public function showLoginForm() { return view('auth.login', ['request_url' => $_GET['request_url']]); } public function login(Request $request) { $request->validate([ 'email' => 'required', 'password' => 'required', ]); $credentials = $request->only('email', 'password'); if (! $token = auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } $authUser = auth()->user(); //redirect to external url with token if($request->request_url){ return redirect($request->request_url . '?token=' . $token ); } } protected function respondWithToken($token) { $authUser = auth()->user(); return response()->json([ 'access_token' => $token, 'package' => $authUser->package, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } }
package com.example.android_nhom8.login; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.example.android_nhom8.R; import com.example.android_nhom8.User; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.regex.Pattern; public class register extends AppCompatActivity implements View.OnClickListener{ private EditText fullname,email,phone,password,conPassword; private TextView txtLoginNow; private Button btnRegister; private FirebaseAuth firebaseAuth; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); fullname =(EditText) findViewById(R.id.fullname); email =(EditText) findViewById(R.id.email); phone = (EditText) findViewById(R.id.phone); password =(EditText) findViewById(R.id.password); conPassword =(EditText) findViewById(R.id.conPassword); btnRegister = findViewById(R.id.btnRegister); txtLoginNow = findViewById(R.id.txtLoginNow); progressBar = (ProgressBar) findViewById(R.id.progressBar); firebaseAuth = FirebaseAuth.getInstance(); btnRegister.setOnClickListener(this); txtLoginNow.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()){ case(R.id.txtLoginNow): onBackPressed(); break; case(R.id.btnRegister): registerUser(); break; } } private void registerUser() { String txtFullname = fullname.getText().toString().trim(); String txtEmail = email.getText().toString().trim(); String txtPhone = phone.getText().toString().trim(); String txtPassword = password.getText().toString().trim(); String txtConPassword = conPassword.getText().toString().trim(); if(txtFullname.isEmpty()){ fullname.setError("Fullname is required!"); fullname.requestFocus(); return; } if(txtEmail.isEmpty()){ email.setError("Email is required!"); email.requestFocus(); return; } if(!Patterns.EMAIL_ADDRESS.matcher(txtEmail).matches()){ email.setError("Please provide valid Email!"); email.requestFocus(); return; } if(txtPhone.isEmpty()){ phone.setError("Phone is required!"); phone.requestFocus(); return; } if(txtPassword.isEmpty()){ password.setError("Password is required!"); password.requestFocus(); return; } if(txtConPassword.isEmpty()) { conPassword.setError("Confirm Password is required!"); conPassword.requestFocus(); return; } if(!txtConPassword.equals(txtPassword)){ conPassword.setError("Password & Confirm Password aren't meet!"); conPassword.requestFocus(); return; } progressBar.setVisibility(View.VISIBLE); firebaseAuth.createUserWithEmailAndPassword(txtEmail,txtPassword).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ User user = new User(txtFullname,txtPhone,txtEmail); FirebaseDatabase.getInstance().getReference("Users") .child(FirebaseAuth.getInstance().getCurrentUser().getUid()) .setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { if(task.isSuccessful()) { Toast.makeText(register.this, "Registered successfully!", Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); } else{ Toast.makeText(register.this, "Failed to register!", Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); } } }); } else{ Toast.makeText(register.this, "Failed to register!", Toast.LENGTH_SHORT).show(); progressBar.setVisibility(View.GONE); } } }); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.11 <0.9.0; import "@synthetixio/core-contracts/contracts/utils/SafeCast.sol"; import "@synthetixio/core-contracts/contracts/utils/DecimalMath.sol"; import "../storage/NodeDefinition.sol"; import "../storage/NodeOutput.sol"; library PriceDeviationCircuitBreakerNode { using SafeCastU256 for uint256; using DecimalMath for int256; error DeviationToleranceExceeded(int256 deviation); error InvalidInputPrice(); function process( NodeOutput.Data[] memory parentNodeOutputs, bytes memory parameters ) internal pure returns (NodeOutput.Data memory nodeOutput) { uint256 deviationTolerance = abi.decode(parameters, (uint256)); int256 primaryPrice = parentNodeOutputs[0].price; int256 comparisonPrice = parentNodeOutputs[1].price; if (primaryPrice != comparisonPrice) { int256 difference = abs(primaryPrice - comparisonPrice).upscale(18); if ( primaryPrice == 0 || deviationTolerance.toInt() < (difference / abs(primaryPrice)) ) { if (parentNodeOutputs.length > 2) { return parentNodeOutputs[2]; } else { if (primaryPrice == 0) { revert InvalidInputPrice(); } else { revert DeviationToleranceExceeded(difference / abs(primaryPrice)); } } } } return parentNodeOutputs[0]; } function abs(int256 x) private pure returns (int256 result) { return x >= 0 ? x : -x; } function isValid(NodeDefinition.Data memory nodeDefinition) internal pure returns (bool valid) { // Must have 2-3 parents if (!(nodeDefinition.parents.length == 2 || nodeDefinition.parents.length == 3)) { return false; } // Must have correct length of parameters data if (nodeDefinition.parameters.length != 32) { return false; } return true; } }
/* eslint jsx-a11y/click-events-have-key-events: off */ import React from 'react' import PropTypes from 'prop-types' import InputWithFocus from './InputWithFocus' const styles = {} styles.input = { fontFamily: 'verdana', fontSize: '11pt', background: '#fff', border: '1px solid transparent', outline: 'none', } styles.wrapper = { flex: 1, display: 'flex', justifyContent: 'space-between', } styles.description = { ...styles.input, flex: 1, } styles.estimate = { ...styles.input, width: 50, textAlign: 'right', } class InlineEditForm extends React.Component { static propTypes = { id: PropTypes.number.isRequired, details: PropTypes.shape({ description: PropTypes.string.isRequired, status: PropTypes.bool.isRequired, estimate: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), }).isRequired, focusOn: PropTypes.string, onChange: PropTypes.func.isRequired, } static defaultProps = { focusOn: 'description', } state = { details: { ...this.props.details, }, } emitOnChange = () => { this.props.onChange(this.props.id, this.state.details) } updateDescription = (evt) => { this.setState({ details: { ...this.state.details, description: evt.target.value, }, }) setTimeout(this.emitOnChange) } updateEstimate = (evt) => { this.setState({ details: { ...this.state.details, estimate: evt.target.value, }, }) setTimeout(this.emitOnChange) } render () { return ( <div style={styles.wrapper}> <InputWithFocus hasFocus={this.props.focusOn === 'description'} value={this.state.details.description} onChange={this.updateDescription} onCancel={() => { }} style={styles.description} /> <InputWithFocus hasFocus={this.props.focusOn === 'estimate'} value={this.state.details.estimate} onChange={this.updateEstimate} style={styles.estimate} /> </div> ) } } export default InlineEditForm
using Mirror; using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using UnityEngine.Events; public class NetworkChangeEquipment3 : NetworkBehaviour { //public static NetworkChangeEquipment3 Instance; [SerializeField] Weapon[] weaponScriptableObjects = null; [SerializeField] Transform weaponHolderTransform = null; [SerializeField] GameObject weaponHolder = null; [SerializeField] Animator animator = null; public static UnityEvent OnLocalPlayerStart = new UnityEvent(); [SyncVar(hook = nameof(OnChangeWeaponType))] public WeaponType weaponType; private void OnEnable() { WeaponSelectionScreen.OnWeaponButtonDisabled.AddListener(DestroyWeaponOnServer); } private void OnDisable() { WeaponSelectionScreen.OnWeaponButtonDisabled.RemoveListener(DestroyWeaponOnServer); } void OnChangeWeaponType(WeaponType oldWeaponType, WeaponType newWeaponType) { StartCoroutine(ChangeWeapon(newWeaponType)); } public override void OnStartLocalPlayer() { base.OnStartLocalPlayer(); OnLocalPlayerStart.Invoke(); #region Set Weapon ScriptableObjects to false foreach (Weapon weaponScriptableObject in weaponScriptableObjects) { weaponScriptableObject.allowed = false; } #endregion #region Set Weapon ScriptableObjects using PlayerMain.allowedWeaponsDict //foreach (KeyValuePair<string, bool> p in PlayerMain.allowedWeaponsDict) //{ // if (p.Value == true) // { // foreach (Weapon weapon in weaponScriptableObjects) // { // if (weapon.weaponType.ToString() == p.Key) // { // weapon.allowed = true; // } // } // } //} #endregion } #region Enable Weapon Functions public void EnableWoodenSwordButton() { if (!isLocalPlayer) return; CmdSetWeaponType(WeaponType.swordWooden); } public void EnableSteelSwordButton() { if (!isLocalPlayer) return; CmdSetWeaponType(WeaponType.swordSteel); } public void EnableRubySwordButton() { if (!isLocalPlayer) return; CmdSetWeaponType(WeaponType.swordRuby); } public void EnableEmeraldSwordButton() { if (!isLocalPlayer) return; CmdSetWeaponType(WeaponType.swordEmerald); } public void EnableScytheButton() { if (!isLocalPlayer) return; CmdSetWeaponType(WeaponType.scythe); } public void EnableStaffButton() { if (!isLocalPlayer) return; CmdSetWeaponType(WeaponType.staff); } public void EnableHammerButton() { if (!isLocalPlayer) return; CmdSetWeaponType(WeaponType.hammer); } public void EnableAxeButton() { if (!isLocalPlayer) return; CmdSetWeaponType(WeaponType.axe); } public void EnableDaggerButton() { if (!isLocalPlayer) return; CmdSetWeaponType(WeaponType.dagger); } #endregion IEnumerator ChangeWeapon(WeaponType newWeaponType) { while (weaponHolder.transform.childCount > 0) { Destroy(weaponHolder.transform.GetChild(0).gameObject); // change this to cmd yield return null; } switch (newWeaponType) { case WeaponType.axe: CmdSpawnWeapon(WeaponType.axe); break; case WeaponType.dagger: CmdSpawnWeapon(WeaponType.dagger); break; case WeaponType.hammer: CmdSpawnWeapon(WeaponType.hammer); break; case WeaponType.scythe: CmdSpawnWeapon(WeaponType.scythe); break; case WeaponType.swordSteel: CmdSpawnWeapon(WeaponType.swordSteel); break; case WeaponType.swordWooden: CmdSpawnWeapon(WeaponType.swordWooden); break; case WeaponType.swordRuby: CmdSpawnWeapon(WeaponType.swordRuby); break; case WeaponType.swordEmerald: CmdSpawnWeapon(WeaponType.swordEmerald); break; case WeaponType.staff: CmdSpawnWeapon(WeaponType.staff); break; } } [Command] void CmdSetWeaponType(WeaponType wt) { weaponType = wt; } [Command] void CmdSpawnWeapon(WeaponType wt) { if (weaponScriptableObjects == null) return; if (weaponHolder.transform.childCount > 0) { NetworkServer.Destroy(weaponHolder.transform.GetChild(0).gameObject); } foreach (Weapon weaponScriptableObject in weaponScriptableObjects) { //if(weaponScriptableObject.weaponType == wt && weaponScriptableObject.allowed) if (weaponScriptableObject.weaponType == wt) { animator.runtimeAnimatorController = weaponScriptableObject.weaponAnimOverride; GameObject instantiatedWeapon = Instantiate(weaponScriptableObject.weaponPrefab, weaponHolderTransform); NetworkServer.Spawn(instantiatedWeapon, connectionToClient); RpcSpawnWeapon(weaponScriptableObject.weaponType); } } } [ClientRpc] void RpcSpawnWeapon(WeaponType CmdWt) { foreach (Weapon weaponScriptableObject in weaponScriptableObjects) { if (weaponScriptableObject.weaponType == CmdWt) { animator.runtimeAnimatorController = weaponScriptableObject.weaponAnimOverride; GameObject instantiatedWeapon = Instantiate(weaponScriptableObject.weaponPrefab, weaponHolderTransform); instantiatedWeapon.transform.SetParent(weaponHolderTransform); } } } void DestroyWeaponOnServer() { if (!isLocalPlayer) return; CmdDestroyWeapon(); } [Command] public void CmdDestroyWeapon() { if (weaponHolder.transform.childCount > 0) { NetworkServer.Destroy(weaponHolder.transform.GetChild(0).gameObject); RpcDestroyWeaponOnClient(); } } [ClientRpc] void RpcDestroyWeaponOnClient() { if (weaponHolder.transform.childCount > 0) { Destroy(weaponHolder.transform.GetChild(0).gameObject); } } }
/** * This is the main component of the application. * It renders the header and main content of the app. * The header contains a logo and a link to create a new post. * The main content contains the routes to the home page and create post page. * @return {JSX.Element} Returns the main component of the app. */ import React from 'react'; import { BrowserRouter, Link, Route, Routes} from 'react-router-dom'; import { logo } from './assets'; import { Home, CreatePost } from './pages'; const App = () => { return ( <BrowserRouter> {/* Header section */} <header className="w-full flex justify-between items-center bg-[#eef5fc] sm:px-8 px-4 py-4 "> <Link to="/"> <img src={logo} alt="logo" className="w-28 h-15 object-contain"/> </Link> <Link to="/createpost" className="font-inter font-medium bg-[#120476] text-white py-2 px-4 rounded-md">Create</Link> </header> {/* Main content section */} <main className="sm:p-8 px-4 py-8 w-full bg-[#eef5fc] min-h-[calc(100vh-73px)]"> <Routes> <Route path="/" element={<Home />}/> <Route path="/createpost" element={<CreatePost />}/> </Routes> </main> </BrowserRouter> ) } export default App
package backup import ( "archive/zip" "io" "os" "path/filepath" ) type Archiver interface { DestExt() string Archiver(src, dst string) error } type zipper struct { } func (z *zipper) Archiver(src, dst string) error { if err := os.MkdirAll(filepath.Dir(dst), os.ModePerm); err != nil { return err } out, err := os.Create(dst) if err != nil { return err } defer out.Close() w := zip.NewWriter(out) defer w.Close() return filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if info.IsDir() { return nil // skip } if err != nil { return err } in, err := os.Open(path) if err != nil { return err } defer in.Close() f, err := w.Create(path) if err != nil { return err } _, err = io.Copy(f, in) if err != nil { return err } return nil }) } func (z *zipper) DestExt() string { return ".zip" } // ZIP 建立不同的 Archive 对象,对外暴露只有名字不同,类型一样。但是不同名字的 Archieve 却可以再同名函数下完成不同的功能。 var ZIP Archiver = (*zipper)(nil)
import { motion } from "framer-motion"; import { iconsArray } from "../assets/iconsArray"; const Home: React.FC = () => { let y = -30; let delay = 0.1; let duration = 0.2; const displayIcons = iconsArray.map((icon, i) => { return ( <motion.li className="hover:text-react" whileHover={{ scale: 1.5 }} key={i} > <a href={icon.link} target="#"> <img src={icon.src} alt={icon.alt} className="w-5 xl:w-[1.5rem]" /> </a> </motion.li> ); }); return ( <motion.section className="relative h-[75vh] w-full lg:h-[80vh]"> <div className="flex h-full flex-col items-center"> <h1 className="absolute top-8 text-center text-2xl font-bold text-react underline underline-offset-8 xl:text-3xl "> Home </h1> <motion.div className="my-auto flex w-4/5 max-w-[45rem] flex-col items-center lg:justify-center "> <motion.h2 className="font-poppins text-[2.4rem] font-bold text-title xl:text-[4.2rem]" initial={{ opacity: 0, y: y }} animate={{ opacity: 1, y: 0, transition: { delay: delay + 0.1, duration: duration }, }} > <motion.span className="block text-xs text-react xl:mb-3 xl:text-[0.81rem]" initial={{ opacity: 0, y: y }} animate={{ opacity: 1, y: 0, transition: { delay: delay + 0.2, duration: duration }, }} > HI, I'M </motion.span> JAWAD NAZIR </motion.h2> <motion.span className="mt-4 font-poppins text-sm text-react underline decoration-dashed underline-offset-8 md:text-[1.1rem] xl:mt-8 xl:text-[1.7rem]" initial={{ opacity: 0, y: y }} animate={{ opacity: 1, y: 0, transition: { delay: delay + 0.3, duration: duration }, }} > Front-End Developer </motion.span> <motion.p className="mt-12 block text-center text-xs text-[#282d35] md:w-[50ch] xl:text-base 2xl:text-lg lg-2:w-[65ch]" initial={{ opacity: 0, y: y }} animate={{ opacity: 1, y: 0, transition: { delay: delay + 0.5, duration: duration }, }} > A Developer with a passion for creating simple and intuitive web experiences. <br /> <span className="mt-2 block"> I'm currently seeking a role as a Front-End Developer. </span> </motion.p> <motion.a href={require("../assets/jawad-resume.pdf")} download="Resume.pdf" className="relative top-12 w-fit cursor-pointer rounded-lg bg-body p-[.8rem] text-xs text-white shadow-card before:absolute before:left-[4px] before:bottom-[4px] before:h-full before:w-full before:rounded-lg before:border-2 before:border-react lg:top-[3.5rem] xl:p-4 xl:text-base 2xl:px-4 2xl:text-lg " initial={{ opacity: 0, y: y }} animate={{ opacity: 1, y: 0, rotateX: "-5deg", transition: { delay: delay + 0.6, duration: duration }, }} whileHover={{ scale: 1.2, opacity: 1, zIndex: 20 }} > Resume </motion.a> </motion.div> <motion.ul className="relative mx-auto flex w-full items-center justify-evenly gap-2 bg-body p-2 shadow-card md:mb-4 md:max-w-[20rem] md:rounded-xl xl:max-w-[25rem] xl:p-3" initial={{ opacity: 0, y: -y }} animate={{ opacity: 1, y: 0, transition: { delay: delay + 0.8 } }} > {displayIcons} </motion.ul> </div> <h4 className="fixed right-0 bottom-0 z-10 font-poppins text-[0.75rem] text-white lg:m-3"> Designed & built with <span className="text-red-500">&#10084;</span> by <span className="text-white"> Jawad Nazir.</span> </h4> </motion.section> ); }; export default Home;
import { DatasourceStatus, DatasourceType, SubscriptionPlan, Usage, } from '@prisma/client'; import { TaskLoadDatasourceRequestSchema } from '@app/types/dtos'; import accountConfig from '@app/utils/account-config'; import { s3 } from '@app/utils/aws'; import { DatastoreManager } from '@app/utils/datastores'; import type { Document } from '@app/utils/datastores/base'; import { DatasourceLoader } from '@app/utils/loaders'; import logger from '@app/utils/logger'; import prisma from '@app/utils/prisma-client'; import { ApiError, ApiErrorType } from './api-error'; import cuid from './cuid'; import findDomainPages, { getSitemapPages } from './find-domain-pages'; import findSitemap from './find-sitemap'; import guardDataProcessingUsage from './guard-data-processing-usage'; import triggerTaskLoadDatasource from './trigger-task-load-datasource'; const taskLoadDatasource = async (data: TaskLoadDatasourceRequestSchema) => { logger.info(`${data.datasourceId}: fetching datasource`); const datasource = await prisma.appDatasource.update({ where: { id: data.datasourceId, }, data: { status: DatasourceStatus.running, }, include: { datastore: true, owner: { include: { usage: true, subscriptions: { where: { status: 'active', }, }, }, }, }, }); if (!datasource) { throw new Error('Not found'); } const currentPlan = datasource?.owner?.subscriptions?.[0]?.plan || SubscriptionPlan.level_0; try { guardDataProcessingUsage({ usage: datasource?.owner?.usage as Usage, plan: currentPlan, }); } catch { logger.info(`${data.datasourceId}: usage limit reached`); await prisma.appDatasource.update({ where: { id: datasource.id, }, data: { status: DatasourceStatus.usage_limit_reached, }, }); return; } // TODO: find a better way to handle this if (datasource.type === DatasourceType.web_site) { let urls: string[] = []; let nestedSitemaps: string[] = []; const sitemap = (datasource.config as any).sitemap; const source = (datasource.config as any).source; if (sitemap) { const { pages, sitemaps } = await getSitemapPages(sitemap); urls = pages; nestedSitemaps = sitemaps; } else if (source) { // Try to find sitemap const sitemapURL = await findSitemap(source); if (sitemapURL) { const { pages, sitemaps } = await getSitemapPages(sitemapURL); urls = pages; nestedSitemaps = sitemaps; } else { // Fallback to recursive search urls = await findDomainPages(source); } } else { return; } urls = urls.slice( 0, accountConfig[currentPlan]?.limits?.maxWebsiteURL || 10 ); const ids = urls.map(() => cuid()); const idsSitemaps = nestedSitemaps.map(() => cuid()); if (ids.length > 0) { await prisma.appDatasource.createMany({ data: urls.map((each, idx) => ({ id: ids[idx], type: DatasourceType.web_page, name: each, config: { ...(datasource.config as any), source: each, }, ownerId: datasource?.ownerId, datastoreId: datasource?.datastoreId, })), }); } if (idsSitemaps.length > 0) { await prisma.appDatasource.createMany({ data: nestedSitemaps.map((each, idx) => ({ id: idsSitemaps[idx], type: DatasourceType.web_site, name: each, config: { ...(datasource.config as any), sitemap: each, }, ownerId: datasource?.ownerId, datastoreId: datasource?.datastoreId, })), }); } await triggerTaskLoadDatasource( [...ids, ...idsSitemaps].map((each) => ({ userId: datasource?.ownerId!, datasourceId: each, priority: 10, })) ); await prisma.appDatasource.delete({ where: { id: datasource.id, }, }); logger.info( `${datasource?.id}: datasource of type ${datasource?.type} runned successfully` ); return; } console.log('datasource', datasource); let document: Document; try { document = data.isUpdateText ? await new DatasourceLoader(datasource).loadText() : await new DatasourceLoader(datasource).load(); } catch (err) { if (err instanceof ApiError) { if (err.name === ApiErrorType.WEBPAGE_IS_SITEMAP) { console.log( 'ApiErrorType.WEBPAGE_IS_SITEMAP', ApiErrorType.WEBPAGE_IS_SITEMAP ); // WebPage is a sitemap re-run as a sitemap await prisma.appDatasource.update({ where: { id: datasource.id, }, data: { type: DatasourceType.web_site, status: DatasourceStatus.unsynched, config: { ...(datasource.config as any), sitemap: (datasource?.config as any)?.source, }, }, }); // await triggerTaskLoadDatasource([ { userId: datasource.ownerId!, datasourceId: datasource.id, priority: 2, }, ]); return; } } throw err; } // console.log('document', document); const chunks = await new DatastoreManager(datasource.datastore!).upload( document ); const hash = chunks?.[0]?.metadata?.datasource_hash as string; logger.info(`${data.datasourceId}: loading finished`); const updated = await prisma.appDatasource.update({ where: { id: datasource.id, }, data: { nbChunks: chunks.length, textSize: document?.pageContent?.length || 0, status: DatasourceStatus.synched, lastSynch: new Date(), nbSynch: datasource?.nbSynch! + 1, hash, // Update usage owner: { update: { usage: { update: { nbDataProcessingBytes: (datasource?.owner?.usage?.nbDataProcessingBytes || 0) + new TextEncoder().encode(document?.pageContent).length, }, }, }, }, }, include: { datastore: true, }, }); // Add to S3 const params = { Bucket: process.env.NEXT_PUBLIC_S3_BUCKET_NAME!, Key: `datastores/${datasource.datastore?.id}/${datasource.id}/data.json`, Body: Buffer.from( JSON.stringify({ hash, text: document.pageContent, }) ), CacheControl: 'no-cache', ContentType: 'application/json', ACL: 'public-read', }; await s3.putObject(params).promise(); logger.info(`${data.datasourceId}: datasource runned successfully`); }; export default taskLoadDatasource;
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; contract RecipeContract { struct Recipe { string name; string[] ingredients; uint256 fundAmount; address recipeOwnerAddress; uint256 fundRaisedSoFar; uint256 timeForFund; } mapping(string => uint256) private recipeIdx; Recipe[] private recipes; event RecipeCreated(string name); function createRecipe( string memory _name, string[] memory _ingredients, uint256 _fundAmount, uint256 _timeForFund ) public { recipeIdx[_name] = recipes.length; Recipe memory newRecipe; newRecipe.name = _name; newRecipe.ingredients = _ingredients; newRecipe.fundAmount = _fundAmount; newRecipe.timeForFund = _timeForFund; newRecipe.recipeOwnerAddress = msg.sender; newRecipe.fundRaisedSoFar = 0; recipes.push(newRecipe); emit RecipeCreated(_name); } function getRecipe( string memory _name ) public view returns ( string memory name, string[] memory ingredients, uint256 fundAmount, address recipeOwnerAddress, uint256 fundRaisedSoFar, uint256 timeForFund ) { uint256 recipeIndex = recipeIdx[_name]; require(recipeIndex < recipes.length, "Recipe does not exist"); Recipe memory recipe = recipes[recipeIndex]; return ( recipe.name, recipe.ingredients, recipe.fundAmount, recipe.recipeOwnerAddress, recipe.fundRaisedSoFar, recipe.timeForFund ); } function sendFunding(uint256 indexOfRecipe) public payable { require(msg.value > 0, "Please add more fund"); recipes[indexOfRecipe].fundRaisedSoFar += msg.value; } function withdrawFunding(string memory _name) public { uint256 recipeIndex = recipeIdx[_name]; require(recipeIndex < recipes.length, "Recipe does not exist"); Recipe storage recipe = recipes[recipeIndex]; require( msg.sender == recipe.recipeOwnerAddress, "Only the recipe owner can withdraw funds" ); require(recipe.fundRaisedSoFar >= recipe.fundAmount, "Not enough fund"); uint256 amountToWithdraw = recipe.fundRaisedSoFar; recipe.fundRaisedSoFar = 0; // Reset the raised funds to zero (bool success, ) = msg.sender.call{value: amountToWithdraw}(""); require(success, "Withdrawal failed"); } }
const express = require('express'); const session = require('express-session'); const mysql = require('mysql'); const path = require('path'); const { createUsers, createAdmins, createToys, createClothings, createFeeds, createAccessories } = require('../animalsite/public/factories.js'); const parser = require('./public/parser'); // Подключаем файл с настройкой парсера const registerRouter = require('./public/register'); // Подключаем файл с обработчиком регистрации const loginRouter = require('./public/login'); //Подключаем файл с обработчиком авторизации const profileRouter = require('./public/profile'); // Подключаем файл с обработчиком профиля const logoutRouter = require('./public/logout'); // Подключаем файл с обработчиком выхода const addToyToCart = require('./public/addToyToCart'); //Подключаем файл с обработчиком покупок игрушек const addClothingToCart = require('./public/addClothingToCart'); //Подключаем файл с обработчиком покупок одежды const addFeedToCart = require('./public/addFeedToCart'); //Подключаем файл с обработчиком покупок корма const addAccessoryToCart = require('./public/addAccessoryToCart'); //Подключаем файл с обработчиком покупок аксессуаров const enterRouter = require('./public/Routes/enter'); //Подключаем обработчик страницы авторизации const cartRouter = require('./public/Routes/cart'); //Подключаем обработчик страницы корзины const removeItemRouter = require('./public/removeItem'); //Подключаем обработчик удаления товара из корзины //Маршруты товаров const toyRoutes = require('./public/Routes/toys'); const clothingRoutes = require('./public/Routes/clothing'); const feedRoutes = require('./public/Routes/feed'); const accessoryRoutes = require('./public/Routes/accessory'); const shopRoutes = require('./public/Routes/shop'); const app = express(); const port = 3000; app.set('views', path.join(__dirname, 'public')); app.set('view engine', 'ejs'); // Настройка сессий app.use(session({ secret: 'TPFtZomp0o', resave: false, saveUninitialized: true, })); function handleDisconnect() { // Создание подключения к базе данных var connection = mysql.createConnection({ host : 'animalzd.beget.tech', user : 'animalzd_goods', password : 'Qwerty12345', database : 'animalzd_goods', }); // Подключение к базе данных connection.connect(function(err) { if (err) { console.error('Ошибка подключения: ' + err.stack); return; } console.log('Успешно подключено к базе данных с ID ' + connection.threadId); }); // Обработка ошибок соединения connection.on('error', function(err) { console.error('Ошибка базы данных: ' + err); if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Если соединение было потеряно, повторно подключаемся handleDisconnect(); } else { throw err; } }); // Присваиваем подключение глобальной переменной global.db = connection; } app.use(express.urlencoded({extended: true})); app.use(parser); // Используем настройки парсера из parser.js app.use(registerRouter); // Используем маршрут для обработки регистрации app.use(loginRouter); //Используем маршрут для обработки авторизации app.use(profileRouter); // Используем маршрут для обработки профиля app.use(logoutRouter); //Используем маршрут для обработки выхода app.use('/enter', enterRouter); //Используем обработчик страницы входа app.use('/cart', cartRouter); //Используем обработчик страницы корзина app.use(removeItemRouter); //Используем обработчик удаления товара из корзины //Использование маршрутов товаров app.use('/toys', toyRoutes); app.use('/clothing', clothingRoutes); app.use('/feed', feedRoutes); app.use('/accessory', accessoryRoutes); app.use('/shop', shopRoutes); //Использование покупок товаров app.use('/', addToyToCart); app.use('/', addClothingToCart); app.use('/', addFeedToCart); app.use('/', addAccessoryToCart); // Запускаем функцию обработки подключения handleDisconnect(); //Заполняем базу данных // async function createAll() { // await createUsers(); // await createAdmins(); // await createToys(); // await createClothings(); // await createFeeds(); // await createAccessories(); // console.log('Все функции выполнены последовательно'); // } // createAll().catch((error) => console.error('Ошибка:', error)); // Обслуживание статических файлов из папки 'public' app.use(express.static('public')); app.get('/', (req, res) => { // Отправка файла 'index.html' в ответ на запрос к главной странице res.sendFile(__dirname + '/public/index.html'); }); app.listen(port, () => { console.log("Server listening at http://localhost:" + port); });