text
stringlengths
184
4.48M
### 577 Day 69 Goals - Adding Users to Our Blog Project Wouldn't it be great if we could have some users on our blog? What if we could let anyone sign up and comment on our blog posts? In order for that to work, we would need to add authentication to our blog. This will be the final step in our Blog Capstone Project. Once we're done, it will be a fully-fledged blog website that you can publish and launch. This is what you'll make by the end: ![01](./images/01.gif) ### 578 Download the Starting Project ### 579 Requirement 1 - Register New Users 1. Use what you've learnt yesterday to allow users to go to the /register route to sign up to your blog website. You should create a WTForm in forms.py called RegisterForm and use Flask-Bootstrap to render a wtf quick_form. The data the user entered should be used to create a new entry in your blog.db in a User table. Steps 1. When the user clicks "Register" from the homepage, s/he should be able to see a form in the register page. - Create the form forms.py - ```python class RegisterForm(FlaskForm): email = EmailField(label="Email", validators=[DataRequired()]) name = StringField(label="Username", validators=[DataRequired()]) password = PasswordField(label="Password", validators=[DataRequired()]) submit = SubmitField("Register") ``` main.py - ```python @app.route('/register', methods=['GET', 'POST']) def register(): reg_form = RegisterForm() return render_template(template_name_or_list="register.html", form=reg_form) ``` - Render the form in the register page - register.html - ```html {{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }} ``` 2. When the user fills out the form, the data gets stored in another table named "users" in the database. - Create a new table named "users" in the existing database. main.py - ```python # this is the previous table, some data have already been added to it class BlogPost(db.Model): __tablename__ = "blog_posts" id = db.Column(db.Integer, primary_key=True) author = db.Column(db.String(250), nullable=False) title = db.Column(db.String(250), unique=True, nullable=False) subtitle = db.Column(db.String(250), nullable=False) date = db.Column(db.String(250), nullable=False) body = db.Column(db.Text, nullable=False) img_url = db.Column(db.String(250), nullable=False) # this is the new table we are creating class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True, nullable=False) name = db.Column(db.String(250), nullable=False) password = db.Column(db.String(250), nullable=False) # the below code to be run just once to create the tables with app.app_context(): db.create_all() ``` [db.create_all() doesn’t modify any existing entry. If there is a model that is not present in the current db schema it’s going to add it.](https://www.reddit.com/r/flask/comments/pgvne7/am_confused_about_the_best_way_to_add_a_new_table/?utm_source=share&utm_medium=web3x&utm_name=web3xcss&utm_term=1&utm_content=share_button) - Now that the new table is created, make it so that when the user registers from the register.html page, his data gets captured. register.html - ```html <div class="col-lg-8 col-md-10 mx-auto"> <form method="post" action="{{ url_for('register') }}" novalidate> {{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }} </form> </div> ``` - Make it so that the data captured gets stored in the "users" table, with the password hashed. main.py - ```python @app.route('/register', methods=['GET', 'POST']) def register(): reg_form = RegisterForm() if reg_form.validate_on_submit(): hashed_password = generate_password_hash( password=reg_form.password.data, method='pbkdf2:sha256', salt_length=8 ) with app.app_context(): new_user = User( email=reg_form.email.data, name=reg_form.name.data, password=hashed_password ) db.session.add(new_user) db.session.commit() return redirect(url_for('get_all_posts')) return render_template(template_name_or_list="register.html", form=reg_form) ``` ### 580 Requirement 2 - Login Registered Users 1. Users who have been successfully registered (added to the user table in the database) should be able to go to the /login route to use their credentials to log in. - Initiate Flask-login ```python # CREATE THE LOGIN MANAGER CLASS login_manager = LoginManager() # CONFIGURE THE APP login_manager.init_app(app) ``` After the User table has been declared, the code below should be added ```python # PROVIDING THE USER LOADER CALLBACK @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) ``` Now we come to the login route. But where is the form? We should have a form in the login page too. - Create the login form in the forms.py ```python class LoginForm(FlaskForm): username_or_email = StringField(label="Username or Email", validators=[DataRequired()]) password = StringField(label="Password", validators=[DataRequired()]) submit = SubmitField("Login") ``` - Now in the login route, create the login form object - ```python @app.route('/login') def login(): login_form = LoginForm() return render_template("login.html") ``` - The login form object should be sent to the login.html so that the form gets rendered ```python @app.route('/login') def login(): login_form = LoginForm() return render_template("login.html", form=login_form) ``` login.html - ```html <div class="col-lg-8 col-md-10 mx-auto content"> <form method="post" action="{{ url_for('login') }}" novalidate> {{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }} </form> </div> ``` - If the login form is submitted and the inputs validated, then it should redirect to the homepage. ```python @app.route('/login') def login(): login_form = LoginForm() if login_form.validate_on_submit(): return redirect(url_for('get_all_posts')) return render_template("login.html", form=login_form) ``` - Capture the "email or username" input in the form ```python @app.route('/login') def login(): login_form = LoginForm() if login_form.validate_on_submit(): email_or_username_entered = login_form.username_or_email.data return redirect(url_for('get_all_posts')) return render_template("login.html", form=login_form) ``` - Check the username or the email entered by the user against both the "name" column and the "email" column ```python @app.route('/login', methods=['GET', 'POST']) def login(): login_form = LoginForm() if login_form.validate_on_submit(): email_or_username_entered = login_form.username_or_email.data attempted_user = User.query.filter_by(email=email_or_username_entered).first() or User.query.filter_by(name=email_or_username_entered).first() if attempted_user: print('User Found') return redirect(url_for('get_all_posts')) return render_template("login.html", form=login_form) ``` ```commandline User Found ``` - If the user passes the "username or email" check, then check the password ```python @app.route('/login', methods=['GET', 'POST']) def login(): login_form = LoginForm() if login_form.validate_on_submit(): email_or_username_entered = login_form.username_or_email.data pass_entered = login_form.password attempted_user = User.query.filter_by(email=email_or_username_entered).first() or User.query.filter_by(name=email_or_username_entered).first() if attempted_user: # print('User Found') if check_password_hash(attempted_user.password, pass_entered): login_user(attempted_user) return redirect(url_for('get_all_posts')) else: print('wrong pass') else: print("username or email not found, kindly register") return render_template(template_name_or_list="login.html", form=login_form) ``` ![02](./images/02.gif) - WHen the username/email is not found in the database, send the user to the register page ```python @app.route('/login', methods=['GET', 'POST']) def login(): login_form = LoginForm() if login_form.validate_on_submit(): email_or_username_entered = login_form.username_or_email.data pass_entered = login_form.password.data attempted_user = User.query.filter_by(email=email_or_username_entered).first() or User.query.filter_by(name=email_or_username_entered).first() if attempted_user: print('User Found') print(attempted_user) if check_password_hash(attempted_user.password, pass_entered): login_user(attempted_user) return redirect(url_for('get_all_posts')) else: print('wrong pass') else: print("username or email not found, kindly register") return redirect(url_for('register')) return render_template(template_name_or_list="login.html", form=login_form) ``` - Flash messages when (i) Email not found, (ii) Wrong pass main.py ```python @app.route('/login', methods=['GET', 'POST']) def login(): login_form = LoginForm() if login_form.validate_on_submit(): email_or_username_entered = login_form.username_or_email.data pass_entered = login_form.password.data attempted_user = User.query.filter_by(email=email_or_username_entered).first() or User.query.filter_by(name=email_or_username_entered).first() if attempted_user: print('User Found') print(attempted_user) if check_password_hash(attempted_user.password, pass_entered): login_user(attempted_user) return redirect(url_for('get_all_posts')) else: print('wrong pass') flash('Wrong Password') return redirect(url_for('login')) else: print("username or email not found, kindly register") flash('Username or email not found, kindly register') return redirect(url_for('register')) return render_template(template_name_or_list="login.html", form=login_form) ``` login.html ```html <div class="container"> <div class="row"> {% with messages = get_flashed_messages() %} {% if messages %} <ul class=flashes> {% for message in messages %} <p style="font-style: italic; color:red;">{{ message }}</p> {% endfor %} </ul> {% endif %} {% endwith %} <div class="col-lg-8 col-md-10 mx-auto content"> <form method="post" action="{{ url_for('login') }}" novalidate> {{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }} </form> </div> </div> </div> ``` register.html ```html <div class="container"> <div class="row"> {% with messages = get_flashed_messages() %} {% if messages %} <ul class=flashes> {% for message in messages %} <p style="font-style: italic; color:red;">{{ message }}</p> {% endfor %} </ul> {% endif %} {% endwith %} <div class="col-lg-8 col-md-10 mx-auto"> <form method="post" action="{{ url_for('register') }}" novalidate> {{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }} </form> </div> </div> </div> ``` - Adjust the navbar so the 'Login' and 'Register' buttons do not, and a 'Logout' button do, show while logged in header.html ```html {% if not current_user.is_authenticated %} <li class="nav-item"> <a class="nav-link" href="{{ url_for('login') }}">Login</a> </li> <li class="nav-item"> <a class="nav-link" href="{{ url_for('register') }}">Register</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{{ url_for('logout') }}">Log Out</a> </li> {% endif %} ``` - Code up the /logout route so that when the user clicks on the LOG OUT button, it logs them out and takes them back to the home page. ```python @app.route('/logout') def logout(): logout_user() return redirect(url_for('get_all_posts')) ``` ![03](./images/03.gif) ### 581 Requirement 3 - Protect Routes In our blog, the first registered user will be the admin. They will be able to create new blog posts, edit posts and delete posts. 1. The first user's id is 1. We can use this in index.html and post.html to make sure that only the admin user can see the "Create New Post" and "Edit Post" and Delete buttons. index.html - ```html <p class="post-meta">Posted by <a href="#">{{post.author}}</a> on {{post.date}} {% if current_user.id == 1 %} <a href="{{url_for('delete_post', post_id=post.id) }}">✘</a> {% endif %} </p> {% if current_user.id == 1 %} <div class="clearfix"> <a class="btn btn-primary float-right" href="{{url_for('add_new_post')}}">Create New Post</a> </div> {% endif %} ``` post.html ```html {% if current_user.id == 1 %} <div class="clearfix"> <a class="btn btn-primary float-right" href="{{url_for('edit_post', post_id=post.id)}}">Edit Post</a> </div> {% endif %} ``` 2. Just because a user can't see the buttons, they can still manually access the /edit-post or /new-post or /delete routes. Protect these routes by creating a Python decorator called @admin_only If the current_user's id is 1 then they can access those routes, otherwise, they should get a 403 error (not authorised). - the logic ```python if current_user.is_authenticated and current_user.id == 1: # if user is authenticated, then show the function (the add_new_post function) return function(*args, **kwargs) ``` - the abort function ```python else: abort(403) ``` - the decorator ```python def admin_only(function): @wraps(function) # which function? the add_new_post function def decorated_function(*args, **kwargs): print("decorator works") # print(current_user.get_id()) # print(current_user.is_active) if current_user.is_authenticated and current_user.id == 1: # if user is authenticated with id = 1, then show the function (the add_new_post function) return function(*args, **kwargs) else: # otherwise abort abort(403) return decorated_function ``` - the application ```python @app.route("/new-post") @admin_only def add_new_post(): form = CreatePostForm() if form.validate_on_submit(): new_post = BlogPost( title=form.title.data, subtitle=form.subtitle.data, body=form.body.data, img_url=form.img_url.data, author=current_user, date=date.today().strftime("%B %d, %Y") ) db.session.add(new_post) db.session.commit() return redirect(url_for("get_all_posts")) return render_template("make-post.html", form=form) ``` ![04](./images/04.gif) Protect the edit and delete routes too, to be only visible to the admin. Just add @admin_only before the code. ```python @app.route("/edit-post/<int:post_id>") @admin_only def edit_post(post_id): post = BlogPost.query.get(post_id) edit_form = CreatePostForm( title=post.title, subtitle=post.subtitle, img_url=post.img_url, author=post.author, body=post.body ) if edit_form.validate_on_submit(): post.title = edit_form.title.data post.subtitle = edit_form.subtitle.data post.img_url = edit_form.img_url.data post.author = edit_form.author.data post.body = edit_form.body.data db.session.commit() return redirect(url_for("show_post", post_id=post.id)) return render_template("make-post.html", form=edit_form) @app.route("/delete/<int:post_id>") @admin_only def delete_post(post_id): post_to_delete = BlogPost.query.get(post_id) db.session.delete(post_to_delete) db.session.commit() return redirect(url_for('get_all_posts')) ``` ### 582 Creating Relational Databases Currently, at the database level, the two tables are not connected. We would essentially want to connect each blog post to the user who has written it. How can we do it on a database level? 1. Modify the User (Parent) and BlogPost (Child) class code to create a bidirectional One-to-Many relationship between the two tables. You should be able to easily locate the BlogPosts a User has written and also the User of any BlogPost object. - the doc from the docs **One To Many** A one to many relationship places a foreign key on the child table referencing the parent. `relationship()` is then specified on the parent, as referencing a collection of items represented by the child: ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) ``` To establish a bidirectional relationship in one-to-many, where the “reverse” side is a many to one, specify an additional `relationship()` and connect the two using the `relationship.back_populates` parameter: ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child", back_populates="parent") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id')) parent = relationship("Parent", back_populates="children") ``` Child will get a parent attribute with many-to-one semantics. Alternatively, the `relationship.backref` option may be used on a single `relationship()` instead of using `relationship.back_populates`: ```python class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child", backref="parent") ``` - the code change in the class So the user will be my parent and the blogposts will be my children. ```python ##CONFIGURE TABLES # Parent class User(UserMixin, db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True, nullable=False) name = db.Column(db.String(250), nullable=False) password = db.Column(db.String(250), nullable=False) children = relationship("BlogPost", back_populates="author") # Child class BlogPost(db.Model): __tablename__ = "blog_posts" id = db.Column(db.Integer, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) # the old author column was a simple string, modify it so it auto populates from whoever is writing the post author = relationship("User", back_populates="children") # author = db.Column(db.String(250), nullable=False) title = db.Column(db.String(250), unique=True, nullable=False) subtitle = db.Column(db.String(250), nullable=False) date = db.Column(db.String(250), nullable=False) body = db.Column(db.Text, nullable=False) img_url = db.Column(db.String(250), nullable=False) with app.app_context(): db.create_all() ``` **Re-creating the Database after changes to the Schema** If you re-run your blog at this point you'll get an error: `OperationalError: (sqlite3.OperationalError) no such column: blog_posts.author_id` The reason is that our new code in the main.py modifies our database model by adding a new column into our database that was not present in the original blog.db from the starter code: ```python parent_id = db.Column(db.Integer, db.ForeignKey('users.id')) ``` We don't have any valuable data at this point that we'd like to preserve, so the easiest way to simply delete the existing blog.db entirely and to use the line db.create_all() to re-create all the tables from scratch. Remember, this means you also have to register your user again and create a post since we've just wiped our database. Now if you refresh your Blog website, you'll see the author name disappear from the index.html and page.html pages. 2. Modify the index.html and post.html pages so that the author name is still displayed in the right places. index.html - ```html <p class="post-meta">Posted by <a href="#">{{current_user.name}}</a> on {{post.date}} {% if current_user.id == 1 %} <a href="{{url_for('delete_post', post_id=post.id) }}">✘</a> {% endif %} </p> ``` post.html - ```html <span class="meta">Posted by <a href="#">{{current_user.name}}</a> on {{post.date}} </span> ``` ### 583 Requirement 4 - Allow Any User to Add Comments to BlogPosts 1. Create a CommentForm in the form.py file it will only contain a single CKEditorField for users to write their comments. forms.py - ```python class CommentForm(FlaskForm): comment_text = CKEditorField("Comment", validators=[DataRequired()]) submit = SubmitField("Submit Comment") ``` main.py - ```python @app.route("/post/<int:post_id>") def show_post(post_id): comment_form = CommentForm() requested_post = BlogPost.query.get(post_id) return render_template("post.html", post=requested_post, form=comment_form) ``` post.html - ```html {% import 'bootstrap/wtf.html' as wtf %} <!--inserting this at the bottom of the page--> <div class="container"> <div class="row"> <div class="col-lg-10 col-md-10 mx-auto"> <form method="post" action="{{ url_for('get_all_posts') }}" novalidate> {{ ckeditor.load() }} {{ ckeditor.config(name='comment_body') }} {{ form.csrf_token }} {{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }} </form> </div> </div> </div> ``` The next step is to allow users to leave a comment and save the comment. Now that we've seen how relationships can be established between tables in our database. Let's step up our relationships to create a new Table where any user can write comments to our blog posts. 2. Create a Table called `Comment` where the tablename is "comments". It should contain an id and a text property which will be the primary key and the text entered into the CKEditor. ```python ##CONFIGURE TABLES # Parent class User(UserMixin, db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True, nullable=False) name = db.Column(db.String(250), nullable=False) password = db.Column(db.String(250), nullable=False) children = relationship("BlogPost", back_populates="author") # Child class BlogPost(db.Model): __tablename__ = "blog_posts" id = db.Column(db.Integer, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) author = relationship("User", back_populates="children") # author = db.Column(db.String(250), nullable=False) title = db.Column(db.String(250), unique=True, nullable=False) subtitle = db.Column(db.String(250), nullable=False) date = db.Column(db.String(250), nullable=False) body = db.Column(db.Text, nullable=False) img_url = db.Column(db.String(250), nullable=False) # This is where the new table will go class Comment(db.Model): __tablename__ = "comments" id = db.Column(db.Integer, primary_key=True) commented_text = db.Column(db.String(500), nullable=False) # Run this the first time only, after you have made any changes to the database # with app.app_context(): # db.create_all() ``` 3. Establish a One to Many relationship Between the User Table (Parent) and the Comment table (Child). Where One User is linked to Many Comment objects. ![05](./images/05.png) At this point, it is better to change the existing tables a bit. These - ```python children = relationship("BlogPost", back_populates="author") ``` ```python author_id = db.Column(db.Integer, db.ForeignKey('users.id')) author = relationship("User", back_populates="children") ``` Changed to - ```python posts = relationship("BlogPost", back_populates="author") ``` ```python author_id = db.Column(db.Integer, db.ForeignKey('users.id')) author = relationship("User", back_populates="comments") ``` This way now that we have to create another set of children, i.e. comments, there won't be any confusion. Now let's create the relationship - ```python # The parent, understandably, is the user. class User(UserMixin, db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True, nullable=False) name = db.Column(db.String(250), nullable=False) password = db.Column(db.String(250), nullable=False) posts = relationship("BlogPost", back_populates="author") # Here is where the new relationship is established comments = relationship("Comment", back_populates="reader") class Comment(db.Model): __tablename__ = "comments" id = db.Column(db.Integer, primary_key=True) # Every comment will have a reader id, which is essentially just the uesr id reader_id = db.Column(db.Integer, db.ForeignKey('users.id')) # Here every comment is tagged with the reader who made the comment reader = relationship("User", back_populates="comments") commented_text = db.Column(db.String(500), nullable=False) ``` Apart from each user having many comments, each blogpost can have many comments as well. 4. Establish a One to Many relationship between each BlogPost object (Parent) and Comment object (Child). Where each BlogPost can have many associated Comment objects. ```python class BlogPost(db.Model): __tablename__ = "blog_posts" id = db.Column(db.Integer, primary_key=True) author_id = db.Column(db.Integer, db.ForeignKey('users.id')) author = relationship("User", back_populates="posts") # author = db.Column(db.String(250), nullable=False) title = db.Column(db.String(250), unique=True, nullable=False) subtitle = db.Column(db.String(250), nullable=False) date = db.Column(db.String(250), nullable=False) body = db.Column(db.Text, nullable=False) img_url = db.Column(db.String(250), nullable=False) blog_comments = relationship("Comment", back_populates="the_post") class Comment(db.Model): __tablename__ = "comments" id = db.Column(db.Integer, primary_key=True) reader_id = db.Column(db.Integer, db.ForeignKey('users.id')) reader = relationship("User", back_populates="comments") the_post_id = db.Column(db.Integer, db.ForeignKey('blog_posts.id')) the_post = relationship("BlogPost", back_populates="blog_comments") commented_text = db.Column(db.String(500), nullable=False) ``` 5. The comments form, once filled, should populate the db. Code in the route. Issues - - post_id and reader_id does not get posted in the comments database - when post and reader parameter is added, throws `sqlalchemy.exc.InvalidRequestError: Object '<BlogPost at 0x1dcb7c56540>' is already attached to session '3' (this is '4')` ```python @app.route("/post/<int:post_id>", methods=['GET', 'POST']) def show_post(post_id): print(post_id) comment_form = CommentForm() requested_post = BlogPost.query.get(post_id) print(requested_post) if comment_form.validate_on_submit(): with app.app_context(): new_comment = Comment( commented_text=comment_form.comment_text.data, reader=current_user, parent_post=requested.post ) db.session.add(new_comment) db.session.commit() return redirect(url_for('show_post', post_id=requested_post.id)) return render_template("post.html", post=requested_post, form=comment_form) ``` - is the problem in the table design? - no, checked by changing the parameters. code throws error then. not now - **fixed this by changing `requested.post` to `BlogPost.query.get(post_id)`** ```python @app.route("/post/<int:post_id>", methods=['GET', 'POST']) def show_post(post_id): print(post_id) comment_form = CommentForm() requested_post = BlogPost.query.get(post_id) print(requested_post) if comment_form.validate_on_submit(): with app.app_context(): new_comment = Comment( commented_text=comment_form.comment_text.data, reader=current_user, parent_post=BlogPost.query.get(post_id) ) db.session.add(new_comment) db.session.commit() return redirect(url_for('show_post', post_id=requested_post.id)) return render_template("post.html", post=requested_post, form=comment_form) ``` - post author shows name of the current user, instead of showing author's name - changed `current.user.name` to `post.author.name` _index.html - _ ```html <p class="post-meta">Posted by <a href="#">{{post.author.name}}</a> on {{post.date}} {% if current_user.id == 1 %} <a href="{{url_for('delete_post', post_id=post.id) }}">✘</a> {% endif %} </p> ``` _post.html -_ ```html <div class="col-lg-8 col-md-10 mx-auto"> <div class="post-heading"> <h1>{{post.title}}</h1> <h2 class="subheading">{{post.subtitle}}</h2> <span class="meta"> Posted by <a href="#">{{post.author.name}}</a> on {{post.date}} </span> </div> </div> ``` - what if I want to change the db file name from blog.db to v3_blog.db? ```python ##CONNECT TO DB app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///v3_blog.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) ``` - Make sure that only authenticated (logged-in) users can save their comment. Otherwise, they should see a flash message telling them to log in and redirect them to the /login route. - the post route should have an argument to this effect - can we do this using current_user? - Nope, throws `AttributeError: 'AnonymousUserMixin' object has no attribute '_sa_instance_state'` error - this is because the current_user always has an object, when logged in it has a user object, when not, it has a 'AnonymousUserMixin' object - we can do this with `current_user.is_authenticated` - main.py - ```python if comment_form.validate_on_submit(): if current_user.is_authenticated: with app.app_context(): new_comment = Comment( commented_text=comment_form.comment_text.data, reader=current_user, parent_post=BlogPost.query.get(post_id) ) db.session.add(new_comment) db.session.commit() else: flash('Please log in to post a comment') return redirect(url_for('show_post', post_id=requested_post.id)) ``` - also update the post.html ```html <div class="container"> <div class="row"> {% with messages = get_flashed_messages() %} {% if messages %} <ul class=flashes> {% for message in messages %} <p style="font-style: italic; color:red;">{{ message }}</p> {% endfor %} </ul> {% endif %} {% endwith %} <div class="col-lg-10 col-md-10 mx-auto"> <form method="post" action="{{ url_for('show_post', post_id=post.id) }}" novalidate> {{ ckeditor.load() }} {{ ckeditor.config(name='comment_body') }} {{ form.csrf_token }} {{ wtf.quick_form(form, novalidate=True, button_map={"submit": "primary"}) }} </form> </div> </div> </div> ``` ![06](./images/06.gif) 6. The post page, should take all comments from the db and display them - We could use `all_comments = Comments.query.all()` but that would list all comments, not just the comments made on the post specifically. - We want only the comments made in the post. Each post has a comments object as children. ```html <!-- Comments Area --> {% for one_comment in post.blog_comments %} <div class="col-lg-8 col-md-10 mx-auto comment"> <ul class="commentList"> <li> <div class="commenterImage"> <img src="https://pbs.twimg.com/profile_images/744849215675838464/IH0FNIXk.jpg"/> </div> <div class="commentText"> <p>{{ one_comment.commented_text }}</p> <span class="date sub-text">{{ one_comment.reader.name }}</span> </div> </li> </ul> </div> ``` - Issue - - The comments get posted like this - [07](./images/07.png) - Use the |safe filter in jinza to avoid this - ```html <!-- Comments Area --> {% for one_comment in post.blog_comments %} <div class="col-lg-8 col-md-10 mx-auto comment"> <ul class="commentList"> <li> <div class="commenterImage"> <img src="https://pbs.twimg.com/profile_images/744849215675838464/IH0FNIXk.jpg"/> </div> <div class="commentText"> <p>{{ one_comment.commented_text|safe }}</p> <span class="date sub-text">{{ one_comment.reader.name }}</span> </div> </li> </ul> </div> ``` 7. Use Gravatar to assign images to each commenter. - Issue - The updated version of Flask such as this does not support Gravatar anymore. - There are various **_unofficial_** workarounds. - https://gist.github.com/angelabauer/70d5fa9b62654cd40f4df92f3a196a02?permalink_comment_id=4873282#gistcomment-4873282 #### fin
import { FormEvent, useState } from "react"; function useForm() { const [status, setStatus] = useState(""); const [message, setMessage] = useState(""); const handleSubmit = async (e: FormEvent) => { e.preventDefault(); setStatus("loading"); setMessage(""); const finalFormEndpoint = (e.target as HTMLFormElement).action; const data = Array.from((e.target as HTMLFormElement).elements) .filter((input: unknown) => (input as HTMLInputElement).name) .reduce( (obj: Object, input: unknown) => Object.assign(obj, { [(input as HTMLInputElement).name]: (input as HTMLInputElement) .value, }), {} ); try { const response = await fetch(finalFormEndpoint, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify(data), }); if (response.status !== 200) { throw new Error(response.statusText); } const parsedResponse = (await response.json()) as { result: string }; setMessage(parsedResponse.result); setStatus("success"); } catch (e: unknown) { if (e instanceof Error) { setMessage(e.toString()); setStatus("error"); } } }; return { handleSubmit, status, message }; } export default useForm;
<!DOCTYPE html> @guest <script>window.location = "{{ route('login') }}";</script> @endguest <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>@yield('title')</title> <!-- Fonte Google --> <link rel="preconnect" href="https://fonts.bunny.net"> <link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" /> <!-- Tailwind --> <script src="https://cdn.tailwindcss.com"></script> <!-- Bootstrap 5 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> <!-- CND Jquey mask --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script> <!-- JS --> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css"/> <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script> @yield("scriptjs") </head> <body style="background-color: #e5e7eb"> <!-- Integracao Login Facebook --> <script> window.fbAsyncInit = function() { FB.init({ appId : '393683216698941', xfbml : true, version : 'v19.0' }); FB.AppEvents.logPageView(); }; (function(d, s, id){ var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); </script> <div class="bg-light"> <header class="d-flex flex-wrap align-items-center justify-content-center justify-content-md-between py-3 mb-4 border-bottom"> <div class="col-md-3 mb-2 mb-md-0"> <span class="fs-3">5Tech</span> </div> <ul class="nav col-12 col-md-auto mb-2 justify-content-center mb-md-0 fs-5"> <li><a href="{{route('rota')}}" class="nav-link px-2 text-secondary">Produtos</a></li> <li><a href="{{route('restaurantes.loja')}}" class="nav-link px-2 text-secondary">Restaurantes e Mercados</a></li> <li><a href="#" class="nav-link px-2 text-secondary">Quem Somos</a></li> </ul> <div class="d-flex gap-3 col-md-3 text-end"> @guest <a type="button" class="btn btn-outline-primary me-2" href="/login">Entrar</a> <a type="button" class="btn btn-primary" href="/register">Criar conta</a> @endguest @auth <div class="dropdown text-start align-self-center"> <a href="#" class="d-block link-body-emphasis text-decoration-none dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false"> @php $fullName = Auth::user()->name; // Divide o nome completo em partes com base nos espaços em branco $nameParts = explode(' ', $fullName); // Obtém o primeiro nome $firstName = $nameParts[0]; @endphp Ola {{$firstName}} </a> <ul class="dropdown-menu text-small" style=""> <li><a class="dropdown-item" href="{{route('hist_pedidos')}}">Meu Pedidos</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="/user/profile">Minha Conta</a></li> <li><hr class="dropdown-divider"></li> <li> <form method="POST" action="{{ route('logout') }}"> @csrf <a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault(); this.closest('form').submit();"> {{ __('Sair') }} </a> </form> </li> </ul> </div> <a href="{{ route('ver_carrinho') }}" class="btn btn-sm"> <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="currentColor" class="bi bi-cart4" viewBox="0 0 16 16"> <path d="M0 2.5A.5.5 0 0 1 .5 2H2a.5.5 0 0 1 .485.379L2.89 4H14.5a.5.5 0 0 1 .485.621l-1.5 6A.5.5 0 0 1 13 11H4a.5.5 0 0 1-.485-.379L1.61 3H.5a.5.5 0 0 1-.5-.5M3.14 5l.5 2H5V5zM6 5v2h2V5zm3 0v2h2V5zm3 0v2h1.36l.5-2zm1.11 3H12v2h.61zM11 8H9v2h2zM8 8H6v2h2zM5 8H3.89l.5 2H5zm0 5a1 1 0 1 0 0 2 1 1 0 0 0 0-2m-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0m9-1a1 1 0 1 0 0 2 1 1 0 0 0 0-2m-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0"/> </svg> </a> <!-- Button trigger modal --> <button type="btn btn-sm" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal"> <svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" fill="currentColor" class="bi bi-geo-alt" viewBox="0 0 16 16"> <path d="M12.166 8.94c-.524 1.062-1.234 2.12-1.96 3.07A32 32 0 0 1 8 14.58a32 32 0 0 1-2.206-2.57c-.726-.95-1.436-2.008-1.96-3.07C3.304 7.867 3 6.862 3 6a5 5 0 0 1 10 0c0 .862-.305 1.867-.834 2.94M8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10"/> <path d="M8 8a2 2 0 1 1 0-4 2 2 0 0 1 0 4m0 1a3 3 0 1 0 0-6 3 3 0 0 0 0 6"/> </svg> </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ... </div> <div class="modal-footer" style="background-color: #212529"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> @endauth </div> </header> </div> <main class="container-xxl bd-gutter mt-3 my-md-4 bd-layout"> @yield('content') </main> <footer class="bd-footer py-4 py-md-5 mt-5 bg-body-tertiary"> <h2>5Tech &copy; 2024 </h2> </footer> </body> </html>
package com.parking.service; import java.util.List; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.data.domain.Sort; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.parking.entity.Usuario; import com.parking.exception.EntityNotFoundException; import com.parking.exception.PasswordInvalidException; import com.parking.exception.UsernameUniqueViolationException; import com.parking.repository.UsuarioRepository; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor @Service public class UsuarioService { private final UsuarioRepository repository; private final PasswordEncoder encoder; @Transactional public Usuario salvar(Usuario usuario) { try { usuario.setPassword(encoder.encode(usuario.getPassword())); return repository.save(usuario); } catch (DataIntegrityViolationException ex) { throw new UsernameUniqueViolationException( String.format("O e-mail %s já está cadastrado", usuario.getUsername())); } } @Transactional(readOnly = true) public Usuario buscarPorId(Long id) { return repository.findById(id).orElseThrow( () -> new EntityNotFoundException(String.format("Usuário id=%s não encontrado", id)) ); } /*@Transactional public Usuario editarSenha(Long id, String password) { Usuario user = buscarPorId(id); user.setPassword(password); return user; }*/ @Transactional public Usuario editarSenha(Long id, String senhaAtual, String novaSenha, String confirmaSenha) { // confere se as senhas são iguais if (!novaSenha.equals(confirmaSenha)) { throw new PasswordInvalidException("As senhas não conferem"); } // se passou pelo if, busca usuário Usuario user = buscarPorId(id); // verifica a senha atual informada //if (!user.getPassword().equals(senhaAtual)) { if (!encoder.matches(senhaAtual, user.getPassword())) { throw new PasswordInvalidException("Senha atual não confere"); } // se passou, salva a nova senha user.setPassword(encoder.encode(novaSenha)); return user; } @Transactional(readOnly = true) public List<Usuario> buscarTodos() { return repository.findAll(Sort.by("username")); } @Transactional(readOnly = true) public Usuario buscarPorUsername(String username) { return repository.findByUsername(username).orElseThrow( () -> new EntityNotFoundException(String.format("Usuario com %s não encontrado", username)) ); } @Transactional(readOnly = true) public Usuario.Role buscarRolePorUsername(String username) { return repository.findRoleByUsername(username); } }
/** * 发布订阅模式的事件模型 */ export class EventEmitter { events: { [x: string]: Function[] } constructor() { this.events = {} } on(type: string, cb: Function) { if (!this.events[type]) { this.events[type] = [cb] } else if (!this.events[type].includes(cb)) { this.events[type].push(cb) } return this } emit(type: string, ...rest: unknown[]) { const fns = this.events[type] if (fns) { fns.forEach(cb => { cb(...rest) }) } return this } off(type: string, fn: Function) { const fns = this.events[type] if (fns) { for (let i = 0; i < fns.length; i++) { if (fns[i] === fn) { fns.splice(i, 1) break } } } return this } }
class_name Bucket extends RefCounted signal color_filled const NEIGHBOURS: PackedVector2Array = [ Vector2.DOWN, Vector2.RIGHT, Vector2.LEFT, Vector2.UP, ] var image := Image.new() var image_rect :Rect2i : get: return Rect2i(Vector2i.ZERO, image.get_size()) var mask := Image.new() var fill_color := Color.BLACK var tolerance := 0 : set(val): tolerance = clampi(val, 0, 100) var opt_contiguous := true func _init(sel_mask): mask = sel_mask func attach(img :Image): image = img func fill(pos :Vector2i): if not image_rect.has_point(pos): return if mask.is_empty() or mask.is_invisible(): var target_color = image.get_pixelv(pos) if opt_contiguous: fill_to_color_contiguous(pos, target_color) else: fill_to_color(target_color) else: fill_selection() color_filled.emit() func fill_selection(): var fill_rect = mask.get_used_rect() for x in range(fill_rect.position.x, fill_rect.end.x): for y in range(fill_rect.position.y, fill_rect.end.y): var p := Vector2i(x, y) image.set_pixelv(p, fill_color) func fill_to_color(target_color :Color): for x in image.get_width(): for y in image.get_height(): var p := Vector2i(x, y) var p_color = image.get_pixelv(p) if is_matched(p_color, target_color): image.set_pixelv(p, fill_color) func fill_to_color_contiguous(pos :Vector2i, target_color :Color): var queue :PackedVector2Array = [] var visited :Dictionary = {} var rect :Rect2 = image_rect queue.append(pos) visited[pos] = true while queue: var i = queue.size() - 1 var p = queue[i] queue.remove_at(i) # remove from last, is much much faster. # DOC says: On large arrays, this method will be slower if the removed # element is close to the beginning of the array (index 0). # This is because all elements placed after the removed element # have to be reindexed. image.set_pixelv(p, fill_color) for n in NEIGHBOURS: var np = p + n if rect.has_point(np) and not visited.has(np): visited[np] = true var np_color = image.get_pixelv(np) if is_matched(np_color, target_color): queue.append(np) func is_matched(img_color :Color, target_color :Color): if target_color.is_equal_approx(img_color): return true elif tolerance > 0: var diff = target_color - img_color var t = tolerance / 100.0 diff.r = abs(diff.r) diff.g = abs(diff.g) diff.b = abs(diff.b) diff.a = abs(diff.a) return diff.r < t and diff.g < t and diff.b < t and diff.a < t
<template> <GuestLayout title="Sign into your account"> <form class="space-y-6" method="POST" @submit.prevent="login"> <div v-if="errorMsg" class="flex items-center justify-between py-3 px-3 bg-red-500 text-white rounded"> {{ errorMsg }} <span @click="errorMsg= ''" class="w-8 h-8 flex items-center justify-center rounded-full transition-colors cursor-pointer hover:bg-black/20"> <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M6 18 18 6M6 6l12 12" /> </svg> </span> </div> <div> <label for="email" class="block text-sm font-medium leading-6 text-gray-900">Email address</label> <div class="mt-2"> <input id="email" name="email" type="email" autocomplete="email" required="" v-model="user.email" class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> <div> <div class="flex items-center justify-between"> <label for="password" class="block text-sm font-medium leading-6 text-gray-900">Password</label> <div class="text-sm"> <router-link :to="{name: 'requestPassword'}" href="#" class="font-semibold text-indigo-600 hover:text-indigo-500">Forgot password?</router-link> </div> </div> <div class="mt-2"> <input id="password" name="password" type="password" autocomplete="current-password" required="" v-model="user.password" class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6" /> </div> </div> <div class="flex items-center justify-between"> <div class="flex items-center"> <input id="remember-me" name="remember-me" type="checkbox" v-model="user.remember" class="h-4 w-4 text-indigo-600 focus:ring-indigo-500 border-gray-300 rounded"/> <label for="remember-me" class="ml-2 block text-sm text-gray-900"> Remember me </label> </div> </div> <div> <button type="submit" :disabled="loading" class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" :class="{ 'cursor-not-allowed': loading, 'hover:bg-indigo-500': loading, }"> <svg v-if="loading" class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"> <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle> <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path> </svg> <span class="absolute left-0 inset-y-0 flex items-center pl-3"> <LockClosedIcon class="h-5 w-5 text-indigo-500 group-hover:text-indigo-400" aria-hidden="true"/> </span> Sign in </button> </div> </form> </GuestLayout> </template> <style scoped> </style> <script setup> import {ref} from 'vue'; import {LockClosedIcon} from '@heroicons/vue/solid'; import GuestLayout from "../components/GuestLayout.vue"; import store from "../store/index.js"; import router from "../router/index.js"; //TO BE USED WHEN FORM ACTIONS ARE BEING EMITTED FROM THE GUESTLAYOUT // function login(){ // console.log("Attempting to Login"); // } let loading = ref(false); let errorMsg = ref(""); const user = { email: '', password: '', remember: false } function login(){ // console.log(user); loading.value = true; store.dispatch('login', user) .then(() => { loading.value = false; router.push({name: 'app.dashboard'}) }) .catch(({response}) => { //debugger; loading.value = false; errorMsg.value = response.data.message; }) } </script>
/** * @copyright 2023-present Brian Cairl * * @file transform.cpp */ // C++ Standard Library #include <algorithm> #include <vector> // GTest #include <gtest/gtest.h> // Parachute #include <parachute/algorithm/transform.hpp> #include <parachute/pool.hpp> using namespace para; TEST(TransformUnordered, EmptySequence) { using pool_type = worker; pool_type wp; const std::vector<double> original_sequence = {}; std::vector<double> expected_sequence = original_sequence; std::for_each(expected_sequence.begin(), expected_sequence.end(), [](double& v) { v *= 2; }); std::vector<double> transformed_sequence; algorithm::transform( wp, original_sequence.begin(), original_sequence.end(), std::back_inserter(transformed_sequence), [](double v) { return v * 2; }); std::sort(transformed_sequence.begin(), transformed_sequence.end()); EXPECT_EQ(transformed_sequence, expected_sequence); } TEST(TransformUnordered, FullSequence) { using pool_type = static_pool<4>; pool_type wp; const std::vector<double> original_sequence = { 1, 2, 3, 4, 5, 6 }; std::vector<double> expected_sequence = original_sequence; std::for_each(expected_sequence.begin(), expected_sequence.end(), [](double& v) { v *= 2; }); std::vector<double> transformed_sequence; algorithm::transform( wp, original_sequence.begin(), original_sequence.end(), std::back_inserter(transformed_sequence), [](double v) { return v * 2; }); std::sort(transformed_sequence.begin(), transformed_sequence.end()); EXPECT_EQ(transformed_sequence, expected_sequence); } TEST(TransformOrdered, EmptySequence) { using pool_type = static_pool<4>; pool_type wp; const std::vector<double> original_sequence = {}; std::vector<double> expected_sequence = original_sequence; std::for_each(expected_sequence.begin(), expected_sequence.end(), [](double& v) { v *= 2; }); std::vector<double> transformed_sequence; transformed_sequence.resize(original_sequence.size()); algorithm::transform( wp, original_sequence.begin(), original_sequence.end(), transformed_sequence.begin(), transformed_sequence.end(), [](double v) { return v * 2; }); EXPECT_EQ(transformed_sequence, expected_sequence); } TEST(TransformOrdered, FullSequence) { using pool_type = static_pool<4>; pool_type wp; const std::vector<double> original_sequence = { 1, 2, 3, 4, 5, 6 }; std::vector<double> expected_sequence = original_sequence; std::for_each(expected_sequence.begin(), expected_sequence.end(), [](double& v) { v *= 2; }); std::vector<double> transformed_sequence; transformed_sequence.resize(original_sequence.size()); algorithm::transform( wp, original_sequence.begin(), original_sequence.end(), transformed_sequence.begin(), transformed_sequence.end(), [](double v) { return v * 2; }); EXPECT_EQ(transformed_sequence, expected_sequence); } TEST(TransformOrdered, UndersizedOupoutSequence) { using pool_type = static_pool<4>; pool_type wp; const std::vector<double> original_sequence = { 1, 2, 3, 4, 5, 6 }; std::vector<double> expected_sequence = original_sequence; std::for_each(expected_sequence.begin(), expected_sequence.end(), [](double& v) { v *= 2; }); std::vector<double> transformed_sequence; transformed_sequence.resize(original_sequence.size() / 2 + 1); algorithm::transform( wp, original_sequence.begin(), original_sequence.end(), transformed_sequence.begin(), transformed_sequence.end(), [](double v) { return v * 2; }); EXPECT_NE(transformed_sequence, expected_sequence); }
/* eslint-disable no-unused-vars */ /* eslint-disable react/prop-types */ import { Link } from "react-router-dom"; import "../styles/card.scss"; export default function Card({ // eslint-disable-next-line react/prop-types element, children, customcss, }) { const { _id, coursetitle, slogan, thumbnail, coursefee, description, category, } = element || {}; return ( <div className={`card rounded-md relative shadow-lg overflow-hidden cursor-pointer bg-base-100 ${customcss}`} > <figure className="rounded-none coursefigure relative overflow-hidden h-72"> <img className={`w-full h-full object-cover`} src={thumbnail} alt={coursetitle} /> <div className="overlay absolute bg-black top-0 h-full w-full"> </div> </figure> <div className="card-body gap-4"> <div className=" flex justify-between"> <Link to={`/courses/${category}`}> <span className="px-2 py-1 text-sm font-bold rounded-sm bg-sky-500 text-white"> {category} </span> </Link> {/* <Rating className="text-yellow-400" fullSymbol={<i className="fa-solid fa-star"></i>} emptySymbol={<i className="fa-regular fa-star"></i>} initialRating={Review} readonly /> */} </div> <Link to={`/single-course-view/${_id}`} className={`card-title block hover:text-sky-500 transition-all`} > {coursetitle.slice(0,50)+"..."} </Link> <p className="leading-8">{description.slice(0, 100) + "..."}</p> <hr className="my-3 border-gray-300" /> <div className="flex justify-between"> <p className="text-lg text-sky-500 ">${coursefee}</p> <div className="bookmark"> <i className="text-sky-500 fa-light fa-bookmark"></i> </div> </div> <div>{children}</div> </div> </div> ); }
import ScaleDownDestroy from "phaser3-rex-plugins/plugins/scale-down-destroy.js"; import { Label, RoundRectangle } from "phaser3-rex-plugins/templates/ui/ui-components.js"; export class ColoredWord extends Label { private readonly _config: ColoredWordConfig; private readonly _textElement: Phaser.GameObjects.Text; private readonly _visibleTimeline: Phaser.Tweens.Timeline; private _visibleTimelineCallback: () => void; constructor(scene: Phaser.Scene, config: ColoredWordConfig) { config = getValidConfig(config); const textElement = new Phaser.GameObjects.Text(scene, 0, 0, config.data.text, config.style); const background = new RoundRectangle(scene, 0, 0, 0, 0, 10, 0x0, 0.5); super(scene, { x: config.x, y: config.y, text: textElement, background: background, align: "center", space: { top: 10, left: 10, right: 10, bottom: 10 } }); this._config = config; this._textElement = textElement; this._visibleTimeline = this.createVisibleTimeline(); this.setInteractive() .on("pointerup", () => { if (this._config.onClick) { this._config.onClick(); } }); textElement.setDepth(2); background.setDepth(1); scene.add.existing(textElement); scene.add.existing(background); this.layout(); } public get originalColor(): string { return this._config.data.color; } public get actualColor(): string { return this._textElement.style.color; } public setOnClick(callback: () => void): ColoredWord { this._config.onClick = callback; return this; } public tweenVisible(callback?: () => void) { this._visibleTimelineCallback = callback; this._visibleTimeline.play(); } public tweenDestroy() { this._visibleTimeline.pause(); ScaleDownDestroy(this, 500); } public destroy(fromScene?: boolean): void { super.destroy(fromScene); } private createVisibleTimeline(): Phaser.Tweens.Timeline { const orgScale = this.scale; const timeline = this.scene.tweens.timeline({ targets: this, yoyo: false, loop: 0, paused: true, ease: "Cubic.easeIn", tweens: [ { duration: 1000, props: { scale: orgScale, alpha: 1.0 }, onStart: () => { this.setVisible(true); this.setOrigin(0.5); this.setScale(0); this.setAlpha(0); }, onComplete: () => { this.setScale(orgScale); } }, { duration: this._config.visibilityDuration, props: { scale: orgScale } }, { duration: 1000, props: { scale: orgScale*1.5, alpha: 0 }, onComplete: () => { this.setVisible(false); this.setScale(orgScale); this.setOrigin(0); this.setAlpha(1.0); } }, ], onComplete: () => { if (this._visibleTimelineCallback) { this._visibleTimelineCallback(); } } }); return timeline; } } export type ColoredWordConfig = { x: number; y: number; data: ColoredWordData; visibilityDuration?: number; style?: Phaser.Types.GameObjects.Text.TextStyle; onClick?: () => void; } export type ColoredWordData = { text: string; color?: string; } function getValidConfig(config: ColoredWordConfig): ColoredWordConfig { if (!config.data.color) { config.data.color = "#ffffff"; } if (!config.visibilityDuration) { config.visibilityDuration = 2000; } if (!config.style) { const fontSize = 2 * window.devicePixelRatio; config.style = { fontSize: `${fontSize}rem`, }; } config.data.color = config.data.color.toLowerCase(); config.data.text = config.data.text.toUpperCase(); return config; }
<script setup lang="ts"> import { UserOutlined, LockOutlined } from '@ant-design/icons-vue' import { reactive, ref } from 'vue' import type { FormInstance, Rule } from 'ant-design-vue/es/form' import type { Login } from '@/client' import { useUserStore } from '@/stores' const formState = reactive<Login>({ username: 'admin', password: '123456' }) const formRef = ref<FormInstance | null>() const rules: Record<string, Rule[]> = { username: [ { required: true, min: 5, max: 12, trigger: 'change', message: '请输入账号' } ], password: [ { required: true, min: 6, max: 12, trigger: 'change', message: '请输入密码' } ] } const userStore = useUserStore() const hadndleLogin = async () => { try { await formRef.value?.validateFields() } catch (error) { return } userStore.loginAction(formState) } </script> <template> <div class="login"> <div class="login-continer"> <h2>Mini RBAC</h2> <a-form :model="formState" :rules="rules" ref="formRef"> <a-form-item name="username"> <a-input v-model:value.trim="formState.username" placeholder="账号"> <template #prefix ><UserOutlined style="color: rgba(0, 0, 0, 0.25)" /></template> </a-input> </a-form-item> <a-form-item name="password"> <a-input v-model:value.trim="formState.password" type="password" placeholder="密码" > <template #prefix ><LockOutlined style="color: rgba(0, 0, 0, 0.25)" /></template> </a-input> </a-form-item> <a-form-item> <a-button type="primary" style="width: 100%" html-type="submit" :disabled="formState.username === '' || formState.password === ''" @click="hadndleLogin" > 登录 </a-button> </a-form-item> </a-form> </div> </div> </template> <style scoped> .login { display: flex; width: 100wh; height: 100vh; /* 主轴居中 */ justify-content: center; /* 交叉轴居中,需要有宽高 */ align-items: center; background: url('http://49.232.203.244:1856/assets/background.d7103c44.svg'); } .login-continer { /* 文本居中 */ text-align: center; width: 300px; height: 300px; padding: 20px; } .login-continer:hover { border: 1px solid rgba(220, 220, 220, 0.1); border-radius: 2rem; } /* 最后一个item 元素 外边距 */ .ant-form-item:last-child { margin-bottom: 0px !important; } </style>
import React from 'react'; import MoviesCard from "../MoviesCard/MoviesCard"; import {useLocation} from "react-router-dom"; import {getLikedMovies} from "../../utils/moviesUtils"; import {devices} from "../../utils/constants"; import useScreenWidth from "../../hooks/useScreenWidth"; import './MoviesCardList.css'; function MoviesCardList(props) { const {pathname: location} = useLocation(); const [showMovieList, setShowMovieList] = React.useState([]); const [cardsShowDetails, setCardsShowDetails] = React.useState({ total: 12, more: 3 }); const [isRender, setIsRender] = React.useState(true); const { desktop, tablet, mobile } = devices; const screenWidth = useScreenWidth(); function handleLoadMoreMovies() { const start = showMovieList.length; const end = start + cardsShowDetails.more; const add = props.moviesList.length - start; if (add > 0) { const newMovies = props.moviesList.slice(start, end); setShowMovieList([...showMovieList, ...newMovies]); } } React.useEffect(() => { if (location === '/movies') { if (screenWidth > desktop.width) { setCardsShowDetails(desktop.cards); } else if (screenWidth <= desktop.width && screenWidth > mobile.width) { setCardsShowDetails(tablet.cards); } else { setCardsShowDetails(mobile.cards); } return () => setIsRender(false); } }, [screenWidth, isRender, desktop, tablet, mobile, location]); React.useEffect(() => { if (props.moviesList.length) { const res = props.moviesList.filter((item, i) => i < cardsShowDetails.total); setShowMovieList(res); } }, [props.moviesList, cardsShowDetails.total]); return ( <section className='movies'> <ul className='movies__list'> {showMovieList.map(movie => ( <MoviesCard key={movie.id || movie._id} movie={movie} onDeleteClick={props.onDeleteClick} onLikeClick={props.onLikeClick} liked={getLikedMovies(props.likedMoviesList, movie)} /> ))} </ul> {location === '/movies' && showMovieList.length>=5 && showMovieList.length < props.moviesList.length && ( <button className="movies__button" type="button" onClick={handleLoadMoreMovies}>Ещё</button> )} </section> ) } export default MoviesCardList;
import { Component, OnInit } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormBuilder, FormControl, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { IonicModule, MenuController, NavController } from '@ionic/angular'; import { FormValidators as CustomValidators } from 'src/app/helpers/validators'; @Component({ selector: 'app-start', templateUrl: './start.page.html', styleUrls: ['./start.page.scss'], standalone: true, imports: [IonicModule, CommonModule, FormsModule, ReactiveFormsModule] }) export class StartPage implements OnInit { protected processing: boolean = false; protected isAlertOpen: boolean = false; protected alertMessage: string = ''; protected alertButtons: any = ['Ok']; protected registrationStartForm = this.formBuilder.group({ email: new FormControl<string>('', [Validators.required, Validators.email]), nick: new FormControl<string>('', Validators.required), password: new FormControl<string>('', Validators.required), passwordConfirmation: new FormControl<string>('', Validators.required), name: new FormControl<string>('', Validators.required), lastName: new FormControl<string>('', Validators.required), },{ validators: CustomValidators.ConfirmedValidator('password', 'passwordConfirmation') }); constructor( private navCtrl: NavController, private formBuilder: FormBuilder, private menuCtrl: MenuController ) { } ngOnInit() { } ionViewWillEnter() { this.menuCtrl.enable(false); } protected onBack() { this.navCtrl.navigateBack('/authentication/login'); } protected onNext() { this.navCtrl.navigateForward('/authentication/registration/skills'); } }
package io.binghe.seckill.interfaces.interceptor; import io.binghe.seckill.domain.code.HttpCode; import io.binghe.seckill.domain.constants.SeckillConstants; import io.binghe.seckill.domain.exception.SeckillException; import io.binghe.seckill.infrastructure.shiro.utils.JwtUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; /** * @author YouChuande */ @Component public class AuthInterceptor implements HandlerInterceptor { public static final String USER_ID = "userId"; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Object userId = request.getAttribute(USER_ID); if (userId != null) { return true; } String token = request.getHeader(SeckillConstants.TOKEN_HEADER_NAME); if (StringUtils.isEmpty(token)) { throw new SeckillException(HttpCode.USER_NOT_LOGIN); } Long userId1 = JwtUtils.getUserId(token); if (userId1 == null) { throw new SeckillException(HttpCode.USER_NOT_LOGIN); } HttpServletRequestWrapper authRequestWrapper = new HttpServletRequestWrapper(request); authRequestWrapper.setAttribute(USER_ID, userId1); return true; } }
<?php declare(strict_types=1); /** * @license MIT * @author hazuki3417<hazuki3417@gmail.com> * @copyright 2022 hazuki3417 all rights reserved. */ namespace Tests\Selen\MongoDB\Validator\Model; use PHPUnit\Framework\TestCase; use Selen\MongoDB\Validator\Model\ValidateResult; /** * @requires PHP >= 8.0 * * @coversDefaultClass \Selen\MongoDB\Validator\Model\ValidateResult * * @see ValidateResult * * @internal */ class ValidateResultTest extends TestCase { public function testConstruct(): void { $this->assertInstanceOf(ValidateResult::class, new ValidateResult()); } public function testSetResult(): void { $this->assertInstanceOf(ValidateResult::class, (new ValidateResult())->setResult(true)); } public function testSetArrayPath(): void { $this->assertInstanceOf(ValidateResult::class, (new ValidateResult())->setArrayPath('')); } public function testSetMessage(): void { $this->assertInstanceOf(ValidateResult::class, (new ValidateResult())->setMessage('')); } public function testGetResult1(): void { $this->assertTrue((new ValidateResult())->getResult()); } /** * @return array<string, array<string, mixed>> */ public function dataProviderGetResult(): array { return [ 'pattern001' => ['expected' => true, 'input' => true], 'pattern002' => ['expected' => false, 'input' => false], ]; } /** * @dataProvider dataProviderGetResult * * @param mixed $expected * @param mixed $input */ public function testGetResult2($expected, $input): void { $this->assertSame($expected, (new ValidateResult($input))->getResult()); } /** * @dataProvider dataProviderGetResult * * @param mixed $expected * @param mixed $input */ public function testGetResult3($expected, $input): void { $instance = new ValidateResult(); $this->assertSame($expected, $instance->setResult($input)->getResult()); } public function testGetArrayPath1(): void { $this->assertSame('', (new ValidateResult())->getArrayPath()); } /** * @return array<string, array<string, mixed>> */ public function dataProviderGetArrayPath(): array { return [ 'pattern001' => ['expected' => '', 'input' => ''], 'pattern002' => ['expected' => 'aaaaa', 'input' => 'aaaaa'], ]; } /** * @dataProvider dataProviderGetArrayPath * * @param mixed $expected * @param mixed $input */ public function testGetArrayPath2($expected, $input): void { $this->assertSame($expected, (new ValidateResult(true, $input))->getArrayPath()); } /** * @dataProvider dataProviderGetArrayPath * * @param mixed $expected * @param mixed $input */ public function testGetArrayPath3($expected, $input): void { $instance = new ValidateResult(); $this->assertSame($expected, $instance->setArrayPath($input)->getArrayPath()); } public function testGetMessage1(): void { $this->assertSame('', (new ValidateResult())->getMessage()); } /** * @return array<string, array<string, mixed>> */ public function dataProviderGetMessage(): array { return [ 'pattern001' => ['expected' => '', 'input' => ''], 'pattern002' => ['expected' => 'aaaaa', 'input' => 'aaaaa'], ]; } /** * @dataProvider dataProviderGetMessage * * @param mixed $expected * @param mixed $input */ public function testGetMessage2($expected, $input): void { $this->assertSame($expected, (new ValidateResult(true, '', $input))->getMessage()); } /** * @dataProvider dataProviderGetMessage * * @param mixed $expected * @param mixed $input */ public function testGetMessage3($expected, $input): void { $instance = new ValidateResult(); $this->assertSame($expected, $instance->setMessage($input)->getMessage()); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="./css/backgroundStar.css"> <link rel="stylesheet" href="./css/style.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;900&display=swap" rel="stylesheet"> </head> <body> <section class="content"> <div class="container" id="app" v-cloak> <!-- Header --> <div class="header" :class="{float}"> <div class="logo" :class="{hidden}"> <h1>My To Do List</h1> </div> <div class="nav " > <div class="btn btn-s" :class="{userName}"> <span></span>{{Welcome}}<br>{{FirstName}} {{LastName}}!</div> <a class="btn" href="#" @click="exit()" :class="{exitHidden}"> <span></span>{{End}}</a> <div class="translate"> <span></span> <div class="Ru" @click="Rus">Ru</div> <div class="En" @click="Eng">En</div> </div> </div> </div> <!-- Приветствие --> <div class="open "> <a class="btn" href="#" @click="start(), toggleAcc()" :class="{openHidden}"> <span></span>{{Welcome}} </a> </div> <!-- Меню авторизации --> <div class="account" v-if="accountV"> <div class="inputBox"> <input type="text" required="required" v-model="FirstName"> <span>{{FirstN}}</span> </div> <div class="inputBox"> <input type="text" required="required" v-model="LastName"> <span>{{LastN}}</span> </div> </div> <div class="login" :class="{loginNone}"> <a class="btn" href="#" @click="login"><span></span>{{Start}}</a> </div> <!-- Поле задач --> <div class="content__inner" :class="{table}"> <input class="input" type="text" :value="valueInput" @input="handleInput" @keypress.enter="addNote"> <button class="tableBtn" @click="addNote"><span></span>{{Add}}</button> <div class="counter">{{counter = notes.length}}</div> <ul class="list"> <li class="list__item" v-for="(note, index) in notes" :key="note.id"> {{note.title}} <button class="removeBtn" @click="removeBtn(index)"><span></span>{{Remove}}</button> </li> </ul> </div> </div> </section> <section class="wrapper"> <div id="stars"></div> <div id="stars1"></div> <div id="stars2"></div> <div id="stars3"></div> </section> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://unpkg.com/vue@next"></script> <script src="./js/app.js"></script> <script> $(document).ready(function (e) { $('.btn, .tableBtn, .translate').on('mouseenter', function (e) { x = e.pageX - $(this).offset().left; y = e.pageY - $(this).offset().top; $(this).find('span').css({ top: y, left: x }) }) $('.btn, .tableBtn, .translate').on('mouseout', function (e) { x = e.pageX - $(this).offset().left; y = e.pageY - $(this).offset().top; $(this).find('span').css({ top: y, left: x }) }) }) </script> </body> </html>
package com.example.bb2formacion.model; import com.fasterxml.jackson.annotation.JsonIgnore; import javax.persistence.*; import java.util.Date; @Entity @Table(name="`reduction`") public class Reduction { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "reduction_code", unique = true) private Integer reductionCode; private Double reducedPrice; private Date startDate; private Date endDate; @ManyToOne @JoinColumn(name="item_id") @JsonIgnore private Item item; public Reduction(Long id, Integer reductionCode, Double reducedPrice, Date startDate, Date endDate, Item item) { this.id = id; this.reductionCode = reductionCode; this.reducedPrice = reducedPrice; this.startDate = startDate; this.endDate = endDate; this.item = item; } public Reduction(){ } @Override public String toString() { return "Reduction{" + "id=" + id + ", reductionCode=" + reductionCode + ", reducedPrice=" + reducedPrice + ", startDate=" + startDate + ", endDate=" + endDate + ", item=" + item + '}'; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getReductionCode() { return reductionCode; } public void setReductionCode(Integer reductionCode) { this.reductionCode = reductionCode; } public Double getReducedPrice() { return reducedPrice; } public void setReducedPrice(Double reducedPrice) { this.reducedPrice = reducedPrice; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public Item getItem() { return item; } public void setItem(Item item) { this.item = item; } }
// // Copyright (c) 2020 Open Whisper Systems. All rights reserved. // import Foundation extension ConversationViewController { /// The visble content rect in the collection view's coordinate space /// This rect does not include displayed cells occluded by content inset @objc var visibleContentRect: CGRect { let collectionViewBounds = collectionView.bounds let insetBounds = collectionViewBounds.inset(by: collectionView.adjustedContentInset) return insetBounds } /// The index path of the last item in the collection view's visible rect @objc var lastVisibleIndexPath: IndexPath? { // For people looking at this in the future, UICollectionView has a very similar looking // property: -indexPathsForVisibleItems. Why aren't we using that? // // That property *almost* gives us what we want, but UIKit ordering isn't favorable. That property // gets updated after -scrollViewDidScroll: returns. But sometimes we want to know what cells are visible // with the updated -contentOffset in -scrollViewDidScroll:. So instead, we'll just see what layoutAttributes // are now in the collection view's visible content rect. This should be safe, since it's computed from the // already updated -contentOffset. let visibleLayoutAttributes = layout.layoutAttributesForElements(in: visibleContentRect) ?? [] let lastVisibleIndexPath = visibleLayoutAttributes .map { $0.indexPath } .max { $0.row < $1.row } if let lastVisibleIndexPath = lastVisibleIndexPath { assert(percentOfIndexPathVisibleAboveBottom(lastVisibleIndexPath) > 0) } return lastVisibleIndexPath } @objc var lastVisibleSortId: UInt64 { guard let lastVisibleIndexPath = lastVisibleIndexPath else { return 0 } return firstIndexPathWithSortId(atOrBeforeIndexPath: lastVisibleIndexPath)?.sortId ?? 0 } @objc var lastIndexPathInLoadedWindow: IndexPath? { guard !viewItems.isEmpty else { return nil } return IndexPath(row: viewItems.count - 1, section: 0) } @objc var lastSortIdInLoadedWindow: UInt64 { guard let lastIndexPath = lastIndexPathInLoadedWindow else { return 0 } return firstIndexPathWithSortId(atOrBeforeIndexPath: lastIndexPath)?.sortId ?? 0 } @objc func saveLastVisibleSortIdAndOnScreenPercentage() { AssertIsOnMainThread() let sortIdToSave: UInt64 let onScreenPercentageToSave: Double if let lastVisibleIndexPath = lastVisibleIndexPath, let (indexPath, sortId) = firstIndexPathWithSortId(atOrBeforeIndexPath: lastVisibleIndexPath) { sortIdToSave = sortId onScreenPercentageToSave = Double(percentOfIndexPathVisibleAboveBottom(indexPath)) } else { sortIdToSave = 0 onScreenPercentageToSave = 0 } guard thread.lastVisibleSortId != sortIdToSave || !thread.lastVisibleSortIdOnScreenPercentage.isEqual(to: onScreenPercentageToSave) else { return } databaseStorage.asyncWrite { transaction in self.thread.update( withLastVisibleSortId: sortIdToSave, onScreenPercentage: onScreenPercentageToSave, transaction: transaction ) } } private func percentOfIndexPathVisibleAboveBottom(_ indexPath: IndexPath) -> CGFloat { // If we don't have layout attributes, it's not visible guard let attributes = layout.layoutAttributesForItem(at: indexPath) else { return 0.0 } // Map everything to view controller's coordinate space let cellFrameInPrimaryCoordinateSpace = view.convert(attributes.frame, from: collectionView) let contentFrameInPrimaryCoordinateSpace = view.convert(visibleContentRect, from: collectionView) // Distance between top edge of cell's frame and the bottom of the content frame let heightAboveBottom = contentFrameInPrimaryCoordinateSpace.maxY - cellFrameInPrimaryCoordinateSpace.minY return CGFloatClamp01(heightAboveBottom / cellFrameInPrimaryCoordinateSpace.height) } private func firstIndexPathWithSortId(atOrBeforeIndexPath indexPath: IndexPath) -> (indexPath: IndexPath, sortId: UInt64)? { AssertIsOnMainThread() var matchingIndexPath = indexPath while let viewItem = viewItem(forIndex: matchingIndexPath.row), matchingIndexPath.row > 0 { guard !viewItem.interaction.isDynamicInteraction() else { matchingIndexPath.row -= 1 continue } return (matchingIndexPath, viewItem.interaction.sortId) } return nil } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!-- Generators is basically a function only but we can resume and pause it that means if we have 20 lines of code in function and we want to use only first 10 lines only then we can use Generators --> <h1>Generators</h1> <button onclick="getstep()">Go step by step</button> </body> <script> function* steps() // * to define generator function { let a = 10; let b = 20; console.log(a + b); yield 'step 1 completed' console.log(a - b); yield 'step 2 completed' console.log(a * b); yield 'step 3 completed' return "all steps done"; // optional } let stp = steps(); function getstep() { console.log(stp.next()); // stp.next() means ek step tak run karke pause kar dega i.e we are calling the generator using next(). } </script> </html>
Slope field Slope field table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode { margin: 0; padding: 0; vertical-align: baseline; border: none; } <style> table.sourceCode { width: 100%; line-height: 100%; } td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; } td.sourceCode { padding-left: 5px; } code > span.kw { color: #007020; font-weight: bold; } /* Keyword */ code > span.dt { color: #902000; } /* DataType */ code > span.dv { color: #40a070; } /* DecVal */ code > span.bn { color: #40a070; } /* BaseN */ code > span.fl { color: #40a070; } /* Float */ code > span.ch { color: #4070a0; } /* Char */ code > span.st { color: #4070a0; } /* String */ code > span.co { color: #60a0b0; font-style: italic; } /* Comment */ code > span.ot { color: #007020; } /* Other */ code > span.al { color: #ff0000; font-weight: bold; } /* Alert */ code > span.fu { color: #06287e; } /* Function */ code > span.er { color: #ff0000; font-weight: bold; } /* Error */ code > span.wa { color: #60a0b0; font-weight: bold; font-style: italic; } /* Warning */ code > span.cn { color: #880000; } /* Constant */ code > span.sc { color: #4070a0; } /* SpecialChar */ code > span.vs { color: #4070a0; } /* VerbatimString */ code > span.ss { color: #bb6688; } /* SpecialString */ code > span.im { } /* Import */ code > span.va { color: #19177c; } /* Variable */ code > span.cf { color: #007020; font-weight: bold; } /* ControlFlow */ code > span.op { color: #666666; } /* Operator */ code > span.bu { } /* BuiltIn */ code > span.ex { } /* Extension */ code > span.pp { color: #bc7a00; } /* Preprocessor */ code > span.at { color: #7d9029; } /* Attribute */ code > span.do { color: #ba2121; font-style: italic; } /* Documentation */ code > span.an { color: #60a0b0; font-weight: bold; font-style: italic; } /* Annotation */ code > span.cv { color: #60a0b0; font-weight: bold; font-style: italic; } /* CommentVar */ code > span.in { color: #60a0b0; font-weight: bold; font-style: italic; } /* Information */ In mathematics, a slope field (or direction field) is a graphical representation of the solutions of a first-order differential equation. It is useful because it can be created without solving the differential equation analytically. The representation may be used to qualitatively visualize solutions, or to numerically approximate them. Definition Standard case The slope field is traditionally defined for the following type of differential equations . It can be viewed as a creative way to plot a real-valued function of two real variables as a planar picture. Specifically, for a given pair , a vector with the components is drawn at the point on the -plane. Sometimes, the vector is normalized to make the plot better looking for a human eye. A set of pairs making a rectangular grid is typically used for the drawing. An Isocline (a series of lines with the same slope) is often used to supplement the slope field. In an equation of the form , the isocline is a line in the -plane plane obtained by setting equal to a constant. General case of a system of differential equations Given a system of differential equations, the slope field is an array of slope marks in the phase space (in any number of dimensions depending on the number of relevant variables; for example, two in the case of a first-order linear ODE, as seen to the right). Each slope mark is centered at a point and is parallel to the vector . The number, position, and length of the slope marks can be arbitrary. The positions are usually chosen such that the points make a uniform grid. The standard case, described above, represents . The general case of the slope field for systems of differential equations is not easy to visualize for . General application With computers, complicated slope fields can be quickly made without tedium, and so an only recently practical application is to use them merely to get the feel for what a solution should be before an explicit general solution is sought. Of course, computers can also just solve for one, if it exists. If there is no explicit general solution, computers can use slope fields (even if they aren’t shown) to numerically find graphical solutions. Examples of such routines are Euler's method, or better, the Runge-Kutta methods. Software for plotting slope fields Different software packages can plot slope fields. Example code in GNU Octave/MATLAB Ffun = @(X,Y)X.*Y; % function f(x,y)=xy [X,Y]=meshgrid(-2:.3:2,-2:.3:2); % choose the plot sizes DY=Ffun(X,Y); DX=ones(size(DY)); % generate the plot values quiver(X,Y,DX,DY); % plot the direction field hold on; contour(X,Y,DY,[-6 -2 -1 0 1 2 6]); %add the isoclines title('Slope field and isoclines for f(x,y)=xy') Alternate example code in GNU Octave/MATLAB funn = @(x,y)y-x; % function f(x,y)=y-x [x,y]=meshgrid(-2:0.5:2); % intervals for x and y slopes=funn(x,y); % matrix of slopes dy=slopes./sqrt(1+slopes.^2); % normalize the line element... dx=sqrt(1-dy.^2); % ...magnitudes for dy and dx quiver(x,y,dx,dy); % plot the direction field Example code for Maxima /* field for y'=xy (click on a point to get an integral curve) */ plotdf( x*y, [x,-2,2], [y,-2,2]); Example code for Mathematica (* field for y'=xy *) VectorPlot[{1,x*y},{x,-2,2},{y,-2,2}] Examples Image:Slope_field_1.svg|Slope field Image:Slope_field_with_integral_curves_1.svg|Integral curves image:Isocline_3.png|Isoclines (blue), slope field (black), and some solution curves (red) See also Examples of differential equations Vector field Laplace transform applied to differential equations List of dynamical systems and differential equations topics References Blanchard, Paul; Devaney, Robert L.; and Hall, Glen R. (2002). Differential Equations (2nd ed.). Brooks/Cole: Thompson Learning. ISBN 0-534-38514-1 External links Slope field plotter " Category:Calculus Category:Differential equations Category:Articles with example MATLAB/Octave code
#include "header.h" int main (int argc, char *argv[]) { //********************************************************* // VARIABLES PARA MEDIR TIEMPO //********************************************************* double utime0, stime0, wtime0,utime1, stime1, wtime1; //Variables para medición de tiempos int n; //n determina el tamaño del algorito dado por argumento al ejecutar int i; //Variables para loops //************************************************************************** // Iniciar el conteo del tiempo para las evaluaciones de rendimiento //************************************************************************** uswtime(&utime0, &stime0, &wtime0); srand(time(NULL)); int **matrix1 = generateMatrix(); int **matrix2 = generateMatrix(); printf("Matriz 1:\n"); showMatrix(matrix1, 10); printf("\nMatriz 2:\n"); showMatrix(matrix2, 10); char folder[] = "./output"; char sub_FILE[] = "Resta.txt"; char add_FILE[] = "Suma.txt"; char mult_FILE[] = "Mult.txt"; char inverse_FILE[] = "Inversa.txt"; char transpose_FILE[] = "Transpuesta.txt"; char transpose2_FILE[] = "Transpuesta2.txt"; char inverse2_FILE[] = "Inversa2.txt"; FILE *addFile = createFile(folder, add_FILE); FILE *subFile = createFile(folder, sub_FILE); FILE *multFile = createFile(folder, mult_FILE); FILE *transposeFile = createFile(folder, transpose_FILE); FILE *transpose2File = createFile(folder, transpose2_FILE); FILE *inverseFile = createFile(folder, inverse_FILE); FILE *inverse2File = createFile(folder, inverse2_FILE); addMatrix(matrix1, matrix2, addFile); subMatrix(matrix1, matrix2, subFile); multMatrix(matrix1, matrix2, multFile); int **transpose = transposeMatrix(matrix1, 10); int **transpose2 = transposeMatrix(matrix2, 10); writeMatrix(transposeFile, (void **) transpose, 10, 'i'); writeMatrix(transpose2File, (void **) transpose2, 10, 'i'); // Inversa de la matriz float **inverse = inverseMatrix(matrix1, 10); float **inverse2 = inverseMatrix(matrix2, 10); writeMatrix(inverseFile, (void **) inverse, 10, 'f'); writeMatrix(inverse2File, (void **) inverse2, 10, 'f'); //****************************************************************** // Mostrar Resultados //****************************************************************** printf("Suma:\n\n"); readIntMatrix(addFile, 10); printf("\nResta:\n\n"); readIntMatrix(subFile, 10); printf("\nMultiplicación:\n\n"); readIntMatrix(multFile, 10); printf("\nTranspuesta de la Matriz 1:\n\n"); readIntMatrix(transposeFile, 10); printf("\nTranpuesta de la Matriz 2: \n\n"); readIntMatrix(transpose2File, 10); printf("\nInversa de la Matriz 1: \n\n"); readFloatMatrix(inverseFile, 10); printf("\nInversa de la Matriz 2:\n\n"); readFloatMatrix(inverse2File, 10); //****************************************************************** // Liberar Memoria //****************************************************************** freeIntMatrix(transpose, 10); freeIntMatrix(matrix1, 10); freeIntMatrix(matrix2, 10); freeFloatMatrix(inverse, 10); freeFloatMatrix(inverse2, 10); //****************************************************************** // Cerrar los Archivos //****************************************************************** fclose(transposeFile); fclose(multFile); fclose(addFile); fclose(subFile); fclose(inverseFile); //****************************************************************** // Evaluar los tiempos de ejecución //****************************************************************** uswtime(&utime1, &stime1, &wtime1); printf("\nTiempo de Ejecucion\n"); printf("real (Tiempo total) %.10f s\n", wtime1 - wtime0); printf("user (Tiempo de procesamiento en CPU) %.10f s\n", utime1 - utime0); printf("sys (Tiempo en acciónes de E/S) %.10f s\n", stime1 - stime0); printf("CPU/Wall %.10f %% \n",100.0 * (utime1 - utime0 + stime1 - stime0) / (wtime1 - wtime0)); printf("\n"); // Mostrar los tiempos en formato exponecial printf("\n"); printf("real (Tiempo total) %.10e s\n", wtime1 - wtime0); printf("user (Tiempo de procesamiento en CPU) %.10e s\n", utime1 - utime0); printf("sys (Tiempo en acciónes de E/S) %.10e s\n", stime1 - stime0); printf("CPU/Wall %.10f %% \n",100.0 * (utime1 - utime0 + stime1 - stime0) / (wtime1 - wtime0)); printf("\n"); //****************************************************************** return 0; }
package com.example.date_notes.data.converters import androidx.room.TypeConverter import java.time.LocalDateTime import java.time.ZoneOffset object LocalDateTimeConverter { @TypeConverter fun fromSeconds(seconds: Long?): LocalDateTime? { return seconds?.let { LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC) } } @TypeConverter fun toSeconds(dateTime: LocalDateTime?): Long? { return dateTime?.atZone(ZoneOffset.UTC)?.toEpochSecond() } }
class Solution { public int countSubstrings(String s) { int count = 0; int n = s.length(); boolean[][] isPalindrome = new boolean[n][n]; for (int len = 1; len <= n; len++) { for (int start = 0; start <= n - len; start++) { int end = start + len - 1; if (len == 1) { isPalindrome[start][end] = true; } else if (len == 2) { isPalindrome[start][end] = (s.charAt(start) == s.charAt(end)); } else { isPalindrome[start][end] = (s.charAt(start) == s.charAt(end) && isPalindrome[start + 1][end - 1]); } if (isPalindrome[start][end]) { count++; } } } return count; } }
package handlers import ( "fmt" dto "moonlay-test/internal/app/dto/result" todolistsdto "moonlay-test/internal/app/dto/todolist" "moonlay-test/internal/app/models" "moonlay-test/internal/app/repositories" "net/http" "strconv" "strings" "github.com/go-playground/validator/v10" "github.com/labstack/echo/v4" ) type handlerTodoList struct { TodoListRepository repositories.TodoListRepository } func HandlerTodoList(TodoListRepository repositories.TodoListRepository) *handlerTodoList { return &handlerTodoList{TodoListRepository} } func (h *handlerTodoList) FindTodoList(c echo.Context) error { todos, err := h.TodoListRepository.FindTodoList() if err != nil { return c.JSON(http.StatusInternalServerError, dto.ErrorResult{Code: http.StatusBadRequest, Message: err.Error()}) } if len(todos) > 0 { return c.JSON(http.StatusOK, dto.SuccessResult{Code: http.StatusOK, Message: "Data for all todos was successfully obtained", Data: todos}) } else { return c.JSON(http.StatusBadRequest, dto.ErrorResult{Code: http.StatusBadRequest, Message: "No record found"}) } } func (h *handlerTodoList) GetAllTodoLists(c echo.Context) error { page, _ := strconv.Atoi(c.QueryParam("page")) pageSize, _ := strconv.Atoi(c.QueryParam("page_size")) search := c.QueryParam("search") todolists, totalCount, err := h.TodoListRepository.GetAllTodoLists(page, pageSize, search) if err != nil { return c.JSON(http.StatusInternalServerError, dto.ErrorResult{Code: http.StatusInternalServerError, Message: err.Error()}) } responseData := struct { TotalCount int `json:"total_count"` Page int `json:"page"` PageSize int `json:"page_size"` Data []models.TodoList `json:"data"` }{ TotalCount: totalCount, Page: page, PageSize: pageSize, Data: todolists, } return c.JSON(http.StatusOK, dto.SuccessResult{Code: http.StatusOK, Message: "Todo data successfully obtained", Data: responseData}) } func (h *handlerTodoList) GetTodoList(c echo.Context) error { id, _ := strconv.Atoi(c.Param("id")) var todolist models.TodoList todolist, err := h.TodoListRepository.GetTodoList(id) if err != nil { return c.JSON(http.StatusBadRequest, dto.ErrorResult{Code: http.StatusBadRequest, Message: err.Error()}) } return c.JSON(http.StatusOK, dto.SuccessResult{Code: http.StatusOK, Data: todolist}) } func (h *handlerTodoList) CreateTodoList(c echo.Context) error { dataFile := c.Get("dataFiles").([]string) stringDataFiles := strings.Join(dataFile, ",") request := todolistsdto.CreateTodoListRequest{ Title: c.FormValue("title"), Description: c.FormValue("description"), Files: stringDataFiles, } validation := validator.New() err := validation.Struct(request) if err != nil { return c.JSON(http.StatusBadRequest, dto.ErrorResult{Code: http.StatusBadRequest, Message: err.Error()}) } todolist := models.TodoList{ Title: request.Title, Description: request.Description, Files: request.Files, } data, err := h.TodoListRepository.CreateTodoList(todolist) if err != nil { return c.JSON(http.StatusInternalServerError, dto.ErrorResult{Code: http.StatusInternalServerError, Message: err.Error()}) } fmt.Println(data.Files, "dataFiles") result := map[string]interface{}{ "title": data.Title, "description": data.Description, "files": strings.Split(data.Files, ","), "sublist": data.SubList, } return c.JSON(http.StatusOK, dto.SuccessResult{Code: http.StatusOK, Data: result}) } func (h *handlerTodoList) UpdateTodoList(c echo.Context) error { dataFile := c.Get("dataFiles").([]string) stringDataFiles := strings.Join(dataFile, ",") request := todolistsdto.UpdateTodoListRequest{ Title: c.FormValue("title"), Description: c.FormValue("description"), Files: stringDataFiles, } id, _ := strconv.Atoi(c.Param("id")) todolist, err := h.TodoListRepository.GetTodoList(id) if err != nil { return c.JSON(http.StatusBadRequest, dto.ErrorResult{Code: http.StatusBadRequest, Message: err.Error()}) } if request.Title != "" { todolist.Title = request.Title } if request.Description != "" { todolist.Description = request.Description } if request.Files != "" { todolist.Files = request.Files } data, err := h.TodoListRepository.UpdateTodoList(todolist) if err != nil { return c.JSON(http.StatusInternalServerError, dto.ErrorResult{Code: http.StatusInternalServerError, Message: err.Error()}) } fmt.Println(data.Files) result := map[string]interface{}{ "title": data.Title, "description": data.Description, "files": strings.Split(data.Files, ","), "sublist": data.SubList, } return c.JSON(http.StatusOK, dto.SuccessResult{Code: http.StatusOK, Data: result}) } func (h *handlerTodoList) DeleteTodoList(c echo.Context) error { id, _ := strconv.Atoi("id") todolist, err := h.TodoListRepository.GetTodoList(id) if err != nil { return c.JSON(http.StatusBadRequest, dto.ErrorResult{Code: http.StatusBadRequest, Message: err.Error()}) } data, err := h.TodoListRepository.DeleteTodoList(todolist) if err != nil { return c.JSON(http.StatusInternalServerError, dto.ErrorResult{Code: http.StatusInternalServerError, Message: err.Error()}) } return c.JSON(http.StatusOK, dto.SuccessResult{Code: http.StatusOK, Data: data}) }
import React, { Component } from "react"; import PropTypes from "prop-types"; import { withStyles } from "@material-ui/core/styles"; import Table from "@material-ui/core/Table"; import TableBody from "@material-ui/core/TableBody"; import TableCell from "@material-ui/core/TableCell"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import Paper from "@material-ui/core/Paper"; import { LocationOnOutlined, InfoOutlined } from "@material-ui/icons"; import { Link } from "@material-ui/core"; const CustomTableCell = withStyles(theme => ({ head: { backgroundColor: theme.palette.common.black, color: theme.palette.common.white }, body: { fontSize: 14 } }))(TableCell); const styles = theme => ({ root: { width: "90ch", marginTop: theme.spacing.unit * 3, overflowX: "auto" }, table: { minWidth: 700 }, row: { "&:nth-of-type(odd)": { backgroundColor: theme.palette.background.default } } }); class DataTable extends Component { render() { const { classes } = this.props; return ( <Paper className={classes.root}> <Table className={classes.table}> <TableHead style={{ position: "" }}> <TableRow> <CustomTableCell>MARKET</CustomTableCell> <CustomTableCell>INFO</CustomTableCell> <CustomTableCell align="center">OPENINGS</CustomTableCell> <CustomTableCell align="center">MORE</CustomTableCell> </TableRow> </TableHead> <TableBody> {this.props.data.map(data => ( <TableRow className={classes.row} key={data.id}> <CustomTableCell component="th" scope="row" style={{ width: "25vw" }} > <b>{data.market}</b> </CustomTableCell> <CustomTableCell align="center" style={{ width: "5vw" }}> <Link href={data.location} target="_blank" color="secondary"> <LocationOnOutlined /> </Link> <Link href={data.offer} target="_blank" color="primary"> <InfoOutlined /> </Link> </CustomTableCell> <CustomTableCell align="center" style={{ width: "30vw" }}> {data.opening} </CustomTableCell> <CustomTableCell align="center" style={{ width: "25vw" }}> {data.information} </CustomTableCell> </TableRow> ))} </TableBody> </Table> </Paper> ); } componentWillMount() { this.props.displayLoadingBar(500); } } DataTable.propTypes = { classes: PropTypes.object.isRequired }; export default withStyles(styles)(DataTable);
<?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:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.org/ui"> <ui:composition> <p:dialog id="ServiceClientsCreateDlg" widgetVar="ServiceClientsCreateDialog" modal="true" resizable="false" appendTo="@(body)" header="#{myBundle.CreateServiceClientsTitle}" closeOnEscape="true"> <h:form id="ServiceClientsCreateForm"> <h:panelGroup id="display" rendered="#{serviceClientsController.selected != null}"> <p:panelGrid columns="2" columnClasses="column"> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_name}" for="name" /> <p:inputText id="name" value="#{serviceClientsController.selected.name}" title="#{myBundle.CreateServiceClientsTitle_name}" required="true" requiredMessage="#{myBundle.CreateServiceClientsRequiredMessage_name}" size="100" maxlength="100"/> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_hostname}" for="hostname" /> <p:inputText id="hostname" value="#{serviceClientsController.selected.hostname}" title="#{myBundle.CreateServiceClientsTitle_hostname}" required="true" requiredMessage="#{myBundle.CreateServiceClientsRequiredMessage_hostname}" size="100" maxlength="100"/> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_addressBegin}" for="addressBegin" /> <p:inputText id="addressBegin" value="#{serviceClientsController.selected.addressBegin}" title="#{myBundle.CreateServiceClientsTitle_addressBegin}" size="100" maxlength="100"/> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_addressEnd}" for="addressEnd" /> <p:inputText id="addressEnd" value="#{serviceClientsController.selected.addressEnd}" title="#{myBundle.CreateServiceClientsTitle_addressEnd}" size="100" maxlength="100"/> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_username}" for="username" /> <p:inputText id="username" value="#{serviceClientsController.selected.username}" title="#{myBundle.CreateServiceClientsTitle_username}" size="100" maxlength="100"/> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_password}" for="password" /> <p:inputText id="password" value="#{serviceClientsController.selected.password}" title="#{myBundle.CreateServiceClientsTitle_password}" size="100" maxlength="100"/> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_credentialsRequired}" for="credentialsRequired" /> <p:selectBooleanCheckbox id="credentialsRequired" value="#{serviceClientsController.selected.credentialsRequired}" required="true" requiredMessage="#{myBundle.CreateServiceClientsRequiredMessage_credentialsRequired}"/> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_ignoreRegistrationValidations}" for="ignoreRegistrationValidations" /> <p:selectBooleanCheckbox id="ignoreRegistrationValidations" value="#{serviceClientsController.selected.ignoreRegistrationValidations}" required="true" requiredMessage="#{myBundle.CreateServiceClientsRequiredMessage_ignoreRegistrationValidations}"/> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_channelId}" for="channelId" /> <p:selectOneMenu id="channelId" value="#{serviceClientsController.selected.channelId}" converter="channelsConverter"> <f:selectItem itemLabel="#{myBundle.SelectOneMessage}"/> <f:selectItems value="#{channelsController.items}" var="channelIdItem" itemValue="#{channelIdItem}" itemLabel="#{channelIdItem.internalName.toString()}" /> </p:selectOneMenu> <p:outputLabel value="#{myBundle.CreateServiceClientsLabel_memberId}" for="memberId" /> <p:selectOneMenu id="memberId" value="#{serviceClientsController.selected.memberId}" converter="membersConverter"> <f:selectItem itemLabel="#{myBundle.SelectOneMessage}"/> <f:selectItems value="#{membersController.items}" var="memberIdItem" itemValue="#{memberIdItem}" itemLabel="#{memberIdItem.name.toString()}" /> </p:selectOneMenu> </p:panelGrid> <p:commandButton actionListener="#{serviceClientsController.saveNew}" value="#{myBundle.Save}" update="display,:ServiceClientsListForm:datalist,:growl" oncomplete="handleSubmit(xhr,status,args,PF('ServiceClientsCreateDialog'));"> <p:confirm header="#{myBundle.ConfirmationHeader}" message="#{myBundle.ConfirmCreateMessage}" icon="ui-icon-alert"/> </p:commandButton> <p:commandButton value="#{myBundle.Cancel}" oncomplete="PF('ServiceClientsCreateDialog').hide()" update="display" process="@this" immediate="true" resetValues="true"/> </h:panelGroup> </h:form> </p:dialog> </ui:composition> </html>
<h1>Listing articles</h1> <%= button_to "New Article", new_article_path, :method => :get, class: 'btn btn-block btn-outline-primary' %> <br> <table class="table table-hover table-dark"> <tr> <th>Title</th> <th>Text</th> <th>Actions</th> </tr> <% @articles.each do |article| %> <tr> <td><%= article.title %></td> <td><%= article.text %></td> <td> <% if can? :manage, article %> <%= link_to 'Show', article_path(article), class: 'btn btn-outline-light' %> <%= link_to 'Edit', edit_article_path(article), class: 'btn btn-outline-warning' %> <%= link_to 'Destroy', article_path(article), class: 'btn btn-outline-danger', method: :delete, data: { confirm: 'Are you sure?' } %> <% end %> </td> </tr> <% end %> </table>
export interface TeamDetails { id: string; name: string; shortName: string; officialName: string; code: string; position: string; country: { id: string; name: string; }; } export interface CompetitionDetails { coverageLevel: string; tournamentCalendar: { id: string; name: string; }; competition: { id: string; name: string; stage: string; }; venue: { id: string; name: string; }; } export interface TeamStats { fh: string; sh: string; type: string; value: string; } export interface MatchDetails { scores: { ht: { home: number; away: number; }; ft: { home: number; away: number; }; total: { home: number; away: number; }; }; } export interface APIResponse { match: { contestant: TeamDetails[]; liveData: { lineups: { home: { stats: TeamStats[]; }; away: { stats: TeamStats[]; }; }; matchDetails: MatchDetails; }; meta: CompetitionDetails; }; }
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray, Validators, FormControl, } from '@angular/forms'; import { HttpClient } from '@angular/common/http'; import { Router } from '@angular/router'; import { settings } from '../envs/environment'; @Component({ selector: 'app-frame-submission', templateUrl: './framesubmission.component.html', styleUrls: ['./framesubmission.component.css'], }) export class FrameSubmissionComponent implements OnInit { frameForm: FormGroup; submitting = false; constructor( private fb: FormBuilder, private http: HttpClient, private router: Router ) {} ngOnInit() { this.frameForm = this.fb.group({ title: [ '', [ Validators.required, Validators.minLength(3), Validators.maxLength(30), ], ], frames: this.fb.array([]), }); } get frames() { return this.frameForm.get('frames') as FormArray; } get Title() { return this.frameForm.get('title') as FormControl; } bulkSelection(event) { var files = event.target.files; let filesArray = Array.from(files); console.log(filesArray); filesArray.forEach((file: any, index) => { if (file) { // this.frames.controls[index].get('image').setValue(file); const reader = new FileReader(); reader.onload = () => { this.frames.controls[index].get('imageData').setValue(reader.result); }; reader.readAsDataURL(file); this.frames.push( this.fb.group({ answer: [ '', [ Validators.required, Validators.minLength(3), Validators.maxLength(30), ], ], imageData: reader.result, image: [file, [Validators.required]], // Store the selected image file here }) ); } }); } addFrame() { this.frames.push( this.fb.group({ answer: [ '', [ Validators.required, Validators.minLength(3), Validators.maxLength(30), ], ], imageData: '', image: [null, [Validators.required]], // Store the selected image file here }) ); } answerErrors(index) { return ( this.frames.controls[index].get('answer').touched && this.frames.controls[index].get('answer').errors ); } fileErrors(index) { return ( this.frames.controls[index].get('image').touched && this.frames.controls[index].get('image').errors ); } AnswerErrors(index) { return this.frames.controls[index].get('answer').errors; } ImageErrors(index) { return this.frames.controls[index].get('image').errors; } onFileChange(event: any, index: number) { const file = event.target.files[0]; if (file) { this.frames.controls[index].get('image').setValue(file); const reader = new FileReader(); reader.onload = () => { this.frames.controls[index].get('imageData').setValue(reader.result); }; reader.readAsDataURL(file); } } removeEntry(index) { this.frames.removeAt(index); } submitFrames() { this.submitting = true; const formData = new FormData(); formData.append('title', this.frameForm.get('title').value); this.frameForm.value.frames.forEach((frame: any) => { formData.append('answers', frame.answer); if (frame.image) { formData.append('images', frame.image, frame.image.name); } }); console.log(this.frameForm.value); this.http.post(`${settings.url}/api/Survey/PostFrames`, formData).subscribe( (response) => { console.log('Response from backend:', response); this.router.navigate(['/']); this.submitting = false; }, (error) => { console.error('Error while submitting:', error); this.submitting = false; } ); } }
package main import ( "encoding/xml" "fmt" "io" "log" "net/http" "os" rpc_xml "github.com/divan/gorilla-xmlrpc/xml" "github.com/gorilla/rpc" "layout" ) // Define a struct for your service and the methods you want to expose via XML-RPC. type DisplayService struct{} type XMLLayout struct { XMLContent []byte } func (h *DisplayService) SetDisplayLayout(r *http.Request, args *XMLLayout, reply *struct{ Message string }) error { var layoutDef layout.LayoutDefinition xml.Unmarshal(args.XMLContent, &layoutDef) fmt.Printf("Device Type: %d\n", layoutDef.DeviceType) fmt.Printf("Display Width: %d\n", layoutDef.DisplayWidth) fmt.Printf("Display Height: %d\n", layoutDef.DisplayHeight) for _, layout := range layoutDef.Layouts { fmt.Printf("Layout Name: %s\n", layout.Name) for _, page := range layout.Pages { for _, panel := range page.Panels { fmt.Printf("Panel X: %d, Y: %d, Width: %d, Height: %d\n", panel.X, panel.Y, panel.Width, panel.Height) for _, text := range panel.Texts { fmt.Printf("Text Name: %s, X: %d, Y: %d, Width: %d, Height: %d, FontList: %s, AlignX: %s, AlignY: %s, RotationType: %s, Border: %s\n", text.Name, text.X, text.Y, text.Width, text.Height, text.FontList, text.AlignX, text.AlignY, text.RotationType, text.Border) } } } } reply.Message = "Success" return nil } func serveHTML(w http.ResponseWriter, r *http.Request) { htmlFile, err := os.Open("display/template/page.html") if err != nil { fmt.Printf("Error opening file: %v\n", err) return } defer htmlFile.Close() html, _ := io.ReadAll(htmlFile) w.Header().Set("Content-Type", "text/html") fmt.Fprint(w, string(html)) } func main() { /* var layoutDef layout.LayoutDefinition err := (&layoutDef).ReadLayout() if err != nil { fmt.Printf("Error decoding XML: %v\n", err) return } */ // create a default route handler http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) { fmt.Fprint(res, "Hello: "+req.Host) }) s := rpc.NewServer() xmlrpcCodec := rpc_xml.NewCodec() s.RegisterCodec(xmlrpcCodec, "text/xml") s.RegisterService(new(HelloService), "") s.RegisterService(new(DisplayService), "") http.Handle("/RPC2", s) http.HandleFunc("/display", serveHTML) log.Println("Starting XML-RPC server on localhost:5000/RPC2") log.Fatal(http.ListenAndServe(":5000", nil)) log.Println("Server started...") }
import { WalletError, WalletNotConnectedError, WalletNotReadyError } from '@solana/wallet-adapter-base'; import { get, writable } from 'svelte/store'; import { WalletNotSelectedError } from './errors'; import { useLocalStorage } from './useLocalStorage'; import type { Connection, PublicKey, Transaction, TransactionSignature } from '@solana/web3.js'; import type { SendTransactionOptions, SignerWalletAdapterProps, MessageSignerWalletAdapterProps } from '@solana/wallet-adapter-base'; import type { Wallet, WalletName } from '@solana/wallet-adapter-wallets'; type Adapter = ReturnType<Wallet['adapter']>; type WalletDictionary = { [name in WalletName]: Wallet }; type onError = (error: WalletError) => void; interface useWalletStoreT { wallets: Wallet[]; autoConnect: boolean; walletsByName: WalletDictionary; wallet: Wallet | null; publicKey: PublicKey | null; ready: boolean; connected: boolean; connecting: boolean; disconnecting: boolean; select(walletName: WalletName): void; connect(): Promise<void>; disconnect(): Promise<void>; sendTransaction( transaction: Transaction, connection: Connection, options?: SendTransactionOptions ): Promise<TransactionSignature>; signTransaction: SignerWalletAdapterProps['signTransaction'] | undefined; signAllTransactions: SignerWalletAdapterProps['signAllTransactions'] | undefined; signMessage: MessageSignerWalletAdapterProps['signMessage'] | undefined; } interface useWalletNameStoreT { walletName: WalletName | undefined; } interface useWalletAdapterStoreT { adapter: Adapter | null; } const select = async (newWalletName: WalletName): Promise<void> => { const { walletName } = get(useWalletName); const { adapter } = get(useWalletAdapter); if (walletName === newWalletName) return; if (adapter) await adapter.disconnect(); useWalletName.update((storeValues: useWalletNameStoreT) => ({ ...storeValues, walletName: newWalletName })); }; // Connect the adapter to the wallet. const connect = async (): Promise<void> => { const { connected, connecting, disconnecting, wallet, ready } = get(useWallet); const { adapter } = get(useWalletAdapter); if (connected || connecting || disconnecting) return; if (!wallet || !adapter) throw newError(new WalletNotSelectedError()); if (!ready) { useWalletName.update((storeValues: useWalletNameStoreT) => ({ ...storeValues, walletName: undefined })); window.open(wallet.url, '_blank'); throw newError(new WalletNotReadyError()); } try { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, connecting: true })); await adapter.connect(); } catch (error: unknown) { useWalletName.update((storeValues: useWalletNameStoreT) => ({ ...storeValues, walletName: undefined })); throw error; } finally { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, connecting: false })); } }; // Disconnect the adapter from the wallet. const disconnect = async (): Promise<void> => { const { disconnecting } = get(useWallet); const { adapter } = get(useWalletAdapter); if (disconnecting) return; if (!adapter) { useWalletName.update((storeValues: useWalletNameStoreT) => ({ ...storeValues, walletName: undefined })); return; } try { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, disconnecting: true })); await adapter.disconnect(); // localStorage.removeItem(localStorageKey); } finally { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, disconnecting: false })); useWalletName.update((storeValues: useWalletNameStoreT) => ({ ...storeValues, walletName: undefined })); } }; // Send a transaction using the provided connection. const sendTransaction = async ( transaction: Transaction, connection: Connection, options?: SendTransactionOptions ) => { const { connected } = get(useWallet); const { adapter } = get(useWalletAdapter); if (!adapter) throw newError(new WalletNotSelectedError()); if (!connected) throw newError(new WalletNotConnectedError()); return await adapter.sendTransaction(transaction, connection, options); }; //export const useWallet export const useWallet = writable<useWalletStoreT>({ //Props wallets: [], autoConnect: false, // Data walletsByName: null, wallet: null, publicKey: null, ready: false, connected: false, connecting: false, disconnecting: false, // Methods select, connect, disconnect, sendTransaction, signTransaction: undefined, signAllTransactions: undefined, signMessage: undefined }); const useWalletName = writable<useWalletNameStoreT>({ walletName: undefined }); const useWalletAdapter = writable<useWalletAdapterStoreT>({ adapter: null }); let triggerError: onError; let key: string; export async function initWallet({ wallets, autoConnect = false, localStorageKey = 'walletAdapter', onError = (error: WalletError) => console.error(error) }: { wallets: Wallet[]; autoConnect?: boolean; localStorageKey: string; onError?: onError; }): Promise<void> { const walletsByName = (): WalletDictionary => { return wallets.reduce((walletsByName, wallet) => { walletsByName[wallet.name] = wallet; return walletsByName; }, {} as WalletDictionary); }; triggerError = onError; key = localStorageKey; const walletName = useLocalStorage(key); useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, wallets, autoConnect, walletsByName: walletsByName() })); useWalletName.update((storeValues: useWalletNameStoreT) => ({ ...storeValues, walletName })); } // Handle the adapter events. const onReady = () => { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, ready: true })); }; const newError = (error: WalletError): WalletError => { triggerError(error); return error; }; const onConnect = () => { const { adapter } = get(useWalletAdapter); const { wallet } = get(useWallet); if (!adapter || !wallet) return; useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, wallet, ready: adapter.ready, publicKey: adapter.publicKey, connected: adapter.connected })); useWalletAdapter.update((storeValues: useWalletAdapterStoreT) => ({ ...storeValues, adapter })); }; const onDisconnect = () => { useWalletName.update((storeValues: useWalletNameStoreT) => ({ ...storeValues, walletName: undefined })); }; // watcher for walletName useWalletName.subscribe(({ walletName }: { walletName: WalletName | undefined }) => { if (walletName) { useLocalStorage(key, walletName); } const { walletsByName } = get(useWallet); const wallet = walletsByName?.[walletName as WalletName] ?? null; const adapter = wallet?.adapter() ?? null; if (adapter) { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, wallet })); useWalletAdapter.update((storeValues: useWalletAdapterStoreT) => ({ ...storeValues, adapter })); useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, ready: adapter.ready, publicKey: adapter.publicKey, connected: adapter.connected })); } else { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, wallet: null, ready: false, publicKey: null, connected: false })); useWalletAdapter.update((storeValues: useWalletAdapterStoreT) => ({ ...storeValues, adapter: null })); } }); // watcher for adapter useWalletAdapter.subscribe(({ adapter }: { adapter: Adapter | null }) => { if (!adapter) return; adapter.on('ready', onReady); adapter.on('connect', onConnect); adapter.on('disconnect', onDisconnect); adapter.on('error', triggerError); }); // watcher for auto-connect useWalletAdapter.subscribe(async ({ adapter }: { adapter: Adapter | null }) => { const { autoConnect, ready, connected, connecting } = get(useWallet); const { walletName } = get(useWalletName); if (!autoConnect || !adapter || !walletName || !ready || connected || connecting) return; try { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, connecting: true })); await adapter.connect(); } catch (error: unknown) { // Clear the selected wallet useWalletName.update((storeValues: useWalletNameStoreT) => ({ ...storeValues, walletName: undefined })); // Don't throw error, but onError will still be called } finally { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, connecting: false })); } }); // watcher for signature functions useWalletAdapter.subscribe(({ adapter }: { adapter: Adapter | null }) => { const { connected } = get(useWallet); // Sign a transaction if the wallet supports it. if (!(adapter && 'signTransaction' in adapter)) { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, signTransaction: undefined })); } else { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, signTransaction: async (transaction: Transaction) => { if (!connected) throw newError(new WalletNotConnectedError()); return await adapter.signTransaction(transaction); } })); } // Sign multiple transactions if the wallet supports it if (!(adapter && 'signAllTransactions' in adapter)) { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, signAllTransactions: undefined })); } else { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, signAllTransactions: async (transactions: Transaction[]) => { if (!connected) throw newError(new WalletNotConnectedError()); return await adapter.signAllTransactions(transactions); } })); } // Sign an arbitrary message if the wallet supports it. if (!(adapter && 'signMessage' in adapter)) { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, signMessage: undefined })); } else { useWallet.update((storeValues: useWalletStoreT) => ({ ...storeValues, signMessage: async (message: Uint8Array) => { if (!connected) throw newError(new WalletNotConnectedError()); return await adapter.signMessage(message); } })); } }); // This has to be used Svelte component inside onDestroy method export const destroyAdapter = (): void => { const { adapter } = get(useWalletAdapter); if (!adapter) return; adapter.off('ready', onReady); adapter.off('connect', onConnect); adapter.off('disconnect', onDisconnect); adapter.off('error', triggerError); };
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:uuid/uuid.dart'; final formatter = DateFormat.yMd(); const uuid = Uuid(); enum Category { Yemek, Seyahat, Eglence, IS } const categoryIcons = { Category.Yemek: Icons.lunch_dining, Category.Seyahat: Icons.flight_takeoff, Category.Eglence: Icons.movie, Category.IS: Icons.work, }; class ExpenseModel { ExpenseModel({required this.title, required this.amount, required this.date, required this.category}) : id = uuid.v4(); final String id; final String title; final double amount; final DateTime date; final Category category; String get formattedDate { return formatter.format(date); } } class ExpenseBucket { ExpenseBucket(this.category, this.expenses); final Category category; final List<ExpenseModel> expenses; ExpenseBucket.forCategory(List<ExpenseModel> allExpenses, this.category) : expenses = allExpenses.where((expense) => expense.category == category).toList(); double get totalExpenses { double sum = 0; for (final expense in expenses) { sum += expense.amount; } return sum; } }
package robjam1990.analytics.deeplearning; /** * Uses the Tanh function. * Tanh is a non-linear (S curve) function bounded by -1 and +1. * See, https://en.wikipedia.org/wiki/Hyperbolic_function#Hyperbolic_tangent */ public class TanhActivationFunction implements ActivationFunction { @Override public double calculate(double value) { return tanh(value); } @Override public double calculateInverse(double value) { double result = tanh(value); return 1.0 - (result * result); } private double tanh(double value) { return Math.tanh(value); } }
import csv from typing import List, Dict from elections_app.app.dtos.election_dto import ElectionsRequest, ContactsElectionResponse, UpdateContactRequest, \ ContactInfo from elections_app.app.persistency.contacts_db_access import ContactsDbAccess class Elections: def __init__(self): self.db_access = ContactsDbAccess({}) def get_contact_details(self, request: ElectionsRequest) -> List[ContactInfo]: # Determine the search criterion and value from the request if request.identity_number: criterion, value = 'identity_number', request.identity_number elif request.ballot_number: criterion, value = 'ballot_number', request.ballot_number elif request.ballot_order_number: criterion, value = 'ballot_order_number', request.ballot_order_number else: raise ValueError("No valid search criterion provided in the request") # Search for records using the new method all_records = self.db_access.search_contacts(criterion, value) filtered_records = [] for record in all_records: filtered_records.append(ContactInfo( id=record.identity_number, first_name=record.first_name, last_name=record.last_name, father_name=record.father_name, street=record.street_name, # Assuming street_name is the correct field house_number=record.house_number, ballot=record.ballot_number, voted=record.voted or False )) return filtered_records def get_all(self, page: int, filters: Dict, sort: str) -> ContactsElectionResponse: # Retrieve all records from the database results = self.db_access.get_all(filters=filters, page=page, sort=sort,page_size=25) all_records = results.get('contacts') total_rows = results.get('total_rows') total_pages = results.get('total_pages') all_contacts = [] for record in all_records: all_contacts.append(ContactInfo( id=record.identity_number, first_name=record.first_name, last_name=record.last_name, father_name=record.father_name, street=record.street_name, # Assuming street_name is the correct field house_number=record.house_number, ballot=record.ballot_number, voted=record.voted or False, )) return ContactsElectionResponse(results=all_contacts, total_pages=total_pages, total_rows=total_rows) def update_contact_voted(self, request: UpdateContactRequest): # Search for records using the new method record = self.db_access.update_contact_voted_status(request.id, request.ballot_order_id, request.voted) if record: return True
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title>Alexis Suárez</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <meta name="keywords" content="Desarrollo de Software, Diseño de páginas Web, Creación de Apps"> <meta name="description" content="Creación de Software profesional"> <meta name="owner" content="Alexis Suárez"> <meta name="author" content="alexissuarezllamas"> <meta name="robots" content="index, follow"> <script src="js/modernizr.js"></script> <link href="css/normalize.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <link href="css/design.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet"> </head> <body> <header> <h1> <a href="index.html"> <figure> <img src="img/icon.png" alt=""> </figure> </a> <a href="index.html">Alexis Suárez</a> </h1> <nav id="ioMenu"> <figure id="showMenu" class="ioMenuMovil" onclick="displayMenu()"> <img src="img/menu.png" alt=""> </figure> <div id="cardMenu"> <figure id="hideMenu" class="ioMenuMovil" onclick="displayMenu()"> <img src="img/exit.png" alt=""> </figure> <figure id="logoMenu"> <img src="img/logo.png" alt=""> </figure> <ul> <li><a onclick="navSection('home')" href="#">Home</a></li> <li><a onclick="navSection('aboutme')" href="#">Sobre Mi</a></li> <li><a onclick="navSection('skills')" href="#">Skills</a></li> <li><a onclick="navSection('portafolio')" href="#">Portafolio</a></li> <li><a onclick="navSection('blog')" href="#">Blog</a></li> <li><a onclick="displayFormContact('block')" href="#">Contacto</a></li> </ul> </div> </nav> <div id="prev_section" onclick="displaySection('prev')"><img src="icons/icon-08.png" alt=""></div> <div id="next_section" onclick="displaySection('next')"><img src="icons/icon-08.png" alt=""></div> </header> <div id="slider"> <section class="slide" id="home" style="display:block"> <div class="mainAnimation"> <div id="particles-js"></div> </div> <div class="mainLogo"> <h2>Soy un <strong>Desarrollador de Software</strong></h2> <figure> <img src="img/logo.png" alt=""> </figure> </div> <div class="buttonPage"> <div id="contratame" onclick="displayFormContact('block')">CONTRATAME</div> <a href="docs/cv-alexis-2017.pdf" target="_blank">DESCARGAR CV</a> </div> </section> <section class="slide" id="aboutme" style="display:none"></section> <section class="slide" id="skills" style="display:none"></section> <section class="slide" id="portafolio" style="display:none"></section> <section class="slide" id="blog" style="display:none"></section> </div> <div id="contactForm"> <form action="contac.php" id="form1" name="form1" method="post"> <div id="closeForm" onclick="displayFormContact('none')"></div> <figure id="logoMensaje"><img src="icons/icon-17.png" alt=""></figure> <p>Dí Hola</p> <input id="name" type="text" name="name" placeholder="Tu Nombre"> <input id="email" type="text" name="email" placeholder="Tu Email"> <textarea id="message" name="message" placeholder="Mesaje"></textarea> <input id="button" type="submit" name="submit" value="ENVIAR"> </form> </div> <div id="contactButton" onclick="displayFormContact('block')"></div> <footer> <div class="rrss"> <a href="https://www.facebook.com/alex.suarez.92372446" target="_blank"></a> <a href="https://www.instagram.com/?hl=es" target="_blank"></a> <a href="https://www.whatsapp.com/?l=es" target="_blank"></a> <a href="https://twitter.com/?lang=es" target="_blank"></a> </div> <p>© 2016 All rights reserved | Privacity Policy</p> </footer> <script src="js/particles.js"></script> <script src="js/app.js"></script> <script src="js/slider.js"></script> </body> </html>
import React from 'react'; import { beforeEach, describe, expect, it } from 'vitest'; import { render, screen } from '@testing-library/react'; import { BankItem } from '../src/components/ListBanks/BankItem'; describe('BankItem component', () => { const mockBank = { description: 'A modern bank for you', age: 2, url: 'https://image.com/like-bank', bankName: 'Fast Bank', }; beforeEach(() => { render(<BankItem bank={mockBank} />); }); it('Render the bank info', () => { expect(screen.getByText(mockBank.bankName)).toBeInTheDocument(); expect(screen.getByText(mockBank.description)).toBeInTheDocument(); expect( screen.getByText(`Antigüedad: ${mockBank.age} años`) ).toBeInTheDocument(); }); it('Render the bank image', () => { const imgElement = screen.getByRole('img'); expect(imgElement).toBeInTheDocument(); expect(imgElement).toHaveAttribute('src', mockBank.url); }); });
import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; Future<void> updateUsername(User user, String newUsername) async { try { String uid = user.uid; await FirebaseFirestore.instance .collection('users') .doc(uid) .update({'displayName': newUsername}); print('Username updated successfully.'); } catch (e) { print('Error updating username: $e'); } } Future<void> updatePassword(String newPassword) async { try { User? currentUser = FirebaseAuth.instance.currentUser; if (currentUser != null) { await currentUser.updatePassword(newPassword); print('Password updated successfully.'); } else { print('Error: No user is currently signed in.'); } } catch (e) { print('Error updating password: $e'); } } Future<String> updateAvatar(User user, String imagePath) async { try { User? currentUser = FirebaseAuth.instance.currentUser; String uid = user.uid; Reference storageReference = FirebaseStorage.instance.ref().child('avatars/$uid/avatar.jpg'); UploadTask uploadTask = storageReference.putFile(File(imagePath)); await uploadTask.whenComplete(() => null); await currentUser?.updatePhotoURL(imagePath); String newAvatarURL = await storageReference.getDownloadURL(); FirebaseFirestore.instance.collection('users').doc(uid).update({'avatarURL': newAvatarURL}); return newAvatarURL; } catch (e) { print('Error updating avatar: $e'); rethrow; } }
package models import ( "context" "database/sql" "log" "time" ) type DBModel struct { DB *sql.DB } func (m *DBModel) GetIn(id int) (*Income, error) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() query := `select id, tanggal_in, jumlah_in, catatan_in, created_date, updated_date from tblm_income where id = $1` row := m.DB.QueryRowContext(ctx, query, id) var income Income err := row.Scan( &income.ID, &income.TanggalIn, &income.JumlahIn, &income.CatatanIn, &income.CreatedDate, &income.UpdatedDate, ) if err != nil { return nil, err } return &income, nil } func (m *DBModel) AllIn() ([]*Income, error) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() query := `select id, tanggal_in, jumlah_in, catatan_in, created_date, updated_date from tblm_income order by tanggal_in desc` rows, err := m.DB.QueryContext(ctx, query) if err != nil { return nil, err } defer rows.Close() var income []*Income for rows.Next() { var income Income err := rows.Scan( &income.ID, &income.TanggalIn, &income.JumlahIn, &income.CatatanIn, &income.CreatedDate, &income.UpdatedDate, ) if err != nil { return nil, err } } return income, nil } func (m *DBModel) InsertIncome(income Income) error { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() stmt := `insert into tblm_income (tanggal_in, jumlah_in, catatan_in, created_date, updated_date) values ($1, $2, $3, $4, $5)` _, err := m.DB.ExecContext(ctx, stmt, income.TanggalIn, income.JumlahIn, income.CatatanIn, income.CreatedDate, income.UpdatedDate, ) if err != nil { log.Println(err) return err } return nil } func (m *DBModel) GetEx(id int) (*Expenses, error) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() query := `select id, tanggal_ex, jumlah_ex, catatan_ex, created_date, updated_date from tblm_expenses where id = $1` row := m.DB.QueryRowContext(ctx, query, id) var expenses Expenses err := row.Scan( &expenses.ID, &expenses.TanggalEx, &expenses.JumlahEx, &expenses.CatatanEx, &expenses.CreatedDate, &expenses.UpdatedDate, ) if err != nil { return nil, err } return &expenses, nil } func (m *DBModel) AllEx() ([]*Expenses, error) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() query := `select id, tanggal_ex, jumlah_ex, catatan_ex, created_date, updated_date from tblm_expenses order by tanggal_ex desc` rows, err := m.DB.QueryContext(ctx, query) if err != nil { return nil, err } defer rows.Close() var expenses []*Expenses for rows.Next() { var expenses Expenses err := rows.Scan( &expenses.ID, &expenses.TanggalEx, &expenses.JumlahEx, &expenses.CatatanEx, &expenses.CreatedDate, &expenses.UpdatedDate, ) if err != nil { return nil, err } } return expenses, nil } func (m *DBModel) InsertExpenses(expenses Expenses) error { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() stmt := `insert into tblm_expenses (tanggal_ex, jumlah_ex, catatan_ex, created_date, updated_date) values ($1, $2, $3, $4, $5)` _, err := m.DB.ExecContext(ctx, stmt, expenses.TanggalEx, expenses.JumlahEx, expenses.CatatanEx, expenses.CreatedDate, expenses.UpdatedDate, ) if err != nil { log.Println(err) return err } return nil }
import Navbar from "./navbar"; import { useState, useEffect } from "react"; // import { useNavigate } from "react-router-dom"; import "../styles/FileUpload.css"; import axios from "axios"; export const FileUpload = () => { // const navigate = useNavigate(); const baseUrl = process.env.REACT_APP_BASE_URL || `http://localhost:8080`; // const [uploadedFiles, setUploadedFiles] = useState([]); const [selectedFile, setSelectedFile] = useState(null); const [token, setToken] = useState(""); const [fileRecords, setFileRecords] = useState([]); useEffect(() => { const fetchFileRecords = async () => { try { // Retrieve item from local storage const storedItem = localStorage.getItem("token"); console.log(storedItem); if (storedItem) { const parsedToken = JSON.parse(storedItem); setToken(parsedToken); } // Fetch file records from the database const response = await axios.get(`${baseUrl}/file/get_all`, { headers: { Authorization: token, }, }); console.log("Fetched records:", response.data); setFileRecords(response.data.files); } catch (error) { console.error("Error fetching records:", error); } }; fetchFileRecords(); }, [baseUrl, token]); // const handleFileChange = (event) => { // const files = event.target.files; // setSelectedFile(files); // }; const handleFileChange = (event) => { console.log(event.target.files[0]); const file = event.target.files[0]; // Get the first selected file setSelectedFile(file); // Set the selected file in state }; const handleUpload = () => { if (!selectedFile) { console.error("No file selected for upload"); return; } const formData = new FormData(); if (selectedFile instanceof Blob) { // Append selectedFile directly to FormData formData.append("file", selectedFile); } else { console.error("Selected file is not a valid Blob object"); return; } axios .post(`${baseUrl}/file/upload`, formData, { headers: { Authorization: token, }, }) .then((response) => { console.log("Upload successful", response.data); // setUploadedFiles(selectedFile); setSelectedFile(); }) .catch((error) => { console.error("Upload failed", error); }); }; return ( <> <Navbar /> <div className="file-upload-container"> <h2>Upload Files</h2> {/* File selection input */} <input type="file" onChange={handleFileChange} /> {/* Upload button */} <button onClick={handleUpload} disabled={selectedFile == null}> Upload </button> {/* Display uploaded files */} {/* <div className="uploaded-files-container"> {uploadedFiles.map((file, index) => ( <div className="file-item" key={index}> <span>{file.name}</span> </div> ))} </div> */} {/* Display file records */} <div className="file-records-container"> <h2>File Records</h2> <ul> {fileRecords ? ( fileRecords.map((record) => ( <li key={record.id}> Name: {record.file_name}, Type: {record.file_type} </li> )) ) : ( <></> )} </ul> </div> </div> </> ); };
### 解题思路 1. 两种思路非常明确:O(NlogN) - **最大堆,有元素比堆顶小,替换并调整堆** - **partion 思想** 2. **漏洞百出,调试出了4处错误,这值得深思** - 当然需要总结模板了 - **边界控制问题, error3 error 4 ** - **error 1 2 其实书写代码习惯不好造成的**。 3. 快排思想的空间、时间复杂度分析: - **时间复杂度:期望为 O(n)** ,由于证明过程很繁琐,所以不再这里展开讲。具体证明可以参考《算法导论》第 9 章第 2 小节。 - **最坏情况下的时间复杂度为 O(n^2)**。情况最差时,每次的划分点都是最大值或最小值,一共需要划分 n - 1次,而一次划分需要线性的时间复杂度,所以最坏情况下时间复杂度为 O(n^2)。 - **空间复杂度:期望为 O(log n)**,**递归调用的期望深度为 O(log n),**每层需要的空间为 O(1),只有常数个变量。 - **最坏情况下的空间复杂度为 O(n)**。最坏情况下需要划分 n次,即 randomized_selected 函数递归调用最深 n - 1 层,而每层由于需要 O(1)的空间,所以一共需要 O(n)的空间复杂度。 4. 方法二:堆 空间、时间复杂度 - **时间复杂度:O(nlogk)**,其中 n是数组 arr 的长度。由于大根堆实时维护前 k小值,所以插入删除都是 O(logk) 的时间复杂度,最坏情况下数组里 n个数都会插入,所以一共需要 O(nlogk) 的时间复杂度。 - **空间复杂度:O(k)**,因为大根堆里最多 k个数 5. [Python标准库模块之heapq](https://www.jianshu.com/p/801318c77ab5) - 最大堆中父节点 是 最大值 --- 最小堆父节点 是 最小值;因此求前k个最小值: - 1) **应该采用 k个元素(arr[:k])的最大堆; ** - 2) **并遍历arr[k:] ,小于堆顶,交换。** - **heapq 只支持最小堆,因此把元素取负,就是”最大堆”** - heapq有两种方式创建堆: - 一种是使用一个空列表,然后使用**heapq.heappush()函数把值加入堆中** - 另外一种就是使用**heap.heapify(list)转换列表成为堆结构** - 堆创建好后,可以通过`heapq.heappop() 函数弹出堆中最小值 ### 代码 ```python3 class Solution: def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: # 最大堆,有元素比堆顶小,替换并调整堆 # partion 思想 nsize = len(arr) if nsize < k: return arr if nsize < 1 or k < 1: return [] self.qsort(arr, k, 0, nsize -1) return arr[:k] def qsort(self, arr, k, low, high): if low >= high: ## error 1: low <= high return mid = self.partion(arr, k, low, high) if mid < k: ## error 2: low < k; low >k 代码迁移导致 self.qsort(arr, k, mid+1, high) elif mid > k: self.qsort(arr, k, low, mid-1) else: return def partion(self, arr, k, low, high): par = arr[low] while low < high: while low < high and arr[high] >= par: ## error 3 : arr[high]>par 和 arr[low] < par 无等号,导致进入死循环 high -= 1 arr[low] = arr[high] while low < high and arr[low] <= par: low += 1 arr[high] = arr[low] ## error 4: low <= high,导致越界 arr[low] = par return low ``` ## heap 操作 ``` import heapq class Solution: def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: nsize = len(arr) if nsize < k: return arr if nsize < 1 or k < 1: return [] hq = [-x for x in arr[:k]] heapq.heapify(hq) for i in range(k, nsize): if -hq[0] > arr[i]: heapq.heappop(hq) heapq.heappush(hq, -arr[i]) ans = [-x for x in hq] return ans ```
import { PersonAddOutlined,PersonRemoveOutlined } from "@mui/icons-material"; import { Box, IconButton, Typography } from "@mui/material"; import { useDispatch,useSelector } from "react-redux"; import { setFriends } from "state"; import FlexBetween from "./flexBetween"; import UserImage from "./userImage"; import { useTheme } from "@emotion/react"; import { useNavigate } from "react-router-dom"; const Friend=({friendId,name,subtitle,userPicturePath})=>{ const { palette }=useTheme(); const dispatch=useDispatch(); const navigate=useNavigate(); const {_id}=useSelector((state)=>state.user); const token=useSelector((state)=>state.token); const friends=useSelector((state)=>state.user.friends); const primaryLight=palette.primary.light; const primaryDark=palette.primary.dark; const main=palette.neutral.main; const medium=palette.neutral.medium; const isFriend=friends.find((friend)=>friend._id===friendId); const patchFriend=async()=>{ // an api call to add or remove a friend const response=await fetch( `http://localhost:3001/users/${_id}/${friendId}`, { method:"PATCH", headers:{ Authorization:`Bearer ${token}`, "Content-Type":"application/json" } } ); const data=await response.json(); dispatch(setFriends({friends:data})); }; return ( <FlexBetween> <FlexBetween gap="1rem"> <UserImage image={userPicturePath} size="55px" /> <Box onClick={()=>{ navigate(`/profile/${friendId}`); // bug - when we go to a certain profile page and then try to go to a certain profile page the url does update with the react router but the components does not render navigate(0); // a not so recommended workaround for the above bug - it will go to the next users page and then refresh the page }} > <Typography color={main} variant="h5" fontWeight="500" sx={{ "&:hover":{ color:palette.primary.light, cursor:"pointer" } }} > {name} </Typography> <Typography color={medium} fontSize="0.75rem"> {subtitle} </Typography> </Box> </FlexBetween> {/* Friend Removal Button */} <IconButton onClick={()=>patchFriend()} sx={{backgroundColor:primaryLight,p:"0.6rem"}} > {isFriend?( <PersonRemoveOutlined sx={{color:primaryDark}}/> ):( <PersonAddOutlined sx={{color:primaryDark}}/> )} </IconButton> </FlexBetween> ); }; export default Friend;
import { useState } from "react" import { Button, Form } from 'react-bootstrap'; import { ErrorMessage, Field, Formik } from "formik"; import * as Yup from 'yup'; import axios from 'axios'; const SignIn = () => { const handleLogin = (values) => { const body = { email: values.mail, password: values.password } axios.post('http://challenge-react.alkemy.org/', body).then(response => { localStorage.setItem('token', response.data.token) }) } const startValues = { mail: "", password: "", } return ( <Formik initialValues={startValues} validationSchema={Yup.object().shape({ mail: Yup.string().required('Campo Requerido'), password: Yup.string().min(5, 'minimo 5 caracteres').max(8, 'maximo 8 caracteres').required('Campo Requerido'), })} onSubmit={(values) => { handleLogin(values) }} > {({ errors, handleSubmit }) => ( <Form onSubmit={handleSubmit}> <Form.Group className="mb-3" controlId="formBasicEmail"> <Form.Label>Email</Form.Label> <Field type="email" placeholder="Enter email" name="mail" /> <ErrorMessage name="mail" component={() => (<div class="alert alert-danger" role="alert">{errors.mail}</div>)} /> <Form.Text className="text-muted"> We'll never share your email with anyone else. </Form.Text> </Form.Group> <Form.Group className="mb-3" controlId="formBasicPassword"> <Form.Label>Password</Form.Label> <Field type="password" placeholder="Password" name="password" /> <ErrorMessage name="password" component={() => (<div class="alert alert-danger" role="alert">{errors.password}</div>)} /> </Form.Group> <Form.Group className="mb-3" controlId="formBasicCheckbox"> <Form.Check type="checkbox" label="Check me out" /> </Form.Group> <Button variant="primary" type="submit" > Log In </Button> </Form> )} </Formik> ) } export default SignIn;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>My Web Project</title> <link rel="stylesheet" href="styles.css" /> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous" ></script> </head> <body class="container"> <!-- Header Navbar --> <nav class="navbar navbar-expand-lg bg-body-tertiary"> <div class="container-fluid"> <a class="navbar-brand" href="#">FITTIP</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#" >Contact</a > </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#" >Service</a > </li> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#" >About US</a > </li> </ul> <form class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search" /> <button class="btn btn-outline-success" type="submit"> Search </button> </form> </div> </div> </nav> <!-- Hero Section --> <div id="carouselExampleAutoplaying" class="carousel slide" data-bs-ride="carousel" > <div class="carousel-inner"> <div class="carousel-item active"> <img src="./Image/1st.avif" class="d-block w-100" alt="..." /> <div class="carousel-caption d-none d-md-block"> <h5>First slide label</h5> <p>Some representative placeholder content for the first slide.</p> </div> </div> <div class="carousel-item"> <img src="./Image/2nd.avif" class="d-block w-100" alt="..." /> <div class="carousel-caption d-none d-md-block"> <h5>Second slide label</h5> <p>Some representative placeholder content for the first slide.</p> </div> </div> <div class="carousel-item"> <img src="./Image/3rd.avif" class="d-block w-100" alt="..." /> <div class="carousel-caption d-none d-md-block"> <h5>Third slide label</h5> <p>Some representative placeholder content for the first slide.</p> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="prev" > <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleAutoplaying" data-bs-slide="next" > <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <!-- Fitness Tips Section --> <div id="fitness-tips" class="fs-3"> <h2 >My Fitness Tip:-</h2> </div> <!-- Footer Section --> <footer class="d-flex flex-row justify-content-center"> <p class="m-2 ">&copy; 2023 My Fitness Tips. All rights reserved.</p> <ul class="d-flex felx-column "> <li class="m-2 fs-4"><a href="#">Privacy Policy</a></li> <li class="m-2 fs-4"><a href="#">Terms of Service</a></li> </ul> </footer> <script src="script.js"></script> </body> </html>
import 'package:firstfluttervscodeproj/size_config.dart'; import 'package:flutter/material.dart'; class DiscountBanner extends StatelessWidget { const DiscountBanner({ super.key, }); @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.symmetric(horizontal: getProportionateScreenWidth(20)), padding: EdgeInsets.symmetric( horizontal: getProportionateScreenWidth(20), vertical: getProportionateScreenWidth(8)), width: double.infinity, // height: 90, decoration: BoxDecoration( color: Colors.blue, borderRadius: BorderRadius.circular(15), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, // Align text to the left children: [ Text( "A Summer Surprise", style: TextStyle( fontSize: getProportionateScreenWidth(16), fontWeight: FontWeight.normal, color: Colors.white, ), ), Text( "Cashback 20%", style: TextStyle( fontSize: getProportionateScreenWidth(26), fontWeight: FontWeight.bold, color: Colors.white, ), ), // Add more Text widgets as needed ], ), ); } }
#pragma once #include <iostream> #include <string> #include <vector> #include <fstream> #include <queue> #include <ostream> #include <memory> //for std::shared_ptr //opencv #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d.hpp> #include <opencv2/imgproc/imgproc.hpp> #if 0 #include <opencv2/nonfree/features2d.hpp> #include <opencv2/nonfree/nonfree.hpp> #endif #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/Geometry> using namespace Eigen; #include <opencv2/core/eigen.hpp> // Camodocal #include "camodocal/camera_models/Camera.h" #include "camodocal/camera_models/CameraFactory.h" using namespace std; #include "GMSMatcher/gms_matcher.h" #include "ElapsedTime.h" #include "MiscUtils.h" #include "TermColor.h" #include "CameraGeometry.h" // this will hold numbers to indicate the performance. Specific for each type of matcher // TODO: ideal for inheritance structure class PointFeatureMatchingSummary { public: string feature_detector_type; // ORB, FAST, SURF etc string feature_descriptor_type; // ORB, SURF string matcher_type; // BFMatcher, FLANN int n_keypoints; // number of detected keypoints int n_descriptor_dimension; // the dimension of the descriptor int n_keypoints_pass_ratio_test; // number of points that pass the ratio test int n_keypoints_pass_f_test; //number of points that pass the fundamental matrix test int n_total_usable_features; // after eliminating features which dont pass the ratio test and the f-test, how many remain? // 0 : no printing // 1 : minimal // 2 : more // 5 : elaborate void prettyPrint( int debug_level ) { if( debug_level <= 0) return ; cout << TermColor::GREEN() << "PointFeatureMatchingSummary\n"; if( debug_level > 2 ) { cout << "\tfeature_detector_type: " << feature_detector_type << "\t"; cout << "\tfeature_descriptor_type: " << feature_descriptor_type << "\t"; cout << "\tmatcher_type: " << matcher_type << "\t"; cout << "\tn_descriptor_dimension: " << n_descriptor_dimension << "\t"; cout << endl; } cout << "\tn_keypoints: " << n_keypoints << "\t"; cout << "\tn_keypoints_pass_ratio_test: " << n_keypoints_pass_ratio_test << "\t"; cout << "\tn_keypoints_pass_f_test: " << n_keypoints_pass_f_test << "\t"; if( debug_level > 2 ) { cout << "\tn_total_usable_features: " << n_total_usable_features << "\t";} cout << TermColor::RESET() << endl; } }; class StaticPointFeatureMatching { public: static void gms_point_feature_matches( const cv::Mat& imleft_undistorted, const cv::Mat& imright_undistorted, MatrixXd& u, MatrixXd& ud, int n_orb_feat=5000 ); //< n_orb_feat has to be a few thousands atleast for spatial consistency checks. // This will down scale the input image, do the feature correspondences and then upscale the co-ordinates of // correspondences and return these. static void gms_point_feature_matches_scaled( const cv::Mat& imleft_undistorted, const cv::Mat& imright_undistorted, MatrixXd& u, MatrixXd& ud, float scale, int n_orb_feat=3000 ); // Given a match refines it. Use this with GMS matcher which usually gives quite dense matching but not as precise. // This does the following: // a. Sparify the matches // b. Do optical flow tracking using the matches as initial guess for LKOpticalFlow. This is done to improve precision of the point matches. // Params: // im_a, im_b : Input images (full resolution) // uv_a, uv_b : Coarse matching points 2xN or 3xN. Initial matches to be refined for those 2 images respectively. // refined_uv_a, refined_uv_b [output] : refined and sparsified points static void refine_and_sparsify_matches( const cv::Mat im_a, const cv::Mat im_b, const MatrixXd& uv_a, const MatrixXd& uv_b, MatrixXd& refined_uv_a, MatrixXd& refined_uv_b ); // u : 3xN. (x,y) or (colID,rowID) static void point_feature_matches( const cv::Mat& imleft_undistorted, const cv::Mat& imright_undistorted, MatrixXd&u, MatrixXd& ud, PointFeatureMatchingSummary& summary ); // Given the point feature matches and the 3d image (from disparity map) will return // the valid world points and corresponding points. // [Input] // uv: 2xN matrix of point-feature in image-a. In image co-ordinates (not normalized image cords) // _3dImage_uv : 3d image from disparity map of image-a. sizeof( _3dImage_uv) === WxHx3 // uv_d: 2xN matrix of point-feature in image-b. Note that uv<-->uv_d are correspondences so should of equal sizes // [Output] // feature_position_uv : a subset of uv but normalized_image_cordinates // feature_position_uv_d : a subset of uv_d. results in normalized_image_cordinates // world_point : 3d points of uv. // [Note] // feature_position_uv \subset uv. Selects points which have valid depths. // size of output is same for all 3 // world points are of uv and in co-ordinate system of camera center of uv (or image-a). static bool make_3d_2d_collection__using__pfmatches_and_disparity( std::shared_ptr<StereoGeometry> stereogeom, const MatrixXd& uv, const cv::Mat& _3dImage_uv, const MatrixXd& uv_d, std::vector<Eigen::Vector2d>& feature_position_uv, std::vector<Eigen::Vector2d>& feature_position_uv_d, std::vector<Eigen::Vector3d>& world_point ); // given pf-matches uv<-->ud_d and their _3dImages. returns the 3d point correspondences at points where it is valid // uv_X: the 3d points are in frame of ref of camera-uv // uvd_Y: these 3d points are in frame of ref of camera-uvd static bool make_3d_3d_collection__using__pfmatches_and_disparity( const MatrixXd& uv, const cv::Mat& _3dImage_uv, const MatrixXd& uv_d, const cv::Mat& _3dImage_uv_d, vector<Vector3d>& uv_X, vector<Vector3d>& uvd_Y ); // given pf-matches uv<-->ud_d and their depth images and camera, returns the 3d point correspondences at points where it is valid // uv_X: the 3d points are in frame of ref of camera-uv // uvd_Y: these 3d points are in frame of ref of camera-uvd // depth_image_uv, depth_image_uvd: assumes either CV_16uc1 or CV_32FC1, depth values expressed in millimeters. static bool make_3d_3d_collection__using__pfmatches_and_depthimage( camodocal::CameraPtr _camera, const MatrixXd& uv, const cv::Mat& depth_image_uv, const MatrixXd& uv_d, const cv::Mat& depth_image_uvd, // vector<Vector3d>& uv_X, vector<Vector3d>& uvd_Y MatrixXd& uv_X, MatrixXd& uvd_Y, vector<bool>& valids ); // Give as input the imaged co-ordinates to get these in normalized image co-ordinates. // Params: // camera [input]: The camodocal (general) camera // uv : The co-ordinates (x,y) 2xN or 3xN in imaged co-ordinates // normed_uv [output]: The resulting imaged co-ordinates (uv) to normalized. normed_uv := K.inverse() * [u_i;v_i;1] static bool image_coordinates_to_normalized_image_coordinates( const camodocal::CameraPtr camera, const MatrixXd& uv, MatrixXd& normed_uv ); static MatrixXd image_coordinates_to_normalized_image_coordinates( const camodocal::CameraPtr camera, const MatrixXd& uv ); // Give as input the normalized image co-ordinates and get the image co-ordinates // Params: // camera [input]: The camodocal (general) camera // normed_uv [input]: as a 3xN or 2xN matrix // uv [output] : The image co-ordinates static MatrixXd normalized_image_cordinates_to_image_coordinates( const camodocal::CameraPtr camera, const MatrixXd& normed_uv ); // Given image co-ordinates and the depth_image, will lookup the depth values at those image co-ordinates static VectorXd depth_at_image_coordinates( const MatrixXd& uv, const cv::Mat& depth_image ); static MatrixXd normalized_image_coordinates_and_depth_to_3dpoints( const MatrixXd& normed_uv, const VectorXd d, bool make_homogeneous ); private: // Give a set of knn=2 raw matches, eliminates matches based on Lowe's Ratio test. // Also returns the point features set. // Cite: Lowe, David G. "Distinctive image features from scale-invariant keypoints." International journal of computer vision 60.2 (2004): 91-110. static void lowe_ratio_test( const vector<cv::KeyPoint>& keypoints1, const vector<cv::KeyPoint>& keypoints2 , const std::vector< std::vector< cv::DMatch > >& matches_raw, vector<cv::Point2f>& pts_1, vector<cv::Point2f>& pts_2, float threshold=0.85 ); };
<script setup lang="ts"> import {onMounted, ref} from "vue"; import VectorSource from "ol/source/Vector"; import Map from "ol/Map"; import View from "ol/View"; import {GeoJSON} from "ol/format"; import {geojson} from "flatgeobuf"; import {VectorImage} from "ol/layer"; import TileLayer from "ol/layer/Tile.js"; import {XYZ} from "ol/source"; const mapRef = ref<HTMLElement>(); onMounted(async () => { if (mapRef.value) { const source = new VectorSource({ format: new GeoJSON(), loader: async function () { const response = await fetch('https://flatgeobuf.org/test/data/UScounties.fgb') // const response = await fetch('/public/test/data/UScounties.fgb') if (response.body) { for await (let json of geojson.deserialize(response.body)) { const feature = new GeoJSON().readFeature(json); if (feature) { const geometry = feature.getGeometry(); if (geometry) { geometry.transform('EPSG:4326', 'EPSG:3857'); source.addFeature(feature); } else { console.error('Feature has no geometry:', feature); } } else { console.error('Failed to create feature from GeoJSON:', json); } } } else { console.error('No response body received'); } } }) new Map({ target: mapRef.value, layers: [ new TileLayer({ source: new XYZ({ url: 'http://t4.tianditu.com/DataServer?T=vec_w&tk=a9bbec302f2213e1fe33e9775187d021&x={x}&y={y}&l={z}', }), zIndex: 0, }), new TileLayer({ source: new XYZ({ url: 'http://t4.tianditu.com/DataServer?T=cva_w&tk=81b9a9cf3e4be1df181e7bf54c5949fc&x={x}&y={y}&l={z}', }), zIndex: 1, }), new VectorImage({ source: source, }) ], view: new View({ center: [0, 0], zoom: 0, }), }); } }) </script> <template> <div id="ol-map" ref="mapRef"></div> </template> <style scoped> </style>
--- title: In 2024, Things You Should Know When Unlocking Total Wireless Of iPhone 13 Pro date: 2024-03-29 12:31:13 updated: 2024-04-01 12:49:10 tags: - unlock - remove screen lock categories: - ios - iphone description: This article describes Things You Should Know When Unlocking Total Wireless Of iPhone 13 Pro excerpt: This article describes Things You Should Know When Unlocking Total Wireless Of iPhone 13 Pro keywords: how to unlock iphone passcode without computer,forgot passcode iphone 6,disable parental control,change apple id email address,unlock disabled iphone without computer,forgot locked note password,unlock iphone without passcode thumbnail: https://www.lifewire.com/thmb/Qyfd5yWYmuBE75uyOeLeSQxzUMY=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/001_best-movies-on-hulu-right-now-5025149-3c80b5664f6541b4a0698333fc447251.jpg --- ## Things You Should Know When Unlocking Total Wireless Of Apple iPhone 13 Pro Total Wireless is a prominent name when it comes to affordable network carriers. It offers users a wide range of call and data packages. The company also offers smartphones; however, they are carrier-locked. This can become a problem for users who want to switch networks. Users need to learn unlocking methods that seek greater flexibility and control over their phones. In this article, we go through the essence of **unlocking a Total Wireless phone**. Our focus is to present a comprehensive overview of the methods and essential details required to unlock your device. It will enable users to make informed decisions and achieve the best possible results. ![unlock your total wireless phone](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-1.jpg) ## Part 1. Defining The Total Wireless Phone Terminology A [Total Wireless](https://www.totalbyverizon.com/) phone refers to a mobile device that operates on the Total Wireless network. It is a prepaid mobile virtual network operator (MVNO) that uses Verizon's network infrastructure. These phones are often sold with Total Wireless plans. Moreover, they are optimized to function within its network coverage area. Unlocking a Total Wireless phone can pose challenges due to the Apple iPhone 13 Pro device's association with a specific carrier. The difficulty level largely depends on factors such as the phone model, contract status, and carrier policies. **Unlock Total Wireless iPhone** is indeed feasible under specific conditions. Even so, the procedure might not follow a direct path and is subject to variation on various factors. Like its counterparts, Total Wireless presents distinct guidelines and eligibility criteria for phone unlocking. ![total wireless phone service](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-2.jpg) ## Part 2. Looking out the Reasons for Unlocking a Total Wireless Phone Understanding the details of unlocking a Total Wireless phone opens up many compelling reasons to pursue this task. It enables users to bypass limitations and enjoy the benefits of a more liberated mobile experience. Given below are some of the many reasons why you should go for **unlocking a Total Wireless phone**: 1. **Switching Carriers:** Total Wireless phones are often locked to their network, which limits users to their services. [Unlocking allows users to switch to other carriers](https://drfone.wondershare.com/sim-unlock/carrier-unlock-android-phone.html)for better plans, coverage, or services that suit their needs. 2. **International Travel:** On Total Wireless, international roaming options might be limited or expensive. Unlocking the phone enables the use of local SIM cards abroad. This offers more cost-effective communication options during travel. 3. **Network Compatibility:** Total Wireless phones don't work with other carriers due to specific network configurations. Unlocking enables these devices to work with a broader range of networks, enhancing usability. ### Advantages of Unlocking a Total Wireless Device Unlocking a Total Wireless phone opens up a lot of advantages. Here are a few of the benefits associated with **unlocking Total Wireless iPhone**: 1. **Flexibility**: The freedom to select among different carriers, plans, and services is offered by unlocked phones. It grants users increased flexibility in handling their communication requirements. 2. **Cost Savings:** Switching to more affordable or better-suited plans from different carriers can result in cost savings. This is especially true for users with specific usage patterns or travel requirements. 3. **Improved Resale Value:** Unlocked phones generally have higher demand in the resale market. It appeals to a wider range of buyers and potentially fetching better prices. ![looking into unlocking total wireless](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-3.jpg) ## Part 3. How To Check if Your Apple iPhone 13 Pro Is Already Unlocked? No need to worry if you're unsure whether your Total Wireless device is unlocked. You can easily verify its status through a simple SIM test. Here's a straightforward set of steps to check if your **iPhone Total Wireless unlock** is already unlocked: - **Step 1.** Turn off your device and remove the SIM tray to start. Swap the current SIM card for one from a different carrier and position it in the tray. Reinsert the tray into your device and power it on again. ![changing sim to check status](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-4.jpg) - **Step 2.** First, check to see if the SIM card is getting network service. Attempting a call or sending an SMS are alternative methods to test whether your phone is unlocked. If it fails, it suggests that your phone might still be locked to Total Wireless. ## Part 4. A Small Checklist to Ensure Before Unlocking Your Total Wireless Phone Prior to **Total Wireless unlock**, it's essential to verify that it meets the specified criteria. Ensure your phone aligns with the requirements by following the provided checklist: 1. **Check Contract Status:** Ensure your device is not bound by an ongoing contract with Total Wireless. If under contract, complete the contractual obligations, which include payment of fees or early termination charges. 2. **Verify Eligibility:** Confirm your device's eligibility for unlocking. Total Wireless requires your device to be at least completed 12 months of service period. Moreover, you need to ensure the Apple iPhone 13 Pro device isn't reported lost or stolen. 3. **Clear Outstanding Payments:** Make sure no outstanding payments or dues are associated with your Total Wireless account. These cover any installment plans or unpaid bills involving the Apple iPhone 13 Pro device. 4. **IMEI Compatibility:** [Check if your device's IMEI is compatible](https://drfone.wondershare.com/unlock/imei-blacklist-check.html)with unlocking services. Moreover, you need to ensure that it is not blacklisted. 5. **Backup Your Data:** Before initiating the unlocking process, [back up all your important data](https://drfone.wondershare.com/backup/android-backup-software.html). This includes contacts, photos, and files to prevent any potential loss during the process. 6. **Understand Terms and Conditions:** Familiarize yourself with the unlocking policies and terms Total Wireless provides. Ensure compliance with their guidelines to avoid complications during the unlocking process. ## Part 5. How To Unlock Total Wireless Phone: The Best Methods You are now armed with an inherent understanding of Total Wireless phones. We discussed the reasons for **unlocking a Total Wireless phone free** and its prerequisites. Below, the most common methods to unlock a Total Wireless phone are summarized. These will equip you completely to explore the most effective ways to unlock your device. ### Way 1. Accessing All Important Carriers Unlocking a phone to access various carriers involves understanding the unique policies of each carrier. Below are the differing policies of prominent carriers: #### [AT&T](https://www.att.com/deviceunlock) **Instructions.** Using a browser, open the att.com/deviceunlock website. Here, choose the “Start an unlock request" option and follow the on-screen prompts to complete the process. [AT&T will let you know about the unlock status](https://drfone.wondershare.com/sim-unlock/att-unlock.html) via the provided email. ![requesting at&t to unlock device](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-5.jpg) #### [T-Mobile](https://drfone.wondershare.com/iphone-unlock/total-wireless-unlock.html#:~:text=Unlock%20your%20device,-If%20you%20didn&text=Log%20into%20your%20T%2DMobile,a%20list%20of%20eligibility%20requirements.) **Instructions.** Access the T-Mobile website and navigate to the “Contact US" page. Here, choose a way to contact customer service and request device unlocking. If you meet the basic criteria set by T-Mobile, your device will be unlocked. ![requesting t mobile to unlock](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-6.jpg) #### [Verizon](https://www.verizon.com/business/support/equipment-devices-services/wireless-devices/unlock-device/) **Instructions.** [Verizon](https://drfone.wondershare.com/iphone-tips/activate-new-iphone-verizon.html) has established a minimum period of 60 days, after which your device will be unlocked. However, it is necessary that you don’t have any outstanding payments. Moreover, your device is not blacklisted is also an essential requirement. ![requesting verizon to unlock device](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-7.jpg) ### Way 2. Contact the Total Wireless Customer Service As explained before, Total Wireless requires you to use your device for at least 365 days before you can request device unlocking. Moreover, the Apple iPhone 13 Pro device should be white-listed and should not be reported missing or stolen. These are the simple instructions to **unlock Total Wireless phone free**: - **Step 1.** After ensuring you meet all the criteria, you can contact them by dialing 1-888-442-5102. This number is available throughout the week between 8 A.M and 11:45 P.M EST. Once you reach out, the department will request your IMEI number. - **Step 2.** Following that, they will advise you to wait a few days as they need this time to verify your request. They will contact you to unlock your device if you meet their requirements. It is an unlock code for Android devices, while iPhones can be unlocked remotely. ![contacting total wireless support](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-8.jpg) ### Way 3. Make the Urgency Fee Payment While the official Total Wireless device unlocking policy requires you to use the Apple iPhone 13 Pro device for at least a year, there are times when it might not be feasible. In such scenarios, you can pay an urgent fee to unlock the Apple iPhone 13 Pro device. Remember that even when paying an urgency fee, you need to have used the Apple iPhone 13 Pro device for at least 60 days. ### Way 4. Unlock Your Total Wireless Phone Using SafeUnlocks SafeUnlocks stands as the premier choice for unlocking your phone. It is committed to delivering unparalleled services, including speed, safety, and affordability. The aim of the superior quality is a guaranteed phone unlocking experience. It boasts a 99.9% success rate and can unlock any phone's brand without a hassle. Additionally, we specialize in unlocking devices from numerous carriers worldwide. Here's **how to unlock Total Wireless phone** using SafeUnlocks: - **Step 1**. Begin by accessing the official SafeUnlocks website. Click "Services" from the top toolbar and choose the "Carrier Unlock" option. Provide your name, email, device model, and IMEI number on the following screen. ![access carrier lock services](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-9.jpg) - **Step 2.** After ensuring you've marked the "I accept the $1 fee for signing up and unlocking my device" box, proceed by tapping "Proceed." Next, on the following screen, select a payment method and then follow the prompts displayed on the screen. ![provide details to unlocking phone](https://images.wondershare.com/drfone/article/2024/01/details-to-discuss-while-unlocking-total-wireless-phone-10.jpg) ## Bonus Tip. What To Do if Your Apple iPhone 13 Pro Is Locked? Use Wondershare Dr.Fone Should your Apple iPhone 13 Pro become locked because of forgotten passcodes or any other issues, there's no need to panic. [Wondershare Dr.Fone](https://tools.techidaily.com/wondershare/drfone/drfone-toolkit/), a dependable software tool, seeks to rescue the situation. It is a reputable software known for its utility. You can find options to resolve various iOS device-related problems, including unlocking iPhone screens. Dr.Fone effectively unlocks your iOS devices across various iOS versions, from iOS 7 to iOS 17. It covers various lock types, including touch lock screens, 4-digit/6-digit passcodes, numeric codes, and alphanumeric passcodes. Moreover, it can bypass Face ID, Touch ID, and Screen Time Passcode, among others. With Dr.Fone, you can unlock your iDevices within minutes. ### Key Characteristics of Wondershare Dr.Fone 1. This tool can effortlessly bypass the iCloud activation lock without needing the Apple ID. 2. You can find a dedicated option for Data Recovery in Dr.Fone's service, allowing you to easily recover all types of lost data. 3. It can remove encryption locks from iTunes backups without causing any data loss. ### Steps To Unlock Your Locked iPhone Using Wondershare Dr.Fone This tool ensures a straightforward process without any learning curve. Experience the simplicity of unlocking your Apple iPhone 13 Pro in just a few easy steps: - **Step 1. Initialization and Setup of Screen Unlocking** After installing Wondershare Dr.Fone on your computer, begin by launching the program. Access the "Toolbox" section and find "Screen Unlock". Choose "iOS" as your device type and proceed by selecting "Unlock iOS Screen ." Initiate the unlocking process by clicking "Start." ![start ios screen lock removal](https://images.wondershare.com/drfone/guide/unlock-ios-screen-2.png) _**Tips:** Are you searching for a powerful iPhone Unlock tool? No worries as [Dr.Fone](https://tools.techidaily.com/wondershare-dr-fone-unlock-android-screen/) is here to help you. Download it and start a seamless unlock experience!_ - **Step 2. Preparing Devices and Firmware** Follow the prompts on the screen to put your iDevice into Recovery Mode. The platform will automatically detect and showcase the “Device Model.” If necessary, modify the model or System Version accordingly and click “Start.” Monitor the progress of the iOS firmware download on the following screen. ![provide device details and proceed](https://images.wondershare.com/drfone/guide/unlock-ios-screen-4.png) - **Step 3. Validation and Completion** Ensure that the downloaded iOS firmware is validated before proceeding. To start the unlocking process, click "Unlock Now". Enter the required code and tap "Unlock" to continue. Upon successfully unlocking the Apple iPhone 13 Pro device, finalize the process by clicking the "Done" button. ![validate new ios firmware installation](https://images.wondershare.com/drfone/guide/unlock-ios-screen-9.png) ## Conclusion In this comprehensive guide, we navigated through **how to unlock Total Wireless phone**. It covered its definition, reasons for unlocking, and a checklist before initiating the process. We explored multiple unlocking methods, including carrier-specific policies and third-party services. Additionally, we discussed Wondershare Dr.Fone as the ultimate choice when users encounter device unlocking. ## How to Fix Apple iPhone 13 Pro Passcode not Working? Apple has always been one of the top successful companies. The reason for its success can be clearly seen through its efforts in pioneering top-notch products. It not only puts its efforts into ensuring the perfect working of the Apple iPhone 13 Pro device but also provides the user with essential security measures to protect the data of the Apple iPhone 13 Pro device from unauthorized access. This is the sole reason why Apple focuses so much on privacy through passcodes. But sometimes, these passcodes can be a hurdle in the working of the iPhone. If you're facing this issue, then you've come to the right place. This article shall cover your queries regarding fixing the Apple iPhone 13 Pro passcode that is not working and providing full-depth details for your ease. ## Part 1: Why iPhone is Saying Passcode is Wrong? If you enter the wrong password, your Apple iPhone 13 Pro will not accept it and won’t open your phone. If you repeatedly enter the wrong password, it will disable your phone mainly because of security reasons. However, sometimes you’re genuinely trying to enter the correct password, but your device won’t accept it. This isn't common, but there are quite a few reasons why iPhone is saying your passcode is wrong. Sometimes the problem is trivial, like you may have entered the wrong keys in a hurry, due to which it won't accept your passcode. In other cases, face recognition may not recognize your face if you're wearing any mask. However, occasionally the problem is technical. Sometimes, your Apple iPhone 13 Pro may be corrupted. This can cause trouble for your device to detect the security file where your passcode is stored. Other times, the operating system may not be installed properly after updating to the new version of iOS. ## Part 2: Remove iPhone Passcode with Dr.Fone Without Losing Data Everyone in the field of tech is familiar with Wondershare as it is the most innovative and versatile software in the market. Dr.Fone is a toolkit containing data recovery, phone manager software, etc., introduced by Wondershare. One of the many reasons for its success is the intuitive interface that has made it convenient for professionals as well as amateurs. When it comes to fixing your Apple iPhone 13 Pro passcode, which is not working, Wondershare Dr.Fone - [Screen Unlock](https://tools.techidaily.com/wondershare/drfone/iphone-unlock/) does wonders. iTunes is another great way to bypass the activation screen without a SIM card. If you’re new to this, here's a small guide on how to use iTunes to bypass the activation screen. ### [Dr.Fone - Screen Unlock (iOS)](https://tools.techidaily.com/wondershare/drfone/iphone-unlock/) Remove iPhone Passcode. - If you don’t have access to iTunes, Dr.Fone is a great alternative. - Compatible with all models of iPhone and other iOS devices. - It resets the factory settings without requiring the passcode. - It recovers data after resetting iPhone’s passcode. **3981454** people have downloaded it **Step 1: Connect Apple iPhone 13 Pro to your Computer** The first step is to connect your Apple iPhone 13 Pro to your computer via cable and install Wondershare Dr.Fone - Screen Unlock. ![download and open dr.fone](https://images.wondershare.com/drfone/guide/drfone-home.png) **Step 2: Screen Unlock Tool** Select the "Screen Unlock" tool from the given tools on the home interface. Another interface will be displayed on the screen in which you've to select "Unlock iOS Screen." ![select unlock apple id option](https://images.wondershare.com/drfone/guide/android-screen-unlock-2.png) **Step 3: DFU Mode** Before directly unlocking the Apple iPhone 13 Pro lock screen, you've to set it up in either Recovery mode or DFU mode. Mostly ‘Recovery Mode’ is recommended as it removes the passcode by default. However, if your device fails to activate it, you can opt for DFU mode. ![set your iphone in dfu mode](https://images.wondershare.com/drfone/guide/unlock-ios-screen-3.png) **Step 4: Download Firmware** Once your Apple iPhone 13 Pro is in DFU mode, another window will be displayed on the screen, asking for confirmation regarding the Apple iPhone 13 Pro device Model and System Version. Now click on the "Download" button placed at the bottom. ![download iphone firmware](https://images.wondershare.com/drfone/guide/unlock-ios-screen-4.png) **Step 5: Unlock your Apple iPhone 13 Pro.** After downloading the firmware, select “Unlock Now” to unlock your Apple iPhone 13 Pro. ![unlock iphone passcode successfully ](https://images.wondershare.com/drfone/guide/unlock-ios-screen-6.png) ## Part 3: Effective Ways to Fix iPhone Password Not Working This part shall assert its focus on the effective ways of resolving the issue involving the Apple iPhone 13 Pro password not working on your device. It revolves around the methods involving iTunes, iCloud, and iPhone Recovery Mode. ### 3.1 By using iTunes and iPhone Cables iTunes is one of the most used and innovational software pioneered by Apple. It has proved to be the best software out there through its versatility and exceptional performance. This software is your savior if you’re looking for something to organize your files in iPhone as it has great integration with iOS. If you want to fix your Apple iPhone 13 Pro passcode, which is not working, then iTunes can be an efficacious solution for your problem. Below we have explained step-by-step how to fix your passcode in iPhone using iTunes: **Step 1: Connect to Computer** The first step is to connect your Apple iPhone 13 Pro to the computer with which you've synced previously. **Step 2: Recovery Mode and Synchronize** Now open iTunes. If it asks for a passcode, try another computer that you've synced your device with. Else, put your phone to Recovery mode. Wait for iTunes to detect and sync your device. It will then create a backup. **Step 4: Restore** Once your device is synced with iTunes, a "Set Up" window will pop up on the screen displaying two options, "Restore" or "Update." Select "Restore" to proceed further. ![restore iphone with itunes](https://images.wondershare.com/drfone/article/2021/06/iphone-passcode-not-working-1.jpg) **Step 5: Reset Passcode** Select your device and the appropriate backup for your device in iTunes. Once the process is completed, you can reset the passcode of your Apple iPhone 13 Pro in the settings. ![restore backup in itunes](https://images.wondershare.com/drfone/article/2021/06/iphone-passcode-not-working-2.jpg) ### 3.2 Apple iCloud Feature iCloud is a multifunctional drive compatible with iOS and macOS. It saves your data, your media and organizes your files in folders. Moreover, it allows the user to share media, data, files, and even location with the other iPhone/iOS user. The major feature of Apple iCloud is its ‘Backup’ which stores all your data in case you lose or damage your phone. To fix the Apple iPhone 13 Pro passcode, which is not working, iCloud can come in handy. But this method can only work if you've logged in to your iCloud account on your Apple iPhone 13 Pro and your "Find My iPhone" application is turned on. All you have to do is erase your data which will automatically erase your passcode through iCloud. **Step 1: Sign in with Apple ID** First, open iCloud.com on another iOS and write your credentials to sign in your Apple ID. **Step 2: Select your Device** Click on "Find My iPhone" and select "All devices," and a list of devices will come up which are working under the same Apple ID. Select your Apple iPhone 13 Pro. ![select iphone on icloud](https://images.wondershare.com/drfone/article/2021/06/iphone-passcode-not-working-3.jpg) **Step 3: Erase Data and Set up your Apple iPhone 13 Pro.** Now click on the option of “Erase iPhone” to erase all your data and even your passcode. You have the autonomy to set up your Apple iPhone 13 Pro from a previous backup or set it up as a new device. ![erase iphone from icloud](https://images.wondershare.com/drfone/article/2021/06/iphone-passcode-not-working-4.jpg) ### 3.3 Using iPhone Recovery Mode If you’ve never synced your Apple iPhone 13 Pro with iTunes or set up “Find my iPhone” and you’re out of options, then iPhone Recovery Mode can come to the rescue. Recovery Mode allows your Apple iPhone 13 Pro to connect with iTunes without restarting the system. This process is quite time-consuming and different for different versions of the iPhone. Here we will guide you on how to fix the Apple iPhone 13 Pro passcode via Recovery Mode. **Step 1: Connect your device to the Computer** Connect your Apple iPhone 13 Pro to your computer and open iTunes. **Step 2: Activate Recovery Mode** Once the computer detects your Apple iPhone 13 Pro, it force restarts it. Activating Recovery Mode is different for different models of iPhone. - For iPhone 6s and earlier versions: Press and hold the Home Button and the Power Button simultaneously. - For iPhone 7 and 7 Plus: Press and hold the Power Button and Volume Down Button simultaneously. - For iPhone 8 and latest versions: Press and release the Volume Down button instantly. Then again, press and release the Volume up button. Now press the Power Button till you see the option of "Recovery Mode." **Step 3: Restore your Apple iPhone 13 Pro.** When you’re given the option of Restore or Update, choose ‘Restore.' iTunes will automatically download the appropriate software. ![restore iphone successfully from itunes](https://images.wondershare.com/drfone/article/2021/06/iphone-passcode-not-working-5.jpg) **Step 4: Set Up your Apple iPhone 13 Pro** Once the process has reached completion, set up your Apple iPhone 13 Pro, if this process takes more than 15 minutes, it will leave the Recovery Mode automatically and repeat the steps again. ### Conclusion This article has provided you the reasons and best possible ways to fix the issue of the Apple iPhone 13 Pro passcode not working in detail. You must follow these steps immediately if you've locked your Apple iPhone 13 Pro to avoid further trouble and anxiety. We hope we have covered every bit of this article perfectly and you have successfully unlocked your Apple iPhone 13 Pro without any hassle. ## How to Turn Off Find My Apple iPhone 13 Pro when Phone is Broken? In today’s world, your phone is your most important asset. Especially when you own an iPhone, you’re much more careful because it is pretty expensive than normal phones. You're always making sure to keep it safe and secure, but Apple has ways to keep you away from this hassle. Apple ensures the privacy and security of its customers. For that, it has introduced this excellent feature of Find My iPhone, which keeps track of the location of your device no matter in which part of the world you are. So, if you've lost your Apple iPhone 13 Pro or it is stolen, this app is your savior. Downloading and enabling Find My iPhone can be really easy and cinch but turning it off can be an arduous task. But we have you covered through this article that shall tell you about this app in detail and guide you on how to turn off Find My iPhone even when your Apple iPhone 13 Pro is broken. ## Part 1: What is Find My iPhone? Find My iPhone is an application forged by Apple that keeps track of your Apple iPhone 13 Pro's location protects your data. Once you enable this application, it requires your iCloud password to unlock your phone to keep your Apple iPhone 13 Pro safe from the wrong hands. This application comes in handy when you accidentally lose or misplace your phone. The best part about this application is that it is free of cost. It usually comes built-in your Apple iPhone 13 Pro already, but if not, you can easily download it from the app store. Sign in with your Apple ID, and it will automatically locate your Apple iPhone 13 Pro no matter where you go. ## Part 2: Efficient Way of Turning Off Find My iPhone Within Second- Dr. Fone [Dr.Fone - Screen Unlock](https://tools.techidaily.com/wondershare/drfone/iphone-unlock/) is an excellent data recovery and management software created by Wondershare. However, limiting it to just recovery and management of data will not be just as it offers much more than just that. Transferring files, repairing the operating system, changing the GPS location, and fixing the activation lock are its amazing services. ### [Dr.Fone - Screen Unlock (iOS)](https://tools.techidaily.com/wondershare/drfone/iphone-unlock/) Turning Off Find My iPhone Within Second. - Maintains the security of your data and keeps it in its original form. - Recovers your data from damaged or broken devices. - Erase’s data in such a way that no other software can recover it. - Has great integration with iOS and macOS. **3981454** people have downloaded it Dr.Fone can also be a great solution for how to turn off Find My iPhone when your Apple iPhone 13 Pro is broken. **Step 1: Install Dr. Fone** Launch Wondershare Dr.Fone on your computer and connect your Apple iPhone 13 Pro with it via cable. **Step 2: Unlock Apple ID** Open Wondershare Dr.Fone and select “Screen Unlock” among the other options on the home interface. Now another interface will appear displaying four options. Click on "Unlock Apple ID." ![select unlock apple id option](https://images.wondershare.com/drfone/guide/android-screen-unlock-2.png) **Step 3: Remove Active Lock** After choosing the “Unlock Apple ID” option, an interface will be displayed that will show another two options, out of which you have to select “Remove Active Lock” to proceed further. ![tap on remove activation lock](https://images.wondershare.com/drfone/drfone/remove-activation-lock-1.jpg) **Step 4: Jailbreak your Apple iPhone 13 Pro** Jailbreak your Apple iPhone 13 Pro by following the instructions given by the system. Once you complete them, click on "Finish Jailbreak." ![jailbreak your device](https://images.wondershare.com/drfone/drfone/remove-activation-lock-2.jpg) **Step 5: Confirmation Window** A warning will be displayed on the screen asking for confirmation to remove the active lock. Then again, another confirmation message will pop up confirming the model of your device. ![confirm the agreement](https://images.wondershare.com/drfone/drfone/remove-activation-lock-3.jpg) **Step 6: Unlock your Apple iPhone 13 Pro** Click on “Start Unlock” to proceed. Once the process is started, you have to wait for a moment until the activation lock is successfully removed. ![start the unlock process](https://images.wondershare.com/drfone/drfone/remove-activation-lock-4.jpg) **Step 7: Turn off Find My iPhone** As your activation lock is removed, go to the settings and remove your Apple ID. Consequently, Find My iPhone will be disabled. ![activation lock removed](https://images.wondershare.com/drfone/guide/bypass-activation-lock-9.png) ## Part 3: How to Turn Off Find My iPhone on Broken iPhone Using iCloud? iCloud is the most secure storage drive introduced by Apple. It keeps your gallery, your reminders, contacts, and your messages up to date. Moreover, it also organizes and stores your files while keeping them private and secure. iCloud strongly integrates your Apple iPhone 13 Pro with other iOS devices so you can share your data, documents, and location with other iCloud users. As mentioned earlier, turning off Find My iPhone can be very complex. But if your Apple iPhone 13 Pro is damaged in some way, turning it off can be much more stressful. Here, iCloud can come to the rescue as it’s the most effective solution for how to turn off Find My iPhone when your phone is broken. Here we have explained to you step by step how to turn off Find My iPhone on broken iPhone using iCloud: **Step 1:** Go to the official website of iCloud.com and enter your credentials to sign in with your Apple ID. **Step 2:** Click on the "Find My iPhone" icon at the end of the page. The app will start locating your device, but as your Apple iPhone 13 Pro is damaged, it might not find anything. ![select the option of find my iphone](https://images.wondershare.com/drfone/article/2021/06/turn-off-find-my-iphone-1.jpg) **Step 3:** Click on the "All Devices" option from the top. Select your Apple iPhone 13 Pro, which you want to remove by clicking on "Remove from account." ![select your device](https://images.wondershare.com/drfone/article/2021/06/turn-off-find-my-iphone-2.jpg) **Step 4:** Once your device is removed from the account, a window will pop up asking you to delete the option of that device from your iCloud account. Now you may log in Find My iPhone with your iCloud account on another device. ![confirm removal](https://images.wondershare.com/drfone/article/2021/06/turn-off-find-my-iphone-3.jpg) ## Part 4: Turn off Find My iPhone using Recovery Mode The recovery model of the Apple iPhone 13 Pro allows you to reset or restore your data. It also offers data cleaning and backing up of apps to keep your Apple iPhone 13 Pro updated and free of glitches. When your phone is lagging or not working properly, then you need to put it into Recovery Mode. However, Recovery Mode can also be useful to turn off Find My iPhone on your device. Here are the steps that will guide you on how to turn off Find My iPhone on a broken phone using Recovery Mode. **Step 1:** Connect your Apple iPhone 13 Pro to your computer via cable and wait for your computer to detect your device. **Step 2:** As soon as your Apple iPhone 13 Pro is detected, open iTunes and force restart your phone to activate the Recovery Mode. Activating this mode is different for different models of iPhone. - For iPhone 8 and the later: Press the Volume Down button and release is immediately. Then press the Volume Up button and release it immediately again. After that, press and hold the Power Button until you see the Apple logo. - For iPhone 7 and 7+: Press the Power Button and Volume Down button at the same time and hold them until the Apple logo appears on your screen. - For iPhone 6s, and Previous Models: Press and hold the Home Button and Power button concurrently until your Apple iPhone 13 Pro shows the Apple logo. Once your Apple iPhone 13 Pro shows the Apple logo, it means the Recovery Mode is activated. ![wait for apple logo to appear](https://images.wondershare.com/drfone/article/2021/06/turn-off-find-my-iphone-4.jpg) **Step 3:** Now click on “Restore” so iTunes can download software on your Apple iPhone 13 Pro. Once the process is completed, you can set up your Apple iPhone 13 Pro as new. This means your previous data will be erased, and Find My iPhone will be disabled automatically. ![tap on restore option](https://images.wondershare.com/drfone/article/2021/06/turn-off-find-my-iphone-5.jpg) ### Conclusion Now we’re done as we’ve provided you the best possible solutions to turn off Find My iPhone when your Apple iPhone 13 Pro is broken. It is obvious that it is a quite complicated process, but you have to be patient and follow the steps correctly to disable Find My Apple iPhone 13 Pro to avoid any inconvenience in the future. We hope this article answers all your queries regarding it. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins>
import styled from "styled-components"; import profileImage from "../assets/images/profile.jpg"; import { NavLink } from "react-router-dom"; const ProfileWrapper = styled.div` display: flex; align-items: center; height: 57px; margin-left: 8px; overflow: hidden; > * { flex: 0 0 auto; } `; const ProfileImage = styled.img` margin-right: 8px; border-radius: 5px; `; const ProfileName = styled.span` font-size: 14px; font-weight: 700; cursor: default; `; const SlideDown = styled.div<{ $subMenuIsOpen: boolean }>` max-height: ${(props) => (props.$subMenuIsOpen ? "120px" : "30px")}; overflow: hidden; transition: max-height 0.1s ease-in-out; `; const AsideItem = styled(NavLink)` display: flex; align-items: center; width: 100%; height: 30px; padding: 4px 7px; overflow: hidden; cursor: pointer; &:hover { border-radius: 3px; background-color: #ffb8b8; } &.active { border-radius: 3px; background-color: #ffb8b8; > span { color: #37352f; } } > * { flex: 0 0 auto; } > svg { margin: 3px; } > span { color: #707070; font-size: 14px; } `; const SubAsideItem = styled(AsideItem)` &:hover { border-radius: 3px; background-color: rgba(255, 184, 184, 0.4) !important; } &.active { background: none; } `; const SubMenuButton = styled.div<{ $subMenuIsOpen: boolean }>` display: flex; padding: 3px; &:hover { border-radius: 3px; background-color: rgba(0, 0, 0, 0.1); } > svg { transform: rotateZ(${(props) => (props.$subMenuIsOpen ? 90 : 0)}deg); transition: transform 0.25s ease-in-out; } `; const SubMenuWrapper = styled.div` display: flex; flex-direction: column; > a { padding-left: 35px; } `; const Dot = styled.div` width: 5px; height: 5px; margin-right: 5px; border-radius: 2.5px; background-color: #707070; `; interface IAsideMenuProp { scrollbarsRef: any; educationRef: any; certificateRef: any; awardsRef: any; subMenuIsOpen: boolean; toggleSubMenu: () => void; scrollTop: number; } function AsideMenu({ scrollbarsRef, educationRef, certificateRef, awardsRef, subMenuIsOpen, toggleSubMenu, scrollTop, }: IAsideMenuProp) { return ( <> <ProfileWrapper> <ProfileImage src={profileImage} alt="profile" width={30} /> <ProfileName>mijin Portfolio</ProfileName> </ProfileWrapper> <SlideDown $subMenuIsOpen={subMenuIsOpen}> <AsideItem to="/info" onClick={() => scrollbarsRef?.current?.scrollTop(0)}> <SubMenuButton onClick={toggleSubMenu} $subMenuIsOpen={subMenuIsOpen}> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9 6L15 12L9 18" stroke="#707070" strokeWidth="2" strokeLinecap="round" /> </svg> </SubMenuButton> <span>🐯 백미진</span> </AsideItem> <SubMenuWrapper> <SubAsideItem to="/info" onClick={() => setTimeout(() => educationRef?.current?.scrollIntoView({ behavior: "smooth" }), 100) } style={({ isActive }) => { if ( isActive && scrollTop >= educationRef?.current?.offsetTop - 200 && scrollTop < certificateRef?.current?.offsetTop - 200 ) { return { backgroundColor: "rgba(255, 184, 184, 0.4)" }; } }} > <Dot /> <span>👩‍🎓 Education</span> </SubAsideItem> <SubAsideItem to="/info" onClick={() => setTimeout(() => certificateRef?.current?.scrollIntoView({ behavior: "smooth" }), 100) } style={({ isActive }) => { if ( isActive && scrollTop >= certificateRef?.current?.offsetTop - 200 && scrollTop < awardsRef?.current?.offsetTop - 200 ) { return { backgroundColor: "rgba(255, 184, 184, 0.4)" }; } }} > <Dot /> <span>📚 Certificate</span> </SubAsideItem> <SubAsideItem to="/info" onClick={() => setTimeout(() => awardsRef?.current?.scrollIntoView({ behavior: "smooth" }), 100) } style={({ isActive }) => { if (isActive && scrollTop >= awardsRef?.current?.offsetTop - 200) { return { backgroundColor: "rgba(255, 184, 184, 0.4)" }; } }} > <Dot /> <span>🏆 Awards</span> </SubAsideItem> </SubMenuWrapper> </SlideDown> <AsideItem to="/skills" onClick={() => scrollbarsRef?.current?.scrollTop(0)}> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9 6L15 12L9 18" stroke="#707070" strokeWidth="2" strokeLinecap="round" /> </svg> <span>🎨 SKILLS</span> </AsideItem> <AsideItem to="/project" onClick={() => scrollbarsRef?.current?.scrollTop(0)}> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9 6L15 12L9 18" stroke="#707070" strokeWidth="2" strokeLinecap="round" /> </svg> <span>🖼️ PROJECT</span> </AsideItem> <AsideItem to="/activity" onClick={() => scrollbarsRef?.current?.scrollTop(0)}> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M9 6L15 12L9 18" stroke="#707070" strokeWidth="2" strokeLinecap="round" /> </svg> <span>👩‍🎨 ACTIVITY</span> </AsideItem> </> ); } export default AsideMenu;
import { useEffect, useState } from 'react' import { useDispatch, useSelector } from 'react-redux' import { AccountCircle, Logout } from '@mui/icons-material' import Image from 'next/image' import Link from 'next/link' import { headerTabs } from '../../utils/Utils' import styles from './header.module.scss' import CommonButton from '../common/button/CommonButton' import AuthPopup from '../auth' import { handleLoginPopup, setUserData } from '../../redux/features/userSlice' import { useRouter } from 'next/navigation' export default function Header() { const { currentUser } = useSelector((state) => state.user) const dispatch = useDispatch() const router = useRouter() const headerTabs = [ { title: 'Home', link: '/' }, { title: 'About', link: '/about' }, { title: 'My Dashboard', link: '/institute/dashboard' }, { title: 'My Plan', link: '/pricing' }, ] const handleLogout = () => { localStorage.removeItem('current-user-data') } useEffect(() => { const userData = localStorage.getItem('currentUser') console.log() if (userData) { dispatch(setUserData(JSON.parse(userData).foundUser)) } }, []) return ( <div className={styles.headerContainer}> <div className={styles.headerWrapper}> <div className={styles.logo}> <Image src="/images/logo.png" alt="logo" width={200} height={50} /> </div> <div className={styles.options}> {headerTabs.map((tab, i) => { return ( <> {tab.title !== 'My Dashboard' ? ( <Link href={tab.link} key={i}> {tab.title} </Link> ) : ( <a href={``} key={i} target="blank"> {tab.title} </a> )} </> ) })} {currentUser ? ( <> <div className={styles.profile}> {currentUser?.dp ? ( <img src={currentUser.dp} alt="dp" /> ) : ( <AccountCircle /> )} <p>{currentUser?.ownerName}</p> </div> <Logout sx={{ cursor: 'pointer' }} onClick={handleLogout} /> </> ) : ( <Link href="/login"> <CommonButton text={'Login'} /> </Link> )} </div> </div> <AuthPopup /> </div> ) }
import * as TE from 'fp-ts/TaskEither'; import { SpotifyCode, SpotifyState, SpotifyTokenData, } from '../../../../utils/types'; import { getRedirect_uri } from '../../../../utils/utils'; import { pipe } from 'fp-ts/function'; import axios from 'axios'; import { AccessTokenFailure } from '../../../../utils/errors'; import { encryptString } from '../../../../services'; const REDIRECT_URI = getRedirect_uri(); export function getAccessToken([spotifyCode, spotifyState]: [ SpotifyCode, SpotifyState, ]): TE.TaskEither<Error, SpotifyTokenData> { const authOptions = { url: 'https://accounts.spotify.com/api/token', method: 'POST', params: { code: spotifyCode, redirect_uri: REDIRECT_URI, grant_type: 'authorization_code', }, headers: { Authorization: 'Basic ' + Buffer.from( process.env.SPOTIFY_CLIENT_ID + ':' + process.env.SPOTIFY_CLIENT_SECRET ).toString('base64'), }, }; return pipe( TE.tryCatch( () => axios(authOptions), () => new AccessTokenFailure() ), TE.chain((response) => response.status === 200 && response.data.access_token !== null ? TE.right({ accessToken: encryptString( response.data.access_token as string, process.env.ENCRYPTION_SECRET as string ), refreshToken: encryptString( response.data.refresh_token as string, process.env.ENCRYPTION_SECRET as string ), state: spotifyState, scope: response.data.scope, tokenExpiry: response.data.expires_in, tokenExpiryTime: new Date( Date.now() + response.data.expires_in * 1000 ), tokenType: response.data.token_type, }) : TE.left(new AccessTokenFailure()) ) ); }
using System.Diagnostics; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace SimpleApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.Use(async (context, next) => { var sw = Stopwatch.StartNew(); await next(); await context.Response.WriteAsync($"Lambda: elapsed {sw.ElapsedMilliseconds} ms<br>"); }); app.UseMiddleware<SimpleTimeMeasurer>(); app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
""" 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 示例 1: 输入: "babad" 输出: "bab" 注意: "aba" 也是一个有效答案。 示例 2: 输入: "cbbd" 输出: "bb" 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-palindromic-substring 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ class Solution: """ 维护一个二维数组dp,其中dp[i][j]表示字符串区间[i, j]是否为回文串,当i = j时,只有一个字符,肯定是回文串, 如果i = j + 1,说明是相邻字符,此时需要判断s[i]是否等于s[j],如果i和j不相邻,即i - j >= 2时,除了判断s[i]和s[j]相等之外,dp[j + 1][i - 1]若为真, 就是回文串 """ def longestPalindrome(self, s: str) -> str: size = len(s) if size < 2: return s dp = [[False] * size for _ in range(size)] for i in range(size): dp[i][i] = True max_len = 1 start = 0 for j in range(1, size): for i in range(0, j): if s[i] == s[j]: if j - i < 3: dp[i][j] = True else: dp[i][j] = dp[i + 1][j - 1] else: dp[i][j] = False if dp[i][j]: cur_len = j - i + 1 if cur_len > max_len: max_len = cur_len start = i return s[start:start + max_len]
package com.example.mareu.ui.reunion_list; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.mareu.R; import com.example.mareu.event.DeleteReunionEvent; import com.example.mareu.model.Reunion; import org.greenrobot.eventbus.EventBus; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class ReunionRecyclerViewAdapter extends RecyclerView.Adapter<ReunionRecyclerViewAdapter.ViewHolder> { private final List<Reunion> mReunions; public ReunionRecyclerViewAdapter(List<Reunion> reunions) { mReunions = reunions; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_reunion_item, null); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Reunion reunion =mReunions.get(position); holder.mReunionPlace.setText(doString(reunion.getPlace())); holder.mReunionTime.setText(doString(reunion.getStringTime())); holder.mReunionTopic.setText(doString(reunion.getTopic())); holder.mReunionParticipant.setText(doString(reunion.getParticipant())); holder.mDeleteButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EventBus.getDefault().post(new DeleteReunionEvent(reunion)); } }); } public String doString(Object object) { if (object == null) { return "no data"; } else { return object.toString(); } } @Override public int getItemCount() { return mReunions.size(); } public class ViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.item_list_delete_button) ImageButton mDeleteButton; @BindView(R.id.item_list_place) TextView mReunionPlace; @BindView(R.id.item_list_time) TextView mReunionTime; @BindView(R.id.item_list_topic) TextView mReunionTopic; @BindView(R.id.item_list_participant) TextView mReunionParticipant; public ViewHolder (View view) { super(view); ButterKnife.bind(this,view); } } }
import { Disclosure } from "@headlessui/react"; import Logout from "./Logout"; interface Props { onClick: (event: React.MouseEvent<HTMLAnchorElement>) => void; } export default function Header({ onClick }: Props) { return ( <Disclosure as="nav" className="bg-gray-800"> {({ open }) => ( <> <div className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8"> <div className="relative flex h-16"> <div className="flex flex-1 justify-center sm:items-stretch sm:justify-center"> <div className="flex flex-shrink-0 items-center"> <h1 id="headerTitle">EXPENSE TRACKER</h1> </div> </div> <div className="flex flex-shrink-0 items-right absolute inset-y-0 right-0 flex items-center pr-2 sm:static sm:inset-auto sm:ml-6 sm:pr-0"> <Logout onClick={onClick} /> </div> </div> </div> </> )} </Disclosure> ); }
import * as React from "react"; import { styled } from "@mui/material/styles"; import Table from "@mui/material/Table"; import TableBody from "@mui/material/TableBody"; import TableCell, { tableCellClasses } from "@mui/material/TableCell"; import TableContainer from "@mui/material/TableContainer"; import TableHead from "@mui/material/TableHead"; import TableRow from "@mui/material/TableRow"; import Paper from "@mui/material/Paper"; import { useProducts } from "../../contexts/ProductContext"; import "./Cart.css"; import { Delete } from "@mui/icons-material"; const StyledTableCell = styled(TableCell)(({ theme }) => ({ [`&.${tableCellClasses.head}`]: { backgroundColor: theme.palette.common.black, color: theme.palette.common.white, }, [`&.${tableCellClasses.body}`]: { fontSize: 14, }, })); const StyledTableRow = styled(TableRow)(({ theme }) => ({ "&:nth-of-type(odd)": { backgroundColor: theme.palette.action.hover, }, // hide last border "&:last-child td, &:last-child th": { border: 0, }, })); function createData(name, calories, fat, carbs, protein) { return { name, calories, fat, carbs, protein }; } const rows = [ createData("Frozen yoghurt", 159, 6.0, 24, 4.0), createData("Ice cream sandwich", 237, 9.0, 37, 4.3), createData("Eclair", 262, 16.0, 24, 6.0), createData("Cupcake", 305, 3.7, 67, 4.3), createData("Gingerbread", 356, 16.0, 49, 3.9), ]; export default function Cart() { const [count, setCount] = React.useState([]); const { cart, getCart, changeProductCart, deleteCartProducts } = useProducts(); React.useEffect(() => { getCart(); }); return ( <TableContainer className="favorWrap" component={Paper}> <Table aria-label="customized table"> <TableBody> {cart.products.map((row) => ( <StyledTableRow key={row.name}> <StyledTableCell component="th" scope="row"> <img src={row.item.picture} alt="" style={{ width: "20vw", height: "30vh" }} /> </StyledTableCell> <StyledTableCell align="right">{row.item.name}</StyledTableCell> <StyledTableCell align="right"> {row.item.description} </StyledTableCell> <StyledTableCell align="right">{row.item.price}</StyledTableCell> </StyledTableRow> ))} </TableBody> </Table> </TableContainer> ); }
<!DOCTYPE html> <meta charset="utf-8"> <body> <style> .countries { fill: none; stroke: rgb(5, 15, 1); stroke-linejoin: round; } .legendThreshold { font-size: 13px; font-family: sans-serif; } .caption { fill: rgb(20, 1, 1); text-anchor: start; font-weight: bold; } </style> <svg width="1000" height="600"></svg> <script src="https://d3js.org/d3.v4.min.js"></script> <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script> <script src="https://d3js.org/d3-geo-projection.v2.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3-legend/2.24.0/d3-legend.js"></script> <script> // The svg var svg = d3.select("svg"), width = +svg.attr("width"), height = +svg.attr("height"); // Map and projection var path = d3.geoPath(); var projection = d3.geoNaturalEarth() .scale(width / 2 / Math.PI) .translate([width / 2, height / 2]) var path = d3.geoPath() .projection(projection); // Data and color scale var data = d3.map(); var colorScheme = d3.schemeBlues[6]; colorScheme.unshift("#eee") var colorScale = d3.scaleThreshold() .domain([26, 51,76, 101, 151, 201]) .range(colorScheme); // Legend var g = svg.append("g") .attr("class", "legendThreshold") .attr("transform", "translate(50,200)"); g.append("text") .attr("class", "caption") .attr("x", 0) .attr("y", -10) .text("SMOKING"); var g = svg.append("g") .attr("transform", "translate(350,50)"); g.append("text") .attr("class", "caption") .attr("x", 5) .attr("y", -10) .text("2018 Death Rate From Smoking per 100,000 people"); var labels = ['0-25', '26-50', '51-75', '76-100', '101-150', '151-200', '> 200']; var legend = d3.legendColor() .labels(function (d) { return labels[d.i]; }) .shapePadding(4) .scale(colorScale); svg.select(".legendThreshold") .call(legend); // Load external data and boot d3.queue() .defer(d3.json, "http://enjalot.github.io/wwsd/data/world/world-110m.geojson") .defer(d3.csv, "https://raw.githubusercontent.com/charles-peprah/data/master/d3static1.csv", function(d) { data.set(d.Code, +d.Deaths); }) .await(ready); function ready(error, topo) { if (error) throw error; // Draw the map svg.append("g") .attr("class", "countries") .selectAll("path") .data(topo.features) .enter().append("path") .attr("fill", function (d){ // Pull data for this country d.Deaths = data.get(d.id) || 0; // Set the color return colorScale(d.Deaths); }) .attr("d", path); } </script> </body>
import { IConsole } from "types/console"; import { IMirror } from "types/mirror"; import { ActionTypes } from "./actionTypes"; export interface IPayloadCartCreate { date_created: string; date_updated: string; id: number; user: number | null; } export interface IActionCartCreate { type: ActionTypes.CART_SET; payload: IPayloadCartCreate; } export interface IPayloadCartItem { cart: number; date_created: string; date_updated: string; id: number; product: IConsole | IMirror; quantity: number; } export interface IActionCartAddItem { type: ActionTypes.CART_ADD_ITEM; payload: IPayloadCartItem; } export interface IActionCartItemChange { type: ActionTypes.CART_ITEM_CHANGE; payload: IPayloadCartItem; } export interface IActionCartItemDecrement { type: ActionTypes.CART_ITEM_DECREMENT; payload: IPayloadCartItem; } export interface IActionCartItemIncrement { type: ActionTypes.CART_ITEM_INCREMENT; payload: IPayloadCartItem; } export interface IPayloadCartItemDelete { id: number; } export interface IActionCartItemDelete { type: ActionTypes.CART_ITEM_DELETE; payload: IPayloadCartItemDelete; } export interface IActionCartUserSet { type: ActionTypes.CART_USER_SET; payload: number; } export interface IActionCartClear { type: ActionTypes.CART_CLEAR; } export interface IFetchCartCreateProps { payload: number; type: string; } export interface IFetchCartAddItemPayload { cart: number; product: number; quantity: number; } export interface IFetchCartAddItemProps { payload: IFetchCartAddItemPayload; type: string; } export interface IFetchCartItemChangePayload { id: number; quantity: number; } export interface IFetchCartItemChangeProps { payload: IFetchCartItemChangePayload; type: string; } export interface IFetchCartItemIncrementPayload { id: number; quantity: number; } export interface IFetchCartItemIncrementProps { payload: IFetchCartItemIncrementPayload; type: string; } export interface IFetchCartItemDecrementPayload { id: number; quantity: number; } export interface IFetchCartItemDecrementProps { payload: IFetchCartItemDecrementPayload; type: string; } export interface IFetchCartItemDeletePayload { id: number; } export interface IFetchCartItemDeleteProps { payload: IFetchCartItemDeletePayload; type: string; } export interface ICartState { date_created: string; date_updated: string; entities: IPayloadCartItem[]; id: number; user: number; } export type CartActionsType = | IActionCartCreate | IActionCartAddItem | IActionCartItemChange | IActionCartItemDecrement | IActionCartItemIncrement | IActionCartItemDelete | IActionCartUserSet | IActionCartClear;
package com.TrX.Activities import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import com.TrX.databinding.ActivityLoginBinding import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class LoginActivity : AppCompatActivity() { private var binding:ActivityLoginBinding? = null lateinit var firebaseAuth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding?.root) firebaseAuth = Firebase.auth binding?.loginButton?.setOnClickListener { loginUser() } binding?.tvSignup?.setOnClickListener{ val intent = Intent(this, SignUpActivity::class.java) startActivity(intent) finish() } } private fun loginUser(){ val email:String = binding?.etEmail?.text.toString() val password:String = binding?.etPassword?.text.toString() if(email.isBlank() || password.isBlank()){ Toast.makeText(this, "Fields cannot be Blank", Toast.LENGTH_SHORT).show() return } firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener { if(it.isSuccessful){ Toast.makeText(this, "Logged in", Toast.LENGTH_SHORT).show() val intent = Intent(this, MainActivity::class.java) startActivity(intent) finish() } else{ Toast.makeText(this, "User does not exist", Toast.LENGTH_SHORT).show() } } } }
(function (global) { let formHandler = {}; /** * @abstract Clears form fields and hides empty errors. * * Only inputs and wrapped in an element with class name "form-field" are cleared */ function clearForm() { let inputs = document.querySelectorAll(".form-field"); for (let i = 0; i < inputs.length; i++) { for (let j = 0; j < inputs[i].children.length; j++) { if (inputs[i].children[j].tagName === "INPUT") { inputs[i].children[j].value = ""; hideEmptyError(inputs[i]); } } } } /** * @abstract Checks if fields are empty and shows or hides their respective empty errors * * Only inputs and wrapped in an element with class name "form-field" are checked */ function isFieldEmpty() { let inputs = document.querySelectorAll(".form-field"); let isEmpty = false; for (let i = 0; i < inputs.length; i++) { for (let j = 0; j < inputs[i].children.length; j++) { if (inputs[i].children[j].tagName === "INPUT") { if (inputs[i].children[j].value === "") { isEmpty = true; showEmptyError(inputs[i]); break; } hideEmptyError(inputs[i]); break; } } } return isEmpty; } /** *@abstract Finds child with "empty-error" class and makes it visible * Makes error visible by removing "hidden" class * * @param {HTMLElement} parent Parent element with the error as child */ function showEmptyError(parent) { for (let i = 0; i < parent.children.length; i++) { if (parent.children[i].classList.contains("empty-error")) { parent.children[i].classList.remove("hidden"); return; } } } /** * @abstract Finds child with empty-error class and makes it invisible * * Makes error invisible by adding "hidden" class * * @param {HTMLElement} parent Parent element with the error as child */ function hideEmptyError(parent) { for (let i = 0; i < parent.children.length; i++) { if (parent.children[i].classList.contains("empty-error")) parent.children[i].classList.add("hidden"); } } /** *@abstract Makes element visible * * @param {HTMLElement} element Element to be made visible */ function makeVisible(element) { element.classList.remove("hidden"); } /** *@abstract Makes element invisible * * @param {HTMLElement} element Element to be made invisible */ function makeInvisible(element) { element.classList.add("hidden"); } /** * @abstract Checks if email is valid and shows or hides error message * * Email input must have id "target-email" and email error id "" */ function isEmailValid() { if (document.querySelector("#target-email:invalid") != null) { makeVisible(document.querySelector("#email-error")); return false; } makeInvisible(document.querySelector("#email-error")); return true; } formHandler.isEmailValid = isEmailValid; formHandler.clearForm = clearForm; formHandler.isFieldEmpty = isFieldEmpty; formHandler.makeInvisible = makeInvisible; formHandler.makeVisible = makeVisible; global.$formHandler = formHandler; })(window);
package jwks_endpoint import ( "net/http" di "github.com/fluffy-bunny/fluffy-dozm-di" wellknown_echo "github.com/fluffy-bunny/fluffycore-rage-identity/pkg/wellknown/echo" fluffycore_contracts_jwtminter "github.com/fluffy-bunny/fluffycore/contracts/jwtminter" contracts_handler "github.com/fluffy-bunny/fluffycore/echo/contracts/handler" echo "github.com/labstack/echo/v4" ) type ( service struct { jwtMinter fluffycore_contracts_jwtminter.IJWTMinter } ) var stemService = (*service)(nil) func init() { var _ contracts_handler.IHandler = stemService } func (s *service) Ctor(jwtMinter fluffycore_contracts_jwtminter.IJWTMinter) (*service, error) { return &service{ jwtMinter: jwtMinter, }, nil } // AddScopedIHandler registers the *service as a singleton. func AddScopedIHandler(builder di.ContainerBuilder) { contracts_handler.AddScopedIHandleWithMetadata[*service](builder, stemService.Ctor, []contracts_handler.HTTPVERB{ contracts_handler.GET, }, wellknown_echo.WellKnownJWKS, ) } func (s *service) GetMiddleware() []echo.MiddlewareFunc { return []echo.MiddlewareFunc{} } // JWKS godoc // @Summary get the public keys of the servere. // @Description get the public keys of the server. // @Tags root // @Accept */* // @Produce json // @Success 200 {object} string // @Router /.well-known/jwks [get] func (s *service) Do(c echo.Context) error { ctx := c.Request().Context() publickKeys, err := s.jwtMinter.PublicKeys(ctx) if err != nil { return c.JSONPretty(http.StatusInternalServerError, err.Error(), " ") } return c.JSONPretty(http.StatusOK, publickKeys, " ") }
import React, { useState } from 'react' import './Restore.scss' import Checkbox from '@mui/material/Checkbox'; import Radio from '@mui/material/Radio'; import RadioGroup from '@mui/material/RadioGroup'; import FormControlLabel from '@mui/material/FormControlLabel'; import FormControl from '@mui/material/FormControl'; import FormLabel from '@mui/material/FormLabel'; import { MdOutlineClose } from "react-icons/md"; import Loading from '../../../components/Loading/Loading.jsx' //domain import { useDomain } from '../../../components/DomainContext/DomainContext'; const Restore = ({ setRestorePage, restorePage }) => { // Domain const { domain } = useDomain(); const [checked1, setChecked1] = useState(false); const [checked2, setChecked2] = useState(false); const [radioValue, setRadioValue] = useState('option-1'); const myAuthority = localStorage.getItem('myAuthority'); const [loading, setLoading] = useState(false); const handleRadioChange = (e) => { setRadioValue(e.target.value); if (e.target.value === 'option-2') { setChecked1(true); setChecked2(true); } }; const handleCheckboxChange = (e, setChecked) => { if (radioValue !== 'option-2') { setChecked(e.target.checked); } }; const submitHandle2 = (e) => { e.preventDefault(); // 詢問 const isConfirmed = window.confirm(`您確定要送出嗎? ${checked1 === true ? '*清空地震資料' : ''} ${checked2 === true ? '*清空系統Log' : ''}`); if (!isConfirmed) { return; } // 發送 const resetHttp = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ eqLogReset: checked1, systemLogReset: checked2, modReset: radioValue, authority: myAuthority }) }; // 啟動 loading 畫面 setLoading(true); fetch(`http://${domain}:4000/system/reset`, resetHttp) .then(response => response.json()) .then(data => { console.log(data); // 關閉 loading 畫面並跳轉至首頁 setTimeout(() => { setLoading(false); window.location.href = '/'; }, 15000); // 15 秒後執行 }) .catch(err => { console.log(err); // 若有錯誤,關閉 loading 畫面 setLoading(false); }); } return ( <div style={{ display: `${restorePage === false ? 'none' : 'flex'}` }} className='restore-container'> <button onClick={() => setRestorePage(false)} className='restore-container-close-btn'><MdOutlineClose /></button> <div className='restore-wrapper-bg' onClick={() => setRestorePage(false)}></div> <div className='restore-wrapper'> <h2>系統還原選項</h2> {loading === true ? <Loading height={50} /> : null} <form id="form2" onSubmit={(e) => submitHandle2(e)} className='restore-form'> <p>選擇您要清除的內容 (可不勾選)</p> <article> <Checkbox type="checkbox" checked={checked1} onChange={(e) => handleCheckboxChange(e, setChecked1)} /> <p>清除地震資料</p> </article> <article> <Checkbox type="checkbox" checked={checked2} onChange={(e) => handleCheckboxChange(e, setChecked2)} /> <p>清除系統Log</p> </article> <p>請選擇重設的模式</p> <article className='select-restore-option-wrapper'> <FormControl> <FormLabel style={{ marginBottom: '10px' }}>機器還原設定選項 (進入初始化設定)</FormLabel> <RadioGroup value={radioValue} onChange={handleRadioChange} > <FormControlLabel value="option-1" control={<Radio />} label="(保留) 帳號設定 & 系統設定,只進行初始化設定" /> <FormControlLabel value="option-2" control={<Radio />} label="(不保留) 直接還原機器出場預設" /> </RadioGroup> </FormControl> </article> <div className='restore-btns-wrapper'> <button type="button" onClick={() => setRestorePage(false)}>取消</button> <button type="button" onClick={(e) => submitHandle2(e)}>確定</button> </div> </form> </div> </div > ) } export default Restore
import { FontAwesome, Ionicons } from '@expo/vector-icons'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import { useWalletConnect } from '@walletconnect/react-native-dapp'; import * as React from 'react'; import { Fragment } from 'react'; import Colors, { DefaultColor } from '../constants/Colors'; import useColorScheme from '../hooks/useColorScheme'; import { HomeScreen } from '../screens/Home'; import { TabParamList } from '../types'; import ChatNavigator from './ChatNavigator'; import HomeNavigator from './HomeNavigator'; import NotificationNavigator from './NotificationNavigator'; import ProfileNavigator from './ProfileNavigator'; const BottomTab = createBottomTabNavigator<TabParamList>(); export default function TabNavigator() { const colorScheme = useColorScheme(); const themeColor = colorScheme === 'light' ? DefaultColor.darken : DefaultColor.white; const connected = useWalletConnect().connected; return ( <BottomTab.Navigator initialRouteName={"Home"} screenOptions={{ tabBarActiveTintColor: DefaultColor.main, headerShown: false, tabBarShowLabel: false }}> <BottomTab.Screen name="Home" component={HomeNavigator} options={{ tabBarIcon: ({ color, focused }) => <TabBarIcon name="home" color={focused ? color : themeColor} />, }} /> {connected && <Fragment> <BottomTab.Screen name="Notification" component={NotificationNavigator} options={{ tabBarBadge: 10, tabBarIcon: ({ color, focused }) => <TabBarIcon name="notifications" color={focused ? color : themeColor} />, }} /> <BottomTab.Screen name="Chat" component={ChatNavigator} options={{ tabBarIcon: ({ color, focused }) => <TabBarIcon name="chatbox" color={focused ? color : themeColor} />, }} /> </Fragment> } <BottomTab.Screen name="Profile" component={ProfileNavigator} options={{ tabBarIcon: ({ color, focused }) => <TabBarIcon name="person" color={focused ? color : themeColor} />, }} /> </BottomTab.Navigator> ); } /** * You can explore the built-in icon families and icons on the web at https://icons.expo.fyi/ */ function TabBarIcon(props: { name: React.ComponentProps<typeof Ionicons>['name']; color: string; }) { return <Ionicons size={24} style={{ marginBottom: -3 }} {...props} />; }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libft.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jrasser <jrasser@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/02/21 15:22:00 by jrasser #+# #+# */ /* Updated: 2022/05/29 21:12:57 by jrasser ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef LIBFT_H # define LIBFT_H # include <stdlib.h> # include <unistd.h> # include <stdarg.h> # include <unistd.h> # include <stdlib.h> # include <stdio.h> # define PTR "0123456789abcdef" # define BUFFER_SIZE 100 typedef struct s_list { void *content; struct s_list *next; } t_list; /* LIBFT */ int ft_isalpha(int c); int ft_isdigit(int c); int ft_isalnum(int c); int ft_isascii(int c); int ft_isprint(int c); size_t ft_strlen(const char *s); void *ft_memset(void *b, int c, size_t len); void ft_bzero(void *s, size_t n); void *ft_memcpy(void *dst, const void *src, size_t n); void *ft_memmove(void *dst, const void *src, size_t len); size_t ft_strlcpy(char *dst, const char *src, size_t dstsize); size_t ft_strlcat(char *dst, const char *src, size_t dstsize); int ft_toupper(int c); int ft_tolower(int c); char *ft_strchr(const char *s, int c); char *ft_strrchr(const char *s, int c); int ft_strncmp(const char *s1, const char *s2, size_t n); void *ft_memchr(const void *s, int c, size_t n); int ft_memcmp(const void *s1, const void *s2, size_t n); char *ft_strnstr(const char *haystack, const char *needle, \ size_t len); int ft_atoi(const char *str); void *ft_calloc(size_t count, size_t size); char *ft_strdup(const char *s1); char *ft_substr(char const *s, unsigned int start, size_t len); char *ft_strjoin(char const *s1, char const *s2); char *ft_strtrim(char const *s1, char const *set); char **ft_split(char const *s, char c); char *ft_itoa(int n); char *ft_strmapi(char const *s, char (*f)(unsigned int, char)); void ft_striteri(char *s, void (*f)(unsigned int, char*)); void ft_putchar_fd(char c, int fd); void ft_putstr_fd(char *s, int fd); void ft_putendl_fd(char *s, int fd); void ft_putnbr_fd(int n, int fd); /* LISTE CHAIN */ void ft_lstadd_back(t_list **lst, t_list *new); void ft_lstadd_front(t_list **lst, t_list *new); void ft_lstclear(t_list **lst, void (*del)(void *)); void ft_lstdelone(t_list *lst, void (*del)(void *)); void ft_lstiter(t_list *lst, void (*f)(void *)); t_list *ft_lstlast(t_list *lst); t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *)); t_list *ft_lstnew(void *content); int ft_lstsize(t_list *lst); /* PRINTF */ int ft_printf(const char *str, ...); unsigned int ft_printf_char(va_list ptr); unsigned int ft_put_char(char c); char *ft_put_ptr(unsigned long long int nbr, char *base); char *ft_putunbr_base(unsigned int nbr, char *base); char *ft_uitoa(unsigned int n); char *ft_itoa_printf(int n); unsigned int ft_putstr(char *str, char c); char *ft_litoa(long int n); char *ctos(char c); char *ft_sub_char(char c, va_list ptr); unsigned int ft_putstrstr(char *str); unsigned int ft_putstr_minus_less(char *str, char c); char *ft_arg_multi(const char *str, int i); char *ft_arg_multi(const char *str, int i); int ft_dash_flag(const char *str, int i, va_list ptr, int *z); int ft_dot_flag(const char *str, int i, va_list ptr, int *z); int ft_zero_flag(const char *str, int i, va_list ptr, int *z); int ft_space_flag(const char *str, int i, va_list ptr, int *z); int ft_diese_flag(const char *str, int i, va_list ptr, int *z); int ft_plus_flag(const char *str, int i, va_list ptr, int *z); /* GET_NEXT_LINE */ int ft_read(int fd, char *buffer); char *ft_calloc_line(char *buffer, long size); char *ft_check_retour(int ret, char *buffer, char *line); char *ft_check_buffer_line(char *buffer); char *get_next_line(int fd); char *ft_strconcat(char *line, char *buffer); char *update_buffer(char *buffer); int ft_check_buffer_empty(char **buffer, int fd); int ft_is_buffer_end_line(char *buffer); #endif
import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core'; import { IntegrationEventHandlerService } from './services/integration-event-handler.service'; import { AccountRegistrationCorrelationIdStore } from './stores/account-registration-correlation-id.store'; @NgModule() export class CoreModule { constructor(@Optional() @SkipSelf() parentModule: CoreModule) { if (parentModule) { throw new Error('CoreModule is already loaded. Import it in the AppModule only.'); } } static forRoot(): ModuleWithProviders<CoreModule> { return { ngModule: CoreModule, providers: [AccountRegistrationCorrelationIdStore, IntegrationEventHandlerService] }; } }
/** * @level Private * @usage U1 */ // COPYRIGHT Dassault Systemes 2004 // // Services de nommage d'objets virtuels // // Sep. 04 Creation O.PERIOU #ifndef CATLinkableServicesForVO_H #define CATLinkableServicesForVO_H #include "CATOmbLnkVO.h" #include "CATBoolean.h" #include "CATBaseUnknown.h" class CATDocument; class CATIVOFactory; class sequence_octet; /** * Virual Objects naming services. * <b>Role</b>: Services for naming Virtual Objects .<br> */ class ExportedByCATOmbLnkVO CATLinkableServicesForVO { public: /** * Gets the naming context of the VO. * @param iVO * The virual object. * @param iFactory * The factory. * @param iInterfaceID * Interface to query on the naming context. * @return * the naming context of the VO.<br> */ static CATBaseUnknown* GetNamingContext (const CATBaseUnknown* iVO, CATIVOFactory* iFactory, CATIdent iInterfaceID); /** * Gets the identifier of the VO. * @param iVO * The virual object. * @param iFactory * The factory. * @param oIdentifier * The identifier of the VO. It is the sequence of the identifiers of the simple objects componing the VO * @param oIsAnUuid * TRUE if the identifier is an UUID else FALSE.<br> */ static void GetIdentifier(const CATBaseUnknown* iVO, CATIVOFactory* iFactory , SEQUENCE(octet) & oIdentifier,CATBoolean& oIsAnUuid); /** * Gets the document containing the VO. * @param iVO * The virual object. * @param iFactory * The factory. * @return * the document containing the VO. Should be NULL. <br> */ static CATDocument* GetDocument (const CATBaseUnknown* iVO, CATIVOFactory* iFactory); /** * Gets the locator type of the VO. * @param iVO * The virual object. * @param iFactory * The factory. * @return * the locator type of the VO. Should be VOLocator. <br> */ static SEQUENCE(octet) GetLocatorType(const CATBaseUnknown* iVO, CATIVOFactory* iFactory); /** * Gets the Additional Infos of the VO. * @param iVO * The virual object. * @param iFactory * The factory. * @return * the Additional Infos of the VO. Should be void. <br> */ static SEQUENCE(octet) GetAdditionalInfos(const CATBaseUnknown* iVO, CATIVOFactory* iFactory); /** * Gets the Last Modification Id of the VO. * @param iVO * The virual object. * @param iFactory * The factory. * @return * the Last Modification Idof the VO. Should be void. <br> */ static SEQUENCE(octet) GetLastModificationId (const CATBaseUnknown* iVO, CATIVOFactory* iFactory); /** * Retrieves an equivalent VO inserted in the session link cache. * @param iVO * The virual object. * @param iFactory * The factory. * @return * <dl> * <dt> The equivalent VO if found in link cache. (Object should be released by caller) * </dl> */ static CATBaseUnknown * GetVOInLinkCache (const CATBaseUnknown* iVO, CATIVOFactory* iFactory); private: // Not implemented CATLinkableServicesForVO(); ~CATLinkableServicesForVO(); CATLinkableServicesForVO(const CATLinkableServicesForVO&); CATLinkableServicesForVO& operator = (const CATLinkableServicesForVO&); }; #endif
// import * as wasm from "hello-wasm-pack"; import * as wasm from "wasm-game-of-life"; import { main, Universe, Cell } from "wasm-game-of-life"; import { memory } from "wasm-game-of-life/wasm_game_of_life_bg.wasm"; if (window.location.pathname === '/') { let runr = main(); console.log({ runr }); } else if (window.location.pathname === '/life.html') { var x = 3; wasm.info("hello" + x); const CELL_SIZE = 5; // px const GRID_COLOR = "#CCCCCC"; const DEAD_COLOR = "#FFFFFF"; const ALIVE_COLOR = "#000000"; // wasm.greet("you" + x); // const pre = document.getElementById("game-of-life-canvas"); // const universe = Universe.new(); // // const renderLoop = () => { // pre.textContent = universe.render(); // universe.tick(); // // requestAnimationFrame(renderLoop); // }; // requestAnimationFrame(renderLoop); // const universe = Universe.new(); const width = universe.width(); const height = universe.height(); const canvas = document.getElementById("game-of-life-canvas"); canvas.height = (CELL_SIZE + 1) * height + 1; canvas.width = (CELL_SIZE + 1) * width + 1; const ctx = canvas.getContext('2d'); const renderLoop = () => { universe.tick(); drawGrid(); drawCells(); requestAnimationFrame(renderLoop); }; const drawGrid = () => { ctx.beginPath(); ctx.strokeStyle = GRID_COLOR; // Vertical lines. for (let i = 0; i <= width; i++) { ctx.moveTo(i * (CELL_SIZE + 1) + 1, 0); ctx.lineTo(i * (CELL_SIZE + 1) + 1, (CELL_SIZE + 1) * height + 1); } // Horizontal lines. for (let j = 0; j <= height; j++) { ctx.moveTo(0, j * (CELL_SIZE + 1) + 1); ctx.lineTo((CELL_SIZE + 1) * width + 1, j * (CELL_SIZE + 1) + 1); } ctx.stroke(); }; const getIndex = (row, column) => { return row * width + column; }; const drawCells = () => { const cellsPtr = universe.cells(); const cells = new Uint8Array(memory.buffer, cellsPtr, width * height); ctx.beginPath(); for (let row = 0; row < height; row++) { for (let col = 0; col < width; col++) { const idx = getIndex(row, col); ctx.fillStyle = cells[idx] === Cell.Dead ? DEAD_COLOR : ALIVE_COLOR; ctx.fillRect( col * (CELL_SIZE + 1) + 1, row * (CELL_SIZE + 1) + 1, CELL_SIZE, CELL_SIZE ); } } ctx.stroke(); }; drawGrid(); drawCells(); requestAnimationFrame(renderLoop); }
import { useEffect, useState } from "react"; import { getGifs } from "../helpers/getGifs"; //un hook es una funcion que regresa algo, en este caso, un objeto export const useFetchGifs = ( category ) => { const [images, setImages] = useState([]) const [isLoading, setIsLoading] = useState( true ) const getImages =async() => { const newImages = await getGifs( category ); setImages(newImages); setIsLoading( false ); } useEffect( () => { getImages(); }, []//si la dependencia esta vacia solo se ejecuta una vez ) return { images, //es lo mismo que images: images isLoading } }
const express = require('express'); const morgan = require('morgan'); const tourRouter = require('./routes/tourRoutes'); const userRouter = require('./routes/userRoutes'); const app = express(); //1. MIDDLEWARES --> middle betn request and response //middleware can be use to corverted the data into other things if(process.env.NODE_ENV === 'development'){ app.use(morgan('dev')); } app.use(express.json()); app.use(express.static(`${__dirname}/public`)); //3. ROUTES app.use('/api/v1/tours', tourRouter); app.use('/api/v1/users', userRouter); module.exports = app;
# Quiz - ¿Qué es JavaScript? - ¿Qué tipo de datos acepta javascript? - ¿Qué diferencias existen entre var, let y const? https://www.w3schools.com/js/js_const.asp - EXPLICAR HOISTING - ¿Que son las variables de ámbito global y local? - ¿Cuales son los operadores en javascript? https://www.w3schools.com/js/js_operators.asp - - Diferencia entre =, == y === - ¿Cual es la diferencia entre null y undefined? - ¿Qué es el type coercion? - ¿Qué es una funcion y como se define? # Clasificación de triangulos 1. Definimos la funcion llamandola clasificarTriangulo y tomará tres argumentos: lado1, lado2 y lado3. Estos argumentos representan los tres lados de un triangulo. 2. Comenzamos con una declaración `if` que verifica si todos los lados del triangulo son iguales. Utilizamos el operador de igualdad estricta `===` para comparar `lado1` con `lado2` y `lado2` con `lado3`. Si ambas comprobaciones son verdaderas, significa que todos los lados son iguales. 3. Si la condicion es verdadera se imprimirá por un console.log el mensaje "El triangulo es equilatero". 4. Si la condicion del `if` anterior no se cumple (es decir, no todos sus lados son iguales) entonces se verifica la siguiente condicion con un `else if`. Esta condición verifica si al menos dos lados del triángulo son iguales. Utilizamos el operador `||` (OR), que devuelve verdadero si al menos una de las condiciones es verdadera. 5. Si ninguna de las condiciones anteriores es verdadera, entonces se ejecuta el código dentro del bloque `else`. Esto significa que el triángulo no es ni equilatero ni isosceles. # División de números 1. Se utiliza prompt para mostrar un cuadro de diálogo que solicita al usuario que ingrese el primer número. La función prompt devuelve una cadena de texto, por lo que se utiliza `parseInt` para convertir esa cadena en un número entero. El resultado se almacena en la variable `num1`. 2. Se solicita al usuario que ingrese el segundo número. El resultado se almacena en la variable num2. 3. Se inicia una estructura de control `if` que verifica si `num2` es diferente de cero (!== 0). Esto es importante porque la división por cero en matemáticas no está definida y resultaría en un error. 4. Si `num2` es diferente de cero, se realiza la división de `num1` entre `num2`, y el resultado se almacena en la variable cociente. Luego, se utiliza console.log para mostrar el resultado en la consola. 5. Si `num2` es igual a cero, se ejecuta el bloque de código dentro del else, que muestra un mensaje de error en la consola indicando que no se puede dividir por cero. # Verificador de contraseñas 1. A través de un prompt para m ostrar un cuadro de dialogo que solicita al usuario que ingrese su contraseña. La contraseña ingresada por el usuario se almacena en la variable `contraseña`. 2. Aquí, se verifica si la longitud de la contraseña ingresada es mayor o igual a 8 caracteres. Si es así, la variable `minimo8Caracteres` se establece en `true`; de lo contrario, es `false`. 3. Esta línea utiliza una expresión regular para verificar si la contraseña contiene al menos una letra mayúscula. La expresión regular /[A-Z]/ busca cualquier letra mayúscula en la cadena de la contraseña. Si encuentra una, test devuelve `true`; de lo contrario, devuelve `false`. 4. Esta vez se verifica si la contraseña contiene al menos un número. La expresión regular /\\d/ busca cualquier dígito en la cadena de la contraseña. Si encuentra un dígito, test devuelve true; de lo contrario, devuelve false. 5. Este bloque if verifica si todas las condiciones anteriores son verdaderas (minimo8Caracteres, tieneMayuscula, tieneNumero). Si todas son verdaderas, significa que la contraseña cumple con los requisitos (tener al menos 8 caracteres, incluir una letra mayúscula y un número). Si se cumplen estas condiciones, se imprime "Contraseña válida." en la consola. 6. Si alguna de las condiciones no se cumple, se ejecuta el bloque else, y se imprime "La contraseña no cumple con los requisitos." en la consola. # Calculadora IMC 1. Solicitamos al usuario que ingrese su peso y altura. La función prompt muestra un cuadro de diálogo que pide al usuario que ingrese un valor. parseFloat convierte la entrada del usuario de una cadena a un número de punto flotante. Esto es necesario porque prompt devuelve una cadena, y queremos trabajar con números. 2. Se calcula el Índice de Masa Corporal (IMC) utilizando la fórmula peso / (altura * altura). El IMC es una medida de la grasa corporal basada en el peso y la altura de una persona. La operación ** 2 es una forma de elevar al cuadrado el valor de altura. 3. Se muestra el IMC calculado en la consola con dos decimales de precisión. toFixed(2) convierte el número a una cadena y formatea el resultado con dos decimales. 4. Estas líneas evalúan el IMC calculado y determinan el estado de salud de la persona basándose en los rangos de IMC. El IMC se utiliza para clasificar a las personas en categorías de peso. 5. Se utiliza una estructura de control if...else if...else para evaluar el IMC y determinar el estado de salud correspondiente. Cada condición verifica un rango específico de IMC y, si se cumple, imprime el estado de salud correspondiente en la consola. # Lista de numeros primos FUNCION ESPRIMO 1. creamos una funcion que determina si un numero dado es primo o no. Un numero primo es aquel que solo tiene dos divisores: 1 y él mismo. 2. Si el numero es mayor o igual a 1, la funcion devuelve false, ya que estos numeros no son primos. 3. Itera desde 2 hasta la raiz cuadrada del numero (esto se hace para optimizar el proceso, ya que un numero no puede tener un divisor mayor que su raiz cuadrada). 4. si encuentra algun divisot (es decir, si el numero es divisible por cualquier numero en este rango) devuelve false, indicando que el numero no es primo. 5. Si no encuentra ningun divisor, devuelve true, indicando que el numero es primo. FUNCION LISTARPRIMOS 1. Esta funcion genera una lista de todos los numeros primos hasta un numero dado. 2. Inicializamos un array vacio llamado `primos`. 3. Ireta desde 2 hasta el número `hasta` 4. Para cada número en este rango, utiliza la funcion `esPrimo` para verificar si es primo 5. Si el número es primo, lo agrega al array `primos` 6. Al final, devuelve el array `primos` que contiene todos los numeros primos hasta el numero `hasta` Despues de definir estas funciones, el código solicita al usuario que ingrese un número. Este número se pasa a la función `listarPrimos`, que genera la lista de números primos hasta ese número. Finalmente, se imprime por consola. # Conversor celsius/farenheit FUNCION celsiusToFarenheit(celsius) 1. Esta función toma un argumento `celsius`, que es la temperatura en grados Celsius. 2. La fórmula para convertir grados Celsius a Fahrenheit es `(celsius * 9/5) + 32.` 3. La función devuelve el resultado de esta fórmula, que es la temperatura en grados Fahrenheit. FUNCION fahrenheitToCelsius(fahrenheit) 1. Esta función toma un argumento `fahrenheit`, que es la temperatura en grados Fahrenheit. 2. La fórmula para convertir grados Fahrenheit a Celsius es `((fahrenheit - 32) * 5/9)`. 3. La función devuelve el resultado de esta fórmula, que es la temperatura en grados Celsius. Despues definimos dos constantes con valores de temperatura en gracos Celsius y Fahrenheit. temperaturaCelsius se inicializa con el valor 25 y temperaturaFahrenheit con valor 77. Se utilizan estas constantes para convertir entre Celsisus y Fahrenheit utilizando las funciones definidas anteriormente
/** * \file parsing\cmd_line_parser.cpp **/ #include "parsing\cmd_line_parser.hpp" namespace other { namespace { class CmdLineParser { public: CmdLineParser(const std::vector<std::string>& argv) : argc(argv.size()) , argv(argv) {} std::map<uint64_t , Arg> Parse() { ParseArgs(); return args; } private: int argc; const std::vector<std::string>& argv; size_t i = 0; std::map<uint64_t , Arg> args; void ParseArgs() { while (!AtEnd()) { const RawArg* ra = Peek(); if (ra != nullptr) { Arg arg { .hash = ra->hash , .flag = ra->lflag , .args = {} }; if (ra->has_args) { for (uint32_t j = 0; j < ra->num_args; ++j) { Advance(); if (AtEnd()) { println("Expected {} arguments for flag {}" , ra->num_args , ra->lflag); break; } arg.args.push_back(PeekRaw()); } } args.insert({ arg.hash , arg }); } else { println("Unknown flag: ", PeekRaw()); } Advance(); } for (const auto& [hash , arg] : args) { println("Flag: {}" , arg.flag); for (const auto& a : arg.args) { println(" Arg: {}" , a); } } } bool AtEnd() const { return i >= argc; } const std::string PeekRaw() const { if (AtEnd()) { return ""; } else { return argv[i]; } } const RawArg* Peek() const { if (AtEnd()) { return nullptr; } else { auto ra = std::ranges::find_if(kRawArgs, [&](const RawArg& arg) { return arg.sflag == argv[i] || arg.lflag == argv[i]; }); if (ra != kRawArgs.end()) { return &(*ra); } else { return nullptr; } } } void Advance() { i++; } }; } // namespace <anonymous> CmdLine::CmdLine(int argc , char* argv[]) { program_name = argv[0]; raw_args.reserve(argc - 1); raw_args.insert(raw_args.end() , argv + 1 , argv + argc); CmdLineParser parser{ raw_args }; args = parser.Parse(); } bool CmdLine::HasFlag(const std::string& flag) const { uint64_t hash = FNV(flag); if (args.contains(hash)) { return true; } else { return false; } } Opt<Arg> CmdLine::GetArg(const std::string& flag) const { uint64_t hash = FNV(flag); if (args.contains(hash)) { return args.at(hash); } else { return std::nullopt; } } } // namespace other
extends CharacterBody2D # Constants const SPEED = 120.0 const CHASE_DISTANCE = 100.0 const IDLE_TIME = 3 const GAP_BETWEEN_ENEMY_AND_PLAYER = 20 const DAMAGE = 30 const INSPECTING_RADIUS = 50 const PATROL_DISTANCE = 75 const RANGED_ATTACK_DISTANCE = 60 const RANGED_ATTACK_COOLDOWN = 3.0 const ATTACK_INTERVAL = 1 # Variables @onready var sprite = $Sprite @onready var playback = $AnimationTree.get("parameters/playback") @export var player: Player @onready var damageable = $Damageable var direction = 1 var state = "idle" var radius_where_enemy_inspecting = 0 var gravity: int = ProjectSettings.get_setting("physics/2d/default_gravity") var ranged_attack_timer = 0.0 func _ready() -> void: $AnimationTree.active = true $Timer.start(IDLE_TIME) func _physics_process(delta: float) -> void: if player.dead: return if state == "death" || state == "hit": return if not is_on_floor(): # if enemy is not on the ground apply gravity velocity.y += gravity # Choose behavior based on current state match state: "idle": velocity.x = move_toward(velocity.x, 0, SPEED) # Move towards 0 with given speed #playback.travel("Move", 0) "patrol": velocity.x = direction * SPEED # Move in patrol direction with given speed if abs(position.x - player.poosition.x) > PATROL_DISTANCE: # If enemy exceeds the patrol distance, change direction direction = -direction #playback.travel("Move", clamp(velocity.x, -1, 1)) "chase": # If distance is less then actual gap then always move in opposite direction of the player direction = sign(player.position.x - position.x) velocity.x = direction * SPEED radius_where_enemy_inspecting = radius_where_enemy_inspecting - 1 if direction == -1 else radius_where_enemy_inspecting + 1 #playback.travel("Move", clamp(velocity.x, -1, 1)) # Ranged attack if cooldown has elapsed and player is within range if ranged_attack_timer <= 0 and position.distance_to(player.position) < RANGED_ATTACK_DISTANCE: ranged_attack_timer = RANGED_ATTACK_COOLDOWN if abs(position.x - player.position.x) < GAP_BETWEEN_ENEMY_AND_PLAYER: velocity.x = move_toward(velocity.x, 0, SPEED) _update_facing_direction() move_and_slide() # Move the enemy with slide effect # Update the animation _update_animation() func _update_animation(): if state != "attack" && state != "death" && state != "hit": $AnimationTree.set("parameters/Move/blend_position", direction) func _update_facing_direction(): if direction > 0: # right $Sprite.flip_h = false elif direction < 0: # left $Sprite.flip_h = true func _on_timer_timeout() -> void: $Timer.start(IDLE_TIME) if state == "idle": state = "patrol" elif state == "patrol": state = "idle" func _process(delta: float): if player.dead: return if state == "death": return # Check the distance between the enemy and the player var distance_between_player_and_enemy = position.distance_to(player.position) # Choose behavior based on distance and state if state == "chase" and CHASE_DISTANCE < distance_between_player_and_enemy or distance_between_player_and_enemy < GAP_BETWEEN_ENEMY_AND_PLAYER and INSPECTING_RADIUS > abs(radius_where_enemy_inspecting): state = "idle" else: state = "chase" # TODO: Check for collision with other objects # TODO: Handle collision with other objects # TODO: Implement func _on_area_2d_body_entered(body): for child in body.get_children(): if child is Damageable_player: child.hit(DAMAGE) func _on_animation_tree_animation_finished(anim_name): #if state == "attack" && anim_name == "Attack": #state = "idle" if anim_name == "Death": print("anim finished") queue_free() return if state == "death": return if anim_name == "Hit": state == "idle" return if state == "hit": return if anim_name == "Attack": $AttackTimer.start(ATTACK_INTERVAL) return func _on_detector_body_entered(body): state = "attack" playback.travel("Attack") func _on_detector_body_exited(body): state == "idle" func _on_attack_timer_timeout(): if(state != "Hit" && state != "Death"): playback.travel("Attack") func _on_damageable_death(): state = "death" if $Sprite.flip_h: $Particles.process_material.gravity = Vector3(-100, 0,0) else: $Particles.process_material.gravity = Vector3(100, 0,0) $Particles.emitting = true playback.travel("Death") func _on_damageable_got_hit(): if state == "death": return if $Sprite.flip_h: $Particles.process_material.gravity = Vector3(-100, 0,0) else: $Particles.process_material.gravity = Vector3(100, 0,0) $Particles.emitting = true playback.travel("Hit") state = "hit"
context("Export Logging Argument Validation") ##################################################################### # Argument Validation test_that( "Return an error when rcon is not a redcapConnection object", { local_reproducible_output(width = 200) expect_error( exportLogging(rcon = "not an rcon"), "no applicable method for 'exportLogging'" ) } ) test_that( "Return an error when batchInterval is given without beginTime", expect_error( exportLogging(rcon, batchInterval=7), "Variable 'beginTime': Must have length >= 1, but has length 0" ) ) test_that( "Return an error when log_type is not one of event types", { local_reproducible_output(width = 200) expect_error( exportLogging(rcon, logtype = "abc"), "Variable 'logtype': Must be element of set" ) } ) test_that( "Return an error when user is not character", { local_reproducible_output(width = 200) expect_error( exportLogging(rcon, user = 1:2), "Variable 'user': Must be of type 'character'" ) } ) test_that( "Return an error when record is not character", { local_reproducible_output(width = 200) expect_error( exportLogging(rcon, record = 1:2), "Variable 'record': Must be of type 'character'" ) } ) test_that( "Return an error when dag is not a character", { local_reproducible_output(width = 200) expect_error( exportLogging(rcon, dag = 1:2), "Variable 'dag': Must be of type 'character'" ) } ) test_that( "Return an error when beginTime is not POSIXct", { local_reproducible_output(width = 200) expect_error( exportLogging(rcon, beginTime = "2023-01-01 00:00:00"), "Variable 'beginTime': Must be of type 'POSIXct'" ) } ) test_that( "Return an error when beginTime has length > 1", { local_reproducible_output(width = 200) expect_error( exportLogging(rcon, beginTime = rep(Sys.time(), 2)), "Variable 'beginTime': Must have length <= 1" ) } ) test_that( "Return an error when endTime is not POSIXct", { local_reproducible_output(width = 200) expect_error( exportLogging(rcon, endTime = "2023-01-01 00:00:00"), "Variable 'endTime': Must be of type 'POSIXct'" ) } ) test_that( "Return an error when endTime has length > 1", { local_reproducible_output(width = 200) expect_error( exportLogging(rcon, endTime = rep(Sys.time(), 2)), "Variable 'endTime': Must have length <= 1" ) } ) test_that( "Validate config, api_param", { local_reproducible_output(width = 200) expect_error(exportLogging(rcon, config = list(1)), "'config': Must have names") expect_error(exportLogging(rcon, config = "not a list"), "'config': Must be of type 'list'") expect_error(exportLogging(rcon, api_param = list(1)), "'api_param': Must have names") expect_error(exportLogging(rcon, api_param = "not a list"), "'api_param': Must be of type 'list'") } )
# Databricks notebook source from pyspark.sql.functions import * from pyspark.sql.types import * df_carros = spark.read.format("csv").option("header", True).load("/lab_pyspark_dados/modelo_carro.csv") df_marcas = spark.read.format("csv").option("header", True).load("/lab_pyspark_dados/marca_carro.csv") display(df_carros.head(5)) display(df_marcas.head(5)) # COMMAND ---------- print(df_carros.count()) df_carros= df_carros.filter(col("cod_marca")!='22') print(df_carros.count()) # COMMAND ---------- df_carros.createOrReplaceTempView("carros") df_marcas.createOrReplaceTempView("marcas") # COMMAND ---------- # MAGIC %sql # MAGIC select * from carros c inner join marcas m on c.cod_marca = m.cod_marca # COMMAND ---------- # MAGIC %sql # MAGIC select c.*, m.marca_carro from carros c inner join marcas m on c.cod_marca = m.cod_marca # COMMAND ---------- # COMMAND ---------- # MAGIC %sql # MAGIC select m.*, c.modelo_carro from marcas m left join carros c on c.cod_marca = m.cod_marca # COMMAND ---------- # MAGIC %sql # MAGIC select m.*, c.modelo_carro from marcas m right join carros c on c.cod_marca = m.cod_marca # COMMAND ---------- # COMMAND ---------- display( df_carros.join( df_marcas,(df_carros.cod_marca == df_marcas.cod_marca), "inner" ) ) # COMMAND ---------- display( df_carros.join( df_marcas,(df_carros.cod_marca == df_marcas.cod_marca), "right" ) ) # COMMAND ---------- display( df_carros.join( df_marcas,(df_carros.cod_marca == df_marcas.cod_marca), "right" ).select( df_marcas.marca_carro, df_carros["*"]) )
/* * Licensed under the Apache License, Version 2.0 (the "License"); * * Copyright 2011 JBoss Inc * 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.drools.chance.test; import org.drools.chance.factmodel.Imperfect; import org.drools.chance.factmodel.LinguisticPartition; import de.lab4inf.fuzzy.FuzzySet; import de.lab4inf.fuzzy.polygons.FuzzyTriangle; import org.drools.chance.degree.Degree; global java.util.Map map; declare enum Age @LinguisticPartition YOUNG( "young", new de.lab4inf.fuzzy.polygons.FuzzyTriangle( -0.01, 0, 100 ) ), OLD( "old", new de.lab4inf.fuzzy.polygons.FuzzyTriangle( 0, 100, 100.01 ) ); label : String set : FuzzySet end declare Person @Traitable name : String years : Double end declare trait Student @Imperfect( kind=ImpKind.FUZZINESS, type=ImpType.BASIC, degree=DegreeType.SIMPLE ) name : String years : Double age : Age @Imperfect( kind=ImpKind.FUZZINESS, type=ImpType.LINGUISTIC, degree=DegreeType.SIMPLE, support="years" ) school : String end rule "Init" when then insert( new Person( "john", 25.0 ) ); end rule "Imperfect Don" no-loop when $p : Person( years ~is Age.YOUNG ) then Degree degree = chance.getDegree(); System.out.println( "X " + degree ); // 0.75 map.put( "X", degree.getValue() ); // imperfect don: $p is a Student only up to some degree! Student student = chance.don( $p, Student.class, degree ); update( $p ); end rule "Imperfect ~isA" when $p : Person( this ~isA Student ) then Degree degree = chance.getDegree(); System.out.println( "Y " + degree ); // 0.75 map.put( "Y", degree.getValue() ); end rule "Implicit ~isA" when $p : Student( age ~is Age.OLD ) @Imperfect( family=MvlFamilies.PRODUCT ) then Degree degree = chance.getDegree(); System.out.println( "Z " + degree ); // 0.75 * 0.5 map.put( "Z", degree.getValue() ); end
import 'package:flutter/material.dart'; import 'package:intl_phone_field/intl_phone_field.dart'; import 'package:whatsapp/Chatfirst.dart'; class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Column( children: [ SizedBox( height: 40, width: 400, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const SizedBox( width: 70, ), const Text( 'Phone number', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20, ), ), Container( margin: const EdgeInsets.only(right: 10), child: const Text( 'Done', style: TextStyle( color: Colors.grey, ), )), ], ), ), Container( width: 400, height: 60, color: Colors.white, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Text( 'Please confirm your country code and', style: TextStyle( fontSize: 16, ), ), Text( 'enter your phone number', style: TextStyle(fontSize: 16), ), ], ), ), Container( height: 50, decoration: BoxDecoration( border: Border.all(color: Colors.black12), color: Colors.white, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( margin: const EdgeInsets.only(left: 20), child: const Text( 'United States', style: TextStyle( fontSize: 20, color: Colors.blue, ), ), ), Container( height: 15, margin: const EdgeInsets.only(right: 10), child: GestureDetector( onTap: (){ Navigator.push(context, MaterialPageRoute( builder: (context) => const Secondscreen(), )); }, child: const ImageIcon( AssetImage('assets/skip-track.png'), color: Colors.grey, ), ), ) ], )), Column( children: [ SizedBox( height: 90, child: IntlPhoneField( decoration: const InputDecoration( labelText: "Phone Number", labelStyle: TextStyle( fontSize: 20.0, ), hintStyle: TextStyle( color: Colors.grey, fontSize: 10.0, ), ), initialCountryCode: 'US', //default country code onChanged: (phone) { //when phone number country code is changed print(phone.completeNumber); //get complete number print(phone.countryCode); // get country code only print(phone.number); // only phone number },), ), ], ) ], ), )); } }
// // ValidationService.swift // Delegate // // Created by Dmitry Ivashin on 2/2/18. // Copyright © 2018 Dmitry Ivashin. All rights reserved. // import UIKit import SwiftyJSON enum FirebaseError: LocalizedError { case unknownError case noFirebaseUserRegistered case invalidCredentials case accessRestricted case emailInUse case missingEmail case userRemoved public var errorDescription: String? { switch self { case .unknownError: return ErrorMessage.errorUnknown case .noFirebaseUserRegistered: return ErrorMessage.noUserFound case .invalidCredentials: return ErrorMessage.invalidCredentials case .accessRestricted: return ErrorMessage.accessRestricted case .emailInUse: return ErrorMessage.emailTaken case .missingEmail: return ErrorMessage.emailEmpty case .userRemoved: return ErrorMessage.userRemoved } } } enum PasswordValidationError: LocalizedError { case passwordIdentity case passwordEmpty case passworConfirmedEmpty case passwordIncorrectFormat public var errorDescription: String? { switch self { case .passwordIdentity: return ErrorMessage.passwordIdentity case .passwordEmpty: return ErrorMessage.passwordEmpty case .passworConfirmedEmpty: return ErrorMessage.confirmPasswordEmpty case .passwordIncorrectFormat: return ErrorMessage.passwordIncorrectFormat } } } enum EmailValidationError: LocalizedError { case emptyEmail case emailIncorrectFormat public var errorDescription: String? { switch self { case .emptyEmail: return ErrorMessage.emailEmpty case .emailIncorrectFormat: return ErrorMessage.emailIncorrectFormat } } } enum ValidationState { case undefined case valid case invalid(errorMessage: String?) } enum JSONError { static let errorCode = "error_code" } enum ErrorCode { static let noFirebaseUserRegistered = "17011" static let invalidPassword = "17009" static let noNetworkConnection = "17020" static let invalidEmail = "17008" static let accessRestricted = "17005" static let emailInUse = "17007" static let missingEmail = "17999" static let linkedInCanceled = 3 } class ValidationService: NSObject { func handle(remoteResponce error: Error?) throws { guard let error = error else { return } let firebaseError: FirebaseError let code = String(error.code) switch code { case ErrorCode.noFirebaseUserRegistered: firebaseError = FirebaseError.noFirebaseUserRegistered throw firebaseError case ErrorCode.invalidPassword, ErrorCode.invalidEmail: firebaseError = FirebaseError.invalidCredentials throw firebaseError case ErrorCode.accessRestricted: firebaseError = FirebaseError.accessRestricted throw firebaseError case ErrorCode.emailInUse: firebaseError = FirebaseError.emailInUse throw firebaseError case ErrorCode.missingEmail: firebaseError = FirebaseError.missingEmail throw firebaseError default: break } } // MARK: - Main methods fileprivate func handleFetchUserFromFirebase(with dictionary: [String: Any]?) throws { let error: FirebaseError guard let unwrappedDictionary = dictionary else { error = FirebaseError.userRemoved throw error } } func checkPasswords(_ password: String?, with confirmedPassword: String?) throws { let error: PasswordValidationError guard let password = password, password.count != 0 else { error = .passwordEmpty throw error } try validate(password: password) guard let confirmedPassword = confirmedPassword, confirmedPassword.count != 0 else { error = .passworConfirmedEmpty throw error } if password != confirmedPassword { error = .passwordIdentity throw error } } func validate(email: String?) throws { let error: EmailValidationError guard let email = email, email.count != 0 else { error = .emptyEmail throw error } let emailRegex = "(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])" let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex) if !emailTest.evaluate(with: email) { error = .emailIncorrectFormat throw error } } func validate(password: String?) throws { let error: PasswordValidationError guard let password = password, password.count != 0 else { error = .passwordEmpty throw error } let passwordRegex = Constants.passwordRegex let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordRegex) if !passwordTest.evaluate(with: password) { error = .passwordIncorrectFormat throw error } } }
import 'package:flutter/material.dart'; import 'package:flutter_babe/controller/history_table_controller.dart'; import 'package:flutter_babe/routes/router_help.dart'; import 'package:flutter_babe/utils/colors.dart'; import 'package:flutter_babe/utils/dimension.dart'; import 'package:flutter_babe/widgets/big_text.dart'; import 'package:flutter_babe/widgets/custom_loader.dart'; import 'package:flutter_babe/widgets/small_text.dart'; import 'package:get/get.dart'; class HistoryBookTableWidget extends StatefulWidget { const HistoryBookTableWidget({super.key}); @override State<HistoryBookTableWidget> createState() => _HistoryBookTableWidgetState(); } class _HistoryBookTableWidgetState extends State<HistoryBookTableWidget> { final HistoryBookTableController historyBookTableController = Get.find<HistoryBookTableController>(); @override void initState() { super.initState(); historyBookTableController.getDataHistoryTable(); } @override Widget build(BuildContext context) { return GetBuilder<HistoryBookTableController>(builder: (controller) { if (controller.isLoading) { return CustomLoader(); } else { if (controller.historyBookTableList.isEmpty) { return Center( child: BigText( text: "no_orders_yet".tr, color: Theme.of(context).disabledColor, size: Dimensions.font20, ), ); } else { return SingleChildScrollView( child: Container( child: ListView.builder( itemCount: controller.historyBookTableList.length, physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemBuilder: (context, index) { return Container( decoration: BoxDecoration( //color: Colors.amber, borderRadius: BorderRadius.circular(Dimensions.radius20), border: Border.all(color: Theme.of(context).disabledColor)), margin: EdgeInsets.only( left: Dimensions.width10, right: Dimensions.width10, bottom: Dimensions.height10), child: Padding( padding: EdgeInsets.all(10), child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SmallText( text: "order_code".tr + controller.historyBookTableList[index].id! .toString(), color: AppColors.textColorBlack, size: Dimensions.font16 - 2, ), SizedBox( height: Dimensions.height10, ), SmallText( text: "fullname".tr + ": " + controller .historyBookTableList[index].name!, color: AppColors.textColorBlack, size: Dimensions.font16 - 2, ), SizedBox( height: Dimensions.height10, ), SmallText( text: "check_in".tr + ": " + controller .historyBookTableList[index].date!, color: AppColors.textColorBlack, size: Dimensions.font16 - 2, ), SizedBox( height: Dimensions.height10, ), SmallText( text: "time".tr + ": " + controller .historyBookTableList[index].time!, color: AppColors.textColorBlack, size: Dimensions.font16 - 2, ), SizedBox( height: Dimensions.height10, ), SmallText( text: "number_of_table".tr + controller.historyBookTableList[index] .numberTable! .toString(), size: Dimensions.font16 - 2, color: AppColors.textColorBlack, ), SizedBox( height: Dimensions.height10, ), SmallText( text: "number_of_people".tr + controller .historyBookTableList[index].people! .toString(), size: Dimensions.font16 - 2, color: AppColors.textColorBlack, ), ], ), Container( child: ElevatedButton( child: SmallText( text: "view_detail".tr, color: Colors.white, ), onPressed: () { Get.toNamed( RouteHelper.getDetailHistoryBookTable( controller .historyBookTableList[index].id!, "historyBookTablePage")); }, style: ElevatedButton.styleFrom( backgroundColor: AppColors.colorButton, padding: EdgeInsets.symmetric( horizontal: 5, vertical: 5), ), ), ) ], ), ), ); }, ), ), ); } } }); } }
import { memo, useEffect } from 'react' import type { ReactNode, FC } from 'react' import RecTitle from '../rec-title' import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store' import { fetchGetHotRecommendAction } from '../../store/action' import { getImgUrl } from '../../../../../../utils/tool' interface IProps { children?: ReactNode } const HotRecommend: FC<IProps> = () => { const title = ( <div className="flex items-center"> <span>热门推荐</span> <div className="text-[12px] ml-20px flex items-center text-[#666]"> {['华语', '流行', '摇滚', '民谣', '电子'].map((item, index) => { return ( <div key={index} className="flex items-center"> <a href={`#/discover/songs?cat=${item}`}>{item}</a> <span className="mx-10px">|</span> </div> ) })} </div> </div> ) const dispatch = useAppDispatch() const { hotRecommendList } = useAppSelector( (state) => state.recommend, shallowEqualApp ) useEffect(() => { dispatch(fetchGetHotRecommendAction(8)) }, []) return ( <div> <RecTitle title={title}> <a href="#/discover/songs"> 更多<i></i> </a> </RecTitle> <ul className="-ml-42px flex flex-wrap mt-20px"> {hotRecommendList?.map((item, index) => { return ( <li key={index} className="pl-42px w-140px h-204px box-content"> <div className="relative w-140px h-140px"> <a href={'#/playlist?id=' + item.id}> <img src={getImgUrl(item.picUrl, 140)} /> <div className="absolute bottom-0px h-27px bottom sprite_cover w-full flex items-center" style={{ backgroundPosition: '0px -537px', color: 'rgb(204, 204, 204)' }} > <i className="sprite_icon" style={{ width: '14px', height: '11px', backgroundPosition: '0px -24px', margin: '9px 5px 9px 10px' }} ></i> <span>{(item.playCount / 10000).toFixed(0)}万</span> <i className="icon-play sprite_icon"></i> </div> </a> </div> <p className="mt-8px mb-3px text-[14px]"> <a className="leading-20px" href={'#/playlist?id=' + item.id}> {item.name} </a> </p> </li> ) })} </ul> </div> ) } export default memo(HotRecommend)
package com.example.question6; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private RecyclerView recyclerView; private List<ContactItem> personList; private PersonAdapter personAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); personList = generatePersonData(); personAdapter = new PersonAdapter(personList); recyclerView.setAdapter(personAdapter); } private List<ContactItem> generatePersonData() { List<ContactItem> personList = new ArrayList<>(); for (int i = 1; i <= 10; i++) { String name = "Person " + i; String address = "Address " + i; String contact = "Contact " + i; int age = 20 + i; ContactItem person = new ContactItem(name, address, contact, age); personList.add(person); } return personList; } }
// // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // import Foundation import UIKit protocol ColorSelectorControllerDelegate: AnyObject { /// Called to ask if tooltip should be shown /// /// - Returns: Bool for tooltip func shouldShowTooltip() -> Bool /// Called after the tooltip is dismissed func didDismissTooltip() /// Called when the selection circle is panned /// /// - Parameter point: location to take the color from /// - Returns: Color from image func getColor(at point: CGPoint) -> UIColor /// Called when the selection circle appears func didShowCircle() /// Called when the selection circle is starts its movement func didStartMovingCircle() /// Called when the selection circle is released /// /// - Parameter color: selected color func didEndMovingCircle(color: UIColor) } /// Controller for handling the color selector in the drawing menu. final class ColorSelectorController: UIViewController, ColorSelectorViewDelegate { weak var delegate: ColorSelectorControllerDelegate? var circleInitialLocation: CGPoint { get { return colorSelectorView.circleInitialLocation } set { colorSelectorView.circleInitialLocation = newValue } } private lazy var colorSelectorView: ColorSelectorView = { let view = ColorSelectorView() view.delegate = self return view }() init() { super.init(nibName: .none, bundle: .none) } @available(*, unavailable, message: "use init() instead") required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @available(*, unavailable, message: "use init() instead") public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { fatalError("init(nibName:bundle:) has not been implemented") } // MARK: - View Life Cycle override func loadView() { view = colorSelectorView } // MARK: - Public interface /// Shows or hides the color Selector /// /// - Parameter show: true to show, false to hide func show(_ show: Bool) { colorSelectorView.show(show) if delegate?.shouldShowTooltip() == true { colorSelectorView.showOverlay(true) colorSelectorView.showTooltip(true) } if show { delegate?.didShowCircle() } } /// Sets a new color for the color circle and drops /// /// - Parameter color: new color for the color Selector func setColor(_ color: UIColor) { colorSelectorView.setColor(color) } /// Takes the selection circle back to its initial position func resetLocation() { colorSelectorView.moveCircle(to: colorSelectorView.circleInitialLocation) colorSelectorView.transformCircle(CGAffineTransform(scaleX: 0, y: 0)) } /// Changes the color of the selection circle to the one from the initial position func resetColor() { let color = getColor(at: circleInitialLocation) colorSelectorView.setColor(color) } // MARK: - Private utilities /// Changes the location of the color Selector to the location of the user's finger /// /// - Parameter recognizer: the gesture recognizer /// - Returns: the new location of the color Selector private func moveCircle(recognizer: UIPanGestureRecognizer) -> CGPoint { let translation = recognizer.translation(in: colorSelectorView) let point = CGPoint(x: circleInitialLocation.x + translation.x, y: circleInitialLocation.y + translation.y) colorSelectorView.moveCircle(to: point) return point } /// Gets the color of a certain point of the background /// /// - Parameter point: the location to take the color from /// - Returns: the color of the pixel private func getColor(at point: CGPoint) -> UIColor { guard let delegate = delegate else { return .black } return delegate.getColor(at: point) } // MARK: - ColorSelectorViewDelegate func didPanCircle(recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: delegate?.didStartMovingCircle() if delegate?.shouldShowTooltip() == true { colorSelectorView.showTooltip(false) colorSelectorView.showOverlay(false) } case .changed: let currentLocation = moveCircle(recognizer: recognizer) let color = getColor(at: currentLocation) colorSelectorView.setColor(color) case .ended, .failed, .cancelled: let currentLocation = moveCircle(recognizer: recognizer) let color = getColor(at: currentLocation) show(false) delegate?.didEndMovingCircle(color: color) case .possible: break @unknown default: break } } func didDismissTooltip() { delegate?.didDismissTooltip() } }
import Account from 'ethereumjs-account' import * as ethereumUtil from 'ethereumjs-util' import * as fs from 'fs-extra' import leveldown from 'leveldown' import levelup from 'levelup' import * as util from 'util' const ethjsUtil = require('ethjs-util') const Trie = require('merkle-patricia-tree/secure') const Block = require('ethereumjs-block') const Blockchain = require('ethereumjs-blockchain') const VM = require('ethereumjs-vm') const level = require('level') function format(a: any, toZero?: any, isHex?: boolean) { if (a === '') { return Buffer.alloc(0) } if (a.slice && a.slice(0, 2) === '0x') { a = a.slice(2) if (a.length % 2) a = '0' + a a = Buffer.from(a, 'hex') } else if (!isHex) { a = Buffer.from(new ethereumUtil.BN(a).toArray()) } else { if (a.length % 2) a = '0' + a a = Buffer.from(a, 'hex') } if (toZero && a.toString('hex') === '') { a = Buffer.from([0]) } return a } async function setupPreConditions(state: any, testData: any) { const keysOfPre = Object.keys(testData.pre) return Promise.all(keysOfPre.map(async (key: any) => { const acctData = testData.pre[key] const account = new Account() account.nonce = format(acctData.nonce) account.balance = format(acctData.balance) const storageTrie = state.copy() storageTrie.root = null const keys = Object.keys(acctData.storage) await Promise.all(keys.map(async (key: any) => { let val = acctData.storage[key] val = ethereumUtil.rlp.encode(Buffer.from(val.slice(2), 'hex')) key = ethereumUtil.setLength(Buffer.from(key.slice(2), 'hex'), 32) return util.promisify(storageTrie.put)(key, val) })) const codeBuf = Buffer.from(acctData.code.slice(2), 'hex') await new Promise((resolve, reject) => { account.setCode(state, codeBuf, (err: any, codeHash: Buffer) => { if (err) return reject(err) resolve(codeHash) }) }) account.stateRoot = storageTrie.root if (testData.exec && key === testData.exec.address) { testData.root = storageTrie.root } return util.promisify(state.put)(Buffer.from(ethjsUtil.stripHexPrefix(key), 'hex'), account.serialize()) })) } export const enum SupportedHardforkType { byzantium = 'byzantium' } export interface BlockChainConfig { dbPath: string, validate: boolean, cachePath: string, hardfork: SupportedHardforkType data: any reset?: boolean } export async function runBlockchain(config: BlockChainConfig) { const hardfork = config.hardfork const validate = config.validate const data = config.data if (config.reset) { await Promise.all([config.dbPath, config.cachePath].map(async path => { if (path) { await fs.emptyDir(path) } })) } await Promise.all([config.dbPath, config.cachePath].map(async dir => { if (dir) { await fs.ensureDir(dir) } })) const db = levelup(leveldown(config.dbPath)) const blockchain = new Blockchain({db, hardfork, validate}) if (validate) blockchain.ethash.cacheDB = level(config.cachePath) const state = new Trie(db) const vm = new VM({state, blockchain, hardfork}) data.homestead = true vm.on('beforeTx', (tx: any) => { tx._homestead = true }) vm.on('beforeBlock', (block: any) => { block.header.isHomestead = function () { return true } }) const genesisBlock = new Block({hardfork}) // Setup pre state await setupPreConditions(state, data) // Create genesis block await new Promise((resolve, reject) => { genesisBlock.header = new Block.Header(data.genesisBlockHeader, {hardfork}) blockchain.putGenesis(genesisBlock, (err: any, value: any) => { if (err) reject(err) resolve(value) }) }) // add some following blocks for (const raw of data.blocks) { const block = new Block(Buffer.from(raw.rlp.slice(2), 'hex')) // forces the block into thinking they are homestead block.header.isHomestead = () => { return true } block.uncleHeaders.forEach((uncle: any) => { uncle.isHomestead = function () { return true } }) await new Promise((resolve, reject) => { blockchain.putBlock(block, (err: any, result: any) => { if (err) reject(err) resolve(result) }) }) } // Run blockchain await new Promise((resolve, reject) => { vm.runBlockchain((err: any, value: any) => { if (err) reject(err) resolve(value) }) }) return vm }
# sort - R package for fast multi-threaded sorting of vectors # # Copyright (C) 2017-present, Mark AJ Klik # # This file is part of the sort R package. # # The sort R package is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License version 3 as # published by the Free Software Foundation. # # The sort R package 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 Affero General Public License # for more details. # # You should have received a copy of the GNU Affero General Public License along # with the sort R package. If not, see <http://www.gnu.org/licenses/>. # # You can contact the author at: # - sort R package source repository : https://github.com/fstpackage/sort #' Sort integer vector #' #' Fast in-place sorting of an integer vector. Uses multithreading to increase sorting #' speed. #' #' @param vec integer vector to be sorted #' @param method character string specifying the algorithm used. Valid methods are #' 'quick' for quicksort and 'radix' for radix sort. #' #' @return sorted vector #' @export msort <- function(vec, method = "radix") { if (is.logical(vec)) { sort:::fstsort_radix_logical(vec) return(vec) } if (is.integer(vec)) { if (method == "radix") { return(fstsort_radix_int(vec)) } else if (method == "quick") { fstsort(vec) return(vec) } else { stop("please select a valid sorting method, allowed values are 'radix' and 'quick'") } } stop("Type not implemented (yet)") } #' Fast-sort a vector and it's ordering #' #' @param vec vector to be sorted #' @param order a vector with integer values 1 to length(vec) that represents an ordering of vector _vec_. #' #' @return an integer vector containing the same values as _order_ but reordered in the the same way as _vec_. #' @export msort_order <- function(vec, order = NULL) { if (!is.logical(vec)) { stop("Use a logical") } if (!is.null(order)) { if (!is.integer(order)) { stop("Use an integer vector for parameter order") } if (length(order) != length(vec)) { stop("parameter order must have the same length as parameter vec") } } sort:::fstsort_radix_logical_order(vec, order) }
/* eslint-disable import/no-extraneous-dependencies */ import React from 'react' import { withDesign } from 'storybook-addon-designs' import { Form } from 'antd' import { ComponentStory } from '@storybook/react' import ToggleField from '../../atoms/ToggleField' const options = ['Test 1', 'Test 2', 'Test 3'] export default { title: 'Fields/Toggle', component: ToggleField, decorators: [withDesign], args: { meta: { touched: false }, input: { onChange: () => {} } } } const Template: ComponentStory<typeof ToggleField> = (args) => ( <Form> <ToggleField {...args} /> </Form> ) // stories export const ToggleDefault = Template.bind({}) export const ToggleDisabled = Template.bind({}) export const ToggleSmall = Template.bind({}) export const ToggleSmallDisabled = Template.bind({}) // arguments ToggleDefault.args = { options } // arguments ToggleDisabled.args = { disabled: true, options } ToggleSmall.args = { size: 'small', options, defaultChecked: true } ToggleSmallDisabled.args = { size: 'small', options, disabled: true }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Bot.Builder; using Microsoft.Bot.Schema; using Serious.Abbot.Scripting; using Serious.Slack; namespace Serious.Abbot.Messaging; /// <summary> /// The simplest interface for responding back to chat. This wraps an <see cref="ITurnContext"/>. /// </summary> public interface IResponder : IModalSource { /// <summary> /// Sends an activity response back to the chat platform. /// </summary> /// <param name="message">The message to send.</param> /// <param name="messageTarget">The target of the message. If null, targets the current thread (if in a thread) or the current room.</param> Task SendActivityAsync(IMessageActivity message, IMessageTarget? messageTarget = null); /// <summary> /// Updates an existing chat message. /// </summary> /// <param name="message">The message to update.</param> Task UpdateActivityAsync(IMessageActivity message); /// <summary> /// When an interaction occurs, this method is used to report back that there were validation errors in the /// submission. /// </summary> /// <param name="errors">Dictionary of errors where the keys match block Ids and values are the error message to display.</param> void ReportValidationErrors(IReadOnlyDictionary<string, string> errors); /// <summary> /// Sets the <see cref="ResponseAction"/> to be sent for this submission. /// This will override any validation errors specified in <see cref="ReportValidationErrors"/>. /// </summary> void SetResponseAction(ResponseAction action); /// <summary> /// This is used by by the <see cref="BlockSuggestionPayloadHandler"/> so we can respond with /// a JSON payload. /// </summary> void SetJsonResponse(object responseBody); /// <summary> /// Returns true if there are any validation errors. /// </summary> bool HasValidationErrors { get; } /// <summary> /// Removes a chat message from the chat platform. /// </summary> /// <param name="platformRoomId">The platform-specific Id of the room the activity is in.</param> /// <param name="activityId">The Id of the activity. In the case of Slack, the timestamp for the message.</param> Task DeleteActivityAsync(string platformRoomId, string activityId); /// <summary> /// Removes a chat message from the chat platform. /// </summary> /// <param name="responseUrl">The message response URL used to delete a message.</param> Task DeleteActivityAsync(Uri responseUrl); /// <summary> /// Push a view onto the stack of a root view. Use this to Push a new view onto the existing view stack by /// passing a view object and a valid <c>trigger_id</c> generated from an interaction within the existing /// modal. The pushed view is added to the top of the stack, so the user will go back to the previous view /// after they complete or cancel the pushed view. /// <para> /// After a modal is opened, the app is limited to pushing 2 additional views. /// </para> /// </summary> /// <remarks> /// See <see href="https://api.slack.com/methods/views.push" /> for more info. /// </remarks> /// <param name="triggerId">A short-lived ID that can be used to <see href="https://api.slack.com/interactivity/handling#modal_responses">open modals</see>.</param> /// <param name="view">The view to push onto the stack.</param> Task<ViewResponse> PushModalAsync(string triggerId, ViewUpdatePayload view); /// <summary> /// Update an existing view. Update a view by passing a new view definition object along with the /// <c>view_id</c> returned in views.open or the <c>external_id</c>. See the modals documentation /// to learn more about updating views and avoiding race conditions with the hash argument. /// </summary> /// <remarks> /// See <see href="https://api.slack.com/methods/views.update" /> for more info. /// </remarks> /// <param name="viewId">The Id of the view to update.</param> /// <param name="view">Information about the modal view to update.</param> Task<ViewResponse> UpdateModalAsync(string viewId, ViewUpdatePayload view); } /// <summary> /// A source that can open new modals. /// </summary> public interface IModalSource { /// <summary> /// Opens the view as a modal (Slack only). /// </summary> /// <param name="triggerId">A short-lived ID that can be used to <see href="https://api.slack.com/interactivity/handling#modal_responses">open modals</see>.</param> /// <param name="view">The view to open.</param> Task<ViewResponse> OpenModalAsync(string triggerId, ViewUpdatePayload view); }
<form> <mat-form-field class="col-lg-3 col-md-3 col-xs-10 col-sm-6"> <mat-select placeholder="Select Customer" [(value)]="customid" > <mat-option *ngFor="let customer of customers" [value]="customer.custid">{{customer.custname}}</mat-option> </mat-select> </mat-form-field> <div class="col-xs-2"> <button type="button" (click)="openDialog()" mat-icon-button><i class="material-icons"> face </i></button> </div> <mat-form-field class="col-lg-3"> <input matInput [matDatepicker]="picker" (dateChange)="addEvent('change', $event)" placeholder="Choose A Date" /> <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker> </mat-form-field> <div class="col-12 table-responsive"> <table mat-table [dataSource]="dt" width="100%"> <ng-container matColumnDef="srno"> <th mat-header-cell *matHeaderCellDef>Sr No</th> <td mat-cell *matCellDef="let row">{{row.srno}}</td> </ng-container> <ng-container matColumnDef="matdescription"> <th mat-header-cell *matHeaderCellDef>Material Description </th> <td mat-cell *matCellDef="let row"> <mat-list> <mat-list-item *ngFor="let x of row.item.bom">{{x.material.name}}</mat-list-item> </mat-list> </td> </ng-container> <ng-container matColumnDef="minqty"> <th mat-header-cell *matHeaderCellDef>Minimum Qty/Sheets</th> <td mat-cell *matCellDef="let row"> <mat-list> <mat-list-item *ngFor="let x of row.item.bom">{{x.qty}}</mat-list-item> </mat-list> </td> </ng-container> <ng-container matColumnDef="itemname"> <th mat-header-cell *matHeaderCellDef>Item Name </th> <td mat-cell *matCellDef="let row">{{row.item.productname}}</td> </ng-container> <ng-container matColumnDef="qty"> <th mat-header-cell *matHeaderCellDef>Qty </th> <td mat-cell *matCellDef="let row">{{row.qty}}</td> </ng-container> <ng-container matColumnDef="rate"> <th mat-header-cell *matHeaderCellDef>Rate/Cartoon</th> <td mat-cell *matCellDef="let row">{{row.rate}}</td> </ng-container> <ng-container matColumnDef="total"> <th mat-header-cell *matHeaderCellDef>Total </th> <td mat-cell *matCellDef="let row">{{row.total}}</td> </ng-container> <ng-container matColumnDef="option"> <th mat-header-cell *matHeaderCellDef></th> <td mat-cell *matCellDef="let row; let i = index;"><button mat-icon-button type="button" (click)="removeitem(i)" ><i class="material-icons">remove</i></button> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="datafields"></tr> <tr mat-row *matRowDef="let row; columns: datafields;"></tr> </table> </div> <mat-form-field class="col-lg-3"> <mat-select placeholder="Item " [(value)]="sitem" > <mat-option *ngFor="let pro of product;let i = index" [value]="i">{{ pro.productname }}</mat-option> </mat-select> </mat-form-field> <mat-form-field class="col-lg-3"> <input matInput type="text" [value]="sqty" (input)="getqty($event)" placeholder="Quantity" /> <mat-hint>Should be in digits</mat-hint> </mat-form-field> <button mat-raised-button type="button" class="co-2" color="primary" (click)="additem()">Add</button>&nbsp; <button type="button" mat-raised-button class="co-2" (click)="save()" color="primary">Save</button> </form>
package dicoding.compose.jetpackprime.di import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor import com.facebook.flipper.plugins.network.NetworkFlipperPlugin import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dicoding.compose.jetpackprime.BuildConfig import dicoding.compose.jetpackprime.data.remote.network.MovieApi import dicoding.compose.jetpackprime.data.remote.network.SearchApi import dicoding.compose.jetpackprime.data.remote.network.TrendingApi import dicoding.compose.jetpackprime.util.General import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory @Module @InstallIn(SingletonComponent::class) object NetworkModule { private val flipperPlugin = NetworkFlipperPlugin() private val client = OkHttpClient.Builder() .addNetworkInterceptor(FlipperOkhttpInterceptor(flipperPlugin)) .addNetworkInterceptor {chain-> val original = chain.request() val originalAuthToken = original.header("Authorization") if (originalAuthToken.isNullOrEmpty()) { val requestBuilder = original.newBuilder() .header( "Authorization", "Bearer ${BuildConfig.apiKey}" ).header( "App-Version", BuildConfig.VERSION_NAME ) val request = requestBuilder.build() chain.proceed(request) } else { chain.proceed(original) } } .build() @Provides fun networkFlipperPlugin():NetworkFlipperPlugin = flipperPlugin @Provides fun retrofit(): Retrofit = Retrofit.Builder() .baseUrl(General.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() @Provides fun provideTrendingApi(retrofit:Retrofit):TrendingApi =retrofit.create(TrendingApi::class.java) @Provides fun provideSearchApi(retrofit:Retrofit):SearchApi =retrofit.create(SearchApi::class.java) @Provides fun provideMovieApi(retrofit:Retrofit):MovieApi =retrofit.create(MovieApi::class.java) }
import { matrixZero } from "./index.ts" describe("matrixZero", () => { test("it sets rows and columns containing zeros to zero (one zero case)", () => { const inputMatrix = [ [1, 2, 3], [4, 0, 6], [7, 8, 9] ] const expectedOutput = [ [1, 0, 3], [0, 0, 0], [7, 0, 9] ] expect(matrixZero(inputMatrix)).toEqual(expectedOutput) }) test("it sets rows and columns containing zeros to zero (multiple zero case)", () => { const inputMatrix = [ [1, 2, 0], [4, 0, 6], [0, 8, 9] ] const expectedOutput = [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] expect(matrixZero(inputMatrix)).toEqual(expectedOutput) }) test("it sets rows and columns containing zeros to zero (negative numbers occur case)", () => { const inputMatrix = [ [-1, -2, 3], [4, 0, -6], [7, -8, -9] ] const expectedOutput = [ [-1, 0, 3], [0, 0, 0], [7, 0, -9] ] expect(matrixZero(inputMatrix)).toEqual(expectedOutput) }) test("it sets rows and columns containing zeros to zero (huge matrix case)", () => { const inputMatrix = [ [ 0, 1, 0, 1, 0, 1, 0, 1], [ 1, 1, 1, 0, 0, 1, 1, 0], [ 0, 1, 1, 0, 1, 1, 1, 1], [ 1, 1, 1, 1, 1, 1, 1, 1], [ 0, 1, 1, 0, 1, 1, 1, 1], [ 0, 1, 1, 0, 1, 1, 1, 1], [ 0, 1, 1, 0, 1, 1, 1, 1], ] const expectedOutput = [ [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 1, 0, 0, 0, 1, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0], ] expect(matrixZero(inputMatrix)).toEqual(expectedOutput) }) test("it does not change matrix when it does not contain zeros", () => { const inputMatrix = [ [1, 2, 3], [4, 1, 6], [7, 8, 9] ] expect(matrixZero(inputMatrix)).toEqual(inputMatrix) }) test("it does not change matrix when the matrix is made of empty matrices", () => { const inputMatrix = [[], []] expect(matrixZero(inputMatrix)).toEqual(inputMatrix) }) test("it throws an error when the matrix's rows have different length", () => { const inputMatrix = [[1,2,3],[0,5],[6,7]] expect(() => matrixZero(inputMatrix)).toThrow("Every row should have the same length.") }) })
import json from peewee import fn import pandas as pd import plotly.express as px from scripts.entry import entry_key_readable_source from scripts.index import IndexEntry, IndexBookCharacter, IndexBook LAYOUT = { "xaxis_title": None, "yaxis_title": None, "margin": dict(l=20, r=20, t=20, b=20), } def graph_languages_over_time(): languages = [ "Japanese", "English", "Chinese", "Spanish", ] query = (IndexEntry .select(fn.Min(IndexEntry.date), IndexEntry.language) .where(IndexEntry.language << languages) .group_by(IndexEntry.book, IndexEntry.language)) df = (pd.DataFrame(query.dicts()) .groupby("language") .resample("1M", on="date").count() .rename(columns={"language": "count"}) .groupby("language").cumsum() .reset_index()) legend = (df.groupby("language") .max().sort_values(by="count", ascending=False) .reset_index()["language"].tolist()) fig = px.line( df, x="date", y="count", color="language", labels={"date": "Date", "count": "Count", "language": "Language"}, category_orders={"language": legend}, ) fig.update_layout(LAYOUT) return fig.to_json() def graph_websites_over_time(): # Ignore metadata-only entries. query = [ {"site": entry_key_readable_source(entry.id), "date": entry.date} for entry in (IndexEntry .select(IndexEntry.id, IndexEntry.date) .where(~IndexEntry.language.is_null())) ] df = (pd.DataFrame(query) .groupby("site") .resample("1M", on="date").count() .rename(columns={"site": "count"}) .groupby("site").cumsum() .reset_index()) legend = (df.groupby("site") .max().sort_values(by="count", ascending=False) .reset_index()["site"].tolist()) fig = px.line( df, x="date", y="count", color="site", labels={"date": "Date", "count": "Count", "site": "Website"}, category_orders={"site": legend}, ) fig.update_layout(LAYOUT) return fig.to_json() def graph_page_counts(): query = (IndexEntry .select(fn.Max(IndexEntry.page_count)) .group_by(IndexEntry.book)) df = pd.DataFrame(query.dicts()) df = df[df["page_count"] <= 100] fig = px.histogram( df, x="page_count", nbins=20, labels={"page_count": "Number of pages"} ) fig.update_layout(LAYOUT) return fig.to_json() def graph_characters_over_time(): query = (IndexBookCharacter .select(fn.Min(IndexEntry.date), IndexBookCharacter.character) .join(IndexBook).join(IndexEntry) .group_by(IndexEntry.book, IndexBookCharacter.character)) df = (pd.DataFrame(query.dicts()) .groupby("character") .resample("1M", on="date").count() .rename(columns={"character": "count"}) .groupby("character").cumsum() .reset_index()) significant = set() for name in list(df.character.unique()): if max(df[df.character == name]["count"]) > 500: significant.add(name) df = df[df.character.isin(significant)] legend = (df.groupby("character") .max().sort_values(by="count", ascending=False) .reset_index()["character"].tolist()) fig = px.line( df, x="date", y="count", color="character", labels={"date": "Date", "count": "Count", "character": "Character"}, category_orders={"character": legend}, ) fig.update_layout(LAYOUT) return fig.to_json() def main(): data = { "languages": graph_languages_over_time(), "websites": graph_websites_over_time(), "page-counts": graph_page_counts(), "characters": graph_characters_over_time(), } with open("data/statistics.json", "w") as f: json.dump(data, f) if __name__ == '__main__': main()
export type FragmentCustomType = { custom: { name: string; value: string; }; metadata?: any; }; export type FragmentMarkdownType = { markdown: string; metadata?: any; }; export type FragmentPlainType = { plain: string; metadata?: any; }; export type FragmentBoldType = { bold: string; metadata?: any; }; export type FragmentItalicsType = { italics: string; metadata?: any; }; export type FragmentStrikeType = { strike: string; metadata?: any; }; export type FragmentBoldItalicsType = { 'bold-italics': string; metadata?: any; }; export type FragmentBoldStrikeType = { 'bold-strike': string; metadata?: any; }; export type FragmentItalicsStrikeType = { 'italics-strike': string; metadata?: any; }; export type FragmentBoldItalicsStrikeType = { 'bold-italics-strike': string; metadata?: any; }; export type FragmentBlockquoteType = { blockquote: string; metadata?: any; }; export type FragmentInlineCodeType = { 'inline-code': string; metadata?: any; }; export type FragmentShipType = { ship: string; metadata?: any; }; export type FragmentCodeType = { code: string; metadata?: any; }; export type FragmentLinkType = { link: string; metadata?: any; }; export type FragmentImageType = { image: string; metadata?: { width?: string; height?: string; }; }; export type FragmentUrLinkType = { 'ur-link': string; metadata?: any; }; export type FragmentBreakType = { break: null; metadata?: any; }; export type FragmentStatusType = { status: string; metadata?: any; }; export type FragmentTabType = { tab: { url: string; favicon: string; title: string; }; }; export type FragmentType = | FragmentCustomType | FragmentMarkdownType | FragmentPlainType | FragmentBoldType | FragmentItalicsType | FragmentStrikeType | FragmentBoldItalicsType | FragmentBoldStrikeType | FragmentItalicsStrikeType | FragmentBoldItalicsStrikeType | FragmentBlockquoteType | FragmentInlineCodeType | FragmentShipType | FragmentCodeType | FragmentLinkType | FragmentImageType | FragmentUrLinkType | FragmentBreakType | FragmentReplyType | FragmentTabType | FragmentStatusType; export type FragmentKey = keyof FragmentType; export type FragmentReplyType = { reply: { msgId: string; author: string; message: FragmentType[]; }; }; export type FragmentReactionType = { msgId: string; by: string; emoji: string; // emoji.unified -> see emoji-picker-react }; export type ChatMessageType = { author: string; authorColor?: string; sentAt: string; our?: boolean; message?: FragmentType[]; reactions?: FragmentReactionType[]; }; export const TEXT_TYPES = [ 'plain', 'bold', 'italics', 'strike', 'bold-italics', 'bold-strike', 'italics-strike', 'bold-italics-strike', 'inline-code', 'ship', ];
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Web Font Loader (локальные файлы шрифта)</title> <link rel="stylesheet" href="css/style.min.css"> <link rel="stylesheet" href="css/font-webfontloader.css"> <!-- https://github.com/typekit/webfontloader --> <!-- <script src="https://ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js"></script> --> <script> // Конфигурируем WebFontConfig = { custom: { // families: ['Merriweather_circle', 'Rubik_kubik'], families: ['Merriweather_circle:n7', 'Rubik_kubik:n4'], urls: ['css/font-face-only.css'] }, timeout: 2000, loading: function() {console.log('загрузка');}, active: function() { console.log('активность'); sessionStorage.fontsLoaded = true; }, inactive: function() {console.log('неактивность');}, fontloading: function(familyName, fvd) {console.log('загрузка '+familyName);}, fontactive: function(familyName, fvd) {console.log('активность '+familyName);}, fontinactive: function(familyName, fvd) {console.log('неактивность '+familyName);} }; // Получим скрипт асинхронно (function(d) { var wf = d.createElement('script'), s = d.scripts[0]; wf.src = 'https://ajax.googleapis.com/ajax/libs/webfont/1.6.16/webfont.js'; s.parentNode.insertBefore(wf, s); })(document); // Проверим флаг, вероятно, шрифты уже в кеше браузера (function() { if (sessionStorage.fontsLoaded) { console.log('Метка есть, в рамках сессии шрифты загружались, добавляем классы активности сразу'); document.documentElement.classList.add('wf-merriweathercircle-n7-active', 'wf-rubikkubik-n4-active'); } else { console.log('Метки загрузки шрифтов еще нет, ЩАЗ БУДИМ ЗАГРУЗИТЬ.'); } })(); </script> </head> <body> @@include('_include/nav.html') <p class="descr">Web Font Loader (локальные файлы шрифта). Внимание на CSS-классы, добавляемые к <code>html</code></p> <h1>Тестовый стенд</h1> <h2>Заголовок header</h2> <img src="img/image.jpg" alt="" class="demo-image"> <p>Далеко-далеко за словесными горами в стране, гласных и согласных живут рыбные тексты. Своего дал алфавит заманивший, переписали коварных.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, voluptatibus ut minus necessitatibus saepe laborum optio.</p> <p>Далеко-далеко за словесными горами в стране, гласных и согласных живут рыбные тексты. Своего дал алфавит заманивший, переписали коварных.</p> @@include('_include/demo-table.html') <p>Снова мир всемогущая, языком великий заголовок запятой его власти, рыбного последний текст, текста безорфографичный обеспечивает оксмокс.</p> <p>Ratione voluptates praesentium, earum quisquam. Animi dolorum enim quidem quae fugiat porro voluptate dolorem repellat accusantium.</p> <h2>Заголовок header</h2> <img src="img/image.jpg" alt="" class="demo-image"> <p>Далеко-далеко за словесными горами в стране, гласных и согласных живут рыбные тексты. Своего дал алфавит заманивший, переписали коварных.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, voluptatibus ut minus necessitatibus saepe laborum optio.</p> <p>Далеко-далеко за словесными горами в стране, гласных и согласных живут рыбные тексты. Своего дал алфавит заманивший, переписали коварных.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, voluptatibus ut minus necessitatibus saepe laborum optio.</p> <p>Далеко-далеко за словесными горами в стране, гласных и согласных живут рыбные тексты. Своего дал алфавит заманивший, переписали коварных.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, voluptatibus ut minus necessitatibus saepe laborum optio.</p> <h2>Заголовок header</h2> <img src="img/image.jpg" alt="" class="demo-image"> <p>Далеко-далеко за словесными горами в стране, гласных и согласных живут рыбные тексты. Своего дал алфавит заманивший, переписали коварных.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, voluptatibus ut minus necessitatibus saepe laborum optio.</p> <p>Далеко-далеко за словесными горами в стране, гласных и согласных живут рыбные тексты. Своего дал алфавит заманивший, переписали коварных.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, voluptatibus ut minus necessitatibus saepe laborum optio.</p> <p>Далеко-далеко за словесными горами в стране, гласных и согласных живут рыбные тексты. Своего дал алфавит заманивший, переписали коварных.</p> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repudiandae, voluptatibus ut minus necessitatibus saepe laborum optio.</p> </body> </html>
import product from "../models/image_models.js"; import path from 'path' import fs from 'fs' export const getData = async (req, res) => { try { const response = await product.findAll() res.status(200).json(response); } catch (error) { console.log(error) } } export const getDataById = async (req, res) => { try { const response = await product.findOne({ where: { id: req.params.id } }) res.json(response) } catch (error) { console.log(error) } } export const saveData = (req, res) => { if (req.files === null) return res.status(400).json({ msg: 'No file uploaded' }) const name = req.body.title; const file = req.files.file; const fileSize = file.data.length; const ext = path.extname(file.name); const fileName = file.md5 + ext; const url = `${req.protocol}://${req.get("host")}/images/${fileName}` const allowedType = ['.png', '.jpg', '.jpeg']; if (!allowedType.includes(ext.toLowerCase())) return res.status(422).json({ msg: 'Invalid image' }) if (fileSize > 5000000) return res.status(422).json({ mgs: 'Gambar terlalu besar!' }) file.mv(`./public/images/${fileName}`, async (err) => { if (err) return res.status(500).json({ msg: err.message }) try { await product.create({ name: name, image: fileName, url: url }); res.status(201).json({ msg: 'has been success..' }) } catch (error) { console.log(error) } }) } export const updateData = async (req, res) => { const Product = await product.findOne({ where: { id: req.params.id } }) if (!Product) return res.status(404).json({ msg: 'Data not found' }) let fileName = ""; if (req.file === null) { fileName = product.image; } else { const file = req.files.file; const fileSize = file.data.length; const ext = path.extname(file.name); fileName = file.md5 + ext; const allowedType = ['.png', '.jpg', '.jpeg']; if (!allowedType.includes(ext.toLowerCase())) return res.status(422).json({ msg: 'Invalid image' }) if (fileSize > 5000000) return res.status(422).json({ mgs: 'Gambar terlalu besar!' }) const filePath = `./public/images/${Product.image}` fs.unlinkSync(filePath) file.mv(`./public/images/${fileName}`, (err) => { if (err) return res.status(500).json({ msg: err.message }) }) } const name = req.body.title; const url = `${req.protocol}://${req.get("host")}/images/${fileName}` try { await product.update({ name: name, image: fileName, url: url }, { where: { id: req.params.id } }) res.status(200).json({ msg: 'has been updated' }) } catch (error) { console.log(error) } } export const deleteData = async (req, res) => { const Product = await product.findOne({ where: { id: req.params.id } }) if (!Product) return res.status(404).json({ msg: 'Data not found' }) try { const filePath = `./public/images/${Product.image}` fs.unlinkSync(filePath) await product.destroy({ where: { id: req.params.id } }) res.status(200).json({ msg: 'Product deleted' }) } catch (error) { console.log(error) } }
import React, { useEffect } from "react"; import { connect } from "react-redux"; import { initializeAnecdotes } from "./reducers/anecdotesReducer"; import Notification from "./components/Notification"; import Filter from "./components/Filter"; import AnecdoteForm from "./components/AnecdoteForm"; import AnecdoteList from "./components/AnecdoteList"; const App = props => { useEffect(() => { props.initializeAnecdotes(); }, [props]); return ( <> <h2>Anecdotes</h2> <Notification /> <Filter /> <AnecdoteForm /> <AnecdoteList /> </> ); }; export default connect( null, { initializeAnecdotes } )(App);
package aliyun import ( "testing" "github.com/stretchr/testify/assert" "github.com/voidint/g/pkg/errs" "github.com/voidint/g/version" ) func Test_getGoVersion(t *testing.T) { items := []*struct { In *goFileItem Expected string }{ { In: &goFileItem{ FileName: "go1.18beta1.darwin-amd64.pkg", URL: "https://mirrors.aliyun.com/golang/go1.18beta1.darwin-amd64.pkg", Size: "136.9 MB", }, Expected: "1.18beta1", }, { In: &goFileItem{ FileName: "go1.18beta2.freebsd-386.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.18beta2.freebsd-386.tar.gz", Size: "107.2 MB", }, Expected: "1.18beta2", }, { In: &goFileItem{ FileName: "go1.18rc1.darwin-amd64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.18rc1.darwin-amd64.tar.gz", Size: "107.2 MB", }, Expected: "1.18rc1", }, { In: &goFileItem{ FileName: "go1.18.windows-arm64.zip", URL: "https://mirrors.aliyun.com/golang/go1.18.windows-arm64.zip", Size: "118.0 MB", }, Expected: "1.18", }, { In: &goFileItem{ FileName: "go1.18.1.linux-386.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.18.1.linux-386.tar.gz", Size: "107.6 MB", }, Expected: "1.18.1", }, { In: &goFileItem{ FileName: "go1.18.1.src.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.18.1.src.tar.gz", Size: "21.8 MB", }, Expected: "1.18.1", }, } t.Run("从文件名中获取go版本号", func(t *testing.T) { for _, item := range items { assert.Equal(t, item.Expected, item.In.getGoVersion()) } }) } func Test_isSHA256File(t *testing.T) { items := []*struct { In *goFileItem Expected bool }{ { In: &goFileItem{ FileName: "go1.18beta1.darwin-amd64.pkg", URL: "https://mirrors.aliyun.com/golang/go1.18beta1.darwin-amd64.pkg", Size: "136.9 MB", }, Expected: false, }, { In: &goFileItem{ FileName: "go1.4-bootstrap-20170518.tar.gz.sha256", URL: "https://mirrors.aliyun.com/golang/go1.4-bootstrap-20170518.tar.gz.sha256", Size: "64.0 B", }, Expected: true, }, { In: &goFileItem{ FileName: "go1.4-bootstrap-20170518.tar.gz.sha256", URL: "https://mirrors.aliyun.com/golang/go1.4-bootstrap-20170518.tar.gz.sha256", Size: "64.0 B", }, Expected: true, }, { In: &goFileItem{ FileName: "go1.5.4.darwin-amd64.tar.gz.sha256", URL: "https://mirrors.aliyun.com/golang/go1.5.4.darwin-amd64.tar.gz.sha256", Size: "64.0 B", }, Expected: true, }, } t.Run("判断是否是SHA256校验和文件", func(t *testing.T) { for _, item := range items { assert.Equal(t, item.Expected, item.In.isSHA256File()) } }) } func Test_isPackageFile(t *testing.T) { items := []*struct { In *goFileItem Expected bool }{ { In: &goFileItem{ FileName: "go1.10.1.darwin-amd64.pkg", URL: "https://mirrors.aliyun.com/golang/go1.10.1.darwin-amd64.pkg", }, Expected: true, }, { In: &goFileItem{ FileName: "go1.10.1.darwin-amd64.pkg.sha256", URL: "https://mirrors.aliyun.com/golang/go1.10.1.darwin-amd64.pkg.sha256", }, Expected: false, }, { In: &goFileItem{ FileName: "go1.10.1.linux-amd64.tar.gz.sha256", URL: "https://mirrors.aliyun.com/golang/go1.10.1.linux-amd64.tar.gz.sha256", }, Expected: false, }, { In: &goFileItem{ FileName: "go1.10.1.linux-arm64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.10.1.linux-arm64.tar.gz", }, Expected: true, }, { In: &goFileItem{ FileName: "go1.10.1.linux-arm64.tar.gz.asc", URL: "https://mirrors.aliyun.com/golang/go1.10.1.linux-arm64.tar.gz.asc", }, Expected: false, }, { In: &goFileItem{ FileName: "go1.10.1.windows-386.msi", URL: "https://mirrors.aliyun.com/golang/go1.10.1.windows-386.msi", }, Expected: true, }, { In: &goFileItem{ FileName: "go1.10.1.windows-386.zip", URL: "https://mirrors.aliyun.com/golang/go1.10.1.windows-386.zip", }, Expected: true, }, } t.Run("判断是否是go安装包文件", func(t *testing.T) { for _, item := range items { assert.Equal(t, item.Expected, item.In.isPackageFile()) } }) } func Test_getKind(t *testing.T) { items := []*struct { In *goFileItem Expected version.PackageKind }{ { In: &goFileItem{ FileName: "go1.10.1.darwin-amd64.pkg", URL: "https://mirrors.aliyun.com/golang/go1.10.1.darwin-amd64.pkg", }, Expected: version.InstallerKind, }, { In: &goFileItem{ FileName: "go1.10.1.darwin-amd64.pkg.sha256", URL: "https://mirrors.aliyun.com/golang/go1.10.1.darwin-amd64.pkg.sha256", }, Expected: "Unknown", }, { In: &goFileItem{ FileName: "go1.10.1.linux-amd64.tar.gz.sha256", URL: "https://mirrors.aliyun.com/golang/go1.10.1.linux-amd64.tar.gz.sha256", }, Expected: "Unknown", }, { In: &goFileItem{ FileName: "go1.10.1.linux-arm64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.10.1.linux-arm64.tar.gz", }, Expected: version.ArchiveKind, }, { In: &goFileItem{ FileName: "go1.10.1.linux-arm64.tar.gz.asc", URL: "https://mirrors.aliyun.com/golang/go1.10.1.linux-arm64.tar.gz.asc", }, Expected: "Unknown", }, { In: &goFileItem{ FileName: "go1.10.1.windows-386.msi", URL: "https://mirrors.aliyun.com/golang/go1.10.1.windows-386.msi", }, Expected: version.InstallerKind, }, { In: &goFileItem{ FileName: "go1.10.1.windows-386.zip", URL: "https://mirrors.aliyun.com/golang/go1.10.1.windows-386.zip", }, Expected: version.ArchiveKind, }, { In: &goFileItem{ FileName: "go1.10.2.src.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.10.2.src.tar.gz", }, Expected: version.SourceKind, }, } t.Run("从文件名中获取文件类型", func(t *testing.T) { for _, item := range items { assert.Equal(t, item.Expected, item.In.getKind()) } }) } func Test_getOS(t *testing.T) { items := []*struct { In *goFileItem Expected string }{ { In: &goFileItem{ FileName: "go1.10.1.darwin-amd64.pkg", URL: "https://mirrors.aliyun.com/golang/go1.10.1.darwin-amd64.pkg", }, Expected: "macOS", }, { In: &goFileItem{ FileName: "go1.10.1.darwin-amd64.pkg.sha256", URL: "https://mirrors.aliyun.com/golang/go1.10.1.darwin-amd64.pkg.sha256", }, Expected: "macOS", }, { In: &goFileItem{ FileName: "go1.10.1.linux-amd64.tar.gz.sha256", URL: "https://mirrors.aliyun.com/golang/go1.10.1.linux-amd64.tar.gz.sha256", }, Expected: "Linux", }, { In: &goFileItem{ FileName: "go1.10.1.linux-arm64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.10.1.linux-arm64.tar.gz", }, Expected: "Linux", }, { In: &goFileItem{ FileName: "go1.10.1.linux-arm64.tar.gz.asc", URL: "https://mirrors.aliyun.com/golang/go1.10.1.linux-arm64.tar.gz.asc", }, Expected: "Linux", }, { In: &goFileItem{ FileName: "go1.10.1.windows-386.msi", URL: "https://mirrors.aliyun.com/golang/go1.10.1.windows-386.msi", }, Expected: "Windows", }, { In: &goFileItem{ FileName: "go1.10.1.windows-386.zip", URL: "https://mirrors.aliyun.com/golang/go1.10.1.windows-386.zip", }, Expected: "Windows", }, { In: &goFileItem{ FileName: "go1.10.2.src.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.10.2.src.tar.gz", }, Expected: "", }, { In: &goFileItem{ FileName: "go1.10.3.freebsd-386.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.10.3.freebsd-386.tar.gz", }, Expected: "FreeBSD", }, } t.Run("从文件名中获取操作系统", func(t *testing.T) { for _, item := range items { assert.Equal(t, item.Expected, item.In.getOS()) } }) } func Test_getArch(t *testing.T) { items := []*struct { In *goFileItem Expected string }{ { In: &goFileItem{ FileName: "go1.10.2.src.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.10.2.src.tar.gz", }, Expected: "", }, { In: &goFileItem{ FileName: "go1.10.1.freebsd-386.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.10.1.freebsd-386.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "x86", }, { In: &goFileItem{ FileName: "go1.10.1.freebsd-amd64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.10.1.freebsd-amd64.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "x86-64", }, { In: &goFileItem{ FileName: "go1.21.0.freebsd-arm.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.0.freebsd-arm.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "ARMv6", }, { In: &goFileItem{ FileName: "go1.20rc3.windows-arm64.msi", URL: "https://mirrors.aliyun.com/golang/go1.20rc3.windows-arm64.msi?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "ARM64", }, { In: &goFileItem{ FileName: "go1.21.0.linux-armv6l.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.0.linux-armv6l.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "ARMv6", }, { In: &goFileItem{ FileName: "go1.21.0.aix-ppc64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.0.aix-ppc64.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "ppc64", }, { In: &goFileItem{ FileName: "go1.21.0.linux-ppc64le.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.0.linux-ppc64le.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "ppc64le", }, { In: &goFileItem{ FileName: "go1.21.1.linux-mips.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.1.linux-mips.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "mips", }, { In: &goFileItem{ FileName: "go1.21.2.linux-mipsle.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.2.linux-mipsle.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "mipsle", }, { In: &goFileItem{ FileName: "go1.21.3.linux-mips64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.3.linux-mips64.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "mips64", }, { In: &goFileItem{ FileName: "go1.21.3.linux-mips64le.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.3.linux-mips64le.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "mips64le", }, { In: &goFileItem{ FileName: "go1.21.3.linux-s390x.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.3.linux-s390x.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "s390x", }, { In: &goFileItem{ FileName: "go1.21.4.freebsd-riscv64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.4.freebsd-riscv64.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "riscv64", }, { In: &goFileItem{ FileName: "go1.21.4.linux-loong64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.21.4.linux-loong64.tar.gz?spm=a2c6h.25603864.0.0.a6b07c45KMj71H", }, Expected: "loong64", }, } t.Run("从文件名中获取架构", func(t *testing.T) { for _, item := range items { assert.Equal(t, item.Expected, item.In.getArch()) } }) } func Test_convert2Versions(t *testing.T) { items := []*goFileItem{ { FileName: "go1.18.windows-arm64.zip", URL: "https://mirrors.aliyun.com/golang/go1.18.windows-arm64.zip", Size: "118.0 MB", }, { FileName: "go1.18.1.linux-386.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.18.1.linux-386.tar.gz", Size: "107.6 MB", }, { FileName: "go1.18.1.src.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.18.1.src.tar.gz", Size: "21.8 MB", }, { FileName: "go1.17.1.linux-amd64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.17.1.linux-amd64.tar.gz", Size: "128.5 MB", }, { FileName: "go1.17.1.linux-amd64.tar.gz.sha256", URL: "https://mirrors.aliyun.com/golang/go1.17.1.linux-amd64.tar.gz.sha256", Size: "64.0 B", }, } t.Run("不存在无效版本号", func(t *testing.T) { vs, err := convert2Versions(items) assert.Nil(t, err) assert.Equal(t, 3, len(vs)) assert.Equal(t, "1.17.1", vs[0].Name()) assert.Equal(t, "1.18", vs[1].Name()) assert.Equal(t, "1.18.1", vs[2].Name()) assert.Equal(t, []version.Package{ { FileName: "go1.17.1.linux-amd64.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.17.1.linux-amd64.tar.gz", Kind: version.ArchiveKind, OS: "Linux", Arch: "x86-64", Size: "128.5 MB", ChecksumURL: "https://mirrors.aliyun.com/golang/go1.17.1.linux-amd64.tar.gz.sha256", Algorithm: "SHA256", }, }, vs[0].Packages()) assert.Equal(t, []version.Package{ { FileName: "go1.18.windows-arm64.zip", URL: "https://mirrors.aliyun.com/golang/go1.18.windows-arm64.zip", Kind: version.ArchiveKind, OS: "Windows", Arch: "ARM64", Size: "118.0 MB", ChecksumURL: "", Algorithm: "", }, }, vs[1].Packages()) assert.Equal(t, []version.Package{ { FileName: "go1.18.1.linux-386.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.18.1.linux-386.tar.gz", Kind: version.ArchiveKind, OS: "Linux", Arch: "x86", Size: "107.6 MB", ChecksumURL: "", Algorithm: "", }, { FileName: "go1.18.1.src.tar.gz", URL: "https://mirrors.aliyun.com/golang/go1.18.1.src.tar.gz", Kind: version.SourceKind, OS: "", Arch: "", Size: "21.8 MB", ChecksumURL: "", Algorithm: "", }, }, vs[2].Packages()) }) t.Run("存在无效版本号", func(t *testing.T) { items = append(items, &goFileItem{ FileName: "goa.b.c.linux-amd64.tar.gz", URL: "https://mirrors.aliyun.com/golang/goa.b.c.linux-amd64.tar.gz", Size: "64.0 B", }) vs, err := convert2Versions(items) assert.Nil(t, vs) assert.True(t, errs.IsMalformedVersion(err)) }) }
import 'package:flutter/material.dart'; import 'package:post_api_with_provider/provider.dart'; import 'package:provider/provider.dart'; class LogInScreen extends StatefulWidget { const LogInScreen({super.key}); @override State<LogInScreen> createState() => _LogInScreenState(); } class _LogInScreenState extends State<LogInScreen> { TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, backgroundColor: Colors.brown, title: const Text("Login Screen", style: TextStyle(color: Colors.white),), ), body: Center( child: Padding( padding: const EdgeInsets.all(20.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextFormField( controller: emailController, decoration:const InputDecoration( hintText: "Enter email" ), ), const SizedBox(height: 10,), TextFormField( controller: passwordController, decoration: const InputDecoration( hintText: "Enter password" ), ), const SizedBox(height: 30,), SizedBox( height: 50,width: double.infinity, child: ElevatedButton( onPressed: (){ WidgetsBinding.instance.addPostFrameCallback((timeStamp) { Provider.of<ApiProvider>(context, listen: false).getData(context, emailController.text.toString(), passwordController.text.toString()); }); }, child: Provider.of<ApiProvider>(context).isLoading? const CircularProgressIndicator(): const Text("LogIn")), ) ], ), ), ), ); } }
local PARENT = SortManager ------------------------------------- -- class SortManager_Fruit -- @breif 열매 정렬 관리자 ------------------------------------- SortManager_Fruit = class(PARENT, { m_tableItem = 'TableItem', m_mAttrSortLevel = 'map', }) ------------------------------------- -- function init ------------------------------------- function SortManager_Fruit:init() self.m_tableItem = TableItem() -- 속성별 정렬 레벨 self.m_mAttrSortLevel = {} self.m_mAttrSortLevel[''] = -2 self.m_mAttrSortLevel['display'] = -1 self.m_mAttrSortLevel['reset'] = 0 self.m_mAttrSortLevel['dark'] = 1 self.m_mAttrSortLevel['light'] = 2 self.m_mAttrSortLevel['fire'] = 3 self.m_mAttrSortLevel['water'] = 4 self.m_mAttrSortLevel['earth'] = 5 self.m_mAttrSortLevel['global'] = 6 self:addSortType('grade', false, function(a, b, ascending) return self:sort_grade(a, b, ascending) end) self:addSortType('attr', false, function(a, b, ascending) return self:sort_attr(a, b, ascending) end) self:setDefaultSortFunc(function(a, b, ascending) return self:sort_fid(a, b, ascending) end) end ------------------------------------- -- function sort_attr -- @brief 속성 ------------------------------------- function SortManager_Fruit:sort_attr(a, b, ascending) local a_data = a['data'] local b_data = b['data'] local a_item = self.m_tableItem:get(a_data['fid']) local b_item = self.m_tableItem:get(b_data['fid']) local a_value = a_item['attr'] local b_value = b_item['attr'] a_value = self.m_mAttrSortLevel[a_value] b_value = self.m_mAttrSortLevel[b_value] if (a_value == b_value) then return nil end -- 오름차순 or 내림차순 if ascending then return a_value < b_value else return a_value > b_value end end ------------------------------------- -- function sort_grade -- @brief 등급 ------------------------------------- function SortManager_Fruit:sort_grade(a, b, ascending) local a_data = a['data'] local b_data = b['data'] local a_item = self.m_tableItem:get(a_data['fid']) local b_item = self.m_tableItem:get(b_data['fid']) local a_value = a_item['grade'] local b_value = b_item['grade'] if (a_value == b_value) then return nil end -- 오름차순 or 내림차순 if ascending then return a_value < b_value else return a_value > b_value end end ------------------------------------- -- function sort_fid -- @brief 열매 ID ------------------------------------- function SortManager_Fruit:sort_fid(a, b, ascending) local a_data = a['data'] local b_data = b['data'] -- 최종 정렬 조건으로 사용하기때문에 같은 경우에도 리턴함 if ascending then return a_data['fid'] < b_data['fid'] else return a_data['fid'] > b_data['fid'] end end
<template> <div> <section class="bg-info"> <div class="container"> <div class="row"> <div class="col-4 p-5"> <img class="card-img-top" :src="project.images[0].url" alt="カードの画像"> </div> <div class="col-8 bg-info p-5 align-middle"> <div class="d-flex align-items-center mb-4"> <h2 class="font-weight-bold text-white mb-0 mr-2">{{project.name}}</h2> <span class="badge badge-primary">{{statusDescription(project.status)}}</span> </div> <p class="text-white">{{project.copy}}</p> <div> <a class="badge" v-for="tag in project.tags" :href="`/language/${tag.name}`">{{tag.name}}</a> </div> </div> </div> </div> </section> <div> <b-tabs content-class="mt-3" align="center"> <b-tab title="プロジェクト概要" active> <div class="container"> <div class="mb-5"> <h3 class="font-weight-bold">プロジェクト概要</h3> <h4 class="font-weight-bold">解決したい課題</h4> <p>{{project.problem}}</p> <h4 class="font-weight-bold">サービス概要</h4> <p>{{project.solution}}</p> <h4 class="font-weight-bold">今後の課題</h4> <p>{{project.todo}}</p> </div> <div class="mb-5"> <h3 class="font-weight-bold">参考URL</h3> <a :href="project.link">{{project.name}}</a> </div> </div> </b-tab> <b-tab title="課題"> <div class="container"> <problem-card v-for="problem in project.problems" :key="problem.id" :problem="problem"/> </div> </b-tab> </b-tabs> </div> </div> </template> <script> import CodingPoint from '~/components/projects/CodingPoint.vue' import ProblemCard from '~/components/projects/ProblemCard.vue' import ReviewCard from '~/components/projects/ReviewCard.vue' import { mapGetters } from 'vuex' export default { async fetch({store, params}){ try { await store.dispatch('project/detail/init', params.id) }catch(e){ console.log("error") } }, components: { CodingPoint, ProblemCard, ReviewCard }, methods: { statusDescription(status_code){ switch (status_code) { case "PLANNIG": return "構想中" break case "CODING": return "実装中" break case "RELEASE": return "リリース済" break default: return "その他" } } }, computed: { ...mapGetters('project/detail', ['project']) } } </script> <style scoped> </style>
package dev.joseluisgs.productos.repositories import dev.joseluisgs.database.service.SqlDeLightManager import dev.joseluisgs.productos.mappers.toProducto import dev.joseluisgs.productos.model.Producto import dev.joseluisgs.productos.reposiitories.ProductosRepository import org.koin.core.annotation.Singleton import org.lighthousegames.logging.logging import java.time.LocalDateTime private val logger = logging() @Singleton class ProductosRepositoryImpl( private val dbManager: SqlDeLightManager ) : ProductosRepository { private val db = dbManager.databaseQueries /** * Obtiene todos los productos de la base de datos */ override fun findAll(): List<Producto> { logger.debug { "Obteniendo todos los productos" } return db.selectAllProductos() .executeAsList() .map { it.toProducto() } } /** * Obtiene un producto por id */ override fun findById(id: Long): Producto? { logger.debug { "Obteniendo producto por id: $id" } return db.selectProductoById(id) .executeAsOneOrNull() ?.toProducto() } /** * Obtiene productos por categoría */ override fun findByCategoria(categoria: String): List<Producto> { logger.debug { "Obteniendo productos por categoría: $categoria" } return db.selectAllProductosByCategoria(categoria) .executeAsList() .map { it.toProducto() } } /** * Guarda un producto en la base de datos */ override fun save(producto: Producto): Producto { logger.debug { "Guardando producto: $producto" } val timeStamp = LocalDateTime.now().toString() // Las transacciones son necesarias para que se hagan todas las operaciones juntas // Si no se hace así, se pueden hacer operaciones intermedias y no se garantiza la atomicidad // esto es así porque insertamos y luego seleccionamos el último insertado para el id db.transaction { db.insertProducto( nombre = producto.nombre, precio = producto.precio, stock = producto.stock.toLong(), categoria = producto.categoria.name, created_at = timeStamp, updated_at = timeStamp ) } return db.selectProductoLastInserted() .executeAsOne() .toProducto() } /** * Actualiza un producto en la base de datos */ override fun update(id: Long, producto: Producto): Producto? { logger.debug { "Actualizando producto por id: $id" } var result = this.findById(id) ?: return null val timeStamp = LocalDateTime.now() result = result.copy( nombre = producto.nombre, precio = producto.precio, stock = producto.stock, categoria = producto.categoria, isDeleted = producto.isDeleted, updatedAt = timeStamp ) db.updateProducto( nombre = result.nombre, precio = result.precio, stock = result.stock.toLong(), categoria = result.categoria.name, is_deleted = if (result.isDeleted) 1 else 0, updated_at = timeStamp.toString(), id = producto.id, ) return result } /** * Borra un producto de la base de datos */ override fun delete(id: Long): Producto? { logger.debug { "Borrando producto por id: $id" } val result = this.findById(id) ?: return null // Esto es borrado fisico, pero lo ideal sería un borrado lógico si se quiere mantener la integridad // db.deleteProducto(id) // Borrado lógico val timeStamp = LocalDateTime.now() db.updateProducto( nombre = result.nombre, precio = result.precio, stock = result.stock.toLong(), categoria = result.categoria.name, is_deleted = 1, updated_at = timeStamp.toString(), id = result.id, ) return result.copy(isDeleted = true, updatedAt = timeStamp) } }
import React, { useMemo } from 'react'; import PropTypes from 'prop-types'; import EmailVerifier from './EmailVerifier'; import TaskComplete from '../components/TaskComplete'; import ErrorBoundary from 'components/ErrorBoundary'; import { useKeyContext } from 'contexts'; Email.propTypes = { taskId: PropTypes.number.isRequired }; export default function Email({ taskId }) { const { verifiedEmail, emailMissionAttempted } = useKeyContext( (v) => v.myState ); const conditionPassed = useMemo(() => !!verifiedEmail, [verifiedEmail]); const passMessage = useMemo( () => emailMissionAttempted ? 'Congratulations on successfully setting up your own email address!' : `It looks like you already have an email address!`, [emailMissionAttempted] ); return ( <ErrorBoundary componentPath="MissionModule/Email" style={{ width: '100%' }} > {conditionPassed ? ( <TaskComplete taskId={taskId} passMessage={passMessage} /> ) : ( <EmailVerifier /> )} </ErrorBoundary> ); }
package com.controller; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.mapper.Wrapper; import com.entity.YizhuEntity; import com.entity.YonghuEntity; import com.entity.view.YizhuView; import com.service.DictionaryService; import com.service.TokenService; import com.service.YizhuService; import com.service.YonghuService; import com.utils.PageUtils; import com.utils.R; import com.utils.StringUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; /** * 医嘱 * 后端接口 * @author * @email * @date 2021-04-30 */ @RestController @Controller @RequestMapping("/yizhu") public class YizhuController { private static final Logger logger = LoggerFactory.getLogger(YizhuController.class); @Autowired private YizhuService yizhuService; @Autowired private TokenService tokenService; @Autowired private DictionaryService dictionaryService; //级联表service @Autowired private YonghuService yonghuService; /** * 后端列表 */ @RequestMapping("/page") public R page(@RequestParam Map<String, Object> params, HttpServletRequest request){ logger.debug("page方法:,,Controller:{},,params:{}",this.getClass().getName(),JSONObject.toJSONString(params)); String role = String.valueOf(request.getSession().getAttribute("role")); if(StringUtil.isNotEmpty(role) && "用户".equals(role)){ params.put("yonghuId",request.getSession().getAttribute("userId")); } params.put("orderBy","id"); PageUtils page = yizhuService.queryPage(params); //字典表数据转换 List<YizhuView> list =(List<YizhuView>)page.getList(); for(YizhuView c:list){ //修改对应字典表字段 dictionaryService.dictionaryConvert(c); } return R.ok().put("data", page); } /** * 后端详情 */ @RequestMapping("/info/{id}") public R info(@PathVariable("id") Long id){ logger.debug("info方法:,,Controller:{},,id:{}",this.getClass().getName(),id); YizhuEntity yizhu = yizhuService.selectById(id); if(yizhu !=null){ //entity转view YizhuView view = new YizhuView(); BeanUtils.copyProperties( yizhu , view );//把实体数据重构到view中 //级联表 YonghuEntity yonghu = yonghuService.selectById(yizhu.getYonghuId()); if(yonghu != null){ BeanUtils.copyProperties( yonghu , view ,new String[]{ "id", "createDate"});//把级联的数据添加到view中,并排除id和创建时间字段 view.setYonghuId(yonghu.getId()); } //修改对应字典表字段 dictionaryService.dictionaryConvert(view); return R.ok().put("data", view); }else { return R.error(511,"查不到数据"); } } /** * 后端保存 */ @RequestMapping("/save") public R save(@RequestBody YizhuEntity yizhu, HttpServletRequest request){ logger.debug("save方法:,,Controller:{},,yizhu:{}",this.getClass().getName(),yizhu.toString()); Wrapper<YizhuEntity> queryWrapper = new EntityWrapper<YizhuEntity>() .eq("yonghu_id", yizhu.getYonghuId()) ; logger.info("sql语句:"+queryWrapper.getSqlSegment()); YizhuEntity yizhuEntity = yizhuService.selectOne(queryWrapper); if(yizhuEntity==null){ yizhu.setInsertTime(new Date()); yizhu.setCreateTime(new Date()); // String role = String.valueOf(request.getSession().getAttribute("role")); // if("".equals(role)){ // yizhu.set // } yizhuService.insert(yizhu); return R.ok(); }else { return R.error(511,"表中有相同数据"); } } /** * 后端修改 */ @RequestMapping("/update") public R update(@RequestBody YizhuEntity yizhu, HttpServletRequest request){ logger.debug("update方法:,,Controller:{},,yizhu:{}",this.getClass().getName(),yizhu.toString()); //根据字段查询是否有相同数据 Wrapper<YizhuEntity> queryWrapper = new EntityWrapper<YizhuEntity>() .notIn("id",yizhu.getId()) .andNew() .eq("yonghu_id", yizhu.getYonghuId()) ; logger.info("sql语句:"+queryWrapper.getSqlSegment()); YizhuEntity yizhuEntity = yizhuService.selectOne(queryWrapper); if(yizhuEntity==null){ // String role = String.valueOf(request.getSession().getAttribute("role")); // if("".equals(role)){ // yizhu.set // } yizhuService.updateById(yizhu);//根据id更新 return R.ok(); }else { return R.error(511,"表中有相同数据"); } } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Integer[] ids){ logger.debug("delete:,,Controller:{},,ids:{}",this.getClass().getName(),ids.toString()); yizhuService.deleteBatchIds(Arrays.asList(ids)); return R.ok(); } }
import { FC, SyntheticEvent, useEffect, useState } from 'react' import Image, { ImageProps } from 'next/image' import { Nullable } from 'shared/types/common' import { WithSpring } from 'shared/lib/components' import { publicAssets } from 'shared/lib/helpers' // @ts-ignore interface NextImageProps extends ImageProps { alt?: string def?: string, src: Nullable<string> } export const NextImage: FC<NextImageProps> = ({ src: initialSrc, alt = '', onClick = () => {}, def: defaultSrc, ...props }) => { const [src, setSrc] = useState(initialSrc || publicAssets(defaultSrc)) useEffect(() => { setSrc(initialSrc || publicAssets(defaultSrc)) }, [initialSrc]) const onError = (e: SyntheticEvent<HTMLImageElement>) => { if (defaultSrc) { setSrc(publicAssets(defaultSrc)) } props.onError?.(e) } return <WithSpring key={src}> <Image src={src as string} alt={alt} fill priority={true} sizes={'100%, 100%'} onClick={onClick} {...props} onError={onError} quality={100}/> </WithSpring> }