text
stringlengths
184
4.48M
# from flask import Flask, render_template, request, jsonify # from threading import Thread # from object_detection_script import ObjectDetector # app = Flask(__name__) # # Initialize ObjectDetector without passing any arguments # detector = ObjectDetector() # @app.route("/") # def index(): # return render_template("object.html") # @app.route("/detection", methods=["POST"]) # def start_weapon_detection(): # try: # video_file = request.files["video"] # # Save the uploaded video file to a temporary location # video_path = "uploaded_video.mp4" # video_file.save(video_path) # # Run object detection in a separate thread # detection_thread = Thread( # target=detector.performObjectDetection, args=(video_path,) # ) # detection_thread.start() # return jsonify({"message": "Weapon detection started successfully!"}) # except Exception as e: # return jsonify({"error": str(e)}), 500 # if __name__ == "__main__": # app.run(debug=True) from flask import Flask, render_template, request, jsonify from threading import Thread from object_detection_script import ObjectDetector import subprocess app = Flask(__name__) # Initialize ObjectDetector without passing any arguments detector = ObjectDetector() @app.route("/") def index(): return render_template("object.html") @app.route("/detection", methods=["POST"]) def start_weapon_detection(): try: video_file = request.files["video"] # Save the uploaded video file to a temporary location video_path = "uploaded_video.mp4" video_file.save(video_path) # Run object detection in a separate thread detection_thread = Thread( target=detector.performObjectDetection, args=(video_path,) ) detection_thread.start() return jsonify({"message": "Weapon detection started successfully!"}) except Exception as e: return jsonify({"error": str(e)}), 500 @app.route('/start_weapon_detection', methods=['GET']) def start_weapon_detection_external(): try: # Call your Python script for weapon detection subprocess.run(['python', 'weapon_detection.py'], check=True) return jsonify({'message': 'Weapon detection started successfully!'}) except Exception as e: return jsonify({'error': str(e)}), 500 if __name__ == "__main__": app.run(debug=True)
# frozen_string_literal: true namespace :karafka do # Stops a given Karafka process # @param pidfile [String] path to a pidfile of a process that we're suppose to stop def stop_karafka(pidfile) # If there's no pidfile it means that Karafka is not running unless test "cat #{pidfile}" info "Karafka is not started: #{pidfile}" return end # Send a kill signal to a given process execute "kill -INT `cat #{pidfile}`" # And wait until it finishes. We wait because we don't want to start next process until # the previous one is stopped. That way we won't have problems with Kafka registering and # deregistering processes from topics (although nothing bad would happen. It would just # take more time to rebalance) loop do break unless test "cat #{pidfile}" info 'Waiting for Karafka to stop' sleep 5 end end desc 'Stop Karafka' task :stop do on roles(fetch(:karafka_role)) do for_each_karafka_process do |process_details| stop_karafka(process_details[:pidfile]) end end end end
import { useEffect, lazy, Suspense } from 'react'; import Head from '../Head/Head'; import Loading from '../Loading/Loading'; import Error from '../Error/Error'; const UserStatsGraphs = lazy(() => import('../UserStatsGraphs/UserStatsGraphs') ); import useFetch from '../../hooks/useFetch'; import { getStats } from '../../services/dogsService'; const UserStats = () => { const { data, error, loading, request } = useFetch(); useEffect(() => { const getData = async () => { const token = window.localStorage.getItem('token'); await request(getStats, token); }; getData(); }, [request]); if (loading) return <Loading />; if (error) return <Error error={error} />; if (data) return ( <Suspense fallback={<div></div>}> <Head title={'Estatisticas'} /> <UserStatsGraphs data={data} /> </Suspense> ); else return null; }; export default UserStats;
import { useCallback, useRef } from "react"; export function useClickOutsideListenerRef<T extends HTMLElement>( onClose: () => void ) { const ref = useRef<T | null>(null); const escapeListener = useCallback((e: KeyboardEvent) => { if (e.key === "Escape") onClose(); }, []); const clickListener = useCallback((e: MouseEvent) => { const clickedWithin = ref.current!.contains(e.target as any); if (!clickedWithin) onClose(); }, []); const setRefAndListeners = useCallback((value: T) => { if (value) { ref.current = value; document.addEventListener("mousedown", clickListener); document.addEventListener("keyup", escapeListener); } else { document.removeEventListener("mousedown", clickListener); document.removeEventListener("keyup", escapeListener); ref.current = null; } }, []); return setRefAndListeners; }
package com.example.bintagram.activity import android.content.Intent import android.os.Bundle import android.text.Html import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import com.example.bintagram.Models.User import com.example.bintagram.databinding.ActivitySignUpBinding import com.example.bintagram.utils.USER_NODE import com.example.bintagram.utils.USER_PROFILE_FOLDER import com.example.bintagram.utils.uploadImage import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.google.firebase.firestore.ktx.firestore import com.google.firebase.firestore.toObject import com.google.firebase.ktx.Firebase import com.squareup.picasso.Picasso class SignUpActivity : AppCompatActivity() { val binding by lazy { ActivitySignUpBinding.inflate(layoutInflater) } lateinit var user:User private lateinit var mDbRef: DatabaseReference private val launcher= registerForActivityResult(ActivityResultContracts.GetContent()){ uri-> uri?.let { uploadImage(uri, USER_PROFILE_FOLDER){ if (it!=null){ user.image=it binding.profileImage.setImageURI(uri) }else{ user.image="" } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) val text ="<font color=#FF000000>Already have an Account</font> <font color=#1E88E5>Login</font>" val text2 ="<font color=#FF000000>Already have another Account</font> <font color=#1E88E5>Logout</font>" binding.login.setText(Html.fromHtml(text)) user=User() if (intent.hasExtra("MODE")){ if (intent.getIntExtra("MODE",-1)== 1){ binding.signUpBtn.text="Update Profile" binding.login.setText(Html.fromHtml(text2)) Firebase.firestore.collection(USER_NODE).document(Firebase.auth.currentUser!!.uid).get().addOnSuccessListener { user = it.toObject<User>()!! if (!user.image.isNullOrEmpty()){ Picasso.get().load(user.image).into(binding.profileImage) } binding.name.editText?.setText(user.name) binding.email.editText?.setText(user.email) binding.password.editText?.setText(user.uid) } } } binding.signUpBtn.setOnClickListener { if (intent.hasExtra("MODE")) { if (intent.getIntExtra("MODE", -1) == 1) { Firebase.firestore.collection(USER_NODE) .document(Firebase.auth.currentUser!!.uid).set(user) .addOnSuccessListener { startActivity(Intent(this@SignUpActivity, HomeActivity::class.java)) finish() } } } else { if (binding.name.editText?.text.toString().equals("") or binding.email.editText?.text.toString().equals("") or binding.password.editText?.text.toString().equals("") ) { Toast.makeText( this@SignUpActivity, "Please fill information", Toast.LENGTH_SHORT ).show() } else { FirebaseAuth.getInstance().createUserWithEmailAndPassword( binding.email.editText?.text.toString(), binding.password.editText?.text.toString() ).addOnCompleteListener { result -> if (result.isSuccessful) { user.name = binding.name.editText?.text.toString() user.caption = "" user.email = binding.email.editText?.text.toString() user.uid = Firebase.auth.currentUser!!.uid Firebase.firestore.collection(USER_NODE) .document(Firebase.auth.currentUser!!.uid).set(user) .addOnSuccessListener { startActivity( Intent( this@SignUpActivity, HomeActivity::class.java ) ) finish() } mDbRef= FirebaseDatabase.getInstance().getReference() mDbRef.child(USER_NODE).child(Firebase.auth.currentUser!!.uid).setValue(user) } else { Toast.makeText( this@SignUpActivity, result.exception?.localizedMessage, Toast.LENGTH_SHORT ).show() } } } } } binding.addImage.setOnClickListener{ launcher.launch("image/*") } binding.login.setOnClickListener{ FirebaseAuth.getInstance().signOut() startActivity(Intent(this@SignUpActivity, LoginActivity::class.java)) finish() } } }
// To parse this JSON data, do // // final dataUser = dataUserFromJson(jsonString); import 'dart:convert'; DataUser dataUserFromJson(String str) => DataUser.fromJson(json.decode(str)); String dataUserToJson(DataUser data) => json.encode(data.toJson()); class DataUser { final Map<String, InternshipsMeta>? internshipsMeta; final List<int>? internshipIds; DataUser({ this.internshipsMeta, this.internshipIds, }); factory DataUser.fromJson(Map<String, dynamic> json) => DataUser( internshipsMeta: Map.from(json["internships_meta"]!).map((k, v) => MapEntry<String, InternshipsMeta>(k, InternshipsMeta.fromJson(v))), internshipIds: json["internship_ids"] == null ? [] : List<int>.from(json["internship_ids"]!.map((x) => x)), ); Map<String, dynamic> toJson() => { "internships_meta": Map.from(internshipsMeta!).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())), "internship_ids": internshipIds == null ? [] : List<dynamic>.from(internshipIds!.map((x) => x)), }; } class InternshipsMeta { final int? id; final String? title; final EmploymentType? employmentType; final ApplicationStatusMessage? applicationStatusMessage; final dynamic jobTitle; final bool? workFromHome; final Segment? segment; final dynamic segmentLabelValue; final dynamic internshipTypeLabelValue; final List<Segment>? jobSegments; final String? companyName; final String? companyUrl; final bool? isPremium; final bool? isPremiumInternship; final String? employerName; final CompanyLogo? companyLogo; final InternshipsMetaType? type; final String? url; final int? isInternchallenge; final bool? isExternal; final bool? isActive; final DateTime? expiresAt; final String? closedAt; final String? profileName; final bool? partTime; final StartDate? startDate; final Duration? duration; final Stipend? stipend; final dynamic salary; final dynamic jobExperience; final String? experience; final String? postedOn; final int? postedOnDateTime; final String? applicationDeadline; final String? expiringIn; final String? postedByLabel; final PostedByLabelType? postedByLabelType; final List<String>? locationNames; final List<Location>? locations; final DateTime? startDateComparisonFormat; final DateTime? startDate1; final DateTime? startDate2; final bool? isPpo; final bool? isPpoSalaryDisclosed; final dynamic ppoSalary; final dynamic ppoSalary2; final PpoLabelValue? ppoLabelValue; final bool? toShowExtraLabel; final String? extraLabelValue; final bool? isExtraLabelBlack; final List<dynamic>? campaignNames; final String? campaignName; final bool? toShowInSearch; final String? campaignUrl; final dynamic campaignStartDateTime; final dynamic campaignLaunchDateTime; final dynamic campaignEarlyAccessStartDateTime; final dynamic campaignEndDateTime; final List<LabelElement>? labels; final LabelsAppElement? labelsApp; final List<LabelsAppElement>? labelsAppInCard; final bool? isCovidWfhSelected; final bool? toShowCardMessage; final String? message; final bool? isApplicationCappingEnabled; final String? applicationCappingMessage; final List<dynamic>? overrideMetaDetails; final bool? eligibleForEasyApply; final bool? eligibleForB2BApplyNow; final bool? toShowB2BLabel; final bool? isInternationalJob; final bool? toShowCoverLetter; final String? officeDays; InternshipsMeta({ this.id, this.title, this.employmentType, this.applicationStatusMessage, this.jobTitle, this.workFromHome, this.segment, this.segmentLabelValue, this.internshipTypeLabelValue, this.jobSegments, this.companyName, this.companyUrl, this.isPremium, this.isPremiumInternship, this.employerName, this.companyLogo, this.type, this.url, this.isInternchallenge, this.isExternal, this.isActive, this.expiresAt, this.closedAt, this.profileName, this.partTime, this.startDate, this.duration, this.stipend, this.salary, this.jobExperience, this.experience, this.postedOn, this.postedOnDateTime, this.applicationDeadline, this.expiringIn, this.postedByLabel, this.postedByLabelType, this.locationNames, this.locations, this.startDateComparisonFormat, this.startDate1, this.startDate2, this.isPpo, this.isPpoSalaryDisclosed, this.ppoSalary, this.ppoSalary2, this.ppoLabelValue, this.toShowExtraLabel, this.extraLabelValue, this.isExtraLabelBlack, this.campaignNames, this.campaignName, this.toShowInSearch, this.campaignUrl, this.campaignStartDateTime, this.campaignLaunchDateTime, this.campaignEarlyAccessStartDateTime, this.campaignEndDateTime, this.labels, this.labelsApp, this.labelsAppInCard, this.isCovidWfhSelected, this.toShowCardMessage, this.message, this.isApplicationCappingEnabled, this.applicationCappingMessage, this.overrideMetaDetails, this.eligibleForEasyApply, this.eligibleForB2BApplyNow, this.toShowB2BLabel, this.isInternationalJob, this.toShowCoverLetter, this.officeDays, }); factory InternshipsMeta.fromJson(Map<String, dynamic> json) => InternshipsMeta( id: json["id"], title: json["title"], employmentType: employmentTypeValues.map[json["employment_type"]]!, applicationStatusMessage: json["application_status_message"] == null ? null : ApplicationStatusMessage.fromJson(json["application_status_message"]), jobTitle: json["job_title"], workFromHome: json["work_from_home"], segment: segmentValues.map[json["segment"]]!, segmentLabelValue: json["segment_label_value"], internshipTypeLabelValue: json["internship_type_label_value"], jobSegments: json["job_segments"] == null ? [] : List<Segment>.from(json["job_segments"]!.map((x) => segmentValues.map[x]!)), companyName: json["company_name"], companyUrl: json["company_url"], isPremium: json["is_premium"], isPremiumInternship: json["is_premium_internship"], employerName: json["employer_name"], companyLogo: companyLogoValues.map[json["company_logo"]]!, type: internshipsMetaTypeValues.map[json["type"]]!, url: json["url"], isInternchallenge: json["is_internchallenge"], isExternal: json["is_external"], isActive: json["is_active"], expiresAt: json["expires_at"] == null ? null : DateTime.parse(json["expires_at"]), closedAt: json["closed_at"], profileName: json["profile_name"], partTime: json["part_time"], startDate: startDateValues.map[json["start_date"]]!, duration: durationValues.map[json["duration"]]!, stipend: json["stipend"] == null ? null : Stipend.fromJson(json["stipend"]), salary: json["salary"], jobExperience: json["job_experience"], experience: json["experience"], postedOn: json["posted_on"], postedOnDateTime: json["postedOnDateTime"], applicationDeadline: json["application_deadline"], expiringIn: json["expiring_in"], postedByLabel: json["posted_by_label"], postedByLabelType: postedByLabelTypeValues.map[json["posted_by_label_type"]]!, locationNames: json["location_names"] == null ? [] : List<String>.from(json["location_names"]!.map((x) => x)), locations: json["locations"] == null ? [] : List<Location>.from(json["locations"]!.map((x) => Location.fromJson(x))), startDateComparisonFormat: json["start_date_comparison_format"] == null ? null : DateTime.parse(json["start_date_comparison_format"]), startDate1: json["start_date1"] == null ? null : DateTime.parse(json["start_date1"]), startDate2: json["start_date2"] == null ? null : DateTime.parse(json["start_date2"]), isPpo: json["is_ppo"], isPpoSalaryDisclosed: json["is_ppo_salary_disclosed"], ppoSalary: json["ppo_salary"], ppoSalary2: json["ppo_salary2"], ppoLabelValue: ppoLabelValueValues.map[json["ppo_label_value"]]!, toShowExtraLabel: json["to_show_extra_label"], extraLabelValue: json["extra_label_value"], isExtraLabelBlack: json["is_extra_label_black"], campaignNames: json["campaign_names"] == null ? [] : List<dynamic>.from(json["campaign_names"]!.map((x) => x)), campaignName: json["campaign_name"], toShowInSearch: json["to_show_in_search"], campaignUrl: json["campaign_url"], campaignStartDateTime: json["campaign_start_date_time"], campaignLaunchDateTime: json["campaign_launch_date_time"], campaignEarlyAccessStartDateTime: json["campaign_early_access_start_date_time"], campaignEndDateTime: json["campaign_end_date_time"], labels: json["labels"] == null ? [] : List<LabelElement>.from(json["labels"]!.map((x) => LabelElement.fromJson(x))), labelsApp: labelsAppElementValues.map[json["labels_app"]]!, labelsAppInCard: json["labels_app_in_card"] == null ? [] : List<LabelsAppElement>.from(json["labels_app_in_card"]!.map((x) => labelsAppElementValues.map[x]!)), isCovidWfhSelected: json["is_covid_wfh_selected"], toShowCardMessage: json["to_show_card_message"], message: json["message"], isApplicationCappingEnabled: json["is_application_capping_enabled"], applicationCappingMessage: json["application_capping_message"], overrideMetaDetails: json["override_meta_details"] == null ? [] : List<dynamic>.from(json["override_meta_details"]!.map((x) => x)), eligibleForEasyApply: json["eligible_for_easy_apply"], eligibleForB2BApplyNow: json["eligible_for_b2b_apply_now"], toShowB2BLabel: json["to_show_b2b_label"], isInternationalJob: json["is_international_job"], toShowCoverLetter: json["to_show_cover_letter"], officeDays: json["office_days"], ); Map<String, dynamic> toJson() => { "id": id, "title": title, "employment_type": employmentTypeValues.reverse[employmentType], "application_status_message": applicationStatusMessage?.toJson(), "job_title": jobTitle, "work_from_home": workFromHome, "segment": segmentValues.reverse[segment], "segment_label_value": segmentLabelValue, "internship_type_label_value": internshipTypeLabelValue, "job_segments": jobSegments == null ? [] : List<dynamic>.from(jobSegments!.map((x) => segmentValues.reverse[x])), "company_name": companyName, "company_url": companyUrl, "is_premium": isPremium, "is_premium_internship": isPremiumInternship, "employer_name": employerName, "company_logo": companyLogoValues.reverse[companyLogo], "type": internshipsMetaTypeValues.reverse[type], "url": url, "is_internchallenge": isInternchallenge, "is_external": isExternal, "is_active": isActive, "expires_at": "${expiresAt!.year.toString().padLeft(4, '0')}-${expiresAt!.month.toString().padLeft(2, '0')}-${expiresAt!.day.toString().padLeft(2, '0')}", "closed_at": closedAt, "profile_name": profileName, "part_time": partTime, "start_date": startDateValues.reverse[startDate], "duration": durationValues.reverse[duration], "stipend": stipend?.toJson(), "salary": salary, "job_experience": jobExperience, "experience": experience, "posted_on": postedOn, "postedOnDateTime": postedOnDateTime, "application_deadline": applicationDeadline, "expiring_in": expiringIn, "posted_by_label": postedByLabel, "posted_by_label_type": postedByLabelTypeValues.reverse[postedByLabelType], "location_names": locationNames == null ? [] : List<dynamic>.from(locationNames!.map((x) => x)), "locations": locations == null ? [] : List<dynamic>.from(locations!.map((x) => x.toJson())), "start_date_comparison_format": "${startDateComparisonFormat!.year.toString().padLeft(4, '0')}-${startDateComparisonFormat!.month.toString().padLeft(2, '0')}-${startDateComparisonFormat!.day.toString().padLeft(2, '0')}", "start_date1": "${startDate1!.year.toString().padLeft(4, '0')}-${startDate1!.month.toString().padLeft(2, '0')}-${startDate1!.day.toString().padLeft(2, '0')}", "start_date2": "${startDate2!.year.toString().padLeft(4, '0')}-${startDate2!.month.toString().padLeft(2, '0')}-${startDate2!.day.toString().padLeft(2, '0')}", "is_ppo": isPpo, "is_ppo_salary_disclosed": isPpoSalaryDisclosed, "ppo_salary": ppoSalary, "ppo_salary2": ppoSalary2, "ppo_label_value": ppoLabelValueValues.reverse[ppoLabelValue], "to_show_extra_label": toShowExtraLabel, "extra_label_value": extraLabelValue, "is_extra_label_black": isExtraLabelBlack, "campaign_names": campaignNames == null ? [] : List<dynamic>.from(campaignNames!.map((x) => x)), "campaign_name": campaignName, "to_show_in_search": toShowInSearch, "campaign_url": campaignUrl, "campaign_start_date_time": campaignStartDateTime, "campaign_launch_date_time": campaignLaunchDateTime, "campaign_early_access_start_date_time": campaignEarlyAccessStartDateTime, "campaign_end_date_time": campaignEndDateTime, "labels": labels == null ? [] : List<dynamic>.from(labels!.map((x) => x.toJson())), "labels_app": labelsAppElementValues.reverse[labelsApp], "labels_app_in_card": labelsAppInCard == null ? [] : List<dynamic>.from(labelsAppInCard!.map((x) => labelsAppElementValues.reverse[x])), "is_covid_wfh_selected": isCovidWfhSelected, "to_show_card_message": toShowCardMessage, "message": message, "is_application_capping_enabled": isApplicationCappingEnabled, "application_capping_message": applicationCappingMessage, "override_meta_details": overrideMetaDetails == null ? [] : List<dynamic>.from(overrideMetaDetails!.map((x) => x)), "eligible_for_easy_apply": eligibleForEasyApply, "eligible_for_b2b_apply_now": eligibleForB2BApplyNow, "to_show_b2b_label": toShowB2BLabel, "is_international_job": isInternationalJob, "to_show_cover_letter": toShowCoverLetter, "office_days": officeDays, }; } class ApplicationStatusMessage { final bool? toShow; final Message? message; final ApplicationStatusMessageType? type; ApplicationStatusMessage({ this.toShow, this.message, this.type, }); factory ApplicationStatusMessage.fromJson(Map<String, dynamic> json) => ApplicationStatusMessage( toShow: json["to_show"], message: messageValues.map[json["message"]]!, type: applicationStatusMessageTypeValues.map[json["type"]]!, ); Map<String, dynamic> toJson() => { "to_show": toShow, "message": messageValues.reverse[message], "type": applicationStatusMessageTypeValues.reverse[type], }; } enum Message { THE_0_APPLICANTS, THE_1_APPLICANTS, THE_2_APPLICANTS } final messageValues = EnumValues({ "0 applicants": Message.THE_0_APPLICANTS, "1 applicants": Message.THE_1_APPLICANTS, "2 applicants": Message.THE_2_APPLICANTS }); enum ApplicationStatusMessageType { HIGH_APPLICATIONS } final applicationStatusMessageTypeValues = EnumValues({ "high_applications": ApplicationStatusMessageType.HIGH_APPLICATIONS }); enum CompanyLogo { EMPTY, THE_6385_F8_A1_C006_B1669724321_PNG, THE_7_GZRSOJ5_KO8_4424_PNG } final companyLogoValues = EnumValues({ "": CompanyLogo.EMPTY, "6385f8a1c006b1669724321.png": CompanyLogo.THE_6385_F8_A1_C006_B1669724321_PNG, "7gzrsoj5ko8-4424.png": CompanyLogo.THE_7_GZRSOJ5_KO8_4424_PNG }); enum Duration { THE_2_MONTHS, THE_3_MONTHS, THE_5_MONTHS } final durationValues = EnumValues({ "2 Months": Duration.THE_2_MONTHS, "3 Months": Duration.THE_3_MONTHS, "5 Months": Duration.THE_5_MONTHS }); enum EmploymentType { INTERNSHIP } final employmentTypeValues = EnumValues({ "internship": EmploymentType.INTERNSHIP }); enum Segment { EMPTY, INTERNSHIP_FOR_WOMEN } final segmentValues = EnumValues({ "": Segment.EMPTY, "internship_for_women": Segment.INTERNSHIP_FOR_WOMEN }); class LabelElement { final List<LabelsAppElement>? labelValue; final List<LabelsAppElement>? labelMobile; final List<LabelsAppElement>? labelApp; final List<LabelsAppElement>? labelsAppInCard; LabelElement({ this.labelValue, this.labelMobile, this.labelApp, this.labelsAppInCard, }); factory LabelElement.fromJson(Map<String, dynamic> json) => LabelElement( labelValue: json["label_value"] == null ? [] : List<LabelsAppElement>.from(json["label_value"]!.map((x) => labelsAppElementValues.map[x]!)), labelMobile: json["label_mobile"] == null ? [] : List<LabelsAppElement>.from(json["label_mobile"]!.map((x) => labelsAppElementValues.map[x]!)), labelApp: json["label_app"] == null ? [] : List<LabelsAppElement>.from(json["label_app"]!.map((x) => labelsAppElementValues.map[x]!)), labelsAppInCard: json["labels_app_in_card"] == null ? [] : List<LabelsAppElement>.from(json["labels_app_in_card"]!.map((x) => labelsAppElementValues.map[x]!)), ); Map<String, dynamic> toJson() => { "label_value": labelValue == null ? [] : List<dynamic>.from(labelValue!.map((x) => labelsAppElementValues.reverse[x])), "label_mobile": labelMobile == null ? [] : List<dynamic>.from(labelMobile!.map((x) => labelsAppElementValues.reverse[x])), "label_app": labelApp == null ? [] : List<dynamic>.from(labelApp!.map((x) => labelsAppElementValues.reverse[x])), "labels_app_in_card": labelsAppInCard == null ? [] : List<dynamic>.from(labelsAppInCard!.map((x) => labelsAppElementValues.reverse[x])), }; } enum LabelsAppElement { INTERNATIONAL, INTERNSHIP } final labelsAppElementValues = EnumValues({ "International": LabelsAppElement.INTERNATIONAL, "Internship": LabelsAppElement.INTERNSHIP }); class Location { final String? string; final String? link; final Country? country; final String? region; final String? locationName; Location({ this.string, this.link, this.country, this.region, this.locationName, }); factory Location.fromJson(Map<String, dynamic> json) => Location( string: json["string"], link: json["link"], country: countryValues.map[json["country"]]!, region: json["region"], locationName: json["locationName"], ); Map<String, dynamic> toJson() => { "string": string, "link": link, "country": countryValues.reverse[country], "region": region, "locationName": locationName, }; } enum Country { INDIA, PHILIPPINES } final countryValues = EnumValues({ "India": Country.INDIA, "Philippines": Country.PHILIPPINES }); enum PostedByLabelType { INFO, SUCCESS } final postedByLabelTypeValues = EnumValues({ "info": PostedByLabelType.INFO, "success": PostedByLabelType.SUCCESS }); enum PpoLabelValue { WITH_JOB_OFFER } final ppoLabelValueValues = EnumValues({ "With job offer": PpoLabelValue.WITH_JOB_OFFER }); enum StartDate { STARTS_IMMEDIATELY } final startDateValues = EnumValues({ "Starts Immediately": StartDate.STARTS_IMMEDIATELY }); class Stipend { final String? salary; final dynamic tooltip; final int? salaryValue1; final dynamic salaryValue2; final SalaryType? salaryType; final Currency? currency; final Scale? scale; final bool? largeStipendText; Stipend({ this.salary, this.tooltip, this.salaryValue1, this.salaryValue2, this.salaryType, this.currency, this.scale, this.largeStipendText, }); factory Stipend.fromJson(Map<String, dynamic> json) => Stipend( salary: json["salary"], tooltip: json["tooltip"], salaryValue1: json["salaryValue1"], salaryValue2: json["salaryValue2"], salaryType: salaryTypeValues.map[json["salaryType"]]!, currency: currencyValues.map[json["currency"]]!, scale: scaleValues.map[json["scale"]]!, largeStipendText: json["large_stipend_text"], ); Map<String, dynamic> toJson() => { "salary": salary, "tooltip": tooltip, "salaryValue1": salaryValue1, "salaryValue2": salaryValue2, "salaryType": salaryTypeValues.reverse[salaryType], "currency": currencyValues.reverse[currency], "scale": scaleValues.reverse[scale], "large_stipend_text": largeStipendText, }; } enum Currency { INR } final currencyValues = EnumValues({ "INR ": Currency.INR }); enum SalaryType { FIXED } final salaryTypeValues = EnumValues({ "fixed": SalaryType.FIXED }); enum Scale { PERMONTH } final scaleValues = EnumValues({ "permonth": Scale.PERMONTH }); enum InternshipsMetaType { REGULAR, VIRTUAL } final internshipsMetaTypeValues = EnumValues({ "regular": InternshipsMetaType.REGULAR, "virtual": InternshipsMetaType.VIRTUAL }); class EnumValues<T> { Map<String, T> map; late Map<T, String> reverseMap; EnumValues(this.map); Map<T, String> get reverse { reverseMap = map.map((k, v) => MapEntry(v, k)); return reverseMap; } }
<!DOCTYPE ARTICLE PUBLIC "-//OASIS//DTD DocBook V4.1//EN"> <article lang="sl" id="index"> <articleinfo> <title>Muttprint -- Navodila za uporabo</title> <author> <firstname>Bernhard</firstname> <surname>Walle</surname> <affiliation> <address><email>Bernhard.Walle@gmx.de</email></address> </affiliation> </author> <pubdate>2003-05-27</pubdate> <releaseinfo>Verzija 0.71</releaseinfo> <copyright> <year>2000-2003</year> <holder role="mailto:Bernhard.Walle@gmx.de">Bernhard Walle</holder> </copyright> </articleinfo> <sect1 id="about"> <title>O Muttprint-u</title> <para>Tiskanje po&scaron;te iz programa Mutt (ter mnogo ostalie email klientov) se opravi kot ``plain text''. Navadno je to dovolj, vendar po mojem mnenju ni tako lepo kot formatirano tiskanje, n.&nbsp;p. iz <application>Netscape-a</application>.</para> <para>Drugo dejstvo, ki me moti: Tiskanje vsebuje vse prikazane dele informacij glave. Sam sem ponastavil Mutt tako, da prikazuje stvari kot <quote>X-Mailer</quote>, toda no&ccaron;em, da to tudi natisne. <application>XFMail</application> je &scaron;e huj&scaron;i: Natisne vse informacije v glavi, tako, da je tiskanje po mojem neuporabno.</para> <para>Nekaj &ccaron;asa sem imel idejo, da sam napi&scaron;em skripto, ki kreira lepo tiskanje. In tu je rezultat. Menim, da izgleda bolje kot navaden ASCII tekst ter je primerljivo z tiskanjem bolje znanih po&scaron;tnih odjemalcev pod Mirkosoft Windos..</para> </sect1> <sect1 id="installation"> <title>Namestitev</title> <sect2 id="sysreq"> <title>Zahteve za namestitev</title> <para>Muttprint je bil realiziran v programskem jeziku <emphasis>Perl</emphasis>, ki zahteva delujo&ccaron; Perl interpreter verzije 5. Ta naj bi bil &zcaron;e privzeto na vsakem Linux sistemu.</para> <para>Prepri&ccaron;ajte se, da imate na sistemu name&scaron;&ccaron;en LaTeX (priporo&ccaron;am teTeX verzijo vi&scaron;jo od 1.0) ter programe <emphasis>psselect</emphasis> ter <emphasis>psnup</emphasis> iz paketa <emphasis>PS-Utils</emphasis> Zadnja dva sta potrebna le &ccaron;e ho&ccaron;ete uporabljati "paper save mode" ter/ali obojestransko (duplex) tiskanje; ter nista obvezna &ccaron;e imete CUPS ter ste nastavili Muttprint da ga uporablja , glej <xref linkend="printcommand">.</para> <para>Vse zahtevani LaTeX paketi so vklju&ccaron;eni v teTeX-u. &Ccaron;e &zcaron;elite uporabljati drugo LaTeX distribucijo preberite datoteko <filename>README.latex</filename>, ki vsebuje informacije o vseh zahtevanih paketih. Namestiti morate vse pakete, ki niso prisotni na va&scaron;em sistemu.</para> <para>Za raz&ccaron;lenitev datuma, Muttprint uporablja Perl-ov modul <application>Date::Parse</application><footnote> <para> <ulink url="http://www.cpan.org/authors/id/GBARR/TimeDate-1.10.tar.gz"></ulink> </para> </footnote> <footnote><para>Detajle o namestitvi boste na&scaron;li v datoteki sami. Navadno bi moralo delti z uporabo naslednje procedure:</para> <para> <prompt>$ </prompt><userInput>tar xvfz Time-Date-1.10.tar.gz</userinput> </para> <para> <prompt>$ </prompt><userinput>perl Makefile.PL</userinput> </para> <para> <prompt>$ </prompt><userinput>make</userinput> </para> <para> <prompt>$ </prompt><userinput>make test</userinput> </para> <para> <prompt># </prompt><userinput>make install</userinput> </para> </footnote>. &Ccaron;e modul ni name&scaron;&ccaron;en, bo Muttprint delal brez problemov razen funkcije za pretvorbo &ccaron;asovnega pasu ter izpisa datuma v lokalnem jeziku, glej <xref linkend="date">.</para> <para>Da bi imeli podporo nabora znakov UTF-8 mora LaTeX podpirati ukaze za spreminjane podpore v UTF-8. To je navadno ni prednastavljeno! Primerne dodatke boste na&scaron;li na CTAN. Le downloadajte datoteko <ulink url="ftp://ftp.dante.de/tex-archive/macros/latex/contrib/supported/unicode.tar.gz"></ulink> ter jo namestite kot je opisano v datoteki <filename>INSTALL</filename> v paketu samem. UTF-8 podporo potrebujete samo, &ccaron;e va&scaron; po&scaron;tni odjemalec po&scaron;ilja Muttprint-u podatke zapisane v UTF-8.</para> </sect2> <sect2> <title>Namestitev datotek na va&scaron;em ra&ccaron;unalniku</title> <sect3> <title>Ro&ccaron;na namestitev</title> <para>Najprej morate razpakirati arhiv. To lahko naredite z ukazom </para> <para> <prompt>$ </prompt> <UserInput>tar xvfz muttprint-<replaceable>Verzija</replaceable>.tar.gz</UserInput> </para> <para>Premaknite se v direktorij, ki je bil ustvarjen:</para> <para> <prompt>$ </prompt> <UserInput>cd muttprint-<Replaceable>Verzija</Replaceable></UserInput> </para> <para>Tam najdete prilo&zcaron;en primeren <Filename>Makefile</Filename> za Muttprint. Za prilagoditev lokacij na va&scaron;em sistemu, uredite Makefile z va&scaron; priljubljen urejevalnik teksta.</para> <para>Za instalacijo programa boste potrebovali dovoljenja Root-a, do katerih lahko pridete z uporabo ukaza <command>su</command>, ter nadaljujete namestitev z</para> <para> <prompt># </prompt> <UserInput>make install</UserInput> </para> <para>Skripta bi sedaj morala delati.</para> <para>&Ccaron;e bi kasneje radi odstranili Muttprint ter imate &scaron;e vse datoteke na isti lokaciji enostavno izvr&scaron;ite ukaz</para> <para> <prompt># </prompt> <UserInput>make uninstall</UserInput> </para> <para>kot root.</para> </sect3> <sect3> <title>Namestitev paketov</title> <para>&Ccaron;e va&scaron;a distribucija uporablja sistem za vzdr&zcaron;evanje paketov kot je RPM ali DPKG, je verjetno dobra ideja uporabiti pripadajo&ccaron;i paket. Najve&ccaron;ja prednost tega je enostavna odstranitev.</para> <para>Ve&ccaron;ina Linux distribucij uporablja RPM sistem urejanja paketov. Najla&zcaron;ji na&ccaron;in in&scaron;talacije paketa je z ukazom</para> <para> <prompt># </prompt> <userinput>rpm -Uvh muttprint-<replaceable>Verzija</replaceable>-<replaceable>Release</replaceable>.noarch.rpm </userinput> </para> <para>Vsi RPM paketi so podpisani z mojim GnuPG-Key (ID DDAF6454). Ve&ccaron; informacij o RPM ter verifikaciji podpisov dobite tule: <ULink url="http://www.rpm.org/maximum-rpm.ps.gz">Maximum RPM</ULink>.</para> <para>Pakete za Debian ustvarja Ren&eacute; Enelhard <email>rene@debian.org</email> ter so navadno dosegljivi nekaj dni po novi izdaji Muttprint-a. Te lahko namestite z</para> <para> <prompt># </prompt> <UserInput>dpkg -i muttprint_[verzija]-[release]_all.deb</UserInput> </para> <para>Oglejte si <ulink url="http://www.debian.org/devel/">Debian <quote>Developer's Corner</quote></ulink> za ve&ccaron; informacij o Debianovih paketih.</para> <para>Druga mo&zcaron;nost namestitve Debianovih paketov je <command>apt-get</command>.</para> </sect3> </sect2> <sect2> <title>Integracija Muttprint-a v po&scaron;tne ter novi&ccaron;arske kliente</title> <para>Muttprint je bil prvotno razvit za uporabo skupaj le z programom Mutt. Toda brez problema lahko se ga integrira tudi v slede&ccaron;e po&scaron;tne programe. Dobil sem opise uporabnikov. Muttprint bo tudi v prihodnje deloval neodvisno od Mutt-a.</para> <sect3 id="muttconfig"> <title>Mutt</title> <para>Spremeniti morate naslednjo vrstico v datoteki <Filename>$HOME/.muttrc</Filename> ali globalni datoteki <FileName>##SYSCONFDIR##/Muttrc</FileName>:</para> <ProgramListing>set print_command="muttprint"</ProgramListing> <para>Prepri&ccaron;ati se morate tudi, da ignorira nepotrebne dele glave ko se email natisne. Najla&zcaron;ji na&ccaron;in za to je, da napi&scaron;ete makro (v va&scaron;em <filename>~/.muttrc</filename>) ki se prepri&ccaron;a, da so deli glave izpu&scaron;&ccaron;eni. Samo najbolj pomembni deli glave so dejansko natisnjeni (glej <xref linkend="printedheaders">).</para> <para>Tule je makro:</para> <programlisting> # Ignoriraj celo glavo macro index p "&lt;display-toggle-weed&gt; &lt;print-message&gt; &lt;display-toggle-weed&gt; &lt;exit&gt;" macro pager p "&lt;display-toggle-weed&gt; &lt;print-message&gt; &lt;display-toggle-weed&gt;" </programlisting> <para>Na za&ccaron;etku makro zamenja stanje, kjer so vsi deli glave vidni , nato se po&scaron;ta natisne in na kncu se glava nastavi nazaj. Nujno je da se izklju&ccaron;i potrjevanje tiskanja, tako da makro dela v redu:</para> <programlisting> # No confirmation before printing set print="yes" </programlisting> <para>Da natisnete ve&ccaron; kot en mail normalno v enem koraku, dodajte naslednji vnos:</para> <ProgramListing> # Print every mail extra set print_split </ProgramListing> <para>Ve&ccaron; informacij o Mutt-i boste na&scaron;li v njegovi dokumentaciji (<Filename>##DOCDIR##/mutt/manual.txt(.gz)</Filename>).</para> </sect3> <sect3> <title>Slrn</title> <para>Enostavno dodajte naslednje vrstice v va&scaron;o konfiguracijsko datoteko <filename>~/.slrnrc</filename>:</para> <programlisting> % Use Muttprint for printing set printer_name "muttprint" </programlisting> <para>&Ccaron;e bi moral muttprint natisniti ve&ccaron; delov glave kot jih je prikazanih na zaslonu boste morali namesto normalnega ukaza za tiskanje <keycap>y</keycap> uporabiti kombinacijo <keycap>Esc</keycap>, <keycap>1</keycap>, <keycap>y</keycap> (eno za drugim). To je pomembno za tiskanje X-Face glave glej <xref linkend="xface">.</para> </sect3> <sect3> <title>XFMail</title> <para>V dialogu <GUImenu>Misc</GUImenu>, <GUImenuItem>Config Misc</GUImenuItem> morate dodati vnost v <GUIlabel>Print Command</GUIlabel>: <literal>##BINDIR##/muttprint -f $f</literal>.</para> <Note> <para>Pri nekaterih verzijah <Application>XFMail</Application>, se pojavijo problemi ker XFMail ne doda glave pri tiskanju. To ni problem Muttprint-a. Da re&scaron;ite ta problem lahko poi&scaron;&ccaron;ete novej&scaron;o verzijo XFMail-a, ki nima te napake.</para> <para>Glej tudi <ulink url="http://slappy.org/listarchives/xfmail/2001-June/002398.html"> XFMail arhiv liste razvijalcev programa</ulink> za re&scaron;itev.</para> </Note> </sect3> <sect3> <title>Pine</title> <para>Vnesite ukaz za tiskanje <literal>muttprint</literal> v <GUIlabel>Setup</GUIlabel>, <GUIlabel>Printer</GUIlabel>, <GUIlabel>Personally select print command</GUIlabel>. Save the changes.</para> </sect3> <sect3> <title>Sylpheed</title> <para>Za uporabo Muttprint-a kot stalni program za tiskanje pokli&ccaron;ite <GUImenu>Configuration</GUImenu>, <GUImenuItem>Common preferences</GUImenuItem>, <GUIlabel>Other</GUIlabel>, <GUIlabel>Printing</GUIlabel> ter vnos <literal>muttprint -f %s</literal>.</para> </sect3> <sect3> <title>Gnus</title> <para>Muttprint lahko integrirate tudi v <application>Gnus</application>. Dobil sem Lisp kodo od uporabnika ki realizira integracijo. Prosim, da mi o tem ne postavljate vpra&scaron;anj, ker Lisp-a ne pounam in sam ne uporabljam <application>(X)Emacs</application>.</para> <para>Kodo najdete v <filename>README.Gnus</filename> ter bi vas rad usmeril za navodila v tej datoteki. &Ccaron;e uporabljate za namestitev pakete boste datoteko na&scaron;li v direktoriju <filename>##DOCDIR##/muttprint/</filename> .</para> </sect3> <sect3> <title>Exmh</title> <para>Najprej izberite <GUIlabel>Preferences</GUIlabel>, nato <GUIlabel>Text Print Command</GUIlabel> ter nastavite <GUIlabel>Text Print Command</GUIlabel> na <literal>muttprint -f $file</literal>.</para> </sect3> <sect3> <title>Ostali po&scaron;tni klienti</title> <para>Muttprint deluje teoreti&ccaron;no z vsemi programi za po&scaron;to, &ccaron;e le-ti lahko ustrezajo naslednjim pogojem:</para> <ItemizedList spacing="compact"> <listitem> <Para>Izhodni tekst mora biti navaden ASCII tekst brez kakr&scaron;negakoli formatiranja.</Para> </listitem> <listitem> <Para>Mora vam omogo&ccaron;ati prosto izbio ukaza za tiskanje.</Para> </listitem> </ItemizedList> <para>Tudi programi za branje novic so podprti, ker polje <ComputerOutput>To</ComputerOutput> v glavi ni obvezno ter je <ComputerOutput>Newsgroups</ComputerOutput> polje glave tudi uporabljeno.</para> <para>&Ccaron;e uporabljate Muttprint z drugimi programi kot so omenjeni zgoraj, prosim da mi po&scaron;ljete kratko sporo&ccaron;ilo, kjer opi&scaron;ete kako ste nastavili program. Tako bom tu lahko dodal opise.</para> </sect3> </sect2> </sect1> <sect1 id="config"> <title>Nastavitve</title> <sect2> <title>Konfiguracijska datoteka</title> <para>Nekatere stvari se da nastaviti v Muttprint-u. To se lahko za stalno naredi v konfiguracijski datoteki <filename>$HOME/.muttprintrc</filename> (samo za tega uporabnika) ali <filename>##SYSCONFDIR##/Muttprintrc</filename> (globalno za vse uporabnike). Uporabni&scaron;ke nastavitve prevladajo nad globalnimi.</para> <para>Lahko tudi nastavite dodatno konfiguracijsko datoteko z paramtrom <option>-r <replaceable>filename</replaceable></option> . Ta datoteka je prebrana na koncu in prepi&scaron;e opcije napisena v ukazni vrstici. Ta dodatna konfiguracijska datoteka je uporabna &ccaron;e imate ve&ccaron; konfiguracij ter jih lahko nastavite skupaj z <emphasis>Hooks</emphasis> v Mutt-u.</para> <para>Konfiguracijska datoteka je oblikovana na tak na&ccaron;in, da so vrednosti dodeljene razli&ccaron;nim variablam -- to se razlikuje od <filename>.muttrc</filename>. Ime variable je postavljeno najprej ter je ob&ccaron;utljivo na male/velike &ccaron;rke. Nato sleid ena&ccaron;aj (<literal>=</literal>) brez presledkov. Na koncu je vrednost. Narekovaji (<literal>'</literal> ali <literal>"</literal>) so neobvezni.</para> <para>Primer konfiguracijske datoteke je prilo&zcaron;en Muttprint-u (<filename>sample-muttprintrc</filename>). &Ccaron;e ste namestili RPM ali Debian paket, jo boste na&scaron;li v <filename>##DOCDIR##/muttprint/</filename>.</para> <para>Primer pravilne dodelitve:</para> <ProgramListing>VARIABLE=value</ProgramListing> <para>Navadno skripta deluje brez vseh sprememb. Toda priporo&ccaron;eno je ,da se informirate o mo&zcaron;nostih, ki jih imate.</para> <sect3> <title>Tiskalnik</title> <para>&Ccaron;e naj Muttprint nebi tiskal na privzeti tiskalnik, potem spremenite to nastavitev <literal>PRINTER</literal> in jo nastavite na pravilno vrednost.</para> <para>Da bi tiskali v datoteko lahko uporabite naslednjo sintakso: ime (ter lokacijo) datoteke lahko prosto izberete:</para> <ProgramListing>PRINTER="TO_FILE:/foo/bar/test.ps"</ProgramListing> <para>&Ccaron;e ima tiskalnik omogo&ccaron;eno obojestransko tiskanje, Muttprint ustvari drugo datoteko z predpon <filename>2</filename>, npr. <filename>test2.ps</filename>.</para> <para>&Ccaron;e variabla ni nastavljena, Muttprint oceni spremenljivko okolja <envar>PRINTER</envar> ter uporabi njeno vrednost da dobi pravi tiskalnik. Navadno je ta nastavljena na privzeti tiskalnik. &Ccaron;e uporabljate CDE (kar je v navadi pri komercialnih Unix sistemih) je njegova konfiguracijska datoteka prebrana za privzeti tiskalnik.</para> <para>Od verzije 0.70 dalje Muttprint nudi direktno podporo novega sistema za tiskanje CUPS. Vklopi se ga tako, da se nastavi <literal>PRINT_COMMAND</literal> na <literal>CUPS</literal>. Alternativno lahko nastavite arbitrarni ukaz ki vsebuje niz <literal>$CUPS_OPTIONS</literal> kateri je zamenjan z CUPS mo&zcaron;nostmi tiskanja.</para> <tip> <para>Lahko uporabite nastavitve <literal>gv -</literal> da dobite predogled tiskanja. To je uporabno, &ccaron;e &zcaron;elite testirati razne nastavitve. </para> </tip> </sect3> <sect3 id="printcommand"> <title>Ukaz za tiskanje</title> <para>Muttprint za privzeto uporablja <application>lpr</application> za tiskanje. &Ccaron;e bi radi uporabljali kak drug ukaz za tiskanje, nastavite <literal>PRINT_COMMAND</literal> na &zcaron;eljeni ukaz. Niz <literal>$PRINTER</literal> je zamenjan z &zcaron;eljnim tiskalnikom. Provzeto je nastavljen na <literal>lpr -P$PRINTER</literal>. </para> <tip> <para>Uporabite lahko tudi nastavitev <literal>gv -</literal> za predogled tiskanja. To je uporabno &ccaron;e &zcaron;lite testirati razne nastavitve. </para> </tip> </sect3> <sect3> <title>Pingvin</title> <para>Kot privzeto nastavitev se majhen pingvin natisne v desni zgornji kot strani. &Ccaron;e bi tam &zcaron;eleli imeti drugo sliko ali &ccaron;e je pingvin na drugi lokaciji kot to predvideva Muttprint lahko to nastavite z varablo <literal>PENGUIN</literal> Slika mora biti v obliki Encapsulated PostScript (lahko uporabite <command>convert</command> iz paketa <application>Image Magick</application> za pretvarjanje va&scaron;e priljubljene slike v EPS) ter je velikosti vi&scaron;ine 2&nbsp;cm (5.08 in). Logotip ne sme biti &scaron;ir&scaron;i kot je njegova vi&scaron;ina.</para> <para>&Ccaron;e <literal>PENGUIN=on</literal>, Muttprint poskusi najti lokacijo datoteke s pingvinom. (Preberite izvorno kodo, da izveste kje Muttprint i&scaron;&ccaron;e.) To je privzeta nastavitev.</para> <para>Poleg tega pri Muttprint-u najdete tudi dodatne primere slik ki so &zcaron;e spremenjene v EPS format. Po namestitvi jih boste na&scaron;li v <filename>##SHAREDIR##/muttprint</filename>.</para> <para>&Ccaron;e naj bi bilo tiskanje slik izklopljeno nastavite vrednost <literal>PENGUIN</literal> na <literal>off</literal>. </para> </sect3> <sect3 id="xface"> <title>Tiskanje X-Faces</title> <para>X-Faces so &ccaron;rno-bele slike velikosti 48 x 48 pikslov ki so lahko vklju&ccaron;ene v glavi emaila (<literal>X-Face:</literal> glava) v vsakem sporo&ccaron;ilu. To ni <quote>uradni</quote> standard toda je raz&scaron;irjen, &scaron;e posebno v novi&ccaron;arskih skupinah.</para> <para>Muttprint podpira tiskanje te slike namesto slike podane v spremenljivki <literal>PENGUIN</literal>. Da to omogo&ccaron;ite, nastavite <literal>XFACE</literal> na <literal>on</literal>. &Ccaron;e ni take glave bo natisnjena slika <literal>PENGUIN</literal> (ali prazno) .</para> <para>Da to pravilno deluje potrebujete dva programa:</para> <itemizedlist spacing="compact"> <listitem> <para> <application>convert</application> iz <ulink url="http://www.imagemagick.org">paketa <application>Image Magick</application> </ulink> </para> </listitem> <listitem> <para> <ulink url="http://www.ibiblio.org/pub/Linux/apps/graphics/convert/compface-1.4.tar.gz"><application>uncompface</application></ulink> </para> </listitem> </itemizedlist> <para>Oba programa naj bi bila del osnovne Linux distribucije ter sta enostavno name&scaron;&ccaron;ena.</para> <para>V vsakem primeru se morate prepri&ccaron;ati da je ta del glave res poslan v Muttprint. &Ccaron;e uporabljate Mutt, glej <xref linkend="muttconfig"> za pravilne nastavitve. V drugih primerih pa si preberite dokumentacijo va&scaron;ega programa za po&scaron;to.</para> </sect3> <sect3> <title>Obojestransko tiskanje</title> <para>Muttprint dovoli ro&ccaron;no obojestransko tiskanje. NAtisne najprej lihe strani, po&ccaron;aka nekaj &ccaron;asa ter natisne &scaron;e sode.</para> <para>Muttprint potrebuje hitrost va&scaron;ega tiskalnika, da izra&ccaron;una &ccaron;as ko se bo tiskanje sodih strani za&ccaron;elo, glej, <xref linkend="speed">.</para> <para>Za aktivacijo obojestranskega tiskanja nastavite <literal>DUPLEX</literal> na <literal>on</literal>.</para> <para>&Ccaron;e imate pravi Postscript tiskalnik ki ima mo&zcaron;nost obojestranskega tiskanja, potem nastavite <literal>DUPLEX</literal> na <literal>printer</literal>. To spremeni Postscript kodo na tak na&ccaron;in, da sporo&ccaron;i va&scaron;em printerju, da naj vklju&ccaron;i avtomatsko obojestransko tiskanje; za CUPS se uporabi pripadajo&ccaron;a opcija.</para> </sect3> <sect3> <title>Na&ccaron;in za ohranjevanje papirja</title> <para>Lahko natisnete dve strani na eno stran v "landscape" na&ccaron;inu. To vam omogo&ccaron;a prihranek papirja ter &ccaron;rnila ter pove&ccaron;a hitrost tiskanja. Tak&scaron;no delovanje je smselno le z papirjem ormata DIN A4 ker dve pomanj&scaron;ani strani pa&scaron;eta to&ccaron;no na en list.</para> <para>Da omogo&ccaron;ite ta na&ccaron;in nastavite <literal>PAPERSAVE</literal> na <literal>on</literal>.</para> <para>&Ccaron;e &zcaron;elite na&ccaron;in za ohranjevanje papirja vklju&ccaron;iti le &ccaron;e se natisne ve&ccaron; kot ena stran nastavite <literal>PAPERSAVE</literal> na <literal>optional</literal>. </para> </sect3> <sect3 id="date"> <title>Datum</title> <para>Opcija <literal>DATE</literal> omogo&ccaron;a dve nastavitvi: <literal>original</literal> ter <literal>local</literal>. &Ccaron;e nastavite na <literal>original</literal>, Muttprint natisne datum nespremenjeno, kot je v glavi po&scaron;te, npr. v angle&scaron;&ccaron;ini ter v po&scaron;iljateljevem &ccaron;asovnem pasu.</para> <para>&Ccaron;e nastavite to mo&zcaron;nost na <literal>local</literal>, Muttprint spremeni &ccaron;asovni pas na &ccaron;asovni pas ssistema ter natisne datum v lokalnem jeziku <footnote> <para>To deluje neodvisno od datoteke s prevodom z uporabo funkcij operacijskega sistema. Navkljub temu <literal>LANG</literal> (glej <xref linkend="lang">) v konfiguracijski datoteki vpliva na jezik v datumu.</para> </footnote>.</para> <para>Format datuma lahko podate tudi z spremeljivko <literal>DATE_FORMAT</literal>. Argument je formatiran niz, npr. <literal>"%A, %d. %B %Y %H:%M:%S"</literal>. Narekovaji so obvezni, ker niz vsebuje presledke. <citerefentry><refentrytitle>strftime</refentrytitle> <manvolnum>3</manvolnum></citerefentry> manpage vsebuje detajle o njem.</para> </sect3> <sect3> <title>Format natisnjenega email naslova</title> <para>Obstaja ve&ccaron; na&ccaron;inov pisanja email naslova ter imena skupaj v glavi sporo&ccaron;ila. Tu je nekaj primerov:</para> <ItemizedList spacing="compact"> <ListItem><para><literal>Bernhard Walle &lt;Bernhard.Walle@gmx.de&gt; </literal></para></ListItem> <ListItem><para><literal>"Bernhard Walle &lt;Bernhard.Walle@gmx.de&gt; </literal></para></ListItem> <ListItem><para><literal>Bernhard.Walle@gmx.de (Bernhard Walle) </literal></para></ListItem> </ItemizedList> <para>Uporabljen format je odvisen od programa za po&scaron;to po&scaron;iljatelja; vsi trije so pravilni. &Ccaron;e je spremenljivka <literal>ADDRESSFORMAT</literal> nastavljena na vrednost <literal>original</literal>, je naslov natisnjen nespremenjen.</para> <para>&Ccaron;e bi &zcaron;eleli konstantno glavo e-maila lahko dodelite format niza tej spremenljivki. Privzeta nastavitev je <literal>"%r &lt;%a&gt;,\n"</literal>. Uporabite lahko vse znake kot obliko niza, <literal>%r</literal> je zamenjan z imenom (<quote>pravo ime</quote>), <literal>%a</literal> z email naslovom ter <literal>\n</literal> natisne novo vrstico. Mejniu narekovaji so nujni zaradi presledkov. Znak za novo vrstico pomeni, da je vsak naslov natisnjen v svojo vrstico, &ccaron;e je podan ve&ccaron; kot en naslov. Muttprint odstrani znake za novo vrstico in vejice po zadnjem obdelanem naslovu.</para> <para>Dodatno se lahko dolo&ccaron;eni deli natisnejo krepko ali po&scaron;even tekst. &Ccaron;e je del omejen z zvezdicami (<literal>*</literal>), je tekst krepek; po&scaron;evnice (<literal>/</literal>) pomenijo po&scaron;even tekst; mo&zcaron;no je tudi gnezdenje.</para> <para>tu je drug primer uporabe formatiranega niza (tega uporabljam tudi sam): <literal>"/%r/ (%a),"</literal>.</para> </sect3> <sect3 id="speed"> <title>Hitrost tiskanja</title> <para>Kot omenjeno zgoraj, Muttprint zahteva podatek o trajanju v katerem va&scaron; tiskalnik natisne eno stran. Ta nastavitev se spremeni z nastavitvijo spremenljivke <literal>SPEED</literal> na vrednost &ccaron;asa v sekundah (samo cela &scaron;tevila so dovoljena). Privzeto je nastavljeno na 30&nbsp;sekund (<literal>SPEED=30</literal>).</para> </sect3> <sect3 id="font"> <title>Pisava</title> <para>Pri tiskanju lahko uporabite razne pisave. Ime pripadajo&ccaron;e spremenljivke je <literal>FONT</literal>. Vrednost <literal>Latex</literal> (standardna nastavitev) pomeni standardno LaTeX pisavo iz dru&zcaron;ine EC. <literal>Latex-bright</literal> uporablja <emphasis>Computer Modern Bright</emphasis>. Te pisave na mnogih sistemih ni zaradi licence pod katero spada<footnote> <!-- Footnote --> <para>Na svoj ra&ccaron;unalnik lahko to pisavo nalo&zcaron;ite z CTAN-a Pisave najdete v CTAN:/tex-archive/nonfree/fonts/cmbright/ (CTAN = <emphasis>Comprehensive TeX Archive Network</emphasis> sestavljen iz mre&zcaron;e ve&ccaron;ih stre&zcaron;nikov. CTAN stre&zcaron;nik v Nem&ccaron;iji je <ulink url="ftp://ftp.dante.de"></ulink>, ter v Veliki Britaniji <ulink url="ftp://cam.ctan.org"></ulink> ter v Zdru&zcaron;enih Dr&zcaron;avah <ulink url="ftp://tug.ctan.org"></ulink>). </para> <!-- /Footnote --> </footnote>. </para> <para>Obstaja ve&ccaron; Postscript pisav, med uporabnimi tu so: <literal>Times</literal>, <literal>Palatino</literal>, <literal>Utopia</literal>, <literal>Charter</literal> <literal>Bookman</literal>, <literal>CentSchool</literal> (New Century Schoolbook), <literal>Chancery</literal> (Zapf Chancery), <literal>Helvetica</literal> ali <literal>AvantGarde</literal>.</para> <para>Seveda morajo pisave biti name&scaron;&ccaron;ene na va&scaron;em sistemu. Ker je LaTeX distribucija <emphasis>teTeX</emphasis> standardna na Linux sistemih, to nebi smelo predstavljati problema.</para> </sect3> <sect3> <title>Velikost pisav</title> <para>Velikost pisav lahko uravnavate z spremenljivko <literal>FONTSIZE</literal>. Samo vrednosti <literal>10pt</literal>, <literal>11pt</literal> ter <literal>12pt</literal> so mo&zcaron;ne. </para> </sect3> <sect3> <title>Oblikovanje telesa e-po&scaron;te</title> <para>Telo sporo&ccaron;ila je razdeljeno na dva dela: tekst ter podpis. &Ccaron;e podpis obstaja in naj se ga ne odstrani (glej <xref linkend="remsig">), lahko ta dva dela oblikujete lo&ccaron;eno.</para> <para>Muttprint uporablja LaTeX paket <filename>fancyvrb.sty</filename> za izpis telesa, kateri nudi mnogo opcij za oblikovanje. Mo&zcaron;nosti, ki so poslane v <literal>Verbatim</literal> okolje se lahko nastavijo z spremenljivko <literal>VERBATIMNORMAL</literal> (za navaden tekst) ter <literal>VERBATIMSIG</literal> (za podpis).</para> <para>Natan&ccaron;no sintakso boste na&scaron;li v dokumentaciji <filename>fancyvrb.sty</filename>, katero si lahko ogledate z ukazom <command>texdoc fancyvrb</command>. Navadno je podpis natisnjen s po&scaron;evno pisavo. Natisnete lahko tudi robove.</para> <para>&Ccaron;e ne &zcaron;elite lo&ccaron;iti oblikovanja telesa ter podpisa po&scaron;te nastavite <literal>VERBATIMSIG</literal> na <literal>raw</literal>. &Ccaron;e to nastavite bo podpis obravnavan kot navaden del teksta ter natisnjen kot tak (vklju&ccaron;no z lo&ccaron;evalcem podpisa).</para> <para>Nekaj primerov:</para> <itemizedList spacing="compact"> <listitem> <para> <literal>fontshape=it,frame=topline</literal>: po&scaron;evna pisava, rob okrog polja </para> </listitem> <listitem> <para> <literal>fontfamily=helvetica,fontseries=b</literal>: pisava Helvetica, krepko </para> </listitem> <listitem> <para> <literal>numbers=left,stepnumber=5</literal>: &Scaron;tevilk&ccaron;enje vrstic, vsaka peta vrstica </para> </listitem> </itemizedList> </sect3> <sect3> <title>Nastavljanje robov</title> <para>Robove lahko nastavite z nastavitvijo naslednjih spremenljivk: <literal>TOPMARGIN</literal> (zgornji rob), <literal>BOTTOMMARGIN</literal> (spodnji rob), <literal>LEFTMARGIN</literal> (levi rob) ter <literal>RIGHTMARGIN</literal> (desni rob).</para> <para>Te spremenljivke naj bi bile nastavljene na celo&scaron;tevilsko vrednost, ki pomeni rob v milimetrih (mm). Ostale merske enote niso mo&zcaron;ne; 25.4&nbsp;mm je 1&nbsp;inch.</para> </sect3> <sect3> <title>Prelom dolgih vrstic</title> <para>Dol&zcaron;ina najdalj&scaron;e vrstice se dolo&ccaron;i z spremenljivko <literal>WRAPMARGIN</literal>. Dalj&scaron;e vrstice so prelomljene avtomatsko, toda kraj&scaron;e niso zdru&zcaron;ene.</para> </sect3> <sect3> <title>Pravila pred/za glavo ter nogo</title> <para>Natisne se lahko previlo pod glavo ali nad nogo sporo&ccaron;ila. Privzeto so izklju&ccaron;ena.</para> <para>Za aktivacijo astavite spremenljivko <literal>HEADRULE</literal> ali <literal>FOOTRULE</literal> na <literal>on</literal> ali <literal>off</literal>.</para> </sect3> <sect3> <title>Oblika prve strani</title> <para>Obstajajo razli&ccaron;ne mo&zcaron;nosti poudarjanja glave sporo&ccaron;ila na prvi strani. Tule je izpis teh pravil:</para> <informaltable frame="topbot"> <tgroup cols="2" align="left"> <colspec colnum="1" colwidth="1.5in"> <thead> <row> <entry>Stil</entry> <entry>Opis</entry> </row> </thead> <tbody> <row> <entry><literal>plain</literal></entry> <entry><para>brez pravil</para></entry> </row> <row> <entry><literal>border</literal></entry> <entry><para>pravilo za glavo (<emphasis>privzeta nastavitev)</emphasis>) </para></entry> </row> <row> <entry><literal>fbox</literal></entry> <entry><para>enostaven rob okrog glave sporo&ccaron;ila</para></entry> </row> <row> <entry><literal>shadowbox</literal></entry> <entry><para>sen&ccaron;en rob okrog glave sporo&ccaron;ila</para></entry> </row> <row> <entry><literal>ovalbox</literal></entry> <entry><para>zaokro&zcaron;en rob okrog glave sporo&ccaron;ila (tanke vrstice)</para></entry> </row> <row> <entry><literal>Ovalbox</literal></entry> <entry><para>enako kot <literal>ovalbox</literal> toda krepkej&scaron;e &ccaron;rte</para></entry> </row> <row> <entry><literal>doublebox</literal></entry> <entry><para>okvir z dvojno &ccaron;rto okrog glave sporo&ccaron;ila</para></entry> </row> <row> <entry><literal>grey</literal></entry> <entry><para>sivo ozadje za glavo sporo&ccaron;ila</para></entry> </row> <row> <entry><literal>greybox</literal></entry> <entry><para>enako kot <literal>grey</literal> toda z dodatnimim &ccaron;rnim robom</para></entry> </row> </tbody> </tgroup> </informaltable> <para>Nastavite spremenljivko <literal>FRONTSTYLE</literal> na vrednost iz zgornje tabele.</para> </sect3> <sect3> <title>Format papirja</title> <para>Za nastavitev formata papirja nastavite <literal>PAPER</literal> na pravilno vrednost. Mo&zcaron;no je le <literal>A4</literal> ter <literal>letter</literal>.</para> <para>&Ccaron;e obstaja datoteka <filename>##SYSCONFDIR##/papersize</filename> kot je navada na Debian sistemu, je upo&scaron;tevana. Lastne nastavitve prepi&scaron;ejo sistemske nastavitve.</para> </sect3> <sect3 id="remsig"> <title>Odre&zcaron;i podpis</title> <para>Pogosto podpis vsebuje neuporabne podatke ali reklame in se ga zatorej nebi tiskalo. Muttprint lahko odre&zcaron;e podpis, &ccaron;e je bil lo&ccaron;en od besedila po&scaron;te z uporabo <quote><literal>&ndash;&ndash; </literal></quote> -- pazi na presledek (nekateri po&scaron;tni odjemalci ne generirajo pravilnega lo&ccaron;ila).</para> <para>Da to dose&zcaron;ete nastavite <literal>REM_SIG</literal> (to pomeni <quote>odstrani podpis</quote> na vrednost <literal>on</literal>.</para> </sect3> <sect3> <title>Izpusti citate</title> <para>Pogosto avtor emaila ne citira smotrno, temve&ccaron; pripne celotno sporo&ccaron;ilo, tako da izpis pri tiskanju postane zelo dolg in nerazumljiv.</para> <para>&Ccaron;e je <literal>REM_QUOTE</literal> nastavljen na <literal>on</literal>, potem citati ne bodo natisnjeni. Muttprint zazna citate z uporabo regularnih izrazov tako kot program Mutt v njegovai standardni namestitveni datoteki. Tako, da je tekst, ki je v Mutt-u poudarjen z barvo, izpu&scaron;&ccaron;en pri tiskanju. To sovpada z funkcijo <emphasis>toggle quote</emphasis> (<keycombo><keycap>Shift</keycap><keycap>t</keycap></keycombo>) na zaslonu.</para> </sect3> <sect3 id="printedheaders"> <title>Tiskanje glave</title> <para>Navadno se natisne le zanimive dele glave. To lahko spremenite z nastavitvijo spremenljivke <literal>PRINTED_HEADERS</literal>. Definirajte vsak del glave lo&ccaron;en z pod&ccaron;rtajem (<literal>_</literal>).</para> <para>Zaporedje je pomembno za tiskanje. Evaluacija izrazov lo&ccaron;i male/velike &ccaron;rke. Deli glave, ki ne obstajajo se ignorirajo. Za krepko tiskanje vstavite ime dela glave med zvezdici (<literal>*</literal>), za po&scaron;evno tiskanje naredite enako s po&scaron;evnico (<literal>/</literal>).</para> <para>Privzeta nastavitev je:</para> <programlisting>PRINTED_HEADERS="Date_To_From_CC_Newsgroups_*Subject*"</programlisting> <para>&Scaron;e en primer razumne nastavitve:</para> <programlisting>PRINTED_HEADERS="/Date/_To_From_*Subject*_X-Mailer"</programlisting> </sect3> <sect3> <title>Lastna LaTeX koda</title> <para>Spremenljivka <literal>LATEXCODE</literal> je za ljudi, ki so doma&ccaron;i z LaTeX-om ter bi si radi nastavili tiskanje brez spreminjanja izborne kode programa Muttprint. Na primer, uporabno je nastaviti svoje pisave.</para> <para>Poleg <literal>LATEXCODE</literal> obstaja &scaron;e pet dodatnih spremenjljivk (<literal>LATEXCODE1</literal> do <literal>LATEXCODE5</literal>) ki lepo razdelijo va&scaron;o LaTeX kodo Te spremenljivke so vklju&ccaron;ene v kodo v tem zaporedju.</para> <tip> <para>Email lahko tiskate tudi z proporcionalnimi pisavami (namesto typewriter pisv) z naslednjo nastavitvijo: </para> <programlisting>LATEXCODE="\renewcommand{\ttdefault}{\rmdefault}"</programlisting> </tip> </sect3> <sect3> <title>Poro&ccaron;ila o napakah</title> <para>Izhodna sporo&ccaron;ila ukaza <command>latex</command> ter <command>dvips</command> niso prikazana. &Ccaron;e se pojavijo kaki problemi, bi bilo uporabno, &ccaron;e bi lahko prebrali izhode. Takrat nastavite variablo <literal>DEBUG</literal> na <literal>1</literal> v va&scaron;em <filename>.muttprintrc</filename>. Sedaj Muttprint ustvari dnevnik imenovan <filename>/tmp/muttprint.log</filename> tako lahko, ko naslednji&ccaron; po&zcaron;enete Muttprin opazujete izpis napak. To lahko pride prav tudi pri poro&ccaron;ilu o napakah.</para> </sect3> </sect2> <sect2> <title>Mo&zcaron;nosti ukazne vrstice</title> <para>Ve&ccaron;ina nastavitev se lahko nastavi tudi v ukazni vrstici. To na da prednost la&zcaron;je integracije z po&scaron;tnim odjemalcem (npr. z lastnimi makroji).</para> <para>Natan&ccaron;en opis vseh mo&zcaron;nosti dobite z ukazom <command>muttprint</command> <option>-h</option> ali v man strani <citerefentry><refentrytitle>muttprint</refentrytitle> <manvolnum>1</manvolnum></citerefentry>.</para> <para>Efekt teh mo&zcaron;nosti je enak kot v konfiguracijski datoteki, toda ukazna vrstica prevlada nad ostalimi nastavitvami.</para> </sect2> <sect2 id="lang"> <title>Razli&ccaron;ni jeziki</title> <para>Muttprint podpira razne jezike. Navadno se okoljsko spremenljivko <envar>LANG</envar> nastavi na pravilno vrednost: npr. <literal>de</literal>, <literal>it</literal>, <literal>fr</literal>, <literal>es</literal> ali <literal>en</literal>, kar je bli&zcaron;njica glede na ISO 639. Prepoznana sta le prva dva znaka, tako da je <literal>de_DE@euro</literal> v redu. &Ccaron;e vrednost ni znana, Muttprint privzame angle&scaron;&ccaron;ino.</para> <para>Opis mo&zcaron;nih prevodov najdete v datoteki <filename>README.translations</filename>, ki se namesti z dokumentacijo v skupen direktorij.</para> <para>&Ccaron;e bi radi uporabljali drug jezik za Muttprint kot za ostale programe sistema, lahko nastavite <literal>LANG</literal> v va&scaron;em <filename>.muttprintrc</filename>.</para> <sect3> <title>Jeziki pri tiskanju</title> <para>Najbolj pomembni u&ccaron;inki prilagoditve jezika pri tiskanju so: glava pisma ter datume.</para> <para>Zadnji se ustvari z LaTeX paketom <filename>babel.sty</filename>. Muttprint po&scaron;lje pravilno vrednost, ki sovpada z va&scaron;im jezikom paketu. Lahko nastavite va&scaron;o lastno vrednost v spremenljivki <literal>LPack</literal>, npr. na <literal>austrian</literal>, <literal>spanish</literal>. Preberite <command>texdoc babel</command> za spisek mo&zcaron;nih vrednosti.</para> <para>&Ccaron;e bi radi za tiskanje glave uporabili &scaron;e druge nize si lahko nastavite naslednje spremenljivke:</para> <ItemizedList spacing="compact"> <ListItem><para><literal>FROM_STRING</literal></para></ListItem> <ListItem><para><literal>TO_STRING</literal></para></ListItem> <ListItem><para><literal>SUBJECT_STRING</literal></para></ListItem> <ListItem><para><literal>CC_STRING</literal></para></ListItem> <ListItem><para><literal>DATE_STRING</literal></para></ListItem> <ListItem><para><literal>PAGE_STRING</literal></para></ListItem> <ListItem><para><literal>OF_STRING</literal></para></ListItem> <ListItem><para><literal>NEWSGROUPS_STRING</literal></para></ListItem> </ItemizedList> <para>Dodatni deli glave, ki so nastavljeni za tiskanje (glej <xref linkend="printedheaders">) se ne dajo prevesti.</para> </sect3> <sect3> <title>Nabori znakov</title> <para>Muttprint podpira razli&ccaron;ne nabore znakov za tiskanje. Tule je kratek pregled:</para> <informaltable frame="topbot"> <tgroup cols="3" align="left"> <colspec colnum="1" colwidth="1in"> <colspec colnum="2" colwidth="0.8in"> <thead> <row> <entry>nabor</entry> <entry>mo&zcaron;nost</entry> <entry>opis</entry> </row> </thead> <tbody> <row> <entry>ISO-8859-1</entry> <entry><literal>latin1</literal></entry> <entry>zahodno evropski jeziki</entry> </row> <row> <entry>ISO-8859-2</entry> <entry><literal>latin2</literal></entry> <entry>vzhodno evropski jeziki</entry> </row> <row> <entry>ISO-8859-3</entry> <entry><literal>latin3</literal></entry> <entry>ju&zcaron;nozahodno evropski ter razni drugi jeziki</entry> </row> <row> <entry>ISO-8859-4</entry> <entry><literal>latin4</literal></entry> <entry>ju&zcaron;novzhodno evropski ter razni drugi jeziki</entry> </row> <row> <entry>ISO-8859-9</entry> <entry><literal>latin5</literal></entry> <entry>Latin-1 prirejen za tur&scaron;&ccaron;ino</entry> </row> <row> <entry>ISO-8859-15</entry> <entry><literal>latin9</literal></entry> <entry>Latin-1 z nekaj spremembami npr. znak za Evro </entry> </row> <row> <entry>KOI8-R</entry> <entry><literal>koi8-r</literal></entry> <entry>Jeziki z cirili&ccaron;nimi znaki kot je Ru&scaron;&ccaron;ina</entry> </row> <row> <entry>Windows-1252</entry> <entry><literal>latin1</literal></entry> <entry>Latin-1 z nekatermi dodatki</entry> </row> <row> <entry>Windows-1250</entry> <entry><literal>latin2</literal></entry> <entry>Latin-2 z nekatermim dodatki</entry> </row> <row> <entry>UTF-8</entry> <entry><literal>utf8</literal></entry> <entry>Unicode kot ga podpira LaTeX, glej <xref linkend="sysreq"></entry> </row> </tbody> </tgroup> </informaltable> <para>Ta nabor znakov omogo&ccaron;a tiskanje ve&ccaron;ine jeziko, ki uporabljajo latin znake. Obna&scaron;anje nabora je odvisno v lgavnem od paketa LaTeX <filename>inputenc.sty</filename>, vendar je raz&zcaron;irjen.</para> <para>Privzeti nabor je Latin-1. &Ccaron;e obstajajo datoteke s prevodi, je nabor znakov spremenjen v dr&zcaron;avi pripradajo&ccaron;ega. Naprimer, za nem&scaron;&ccaron;ino je uporabljen nabor Latin-9 za pravilno tiskanje znaka valute Evro. Za &Ccaron;ehe je nabor spremenjen v Latin-2, ker je to vzhodno evropski jezik.</para> <para>Kljub temu, pa lahko nabor znakov lo&ccaron;eno nastavite v namestitveni datoteki z spremenljivko <literal>CHARSET</literal>. Navadno se to nastavi na nabor znakov, ki se uporablja za prikaz na zaslonu glej spremenljivko <varname>charset</varname> pri Mutt-u.</para> <para>&Ccaron;e nastavite <literal>CHARSET</literal> na vrednost <literal>auto</literal>, bo Muttprint poskusil najti primeren delglave, ki vsebuje nabor znakov sporo&ccaron;ila. To nastavitev uporabljajte pazljivo. Npr. Mutt prilagodi izgled naboru zaslonskih znakov. Na drugi strani, pa bi bile te nastavitve lahko uporabne, &ccaron;e tiskate mnogo po&scaron;te z razli&ccaron;nimi nabori znakov.</para> <para>Poleg znakov iz dru&zcaron;ine ISO-Latin Muttprint podpira tudi izbolj&scaron;ave nabora Windos Windows-1252 (zhodno evropski) ter Windows-1250 (vzhodno evropski). Ta nabor raz&scaron;iri ISO nabor z nekatermi znaki, naprimer tipografski narekovaji, znak "na miljo", znak za valuto Evro. Zadnji se pogosto pojavlja na mestu 128 (decimalno) zaradi &scaron;iroke raz&scaron;irjenosti Windows -- delno prznan kot ISO-8859-1. Muttprint natisne te maile pravilno, &ccaron;e po&scaron;tni odjemalec &ccaron;esa ne spremeni.</para> <para>Od verzije 0.65 Muttprint podpira tiskanje po&scaron;te z cirili&ccaron;nimi znaki. V tem primeru je nabor znakov <literal>koi8-r</literal>. Prosim upo&scaron;tevajte, da to ne deluje z vsemi sistemi LaTeX-a; sam priporo&ccaron;am verzijo teTeX <emphasis>2.0</emphasis> ali vi&scaron;jo. &Scaron;e ve&ccaron;, vse pisave ne vsebujejo potrebnih znakov, prosim uporabljajte LaTeX-ove standardne pisave, glej <xref linkend="font">.</para> <para>Poln pregled ISO-8859-* znakovnih naborov najdete na <ulink url="http://czyborra.com/charsets/iso8859.html"></ulink>. </para> </sect3> <sect3> <title>Datoteka s prevodi</title> <para>Prevodi Muttprint datotek se nahajajo v <filename>share</filename> imeniku, ter imajo ime <filename>translation-<replaceable>jezik</replaceable>.pl</filename>. Lahko dodate nove datoteke v ta imenik brez kakrsnihkoli sprememb Muttprint skripte. Ne samo deli glave omenjeni zgoraj, temve&ccaron; tudi sporo&ccaron;ila pomo&ccaron;i so prevedena tu.</para> <para>Za nove prevede vzemite katerokoli datoteko kot predlogo, jo skopirajte ter prevedite. &Ccaron;e bi radi va&scaron; prevod ponudili drugim uporabnikom mi le po&scaron;ljite datoteko po e-mail-u in jo bom dodal v naslednjo verzijo programa.</para> </sect3> </sect2> </sect1> <sect1 id="nots"> <title>Opombe</title> <sect2> <title>Avtor, Licenca</title> <para>Skripto je napisal Bernhard Walle <email>Bernhard.Walle@gmx.de</email>.</para> <para>Ta program je prosto programje; lahko ga raz&scaron;irjate in/ali spreminjate pod pogoji GNU General Public License kot jo je objavila Free Software Foundation; verzije 2 ali (po va&scaron;i &zcaron;elji) katero kasnej&scaron;o verzijo.</para> <para>Ta program se raz&scaron;irja z upanjem, da bo uporaben, toda <emphasis>brez kakr&scaron;nekoli garancije</emphasis>; tudi brez nazna&ccaron;ene garancije o <emphasis>prodaji</emphasis> ali <emphasis>sposobnosti za dolo&ccaron;en namen</emphasis>. Glej GNU General Public License za natan&ccaron;nej&scaron;i opis.</para> <para>Skupaj s to verzijo programa ste prejeli GNU General Public License (datoteka <filename>COPYING</filename>).</para> <para>Prosim po&scaron;ljite mi opombe, komentarje, izbolj&scaron;ave ter predloge preko e-maila.</para> <para>Pravice za kopiranje prevodov pripadajo njihovim prevajalcem. Preberite <filename>README.translations</filename> za imena prevajalcev.</para> </sect2> <sect2> <title>Download</title> <para>Trenutno verzijo, ter vse stare verzije lahko downloadate z <ulink url="http://muttprint.sourceforge.net"></ulink>. To je doma&ccaron;a stran programa Muttprint.</para> <para>Obvestila o novih verzijah objavljam na <ulink url="http://www.freshmeat.net">Freshmeat</ulink>.</para> </sect2> <sect2> <title>Tiskanje priponk</title> <para>Muttprint ni sposoben natisniti priponk po&scaron;te. Da bi to dosegel, bi Muttprint moral analizirati surova MIME sporo&ccaron;ila ter jih dekodirati. To je precej zahtevno. Na primer Muttprint bi moral dekriptirati PGP-enkriptirana sporo&ccaron;ila, se odlo&ccaron;ati za pravo alternativo <literal>multipart/alternative</literal> sporo&ccaron;il ter delati rekurzivno za <literal>message/*</literal> -- to so le nekatere re&ccaron;i. Na kratko: Esencialni deli odjemalcev po&scaron;te bi morali integrirani ter mnogo nastavitev (naprimer za PGP) bi morali opraviti. &Scaron;e ve&ccaron;, vsi odjemalci po&scaron;te ne podpirajo "raw" izpisa sporo&ccaron;il za tiskanje.</para> <para>Toda Mutt ima svojo uporabno funkcijo za tiskanje priponk. Lahko izbirate med lo&ccaron;enimi ukazi za tiskanje razli&ccaron;nih tipov MIME. Ti se lahko nastavijo v <filename>~/.mailcap</filename>. Ve&ccaron; o tem si preberite v Mutt priro&ccaron;niku, razdelek 5.3.3.1.</para> <para>Napisal sem zelo malo skripto imenovano <literal>imageprint</literal> za tiskanje slik (skoraj vsi formati so podprti). Lahko jo uporabite kot predlogo za lastne skripte. Tule je:</para> <programlisting> #!/bin/sh target=/tmp/imageprint-$$.ps convert -page A4 $1 $target lpr $target rm $target</programlisting> <para>Le pritisnite tipko <keycap>p</keycap> v meniju priponk v Mutt-u .</para> <para>Uporabniki ostalih odjemalcev po&scaron;te pa naj si preberejo naovodila za ionformacijo kako tiskati priponke.</para> </sect2> <sect2> <title>Zahvala</title> <para>vsem, ki so mi pomagali z poro&ccaron;ili o napakah, da bi izbolj&scaron;ali Muttprint. &Scaron;e posebno bi se rad zahvalil Romanu Beigelbecku za pripravo dodatnih slik, Robertu Valloneu za italjanski prevod, Vincentu Bernatu za francoski prevod, Marcelu Ramosu za &scaron;panski prevod, Dominiku Form&aacute;neku za &ccaron;e&scaron;ki prevod ter vzdr&zcaron;evalcem Debian paketov Dr. Guenterju Bechlyju ter Chanopu Silpa-Ananu.</para> <para>Na koncu bi se rad zahvalil vsem ljudem, ki prispevajo k k prostem programju. Ve&ccaron;ina ljudi to dela v svojem prostem &ccaron;asu, brez kakr&scaron;nega koli pla&ccaron;ila!</para> </sect2> </sect1> </article> <!-- ViM settings vim:tw=80 sw=2 ts=2 -->
const express = require("express"); const app = express(); const cors = require("cors"); // const admin = require("firebase-admin"); require("dotenv").config(); const { MongoClient } = require("mongodb"); const ObjectId = require("mongodb").ObjectId; const port = process.env.PORT || 5000; app.use(cors()); app.use(express.json()); const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.jlnis.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`; const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, }); // const serviceAccount = JSON.parse(process.env.FIREBASE_SERVICE_ACCOUNT); // admin.initializeApp({ // credential: admin.credential.cert(serviceAccount), // }); // async function verifyToken(req, res, next) { // console.log("in vergy token"); // if (req.headers?.authorization?.startsWith("Bearer ")) { // const token = req.headers.authorization.split(" ")[1]; // try { // const decodedUser = await admin.auth().verifyIdToken(token); // req.decodedEmail = decodedUser.email; // } catch {} // } // next(); // } async function run() { try { await client.connect(); const database = client.db("MyCar"); const carsCollection = database.collection("Cars"); const usersCollection = database.collection("users"); const ordersCollection = database.collection("orders"); const reviewCollection = database.collection("review"); app.get("/cars", async (req, res) => { const cursor = carsCollection.find({}); const cars = await cursor.toArray(); res.send(cars); }); app.get("/users/:email", async (req, res) => { const email = req.params.email; const query = { email: email }; const user = await usersCollection.findOne(query); let isAdmin = false; if (user?.role === "admin") { isAdmin = true; } res.json({ admin: isAdmin }); }); app.get("/review", async (req, res) => { const cursor = reviewCollection.find({}); const cars = await cursor.toArray(); res.send(cars); }); app.get("/orders", async (req, res) => { const email = req.query.email; let query; // console.log(email); if (email) { query = { Email: email }; } else { query = {}; } console.log(query); const orders = await ordersCollection.find(query); const result = await orders.toArray(); res.send(result); }); app.post("/users", async (req, res) => { const user = req.body; const result = await usersCollection.insertOne(user); res.json(result); }); app.post("/review", async (req, res) => { const user = req.body; const result = await reviewCollection.insertOne(user); res.json(result); }); app.post("/order", async (req, res) => { const order = req.body; console.log(order); const result = await ordersCollection.insertOne(order); res.json(result); }); app.post("/cars", async (req, res) => { const car = req.body; const result = await carsCollection.insertOne(car); res.json(result); }); app.put("/users", async (req, res) => { const user = req.body; console.log("put", user); const filter = { email: user.email }; const options = { upsert: true }; const updateDoc = { $set: user }; const result = await usersCollection.updateOne( filter, updateDoc, options ); res.json(result); }); // GET Single car app.get("/cars/:id", async (req, res) => { const id = req.params.id; const query = { _id: ObjectId(id) }; const result = await carsCollection.findOne(query); res.json(result); }); // Delete Api app.delete("/orders/:id", async (req, res) => { const id = req.params.id; const query = { _id: ObjectId(id) }; const result = await ordersCollection.deleteOne(query); res.json(result); }); app.delete("/cars/:id", async (req, res) => { const id = req.params.id; const query = { _id: ObjectId(id) }; const result = await carsCollection.deleteOne(query); res.json(result); }); app.put("/users/admin", async (req, res) => { const user = req.body; const requesterAccount = user.requester; const email = user.email; if (user) { const checkRequesterAccount = await usersCollection.findOne({ email: requesterAccount, }); if (checkRequesterAccount.role === "admin") { const filter = { email: email }; const updateDoc = { $set: { role: "admin" } }; const result = await usersCollection.updateOne(filter, updateDoc); res.json(result); } } else { res .status(403) .json({ message: "You do not have access to make admin" }); } }); } finally { // await client.close(); } } run().catch(console.dir); app.get("/", (req, res) => { res.send("Hello MyCars "); }); app.listen(port, () => { console.log(`listening at ${port}`); });
// Flatten /** * In this challenge, you would need to write a type that takes an array and emitted the flatten array type. */ // solution /** * 先判断第一个是否为数组,是的话递归判断,直到它递归到不是一个数组后将这个值放在数组里面 * 一直重复这个过程 */ export type Flatten<T extends any[]> = T extends [infer First, ...infer Rest] ? [...(First extends any[] ? Flatten<First> : [First]), ...Flatten<Rest>] : []; // test type flatten = Flatten<[1, 2, [3, 4], [[[5]]]]>; // [1, 2, 3, 4, 5]
from django.shortcuts import render import json # Create your views here. from django.http import HttpResponse,JsonResponse from django.views import View from utils.s3_client import * from django.views.decorators.csrf import csrf_exempt from .models import Document class Service: def getAll(): documents = Document.objects.all() return documents def deleteDocument(documentName): document = Document.objects.get(documentName=documentName) document.delete() return True class IndexView(View): def get(self, request): # read the Documents Table and return documents = Service.getAll() return render(request, 'index.html',{'documents' : documents}) class UploadFileView(View): @csrf_exempt def post(self, request): uploaded_file = request.FILES['file'] result = uploadDoc(uploaded_file) if (result): # store the file name on the database and send the document = Document(documentName=result,createdBy='userId') document.save() return HttpResponse(200,'File Created Successfully') return HttpResponse(400,"file not uploaded") class DownloadFileView(View): def post(self, request): data = json.loads(request.body) document = data['fileName'] presigned_url = generatePresignedURL(document) return JsonResponse({ "presigned_url" : presigned_url}) class DeleteFileView(View): def post(self, request): data = json.loads(request.body) document = data['fileName'] result = delete_file(document) if (result): Service.deleteDocument(document) return HttpResponse(200,'File Deleted Successfully') return HttpResponse(400,"file not deleted")
## OPERATORS ### Arithmetic --- > Returns the resulting value based on which arithmetic operator is used ``` + (a + b): adding two numerical values - (a - b): minus two numerical values * (a * b): times two numerical values / (a / b): divides two numerical values % (a % b): divides two numerical values, returns remainder ``` ### Logical --- > Returns either 1 (TRUE) or 0 (FALSE) by evaluating a and b ``` || (a OR b): evaluates if either are true, the statement is true, otherwise false && (a AND b): evaluates only if both are true, the statement is true, otherwise false ! (NOT a): evaluates negates the boolean, changing false to true, and vice versa ``` ### Comparison --- > Returns either 1 (TRUE) or 0 (FALSE) by comparing a and b ``` > (a > b): checks if a is strictly greater than b >= (a >= b): checks if a is greater or equal to b < (a < b): checks if a is strictly less than b <= (a <= b): checks if a is less or equal to b != (a != b): checks if both are not matching in numerical values == (a == b): checks if both are matching in numerical values ``` ### Other --- > These operators are just arithmetic operators simplified with storing the returning value in a <br> (Allowing us to write less, especially for frequent code like incrementing by 1) ``` Example: a = a + 1; (Standard Way) a += 1; (Simplified) a++; (Simplified Further) ``` ``` Increment and Decrement ++ (a++): when we add 1 to a -- (a--): when we subtract 1 from a Simplified arithmetic += (a += b): adds two numerical values, storing result in a -= (a -= b): subtracts two numerical values, storing result in a *= (a *= b): multiply two numerical values, storing result in a /= (a /= b): divides two numerical values, storing result in a ``` ### Bitwise --- > These operators aren't covered in this course, AVOID using them (COMP1521 will teach these) ``` ^: XOR (Does not perform exponent calculations) >>: Bitshift Right <<: Bitshift Left &: Bitwise AND (Not the same as Logical AND) |: Bitwise OR (Not the same as Logical OR) ```
// Importar el framework Express para la creación de la aplicación const express = require('express'); // Importar la biblioteca para trabajar con el sistema de archivos (file system) var fs = require("fs"); // Importar la librería para manejar sesiones en Express (para autenticación, por ejemplo) var session = require("express-session"); // Crear una instancia de la aplicación Express const app = express(); // Crear una instancia del servidor HTTP utilizando la aplicación Express const server = require('http').Server(app); // Importar y configurar Socket.IO para la comunicación en tiempo real const io = require("socket.io")(server); // Definir el puerto en el que la aplicación escuchará, con opción de usar el puerto proporcionado por el entorno const port = process.env.PORT || 3000; // Configurar Express para servir archivos estáticos desde la carpeta "public" app.use(express.static("public")); // Importar Mongoose para la conexión a MongoDB y el manejo de esquemas const mongoose = require("mongoose"); // Importar funciones y modelo definidos en el archivo "conexionMongo.js" const { Usuario, conectarDB } = require("./conexionMongo.js"); // Configurar Express para manejar datos en formato JSON app.use(express.json()); // Configurar Express para usar el middleware de sesión app.use(session({ secret: "Tu cadena secreta", // Agrega tu propia cadena secreta aquí resave: false, saveUninitialized: true, cookie: { secure: false } })); // Middleware de autenticación var auth = function (req, res, next) { // Verificar si hay una sesión activa y si el usuario es "admin" y tiene el rol de administrador if (req.session && req.session.user === "admin" && req.session.admin) { // Permitir el acceso al siguiente middleware o ruta return next(); } else { // Devolver un código de estado 401 (No autorizado) si la autenticación falla return res.sendStatus(401); } } /**VARIABLES GLOBALES**/ var usuarioConectado={};//Almacenará el nombre del usuario actual var usuariosConectados={};//Almacenará todos los nombres de los usuarios que se han ido conectando var guardarNombreUsuariosBdd=[];//Este array guardará los nombres de los usuarios de la bdd con lo que devuelve la función //var usuariosConectadosId=[]; //var contador=0;//Esta variable lo usare para la coleccion de usuariosConectadosId //iniciar(); //console.log(guardarNombreUsuariosBdd) /*** FUNCIONES GET ***/ app.get('/', (req, res) => { var contenido=fs.readFileSync("public/index.html"); res.setHeader("Content-type", "text/html"); res.send(contenido); }); app.get('/login', (req, res) => { var contenido=fs.readFileSync("public/login.html"); res.setHeader("Content-type", "text/html"); res.send(contenido); }); app.get('/registro', (req, res) => { var contenido=fs.readFileSync("public/registro.html"); res.setHeader("Content-type", "text/html"); res.send(contenido); }); app.get('/chat', auth, (req, res) => { var contenido=fs.readFileSync("public/chat.html"); res.setHeader("Content-type", "text/html"); res.send(contenido); }); /*** FUNCIONES POST ***/ // Ruta para registrar un nuevo usuario en la base de datos app.post("/registrar", async function(req, res) { // Verificar si los campos de nombre de usuario y contraseña están presentes en la solicitud if (!req.body.username || !req.body.password) { res.send({"res": "register failed"}); // Enviar respuesta de fallo si los campos no están presentes } else { let usuarioExistente; try { // Comprobar si ya existe un usuario con el mismo nombre usuarioExistente = await Usuario.findOne({ nombre: req.body.username }); } catch (err) { console.error("Error al crear usuario: ", err); } if (usuarioExistente) { console.log("Ya existe un usuario con ese nombre"); res.send({"res": "usuario ya existe"}); // Enviar respuesta de fallo si el usuario ya existe } else { // Crear un nuevo usuario utilizando el modelo Mongoose const nuevoUsuario = new Usuario({ nombre: req.body.username, password: req.body.password }); try { // Guardar el nuevo usuario en la base de datos nuevoUsuario.save(); console.log("Nuevo usuario creado: ", nuevoUsuario); res.send({"res": "register true"}); // Enviar respuesta de éxito si el registro es exitoso } catch (err) { console.error("Error al crear usuario: ", err); } } } }); /**************************************************************************************/ // Ruta para identificar y autenticar a un usuario utilizando la base de datos app.post("/identificar", async function(req, res) { // Verificar si los campos de nombre de usuario y contraseña están presentes en la solicitud if (!req.body.username || !req.body.password) { res.send({"res": "login failed"}); // Enviar respuesta de fallo si los campos no están presentes } else { try { obtenerNombresUsuarios(); // Buscar un usuario en la base de datos con el nombre y contraseña proporcionados const usuarioEncontrado = await Usuario.findOne({ nombre: req.body.username, password: req.body.password }); if (usuarioEncontrado) { // Usuario autenticado con éxito usuarioConectado = { nombre: req.body.username }; // Almacenar el usuario en un objeto de usuarios conectados if (!usuariosConectados.hasOwnProperty(req.body.username)) { // Si no existe, lo añadimos usuariosConectados[req.body.username] = usuarioConectado; } else { // Si ya existe, puedes manejarlo de acuerdo a tus necesidades, como emitir un mensaje de error console.log('El usuario ya existe en usuariosConectados.'); } // Establecer la sesión indicando que el usuario está autenticado y es un administrador req.session.user = "admin"; req.session.admin = true; // Enviar respuesta de éxito return res.send({"res": "login true"}); } else { // Enviar respuesta de fallo si el usuario no es válido res.send({"res": "usuario no válido"}); } } catch (err) { console.error("Error al identificar usuario: ", err); } } }); /**FUNCIÓN PARA RECUPERAR TODOS LOS NOMBRES DE LA BDD**/ // Función para obtener y mostrar los nombres de todas las colecciones en la base de datos async function obtenerNombresUsuarios() { let contenedor=[]; try { // Esperar a que la conexión a la base de datos se haya establecido await conectarDB(); // Realizar una consulta para obtener los nombres de los usuarios const usuarios = await Usuario.find({}, 'nombre'); // Mostrar los nombres de los usuarios usuarios.forEach((usuario) => { contenedor.push(usuario.nombre); }); guardarNombreUsuariosBdd=contenedor; //console.log(guardarNombreUsuariosBdd) return true; } catch (error) { console.error('Error al obtener nombres de usuarios:', error); } } /********************************************************************************/ // Llamar a la función obtenerNombresUsuarios después de definirla /**CONEXIONES DE SOCKET**/ var usuariosConectadosId={};//Esta variable ira almacenando todos los usuarios que vaya enviando el cliente para posteriormente enviarle toda la coleccion a este para que los vaya añadiendo al desplegable io.on("connection", function(socket) { //var usuarioActual = {}; // Almacena el nombre y el ID del usuario actual /**PARA LOS MENSAJES PÚBLICOS**/ io.emit("listaUsuarios", guardarNombreUsuariosBdd); io.emit("miNombre", usuarioConectado); //Para que los usuarios vayan mandando su socketid al servidor, y este los vaya almacenando para volver a enviarlos al cliente y los trate en el desplegable socket.on("idActual", function(data) { usuariosConectadosId[socket.id]=data; console.log(usuariosConectadosId," Este es el usuariosConectadosId de idActual"); io.emit("listaId",usuariosConectadosId); }); //Para enviar al cliente todos los usuarios e ids para manejarlos en el desplegable socket.on("publico", async function(data) { //io.emit("publico", {mensaje: mensaje, de: socket.id, para: null }); io.emit("publico",{mensaje: data.mensaje, de: data.de, para: data.para}); //Para el tema de guardar mensajes en la bdd try { const usuarioRemitente = await Usuario.findOne({ nombre: data.de }); if (!usuarioRemitente) { console.error("Usuario remitente no encontrado en la base de datos"); return; } usuarioRemitente.mensajes.push({ de: data.de, mensaje: data.mensaje }); await usuarioRemitente.save(); } catch (err) { console.error("Error al guardar el mensaje en la base de datos:", err); } }); socket.on('privado', async function(data) { let variablePrivado=null; for (const clave in usuariosConectadosId) { if (usuariosConectadosId.hasOwnProperty(clave)) { const elemento = usuariosConectadosId[clave]; // Comprueba si el valor del nombre es igual al que tienes if (elemento.nombre == data.para) { //console.log("este es el log de elemento.nombre", elemento.nombre) variablePrivado=elemento.id; // Asigna el valor del atributo id a la variablePrivado // Puedes realizar otras acciones aquí si es necesario } } } //console.log("este es el data.para",data.para); //console.log("esto es lo que hay dentro de usuariosEId",usuariosEId) /*usuariosEId.forEach(function(usuario) { if(usuario.nombre==data.para){ variableEmit=usuario.id; } });*/ //console.log("esta es la variable emit: ", variableEmit); socket.to(variablePrivado).emit('privado', {mensaje: data.mensaje, de: data.de, para: data.para}); socket.emit('privado', {mensaje: data.mensaje, de: data.de, para: data.para}); //Para guardar los mensajes en la bdd try { const usuarioRemitente = await Usuario.findOne({ nombre: data.de }); const usuarioDestinatario = await Usuario.findOne({ nombre: data.para }); usuarioRemitente.mensajes.push({ de: data.de, mensaje: data.mensaje }); usuarioDestinatario.mensajes.push({ de: data.de, mensaje: data.mensaje }); await usuarioRemitente.save(); await usuarioDestinatario.save(); } catch (err) { console.error("Error al guardar el mensaje en la base de datos:", err); } }); socket.on("disconnect", ()=>{ //Eliminar al usuario del registro cuando se desconecta delete usuariosConectadosId[socket.id]; //console.log("Este es el log del disconect",usuariosConectadosId) //Notificar a todos los usuarios sobre el cambio en la lista de conectados io.emit("listaId", usuariosConectadosId); }); }); /**FUNCION PARA LOS MENSAJES PRIVADOS**/ conectarDB(); server.listen(port, () => { console.log(`App escuchando en el puerto ${port}`); });
package com.ssafy.alphano.api.stock.service.response; import com.ssafy.alphano.domain.stock.entity.Stock; import com.ssafy.alphano.domain.stock.entity.StockDaily; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.time.LocalDateTime; import static com.ssafy.alphano.domain.stock.entity.QStockDaily.stockDaily; @Data @NoArgsConstructor public class StockDailyResponse { Long id; int maxPrice; int minPrice; int startPrice; int endPrice; int todayVolume; float aiReliability; int aiMaxPrice; int aiMinPrice; int aiEndPrice; LocalDateTime aiInputTime; LocalDateTime aiCompleteTime; boolean aiIsSuccess; Stock stock; String stockDate; @Builder public StockDailyResponse(Long id, int maxPrice, int minPrice, int startPrice, int endPrice, int todayVolume, float aiReliability, int aiMaxPrice, int aiMinPrice, int aiEndPrice, LocalDateTime aiInputTime, LocalDateTime aiCompleteTime, boolean aiIsSuccess, Stock stock, String stockDate) { this.id = id; this.maxPrice = maxPrice; this.minPrice = minPrice; this.startPrice = startPrice; this.endPrice = endPrice; this.todayVolume = todayVolume; this.aiReliability = aiReliability; this.aiMaxPrice = aiMaxPrice; this.aiMinPrice = aiMinPrice; this.aiEndPrice = aiEndPrice; this.aiInputTime = aiInputTime; this.aiCompleteTime = aiCompleteTime; this.aiIsSuccess = aiIsSuccess; this.stock = stock; this.stockDate = stockDate; } public StockDailyResponse(int startPrice, int endPrice, int minPrice, int maxPrice, String stockDate) { this.startPrice = startPrice; this.endPrice = endPrice; this.minPrice = minPrice; this.maxPrice = maxPrice; this.stockDate = stockDate; } public StockDailyResponse(int startPrice, int endPrice, int minPrice, int maxPrice, int todayVolume, int aiMaxPrice, int aiMinPrice, int aiEndPrice, String stockDate) { this.startPrice = startPrice; this.endPrice = endPrice; this.minPrice = minPrice; this.maxPrice = maxPrice; this.todayVolume = todayVolume; this.aiMaxPrice = aiMaxPrice; this.aiMinPrice = aiMinPrice; this.aiEndPrice = aiEndPrice; this.stockDate = stockDate; } public static StockDailyResponse of(StockDaily stockDaily) { return StockDailyResponse.builder() .id(stockDaily.getId()) .maxPrice(stockDaily.getMaxPrice()) .minPrice(stockDaily.getMinPrice()) .startPrice(stockDaily.getStartPrice()) .endPrice(stockDaily.getEndPrice()) .todayVolume(stockDaily.getTodayVolume()) .aiReliability(stockDaily.getAiReliability()) .aiMaxPrice(stockDaily.getAiMaxPrice()) .aiMinPrice(stockDaily.getAiMinPrice()) .aiEndPrice(stockDaily.getAiEndPrice()) .aiInputTime(stockDaily.getAiInputTime()) .aiCompleteTime(stockDaily.getAiCompleteTime()) .aiIsSuccess(stockDaily.isAiIsSuccess()) .stock(stockDaily.getStock()) .stockDate(stockDaily.getStockDate().toString()) .build(); } }
use std::time::{ Duration, SystemTime, UNIX_EPOCH }; use wasm_bindgen::prelude::*; extern crate console_error_panic_hook; use std::panic; use authdecode::{ backend::{ halo2, halo2::{ prover::Prover as Halo2ProverBackend, verifier::Verifier as Halo2VerififerBackend, onetimesetup::OneTimeSetup, }, }, encodings::{ ActiveEncodings, Encoding, FullEncodings, ToActiveEncodings }, prover::{ backend::Backend as ProverBackend, error::ProverError, prover::{ ProofInput, Prover }, InitData, ToInitData, }, utils::{ choose, u8vec_to_boolvec }, verifier::verifier::Verifier, }; use std::env; use tracing_subscriber::{ fmt::format::FmtSpan, EnvFilter }; use hex::encode; use num::BigUint; use rand::{ Rng, SeedableRng }; use rand_chacha::ChaCha12Rng; use web_time::{ Instant }; const PLAINTEXT_SIZE: usize = 1000; struct DummyEncodingsVerifier {} #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] fn log(a: &str); } macro_rules! console_log { ($($t:tt)*) => (log(&format_args!($($t)*).to_string())); } impl authdecode::prover::EncodingVerifier for DummyEncodingsVerifier { fn init(&self, init_data: InitData) {} fn verify( &self, _encodings: &FullEncodings ) -> Result<(), authdecode::prover::EncodingVerifierError> { Ok(()) } } #[wasm_bindgen] pub fn work() { panic::set_hook(Box::new(console_error_panic_hook::hook)); let window = web_sys::window().expect("should have a window in this context"); let performance = window.performance().expect("performance should be available"); tracing_wasm::set_as_global_default(); console_log!("the current time (in ms) is {}", performance.now()); performance.mark("beginauthdecode"); let mut rng = ChaCha12Rng::from_seed([0; 32]); let plaintext: Vec<u8> = core::iter ::repeat_with(|| rng.gen::<u8>()) .take(PLAINTEXT_SIZE) .collect(); let full_encodings: Vec<[u128; 2]> = core::iter ::repeat_with(|| rng.gen::<[u128; 2]>()) .take(PLAINTEXT_SIZE * 8) .collect(); let full_encodings = full_encodings .into_iter() .map(|pair| { [Encoding::new(BigUint::from(pair[0])), Encoding::new(BigUint::from(pair[1]))] }) .collect::<Vec<_>>(); let full_encodings = FullEncodings::new(full_encodings); console_log!("plaintext: {:x?}", plaintext); let active_encodings = full_encodings.encode(&u8vec_to_boolvec(&plaintext)); let params = OneTimeSetup::params(); let proving_key = OneTimeSetup::proving_key(params.clone()); let verification_key = OneTimeSetup::verification_key(params); let h2proverBackend = Halo2ProverBackend::new(proving_key); let h2verifierBackend = Halo2VerififerBackend::new(verification_key); let prover = Prover::new(Box::new(h2proverBackend)); let verifier = Verifier::new(Box::new(h2verifierBackend)); let (prover, commitments) = prover.commit(vec![(plaintext, active_encodings)]).unwrap(); let (verifier, verification_data) = verifier .receive_commitments( commitments, vec![full_encodings.clone()], InitData::new(vec![1u8; 100]) ) .unwrap(); let prover = prover.check(verification_data, DummyEncodingsVerifier {}).unwrap(); let (prover, proof_sets) = prover.prove().unwrap(); let verifier = verifier.verify(proof_sets).unwrap(); performance.mark("endauthdecode"); performance.measure_with_start_mark_and_end_mark( "measureauthdecode", "beginauthdecode", "endauthdecode" ); for item in performance.get_entries_by_name("measureauthdecode").iter() { console_log!("{:?}", item); } } fn perf_to_system(amt: f64) -> SystemTime { let secs = (amt as u64) / 1_000; let nanos = (((amt as u64) % 1_000) as u32) * 1_000_000; UNIX_EPOCH + Duration::new(secs, nanos) }
/* Cutter Copyright(C) 2019 R Bruce Porteous This program is free software : you can redistribute it and / or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program.If not, see <http://www.gnu.org/licenses/>. */ #include "stdafx.h" #include "CutterConfig.h" #include "fstream" #include "../Kernel/ObjectSerializer.h" using namespace std; CutterConfig::CutterConfig() : cutterWidth(1000) , blockLeft(100) , blockRight(900) , defaultFeedRate(5) , defaultComPort("COM1") , connectAutomatically(false) , defaultListenPort(8193) , listenAutomatically(false) , xScrewLead(2.0) , yScrewLead(2.0) , xStepsPerRev(200) , yStepsPerRev(200) , xMicroStepping(4) , yMicroStepping(4) , stepFrequency(2000) { } CutterConfig::~CutterConfig() { } bool CutterConfig::save(std::string& path) { bool success = true; try { fstream ofs(path, ios_base::out); CObjectSerializer serializer(&ofs); serializeTo(serializer); } catch (...) { success = false; } return success; } bool CutterConfig::load(std::string& path) { bool success = true; try { fstream ifs(path, ios_base::in); CObjectSerializer serializer(&ifs); if (ifs.good()) { serializeFrom(serializer); } } catch (...) { success = false; } return success; } void CutterConfig::serializeTo(CObjectSerializer & os) { os.startSection("config", this); os.write("cutterWidth", cutterWidth); os.write("blockLeft", blockLeft); os.write("blockRight", blockRight); os.write("defaultFeedRate", defaultFeedRate); os.write("xLead", xScrewLead); os.write("xStepsPerRev", xStepsPerRev); os.write("xMicroStepping", xMicroStepping); os.write("yLead", yScrewLead); os.write("yStepsPerRev", yStepsPerRev); os.write("yMicroStepping", yMicroStepping); os.write("stepFrequency", stepFrequency); os.write("defaultComPort", defaultComPort.c_str()); os.write("connectAutomatically", connectAutomatically); os.write("defaultListenPort", defaultListenPort); os.write("listenAutomatically", listenAutomatically); os.startCollection("buttons", BUTTON_COUNT); for (int i = 0; i < BUTTON_COUNT; ++i) { os.startSection("button", buttons + i); os.write("label", buttons[i].label.c_str()); os.write("code", buttons[i].code.c_str()); os.endSection(); } os.endCollection(); os.endSection(); } void CutterConfig::serializeFrom(CObjectSerializer & os) { os.startReadSection("config", this); os.read("cutterWidth", cutterWidth); os.read("blockLeft", blockLeft); os.read("blockRight", blockRight); os.read("defaultFeedRate", defaultFeedRate); os.read("xLead", xScrewLead); os.read("xStepsPerRev", xStepsPerRev); os.read("xMicroStepping", xMicroStepping); os.read("yLead", yScrewLead); os.read("yStepsPerRev", yStepsPerRev); os.read("yMicroStepping", yMicroStepping); os.read("stepFrequency", stepFrequency); os.read("defaultComPort", defaultComPort); os.read("connectAutomatically", connectAutomatically); os.read("defaultListenPort", defaultListenPort); os.read("listenAutomatically", listenAutomatically); if (os.ifExists("buttons")) { int values = os.startReadCollection("buttons"); for (int i = 0; i < values; ++i) { std::string label; std::string code; os.startReadSection("button", buttons + i); os.read("label", label); os.read("code", code); os.endReadSection(); if (i < BUTTON_COUNT) { buttons[i].label = label; buttons[i].code = code; } } os.endReadCollection(); } os.endReadSection(); }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('customers', function (Blueprint $table) { $table->id(); $table->string('name')->nullable(); $table->string('contact')->nullable(); $table->string('address')->nullable(); $table->double('balance')->default(0.0); $table->double('opening_balance')->default(0.0); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('customers'); } };
<div class="register_page"> <div class="register_wrapper"> <div class="heading">Login</div> <div class="error_register" *ngIf="errorMsg">{{ errorMsg }}</div> <form class="ng_form" [formGroup]="form" (ngSubmit)="login()"> <input class="input_field" type="email" placeholder="Email address" name="email" formControlName="email" /> <ng-container *ngIf="form.get('email')?.touched"> <div class="error_register" *ngIf="form.get('email')?.errors?.['required']" > Email is required! </div> <div class="error_register" *ngIf="form.get('email')?.errors?.['appEmailValidator']" > Email is invalid! </div> </ng-container> <input class="input_field" type="password" placeholder="Password" name="password" formControlName="password" /> <ng-container *ngIf="form.get('password')?.touched"> <div class="error_register" *ngIf="form.get('password')?.errors?.['required']" > Password is required! </div> </ng-container> <button class="sign_in_button" type="submit" [disabled]="form.invalid"> Log in </button> <div class="log_in_link"> If you don't have an account? <a routerLink="/users/register" class="sign_in">Sign Up</a> </div> </form> </div> </div>
// // CoinDetailDataService.swift // CryptoApp // // Created by Uri on 26/11/23. // import Foundation import Combine class CoinDetailDataService { @Published var coinDetails: CoinDetailModel? = nil // exclusive cancellable for getCoinDetails var coinDetailSubscription: AnyCancellable? // we pass a coin from home module let coin: CoinModel init(coin: CoinModel) { self.coin = coin getCoinDetails() } func getCoinDetails() { guard let url = URL(string: "https://api.coingecko.com/api/v3/coins/\(coin.id)?localization=false&tickers=false&market_data=false&community_data=false&developer_data=false&sparkline=false") else { return } coinDetailSubscription = NetworkManager.fetch(url: url) .decode(type: CoinDetailModel.self, decoder: JSONDecoder()) .receive(on: DispatchQueue.main) .sink(receiveCompletion: NetworkManager.handleCompletion, receiveValue: { [weak self] (returnedCoinDetails) in guard let self = self else { return } self.coinDetails = returnedCoinDetails self.coinDetailSubscription?.cancel() // -> cancel because it won't call api continously }) } }
<script lang="ts" setup> import { type NewsArticle, type NewsTag, newsTags } from '~/types/news' const props = defineProps<{ article: NewsArticle; }>() /** 公開日 */ const dateString = computed<string>(() => { const article = props.article const date = new Date(article.date || article.createdAt) return date.toLocaleDateString('ja') }) /** お知らせの画像(なければデフォルト画像) */ const newsImage = computed<string>(() => { const article = props.article return article.thumbnail ? article.thumbnail.url : '/news_default.png' }) /** お知らせの種類(色とラベル) */ const tags = computed<NewsTag[]>(() => { return props.article.tags.length > 0 ? props.article.tags.map(tag => newsTags[tag]) : [newsTags['お知らせ']] }) </script> <template> <NuxtLink :to="`news/${props.article.id}`" class="news-link" > <NuxtImg class="image" :src="newsImage.replace('https://images.microcms-assets.io', 'microcms')" :alt="props.article.title" sizes="sm:1280px 500px" /> <strong class="title">{{ props.article.title }}</strong> <div class="date"> <UBadge v-for="tag in tags" :key="`newsLink-${props.article.id}-tag-${tag.label}`" :color="tag.color" :label="tag.label" size="md" /> {{ dateString }} </div> </NuxtLink> </template> <style lang="scss" scoped> .news-link { color: $primary; text-decoration: none; display: grid; grid-template-columns: 250px 1fr; grid-template-rows: auto 1fr; margin: 0 1rem 1rem 1rem; overflow: hidden; .image { grid-row: 1 / 3; max-height: 25vh; object-fit: contain; align-self: stretch; justify-self: center; } .title { padding: 1rem 1rem 0 1rem; font-size: 1.25rem; } .date { padding: 0.5rem 1rem 1rem 1rem; color: $sub; } &:hover { background-color: $bg-alt; } } @media (max-width: $spwidth) { .news-link { grid-template-columns: 1fr; grid-template-rows: auto auto auto; .image { grid-row: 1 / 2; } } } </style>
/*______________________________________________________ -------------- CLASS FOR MAKING A MANGO ---------------- == Created by Sameer Karna (Student of WhiteHat Jr.) == ______________CREATED ON 3rd OCTOBER 2020_______________ - - - - - - - - - Copyright (c) 2020 - - - - - - - - - - The permission to view and handle this game is hereby granted to all viewers. The above Copyright also disallows the viewers to copy this code. If any copied version is published then the viewer will be charged. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ~~~~~ The below CLASS file is a part of 'sketch.js' file ~~~~~ ~~~~ 'sketch.js' file comes under PLUCKING MANGOES project ~~~~ ~~~ The viewer is restricted from copying any content ~~~ */ //To create a Mango. class Mangoes { //This is used to construct an object. constructor(x, y, radius, angle) { //Properties for Mango var mango_options = { friction: 1, isStatic: true, } this.body = Bodies.circle(x, y, radius, mango_options); this.radius = radius; this.image = loadImage("mango.png"); this.angle = angle; //This adds the constructed object. World.add(world, this.body) } //This is used to display the constructed object. display() { //Variable for the constructed object's position. var position = this.body.position; //Variable for constructed object's angle. var angle = this.body.angle; //This is used for displaying an object. push(); translate(position.x, position.y); rotate(angle); //This makes the object be at its center. imageMode(CENTER) image(this.image, 0, 0, this.radius * 2.4, this.radius * 2.4); pop(); } } ---------- CLASS FILE END -----------
#!/usr/bin/python3 """Defines a class named Square.""" class Square: """Represent a square.""" def __init__(self, size=0): """Initialize a new Square instance. Args: size (int): The size of the square. Default is 0. """ self.__size = size if not isinstance(size, int): raise TypeError("size must be an integer") elif size < 0: raise ValueError("size must be >= 0") def area(self): """Calculate the area of the square. Returns: int: The area of the square. """ return self.__size ** 2
import { useState, useEffect } from "react"; import "./App.css"; function App() { const [message, setMessage] = useState(""); const [chats, setChats] = useState([]); const [isTyping, setIsTyping] = useState(false); useEffect(() => { scrollToBottom(); }, [chats]); const scrollToBottom = () => { const chatContainer = document.getElementById("chat-container"); if (chatContainer) { chatContainer.scrollTop = chatContainer.scrollHeight; } }; const chat = async (e, message) => { e.preventDefault(); if (!message) return; setIsTyping(true); let msgs = chats.slice(); // Create a copy of the chats array msgs.push({ role: "user", content: message }); setChats(msgs); setMessage(""); fetch("http://localhost:8000/query", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query: message, // Send the message as "query" to match the backend model }), }) .then((response) => response.json()) .then((data) => { msgs.push({ role: "AI", content: data.result }); // Assuming the response structure is { "result": "response content" } setChats(msgs); setIsTyping(false); }) .catch((error) => { console.log(error); }); }; return ( <main> <h1>Hive Chatbot</h1> <section id="chat-container"> {chats && chats.length ? chats.map((chat, index) => ( <p key={index} className={chat.role === "user" ? "user_msg" : "AI_msg"} // Add a class for AI messages > <span> <b>{chat.role.toUpperCase()}</b> </span> <span>:</span> <span>{chat.content}</span> </p> )) : ""} </section> <div className={isTyping ? "" : "hide"}> <p> <i>{isTyping ? "Typing" : ""}</i> </p> </div> <form onSubmit={(e) => chat(e, message)}> <input type="text" name="message" value={message} placeholder="Type a message here and hit Enter..." onChange={(e) => setMessage(e.target.value)} /> </form> </main> ); } export default App;
import { app } from "@/app"; import { createAndAuthenticateUser } from "@/utils/test/create-and-authenticate-user"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import request from "supertest"; import { prisma } from "@/lib/prisma"; import { createExercise } from "@/utils/test/create-exercise"; describe('Update Exercise Use Case (e2e)', () => { beforeAll(async () => { await app.ready() }) afterAll(async () => { await app.close() }) it('should be able to update exercise', async () => { const { token } = await createAndAuthenticateUser(app); const user = await prisma.user.findFirstOrThrow(); const exercise = await createExercise(user) const updateExerciseResponse = await request(app.server) .put(`/exercises/${exercise.id}`) .set('Authorization', `Bearer ${token}`) .send({ name: 'prettier exercise name', equipment: 'barbell', unilateral: false, }); expect(updateExerciseResponse.statusCode).toEqual(204); const updatedExercise = await prisma.exercise.findFirstOrThrow({ where: { id: exercise.id, }, }); expect(updatedExercise.name).toBe('prettier exercise name'); expect(updatedExercise.equipment).toBe('barbell'); expect(updatedExercise.unilateral).toBe(false); }); })
const usersService = require('./users-service'); const { errorResponder, errorTypes } = require('../../../core/errors'); /** * Handle get list of users request * @param {object} request - Express request object * @param {object} response - Express response object * @param {object} next - Express route middlewares * @returns {object} Response object or pass an error to the next route */ async function getUsers(request, response, next) { try { const users = await usersService.getUsers(); return response.status(200).json(users); } catch (error) { return next(error); } } /** * Handle get user detail request * @param {object} request - Express request object * @param {object} response - Express response object * @param {object} next - Express route middlewares * @returns {object} Response object or pass an error to the next route */ async function getUser(request, response, next) { try { const user = await usersService.getUser(request.params.id); if (!user) { throw errorResponder(errorTypes.UNPROCESSABLE_ENTITY, 'Unknown user'); } return response.status(200).json(user); } catch (error) { return next(error); } } /** * Handle create user request * @param {object} request - Express request object * @param {object} response - Express response object * @param {object} next - Express route middlewares * @returns {object} Response object or pass an error to the next route */ async function createUser(request, response, next) { try { const name = request.body.name; const email = request.body.email; const password = request.body.password; const passwordConfirm = request.body.passwordConfirm; // Check if the email is already in use const emailExists = await usersService.checkEmailAvailability(email); if (emailExists) { throw errorResponder( errorTypes.EMAIL_ALREADY_TAKEN ) } if(passwordConfirm !== password){ throw errorResponder ( errorTypes.INVALID_PASSWORD ) } // If the email is available, proceed to create the user const success = await usersService.createUser(name, email, password); if (!success) { throw errorResponder( errorTypes.UNPROCESSABLE_ENTITY, 'Failed to create user' ); } return response.status(200).json({ name, email }); } catch (error) { return next(error); } } /** * Handle update user request * @param {object} request - Express request object * @param {object} response - Express response object * @param {object} next - Express route middlewares * @returns {object} Response object or pass an error to the next route */ async function updateUser(request, response, next) { try { const id = request.params.id; const name = request.body.name; const email = request.body.email; const emailExists = await usersService.checkEmailAvailability(email); if (emailExists) { throw errorResponder( errorTypes.EMAIL_ALREADY_TAKEN ) } const success = await usersService.updateUser(id, name, email); if (!success) { throw errorResponder( errorTypes.UNPROCESSABLE_ENTITY, 'Failed to update user' ); } return response.status(200).json({ id }); } catch (error) { return next(error); } } /** * Handle delete user request * @param {object} request - Express request object * @param {object} response - Express response object * @param {object} next - Express route middlewares * @returns {object} Response object or pass an error to the next route */ async function deleteUser(request, response, next) { try { const id = request.params.id; const success = await usersService.deleteUser(id); if (!success) { throw errorResponder( errorTypes.UNPROCESSABLE_ENTITY, 'Failed to delete user' ); } return response.status(200).json({ id }); } catch (error) { return next(error); } } /** * Handle change Password user request * @param {object} request - Express request object * @param {object} response - Express response object * @param {object} next - Express route middlewares * @returns {object} Response object or pass an error to the next route */ async function changePassword(request, response, next) { try { const id = request.params.id; const currentPassword = request.body.currentPassword; const newPassword = request.body.newPassword; const confirmNewPass = request.body.confirmNewPass; const loginSuccess = await usersService.checkLoginCredentials(id, currentPassword); if (!loginSuccess) { throw errorResponder( errorTypes.INVALID_CREDENTIALS, 'Wrong password' ); } // Check if the new password matches the confirmed new password if (newPassword !== confirmNewPass) { throw errorResponder( errorTypes.INVALID_PASSWORD, 'New password does not match the confirmation' ); } // Proceed with changing the password const success = await usersService.changePassword(id, newPassword); if (!success) { throw errorResponder( errorTypes.UNPROCESSABLE_ENTITY, 'Failed to update user password' ); } return response.status(200).json({ id }); } catch (error) { return next(error); } } module.exports = { getUsers, getUser, createUser, updateUser, deleteUser, changePassword, };
import React, { useState } from 'react'; import { useNavigate } from 'react-router-dom'; import Cookies from 'js-cookie'; import axios from 'axios'; import Logo from '../styles/LandQuoteLogo.png' import '../styles/LoginReg.css' const LoginReg = () => { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [confirmPassword, setConfirmPassword] = useState(""); const [formToggle, setFormToggle] = useState(true); const navigate = useNavigate(); const [duplicateEmailError, setDuplicateEmailError] = useState(''); const [emailError, setEmailError] = useState(''); const [passwordError, setPasswordError] = useState(''); const [confirmPasswordError, setConfirmPasswordError] = useState(''); const registerHandler = (e) => { e.preventDefault(); axios.post("http://localhost:8000/api/users/register", { email, password, confirmPassword }, { withCredentials: true }) .then(res => { navigate("/home"); }) .catch(err => { console.log(err); const { errors } = err.response.data; if (err.response.data.message) { setDuplicateEmailError(err.response.data.message); } else { setDuplicateEmailError(''); } setEmailError(errors.email ? errors.email.message : ''); setPasswordError(errors.password ? errors.password.message : ''); setConfirmPasswordError(errors.confirmPassword ? errors.confirmPassword.message : ''); }); } const loginHandler = (e) => { e.preventDefault(); axios.post("http://localhost:8000/api/users/login", { email, password }, { withCredentials: true }) .then(res => { const token = res.data.token; // Store the token in cookies Cookies.set('token', token, {expires: 1}); // Set the token as the default Authorization header for future requests axios.defaults.headers.common['Authorization'] = `Bearer ${token}`; navigate("/home"); }) .catch(err => { console.log(err); setEmailError(err.response.data); }) } const handleFormToggle = () => { setFormToggle(!formToggle); } const handleInputChange = (e) => { const input = e.target; if (input.value.trim() !== "") { input.classList.add("has-content"); } else { input.classList.remove("has-content"); } } return ( <div className="test"> <img src={Logo} alt="Logo" className='logo-login'/> <div className='loginreg-container'> <i style={{ "--clr": "black" }}></i> <i style={{ "--clr": "black" }}></i> <i style={{ "--clr": "black" }}></i> <div className="slider-box"> <input id='slider' type='checkbox' checked={formToggle} onChange={handleFormToggle}/> <label className='login-label' htmlFor='slider'>Login</label> <label className='register-label' htmlFor='slider'>Register</label> <span className="slider"></span> </div> <ul className="social-icon2"> </ul> {formToggle ? ( <> <div className="login-form"> <form onSubmit={loginHandler}> {emailError && <p className='text-danger'>{emailError}</p>} <div className="input-container-login"> <input type="email" className="input-field-login" id="email" name="email" onChange={e => {setEmail(e.target.value); handleInputChange(e); }} /> <label htmlFor="email" className='input-label-login'>Email:</label> </div> <div className="input-container-login"> <input type="password" className="input-field-login" id="password" name="password" onChange={e => {setPassword(e.target.value); handleInputChange(e); }} /> <label htmlFor="password" className='input-label-login'>Password:</label> </div> <section className="section"> <label className="bb_button_login bb_button--corner_login" htmlFor="submitButton"> <span className="bb_button__text_login">Submit</span> </label> <button id="submitButton" type="submit" style={{ display: 'none' }} /> </section> </form> </div> </> ) : ( <> <div className="registration-form"> <form onSubmit={registerHandler} className='register'> {emailError && <p className='email-error'>{emailError}</p>} {duplicateEmailError && <p className='email-error'>{duplicateEmailError}</p>} <div className="input-container-login"> <input type="email" className="input-field-login" id="email" name="email" onChange={e => {setEmail(e.target.value); handleInputChange(e); }} /> <label htmlFor="email" className='input-label-login'>Email:</label> </div> {passwordError && <p className='password-error'>{passwordError}</p>} <div className="input-container-login"> <input type="password" className="input-field-login" id="password" name="password" onChange={e => {setPassword(e.target.value); handleInputChange(e); }} /> <label htmlFor="password" className='input-label-login'>Password:</label> </div> {confirmPasswordError && <p className='confirmPassword-error'>{confirmPasswordError}</p>} <div className="input-container-login"> <input type="password" className="input-field-login" id="confirmPassword" name="confirmPassword" onChange={e => {setConfirmPassword(e.target.value); handleInputChange(e); }} /> <label htmlFor="confirmPassword" className='input-label-login'>Confirm Password:</label> </div> <section className="section"> <label className="bb_button_login bb_button--corner_login" htmlFor="submitButton"> <span className="bb_button__text_login">Register</span> </label> <button id="submitButton" type="submit" style={{ display: 'none' }} /> </section> </form> </div> </> )} </div> </div> ) } export default LoginReg;
<template> <div :class="`${prefixCls}`"> <div :class="`${prefixCls}__items-wrap`" v-if ="value.length"> <div :class="`${prefixCls}__item`" v-for="(item,index) in value" :key="index" > <span>{{ item }}</span> <i @click="removeInput(index)" class="h3yun_All close-circle"></i> </div> </div> <div :class="[`${prefixCls}__add-wrap`,value.length ?'':'pt']" v-if = "!isShowArea"> <div :class="`${prefixCls}__add`" @click="showTextArea" > <i class="h3yun_All plus-o"></i> </div> </div> <div :class="`${prefixCls}__area-wrap`" v-if="isShowArea"> <h3-textarea ref="textarea" :maxlength="200" :border="false" placeholder="请输入" count @blur = "addText($event)" /> </div> </div> </template> <script lang='ts'> import {Component, Prop, Vue, Watch} from 'vue-property-decorator'; import {Mutation, Action, State, namespace} from 'vuex-class'; import { H3Textarea } from '@h3/thinking-ui'; const ReportPro = namespace('report'); @Component({ name: 'h3-report-multi-input', components: { H3Textarea } }) export default class ReportDateInput extends Vue { @Prop({ default: ()=> [] }) value!: Array<string | number | any>; prefixCls = 'h3-report-multi-input'; isShowArea: boolean = false; // 是否显示输入框 /** * 显示输入框 */ removeInput(i: number) { this.value.splice(i, 1); this.$emit('input', this.value); } /** * 关闭 */ closeTextArea() { this.isShowArea = false; } /** * 新增筛选器 */ addText(e) { const value = e.target.value.trim(); if (value) { this.value.push(value); } e.target.value = ''; this.closeTextArea(); this.$emit('input', this.value); } /** * 显示输入框 */ showTextArea(){ this.isShowArea = true; this.$nextTick(() => { (this.$refs.textarea as HTMLElement).focus(); }); } created() { } } </script> <style lang="less"> .h3-report-multi-input { &__items-wrap{ padding: 12px 16px 0 16px; } &__add-wrap { padding-left: 16px; padding-bottom: 12px; } &__add-wrap.pt { padding-top: 12px; } &__add{ height: 36px; width: 36px; background-color: #fff; border-radius: 50%; display: flex; justify-content: center; align-items: center; .plus-o { color: #107FFF; font-size: 24px; } } &__item{ position: relative; display: inline-block; background-color: #fff; border-radius: 4px; height: 32px; line-height: 32px; margin:0 12px 12px 0; padding: 0 20px 0 8px; max-width: calc(100% - 8px); overflow: hidden; font-size: 14px; span { display: inline-block; max-width: 100%; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .close-circle{ position: absolute; top: 0; right: 4px; font-size: 14px; line-height: 32px; margin-left: 4px; color: #C7C7C7; } } } </style>
use crate::{ DbcTable, Indexable, }; use crate::header::{ DbcHeader, HEADER_SIZE, parse_header, }; use std::io::Write; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct BankBagSlotPrices { pub rows: Vec<BankBagSlotPricesRow>, } impl DbcTable for BankBagSlotPrices { type Row = BankBagSlotPricesRow; const FILENAME: &'static str = "BankBagSlotPrices.dbc"; fn rows(&self) -> &[Self::Row] { &self.rows } fn rows_mut(&mut self) -> &mut [Self::Row] { &mut self.rows } fn read(b: &mut impl std::io::Read) -> Result<Self, crate::DbcError> { let mut header = [0_u8; HEADER_SIZE]; b.read_exact(&mut header)?; let header = parse_header(&header)?; if header.record_size != 8 { return Err(crate::DbcError::InvalidHeader( crate::InvalidHeaderError::RecordSize { expected: 8, actual: header.record_size, }, )); } if header.field_count != 2 { return Err(crate::DbcError::InvalidHeader( crate::InvalidHeaderError::FieldCount { expected: 2, actual: header.field_count, }, )); } let mut r = vec![0_u8; (header.record_count * header.record_size) as usize]; b.read_exact(&mut r)?; let mut rows = Vec::with_capacity(header.record_count as usize); for mut chunk in r.chunks(header.record_size as usize) { let chunk = &mut chunk; // id: primary_key (BankBagSlotPrices) uint32 let id = BankBagSlotPricesKey::new(crate::util::read_u32_le(chunk)?); // cost: int32 let cost = crate::util::read_i32_le(chunk)?; rows.push(BankBagSlotPricesRow { id, cost, }); } Ok(BankBagSlotPrices { rows, }) } fn write(&self, b: &mut impl Write) -> Result<(), std::io::Error> { let header = DbcHeader { record_count: self.rows.len() as u32, field_count: 2, record_size: 8, string_block_size: 1, }; b.write_all(&header.write_header())?; for row in &self.rows { // id: primary_key (BankBagSlotPrices) uint32 b.write_all(&row.id.id.to_le_bytes())?; // cost: int32 b.write_all(&row.cost.to_le_bytes())?; } b.write_all(&[0_u8])?; Ok(()) } } impl Indexable for BankBagSlotPrices { type PrimaryKey = BankBagSlotPricesKey; fn get(&self, key: impl TryInto<Self::PrimaryKey>) -> Option<&Self::Row> { let key = key.try_into().ok()?; self.rows.iter().find(|a| a.id.id == key.id) } fn get_mut(&mut self, key: impl TryInto<Self::PrimaryKey>) -> Option<&mut Self::Row> { let key = key.try_into().ok()?; self.rows.iter_mut().find(|a| a.id.id == key.id) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash, Default)] pub struct BankBagSlotPricesKey { pub id: u32 } impl BankBagSlotPricesKey { pub const fn new(id: u32) -> Self { Self { id } } } impl From<u8> for BankBagSlotPricesKey { fn from(v: u8) -> Self { Self::new(v.into()) } } impl From<u16> for BankBagSlotPricesKey { fn from(v: u16) -> Self { Self::new(v.into()) } } impl From<u32> for BankBagSlotPricesKey { fn from(v: u32) -> Self { Self::new(v) } } impl TryFrom<u64> for BankBagSlotPricesKey { type Error = u64; fn try_from(v: u64) -> Result<Self, Self::Error> { Ok(TryInto::<u32>::try_into(v).ok().ok_or(v)?.into()) } } impl TryFrom<usize> for BankBagSlotPricesKey { type Error = usize; fn try_from(v: usize) -> Result<Self, Self::Error> { Ok(TryInto::<u32>::try_into(v).ok().ok_or(v)?.into()) } } impl TryFrom<i8> for BankBagSlotPricesKey { type Error = i8; fn try_from(v: i8) -> Result<Self, Self::Error> { Ok(TryInto::<u32>::try_into(v).ok().ok_or(v)?.into()) } } impl TryFrom<i16> for BankBagSlotPricesKey { type Error = i16; fn try_from(v: i16) -> Result<Self, Self::Error> { Ok(TryInto::<u32>::try_into(v).ok().ok_or(v)?.into()) } } impl TryFrom<i32> for BankBagSlotPricesKey { type Error = i32; fn try_from(v: i32) -> Result<Self, Self::Error> { Ok(TryInto::<u32>::try_into(v).ok().ok_or(v)?.into()) } } impl TryFrom<i64> for BankBagSlotPricesKey { type Error = i64; fn try_from(v: i64) -> Result<Self, Self::Error> { Ok(TryInto::<u32>::try_into(v).ok().ok_or(v)?.into()) } } impl TryFrom<isize> for BankBagSlotPricesKey { type Error = isize; fn try_from(v: isize) -> Result<Self, Self::Error> { Ok(TryInto::<u32>::try_into(v).ok().ok_or(v)?.into()) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct BankBagSlotPricesRow { pub id: BankBagSlotPricesKey, pub cost: i32, }
use std::collections::HashMap; use std::fs::File; use std::io::{self, BufRead}; struct HandBuilder { map: HashMap<u8, usize>, joker: bool, } type Hand = ([usize; 5], [usize; 5]); impl HandBuilder { fn new(joker: bool) -> HandBuilder { let priority = if joker { "J23456789TQKA" } else { "23456789TJQKA" }; HandBuilder { map: HashMap::from_iter(priority.as_bytes().iter().enumerate().map(|(i, &b)| (b, i))), joker, } } fn build(&self, s: &str) -> Hand { let mut cards = [0; 5]; s.bytes() .enumerate() .for_each(|(i, b)| cards[i] = self.map[&b]); let mut card_counts = [0usize; 13]; cards.iter().for_each(|&c| card_counts[c] += 1); if self.joker { // Convert all Jokers to the most frequent non-Joker card. let max = card_counts .iter() .enumerate() .skip(1) // Skip Joker cards .map(|(i, &c)| (c, i)) .max() .unwrap(); card_counts[max.1] += card_counts[0]; card_counts[0] = 0; } let mut hist = [0usize; 5]; card_counts .iter() .filter(|&&c| c > 0) .for_each(|&c| hist[5 - c] += 1); (hist, cards) } } fn solve(path: &str, joker: bool) { let file = File::open(path).unwrap(); let reader = io::BufReader::new(file); let hand_builder = HandBuilder::new(joker); let mut input: Vec<(Hand, usize)> = reader .lines() .map(|line| { let line = line.unwrap(); let parts: Vec<_> = line.split(' ').collect(); let input = (hand_builder.build(parts[0]), parts[1].parse().unwrap()); input }) .collect(); input.sort(); let sum: usize = input.iter().enumerate().map(|(i, h)| (i + 1) * h.1).sum(); println!("{sum}"); } pub fn part1(path: &str) { solve(path, false); } pub fn part2(path: &str) { solve(path, true); }
import { Column, CreateDateColumn, Entity, JoinColumn, ManyToOne, OneToMany, OneToOne, PrimaryGeneratedColumn, UpdateDateColumn, } from 'typeorm'; import type { RetirementForm } from './retirement-form.entity'; import type { Approvals } from './approval.entity'; import type { AdvanceDetails } from './advance-details.entity'; import type { User } from './user.entity'; import { RoleColumn } from './role-column'; import { ApiProperty } from '@nestjs/swagger'; import { CurrencyScope, Role } from '../types'; import { SupportingDocs } from './supporting-docs.entity'; @Entity('advance_forms') export class AdvanceForm { @ApiProperty() @PrimaryGeneratedColumn() id: number; @ManyToOne('User', 'advanceForms') @JoinColumn({ name: 'user_id' }) user: User; @ApiProperty() @Column({ nullable: true, name: 'user_id' }) userId: number; @ApiProperty() @Column() purpose: string; @ApiProperty() @Column({ name: 'departure_date' }) departureDate: Date; @ApiProperty() @Column({ name: 'return_date' }) returnDate: Date; @ApiProperty() @Column() origination: string; @ApiProperty() @Column() destination: string; @ApiProperty() @Column({ nullable: true, name: 'pre_approval_remark_by_fin' }) preApprovalRemarkByFinance: string; @ApiProperty() @Column({ nullable: true, name: 'finance_go_ahead' }) financeGoAhead: boolean; @ApiProperty() @Column(RoleColumn({ enum: Role, name: 'approval_level' })) approvalLevel: Role; @ApiProperty() @Column( RoleColumn({ enum: Role, nullable: true, name: 'next_approval_level' }), ) nextApprovalLevel: Role; @ApiProperty() @Column({ type: 'bool', default: false, name: 'pushed_to_finance' }) pushedToFinance: boolean; @ApiProperty() @Column({ default: false, name: 'approved_by_fin' }) approvedByFin: boolean; @ApiProperty() @Column({ default: false }) rejected: boolean; @ApiProperty() @Column({ nullable: true, name: 'rejection_reason' }) rejectionReason: string; @ApiProperty() @UpdateDateColumn({ name: 'updated_at' }) updatedAt: Date; @ApiProperty() @CreateDateColumn({ name: 'created_at' }) createdAt: Date; @ApiProperty() @Column({ nullable: true, name: 'remark_by_fin' }) remarkByFin: string; @ApiProperty({ isArray: true, type: 'AdvanceDetails' }) @OneToMany('AdvanceDetails', 'advanceForm', { cascade: true }) details: AdvanceDetails[]; @OneToMany('Approvals', 'advanceApproved') approvals: Approvals[]; @ApiProperty() @Column({ nullable: true, name: 'retirement_id' }) retirementId: number; @ApiProperty() @Column({ type: 'numeric', name: 'total_amount' }) totalAmount: number; @ApiProperty() @OneToOne('SupportingDocs', 'advanceForm', { cascade: true, }) emailApproval: SupportingDocs; @OneToOne('RetirementForm', 'advance', { onDelete: 'RESTRICT', }) @JoinColumn({ name: 'retirement_id' }) retirement: RetirementForm; @Column({ default: false }) disbursed: boolean; @Column({ type: 'enum', enum: CurrencyScope, default: CurrencyScope.local, name: 'currency_scope', }) currencyScope: CurrencyScope; } export class SerializedAdvanceForm { id: number; user: User; userId: number; purpose: string; departureDate: Date; returnDate: Date; origination: string; destination: string; preApprovalRemarkByFinance: string; financeGoAhead: boolean; approvalLevel: number; nextApprovalLevel: Role; pushedToFinance: boolean; approvedByFin: boolean; rejected: boolean; rejectionReason: string; updatedAt: Date; createdAt: Date; remarkByFin: string; details: AdvanceDetails[]; approvals: Approvals[]; retirementId: number; totalAmount: number; emailApproval: SupportingDocs; retirement: RetirementForm; disbursed: boolean; currencyScope: CurrencyScope; constructor(partial: Partial<SerializedAdvanceForm>) { Object.assign(this, partial); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" href="style.css"> <title>Portfolio</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand">Jae Kim</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <section class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="contact.html">Contact</a> </li> <li class="nav-item active"> <a class="nav-link" href="portfolio.html">Portfolio</a> </li> <li class="nav-item"> <a class="nav-link" href="index.html">About</a> </li> </ul> </section> </nav> <article class="container"> <figure class="row"> <figcaption class="col-md-12"> <h1>Portfolio</h1> <hr> </figure> <figure class="row"> <figcaption class="col-md-6 project"> <div class="hovereffect"> <img src="Assets/Images/patched_index.png" alt="Work-Scheduler" class="img-fluid"> <div class="overlay"> <h2>Patched!</h2> <a class="btn btn-dark" href="https://github.com/ckomodo/garden-share">Patched</a> <a class="btn btn-dark" href="https://patchedapp.herokuapp.com/">Heroku Link</a> </div> </div> </figcaption> <figcaption class="col-md-6 project"> <div class="hovereffect"> <img src="Assets/Images/gym_bro.png" alt="Gym-Bro" class="img-fluid"> <div class="overlay"> <h2>Gym Bro!</h2> <a class="btn btn-dark" href="https://dan-gentile.github.io/gym-bro/index.html">Gym Bro Link</a> <a class="btn btn-dark" href="https://github.com/dan-gentile/gym-bro">Github Link</a> </div> </div> </figcaption> <figcaption class="col-md-6 project"> <div class="hovereffect"> <img src="Assets/Images/lion_king_quiz.png" alt="Lion-King-Quiz-Game" class="img-fluid"> <div class="overlay"> <h2>The Lion King Quiz Game!</h2> <a class="btn btn-dark" href="https://jsk321.github.io/Quiz-Game/">Lion King Quiz Game</a> <a class="btn btn-dark" href="https://github.com/JSK321/Quiz-Game">Github Link</a> </div> </div> </figcaption> <figcaption class="col-md-6 project"> <div class="hovereffect"> <img src="Assets/Images/workscheduler.png" alt="Work-Scheduler" class="img-fluid"> <div class="overlay"> <h2>Work Schedule Planner!</h2> <a class="btn btn-dark" href="https://jsk321.github.io/work-scheduler/">Work Scheduler</a> <a class="btn btn-dark" href="https://github.com/JSK321/work-scheduler">Github Link</a> </div> </div> </figcaption> <figcaption class="col-md-6 project"> <div class="hovereffect"> <img src="Assets/Images/burgers_r_us.png" alt="Burgers-R-Us" class="img-fluid"> <div class="overlay"> <h2>Burgers "R" Us!</h2> <a class="btn btn-dark" href="https://github.com/JSK321/burgers-r-us">Burgers "R" Us</a> <a class="btn btn-dark" href="https://jk-burgers.herokuapp.com/">Heroku Link</a> </div> </div> </figcaption> </figcaption> </figure> </article> <footer>&copy Copyright</footer> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> </body> </html>
# TCC forecast: Get and organise data # Bernardo Cainelli Gomes da Silva # Jun - 2023 # _____________________________________________________________________________ # _______________________________ HELPER FUNCTIONS ____________________________ # _____________________________________________________________________________ source("00_functions.R") fredr_set_key(pull(read_csv("fred_key.txt", col_names = F))) # View(imf_databases()) # View(imf_parameters(database_id = "MFS")) # View(imf_parameters(database_id = "MFS")[[3]]) # _____________________________________________________________________________ # ________________________________ GET DATA ___________________________________ # _____________________________________________________________________________ # nominal exchange rate, NSA nominal_exchange <- imf_dataset( database_id = "IFS", indicator = "ENDE_XDC_USD_RATE", freq = "M", ref_area = c("BR", "RU", "IN", "CN", "ZA") ) br_exchange <- filter_ifs(nominal_exchange, filter = "BR", colname = "br_exchange") ru_exchange <- filter_ifs(nominal_exchange, filter = "RU", colname = "ru_exchange") in_exchange <- filter_ifs(nominal_exchange, filter = "IN", colname = "in_exchange") cn_exchange <- filter_ifs(nominal_exchange, filter = "CN", colname = "cn_exchange") za_exchange <- filter_ifs(nominal_exchange, filter = "ZA", colname = "za_exchange") # a <- br_exchange %>% mutate( # lead1 = lead(br_exchange, 1), # var1 = (lead(br_exchange, 1) / br_exchange) - 1 # ) # b <- br_exchange %>% mutate( # lag1 = lag(br_exchange, 1), # var1 = (br_exchange / lag(br_exchange, 1)) - 1 # ) # c <- br_exchange %>% mutate( # log1 = log(br_exchange), # loglead = lead(log(br_exchange),1), # var1 = lead(log(br_exchange),1) - log(br_exchange) # ) br_exchange_rate <- br_exchange %>% mutate( br_exchange_rate_h1 = lead(log(br_exchange), 1) - log(br_exchange), br_exchange_rate_h12 = lead(log(br_exchange), 12) - log(br_exchange) ) %>% select(-br_exchange) ru_exchange_rate <- ru_exchange %>% mutate( ru_exchange_rate_h1 = lead(log(ru_exchange), 1) - log(ru_exchange), ru_exchange_rate_h12 = lead(log(ru_exchange), 12) - log(ru_exchange) ) %>% select(-ru_exchange) in_exchange_rate <- in_exchange %>% mutate( in_exchange_rate_h1 = lead(log(in_exchange), 1) - log(in_exchange), in_exchange_rate_h12 = lead(log(in_exchange), 12) - log(in_exchange) ) %>% select(-in_exchange) cn_exchange_rate <- cn_exchange %>% mutate( cn_exchange_rate_h1 = lead(log(cn_exchange), 1) - log(cn_exchange), cn_exchange_rate_h12 = lead(log(cn_exchange), 12) - log(cn_exchange) ) %>% select(-cn_exchange) za_exchange_rate <- za_exchange %>% mutate( za_exchange_rate_h1 = lead(log(za_exchange), 1) - log(za_exchange), za_exchange_rate_h12 = lead(log(za_exchange), 12) - log(za_exchange) ) %>% select(-za_exchange) # interest rate, NSA # br_interest <- fredr(series_id = "BRALOCOSTORSTM") %>% select(1, 3) # selic br_interest <- fredr(series_id = "IRSTCI01BRM156N") %>% select(1, 3) # interbank <24h ru_interest <- fredr(series_id = "IRSTCI01RUM156N") %>% select(1, 3) # in_interest <- fredr(series_id = "INDLOCOSTORSTM") %>% select(1, 3) # selic india in_interest <- fredr(series_id = "IRSTCI01INM156N") %>% select(1, 3) # interbank <24h cn_interest <- fredr(series_id = "IRSTCI01CNM156N") %>% select(1, 3) # interbank <24h za_interest <- fredr(series_id = "IRSTCI01ZAM156N") %>% select(1, 3) # interbank <24h # us_interest <- fredr(series_id = "FEDFUNDS") %>% select(1, 3) # fed funds us_interest <- fredr(series_id = "IR3TIB01USM156N") %>% select(1, 3) # interbank <24h colnames(br_interest) <- c("date", "br_interest") colnames(ru_interest) <- c("date", "ru_interest") colnames(in_interest) <- c("date", "in_interest") colnames(cn_interest) <- c("date", "cn_interest") colnames(za_interest) <- c("date", "za_interest") colnames(us_interest) <- c("date", "us_interest") # inflation, NSA inflation <- imf_dataset( database_id = "CPI", indicator = "PCPI_IX", freq = "M", ref_area = c("BR", "RU", "IN", "CN", "ZA", "US") ) br_inflation <- filter_ifs(inflation, filter = "BR", colname = "br_inflation") ru_inflation <- filter_ifs(inflation, filter = "RU", colname = "ru_inflation") in_inflation <- filter_ifs(inflation, filter = "IN", colname = "in_inflation") cn_inflation <- filter_ifs(inflation, filter = "CN", colname = "cn_inflation") za_inflation <- filter_ifs(inflation, filter = "ZA", colname = "za_inflation") us_inflation <- filter_ifs(inflation, filter = "US", colname = "us_inflation") br_inflation_rate <- br_inflation %>% mutate(br_inflation_rate = (br_inflation / lag(br_inflation)) - 1) %>% select(-br_inflation) ru_inflation_rate <- ru_inflation %>% mutate(ru_inflation_rate = (ru_inflation / lag(ru_inflation)) - 1) %>% select(-ru_inflation) in_inflation_rate <- in_inflation %>% mutate(in_inflation_rate = (in_inflation / lag(in_inflation)) - 1) %>% select(-in_inflation) cn_inflation_rate <- cn_inflation %>% mutate(cn_inflation_rate = (cn_inflation / lag(cn_inflation)) - 1) %>% select(-cn_inflation) za_inflation_rate <- za_inflation %>% mutate(za_inflation_rate = (za_inflation / lag(za_inflation)) - 1) %>% select(-za_inflation) us_inflation_rate <- us_inflation %>% mutate(us_inflation_rate = (us_inflation / lag(us_inflation)) - 1) %>% select(-us_inflation) # M1, NSA br_m1 <- fredr(series_id = "MANMM101BRM189N") %>% select(1, 3) colnames(br_m1) <- c("date", "br_m1") br_m1 <- mutate(br_m1, br_m1_log = log(br_m1)) ru_m1 <- fredr(series_id = "MANMM101RUM189N") %>% select(1, 3) colnames(ru_m1) <- c("date", "ru_m1") ru_m1 <- mutate(ru_m1, ru_m1_log = log(ru_m1)) in_m1 <- fredr(series_id = "MANMM101INM189N") %>% select(1, 3) colnames(in_m1) <- c("date", "in_m1") in_m1 <- mutate(in_m1, in_m1_log = log(in_m1)) cn_m1 <- fredr(series_id = "MANMM101CNM189N") %>% select(1, 3) colnames(cn_m1) <- c("date", "cn_m1") cn_m1 <- mutate(cn_m1, cn_m1_log = log(cn_m1)) za_m1 <- fredr(series_id = "MANMM101ZAM189N") %>% select(1, 3) colnames(za_m1) <- c("date", "za_m1") za_m1 <- mutate(za_m1, za_m1_log = log(za_m1)) us_m1 <- fredr(series_id = "MANMM101USM189N") %>% select(1, 3) colnames(us_m1) <- c("date", "us_m1") us_m1 <- mutate(us_m1, us_m1_log = log(us_m1)) # Industrial production: GDP proxy, monthly, NSA br_ip <- fredr(series_id = "BRAPRMNTO01IXOBM") %>% select(1, 3) ru_ip <- fredr(series_id = "RUSPRMNTO01IXOBM") %>% select(1, 3) # ru_ip <- fredr(series_id = "RUSPRINTO01IXOBM") %>% select(1, 3) # ru_ip <- fredr(series_id = "RUSSLRTTO02MLM") %>% select(1, 3) in_ip <- fredr(series_id = "INDPRMNTO01IXOBM") %>% select(1, 3) cn_ip <- fredr(series_id = "CHNPRINTO01IXPYM") %>% select(1, 3) za_ip <- fredr(series_id = "ZAFPRMNTO01IXOBM") %>% select(1, 3) us_ip <- fredr(series_id = "USAPRMNTO01IXOBM") %>% select(1, 3) us_ip <- us_ip[rowSums(is.na(us_ip)) == 0, ] # nominal gdp, quarterly, NSA nominal_gdp <- imf_dataset( database_id = "IFS", indicator = "NGDP_NSA_XDC", freq = "Q", ref_area = c("BR", "RU", "IN", "CN", "ZA", "US") ) # Output gap via Hamilton Filter from quarterly series # br_gap <- output_gap_q(data = nominal_gdp, filtro = "BR", colname = "br_gap") # ru_gap <- output_gap_q(data = nominal_gdp, filtro = "RU", colname = "ru_gap") # in_gap <- output_gap_q(data = nominal_gdp, filtro = "IN", colname = "in_gap") # cn_gap <- output_gap_q(data = nominal_gdp, filtro = "CN", colname = "cn_gap") # za_gap <- output_gap_q(data = nominal_gdp, filtro = "ZA", colname = "za_gap") # us_gap <- output_gap_q(data = nominal_gdp, filtro = "US", colname = "us_gap") # gdp: Quarterly to Monthly br_gdp <- quartet_to_monthly( data_gdp = nominal_gdp, data_ip = br_ip, filtro = "BR", # colname = "br_gdp", gdp_ano_0 = 1996, gdp_quarter_0 = 1, ip_ano_0 = 1975, ip_mes_0 = 1 ) %>% mutate(gdp_log = log(value)) ru_gdp <- quartet_to_monthly( data_gdp = nominal_gdp, data_ip = ru_ip, filtro = "RU", # colname = "ru_gdp", gdp_ano_0 = 2003, gdp_quarter_0 = 1, ip_ano_0 = 1999, ip_mes_0 = 1 ) %>% mutate(gdp_log = log(value)) in_gdp <- quartet_to_monthly( data_gdp = nominal_gdp, data_ip = in_ip, filtro = "IN", # colname = "in_gdp", gdp_ano_0 = 2004, gdp_quarter_0 = 2, ip_ano_0 = 1994, ip_mes_0 = 4 ) %>% mutate(gdp_log = log(value)) cn_gdp <- quartet_to_monthly( data_gdp = nominal_gdp, data_ip = cn_ip, filtro = "CN", # colname = "cn_gdp", gdp_ano_0 = 1992, gdp_quarter_0 = 1, ip_ano_0 = 1999, ip_mes_0 = 1 ) %>% mutate(gdp_log = log(value)) za_gdp <- quartet_to_monthly( data_gdp = nominal_gdp, data_ip = za_ip, filtro = "ZA", # colname = "za_gdp", gdp_ano_0 = 1993, gdp_quarter_0 = 1, ip_ano_0 = 1990, ip_mes_0 = 1 ) %>% mutate(gdp_log = log(value)) us_gdp <- quartet_to_monthly( data_gdp = nominal_gdp, data_ip = us_ip, filtro = "US", # colname = "us_gdp", gdp_ano_0 = 1950, gdp_quarter_0 = 1, ip_ano_0 = 1960, ip_mes_0 = 1 ) %>% mutate(gdp_log = log(value)) # Output gap via Hamilton Filter from monthly series br_gap <- output_gap_m(data = br_gdp, colname = "br_gap") ru_gap <- output_gap_m(data = ru_gdp, colname = "ru_gap") in_gap <- output_gap_m(data = in_gdp, colname = "in_gap") cn_gap <- output_gap_m(data = cn_gdp, colname = "cn_gap") za_gap <- output_gap_m(data = za_gdp, colname = "za_gap") us_gap <- output_gap_m(data = us_gdp, colname = "us_gap") # VIX vix <- fredr(series_id = "VIXCLS") %>% select(1, 3) %>% dplyr::mutate(date = lubridate::floor_date(date, "month")) %>% group_by(date) %>% summarise(vix = dplyr::last(value)) # Rename colnames of gdp here because if done before would break the functions colnames(br_gdp) <- c("date", "br_gdp", "br_gdp_log") colnames(ru_gdp) <- c("date", "ru_gdp", "ru_gdp_log") colnames(in_gdp) <- c("date", "in_gdp", "in_gdp_log") colnames(cn_gdp) <- c("date", "cn_gdp", "cn_gdp_log") colnames(za_gdp) <- c("date", "za_gdp", "za_gdp_log") colnames(us_gdp) <- c("date", "us_gdp", "us_gdp_log") # _____________________________________________________________________________ # ______________________________ BUILD PANEL __________________________________ # _____________________________________________________________________________ # All the data panel_data <- reduce( list( br_exchange, br_exchange_rate, br_gap, br_gdp, br_inflation, br_inflation_rate, br_interest, br_m1, ru_exchange, ru_exchange_rate, ru_gap, ru_gdp, ru_inflation, ru_inflation_rate, ru_interest, ru_m1, in_exchange, in_exchange_rate, in_gap, in_gdp, in_inflation, in_inflation_rate, in_interest, in_m1, cn_exchange, cn_exchange_rate, cn_gap, cn_gdp, cn_inflation, cn_inflation_rate, cn_interest, cn_m1, za_exchange, za_exchange_rate, za_gap, za_gdp, za_inflation, za_inflation_rate, za_interest, za_m1, us_gap, us_gdp, us_inflation, us_inflation_rate, us_interest, us_m1, vix ), full_join, by = "date" ) %>% mutate( br_interest_lag = dplyr::lag(br_interest, 1), ru_interest_lag = dplyr::lag(ru_interest, 1), in_interest_lag = dplyr::lag(in_interest, 1), cn_interest_lag = dplyr::lag(cn_interest, 1), za_interest_lag = dplyr::lag(za_interest, 1), us_interest_lag = dplyr::lag(us_interest, 1), us_inflation_log = log(us_inflation), br_exchange_log = log(br_exchange), br_inflation_log = log(br_inflation), ru_exchange_log = log(ru_exchange), ru_inflation_log = log(ru_inflation), in_exchange_log = log(in_exchange), in_inflation_log = log(in_inflation), cn_exchange_log = log(cn_exchange), cn_inflation_log = log(cn_inflation), za_exchange_log = log(za_exchange), za_inflation_log = log(za_inflation) ) %>% arrange(date) panel_data <- panel_data[rowSums(is.na(panel_data)) == 0, ] rownames(panel_data) <- seq(length = nrow(panel_data)) # Brazilian data br_panel_data <- reduce( list( br_exchange, br_exchange_rate, br_gap, br_gdp, br_inflation, br_interest, br_m1, br_inflation_rate, us_gap, us_gdp, us_inflation, us_interest, us_m1, us_inflation_rate, vix ), full_join, by = "date" ) %>% mutate( br_interest_lag = dplyr::lag(br_interest, 1), us_interest_lag = dplyr::lag(us_interest, 1), br_exchange_log = log(br_exchange), br_inflation_log = log(br_inflation), us_inflation_log = log(us_inflation), diff_inflation_rate = br_inflation_rate - us_inflation_rate, diff_gap = br_gap - us_gap, real_exchange_rate = br_exchange_log + us_inflation_log - br_inflation_log, diff_interest_lag = br_interest_lag - us_interest_lag, diff_interest = br_interest - us_interest, diff_m1 = br_m1_log - us_m1_log, diff_gdp = br_gdp_log - us_gdp_log ) %>% arrange(date) br_panel_data <- br_panel_data[rowSums(is.na(br_panel_data)) == 0, ] rownames(br_panel_data) <- seq(length = nrow(br_panel_data)) # Russian data ru_panel_data <- reduce( list( ru_exchange, ru_exchange_rate, ru_gap, ru_gdp, ru_inflation, ru_interest, ru_m1, ru_inflation_rate, us_gap, us_gdp, us_inflation, us_interest, us_m1, us_inflation_rate, vix ), full_join, by = "date" ) %>% mutate( ru_interest_lag = dplyr::lag(ru_interest, 1), us_interest_lag = dplyr::lag(us_interest, 1), ru_exchange_log = log(ru_exchange), ru_inflation_log = log(ru_inflation), us_inflation_log = log(us_inflation), diff_inflation_rate = ru_inflation_rate - us_inflation_rate, diff_gap = ru_gap - us_gap, real_exchange_rate = ru_exchange_log + us_inflation_log - ru_inflation_log, diff_interest_lag = ru_interest_lag - us_interest_lag, diff_interest = ru_interest - us_interest, diff_m1 = ru_m1_log - us_m1_log, diff_gdp = ru_gdp_log - us_gdp_log ) %>% arrange(date) ru_panel_data <- ru_panel_data[rowSums(is.na(ru_panel_data)) == 0, ] rownames(ru_panel_data) <- seq(length = nrow(ru_panel_data)) # Indian data in_panel_data <- reduce( list( in_exchange, in_exchange_rate, in_gap, in_gdp, in_inflation, in_interest, in_m1, in_inflation_rate, us_gap, us_gdp, us_inflation, us_interest, us_m1, us_inflation_rate, vix ), full_join, by = "date" ) %>% mutate( in_interest_lag = dplyr::lag(in_interest, 1), us_interest_lag = dplyr::lag(us_interest, 1), in_exchange_log = log(in_exchange), in_inflation_log = log(in_inflation), us_inflation_log = log(us_inflation), diff_inflation_rate = in_inflation_rate - us_inflation_rate, diff_gap = in_gap - us_gap, real_exchange_rate = in_exchange_log + us_inflation_log - in_inflation_log, diff_interest_lag = in_interest_lag - us_interest_lag, diff_interest = in_interest - us_interest, diff_m1 = in_m1_log - us_m1_log, diff_gdp = in_gdp_log - us_gdp_log ) %>% arrange(date) in_panel_data <- in_panel_data[rowSums(is.na(in_panel_data)) == 0, ] rownames(in_panel_data) <- seq(length = nrow(in_panel_data)) # Chinese data cn_panel_data <- reduce( list( cn_exchange, cn_exchange_rate, cn_gap, cn_gdp, cn_inflation, cn_interest, cn_m1, cn_inflation_rate, us_gap, us_gdp, us_inflation, us_interest, us_m1, us_inflation_rate, vix ), full_join, by = "date" ) %>% mutate( cn_interest_lag = dplyr::lag(cn_interest, 1), us_interest_lag = dplyr::lag(us_interest, 1), cn_exchange_log = log(cn_exchange), cn_inflation_log = log(cn_inflation), us_inflation_log = log(us_inflation), diff_inflation_rate = cn_inflation_rate - us_inflation_rate, diff_gap = cn_gap - us_gap, real_exchange_rate = cn_exchange_log + us_inflation_log - cn_inflation_log, diff_interest_lag = cn_interest_lag - us_interest_lag, diff_interest = cn_interest - us_interest, diff_m1 = cn_m1_log - us_m1_log, diff_gdp = cn_gdp_log - us_gdp_log ) %>% arrange(date) cn_panel_data <- cn_panel_data[rowSums(is.na(cn_panel_data)) == 0, ] rownames(cn_panel_data) <- seq(length = nrow(cn_panel_data)) # South african data za_panel_data <- reduce( list( za_exchange, za_exchange_rate, za_gap, za_gdp, za_inflation, za_interest, za_m1, za_inflation_rate, us_gap, us_gdp, us_inflation, us_interest, us_m1, us_inflation_rate, vix ), full_join, by = "date" ) %>% mutate( za_interest_lag = dplyr::lag(za_interest, 1), us_interest_lag = dplyr::lag(us_interest, 1), za_exchange_log = log(za_exchange), za_inflation_log = log(za_inflation), us_inflation_log = log(us_inflation), diff_inflation_rate = za_inflation_rate - us_inflation_rate, diff_gap = za_gap - us_gap, real_exchange_rate = za_exchange_log + us_inflation_log - za_inflation_log, diff_interest_lag = za_interest_lag - us_interest_lag, diff_interest = za_interest - us_interest, diff_m1 = za_m1_log - us_m1_log, diff_gdp = za_gdp_log - us_gdp_log ) %>% arrange(date) za_panel_data <- za_panel_data[rowSums(is.na(za_panel_data)) == 0, ] rownames(za_panel_data) <- seq(length = nrow(za_panel_data)) # Export write_csv2(panel_data, "outputs/panel_data.csv") write_csv2(br_panel_data, "outputs/br_panel_data.csv") write_csv2(ru_panel_data, "outputs/ru_panel_data.csv") write_csv2(in_panel_data, "outputs/in_panel_data.csv") write_csv2(cn_panel_data, "outputs/cn_panel_data.csv") write_csv2(za_panel_data, "outputs/za_panel_data.csv")
package repository.module.integration.bse import com.fincash.integration.ws.client.bsestar.upload.MFAPIResponse import com.fincash.integration.ws.client.bsestar.{GetPasswordResponse, SipOrderEntryParamResponse, SpreadOrderEntryParamResponse, SwitchOrderEntryParamResponse, XsipOrderEntryParamResponse, _} import com.google.inject.Inject import helpers.integration.bse.{AdditionalResponseLogHelper, OrderResponseLogHelper} import repository.module.IntegrationRepository import scala.collection.mutable.ListBuffer /** * Created by fincash on 24-01-2017. */ class BSEResponseLogRepository @Inject()(integrationRepository: IntegrationRepository){ def saveGetPasswordResponse(getPasswordResponse: GetPasswordResponse, integrationId:String, userName:String) = { val paramListTuple = OrderResponseLogHelper.getPasswordParameters(getPasswordResponse) saveResponseLog(paramListTuple,integrationId,userName) } def saveOrderEntryResponse(orderEntryParamResponse: OrderEntryParamResponse, integrationId:String, userName:String) = { val paramListTuple = OrderResponseLogHelper.getOrderParameters(orderEntryParamResponse) saveResponseLog(paramListTuple,integrationId,userName) } def saveSipOrderEntryResponse(sipOrderEntryParamResponse: SipOrderEntryParamResponse, integrationId:String, userName:String) = { val paramListTuple = OrderResponseLogHelper.getSipOrderParameters(sipOrderEntryParamResponse) saveResponseLog(paramListTuple,integrationId,userName) } def saveXSipOrderEntryResponse(xsipOrderEntryParamResponse: XsipOrderEntryParamResponse, integrationId:String, userName:String) = { val paramListTuple = OrderResponseLogHelper.getXSipOrderParameters(xsipOrderEntryParamResponse) saveResponseLog(paramListTuple,integrationId,userName) } def saveSpreadOrderEntryResponse(spreadOrderEntryParamResponse: SpreadOrderEntryParamResponse, integrationId:String, userName:String) = { val paramListTuple = OrderResponseLogHelper.getSpreadOrderParameters(spreadOrderEntryParamResponse) saveResponseLog(paramListTuple,integrationId,userName) } def saveSwitchOrderEntryResponse(switchOrderEntryParamResponse: SwitchOrderEntryParamResponse, integrationId:String, userName:String) = { val paramListTuple = OrderResponseLogHelper.getSwitchOrderParameters(switchOrderEntryParamResponse) saveResponseLog(paramListTuple,integrationId,userName) } def saveMfApiGetPasswordResponse(passwordResponse: com.fincash.integration.ws.client.bsestar.upload.GetPasswordResponse, integrationId:String, userName:String) = { val paramListTuple = AdditionalResponseLogHelper.getPasswordParameters(passwordResponse) saveResponseLog(paramListTuple,integrationId,userName) } def saveMfApiResponse(mFAPIResponse: MFAPIResponse, integrationId:String, userName:String) = { val paramListTuple = AdditionalResponseLogHelper.getMfApiParameters(mFAPIResponse) saveResponseLog(paramListTuple,integrationId,userName) } private def saveResponseLog(paramListTuple:(ListBuffer[String],ListBuffer[String]),integrationId:String,userName:String) = { val paramNameList:ListBuffer[String] = paramListTuple._1 val paramValueList:ListBuffer[String] = paramListTuple._2 integrationRepository.saveBSEResponseParameters(Some(integrationId),paramNameList,paramValueList,userName) } }
import React from "react"; import { motion, Transition, SVGMotionProps } from "framer-motion"; type Props = { isOpen: boolean; width?: number; height?: number; strokeWidth?: number; transition?: Transition; lineProps?: SVGMotionProps<SVGLineElement>; lineClassNames?: string; }; const MenuButton = ({ isOpen = false, width = 24, height = 24, strokeWidth = 2, transition = {}, lineProps = {}, lineClassNames = "" }: Props) => { const variant = isOpen ? "opened" : "closed"; const top = { closed: { rotate: 0, translateY: 0 }, opened: { rotate: 45, translateY: 2 } }; const center = { closed: { opacity: 1 }, opened: { opacity: 0 } }; const bottom = { closed: { rotate: 0, translateY: 0 }, opened: { rotate: -45, translateY: -2 } }; lineProps = { strokeWidth: strokeWidth as number, vectorEffect: "non-scaling-stroke", initial: "closed", animate: variant, transition, }; const unitHeight = 4; const unitWidth = (unitHeight * (width as number)) / (height as number); return ( <motion.svg viewBox={`0 0 ${unitWidth} ${unitHeight}`} overflow="visible" preserveAspectRatio="none" width={width} height={height} className="cursor-pointer" > <motion.line x1="0" x2={unitWidth} y1="0" y2="0" variants={top} className={lineClassNames} {...lineProps} /> <motion.line x1="0" x2={unitWidth} y1="2" y2="2" variants={center} className={lineClassNames} {...lineProps} /> <motion.line x1="0" x2={unitWidth} y1="4" y2="4" variants={bottom} className={lineClassNames} {...lineProps} /> </motion.svg> ); }; export default MenuButton;
import { NextApiRequest, NextApiResponse } from 'next'; import { getSession } from 'next-auth/client'; import Log from '../../../utils/Log'; import { TwitterApi } from 'twitter-api-v2'; import TwitterAuth from '../../../utils/TwitterAuth'; import { TweetV1, UserV1 } from 'twitter-api-v2/dist/types'; import { Collection, Db, FindAndModifyWriteOpResultObject } from 'mongodb'; import MongoDBUtils from '../../../utils/MongoDBUtils'; import constants from '../../../constants/constants'; import { POAPTwitterParticipants } from '../../../models/POAPTwitterParticipants'; import { Session } from 'next-auth'; import { POAPTwitterSettings } from '../../../models/POAPTwitterSettings'; import dayjs, { Dayjs } from 'dayjs'; const tweet = async (request: NextApiRequest, response: NextApiResponse) => { const session = await getSession({ req: request }); if (session == null || !session.isTwitterLinked) { Log.warn('not authorized 404'); response.status(401).send('Not authorized'); return; } switch(request.method) { case 'POST': await postTweet(session, response, request.body?.code); return; case 'GET': await checkTweet(session, request, response); return; default: Log.warn('not found 404'); response.status(404).send('Not found.'); } }; const postTweet = async (session: Session, response: NextApiResponse, code?: string): Promise<void> => { Log.debug('starting to post tweet'); if (code == null) { Log.warn('missing claim code'); response.status(400).send('Missing claim code.'); return; } const client: TwitterApi = TwitterAuth.clientV1(session.twitterAccessToken, session.twitterAccessSecret); const twitterUser: UserV1 = await client.currentUser(); const tweetResult: TweetV1 = await client.v1.tweet(`I consent to receiving a #POAP claim link for attending https://twitter.com/i/spaces/${code}`); const tweetId: string = tweetResult.id_str; if (tweetId == null) { response.status(200).send('Failed to tweet twitter spaces status'); return; } const db: Db = await MongoDBUtils.connectDb(constants.DB_NAME_DEGEN); const poapSettings: Collection<POAPTwitterSettings> = db.collection(constants.DB_COLLECTION_POAP_TWITTER_SETTINGS); const organizerSettings: POAPTwitterSettings = await poapSettings.findOne({ isActive: true, twitterSpaceId: code, }); if (organizerSettings == null) { Log.warn('twitter settings not found'); response.status(404).send('Twitter event settings not found.'); return; } const currentDate: Dayjs = dayjs(); const poapTwitterParticipants: Collection<POAPTwitterParticipants> = db.collection(constants.DB_COLLECTION_POAP_TWITTER_PARTICIPANTS); const result: FindAndModifyWriteOpResultObject<POAPTwitterParticipants> = await poapTwitterParticipants.findOneAndReplace({ twitterSpaceId: code, twitterUserId: twitterUser.id_str, }, { twitterSpaceId: code, twitterUserId: twitterUser.id_str, tweetId: tweetId, dateOfTweet: currentDate.toISOString(), }, { upsert: true, }); if (result.ok == 1) { response.status(200).send({ description: 'Success', tweetId: tweetId, }); return; } response.status(500).send('Failed'); }; const checkTweet = async (session: Session, request: NextApiRequest, response: NextApiResponse) => { Log.debug('starting to check if tweet was posted'); const code: string = request.query.code as string; if (code == null) { Log.warn('missing claim code'); response.status(400).send('Missing claim code'); return; } const client: TwitterApi = TwitterAuth.clientV1(session.twitterAccessToken, session.twitterAccessSecret); const currentTwitterUser: UserV1 = await client.currentUser(); const db: Db = await MongoDBUtils.connectDb(constants.DB_NAME_DEGEN); const poapTwitterParticipantsCollection: Collection<POAPTwitterParticipants> = db.collection(constants.DB_COLLECTION_POAP_TWITTER_PARTICIPANTS); const result: POAPTwitterParticipants = await poapTwitterParticipantsCollection.findOne({ twitterSpaceId: code, twitterUserId: currentTwitterUser.id_str, }); if (result == null || result.tweetId == null) { Log.debug('tweet not found in db'); response.status(200).send({ hasPosted: false, }); return; } const tweet: TweetV1 = await client.v1.singleTweet(result.tweetId); if (tweet == null || tweet.user == null || tweet.user.id_str != currentTwitterUser.id_str) { Log.debug('tweet not found'); response.status(200).send({ hasPosted: false, }); return; } response.status(200).send({ hasPosted: true, }); }; export default tweet;
### includes() 在一个字符串中搜索是否包含指定的另一个字符串,返回布尔值。该方法区分字符串大小写。 `includes(searchString, position)` `position`可选值,表示从指定索引开始搜索。 ```js filename="example.js" 'hello world'.includes('hello'); // true 'hello world'.includes('Hello'); // false 'hello world'.includes('hello', 6); // false ``` ### startsWith() 和 endsWith() `startsWith()`用于判断字符串是否以指定字符串开头,返回布尔值。该方法区分字符串大小写。 `endsWith()`用于判断字符串是否以指定字符串结尾,返回布尔值。该方法区分字符串大小写。 ```js filename="example.js" 'hello world'.startsWith('hello'); // true 'hello world'.startsWith('Hello'); // false 'hello world'.startsWith('world', 6); // true 'hello world'.endsWith('world'); // true 'hello world'.endsWith('World'); // false 'hello world'.endsWith('hello', 5); // true ``` ### repeat() `repeat()`方法返回一个新字符串,表示将原字符串重复n次。 ```js filename="example.js" 'x'.repeat(3); // 'xxx' 'hello'.repeat(2); // 'hellohello' 'na'.repeat(0); // '' // 参数如果是小数,会被上取整 'na'.repeat(2.9); // 'nana' // 参数如果是负数或Infinity,会报错 'na'.repeat(-1); // RangeError // 参数如果是字符串,则会先转换成数字 'na'.repeat('na'); // '' 'na'.repeat('3'); // 'nanana' // 参数如果是对象,则会先转换成字符串 'na'.repeat({}); // '' 'na'.repeat({ valueOf: () => 2 }); // 'nana' // 参数如果是NaN,则等同于0 'na'.repeat(NaN); // '' // 参数如果是0到-1之间的小数,则等同于0 'na'.repeat(-0.9); // '' ``` ### padStart() 和 padEnd() ES6中新增了补全字符串长度的方法。如果某个字符串不够指定长度,则会从头部或尾部补全指定内容。 ```js filename="example.js" 'a'.padStart(5, 'bc'); // 'bcbca' 'a'.padStart(6, 'bc'); // 'bcbcba' 'a'.padEnd(5, 'bc'); // 'abcbc' 'a'.padEnd(6, 'bc'); // 'abcbcb' ``` 如果原字符串的长度,等于或大于指定的最小长度,则返回原字符串。 如果省略了第二个参数,则会使用空格进行补全。 ```js filename="example.js" 'abc'.padStart(3, 'd'); // 'abc' 'abc'.padStart(10); // ' abc' ``` ### trimStart() 和 trimEnd() 该方法都是用于去除字符串空格,区别在于`trimStart()`只去除头部空格,`trimEnd()`只去除尾部空格。头尾空格都去除的是`trim()`。 ```js filename="example.js" ' abc '.trimStart(); // 'abc ' ' abc '.trimEnd(); // ' abc' ' abc '.trim(); // 'abc' ```
/** * Copied from DRtunime * Treap container for internal usage. * * Copyright: Copyright Digital Mars 2014 - 2014. * License: $(WEB www.boost.org/LICENSE_1_0.txt, Boost License 1.0). */ module vulture.treap; import core.stdc.stdlib; struct Rand48 { private ulong rng_state; @safe @nogc nothrow: void defaultSeed() { import ctime = core.stdc.time : time; seed(cast(uint)ctime.time(null)); } pure: void seed(uint seedval) { assert(seedval); rng_state = cast(ulong)seedval << 16 | 0x330e; popFront(); } auto opCall() { auto result = front; popFront(); return result; } @property uint front() { return cast(uint)(rng_state >> 16); } void popFront() { immutable ulong a = 25214903917; immutable ulong c = 11; immutable ulong m_mask = (1uL << 48uL) - 1; rng_state = (a*rng_state+c) & m_mask; } enum empty = false; } struct Treap(E) { nothrow: static struct Node { Node* left, right; E element; uint priority; } @disable this(this); ~this() { removeAll(); } void initialize() { rand48.defaultSeed(); } void insert(E element) @nogc { root = insert(root, element); } void remove(E element) { remove(&root, element); } int opApply(scope int delegate(ref E) nothrow dg) { return (cast(const)&this).opApply((ref const E e) => dg(*cast(E*)&e)); } int opApply(scope int delegate(ref const E) nothrow dg) const { return opApplyHelper(root, dg); } version(unittest) bool opEquals(E[] elements) { size_t i; foreach (e; this) { if (i >= elements.length) return false; if (e != elements[i++]) return false; } return i == elements.length; } void removeAll() { removeAll(root); root = null; } version(none) uint height() { static uint height(Node* node) { if (!node) return 0; auto left = height(node.left); auto right = height(node.right); return 1 + (left > right ? left : right); } return height(root); } version(none) size_t count() { static size_t count(Node* node) { if (!node) return 0; return count(node.left) + count(node.right) + 1; } return count(root); } private: Node* root; Rand48 rand48; Node* allocNode(E element) @nogc { Node* node = cast(Node*)malloc(Node.sizeof); node.left = node.right = null; node.priority = rand48(); node.element = element; return node; } Node* insert(Node* node, E element) @nogc { if (!node) return allocNode(element); else if (element < node.element) { node.left = insert(node.left, element); if (node.left.priority < node.priority) node = rotateR(node); } else if (element > node.element) { node.right = insert(node.right, element); if (node.right.priority < node.priority) node = rotateL(node); } else {} // ignore duplicate return node; } static: void freeNode(Node* node) { free(node); } Node* rotateL(Node* root) { auto pivot = root.right; root.right = pivot.left; pivot.left = root; return pivot; } Node* rotateR(Node* root) { auto pivot = root.left; root.left = pivot.right; pivot.right = root; return pivot; } void remove(Node** ppnode, E element) { Node* node = *ppnode; if (!node) return; // element not in treap if (element < node.element) { remove(&node.left, element); } else if (element > node.element) { remove(&node.right, element); } else { while (node.left && node.right) { if (node.left.priority < node.right.priority) { *ppnode = rotateR(node); ppnode = &(*ppnode).right; } else { *ppnode = rotateL(node); ppnode = &(*ppnode).left; } } if (!node.left) *ppnode = node.right; else *ppnode = node.left; freeNode(node); } } void removeAll(Node* node) { if (!node) return; removeAll(node.left); removeAll(node.right); freeNode(node); } int opApplyHelper(const Node* node, scope int delegate(ref const E) nothrow dg) { if (!node) return 0; int result = opApplyHelper(node.left, dg); if (result) return result; result = dg(node.element); if (result) return result; return opApplyHelper(node.right, dg); } }
import { useContext } from "react"; import { RestaurantsContext } from "../hook/RestaurantsContext"; export const ReviewModal = ({ chosenRestaurant, setShowModal }) => { const { ratingChunk: { comment, rating }, dispatchRestaurantState, ratingChunk, } = useContext(RestaurantsContext); const inputHandler = (event) => { const { name, value } = event.target; dispatchRestaurantState({ type: "SET_RATING_CHUCK", payload: { name, value }, }); }; const formSubmitHandler = (event) => { event.preventDefault(); setShowModal(false); dispatchRestaurantState({ type: "GET_RATING_CHUCK", payload: chosenRestaurant.id, }); dispatchRestaurantState({type:'RESET_RATING_CHUNK'}) }; return ( <form className="modal-case" onSubmit={formSubmitHandler}> <div className="modal-content"> <div class="input-group mb-3"> Rating &nbsp; &nbsp; &nbsp; <input value={rating} name="rating" type="number" class="form-control" placeholder="Rating" min="1" max="5" onChange={inputHandler} /> </div> <div class="input-group mb-3"> Comment <input value={comment} name="comment" type="text" class="form-control" placeholder="comment" onChange={inputHandler} /> </div> <center> <button className="btn btn-outline-danger m-3">Add Review</button> <button className="btn btn-dark" type="button" onClick={() => setShowModal(false)} > Discard </button> </center> </div> </form> ); };
import request from "supertest"; import { Connection } from "typeorm"; import { app } from "../../../../shared/infra/http/app"; import createConnection from "../../../../shared/infra/typeorm"; let connection: Connection; describe("Create User", () => { beforeAll(async () => { connection = await createConnection(); await connection.runMigrations(); }); afterAll(async () => { await connection.dropDatabase(); await connection.close(); }); it("should be able to create a new user", async () => { const response = await request(app).post("/users").send({ email: "user@test.com.br", name: "User Test", password: "userTesPassword", username: "userTestUsername", }); expect(response.status).toBe(201); }); it("should not be able to create a new user with email already exists", async () => { await request(app).post("/users").send({ email: "user@test.com.br", name: "User Test", password: "userTesPassword", username: "userTestUsername", }); const response = await request(app).post("/users").send({ email: "user@test.com.br", name: "User Test", password: "userTesPassword", username: "userTestUsernameEmailAlreadyExists", }); expect(response.status).toBe(400); }); it("should not be able to create a new user with username already exists", async () => { await request(app).post("/users").send({ email: "user@test.com.br", name: "User Test", password: "userTesPassword", username: "userTestUsername", }); const response = await request(app).post("/users").send({ email: "user@testUsernameAlreadyExists.com.br", name: "User Test", password: "userTesPassword", username: "userTestUsername", }); expect(response.status).toBe(400); }); });
import unittest from abtoolkit.continuous.simulation import StatTestsSimulation from abtoolkit.utils import generate_data class TestStatTestsSimulation(unittest.TestCase): tests = ["ttest", "diff_ttest", "regression_test", "cuped_ttest", "did_regression_test", "additional_vars_regression_test"] def test_success(self): variable = generate_data(100, distribution_type="cont") previous_value = generate_data(100, distribution_type="cont", index=variable.index).rename("prev") experiments_num = 10 sim = StatTestsSimulation( variable, stattests_list=self.tests, experiments_num=experiments_num, alternative="two-sided", sample_size=50, mde=10, alpha_level=0.05, power=0.8, previous_values=previous_value, cuped_covariant=previous_value, additional_vars=[previous_value], ) info = sim.run() self.assertTrue(len(self.tests) == len(info.keys()), "Number of tests doesn't match with number of result dicts") for test in self.tests: self.assertTrue(test in info.keys(), f"Test '{test}' is not in result dict") test_info = info[test] self.assertTrue("alpha" in test_info, f"Alpha value not in result dict") self.assertTrue(0 <= test_info["alpha"] <= 1, f"Alpha value has wrong value: {test_info['alpha']}") self.assertTrue("alpha_ci" in test_info, f"Alpha CI value not in result dict") self.assertTrue(len(test_info["alpha_ci"]) == 2, f"Wrong confidence interval for alpha: {test_info['alpha_ci']}") self.assertTrue("power" in test_info, f"Power value not in result dict") self.assertTrue(0 <= test_info["power"] <= 1, f"Power value has wrong value: {test_info['power']}") self.assertTrue("power_ci" in test_info, f"Power CI value not in result dict") self.assertTrue(len(test_info["power_ci"]) == 2, f"Wrong confidence interval for power: {test_info['power_ci']}") self.assertTrue("aa_pvalues" in test_info, f"AA p-values not in result dict") self.assertTrue(len(test_info["aa_pvalues"]) == experiments_num, f"Number of p-values in AA test doesn't match with number of experiments") self.assertTrue("ab_pvalues" in test_info, f"AB p-values not in result dict") self.assertTrue(len(test_info["ab_pvalues"]) == experiments_num, f"Number of p-values in AB test doesn't match with number of experiments")
import React from 'react'; import { List, Avatar, Button, Row, Col, Modal, message } from 'antd'; import axios from 'axios'; import ApiUrl from '../config/api_url'; import TokenHeaders from '../utils/tokenUtils'; const { confirm } = Modal; export default class CategoryList extends React.Component { constructor(props) { super(props); this.state = { categoryList: [], }; } componentDidMount() { this._isMounted = true; this.getCategoryList(); } componentWillUnmount() { this._isMounted = false; } getCategoryList = () => { axios({ method: 'get', url: ApiUrl.CATEGORY_ALL, headers: TokenHeaders, }).then((res) => { let data = res.data.data; if (this._isMounted) { this.setState({ categoryList: data, }); } }); }; deleteCategory = (id) => { let dataProps = { id: id, }; confirm({ title: '是否確定刪除此分類?', content: '若您點擊確認按鈕,此分類將被永久刪除,無法復原。', okText: '確認', cancelText: '取消', onOk() { axios({ method: 'post', url: ApiUrl.CATEGORY_DELETE, headers: TokenHeaders, data: dataProps, }).then((res) => { message.success('刪除成功'); }); }, onCancel() { message.success('刪除失敗'); }, }); }; updateCategory = (id) => { this.props.history.push('/admin/category/edit/' + id); }; render() { let { categoryList } = this.state; return ( <div> <List header={ <Row className="w-100"> <Col span={2}> <b>分類</b> </Col> <Col span={6}> <b>名稱</b> </Col> <Col span={8}> <b>等級</b> </Col> <Col span={6}> <b>操作</b> </Col> </Row> } bordered dataSource={categoryList} renderItem={(item) => ( <List.Item> <Row className="w-100"> <Col span={2}> <List.Item.Meta avatar={<Avatar src={item.image} />} /> </Col> <Col span={6}>{item.name}</Col> <Col span={8}>{item.level}</Col> <Col span={6}> <Button type="primary" onClick={(e) => { this.updateCategory(item.id); }} className="me-2" > 編輯 </Button> <Button type="primary" onClick={(e) => { this.deleteCategory(item.id); }} > 刪除 </Button> </Col> </Row> </List.Item> )} ></List> </div> ); } }
import sys from PyQt5 import QtWidgets, QtCore import pandas as pd import matplotlib.pyplot as plt import os import numpy as np from sklearn.cluster import AgglomerativeClustering from tensorflow import keras from IPython.display import display from skimage.color import gray2rgb from PIL import Image import io from tqdm import tqdm class MainWindow(QtWidgets.QMainWindow): def __init__(self): super().__init__() #MARGIN = 40 self.setWindowTitle("Text File Browser") self.setGeometry(100, 100, 1500, 1500) # Create a button to browse trajectory file self.trajectory_button = QtWidgets.QPushButton("Trajectory file", self) self.trajectory_button.clicked.connect(self.load_trajectory_file) self.trajectory_button.move(20, 20) # Create a button to browse motility file self.motility_button = QtWidgets.QPushButton("Motility file", self) self.motility_button.clicked.connect(self.load_motility_file) self.motility_button.move(150, 20) # Create a button to merge files self.merge_button = QtWidgets.QPushButton("Merge files", self) self.merge_button.clicked.connect(self.merge_files) self.merge_button.move(280, 20) # Create table view to display DataFrame self.table_view = QtWidgets.QTableView(self) self.table_view.setGeometry(20, 60, 1500, 900) self.trajectory_df = None self.motility_df = None self.grouped_df = None # Create a button to generate plots self.plot_button = QtWidgets.QPushButton("Generate imgs", self) self.plot_button.clicked.connect(self.generate_plots) self.plot_button.move(410, 20) # Create a spin box for selecting the number of clusters self.cluster_spinbox = QtWidgets.QSpinBox(self) self.cluster_spinbox.setMinimum(2) # Minimum 2 clusters self.cluster_spinbox.setValue(5) # Default value self.cluster_spinbox.move(550, 20) # Create a button to run the clustering self.cluster_button = QtWidgets.QPushButton("Run AH", self) self.cluster_button.clicked.connect(self.run_clustering) self.cluster_button.move(680, 20) # Create a button to display the cluster plot self.plot_clusters_button = QtWidgets.QPushButton("Cluster Plot", self) self.plot_clusters_button.clicked.connect(self.plot_clusters) self.plot_clusters_button.move(800, 20) self.run_model_button = QtWidgets.QPushButton("Run Model", self) self.run_model_button.clicked.connect(self.predict_classes) self.run_model_button.move(920, 20) # Adjust the position as needed self.save_pickle_button = QtWidgets.QPushButton('Save df', self) self.save_pickle_button.clicked.connect(self.save_dataframe_as_pickle) #layout.addWidget(self.save_pickle_button) # Assuming 'layout' is the layout variable you're using for your GUI self.save_pickle_button.move(1040,20) self.trajectory_plot_button = QtWidgets.QPushButton("Con. Plot", self) self.trajectory_plot_button.clicked.connect(self.plot_trajectory_colored) self.trajectory_plot_button.move(1160, 20) # Adjust the position as needed # Add a button for plotting trajectories based on predicted classes self.class_plot_button = QtWidgets.QPushButton('Classes Plot', self) self.class_plot_button.clicked.connect(self.plot_predicted_classes) self.class_plot_button.move(1280, 20) # Create a button to load dataframe self.load_df_button = QtWidgets.QPushButton("Load DataFrame", self) self.load_df_button.clicked.connect(self.load_dataframe) self.load_df_button.move(1400, 20) # Adjust the position as needed self.show() def load_trajectory_file(self): file_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open trajectory file", "", "Text Files (*.txt);;CSV Files (*.csv)") if file_path: # Read CSV file into DataFrame columns = ["name", "date", "concentration", "exposure", "id", "x", "y"] self.trajectory_df = pd.read_csv(file_path, header=None, names=columns) # Group and display self.display_trajectory() def display_trajectory(self): self.grouped_df = self.trajectory_df.groupby(["name", "date", "concentration", "exposure", "id"]).agg( x=pd.NamedAgg(column='x', aggfunc=list), y=pd.NamedAgg(column='y', aggfunc=list) ).reset_index() # Center the x and y coordinates self.grouped_df['centered_x'] = self.grouped_df.apply(lambda row: [x - sum(row['x'])/len(row['x']) for x in row['x']], axis=1) self.grouped_df['centered_y'] = self.grouped_df.apply(lambda row: [y - sum(row['y'])/len(row['y']) for y in row['y']], axis=1) # Convert DataFrame to Qt Table Model and display model = pandasModel(self.grouped_df) self.table_view.setModel(model) def load_motility_file(self): file_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Open motility file", "", "Text Files (*.txt);;CSV Files (*.csv)") if file_path: # Read the motility file with custom column names columns = ["name", "date", "exposure", "concentration", "VCL", 'VAP', 'VSL', 'LIN', 'STR', 'WOB', 'BeatCross', 'ALH'] self.motility_df = pd.read_csv(file_path, header=None, names=columns, skiprows=1) # Print the motility DataFrame to the terminal #print("Motility DataFrame:") #print(self.motility_df) def merge_files(self): if self.grouped_df is not None and self.motility_df is not None: # Extract the specified columns from motility_df motility_columns = ["VCL", "VAP", "VSL", "LIN", "STR", "WOB", "BeatCross", "ALH"] extracted_motility = self.motility_df[motility_columns] # Merge grouped_df with the extracted columns by index merged_df = pd.concat([self.grouped_df, extracted_motility], axis=1) # Display the merged DataFrame model = pandasModel(merged_df) self.table_view.setModel(model) def generate_plots(self): if self.grouped_df is None: QtWidgets.QMessageBox.warning(self, "Warning", "Please load and display the trajectory file first!") return image_arrays = [] # Generate plots for each element in grouped_df for idx, row in tqdm(self.grouped_df.iterrows(), total=len(self.grouped_df), desc="Generating Images"): plt.figure(figsize=(1, 1), dpi=60) # 1x1 inch figure at 60 dpi results in 60x60 pixel image plt.plot(row['centered_x'], row['centered_y'], '-', color='black') plt.axis('off') plt.gca().set_aspect('equal', adjustable='box') plt.tight_layout() # Save the plot to an in-memory bytes buffer buf = io.BytesIO() plt.savefig(buf, format='png', cmap='gray') buf.seek(0) plt.close() # Read the image buffer using PIL and convert to numpy array image = Image.open(buf) image_array = np.asarray(image) image_array = image_array / 255.0 # Since the image saved is RGBA, we convert it to grayscale and then to RGB gray_image = image_array[:,:,0] # Taking one channel since it's grayscale rgb_image = gray2rgb(gray_image) # Crop or resize if needed to make it 36x36 if rgb_image.shape[0] != 36 or rgb_image.shape[1] != 36: rgb_image = rgb_image[:36, :36] image_arrays.append(rgb_image) # Add the list of numpy arrays as a new column to grouped_df self.grouped_df['image_arrays'] = image_arrays QtWidgets.QMessageBox.information(self, "Info", "Images added to the dataframe!") print(self.grouped_df['image_arrays'][0].shape) def run_clustering(self): # Check if grouped_df exists and contains image_arrays if self.grouped_df is None or 'image_arrays' not in self.grouped_df.columns: QtWidgets.QMessageBox.warning(self, "Warning", "Please load the trajectory file, generate the plots, and add them to the dataframe first!") return # Flatten the image arrays for clustering flattened_images = [img.flatten() for img in self.grouped_df['image_arrays']] # Number of clusters from the spinbox n_clusters = self.cluster_spinbox.value() # Run agglomerative clustering clustering = AgglomerativeClustering(n_clusters=n_clusters) cluster_labels = clustering.fit_predict(flattened_images) # Add cluster labels to the dataframe self.grouped_df['cluster'] = cluster_labels # Refresh the displayed dataframe to show the new cluster column model = pandasModel(self.grouped_df) self.table_view.setModel(model) def plot_clusters(self): # Check if grouped_df exists and contains cluster labels if self.grouped_df is None or 'cluster' not in self.grouped_df.columns: QtWidgets.QMessageBox.warning(self, "Warning", "Please load the trajectory file, generate the plots, add them to the dataframe, and run clustering first!") return # Generate a list of colors (extend this if more clusters are needed) colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] plt.figure(figsize=(10, 10)) for idx, row in self.grouped_df.iterrows(): color = colors[row['cluster'] % len(colors)] # Use modulo to avoid index out of range plt.plot(row['x'], row['y'], '-', color=color) list_cluster = self.grouped_df['cluster'].unique() plt.title('Clustered Trajectories') plt.xlabel('X') plt.ylabel('Y') plt.legend(list_cluster) plt.gca().set_aspect('equal', adjustable='box') plt.show() def predict_classes(self): # Ensure that the DataFrame exists and contains image arrays if self.grouped_df is None or 'image_arrays' not in self.grouped_df.columns: QtWidgets.QMessageBox.warning(self, "Warning", "Ensure both trajectory and motility files are loaded, merged, and images are generated!") return # Load the trained model model = keras.models.load_model("cnn_top50_classes6-0.h5", compile=False) # Prepare the images for the model (assuming grayscale images with 60x60 resolution) images = np.array(self.grouped_df['image_arrays'].tolist()).reshape(-1, 36, 36, 3) # Predict classes predictions = model.predict(images) predicted_classes = np.argmax(predictions, axis=1) # Update DataFrame with predicted classes self.grouped_df['predicted_class'] = predicted_classes # Refresh the displayed dataframe to show the new 'predicted_class' column model_qt = pandasModel(self.grouped_df) self.table_view.setModel(model_qt) def save_dataframe_as_pickle(self): # Check if the dataframe exists if self.grouped_df is None: QtWidgets.QMessageBox.warning(self, "Warning", "The dataframe is empty!") return options = QtWidgets.QFileDialog.Options() fileName, _ = QtWidgets.QFileDialog.getSaveFileName(self, "Save Pickle File", "", "Pickle Files (*.pkl);;All Files (*)", options=options) if fileName: if not fileName.endswith('.pkl'): fileName += '.pkl' self.grouped_df.to_pickle(fileName) QtWidgets.QMessageBox.information(self, "Info", f"Dataframe saved as '{os.path.basename(fileName)}'!") def plot_trajectory_colored(self): # Check if grouped_df exists if self.grouped_df is None: QtWidgets.QMessageBox.warning(self, "Warning", "Please load and display the trajectory file first!") return # Extract unique concentrations and map them to colors unique_concentrations = self.grouped_df['concentration'].unique() colors = plt.cm.viridis(np.linspace(0, 1, len(unique_concentrations))) # Create a colormap that spans the unique concentrations concentration_to_color = dict(zip(unique_concentrations, colors)) plt.figure(figsize=(10, 10)) for concentration, color in concentration_to_color.items(): subset = self.grouped_df[self.grouped_df['concentration'] == concentration] for idx, row in subset.iterrows(): plt.plot(row['x'], row['y'], '-', color=color, label=f"Concentration: {concentration}" if f"Concentration: {concentration}" not in plt.gca().get_legend_handles_labels()[1] else "") plt.title('Trajectories Colored by Concentration') plt.xlabel('X') plt.ylabel('Y') plt.legend(loc="upper right") plt.gca().set_aspect('equal', adjustable='box') plt.show() def plot_predicted_classes(self): # Check if grouped_df exists and contains cluster labels if self.grouped_df is None or 'predicted_class' not in self.grouped_df.columns: QtWidgets.QMessageBox.warning(self, "Warning", "Please load the trajectory file, generate the plots, add them to the dataframe, and run clustering first!") return # Generate a list of colors (extend this if more clusters are needed) colors = ['b', 'g', 'r', 'c', 'm', 'y', 'k'] plt.figure(figsize=(10, 10)) # Create a set to keep track of classes that have been labeled already labeled_classes = set() for idx, row in self.grouped_df.iterrows(): color = colors[row['predicted_class'] % len(colors)] # Use modulo to avoid index out of range # Check if this class has been labeled already if row['predicted_class'] not in labeled_classes: plt.plot(row['x'], row['y'], '-', color=color, label=row['predicted_class']) labeled_classes.add(row['predicted_class']) else: plt.plot(row['x'], row['y'], '-', color=color) plt.title('Classified Trajectories') plt.xlabel('X') plt.ylabel('Y') plt.legend() plt.gca().set_aspect('equal', adjustable='box') plt.show() def load_dataframe(self): options = QtWidgets.QFileDialog.Options() file_path, _ = QtWidgets.QFileDialog.getOpenFileName(self, "Load Pickle File", "", "Pickle Files (*.pkl);;All Files (*)", options=options) if file_path: # Read the DataFrame from the pickle file self.grouped_df = pd.read_pickle(file_path) # Display the loaded DataFrame model = pandasModel(self.grouped_df) self.table_view.setModel(model) QtWidgets.QMessageBox.information(self, "Info", "DataFrame loaded successfully!") class pandasModel(QtCore.QAbstractTableModel): def __init__(self, df, parent=None): QtCore.QAbstractTableModel.__init__(self, parent) self._df = df def rowCount(self, parent=None): return self._df.shape[0] def columnCount(self, parent=None): return self._df.shape[1] def data(self, index, role=QtCore.Qt.DisplayRole): if index.isValid(): if role == QtCore.Qt.DisplayRole: return str(self._df.iloc[index.row(), index.column()]) return None def headerData(self, col, orientation, role): if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole: return self._df.columns[col] return None if __name__ == "__main__": app = QtWidgets.QApplication(sys.argv) window = MainWindow() sys.exit(app.exec_())
%% RUNFILE for the PAM1 function % This file can be changed to suit your requirements. Currently, the % function suits a membrane photo bio CSTR, but will be expanded to general % reactor types in the future % Author Ed Barry UQ e.barry@uq.edu.au 23/11/2016 for Paper: clear; clc; global V %% USER INPUT % Read the input data and organise. Prompt whether the user wants a % clarifier, and what HRT and SRT are required data = csvread('dynamicInfluent.csv'); % Raw influent file included tu = data(:,1); % Time (t) to which raw input (u) is mapped %---------------------------------------------- %% Assign variable names to influent data % Conditions preamble. Previously scripted as user prompts - can put these % back in if required. HRT = 12; thetaS = 3; V = mean(data(:,12))*HRT/24; % If clarifier is used, the solids content will be reduced by 50% as per % Tchobanoglous, Ch 5, Section 5-7. Assume same volume of water as % 'non-clarifier' case. str = 'N'; % Do we want a clarifier solidsRemoved = zeros(length(tu),3); if str == 'Y' removalFrac = normrnd(0.6,0.03,length(tu),1); for i = 9:11 solidsRemoved(:,i-8) = data(:,i).*removalFrac; data(:,i) = data(:,i).*(1 - removalFrac); end end Ss0 = data(:,2); Sac0 = data(:,3); Sic0 = data(:,4); Sh20 = data(:,5); Sin0 = data(:,6); Sip0 = data(:,7); Si0 = data(:,8); XPB0 = data(:,9); Xs0 = data(:,10); Xi0 = data(:,11); % Flowrates QinVec = data(:,12); QslVec = V/thetaS; QoutVec = QinVec - QslVec; % Solids are removed from the effluent feed = [Ss0, Sac0, Sic0, Sh20, Sin0, ... Sip0, Si0, XPB0, Xs0, Xi0, QinVec, QoutVec]; %% ADDITION OF SAC % Determine how much SAC is needed to be added to the system % We will show the system running steadily for 150 days then will % increase the SAC such that the limiting reagent (N or P) be consumed. % This will be done for a period of 150 days, then SAC will no longer % be added to the system for the remainder of the period. SAC_ADDED = zeros(length(tu), 1); for j = 1:length(tu) - 1 if (j+1 > floor(300/0.0104) && j+1 <= floor(450/0.0104)) if Sin0(j) < 8.6/1.5*Sip0(j) SAC_ADDED(j) = 1.2*(Sin0(j)*100/8.6 - (Ss0(j) + Sac0(j))); else SAC_ADDED(j) = 1.2*(Sip0(j)*100/1.5 - (Ss0(j) + Sac0(j))); end else SAC_ADDED(j) = 0.0; end end % Pass this array of dynamic inputs into ODE call and the function will % take care of mapping it to the time array. uOrig = feed; uOrig(:,2) = feed(:,2) + SAC_ADDED; tspace = [0 600]; %% tic [t,y] = ode15s(@(t,y)PAM1(t,y,tu, uOrig, V), tspace, uOrig(1,1:10)); toc %% Save files PAMStateMatrix = y; [yy,ts,pHs]=PAM1(t(1),y(1,:),tu,uOrig, V); %can filter out failed iterations or just leave in. Leave in for now. % Find start time for i = 2:length(t) if t(i-1) < 150 && t(i+1) > 150 break end end stateResults = PAMStateMatrix(i:end,:); if str == 'Y' stateInput = [feed, SAC_ADDED, ... solidsRemoved, removalFrac, ... QinVec, QoutVec]; else stateInput = [feed, SAC_ADDED, QinVec, QoutVec]; end stateInput = interp1(tu, stateInput, t); stateInputs = stateInput(i:end,:); %% csvwrite(sprintf('stateOutputsRaw%iS%iH%s.csv', thetaS, HRT, str), stateResults); csvwrite(sprintf('stateInputsRaw%iS%iH%s.csv', thetaS, HRT, str), stateInputs); csvwrite('t.csv',t); csvwrite('V.csv', V); csvwrite('pH_vals.csv', [ts, pHs]); %% Balances balances; % Check to see if model balanced over C, COD, N, P
package com.mlorenzo.demo.customer; import com.mlorenzo.demo.exception.NotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List; @Service public class CustomerService { private final static Logger LOGGER = LoggerFactory.getLogger(CustomerService.class); private final ICustomerRepository customerRepository; public CustomerService(ICustomerRepository customerRepo) { customerRepository = customerRepo; } public List<Customer> getCustomers() { LOGGER.info("getCustomers was called"); return customerRepository.getCustomers(); } public Customer getCustomer(Long id) { return customerRepository.getCustomer(id) .orElseThrow(() -> { NotFoundException notFoundException = new NotFoundException("Customer with id " + id + " not found"); LOGGER.error("error in getting customer with id {}", id, notFoundException); return notFoundException; }); } }
import { notFound } from 'next/navigation'; import { getServerSession } from 'next-auth/next'; import { NextIntlClientProvider, useLocale, useMessages } from 'next-intl'; import RootStyleRegistry from '@/app/emotion'; import AuthContext from '@/context/AuthContext/AuthContext'; import { StoreProvider } from '@/context/StoreContext'; import { authOptions } from '@/lib/auth'; import AppThemeProvider from '@/provider/AppThemeProvider'; import cookieStore from '@/provider/cookieStore'; import { getDirection } from '@/utils/config'; import { AppProviderProps } from '@/types/layout'; import { PageProps } from '@/types/page'; export async function AppProvider({ children, dir }: AppProviderProps) { const clientData = await cookieStore.getClient() const languagesData = await cookieStore.getLanguages() const [client, languages] = await Promise.all([clientData, languagesData]) const session = await getServerSession(authOptions) return ( <AuthContext session={session}> <StoreProvider client={client} languages={languages} direction={dir}> <RootStyleRegistry dir={dir}> <AppThemeProvider> {children} </AppThemeProvider> </RootStyleRegistry> </StoreProvider> </AuthContext> ) } export default function LocaleLayout({ children, params }: PageProps) { const locale = useLocale(); if (params.locale !== locale) { notFound(); } const dir = getDirection(locale) const messages = useMessages() return ( <html lang={locale} dir={dir}> <head></head> <NextIntlClientProvider locale={locale} messages={messages}> <AppProvider dir={dir}> {children} </AppProvider> </NextIntlClientProvider> </html> ); }
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../../../core/hive/product_model.dart'; import '../../../../core/themes/colors.dart'; import '../../../../core/themes/images.dart'; import '../../../../core/widgets/custom_text_widget.dart'; class BuildProductItemGrid extends StatelessWidget { const BuildProductItemGrid({ super.key, required this.product, }); final ProductModel product; @override Widget build(BuildContext context) { log('product.images => ${product.images}'); return ClipRRect( borderRadius: BorderRadius.circular(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: product.images?.isEmpty ?? false || product.images?[0] == null ? Image.asset( Images.img4, fit: BoxFit.cover, width: double.infinity, ) : Image.memory( product.images![0], fit: BoxFit.cover, width: double.infinity, )), const SizedBox(width: 14), CustomTextWidget( title: product.productName, size: 14, fontWeight: FontWeight.w500, paddingTop: 8, ), Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ CustomTextWidget( title: product.productPrice, size: 20, fontWeight: FontWeight.w500, color: ThemeColors.primary, ), const CustomTextWidget( title: "دولار", size: 12, color: Color(0xff3E3E68), ), ], ), Container( height: 30.sp, width: 65.w, alignment: Alignment.center, decoration: BoxDecoration( color: const Color(0xffEEEEEE), borderRadius: BorderRadius.circular(8)), child: CustomTextWidget( title: product.storeName, size: 10, fontWeight: FontWeight.w300, color: const Color(0xffA1A1A1), ), ), ], ) ], ), ); } }
import React from 'react'; import { cleanup, render } from '@testing-library/react'; import '@testing-library/jest-dom/extend-expect'; import FullscreenModal from './FullscreenModal'; describe('<FullscreenModal />', () => { afterEach(cleanup); test('given isOpen when passed true then display modal', () => { const { getByTestId } = render(<FullscreenModal isOpen={true} setModalState={() => undefined} title={""} />); const fullscreenModal = getByTestId('FullscreenModal'); expect(fullscreenModal).toBeInTheDocument(); }); test('given isOpen when passed false then modal is not displayed', () => { const { queryByTestId } = render(<FullscreenModal isOpen={false} setModalState={() => undefined} title={""} />); const fullscreenModal = queryByTestId('FullscreenModal'); expect(fullscreenModal).toBeNull(); }); });
package post import ( "github.com/go-playground/validator/v10" "overdoll/applications/sting/internal/domain/club" "overdoll/libraries/errors/domainerror" "overdoll/libraries/media" "overdoll/libraries/principal" "overdoll/libraries/uuid" "time" "overdoll/libraries/localization" "overdoll/libraries/paging" ) var ( ErrCharacterSlugNotUnique = domainerror.NewValidation("character slug is not unique") ) type Character struct { *paging.Node id string slug string name *localization.Translation thumbnailMedia *media.Media bannerMedia *media.Media series *Series clubId *string totalLikes int totalPosts int createdAt time.Time updatedAt time.Time } func NewCharacter(requester *principal.Principal, slug, name string, series *Series, club *club.Club) (*Character, error) { if requester.IsLocked() { return nil, principal.ErrLocked } if series != nil { if !requester.IsStaff() { return nil, principal.ErrNotAuthorized } } if club != nil { if !club.CharactersEnabled() { return nil, domainerror.NewValidation("characters are not enabled for this club") } if !requester.IsWorker() { if err := requester.CheckClubOwner(club.ID()); err != nil { return nil, err } } } lc, err := localization.NewDefaultTranslation(name) if err != nil { return nil, err } if err := validateCharacterName(name); err != nil { return nil, err } if err := validateSlug(slug); err != nil { return nil, err } var clubId *string if club != nil { id := club.ID() clubId = &id } return &Character{ id: uuid.New().String(), slug: slug, name: lc, series: series, clubId: clubId, totalLikes: 0, totalPosts: 0, createdAt: time.Now(), updatedAt: time.Now(), }, nil } func (c *Character) ID() string { return c.id } func (c *Character) Slug() string { return c.slug } func (c *Character) Name() *localization.Translation { return c.name } func (c *Character) Series() *Series { return c.series } func (c *Character) SeriesId() *string { if c.series == nil { return nil } id := c.series.ID() return &id } func (c *Character) ClubId() *string { return c.clubId } func (c *Character) CreatedAt() time.Time { return c.createdAt } func (c *Character) UpdatedAt() time.Time { return c.updatedAt } func (c *Character) update() { c.updatedAt = time.Now() } func (c *Character) ThumbnailMedia() *media.Media { return c.thumbnailMedia } func (c *Character) BannerMedia() *media.Media { return c.bannerMedia } func (c *Character) TotalLikes() int { return c.totalLikes } func (c *Character) TotalPosts() int { return c.totalPosts } func (c *Character) UpdateTotalPosts(totalPosts int) error { c.totalPosts = totalPosts c.update() return nil } func (c *Character) UpdateTotalLikes(totalLikes int) error { c.totalLikes = totalLikes c.update() return nil } func (c *Character) UpdateName(requester *principal.Principal, name, locale string) error { if err := c.canUpdate(requester); err != nil { return err } if err := validateCharacterName(name); err != nil { return err } if err := c.name.UpdateTranslation(name, locale); err != nil { return err } c.update() return nil } func (c *Character) UpdateBannerExisting(thumbnail *media.Media) error { if err := validateExistingResource(c.bannerMedia, thumbnail); err != nil { return err } c.bannerMedia = thumbnail c.update() return nil } func (c *Character) UpdateBanner(thumbnail *media.Media) error { c.bannerMedia = thumbnail c.update() return nil } func (c *Character) canUpdate(requester *principal.Principal) error { if c.clubId != nil { if !requester.IsWorker() { if err := requester.CheckClubOwner(*c.clubId); err != nil { return err } } } if c.series != nil { if !requester.IsStaff() { return principal.ErrNotAuthorized } } if requester.IsLocked() { return principal.ErrLocked } return nil } func UnmarshalCharacterFromDatabase(id, slug string, name map[string]string, thumbnail, banner *media.Media, totalLikes, totalPosts int, createdAt, updatedAt time.Time, media *Series, clubId *string) *Character { return &Character{ id: id, slug: slug, name: localization.UnmarshalTranslationFromDatabase(name), thumbnailMedia: thumbnail, bannerMedia: banner, series: media, clubId: clubId, totalLikes: totalLikes, totalPosts: totalPosts, createdAt: createdAt, updatedAt: updatedAt, } } func validateCharacterName(name string) error { err := validator.New().Var(name, "required,max=25") if err != nil { return domainerror.NewValidation(err.Error()) } return nil }
package com.cydeo; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ConfigCar { @Bean Car car(){ Car c = new Car(); c.setMake("Honda"); return c; } //Direct Wiring // @Bean // Person person(){ // // Person p = new Person(); // p.setCar(car()); // p.setName("Mike"); // return p; // } //Auto wiring @Bean Person person(Car car){ Person p = new Person(); p.setCar(car); p.setName("Mike"); return p; } }
using System.Diagnostics; using CadastroDeUsuario.Models; using CadastroDeUsuario.Models.ViewModel; using CadastroDeUsuario.services; using Microsoft.AspNetCore.Mvc; namespace CadastroDeUsuario.Controllers { public class UserController : Controller { private readonly UserServices _userServices; public UserController(UserServices userServices) { _userServices = userServices; } public async Task<IActionResult> Index() { List<User> users = await _userServices.FindAllAsync(); return View(users); } public IActionResult Create() { var viewModel = new UserFormViewModel(); return View(viewModel); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(User user) { if (!ModelState.IsValid) { var viewModel = new UserFormViewModel { User = user }; return View(viewModel); } await _userServices.InsertAsync(user); return RedirectToAction(nameof(Index)); } public async Task<IActionResult> Delete(int? id) { if (id == null) { return RedirectToAction(nameof(Error), new { message = "id não encontrado" }); } try { var user = await _userServices.FindByIdAsync(id.Value); return View(user); } catch (Exception error) { return RedirectToAction(nameof(Error), new { message = error.Message }); } } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Delete(int id) { try { await _userServices.RemoveAsync(id); return RedirectToAction(nameof(Index)); } catch (Exception error) { return RedirectToAction(nameof(Error), new { message = error.Message }); } } public async Task<IActionResult> Edit(int id) { try { var user = await _userServices.FindByIdAsync(id); var viewModel = new UserFormViewModel { User = user }; return View(viewModel.User); } catch (Exception error) { return RedirectToAction(nameof(Error), new { message = error.Message }); } } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, User user) { try { if (!ModelState.IsValid) { var viewModel = new UserFormViewModel { User = user }; return View(viewModel); } await _userServices.UpdateAsync(id, user); return RedirectToAction(nameof(Index)); } catch (Exception error) { return RedirectToAction(nameof(Error), new { message = error.Message }); } } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error(string message) { var viewModel = new ErrorViewModel { Message = message, RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }; return View(viewModel); } } }
import { FontAwesome5 } from "@expo/vector-icons"; import { useNavigation } from "@react-navigation/native"; import { NativeStackNavigationProp } from "@react-navigation/native-stack"; import { Audio } from "expo-av"; import React, { useEffect, useState } from "react"; import { Image } from "react-native"; import { Button, Divider, Surface, Text, useTheme } from "react-native-paper"; import styled from "styled-components/native"; import { ChoreStackParams } from "../../navigation/ChoreStackNavigator"; import { Chore } from "../../store/chore/choreModel"; import { selectCompletedChores } from "../../store/completedChore/completedChoreSelector"; import { postCompletedChore } from "../../store/completedChore/completedChoreThunks"; import { selectCurrentProfile } from "../../store/profile/profileSelectors"; import { useAppDispatch, useAppSelector } from "../../store/store"; interface Props { chore: Chore; } type ChoreDetailsScreenNavProp = NativeStackNavigationProp<ChoreStackParams, "ChoresScreen">; const ChoreDetails = ({ chore }: Props) => { const [sound, setSound] = useState<Audio.Sound>(); const completedChores = useAppSelector(selectCompletedChores).completedChores; const profile = useAppSelector(selectCurrentProfile); const navigation = useNavigation<ChoreDetailsScreenNavProp>(); const dispatch = useAppDispatch(); const completedChore = completedChores.find((completedChore) => completedChore.choreId === chore?.id && profile?.id === completedChore?.profileId); const { colors } = useTheme(); const today = new Date().getDate(); const energyLevels = [2, 4, 6, 8, 10]; useEffect(() => { if (chore?.soundUrl) { const loadSound = async () => { const loadedSound = new Audio.Sound(); await loadedSound.loadAsync({ uri: chore.soundUrl, }); setSound(loadedSound); }; loadSound(); } }, []); function handlePress() { if (chore?.id && profile?.id) { dispatch(postCompletedChore({ choreId: chore?.id, date: new Date(), profileId: profile?.id })); navigation.navigate("ChoresScreen"); } } return ( <Container> <TitleContainer> <Text variant="bodySmall">Titel</Text> <Text variant="headlineLarge">{chore.name}</Text> </TitleContainer> <DetailsContainer> <DescriptionContainer> <Text variant="bodySmall">Beskrivning</Text> <Text variant="headlineSmall">{chore.description}</Text> </DescriptionContainer> <Divider bold style={{ marginHorizontal: 5 }} /> <IntervalContainer> <Text variant="bodySmall">Intervall</Text> <IntervalContent> <Text variant="headlineSmall">Återkommer var</Text> <Interval elevation={1}> <Text variant="headlineSmall">{chore.interval}</Text> </Interval> <Text variant="headlineSmall">dag</Text> </IntervalContent> </IntervalContainer> <Divider bold style={{ marginHorizontal: 5 }} /> <EnergyContainer> <Text variant="bodySmall">Energinivå</Text> <EnergyContent> {energyLevels.map((level) => ( <Text key={level} variant={level === chore.energy ? "headlineLarge" : "headlineMedium"} style={{ opacity: level === chore.energy ? 1 : 0.5 }} > {level} </Text> ))} </EnergyContent> </EnergyContainer> {(chore.imgUrl || sound) && ( <> <Divider bold style={{ marginHorizontal: 5 }} /> <AttachmentsContainer> <Text variant="bodySmall">Bifogade filer</Text> <AttachmentsContent> {chore.imgUrl && <Image source={{ uri: chore.imgUrl }} style={{ width: 100, height: 100, borderRadius: 10, margin: 10 }} />} {sound && ( <> <PlayButton onPress={() => sound.replayAsync()} style={{ backgroundColor: colors.primary, justifyContent: "center", alignItems: "center", padding: 10, borderRadius: 10 }} > <FontAwesome5 name="volume-up" size={50} color={colors.surface} /> </PlayButton> </> )} </AttachmentsContent> </AttachmentsContainer> </> )} </DetailsContainer> <ButtonContainer> {!(completedChore && today === completedChore.date.getDate() && profile?.id === completedChore?.profileId) && ( <Button onPress={handlePress} style={{ marginHorizontal: 20 }} mode="contained"> Markera som klar </Button> )} </ButtonContainer> </Container> ); }; export default ChoreDetails; const Container = styled.View` flex: 1; `; const TitleContainer = styled(Surface)` margin: 10px; border-radius: 10px; padding: 10px; `; const DetailsContainer = styled(Surface)` margin: 5px 10px; border-radius: 10px; `; const DescriptionContainer = styled.View` padding: 10px; `; const AttachmentsContainer = styled.View` padding: 10px; `; const AttachmentsContent = styled.View` flex-direction: row; margin: 10px; justify-content: center; `; const IntervalContainer = styled.View` padding: 10px; `; const IntervalContent = styled.View` flex-direction: row; `; const Interval = styled(Surface)` align-items: center; border-radius: 20px; padding: 0 10px; margin: 0 8px; `; const EnergyContainer = styled.View` padding: 10px; `; const EnergyContent = styled.View` flex-direction: row; justify-content: space-around; align-items: center; `; const ButtonContainer = styled.View` justify-content: flex-end; margin-bottom: 20px; margin: 50px 20px 20px 20px; `; const PlayButton = styled.Pressable` width: 100px; height: 100px; margin: 10px; `;
import React from 'react'; import { ChartProvider, AreaSeries, XAxis, YAxis, Tooltip } from 'rough-charts'; import { scaleTime, scaleLinear } from 'd3-scale'; import { CHART_DATE_RANGE, CHART_HEIGHT_PX } from '../../config/charts'; import { colors } from '../../config/colors'; import { drawTransparentDataPoint } from '../../functions/charts/drawTransparentDataPoint'; import { formatDate } from '../../functions/ui/formatDate'; import { RainfallDataPoint } from '../../types/RainfallDataPoint'; import { RoughHeader } from '../RoughHeader/RoughHeader'; type Props = { data: RainfallDataPoint[]; }; const X_SCALE = scaleTime().domain(CHART_DATE_RANGE); const Y_SCALE = scaleLinear().domain([0, 35]); const X_TICK_COUNT = 12; const Y_TICK_COUNT = 10; const CHART_FILL_STYLE = 'cross-hatch'; const STROKE_COLOR = colors.azure; const AREA_CHART_OPTIONS = { fillStyle: CHART_FILL_STYLE, stroke: STROKE_COLOR, } as const; export class RainfallChart extends React.PureComponent<Props> { render() { return ( <div className="RainfallChart"> <RoughHeader> Rain </RoughHeader> <ChartProvider xScale={X_SCALE} yScale={Y_SCALE} height={CHART_HEIGHT_PX} data={this.props.data} > <AreaSeries dataKey="rainfall" options={AREA_CHART_OPTIONS} > { drawTransparentDataPoint } </AreaSeries> <XAxis tickCount={X_TICK_COUNT} dataKey="date" tickSize={1} format={formatDate} /> <YAxis tickCount={Y_TICK_COUNT} /> <Tooltip> {getTooltip} </Tooltip> </ChartProvider> </div> ); } } const getTooltip = (item: RainfallDataPoint) => `Rain on ${formatDate(item.date)}: ${roundTo1Decimal(item.rainfall)} mm`; const roundTo1Decimal = (n: number) => (Math.round(n * 10) / 10).toFixed(1);
import { ReferComponent } from './refer/refer.component'; import { FinancialComponent } from './financial/financial.component'; import { StatisticComponent } from './statistic/statistic.component'; import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: 'statistic', component: StatisticComponent }, { path: 'financial', component: FinancialComponent }, { path: 'refer', component: ReferComponent }, { path: '', redirectTo: '/statistic#statistic', pathMatch: 'full' }, { path: '**', redirectTo: '/statistic#statistic'} ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {}
import { OrgRepo } from 'src/types' import { StarIcon, ForkIcon } from 'src/assets' import { Grid } from 'src/pages/style' import { CardRepo, RepoHeader, RepoDescription, RepoFooterInfo, RepoFooter, } from './style' type CardRepositoryProps = { orgsRepositories: OrgRepo[] } export function CardRepository({ orgsRepositories }: CardRepositoryProps) { return ( <Grid> {orgsRepositories?.map((repo: OrgRepo) => ( <CardRepo key={repo.id}> <RepoHeader> <h2 className="repo-name">{repo.name}</h2> <span className="repo-label">Public</span> </RepoHeader> <RepoDescription>{repo.description}</RepoDescription> <RepoFooter> {repo.language && ( <RepoFooterInfo> <span className="lang-circle" /> {repo.language} </RepoFooterInfo> )} <RepoFooterInfo> <StarIcon /> {repo.stargazers_count} </RepoFooterInfo> <RepoFooterInfo> <ForkIcon /> {repo.forks_count} </RepoFooterInfo> </RepoFooter> </CardRepo> ))} </Grid> ) }
<?php session_start(); require 'conexao.php'; if (isset($_POST['adicionar_carrinhoP'])) { $nome = $_POST['nome']; $pizza_perso = $_POST['pizza_perso']; $valorTotal = $_POST['valor_total']; // Recupere os ingredientes personalizados dos arrays $nomesIngredientes = $_POST['nome_ingrediente']; $quantidades = $_POST['quantidade']; $precosIngredientes = $_POST['preco']; // Certifique-se de que os arrays tenham o mesmo comprimento if (count($nomesIngredientes) === count($quantidades) && count($quantidades) === count($precosIngredientes)) { try { $PDO->beginTransaction(); // Insira a pizza personalizada $stmt = $PDO->prepare("INSERT INTO pizzas_personalizada (pizza_id, preco, nome) VALUES (?, ?, ?)"); $stmt->execute([$pizza_perso, $valorTotal, $nome]); // Obtenha o ID da pizza personalizada recém-inserida $pizza_personalizada_id = $PDO->lastInsertId(); // Insira cada ingrediente personalizado for ($i = 0; $i < count($nomesIngredientes); $i++) { $nomeIngrediente = $nomesIngredientes[$i]; $quantidade = $quantidades[$i]; $precoIngrediente = $precosIngredientes[$i]; $stmt = $PDO->prepare("INSERT INTO ingredientes_personalizados (pizza_personalizada_id, nome, quantidade, preco) VALUES (?, ?, ?, ?)"); $stmt->execute([$pizza_personalizada_id, $nomeIngrediente, $quantidade, $precoIngrediente]); } $PDO->commit();?> <form id="redirectForm" action="add_to_cart.php" method="post"> <input type="hidden" name="pizza_id" value="<?= $pizza_personalizada_id ?>"> <input type="hidden" name="pizza_name" value="<?=$nome?>"> <input type="hidden" name="pizza_price" value="<?=$valorTotal?>"> <input type="hidden" name="pizza_type" value="Personalizada"> <input type="hidden" name="quantity" value="1"> <input type="hidden" name="add_to_cart" value="1"> </form> <script type="text/javascript"> document.getElementById("redirectForm").submit(); </script> <?php exit(); } catch (PDOException $e) { $PDO->rollBack(); echo 'Erro no banco de dados: ' . $e->getMessage(); exit(); } } else { echo 'Erro: Tamanhos dos arrays não correspondem.'; exit(); } } ?>
import React, {useEffect} from "react"; import s from "./style.module.scss" import DevicesList from './DeviseList' import {useDispatch, useSelector} from "react-redux"; import {fetchDevices} from "../../store/actions/entities/devices.actions"; import {AppDispatch} from "../../store/store"; import {allDevicesListSelector} from "../../store/selectors/entities/devices.selectors"; const DeviceRental = () => { const dispatch = useDispatch<AppDispatch>() useEffect(() => { dispatch(fetchDevices()) }, [dispatch]) const devices = useSelector(allDevicesListSelector) const IphoneDevices = devices?.filter(item => item.device_name.includes('iPhone') ) const AndroidDevices = devices?.filter(item => !item.device_name.includes('iPhone')) return ( <div className={s.DeviceRental}> <p className={s.title}>Аренда устройства</p> <p className={s.IOSTittle}>IOS</p> <p className={s.AndroidTittle}>Android</p> <div className={s.IOSListDevice}> <DevicesList device={IphoneDevices} /> </div> <div className={s.AndroidListDevice}> <DevicesList device={AndroidDevices} /> </div> </div> ); }; export default DeviceRental;
using Event.API.Core; using Event.API.Dtos.Events; using Microsoft.AspNetCore.Mvc; using SharedLib.BaseController; namespace Event.API.Controllers; public class EventController : CustomBaseController { private readonly IEventService _eventService; public EventController(IEventService eventService) { _eventService = eventService; } [HttpGet] public async Task<IActionResult> Get() { return CreateActionResult(await _eventService.GetAllAsync()); } [HttpGet("{id}")] public async Task<IActionResult> GetById(Guid id) { return CreateActionResult(await _eventService.GetByIdAsync(id)); } [HttpPost] public async Task<IActionResult> Create(CreateEventRequest createEventRequest) { return CreateActionResult(await _eventService.CreateAsync(createEventRequest)); } [HttpPut("{id}")] public async Task<IActionResult> Update(UpdateEventRequest updateEventRequest, Guid id) { return CreateActionResult(await _eventService.UpdateAsync(updateEventRequest, id)); } [HttpDelete("{id}")] public async Task<IActionResult> Delete(Guid id) { return CreateActionResult(await _eventService.DeleteAsync(id)); } }
import { useEffect, useState } from "react"; import { ResType } from "../../interface/iTunes"; import { getSearchFilter } from "../../useServices/itunesService"; import ShowAll from "./showAll"; import { Box } from "@mui/material"; import Typography from "@mui/material/Typography"; import CircularProgress from "@mui/material/CircularProgress"; interface Params { search: string; kind: string; text: string; } const GetAll = (params: Params) => { const { search, kind, text } = params; const isVideo = kind === "musicVideo" ? true : false; const [data, setData] = useState({} as ResType); const [loading, setLoading] = useState(true); // ========= Msg Error ======= const [msgError, setMessage] = useState<string | null>(""); const handleGetAllData = async () => { setLoading(true); const { res, error } = await getSearchFilter<ResType>(search, kind); if (res) { setData(res); } setMessage(error); setLoading(false); }; useEffect(() => { handleGetAllData(); }, [search, kind]); return ( <Box sx={{ display: "flex", alignItems: "center", flexDirection: "column" }} > <Typography sx={{ fontSize: 25, marginTop: "20px" }} color="black"> {text} </Typography> {!loading && msgError ! == null ? ( <ShowAll data={data} isVideo={isVideo} /> ) : msgError === null || msgError !== "" ? ( <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "50vh", }} > <CircularProgress color="inherit" /> </Box> ) : ( <Typography variant="h6" color="error"> {msgError} </Typography> )} </Box> ); }; export default GetAll;
<?php namespace App\Models; use Cviebrock\EloquentSluggable\Sluggable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Kyslik\ColumnSortable\Sortable; class Genre extends Model { use HasFactory, Sluggable, Sortable; protected $guarded = ['id']; public $sortable = ['name']; public function movies() { return $this->belongsToMany(Movie::class); } public function getRouteKeyName() { return 'slug'; } public function sluggable(): array { return [ 'slug' => [ 'source' => 'name' ] ]; } }
<!DOCTYPE html> <html lang="ru"> {% load static %} {% load menu_tags %} <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta charset="UTF-8"> <title>Title</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css"> <script src=" https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js "></script> <style> :root { --bg-main-color: #ba0913; } </style> {% block extra-head %} {% endblock %} </head> <body class="d-flex flex-column min-vh-100" style="background-color: whitesmoke;"> {% include_menu %} <section class="flex-grow-1"> {% if messages %} {% for message in messages %} <div class="{% if message.tags == 'success' %} bg-success-subtle text-success-emphasis {% elif message.tags == 'error' %} bg-danger-subtle text-danger-emphasis {% else %} bg-warning-subtle text-warning-emphasis {% endif %}"> <div class="container py-3"> {{ message }} </div> </div> {% endfor %} {% endif %} {% block header %} {% endblock %} <section class="container py-3"> {% block content %} {% endblock %} </section> </section> <footer class="py-3" style="backdrop-filter: brightness(95%);"> <ul class="nav justify-content-center border-bottom pb-3 mb-3"> <li class="nav-item"><a href="#" class="nav-link px-2 text-body-secondary">Главная</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-body-secondary">Каталог</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-body-secondary">Услуги</a></li> <li class="nav-item"><a href="#" class="nav-link px-2 text-body-secondary">О нас</a></li> </ul> <p class="text-center text-body-secondary">© 2024 АвтоМастер</p> </footer> {% block scripts %} {% endblock %} </body> </html>
import type { GetServerSideProps, NextPage } from 'next' import Head from 'next/head' import Image from 'next/image' import Link from 'next/link' import {sanityClient, urlFor} from '../sanity' import { Collection } from '../typing' interface Props { collections: Collection[] } const Home = ({collections}:Props) => { return ( <div className="max-w-7xl mx-auto flex flex-col py-20 px-10 2xl-px-0 xl-ps-0 xl:m-auto "> <Head> <title>NFT DROP</title> <link rel="icon" href="/favicon.ico" /> </Head> <h1 className='w-52 cursor-pointer text-xl font-extralight sm:w-80 '> The{' '} <span className='font-extrabold underline decoration-purple-600/50'> Atul-Jaiss</span> {' '} NFT Market Place </h1> <main className='bg-slate-100 p-10 shadow-xl shadow-rose-300/20'> <div className='grid space-x-3 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-4'> {collections.map(collection =>( <Link href={`/nft/${collection.slug.current}`}> <div className='flex flex-col cursor-pointer transition-all duration-200 hover:scale-105 items-center'> <img className='h-96 w-60 rounded-2xl object-cover ' src={urlFor(collection.mainImage).url()} alt="" /> <div className='p-5'> <h2 className='text-3xl'>{collection.title}</h2> <p className='mt-2 text-sm text-gray-400'> {collection.description} </p> </div> </div> </Link> ))} </div> </main> {/*<h1 className='text-8xl font-bold text-center justify-center text-BLACK mt-20 p-10'>NFT DROP</h1> <h2 className='text-5xl text-black text-center'> <Typewriter onInit={(typewriter) => { typewriter.typeString( "Welcome to NFT DROP challenge " ) .pauseFor(2000) .deleteAll() .typeString( "Click below link to see my build" ) .pauseFor(2000) .pause() .start(); }} /> </h2> <a className='text-4xl text-center p-10 text-white' href="https://aj-nftdrop.vercel.app/nft/atul">My Day-2 Work(click me)</a> */} </div> ) } export default Home export const getServerSideProps: GetServerSideProps = async () => { const query = `*[_type == 'collection']{ _id, title, address, description, nftCollectionName, mainImage { asset }, previewImage { asset }, slug { current }, creator-> { _id, name, address, slug{ current } } }` const collections = await sanityClient.fetch(query) return { props: { collections } } }
// BIG O O(n) ---> Linear Time export const arrayNemod = new Array(100).fill('nemo'); export const findNemo = (array: string[]) => { array.forEach(element => { if (element === 'nemo') { console.log('found Nemo!'); } }); } export const bigOn = () => { findNemo(arrayNemod); } // BIG O O(1) constant time const boxes = [3, 4, 6]; export const logOfTwoBoxes = (array: number[]) => { console.log(array[0]); console.log(array[1]); } export const bigO1 = () => { logOfTwoBoxes(boxes); } // BIG O challenge O(3 + 4n) function funChallenge(input) { let a = 10; // O(1) a = 50 + 3; // O(1) for (let i = 0; i < input.length; i++) { // O(n) logOfTwoBoxes(boxes); // O(n) let stranger = true; // O(n) a++; // O(n) } return a; // O(1) } export const bigO1a = () => { funChallenge(boxes); } // What is the Big O of the below function? (Hint, you may want to go line by line) O(4 + 7n) function anotherFunChallenge(input) { let a = 5; // O(1) let b = 10; // O(1) let c = 50; // O(1) for (let i = 0; i < input; i++) { // 4 * O(n) let x = i + 1; let y = i + 2; let z = i + 3; } for (let j = 0; j < input; j++) { // 3* O(n) let p = j * 2; let q = j * 2; } let whoAmI = "I don't know"; // O(1) } export const bigO1b = () => { anotherFunChallenge(3); } // test 3 O(n) Drop the Constants function printFirstItemThenFirstHalfThenSayHi100Times(items) { console.log(items[0]); // O(1) var middleIndex = Math.floor(items.length / 2); // O(1) var index = 0; // O(1) while (index < middleIndex) { // O(n/2) console.log(items[index]); index++; } for (var i = 0; i < 100; i++) { // O(100) console.log('hi'); } } //Log all pairs of array O(n^2) const boxes44 = ['a', 'b', 'c', 'd', 'e']; function logAllPairsOfArray(array) { for (let i = 0; i < array.length; i++) { for (let j = 0; j < array.length; j++) { // console.log(array[i], array[j]) } } } export const logAllPairsOfArray44 = () => { logAllPairsOfArray(boxes44) }
// 0.4.7 is the version of solidity we are using, this version number helps the Solidity Compiler to compile correctly pragma solidity ^0.4.7; // MessageBoard is the name of the contract contract MessageBoard { /* string - signifies that the value to be stored in the variable will be string public - signifies that anyone in the world can read/write this variable message - name of the variable */ string public message; /* address - signifies that the addresses like "0x123asdfl123lj123asdf123" can be stored. It's better to use address instead of strings for ethereum addresses because we can run some functions like 'transfer' directly on them. public - signifies that anyone in the world can read/write this variable manager - name of the variable */ address public manager; /* Constructor - It runs only once, when the contract is deployed on Ethereum Network. It also assigns the initial value to our "owner" variable. */ function MessageBoard(string initialMessage) { manager = msg.sender; message = initialMessage; } /* As this function is public, anyone can call this function but our modifier "onlyOwner" will run first. During compile time, Solidity will modify the content of the current function: first it will put all the code of the modifier, then it will replace "_;" with the code of the current function. After compilation, the code of this function will look like: require(msg.sender == manager); message = newMessage; Benefit of using modifier is some common code to be used for multiple functions can be added only once and that will run before the execution of actual function commands */ function setMessage(string newMessage) public onlyOwner { message = newMessage; } /* This is a basic modifier with name onlyOwner. "_;" is replaced by the actual contents of the function with which it is used. Check above function for example. */ modifier onlyOwner() { require(msg.sender == manager); _; } }
import { useEffect, useState } from "react"; const generateGrid = (size) => Array.from({ length: size }, () => Array.from({ length: size }, () => Math.random() > 0.5)); const getNextState = (isAlive, numberOfAliveNeighbours) => !isAlive ? numberOfAliveNeighbours === 3 : numberOfAliveNeighbours === 2 || numberOfAliveNeighbours === 3; const isOutOfBound = ({ length }, { x, y }) => x < 0 || y < 0 || x >= length || y >= length; const countAliveNeighbours = (grid, { x, y }) => [ [x - 1, y - 1], [x - 1, y], [x - 1, y + 1], [x, y + 1], [x + 1, y + 1], [x + 1, y], [x + 1, y - 1], [x, y - 1], ].filter(([i, j]) => !isOutOfBound(grid, { x: i, y: j }) && grid[i][j]).length; const useGameOfLife = ({ gridSize }) => { const [newGrid, setGrid] = useState(generateGrid(gridSize)); const step = (grid) => { let newGrid = structuredClone(grid); for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid.length; j++) { newGrid[i][j] = getNextState(grid[i][j], countAliveNeighbours(grid, { x: i, y: j })); } } setGrid(newGrid); }; return { grid: newGrid, setGrid, step }; }; export default useGameOfLife;
package com.tiooooo.mymovie.pages.genre import android.content.Intent import android.os.Bundle import androidx.core.view.isVisible import androidx.fragment.app.viewModels import androidx.paging.LoadState import androidx.recyclerview.widget.GridLayoutManager import com.tiooooo.core.base.BaseFragment import com.tiooooo.core.extensions.getLaunch import com.tiooooo.data.movie.api.model.list.Genre import com.tiooooo.mymovie.R import com.tiooooo.mymovie.databinding.FragmentGenreBinding import com.tiooooo.mymovie.pages.detail.movie.DetailMovieActivity import com.tiooooo.mymovie.pages.list.ListMovieAdapter import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest private const val EXTRA_GENRE = "EXTRA GENRE" private const val EXTRA_POSITION = "EXTRA POSITION" @AndroidEntryPoint class GenreFragment : BaseFragment<FragmentGenreBinding, GenreActivity>(R.layout.fragment_genre) { companion object { @JvmStatic fun newInstance(genres: ArrayList<Genre>? = null, position: Int) = GenreFragment().apply { arguments = Bundle().apply { putParcelableArrayList(EXTRA_GENRE, genres) putInt(EXTRA_POSITION, position) } } } private var listCategory: List<Genre>? = listOf() private var position: Int = 0 private val genreViewModel: GenreViewModel by viewModels() private lateinit var listMovieAdapter: ListMovieAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { listCategory = it.getParcelableArrayList(EXTRA_GENRE) position = it.getInt(EXTRA_POSITION, 0) } } override fun initView() { listCategory?.let { val categoryId = it[position].id.toString() genreViewModel.getMoviesByType(categoryId) listMovieAdapter = ListMovieAdapter().apply { onItemClick = { val intent = Intent(requireActivity(), DetailMovieActivity::class.java).apply { putExtra(DetailMovieActivity.EXTRA_ID, it) } startActivity(intent) } } binding.rvMovie.apply { this.adapter = listMovieAdapter layoutManager = GridLayoutManager(requireActivity(), 2) } binding.layoutError.btnTryAgain.isVisible = false } } override fun setSubscribeToLiveData() { genreViewModel.movies.observe(this) { getLaunch { listMovieAdapter.submitData(it) } } getLaunch { listMovieAdapter.loadStateFlow.collectLatest { with(binding) { progressBar.isVisible = it.refresh is LoadState.Loading progressBarLoadMore.isVisible = it.append is LoadState.Loading rvMovie.isVisible = it.refresh !is LoadState.Loading && it.refresh !is LoadState.Error layoutError.root.isVisible = it.refresh is LoadState.Error val errorState = it.refresh as? LoadState.Error ?: it.append as? LoadState.Error val errorMessage = errorState?.error?.message layoutError.tvInfo.text = errorMessage } } } } }
<?php namespace Armd\TvigleVideoBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('armd_tvigle_video'); $rootNode ->children() ->scalarNode('api_service_url')->defaultValue('http://pub.tvigle.ru/soap/index.php?wsdl')->end() ->scalarNode('api_login')->cannotBeEmpty()->end() ->scalarNode('api_password')->cannotBeEmpty()->end() ->end(); return $treeBuilder; } }
# Integrating Two-Factor Authentication (TwoFA) into Your Own Web App To access their account, users must first enter their login credentials when using Two-Factor Authentication (TwoFA). In an additional step, they receive an SMS containing a one-time code on their mobile phone or tablet. After correctly entering both security queries, users are allowed to log into their account. As a developer of a web app, you can now enhance the registration and login process for users by adding TwoFA via SMS: 1) Verification: During the registration process, verify the phone number provided by the user. If the user can enter the one-time code received, they confirm the authenticity of their registered number. You can skip this step if you already know all potential visitors and their respective phone numbers through other processes. 2) Authentication: During the login process, verify the already linked phone number to ensure that the user can still access the linked phone number. ## 1) Obtaining Keys Obtain the SiteKey and the SecretKey for your app's domain. You can find detailed instructions [here](https://www.berlinsms.de/fuer-entwickler/dokumentation/sitekey-secretkey-generieren/). Also, provide the SiteKey and SecretKey for your captcha provider if you want to supplement the registration process with TwoFA as described above. ## 2) Verification in the Registration Process To implement verification in the registration process, you need an additional field for the phone number in your registration form. Add the js module "twofa-optin.js" before the submit button and include the SiteKey parameter you received in step 1. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } <script src="https://static.berlinsms.de/twofa/twofa-optin.js?bsmsSitekey=<?php echo TWOFA_SITE_KEY; ?>&onSolved=onSolvedCallback"></script> ``` </details> </div> The module provides an input field for phone numbers and handles the validation in the frontend. It also adds a Hidden Input with a challenge token to the form. Only after correctly entering the code sent via SMS, a registration button will be enabled. Optionally, you can add a callback that is only triggered after confirmation of the code. <div class="tabs"> <details open><summary>.js</summary> ``` { .js } <script language="javascript"> function onSolvedCallback() { document.getElementById("submit").disabled = false; } </script> ``` </details> </div> When the user clicks the registration button, the form is submitted, and the user can be registered. ## 3) Verification in the Backend After submitting the form, the backend receives the challenge token. Since data in the frontend can be manipulated, it is strongly recommended to validate the challenge token on the server side. Use the "Twofa" module, which you can download [here](https://github.com/berlinSMS/twofa/blob/main/twofa.php). Save the module in your web space and import it into your backend code. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } include 'twofa.php'; ``` </details> </div> Create an instance of the "Twofa" class, passing the SiteKey and SecretKey to the constructor. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } $twofa = new Twofa( TWOFA_SITE_KEY, TWOFA_SECRET_KEY ); ``` </details> </div> Retrieve the challenge information using the "getTwofaChallenge" member function. This function expects the challenge token as a parameter. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } $twofaChallenge = $twofa->getTwofaChallenge($_POST['challengeToken']); ``` </details> </div> The returned object contains the verified phone number in the "solved" parameter and information about whether the challenge was successfully solved. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } if ($twofaChallenge->hasError()) { echo 'Error: ' . $twofaChallenge->getError(); } else if (!$twofaChallenge->isSolved()) { echo "<hr>twofa verification failed"; } else { echo "<hr>twofa verifcation successful <br>" . $twofaChallenge->getVerifiedAddress() . " is the verified phone number"; } ``` </details> </div> Now you can create the user and link the phone number. Remember to only use the returned phone number. Phone numbers entered in the frontend or form can be manipulated. ## 4) Authentication in the Login Process To implement phone number authentication in the login process, add another security check after verifying the username and password: Retrieve the user's phone number, for example, from your database. Then, send a code via SMS to this number. Again, use the "Twofa" module. If not done yet, you can download it [here](https://github.com/berlinSMS/twofa/blob/main/twofa.php). Save the module in your web space, import it into your backend code, and create an instance of the "Twofa" class, passing the SiteKey and SecretKey to the constructor. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } include '../twofa.php'; $twofa = new Twofa( TWOFA_SITE_KEY, TWOFA_SECRET_KEY ); ``` </details> </div> Initiate the verification process with the "postTwofaSendsms" member function. This function expects the phone number to be checked. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } $postTwofaSendsmsResponse = $twofa->postTwofaSendsms($phonenumber); ``` </details> </div> The user now receives a code via SMS to the provided phone number. As a result, you get an object with a challenge token. Next, the user enters the code from the SMS into a form provided by you. At the same time, the challenge token is passed as a Hidden Input. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } <form id="code-form" method="post" action="login.php"> <input type="hidden" name="challengeToken" value="<?php echo $postTwofaSendsmsResponse->getChallengeToken(); ?>" /> <br /><label for="code">Code</label> <br /><input id="code" name="code" placeholder="Code" type="number" size="6" oninput="codeEntered" /> <br /><button id="submit" type="submit">Verify Code</button> </form> ``` </details> </div> You can now verify if both parameters - user input and challenge token - match using the "putTwofaPreverifycode" member function. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } $twofaChallenge = $twofa->putTwofaPreverifycode($_POST['challengeToken'], $_POST['code']); ``` </details> </div> The returned object contains the verified phone number and the "solved" parameter, indicating whether the challenge was successfully solved. <div class="tabs"> <details open><summary>.php</summary> ``` { .php } if ($twofaChallenge->hasError()) { echo 'Error: ' . $twofaChallenge->getError(); } else if ($twofaChallenge->getSolved()) { echo 'Succesfully login as ' . $twofaChallenge->getVerifiedAddress(); } else { echo 'Login failed, not verified: ' . $twofaChallenge->getError(); } ``` </details> </div> You can now log in the user. You can find the complete code of this tutorial for download [here](https://github.com/berlinSMS/twofa/tree/main/examples)
const Sequelize = require('sequelize') // Selecting Rows with Operators const { DataTypes, Op } = Sequelize const sequelize = new Sequelize('your_database', 'your_username', 'your_password', { dialect: 'mysql', host:'your_host', port:3306 }) const Customer = sequelize.define('customer', { user_id: { type:DataTypes.INTEGER, primaryKey:true, autoIncrement:true }, username:{ type: DataTypes.STRING, }, password:{ type: DataTypes.STRING, }, age: { type: DataTypes.INTEGER, defaultValue:21 }, vegetarian:{ type: DataTypes.BOOLEAN, defaultValue:true } }, { freezeTableName:true, timestamps:false }); Customer.sync({ alter:true }) .then(() => { // working with our update table. // Executing (default): DELETE FROM `customer` WHERE `username` = 'hello!' // 26 return Customer.destroy({where:{ username:'hello!'}, truncate:true}) // delete every row but don't delete the table itself // return Customer.destroy({where:{ truncate:true }) }). then((data) => { console.log(data) }) .catch((err) => { console.log(err) })
library (data.table) library (lubridate) #Function for calculating solar zenith #---------------------------------------------------------> # This routine used to estimate the zenith angle (Degree) # Modified version of code from Jehn-Yih Juang, Jul 2004 # ref: Campbell and Norman,1998 eq. 11.1 - 11.4 # input # Hr: hour in decimal form, ex: 14:30-->14.5 # LAT: latitude, in degree # LON: longitude, in degree # DOY: day of year # output # ZA: zenith angel in degree # cosZA: cosine of zenith angle #---------------------------------------------------------> zenith_calc <- function (LAT,LON,DOY,Hr){ A = (356.6 + 0.9856 * DOY) * pi/180 A = (278.97 + 0.9856 * DOY + 1.9165 * sin(A)) * pi/180 sinSD = 0.39785 * sin(A) SD = asin (sinSD) STM = seq(-165, 180, by = 15) #Standard meridians LCa = (LON-STM) / 15 LC = min(abs(LCa)) LC = LCa[which(abs(LCa) == LC)] #Longitudinal correction f = 279.575 + 0.9856 * DOY A = f * pi/180 ET = (-104.7 * sin(A) + 596.2 * sin(2 * A) + 4.3 * sin(3 * A) - 12.7 * sin(4 * A) - 429.3 * cos(A) - 2.0 * cos(2 * A) + 19.3 * cos (3 * A)) / 3600 t0 = 12 - LC - ET A = LAT * pi/180.; cosZA = (sin(A) * sin(SD) + cos(A) * cos(SD) * cos (15 * (Hr - t0) * pi/180)) ZA = acos(cosZA) * 180/pi return (c(ZA, cosZA)) } #--------------------------------------------------------------------------------------------- #Read in data from goes fires <- fread('califires2019_goes_cmi2km_mar2019_march2020_cmask.csv', stringsAsFactors = F) #convert stimestamp to utc POSIXct datatype fires$stimestamp_utc = as.POSIXct(fires$stimestamp, tz = 'UTC', format="%Y-%m-%dT%H:%M:%OSZ") #convert to pacific fires$stimestamp_ldt = format(fires$stimestamp_utc, tz = 'US/Pacific') fires$stimestamp_ldt = as.POSIXct(fires$stimestamp_ldt, tz = 'US/Pacific') #Get date to calculate stats by day fires$date_utc = as.POSIXct(date(fires$stimestamp_utc)) fires$date_ldt = as.POSIXct(date(fires$stimestamp_ldt)) #Calculate decimal hour fires[, dec_hour_utc := (hour(stimestamp_utc) + (minute(stimestamp_utc) / 60) + (second(stimestamp_utc) / 3600) )] fires[, dec_hour_ldt := (hour(stimestamp_ldt) + (minute(stimestamp_ldt) / 60) + (second(stimestamp_ldt) / 3600) )] #Calculate solar zenith angle and cos(sza) for each unique fire timestamp fires[, sza := zenith_calc(lat, lon, doy, dec_hour_ldt)[1], by = list(fire, stimestamp, inside_perim)] fires[, cos_sza := zenith_calc(lat, lon, doy, dec_hour_ldt)[2], by = list(fire, stimestamp, inside_perim)] #Clear Kincade fire observations kin = fires[fire == 'Kincade' & cloud == 0] #Calculate NDVI and NDII kin[, NDVI := (CMI_C03 - CMI_C02) / (CMI_C03 + CMI_C02)] kin[, NDII_5 := (CMI_C03 - CMI_C05) / (CMI_C03 + CMI_C05)] kin_day = kin[sza < 70] #Calculate mean daytime NDVI, NDII_5, NDII_6 in_mean_ndvi = kin_day[inside_perim == T, list(mean_NDVI = mean(NDVI), mean_NDII5 = mean(NDII_5), stimestamp_ldt, stimestamp_utc), by = date_utc] out_mean_ndvi = kin_day[inside_perim == F, list(mean_NDVI = mean(NDVI), mean_NDII5 = mean(NDII_5), stimestamp_ldt, stimestamp_utc), by = date_utc] #Calculate median NDVI, NDII_5, NDII_6 surrounding noon hours in_mednoon_ndvi = kin_day[inside_perim == T & dec_hour_ldt > 10 & dec_hour_ldt < 14, list(median_NDVI = median(NDVI), median_NDII5 = median(NDII_5), stimestamp_ldt, stimestamp_utc), by = date_utc] out_mednoon_ndvi = kin_day[inside_perim == F & dec_hour_ldt > 10 & dec_hour_ldt < 14, list(median_NDVI = median(NDVI), median_NDII5 = median(NDII_5), stimestamp_ldt, stimestamp_utc), by = date_utc] #Read in modis data at fire point #fires.modis <- fread('califires2019_modis_l1b1km_mar2019_march2020.csv') fires.modis <- fread ('califires_modis_mcd43a4_2019_2020.csv', stringsAsFactors = F) #Get good quality fire entries fires.modis = fires.modis[Name %in% c('kincade_infire', 'kincade_outfire') & b1_qf == 0 & b2_qf == 0 & b6_qf == 0] #Convert date to string fires.modis$date_str = as.character(fires.modis$date) #convert stimestamp to utc POSIXct datatype fires.modis$date_utc = as.POSIXct(fires.modis$date_str, tz = 'UTC', format="%Y%j" ) #convert to pacific fires.modis$date_ldt = format(fires.modis$date_utc, tz = 'US/Pacific') fires.modis$date_ldt = as.POSIXct(fires.modis$date_utc, tz = 'US/Pacific') #Get date #fires.modis$date_utc = date(fires.modis$date_utc) #fires.modis$date_ldt = date(fires.modis$date_ldt) #Calculate NDVI fires.modis [, NDVI := (b2_ref - b1_ref) / (b2_ref + b1_ref)] fires.modis [, NDII := (b2_ref - b6_ref) / (b2_ref + b6_ref)] #----------------------PLOT NDVI inside fire-------- par(mfrow = c(2, 1)) ylims = c(min(kin_day[inside_perim == T]$NDVI, fires.modis[Name == 'kincade_infire']$NDVI, na.rm = T), max(kin_day[inside_perim == T]$NDVI, fires.modis[Name == 'kincade_infire']$NDVI, na.rm = T) ) #Set up plot plot(NDVI ~ date_utc, kin_day[inside_perim == T], xlab = '', xaxt = 'n', ylab = 'NDVI', ylim = ylims, pch = '', cex.axis = 1) #Shade fire dates x = c(min(kin_day[inside_perim == T & doy == 296]$date_utc), min(kin_day[inside_perim == T & doy == 310]$date_utc), min(kin_day[inside_perim == T & doy == 310]$date_utc), min(kin_day[inside_perim == T & doy == 296]$date_utc)) y = c(-2, -2, 2, 2) polygon(x, y, col = 'gray88', border = 'gray88') #Add NDVI points(NDVI ~ date_utc, kin_day[inside_perim == T], pch = 20, cex = 0.8, col = 'gray50') #Add modis NDVI points(NDVI ~ date_utc, fires.modis[date_utc >= min(kin_day[inside_perim == T]$date_utc) & date_utc <= max(kin_day[inside_perim == T]$date_utc) & Name == 'kincade_infire'], pch = 20, cex = 0.8, col = 'red') #Add GOES noon time median NDVI points(median_NDVI ~ date_utc, in_mednoon_ndvi, pch = 20, cex = 0.8, col = 'goldenrod2') #Add GOES mean NDVI points(mean_NDVI ~ date_utc, in_mean_ndvi, #pch = 5, cex = 0.8, col = 'purple') #Add x-axis date_seq = seq( min(kin_day[inside_perim == T]$date_utc), max(kin_day[inside_perim == T]$date_utc), by = 'week') axis.POSIXct(1, kin_day[inside_perim == T]$date_utc, at = date_seq, format = '%m-%d', las = 3, cex = 0.8) title ("Inside fire perimeter", col = 'gray') #Add legend legend('topright', legend=c("MODIS NBAR NDVI", "GOES TOA NDVI", "GOES median (local hours 10 - 14)", "GOES daily daytime mean", "Fire duration"), pch = c(20, 20, 20, 1, NA), col=c("red", "gray50", "goldenrod2", "purple", NA), border = c(NA, NA, NA, NA, NA), fill = c(NA, NA, NA, NA, 'gray'), ncol=1, bty="n") #-------Plot NDVI outside fire perimeter---------------- ylims_out = c(min(kin_day[inside_perim == F]$NDVI, fires.modis[Name == 'kincade_outfire']$NDVI, na.rm = T), max(kin_day[inside_perim == F]$NDVI, fires.modis[Name == 'kincade_outfire']$NDVI, na.rm = T) ) plot(NDVI ~ date_utc, kin_day[inside_perim == F & NDVI > -1 & NDVI < 1], xlab = '', ylab = 'NDVI', ylim = ylims_out, pch = '', xaxt = 'n') #Shade fire dates x = c(min(kin_day[inside_perim == F & doy == 296]$date_utc), min(kin_day[inside_perim == F & doy == 310]$date_utc), min(kin_day[inside_perim == F & doy == 310]$date_utc), min(kin_day[inside_perim == F & doy == 296]$date_utc)) y = c(-2, -2, 2, 2) polygon(x, y, col = 'gray88', border = 'gray88') #Add NDVI points(NDVI ~ date_utc, kin_day[inside_perim == F], pch = 20, cex = 0.8, col = 'gray50') #Add modis NDVI points(NDVI ~ date_utc, fires.modis[date_utc >= min(kin_day[inside_perim == F]$date_utc) & date_utc <= max(kin_day[inside_perim == F]$date_utc) & Name == 'kincade_outfire'], pch = 20, cex = 0.8, col = 'red') #Add median noon NDVI points(median_NDVI ~ date_utc, out_mednoon_ndvi, pch = 20, cex = 0.8, col = 'goldenrod2') #Add daily mean NDVI points(mean_NDVI ~ date_utc, out_mean_ndvi, cex = 0.8, col = 'purple') #Add x-axis date_seq = seq( min(kin_day[inside_perim == F]$date_utc), max(kin_day[inside_perim == F]$date_utc), by = 'week') axis.POSIXct(1, kin_day[inside_perim == F]$date_utc, at = date_seq, format = '%m-%d', las = 3) title ('Outside fire perimeter', col = 'gray') #Add legend legend('bottomright', legend=c("MODIS NBAR NDVI", "GOES TOA NDVI", "GOES median (local hours 10 - 14)", "GOES daily daytime mean", "Fire duration"), pch = c(20, 20, 20, 1, NA), col=c("red", "gray50", "goldenrod2", "purple", NA), border = c(NA, NA, NA, NA, NA), fill = c(NA, NA, NA, NA, 'gray'), ncol=1, bty="n") #----------Plot NDII inside fire perimeter----------- par(mfrow = c(2, 1)) ylims_out = c(min(c(kin_day$NDII_5, fires.modis$NDII), na.rm = T), max(c(kin_day$NDII_5, fires.modis$NDII), na.rm = T) ) plot(NDII_5 ~ date_utc, kin_day[inside_perim == T & NDII_5 > -1 & NDII_5 < 1], xlab = '', ylab = 'NDII', ylim = ylims_out, pch = '', xaxt = 'n') #Add fire dates x = c(min(kin_day[inside_perim == T & doy == 296]$date_utc), min(kin_day[inside_perim == T & doy == 310]$date_utc), min(kin_day[inside_perim == T & doy == 310]$date_utc), min(kin_day[inside_perim == T & doy == 296]$date_utc)) y = c(-2, -2, 2, 2) polygon(x, y, col = 'gray88', border = 'gray88') #Add NDII points(NDII_5 ~ date_utc, kin_day[inside_perim == T], pch = 20, cex = 0.8, col = 'gray50') #Add modis NDVI points(NDII ~ date_utc, fires.modis[date_utc >= min(kin_day[inside_perim == T]$date_utc) & date_utc <= max(kin_day[inside_perim == T]$date_utc) & Name == 'kincade_infire'], pch = 20, cex = 0.8, col = 'red') #Add median noon NDII points(median_NDII5 ~ date_utc, in_mednoon_ndvi, pch = 20, cex = 0.8, col = 'goldenrod2') #Add daily mean NDII points(mean_NDII5 ~ date_utc, in_mean_ndvi, cex = 0.8, col = 'purple') #Add x-axis date_seq = seq( min(kin_day[inside_perim == T]$date_utc), max(kin_day[inside_perim == T]$date_utc), by = 'week') axis.POSIXct(1, kin_day[inside_perim == T]$date_utc, at = date_seq, format = '%m-%d', las = 3) title ('Inside fire perimeter', col = 'gray') #Add legend legend('topright', legend=c("MODIS NBAR NDII", "GOES TOA NDII", "GOES median (local hours 10 - 14)", "GOES daily daytime mean", "Fire duration"), pch = c(20, 20, 20, 1, NA), col=c("red", "gray50", "goldenrod2", "purple", NA), border = c(NA, NA, NA, NA, NA), fill = c(NA, NA, NA, NA, 'gray'), ncol=1, bty="n") #---------Plot NDII outside of fire perimeter-------- ylims_out = c(min(c(kin_day$NDII_5, fires.modis$NDII), na.rm = T), max(c(kin_day$NDII_5, fires.modis$NDII), na.rm = T) ) plot(NDII_5 ~ date_utc, kin_day[inside_perim == F & NDII_5 > -1 & NDII_5 < 1], xlab = '', ylab = 'NDII', ylim = ylims_out, pch = '', xaxt = 'n') #Add fire dates x = c(min(kin_day[inside_perim == F & doy == 296]$date_utc), min(kin_day[inside_perim == F & doy == 310]$date_utc), min(kin_day[inside_perim == F & doy == 310]$date_utc), min(kin_day[inside_perim == F & doy == 296]$date_utc)) y = c(-2, -2, 2, 2) polygon(x, y, col = 'gray88', border = 'gray88') #Add NDII points(NDII_5 ~ date_utc, kin_day[inside_perim == F], pch = 20, cex = 0.8, col = 'gray50') #Add modis NDVI points(NDII ~ date_utc, fires.modis[date_utc >= min(kin_day[inside_perim == F]$date_utc) & date_utc <= max(kin_day[inside_perim == F]$date_utc) & Name == 'kincade_outfire'], pch = 20, cex = 0.8, col = 'red') #Add median noon NDII points(median_NDII5 ~ date_utc, out_mednoon_ndvi, pch = 20, cex = 0.8, col = 'goldenrod2') #Add daily mean NDII points(mean_NDII5 ~ date_utc, out_mean_ndvi, cex = 0.8, col = 'purple') #Add x-axis date_seq = seq( min(kin_day[inside_perim == F]$date_utc), max(kin_day[inside_perim == F]$date_utc), by = 'week') axis.POSIXct(1, kin_day[inside_perim == F]$date_utc, at = date_seq, format = '%m-%d', las = 3) title ('Outside fire perimeter', col = 'gray') #Add legend legend('bottomright', legend=c("MODIS NBAR NDII", "GOES TOA NDII", "GOES median (local hours 10 - 14)", "GOES daily daytime mean", "Fire duration"), pch = c(20, 20, 20, 1, NA), col=c("red", "gray50", "goldenrod2", "purple", NA), border = c(NA, NA, NA, NA, NA), fill = c(NA, NA, NA, NA, 'gray'), ncol=1, bty="n")
function f = fun(x) f = [x(1)+x(2)-3; x(1)^2+x(2)^2-9];//função a ser minimazada endfunction function G = jacob(x) G = [1 1; 2*x(1) 2*x(2)]; //jacobiana da função endfunction x0 = rand(2,1); //chutes iniciais randomicos max_iter = 100; //numero maximo de interações tol = 1e-4; //precisão dos chutes realizados iter = 0; //iterações realizadas pelo programa error = tol + 1; //condição de parada pela precisão while (iter < max_iter && error > tol) //injetando os chutes nas funções f = fun(x0); G = jacob(x0); //Calculo dos valores ótimos para x S = -G\f; x1 = x0 + S; //Condição de parada error = max(abs(x1 - x0)); x0 = x1;//x recebendo o novo valor ótimo iter = iter + 1;//incrementando o contador de interações end if (iter >= max_iter)//condição de parada caso as interações excedam o limite disp("Não foi possível encontrar o mínimo em ", max_iter, " iterações."); else//disposição dos resultados disp("Valor ótimo:") disp(x0) disp("Número de iterações:") disp(iter) disp("Erro:") disp(error) end //Exibição do grafico function f = fun(x) f = [x(1)+x(2)-3; x(1)^2+x(2)^2-9];//n sei pq tive que recirar a função aqui endfunction x = linspace(-10, 10, 100);//dimensoes do grafico y = linspace(-10, 10, 100); [X, Y] = meshgrid(x, y); Z1 = X + Y - 3; //calculo do f(x) Z2 = X.^2 + Y.^2 - 9;//calculo do g(x) //Desenho dos graficos com as dimensões e o array de resultados da função figure(); subplot(1, 2, 1); surf(X, Y, Z1); xlabel('x') ylabel('y') zlabel('f(x,y)') title('Superfície de otimalidade da função f(x,y)') subplot(1, 2, 2); surf(X, Y, Z2); xlabel('x') ylabel('y') zlabel('g(x,y)') title('Superfície de otimalidade da função g(x,y)')
<div class="form-group mt-4"> <div class="d-flex align-items-center justify-content-between"> <%= form.label(:template, 'Template', class: 'mb-2') %> <%= tooltip(placement: 'right', classes: 'small', message: 'Awesome-o has several blog post templates that have been tested and proven to rank favorably in SERPs.' ) %> </div> <%= panel_item do %> <%= form.select(:template, options_for_select( [ ['Beginners Guide', 'beginners_guide'], ['Comparison', 'comparison'], ['Definition', 'definition'], ['Fact Checker', 'fact_checker'], ['How-to','how_to'], ['Listicle (list)', 'listicle'], ['Product Review', 'product_review'], ], ), { include_blank: "Select a template" }, class: 'form-select', data: { create_panel_target: :templateSelect, action: 'change->create-panel#updatePrompt' } ) %> <% end %> </div> <div class="form-group mt-4"> <div class="d-flex align-items-center justify-content-between"> <%= form.label('Title?', class: 'mb-2') %> <%= tooltip(placement: 'right', classes: 'small', message: 'By default Awesome-o will not generate a title for you. Turn the switch on to generate a title.' ) %> </div> <%= panel_item(classes: 'form-check form-switch d-flex justify-content-between') do %> <%= form.label(:generate_title, 'Generate a title?', class: 'form-check-label') %> <%= form.check_box(:generate_title, { class: 'form-check-input', role: :switch }, 'true', 'false' ) %> <% end %> </div> <div class="form-group mt-4"> <div class="d-flex align-items-center justify-content-between"> <%= form.label(:keywords, class: 'mb-2') %> <%= tooltip(placement: 'right', classes: 'small', message: 'Tell Awesome-o the keywords you\'d like your blog post optimized for. Enter a comma separated list.' ) %> </div> <div class="bg-light rounded border p-1 shadow-sm"> <%= form.text_area(:keywords, rows: 5, class: 'form-control') %> <span class="text-muted small">Comma separated keywords</span> </div> </div>
<h1 align="middle" font-weight="bold" > Builder Design Pattern </h1> <p align="center"> <img src="https://github.com/CharbelElBateh/programmers-pizzeria/assets/99130418/e9e8a733-ca23-4094-a277-59d442948142" width="350" title="Create Your Own Pizza"> </p> # Programmer's Pizzaeria 🍕 This project is an effective implementation of the builder design pattern as part of the COE312 course Fall 2022 ### What is the builder design pattern? The builder design pattern suggests that you extract the object construction code from its own class and move it to separate objects called builders. ### What problem does it solve? The builder design pattern allows you to create different flavors of an object while avoiding constructor pollution. Practical when there could be several flavors of an object. Or when there are many steps involved in creating an object. ## How to run? ### 1. Download your preferred web server I use [XAMPP](https://www.bing.com/ck/a?!&&p=97ffa3fe265a2517JmltdHM9MTY4NTU3NzYwMCZpZ3VpZD0xNWZmYzNkMS03NzE1LTY3NTktMDk0Ny1kMGYzNzY2ZDY2MmUmaW5zaWQ9NTE5Mg&ptn=3&hsh=3&fclid=15ffc3d1-7715-6759-0947-d0f3766d662e&psq=xampp&u=a1aHR0cHM6Ly93d3cuYXBhY2hlZnJpZW5kcy5vcmcvZG93bmxvYWQuaHRtbA&ntb=1) ### 2. Start the servers 💻 This step is very dependable on your preferred web server ### 3. Import the database 🗄️ Create a new database called 'database' and import the `dashboard.sql` file. ### 4. Access the website 🔓 You can access the website through your local Here are the links 🌐: - [Main Website](http://127.0.0.1/programmers-pizzaria/index.php) _Your Database interface location will also depend on your preferred web server_ - [Database Interface](http://localhost/phpmyadmin/index.php) ## Technologies used <p align="middle"> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/danielcranney/readme-generator/main/public/icons/skills/javascript-colored.svg" width="36" height="36" alt="Javascript" /></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/HTML5" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/danielcranney/readme-generator/main/public/icons/skills/html5-colored.svg" width="36" height="36" alt="HTML5" /></a> <a href="https://www.w3.org/TR/CSS/#css" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/danielcranney/readme-generator/main/public/icons/skills/css3-colored.svg" width="36" height="36" alt="CSS3" /></a> <a href="https://git-scm.com/" rel="Git"><img class="ml-4 w-8 h-8 sm:w-10 sm:h-10" src="https://www.vectorlogo.zone/logos/git-scm/git-scm-icon.svg" alt="git" width="36" height="36"></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/PHP" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/danielcranney/readme-generator/main/public/icons/skills/php-colored.svg" width="36" height="36" alt="PHP" /></a> <a href="https://developer.mozilla.org/en-US/docs/Glossary/MYSQL" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/danielcranney/readme-generator/main/public/icons/skills/mysql-colored.svg" width="36" height="36" alt="MySQL" /></a> ## UML Diagram of the builder design pattern implemented 📊 <p align="center"> <img src="https://github.com/CharbelElBateh/programmers-pizzeria/assets/99130418/e949018c-a866-4f56-a73e-13b7002a8f37" title="UML Diagram"> </p> ## Database Structure 🏗️: <p align="center"> <img src="https://github.com/CharbelElBateh/programmers-pizzeria/assets/99130418/34cb26af-7934-4cb7-80ac-e5e48e2d4352" title="Database Structure"> </p> ------------------------------------------------------------
import { Deferred, delay } from 'retil-support' import { TEARDOWN_DELAY, createState, fuseVector, wait } from '../src' import { sendVectorToArray } from './utils/sendToArray' describe(`fuseVector`, () => { test('used sources should stay subscribed while waiting for an async act() to complete', async () => { const [source1, setState] = createState(1) let unsubscribes = 0 const source2 = fuseVector( (use) => use(source1), () => { unsubscribes++ }, ) const deferred = new Deferred() const source = fuseVector((use, act) => { const [state] = use(source2) if (state % 2 === 1) { return act(async () => { await deferred.promise setState(state + 1) }) } return [state] }) const output = sendVectorToArray(source) expect(unsubscribes).toEqual(0) expect(output).toEqual([]) await delay(TEARDOWN_DELAY + 50) deferred.resolve(null) await wait(source, (value) => { return value === 2 }) expect(output).toEqual([[2]]) expect(unsubscribes).toEqual(0) }) })
const express = require('express'); const mongoose = require('mongoose'); const path = require('path'); const bodyParser = require('body-parser'); const { PORT, MONGO_URL } = require('dotenv').config().parsed; const User = require('./src/models/User') // Auth middleware package const session = require('express-session'); const passport = require('passport'); const LocalStrategy = require('passport-local').Strategy; // import routes const router = require('./src/routes/api'); const appRouter = require('./src/routes/app'); const userRouter = require('./src/routes/api/userRouter'); const port = PORT || 3000; // Passport files const verify = (username, password, done) => { User.findOne({ name: username }).then((user, err) => { if (err) { return done(err) } if (!user) { return done(null, false) } if (!User.validate(password, user.password)) { return done(null, false) } return done(null, user) }) } const options = { usernameField: "name", passwordField: "password", } passport.use('local', new LocalStrategy(options, verify)) passport.serializeUser((user, cb) => { cb(null, user._id) }) passport.deserializeUser((id, cb) => { User.findById(id).then((user, err) => { if (err) { return cb(err) } cb(null, user) }) }) const app = express() app.set('view engine', 'ejs') app.use(bodyParser.urlencoded({ extended: true })); app.use(session({ secret: 'SECRET', resave: true, saveUninitialized: true })); app.use(passport.initialize()) app.use(passport.session()) // Routes app.use('/app', appRouter); app.use('/api', router); app.use('/user', userRouter); app.use('/', (req, res) => res.redirect('/app')) const start = async () => { try { await mongoose.connect(MONGO_URL); await app.listen(port, () => { console.log(`Server is running on port ${port}`); }) } catch (error) { console.log('err' + error); } } start()
import React, {useState} from 'react'; import Image from 'next/image'; import logo from '../../src/screens/general/login/Logotipo.svg'; import photo from "../../src/screens/general/login/bg_image.svg"; import effect from "../../src/screens/general/login/Rectangle.svg"; import eye from '../../src/screens/general/login/eye.svg'; import {signInUser} from "../../src/redux/actions/authActions"; import {useDispatch} from "react-redux"; import {ToastContainer ,toast} from 'react-toastify' import 'react-toastify/dist/ReactToastify.css'; import ScaleLoader from "react-spinners/ScaleLoader"; import RecoveryPassword from "../../src/components/recoverPassword/recoveryPassword"; import ChangePassword from "../../src/components/changePassword/changePassword"; import T from '../../src/components/T'; const Login = () => { const dispatch = useDispatch() const [loading, setLoading] = useState(false); const [showRecoveryPassword, setShowRecoveryPassword] = useState(false); const [showChangePassword, setShowChangePassword] = useState(false); const [credentials, setCredentials] = useState({ mail: "", password: "" }) const onSubmit = async (e: any) => { e.preventDefault() const { mail, password} = credentials; setLoading(true) const res = await signInUser(dispatch, mail, password); setLoading(false) if (res == null){ toast.error('Tu usuario no es Administrador', { position: "bottom-right", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, }); return null } // Manejar error if (res.error == "Incorrect username or password."){ toast.warn('El usuario y/o contraseña son incorrectos', { position: "bottom-right", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, }); return null } if(res.error) { toast.error(res.error); return } if(!res.error) { } } function showPassword(){ const tipo = document.getElementById("password"); // @ts-ignore if(tipo.type == "password"){ // @ts-ignore tipo.type = "text"; }else{ // @ts-ignore tipo.type = "password"; } } function onChange(event: any) { setCredentials({ ...credentials, [event.target.name]: event.target.value }) } return ( <div className="relative w-screen h-screen m-0"> { showRecoveryPassword ? <RecoveryPassword setRecovey={setShowRecoveryPassword} mail={setCredentials} /> :null } { showChangePassword ? <ChangePassword setRecovey={setShowRecoveryPassword} setChange={setShowChangePassword} setCredentials={setCredentials} /> :null } <div className="z-0 lg:hidden"><Image src={photo} layout={"responsive"}/></div> <div className="absolute z-0 top-0 opacity-50 w-screen h-screen lg:hidden"> <Image src={effect} layout={"responsive"}/> </div> <div className="z-10 fixed bottom-0 px-10 pt-10 lg:flex lg:flex-row h-auto bg-white rounded-t-[18px] lg:h-screen lg:bottom-auto lg:pt-0 lg:px-0 w-full"> <div className="hidden bg-no-repeat bg-cover bg-[url('../../src/screens/general/login/bg_image.svg')] lg:block lg:w-1/2 lg:max-w-[600px] rounded-r-full"/> <div className="flex flex-col items-center justify-center lg:w-1/2 lg:h-screen flex-grow"> <Image className="" src={logo}/> <form onSubmit={onSubmit} className="mx-7 w-full min-w-min max-w-[400px] px-7 pt-10 lg:w-96 lg:h-auto"> <div className="email"> <label className="text-primary-button-bg text-[10px] lg:text-[14px]">Correo electronico</label> <input required onChange={onChange} name={"mail"} value={credentials.mail} type="text" className="border-b-2 border-neutral-300 w-full min-w-[250px] h-full text-[12px] lg:text-[15px] outline-0 pb-1"/> </div> <div className="password relative mt-3"> <label className="text-primary-button-bg text-[10px] lg:text-[14px]">Contraseña</label> <input required onChange={onChange} name={"password"} value={credentials.password} id="password" className="border-b-2 border-neutral-300 w-full h-full text-[12px] lg:text-[15px] outline-0 pb-1" type="password"/> <div onClick={showPassword} className="h-2 absolute right-1 bottom-4 cursor-pointer"><Image src={eye} height={20} width={30}></Image></div> </div> <div className="flex text-[#9955D4] text-[10px] lg:text-[14px] pt-9"> <div onClick={() => setShowChangePassword(true)} className="cursor-pointer"><a>¿Olvidé mi contraseña?</a></div> </div> <div className="flex justify-center items-center py-9"> {loading ? <ScaleLoader color="#425AC5"/>: <button className="bg-primary-button-bg text-[15px] text-white w-[166px] h-[33px] rounded-[5px]"> Iniciar sesión </button> } </div> </form> </div> </div> </div> ); }; export default Login;
import { useState } from "react" import { Card, CardContent, CardHeader, CardTitle } from "./ui/card" export default function FlashCard({ question, answer, options }: FLASH_CARD) { const [flip, setFlip] = useState(false) return ( <Card className={`${ flip ? "flip" : "" } card rounded-xl flex items-center justify-center flex-col cursor-pointer hover:shadow-xl hover:shadow-primary/20 min-h-[300px]`} onClick={() => setFlip(!flip)} > {flip ? ( <CardContent className="back flex items-center justify-center text-center"> {answer} </CardContent> ) : ( <section className="front flex items-center justify-center flex-col"> <CardHeader> <CardTitle className="text-center">{question}</CardTitle> </CardHeader> <CardContent className="grid grid-cols-2 gap-1 w-full"> {options.map((option) => ( <h1 key={option} className="text-center cursor-pointer"> {option} </h1> ))} </CardContent> </section> )} </Card> ) }
#!/usr/bin/env python # coding: utf-8 # ### Answer 3 # Consider the ‘Blood Pressure Before’ and ‘Blood Pressure After’ columns from the data and calculate the following # https://drive.google.com/file/d/1mCjtYHiX--mMUjicuaP2gH3k-SnFxt8Y/view?usp=share_ # # a. Measure the dispersion in both and interpret the results. # b. Calculate mean and 5% confidence interval and plot it in a graph # c. Calculate the Mean absolute deviation and Standard deviation and interpret the results. # d. Calculate the correlation coefficient and check the significance of it at 1% level of significance. # # In[39]: import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy import stats # Read the data from the provided Google Drive link data_url = "https://drive.google.com/uc?id=1mCjtYHiX--mMUjicuaP2gH3k-SnFxt8Y" data = pd.read_csv(data_url) # Extract the ' Blood Pressure Before (mmHg)' and ' Blood Pressure After (mmHg)' columns bp_before = data[' Blood Pressure Before (mmHg)'] bp_after = data[' Blood Pressure After (mmHg)'] # a. Measure the dispersion in both and interpret the results dispersion_bp_before = np.var(bp_before) dispersion_bp_after = np.var(bp_after) print("Dispersion (Variance) in Blood Pressure Before: ", dispersion_bp_before) print("Dispersion (Variance) in Blood Pressure After: ", dispersion_bp_after) # b. Calculate mean and 5% confidence interval and plot it in a graph mean_bp_before = np.mean(bp_before) mean_bp_after = np.mean(bp_after) confidence_interval_bp_before = stats.t.interval(0.95, len(bp_before)-1, loc=mean_bp_before, scale=stats.sem(bp_before)) confidence_interval_bp_after = stats.t.interval(0.95, len(bp_after)-1, loc=mean_bp_after, scale=stats.sem(bp_after)) # Plotting the mean and confidence interval plt.errorbar(['Blood Pressure Before', 'Blood Pressure After'], [mean_bp_before, mean_bp_after], yerr=[confidence_interval_bp_before[1]-mean_bp_before, confidence_interval_bp_after[1]-mean_bp_after], fmt='o') plt.title("Mean and 5% Confidence Interval") plt.ylabel("Mean") plt.ylim([70, 100]) plt.show() # c. Calculate the Mean Absolute Deviation and Standard Deviation and interpret the results mad_bp_before = np.mean(np.abs(bp_before - mean_bp_before)) mad_bp_after = np.mean(np.abs(bp_after - mean_bp_after)) std_bp_before = np.std(bp_before) std_bp_after = np.std(bp_after) print("Mean Absolute Deviation (MAD) in Blood Pressure Before: ", mad_bp_before) print("Mean Absolute Deviation (MAD) in Blood Pressure After: ", mad_bp_after) print("Standard Deviation (SD) in Blood Pressure Before: ", std_bp_before) print("Standard Deviation (SD) in Blood Pressure After: ", std_bp_after) # d. Calculate the correlation coefficient and check the significance of it at 1% level of significance correlation_coefficient, p_value = stats.pearsonr(bp_before, bp_after) print("Correlation Coefficient: ", correlation_coefficient) print("p-value: ", p_value) if p_value < 0.01: print("The correlation is statistically significant at 1% level of significance.") else: print("The correlation is not statistically significant at 1% level of significance.") # ### Answer 4 # A group of 20 friends decide to play a game in which they each write a number between 1 and 20 on a slip of paper and put it into a hat. They then draw one slip of paper at random. What is the probability that the number on the slip of paper is a perfect square (i.e., 1, 4, 9, or 16)? # In[7]: total_friends = 20 # Total number of friends perfect_squares = [1, 4, 9, 16] # Perfect square numbers total_possible_outcomes = len(perfect_squares) # Number of perfect squares probability_perfect_square = total_possible_outcomes / total_friends print(f"The probability of drawing a perfect square number: {probability_perfect_square}") # ### Answer 5 # # A certain city has two taxi companies: Company A has 80% of the taxis and Company B has 20% of the taxis. Company A's taxis have a 95% success rate for picking up passengers on time, while Company B's taxis have a 90% success rate. If a randomly selected taxi is late, what is the probability that it belongs to Company A? # # In[4]: p_company_a = 0.8 # Probability of selecting a taxi from Company A p_company_b = 0.2 # Probability of selecting a taxi from Company B p_success_a = 0.95 # Probability of a taxi from Company A being on time p_success_b = 0.90 # Probability of a taxi from Company B being on time # Calculate the probability of a taxi being late from each company p_late_a = 1 - p_success_a p_late_b = 1 - p_success_b # Calculate the probability of a randomly selected taxi being late p_late = p_company_a * p_late_a + p_company_b * p_late_b # Calculate the probability that a late taxi belongs to Company A using Bayes' theorem p_company_a_given_late = (p_company_a * p_late_a) / p_late print(f"The probability that a randomly selected late taxi belongs to Company A: {p_company_a_given_late}") # ### Answer 6 # # A pharmaceutical company is developing a drug that is supposed to reduce blood pressure. They conduct a clinical trial with 100 patients and record their blood pressure before and after taking the drug. The company wants to know if the change in blood pressure follows a normal distribution. # https://drive.google.com/file/d/1mCjtYHiX--mMUjicuaP2gH3k-SnFxt8Y/view?usp=share_ # # In[40]: import pandas as pd import matplotlib.pyplot as plt from scipy import stats # Read the data from the provided Google Drive link data_url = "https://drive.google.com/uc?id=1mCjtYHiX--mMUjicuaP2gH3k-SnFxt8Y" data = pd.read_csv(data_url) # Extract the relevant columns bp_before = data[' Blood Pressure Before (mmHg)'] bp_after = data[' Blood Pressure After (mmHg)'] # Calculate the change in blood pressure change_in_bp = bp_after - bp_before # Plotting the histogram of the change in blood pressure plt.hist(change_in_bp, bins=10, edgecolor='black') plt.title("Histogram of Change in Blood Pressure") plt.xlabel("Change in Blood Pressure") plt.ylabel("Frequency") plt.show() # Perform normality test using Shapiro-Wilk test _, p_value = stats.shapiro(change_in_bp) if p_value > 0.05: print("The change in blood pressure follows a normal distribution.") else: print("The change in blood pressure does not follow a normal distribution.") # ### Answer 7 # The equations of two lines of regression, obtained in a correlation analysis between variables X and Y are as follows: and . 2𝑋 + 3 − 8 = 0 2𝑌 + 𝑋 − 5 = 0 The variance of 𝑋 = 4 Find the # a. Variance of Y # b. Coefficient of determination of C and Y # c. Standard error of estimate of X on Y and of Y on X. # # In[5]: import numpy as np variance_x = 4 # Variance of X # a. Variance of Y slope_x = 2 intercept_x = -3 variance_y = variance_x * slope_x ** 2 print(f"Variance of Y: {variance_y}") # b. Coefficient of determination of X and Y slope_y = -1/2 intercept_y = 5 r_squared_xy = (slope_y * variance_x) / variance_y print(f"Coefficient of determination of X and Y: {r_squared_xy}") # c. Standard error of estimate of X on Y and of Y on X std_error_estimate_xy = np.sqrt(1 - r_squared_xy) * np.sqrt(variance_y) std_error_estimate_yx = np.sqrt(1 - (variance_y / (slope_x ** 2 * variance_x))) print(f"Standard error of estimate of X on Y: {std_error_estimate_xy}") print(f"Standard error of estimate of Y on X: {std_error_estimate_yx}") # ### Answer 8 # The anxiety levels of 10 participants were measured before and after a new therapy. The scores are not normally distributed. Use the Wilcoxon signed-rank test to test whether the therapy had a significant effect on anxiety levels. The data is given below: Participant Before therapy After therapy Difference # In[6]: from scipy.stats import wilcoxon # Data before_therapy = [10,8, 12, 15, 6, 9, 11, 7, 14, 10] after_therapy = [7, 6, 10, 12, 5, 8, 9, 6, 12, 8] # Perform Wilcoxon signed-rank test statistic, p_value = wilcoxon(before_therapy, after_therapy) print(f"Wilcoxon signed-rank statistic: {statistic}") print(f"P-value: {p_value}") # ### Answer 9 # Given the score of students in multiple exams # Test the hypothesis that the mean scores of all the students are the same. If not, name the student with the highest score. # In[17]: import pandas as pd from scipy.stats import f_oneway # Create a dataframe with student scores data = { 'Student': ['Karan', 'Deepa', 'Karthik', 'Chandan', 'Jeevan'], 'Test1': [85, 70, 90, 75, 95], 'Test2': [90, 80, 85, 70, 92], 'Final': [92, 85, 88, 75, 96] } df = pd.DataFrame(data) # Perform ANOVA test test1_scores = df['Test1'] test2_scores = df['Test2'] final_scores = df['Final'] f_value, p_value = f_oneway(test1_scores, test2_scores, final_scores) # Print the ANOVA results print("ANOVA Results:") print("F-value:", f_value) print("p-value:", p_value) # Check if the null hypothesis is rejected if p_value < 0.05: print("The mean scores of the students are not the same.") # Find the student with the highest score highest_score_student = df.loc[df['Final'].idxmax(), 'Student'] print("The student with the highest score is:", highest_score_student) else: print("The mean scores of the students are the same.") # ### Answer 10 # Q-10. A factory produces light bulbs, and the probability of a bulb being defective is 0.05. The factory produces a large batch of 500 light bulbs. # a. What is the probability that exactly 20 bulbs are defective? # b. What is the probability that at least 10 bulbs are defective? # c. What is the probability that at max 15 bulbs are defective? # d. On average, how many defective bulbs would you expect in a batch of 500? # # In[8]: from scipy.stats import binom total_bulbs = 500 defective_probability = 0.05 # a. Probability of exactly 20 defective bulbs defective_count_a = 20 probability_a = binom.pmf(defective_count_a, total_bulbs, defective_probability) print(f"Probability of exactly 20 defective bulbs: {probability_a}") # b. Probability of at least 10 defective bulbs defective_count_b = 10 probability_b = 1 - binom.cdf(defective_count_b - 1, total_bulbs, defective_probability) print(f"Probability of at least 10 defective bulbs: {probability_b}") # c. Probability of at most 15 defective bulbs defective_count_c = 15 probability_c = binom.cdf(defective_count_c, total_bulbs, defective_probability) print(f"Probability of at most 15 defective bulbs: {probability_c}") # d. Expected number of defective bulbs expected_defective = total_bulbs * defective_probability print(f"Expected number of defective bulbs: {expected_defective}") # ### Answer 11 # Given the data of a feature contributing to different classes # # # https://drive.google.com/file/d/1mCjtYHiX--mMUjicuaP2gH3k-SnFxt8Y/view?usp # =share_ # # a. Check whether the distribution of all the classes are the same or not. # b. Check for the equality of variance/ # c. Which amount LDA and QDA would perform better on this data for classification and why. # d. Check the equality of mean for between all the classes. # In[76]: import pandas as pd import matplotlib.pyplot as plt from scipy import stats from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis from sklearn.model_selection import cross_val_score # Read the data from the provided link data_url = "https://drive.google.com/file/d/1mCjtYHiX--mMUjicuaP2gH3k-SnFxt8Y/view?usp=sharing" file_id = data_url.split("/")[5].split("?")[0] download_url = f"https://drive.google.com/uc?id={file_id}" data = pd.read_csv(download_url) # Display the column names and a sample of the data print("Column Names:") print(data.columns) print("\nSample Data:") print(data.head()) # Extract the class labels and corresponding feature values class_labels = data.columns[1:] feature_values = data.values[:, 1:] # Separate feature values for each class class_data = [feature_values[:, i] for i in range(len(class_labels))] # Perform Kruskal-Wallis test for equality of distributions _, p_value = stats.kruskal(*class_data) if p_value < 0.05: print("The distributions of the classes are not the same.") else: print("The distributions of the classes are the same.") # c. Which amount LDA and QDA would perform better on this data for classification and why. # d. Check the equality of mean for between all the classes. # Perform one-way ANOVA test to check the equality of mean between all the classes _, p_value_anova = stats.f_oneway(*feature_values.T) if p_value_anova < 0.05: print("The means are not equal between the classes.") else: print("The means are equal between the classes.") # ### Answer 12 # A pharmaceutical company develops a new drug and wants to compare its effectiveness against a standard drug for treating a particular condition. They conduct a study with two groups: Group A receives the new drug, and Group B receives the standard drug. The company measures the improvement in a specific symptom for both groups after a 4-week treatment period. # a. The company collects data from 30 patients in each group and calculates the mean improvement score and the standard deviation of improvement for each group. The mean improvement score for Group A is 2.5 with a standard deviation of 0.8, while the mean improvement score for Group B is 2.2 with a standard deviation of 0.6. Conduct a t-test to determine if there is a significant difference in the mean improvement scores between the two groups. Use a significance level of 0.05. # b. Based on the t-test results, state whether the null hypothesis should be rejected or not. Provide a conclusion in the context of the study. # # In[12]: from scipy.stats import ttest_ind # Group A data group_a_mean = 2.5 group_a_std = 0.8 group_a_size = 30 # Group B data group_b_mean = 2.2 group_b_std = 0.6 group_b_size = 30 # Perform t-test statistic, p_value = ttest_ind( [group_a_mean] * group_a_size, [group_b_mean] * group_b_size, equal_var=False # Assuming unequal variances ) alpha = 0.05 # Significance level if p_value < alpha: print("Reject the null hypothesis: There is a significant difference in mean improvement scores between Group A and Group B.") else: print("Fail to reject the null hypothesis: There is no significant difference in mean improvement scores between Group A and Group B.") # In[ ]:
/* * Copyright (C) 2023 CS416 Rutgers CS * Tiny File System * File: rufs.c * */ #define FUSE_USE_VERSION 26 #include <fuse.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <errno.h> #include <sys/time.h> #include <libgen.h> #include <limits.h> #include "block.h" #include "rufs.h" char diskfile_path[PATH_MAX]; // Used for benchmarks unsigned long long TOTAL_INODE_BLOCKS = 0, TOTAL_DATA_BLOCKS = 0; // Declare your in-memory data structures here static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static struct superblock *superblock; // Get available inode number from bitmap // Status: COMPLETE int get_avail_ino() { // Step 1: Read inode bitmap from disk // Step 2: Traverse inode bitmap to find an available slot // Step 3: Update inode bitmap and write to disk bitmap_t inode_bitmap = get_inode_bitmap(superblock); if (!inode_bitmap) return -1; size_t inode_bitmap_byte_size = (superblock->max_inum + 7) / 8; for (unsigned int i = 0; i < inode_bitmap_byte_size; i++) { if (inode_bitmap[i] == 255) continue; for (int j = 0; j < 8; j++) { if (get_bitmap(inode_bitmap, i * 8 + j) == FALSE) { set_bitmap(inode_bitmap, i * 8 + j); if (update_inode_bitmap(inode_bitmap, TRUE, superblock) != EXIT_SUCCESS) { free(inode_bitmap); return -1; } TOTAL_INODE_BLOCKS++; return i * 8 + j; } } } free(inode_bitmap); return -1; } // Get available data block number from bitmap // Status: COMPLETE int get_avail_blkno() { // Step 1: Read data block bitmap from disk // Step 2: Traverse data block bitmap to find an available slot // Step 3: Update data block bitmap and write to disk bitmap_t data_bitmap = get_data_bitmap(superblock); if (!data_bitmap) return -1; size_t data_bitmap_byte_size = (superblock->max_dnum + 7) / 8; for (unsigned int i = 0; i < data_bitmap_byte_size; i++) { if (data_bitmap[i] == 255) continue; for (int j = 0; j < 8; j++) { if (get_bitmap(data_bitmap, i * 8 + j) == 0) { set_bitmap(data_bitmap, i * 8 + j); if (update_data_bitmap(data_bitmap, TRUE, superblock) != EXIT_SUCCESS) { free(data_bitmap); return -1; } TOTAL_DATA_BLOCKS++; return i * 8 + j; } } } free(data_bitmap); return -1; } /* * inode operations */ // Status: COMPLETE int readi(uint16_t ino, struct inode *inode) { // Step 1: Get the inode's on-disk block number // Step 2: Get offset of the inode in the inode on-disk block // Step 3: Read the block from disk and then copy into inode structure if (ino >= superblock->max_inum) return -1; size_t inodes_byte_size = superblock->max_inum * sizeof(struct inode), inodes_block_size = (inodes_byte_size + BLOCK_SIZE - 1) / BLOCK_SIZE; void *base = malloc(inodes_block_size * BLOCK_SIZE); if (!base) return -1; if (bio_read_multi(superblock->i_start_blk, inodes_block_size, base) != EXIT_SUCCESS) { free(base); return -1; } memcpy((void *)inode, base + ino * sizeof(struct inode), sizeof(struct inode)); free(base); return EXIT_SUCCESS; } // Status: COMPLETE int writei(uint16_t ino, struct inode *inode) { // Step 1: Get the block number where this inode resides on disk // Step 2: Get the offset in the block where this inode resides on disk // Step 3: Write inode to disk if (ino >= superblock->max_inum) return -1; size_t inodes_byte_size = superblock->max_inum * sizeof(struct inode), inodes_block_size = (inodes_byte_size + BLOCK_SIZE - 1) / BLOCK_SIZE; void *base = malloc(inodes_block_size * BLOCK_SIZE); if (!base) return -1; if (bio_read_multi(superblock->i_start_blk, inodes_block_size, base) != EXIT_SUCCESS) { free(base); return -1; } memcpy(base + ino * sizeof(struct inode), (void *)inode, sizeof(struct inode)); if (bio_write_multi(superblock->i_start_blk, inodes_block_size, base) != EXIT_SUCCESS) { free(base); return -1; } free(base); return EXIT_SUCCESS; } // find the directory entry of file fname within directory, also reports which direct pointer was used and the offset into the block where it was found int dir_find_entry_and_location(struct inode inode_of_dir, const char *fname, size_t name_len, int *out_direct_pointer_index, int *out_block_dirent_index, struct dirent *out_dirent){ //debug("dir_find_entry_and_location(): ENTER\n"); //debug("dir_find_entry_and_location(): TARGET DIRENT IS \"%s\" LOCATED IN INO \"%d\"\n", fname, inode_of_dir); void *base = malloc(BLOCK_SIZE); if (!base) { return -1; } size_t inode_block_size = (inode_of_dir.size + BLOCK_SIZE - 1) / BLOCK_SIZE; if (inode_block_size > 16 || inode_of_dir.type != DIRECTORY || inode_of_dir.valid == FALSE) { free(base); return -1; } size_t block_dirent_size = BLOCK_SIZE / sizeof(struct dirent), size = inode_of_dir.size; for (unsigned int i = 0; i < inode_block_size; i++) { int block_num = inode_of_dir.direct_ptr[i]; if (bio_read_multi(block_num, 1, base) != EXIT_SUCCESS) { free(base); return -1; } for (unsigned int j = 0; j < block_dirent_size; j++) { if (size < sizeof(struct dirent)) { free(base); return -1; } struct dirent *current_dirent = (struct dirent *)(base + j * sizeof(struct dirent)); //debug("dir_find_entry_and_location(): CURRENT DIRENT IS \"%s\" WITH INO \"%d\"\n", current_dirent->name, current_dirent->ino); if (current_dirent->valid == TRUE && strcmp(current_dirent->name, fname) == 0) { //debug("dir_find_entry_and_location(): SUCCESSFULLY FOUND DIRENT \"%s\" WITH INO \"%d\"\n", current_dirent->name, current_dirent->ino); *out_direct_pointer_index = i; *out_block_dirent_index = j; memcpy(out_dirent, current_dirent, sizeof(struct dirent)); free(base); return EXIT_SUCCESS; } size = size >= sizeof(struct dirent) ? size - sizeof(struct dirent) : 0; } } free(base); //debug("dir_find_entry_and_location(): TARGET DIRENT \"%s\" NOT LOCATED IN INO \"%d\"\n", fname, inode_of_dir); //debug("dir_find_entry_and_location(): EXIT\n"); return -1; } /* * directory operations */ // Status: COMPLETE int dir_find(uint16_t ino, const char *fname, size_t name_len, struct dirent *dirent) { // Step 1: Call readi() to get the inode using ino (inode number of current directory) // Step 2: Get data block of current directory from inode // Step 3: Read directory's data block and check each directory entry. // If the name matches, then copy directory entry to dirent structure int direct_pointer_index; int block_dirent_index; struct inode inode_of_dir; if (readi(ino, &inode_of_dir) != EXIT_SUCCESS) { return -1; } return dir_find_entry_and_location(inode_of_dir, fname, name_len, &direct_pointer_index, &block_dirent_index, dirent); } // Status: COMPLETE int dir_add(struct inode dir_inode, uint16_t f_ino, const char *fname, size_t name_len) { // Step 1: Read dir_inode's data block and check each directory entry of dir_inode // Step 2: Check if fname (directory name) is already used in other entries // Step 3: Add directory entry in dir_inode's data block and write to disk // Allocate a new data block for this directory if it does not exist // Update directory inode // Write directory entry //debug("dir_add(): ENTER\n"); //debug("dir_add(): PARENT INO IS \"%d\"; CHILD IS \"%s\" WITH INO \"%d\"\n", dir_inode.ino, fname, f_ino); size_t inode_block_size = (dir_inode.size + BLOCK_SIZE - 1) / BLOCK_SIZE; if (inode_block_size > 16 || dir_inode.type != DIRECTORY || dir_inode.valid == FALSE) return -1; void *base = malloc(BLOCK_SIZE); if (!base) return -1; size_t block_dirent_size = BLOCK_SIZE / sizeof(struct dirent), size = dir_inode.size; int block_num_target = -1, dirent_index = -1; for (unsigned int i = 0; i < inode_block_size; i++) { int block_num = dir_inode.direct_ptr[i]; if (bio_read_multi(block_num, 1, base) != EXIT_SUCCESS) { free(base); return -1; } for (unsigned int j = 0; j < block_dirent_size; j++) { if (size < sizeof(struct dirent)) goto end; struct dirent *current_dirent = (struct dirent *)(base + j * sizeof(struct dirent)); if (current_dirent->valid == TRUE && strcmp(current_dirent->name, fname) == 0) { free(base); return -1; } if (current_dirent->valid == FALSE && block_num_target == -1) { block_num_target = i; dirent_index = j; } //debug("dir_add(): EXAMINING DIRENT \"%d\" -- valid = \"%d\", name = \"%s\"\n", j, current_dirent->valid, current_dirent->name); size = size >= sizeof(struct dirent) ? size - sizeof(struct dirent) : 0; } } end: bitmap_t data_bitmap = NULL; if (block_num_target == -1) { if (inode_block_size >= 16) { free(base); return -1; } data_bitmap = get_data_bitmap(superblock); if (!data_bitmap) { free(base); return -1; } int new_block_num = get_avail_blkno_no_wr(data_bitmap, superblock); if (new_block_num == -1) { free(base); free(data_bitmap); return -1; } memset(base, 0, BLOCK_SIZE); dir_inode.size += BLOCK_SIZE; dir_inode.direct_ptr[inode_block_size] = new_block_num; block_num_target = inode_block_size; dirent_index = 0; } else if (inode_block_size < block_dirent_size && bio_read_multi(dir_inode.direct_ptr[block_num_target], 1, base) != EXIT_SUCCESS) { free(base); return -1; } dir_inode.link++; if (writei(dir_inode.ino, &dir_inode) != EXIT_SUCCESS) { free(base); if (data_bitmap) free(data_bitmap); return -1; } struct dirent *dirent = (struct dirent *)(base + dirent_index * sizeof(struct dirent)); dirent->ino = f_ino; dirent->valid = TRUE; memset(dirent->name, 0, 208); memcpy(dirent->name, fname, name_len + 1); // name_len does not account for null terminator dirent->len = name_len; if (bio_write_multi(dir_inode.direct_ptr[block_num_target], 1, base) != EXIT_SUCCESS) { dir_inode.link--; if (data_bitmap) { dir_inode.size -= BLOCK_SIZE; dir_inode.direct_ptr[block_num_target] = 0; free(data_bitmap); } writei(dir_inode.ino, &dir_inode); free(base); return -1; } if (data_bitmap && update_data_bitmap(data_bitmap, TRUE, superblock) != EXIT_SUCCESS) { dir_inode.link--; dir_inode.size -= BLOCK_SIZE; dir_inode.direct_ptr[block_num_target] = 0; writei(dir_inode.ino, &dir_inode); free(data_bitmap); return -1; } free(base); //debug("dir_add(): TARGET BLOCK IS \"%d\"\n", dir_inode.direct_ptr[block_num_target]); //debug("dir_add(): EXIT\n"); return EXIT_SUCCESS; } //clears data block and marks it available in data block bitmap void remove_data_block(int data_block_number){ // should perhaps add sanity checks (number is in range of 0 to superblock->max_dnum) //clear data block struct dirent *block_of_zeroes = malloc(BLOCK_SIZE); memset(block_of_zeroes, 0, BLOCK_SIZE); bio_write_multi(data_block_number, 1, block_of_zeroes); //free(block_of_zeroes); //make data block available in data bitmap bitmap_t data_bitmap = get_data_bitmap(superblock); unset_bitmap(data_bitmap, data_block_number); update_data_bitmap(data_bitmap, TRUE, superblock); free(block_of_zeroes); } // Helper function //clears an inode (setting mem to all 0 will make it invalid) and removes it from inode bitmap void remove_inode(int inode_number){ //clear data in inode struct inode zero; memset(&zero, 0, sizeof(struct inode)); writei(inode_number, &zero); //mark cleared inode as available in inode bitmap bitmap_t inode_bitmap = get_inode_bitmap(superblock); unset_bitmap(inode_bitmap, inode_number); update_inode_bitmap(inode_bitmap, TRUE, superblock); } // Helper function //removes the specified file, note it is not actually removed unless its link count drops to 0 void remove_this_file(struct inode inode_of_file_to_remove){ // pretty sure this being called for a directory is why the directory inode is why there is a leak, but its link count will always be > 1 (min 2) // commented out for now. /*if(inode_of_file_to_remove.link > 1){ inode_of_file_to_remove.link--; writei(inode_of_file_to_remove.ino, &inode_of_file_to_remove); return; }*/ //clear any allocated blocks pointed to directly for(int direct_pointer_index = 0; direct_pointer_index < 16; direct_pointer_index ++){ if(inode_of_file_to_remove.direct_ptr[direct_pointer_index] != 0){ remove_data_block(inode_of_file_to_remove.direct_ptr[direct_pointer_index]); } } int *data_block_number_array = malloc(BLOCK_SIZE); //clear any blocks used by indirect pointers for(int indirect_pointer_index = 0; indirect_pointer_index < 8; indirect_pointer_index ++){ //0 means it doesn't point to a block // all dirents should reach this continue statement, just something to note. if(inode_of_file_to_remove.indirect_ptr[indirect_pointer_index] == 0){ continue; } bio_read_multi(inode_of_file_to_remove.indirect_ptr[indirect_pointer_index], 1, data_block_number_array); //free the blocks pointed to by dirents in indirect block for(int indirect_block_index = 0; indirect_block_index < BLOCK_SIZE / sizeof(int); indirect_block_index ++){ if(data_block_number_array[indirect_block_index] != 0){ remove_data_block(data_block_number_array[indirect_block_index]); } } //remove the indirect blocks themselves remove_data_block(inode_of_file_to_remove.indirect_ptr[indirect_pointer_index]); } free(data_block_number_array); remove_inode(inode_of_file_to_remove.ino); } // Helper function //clears an entry that was occupied in a directory by a now removed file int remove_entry_from_directory(struct inode dir_inode, int direct_pointer_index, int block_dirent_index){ struct dirent *block_of_mem = malloc(BLOCK_SIZE); int err_code = bio_read_multi(dir_inode.direct_ptr[direct_pointer_index], 1, block_of_mem); if(err_code == EXIT_SUCCESS){ memset(block_of_mem + block_dirent_index, 0, sizeof(struct dirent)); err_code = bio_write_multi(dir_inode.direct_ptr[direct_pointer_index], 1, block_of_mem); } free(block_of_mem); return err_code; } //removes the specified directory and recursively removes anything inside of it, directories can only be hard linked once so links are not counted void remove_this_dir(struct inode inode_of_dir_to_remove){ struct dirent *block_of_mem = malloc(BLOCK_SIZE); //this loop deletes files and directories inside of this directory for(int direct_pointer_index = 0; direct_pointer_index < 16; direct_pointer_index ++){ //points to 0th block means it is not a used pointer if(inode_of_dir_to_remove.direct_ptr[direct_pointer_index] == 0){ continue; } bio_read_multi(inode_of_dir_to_remove.direct_ptr[direct_pointer_index], 1, block_of_mem); for(int directory_entry_index = 0; directory_entry_index < BLOCK_SIZE / sizeof(struct dirent); directory_entry_index ++){ struct dirent curr_dir_entry = block_of_mem[directory_entry_index]; if(curr_dir_entry.valid == FALSE || strcmp(curr_dir_entry.name, ".") == 0 || strcmp(curr_dir_entry.name, "..") == 0){ continue; } struct inode inode_of_file_to_remove; readi(curr_dir_entry.ino, &inode_of_file_to_remove); //if there is a directory within the directory we want to delete, recurse to delete it first if(inode_of_file_to_remove.type == DIRECTORY){ remove_this_dir(inode_of_file_to_remove); } else{ remove_this_file(inode_of_file_to_remove); } remove_entry_from_directory(inode_of_dir_to_remove, direct_pointer_index, directory_entry_index); } } free(block_of_mem); //gets called to remove its actual data blocks and inode remove_this_file(inode_of_dir_to_remove); } //removes either directory or file from in the parent directory corresponding to dir_inode //if file_type_to_remove is -1, it will just remove it based on the file type it is // if file_type_to_remove is specified, we will return an error if the given file does not match the type expected int remove_from_dir(struct inode dir_inode, const char *fname, size_t name_len, int file_type_to_remove){ int direct_pointer_index; int block_durent_index; struct dirent found_dir_entry; if(dir_find_entry_and_location(dir_inode, fname, name_len, &direct_pointer_index, &block_durent_index, &found_dir_entry) == -1){ return EXIT_FAILURE; } struct inode inode_of_file_to_remove; readi(found_dir_entry.ino, &inode_of_file_to_remove); if(file_type_to_remove != -1){ if(file_type_to_remove == DIRECTORY && inode_of_file_to_remove.type != DIRECTORY){ return -ENOTDIR; } else if(file_type_to_remove != DIRECTORY && inode_of_file_to_remove.type == DIRECTORY){ return -EISDIR; } } if(inode_of_file_to_remove.type == DIRECTORY){ remove_this_dir(inode_of_file_to_remove); } else if(inode_of_file_to_remove.type == FILE){ remove_this_file(inode_of_file_to_remove); } else{ return -1; } remove_entry_from_directory(dir_inode, direct_pointer_index, block_durent_index); return EXIT_SUCCESS; } //almost unecessary at this point but left in due to project's requests int dir_remove(struct inode dir_inode, const char *fname, size_t name_len) { // Step 1: Read dir_inode's data block and checks each directory entry of dir_inode // Step 2: Check if fname exist // Step 3: If exist, then remove it from dir_inode's data block and write to disk return remove_from_dir(dir_inode, fname, name_len, DIRECTORY); } /* * namei operation */ // Status: COMPLETE int get_node_by_path(const char *path, uint16_t ino, struct inode *inode) { // Step 1: Resolve the path name, walk through path, and finally, find its inode. // Note: You could either implement it in a iterative way or recursive way //debug("get_node_by_path(): ENTER\n"); //debug("get_node_by_path(): STARTING PATH IS \"%s\"\n", path); if (!path || path[0] != '/') return -1; struct dirent *current_dirent = malloc(sizeof(struct dirent)); if (!current_dirent) return -1; int current_ino = ino; int start_ind = 1; int end_ind = split_string(start_ind, path); memset(current_dirent, 0, sizeof(struct dirent)); while (end_ind != -1) { char *target_directory = malloc(end_ind - start_ind + 1); if (!target_directory) { free(current_dirent); return -1; } memcpy(target_directory, path + start_ind, end_ind - start_ind + 1); if (path[end_ind] == '/') target_directory[end_ind - start_ind] = '\0'; //debug("get_node_by_path(): taking a look at \"%s\"\n", target_directory); if (dir_find(current_ino, target_directory, end_ind - start_ind + 1, current_dirent) == -1) { free(current_dirent); free(target_directory); return -1; } current_ino = current_dirent->ino; start_ind = end_ind + 1; free(target_directory); if (start_ind >= strlen(path) + 1) break; end_ind = split_string(start_ind, path); } if (readi(current_ino, inode) != EXIT_SUCCESS) { free(current_dirent); return -1; } free(current_dirent); //debug("get_node_by_path(): FINAL INO IS \"%d\"\n", current_ino); //debug("get_node_by_path(): EXIT\n"); return EXIT_SUCCESS; } /* * Make file system */ // Status: COMPLETE int rufs_mkfs() { // Call dev_init() to initialize (Create) Diskfile // write superblock information // initialize inode bitmap // initialize data block bitmap // update bitmap information for root directory // update inode for root directory /* Hierarchy of blocks: * 1) Superblock * 2) Inode bitmap * 3) Data bitmap * 4) Inodes * 5) Data */ //debug("rufs_mkfs(): ENTER\n"); dev_init(diskfile_path); // Superblock initialization size_t superblock_block_size = (sizeof(struct superblock) + BLOCK_SIZE - 1) / BLOCK_SIZE; struct superblock *superblock = malloc(superblock_block_size * BLOCK_SIZE); memset(superblock, 0, superblock_block_size * BLOCK_SIZE); superblock->magic_num = MAGIC_NUM; superblock->max_inum = MAX_INUM; superblock->max_dnum = MAX_DNUM; unsigned int block_num = superblock_block_size; // Inode bitmap initialization superblock->i_bitmap_blk = block_num; size_t inode_bitmap_byte_size = (MAX_INUM + 7) / 8, inode_bitmap_block_size = (inode_bitmap_byte_size + BLOCK_SIZE - 1) / BLOCK_SIZE; bitmap_t inode_bitmap = malloc(inode_bitmap_block_size * BLOCK_SIZE); memset(inode_bitmap, 0, inode_bitmap_block_size * BLOCK_SIZE); block_num += inode_bitmap_block_size; // Data bitmap initialization superblock->d_bitmap_blk = block_num; size_t data_bitmap_byte_size = (MAX_DNUM + 7) / 8, data_bitmap_block_size = (data_bitmap_byte_size + BLOCK_SIZE - 1) / BLOCK_SIZE; bitmap_t data_bitmap = malloc(data_bitmap_block_size * BLOCK_SIZE); memset(data_bitmap, 0, data_bitmap_block_size * BLOCK_SIZE); block_num += data_bitmap_block_size; // Inodes initialization superblock->i_start_blk = block_num; size_t inodes_byte_size = MAX_INUM * sizeof(struct inode), inodes_block_size = (inodes_byte_size + BLOCK_SIZE - 1) / BLOCK_SIZE; unsigned char *inodes = malloc(inodes_block_size * BLOCK_SIZE); memset(inodes, 0, inodes_block_size * BLOCK_SIZE); block_num += inodes_block_size; // Data initialization superblock->d_start_blk = block_num; // Update data bitmap for (unsigned int current_block_num = 0; current_block_num < block_num; current_block_num++) set_bitmap(data_bitmap, current_block_num); // Initialize root directory struct inode *rootdir_inode = (struct inode *)inodes; set_bitmap(inode_bitmap, 0); rootdir_inode->ino = 0; rootdir_inode->link = 0; rootdir_inode->size = 0/*BLOCK_SIZE*/; rootdir_inode->type = DIRECTORY; rootdir_inode->valid = TRUE; rootdir_inode->vstat.st_atime = rootdir_inode->vstat.st_mtime = time(NULL); // Write data to disk if (bio_write_multi(0, superblock_block_size, superblock) != EXIT_SUCCESS) return EXIT_FAILURE; if (bio_write_multi(superblock->i_bitmap_blk, inode_bitmap_block_size, inode_bitmap) != EXIT_SUCCESS) return EXIT_FAILURE; if (bio_write_multi(superblock->d_bitmap_blk, data_bitmap_block_size, data_bitmap) != EXIT_SUCCESS) return EXIT_FAILURE; if (bio_write_multi(superblock->i_start_blk, inodes_block_size, inodes) != EXIT_SUCCESS) return EXIT_FAILURE; free(superblock); free(inode_bitmap); free(data_bitmap); free(inodes); //debug("rufs_mkfs(): EXIT\n"); return EXIT_SUCCESS; } /* * FUSE file operations */ // Status: COMPLETE static void *rufs_init(struct fuse_conn_info *conn) { // Step 1a: If disk file is not found, call mkfs // Step 1b: If disk file is found, just initialize in-memory data structures // and read superblock from disk //debug("rufs_init(): ENTER\n"); boolean init = FALSE; pthread_mutex_lock(&mutex); if (access(diskfile_path, F_OK) != 0) { if (rufs_mkfs() != EXIT_SUCCESS) { dev_close(); pthread_mutex_unlock(&mutex); return NULL; } init = TRUE; } else if (dev_open(diskfile_path) == -1) { pthread_mutex_unlock(&mutex); return NULL; } if (!(superblock = get_superblock())) { dev_close(diskfile_path); pthread_mutex_unlock(&mutex); return NULL; } if (init == TRUE) { struct inode *rootdir_inode = malloc(sizeof(struct inode)); memset(rootdir_inode, 0, sizeof(struct inode)); readi(ROOT_INO, rootdir_inode); dir_add(*rootdir_inode, 0, ".", 1); dir_add(*rootdir_inode, 0, "..", 2); writei(ROOT_INO, rootdir_inode); free(rootdir_inode); } pthread_mutex_unlock(&mutex); //debug("rufs_init(): EXIT\n"); return NULL; } // Status: COMPLETE static void rufs_destroy(void *userdata) { // Step 1: De-allocate in-memory data structures // Step 2: Close diskfile if (BENCHMARK) printf("TOTAL INODE BLOCKS ALLOCATED: %llu\nTOTAL DATA BLOCKS ALLOCATED: %llu\n", TOTAL_INODE_BLOCKS, TOTAL_DATA_BLOCKS); //debug("rufs_destroy(): ENTER\n"); pthread_mutex_lock(&mutex); free(superblock); dev_close(diskfile_path); pthread_mutex_unlock(&mutex); //debug("rufs_destroy(): EXIT\n"); } // Status: COMPLETE static int rufs_getattr(const char *path, struct stat *stbuf) { // Step 1: call get_node_by_path() to get inode from path // Step 2: fill attribute of file into stbuf from inode //debug("rufs_getattr(): ENTER\n"); struct inode *inode = malloc(sizeof(struct inode)); if (!inode) return -ENOMEM; pthread_mutex_lock(&mutex); if (get_node_by_path(path, ROOT_INO, inode) != EXIT_SUCCESS) { pthread_mutex_unlock(&mutex); free(inode); return -ENOENT; } memset(stbuf, 0, sizeof(struct stat)); stbuf->st_mode = inode->type == DIRECTORY ? DIRECTORY_MODE : FILE_MODE; stbuf->st_nlink = inode->link; stbuf->st_uid = getuid(); stbuf->st_gid = getgid(); stbuf->st_size = inode->size; stbuf->st_blocks = (inode->size + BLOCK_SIZE - 1) / BLOCK_SIZE; stbuf->st_atime = inode->vstat.st_atime = time(NULL); stbuf->st_mtime = inode->vstat.st_mtime; writei(inode->ino, inode); pthread_mutex_unlock(&mutex); free(inode); //debug("rufs_getattr(): EXIT\n"); return 0; } // Status: COMPLETE static int rufs_opendir(const char *path, struct fuse_file_info *fi) { // Step 1: Call get_node_by_path() to get inode from path // Step 2: If not find, return -1 //debug("rufs_opendir(): ENTER\n"); struct inode *inode = malloc(sizeof(struct inode)); if (!inode) return -ENOMEM; pthread_mutex_lock(&mutex); if (get_node_by_path(path, ROOT_INO, inode) != EXIT_SUCCESS) { pthread_mutex_unlock(&mutex); free(inode); return -1; } if (inode->type != DIRECTORY) { pthread_mutex_unlock(&mutex); free(inode); return -ENOTDIR; } pthread_mutex_unlock(&mutex); free(inode); //debug("rufs_opendir(): EXIT\n"); return 0; } // Status: COMPLETE static int rufs_readdir(const char *path, void *buffer, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { // Step 1: Call get_node_by_path() to get inode from path // Step 2: Read directory entries from its data blocks, and copy them to filler //debug("rufs_readdir(): ENTER\n"); struct inode *inode = malloc(sizeof(struct inode)); if (!inode) return -ENOMEM; void *base = malloc(BLOCK_SIZE); if (!base) { free(inode); return -ENOMEM; } pthread_mutex_lock(&mutex); if (get_node_by_path(path, ROOT_INO, inode) != EXIT_SUCCESS) { pthread_mutex_unlock(&mutex); free(inode); free(base); return -ENOENT; } if (inode->type != DIRECTORY) { pthread_mutex_unlock(&mutex); free(inode); free(base); return -ENOTDIR; } size_t inode_block_size = (inode->size + BLOCK_SIZE - 1) / BLOCK_SIZE, block_dirent_size = BLOCK_SIZE / sizeof(struct dirent), size = inode->size; for (unsigned int i = 0; i < inode_block_size; i++) { int block_num = inode->direct_ptr[i]; if (bio_read_multi(block_num, 1, base) != EXIT_SUCCESS) { pthread_mutex_unlock(&mutex); free(inode); free(base); return -EIO; } for (unsigned int j = 0; j < block_dirent_size; j++) { if (size < sizeof(struct dirent)) goto end; struct dirent *current_dirent = (struct dirent *)(base + j * sizeof(struct dirent)); if (current_dirent->valid == TRUE && strcmp(current_dirent->name, ".") != 0 && strcmp(current_dirent->name, "..") != 0) { filler(buffer, current_dirent->name, NULL, 0); //debug("rufs_readdir(): CURRENT DIRENT IS \"%s\" WITH INO \"%d\"\n", current_dirent->name, current_dirent->ino); } size = size >= sizeof(struct dirent) ? size - sizeof(struct dirent) : 0; } } end: time(&inode->vstat.st_atime); writei(inode->ino, inode); pthread_mutex_unlock(&mutex); free(inode); free(base); //debug("rufs_readdir(): EXIT\n"); return 0; } // Status: COMPLETE static int rufs_mkdir(const char *path, mode_t mode) { // Step 1: Use dirname() and basename() to separate parent directory path and target directory name // Step 2: Call get_node_by_path() to get inode of parent directory // Step 3: Call get_avail_ino() to get an available inode number // Step 4: Call dir_add() to add directory entry of target directory to parent directory // Step 5: Update inode for target directory // Step 6: Call writei() to write inode to disk //debug("rufs_mkdir(): ENTER\n"); //debug("rufs_mkdir(): TARGET PATH IS \"%s\"\n", path); char *path_dir = strdup(path); if (!path_dir) return -ENOMEM; char *path_base = strdup(path); if (!path_base) { free(path_dir); return -ENOMEM; } struct inode *dir_inode = malloc(sizeof(struct inode)); if (!dir_inode) { free(path_dir); free(path_base); return -ENOMEM; } struct inode *base_inode = malloc(sizeof(struct inode)); if (!base_inode) { free(path_dir); free(path_base); free(dir_inode); return -ENOMEM; } char *dir_path = dirname(path_dir); char *base = basename(path_base); pthread_mutex_lock(&mutex); if (get_node_by_path(dir_path, ROOT_INO, dir_inode) != EXIT_SUCCESS) { pthread_mutex_unlock(&mutex); free(path_dir); free(path_base); free(dir_inode); free(base_inode); return -ENOENT; } int base_ino; if ((base_ino = get_avail_ino()) == -1) { pthread_mutex_unlock(&mutex); free(path_dir); free(path_base); free(dir_inode); free(base_inode); return -ENOSPC; } if (dir_add(*dir_inode, base_ino, base, strlen(base)) == -1) { bitmap_t inode_bitmap = get_inode_bitmap(superblock); unset_bitmap(inode_bitmap, base_ino); update_inode_bitmap(inode_bitmap, TRUE, superblock); pthread_mutex_unlock(&mutex); free(path_dir); free(path_base); free(dir_inode); free(base_inode); return -ENOSPC; } memset(base_inode, 0, sizeof(struct inode)); base_inode->ino = base_ino; base_inode->link = 0; base_inode->size = 0; base_inode->type = DIRECTORY; base_inode->valid = TRUE; base_inode->vstat.st_atime = base_inode->vstat.st_mtime = time(NULL); writei(base_ino, base_inode); dir_add(*base_inode, base_ino, ".", 1); dir_add(*base_inode, dir_inode->ino, "..", 2); pthread_mutex_unlock(&mutex); free(path_dir); free(path_base); free(dir_inode); free(base_inode); //debug("rufs_mkdir(): EXIT\n"); return 0; } //splits a path into the base path and the final destination ex: /bar/foo/baz -> base: /bar/foo, name -> baz /*void split_path_into_base_path_and_name(const char *path, char **base_path_out, char **name_out){ int ind_of_last_slash; for(int curr_slash_ind = 0; curr_slash_ind != -1; curr_slash_ind = split_string(ind_of_last_slash, path)){ ind_of_last_slash = curr_slash_ind; } int base_path_length_without_nullterm = ind_of_last_slash; *base_path_out = malloc(sizeof(char) * (base_path_length_without_nullterm + 1)); strncpy(*base_path_out, path, base_path_length_without_nullterm); (*base_path_out)[base_path_length_without_nullterm] = '\0'; int dir_name_length_without_nullterm = strlen(path) - ind_of_last_slash; *name_out = malloc(sizeof(char) * (dir_name_length_without_nullterm + 1)); strncpy(*name_out, path + base_path_length_without_nullterm, dir_name_length_without_nullterm); (*name_out)[dir_name_length_without_nullterm] = '\0'; }*/ //removes file or directory, specified by file_to_remove_type static int remove_given_path(const char *path, int file_to_remove_type){ char *dir_copy = strdup(path); if (!dir_copy) return EXIT_FAILURE; // not sure if correct success flag, correct as needed char *base_copy = strdup(path); if (!base_copy) { free(dir_copy); return -1; // same concern as above } char *dir_name = dirname(dir_copy); char *base_name = basename(base_copy); //split_path_into_base_path_and_name(path, &base_path, &remove_target_name); struct inode base_dir_inode; get_node_by_path(dir_name, ROOT_INO, &base_dir_inode); int status = remove_from_dir(base_dir_inode, base_name, strlen(base_name), file_to_remove_type); free(dir_copy); free(base_copy); return status; } static int rufs_rmdir(const char *path) { // Step 1: Use dirname() and basename() to separate parent directory path and target directory name // Step 2: Call get_node_by_path() to get inode of target directory // Step 3: Clear data block bitmap of target directory // Step 4: Clear inode bitmap and its data block // Step 5: Call get_node_by_path() to get inode of parent directory // Step 6: Call dir_remove() to remove directory entry of target directory in its parent directory pthread_mutex_lock(&mutex); int ret = remove_given_path(path, DIRECTORY); pthread_mutex_unlock(&mutex); return ret; } static int rufs_releasedir(const char *path, struct fuse_file_info *fi) { // For this project, you don't need to fill this function // But DO NOT DELETE IT! return 0; } // Status: COMPLETE static int rufs_create(const char *path, mode_t mode, struct fuse_file_info *fi) { // Step 1: Use dirname() and basename() to separate parent directory path and target file name // Step 2: Call get_node_by_path() to get inode of parent directory // Step 3: Call get_avail_ino() to get an available inode number // Step 4: Call dir_add() to add directory entry of target file to parent directory // Step 5: Update inode for target file // Step 6: Call writei() to write inode to disk //debug("rufs_create(): ENTER\n"); //debug("rufs_create(): TARGET PATH IS \"%s\"\n", path); char *path_dir = strdup(path); if (!path_dir) return -ENOMEM; char *path_base = strdup(path); if (!path_base) { free(path_dir); return -ENOMEM; } struct inode *dir_inode = malloc(sizeof(struct inode)); if (!dir_inode) { free(path_dir); free(path_base); return -ENOMEM; } struct inode *base_inode = malloc(sizeof(struct inode)); if (!base_inode) { free(path_dir); free(path_base); free(dir_inode); return -ENOMEM; } char *dir_path = dirname(path_dir); char *base = basename(path_base); pthread_mutex_lock(&mutex); if (get_node_by_path(dir_path, ROOT_INO, dir_inode) != EXIT_SUCCESS) { pthread_mutex_unlock(&mutex); free(path_dir); free(path_base); free(dir_inode); free(base_inode); return -ENOENT; } int base_ino; if ((base_ino = get_avail_ino()) == -1) { pthread_mutex_unlock(&mutex); free(path_dir); free(path_base); free(dir_inode); free(base_inode); return -ENOSPC; } if (dir_add(*dir_inode, base_ino, base, strlen(base)) == -1) { bitmap_t inode_bitmap = get_inode_bitmap(superblock); unset_bitmap(inode_bitmap, base_ino); update_inode_bitmap(inode_bitmap, TRUE, superblock); pthread_mutex_unlock(&mutex); free(path_dir); free(path_base); free(dir_inode); free(base_inode); return -ENOSPC; } memset(base_inode, 0, sizeof(struct inode)); base_inode->link = 1; base_inode->ino = base_ino; base_inode->size = 0; base_inode->type = FILE; base_inode->valid = TRUE; base_inode->vstat.st_mtime = base_inode->vstat.st_atime = time(NULL); writei(base_ino, base_inode); pthread_mutex_unlock(&mutex); free(path_dir); free(path_base); free(dir_inode); free(base_inode); //debug("rufs_create(): EXIT\n"); return 0; } // Status: COMPLETE static int rufs_open(const char *path, struct fuse_file_info *fi) { // Step 1: Call get_node_by_path() to get inode from path // Step 2: If not find, return -1 //debug("rufs_open(): ENTER\n"); struct inode *inode = malloc(sizeof(struct inode)); if (!inode) return -1; pthread_mutex_lock(&mutex); if (get_node_by_path(path, ROOT_INO, inode) != EXIT_SUCCESS || inode->type != FILE) { pthread_mutex_unlock(&mutex); free(inode); return -1; } pthread_mutex_unlock(&mutex); free(inode); //debug("rufs_open(): EXIT\n"); return 0; } // Status: COMPLETE static int rufs_read(const char *path, char *buffer, size_t size, off_t offset, struct fuse_file_info *fi) { // Step 1: You could call get_node_by_path() to get inode from path // Step 2: Based on size and offset, read its data blocks from disk // Step 3: copy the correct amount of data from offset to buffer // Note: this function should return the amount of bytes you copied to buffer //debug("rufs_read(): ENTER\n"); if (size == 0) return 0; struct inode *inode = malloc(sizeof(struct inode)); if (!inode) return 0; char *block_buffer = malloc(BLOCK_SIZE); if (!block_buffer) { free(inode); return 0; } pthread_mutex_lock(&mutex); if (get_node_by_path(path, ROOT_INO, inode) != EXIT_SUCCESS || inode->type != FILE) { pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); return 0; } memset(block_buffer, 0, BLOCK_SIZE); int starting_block_index = offset / BLOCK_SIZE; int ending_block_index = min(16 + 8 * (BLOCK_SIZE / sizeof(int)), (offset + size - 1) / BLOCK_SIZE); if (ending_block_index - starting_block_index < 0) { pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); return 0; } int bytes_left = size, bytes_read = 0, block_offset = offset % BLOCK_SIZE; for (int i = starting_block_index; i <= ending_block_index; i++) { int bytes_to_read = min(bytes_left, BLOCK_SIZE - block_offset); bytes_left = max(0, bytes_left - bytes_to_read); if (i < 16) { if (inode->direct_ptr[i] != 0) { bio_read_multi(inode->direct_ptr[i], 1, block_buffer); memcpy(buffer + bytes_read, block_buffer + block_offset, bytes_to_read); bytes_read += bytes_to_read; } } else { int new_i = i - 16; int val_index = new_i % (BLOCK_SIZE / sizeof(int)); int ptr_index = new_i / (BLOCK_SIZE / sizeof(int)); if (inode->indirect_ptr[ptr_index] != 0) { bio_read_multi(inode->indirect_ptr[ptr_index], 1, block_buffer); int blkno = ((int *)block_buffer)[val_index]; if (blkno != 0) { bio_read_multi(blkno, 1, block_buffer); memcpy(buffer + bytes_read, block_buffer + block_offset, bytes_to_read); bytes_read += bytes_to_read; } } } block_offset = 0; } pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); //debug("rufs_read(): EXIT\n"); return bytes_read; } // Status: COMPLETE static int rufs_write(const char *path, const char *buffer, size_t size, off_t offset, struct fuse_file_info *fi) { // Step 1: You could call get_node_by_path() to get inode from path // Step 2: Based on size and offset, read its data blocks from disk // Step 3: Write the correct amount of data from offset to disk // Step 4: Update the inode info and write it to disk // Note: this function should return the amount of bytes you write to disk //debug("rufs_write(): ENTER\n"); //debug("rufs_write(): WRITING \"%lu\" BYTES WITH AN OFFSET OF \"%ld\"\n", size, offset); if (size == 0) return 0; struct inode *inode = malloc(sizeof(struct inode)); if (!inode) return 0; char *block_buffer = malloc(BLOCK_SIZE); if (!block_buffer) { free(inode); return -ENOMEM; } char *alloc_buffer = malloc(BLOCK_SIZE); if (!alloc_buffer) { free(inode); free(block_buffer); return -ENOMEM; } pthread_mutex_lock(&mutex); bitmap_t data_bitmap = get_data_bitmap(superblock); if (!data_bitmap) { pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); free(alloc_buffer); return -ENOMEM; } if (get_node_by_path(path, ROOT_INO, inode) != EXIT_SUCCESS || inode->type != FILE) { pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); free(data_bitmap); free(alloc_buffer); return -ENOENT; } memset(block_buffer, 0, BLOCK_SIZE); int starting_block_index = offset / BLOCK_SIZE; int ending_block_index = min(15 + 8 * (BLOCK_SIZE / sizeof(int)), (offset + size - 1) / BLOCK_SIZE); if (ending_block_index - starting_block_index < 0) { pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); free(data_bitmap); free(alloc_buffer); return -ENOSPC; } boolean should_save = FALSE; int size_increase = 0; for (int i = starting_block_index; i <= ending_block_index; i++) { int blkno; if (i < 16) { if (inode->direct_ptr[i] == 0) { blkno = get_avail_blkno_no_wr(data_bitmap, superblock); if (blkno == -1) { pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); free(data_bitmap); free(alloc_buffer); return -ENOSPC; } size_increase += BLOCK_SIZE; should_save = TRUE; inode->direct_ptr[i] = blkno; bio_write_multi(blkno, 1, block_buffer); } } else { int new_i = i - 16; int val_index = new_i % (BLOCK_SIZE / sizeof(int)); int ptr_index = new_i / (BLOCK_SIZE / sizeof(int)); if (inode->indirect_ptr[ptr_index] == 0) { blkno = get_avail_blkno_no_wr(data_bitmap, superblock); if (blkno == -1) { pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); free(data_bitmap); free(alloc_buffer); return -ENOSPC; } //size_increase += BLOCK_SIZE; // should realistically not contribute. should_save = TRUE; inode->indirect_ptr[ptr_index] = blkno; bio_write_multi(blkno, 1, block_buffer); } bio_read_multi(inode->indirect_ptr[ptr_index], 1, alloc_buffer); int *list = (int *)alloc_buffer; if (list[val_index] == 0) { blkno = get_avail_blkno_no_wr(data_bitmap, superblock); if (blkno == -1) { pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); free(data_bitmap); free(alloc_buffer); return -ENOSPC; } size_increase += BLOCK_SIZE; should_save = TRUE; list[val_index] = blkno; bio_write_multi(blkno, 1, block_buffer); bio_write_multi(inode->indirect_ptr[ptr_index], 1, alloc_buffer); } } } free(alloc_buffer); if (should_save == TRUE) { inode->size += size_increase; writei(inode->ino, inode); update_data_bitmap(data_bitmap, TRUE, superblock); } else { free(data_bitmap); } int bytes_left = size, bytes_read = 0, block_offset = offset % BLOCK_SIZE; for (int i = starting_block_index; i <= ending_block_index; i++) { int bytes_to_read = min(bytes_left, BLOCK_SIZE - block_offset); bytes_left = max(0, bytes_left - bytes_to_read); if (i < 16) { bio_read_multi(inode->direct_ptr[i], 1, block_buffer); memcpy(block_buffer + block_offset, buffer + bytes_read, bytes_to_read); bio_write_multi(inode->direct_ptr[i], 1, block_buffer); } else { int new_i = i - 16; int val_index = new_i % (BLOCK_SIZE / sizeof(int)); int ptr_index = new_i / (BLOCK_SIZE / sizeof(int)); bio_read_multi(inode->indirect_ptr[ptr_index], 1, block_buffer); int blkno = ((int *)block_buffer)[val_index]; bio_read_multi(blkno, 1, block_buffer); memcpy(block_buffer + block_offset, buffer + bytes_read, bytes_to_read); bio_write_multi(blkno, 1, block_buffer); } bytes_read += bytes_to_read; block_offset = 0; } time(&inode->vstat.st_mtime); writei(inode->ino, inode); pthread_mutex_unlock(&mutex); free(inode); free(block_buffer); //debug("rufs_write(): EXIT\n"); return bytes_read; } static int rufs_unlink(const char *path) { // Step 1: Use dirname() and basename() to separate parent directory path and target file name // Step 2: Call get_node_by_path() to get inode of target file // Step 3: Clear data block bitmap of target file // Step 4: Clear inode bitmap and its data block // Step 5: Call get_node_by_path() to get inode of parent directory // Step 6: Call dir_remove() to remove directory entry of target file in its parent directory // gotta put multithreading locks for this and other rufs functions at the end pthread_mutex_lock(&mutex); int ret = remove_given_path(path, FILE); pthread_mutex_unlock(&mutex); return ret; } static int rufs_truncate(const char *path, off_t size) { // For this project, you don't need to fill this function // But DO NOT DELETE IT! return 0; } static int rufs_release(const char *path, struct fuse_file_info *fi) { // For this project, you don't need to fill this function // But DO NOT DELETE IT! return 0; } static int rufs_flush(const char * path, struct fuse_file_info * fi) { // For this project, you don't need to fill this function // But DO NOT DELETE IT! return 0; } static int rufs_utimens(const char *path, const struct timespec tv[2]) { // For this project, you don't need to fill this function // But DO NOT DELETE IT! return 0; } static struct fuse_operations rufs_ope = { .init = rufs_init, .destroy = rufs_destroy, .getattr = rufs_getattr, .readdir = rufs_readdir, .opendir = rufs_opendir, .releasedir = rufs_releasedir, .mkdir = rufs_mkdir, .rmdir = rufs_rmdir, .create = rufs_create, .open = rufs_open, .read = rufs_read, .write = rufs_write, .unlink = rufs_unlink, .truncate = rufs_truncate, .flush = rufs_flush, .utimens = rufs_utimens, .release = rufs_release }; int main(int argc, char *argv[]) { int fuse_stat; getcwd(diskfile_path, PATH_MAX); strcat(diskfile_path, "/DISKFILE"); fuse_stat = fuse_main(argc, argv, &rufs_ope, NULL); return fuse_stat; }
<style lang="scss" scoped> .sub-mission { height: 100%; display: flex; flex-direction: column; ::v-deep { .el-form-item__content { margin-left: 0 !important; } } .el-scrollbar { height: calc(100vh - 494px); ::v-deep { .el-scrollbar__view { padding: 0 20px; } .el-scrollbar__wrap { overflow-x: hidden; } } } .sub-mission-item { margin-top: 20px; .el-form-item { display: flex; ::v-deep { .el-form-item__content { width: 100%; } } } } .sub-mission-label { position: relative; .add-mission { position: absolute; top: 0; right: -372px; } } } </style> <template> <el-drawer title="任务" :visible="visible" direction="rtl" size="500px" @close="$emit('update:visible', false)"> <div class="drawer-container"> <el-form :data="query" label-width="100px" class="flexCol h100"> <el-form-item label="任务标题"> <el-input v-model="query.title"></el-input> </el-form-item> <el-form-item label="任务内容"> <el-input v-model="query.content" type="textarea" rows="3"></el-input> </el-form-item> <el-form-item label="任务人数"> <el-input v-model="query.recruit" type="number"></el-input> </el-form-item> <el-form-item label="任务地点"> <el-input v-model="query.location"></el-input> </el-form-item> <el-form-item label="任务日期"> <el-date-picker v-model="actionDate" align="right" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" :picker-options="actionDateOptions"> </el-date-picker> </el-form-item> <el-form-item label="任务时间"> <el-date-picker v-model="date" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="missionDateOptions"> </el-date-picker> </el-form-item> <el-form-item label="子任务" class="sub-mission"> <el-scrollbar> <el-card v-for="(mission, index) in subMissionList" :key="index" class="sub-mission-item"> <div class="flexBC mb-10"> <div></div> <div> <el-button type="danger" icon="el-icon-delete" round @click="deleteSubMission(index)">删除</el-button> </div> </div> <el-form-item label="子任务标题" label-width="120px"> <el-input v-model="mission.title"></el-input> </el-form-item> <el-form-item label="子任务时间" label-width="120px"> <el-date-picker v-model="mission.date" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"> </el-date-picker> </el-form-item> </el-card> <div class="flexCC mt-10"> <el-button type="primary" @click="createSubMission">创建子任务</el-button> </div> </el-scrollbar> </el-form-item> </el-form> </div> <div class="drawer-footer"> <el-button type="primary" @click="submit">提交</el-button> </div> </el-drawer> </template> <script lang="ts"> import MissionListApi from '@/api/Mission/List' import { UPDATE_DRAWER_TYPE } from '@/enums/UpdateDrawer' import _ from 'lodash' import moment from 'moment' import { Vue, Component, Prop, Watch } from 'vue-property-decorator' import { SubMissionQueryData, SubMissionChildrenQueryData, SubMissionEditQueryData, CreateMissionQueryData } from '../List' @Component({ name: 'UpdateMission' }) export default class UpdateMission extends Vue { @Prop({ required: true, type: Boolean }) visible!: boolean @Prop({ required: true, type: Number }) type!: UPDATE_DRAWER_TYPE @Prop({ required: true, type: Object }) data!: Record<string, any> @Watch('visible') visibleChanged() { if (this.visible) { // 创建 if (this.type === UPDATE_DRAWER_TYPE.CREATE) { this.resetForm() this.actionDate = moment().format('YYYY-MM-DD') } else { this.query.mission_id = this.data.mission_id this.query.mission_pid = this.data.mission_pid this.query.recruit = this.data.recruit this.query.title = this.data.title this.query.content = this.data.content this.query.location = this.data.location _.forEach(this.data.children as SubMissionEditQueryData[], mission => { if (!mission.date) { this.$set(mission, 'date', [mission.start_time, mission.end_time]) } this.subMissionList.push(mission) }) this.actionDate = this.data.action_date this.date = [this.data.start_time, this.data.end_time] } } else { this.resetForm() } } query: SubMissionChildrenQueryData = { mission_id: 0, mission_pid: 0, recruit: 0, title: '', content: '', location: '', action_date: '', start_time: '', end_time: '', children: { create: [], update: [], delete: [] } } subMissionList: SubMissionEditQueryData[] = [] date: string[] = [] actionDate = '' actionDateOptions = { shortcuts: [ { text: '今儿', onClick: (picker: any) => { picker.$emit('pick', moment().format('YYYY-MM-DD')); } }, { text: '明儿', onClick: (picker: any) => { picker.$emit('pick', moment().add(1, 'day').format('YYYY-MM-DD')); } }, { text: '后天', onClick: (picker: any) => { picker.$emit('pick', moment().add(2, 'days').format('YYYY-MM-DD')); } } ] } missionDateOptions = { shortcuts: [ { text: '任务日期全天', onClick: (picker: any) => { const actionDate = moment(this.getActionDate()) picker.$emit('pick', [actionDate.format('YYYY-MM-DD 00:00:00'), actionDate.format('YYYY-MM-DD 23:59:59')]); } } ] } getActionDate() { return this.actionDate } resetForm() { this.subMissionList = [] this.actionDate = '' this.date = [] this.query = { mission_id: 0, mission_pid: 0, recruit: 0, title: '', content: '', location: '', action_date: '', start_time: '', end_time: '', children: { create: [], update: [], delete: [] } } } createSubMission() { this.subMissionList.push({ mission_pid: this.data.mission_id, title: '', start_time: '', end_time: '' }) } deleteSubMission(index: number) { const mission = this.subMissionList[index] if (_.has(mission, 'mission_id')) { this.query.children.delete.push(mission.mission_id!) } this.subMissionList.splice(index, 1) } async submit() { this.query.start_time = _.get(this.date, '0', '') this.query.end_time = _.get(this.date, '1', '') this.query.action_date = this.actionDate if (this.type === UPDATE_DRAWER_TYPE.CREATE) { const query: CreateMissionQueryData = { recruit: this.query.recruit, title: this.query.title, content: this.query.content, location: this.query.location, action_date: this.query.action_date, start_time: this.query.start_time, end_time: this.query.end_time, children: [] } _.forEach(this.subMissionList, item => { query.children.push({ title: item.title, start_time: _.get(item.date, '0', ''), end_time: _.get(item.date, '1', '') }) }) await MissionListApi.Instance().CreateMission(query) this.$message.success('新增成功') } else { this.query.children.create = [] this.query.children.update = [] const subMissionList = _.cloneDeep(this.subMissionList) _.forEach(subMissionList, item => { item.start_time = _.get(item, 'date.0', '') item.end_time = _.get(item, 'date.1', '') delete item.date if (_.has(item, 'mission_id')) { this.query.children.update.push(item as SubMissionQueryData) } else { this.query.children.create.push(item) } }) await MissionListApi.Instance().UpdateMission(this.query) this.$message.success('修改成功') } this.$emit('reload') this.$emit('update:visible', false) } } </script>
import React, {CSSProperties, HTMLAttributes, ReactNode, useEffect, useRef, useState} from "react"; import {CollapsibleDirection} from "../enums"; import Style from "./Collapsible.module.css"; export function Collapsible(props: CollapsibleProps) { const {label, id, collapsed = true, direction = CollapsibleDirection.HEIGHT, speed = 200, minWidth = 0, minHeight = 0, ...component_method_props} = props; const {onClick, onChange, ...component_props} = component_method_props; const [content_width, setContentWidth] = useState<number>(-1); const [content_height, setContentHeight] = useState<number>(-1); const [last_frame, setLastFrame] = useState<DOMHighResTimeStamp>(0); const ref_label = useRef<HTMLDivElement>(null); const ref_container = useRef<HTMLDivElement>(null); const dynamic = useRef<DynamicVariables>({collapsed, max_height: 0, max_width: 0}); useEffect(onCollapsedChange, [collapsed]); useEffect(onRefContainerChange, [ref_container.current]); useEffect(onFrameChange, [last_frame]); const classes = [Style.Component, "collapsible"]; if (props.className) classes.push(props.className); const content_style: CSSProperties = { minWidth, minHeight, maxWidth: direction !== CollapsibleDirection.HEIGHT ? `${dynamic.current.max_width}px` : undefined, maxHeight: direction !== CollapsibleDirection.WIDTH ? `${dynamic.current.max_height}px` : undefined }; return ( <div {...component_props} className={classes.join(" ")} data-collapsed={dynamic.current.collapsed} data-direction={direction}> {renderLabel(label)} <div className={"collapsible-content"} style={content_style}> <div ref={ref_container} id={id} className={"collapsible-content-container"}> {props.children} </div> </div> </div> ); function renderLabel(label?: ReactNode) { if (!label) return null; return ( <div ref={ref_label} className={"collapsible-label"} onClick={onComponentClick}>{label}</div> ); } function onFrameChange() { if (!last_frame) return; requestAnimationFrame(animate); } function animate(timestamp: DOMHighResTimeStamp) { if (!last_frame) return; let repeat = false; const difference = Math.max(0, timestamp - last_frame); if (dynamic.current.collapsed) { if (dynamic.current.max_height > minHeight) { dynamic.current.max_height = Math.max(minHeight, dynamic.current.max_height - (content_height / speed) * difference); repeat = true; } if (dynamic.current.max_width > minWidth) { dynamic.current.max_width = Math.max(minWidth, dynamic.current.max_width - (content_width / speed) * difference); repeat = true; } } else { if (dynamic.current.max_height < content_height) { dynamic.current.max_height = Math.min(content_height, dynamic.current.max_height + (content_height / speed) * difference); repeat = true; } if (dynamic.current.max_width < content_width) { dynamic.current.max_width = Math.min(content_width, dynamic.current.max_width + (content_width / speed) * difference); repeat = true; } } if (repeat) { setLastFrame(timestamp); } } function collapse(flag: boolean) { dynamic.current.collapsed = flag; setLastFrame(performance.now()); onChange?.(flag); } function onComponentClick(event: React.MouseEvent<HTMLDivElement>) { onClick?.(event); if (event.defaultPrevented) return; collapse(!dynamic.current.collapsed); } function onCollapsedChange() { collapse(collapsed); } function onRefContainerChange() { if (!ref_container.current) return; const observer = new ResizeObserver(onContainerResize); observer.observe(ref_container.current, {box: "border-box"}); return () => observer.disconnect(); } function onContainerResize([{target}]: ResizeObserverEntry[]) { setContentWidth(target.scrollWidth); setContentHeight(target.scrollHeight); if (!dynamic.current.collapsed) { dynamic.current.max_width = target.scrollWidth; dynamic.current.max_height = target.scrollHeight; } } } interface DynamicVariables { collapsed: boolean; max_width: number; max_height: number; } export interface CollapsibleProps extends Omit<HTMLAttributes<HTMLDivElement>, "style" | "onChange"> { collapsed?: boolean; direction?: CollapsibleDirection; label?: React.ReactNode; speed?: number; minWidth?: number; minHeight?: number; onChange?(value: boolean): void; }
#include "input.hh" #include "core/events.hh" // State for the input handler struct InputState { bool initialized = false; uint32_t mousex; uint32_t mousey; KeyboardState keyboardCurrent; KeyboardState keyboardPrev; MouseState mouseCurrent; MouseState mousePrev; }; static InputState input_state = {}; void InputHandler::Startup() { input_state.initialized = true; std::cout << "Input state initialized..." << std::endl; } void InputHandler::Shutdown() { input_state.initialized = false; } void InputHandler::Update(double deltaTime) { (void)deltaTime; if (!input_state.initialized) return; // Copy current state to the previous states input_state.keyboardPrev = input_state.keyboardCurrent; input_state.mousePrev = input_state.mouseCurrent; } void InputHandler::ProcessResize(uint32_t w, uint32_t h) { EventContext data = {}; data.u32[0] = static_cast<uint32_t>(w); data.u32[1] = static_cast<uint32_t>(h); EventHandler::Fire(EVENT_CODE_RESIZED, nullptr, data); } void InputHandler::ProcessKey(Keys key, bool pressed) { // Only do anything if the state has changed if (input_state.keyboardCurrent.keys[key] != pressed) { input_state.keyboardCurrent.keys[key] = pressed; // TODO: Fire an event for immediate processing EventContext data = {}; data.u16[0] = static_cast<uint16_t>(key); EventHandler::Fire( pressed ? EVENT_CODE_KEY_PRESSED : EVENT_CODE_KEY_RELEASED, 0, data); } } void InputHandler::ProcessMouseMove(int32_t x, int32_t y) { // Only do anything if the state actually changed if (input_state.mouseCurrent.x != x || input_state.mouseCurrent.y != y) { input_state.mouseCurrent.x = x; input_state.mouseCurrent.y = y; // TODO: fire an event EventContext data = {}; data.u16[0] = x; data.u16[1] = y; EventHandler::Fire(EVENT_CODE_MOUSE_MOVED, nullptr, data); } } void InputHandler::ProcessMouseWheel(int16_t zDelta) { (void)zDelta; } // Set the parameters to the current position of the mouse's x and y positions void InputHandler::GetMousePosition(int32_t &x, int32_t &y) { x = input_state.mouseCurrent.x; y = input_state.mouseCurrent.y; } // // PRIVATE METHODS // bool InputHandler::_isKeyDown(Keys key) { if (!input_state.initialized) return false; return input_state.keyboardCurrent.keys[key] == true;; } bool InputHandler::_isKeyUp(Keys key) { if (!input_state.initialized) return false; return input_state.keyboardCurrent.keys[key] == false; } bool InputHandler::_wasKeyDown(Keys key) { if (!input_state.initialized) return false; return input_state.keyboardPrev.keys[key] == true; } bool InputHandler::_wasKeyUp(Keys key) { if (!input_state.initialized) return false; return input_state.keyboardPrev.keys[key] == false; } bool InputHandler::_isButtonDown(Buttons button) { if (!input_state.initialized) return false; return input_state.mouseCurrent.buttons[button] == true; } bool InputHandler::_isButtonUp(Buttons button) { if (!input_state.initialized) return false; return input_state.mouseCurrent.buttons[button] == false; } bool InputHandler::_wasButtonDown(Buttons button) { if (!input_state.initialized) return false; return input_state.mousePrev.buttons[button] == true; } bool InputHandler::_wasButtonUp(Buttons button) { if (!input_state.initialized) return false; return input_state.mousePrev.buttons[button] == false; }
# redeemTokensOf Contract: [`JBPayoutRedemptionPaymentTerminal`](../)​‌ Interface: [`IJBPayoutRedemptionPaymentTerminal`](../../../../interfaces/ijbpayoutredemptionpaymentterminal.md) {% tabs %} {% tab title="Step by step" %} **Holders can redeem their tokens to claim the project's overflowed tokens, or to trigger rules determined by the project's current funding cycle's data source.** _Only a token holder or a designated operator can redeem its tokens._ #### Definition ```solidity function redeemTokensOf( address _holder, uint256 _projectId, uint256 _tokenCount, uint256 _minReturnedTokens, address payable _beneficiary, string memory _memo, bytes memory _metadata ) external virtual override requirePermission(_holder, _projectId, JBOperations.REDEEM) returns (uint256 reclaimAmount) { ... } ``` * Arguments: * `_holder` is the account to redeem tokens for. * `_projectId` is the ID of the project to which the tokens being redeemed belong. * `_tokenCount` is the number of project tokens to redeem, as a fixed point number with 18 decimals. * `_minReturnedTokens` is the minimum amount of terminal tokens expected in return, as a fixed point number with the same amount of decimals as this terminal. * `_beneficiary` is the address to send the terminal tokens to. * `_memo` is a memo to pass along to the emitted event. * `_metadata` are bytes to send along to the data source and delegate, if provided. * Through the [`requirePermission`](../../../or-abstract/jboperatable/modifiers/requirepermission.md) modifier, the function is only accessible by the token holder, or from an operator that has been given the [`JBOperations.REDEEM`](../../../../libraries/jboperations.md) permission by the token holder. * The resulting function overrides a function definition from the [`IJBPayoutRedemptionPaymentTerminal`](../../../../interfaces/ijbpayoutredemptionpaymentterminal.md) interface. * The function returns the amount of terminal tokens that the tokens were redeemed for, as a fixed point number with the same amount of decimals as this terminal. #### Body 1. Make sure the provided beneficiary of the claimed funds isn't the zero address. ```solidity // Can't send reclaimed funds to the zero address. if (_beneficiary == address(0)) revert REDEEM_TO_ZERO_ADDRESS(); ``` 2. Define a reference to the project's funding cycle during which the redemption is being made. ```solidity // Define variables that will be needed outside the scoped section below. // Keep a reference to the funding cycle during which the redemption is being made. JBFundingCycle memory _fundingCycle; ``` 3. The following scoped block is a bit of a hack to prevent a "Stack too deep" error. ```solidity // Scoped section prevents stack too deep. `_delegate` only used within scope. { ... } ``` 1. Get a reference to the redemption delegate that. ```solidity IJBRedemptionDelegate _delegate; ``` 2. Record the redemption and get a reference to the funding cycle during which the redemption was made, the terminal token amount that should be reclaimed, a delegate to callback to, and an updated memo. ```solidity // Record the redemption. (_fundingCycle, reclaimAmount, _delegate, _memo) = store.recordRedemptionFor( _holder, _projectId, _tokenCount, decimals, // The fixed point balance has this terminal's token's number of decimals. currency, // The balance is in terms of this terminal's currency. _memo, _metadata ); ``` _External references:_ * [`recordRedemptionFor`](../../../jbpaymentterminalstore/write/recordredemptionfor.md) 3. Make sure the amount of terminal tokens being reclaimed is at least as much as the specified minimum. ```solidity // The amount being reclaimed must be at least as much as was expected. if (reclaimAmount < _minReturnedTokens) revert INADEQUATE_RECLAIM_AMOUNT(); ``` 4. Burn the project's tokens if needed. ```solidity // Burn the project tokens. if (_tokenCount > 0) directory.controllerOf(_projectId).burnTokensOf( _holder, _projectId, _tokenCount, '', false ); ``` _External references:_ * [`controllerOf`](../../../jbdirectory/properties/controllerof.md) * [`burnTokensOf`](../../../or-controllers/jbcontroller/write/burntokensof.md) 5. If a delegate was provided, callback to its `didRedeem` function, and emit an event with the relevant parameters.. ```solidity // If a delegate was returned by the data source, issue a callback to it. if (_delegate != IJBRedemptionDelegate(address(0))) { JBDidRedeemData memory _data = JBDidRedeemData( _holder, _projectId, _tokenCount, JBTokenAmount(token, reclaimAmount, decimals, currency), _beneficiary, _memo, _metadata ); _delegate.didRedeem(_data); emit DelegateDidRedeem(_delegate, _data, msg.sender); } ``` _External references:_ * [`didRedeem`](../../../../interfaces/ijbredemptiondelegate.md) _Event references:_ * [`DelegateDidRedeem`](../events/delegatedidredeem.md) 4. If an amount is being reclaimed, send the funds to the beneficiary. ```solidity // Send the reclaimed funds to the beneficiary. if (reclaimAmount > 0) _transferFrom(address(this), _beneficiary, reclaimAmount); ``` 5. Emit a `RedeemTokens` event with the relevant parameters. ```solidity emit RedeemTokens( _fundingCycle.configuration, _fundingCycle.number, _projectId, _holder, _beneficiary, _tokenCount, reclaimAmount, _memo, msg.sender ); ``` _Event references:_ * [`RedeemTokens`](../events/redeemtokens.md) {% endtab %} {% tab title="Code" %} ```solidity /** @notice Holders can redeem their tokens to claim the project's overflowed tokens, or to trigger rules determined by the project's current funding cycle's data source. @dev Only a token holder or a designated operator can redeem its tokens. @param _holder The account to redeem tokens for. @param _projectId The ID of the project to which the tokens being redeemed belong. @param _tokenCount The number of project tokens to redeem, as a fixed point number with 18 decimals. @param _minReturnedTokens The minimum amount of terminal tokens expected in return, as a fixed point number with the same amount of decimals as this terminal. @param _beneficiary The address to send the terminal tokens to. @param _memo A memo to pass along to the emitted event. @param _metadata Bytes to send along to the data source and delegate, if provided. @return reclaimAmount The amount of terminal tokens that the project tokens were redeemed for, as a fixed point number with 18 decimals. */ function redeemTokensOf( address _holder, uint256 _projectId, uint256 _tokenCount, uint256 _minReturnedTokens, address payable _beneficiary, string memory _memo, bytes memory _metadata ) external virtual override requirePermission(_holder, _projectId, JBOperations.REDEEM) returns (uint256 reclaimAmount) { // Can't send reclaimed funds to the zero address. if (_beneficiary == address(0)) revert REDEEM_TO_ZERO_ADDRESS(); // Define variables that will be needed outside the scoped section below. // Keep a reference to the funding cycle during which the redemption is being made. JBFundingCycle memory _fundingCycle; // Scoped section prevents stack too deep. `_delegate` only used within scope. { IJBRedemptionDelegate _delegate; // Record the redemption. (_fundingCycle, reclaimAmount, _delegate, _memo) = store.recordRedemptionFor( _holder, _projectId, _tokenCount, decimals, // The fixed point balance has this terminal's token's number of decimals. currency, // The balance is in terms of this terminal's currency. _memo, _metadata ); // The amount being reclaimed must be at least as much as was expected. if (reclaimAmount < _minReturnedTokens) revert INADEQUATE_RECLAIM_AMOUNT(); // Burn the project tokens. if (_tokenCount > 0) directory.controllerOf(_projectId).burnTokensOf( _holder, _projectId, _tokenCount, '', false ); // If a delegate was returned by the data source, issue a callback to it. if (_delegate != IJBRedemptionDelegate(address(0))) { JBDidRedeemData memory _data = JBDidRedeemData( _holder, _projectId, _tokenCount, JBTokenAmount(token, reclaimAmount, decimals, currency), _beneficiary, _memo, _metadata ); _delegate.didRedeem(_data); emit DelegateDidRedeem(_delegate, _data, msg.sender); } } // Send the reclaimed funds to the beneficiary. if (reclaimAmount > 0) _transferFrom(address(this), _beneficiary, reclaimAmount); emit RedeemTokens( _fundingCycle.configuration, _fundingCycle.number, _projectId, _holder, _beneficiary, _tokenCount, reclaimAmount, _memo, msg.sender ); } ``` {% endtab %} {% tab title="Errors" %} | String | Description | | ---------------------------- | ------------------------------------------------------- | | **`REDEEM_TO_ZERO_ADDRESS`** | Thrown if the zero address was sent as the beneficiary. | | **`INADEQUATE_RECLAIM_AMOUNT`** | Thrown if the amount being reclaimed is less than the specified minimum. | {% endtab %} {% tab title="Events" %} | Name | Data | | ---------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [**`RedeemTokens`**](../events/redeemtokens.md) | <ul><li><code>uint256 indexed fundingCycleConfiguration</code></li><li><code>uint256 indexed fundingCycleNumber</code></li><li><code>uint256 indexed projectId</code></li><li><code>address holder</code></li><li><code>address beneficiary</code></li><li><code>uint256 tokenCount</code></li><li><code>uint256 claimedAmount</code></li><li><code>string memo</code></li><li><code>address caller</code></li></ul> | {% endtab %} {% tab title="Bug bounty" %} | Category | Description | Reward | | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- | ------ | | **Optimization** | Help make this operation more efficient. | 0.5ETH | | **Low severity** | Identify a vulnerability in this operation that could lead to an inconvenience for a user of the protocol or for a protocol developer. | 1ETH | | **High severity** | Identify a vulnerability in this operation that could lead to data corruption or loss of funds. | 5+ETH | {% endtab %} {% endtabs %}
import React from 'react'; import { useSelector, useDispatch } from 'react-redux'; import { updateCart } from '../store/sliceCart'; function RemoveFromCart({ id }) { const { cart } = useSelector((state) => state.cart); const dispatch = useDispatch(); const { pathname } = window.location; function addProductToCart({ target }) { const currentCart = cart.map((product) => Object.assign({}, product)); currentCart.map((product) => { if (product.id.toString() === target.dataset.id.toString()) { product.cartQuantity -= 1; } return product; }); const noEmptyQuantity = currentCart.filter( (product) => product.cartQuantity !== 0, ); dispatch(updateCart(noEmptyQuantity)); } return ( <> {pathname === '/cart' ? ( <button className="bg-gray-400 hover:bg-gray-500 active:bg-gray-300 w-6 font-bold" data-id={id} onClick={addProductToCart} > - </button> ) : ( <button className="bg-red-500 hover:bg-red-600 active:bg-red-400 text-white px-2 py-1 rounded-md" data-id={id} onClick={addProductToCart} > Remove from cart </button> )} </> ); } export default RemoveFromCart;
import requests import socket from urllib.parse import urlparse import json import os def get_external_ip(url): try: if '://' not in url: url = 'http://' + url hostname = urlparse(url).hostname return socket.gethostbyname(hostname) except Exception as e: print(f"Error getting IP: {e}") return None def get_dns_record_id(subdomain, credentials): try: url = f"https://api.cloudflare.com/client/v4/zones/{credentials['ZONE_ID']}/dns_records?type=A&name={subdomain}" headers = { 'X-Auth-Email': credentials['CLOUDFLARE_EMAIL'], 'X-Auth-Key': credentials['CLOUDFLARE_API_KEY'], 'Content-Type': 'application/json' } response = requests.get(url, headers=headers) if response.status_code == 200 and response.json()['result']: return response.json()['result'][0]['id'] except Exception as e: print(f"Error getting DNS record ID: {e}") return None def delete_dns_record(record_id, credentials): try: url = f"https://api.cloudflare.com/client/v4/zones/{credentials['ZONE_ID']}/dns_records/{record_id}" headers = { 'X-Auth-Email': credentials['CLOUDFLARE_EMAIL'], 'X-Auth-Key': credentials['CLOUDFLARE_API_KEY'], 'Content-Type': 'application/json' } response = requests.delete(url, headers=headers) return response.status_code == 200 except Exception as e: print(f"Error deleting DNS record: {e}") return False def create_dns_record(ip, comment, subdomain, proxied, credentials): try: url = f"https://api.cloudflare.com/client/v4/zones/{credentials['ZONE_ID']}/dns_records" headers = { 'X-Auth-Email': credentials['CLOUDFLARE_EMAIL'], 'X-Auth-Key': credentials['CLOUDFLARE_API_KEY'], 'Content-Type': 'application/json' } data = { 'type': 'A', 'name': subdomain, 'content': ip, 'ttl': 1, 'comment': comment, 'proxied': proxied } response = requests.post(url, headers=headers, json=data) if response.status_code == 200: return True else: print(f"Failed to create DNS record. Status code: {response.status_code}") print(f"Response: {response.text}") return False except Exception as e: print(f"Error creating DNS record: {e}") return False def main(): # Load service configuration with open('/root/cloudflare_dns/service.json', 'r') as file: service_config = json.load(file) credentials = service_config['credentials'] proxied = service_config['proxied'] subdomain_choice = service_config['subdomain_choice'] custom_subdomains = service_config.get('custom_subdomains', {}) # Define records records = [ ("mcic.ircf.space", "همراه اول"), ("mtnc.ircf.space", "ایرانسل"), ("mkhc.ircf.space", "مخابرات"), ("rtlc.ircf.space", "رایتل"), ("hwb.ircf.space", "های وب"), ("ast.ircf.space", "آسیاتک"), ("sht.ircf.space", "شاتل"), ("prs.ircf.space", "پارس آنلاین"), ("mbt.ircf.space", "مبین نت"), ("ask.ircf.space", "اندیشه سبز"), ("rsp.ircf.space", "رسپینا"), ("afn.ircf.space", "افرانت"), ("ztl.ircf.space", "زی تل"), ("psm.ircf.space", "پیشگامان"), ("arx.ircf.space", "آراکس"), ("smt.ircf.space", "سامان تل"), ("shm.ircf.space", "شاتل موبایل"), ("fnv.ircf.space", "فن آوا"), ("dbn.ircf.space", "دیده بان نت"), ("apt.ircf.space", "آپتل"), ("fnp.ircf.space", "فناپ تلکام"), ("ryn.ircf.space", "رای نت"), ("sbn.ircf.space", "صبانت"), ("ptk.ircf.space", "پتیاک"), ("atc.ircf.space", "عصر تلکام") ] updated_records = [] for original_domain, comment in records: ip = get_external_ip(original_domain) if ip: if subdomain_choice == '2' and original_domain in custom_subdomains: new_subdomain = custom_subdomains[original_domain] + '.' + credentials['USER_DOMAIN'] else: new_subdomain = original_domain.split('.')[0] + '.' + credentials['USER_DOMAIN'] updated_records.append((new_subdomain, ip, comment)) for new_subdomain, ip, comment in updated_records: record_id = get_dns_record_id(new_subdomain, credentials) if record_id: delete_dns_record(record_id, credentials) if create_dns_record(ip, comment, new_subdomain, proxied, credentials): print(f"DNS record for {new_subdomain} ({comment}) created successfully") else: print(f"Failed to create DNS record for {new_subdomain}") if __name__ == "__main__": main()
<?php namespace PrestaShop\OAuth2\Client\Provider; /** * { * "issuer":"https://oauth.prestashop.com/", * "authorization_endpoint":"https://oauth.prestashop.com/oauth2/auth", * "token_endpoint":"https://oauth.prestashop.com/oauth2/token", * "jwks_uri":"https://oauth.prestashop.com/.well-known/jwks.json", * "subject_types_supported":["public"], * "response_types_supported":["code","code id_token","id_token","token id_token","token","token id_token code"], * "claims_supported":["sub","name","picture","email","email_verified"], * "grant_types_supported":["authorization_code","implicit","client_credentials","refresh_token"], * "response_modes_supported":["query","fragment"], * "userinfo_endpoint":"https://oauth.prestashop.com/userinfo", * "scopes_supported":["offline_access","offline","openid","profile",...], * "token_endpoint_auth_methods_supported":["client_secret_post","client_secret_basic","private_key_jwt","none"], * "userinfo_signing_alg_values_supported":["none","RS256"], * "id_token_signing_alg_values_supported":["RS256"], * "id_token_signed_response_alg":["RS256"], * "userinfo_signed_response_alg":["RS256"], * "request_parameter_supported":true, * "request_uri_parameter_supported":true, * "require_request_uri_registration":true, * "claims_parameter_supported":false, * "revocation_endpoint":"https://oauth.prestashop.com/oauth2/revoke", * "backchannel_logout_supported":true, * "backchannel_logout_session_supported":true, * "frontchannel_logout_supported":true, * "frontchannel_logout_session_supported":true, * "end_session_endpoint":"https://oauth.prestashop.com/oauth2/sessions/logout", * "request_object_signing_alg_values_supported":["none","RS256","ES256"], * "code_challenge_methods_supported":["plain","S256"] * } */ class WellKnown { /** @var string */ public $issuer; /** @var string */ public $authorization_endpoint; /** @var string */ public $token_endpoint; /** @var string */ public $jwks_uri; /** @var array */ public $subject_types_supported; /** @var array */ public $response_types_supported; /** @var array */ public $claims_supported; /** @var array */ public $grant_types_supported; /** @var array */ public $response_modes_supported; /** @var string */ public $userinfo_endpoint; /** @var array */ public $scopes_supported; /** @var array */ public $token_endpoint_auth_methods_supported; /** @var array */ public $userinfo_signing_alg_values_supported; /** @var array */ public $id_token_signing_alg_values_supported; /** @var array */ public $id_token_signed_response_alg; /** @var array */ public $userinfo_signed_response_alg; /** @var bool */ public $request_parameter_supported; /** @var bool */ public $request_uri_parameter_supported; /** @var bool */ public $require_request_uri_registration; /** @var bool */ public $claims_parameter_supported; /** @var string */ public $revocation_endpoint; /** @var bool */ public $backchannel_logout_supported; /** @var bool */ public $backchannel_logout_session_supported; /** @var bool */ public $frontchannel_logout_supported; /** @var bool */ public $frontchannel_logout_session_supported; /** @var string */ public $end_session_endpoint; /** @var array */ public $request_object_signing_alg_values_supported; /** @var array */ public $code_challenge_methods_supported; /** * @param array|string $infos Url or Properties * @param bool $secure * * @throws \Exception */ public function __construct($infos = [], $secure = \true) { if (\is_array($infos)) { $this->init($infos); } else { $this->init($this->fetch($infos, $secure)); } } /** * @param array $infos * * @return void */ public function init($infos) { foreach ($infos as $key => $value) { if (\property_exists($this, $key)) { $this->{$key} = $value; } } } /** * @param string $url * @param bool $secure * * @return array * * @throws \Exception */ public function fetch($url, $secure = \true) { $wellKnownUrl = $url; if (\strpos($wellKnownUrl, '/.well-known') === \false) { $wellKnownUrl = \preg_replace('/\\/?$/', '/.well-known/openid-configuration', $wellKnownUrl); } return \json_decode(\file_get_contents($wellKnownUrl, \false, \stream_context_create(['ssl' => ['verify_peer' => $secure, 'verify_peer_name' => $secure], 'http' => ['ignore_errors' => '1']])), \true) ?: []; } }
from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.status import ( HTTP_200_OK, HTTP_403_FORBIDDEN, HTTP_201_CREATED, HTTP_204_NO_CONTENT, HTTP_404_NOT_FOUND, HTTP_409_CONFLICT, HTTP_400_BAD_REQUEST ) from .test_views_base import BaseTestCase from ..models import User class UserRequestViewSetTest(BaseTestCase): def setUp(self) -> None: super(UserRequestViewSetTest, self).setUp() # ------------------------------ helper methods ------------------------------ # def user_request_list(self, client, data, status_code=HTTP_200_OK): url = reverse("user-list") return self._make_request(client, self.GET_REQUEST, url, data, status_code) def user_request_retrieve(self, client, pk, status_code=HTTP_200_OK): url = reverse("user-detail", kwargs=dict(pk=pk)) data = dict() return self._make_request(client, self.GET_REQUEST, url, data, status_code) def user_request_create(self, client, data, status_code=HTTP_201_CREATED): url = reverse("user-list") return self._make_request(client, self.POST_REQUEST, url, data, status_code) def user_request_patch(self, client, pk, data, status_code=HTTP_200_OK): url = reverse("user-detail", kwargs=dict(pk=pk)) return self._make_request(client, self.PUT_REQUEST, url, data, status_code) def user_request_delete(self, client, pk, status_code=HTTP_204_NO_CONTENT): url = reverse("user-detail", kwargs=dict(pk=pk)) data = dict() return self._make_request(client, self.DELETE_REQUEST, url, data, status_code) def user_request_change_password(self, client, data, status_code=HTTP_200_OK): url = reverse("change-password") return self._make_request(client, self.PUT_REQUEST, url, data, status_code) # ------------------------------ tests ---------------------------------------- def test_list_with_organization_permissions(self): self.login_dtpm_admin_user() self.user_request_list(self.client, {}) def test_list_without_group_permissions(self): self.login_dtpm_viewer_user() self.user_request_list(self.client, {}, HTTP_403_FORBIDDEN) def test_list_without_active_session(self): self.client.logout() self.user_request_list(self.client, {}, HTTP_403_FORBIDDEN) def test_retrieve_with_group_permissions(self): self.login_dtpm_admin_user() self.user_request_retrieve(self.client, self.dtpm_admin_user.pk) def test_retrieve_without_group_permissions(self): self.login_dtpm_viewer_user() self.user_request_retrieve(self.client, self.dtpm_admin_user.pk, HTTP_403_FORBIDDEN) def test_retrieve_without_active_session(self): self.client.logout() self.user_request_retrieve(self.client, self.dtpm_admin_user.pk, HTTP_403_FORBIDDEN) def test_create_with_group_permissions(self): self.login_dtpm_admin_user() organization = reverse("organization-detail", kwargs=dict(pk=self.dtpm_organization.pk)) new_user_email = 'test_create_user@opct.com' data = { "email": new_user_email, "password": "tcupass123", "organization": organization, "access_to_ops": False, "access_to_organizations": False, "access_to_users": True, "role": "prosecutor", } self.user_request_create(self.client, data) self.assertTrue(get_user_model().objects.filter(email=new_user_email).exists()) def test_create_without_group_permissions(self): self.login_dtpm_viewer_user() self.user_request_create(self.client, {}, HTTP_403_FORBIDDEN) def test_create_without_active_session(self): self.client.logout() self.user_request_create(self.client, {}, HTTP_403_FORBIDDEN) def test_update_with_group_permissions(self): self.login_dtpm_admin_user() organization = reverse("organization-detail", kwargs=dict(pk=self.dtpm_organization.pk)) new_user_email = 'test_create_user@dtpm.com' new_user_email2 = 'test_create_user2@dtpm.com' user = self.create_user(new_user_email, "tcupass123", role=User.PLANNING_TECHNICIAN) data = { "email": new_user_email2, "password": "tcupass123", "organization": organization, "access_to_ops": True, "access_to_organizations": True, "access_to_users": True, "role": User.PROSECUTOR, } self.user_request_patch(self.client, user.pk, data) user.refresh_from_db() self.assertTrue(user.access_to_users) self.assertTrue(user.access_to_organizations) self.assertTrue(user.access_to_ops) self.assertEqual(User.PROSECUTOR, user.role) self.assertEqual(new_user_email2, user.email) def test_update_without_group_permissions(self): self.login_dtpm_viewer_user() self.user_request_patch(self.client, self.dtpm_admin_user.pk, {}, HTTP_403_FORBIDDEN) def test_update_without_active_session(self): self.client.logout() self.user_request_patch(self.client, self.dtpm_admin_user.pk, {}, HTTP_403_FORBIDDEN) def test_delete_with_permissions(self): self.login_dtpm_admin_user() user = self.create_user("test_create_user@opct.com", "tcupass123") self.user_request_delete(self.client, user.pk) def test_delete_with_permissions_not_found(self): self.login_dtpm_admin_user() self.user_request_delete(self.client, -1, HTTP_404_NOT_FOUND) def test_delete_with_permissions_with_references(self): self.login_dtpm_admin_user() user = self.create_user("test_create_user@opct.com", "tcupass123", self.dtpm_organization) counter_part = self.create_counter_part_contact(self.op1_organization, user) self.user_request_delete(self.client, user.pk, HTTP_409_CONFLICT) def test_delete_without_group_permissions(self): self.login_dtpm_viewer_user() self.user_request_delete(self.client, self.dtpm_viewer_user.pk, HTTP_403_FORBIDDEN) def test_delete_without_active_session(self): self.client.logout() self.user_request_delete(self.client, self.dtpm_viewer_user.pk, HTTP_403_FORBIDDEN) def test_change_password(self): self.login_dtpm_viewer_user() data = { 'old_password': 'testpassword1', 'new_password1': 'tcupass321123122312', 'new_password2': 'tcupass321123122312' } self.user_request_change_password(self.client, data, HTTP_204_NO_CONTENT) def test_change_password_but_old_password_is_wrong(self): self.login_dtpm_viewer_user() data = { 'old_password': 'wrong password', 'new_password1': 'tcupass321123122312', 'new_password2': 'tcupass321123122312' } self.user_request_change_password(self.client, data, HTTP_400_BAD_REQUEST) def test_change_password_but_does_not_match(self): self.login_dtpm_viewer_user() data = { 'old_password': 'testpassword1', 'new_password1': '12345', 'new_password2': '56789' } self.user_request_change_password(self.client, data, HTTP_400_BAD_REQUEST) def test_change_password_without_active_session(self): self.client.logout() data = { 'old_password': 'testpassword1', 'new_password1': 'tcupass321123122312', 'new_password2': 'tcupass321123122312' } self.user_request_change_password(self.client, data, HTTP_403_FORBIDDEN)
import 'package:app/views/calendar/row.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:models/calendar.dart'; import 'utils.dart'; void main() { group('Calendar', () { group('Calendar row', () { testWidgets('Normal calendar row', (tester) async { await tester.pumpWidget(makeTestableWidget(CalendarRow( event: CalendarEvent( name: 'Sommerferien', type: EventTypes.vacation, start: DateTime(2019, 7, 15), end: DateTime(2019, 8, 27), ), ))); await tester.pumpAndSettle(); expect(find.text('Sommerferien'), findsOneWidget); expect(find.text('July 15, 2019 - August 27, 2019'), findsOneWidget); }); testWidgets('Normal calendar row with times', (tester) async { await tester.pumpWidget(makeTestableWidget(CalendarRow( event: CalendarEvent( name: 'Sommerferien', type: EventTypes.vacation, start: DateTime(2019, 7, 15, 8), end: DateTime(2019, 8, 27, 8), ), ))); await tester.pumpAndSettle(); expect(find.text('Sommerferien'), findsOneWidget); expect( find.text('July 15, 2019 08:00 - August 27, 2019 08:00'), findsOneWidget, ); }); testWidgets('Normal calendar row on same day', (tester) async { await tester.pumpWidget(makeTestableWidget(CalendarRow( event: CalendarEvent( name: 'Tag der offenen Tür', type: EventTypes.vacation, start: DateTime(2018, 12, 8), end: DateTime(2018, 12, 8, 23, 59, 59), ), ))); await tester.pumpAndSettle(); expect(find.text('Tag der offenen Tür'), findsOneWidget); expect(find.text('December 8, 2018'), findsOneWidget); }); testWidgets('Normal calendar row on same day with time', (tester) async { await tester.pumpWidget(makeTestableWidget(CalendarRow( event: CalendarEvent( name: 'Tag der offenen Tür', type: EventTypes.vacation, start: DateTime(2018, 12, 8, 8), end: DateTime(2018, 12, 8, 23, 59, 59), ), ))); await tester.pumpAndSettle(); expect(find.text('Tag der offenen Tür'), findsOneWidget); expect(find.text('December 8, 2018 08:00'), findsOneWidget); }); }); }); }
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; import {applyMiddleware, combineReducers, createStore} from "redux"; import AuthReducer from "./components/Redux/AuthReducer"; import {Provider} from "react-redux"; import {HashRouter} from "react-router-dom"; import PostsReducer from "./components/Redux/PostsReducer"; import thunkMiddleware from 'redux-thunk'; import {reducer as formReducer} from "redux-form"; const CombineReducer = combineReducers({ authStore: AuthReducer, postsStore: PostsReducer, form: formReducer, }); const store = createStore(CombineReducer, applyMiddleware(thunkMiddleware)); ReactDOM.render( <Provider store={store}> <HashRouter> <App/> </HashRouter> </Provider>, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
// Async - Await function descargarNuevosClientes () { return new Promise (resolve => { console.log('Descargando nuevos clientes... espere...'); setTimeout(() => resolve('Los clientes fueron Descargados'), 5000); }); }; function descargarUltimosPedidos() { return new Promise (resolve => { console.log('Descargando ultimos pedidos... espere...'); setTimeout(() => resolve('Los pedidos fueron Descargados'), 3000); }); }; async function app(){ try { // const clientes = await descargarNuevosClientes(); // const pedidos = await descargarNuevosClientes(); // console.log(clientes); // console.log(pedidos); const resultado = await Promise.all([descargarNuevosClientes(), descargarUltimosPedidos()]); console.log(resultado[0]); console.log(resultado[1]); } catch (error) { console.log(error); }; }; app(); console.log('Este codigo no se bloquea');
import { MouseEventHandler } from "react"; export interface CustomButtonProps{ title:string; containerStyle?: string; btnType?: "button"|"submit"; handleClick ?: MouseEventHandler<HTMLButtonElement>; textStyles?: string, rightIcon?: string, isDisabled?: boolean } export interface SearchManufacturerProps{ manufacturer: string, setManufacturer: (manufacturer:string)=>void; } export interface CarApiProps{ city_mpg: number, class: string, combination_mpg: number, cylinders: number, displacement: number, drive: string, fuel_type: string, highway_mpg: number, make: string, model: string, transmission: string, year: number }
"use client"; import { IoIosArrowDropleft } from "react-icons/io"; import { useScroll, motion, useTransform } from "framer-motion"; import Image from "next/image"; import React, { useRef, useState } from "react"; import Link from "next/link"; const Project = ({ project }) => { const title = project.title; const description = project.description; const tags = project.tags; const imageURL = project.imageURL; const imageLarge = project.imageLargeURL; const link = project.url; const ref = useRef(null); const { scrollYProgress } = useScroll({ target: ref, offset: ["0 1", "1.33 1"], }); const scaleProgress = useTransform(scrollYProgress, [0, 1], [0.8, 1]); const opacityProgress = useTransform(scrollYProgress, [0, 1], [0.6, 1]); const [sectionSwap, setSectionSwap] = useState(false); const swapRight = () => { setSectionSwap(true); console.log(sectionSwap); }; const swapLeft = () => { setSectionSwap(false); }; return ( <div className={`w-[200%] flex h-auto ${ sectionSwap ? "-translate-x-1/2 transition ease-in-out duration-[400ms]" : "transition ease-in-out duration-[500ms]" }`} > <div className="w-[50%] h-auto"> <motion.div className="group mx-auto mb-3 sm:mb-8 last:mb-0 max-w-[42rem] cursor-pointer " ref={ref} style={{ scale: scaleProgress, opacity: opacityProgress, }} onClick={swapRight} > <section className="w-[90%] mx-auto bg-gray-100 border border-black/5 mb-8 overflow-hidden sm:pr-8 relative rounded-lg sm:h-[22rem] group-even:pl-8 hover:bg-gray-200 transition"> <div className="group-even:ml-[18rem] pt-4 pb-8 px-5 flex flex-col h-full sm:pl-10 sm:pr-2 sm:pt-10 max-w-[55%] md:max-w-[49%] lg:max-w-[50%]"> <h3 className="text-2xl font-semibold">{title}</h3> <p className="mt-2 leading-relaxed">{description}</p> <ul className="flex flex-wrap mt-4 gap-2 sm:mt-auto"> {tags.map((tag, index) => ( <li className="bg-black/[0.7] px-3 py-1 text-[0.7rem] uppercase tracking-wider text-white rounded-full" key={index} > {tag} </li> ))} </ul> </div> <Image src={imageURL} alt={title} quality={95} className="absolute top-20 -right-40 w-[20rem] sm:w-[24rem] md:w-[28.25rem] rounded-t-lg shadow-2xl transition ease-in-out duration-300 group-hover: scale-[1.05] group-hover:-translate-x-3 group-hover:-translate-y-3 group-hover:-rotate-2 group-even:group-hover:translate-x-3 group-even:group-hover:translate-y-3 group-even:group-hover:rotate-2 group-even:right-[initial] group-even:-left-40" /> </section> </motion.div> </div> <div className={` ${sectionSwap ? "w-[50%] flex flex-col" : "hidden"}`}> <div className="max-w-[700px] w-[90%] h-full mx-auto mb-8"> <div className="flex items-center gap-2 mb-4"> <div className="w-[40px] h-[40px] cursor-pointer"> <IoIosArrowDropleft className="w-full h-full" onClick={swapLeft} /> </div> <h4 className="uppercase text-xl">{title}</h4> </div> <div className="w-full"> <div className="relative m-h-[600px] mb-6"> <Image src={imageLarge} alt={title} objectFit="contain" objectPosition="center" width="600" height="0" size="100%" className="w-full h-auto" /> </div> <Link href={link} className="py-3 px-4 justify-center rounded-md border-solid border-2 border-green-700 text-green-700 uppercase hover:bg-green-700 hover:text-[#F8F7F1] transition" target="_blank" > Se källkod </Link> </div> </div> </div> </div> ); }; export default Project;
#pragma once #include "intervention_scenario.h" #include <functional> #include <map> #include <optional> namespace hgps { /// @brief Health GPS policy impact types enumeration enum class PolicyImpactType : uint8_t { /// @brief Absolute impact absolute, /// @brief Relative impact relative, }; /// @brief Simple intervention policy definition data type struct SimplePolicyDefinition { SimplePolicyDefinition() = delete; /// @brief Initialise a new instance of the SimplePolicyDefinition structure /// @param type_of_impact The policy impact type /// @param sorted_impacts The impact on risk factors /// @param period The implementation period SimplePolicyDefinition(const PolicyImpactType &type_of_impact, const std::vector<PolicyImpact> &sorted_impacts, const PolicyInterval &period) : impact_type{type_of_impact}, impacts{sorted_impacts}, active_period{period} {} /// @brief Intervention impact type PolicyImpactType impact_type; /// @brief Intervention impacts on risk factors std::vector<PolicyImpact> impacts; /// @brief Active implementation period PolicyInterval active_period; }; /// @brief Defines the simple development intervention scenario class SimplePolicyScenario final : public InterventionScenario { public: SimplePolicyScenario() = delete; /// @brief Initialises a new instance of the SimplePolicyScenario class. /// @param data_sync The data synchronisation channel instance to use. /// @param definition The intervention definition SimplePolicyScenario(SyncChannel &data_sync, SimplePolicyDefinition &&definition); SyncChannel &channel() override; void clear() noexcept override; double apply(Random &generator, Person &entity, int time, const core::Identifier &risk_factor_key, double value) override; const PolicyImpactType &impact_type() const noexcept; const PolicyInterval &active_period() const noexcept override; const std::vector<PolicyImpact> &impacts() const noexcept override; private: std::reference_wrapper<SyncChannel> channel_; SimplePolicyDefinition definition_; std::map<core::Identifier, PolicyImpact> factor_impact_; }; } // namespace hgps
classdef (Sealed) SummaryView < element.ComponentWithListenerPanel properties (Access = private) % Edit box showing the pre-tax voluntary deductions. PreTaxVoluntaryDeductionField (1, 1) % Edit box showing the pre-tax compulsory deductions. PreTaxCompulsoryDeductionField (1, 1) % Edit box showing the post-tax deductions. PostTaxDeductionField (1, 1) end methods function obj = SummaryView(model, varargin) % Call superclass constructors. obj@element.ComponentWithListenerPanel(model) % Create grid. obj.Grid = uigridlayout(obj.Main, [4, 2], ... "RowHeight", ["2x", "1x", "1x", "1x"]); % Retrieve deduction summary values. deductions = obj.Model.Deductions; % Create edit fields. obj.PreTaxVoluntaryDeductionField = uieditfield("numeric", ... "Parent", obj.Grid, ... "ValueDisplayFormat", "£ %.2f", ... "Value", deductions(1), ... "FontSize", 20, ... "Editable", "off"); obj.PreTaxVoluntaryDeductionField.Layout.Row = 2; obj.PreTaxVoluntaryDeductionField.Layout.Column = 2; obj.PreTaxCompulsoryDeductionField = uieditfield("numeric", ... "Parent", obj.Grid, ... "ValueDisplayFormat", "£ %.2f", ... "Value", deductions(2), ... "FontSize", 20, ... "Editable", "off"); obj.PreTaxCompulsoryDeductionField.Layout.Row = 3; obj.PreTaxCompulsoryDeductionField.Layout.Column = 2; obj.PostTaxDeductionField = uieditfield("numeric", ... "Parent", obj.Grid, ... "ValueDisplayFormat", "£ %.2f", ... "Value", deductions(3), ... "FontSize", 20, ... "Editable", "off"); obj.PostTaxDeductionField.Layout.Row = 4; obj.PostTaxDeductionField.Layout.Column = 2; % Create all labels. label = uilabel(obj.Grid, ... "Text", ["Use this app to compute your net income based on your recurring deductions. You can add", ... "pre-tax and post-tax deductions. The values of National Insurance and tax will be computed", ... "based on the gross income, after pre-tax and optional pension deductions have been subtracted."], ... "FontSize", 13, ... "HorizontalAlignment", "left", ... "VerticalAlignment", "top"); label.Layout.Row = 1; label.Layout.Column = [1, 2]; label = uilabel(obj.Grid, ... "Text", "Pre-Tax Voluntary Deductions:", ... "FontSize", 15, ... "HorizontalAlignment", "right", ... "VerticalAlignment", "center"); label.Layout.Row = 2; label.Layout.Column = 1; label = uilabel(obj.Grid, ... "Text", "Pre-Tax Compulsory Deductions:", ... "FontSize", 15, ... "HorizontalAlignment", "right", ... "VerticalAlignment", "center"); label.Layout.Row = 3; label.Layout.Column = 1; label = uilabel(obj.Grid, ... "Text", "Post-Tax Deductions:", ... "FontSize", 15, ... "HorizontalAlignment", "right", ... "VerticalAlignment", "center"); label.Layout.Row = 4; label.Layout.Column = 1; % Set properties. set(obj, varargin{:}) % Show data. obj.onUpdate(); end % constructor end % methods methods (Access = protected) function onUpdate(obj, ~, ~) % ONUPDATE Internal function to update the deductions values % with new model data. This function is triggered by a listener % on the Finance object 'Update' event. % Retrieve deduction summary values. deductions = obj.Model.Deductions; % Update edit boxes. obj.PreTaxVoluntaryDeductionField.Value = deductions(1); obj.PreTaxCompulsoryDeductionField.Value = deductions(2); obj.PostTaxDeductionField.Value = deductions(3); end % onUpdate end % methods (Access = protected) end
import { FeedbackType } from '@/@types/feedback' import { Box, Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, IconButton, TextField } from '@mui/material' import ImageUserDefault from '@/assets/images/avatar-user.jpg' import { formatDateTime } from '@/helpers/formatDateTime' import CommentOutlinedIcon from '@mui/icons-material/CommentOutlined' import RedoOutlinedIcon from '@mui/icons-material/RedoOutlined' import { useState } from 'react' import SendOutlinedIcon from '@mui/icons-material/SendOutlined' import { addResponseApi, deleteFeedBackApi } from '@/services/FeedbackService/feedbackService' import { toast } from 'react-toastify' import { useSelector } from 'react-redux' import { RootState } from '@/store' import DeleteForeverOutlinedIcon from '@mui/icons-material/DeleteForeverOutlined' interface PropsType { feedback: FeedbackType refreshFeedbacks: () => void } const FeedbackItem = ({ feedback, refreshFeedbacks }: PropsType) => { const role = useSelector((state: RootState) => state.auth.role) const [response, setResponse] = useState('') const [isReplying, setIsReplying] = useState(false) const handleResponseChange = (event: React.ChangeEvent<HTMLInputElement>) => { setResponse(event.target.value) } const handleReplyClick = () => { setIsReplying(true) } const handleCancelClick = () => { setIsReplying(false) setResponse('') } const handleResponseSend = async () => { try { const res = await addResponseApi({ response }, feedback.id) if (res && res.status === 200) { toast.success('Thêm phản hồi thành công') console.log('Phản hồi đã được gửi:', response) refreshFeedbacks() setResponse('') setIsReplying(false) } } catch (error) { console.error('Lỗi khi gửi phản hồi:', error) } } const [open, setOpen] = useState(false) const handleClickOpen = () => { setOpen(true) } const handleClose = () => { setOpen(false) } const handleDelete = async () => { try { await deleteFeedBackApi(feedback.id) toast.success('Phản hồi đã được xóa thành công') refreshFeedbacks() handleClose() } catch (error) { console.error('Lỗi khi xóa phản hồi:', error) } } return ( <> <div className='border p-4 rounded shadow mt-10 bg-orange-100'> <Box display='flex' alignItems='center'> <img alt='profile-user' width={50} height={50} src={feedback?.avatarUrl || ImageUserDefault} style={{ cursor: 'pointer', borderRadius: '50%' }} /> <p className='pt-2 font-medium ml-1 text-center mb-1 text-lg'>{feedback.studentName}</p> </Box> {role && ['ADMIN'].includes(role.toUpperCase()) && ( <IconButton onClick={handleClickOpen} color='error'> <DeleteForeverOutlinedIcon /> </IconButton> )} <div className='ml-4'> <p className='font-thin text-sm'> <em>{formatDateTime(feedback.commentDate)}</em> </p> <div className='mt-4 shadow rounded p-2 border'> <p className='font-normal '> <CommentOutlinedIcon /> {feedback.comments} </p> </div> <div className='mt-2 ml-10'> {!feedback.response && role && ['ADMIN', 'STAFF'].includes(role.toUpperCase()) && ( <Box display='flex' alignItems='center'> <button onClick={handleReplyClick} className='text-blue-500 mb-1'> Trả lời </button> {isReplying && ( <button onClick={handleCancelClick} color='error' className='ml-5 mb-1'> Hủy </button> )} </Box> )} {isReplying && ( <div> <TextField label='Nhập phản hồi của bạn' variant='outlined' fullWidth value={response} onChange={handleResponseChange} InputProps={{ endAdornment: ( <IconButton onClick={handleResponseSend} color='primary'> <SendOutlinedIcon /> </IconButton> ) }} /> </div> )} {feedback.response && ( <p> <RedoOutlinedIcon /> {feedback.response} </p> )} </div> </div> </div> <Dialog open={open} onClose={handleClose}> <DialogTitle>Xác nhận xóa câu hỏi đánh giá</DialogTitle> <DialogContent> <DialogContentText>Bạn có chắc chắn khi xóa câu hỏi đánh giá này?</DialogContentText> </DialogContent> <DialogActions> <Button onClick={handleClose} color='primary'> Hủy </Button> <Button onClick={handleDelete} color='primary' autoFocus> Xác nhận </Button> </DialogActions> </Dialog> </> ) } export default FeedbackItem
import React, { useState } from 'react'; import { Box, Button, Container, TextField, Typography, } from '@mui/material'; import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell 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'; const CreateForm = () => { const [user, setUser] = useState({ fName: '', lName: '', email: '', confirmPassword: '', password: '', }); const [userData, setUserData] = useState([]); const handleInput = (e) => { const { name, value } = e.target; setUser((user) => ({ ...user, [name]: value, })); }; const handleSubmit = (e) => { e.preventDefault(); setUserData([...userData, user]); setUser({ fName: '', lName: '', email: '', confirmPassword: '', password: '', }); }; return ( <> <Container maxWidth="md"> <Box sx={{ m: '20px', p: '20px', boxShadow: '0px 0px 5px' }}> <Typography sx={{ textAlign: 'center', fontWeight: 'bold', }} variant="h6" component={'p'} > Form </Typography> <form onSubmit={handleSubmit}> <TextField placeholder="Enter Your First Name" margin="dense" fullWidth type="text" name="fName" value={user.fName} onChange={handleInput} /> <TextField placeholder="Enter Your Last Name" margin="dense" fullWidth type="text" name="lName" value={user.lName} onChange={handleInput} /> <TextField placeholder="Enter Your Email " margin="dense" fullWidth type="email" name="email" value={user.email} onChange={handleInput} /> <TextField placeholder="Confirm Password " margin="dense" fullWidth type="password" name="confirmPassword" value={user.confirmPassword} onChange={handleInput} /> <TextField placeholder="Password" margin="dense" fullWidth type="password" name="password" value={user.password} onChange={handleInput} /> <Button variant="contained" type="submit"> Submit </Button> </form> </Box> </Container> <TableContainer component={Paper}> <Table sx={{ minWidth: 650 }} aria-label="simple table"> <TableHead> <TableRow> <TableCell>FirstName</TableCell> <TableCell>LastName</TableCell> <TableCell align='center'>Email</TableCell> <TableCell>Password</TableCell> <TableCell>Confirm password</TableCell> </TableRow> </TableHead> <TableBody> {userData.map((item, index) => ( <TableRow key={index}> <TableCell>{item.fName}</TableCell> <TableCell>{item.lName}</TableCell> <TableCell>{item.email}</TableCell> <TableCell>{item.password}</TableCell> <TableCell>{item.confirmPassword}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </> ); }; export default CreateForm;
import { useEffect, useState } from "react"; export type ProjectType = { title: string; images: string[]; desc: string; repoLink: string; }; export function useLoadProjects() { const [projects, setProjects] = useState<ProjectType[]>([]); useEffect(() => { fetch("./projects_data.json") .then((res) => res.json()) .then((data) => setProjects(data.projects)); }, []); return projects; }
import React from 'react'; import { render, RenderResult, screen, waitFor } from '@testing-library/react'; import { Simulate } from 'react-dom/test-utils'; import nock from 'nock'; import { QueryClient, QueryClientProvider } from 'react-query'; import NewCommentModal, { NewCommentModalProps } from './NewCommentModal'; import AuthContext from '../../contexts/AuthContext'; import { COMMENT_ON_COMMENT_MUTATION, COMMENT_ON_POST_MUTATION, EDIT_COMMENT_MUTATION, RECOMMEND_MENTIONS_QUERY, PREVIEW_COMMENT_MUTATION, } from '../../graphql/comments'; import { MockedGraphQLResponse, mockGraphQL, } from '../../../__tests__/helpers/graphql'; import { waitForNock } from '../../../__tests__/helpers/utilities'; import { RecommendedMention } from '../RecommendedMention'; import comment from '../../../__tests__/fixture/comment'; import user from '../../../__tests__/fixture/loggedUser'; import { NotificationsContextProvider } from '../../contexts/NotificationsContext'; import { PostType } from '../../graphql/posts'; import { UserShortProfile } from '../../lib/user'; import { SourceType } from '../../graphql/sources'; import { BootApp } from '../../lib/boot'; const onRequestClose = jest.fn(); const onComment = jest.fn(); beforeEach(() => { nock.cleanAll(); jest.clearAllMocks(); }); const renderComponent = ( props: Partial<NewCommentModalProps> = {}, mocks: MockedGraphQLResponse[] = [], ): RenderResult => { const defaultProps: NewCommentModalProps = { authorImage: 'https://daily.dev/nimrod.png', authorName: 'Nimrod', publishDate: new Date(2017, 1, 10, 0, 0), contentHtml: '<p>This is the main comment</p>', commentId: null, post: { id: 'p1', title: 'Title', image: 'https://image.com', commentsPermalink: 'https://daily.dev', type: PostType.Article, summary: '', source: { id: 's', name: 's', handle: 's', image: 's', type: SourceType.Machine, permalink: '', }, }, isOpen: true, ariaHideApp: false, onRequestClose, onComment, }; const client = new QueryClient(); mocks.forEach(mockGraphQL); return render( <QueryClientProvider client={client}> <AuthContext.Provider value={{ user, shouldShowLogin: false, showLogin: jest.fn(), logout: jest.fn(), updateUser: jest.fn(), tokenRefreshed: true, closeLogin: jest.fn(), getRedirectUri: jest.fn(), }} > <NotificationsContextProvider app={BootApp.Webapp}> <NewCommentModal {...defaultProps} {...props} /> </NotificationsContextProvider> </AuthContext.Provider> </QueryClientProvider>, ); }; it('should show twice the author name as title and in reply to', async () => { renderComponent(); expect((await screen.findAllByText('Nimrod')).length).toEqual(2); }); it('should show formatted date of publication', async () => { renderComponent(); await screen.findByText('Feb 10, 2017'); }); it('should show author profile picture', async () => { renderComponent(); const el = await screen.findByAltText(`Nimrod's profile`); expect(el).toHaveAttribute('src', 'https://daily.dev/nimrod.png'); }); it('should show user profile picture', async () => { renderComponent(); const el = await screen.findByAltText(`${user.username}'s profile`); expect(el).toHaveAttribute('src', 'https://daily.dev/ido.png'); }); it('should show content of parent', async () => { renderComponent(); await screen.findByText('This is the main comment'); }); it('should disable submit button when no input', async () => { renderComponent(); const el = await screen.findByText('Post'); // eslint-disable-next-line testing-library/no-node-access expect(el.parentElement).toBeDisabled(); }); it('should enable submit button when no input', async () => { renderComponent(); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; input.value = 'My new comment'; input.dispatchEvent(new Event('input', { bubbles: true })); const el = await screen.findByText('Post'); expect(el.getAttribute('disabled')).toBeFalsy(); }); it('should send commentOnPost mutation', async () => { let mutationCalled = false; const newComment = { __typename: 'Comment', id: 'new', content: 'comment', createdAt: new Date(2017, 1, 10, 0, 1).toISOString(), permalink: 'https://daily.dev', }; renderComponent({}, [ { request: { query: COMMENT_ON_POST_MUTATION, variables: { id: 'p1', content: 'comment' }, }, result: () => { mutationCalled = true; return { data: { comment: newComment, }, }; }, }, ]); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; input.value = 'comment'; input.dispatchEvent(new Event('input', { bubbles: true })); const el = await screen.findByText('Post'); el.click(); await waitFor(() => mutationCalled); await waitFor(() => expect(onComment).toBeCalledWith(newComment, true)); }); it('should send commentOnComment mutation', async () => { let mutationCalled = false; const newComment = { __typename: 'Comment', id: 'new', content: 'comment', createdAt: new Date(2017, 1, 10, 0, 1).toISOString(), permalink: 'https://daily.dev', }; renderComponent({ commentId: 'c1' }, [ { request: { query: COMMENT_ON_COMMENT_MUTATION, variables: { id: 'c1', content: 'comment' }, }, result: () => { mutationCalled = true; return { data: { comment: newComment, }, }; }, }, ]); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; input.value = 'comment'; input.dispatchEvent(new Event('input', { bubbles: true })); const el = await screen.findByText('Post'); el.click(); await waitFor(() => mutationCalled); await waitFor(() => expect(onComment).toBeCalledWith(newComment, true)); }); it('should not send comment if the input is spaces only', async () => { let mutationCalled = false; const newComment = { __typename: 'Comment', id: 'new', content: 'comment', createdAt: new Date(2017, 1, 10, 0, 1).toISOString(), permalink: 'https://daily.dev', }; renderComponent({ commentId: 'c1' }, [ { request: { query: COMMENT_ON_COMMENT_MUTATION, variables: { id: 'c1', content: 'comment' }, }, result: () => { mutationCalled = true; return { data: { comment: newComment, }, }; }, }, ]); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; input.value = ' '; input.dispatchEvent(new Event('input', { bubbles: true })); const el = await screen.findByText('Post'); el.click(); await waitFor(() => expect(onComment).not.toBeCalled()); expect(mutationCalled).toBeFalsy(); }); it('should show alert in case of an error', async () => { let mutationCalled = false; renderComponent({ commentId: 'c1' }, [ { request: { query: COMMENT_ON_COMMENT_MUTATION, variables: { id: 'c1', content: 'comment' }, }, result: () => { mutationCalled = true; return { errors: [] }; }, }, ]); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; input.value = 'comment'; input.dispatchEvent(new Event('input', { bubbles: true })); const el = await screen.findByText('Post'); el.click(); await waitFor(() => mutationCalled); await screen.findByRole('alert'); expect(onRequestClose).toBeCalledTimes(0); }); it('should send editComment mutation', async () => { let mutationCalled = false; renderComponent({ editId: 'c1', editContent: 'My comment to edit' }, [ { request: { query: EDIT_COMMENT_MUTATION, variables: { id: 'c1', content: comment.content }, }, result: () => { mutationCalled = true; return { data: { comment, }, }; }, }, ]); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; input.value = comment.content; input.dispatchEvent(new Event('input', { bubbles: true })); const el = await screen.findByText('Update'); el.click(); await waitFor(() => mutationCalled); await waitFor(() => expect(onComment).toBeCalledWith(comment, false)); }); it('should pre-populate comment box with the author username when', async () => { const replyTo = '@sshanzel '; renderComponent({ commentId: 'c1', replyTo }); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; expect(input).toHaveValue(replyTo); }); const simulateTextboxInput = (el: HTMLTextAreaElement, key: string) => { Simulate.input(el, { data: key } as unknown); // eslint-disable-next-line no-param-reassign el.value += key; }; const defaultMention = [ { name: 'Lee', username: 'sshanzel', image: 'sample.image.com' }, ]; const createMentionMock = ( recommendedMentions: Partial<UserShortProfile>[] = defaultMention, onSuccess?: () => void, query = '', ) => ({ request: { query: RECOMMEND_MENTIONS_QUERY, variables: { postId: 'p1', query, sourceId: 's' }, }, result: () => { onSuccess?.(); return { data: { recommendedMentions }, }; }, }); it('should recommend users previously mentioned', async () => { let queryPreviouslyMentioned = false; renderComponent({}, [ createMentionMock(defaultMention, () => { queryPreviouslyMentioned = true; }), ]); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; simulateTextboxInput(input, '@'); await waitForNock(); expect(queryPreviouslyMentioned).toBeTruthy(); }); it('should recommend users based on query', async () => { let queryPreviouslyMentioned = false; let queryMatchingNameOrUsername = false; renderComponent({}, [ createMentionMock( [{ name: 'Ido', username: 'idoshamun', image: 'sample.image.com' }], () => { queryPreviouslyMentioned = true; }, ), ]); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; simulateTextboxInput(input, '@'); await waitForNock(); expect(queryPreviouslyMentioned).toBeTruthy(); const query = 'l'; mockGraphQL( createMentionMock( defaultMention, () => { queryMatchingNameOrUsername = true; }, query, ), ); simulateTextboxInput(input, query); await waitForNock(); expect(queryMatchingNameOrUsername).toBeTruthy(); }); describe('recommended mention component', () => { it('should display name, username and image of the user', async () => { const client = new QueryClient(); render( <QueryClientProvider client={client}> <RecommendedMention selected={0} users={[ { id: 'u1', name: 'Lee', username: 'sshanzel', image: 'sample.image.com', permalink: 'www.test.com/sshanzel', }, ]} /> </QueryClientProvider>, ); await screen.findByText('@sshanzel'); await screen.findByText('Lee'); await screen.findByAltText(`sshanzel's profile`); }); }); it('should send previewComment query', async () => { let queryCalled = false; mockGraphQL({ request: { query: PREVIEW_COMMENT_MUTATION, variables: { content: '# Test' }, }, result: () => { queryCalled = true; return { data: { preview: '<h1>Test</>' } }; }, }); renderComponent(); const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement; input.value = '# Test'; input.dispatchEvent(new Event('input', { bubbles: true })); const preview = await screen.findByText('Preview'); preview.click(); await waitFor(() => queryCalled); });
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Admin Login</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css"> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">Gamification String</a> </div> <ul class="nav navbar-nav"> <li><a href="index.jsp">Home</a></li> <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Login <span class="caret"></span></a> <ul class="dropdown-menu"> <li class="active"><a href="adminloginform.html">Admin</a></li> <li><a href="userloginform.html">User</a></li> </ul> </li> <li><a href="registration.html">Register</a></li> <li><a href="#">About</a></li> </ul> </div> </nav> <div class="login"> <h1>Admin Login Form</h1> <form:form action="adminloginform.html" commandName="loginForm"> <table> <tr> <td><h6> <form:errors path="email" /></h6></td> </tr> <tr> <td><form:input placeholder="Email" path="email" required="required"/></td> </tr> <tr> <td><h6><form:errors path="password" /></h6></td> </tr> <tr> <td><form:password style="width: 300px;" placeholder="Password" path="password" required="required"/></td> </tr> <tr> <td><input type="submit" style="background-color: #4a77d4;" class="btn btn-primary btn-block btn-large" value="Login" /></td> </tr> </table> </form:form> </div> </body> </html>
// // Created by shexuan on 2021/2/25. // #ifndef CHAPTER7__Q104_MAXIMUM_DEPTH_OF_BINARY_TREE_H #define CHAPTER7__Q104_MAXIMUM_DEPTH_OF_BINARY_TREE_H #include <queue> using namespace std; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: int maxDepth(TreeNode* root) { // 深度优先,递归 if(!root) return 0; return max(maxDepth(root->left), maxDepth(root->right))+1; } }; class Solution2 { public: int maxDepth(TreeNode* root) { // 利用广度搜索的思路来做 int ret = 0; queue<TreeNode*> q; if(root) q.push(root); while(!q.empty()){ int size_ = q.size(); for(int i=0; i<size_; i++){ TreeNode * node = q.front(); q.pop(); if(node->left) q.push(node->left); if(node->right) q.push(node->right); } ret++; } return ret; } }; #endif //CHAPTER7__Q104_MAXIMUM_DEPTH_OF_BINARY_TREE_H
{% set paragraph_blockname = paragraph_blockname|default('accordion') %} {% set accordion_always_open = accordion_always_open|default(false) %} {% set accordion_opened_item = accordion_opened_item|default(0) %} {% extends "@components/paragraph/abstract/paragraph.twig" %} {% block content %} {% include "@components/global/_twig_debug.twig" with { component_debug_path: _self} %} {{ attach_library('otsuka_design_system2022/bootstrap.accordion') }} {% block field_paragraph %} {% if content.field_title_format %} {% block field_title_format %} <div {{ bem(paragraph_base_class ~ '-title', [], paragraph_blockname) }}> <h2> {{ content.field_title_format }} </h2> </div> {% endblock %} {% endif %} <div {{ bem(paragraph_base_class ~ '-paragraphs', [], paragraph_blockname, ['accordion']) }} id="Accordion{{ paragraph.id() }}"> {% for key, item in content.field_paragraph if key|first != '#' %} <div class="accordion-item"> <h2 class="accordion-header" id="heading{{ content.field_paragraph[key]['#paragraph'].id.value }}"> <button class="accordion-button {{ loop.index == accordion_opened_item ? '' : 'collapsed' }}" type="button" data-bs-toggle="collapse" data-bs-target="#collapse{{ content.field_paragraph[key]['#paragraph'].id.value }}" {{ loop.index == accordion_opened_item ? 'aria-expanded="true"' : '' }} aria-controls="collapse{{ content.field_paragraph[key]['#paragraph'].id.value }}"> {{ item['#paragraph'].field_title_format.0.value|raw }} </button> </h2> <div id="collapse{{ content.field_paragraph[key]['#paragraph'].id.value }}" class="accordion-collapse collapse {{ loop.index == accordion_opened_item ? 'show' : '' }}" aria-labelledby="heading{{ content.field_paragraph[key]['#paragraph'].id.value }}" {% if not accordion_always_open %} data-bs-parent="#Accordion{{ paragraph.id() }}" {% endif %} > <div class="accordion-body"> {% if content.field_paragraph[key]['#paragraph'].field_paragraph.storibook_content %} {{ content.field_paragraph[key]['#paragraph'].field_paragraph.storibook_content }} {% else %} {{ content.field_paragraph[key]|render }} {% endif %} </div> </div> </div> {% endfor %} </div> {% endblock %} {% endblock %}
import { COLORS } from '../../constants' import type Database from '../../structures/Database' import AliceaEmbed from '../../structures/Embed' import AliceaExt from '../../structures/Extension' import { diff } from '../../utils/object' import { toTimestamp } from '../../utils/timestamp' import { listener } from '@pikokr/command.ts' import type { GuildMember, Message, TextBasedChannel, VoiceState, } from 'discord.js' import { ActionRowBuilder, ButtonBuilder, ButtonStyle } from 'discord.js' import type { Channel, User } from 'discord.js' const isIgnored = async ( data: { id: string; channel: string }, db: Database, user?: User, channel?: Channel ) => { if (user?.bot) return true const ignoredChannels = await db.ignoredChannel.findMany({ where: { guild: data.id, }, }) const ignoredUsers = await db.ignoredUser.findMany({ where: { guild: data.id, }, }) if (ignoredChannels.some((c) => c.id === channel?.id)) return true if (ignoredUsers.some((u) => u.id === user?.id)) return true return false } class Logging extends AliceaExt { @listener({ event: 'messageUpdate' }) async messageUpdateLogger(before: Message, after: Message) { if (!before.guild) return const data = await this.db.logChannel.findUnique({ where: { id: before.guild.id, }, }) if (!data) return if (await isIgnored(data, this.db, before.author, before.channel)) return const channel = before.guild.channels.cache.get( data.channel ) as TextBasedChannel const msgDiff = diff(after, before) await channel.send({ embeds: [ new AliceaEmbed() .setTitle('Message Updated') .setColor(COLORS.YELLOW) .setDetailedAuthor(before.author) .addFields( { name: 'User', value: `<@${after.author.id}>`, inline: true }, { name: 'Channel', value: `<#${after.channelId}>`, inline: true } ) .addChunkedFields( { name: 'Original', value: msgDiff.original, }, { name: 'Updated', value: msgDiff.updated, } ) .setUNIXTimestamp(), ], components: [ new ActionRowBuilder<ButtonBuilder>().addComponents( new ButtonBuilder() .setStyle(ButtonStyle.Link) .setURL(after.url) .setLabel('Go To Message') ), ], }) } @listener({ event: 'messageDelete' }) async messageDeleteLogger(msg: Message) { if (!msg.guild) return const data = await this.db.logChannel.findUnique({ where: { id: msg.guild.id, }, }) if (!data) return if (await isIgnored(data, this.db, msg.author, msg.channel)) return const channel = msg.guild.channels.cache.get( data.channel ) as TextBasedChannel await channel.send({ embeds: [ new AliceaEmbed() .setTitle('Message Deleted') .setColor(COLORS.RED) .setDetailedAuthor(msg.author) .addFields( { name: 'User', value: `<@${msg.author.id}>`, inline: true }, { name: 'Channel', value: `<#${msg.channelId}>`, inline: true } ) .addChunkedFields({ name: 'Object', value: msg, ignore: ['author'], }) .setUNIXTimestamp(), ], }) } @listener({ event: 'guildMemberAdd' }) async memberJoinLogger(member: GuildMember) { if (!member.guild) return const data = await this.db.logChannel.findUnique({ where: { id: member.guild.id, }, }) if (!data) return if (await isIgnored(data, this.db, member.user)) return const channel = member.guild.channels.cache.get( data.channel ) as TextBasedChannel await channel.send({ embeds: [ new AliceaEmbed() .setTitle('Member Joined') .setColor(COLORS.GREEN) .setDetailedAuthor(member) .addFields( { name: 'User', value: `<@${member.user.id}>`, inline: true }, { name: 'Created At', value: `<t:${toTimestamp(member.user.createdAt)}:R>`, inline: true, } ) .addChunkedFields({ name: 'Object', value: member, ignore: ['guild'], }) .setUNIXTimestamp(), ], }) } @listener({ event: 'guildMemberRemove' }) async memberLeaveLogger(member: GuildMember) { if (!member.guild) return const data = await this.db.logChannel.findUnique({ where: { id: member.guild.id, }, }) if (!data) return if (await isIgnored(data, this.db, member.user)) return const channel = member.guild.channels.cache.get( data.channel ) as TextBasedChannel await channel.send({ embeds: [ new AliceaEmbed() .setTitle('Member Left') .setColor(COLORS.RED) .setDetailedAuthor(member) .addFields( { name: 'User', value: `<@${member.user.id}>`, inline: true, }, { name: 'Joined At', value: member.joinedAt ? `<t:${toTimestamp(member.joinedAt)}:R>` : 'N/A', inline: true, } ) .addChunkedFields({ name: 'Object', value: member, ignore: ['guild'], }) .setUNIXTimestamp(), ], }) } @listener({ event: 'voiceStateUpdate' }) async voiceJoinandLeaveLogger(oldState: VoiceState, newState: VoiceState) { if (!oldState.member || !newState.member) return const data = await this.db.logChannel.findUnique({ where: { id: newState.guild.id, }, }) if (!data) return if (await isIgnored(data, this.db, newState.member.user)) return const channel = newState.guild.channels.cache.get( data.channel ) as TextBasedChannel const embed = new AliceaEmbed() .setDetailedAuthor(newState.member) .setUNIXTimestamp() .addFields({ name: 'User', value: `<@${newState.member.user.id}>`, inline: true, }) const stateDiff = diff(newState, oldState) if (oldState.channelId && !newState.channelId) { embed .setTitle('Left Voice Channel') .setColor(COLORS.RED) .addFields({ name: 'Channel', value: `<#${oldState.channelId}>`, inline: true, }) } else if (newState.channelId && !oldState.channelId) { embed .setTitle('Joined Voice Channel') .setColor(COLORS.GREEN) .addFields({ name: 'Channel', value: `<#${newState.channelId}>`, inline: true, }) } else if ( oldState.channelId && newState.channelId && oldState.channelId !== newState.channelId ) { embed .setTitle('Moved Voice Channel') .setColor(COLORS.YELLOW) .addFields( { name: 'Old Channel', value: `<#${oldState.channelId}>`, inline: true, }, { name: 'New Channel', value: `<#${newState.channelId}>`, inline: true, } ) } else embed.setTitle('Voice State Updated').setColor(COLORS.YELLOW) await channel.send({ embeds: [ embed.addChunkedFields( { name: 'Old', value: stateDiff.original, }, { name: 'New', value: stateDiff.updated, } ), ], }) } } export const setup = async () => new Logging()