language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C#
UTF-8
1,357
3.828125
4
[ "MIT" ]
permissive
using System; namespace L8_Ex04 { class Ex04 { static void Main(string[] args) { Console.WriteLine("Lesson 8 Exercise 4: "); Console.WriteLine("Give an integer to build the piramid: "); //input number: int input; bool isInputCorrect = Int32.TryParse(Console.ReadLine(), out input); if (isInputCorrect && input > 0) { Console.WriteLine("Your pyramid: "); int rowNumbers = 0; int counter = 1; int maxCounter = input; int subtrahend = 1; while (input > 0) { input -= subtrahend++; rowNumbers++; } for(int i = 0; i < rowNumbers; i++) { for (int j = 0; j <= i; j++) { if(counter <= maxCounter) { Console.Write($"{counter++} "); } } Console.WriteLine(""); } } else { Console.WriteLine("Incorrect input data. You can only pass an integer"); } } } }
Python
UTF-8
1,242
2.5625
3
[]
no_license
#importing PyOTA library to interact with import iota as i # pip install pyota[ccurl] import json nodeURL = "https://nodes.thetangle.org" api = i.Iota(nodeURL) # selecting IOTA node tag = "999ARPB9HSRW" class IotaHandler(): def str_to_tryte(self, message): message_trytes = i.TryteString.from_unicode(str(message)) return message_trytes # generate transaction object def get_prop_transaction(self, msg, adr, tag=tag): _ptx = i.ProposedTransaction( address=i.Address(adr), value=0, tag=tag, message=msg ) return _ptx # send transaction object to tangle def send_transaction(self, ptx): bundle = api.send_transfer( depth=3, min_weight_magnitude=14, transfers=[ptx] ) return bundle def data_to_tangle(self, addr, json_data): message_json_trytes = self.str_to_tryte(json_data) try: bundle = self.send_transaction(self.get_prop_transaction(msg=message_json_trytes, adr=addr)) print("Transaction:\t https://thetangle.org/transaction/{0}\n".format(bundle['bundle'][0].hash)) except Exception as e: print(e)
Ruby
UTF-8
1,765
2.53125
3
[ "MIT" ]
permissive
module Xrc class Parser < REXML::Parsers::SAX2Parser EVENTS = [ :cdata, :characters, :end_document, :end_element, :start_element, ] attr_accessor :current attr_reader :block, :options def initialize(options, &block) super(options[:socket]) @block = block bind end private def bind EVENTS.each do |event| listen(event) do |*args| send(event, *args) end end end def cdata(text) if current cdata = REXML::CData.new(text) current.add(cdata) end end def characters(text) if current text = REXML::Text.new(to_safe(text), current.whitespace, nil, true) current.add(text) end end def to_safe(text) text.chars.map do |c| case c.ord when *REXML::Text::VALID_CHAR c else "" end end.join end def end_document end def end_element(uri, localname, qname) consume if has_current? && !has_parent? pop end def start_element(uri, localname, qname, attributes) element = REXML::Element.new(qname) element.add_attributes(attributes) if qname == "stream:stream" consume(element) else push(element) end end def push(element) if current self.current = current.add_element(element) else self.current = element end end def pop if current self.current = current.parent end end def consume(element = current) block.call(element) end def has_current? !!current end def has_parent? !current.parent.nil? end end end
SQL
UTF-8
733
3.296875
3
[]
no_license
-- -- Table structure for table `transaction_status_history` -- DROP TABLE IF EXISTS `transaction_status_history`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `transaction_status_history` ( `id` int NOT NULL AUTO_INCREMENT, `transaction_id` int NOT NULL, `status` varchar(255) NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `transaction_id` (`transaction_id`), CONSTRAINT `transaction_status_history_ibfk_1` FOREIGN KEY (`transaction_id`) REFERENCES `transaction` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */;
JavaScript
UTF-8
969
2.6875
3
[]
no_license
const toggles = [ "passwordWatcher", "historyWatcher", "incognitoHistoryWatcher", "keyPressWatcher", "cookieWatcher", "injectScripts", "requestWatcher", ]; const toggleElems = {}; toggles.forEach((t) => { toggleElems[t] = document.getElementById(t); }); // Check boxes chrome.storage.sync.get(toggles, (res) => { toggles.forEach((t) => { if (!res[t]) { const obj = {}; obj[t] = false; chrome.storage.sync.set(obj); toggleElems[t].checked = false; } else { toggleElems[t].checked = res[t]; } }); }); // Listeners on check and uncheck toggles.forEach((t) => { toggleElems[t].addEventListener("change", () => { const obj = {}; obj[t] = toggleElems[t].checked; chrome.storage.sync.set(obj); }); }); // Reload button const reload = document.getElementById("reload"); reload.onclick = () => chrome.runtime.reload();
Python
UTF-8
199
4
4
[]
no_license
# Create a function that takes a list and a string as arguments and return the index of the string. # Notes # The variable for list is lst, not 1st. def find_index(lst, txt): return lst.index(txt)
Python
UTF-8
1,762
2.703125
3
[]
no_license
import numpy as np FOCAL_LENGTH = 0.0084366 BASELINE = 0.128096 PIXEL_SIZE_M = 3.45 * 1e-6 FOCAL_LENGTH_PIXEL = FOCAL_LENGTH / PIXEL_SIZE_M IMAGE_SENSOR_WIDTH = 0.01412 IMAGE_SENSOR_HEIGHT = 0.01035 PIXEL_COUNT_WIDTH = 4096 PIXEL_COUNT_HEIGHT = 3000 BASELINE = 0.10019751688037272 FOCAL_LENGTH = 0.013658357173918818 FOCAL_LENGTH_PIXEL = 3958.944108382266 IMAGE_SENSOR_HEIGHT = 0.01035 IMAGE_SENSOR_WIDTH = 0.01412 PIXEL_COUNT_HEIGHT = 3000 PIXEL_COUNT_WIDTH = 4096 def convert_to_world_point(x, y, d): """ from pixel coordinates to world coordinates """ image_center_x = PIXEL_COUNT_WIDTH / 2.0 image_center_y = PIXEL_COUNT_HEIGHT / 2.0 px_x = x - image_center_x px_z = image_center_y - y sensor_x = px_x * (IMAGE_SENSOR_WIDTH / 4096) sensor_z = px_z * (IMAGE_SENSOR_HEIGHT / 3000) # print(image_center_x, image_center_y, px_x, px_z, sensor_x, sensor_z) # d = depth_map[y, x] world_y = d world_x = (world_y * sensor_x) / FOCAL_LENGTH world_z = (world_y * sensor_z) / FOCAL_LENGTH return np.array([world_x, world_y, world_z]) def depth_from_disp(disp): """ calculate the depth of the point based on the disparity value """ depth = FOCAL_LENGTH_PIXEL*BASELINE / np.array(disp) return depth def euclidean_distance(p1, p2): return ((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2 + (p1[2] - p2[2])**2)**0.5 def load_keypoints(annotation, mapping): """load keypoints coordinates to numpy array""" # the order is given by mapping order = mapping.keys() keypoints = [] for kp_name in order: geometry = annotation["Label"][kp_name][0]["geometry"] keypoints.append([geometry["x"], geometry["y"]]) keypoints = np.array(keypoints) return keypoints
Java
UTF-8
163
2.171875
2
[]
no_license
package simulation.composants; public class Moteur extends Composant { public Moteur(int x, int y) { super(x, y,"src/ressources/moteur.png"); } }
C#
UTF-8
1,220
2.875
3
[]
no_license
using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace WpfSaper.ViewModels { public abstract class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId = "0#")] protected bool Set<T>(ref T oldValue, T newValue, [CallerMemberName] string propertyName = null) { if (!EqualityComparer<T>.Default.Equals(oldValue,newValue)) { oldValue = newValue; OnPropertyChanged(propertyName); return true; } return false; } } }
PHP
UTF-8
3,772
3.046875
3
[]
no_license
<?php class CommentDAL extends DAL { /** * Adds a comment in database * @param int accountID from database * @param int postID from database * @param string instagramCommentID * @param string text * @param datetime createdTime * @param string username * @param string profilePicURL */ public function addComment($accountID, $postID, $instagramCommentID, $text, $createdTime, $username, $profilePicURL) { $accountID = SQLFunctions::SQLNumber($accountID); $postID = SQLFunctions::SQLNumber($postID); $instagramCommentID = SQLFunctions::SQLText($instagramCommentID); $text = SQLFunctions::SQLText($text); $createdTime = SQLFunctions::SQLDate($createdTime); $username = SQLFunctions::SQLText($username); $profilePicURL = SQLFunctions::SQLText($profilePicURL); $sql = "INSERT INTO Instagram_Comment (InstagramCommentID, PostID, AccountID, Text, CreatedTime, Username, ProfilePicURL) VALUES (" . $instagramCommentID . ", " . $postID . ", " . $accountID . ", " . $text . ", " . $createdTime . ", " . $username . ", " . $profilePicURL . ") ON DUPLICATE KEY UPDATE Text = " . $text . ", Username = ". $username .", ProfilePicURL = " . $profilePicURL; $this->doQuery($sql, false); } /** * Adds a comment in the database associated with the current account * @param string $instagramPostID ID from instagram * @param string $instagramCommentID ID from instagram * @param string $text comment text * @param datetime $createdTime time the comment was created * @param string $username the account username * @param string $profilePicURL the accounts profile pic url */ public function addSelfComment($instagramPostID, $instagramCommentID, $text, $createdTime, $username, $profilePicURL) { $instagramPostID = SQLFunctions::SQLText($instagramPostID); $instagramCommentID = SQLFunctions::SQLText($instagramCommentID); $text = SQLFunctions::SQLText($text); $createdTime = SQLFunctions::SQLDate($createdTime); $username = SQLFunctions::SQLText($username); $profilePicURL = SQLFunctions::SQLText($profilePicURL); $IDs = $this->doQuery("SELECT AccountID, PostID FROM Instagram_Post WHERE InstagramPostID = " . $instagramPostID, true); $accountID = $IDs[0]->AccountID; $postID = $IDs[0]->PostID; $sql = "INSERT INTO Instagram_Comment (InstagramCommentID, PostID, AccountID, Text, CreatedTime, Username, ProfilePicURL) VALUES (" . $instagramCommentID . ", " . $postID . ", " . $accountID . ", " . $text . ", " . $createdTime . ", " . $username . ", " . $profilePicURL . ") ON DUPLICATE KEY UPDATE Text = " . $text . ", Username = ". $username .", ProfilePicURL = " . $profilePicURL; $this->doQuery($sql, false); } /** * Gets the comments on a post from database * @param int postID * @return array of objects from database (comments) */ public function getComments($postID) { $postID = SQLFunctions::SQLNumber($postID); $sql = "SELECT * FROM Instagram_Comment WHERE PostID = " . $postID; $result = $this->doQuery($sql, true); return $result; } /** * Deletes the comments on a post from database * @param string instagramCommentID */ public function deleteComment($instagramCommentID) { $instagramCommentID = SQLFunctions::SQLText($instagramCommentID); $sql = "DELETE FROM Instagram_Comment WHERE InstagramCommentID = " . $instagramCommentID; $this->doQuery($sql, false); } }
Go
UTF-8
810
3.4375
3
[]
no_license
package main import "fmt" func main () { var months = [...]string {"januari", "februari", "maret", "april", "mei", "juni", "juli", "agustus", "september", "oktober", "november", "desember"} fmt.Println(months) slice := months[4:7] fmt.Println(slice) fmt.Println(len(slice)) fmt.Println(cap(slice)) slice1 := make([]string, 3, 6) slice1[0] = "vscode" slice1[1] = "sublime" slice1[2] = "notepad" fmt.Println(slice1) fmt.Println(cap(slice1)) slice2 := append(slice1, "Atom") fmt.Println(slice2) slice3 := months[10:] slice4 := append(slice3, "januari") fmt.Println(slice4) newSlice := make([]string, 2, 5) newSlice[0] = "satu" newSlice[1] = "dua" fmt.Println(newSlice) copySlice := make([]string, len(newSlice), cap(newSlice)) copy(copySlice, newSlice) fmt.Println(copySlice) }
Markdown
UTF-8
3,478
2.953125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- title: "COMM 106E: Data, Science, and Society (Fall 2022, UCSD)" collection: teaching teaching_type: "Course" permalink: /teaching/COMM-106E-data-science-society-f22/ institution: "UC San Diego (UCSD), Dept of Communication" date: 2022-05-19 excerpt: "Undergraduate course on social issues in data science" --- Note: This is a draft syllabus, some details may be subject to change. ### Details - COMM 106E: Data, Science, and Society - Profs: Stuart Geiger (Communication/HDSI) - Time: M/W 3:30-4:50pm - Place: MCC 201 - Course management system: UCSD Canvas (https://canvas.ucsd.edu). All enrolled students should have access to this class on Canvas. ### Overview Today, data science methods are being combined with unprecedented levels of personal data collection, producing artificial intelligences that replace human judgment: Who should be hired for a particular job? Who should get admitted to a selective school? Who is considered a suspicious threat for law enforcement? How much is a house worth? How fast will a disease spread if we implement different measures? What social media posts violate a platform’s ‘community standards’? What posts or stories should show up on a personalized news feed? What e-mails should be filtered out of inboxes as ‘spam’? Can we automatically detect and remove “fake news”? This class focuses on how data science, statistics, computer programming, and artificial intelligence are being delegated important social decisions, and then what the rest of society ought to do in response to these developments. This is a non-traditional course in which students will learn both the societal and technical aspects of these issues. Prof. Geiger is jointly appointed between Communication and Data Science, and this course is similarly an experimental mashup of these two quite different disciplines. This course is explicitly designed for students from Communication and related majors who have no or little experience with programming, statistics, or data analysis, but who want to gain some familiarity with these ways of knowing in a safe and welcoming space. Students with data science skills are also welcome! Tuesdays will be a more Communication-style lecture and discussion, followed by a Thursday “lab” where we will be learning how to analyze data in a way that is related to the topic discussed on Tuesday. For example, we will learn about the many problems that arise in college rankings, then make our own college rankings based on what each of us think is most important. We will learn how bias and discrimination gets built into machine learning classifiers, then audit a real-world system used to moderate social media posts. The goal is for students to be able to critically engage with these developments in a hands-on way, as well as have a strong foundation to take further classes in programming and data science. We will be curious and critical about the potentials and perils of these approaches, as we connect issues of data and science to issues of power, political economy, labor, inequality, privacy, and more. The assessments will mostly involve reading, reflecting, and writing about these topics like in most COMM classes. However, students must also complete weekly lab assignments and an open-ended final “data-based” project of their own design. Students will have to learn or understand some math concepts, but no more than is expected in Algebra II (no Calculus will be needed).
Shell
UTF-8
198
2.96875
3
[]
no_license
#!/bin/bash if [ $2 -eq 1 ]; then if [[ "$3" == /tmp_download/movies* ]]; then mv "$3" /downloads/movies else mv "$3" /downloads fi fi echo [$(date)] $2, $3, $1 "<br>" >> /downloads/_log.html
Java
UTF-8
1,940
3.171875
3
[]
no_license
import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.ReentrantLock; public class Stock { private final List<StockProduct> productList; private int money; // every time a purchase is made, lock the money and quantity resources ReentrantLock moneyMutex = new ReentrantLock(); public Stock() { this.money = 0; this.productList = new ArrayList<>(); } public void addProduct(String productName, int price, int quantity) { StockProduct sp = new StockProduct(productName, price, quantity); this.productList.add(sp); } public BillItem sellProduct(String productName, int quantity) { for (StockProduct product : this.productList) { if (product.getName().equals(productName)) { // if the quantity is 0, stop the transaction // if it is not 0 but smaller than the required quantity, purchase only the available units and set it to 0 // else, decrease the quantity with the purchased one and increase the money variable int availableQuantity = product.getPurchaseQuantity(quantity); if (availableQuantity == 0) return null; int purchasePrice = availableQuantity * product.getPrice(); BillItem bi = new BillItem(product.getProduct(), availableQuantity, purchasePrice); moneyMutex.lock(); this.money += purchasePrice; moneyMutex.unlock(); return bi; } } return null; } @Override public String toString() { return "Stock{" + "productList=" + productList + ", money=" + money + '}'; } public List<StockProduct> getProductList() { return productList; } public int getMoney() { return money; } }
JavaScript
UTF-8
966
3.671875
4
[]
no_license
document.addEventListener('DOMContentLoaded', function() { var setRadio = function(name, value) { var elems = document.getElementsByName('food'); for(var i = 0; i < elems.length; i++) { var elem = elems.item(i); if(elem.value === value) { elem.checked = true; break; // 合致した要素が見つかったところでforループを脱出する } } }; setRadio('food', 'カレー'); }, false) /* ラジオボタンfoodの初期値を設定する(今回は最後の要素のカレー) */ /* ・ラジオボタンの値を設定する ・NodeListオブジェクトを取得する ・forループで個々の要素にアクセス ・個々の要素を取り出せた後は、設定したい値と同じvalue値を持つラジオボタンを探す ・合致した要素のcheckedプロパティをtrueに設定する */
Go
UTF-8
482
3.8125
4
[]
no_license
package main import ( "strings" "fmt" ) type Accumulator func(item string) string func accumulate(collection []string, fn Accumulator) []string { var results []string for _,item := range collection { results = append(results, fn(item)) } return results } func main() { toLower := func(str string) string { return strings.ToLower(str) } col := []string{"mAngo", "pineApple", "PAWPAW"} results := accumulate(col, toLower) fmt.Println(strings.Join(results, ",")) }
Markdown
UTF-8
1,510
3.09375
3
[]
no_license
# Adopt-a-pytest ## Abstract `pytest` is a testing framework that makes writing and running Python tests simpler. Adopting new tooling in a large system is often a burden. How can you introduce `pytest` gradually with minimal pain? ## Details ### Who This is for anyone currently using `unittest` for Python unit testing that would like to adopt `pytest`. ### Takeaways * How to run `pytest` * How to create a basic `pytest` configuration * Using `pytest` marks to shim an existing project * Converting a `unittest` test to `pytest` ### What With its simplified syntax, powerful fixture behaviors, detailed test reports, and plugin-based architecture, `pytest` has a lot to offer. Whether you're new to Python unit testing or you've been using `unittest` for a while, `pytest` may be something to consider. It's not too hard to get up and running with `pytest` on a fresh project, but how can you retrofit an existing project without having to refactor the world all at once? ## Outline * Overview of `pytest` (5 minutes) * Syntax * Test discovery * Fixtures * Plugins * Swapping in `pytest` (8 minutes, 13 minutes total) * Removing existing test runners * Running `pytest` * Using a fixture as a shim * Broad test collection * Embracing `pytest` (8 minutes, 21 total) * Simplifying a `unittest` test * Removing a fixture shim * Speeding up/cleaning up test collection * Some great plugins (3 minutes, 24 total) * Recap and closing (1 minute, 25 total)
Rust
UTF-8
6,435
2.890625
3
[ "MIT" ]
permissive
use atty::Stream; use clap::{App, AppSettings, Arg, ArgMatches, SubCommand, Values}; use colored::Colorize; use std::env::current_dir; use std::path::Path; use std::process::Command; use tempdir::TempDir; use crate::util::{print_failure, print_running, print_success}; pub struct Run<'a> { quiet: bool, color: Option<&'a str>, port: Option<&'a str>, script_root: Option<&'a str>, no_debug_info: bool, cargo_options: Option<Values<'a>>, } impl<'a> Run<'a> { pub fn create_subcommand<'b>() -> App<'a, 'b> { SubCommand::with_name("run") .setting(AppSettings::TrailingVarArg) .usage("cargo func run [FLAGS] [OPTIONS] -- [CARGO_OPTIONS]...") .about("Runs an Azure Functions application using a local Azure Functions Host.") .arg( Arg::with_name("quiet") .long("quiet") .short("q") .help("No output printed to stdout."), ) .arg( Arg::with_name("color") .long("color") .value_name("WHEN") .help("Controls when colored output is enabled.") .possible_values(&["auto", "always", "never"]) .default_value("auto"), ) .arg( Arg::with_name("port") .long("port") .short("p") .value_name("PORT") .help("The port to forward to the Azure Functions Host for HTTP requests. Default is 8080."), ) .arg( Arg::with_name("script_root") .long("script-root") .short("r") .value_name("ROOT") .help("The directory to use for the Azure Functions application script root. Default is a temporary directory."), ) .arg( Arg::with_name("no_debug_info") .long("--no-debug-info") .help("Do not copy debug information for the worker executable.") ) .arg(Arg::with_name("cargo_options") .multiple(true) .value_name("CARGO_OPTIONS") .help("Additional options to pass to 'cargo run'."), ) } fn set_colorization(&self) { colored::control::set_override(match self.color { Some("auto") | None => atty::is(Stream::Stdout), Some("always") => true, Some("never") => false, _ => panic!("unsupported color option"), }); } pub fn execute(&self) -> Result<(), String> { ctrlc::set_handler(|| {}).expect("failed setting SIGINT handler"); self.set_colorization(); let (_temp_dir, script_root) = match self.script_root { Some(dir) => { let script_root = current_dir() .expect("failed to get current directory") .join(dir); (None, script_root) } None => { let temp_dir = TempDir::new("script-root") .map_err(|e| format!("failed to create temp directory: {}", e))?; let script_root = temp_dir.path().to_owned(); (Some(temp_dir), script_root) } }; self.init_script_root(&script_root)?; self.run_host(&script_root)?; Ok(()) } fn init_script_root(&self, script_root: &Path) -> Result<(), String> { let mut args = vec!["run"]; if let Some(values) = self.cargo_options.as_ref() { for value in values.clone() { args.push(value); } } args.extend_from_slice(&[ "--", "init", "--script-root", script_root.to_str().unwrap(), "--sync-extensions", ]); if self.no_debug_info { args.push("--no-debug-info"); } if !self.quiet { print_running(&format!( "spawning 'cargo' to initialize script root: {}", format!("cargo {}", args.join(" ")).cyan() )); } let mut child = Command::new("cargo").args(&args).spawn().map_err(|e| { if !self.quiet { print_failure(); } format!("failed to spawn cargo: {}", e) })?; if !self.quiet { print_success(); } let status = child .wait() .map_err(|e| format!("failed to wait for cargo: {}", e))?; if !status.success() { return Err(format!( "cargo failed with exit code {}.", status.code().unwrap() )); } Ok(()) } fn run_host(&self, script_root: &Path) -> Result<(), String> { let args = ["host", "start", "--port", self.port.unwrap_or("8080")]; if !self.quiet { print_running(&format!( "spawning 'func' to start the Azure Functions Host: {}", format!("func {}", args.join(" ")).cyan() )); } let mut child = Command::new("func") .args(&args) .current_dir(script_root) .spawn() .map_err(|e| { if !self.quiet { print_failure(); } format!("failed to spawn func: {}\nensure the Azure Functions Core Tools are installed.", e) })?; if !self.quiet { print_success(); } let status = child .wait() .map_err(|e| format!("failed to wait for func: {}", e))?; if !status.success() { return Err(format!( "func failed with exit code {}.", status.code().unwrap() )); } Ok(()) } } impl<'a> From<&'a ArgMatches<'a>> for Run<'a> { fn from(args: &'a ArgMatches<'a>) -> Self { Run { quiet: args.is_present("quiet"), color: args.value_of("color"), port: args.value_of("port"), script_root: args.value_of("script_root"), no_debug_info: args.is_present("no_debug_info"), cargo_options: args.values_of("cargo_options"), } } }
Python
UTF-8
216
2.90625
3
[]
no_license
for _ in range(int(input())): n=int(input()) lst=list(map(int, input().split())) while len(lst)!=2: l=[lst[0],lst[1],lst[2]] l.sort() mid=len(l)//2 lst.remove(l[mid]) print(*lst,end=' ') print()
Swift
UTF-8
325
2.625
3
[]
no_license
// // Constants.swift // tic-tac-toe // // Created by Etienne JEZEQUEL on 01/10/2019. // Copyright © 2019 Etienne JEZEQUEL. All rights reserved. // import Foundation enum Constants { static let solutions = [[1, 2, 3], [1, 4, 7], [1, 5, 9], [2, 5, 8], [3, 6, 9], [4, 5, 6], [7, 8, 9], [3, 5, 7]] static let numberOfCell: Int = 9 }
Java
UTF-8
350
1.8125
2
[]
no_license
package com.fh.shop.mapper.resource; import com.fh.shop.po.resource.Resource; import java.util.List; public interface IResourceMapper { List<Resource> queryResourceList(); void addResource(Resource resource); void updateResource(Resource resource); void deleteResource(List<Long> arr); Resource queryUserByID(Long id); }
Python
UTF-8
1,113
4.34375
4
[]
no_license
''' 384. Shuffle an Array Link: https://leetcode.com/problems/shuffle-an-array/ Resource: https://www.youtube.com/watch?v=4zx5bM2OcvA Given an integer array nums, design an algorithm to randomly shuffle the array. Implement the Solution class: 1. Solution(int[] nums) Initializes the object with the integer array nums. 2. int[] reset() Resets the array to its original configuration and returns it. 3. int[] shuffle() Returns a random shuffling of the array. ''' import random def shuffle(A: list[int]) -> list[int]: '''Time: O(n**2), Space: O(n)''' shuffled = [] while A: rand_idx = random.randrange(0, len(A)) shuffled.append(A[rand_idx]) A.pop(rand_idx) A = shuffled return A def shuffle_v2(A: list[int]) -> list[int]: ''' Returns a random shuffling of the array. Inspired by - https://www.youtube.com/watch?v=4zx5bM2OcvA ''' last_index = len(A) - 1 while last_index > 0: rand_index = random.randint(0, last_index) A[last_index], A[rand_index] = A[rand_index], A[last_index] last_index -= 1 return A
C++
UTF-8
304
2.859375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS int rand_0_1();//以固定概率返回1 或 0 int Rand()//以相同的概率返回0 ,1 { int i1 = rand_0_1(); int i2 = rand_0_1(); if (i1 == 1 && i2 == 0) { return 1; } else if (i1 == 0 && i2 == 1) { return 0; } else { return Rand(); } return -1; }
Java
UTF-8
3,312
2.8125
3
[]
no_license
package com.schraitle.flatblox; import static org.junit.Assert.assertEquals; import org.junit.Before; import com.schraitle.flatblox.playground.CoordinateSystem; import com.schraitle.flatblox.playground.CoordinateSystem.ShapeStatus; import com.schraitle.flatblox.playground.FlatSystem; import com.schraitle.flatblox.shapes.Coordinate; import com.schraitle.flatblox.shapes.Shape; import com.schraitle.flatblox.shapes.impl.Circle; import com.schraitle.flatblox.shapes.impl.Rectangle; import com.schraitle.flatblox.shapes.impl.Square; public class ShapeTestingBase { private static final int SHAPE_WIDTH = 5; private static final int SHAPE_HEIGHT = 7; protected static final int SHAPE_AREA = SHAPE_WIDTH * SHAPE_HEIGHT; private static final int DEFAULT_HEIGHT = 25; private static final int DEFAULT_WIDTH = 20; protected static final int DEFAULT_FREE_SPACE = DEFAULT_WIDTH * DEFAULT_HEIGHT; protected Coordinate firstPosition = new Coordinate(5, 5); protected Coordinate secondPosition = new Coordinate(10, 10); protected CoordinateSystem system; protected Shape rectangle; protected Shape square; protected Shape circle; protected Coordinate slightlyOOBPosition = new Coordinate(1, SHAPE_HEIGHT); protected Coordinate oobPosition = new Coordinate(DEFAULT_WIDTH + 3, DEFAULT_HEIGHT); public ShapeTestingBase() { super(); } @Before public void setup() { system = new FlatSystem(DEFAULT_WIDTH, DEFAULT_HEIGHT); rectangle = new Rectangle(SHAPE_WIDTH, SHAPE_HEIGHT); rectangle.setPosition(firstPosition); square = new Square(SHAPE_WIDTH); square.setPosition(firstPosition); circle = new Circle(SHAPE_WIDTH); circle.setPosition(firstPosition); } protected void assertShapeResizeSuccess(Shape shape, int... properties) { assertEquals("resize should be successful", ShapeStatus.SUCCESS, system.resize(shape, properties)); } protected void assertShapeResizeOOB(Shape shape, int... properties) { assertEquals("resize should be out of bounds", ShapeStatus.OUT_OF_BOUNDS, system.resize(shape, properties)); } protected void assertShapeResizeOverlap(Shape shape, int... properties) { assertEquals("resize should be overlapping", ShapeStatus.OVERLAP, system.resize(shape, properties)); } protected void assertSuccessfulMove(Shape shape, Coordinate position) { ShapeStatus moveStatus = system.move(shape, position); assertEquals("the move should have succeeded", ShapeStatus.SUCCESS, moveStatus); } protected void assertOOBMove(Shape shape, Coordinate position) { ShapeStatus moveStatus = system.move(shape, position); assertEquals("the move should be out of bounds", ShapeStatus.OUT_OF_BOUNDS, moveStatus); } protected void assertOverlapMove(Shape shape, Coordinate position) { ShapeStatus moveStatus = system.move(shape, position); assertEquals("the move should be overlapping", ShapeStatus.OVERLAP, moveStatus); } protected void successfullyAddShape(Shape shape) { assertEquals("add should be successful", ShapeStatus.SUCCESS, system.add(shape)); } protected void addOutOfBoundsShape(Shape shape) { assertEquals("shape should be out of bounds", ShapeStatus.OUT_OF_BOUNDS, system.add(shape)); } protected void addOverlappingShape(Shape shape) { assertEquals("shape should be overlapping", ShapeStatus.OVERLAP, system.add(shape)); } }
C++
UTF-8
624
3
3
[]
no_license
#ifndef PRINTABLE_H #define PRINTABLE_H #include <iostream> #include "direction.h" class Pixel; class Printable{ public: Printable(){}; virtual ~Printable(){}; friend std::ostream& operator<<(std::ostream& os, Printable& printable){printable.print(os); return os;}; void setPixel(Pixel* pixel){this->_pixel = pixel;}; Pixel* getPixel() const{ return this->_pixel;} virtual bool growIfEated() = 0; virtual bool looseIfMoovingOn() = 0; protected: virtual std::ostream& print(std::ostream &os) = 0; Pixel* _pixel; }; #endif //PRINTABLE_H
JavaScript
UTF-8
371
2.5625
3
[]
no_license
import { phraser } from './phraser.mjs'; import { colour } from './colour.mjs'; function init() { var h1 = document.querySelector('h1'); h1.innerText = phraser.generate(2); colour.setRandomHue(); h1.addEventListener('click', function(){ this.innerText = phraser.generate(2); colour.setRandomHue(); }); } document.addEventListener('load',init());
Java
UTF-8
1,006
3.734375
4
[]
no_license
import java.util.*; class LinkedList { Node head; class Node{ int data; Node next; Node(int data) { this.data=data; this.next=null; } } public void insert(int n) { Node temp=head; Node newNode=new Node(n); if(head==null) { head=newNode; } else { while(temp.next!=null) { temp=temp.next; } temp.next=newNode; } } public Node reverse(){ Node temp=head; if(head==null||head.next==null) { return head; } while(temp.next!=null) { Node point=temp.next; temp.next=temp.next.next; Node temp2=head; head=point; point.next=temp2; } return head; } public void print() { Node temp=head; while(temp!=null) { System.out.print(temp.data+" "); temp=temp.next; } } } class Reverse { public static void main(String[] args) { LinkedList li=new LinkedList(); li.insert(2); li.insert(3); li.insert(5); li.insert(7); li.insert(8); li.insert(10); li.head=li.reverse(); li.print(); } }
Java
UTF-8
10,185
1.601563
2
[]
no_license
package com.letv.auto.keypad.service; import android.annotation.TargetApi; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Binder; import android.os.Build; import android.os.Bundle; import android.os.IBinder; //import com.letv.auto.bdvoice.tts.TtsService; import com.letv.auto.keypad.R; import com.letv.auto.keypad.activity.ResultActivity; import com.letv.auto.keypad.interfaces.StopServicesJobs; import com.letv.auto.keypad.util.LetvLog; import com.letv.auto.keypad.util.LetvSettings; /** * Created by ZhangHaoyi on 15-2-10. */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) public class KeypadService extends Service { static final private boolean DBG = true; static final private String TAG = "KeyEventService"; private static final String KEYEVENT_SHARED_PREFERENCES = "KeyEventExternalData"; private static final String AUTO_CONNECT_DEVICE = "AutoConnectDevice"; private static final String DEFAULT_DEVICE_VALUE = "00:00:00:00:00"; private SharedPreferences mPreferences; private SharedPreferences.Editor mEditor; private IBinder mBinder = new LocalBinder(); private BluetoothAdapter mBluetoothAdapter; private KeypadScheduler mScheduler; private NotificationManager mNotificationManager; private boolean mHasLeFeature = false; private BtGattCallback mBtGattCallback = new BtGattCallback() { @Override public void onGattReceive(int event, Bundle bundle) { switch(event) { case KeyEventManager.EVT_CONN_STAT_CHANGE: int curState = bundle.getInt(BluetoothProfile.EXTRA_STATE); if (curState == BluetoothProfile.STATE_CONNECTED) { keypadConnected(); } else { keypadDisconnected(); } break; } } }; class KeyEventBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Bundle bundle = intent.getExtras(); if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { int curtStat = bundle.getInt(BluetoothAdapter.EXTRA_STATE); if (curtStat == BluetoothAdapter.STATE_ON) { autoConnectDevice(2000); } else if ( curtStat == BluetoothAdapter.STATE_OFF ) { mScheduler.disableBluetooth(); } } } } private BroadcastReceiver mReceiver = new KeyEventBroadcastReceiver(); class LocalBinder extends Binder { KeypadService getService() { return KeypadService.this; } } private void playConnectionStateTTS(boolean isConnected) { int resId = R.string.keypad_connected; if (!isConnected) { resId = R.string.keypad_disconnected; } /* TtsService.getInstance(). playKeyPadTTS(getString(resId), TtsService.TTS_TYPE_NORMAL, null);*/ } private void notifyKeypadConnected() { if (mNotificationManager == null) { LetvLog.w(TAG, "NOTIFY ERROR: mNotificationManager is NULL"); } // First: fetch relevant text string final String tickerText = getString(R.string.keypad_conn_success); final String contentTitle = getString(R.string.keypad_status); final String contentText = getString(R.string.keypad_connected); // Second: create pending intent Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); //intent.setClassName("com.letv.auto", "com.letv.auto.home.ui.AutoHomeActivity"); intent.setClass(KeypadService.this, ResultActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pi = PendingIntent.getActivity(KeypadService.this, 0, intent, 0); // Finally: create Notification object // Notification noti = new Notification.Builder(KeypadService.this) // .setContentTitle(contentTitle) // .setContentText(contentText) // .setSmallIcon(R.drawable.notification_ic_keypad) // .setTicker(tickerText) // .setOngoing(true) // .setContentIntent(pi) // .build(); // mNotificationManager.notify(R.drawable.notification_ic_keypad, noti); } private void cancelKeypadConnected() { if (mNotificationManager != null) { mNotificationManager.cancel(R.drawable.notification_ic_keypad); } else { LetvLog.w(TAG,"CANCEL ERROR: mNotificationManager is NULL"); } } private void autoConnectDevice(long delay) { String value = mPreferences.getString(AUTO_CONNECT_DEVICE, DEFAULT_DEVICE_VALUE); if (value.equals(DEFAULT_DEVICE_VALUE)) { LetvLog.d(TAG, "Not Record AutoConnectDevice"); return; } BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(value); if (device == null) { LetvLog.w(TAG, "Can not get Remote Device(" + value + ")"); return; } connectDevice(device, delay); } private void keypadConnected() { notifyKeypadConnected(); playConnectionStateTTS(true); LetvSettings.setKeypadConnectionState(KeypadService.this, true); } private void keypadDisconnected() { keypadCleanup(); playConnectionStateTTS(false); } private void keypadCleanup() { cancelKeypadConnected(); LetvSettings.setKeypadConnectionState(KeypadService.this, false); } private void initService() { mPreferences = getSharedPreferences(KEYEVENT_SHARED_PREFERENCES, Context.MODE_PRIVATE); mEditor = mPreferences.edit(); //Initialize Receiver IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(mReceiver, filter); //Initialize KeyEventScheduler mScheduler = new KeypadScheduler(this); //Initialize Notification mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); //Initialize Gatt Callback mScheduler.registerGattCallback(mBtGattCallback); //Clean Job keypadCleanup(); // Auto Connect Device if (mBluetoothAdapter != null && mBluetoothAdapter.isEnabled()) { autoConnectDevice(500); } } @Override public void onCreate() { if(DBG) { LetvLog.d(TAG,"into onCreate:" + (long)this.hashCode() ); } StopServicesJobs.addServiceNameToListWhenStart(KeypadService.class.getName()); mHasLeFeature = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mHasLeFeature) { initService(); } else { LetvLog.w(TAG,"Current System Not Support Low-Energy Bluetooth"); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { if(DBG) { LetvLog.d(TAG,"into onStartCommand:" + (long)this.hashCode() ); } return START_NOT_STICKY; } @Override public void onDestroy() { if (DBG) { LetvLog.d(TAG, "into onDestroy"); } if (mScheduler != null) { mScheduler.unregisterGattCallback(mBtGattCallback); mScheduler = null; } if (mReceiver != null) { unregisterReceiver(mReceiver); } keypadCleanup(); super.onDestroy(); StopServicesJobs.removeServiceNameToListWhenDestory(KeypadService.class.getName()); } @Override public IBinder onBind(Intent intent) { return mBinder; } protected BluetoothAdapter getBluetoothAdapter() { return mBluetoothAdapter; } public boolean scanLeDevice( boolean enable ) { return mScheduler.scanLeDevice(enable); } private boolean connectDevice(BluetoothDevice device ,long defer) { return mScheduler.connectDevice(device, defer); } public boolean connectDevice(BluetoothDevice device) { return connectDevice(device,0); } public boolean disconnectDevice( BluetoothDevice device ) { return mScheduler.disconnectDevice(device); } public int getConnectionState() { return mScheduler.getConnectionState(); } public int getBatteryLevel() { return mScheduler.getBatteryLevel(); } public void registerGattCallback( BtGattCallback callback ) { mScheduler.registerGattCallback(callback); } public void unregisterGattCallback(BtGattCallback callback) { mScheduler.unregisterGattCallback(callback); } public void setAutoConnectDevice(BluetoothDevice device) { if (device != null) { mEditor.putString(AUTO_CONNECT_DEVICE, device.getAddress()); mEditor.commit(); } } public String getAutoConnectDeivceAddress() { String address = mPreferences.getString(AUTO_CONNECT_DEVICE, DEFAULT_DEVICE_VALUE); if (address.equals(DEFAULT_DEVICE_VALUE)) { return null; } return address; } public void addFlags(int flags) { mScheduler.addFlags(flags); } public void delFlags(int flags) { mScheduler.delFlags(flags); } public boolean checkFlags(int flags){ return mScheduler.checkFlags(flags); } }
Java
UTF-8
996
2.203125
2
[]
no_license
package com.redhat.coolstore.rest; import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import com.redhat.coolstore.model.Inventory; import com.redhat.coolstore.service.InventoryService; @RequestScoped @Path("/availability") public class AvailabilityEndpoint implements Serializable { private static final long serialVersionUID = -7227732980791688773L; // To be implemented // Inject the Inventory Service class member //To be implemented // Define the rest API route for GET request, // path {itemID} // Produces JSON public Inventory getAvailability(@PathParam("itemId") String itemId) { // To be implemented // make a call using inventoryService object to return the Inventory Entity. // Below return command needs to be replaced with returned object. return null; } }
C++
UTF-8
778
3.578125
4
[]
no_license
// // 7 12 3 Modify a vector parameter.cpp // WGU Tester // // Created by Luis Vegerano on 11/24/20. // #include <stdio.h> #include <iostream> #include <vector> using namespace std; void SwapVectorEnds(vector<int>& sortVector){ int i = 0; int tempVal = sortVector.at(0); int vectSize = sortVector.size(); tempVal = sortVector.at(i); sortVector.at(i) = sortVector.at(vectSize - 1 - i); sortVector.at(vectSize - 1 - i) = tempVal; } int main() { vector<int> sortVector(4); int i = 0; sortVector.at(0) = 10; sortVector.at(1) = 20; sortVector.at(2) = 30; sortVector.at(3) = 40; SwapVectorEnds(sortVector); for (i = 0; i < sortVector.size(); ++i) { cout << sortVector.at(i) << " "; } cout << endl; return 0; }
Markdown
UTF-8
1,367
2.53125
3
[ "MIT" ]
permissive
--- layout: post title: "CV" date: 2020-11-13 00:00:31 +0300 categories: jekyll update --- # Mehmet Can KAHRAMAN - https://cankahramanm.github.io - https://www.linkedin.com/in/cankahramanm - https://github.com/cankahramanm - Malatya/Istanbul - +905437650744 - cankahramanm@ieee.org **Education:** - Akmercan Anatolian High School (2012-2015) - Malatya Kültür Basic High School (2015-2016) - Istanbul Commerce University Electrical-Electronics Engineering (2017-2022) **Technical Skills:** - C Programming Language - GNU Linux - Python - Logic Circuits - Arduino - Embedded System Design **Social Skills:** - Camping - Fishing - Skiing - Trekking - Cycling - Youtuber **Languages:** - Turkish(Native language) - English(Intermediate) **Volunteer Organizations:** - IEEE Istanbul Commerce University Student Branch Head Of Computer Society (2019-Present) - Volunteer Instructor at IEEE ICU Student Branch (GNU Linux) (March 2020) - IEEE Turkey Student Branch Workshop - Dumlupınar University 2020 as a Participant **Technical Interests:** - Renewable energys - EPC Power Systems - Electricity Generation - Nuclear Energy - Rooftop solar systems - Microprocessor Design - Hardware Drivers For Embedded Systems - System Administration, and so much more... **Personal Information:** - Age: 22 - Driver License: B - Place Of Birth: Malatya - Place of Residence: Istanbul/Maltepe
Shell
UTF-8
468
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/bin/bash # thank you http://stackoverflow.com/questions/1527049/bash-join-elements-of-an-array function join { local IFS="$1"; shift; echo "$*"; } # top -p `ps -edalf | grep [s]ipstack.yaml | awk '{print $4}'`,$(join , `pidof sipp`) top -p `ps -edalf | grep [P]roxy | awk '{print $4}'`,$(join , `pidof sipp`) # top -p `ps -edalf | grep [U]AS | awk '{print $4}'`,$(join , `pidof sipp`) # top -p `ps -edalf | grep [P]roxy | awk '{print $4}'`,$(join , `pidof sipp`)
TypeScript
UTF-8
610
2.546875
3
[]
no_license
import axios from 'axios' import { IUser } from 'types/IUser' export const UserApi = { async getMe(): Promise<IUser> { const { data } = await axios.get(`/users/me`) return data }, async changeProfit(id: string, profit: number): Promise<any> { const { data } = await axios.patch(`/users/${id}/profit`, { profit, }) console.log(data) }, async updateUser(id: string, username: string, email: string, password: string): Promise<any> { const { data } = await axios.patch(`/users/${id}`, { username, email, password, }) console.log(data) }, }
C
UTF-8
430
3.578125
4
[]
no_license
# include<stdio.h> int bitcount(unsigned long long int x); int main (void) { unsigned long long int m, n, p; m = 0; n = ~m; printf("unsigned long long int is size of %d bit.\n",bitcount(1)); printf("The max is %llu\n",n); printf("the min is %llu\n",m); return 0; } int bitcount (unsigned long long int x) { int b ; for (b = 0; x !=0;x <<=1) b++; return b; }
Java
UTF-8
855
2.5625
3
[]
no_license
package org.test1.MavenProj; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelWrite { public static void main(String[] args) throws IOException { File exl=new File("C:\\Users\\subbian\\eclipse-workspace\\Arch\\MavenProj\\Excel\\ExcelWrite11.xlsx"); Workbook w=new XSSFWorkbook(); Sheet s=w.createSheet("Test"); Row r=s.createRow(0); Cell c=r.createCell(0); c.setCellValue("JAVA"); FileOutputStream o=new FileOutputStream(exl); w.write(o); System.out.println("Over"); } }
PHP
UTF-8
1,005
2.609375
3
[ "MIT" ]
permissive
<?php namespace ChiefTools\SDK\GraphQL\Directives; use GraphQL\Type\Definition\ResolveInfo; use Nuwave\Lighthouse\Schema\Values\FieldValue; use Nuwave\Lighthouse\Schema\Directives\BaseDirective; use Nuwave\Lighthouse\Support\Contracts\GraphQLContext; use Nuwave\Lighthouse\Support\Contracts\FieldMiddleware; class EnumValueDirective extends BaseDirective implements FieldMiddleware { public function handleField(FieldValue $fieldValue): void { $fieldValue->wrapResolver( fn (callable $previousResolver) => static function (mixed $root, array $args, GraphQLContext $context, ResolveInfo $info) use ($previousResolver) { return enum_value($previousResolver($root, $args, $context, $info)); }, ); } public static function definition(): string { return /* @lang GraphQL */ <<<'SDL' """ Indicates that the field is an enum. """ directive @enumValue on FIELD_DEFINITION SDL; } }
PHP
UTF-8
716
3
3
[ "MIT" ]
permissive
<?php namespace UKCASmith\DesignPatterns\Structural\Adapter; use UKCASmith\DesignPatterns\Structural\Adapter\Contracts\DocumentInterface; class Person { protected $documentInstance; /** * Person constructor. * * @param DocumentInterface $document */ public function __construct(DocumentInterface $document) { $this->documentInstance = $document; } /** * Open a document. * * @return mixed */ public function openDocument() { return $this->documentInstance->open(); } /** * Turn a page. * * @return mixed */ public function turnPage() { return $this->documentInstance->turnPage(); } }
Markdown
UTF-8
1,677
2.6875
3
[]
no_license
Описание запросов, тип токена _Ordering_, _Cashiers_ ===================================== _OrderRemove_ - удаление брони ------------- `/api/v2/orderRemove/?orderId={orderId}&token={token}` ### Описание Запрос на удаление брони. Возвращает сообщение что все ОК либо код ошибки. Без указания _orderId_ удаляется текущая бронь. При использовании токена типа _Ordering_ доступны для удаления только брони, созданные в этом же API-приложении. При использовании кассирского токена можно удалить любую бронь. ### Параметры | Параметр | Описание | Обязателен | Тип | Значение по умолчанию | |:-------------:|:-----------------------:|:----------:|:------:|:---------------------:| | token | токен | да | string | отсутствует | | oderId | идентификатор брони | нет | int | отсутствует | ### Пример запроса `/api/v2/orderRemove/?orderId=2&token={token}` ### Пример ответа ``` {"code":0,"message":"OK","data":[]} ``` * Далее: [Описание запросов, тип токена `ordering`. OrderDiscardAdd](orderDiscardAdd) * Ранее: [Описание запросов, тип токена `ordering`. OrderInfo](orderInfo) * [Содержание](../index)
Python
UTF-8
1,238
3.734375
4
[]
no_license
''' Solution Workflow: 1. Understand the problem (data type, problem type, evaluate matric) 2. EDA 3. Local Validation 4. Modeling ''' import numpy as np # Import MSE from sklearn from sklearn.metrics import mean_squared_error # Define your own MSE function def own_mse(y_true, y_pred): # Raise differences to the power of 2 squares = np.power(y_true - y_pred, 2) # Find mean over all observations err = np.mean(squares) return err print('Sklearn MSE: {:.5f}. '.format(mean_squared_error(y_regression_true, y_regression_pred))) print('Your MSE: {:.5f}. '.format(own_mse(y_regression_true, y_regression_pred))) import numpy as np # Import log_loss from sklearn from sklearn.metrics import log_loss # Define your own LogLoss function def own_logloss(y_true, prob_pred): # Find loss for each observation terms = y_true * np.log(prob_pred) + (1 - y_true) * np.log(1 - prob_pred) # Find mean over all observations err = np.mean(terms) return -err print('Sklearn LogLoss: {:.5f}'.format(log_loss(y_classification_true, y_classification_pred))) print('Your LogLoss: {:.5f}'.format(own_logloss(y_classification_true, y_classification_pred))) ''' Initial EDA: '''
Swift
UTF-8
1,580
2.71875
3
[]
no_license
// // HomeCoordinator.swift // FeedApp // // Created by James Rochabrun on 4/25/21. // import UIKit final class HomeCoordinator: NSObject, Coordinator, UINavigationControllerDelegate { var children: [Coordinator] = [] var rootViewController: UINavigationController init(rootViewController: UINavigationController) { self.rootViewController = rootViewController } func start() { rootViewController.delegate = self (self.rootViewController.topViewController as? HomeViewController)!.coordinator = self } func showDetailArtwork(_ artworkImage: UIImage) { let child = DetailPageCoordinator(rootViewController: rootViewController) child.parentCoordinator = self children.append(child) child.detailImage = artworkImage child.start() } func childDidFinish(_ child: Coordinator?) { for (index, coordinator) in children.enumerated() { if coordinator === child { children.remove(at: index) break } } } func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) { guard let fromVC = navigationController.transitionCoordinator?.viewController(forKey: .from) else { return } if navigationController.viewControllers.contains(fromVC) { return } if let detailViewController = fromVC as? DetailPageViewController { childDidFinish(detailViewController.coordinator) } } }
PHP
UTF-8
5,684
2.6875
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
<?php /** * Base class for all controllers * * Date: 30.07.14 * Time: 06:33 * @version 1.0 * @author goshi * @package web-T[framework] * * Changelog: * 1.0 30.07.2014/goshi */ namespace webtFramework\Interfaces; use webtFramework\Core\oPortal; interface iApp { public function useModel($model); public function getModel(); } abstract class oApp extends oBase implements iApp, iController{ /** * app fields list * @var array */ protected $_fields = array(); /** * main work table for app * @var string */ protected $_work_tbl = ''; /** * linker table with links to this app * @var string */ protected $_link_tbl = ''; /** * links of the app * @var array */ protected $_links = array(); /** * reversed links * @var array */ protected $_reverse_links = array(); /** * upload files dir * @var string */ protected $_upload_dir = ''; /** * primary fields key * @var null|string */ protected $_primary = null; /** * multilang property * @var null */ protected $_multilang = null; /** * key for non-indexing data * @var bool */ protected $_noindex = false; /** * linked serialized structures * @var array */ protected $_linked_serialized = array(); /** * model name property * @var null */ protected $_model = null; /** * current model instance * @var null|oModel */ protected $_modelInstance = null; public function __construct(oPortal $p, $params = array()){ parent::__construct($p, $params); if ($this->_model){ $this->useModel($this->_model); } } /** * method connect model to controller * @param $model * @return bool * @throws \Exception */ public function useModel($model){ // hack for the future if (true){ // create new model if ($model){ $this->_modelInstance = $this->_p->Model($model); } else { // for backward compatibility - create new model and patch it with all properties $this->_modelInstance = new oModel($this->_p); if (!$this->_work_tbl){ $class = $this->extractClassname(); $this->_work_tbl = $this->_p->getVar('tbl_prefix').$class; } $this->_modelInstance->setModelTable($this->_work_tbl); $this->_modelInstance->setModelLinkTable($this->_link_tbl); $this->_modelInstance->setModelFields($this->_fields); $this->_modelInstance->setModelLinks($this->_links); $this->_modelInstance->setModelReverseLinks($this->_reverse_links); $this->_modelInstance->setUploadDir($this->_upload_dir); $this->_modelInstance->setPrimaryKey($this->_primary); $this->_modelInstance->getIsMultilang($this->_multilang); $this->_modelInstance->getLinkedSerialized($this->_linked_serialized); // initialize model $this->_modelInstance->init(); } if ($this->_modelInstance){ // copy all properties // this is backward compatibility // ToDo: make all calls to the Model directly $this->_work_tbl = $this->_modelInstance->getModelTable(); $this->_link_tbl = $this->_modelInstance->getModelLinkTable(); $this->_fields = $this->_modelInstance->getModelFields(); $this->_links = $this->_modelInstance->getModelLinks(); $this->_reverse_links = $this->_modelInstance->getModelReverseLinks(); $this->_upload_dir = $this->_modelInstance->getUploadDir(); $this->_primary = $this->_modelInstance->getPrimaryKey(); $this->_multilang = $this->_modelInstance->getIsMultilang(); $this->_linked_serialized = $this->_modelInstance->getLinkedSerialized(); return true; } } throw new \Exception($this->_p->trans('errors.no_model_defined')); } /** * get connected model name * @return null */ public function getModel(){ return $this->_model; } /** * get connected model's instance * @return null|oModel */ public function getModelInstance(){ return $this->_modelInstance; } /** * determines is selected method overrided in the current controller * @param null $method * @param array|string $exclude excluded object names for searching * @return bool */ public function isOverrided($method = null, $exclude = array()){ if (!$method) return false; // try to find overrided method $overrided = false; $class_name = get_class($this); $ref = new \ReflectionClass($class_name); if ($ref){ $parentMethods = $ref->getMethods( \ReflectionMethod::IS_PUBLIC ^ \ReflectionMethod::IS_PROTECTED ); foreach ($parentMethods as $v){ if ($v->name == $method && $class_name == $v->class && !in_array($v->class, $exclude)){ $overrided = true; break; } } } return $overrided; } abstract public function get($conditions = array()); abstract public function getById($ids); }
Python
UTF-8
12,570
2.5625
3
[ "MIT" ]
permissive
#!/usr/bin/env python """smugline - command line tool for SmugMug Usage: smugline.py upload <album_name> --api-key=<apy_key> [--from=folder_name] [--media=(videos | images | all)] [--email=email_address] [--password=password] smugline.py download <album_name> --api-key=<apy_key> [--to=folder_name] [--media=(videos | images | all)] [--email=email_address] [--password=password] smugline.py process <json_file> --api-key=<apy_key> [--from=folder_name] [--email=email_address] [--password=password] smugline.py list --api-key=apy_key [--email=email_address] [--password=password] smugline.py create <album_name> --api-key=apy_key [--privacy=(unlisted | public)] [--email=email_address] [--password=password] smugline.py clear_duplicates <album_name> --api-key=<apy_key> [--email=email_address] [--password=password] smugline.py (-h | --help) Arguments: upload uploads files to a smugmug album download downloads an entire album into a folder process processes a json file with upload directives list list album names on smugmug create create a new album clear_duplicates finds duplicate images in album and deletes them Options: --api-key=api_key your smugmug api key --from=folder_name folder to upload from [default: .] --media=(videos | images | all) upload videos, images, or both [default: images] --privacy=(unlisted | public) album privacy settings [default: unlisted] --email=email_address email address of your smugmug account --passwod=password smugmug password """ # pylint: disable=print-statement from docopt import docopt from smugpy import SmugMug import getpass import hashlib import os import re import json import requests import time from itertools import groupby # Python 3 vs 2 try: from urllib.error import HTTPError except: from urllib2 import HTTPError __version__ = '0.6.0' IMG_FILTER = re.compile(r'.+\.(jpg|png|jpeg|tif|tiff|gif)$', re.IGNORECASE) VIDEO_FILTER = re.compile(r'.+\.(mov|mp4|avi|mts)$', re.IGNORECASE) ALL_FILTER = re.compile('|'.join([IMG_FILTER.pattern, VIDEO_FILTER.pattern]), re.IGNORECASE) class SmugLine(object): def __init__(self, api_key, email=None, password=None): self.api_key = api_key self.email = email self.password = password self.smugmug = SmugMug( api_key=api_key, api_version="1.2.2", app_name="SmugLine") self.login() self.md5_sums = {} def get_filter(self, media_type='images'): if media_type == 'videos': return VIDEO_FILTER if media_type == 'images': return IMG_FILTER if media_type == 'all': return ALL_FILTER def upload_file(self, album, image): retries = 5 while retries: try: self.smugmug.images_upload(AlbumID=album['id'], **image) return except HTTPError: print("retry ", image) retries -= 1 # source: http://stackoverflow.com/a/16696317/305019 def download_file(self, url, folder, filename=None): local_filename = os.path.join(folder, filename or url.split('/')[-1]) if os.path.exists(local_filename): print('{0} already exists...skipping'.format(local_filename)) return r = requests.get(url, stream=True) with open(local_filename, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() return local_filename def set_file_timestamp(self, filename, image): if filename is None: return # apply the image date image_info = self.get_image_info(image) timestamp = time.strptime(image_info['Image']['Date'], '%Y-%m-%d %H:%M:%S') t = time.mktime(timestamp) os.utime(filename, (t, t)) def upload_json(self, source_folder, json_file): images = json.load(open(json_file)) # prepend folder for image in images: image['File'] = source_folder + image['File'] # group by album groups = [] images.sort(key=lambda x: x['AlbumName']) for k, g in groupby(images, key=lambda x: x['AlbumName']): groups.append(list(g)) for group in groups: album_name = group[0]['AlbumName'] album = self.get_or_create_album(album_name) self._upload(group, album_name, album) def upload_folder(self, source_folder, album_name, file_filter=IMG_FILTER): album = self.get_or_create_album(album_name) images = self.get_images_from_folder(source_folder, file_filter) self._upload(images, album_name, album) def download_album(self, album_name, dest_folder, file_filter=IMG_FILTER): album = self.get_album_by_name(album_name) if album is None: print('Album {0} not found'.format(album_name)) return images = self._get_images_for_album(album, file_filter) self._download(images, dest_folder) def _upload(self, images, album_name, album): images = self._remove_duplicates(images, album) for image in images: print('uploading {0} -> {1}'.format(image, album_name)) self.upload_file(album, image) def _download(self, images, dest_folder): for img in images: print('downloading {0} -> {1}'.format(img['FileName'], dest_folder)) if 'OriginalURL' not in img: print('no permission to download {0}...skipping'.format(img['FileName'])) continue filename = self.download_file(img['OriginalURL'], dest_folder, img['FileName']) self.set_file_timestamp(filename, img) def _get_remote_images(self, album, extras=None): remote_images = self.smugmug.images_get( AlbumID=album['id'], AlbumKey=album['Key'], Extras=extras) return remote_images def _get_md5_hashes_for_album(self, album): remote_images = self._get_remote_images(album, 'MD5Sum') md5_sums = [x['MD5Sum'] for x in remote_images['Album']['Images']] self.md5_sums[album['id']] = md5_sums return md5_sums def _get_images_for_album(self, album, file_filter=IMG_FILTER): extras = 'FileName,OriginalURL' images = self._get_remote_images(album, extras)['Album']['Images'] for image in [img for img in images \ if file_filter.match(img['FileName'])]: yield image def _file_md5(self, filename, block_size=2**20): md5 = hashlib.md5() f = open(filename, 'rb') while True: data = f.read(block_size) if not data: break md5.update(data) return md5.hexdigest() def _include_file(self, f, md5_sums): try: if self._file_md5(f) in md5_sums: print('skipping {0} (duplicate)'.format(f)) return False return True except IOError as err: # see https://github.com/PyCQA/pylint/issues/165 # pylint: disable=unpacking-non-sequence errno, strerror = err print('I/O Error({0}): {1}...skipping'.format(errno, strerror)) return False def _remove_duplicates(self, images, album): md5_sums = self._get_md5_hashes_for_album(album) return [x for x in images if self._include_file(x.get('File'), md5_sums)] def get_albums(self): albums = self.smugmug.albums_get(NickName=self.nickname) return albums def list_albums(self): print('available albums:') for album in self.get_albums()['Albums']: if album['Title']: print(album['Title'].encode('utf-8')) def get_or_create_album(self, album_name): album = self.get_album_by_name(album_name) if album: return album return self.create_album(album_name) def get_album_by_name(self, album_name): albums = self.get_albums() try: matches = [x for x in albums['Albums'] \ if x.get('Title').lower() == album_name.lower()] return matches[0] except: return None def _format_album_name(self, album_name): return album_name[0].upper() + album_name[1:] def get_album_info(self, album): return self.smugmug.albums_getInfo(AlbumID=album['id'], AlbumKey=album['Key']) def get_image_info(self, image): return self.smugmug.images_getInfo(ImageKey=image['Key']) def create_album(self, album_name, privacy='unlisted'): public = (privacy == 'public') album_name = self._format_album_name(album_name) album = self.smugmug.albums_create(Title=album_name, Public=public) album_info = self.get_album_info(album['Album']) print('{0} album {1} created. URL: {2}'.format( privacy, album_name, album_info['Album']['URL'])) return album_info['Album'] def get_images_from_folder(self, folder, img_filter=IMG_FILTER): matches = [] for root, dirnames, filenames in os.walk(folder): matches.extend( {'File': os.path.join(root, name)} for name in filenames \ if img_filter.match(name)) return matches def _set_email_and_password(self): # for python2 try: input = raw_input except NameError: pass if self.email is None: self.email = input('Email address: ') if self.password is None: self.password = getpass.getpass() def login(self): self._set_email_and_password() self.user_info = self.smugmug.login_withPassword( EmailAddress=self.email, Password=self.password) self.nickname = self.user_info['Login']['User']['NickName'] return self.user_info def _delete_image(self, image): print('deleting image {0} (md5: {1})'.format(image['FileName'], image['MD5Sum'])) self.smugmug.images_delete(ImageID=image['id']) def clear_duplicates(self, album_name): album = self.get_album_by_name(album_name) remote_images = self._get_remote_images(album, 'MD5Sum,FileName') md5_sums = [] for image in remote_images['Album']['Images']: if image['MD5Sum'] in md5_sums: self._delete_image(image) md5_sums.append(image['MD5Sum']) if __name__ == '__main__': arguments = docopt(__doc__, version='SmugLine 0.4') smugline = SmugLine( arguments['--api-key'], email=arguments['--email'], password=arguments['--password']) if arguments['upload']: file_filter = smugline.get_filter(arguments['--media']) smugline.upload_folder(arguments['--from'], arguments['<album_name>'], file_filter) if arguments['download']: file_filter = smugline.get_filter(arguments['--media']) smugline.download_album(arguments['<album_name>'], arguments['--to'], file_filter) if arguments['process']: smugline.upload_json(arguments['--from'], arguments['<json_file>']) if arguments['list']: smugline.list_albums() if arguments['create']: smugline.create_album(arguments['<album_name>'], arguments['--privacy']) if arguments['clear_duplicates']: smugline.clear_duplicates(arguments['<album_name>'])
C++
UTF-8
9,727
2.625
3
[]
no_license
/* #PROJECT: Using esp32 to communicate with firebase, communicate with Arduino Uno through RF (LoRa module). Arduino side: get control value from esp 32 and control relays, reading sensor and send back to ESP32. #OUTSTANDING FEATURE! - Using timer interrupt on atmega328, so missing data is reduced at least!! - Good arrange process for transmit and receive, so process is very sepreate. - High speed response, 1 seconds and relay under your controller. - Safe? but we still prepared in case bad circumstance happended. #NOTICE -> Read README.md for more information about project like: circuit, refer sites, ability,... Created 8 Janaruary 2021 by Viet Long Contact to my email: vietlongle2000@gmail.com for more information. */ #include <SPI.h> #include <LoRa.h> #include <DHT.h> #include <MQUnifiedsensor.h> #include <Servo.h> #define BAND 433E6 // Asia - Viet Nam #define DEVICE_1 5 // digital pin for controlling delay #define DEVICE_2 3 #define DEVICE_3 4 #define DEVICE_4 8 #define SERVO_PIN 6 // control door #define FIRST_BIT 0x01 #define SECOND_BIT 0x02 #define THIRD_BIT 0x04 #define FOURTH_BIT 0x08 #define FIFTH_BIT 0x10 #define GAS_PIN A1 // using gas sensor (MQ135) #define DHT11_PIN A0 // using temperature and humidity sensor void init_lora(); void read_and_send_sensor_data_lora(); bool wait_for(unsigned long interval); bool wait_for_send(unsigned long interval); // void setup_timer_interrupt_4s(); float calibrate_NH4_density(); void init_gas_sensor(); void (* reset_board)(void) = 0; /* setup library */ DHT dht(DHT11_PIN, DHT11); // dht(DHTPIN, DHTTYPE) // MQUnifiedsensor ...(board name, Voltage_Resolution, ADC_Bit_Resolution, pin, type) MQUnifiedsensor MQ135("Arduino UNO", 5, 10, GAS_PIN, "MQ-135"); // init MQ135 Servo Servo1; // init servo /* process variable */ volatile bool is_time_send = false; volatile bool is_door_open = false; void setup() { // Serial.begin(115200); // debug pinMode(DEVICE_1, OUTPUT); pinMode(DEVICE_2, OUTPUT); pinMode(DEVICE_3, OUTPUT); pinMode(DEVICE_4, OUTPUT); pinMode(GAS_PIN, INPUT); pinMode(DHT11_PIN, INPUT); digitalWrite(DEVICE_1, HIGH); // Using relay trigger low (1 - LOW, 0 - HIGH) digitalWrite(DEVICE_2, HIGH); digitalWrite(DEVICE_3, HIGH); digitalWrite(DEVICE_4, HIGH); dht.begin(); // init dht11 init_gas_sensor(); delay(1000); // setup_timer1_interrupt_4s(); init_lora(); Servo1.attach(SERVO_PIN); Servo1.write(0); } void loop() { String string_receive = ""; // try to parse packet if (LoRa.parsePacket() != 0) { while(LoRa.available()){ string_receive += LoRa.readString(); // LoRa read return int type } /* control 4 relays and 1 servo, 4 LSB of receive byte is relay state */ uint8_t data_receive = string_receive.toInt() & 0x1F; // String type to Int type digitalWrite(DEVICE_1, ~data_receive & FIRST_BIT); digitalWrite(DEVICE_2, ~data_receive & SECOND_BIT); digitalWrite(DEVICE_3, ~data_receive & THIRD_BIT); digitalWrite(DEVICE_4, ~data_receive & FOURTH_BIT); if((data_receive & 0x10) != 0x00){ // Serial.println(data_receive & 0x10); is_door_open = true; Servo1.write(150); } Serial.println(string_receive); } if(is_time_send){ // time to send data (only send within 10ms) LoRa.idle(); // put LoRa to concentrate mode (important) read_and_send_sensor_data_lora(); // send sensor data is_time_send = false; delay(100); // very important time for change mode LoRa.receive(); } if(is_door_open){ if(wait_for(3000)){ Servo1.write(0); is_door_open = false; } } if(wait_for_send(4000)){ is_time_send = true; } } // /* remember to keep interrupt so short as possible */ // ISR(TIMER1_COMPA_vect){ // interrupt function for timer1 // // volatile static uint8_t non_send_times = 0; // for bad circumstance // if(non_send_times > 10){ // // // Serial.println("RESET"); // reset_board(); // } // else if(is_time_send == true){ // // non_send_times++; // } // else{ // // non_send_times = 0; // is_time_send = true; // every 4s, got this TRUE // } // } void init_lora(){ while(true){ static uint8_t fail_times = 0; delay(200); if (!LoRa.begin(BAND)){ fail_times++; if(fail_times == 10){ reset_board(); } } else{ return; } } } void read_and_send_sensor_data_lora(){ String string_send = ""; /* add sensor value to string */ string_send += dht.readTemperature(); string_send += "*"; string_send += dht.readHumidity(); string_send += "*"; string_send += calibrate_NH4_density(); string_send += "*"; // Serial.println(string_send); // debug LoRa.beginPacket(); LoRa.print(string_send); // LoRa.print(String_type) LoRa.endPacket(); } bool wait_for(unsigned long interval){ // wait for a time (using timer) static bool is_first_time = true; static unsigned long previous_millis = 0; unsigned long current_millis = millis(); if(is_first_time){ is_first_time = false; /* in case of running for the first time, set previous millis */ previous_millis = current_millis; } if(current_millis - previous_millis >= interval) { /* reset first time identify bool for next usage */ is_first_time = true; return true; } return false; } bool wait_for_send(unsigned long interval){ // wait for a time (using timer) static bool is_first_time = true; static unsigned long previous_millis = 0; unsigned long current_millis = millis(); if(is_first_time){ is_first_time = false; /* in case of running for the first time, set previous millis */ previous_millis = current_millis; } if(current_millis - previous_millis >= interval) { /* reset first time identify bool for next usage */ is_first_time = true; return true; } return false; } // void setup_timer1_interrupt_4s(){ // // /* fix register on atmega328a -pu */ // TCCR1A = 0; // set entire TCCR1A register to 0 // TCCR1B = 0; // same for TCCR1B // TCNT1 = 0; //initialize counter value to 0 // // set compare match register for 0.25 hz increments // OCR1A = 65535; // = (16*4*10^6) / (1*1024) - 1 (must be <65536) // // turn on CTC mode // TCCR1B |= (1 << WGM12); // // Set CS10 and CS12 bits for 1024 prescaler // TCCR1B |= (1 << CS12) | (1 << CS10); // // enable timer compare interrupt // TIMSK1 |= (1 << OCIE1A); // sei(); // allow interrupt // } void init_gas_sensor(){ //Set math model to calculate the PPM concentration and the value of constants MQ135.setRegressionMethod(1); MQ135.init(); /***************************** MQ CAlibration ********************************************/ // Explanation: // In this routine the sensor will measure the resistance of the sensor supposing before was pre-heated // and now is on clean air (Calibration conditions), and it will setup R0 value. // We recomend execute this routine only on setup or on the laboratory and save on the eeprom of your arduino // This routine not need to execute to every restart, you can load your R0 if you know the value float calcR0 = 0; for(int i = 1; i <= 10; i++){ MQ135.update(); // Update data, the arduino will be read the voltage on the analog pin calcR0 += MQ135.calibrate(3.6); } MQ135.setR0(calcR0/10); /* Exponential regression: GAS | a | b CO | 605.18 | -3.937 Alcohol | 77.255 | -3.18 CO2 | 110.47 | -2.862 Tolueno | 44.947 | -3.445 NH4 | 102.2 | -2.473 Acetona | 34.668 | -3.369 */ MQ135.setA(102.2); // Calibrate NH4 density MQ135.setB(-2.473); } float calibrate_NH4_density(){ MQ135.update(); // read data from SMOKE_PIN return MQ135.readSensor(); }
TypeScript
UTF-8
3,299
2.6875
3
[]
no_license
import { AnyAction } from "redux"; import { ORDERS_PROMO_ORDER_CREATING, ORDERS_PROMO_ORDER_CREATING_SUCCESS, ORDERS_PROMO_ORDER_CREATING_ERROR, ORDERS_PRODUCTS_ORDER_CREATING, ORDERS_PRODUCTS_ORDER_CREATING_SUCCESS, ORDERS_PRODUCTS_ORDER_CREATING_ERROR, ORDERS_LOADING, ORDERS_LOADING_SUCCESS, ORDERS_LOADING_ERROR, ORDER_DETAILS_SUCCESS, CHANGE_ORDER_STATUS_LOADING, CHANGE_ORDER_STATUS_SUCCESS, CHANGE_ORDER_STATUS_ERROR, ORDER_RESET, } from "../actions/ordersActions"; import { PaymentApiOrder, ProductOrder } from "../types/paymentapi"; export interface IOrdersState { orderCreating?: boolean; orderCreatingError?: any; order?: PaymentApiOrder; ordersLoading?: boolean; ordersLoadingError?: any; orders?: ProductOrder[]; selectedOrder?: ProductOrder; orderStatusLoading?: boolean; orderStatusLoadingError?: any; } const initialState: IOrdersState = { orderCreating: false, orderCreatingError: null, ordersLoadingError: null, ordersLoading: false, orderStatusLoading: false, orderStatusLoadingError: null, orders: [], selectedOrder: null, }; const ordersReducer = ( state = initialState, action: AnyAction ): IOrdersState => { switch (action.type) { case ORDERS_PROMO_ORDER_CREATING: return { ...state, orderCreating: true, orderCreatingError: null, }; case ORDERS_PROMO_ORDER_CREATING_SUCCESS: return { ...state, orderCreating: false, order: action.order, }; case ORDERS_PROMO_ORDER_CREATING_ERROR: return { ...state, orderCreating: false, orderCreatingError: action.error, }; case ORDERS_PRODUCTS_ORDER_CREATING: return { ...state, orderCreating: true, orderCreatingError: null, }; case ORDERS_PRODUCTS_ORDER_CREATING_SUCCESS: return { ...state, orderCreating: false, order: action.order, }; case ORDERS_PRODUCTS_ORDER_CREATING_ERROR: return { ...state, orderCreating: false, orderCreatingError: action.error, }; case ORDERS_LOADING: return { ...state, ordersLoading: true, ordersLoadingError: null, }; case ORDERS_LOADING_SUCCESS: let { orders } = action; return { ...state, ordersLoading: false, orders: [...orders.reverse()], }; case ORDERS_LOADING_ERROR: return { ...state, ordersLoading: false, ordersLoadingError: action.error, }; case ORDER_DETAILS_SUCCESS: let { order } = action; return { ...state, selectedOrder: order, }; case CHANGE_ORDER_STATUS_LOADING: return { ...state, orderStatusLoading: true, orderStatusLoadingError: null, }; case CHANGE_ORDER_STATUS_SUCCESS: return { ...state, orderStatusLoading: false, selectedOrder: action.order, }; case CHANGE_ORDER_STATUS_ERROR: return { ...state, orderStatusLoading: false, orderStatusLoadingError: action.error, }; case ORDER_RESET: return initialState; default: return state; } }; export default ordersReducer;
Python
UTF-8
289
2.609375
3
[]
no_license
def reconnect(self, dbname): 'Reconnect to another database and return a PostgreSQL cursor object.\n\n Arguments:\n dbname (string): Database name to connect to.\n ' self.db_conn.close() self.module.params['database'] = dbname return self.connect()
Markdown
UTF-8
1,508
2.5625
3
[ "MIT", "CC-BY-4.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
--- title: Application.WorkbookAfterRemoteChange event (Excel) keywords: vbaxl10.chm503114 f1_keywords: - vbaxl10.chm503114 ms.prod: excel api_name: - Excel.Application.WorkbookAfterRemoteChange ms.date: 04/05/2019 ms.localizationpriority: medium --- # Application.WorkbookAfterRemoteChange event (Excel) Occurs after a remote user's edits to the workbook are merged. ## Syntax _expression_.**WorkbookAfterRemoteChange** (_Wb_) _expression_ A variable that represents an **[Application](Excel.Application(object).md)** object. ## Parameters |Name|Required/Optional|Data type|Description| |:-----|:-----|:-----|:-----| | _Wb_|Required| **[Workbook](Excel.Workbook.md)**|The workbook which has been changed by a remote user.| ## Return value Nothing ## Remarks For information about how to use event procedures with the **Application** object, see [Using events with the Application object](../excel/Concepts/Events-WorksheetFunctions-Shapes/using-events-with-the-application-object.md). ## Example This example shows you where you can place code that runs after merging an incoming remote change. This code must be placed in a class module, and an instance of that class must be correctly initialized. ```vb Private Sub App_WorkbookAfterRemoteChange(ByVal Wb As Workbook) 'A remote user has made a change to this workbook and that change has been merged. 'The code in this subroutine will now be run. End Sub ``` [!include[Support and feedback](~/includes/feedback-boilerplate.md)]
Java
UTF-8
962
2.140625
2
[]
no_license
package com.sih.rakshak.features.notes; import io.realm.RealmObject; import io.realm.annotations.PrimaryKey; /** * Created by ManikantaInugurthi on 01-04-2017. */ public class NotesItem extends RealmObject { @PrimaryKey private long id; private String title; private String description; private String lastViewed; public NotesItem() { } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getLastViewed() { return lastViewed; } public void setLastViewed(String lastViewed) { this.lastViewed = lastViewed; } }
Java
UTF-8
1,218
2.3125
2
[]
no_license
package com.example.restservice; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class TicketController { @Autowired private TicketSearchService ticketService; private Set<String> attributeNameSet = new HashSet<>(Arrays.asList("id", "type", "subject", "description", "priority", "status")); @GetMapping("/search") public ResponseEntity<List<Ticket>> search(@RequestParam(value = "attribute") String attribute, @RequestParam(value = "value") String value) { if (StringUtils.isBlank(attribute) || StringUtils.isBlank(value) || !attributeNameSet.contains(attribute)) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); } List<Ticket> tickets = ticketService.search(attribute, value); return ResponseEntity.ok(tickets); } }
TypeScript
UTF-8
1,596
3.4375
3
[]
no_license
interface IScable { getScale():number; getName():string; } class Scales { allProduct:Array <IScable>=[] constructor(){ }; add=(product:IScable):void=>{ (this.allProduct).push(product); } getSumScale=():number=>{ let totalWeight:number=0; (this.allProduct).forEach((item)=>totalWeight+=item.getScale()); return totalWeight } getNameList=():Array<string>=>{ let totalList:Array <string>=[]; this.allProduct.forEach(item=>{ totalList.push(item.getName()); }) return totalList; } } class Apple implements IScable{ nameProduct:string; weight:number constructor(_nameProduct:string, _weight:number ) { this.nameProduct=_nameProduct; this.weight=_weight; } getScale():number{ return this.weight } getName():string{ return this.nameProduct; } } class Tomato implements IScable{ nameProduct:string; weight:number constructor(_nameProduct:string, _weight:number ) { this.nameProduct=_nameProduct; this.weight=_weight; } getScale():number{ return this.weight } getName():string{ return this.nameProduct; } } let apple1:Apple= new Apple('Антоновка', 250); let apple2:Apple= new Apple('Семеновка', 560); let tomato1:Tomato=new Tomato ('Синьерро-помидорро', 150); let scales1:Scales= new Scales(); scales1.add(apple1); scales1.add(apple2); scales1.add(tomato1); console.log( scales1.getNameList()) console.log('Общий веспродуктов: ', scales1.getSumScale())
Markdown
UTF-8
978
3.21875
3
[ "MIT" ]
permissive
# Agile Project Forecaster The following project a shiny calculator of working days needed to complete an agile project basing on historical data. The project is published on [shinyapps.io](). ## Methodology The calculator is able to divide your project in one or more legs, up to 5. For each leg the user is asked to insert: * a sample of cycle times; * the number of stories which will be simulated with the given sample. Then the calculator will: * bootstrap the samples creating a distribution of possible sample means; * run a montecarlo simulation picking randomly from the sample means; * plot a histogram of the simulations. The user is able to customize: * the uantiles to be printed in the histogram; * the number of predictions created in the bootstraps; * the number of runs of the montecarlo simulation. ## Reference It is based on the work of Dimitar Bakardzhiev [published on infoq](http://www.infoq.com/articles/noestimates-monte-carlo) on the 1st of December 2014.
Python
UTF-8
666
4.375
4
[]
no_license
# 生成器是一种特殊的迭代器 # yield 会让程序暂停,并且下次继续从这里开始执行 def create_num(all_num): a, b = 0, 1 current_num = 0 while current_num < all_num: # print(a) yield a # 如果一个函数中有yield语句,那么这个就不再是函数,而是一个生成器的模板 a, b = b, a+b current_num += 1 # 如果在调用create_num的时候,发现这个函数中有yield,那么此时不是调用函数,而是创建一个生成器对象 obj = create_num(10) # ret = next(obj) # print(ret) obj2 = create_num(2) ret2 = next(obj2) print(ret2) for num in obj: print(num)
Java
UTF-8
656
2.234375
2
[]
no_license
package vuki.com.leakcanaryexercise; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.squareup.leakcanary.RefWatcher; public class AnotherActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_another_application ); //Invoke the GC to accelerate the analysis. System.gc(); } @Override protected void onDestroy() { super.onDestroy(); RefWatcher refWatcher = App.getRefWatcher( this ); refWatcher.watch( this ); } }
Markdown
UTF-8
1,537
4.46875
4
[]
no_license
# 二进制中1的个数 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 ## Solution ```java public class Solution { public int NumberOf1(int n) { int count = 0; while (n != 0) { if ((n & 1) == 1) { // if last bit is 1(注意运算符优先顺序) count++; } n = n >>> 1; } return count; } } ``` 注意运算符 `>>` 与 `>>>` 的区别。对于正数而言二者没什么区别。 `>>` 是 right shift,或者称作 算数右移位 (arithmetic right shift),右移后在最左边补上符号位(正数是0,负数是1) `>>>` 是 unsigned right shift,或者称作 逻辑右移位 (logical right shift),右移后在最左边补0 > ⚠️注意:Java中并没有 `<<<` 运算符。 ``` ~ Unary bitwise complement << Signed left shift >> Signed right shift >>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR ``` ## Solution2 也可以用mask = 1,不断左移mask,从右向左👈依次判断 n 的每个bit位。 ```java public class Solution { public int NumberOf1(int n) { int count = 0; int mask = 1; while (mask != 0) { if ((n & mask) != 0) { // 注意不能写成 == 1 count++; } mask = mask << 1; } return count; } } ```
C#
UTF-8
2,218
2.828125
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; namespace Chronozoom.Entities { /// <summary> /// Represents a set of collections. /// </summary> [DataContract] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification="SuperCollection in an inherent ChronoZoom concept")] public class SuperCollection { /// <summary> /// Constructor used to set default values. /// </summary> public SuperCollection() { this.Id = Guid.NewGuid(); // Don't use [DatabaseGenerated(DatabaseGeneratedOption.Identity)] on Id } /// <summary> /// The ID of the supercollection. /// </summary> [Key] [DataMember] public Guid Id { get; set; } /// <summary> /// The path from the web root to the the supercollection. Title must therefore have a globally unique value. /// Is programmatically derived as a URL-sanitized version of user's display name using a-z, 0-9 and hyphen only. /// </summary> [DataMember] [Required] [MaxLength(50)] [Column(TypeName = "varchar")] public string Title { get; set; } /// <summary> /// The user who owns the supercollection. /// </summary> [DataMember] [Required] public User User { get; set; } /// <summary> /// A collection of collections that belong to the supercollection. /// </summary> [DataMember] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly", Justification="Need to be able to assemble this objects collection.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification="Automatically implemented properties must define both get and set accessors.")] public virtual Collection<Entities.Collection> Collections { get; set; } } }
C++
UTF-8
1,397
2.8125
3
[]
no_license
class Solution { public: /** * @param nodes a array of directed graph node * @return a connected set of a directed graph */ vector<vector<int>> connectedSet2(vector<DirectedGraphNode*>& nodes) { if (nodes.size() == 0) return vector<vector<int> >(); for (int i = 0; i < nodes.size(); i++) { for (int j = 0; j < nodes[i]->neighbors.size(); j++) { if (nodes[i]->neighbors[j] == nodes[i]) continue; nodes[i]->neighbors[j]->neighbors.push_back(nodes[i]); } } mp.clear(); res.clear(); vector<int> nset; for (int i = 0; i < nodes.size(); i++) { if (mp.find(nodes[i]) == mp.end()) { nset.clear(); dfs(&nodes[i], nset); res.push_back(nset); } } for (int i = 0; i < res.size(); i++) sort(res[i].begin(), res[i].end()); return res; } private: map<DirectedGraphNode*, bool> mp; vector<vector<int> > res; void dfs(DirectedGraphNode** node, vector<int> &nset) { nset.push_back((*node)->label); mp[*node] = true; for (int i = 0; i < (*node)->neighbors.size(); i++) { if (mp.find((*node)->neighbors[i]) == mp.end()) dfs(&((*node)->neighbors[i]), nset); } } };
PHP
UTF-8
5,740
3.296875
3
[ "MIT" ]
permissive
<?php /* @autor BRUNO MENDES PIMENTA * CLASSE MODEL RESPONSÁVEL POR CRUD DA TABELA PERIODICO */ class Periodico extends AbstractInformacional{ /* *RECEBE O ISSN DO PERIÓDICO @access protected @name $issn */ protected $issn; /* *RECEBE O ANO DE PÚBLICAÇÃO DO PERIÓDICO @access protected @name $ano */ protected $ano; /* *RECEBE O VOLUME DO PERIÓDICO @access protected @name $volume */ protected $volume; /* *RECEBE UMA DESCRIÇÃO DO PERIÓDICO @access protected @name $descricao */ protected $descricao; /* *RECEBE EVENTUAIS ERROS QUE PODEM OCORRER NO OBJETO @access protected @name $erro */ protected $erro; public function __get($property){ if(property_exists($this, $property)){ return $this->$property; } } public function __set($property, $value){ if(property_exists($this, $property)){ switch ($property) { case 'issn': if(gettype($value) == "string" && strlen($value) == 8){ $this->$property = $value; }else{ throw new Exception("Erro: issn deve receber um inteiro."); } break; case 'ano': if(gettype($value) == "integer" && strlen($value) == 4){ $this->$property = $value; }else{ throw new Exception("Erro: ano deve receber um inteiro de quatro digitos."); } break; case 'volume': if(gettype($value) == "integer"){ $this->$property = $value; }else{ throw new Exception("Erro: volume deve receber um inteiro."); } break; case 'descricao': if(gettype($value) == "string" && strlen($value) <= 250){ $this->$property = $value; }else{ throw new Exception("Erro: descricao deve receber uma string de no máximo 250 caracteres."); } break; default: parent::__set($property, $value); break; } } } /* * FUNÇÃO RESPONSÁVEL POR GRAVAR PERIÓDICO NO BANCO DE DADOS * @access public * @return Boolean */ function gravar(){ $sql = "CALL add_periodico('$this->issn', '$this->volume', '$this->ano', '$this->descricao', '$this->titulo', '$this->codBarras', '$this->estante', '$this->exemplares', @gravado)"; $conexao = DAO::conexaoMySQLi(); //VALIDA DADOS ANTES DE SEREM MANDADOS PARA O BANCO if($this->validarInsercao($conexao)){ $conexao->query($sql); $gravado = $conexao->query('SELECT @gravado'); $gravado = $gravado->fetch_array(); if((int) $gravado[0] == 0){ return false; }else{ return true; } }else{ return false; } } /* * FUNÇÃO RESPONSÁVEL POR VALIDAR DADOS ANTES DE ENVIAR AO BANCO * @access public * @return Boolean */ function validarInsercao($conexao){ //VERIFICANDO SE AS PROPRIEDADES ISSN, ANO, TITULO, CODBARRAS, ESTANTE E EXEMPLARES SE ENCONTRAM VÁZIAS $propriedades_faltando = array(); if(empty($this->issn)){ $propriedades_faltando[] = 'issn'; } if(empty($this->ano)){ $propriedades_faltando[] = 'ano'; } if(empty($this->titulo)){ $propriedades_faltando[] = 'titulo'; } if(empty($this->codBarras)){ $propriedades_faltando[] = 'codBarras'; } if(empty($this->estante)){ $propriedades_faltando[] = 'estante'; } if(empty($this->exemplares)){ $propriedades_faltando[] = 'exemplares'; } if(!empty($propriedades_faltando)){ $this->erro = "A(s) propriedade(s) ".implode(", ", $propriedades_faltando)." são obrigatórias!"; return false; } //VERIFICA EXISTÊNCIA E DUPLICIDADE DOS DADOS INFORMADOS PELO USUÁRIO //DECLARANDO COMANDOS SQL QUE SERÃO USADOS NA VALIDAÇÃO $sql_valida_issn = "SELECT COUNT(*) FROM periodico WHERE issn = $this->issn"; //VALIDANDO ISSN DUPLICADO $res_valida_issn = ($conexao->query($sql_valida_issn))->fetch_array()[0]; if((int) $res_valida_issn == 0){ return true; } } /* * FUNÇÃO RESPONSÁVEL POR RESGATAR PERIÓDICOS DO BANCO DE DADOS * @access public * @return Array */ function pegarPeriodicos(){ //ARRAY QUE RECEBERÁ OS PERIODICOS $conexao = DAO::conexaoMySQLi(); $periodicos = array(); //QUERY SQL $sql = 'SELECT * FROM periodico'; //EXECUTANDO QUERY NO BANCO $res = $conexao->query($sql); //WHILE QUE PERCORRERÁ A RESPOSTA, E CRIARÁ OS OBJETOS PERIODICO while($row = $res->fetch_assoc()){ $periodico = new Periodico(); $periodico->issn = $row['issn']; $periodico->ano = $row['ano']; $periodico->descricao = $row['descricao']; $periodico->volume = $row['volume']; $periodico->titulo = $row['titulo']; $periodico->codBarras = $row['codigobarras']; $periodico->estante = $row['estante']; $periodico->exemplares = $row['exemplares']; $periodico->disponiveis = $row['disponiveis']; //COLOCANDO PERIODICO NO ARRAY $periodicos[] = $periodico; } return $periodicos; } static function existePeriodico($codigo){ $sql = "SELECT * FROM periodico WHERE issn = '" . $codigo . "'"; $conexao = DAO::conexaoMySQLi(); $conexao->query($sql); if($conexao->affected_rows > 0){ return true; }else{ return false; } } } ?>
Java
UTF-8
1,827
2.5625
3
[ "Apache-2.0" ]
permissive
package com.rtbhouse.grpc.lbexamples; import io.grpc.health.v1.HealthCheckRequest; import io.grpc.health.v1.HealthCheckResponse; import io.grpc.health.v1.HealthGrpc; import io.grpc.stub.StreamObserver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ExampleHealthService extends HealthGrpc.HealthImplBase { private static final Logger logger = LoggerFactory.getLogger(ExampleHealthService.class); private int checksCount = 0; private int servingPeriodSize; private int notServingPeriodSize; ExampleHealthService(int servingPeriodSize, int notServingPeriodSize) { super(); assert (servingPeriodSize >= 0 && notServingPeriodSize >= 0); assert (servingPeriodSize != 0 || notServingPeriodSize != 0); this.servingPeriodSize = servingPeriodSize; this.notServingPeriodSize = notServingPeriodSize; } /** * First responds HEALTHY to servingPeriodSize requests. Then responds NOT_HEALTHY to * notServingPeriodSize requests. And so on. */ @Override public synchronized void check( HealthCheckRequest request, StreamObserver<HealthCheckResponse> responseObserver) { checksCount = (checksCount + 1) % (servingPeriodSize + notServingPeriodSize); if (checksCount < servingPeriodSize) { logger.info("State HEALTHY"); responseObserver.onNext( HealthCheckResponse.newBuilder() .setStatus(HealthCheckResponse.ServingStatus.SERVING) .build()); } else { logger.info("State NOT_HEALTHY"); responseObserver.onNext( HealthCheckResponse.newBuilder() .setStatus(HealthCheckResponse.ServingStatus.NOT_SERVING) .build()); } responseObserver.onCompleted(); } public boolean isRespondingServing() { return checksCount < servingPeriodSize; } }
C++
UTF-8
1,335
2.71875
3
[]
no_license
#include <cstdio> #include <vector> using namespace std; int ans = 0; int N,M; int Y1[70]; int Y2[70]; int X1 = -100; int X2 = 100; vector<pair<long long,long long> > masks; int bits1(pair<long long,long long> a){ int rez = 0; for(int i = 0;i <= 62;i++){ rez += ((a.first >> i) & 1) + ((a.second >> i) & 1); } return rez; } pair<long long,long long> eval(int Y){ pair<long long,long long> ans; ans.first = ans.second = 0; for(int i = 1;i <= N;i++){ for(int j = 1;j <= M;j++){ if(Y == Y1[i] + Y2[j]){ ans.first |= 1LL << (i - 1); ans.second |= 1LL << (j - 1); } } } return ans; } int main(){ scanf("%d %d",&N,&M); for(int i = 1;i <= N;i++){ scanf("%d",&Y1[i]); } for(int j = 1;j <= M;j++){ scanf("%d",&Y2[j]); } for(int i = 1;i <= N;i++){ for(int j = 1;j <= M;j++){ masks.push_back(eval((Y1[i] + Y2[j]))); } } for(auto it:masks){ for(auto it2:masks){ pair<long long,long long> rez; rez.first = it.first | it2.first; rez.second = it.second | it2.second; if(ans < bits1(rez)){ ans = bits1(rez); } } } printf("%d",ans); return 0; }
Python
UTF-8
2,549
2.78125
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jan 24 09:07:02 2020 @author: JeffHalley """ from bs4 import BeautifulSoup import boto3 from boto.s3.connection import S3Connection import os import pathlib import requests import zstandard def get_newest_comments_file_name(): page = requests\ .get('https://files.pushshift.io/reddit/comments/').text soup = BeautifulSoup(page, 'html.parser') a_tags = soup.find_all('a') latest_comment_file_name = '' for i in a_tags: if i['href'][2:7] == 'RC_20': latest_comment_file_name = i['href'][2:] return latest_comment_file_name def check_if_up_to_date(latest_comment_file_name): conn = S3Connection(os.environ['aws_access'], os.environ['aws_secret_key']) bucket = conn.get_bucket('s3a://jeff-halley-s3/') for key in bucket.list(prefix='2019_comments/'): if key == latest_comment_file_name: return True return False def get_newest_comments_file(latest_comment_file_name): #download file url = 'https://files.pushshift.io/reddit/comments/' + latest_comment_file_name target_path = '/reddit_comments/compressed/' + latest_comment_file_name response = requests.get(url, stream=True) handle = open(target_path, "wb") for chunk in response.iter_content(chunk_size=512): if chunk: # filter out keep-alive new chunks handle.write(chunk) #decompress input_file = pathlib.Path(target_path) destination_dir = '/reddit_comments/compressed/' with open(input_file, 'rb') as compressed: decomp = zstandard.ZstdDecompressor() output_path = pathlib.Path(destination_dir) / input_file.stem with open(output_path, 'wb') as destination: decomp.copy_stream(compressed, destination) return output_path def upload_newest_comments_file(file_path): bucket_name = 'jeff-halley-s3/' file_name = file_path.split(sep = '/')[-1] key = '2019_comments/' + file_name s3 = boto3.client('s3') s3.upload_file(key,bucket_name, file_name) if __name__ == '__main__': latest_comment_file_name = get_newest_comments_file_name() already_up_to_date = check_if_up_to_date(latest_comment_file_name) if already_up_to_date is False: file_path = get_newest_comments_file(latest_comment_file_name) upload_newest_comments_file(latest_comment_file_name) print('file successfully uploaded to s3') else: print('s3 already contains most up to date comment file')
Java
UTF-8
1,532
2.671875
3
[]
no_license
package com.example.grpc.server.services; import com.example.grpc.server.*; import io.grpc.Status; import io.grpc.stub.StreamObserver; import lombok.extern.slf4j.Slf4j; import org.lognet.springboot.grpc.GRpcService; @Slf4j @GRpcService public class GrpcExampleServiceImpl extends GrpcExampleServiceGrpc.GrpcExampleServiceImplBase { @Override public void sayHello(Person request, StreamObserver<Greeting> responseObserver) { log.info("Server received (Thread id: {}): {}", Thread.currentThread().getId(), request); String message = String.format("Welcome %s %s", request.getFirstName(), request.getLastName()); Greeting greeting = Greeting.newBuilder().setMessage(message).build(); log.info("Server responded {}", greeting); if (request.getFirstName().equals("Throw") && request.getLastName().equals("Error")) { responseObserver.onError(Status.INTERNAL.withDescription("Bad name").asRuntimeException()); } responseObserver.onNext(greeting); responseObserver.onCompleted(); } @Override public void getMap(MapRequest request, StreamObserver<MapResponse> responseObserver) { log.info("Service getMap() (Thread id: {})", Thread.currentThread().getId()); MapResponse mapResponse = MapResponse.newBuilder().putMappedValues("one", 1).putMappedValues("two", 2).build(); log.info("Server Response {}", mapResponse); responseObserver.onNext(mapResponse); responseObserver.onCompleted(); } }
Markdown
UTF-8
9,459
3.265625
3
[]
no_license
## Live Demo: [Demo](https://the-color-app.netlify.app/) # PROJECT : COLOR PICKER ## This project is build up by using frontend framework call REACTJS. ## Different libraries are used to make things easy ### 1)Chroma-js Chroma.js is a small-ish zero-dependency JavaScript library (13.5kB) for all kinds of color conversions and color scales. ### 2)rc-slider It is used to build slider in our navbar with the help of this slider we can different type of level for a single color ### 3)react-copy-to-clipboard It is used to copy the name of the color by clicking on respective color ### 4)@material-ui It is the popular interface library for reactjs we can use different types of component’s which is already built in material-ui we just have to import in our file such as Button ,Select ,Dialog-box, Drawer etc. ### 5)@material-ui/styles With the help of this library we can write our css in to our js files With the help of this we can use conditional operator for styling our page, for eg: props=>chroma(props.background).luminance()>=0.7 ?"rgba(0,0,0,0.6)":"white", ### 6)react-ui/form-validator To validate the form to check whether new typed color is unique or not or selected color is unique or not ### 7)react-color With the help of this we can import chromePicker in to our file and we can select colors to add into new palette ### 8)react-sortable-hoc It is the library used to drag-n-drop new colors which is added into our new palette. Therefore user’s can order them in their way. ## Seedcolor.js It contains an array which is used to provide initial colors to our palette ## colorhelper.js it is used to provide single object which contain colors of different level. Each level contains an array and each entry in an array is an object which has id, name ,hex, rgb, rgba. Chroma js library is used to build color in different levels. Levels used are:{50,100,200,300,400,500,600,700,800,900} ## Different types of Component made to build to this project ### 1)App.js (Class Component): It is the epicenter of our project and controls various components according to routes Different Routes are used: 1) “/” to show list of palettes , It renders PaletteList component 2) “/palette/:paletteid” to show single palette , It renders Palette component 3) “/palette/new” to show from for to make new palette, It renders NewPalette component 4) “/palette/paletteid/colorid” to show various levels for single color , It renders singleColor component. ### 2) Pallete.js (Class Component): to show single palette and a navbar. Navbar contains slider and dropdown which is used to change the level of the colors (100,200,..900) of palette and the type (hex , rgb, rgba) respectively . ![image](https://user-images.githubusercontent.com/58387831/104203871-a3609780-5452-11eb-8454-6531f2c2c0ba.png) ### 3)Color.js : (Class Component): It is used to show a single color in our palette each color contains its name and its level , more button which is used to show various level of single color and copy button which is used to copy the color. The copy button shows only when we hover on the color. ![image](https://user-images.githubusercontent.com/58387831/104204032-d1de7280-5452-11eb-8844-f4f8c4c722d0.png) ### 4)Singlecolor.js : (Class Component): to show different levels of single color present in the palette. It is rendered when we click more button . it also show navbar which contains a dropdown to select type of color i.e hex , rgb or rgba. ![image](https://user-images.githubusercontent.com/58387831/104204132-f1759b00-5452-11eb-8038-13ea8ac1cf70.png) ### 5)PaletteList.js (Class Component) : It is used to show list of palettes . It is our initial page of our project. It show minified version of our palette . ![image](https://user-images.githubusercontent.com/58387831/104204211-05210180-5453-11eb-8663-7f6597e52ff1.png) ### 6)MiniPalette.js (Class Component): It is used to show the minifed version of our palette into our initial page. It shows the palette name and the emoji and the color used in our palette. It also show delete icon to delete the palette from the list when we hover on the minipalette ![image](https://user-images.githubusercontent.com/58387831/104204262-1407b400-5453-11eb-94e5-6def3c6a365a.png) ### 7)NewPalette.js (Class Component): It is rendered when we click create palette in our front page. It show us the COLOR PICKER FORM to add new color to our new Palette. Initially it contains 19 colors we can delete these colors add our own colors. This page is made from Drawer Component(material-ui). We can also hide our color picker form. ![image](https://user-images.githubusercontent.com/58387831/104204307-22ee6680-5453-11eb-945f-80b67931c508.png) ![image](https://user-images.githubusercontent.com/58387831/104204338-2f72bf00-5453-11eb-86b7-0e6cc2b6ce41.png) ### 8)Colorpicker.js (Class Compoment): It is used in our NewPalette component to show colorpicker form . We used react-color library to include Chrome Picker in our component. We also used react-ui-form-validator to validate our form. For examples : to check whether color and color-name is unique and to check before submitting the form input value is not empty. It also contains 2 buttons one to clear palette and one to add random color which is not used in our palette. It also alert when our palette is full and we try to add new color by changing the text of ADD COLOR button to PALETTE IS FULL ![image](https://user-images.githubusercontent.com/58387831/104204429-49ac9d00-5453-11eb-9a1c-19c357e255b8.png) ![image](https://user-images.githubusercontent.com/58387831/104204449-4fa27e00-5453-11eb-9062-99f776bc43a2.png) ![image](https://user-images.githubusercontent.com/58387831/104204472-54673200-5453-11eb-80e1-4aa0d255856b.png) ![image](https://user-images.githubusercontent.com/58387831/104204488-592be600-5453-11eb-9899-6b29219a2567.png) ![image](https://user-images.githubusercontent.com/58387831/104204509-5cbf6d00-5453-11eb-975c-ef4f4f5691f1.png) # Getting Started with Create React App This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `npm test` Launches the test runner in the interactive watch mode.\ See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. ### `npm run build` Builds the app for production to the `build` folder.\ It correctly bundles React in production mode and optimizes the build for the best performance. The build is minified and the filenames include the hashes.\ Your app is ready to be deployed! See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. ### `npm run eject` **Note: this is a one-way operation. Once you `eject`, you can’t go back!** If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. ## Learn More You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). To learn React, check out the [React documentation](https://reactjs.org/). ### Code Splitting This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) ### Analyzing the Bundle Size This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) ### Making a Progressive Web App This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) ### Advanced Configuration This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) ### Deployment This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) ### `npm run build` fails to minify This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
Java
UTF-8
3,624
2.671875
3
[]
no_license
package org.supinf.security; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import org.springframework.web.filter.GenericFilterBean; /** * * Filtre utilisée dans la configuration de sécurité et s'intégrant dans la * FilterChain de SpringSecurity pour intercepter les requêtes et contrôler les * entêtes d'autorisation * * @see * JwtWebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity) * * @author BLU Kwensy Eli */ @Component public class JwtAuthorizationFilter extends GenericFilterBean { /** * */ public static final String HEADER = "Authorization"; /** * */ public static final String PREFIX = "Bearer "; /** * Injection instance JwtUtils */ @Autowired private JwtUtils jwtUtils; /** * cette méthode permet d'intercepter toutes les URL sécurisées, vérifier * leur validité (existence d'en-têtes de sécurité, ...), et la validité du * jeton JWT * * @see GenericFilterBean#doFilter(javax.servlet.ServletRequest, * javax.servlet.ServletResponse, javax.servlet.FilterChain) * @param request * @param response * @param filterChain * @throws IOException * @throws ServletException */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest) request; String header = req.getHeader(HEADER); if (header == null || !header.startsWith(PREFIX)) { filterChain.doFilter(request, response); return; } Authentication authentication = getAuthentication(req); //On effectue une authentification explicite en intégrant ... //... un objet de type Authentication dans le contexte de sécurité SecurityContextHolder.getContext().setAuthentication(authentication); filterChain.doFilter(request, response); } /** * Renvoie une classe de type Authentication construite à partir des * informations contenues dans le jeton * * @param request * @return */ private Authentication getAuthentication(HttpServletRequest request) { String token = request.getHeader(HEADER); if (token != null) { // on décode le jeton AbstractUserDetails user = jwtUtils .parseToken(token.replace(PREFIX, "")); // une instance UsernamePasswordAuthenticationToken ... //... se rapproche un peu de notre cas de figure if (user != null) { //utiliser obligatoirement ce constructeur pour la classe UsernamePasswordAuthenticationToken ... // .. pour obtenir une instance valide [isAuthenticated = true] de la classe Authentication auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); return auth; } return null; } return null; } }
JavaScript
UTF-8
728
4.8125
5
[]
no_license
/* exported capitalizeWords */ // i need to capitalize the beginning of a word in a string and lowercase everything else // first i'll split the string into an array. // then i'll loop through the array and uppercase the first index of the array using the toUpperCase method and put // that in a variable. // then i'll push the variable concatenated with the rest of the indexes into a new string // lastly i'll turn them back into a string using the join method. function capitalizeWords(string) { var word = string.split(' '); var arr = []; for (var i = 0; i < word.length; i++) { var fullWord = word[i].charAt(0).toUpperCase(); arr.push(fullWord + word[i].slice(1).toLowerCase()); } return arr.join(' '); }
Java
UTF-8
2,722
2.40625
2
[]
no_license
package s4.spring.reservations.controllers; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import s4.spring.reservations.models.Reservation; import s4.spring.reservations.repositories.LodgementRepository; import s4.spring.reservations.repositories.ReservationRepository; import s4.spring.reservations.services.MyUserDetails; @CrossOrigin @RestController @RequestMapping("/rest/reservations") public class RestReservationController extends AbstractRestController<Reservation>{ @Autowired public RestReservationController(ReservationRepository repo) { super(repo); } @Autowired private LodgementRepository lrepo; @GetMapping("/my") public List<Reservation> read(@AuthenticationPrincipal MyUserDetails user) { List<Reservation> reservations = ((ReservationRepository) repo).findByRentId(user.getId()); return reservations; } @GetMapping("/lodgement/{id}") public List<Date> getFreeDate(@PathVariable int id) throws ParseException { List<Reservation> reservations = ((ReservationRepository) repo).findByLodgementId(id); List<Date> bookDate = new ArrayList<Date>(); String strdate; Date start = new Date(); for(Reservation resa : reservations) { bookDate.add(resa.getStart()); } SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd"); System.out.print(start); Calendar c = Calendar.getInstance(); c.setTime(start); c.add(Calendar.DATE, 90); Date end = c.getTime(); List<Date> totalDates = new ArrayList<Date>(); while (!start.after(end)) { c.setTime(start); strdate = formatter.format(c.getTime()); start = formatter.parse(strdate); totalDates.add(start); c.setTime(start); c.add(Calendar.DATE, 1); } for(Date day : totalDates) { if(bookDate.contains(day)) { totalDates.remove(day); } } System.out.print(totalDates.get(0)); return null; } @Override protected void addObject(Reservation reservation,MyUserDetails user) { reservation.setRented(user.getUser()); repo.saveAndFlush(reservation); } @Override protected void updateObject(Reservation toUpdateObject, Reservation originalObject) { } }
Java
UTF-8
6,269
3.046875
3
[]
no_license
import entities.Address; import entities.Employee; import entities.Project; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.Query; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigDecimal; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class Engine implements Runnable { private final EntityManager entityManager; private BufferedReader bufferedReader; public Engine(EntityManager entityManager) { this.entityManager = entityManager; this.bufferedReader = new BufferedReader(new InputStreamReader(System.in)); } @Override public void run() { System.out.println("Enter exercise number:"); int exNum = 0; try { exNum = Integer.parseInt(bufferedReader.readLine()); switch (exNum) { case 2 -> exTwoChangeCasing(); case 3 -> exThreeContainsEmployee(); case 4 -> exFourEmployeesWithSalaryOver50000(); case 5 -> exFiveEmployeesFromDepartment(); case 6 -> exSixAddingNewAddressAndUpdatingEmployee(); case 7 -> exSevenAddressesWithEmployeeCount(); case 8 -> exEightGetEmployeeWithProject(); case 10 -> exTenIncreaseSalaries(); default -> System.out.println("Wrong number - try again!"); } } catch (IOException e) { e.printStackTrace(); } } private void exTenIncreaseSalaries() { entityManager.getTransaction().begin(); List<Employee> resultList = entityManager.createQuery("select e from Employee e " + "where e.department.name in ('Engineering'," + "'Tool Design', 'Marketing', 'Information Services')", Employee.class).getResultList(); resultList.forEach(e -> { e.setSalary(e.getSalary().multiply(BigDecimal.valueOf(1.12))); entityManager.persist(e); System.out.printf("%s %s ($%.2f)%n", e.getFirstName(), e.getLastName(), e.getSalary()); }); entityManager.getTransaction().commit(); } private void exEightGetEmployeeWithProject() throws IOException { System.out.println("Enter employee ID:"); Integer id = Integer.parseInt(bufferedReader.readLine()); Employee employee = entityManager.find(Employee.class, id); System.out.printf("%s %s - %s%n", employee.getFirstName(), employee.getLastName(), employee.getJobTitle()); Set<Project> projects = employee.getProjects(); System.out.println(projects.stream().map(Project::getName).sorted() .collect(Collectors.toList()).toString().replace("[", "") .replace("]", "").replace(", ", System.lineSeparator())); } private void exSevenAddressesWithEmployeeCount() { entityManager.createQuery ("select a from Address a " + " order by a.employees.size desc ", Address.class).setMaxResults(10) .getResultList().forEach(a -> System.out.printf("%s, %s - %d employees%n" , a.getText(), a.getTown().getName(), a.getEmployees().size())); } private void exSixAddingNewAddressAndUpdatingEmployee() throws IOException { System.out.println("Enter employee last name:"); String lastName = bufferedReader.readLine(); try { Employee employee = entityManager.createQuery("select e from " + "Employee e where e.lastName = :last", Employee.class). setParameter("last", lastName).getSingleResult(); Address address = new Address(); address.setText("Vitoshka 15"); entityManager.getTransaction().begin(); entityManager.persist(address); entityManager.getTransaction().commit(); entityManager.getTransaction().begin(); employee.setAddress(address); entityManager.getTransaction().commit(); } catch (NoResultException e) { System.out.println("No such employee exists in database!!!"); } } private void exFiveEmployeesFromDepartment() { List<Employee> resultList = entityManager.createQuery ("select e from Employee e where e.department.name = 'Research and Development'" + "order by e.salary, e.id", Employee.class) .getResultList(); resultList.forEach(e -> System.out.printf("%s %s from %s - $%.2f%n", e.getFirstName(), e.getLastName(), e.getDepartment().getName(), e.getSalary())); } private void exFourEmployeesWithSalaryOver50000() { List resultList = entityManager.createQuery ("select e.firstName from Employee e where e.salary > 50000") .getResultList(); resultList.forEach(e -> System.out.println(e)); } private void exThreeContainsEmployee() throws IOException { System.out.println("Enter first and last name of employee:"); String[] input = bufferedReader.readLine().split("\\s+"); String firstName = input[0]; String lastName = input[1]; Query query = entityManager.createQuery ("select e.id from Employee e where e.firstName = :first and e.lastName = :last"); query.setParameter("first", firstName); query.setParameter("last", lastName); List resultList = query.getResultList(); int result = resultList.size(); if (result == 0) { System.out.println("No such employee!"); } else { System.out.println(firstName + " " + lastName + " persists in soft_uni database!"); } } private void exTwoChangeCasing() { entityManager.getTransaction().begin(); Query query = entityManager.createQuery ("update Town t set t.name = upper(t.name) where length(t.name) <= 5"); int affectedRows = query.executeUpdate(); entityManager.getTransaction().commit(); System.out.println("Rows affected: " + affectedRows); } }
C++
UTF-8
2,357
2.5625
3
[]
no_license
#include "filtrGauss.h" static wsp_Gauss coeff_tab[SIZE][SIZE]; static void init_wsp(wsp_Gauss coeff[SIZE][SIZE]){ #pragma HLS ARRAY_PARTITION variable=coeff_tab complete dim=1 float coeff_float[SIZE][SIZE]; float sum = 0; for (int i=-(SIZE-1)/2; i<=(SIZE-1)/2; i++){ for (int j=-(SIZE-1)/2; j<=(SIZE-1)/2; j++){ sum += 1/((float)(2*PI*VAR))*exp((-(i*i + (j*j))/((float)(2*VAR)))); coeff_float[i+(SIZE-1)/2][j+(SIZE-1)/2] = 1/((float)(2*PI*VAR))*exp((-(i*i + j*j)/((float)(2*VAR)))); } } // normalizacja for (int i=0; i<SIZE; i++){ for (int j=0; j<SIZE; j++){ coeff_float[i][j] /= sum; coeff_float[i][j] *= SCAL; coeff[i][j] = wsp_Gauss(coeff_float[i][j]); } } } void rozmycie (img_gray& img_in, img_gray& img_out){ #pragma HLS ARRAY_PARTITION variable=coeff_tab complete dim=1 okno_3x3 okno; kontekst_buffer buffer; init_wsp(coeff_tab); OUT_LOOP: for (int i=0; i<IMG_HEIGHT+1; i++){ IN_LOOP: for(int j=0; j<IMG_WIDTH+1; j++){ #pragma HLS DEPENDENCE variable=buffer inter false #pragma HLS PIPELINE II=1 #pragma HLS LOOP_FLATTEN off int tmp1, tmp2; pixel_gray new_pixel, value; if (j < IMG_WIDTH){ buffer.shift_down(j); tmp1 = buffer.getval(1, j); tmp2 = buffer.getval(2, j); if (i < IMG_HEIGHT){ img_in >> new_pixel; buffer.insert_top_row(new_pixel.val[0], j); } } okno.shift_right(); if (j < IMG_WIDTH){ okno.insert(tmp2, 2, 0); okno.insert(tmp1, 1, 0); okno.insert(new_pixel.val[0], 0, 0); } //if context is valid if (i > 1 && j > 1 && i < IMG_HEIGHT && j < IMG_WIDTH) value = operator_Gauss(&okno); else value.val[0] = 0; if (i > 0 && j > 0) img_out << value; } } } pixel_gray operator_Gauss (okno_3x3* okno){ #pragma HLS ARRAY_PARTITION variable=coeff_tab complete dim=1 ap_int<8+FRAC> acc = 0; OUT_LOOP_OPERATOR:for(int i=0; i<SIZE; i++){ IN_LOOP_OPERATOR:for (int j=0; j<SIZE; j++){ acc += coeff_tab[i][j] * okno->getval(i,j); } } return (pixel_gray)(acc >> FRAC); } void filtr_Gauss (dane& in, dane& out){ #pragma HLS DATAFLOW #pragma HLS INTERFACE axis register both port=out #pragma HLS INTERFACE axis register both port=in img_gray instance_in; img_gray instance_out; hls::AXIvideo2Mat(in, instance_in); rozmycie(instance_in, instance_out); hls::Mat2AXIvideo(instance_out, out); }
Python
UTF-8
1,523
3.203125
3
[]
no_license
import unittest import os from classes.file import File from argparse import Namespace ''' Testing methods in File class to run the test cases in this file. python -m unittest test/test_file.py ''' INPUT_DATA_FILENAME = os.path.join(os.path.dirname(__file__), 'input-test-file.txt') OUTPUT_DATA_FILENAME = os.path.join(os.path.dirname(__file__), 'output-test-file.txt') class MyTest(unittest.TestCase): def setUp(self): self.input_testfile = open(INPUT_DATA_FILENAME) self.actual_str_file = self.input_testfile.read() args = Namespace(input=INPUT_DATA_FILENAME, output=OUTPUT_DATA_FILENAME) self.file = File(args) self.words = { 'i': 3, 'here': 2, 'random': 2, 'are': 1 } self.actual_words_from_file = ''' i (3) here (2) random (2) are (1) ''' def tearDown(self): self.input_testfile.close() # os.remove(OUTPUT_DATA_FILENAME) def test_read_input(self): method_str_file = self.file.read_input() self.assertEqual(self.actual_str_file, method_str_file) # def test_write_output(self): # self.file.write_output(self.words) # method_created_file = open(OUTPUT_DATA_FILENAME, "r") # method_created_file_str = method_created_file.read() # method_created_file.close() # print(method_created_file_str, self.words) # self.assertEqual(method_created_file_str, self.words) if __name__ == '__main__': unittest.main()
Go
UTF-8
7,038
2.796875
3
[]
no_license
package main import ( "encoding/json" "github.com/garyburd/go-websocket/websocket" "github.com/gorilla/mux" "io/ioutil" "labix.org/v2/mgo" "labix.org/v2/mgo/bson" "log" "net/http" "time" ) const ( writeWait = 10 * time.Second readWait = 60 * time.Second pingPeriod = (readWait * 9) / 10 maxMessageSize = 512 ) type User struct { userid string pic string } type connection struct { channel string ws *websocket.Conn send chan []byte user User } type controlRequest struct { cmd string param string result chan string } type Message struct { MsgType string Sender string Channel string Content string Date int64 } type hub struct { connections map[*connection]bool channelName string control chan *controlRequest // for control messages broadcast chan *Message register chan *connection unregister chan *connection } var hmap = make(map[string]*hub) // mongo session var mongoSession *mgo.Session var mongoCollection *mgo.Collection func init() { var err error if mongoSession, err = mgo.Dial(mongoServer); err == nil { mongoSession.SetMode(mgo.Monotonic, true) mongoCollection = mongoSession.DB("channelhub").C("messages") } else { mongoSession = nil mongoCollection = nil } } func (u *User) String() string { m := map[string]string{ "user": u.userid, "pic": u.pic, } j, _ := json.Marshal(m) return string(j) } func (u *User) Map() map[string]string { m := map[string]string{ "user": u.userid, "pic": u.pic, } return m } // 从websocket中读出信息,转发到指定channel中,然后广播给其他的人 func (c *connection) ReadPump(channelName string, req *http.Request) { defer func() { hmap[channelName].unregister <- c c.ws.Close() }() c.ws.SetReadLimit(maxMessageSize) c.ws.SetReadDeadline(time.Now().Add(readWait)) for { op, r, err := c.ws.NextReader() if err != nil { break } switch op { case websocket.OpPong: c.ws.SetReadDeadline(time.Now().Add(readWait)) case websocket.OpText: rawmessage, err := ioutil.ReadAll(r) log.Printf("on msg arrival " + string(rawmessage) + " on channel:" + channelName) if err != nil { break } m := make(map[string]string) if err := json.Unmarshal([]byte(rawmessage), &m); err == nil { if userid, err := ReadCookie("userid", req); err == nil { msg := &Message{ MsgType: m["MsgType"], Sender: userid, Content: m["Content"], Channel: c.channel, Date: time.Now().Unix(), } if msg.MsgType == "text" { // write to mongo mongoCollection.Insert(&msg) } hmap[channelName].broadcast <- msg } } } } } // 从channel的拿到广播消息, 并写入当前connection的websocket中, 另外一个功能是心跳. func (c *connection) WritePump() { ticker := time.NewTicker(pingPeriod) defer func() { ticker.Stop() c.ws.Close() }() for { select { case message, ok := <-c.send: if !ok { c.write(websocket.OpClose, []byte{}) return } if err := c.write(websocket.OpText, message); err != nil { return } case <-ticker.C: if err := c.write(websocket.OpPing, []byte{}); err != nil { return } } } } func (c *connection) write(opCode int, payload []byte) error { c.ws.SetWriteDeadline(time.Now().Add(writeWait)) return c.ws.WriteMessage(opCode, payload) } // 获取根据channelName获取channel对象 func GetChannel(channelName string) (*hub, error) { if _, ok := hmap[channelName]; !ok { hmap[channelName] = &hub{ broadcast: make(chan *Message), register: make(chan *connection), unregister: make(chan *connection), connections: make(map[*connection]bool), control: make(chan *controlRequest), channelName: channelName, } log.Printf("new channel: " + channelName + " run!") go hmap[channelName].Run() } return hmap[channelName], nil } func (h *hub) Broadcast(msg *Message, filter func(c *connection) bool) { m := make(map[string]interface{}) m["MsgType"] = msg.MsgType m["Sender"] = msg.Sender m["Content"] = msg.Content m["Channel"] = msg.Channel m["Date"] = msg.Date data, _ := json.Marshal(m) log.Printf(string(data)) for c := range h.connections { if filter != nil && filter(c) == false { continue } select { case c.send <- data: default: close(c.send) delete(h.connections, c) } } } // channel的消息fan-out在这里进行 func (h *hub) Run() { for { select { case req := <-h.control: if req.cmd == "onlineusers" { users := make([]map[string]string, 0) usermap := make(map[string]bool) for k, _ := range h.connections { if _, ok := usermap[k.user.userid]; ok { continue } users = append(users, k.user.Map()) usermap[k.user.userid] = true } b, _ := json.Marshal(users) req.result <- string(b) } if req.cmd == "history" { var messages []Message mongoCollection.Find(bson.M{"channel": h.channelName}).All(&messages) b, _ := json.Marshal(messages) req.result <- string(b) } case c := <-h.register: msg := &Message{ MsgType: "adduser", Sender: "sysadmin", Content: c.user.String(), Channel: c.channel, Date: time.Now().Unix(), } flag := true for k, _ := range h.connections { if c.user.userid == k.user.userid { flag = false break } } if flag { log.Printf("new user coming: " + c.user.userid) h.Broadcast(msg, nil) } h.connections[c] = true case c := <-h.unregister: u_id := c.user.userid msg := &Message{ MsgType: "removeuser", Sender: "sysadmin", Content: c.user.String(), Channel: c.channel, Date: time.Now().Unix(), } delete(h.connections, c) close(c.send) // check if the user is truly go away flag := true for k, _ := range h.connections { // if still in channel, do not broadcast remove message if u_id == k.user.userid { flag = false break } } if flag { log.Printf("user going away: " + c.user.userid) h.Broadcast(msg, nil) } if len(h.connections) == 0 { } case m := <-h.broadcast: h.Broadcast(m, nil) } } } func serveWs(w http.ResponseWriter, r *http.Request) { ws, err := websocket.Upgrade(w, r.Header, nil, 1024, 1024) if _, ok := err.(websocket.HandshakeError); ok { http.Error(w, "Not a websocket handshake", 400) return } else if err != nil { log.Println(err) return } vars := mux.Vars(r) channelName := vars["channel"] // TODO: read user id from cookie if userid, err := ReadCookie("userid", r); err == nil { userpic, _ := ReadCookie("userpic", r) c := &connection{ send: make(chan []byte, 256), ws: ws, channel: channelName, user: User{userid, userpic}, } channel, _ := GetChannel(channelName) channel.register <- c log.Printf("new connect arrival... channel name: " + string(channelName)) go c.WritePump() c.ReadPump(channelName, r) } else { http.Redirect(w, r, "/", http.StatusFound) } }
C++
UTF-8
538
3.625
4
[]
no_license
#include<iostream> using namespace std; struct node { int data; node * next; }; void insert(node **head, int a) { node * newnode = new node(); newnode->data=a; newnode->next = *head; *head = newnode; } void remove_duplicates(node *head) { } void print(node *head) { node *temp = head; while(temp!=NULL) { cout<<temp->data<<"\t"; temp = temp->next; } } int main() { node * head = new node(); insert(&head, 1); insert(&head, 2); insert(&head, 3); print(head); }
Java
UTF-8
1,447
3.25
3
[]
no_license
package com.onepointgroup.pricing; import com.onepointgroup.pricing.core.Article; import com.onepointgroup.pricing.core.Currency; import com.onepointgroup.pricing.currency.Euro; import com.onepointgroup.pricing.discount.PayTwoOneFreeDiscount; import com.onepointgroup.pricing.unit.OunceUnit; import com.onepointgroup.pricing.unit.OneUnit; import java.math.BigDecimal; /** * Hello world! * */ public class App { public static void main( String[] args ) { final Currency EURO = new Euro(); Article bread = new Article(BigDecimal.valueOf(0.15), OneUnit.ONE, EURO); bread.setDiscount(new PayTwoOneFreeDiscount()); System.out.printf("price of %d bread : %f \n", 5,bread.buy(5) ); System.out.printf("price of %d bread : %f \n", 2,bread.buy(2) ); System.out.printf("price of %d bread : %f \n", 3,bread.buy(3) ); System.out.printf("price of %d bread : %f \n", 1,bread.buy(1) ); Article floor = new Article(BigDecimal.valueOf(0.65), OunceUnit.KG, EURO); System.out.printf("price of %.3f %s floor : %f \n", 5d, OunceUnit.KG,floor.buy(5d) ); System.out.printf("price of %.3f %s floor : %f \n", 5.8, OunceUnit.KG,floor.buy(5.8) ); System.out.printf("price of %.3f %s floor : %f \n", 5.8, OunceUnit.DIG,floor.buy(5.8, OunceUnit.DIG) ); System.out.printf("price of %.3f %s floor : %f \n", 5.8, OunceUnit.HG,floor.buy(5.8, OunceUnit.HG) ); } }
Python
UTF-8
363
2.8125
3
[]
no_license
import os import sys from god_crypt import * data = input("Your data here:") data = bytes.fromhex(data) decrypt = god_decrypt() print("packet size: %i" % len(data)) data = decrypt.run(bytearray(data)) print(data) new_data = binascii.hexlify(data) print(new_data) for i in range(0,len(new_data),2): print("0x"+ new_data[i:i+2].decode('UTF-8') +",",end='')
Java
UTF-8
989
2.578125
3
[]
no_license
package com.mimi.FoodDelivery.entities; import javax.persistence.*; import java.math.BigDecimal; @Entity @Table(name="dessert") public class Dessert { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name="dessert_name") private String dessertName; @Column(name="price") private BigDecimal price; public Dessert() { } public Dessert(Long id, String dessertName, BigDecimal price) { this.id = id; this.dessertName = dessertName; this.price = price; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDessertName() { return dessertName; } public void setDessertName(String dessertName) { this.dessertName = dessertName; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } }
Java
UTF-8
1,589
2.953125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
package optjava; import sun.misc.Unsafe; //tag::ATOMIC[] public class AtomicIntegerExample extends Number { private volatile int value; // setup to use Unsafe.compareAndSwapInt for updates private static final Unsafe unsafe = Unsafe.getUnsafe(); private static final long valueOffset; static { try { valueOffset = unsafe.objectFieldOffset( AtomicIntegerExample.class.getDeclaredField("value")); } catch (Exception ex) { throw new Error(ex); } } public final int get() { return value; } public final void set(int newValue) { value = newValue; } public final int getAndSet(int newValue) { return unsafe.getAndSetInt(this, valueOffset, newValue); } // ... // end::ATOMIC[] //tag::UNSAFE[] public final int getAndSetInt(Object o, long offset, int newValue) { int v; do { v = getIntVolatile(o, offset); } while (!compareAndSwapInt(o, offset, v, newValue)); return v; } public native int getIntVolatile(Object o, long offset); public final native boolean compareAndSwapInt(Object o, long offset, int expected, int x); //end::UNSAFE[] @Override public int intValue() { return value; } @Override public long longValue() { return value; } @Override public float floatValue() { return value; } @Override public double doubleValue() { return value; } }
C
UTF-8
889
3.234375
3
[]
no_license
#include <string.h> #include <stdlib.h> #include "free_list.h" /* Implement the first fit algorithm to find free space for the simulated file data. */ int get_free_block(FS *fs, int size) { Freeblock *curr; curr = fs->freelist; int os; if(curr->length >= size){ //check if the first block has length bigger than size os = curr->offset; //if so then update its info curr->offset += size; curr->length -= size; return os; if(curr->length == 0){ fs->freelist = fs->freelist->next; } } while(curr->next!= NULL){ //find the first freeblock then update its info if(size <= curr->next->length){ os = curr->next->offset; curr->next->offset += size; curr->next->length -= size; if(curr->next->length == 0){ curr->next = curr->next->next; } return os; }else{ curr->next= curr->next->next; } } return -1; }
JavaScript
UTF-8
2,341
3.265625
3
[ "MIT" ]
permissive
function mergeValue(context, value) { const contextType = Object.prototype.toString.call(context); const valueType = Object.prototype.toString.call(value); if(contextType !== valueType) { throw new Error('Cannot merge ' + valueType + ' into ' + contextType); } if(contextType === '[object Array]') { return [].concat(context, value); } else if(contextType === '[object Object]') { return Object.assign({}, context, value); } else { throw new Error('Cannot merge ' + valueType + ' into ' + contextType); } } function mergeInRecursive(context, path, value) { var valueType = Object.prototype.toString.call(value); if(valueType !== '[object Object]' && valueType !== '[object Array]') { throw new Error('value has to be either Object or Array'); } if(!path) { return mergeValue(context, value); } if(typeof path === 'string') { path = [path]; } var currentPathPart = path.shift(); if(typeof currentPathPart === 'undefined' || currentPathPart === null) { throw new Error('Path part is undefined'); } if(!context) { context = isNaN(currentPathPart) ? {} : []; } var currentValue = path.length === 0 ? mergeValue(context[currentPathPart] || (isNaN(currentPathPart) ? {} : []), value) : mergeInRecursive(context[currentPathPart], path, value); var contextType2 = Object.prototype.toString.call(context); if(contextType2 === '[object Array]') { var copy = [].concat(context); copy[currentPathPart] = currentValue; return copy; } else if(contextType2 === '[object Object]') { var newValue = {}; newValue[currentPathPart] = currentValue; return Object.assign({}, context, newValue); } else { throw new Error('Trying to add property to ' + contextType2); } } /** * Merges value with value in path. If path does not exist it is created * @param {Object} context * @param {Array|string} path * @param {*} value * @return {Object} */ module.exports = function mergeIn(context, path, value) { if(!value) { value = path; path = undefined; } if(!context) { throw new Error('Context is falsy.'); } return mergeInRecursive(context, path, value); };
PHP
UTF-8
1,400
2.796875
3
[]
no_license
<?php include "config/dbconfig.php"; $nis = $_POST['nis']; $nama = $_POST['nama']; $jenis_kelamin = $_POST['jenis_kelamin']; $telp = $_POST['telp']; $alamat = $_POST['alamat']; $gambar = $_FILES['gambar']['name']; $tmp = $_FILES['gambar']['tmp_name']; // Ganti nama gambar dengan meenambahkan tanggal dan jam upload ke nama gambar yang asli. $newgambar = date('dmYHis').$gambar; // Tentukan tempat menyimpan gambar, pastikan anda sudah membuat folder images didalam folder root. $path = "images/".$newgambar; // Cek apakah gambar berhasil diupload atau tidak if(move_uploaded_file($tmp, $path)){ // Proses simpan nama gambar saja ke Database $query = "INSERT INTO siswa VALUES('', '".$nis."', '".$nama."', '".$jenis_kelamin."', '".$telp."', '".$alamat."', '".$newgambar."')"; $sql = mysqli_query($connect, $query); //Eksekusi $query if($sql){ // Cek apakah proses simpan nama gambar berhasil atau tidak // Jika Berhasil, Kembali kehalaman depan header("location: index.php"); }else{ // Jika Gagal, Beritahukan pesan gagal : echo "Maaf, Terjadi kesalahan saat mencoba untuk menyimpan data ke database."; echo "<br><a href='upload_img.php'>Kembali</a>"; } }else{ // Jika gambar gagal diupload, Beritahukan pesan gagal : echo "Maaf, Gambar gagal untuk diupload."; echo "<br><a href='upload_img.php'>Kembali</a>"; } ?>
TypeScript
UTF-8
1,803
2.515625
3
[]
no_license
import { TodoModelDto } from "../dto/todoModelDto"; import { todoModel } from "../models/todoModel"; import { ResponseModel } from "../dto/responseModel"; export class TodoService3 { public static async AddTodo(data: TodoModelDto) :Promise<ResponseModel<TodoModelDto>>{ try { let newTodo = new todoModel(data); console.log(newTodo); await newTodo.save(); return ResponseModel.getValidResponse<TodoModelDto>(new TodoModelDto(data)); } catch (err) { console.log(err); return ResponseModel.getInvalidResponse(err); } } // public static async get(id:string) :Promise<ResponseModel<TodoModelDto>>{ // try{ // let todo = await todoModel1.findById(id).exec(); // return ResponseModel.getValidResponse<TodoModelDto>(new todoModel1(todo)); // } // catch(err){ // console.log(err); // return ResponseModel.getInvalidResponse<TodoModelDto>(err); // } // } // public static async getAll(){ // try{ // let todos = await todoModel1.find().exec(); // return ResponseModel.getValidResponse(todos); // } // catch(err){ // return ResponseModel.getInvalidResponse(err); // } // } // public static async update(req){ // try{ // let todo = await todoModel1.findById(req.body.id).exec(); // todo.msg = req.body.msg; // todo.up // return ResponseModel.getValidResponse(todo); // } // catch(err){ // return ResponseModel.getInvalidResponse(err); // } // } }
C
UTF-8
264
2.9375
3
[]
no_license
#include<stdio.h> int main() { int n,A=0,D=0; char l; scanf("%d%*c",&n); while (n-->0) { scanf("%c",&l); if (l=='A') A++; else D++; } if (A==D) printf("Friendship\n"); else if (A>D) printf("Anton\n"); else printf("Danik\n"); return 0; }
Python
UTF-8
242
2.546875
3
[]
no_license
__author__ = 'wcybxzj' class RomanError(Exception): pass class OutOfRangerError(RomanError): pass class NotIntegerError(RomanError): pass class InvalidRomanNumeralError(RomanError): pass def toRoman(n): pass def fromRoman(s): pass
Markdown
UTF-8
2,748
3.75
4
[ "MIT" ]
permissive
# About Python Event Emitter This is a python implementation for JavaScript-like EventEmitter class # Usage If you want that your class use a JavaScript-like **on()** and **emit()** approaches for event handling, just extends your class with EventEmitter class just the same as you do in JavaScript ## Example ```python from event_emitter import EventEmitter class MyEventClass(EventEmitter): def __init__(self): super().__init__() print("This is a EventEmitter example") self.on("my-event", lambda value: print(f"my-event got value: {value}")) if __name__ == "__main__": event_example = MyEventClass() event_example.emit("my-event", "Test") ``` ## Classes ### EventEmitter This is your base class for your event-based class. This is the one that implements EventEmitter JavaScript-like class with *on* and *emit* methods for handling and emitting events. ### EventHandler This is a container for events callback you can add or remove functions by using **append** and **remove** methods or **+=** and **-=*** operator. It is an iterable object, so you can iterate through it to get all callback functions. It is also a callable object, so if you want to call all functions, just call this EventHandler instance object, this is the way how EventEmitter run callback functions when an event happens #### Example ```python from event_emitter import EventHandler handler = EventHandler() handler += lambda label: print(f"First callback of f{label}") handler += lambda label: print(f"Second callback of f{label}") handler += lambda label: print(f"Third callback of f{label}") handler("test") ``` ### EventCallable This is a wrapper for event callback. This class implements an *once* static method decorator for handling once-call event handler, you can pass an asyncio event loop object to *loop* parameter in case of using an async function and you want to execute it on a event loop different from your current event loop. #### Example ```python from event_emitter import EventCallable, EventEmitter event_example = EventEmitter() @EventCallable.once(event_example, "test") def callback(label): print(f"Event called with label: {label}") event_example.on("test", callback) event_example.emit("test", "First call") event_example.emit("test", "Second call") ``` # Internals ## Event Handling All events of **EventEmitter** class is execute on a separate thread to avoid event processing to block your application main thread. If your event handler is a coroutine then it is executed on your current event loop. If you want to use a different event loop, then you must use a **EventCallable** class for your event callback and pass a different event loop object to it's argument
Shell
UTF-8
460
2.75
3
[]
no_license
#!/bin/sh INJECTED_GPG_SECREY_KEY_FILE=${INJECTED_GPG_KEY_FILE:-/vault/secrets/gpg-private-key.b64} [[ -f $INJECTED_GPG_SECREY_KEY_FILE ]] && { cat $INJECTED_GPG_SECREY_KEY_FILE | base64 -d | gpg2 --import gpg2 --list-secret-keys } INJECTED_GPG_PUBLIC_KEY_FILE=${INJECTED_GPG_KEY_FILE:-/vault/secrets/gpg-public-key.b64} [[ -f $INJECTED_GPG_PUBLIC_KEY_FILE ]] && { cat $INJECTED_GPG_PUBLIC_KEY_FILE | base64 -d | gpg2 --import gpg2 --list-keys }
Python
UTF-8
506
3.34375
3
[]
no_license
import random, string flag = open("randomFlag.txt", "r").read() print flag deFlag = "" random.seed("random") for c in flag: if c.isupper(): deFlag += chr((ord(c) - ord('A') - random.randrange(0, 26)) % 26 + ord('A')) elif c.islower(): deFlag += chr((ord(c) - ord('a') - random.randrange(0, 26)) % 26 + ord('a')) elif c.isdigit(): deFlag += chr((ord(c) - ord('0') - random.randrange(0, 10)) % 10 + ord('0')) else: deFlag += c print "[#] Decoded flag: " + deFlag
C#
UTF-8
1,164
2.625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Fort : MonoBehaviour { public float maxHealthPoint; // fort HP [SerializeField] private float currentHealthPoint;// current fort HP [SerializeField] private Text healthText; // fort HP text (bar) [SerializeField] private Text scoreText; //score [SerializeField] private int score = 0; // Use this for initialization void Start() { currentHealthPoint = maxHealthPoint; UpdateHealthBar(); } // Update is called once per frame void Update() { } public void reduceHP(float amount) { currentHealthPoint -= amount; UpdateHealthBar(); } public void addScore(int amount) { score += amount; UpdateScore(); } private void UpdateScore () { scoreText.text = "Score : " + score; } private void UpdateHealthBar() { healthText.text = "Fort HP = " + " " + currentHealthPoint + "/" + maxHealthPoint; } public bool fortIsDestroyed() { return currentHealthPoint <= 0; } }
Python
UTF-8
450
2.515625
3
[]
no_license
import socket import sys s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) port=8082 s.bind(('',port)) g=56 n=2371 c=17 print 'G ',g print 'n',n print 'Private Key: ',c msg,addr=s.recvfrom(1024) b = int(msg) s.sendto(str((g**c)%n),(sys.argv[1],8080)) print "Public Key: ",(g**c)%n bc = (b**c)%n print 'BC ',bc msg,addr=s.recvfrom(1024) s.sendto(str(bc),(sys.argv[1],8080)) print 'AB',msg ab = int(msg) abc = (ab**c)%n print 'Key: ',abc
PHP
UTF-8
1,181
3.046875
3
[]
no_license
<?php if ( ! defined('SYSTEM')) exit('Go away!'); /** * Mysql数据库操作(Mysqli) * @author toryzen * */ class DB implements DB_interface { public $conn; public function __construct($conn){ if(!$conn)exit("Database Connect Error!"); $this->conn = $conn; } /** * 执行Query * @param string $sql * @return unknown */ public function query($sql){ if(!$sql)return; $query = $this->conn->query($sql); if(mysqli_insert_id($this->conn))return mysqli_insert_id($this->conn); return $query; } /** * 获取一条记录 * @param string $sql * @return unknown */ public function fetch_one($sql){ if(!$sql)return; $query = $this->conn->query($sql); $result = $query->fetch_array(); return $result; } /** * 获取全部记录 * @param string $sql * @return unknown */ public function fetch_all($sql){ if(!$sql)return; $query = $this->conn->query($sql); while($row = $query->fetch_array()){ $result[] = $row; } return $result; } }
Markdown
UTF-8
467
2.84375
3
[]
no_license
# Text-Data-For-Whatsapp-Status-Emotion-Prediction-using-NLP This data set contains textual data for the prediction of the human emotion. WhatsApp status written in English, has been scraped from various websites. Three basic emotions sad, happy and angry has been scraped differently. Every data set contains two columns one the status and another sentiment of that status. With the help of this data, prediction of the emotion of whatsapp status can be determined.
TypeScript
UTF-8
435
2.65625
3
[]
no_license
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'filter' }) export class FilterPipe implements PipeTransform { transform(value: unknown, ...args: unknown[]): unknown { if (value == 0) { return "Today"; } else if (value == 1) { return "Tomorrow" } else if (value == 2) { return "Custom Filter" } else if (value == 3) { return "All Upcoming" } return null; } }
Java
UTF-8
175
1.773438
2
[]
no_license
package com.example.songlicai.two.Test; /** * Created by songlicai on 2016/11/21. */ public class Test { public String getValue() { return "xyz"; } }
C
UTF-8
715
2.953125
3
[]
no_license
// // Created by Frank on 03/03/2020. // #ifndef ADVENTOFC_CUSTOM_ASSERT_H #define ADVENTOFC_CUSTOM_ASSERT_H #include <stdio.h> #include <stdbool.h> int custom_assert_errors = 0; void custom_assert_init() { custom_assert_errors = 0; } void custom_assert_increment_errors() { custom_assert_errors++; } //TODO: Turn into macro to make file and line work. void custom_assert(bool condition, char* message) { if(!condition) { fprintf(stderr, "Test failed %s, line %d - %s\n", __FILE__, __LINE__, message); custom_assert_errors++; } } void custom_assert_finish() { fprintf(stderr, "Ran with %i failed tests.\n", custom_assert_errors); } #endif //ADVENTOFC_CUSTOM_ASSERT_H
C++
UTF-8
436
3.3125
3
[]
no_license
/* Ques :- Search in row wise and column wise sorted array(Time - O(n+m) ) */ void work() { int n,m; cin>>n>>m; int mat[n][m]; for(int i=0;i<n;++i) for(int j=0;j<m;++j) cin>>mat[i][j]; int key; cin>>key; int row=0,col=m-1; bool ans=0; while(row>=0 && row<n && col>=0 && col<m) { if(mat[row][col] == key) { ans=1; break; } else if(key > mat[row][col]) ++row; else --col; } cout<<ans; }
C++
UTF-8
984
2.5625
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #include "Block.h" #include "WorldGeneration.h" #include "MeshData.h" #include "MeshCreatorUtilities.h" Block::Block(): isSolid(false) { } Block::~Block() { } void Block::LoadBlock(MeshData* meshData, WorldGeneration* world) { MeshCreatorUtilities::FaceUp(meshData, worldPosition); Block* north = world->GetBlock(x + 1, y, z); if (north == nullptr || !north->isSolid) { MeshCreatorUtilities::FaceNorth(meshData, worldPosition); } Block* south = world->GetBlock(x - 1, y, z); if (south == nullptr || !south->isSolid) { MeshCreatorUtilities::FaceSouth(meshData, worldPosition); } Block* west = world->GetBlock(x, y - 1, z); if (west == nullptr || !west->isSolid) { MeshCreatorUtilities::FaceWest(meshData, worldPosition); } Block* east = world->GetBlock(x, y + 1, z); if (east == nullptr || !east->isSolid) { MeshCreatorUtilities::FaceEast(meshData, worldPosition); } }
Java
UTF-8
1,364
2.640625
3
[]
no_license
package entity; import javax.persistence.*; import java.util.Objects; @Entity @Table(name = "publisher", schema = "public", catalog = "bookstore") public class PublisherEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "publisher_id") private Long publisherId; @Basic @Column(name = "publisher_name", nullable = false, length = 120) private String publisherName; public PublisherEntity() {} public PublisherEntity(String publisherName) { this.publisherName = publisherName; } public Long getPublisherId() { return publisherId; } public void setPublisherId(Long publisherId) { this.publisherId = publisherId; } public String getPublisherName() { return publisherName; } public void setPublisherName(String publisherName) { this.publisherName = publisherName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PublisherEntity that = (PublisherEntity) o; return Objects.equals(publisherId, that.publisherId) && Objects.equals(publisherName, that.publisherName); } @Override public int hashCode() { return Objects.hash(publisherId, publisherName); } }
Java
UTF-8
480
3.015625
3
[]
no_license
import java.util.Set; import java.util.HashSet; import java.math.BigInteger; public class Solution29{ public static void main(String[] args) { Set<BigInteger> pows = new HashSet<BigInteger>(); for(int a = 2; a <= 100; a++){ for(int b = 2; b <= 100; b++){ if(!pows.contains(BigInteger.valueOf(a).pow(b))){ pows.add(BigInteger.valueOf(a).pow(b)); } } } System.out.println(pows.size()); } }
C++
SHIFT_JIS
3,702
2.71875
3
[]
no_license
#include"CBullet.h" #include"CSceneGame.h" CBullet::CBullet() :mLife(50), mCollider(this, CVector(0.0f, 0.0f, 0.0f), CVector(0.0f, 0.0f, 0.0f), CVector(1.0f, 1.0f, 1.0f), 0.1f) { mCollider.mTag = CCollider::EBULLET; mTag = EEYE; } //Ɖs̐ݒ //Set(,s) void CBullet::Set(float w, float d){ //XP[ݒ mScale = CVector(1.0f, 1.0f, 1.0f); //Op`̒_ݒ mT.SetVertex(CVector(w, 0.0f, 0.0f), CVector(-w, 0.0f, 0.0f), CVector(0.0f, 0.0f, d)); //Op`̖@ݒ mT.SetNormal(CVector(0.0f, 1.0f, 0.0f)); } //XV void CBullet::Update(){ //Ԃ̔ if (mLife-- > 0){ CCharacter::Update(); //ʒuXV mPosition = CVector(0.0f, 0.0f, 1.0f)*mMatrix; } else{ //ɂ mEnabled = false; } } //Փˏ //Collision(RC_1,RC_2) void CBullet::Collision(CCollider*m, CCollider*y){ if (m->mType == CCollider::ESPHERE&&y->mType == CCollider::ESPHERE){ //RC_myՓ˂Ă邩 if (CCollider::Collision(m, y)){ //@̂̎ if (y->mTag == CCollider::EBODY){ //Փ˂ĂƂ͖ɂ mEnabled = false; } } } } //` void CBullet::Render(){ //DIFFUSEFݒ float c[] = { 1.0f, 1.0f, 0.0f, 1.0f }; glMaterialfv(GL_FRONT, GL_DIFFUSE, c); //Op`` mT.Render(mMatrix); } CBullet2::CBullet2() :mLife(100), mCollider(this, CVector(0.0f, 0.0f, 0.0f), CVector(0.0f, 0.0f, 0.0f), CVector(1.0f, 1.0f, 1.0f), 0.1f) { mpModel = &CSceneGame::mCube; mCollider.mTag = CCollider::EBULLETE; } //Ɖs̐ݒ //Set(,s) void CBullet2::Set(float w, float d){ //XP[ݒ mScale = CVector(1.0f, 1.0f, 1.0f); //Op`̒_ݒ mT.SetVertex(CVector(w, 0.0f, 0.0f), CVector(-w, 0.0f, 0.0f), CVector(0.0f, 0.0f, d)); //Op`̖@ݒ mT.SetNormal(CVector(0.0f, 1.0f, 0.0f)); } //XV void CBullet2::Update(){ //Ԃ̔ if (mLife-- > 0){ CCharacter::Update(); //ʒuXV CVector dir = CXPlayer::mPlayer->mPosition - mPosition; CVector left = CVector(1.0f, 0.0f, 0.0f) * CMatrix().RotateY(mRotation.mY); CVector up = CVector(0.0f, 1.0f, 0.0f) * mMatrix - CVector(0.0f, 0.0f, 0.0f)*mMatrix; //z[~O if (left.Dot(dir) > 0.0f){ mRotation.mY += 0.5f; } else if (left.Dot(dir) < 0.0f){ mRotation.mY -= 0.5f; } if (up.Dot(dir) > 0.0f){ mRotation.mX -= 1.0f; } else if (up.Dot(dir) < 0.0f){ mRotation.mX += 1.0f; } mPosition = CVector(0.0f, 0.0f, 1.0f) * mMatrix; } else{ //ɂ mEnabled = false; } //if (mPosition.mY > 100){ // mPosition.mY = 100; //} //else if (mPosition.mY < -5){ // mEnabled = false; //} //if (mPosition.mZ > 150){ // mPosition.mZ = 150; //} //else if (mPosition.mZ < -150){ // mPosition.mY = -150; //} //if (mPosition.mX > 150){ // mPosition.mX = 150; //} //else if (mPosition.mX < -150){ // mPosition.mX = -150; //} } //Փˏ //Collision(RC_1,RC_2) void CBullet2::Collision(CCollider *m, CCollider *y){ //ɋRC_̎ if (m->mType == CCollider::ESPHERE && y->mType == CCollider::ESPHERE){ //RC_̂ƂՓ˂Ă邩 if (CCollider::Collision(m, y)){ //vC[̎ if (y->mTag == CCollider::EPBODY){ //Փ˂ĂƂ͖ɂ mEnabled = false; } } } } //` void CBullet2::Render(){ //DIFUSEFݒ CCharacter::Render(); //float c[] = { 1.0f, 1.0f, 0.0f, 1.0f }; //glMaterialfv(GL_FRONT, GL_DIFFUSE, c); ////Op`` //mT.Render(mMatrix); //mFp\bh //mCollider.Render(); }
C
UTF-8
912
2.734375
3
[]
no_license
#include<stdio.h> #include<string.h> //using namespace std; int main(){o char line[1000000]; char name[5000]; char fname[5000]; int x, i, q, k, j,t, len, nlen, strt, end; //freopen("b_in.txt", "r", stdin); //freopen("b_out.txt", "w", stdout); scanf("%d", &t); for(i=1; i<=t; i++){ scanf("%s", &line); len=strlen(line); scanf("%d", &q); printf("Case %d:\n", i); for(j=0; j<q; j++){ x=0; scanf("%s", &name); nlen=strlen(name); end=0; for(k=0; k<nlen; k++){ //printf("%c\n", name[k]); for(strt=0; strt<len; strt++){ //printf("%c\n", line[strt]); if(name[k]==line[strt]){ fname[end++]=line[strt]; //printf("%c\n", fname[end]); break; } } } fname[end+1]='\0'; //printf("%s\n", fname); x=strcmp(fname, name); if(x==0) printf("Yes\n"); else printf("No\n"); } } //fclose(stdin); //fclose(stdout); return 0; }
Java
UTF-8
5,412
2.359375
2
[]
no_license
package com.wondertek.mam.util.backupUtils.util22.cache; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; import org.apache.log4j.Logger; import com.wondertek.mobilevideo.core.cache.memcached.Memcached; /** 项目中缓冲的数据来源主要有三种情况: 从数据库中获取: memcache的对象失效由外部定时器进行清理 从文件中获取: memcache的对象失效,根据文件修改时间判断,每2分钟检查 * 从公共服务中获取: memcache的根据设置的过期时间自动失效,同时程序中也会主动更新移除. memExpiry为memcached过期时间 */ public abstract class GenericCacheManager<T, PK extends Serializable> implements com.wondertek.mobilevideo.core.cache.GenericCache<T, PK> { protected final static Logger log = Logger.getLogger(GenericCacheManager.class); /** 如果配置了就会使用,不配置不使用 */ protected Memcached memcached; /** memcached 过期时间,分钟为单位 默认为0为永不过期 */ protected long memExpiry = 0; /** 配置ehcache的名字 */ protected String ehcacheName; protected CacheManager ehcacheManager; protected Cache cache = null; /** 设置NODB模式,避免数据库出错情况下,一直查数据库,把门户服务器拖死 */ public static boolean NO_DB_MODE = false; protected T getCache(PK id) { // 从ehcache中获取成功,则返回 if (cache == null && ehcacheManager != null) cache = ehcacheManager.getCache(ehcacheName); if (cache != null) { Element elm = cache.get(id); if (elm != null) return (T) elm.getObjectValue(); } // 从memcache中获取成功,则返回 if (memcached != null) { Object obj = memcached.get(ehcacheName + id); if (obj != null){ //如果ehcache过期了,memcache还有值,需要重置一下ehcache if (ehcacheManager != null ) { Element elm = new Element(id, obj); if (ehcacheManager.getCache(ehcacheName) != null) ehcacheManager.getCache(ehcacheName).put(elm); } return (T) obj; } } return null; } @Override public T get(PK id) { try { T object = getCache(id); if (object != null) return object; // 缓存中没有,从数据源中获取 object = getObject(id); // 数据源中不存在,则新建 if (object == null) object = createObject(id); // 从数据源中获取或新建完成后,更新缓存 if (object != null) this.update(id, object); return object; } catch (Exception e) { log.error(e.getMessage()); } return null; } @Override public List<T> get(PK[] ids) { List<T> rs = new ArrayList<T>(); for (PK id : ids) { rs.add(this.get(id)); } return rs; } @Override public List<T> getBatch(PK[] ids) { Map<PK, T> incache = new HashMap<PK, T>(); List<PK> nocacheIds = new ArrayList<PK>(); for (PK id : ids) { T obj = getCache(id); if (obj != null) incache.put(id, obj); else nocacheIds.add(id); } Map<PK, T> noincache = this.getBatchObject(nocacheIds); for (PK id : nocacheIds) { update(id, noincache.get(id)); } List<T> rs = new ArrayList<T>(); for (PK id : ids) { T t = incache.get(id); if (t != null) rs.add(t); else { t = noincache.get(id); if (t != null) rs.add(t); else rs.add(this.createObject(id)); } } return rs; } @Override public void remove(PK id) { if (cache == null && ehcacheManager != null) cache = ehcacheManager.getCache(ehcacheName); if (cache != null) cache.remove(id); if (memcached != null) memcached.delete(ehcacheName + id); } @Override public void update(PK id, T obj) { if (ehcacheManager != null && obj != null) { Element elm = new Element(id, obj); if (ehcacheManager.getCache(ehcacheName) != null) ehcacheManager.getCache(ehcacheName).put(elm); } if (memcached != null && obj != null) { // 这里设置的失效时间 是服务器操作点的相对时间 不是 绝对 时间 memcached.set(ehcacheName + id, obj, new Date(getMemExpiry() * 60 * 1000)); } } /** 继承此类需要重载此方法, * @param id * @return */ protected T createObject(PK id) { return null; } /** 继承此类需要重载此方法 * @param id * @return */ protected T getObject(PK id) { return null; } /** 为了提供一次获取大量缓存的效率, 继承此类需要重载此方法 需要取出一组,并把对象放到缓存中. * @param id * @return */ protected Map<PK, T> getBatchObject(List<PK> id) { return null; } public void flushEhCache() { if (ehcacheManager != null) ehcacheManager.clearAll(); } public boolean flushMemcached() { if (memcached != null) { memcached.flushAll(); return true; } return false; } public void setMemcached(Memcached memcached) { this.memcached = memcached; } public void setEhcacheManager(CacheManager ehcacheManager) { this.ehcacheManager = ehcacheManager; } public String getEhcacheName() { return ehcacheName; } public void setEhcacheName(String ehcacheName) { this.ehcacheName = ehcacheName; } public void setMemExpiry(long memExpiry) { this.memExpiry = memExpiry; } public long getMemExpiry() { return memExpiry; } }
Markdown
UTF-8
1,528
3.375
3
[]
no_license
# States and Cities Design and Build Activity In this activity you will design and build a simple application based on the specification below. This specification is intentionally vague, this exercise is meant to force you to think about the design of the application and to ask good questions about the requirements. ## Requirements 1. This application must keep track of state information 1. It must track the following data about states: 1. Name 1. Population 1. Cities 1. It must track the following data about each city in a state: 1. Name 1. Population 1. Whether or not it is the capital 1. The application must allow the user to do the following: 1. Add states 1. Delete states 1. List all states 1. Add a city to a state 1. Delete a city from a state 1. List all the cities for a state 1. Search for states by name 1. Search for states less than or greater than a certain population 1. Search for cities by name for a state 1. List the capital of a state 1. Search for cities less than or greater than a certain population for a state 1. The user interface for this application must be the command line 1. The initial version of this application must store all data in memory, a later version must persist the data to file using one of the techniques shown in class You are to use Collections, Lists, Maps, lambdas, streams and everything else you've learned thus far in the course to solve this problem.
Java
UTF-8
604
2.328125
2
[]
no_license
/** * */ package service; import dao.Dao; /** * @author DUCHAO * */ public class ServiceImpl implements Service { private Dao daoImpl ; public Dao getDaoImpl() { return daoImpl; } public void setDaoImpl(Dao daoImpl) { this.daoImpl = daoImpl; } @Override public void execute(String str) { // TODO Auto-generated method stub System.out.print("HELLO" + str); } @Override public String selectSysDate() { // TODO Auto-generated method stub String str = ""; try { str = daoImpl.selectSysDate(); } catch (Exception e) { e.printStackTrace(); } return str; } }
Python
UTF-8
1,691
4.03125
4
[]
no_license
class Stack(): def __init__(self): self.items = [] def __repr__(self): return repr(self.items) def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def isEmpty(self): return self.items == [] def peak(self): return self.items[-1] def size(self): return len(self.items) # def reverse(self): def reverse(string): s = Stack() for i in string: s.push(i) rs = '' while s.size(): r = s.pop() rs += r print(rs) def checkParenthesis(str): s = Stack() for p in str: if p in '({[': s.push(p) else: if not s.size(): return False else: i = s.pop() if not match(p, i): return False if not s.size(): return True else: return False def divideBybase(num, base): digits = '0123456789ABCDEF' s = Stack() while num: d = num % base s.push(d) num = num // base output = '' while s.size(): output += digits[s.pop()] return output def match(a, b): match_dict = {'}':'{', ']':'[', ')':'('} return match_dict[a] == b def postfix(): """ (a+b)*c-(a-b)*d :return: """ if __name__ == '__main__': # s = Stack() # print(type(s)) # s.push(1) # print(s) # print(list(s)) reverse('cabada') print(checkParenthesis('(([]{(())}))')) print(divideBy2(666,16)) # a = s.pop() # print(a) # list(s) # Write a function revstring(mystr) that uses a stack to reverse the characters in a string.
Python
UTF-8
2,331
2.671875
3
[]
no_license
from json import dumps STD_UNIT = 'kg' def user_json(user): return dumps({ 'id': user._id, 'name': user.name, 'email': user.email, 'password': user.password, 'birthdate': user.birthdate }) def safe_user_json(user): return dumps({ 'id': user._id, 'name': user.name, 'email': user.email, }) def pantry_dictionary(pantry): _pantry = {} _pantry['pantry_id'] = pantry._id _pantry['pantry_name'] = pantry._name _pantry['items'] = [] added_items = set() for item in pantry.get_ingredients(): if item._id not in added_items: added_items.add(item._id) _pantry['items'].append(item_dictionary(item)) return _pantry def item_dictionary(item): _item = {} _item['item_id'] = item._id _item['item_name'] = item._name return _item def user_pantries_json(user, pantries): _json = { 'user_id': user._id } _json['pantries'] = [] for pantry in pantries: _json['pantries'].append(pantry_dictionary(pantry)) return dumps(_json) def ingredients_json(items): ingredients = [] for item in items: ingredients.append(item_dictionary(item)) return dumps({ 'ingredients': ingredients }) def new_pantry_json(user_id, pantry): return dumps({ 'user_id': user_id, 'pantry_name': pantry._name, 'pantry_id': pantry._id, }) def pantry_add_item(pantry): return dumps(pantry_dictionary(pantry)) def pantry_remove_item(pantry): return dumps(pantry_dictionary(pantry)) def ingredient_dictionary(ingredient): return { 'ingredient_id': ingredient._id, 'ingredient_name': ingredient._name, # TODO: check _ } def recipe_dictionary(recipe): res = { 'recipe_id': recipe._id, 'recipe_name': recipe._name, # TODO: check _ 'recipe_percentage': recipe.percentage, 'recipe_ingredients': [] } for ingredient in recipe.ingredients: res['recipe_ingredients'].append(ingredient_dictionary(ingredient)) return res def possible_recipes_json(recipes, pantry_id): res = { 'pantry_id': pantry_id, 'recipes': [], } for recipe in recipes: res['recipes'].append(recipe_dictionary(recipe)) return dumps(res)