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
2,164
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Diagnostics; //using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace File_Manager_ver_2 { public class FindInfoThread : FindInfo_Abstract { string FileForRegex; public FindInfoThread(string CurrentDir, string SelectedItem, int SelectedIndex) : base(CurrentDir, SelectedItem, SelectedIndex) { FileForRegex = "Regex_Thread"; } public override void try_findinfo() { MyFile f2 = new MyFile(FileForRegex); Stopwatch watch = new Stopwatch(); watch.Start(); // сначала необходимо собрать всю информацию по файлам в папке Visitor v = new Visitor(); this.Accept(v); /* * Самое время запустить все потоки и собрать информацию */ // создаем массив из 4-х процессов. (Ровно столько же, сколько у нашего компьютера ядер) MultiRegex[] mr = new MultiRegex[Environment.ProcessorCount]; for (int i = 0; i < mr.Length; i++) { mr[i] = new MultiRegex(file_reg_archive, i); } // запускаем потоки for (int i = 0; i < mr.Length; i++) { mr[i].Start(); } for (int i = 0; i < mr.Length; i++) { mr[i].End(); } for (int i = 0; i < mr.Length; i++) // из каждого потока берем его List data { for (int j = 0; j < data.Length; j++) // @, INN, VK { foreach (string s in mr[i].data[j]) // string из List<string> { data[j].Add(s); } } } FileWrite(FileForRegex); } } }
JavaScript
UTF-8
5,231
3.875
4
[]
no_license
function init() { //Initialize event listener for Basic Calculator var basicCalcBtn = document.getElementById('basic-calc'); basicCalcBtn.addEventListener('click', function(){ //get values from the fields after the button is clicked var basicOperation = document.getElementById('basic-operation').value; var basicNum1 = Number(document.getElementById('basic-num-1').value); var basicNum2 = Number(document.getElementById('basic-num-2').value); //Calculate the answer var answer = evaluate(basicOperation)(basicNum1, basicNum2); //Display answer to answer field var basicAns = document.getElementById('basic-answer-alert'); basicAns.innerHTML = answer.toFixed(4); //Factory to produce a function that does plus, minus, multiply and divide function evaluate(operation) { return function(num1, num2) { if (operation == '+'){ return num1 + num2; } else if(operation == '-') { return num1 - num2; } else if(operation == '*') { return num1 * num2; } else { return num1 / num2; } }; } }); //Initalize event listener for Trip Calculator var tripCalcBtn = document.getElementById('trip-calc'); tripCalcBtn.addEventListener('click', function(){ //get the values of the Trip fields after the button is clicked var tripDistance = Number(document.getElementById('trip-distance').value); var tripMpg = Number(document.getElementById('trip-mpg').value); var tripCost = Number(document.getElementById('trip-cost').value); var tripSpeed = Number(document.getElementById('trip-speed').value); //Calculate the answer var answer = evaluate(tripSpeed)(tripDistance, tripMpg, tripCost); //Display the answer to the answer field var tripAns = document.getElementById('trip-answer-alert'); tripAns.innerHTML = answer.toFixed(2); //Based on the speed return a function with the correct formula function evaluate(speed) { return function(distance, mpg, cost) { if(speed < 60){ return distance / mpg * cost; } else { return distance / (mpg - (speed - 60) * 2) * cost; } }; } }); //Initialize event listener for BMI Calculator var bmiCalcBtn = document.getElementById('bmi-calc'); bmiCalcBtn.addEventListener('click', function() { //get the values of the BMI fields after the button is clicked var bmiHeight = Number(document.getElementById('bmi-height').value); var bmiMass = Number(document.getElementById('bmi-mass').value); var bmiUnits = document.getElementById('bmi-units').value; //Calculate the answer var answer = evaluate(bmiUnits)(bmiMass, bmiHeight); //Display the answer to the answer field var bmiAns = document.getElementById('bmi-answer-alert'); bmiAns.innerHTML = answer.toFixed(2); function evaluate(unitOfMeasure) { return function (mass, height){ if(unitOfMeasure.toLowerCase() == 'metric'){ return (mass / (height * height)); } else { return (mass / (height * height))*703; } } } }); //Initialize event listener for Mortgage Calculator var mortgageCalcBtn = document.getElementById('mortgage-calc'); mortgageCalcBtn.addEventListener('click', function() { //get the values of the BMI fields after the button is clicked var mortgageLoan = Number(document.getElementById('mortgage-loan').value); var mortgageApr = Number(document.getElementById('mortgage-apr').value); var mortgageTerm = Number(document.getElementById('mortgage-term').value); //Calculate the answer var answer = calcMonthlyCost(mortgageLoan, mortgageApr, mortgageTerm); //Display the answer to the answer field var mortgageAns = document.getElementById('mortgage-answer-alert'); mortgageAns.innerHTML = answer.toFixed(2); function calcMonthlyCost(loan, apr, term) { return loan * apr * Math.pow(1 + apr, term) / (Math.pow(1 + apr, term) - 1); } }); //Change the units in the label for BMI fields based on unit selected var bmiUnitsSelect = document.getElementById('bmi-units'); bmiUnitsSelect.addEventListener('change', function(){ //Get the current value of select list var unitOfMeasure = bmiUnitsSelect.value; //Change the text in the label if(unitOfMeasure.toLowerCase() == 'imperial'){ document.getElementById('bmi-mass-unit').innerHTML = "pounds"; document.getElementById('bmi-height-unit').innerHTML = "inches"; } else { document.getElementById('bmi-mass-unit').innerHTML = "kg"; document.getElementById('bmi-height-unit').innerHTML = "m"; } }); }// end of init function init();
Markdown
UTF-8
3,639
2.765625
3
[]
no_license
Modified to work with DEBIAN 11 bullseye and PHP 8.1 ### TuxLite Readme TuxLite is a free collection of shell scripts for rapid deployment of LAMP and LNMP stacks (Linux, Apache/Nginx, MySQL and PHP) for Debian and Ubuntu. Have you considered upgrading from shared hosting to a VPS or dedicated server but held off by the costly control panel licenses, or the fear of managing a Linux server? Now you can leave those worries behind! TuxLite scripts automate configuration of servers for web hosting, so your websites can be online within minutes! Ideal for those who prefer hosting sites on their own server without resorting to expensive and bloated control panels. The following are installed:- - Apache2 with mpm\_event or Nginx - MySQL, MariaDB or Percona - PHP-FPM + commonly used PHP modules removed Postfix mail server (securely configured to be outgoing only) - Varnish cache (optional) For more detailed explanation on the installation, usage and script features, kindly refer to these links:- ### Quick Install (Git) # Install git and clone TuxLite apt install git git clone https://github.com/Almazick/TuxLite cd TuxLite # Edit options to enter server IP, MySQL password etc. nano options.conf # Make all scripts executable. chmod 700 *.sh chmod 700 options.conf # Install LAMP or LNMP stack. ./install.sh # Add a new Linux user and add domains to the user. adduser johndoe ./domain.sh add johndoe yourdomain.com ./domain.sh add johndoe subdomain.yourdomain.com # Install Adminer or phpMyAdmin ./setup.sh dbgui # Enable/disable public viewing of Adminer/phpMyAdmin ./domain.sh dbgui on ./domain.sh dbgui off #Setup MariaDB password. Type line by line #To secure the MariaDB installation, run the next command to improve security of your MySQL server installation. # $ mysql_secure_installation # or mysql -uroot GRANT ALL ON *.* TO 'admin'@'localhost' IDENTIFIED BY 'MyNewPassword' WITH GRANT OPTION; FLUSH PRIVILEGES; or mysql -uroot ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPassword'; flush privileges; exit; then try to login as mysql -uroot -pMyNewPassword ### Requirements - Supports Debian 11, Ubuntu 12.04, 12.10, 13.04, 13.10 and 14.04. - A server with at least 80MB RAM. 256MB and above recommended. - Basic Linux knowledge. You will need know how to connect to your server remotely. - Basic text editor knowledge. For beginners, learning GNU nano is recommended. If this is your first time with a Linux server, I suggest spending a day reading the "getting started" tutorials in Linode Library. ### Why use TuxLite? - TuxLite LAMP stack configures Apache with mpm\_event and PHP with fastcgi (PHP-FPM). This gives much higher performance and lower memory consumption than the regular LAMP tutorials/guides using mod\_php. - Uses official distribution packages. You are not at the mercy of the script maintainer to keep your servers updated. All installed software are tuned, optimized and secured. - Minimal resource usage. Fresh install requires only 50-60MB RAM. - Free from unnecessary or custom changes to your server. Everything is configured according to Debian/Ubuntu standards. - Automatic virtualhost configuration with log rotation, AWStats traffic statistics and phpMyAdmin for managing MySQL. - Varnish cache script included to turbo charge your websites. - Free and open source! Coded in a human readable manner and modular, making custom modifications extremely easy.
Markdown
UTF-8
4,386
3.140625
3
[]
no_license
## 請說明雜湊跟加密的差別在哪裡,為什麼密碼要雜湊過後才存入資料庫 ### 雜湊 * 雜湊無論原文長短,輸出後都會是固定的長度,輸出長度不受原文長度影響 * 雜湊是單向的,無法從輸出推斷出原文 * 不同的原文可能產出相同的雜湊值(雜湊碰撞),但機率極低 * 可能會被暴力破解法、彩虹表查表法破解 ### 加密 * 過程透過加密、解密演算法處理,並使用金鑰進行加密、解密 * 一旦金鑰被盜取,便可以破解原文 * 非對稱式加密(透過公鑰加密內容,私鑰解密)可增強安全性 因為密碼屬於高安全性且僅需個人知道即可,因此不需要具有可逆性,最適合使用雜湊。 若密碼沒有經過雜湊變存入資料庫,即為明碼儲存,一旦被駭客盜取就可以成功駭入使用者的帳戶。如果該使用者在各大網站都使用相同的密碼進行登入,將可以一次盜取多個平台的帳戶。 ![](https://obs.line-scdn.net/0hWhry46ouCEdPAB5C-lF3EHVWCyh8bBtEKzZZRAxuVnBjN0xCemdAdG5VV3BrNk8ZJmdAIm0HE3Y3OBtEJzFA/w1200) [圖片來源:BluesBear 星座小熊](https://today.line.me/tw/v2/article/Q5kGYV) ## `include`、`require`、`include_once`、`require_once` 的差別 include 和 require 都可以在 server 執行當前文件之前,將其他 php 檔案引入。 不同之處在於發生錯誤時,使用 require 會跳 error,且終止程式;而 include 僅會發出 warning,且繼續執行。 而 include_once 與 include 功能相同,差別在於 include_once 會先檢查是否已引入過指定的檔案,若有則不會再重複引入。 require_once 與 require 亦同。 ## 請說明 SQL Injection 的攻擊原理以及防範方法 SQL Injection 也時常被稱為駭客的填字遊戲,意即透過任何能讓使用者在網頁上進行輸入的地方(包括任何輸入框,甚至是使用 get 方法在網址後面帶的參數)填入適合的程式碼,造成原程式碼執行時遭到竄改,進而執行植入的程式碼。若原程式剛好有操作資料庫的行為,一旦被植入的程式執行後,將會對資料庫進行非預期的操作,攻擊者便可透過此方法取得、竄改、刪除資料庫內容。 在撰寫程式時,應完全使用參數化查詢(Parameterized Query)的方式來進行資料庫的操作,處理字串時也應檢查是否有特殊字元、跳脫字元等。 ## 請說明 XSS 的攻擊原理以及防範方法 XSS(Cross Site Scripting)即透過網頁漏洞,將程式碼注入網頁中。常見的方法也是透過任何能讓使用者在網頁上進行輸入的地方,將程式碼當作字串存入目標網站資料庫,一旦資料庫的內容顯示在頁面上,就會直接執行該程式。再者,也能透過 url 參數(或 img element 的 src)執行其他惡意程式,或將使用者導向惡意網站。 在設計網頁程式時,應注意對任何輸入值、導出值進行特殊字元的檢查,此外也能指定 HTTP Header 的解析方式與編碼,以免內容被非預期的方式解析。 ## 請說明 CSRF 的攻擊原理以及防範方法 CSRF(Cross-site request forgery)藉由跨站的方式,讓使用者在不知不覺中將自己瀏覽器中的 cookie 導向其他網站進行操作。比如使用者在 A 網站尚未登出,而在使用 B 網站時,經由惡意程式讓瀏覽器對 A 網站發出 request,並依據瀏覽器帶上相同 domain cookie 的特性,A 網站 server 將會判斷使用者為本人且為登入狀態,使駭客能輕易的藉由惡意程式偽造自己的身份在 A 網站進行操作。 最簡單的預防方式就是使用者在每次使用後都記得登出,不過這樣實在是太不方便了,所以在 server 端進行防範才是最佳的方式。 * **檢查request header referer,確認 request 是否從合法 domain 發出** 難以完全防範、request 不一定會帶 referer * **使用圖形驗證碼、簡訊驗證碼** * **使用 CSRF token** 由 server 隨機產生並儲存於 session 中,每當接受 request 便檢查 client 端的 CSRF token 是否與 server 端相同 * **Double Submit Cookie** server 檢查 cookie 內的 CSRF token 與 form 裡面的 CSRF token 是否有值且相等,但可能透過 subdomain 破解。 * **SameSite cookie(Google 已有)**
Ruby
UTF-8
1,919
2.96875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env ruby Signal.trap("INT") { exit 1 } require "pastel" require "optparse" # Return an unescaped version of delimiter # # @example # unescape("foo\\nbar") => "foo\nbar" # def unescape(str) escable = { '\n' => "\n", '\r' => "\r", '\t' => "\t", '\f' => "\f", '\v' => "\v" } str.gsub(/\\[nrtfv]/) { |m| escable[m] } end options = {} config = { newline: true } ARGV << "-h" if ARGV.empty? parser = OptionParser.new do |opts| opts.banner = "Usage: pastel [options] style [style ...] [text]" opts.on("-d delim", "Specify character to use to split input coloring") do |val| val = val[1..-1] if val.start_with?("=") options[:eachline] = unescape(val) end opts.on("-f", "--force", "Force output coloring regardless of terminal support") do options[:enabled] = true end opts.on("-n", "Skip printing the trailing newline character") do config[:newline] = false end opts.on("-s", "--styles", "Print all available color and style names") do ops = (ARGV.include?("--force") || ARGV.include?("-f")) ? {enabled: true} : {} ops.merge!(options) pastel = Pastel.new(**ops) puts "Swatch Name" pastel.styles.keys.each do |name| next if %i[clear reset].include?(name) puts "%s %s" % [pastel.decorate("◼ pastel", name), name] end exit end opts.on("-h", "--help", "Print this message and exit") do puts opts exit end opts.on("-v", "--version", "Print version information and exit") do puts "0.4.0 (pastel #{Pastel::VERSION})" exit end end begin parser.parse! rescue OptionParser::ParseError => error puts error.message exit 1 end text = STDIN.tty? ? ARGV.pop : $stdin.read pastel = Pastel.new(**options) begin print pastel.decorate(text, *ARGV.map(&:to_sym)) + (config[:newline] ? "\n" : "") rescue Pastel::InvalidAttributeNameError => error puts error.message exit 1 end
C#
UTF-8
1,253
2.921875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; namespace USG_tablet_UI { class TCPconnection { private String IPaddr; private int port; Socket s = null; public TCPconnection(String IP, int po) { this.IPaddr = IP; this.port = po; connect(); } private void connect() { s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipAdd = System.Net.IPAddress.Parse(this.IPaddr); IPEndPoint remoteEP = new IPEndPoint(ipAdd, this.port); s.Connect(remoteEP); } public void disconnect() { s.Disconnect(true); s.Close(); } public void send(String msg) { try // bo nie mozna uzyskac dostepu do usunietego obiektu po powrocie do glownego ekranu { byte[] byData = System.Text.Encoding.ASCII.GetBytes(msg); s.Send(byData); } catch (Exception ex) { } } } }
JavaScript
UTF-8
3,567
2.578125
3
[]
no_license
import React, {Component} from 'react'; import nextId from "react-id-generator"; import styled from 'styled-components'; import AppHeader from '../app-header/'; import AppSearch from '../app-search/'; import AppFilter from '../app-filter/'; import AppForm from '../app-form/'; import AppAdd from '../app-add/' const AppStyle = styled.div` margin: 0 auto; max-width: 800px; ` const DivSearch = styled.div` display: flex; `; export default class App extends Component { state = { data : [ {text : "Учить реакт",important : false, like: false, id : nextId()}, {text : "Отдыхать",important : false, like: false, id : nextId()}, {text : "Прыгать",important : false, like: false, id : nextId()} ], term : '', filter : 'all' } deleteMessage = (id) => { this.setState(({data}) => { const index = data.findIndex(value => value.id === id) const newArr = [...data.slice(0,index),...data.slice(index + 1)] return { data : newArr } }) } addMessage = (body) => { const newMessage = { text : body, important : false, like: false, id : nextId() } this.setState(({data}) => { const newArr = [...data,newMessage] return { data : newArr } }) } onToggleChange(element,id) { this.setState(({data}) => { const index = data.findIndex(value => value.id === id) const old = data[index]; const newItem = {...old, [element]: !old[element]}; const newArr = [...data.slice(0,index), newItem ,...data.slice(index + 1)] return { data : newArr } }) } onToggleLike = (id) => { this.onToggleChange("like",id) } onToggleImportant = (id) => { this.onToggleChange("important",id) } search = (term) => { this.setState({ term }) } searchPost(data,term) { if(term.length === 0) { return data } return data.filter(value => { return value.text.indexOf(term) > - 1 }) } filter(data,filter) { if(filter === "like") { return data.filter(value => value.like) } return data } onChangeTerm = (name) => { this.setState({ filter : name }) } render () { const {data,term,filter} = this.state; const newData = this.filter(this.searchPost(data,term),filter) const countLike = data.filter(value => value.like).length const count = data.length; return ( <AppStyle> <AppHeader countLike = {countLike} count = {count}/> <DivSearch> <AppSearch search = {this.search}/> <AppFilter filter = {filter} onChangeTerm = {this.onChangeTerm}/> </DivSearch> <AppForm content = {newData} deleteMessage = {this.deleteMessage} onToggleImportant ={this.onToggleImportant} onToggleLike ={this.onToggleLike}/> <AppAdd addMessage = {this.addMessage}/> </AppStyle> ) } }
Python
UTF-8
18,622
2.671875
3
[ "MIT" ]
permissive
from os import listdir import cv2 as cv import numpy as np from os import path, makedirs import math import matplotlib.pyplot as plt import argparse import tqdm import tensorflow as tf import time import threading from guided_filter import guided_filter_cv as guided_filter class bbox: def __init__(self, lt, rb): self.lt = [lt[0], lt[1]] self.rb = [rb[0], rb[1]] def is_val(self, img_shape): l_val = self.lt[0] >= 0 t_val = self.lt[1] >= 0 r_val = self.rb[0] < img_shape[0] b_val = self.rb[1] < img_shape[1] if l_val and t_val and r_val and b_val: return True else: return False def get_crop(self, img): if self.is_val(img.shape): return img[self.lt[0]:self.rb[0]+1, self.lt[1]:self.rb[1]+1] else: return None def random_shift(self, img_shape, max_shift): # choose left/right and top/bottom shift_choose = np.random.randint(2, size=(2)) #### Left / Right #### if shift_choose[0] is 0: # shift left tmp_max = min(max_shift, self.lt[0]) if tmp_max > 0: tmp_shift = np.random.randint(tmp_max) self.lt[0] = self.lt[0] - tmp_shift self.rb[0] = self.rb[0] - tmp_shift else: # shift right tmp_max = min(max_shift, img_shape[0] - self.rb[0] - 1) if tmp_max > 0: tmp_shift = np.random.randint(tmp_max) self.lt[0] = self.lt[0] + tmp_shift self.rb[0] = self.rb[0] + tmp_shift #### Lop / Bottom #### if shift_choose[1] is 0: # shift top tmp_max = min(max_shift, self.lt[1]) if tmp_max > 0: tmp_shift = np.random.randint(tmp_max) self.lt[1] = self.lt[1] - tmp_shift self.rb[1] = self.rb[1] - tmp_shift else: # shift bottom tmp_max = min(max_shift, img_shape[1] - self.rb[1] - 1) if tmp_max > 0: tmp_shift = np.random.randint(tmp_max) self.lt[1] = self.lt[1] + tmp_shift self.rb[1] = self.rb[1] + tmp_shift def shift(self, shift_size): shifted = bbox(self.lt, self.rb) shifted.lt[0] = shifted.lt[0] + shift_size[0] shifted.lt[1] = shifted.lt[1] + shift_size[1] shifted.rb[0] = shifted.rb[0] + shift_size[0] shifted.rb[1] = shifted.rb[1] + shift_size[1] return shifted def __repr__(self): tmp = f"LT: {self.lt}, RB: {self.rb}" return tmp def rotate_Fg_Alpha(fg, alpha, angle): def rotatedRectWithMaxArea(w, h, angle): """ https://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders Given a rectangle of size wxh that has been rotated by 'angle' (in radians), computes the width and height of the largest possible axis-aligned rectangle (maximal area) within the rotated rectangle. """ if w <= 0 or h <= 0: return 0, 0 width_is_longer = w >= h side_long, side_short = (w, h) if width_is_longer else (h, w) # since the solutions for angle, -angle and 180-angle are all the same, # if suffices to look at the first quadrant and the absolute values of sin,cos: sin_a, cos_a = abs(math.sin(angle)), abs(math.cos(angle)) if side_short <= 2.*sin_a*cos_a*side_long or abs(sin_a-cos_a) < 1e-10: # half constrained case: two crop corners touch the longer side, # the other two corners are on the mid-line parallel to the longer line x = 0.5*side_short wr, hr = (x/sin_a, x/cos_a) if width_is_longer else (x/cos_a, x/sin_a) else: # fully constrained case: crop touches all 4 sides cos_2a = cos_a*cos_a - sin_a*sin_a wr, hr = (w*cos_a - h*sin_a)/cos_2a, (h*cos_a - w*sin_a)/cos_2a return wr, hr center = (fg.shape[1]//2, fg.shape[0]//2) M = cv.getRotationMatrix2D(center, angle, 1.0) wr, hr = rotatedRectWithMaxArea(fg.shape[1], fg.shape[0], np.deg2rad(angle)) cropped_bbox = (int(wr), int(hr)) rotated_fg = cv.warpAffine(fg, M, fg.shape[::-1]) rotated_alpha = cv.warpAffine(alpha, M, alpha.shape[::-1]) cropped_fg = rotated_fg[center[1]-cropped_bbox[1]//2:center[1]+cropped_bbox[1] // 2, center[0]-cropped_bbox[0]//2:center[0]+cropped_bbox[0]//2] cropped_alpha = rotated_alpha[center[1] - cropped_bbox[1] // 2: center[1] + cropped_bbox[1] // 2, center[0] - cropped_bbox[0] // 2: center[0] + cropped_bbox[0] // 2] return cropped_fg, cropped_alpha def compose(fg, bg, alpha): MAX_BLUR_TIMES = 5 fg = fg.astype(np.float) bg = bg.astype(np.float) fg_blur_times = np.random.randint(1, MAX_BLUR_TIMES+1) bg_blur_times = np.random.randint(1, MAX_BLUR_TIMES+1) filter = [7, 11, 15] # fg_filter = filter[np.random.randint(0, 3)] # bg_filter = filter[np.random.randint(0, 3)] fg_filter = filter[0] bg_filter = filter[0] fg_alpha = fg*alpha # Background Blur bg_blur = bg for i in range(bg_blur_times): bg_blur = cv.GaussianBlur( bg_blur, (bg_filter, bg_filter), (bg_filter-1)/3) bg_blur_alpha = bg_blur*(1-alpha) result1 = fg_alpha + bg_blur_alpha result1 = np.clip(result1, 0, 255) # Foreground Blur fg_alpha_blur = fg_alpha alpha_blur = alpha for i in range(fg_blur_times): fg_alpha_blur = cv.GaussianBlur( fg_alpha_blur, (fg_filter, fg_filter), (fg_filter-1)/3) alpha_blur = cv.GaussianBlur( alpha_blur, (fg_filter, fg_filter), (fg_filter-1)/3) result2 = fg_alpha_blur*(alpha_blur) + bg*(1-alpha_blur) result2 = np.clip(result2, 0, 255) return result1.astype(np.uint8), result2.astype(np.uint8), alpha_blur def get_grid_bbox(img_shape, grid_size, patch_size): row_cond = (img_shape[0] - patch_size[0] - grid_size[0] + 1) >= 0 col_cond = (img_shape[1] - patch_size[1] - grid_size[1] + 1) >= 0 if not (row_cond and col_cond): return [] # row cord_rows = [] val_row_size = img_shape[0] - patch_size[0] + 1 row_space = val_row_size // grid_size[0] for i in range(grid_size[0]): cord_rows.append(i*row_space) cord_rows.append(val_row_size) # column cord_cols = [] val_col_size = img_shape[1] - patch_size[1] + 1 col_space = val_col_size // grid_size[1] for i in range(grid_size[1]): cord_cols.append(i*col_space) cord_cols.append(val_col_size) grids = [] for i in range(grid_size[0]): for j in range(grid_size[1]): lt = [cord_rows[i], cord_cols[j]] rb = [cord_rows[i+1]-1, cord_cols[j+1]-1] grids.append(bbox(lt, rb)) shifted_grids = [] for i in range(len(grids)): shifted_grids.append(grids[i].shift( (patch_size[0]//2-1, patch_size[1]//2-1))) return shifted_grids def get_high_variance_patch(img, patch_size, quantity=1, grid_size=(20, 20)): edges_map = cv.Canny(img, 30, 90, apertureSize=7) grids = get_grid_bbox(img.shape, grid_size, patch_size) grad_grids = [] for g in grids: tmp_crop = g.get_crop(edges_map) if tmp_crop.max() > 0: grad_grids.append(g) patches = [] if len(grad_grids) > 0: for i in range(quantity): tmp_grid = grad_grids[np.random.randint(len(grad_grids))] tmp_crop = tmp_grid.get_crop(edges_map) y_s, x_s = np.where(tmp_crop > 0) tmp_point = np.random.randint(len(y_s)) y, x = y_s[tmp_point], x_s[tmp_point] y = y + tmp_grid.lt[0] x = x + tmp_grid.lt[1] lt = (y - patch_size[0] // 2 + 1, x - patch_size[1] // 2 + 1) rb = (lt[0] + patch_size[0] - 1, lt[1] + patch_size[1] - 1) patches.append(bbox(lt, rb)) return patches def get_random_patch(img, patch_size, quantity=1): lts = [] for i in range(quantity): lt = ( np.random.randint(img.shape[0] - patch_size[0] + 1), np.random.randint(img.shape[1] - patch_size[1] + 1)) rb = (lt[0]+patch_size[0]-1, lt[1]+patch_size[1]-1) lts.append(bbox(lt, rb)) return lts # TFRecords def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value])) def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _float32_feature(value): return tf.train.Feature(float_list=tf.train.FloatList(value=value)) def writeTFRecord(tfrWriter, p1, p2, label): # write data into TFRecord Writer # image serialization str1 = p1.tostring() str2 = p2.tostring() str3 = label.tostring() # Create features tf_features = tf.train.Features(feature={'p1': _bytes_feature( str1), 'p2': _bytes_feature(str2), 'label': _bytes_feature(str3)}) # Create Example tf_example = tf.train.Example(features=tf_features) tfrWriter.write(tf_example.SerializeToString()) def parseDataset(example_proto): # data parsing lambda for parse data of tfrecords file disc = { 'p1': tf.io.FixedLenFeature(shape=(), dtype=tf.string), 'p2': tf.io.FixedLenFeature(shape=(), dtype=tf.string), 'label': tf.io.FixedLenFeature(shape=(), dtype=tf.string) } parse_example = tf.io.parse_single_example(example_proto, disc) parse_example['p1'] = tf.io.decode_raw(parse_example['p1'], tf.float32) parse_example['p1'] = tf.reshape( parse_example['p1'], (320, 320, 1)) parse_example['p2'] = tf.io.decode_raw(parse_example['p2'], tf.float32) parse_example['p2'] = tf.reshape( parse_example['p2'], (320, 320, 1)) parse_example['label'] = tf.io.decode_raw( parse_example['label'], tf.float32) parse_example['label'] = tf.reshape( parse_example['label'], (320, 320, 1)) return parse_example if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument( '--fg_dir', dest='fg_dir', type=str, default='fg', help='directory of the foreground images') parser.add_argument( '--bg_dir', dest='bg_dir', type=str, default='bg', help='directory of the background images') parser.add_argument( '--alpha_dir', dest='alpha_dir', type=str, default='alpha', help='directory of the alpha matting (ground truth)') parser.add_argument('--output', dest='output', type=str, default='train.tfrecords', help='file of processed data') parser.add_argument('--num', dest='num', type=int, default='100000', help='quantity of data') args = parser.parse_args() print(args) fg_dir = args.fg_dir bg_dir = args.bg_dir alpha_dir = args.alpha_dir image_num = int(args.num) tfrecord_path = path.join('.', args.output) writer = tf.io.TFRecordWriter(tfrecord_path) fg_names = listdir(fg_dir) fg_imgs = [] alpha_imgs = [] for fg_name in fg_names: fg_path = path.join(fg_dir, fg_name) alpha_path = path.join(alpha_dir, fg_name) fg = cv.imread(fg_path, cv.IMREAD_GRAYSCALE) fg_imgs.append(fg) alpha_imgs.append(cv.imread(alpha_path, cv.IMREAD_GRAYSCALE)) bgs = listdir(bg_dir) for i in range(image_num): bg_name = bgs[np.random.randint(len(bgs))] bg_path = path.join(bg_dir, bg_name) bg = cv.imread(bg_path, cv.IMREAD_GRAYSCALE) print(f"{i}/{image_num}", f"{i/image_num*100:.2}%", end='\r') # Read fg Image paths rand_fg = np.random.randint(0, len(fg_imgs)) fg = fg_imgs[rand_fg] alpha = alpha_imgs[rand_fg] # FG rotation fg, alpha = rotate_Fg_Alpha(fg, alpha, np.random.rand()*20-10) # FG too small if fg.shape[0] <= 340 or fg.shape[1] <= 340: r = min(fg.shape[0] / 340, fg.shape[1] / 340) new_shape = ( math.ceil(fg.shape[1] / r), math.ceil(fg.shape[0] / r)) fg = cv.resize( fg, new_shape, fx=1 / r, fy=1 / r, interpolation=cv.INTER_CUBIC) alpha = cv.resize( alpha, new_shape, fx=1 / r, fy=1 / r, interpolation=cv.INTER_CUBIC) # Composition wratio = fg.shape[1] / bg.shape[1] hratio = fg.shape[0] / bg.shape[0] ratio = wratio if wratio > hratio else hratio bg_size = (math.ceil(bg.shape[1]*ratio), math.ceil(bg.shape[0]*ratio)) bg = cv.resize(bg, bg_size, fx=ratio, fy=ratio, interpolation=cv.INTER_CUBIC) n_alpha = alpha / 255.0 r1, r2, alpha_blur = compose( fg, bg[:fg.shape[0], :fg.shape[1]], n_alpha) n_r1 = r1 / 255.0 n_r2 = r2 / 255.0 imgf_gray = n_r1 * n_alpha + n_r2 * (1-n_alpha) guided = guided_filter(imgf_gray, n_alpha, 8, 0.1) guided = np.clip(guided, 0, 1) # Randomly crop patches with size 320, 480, 640 lt320 = get_high_variance_patch(alpha, (320, 320), 1) lt480 = get_high_variance_patch(alpha, (480, 480), 1) lt640 = get_high_variance_patch(alpha, (640, 640), 1) lts = [] if len(lt320) > 0: lts.append({'scale': 0, 'lt': lt320}) if len(lt480) > 0: lts.append({'scale': 1, 'lt': lt480}) if len(lt640) > 0: lts.append({'scale': 2, 'lt': lt640}) if len(lts) == 0: lts.append( {'scale': 0, 'lt': get_random_patch(alpha, (320, 320))}) # Create Training Patches rand_int = np.random.randint(len(lts)) training_patches = [] if lts[rand_int]['scale'] == 0: # Crop 320x320 # 1. Choose range, 2. Randomly flip lt320 = lts[rand_int]['lt'] for p in lt320: p.random_shift(guided.shape, 10) # random shift c1 = p.get_crop(n_r1) c2 = p.get_crop(n_r2) gt = p.get_crop(guided) if np.random.rand() > 0.5: c1 = c1[:, ::-1] c2 = c2[:, ::-1] gt = gt[:, ::-1] if np.random.rand() > 0.5: c1 = c1[::-1, :] c2 = c2[::-1, :] gt = gt[::-1, :] if np.random.rand() > 0.5: tmp = c1 c1 = c2 c2 = tmp gt = np.abs(1.0 - gt) training_patches.append({'c1': c1, 'c2': c2, 'gt': gt}) elif lts[rand_int]['scale'] == 1: # Crop 480x480 # 1. Choose range, 2. Resize to 320x320, 3. Randomly flip lt480 = lts[rand_int]['lt'] for p in lt480: p.random_shift(guided.shape, 15) # random shift tmp = 2.0/3.0 c1 = p.get_crop(n_r1) c2 = p.get_crop(n_r2) gt = p.get_crop(guided) c1 = np.clip(cv.resize(c1, (320, 320), fx=tmp, fy=tmp, interpolation=cv.INTER_CUBIC), 0, 1) c2 = np.clip(cv.resize(c2, (320, 320), fx=tmp, fy=tmp, interpolation=cv.INTER_CUBIC), 0, 1) gt = np.clip(cv.resize(gt, (320, 320), fx=tmp, fy=tmp, interpolation=cv.INTER_CUBIC), 0, 1) if np.random.rand() > 0.5: c1 = c1[:, ::-1] c2 = c2[:, ::-1] gt = gt[:, ::-1] if np.random.rand() > 0.5: c1 = c1[::-1, :] c2 = c2[::-1, :] gt = gt[::-1, :] if np.random.rand() > 0.5: tmp = c1 c1 = c2 c2 = tmp gt = np.abs(1.0 - gt) training_patches.append({'c1': c1, 'c2': c2, 'gt': gt}) else: # Crop 640x640 # 1. Choose range, 2. Resize to 320x320, 3. Randomly flip lt640 = lts[rand_int]['lt'] for p in lt640: p.random_shift(guided.shape, 20) # random shift c1 = p.get_crop(n_r1) c2 = p.get_crop(n_r2) gt = p.get_crop(guided) c1 = np.clip(cv.resize(c1, (320, 320), fx=0.5, fy=0.5, interpolation=cv.INTER_CUBIC), 0, 1) c2 = np.clip(cv.resize(c2, (320, 320), fx=0.5, fy=0.5, interpolation=cv.INTER_CUBIC), 0, 1) gt = np.clip(cv.resize(gt, (320, 320), fx=0.5, fy=0.5, interpolation=cv.INTER_CUBIC), 0, 1) if np.random.rand() > 0.5: c1 = c1[:, ::-1] c2 = c2[:, ::-1] gt = gt[:, ::-1] if np.random.rand() > 0.5: c1 = c1[::-1, :] c2 = c2[::-1, :] gt = gt[::-1, :] if np.random.rand() > 0.5: tmp = c1 c1 = c2 c2 = tmp gt = np.abs(1.0 - gt) training_patches.append({'c1': c1, 'c2': c2, 'gt': gt}) # write training data into tfrecords file for patches in training_patches: if patches['c1'].shape == ( 320, 320) and patches['c2'].shape == ( 320, 320) and patches['gt'].shape == ( 320, 320): patches['c1'] = patches['c1'].reshape((320, 320, 1)) patches['c2'] = patches['c2'].reshape((320, 320, 1)) patches['gt'] = patches['gt'].reshape((320, 320, 1)) patches['c1'] = patches['c1']*255.0 patches['c2'] = patches['c2']*255.0 writeTFRecord( writer, patches['c1'].astype(np.float32), patches['c2'].astype(np.float32), patches['gt'].astype(np.float32)) else: print("Shape Error!") writer.close()
Java
UTF-8
387
1.804688
2
[]
no_license
package com.personnal.rhumrating.controller.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Wither; import java.io.Serializable; @Data @Wither @AllArgsConstructor @NoArgsConstructor public class TastingDTO implements Serializable{ private String name; private String country; private String type; }
Java
UTF-8
5,505
2.5
2
[]
no_license
package Steps; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import io.cucumber.datatable.DataTable; import io.cucumber.java.After; import io.cucumber.java.Before; import io.cucumber.java.en.*; public class updatePasswordSteps{ WebDriver driver; @Before public void setup() { System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver"); // Here, chromedriver path is subject to each machine. We can streamline this by containerizing driver = new ChromeDriver(); driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); } @After public void clenup() { driver.manage().deleteAllCookies(); driver.close(); driver.quit(); } @Given("I login to the timetracker as an existing user") public void i_login_to_the_timetracker_as_an_existing_user(DataTable testData) throws Exception { List<String> details = testData.asList(String.class); try { driver.get("https://timetracker.anuko.com/login.php"); driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); driver.findElement(By.id("login")).sendKeys(details.get(0)); Thread.sleep(20); System.out.println("Entered Username"); driver.findElement(By.id("password")).sendKeys(details.get(1)); Thread.sleep(10); System.out.println("Entered Password"); driver.findElement(By.id("btn_login")).click(); System.out.println("Clicked on Login button"); WebElement Logoutele = driver.findElement(By.linkText("Profile")); Logoutele.isDisplayed(); System.out.println("Logged in successfully"); } catch (Exception e){ System.out.println("Something went wrong. Got exception:"+ (e).toString()); } Thread.sleep(30); } @And("I update the Password of the user") public void i_update_the_Password_of_the_user(DataTable testData1) throws Exception { List<String> newdetails = testData1.asList(String.class); try { driver.findElement(By.linkText("Profile")).click(); System.out.println("Clicked on Profile link"); driver.findElement(By.id("password1")).clear(); driver.findElement(By.id("password1")).sendKeys(newdetails.get(0)); System.out.println("Entered new password"); driver.findElement(By.id("password2")).clear(); driver.findElement(By.id("password2")).sendKeys(newdetails.get(1)); System.out.println("Entered new password in Confirm password field"); driver.findElement(By.id("btn_save")).click(); System.out.println("Clicked on Save button"); } catch (Exception e){ System.out.println("Something went wrong. Got exception:"+ (e).toString()); } Thread.sleep(40); } @And("I update the Login of the user") public void i_update_the_login_of_the_user(DataTable testData4) throws Exception { List<String> newdetails = testData4.asList(String.class); try { driver.findElement(By.linkText("Profile")).click(); System.out.println("Clicked on Profile link"); driver.findElement(By.id("login")).clear(); driver.findElement(By.id("login")).sendKeys(newdetails.get(0)); System.out.println("Entered new password"); driver.findElement(By.id("btn_save")).click(); System.out.println("Clicked on Save button"); } catch (Exception e){ System.out.println("Something went wrong. Got exception:"+ (e).toString()); } Thread.sleep(40); } @And("I logout from the timetracker") public void i_logout_from_the_timetracker() throws Exception { try { driver.findElement(By.linkText("Logout")).click(); WebElement elelogintitle = driver.findElement(By.className("page-title")); elelogintitle.isDisplayed(); System.out.println("Logged out successfully"); } catch (Exception e){ System.out.println("Something went wrong. Got exception:"+ (e).toString()); } Thread.sleep(40); } @When("I login with the updated timetracker user details") public void i_login_with_the_updated_timetracker_user_details(DataTable testData3) throws Exception { List<String> updatedcreds = testData3.asList(String.class); try { driver.get("https://timetracker.anuko.com/login.php"); driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); driver.findElement(By.id("login")).clear(); driver.findElement(By.id("login")).sendKeys(updatedcreds.get(0)); Thread.sleep(20); System.out.println("Entered Username"); driver.findElement(By.id("password")).clear(); driver.findElement(By.id("password")).sendKeys(updatedcreds.get(1)); Thread.sleep(10); System.out.println("Entered Password"); driver.findElement(By.id("btn_login")).click(); System.out.println("Clicked on Login button"); WebElement Logoutele = driver.findElement(By.linkText("Profile")); Logoutele.isDisplayed(); System.out.println("Logged in successfully"); } catch (Exception e){ System.out.println("Something went wrong. Got exception:"+ (e).toString()); } Thread.sleep(40); } @Then("I am able to login successfully") public void i_am_able_to_login_successfully() throws Exception { try { WebElement Logoutlink = driver.findElement(By.linkText("Logout")); Logoutlink.isDisplayed(); } catch (Exception e) { System.out.println("Something went wrong. Got Exception:"+(e).toString()); } } }
PHP
UTF-8
435
2.828125
3
[]
permissive
<?php declare(strict_types=1); namespace Linio\Component\Util; class Inflector { public static function pascalize(string $string, string $separator = '_-'): string { return ucfirst(str_replace(' ', '', ucwords(strtr($string, $separator, ' ')))); } public static function camelize(string $string, string $separator = '_-'): string { return lcfirst(self::pascalize($string, $separator)); } }
Java
UTF-8
1,599
2.125
2
[]
no_license
package com.skkj.bcw.blockchainwallet.ui.lead_wallet; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.skkj.bcw.blockchainwallet.inject.Components; import com.yejunsui.bcw.blockchainwallet.R; public class ImportWayPagerAdapter extends FragmentPagerAdapter { public ImportWayPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { switch (position){ case 0: return MnemonicFragment.newInstance(); case 1: return KeyStoreFragment.newInstance(); case 2: return PrivateKeyFragment.newInstance(); case 3: return ObserveFragment.newInstance(); } return null; } @Override public int getCount() { return 4; } @Nullable @Override public CharSequence getPageTitle(int position) { switch (position){ case 0: return Components.appComponent.context().getString(R.string.import_way_mnemonic); case 1: return Components.appComponent.context().getString(R.string.import_way_key_store); case 2: return Components.appComponent.context().getString(R.string.import_way_private_key); case 3: return Components.appComponent.context().getString(R.string.import_way_observe); } return ""; } }
Python
UTF-8
1,129
3.140625
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Jan 9 23:02:57 2019 @author: Hesam """ def whoIsNext(names, r): Next = r+1 ind_name = 0 name = '' counter = 0 while counter < Next: if ind_name+1 >= len(names): ind_name = 0 name=names[ind_name] counter += 1 if counter < Next: name = names[ind_name] counter += 1 ind_name += 1 else: return name # print(ind_name, 1111) else: name=names[ind_name] counter += 1 if counter < Next: name=names[ind_name] counter += 1 ind_name += 1 else: return name return name whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 1) == "Sheldon" whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 52) == "Penny" whoIsNext(["Sheldon", "Leonard", "Penny", "Rajesh", "Howard"], 7230702951) == "Leonard"
C++
UTF-8
727
2.8125
3
[]
no_license
class Solution { public: vector<int> addToArrayForm(vector<int>& A, int K) { vector<int> ret; int n = A.size()-1; int t = 0; while (K) { if (n >=0) { t = A[n] + K%10; } else { t = K%10; } --n; K /= 10; if (t > 9) { ++K; ret.push_back(t-10); } else { ret.push_back(t); } } for (int i=n; i>=0; i--) { ret.push_back(A[i]); } reverse(ret.begin(),ret.end()); return ret; } };
Java
UTF-8
347
3.171875
3
[]
no_license
// Car 클래스를 상속받는 서브클래스(subclass) Automobile public class Automobile extends Car { int seatNum; int getSeatNum() { return seatNum; } // Car 클래스의 upSpeed() 메소드를 오버라이딩 void upSpeed(int value) { if (speed + value >= 300) { speed = 300; } else speed = speed + (int)value; } }
Java
UTF-8
3,898
2.46875
2
[]
no_license
package thinhluffy.com.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import thinhluffy.com.model.*; import thinhluffy.com.service.CategoryService; import thinhluffy.com.service.PostService; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; import java.util.Optional; @RestController public class PostController { @Autowired private PostService postService; @Autowired private CategoryService categoryService; @RequestMapping(value = "/category", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<CategoryBrief>> getAllCategories (HttpServletRequest request){ HttpStatus httpStatus = null; List<CategoryBrief> list = new ArrayList<>(); try { Iterable<Category> listCategories = categoryService.findAll(); for(Category category : listCategories){ CategoryBrief categoryBrief = new CategoryBrief(category.getName()); list.add(categoryBrief); } httpStatus = HttpStatus.OK; }catch (Exception ex){ httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; } return new ResponseEntity<>(list, httpStatus); } @RequestMapping(value = "/post", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<PostBrief>> getAllPosts (HttpServletRequest request){ HttpStatus httpStatus = null; List<PostBrief> list = new ArrayList<>(); try{ Iterable<Post> listPosts = postService.findAll(); for(Post post : listPosts){ PostBrief postBrief = new PostBrief(post.getAuthor(), post.getName()); list.add(postBrief); } httpStatus = HttpStatus.OK; }catch (Exception ex){ httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; } return new ResponseEntity<>(list, httpStatus); } @RequestMapping(value = "/post/category/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<PostWithCategory>> getAllPostsByCategory(@PathVariable int id){ HttpStatus httpStatus = null; List<PostWithCategory> list = new ArrayList<>(); try{ Optional<Iterable<Post>> posts = postService.findAllPostsByCategoryId(id); if(posts.isPresent()){ for(Post post : posts.get()){ PostWithCategory postWithCategory = new PostWithCategory(post.getName(), post.getAuthor(), post.getContent(), post.getCategory().getName()); list.add(postWithCategory); } httpStatus = HttpStatus.OK; }else{ httpStatus = HttpStatus.BAD_REQUEST; } }catch (Exception ex){ httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; } return new ResponseEntity<>(list, httpStatus); } @RequestMapping(value = "/post/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<PostWithCategory> getPostById(@PathVariable int id){ PostWithCategory post = null; HttpStatus httpStatus = null; try{ Post postDB = postService.findById(id); post = new PostWithCategory(postDB.getName(), postDB.getAuthor(), postDB.getContent(), postDB.getCategory().getName()); httpStatus = HttpStatus.OK; }catch (Exception ex){ httpStatus = HttpStatus.INTERNAL_SERVER_ERROR; } return new ResponseEntity<>(post, httpStatus); } }
Python
UTF-8
434
2.96875
3
[]
no_license
import pytest import arrays.even_num_digits as prob class TestEvenNumDigits: def test_case1(self): assert prob.find_numbers([12,345,2,6,7896]) == 2 def test_case2(self): assert prob.find_numbers([555,901,482,1771]) == 1 def test_empty(self): assert prob.find_numbers([]) == 0 def test_case3(self): assert prob.find_numbers([1]) == 0 def test_case4(self): assert prob.find_numbers([22]) == 1
Swift
UTF-8
1,389
2.75
3
[]
no_license
// // ContentView.swift // Graphics Simulator // // Created by Denis Bohm on 10/12/21. // import SwiftUI struct ContentView: View { @EnvironmentObject var deviceModel: DeviceModel static let interval: Float = 0.02 let timer = Timer.publish(every: Double(interval), on: .main, in: .common).autoconnect() var body: some View { VStack { Text("Graphics Simulator") .padding() Image(nsImage: deviceModel.image).frame(width: 128, height: 128).padding(60) }.background(KeyEventHandling()).onReceive(timer){ _ in tick() } } func tick() { fd_timer_update(ContentView.interval) let tick_event = fd_event_get_identifier("fd_ux.tick") fd_event_set(tick_event) fd_event_process() if simulateSSD1327.modified { simulateSSD1327.modified = false let image = NSImage(size: NSSize(width: CGFloat(128), height: CGFloat(128))) image.lockFocus() simulateSSD1327.image.draw(at: NSPoint(x: 0, y: 0), from: NSRect(x: 0, y: 0, width: 128, height: 128), operation: .sourceOver, fraction: 1) image.unlockFocus() deviceModel.setScreen(image: image) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
Python
UTF-8
6,056
2.59375
3
[ "MIT" ]
permissive
import sys import copy import unittest import numpy as np import networkx as nx sys.path.append("..") from contagion import contagion class TestContagion(unittest.TestCase): def test_init_In(self): """ Tests initialization of Infected compartment. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.5, fraction_recovered = 0.35) self.assertEqual(np.sum(network.In), 50) def test_init_Su(self): """ Tests initialization of Susceptible compartment. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.5, fraction_recovered = 0.35) self.assertEqual(np.sum(network.Su), 15) def test_init_Re(self): """ Tests initialization of Recovered compartment. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.5, fraction_recovered = 0.35) self.assertEqual(np.sum(network.Re), 35) def test_reset_Su_In_Re(self): """ Tests reset of compartmental histories. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.5, fraction_recovered = 0.35) network.In -= network.In network.reset_Su_In_Re() self.assertEqual(np.sum(network.In), 50) def test_generate_random_walk_length(self): """ Tests the length of the generated random walk. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.5, fraction_recovered = 0.35) walk = network.generate_random_walk(10) self.assertEqual(len(walk), 10) def test_generate_random_walk_degrees_length(self): """ Tests the length of the generated random degree sequence. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.5, fraction_recovered = 0.35) walk = network.generate_random_walk_degree_sequence(10) self.assertEqual(len(walk), 10) def test_immunize_network_vaccinate(self): """ Tests that network immunization is working correctly. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.5, fraction_recovered = 0.35) Im = copy.deepcopy(network.In) np.random.shuffle(Im) network.immunize_network(Im, efficacy = 0.7) self.assertEqual(np.sum(network.Im), np.sum(Im)) def test_init_histories(self): """ Tests initiation of simulation history. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.25) sim = contagion.Contagion(network, save_history = True) self.assertEqual(len(sim.Su_hist), 1) def test_run_simulation(self): """ Tests that the simulation runs for an appropriate number of steps. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.25) sim = contagion.Contagion(network, save_history = True) sim.run_simulation() self.assertGreater(len(sim.In_hist), 4) def test_time_varying_beta(self): """ Tests that the simulation correctly initializes time-varying transmission rates as a list. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.25) sim = contagion.Contagion( network, beta = [1., 0., 0.5, 1., 0., 0.5]) self.assertIsInstance(sim.beta_queue, list) def test_single_omega(self): """ Tests running of a simulation with a Re-to-Su probability. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.25) sim = contagion.Contagion( network, beta = 0.5, omega = 0.05) sim.run_simulation() self.assertGreater(len(sim.In_hist), 4) def test_multiple_omega(self): """ Tests running of a simulation with Re-to-Su and Im-to_Su probabilities. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.25) Im = copy.deepcopy(network.In) np.random.shuffle(Im) network.immunize_network(Im, efficacy = 0.7) sim = contagion.Contagion( network, beta = 0.5, omega = (0.1, 0.05)) sim.run_simulation() self.assertGreater(len(sim.In_hist), 4) def test_max_infected(self): """ Tests believability of maximum infected during simulation. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.25) sim = contagion.Contagion(network, save_history = True) self.assertGreater(sim.run_simulation_get_max_infected(), 24) def test_max_infected_index(self): """ Tests index of maximum infected during simulation. """ G = nx.barabasi_albert_graph(100, 5) network = contagion.ContactNetwork( G, fraction_infected = 0.25) sim = contagion.Contagion(network, save_history = True) self.assertGreater(sim.run_simulation_get_max_infected_index(), -1) if __name__ == '__main__': unittest.main()
Go
UTF-8
1,937
4.03125
4
[]
no_license
/* Suppose you're given a binary tree represented as an array. For example, [3,6,2,9,-1,10] represents the following binary tree (where -1 is a non-existent node): enter image description here Write a function that determines whether the left or right branch of the tree is larger. The size of each branch is the sum of the node values. The function should return the string "Right" if the right side is larger and "Left" if the left side is larger. If the tree has 0 nodes or if the size of the branches are equal, return the empty string. Example Input: [3,6,2,9,-1,10] Example Output: Left */ package hired import "fmt" func Solution(arr []int64) string { // Type your solution here length := int64(len(arr)) if length == 0 || length == 1 { return "" } else if length == 2 { return "Left" } hl := HeightOfTree(arr[1:]) hr := HeightOfTree(arr[2:]) if hl > hr { return "Left" } else if hr > hl { return "Right" } else { return "" } } func HeightOfTree(arr []int64) int64 { length := int64(len(arr)) if length == 0 { return 0 } else if length == 1 { return 1 } l := LeftChild(0, arr) r := RightChild(0, arr) if l == -1 && r == -1 { return 1 } else if l == -1 && r < length { return 1 + HeightOfTree(arr[r:]) } else if r == -1 && l < length { return 1 + HeightOfTree(arr[l:]) } else if l < length && r < length { fmt.Println(l, r, arr) return 1 + Max(HeightOfTree(arr[r:]), HeightOfTree(arr[l:])) } return 1 } func Max(i, j int64) int64 { if i >= j { return i } return j } func LeftChild(i int64, arr []int64) int64 { var left int64 left = 2*i + 1 length := int64(len(arr)) if i < 0 || i > length || left > length || arr[left] == -1 { return -1 } return left } func RightChild(i int64, arr []int64) int64 { var right int64 length := int64(len(arr)) right = 2*i + 2 if i < 0 || i > length || right > length || arr[right] == -1 { return -1 } return right }
PHP
UTF-8
1,349
2.65625
3
[]
no_license
<?php class OInstaller implements Operation{ public function doOp($data = null){ global $PATH; if($_POST['userDB'] == $PATH['mysql']['user'] && $_POST['pwdDB'] == $PATH['mysql']['password'] ){ //creo la connessione al db mysql_connect( $PATH['mysql']['host'], $PATH['mysql']['user'], $PATH['mysql']['password'] ); mysql_query('CREATE DATABASE IF NOT EXISTS '. $_POST['nameDB']); mysql_select_db($_POST['nameDB']); $PATH['mysql']['database'] = $_POST['nameDB']; $this->importa_sql($_POST['nameDB'].'.sql'); } else{ return false; } } private function importa_sql($sqlfile) { // estraggo il contenuto del file $queries = file_get_contents($sqlfile); // Rimuovo eventuali commenti $queries = preg_replace(array('/\/\*.*(\n)*.*(\*\/)?/', '/\s*--.*\n/', '/\s*#.*\n/'), "\n", $queries); // recupero le singole istruzioni $statements = explode(";\n", $queries); $statements = preg_replace("/\s/", ' ', $statements); // ciclo le istruzioni foreach ($statements as $query) { $query = trim($query); if ($query) { // eseguo la singola istruzione $result = mysql_query($query); // e stampo eventuali errori if (!$result) throw new Exception('Impossibile eseguire la query ' . $query . ': ' . mysql_error()); } } } }
Markdown
UTF-8
1,113
2.75
3
[]
no_license
--- title: 'Elven Trade' taxonomy: category: - docs twittercardoptions: summary articleenabled: false musiceventenabled: false orgaenabled: false orga: ratingValue: 2.5 orgaratingenabled: false eventenabled: false personenabled: false restaurantenabled: false restaurant: acceptsReservations: 'yes' priceRange: $ media_order: Alfglass.jpg --- Although we can not go through the portal we are able to throw certain items in to get new items, this works just like the Mana Pool but instead of normal items such as iron and Ender Pearls you will throw in Mana infused items. ### Elementium Ingot Throwing in 2 Mana Steel Ingots will get you 1 Elementium Ingot, these can be turned into Blocks as well as Nuggets. ### Dragonstone Throwing in 1 Mana Diamond will give you 1 Dragonstone. ### Pixie Dust Throwing in 1 Mana Pearl will give you 1 Pixie Dust. ### Dreamwood Throwing in 1 Living Wood will give you 1 Dream Wood, this can be crafted into sticks. ### Alfglass Throwing in 1 Mana Glass will give you one Alfglass. This glass glows and can be broken and reused. ![](Alfglass.jpg)
Java
UTF-8
1,179
2.203125
2
[]
no_license
package com.example.ISABackend.repository; import com.example.ISABackend.model.DermatologistAppointment; import com.example.ISABackend.model.MedicineReservation; import com.example.ISABackend.model.Pharmacy; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Lock; import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.QueryHints; import org.springframework.data.repository.query.Param; import javax.persistence.LockModeType; import javax.persistence.QueryHint; import java.util.ArrayList; public interface MedicineReservationRepository extends JpaRepository<MedicineReservation, Long> { ArrayList<MedicineReservation> findByMedicineId(Long medicineId); ArrayList<MedicineReservation> findByPharmacyId(Long pharmacyId); ArrayList<MedicineReservation> findByPatientId(Long patientId); @Lock(LockModeType.PESSIMISTIC_WRITE) @QueryHints({@QueryHint(name = "javax.persistence.lock.timeout", value ="0")}) @Query("select mr.id from MedicineReservation mr where mr.id = :id") public MedicineReservation findOneById(@Param("id")Long id); }
C++
UTF-8
547
2.75
3
[]
no_license
#include<cstdio> using namespace std; int main() { int n; scanf("%d", &n); if (n % 3 == 0 && n % 5 == 0 && n % 7 == 0) { printf("%d %d %d", 3, 5, 7); } else if (n % 3 == 0 && n % 5 == 0) { printf("%d %d", 3, 5); } else if (n % 3 == 0 && n % 7 == 0) { printf("%d %d", 3, 7); } else if (n % 5 == 0 && n % 7 == 0) { printf("%d %d", 5, 7); } else if (n % 3 == 0) { printf("%d", 3); } else if (n % 5 == 0) { printf("%d", 5); } else if (n % 7 == 0) { printf("%d", 7); } else { printf("%c", 'n'); } return 0; }
Java
UTF-8
1,091
2.453125
2
[]
no_license
package Cube.GameObjects; import Cube.Draw; import Cube.GO; import Cube.Draw; import Cube.GO; import org.lwjgl.opengl.Display; import java.util.Random; public class GOBonus extends GO { public GOBonus() { this.sx = 25; this.sy = 25; this.figure = 1; Random random = new Random(); this.x = Math.abs(random.nextInt()) % (Display.getWidth() - 100 + 1); random = new Random(); this.y = Math.abs(random.nextInt()) % (Display.getHeight() - 100 + 1); } public GOBonus(int figure, float sx, float sy) { this.sx = sx; this.sy = sy; this.figure = figure; Random random = new Random(); this.x = Math.abs(random.nextInt()) % (Display.getWidth() - 100 + 1); random = new Random(); this.y = Math.abs(random.nextInt()) % (Display.getHeight() - 100 + 1); } @Override public void update() { } @Override public void render() { Draw.draw(figure, x, y, sx, sy); } @Override public String name() { return "bonus"; } }
Markdown
UTF-8
1,927
3.203125
3
[]
no_license
# 11657번 타임머신 > 문제 https://www.acmicpc.net/problem/11657 > 조건 도시의 개수 N (1 ≤ N ≤ 500), 버스 노선의 개수 M (1 ≤ M ≤ 6,000)이 주어지고 M개의 버스 노선의 정보 A, B, C (1 ≤ A, B ≤ N, -10,000 ≤ C ≤ 10,000)가 주어질 때 1번 도시에서 나머지 도시로 가는 가장 빠른 시간을 나타내라 > 접근법 도시와 버스라는 점에서 그래프, 노선의 정보가 음수를 포함하고 있다는 것에서 **벨만포드**를 떠올리고 탐색하면 된다. > 코드 ``` c++ #include<bits/stdc++.h> using namespace std; typedef long long ll; struct vtx { int to, w; }; //priority_queue를 위한 연산자 오버라이딩 bool operator < (vtx a, vtx b) { return a.w == b.w ? a.to > b.to : a.w > b.w; } int v, e; int WMAX = 1e8; vector<vtx > vec[202020]; int arr[20202]; //벨만포드 구현 vector<int> bfs(int s) { vector<int> ans(v + 1, WMAX); vector<int> fail(v + 1, -1); priority_queue<vtx> q; ans[s] = 0; q.push({ s,0 }); arr[s] = 1; int cnt = 0; while (q.size()) { int cur = q.top().to, w = q.top().w; q.pop(); for (int i = 0; i < vec[cur].size(); i++) { int next = vec[cur][i].to, nextw = vec[cur][i].w; if (ans[next] > w + nextw) { arr[next] = arr[cur] + 1; ans[next] = w + nextw; q.push({ next,nextw + w }); } if (arr[next] > v) { arr[s] = -1; return ans; } } } return ans; } int main() { cin >> v >> e; for (int i = 0; i < e; i++) { int from, to, w; cin >> from >> to >> w; vec[from].push_back({ to,w }); } vector<int> ans = bfs(1); if (arr[1] < 0) { puts("-1"); return 0; } for (int i = 2; i < ans.size() ; i++) { if (ans[i] == WMAX) cout << "-1" << "\n"; else cout << ans[i] << "\n"; } } ``` > 배운 점 **벨만포드**의 기본 구조에 대한 문제이기에 구현에 있어서 순서만 헷갈리지 않으면 풀 수 있을 것이다.
C++
GB18030
696
3.4375
3
[]
no_license
//Ŀ //nȡɸ1n͵mϵĸ //統n = 6m = 8ʱϣ[2, 6], [3, 5], [1, 2, 5], [1, 3, 4]޶nmС120 #include<iostream> #include<math.h> #include<algorithm> #include<string> using namespace std; int main() { int a, b; while (cin >> a >> b) { if (a > b || a < 1 || b < 1 || a>1000000000 || b> 1000000000) cout << -1 << endl; string a1, b1; a1 = to_string(a); b1 = to_string(b); int lena, lenb; lena = a1.size(); lenb = b1.size(); int i, sums = 0; for (i = lena; i < lenb; i++) sums = sums + pow(2, i); cout << sums << endl; } return 0; }
C
UTF-8
2,210
3.125
3
[]
no_license
#include "hw6.h" #include <stdlib.h> #include <stdio.h> #include <pthread.h> typedef struct elevator { pthread_mutex_t sword; pthread_barrier_t shield; int current_floor; int dest; int is_locked; enum {ELEVATOR_ARRIVED=1, ELEVATOR_OPEN=2, ELEVATOR_CLOSED=3} state; } elevator; elevator E[ELEVATORS]; int is_locked[ELEVATORS]; void scheduler_init() { for(int i = 0; i < ELEVATORS; ++i) { E[i].current_floor = 0; E[i].dest = -1; E[i].state=ELEVATOR_ARRIVED; E[i].is_locked = 0; pthread_barrier_init(&E[i].shield, 0, 2); pthread_mutex_init(&E[i].sword, 0); } for(int i = 0; i < ELEVATORS; ++i) { is_locked[i] = 0; } } void passenger_request(int passenger, int from_floor, int to_floor, void (*enter)(int, int), void(*exit)(int, int)) { int dif = 999999; int min = -1; while(min == -1) { for(int i = 0; i < ELEVATORS; ++i) { if((is_locked[i] == 0) && E[i].dest == -1 && abs(E[i].current_floor - from_floor) < dif) { min = i; dif = abs(E[i].current_floor - from_floor); } } } is_locked[min] = 1; pthread_mutex_lock(&E[min].sword); E[min].dest = from_floor; pthread_barrier_wait(&E[min].shield); enter(passenger, min); E[min].dest = to_floor; pthread_barrier_wait(&E[min].shield); pthread_barrier_wait(&E[min].shield); exit(passenger, min); E[min].dest = -1; pthread_barrier_wait(&E[min].shield); pthread_mutex_unlock(&E[min].sword); is_locked[min] = 0; } void elevator_ready(int elevator, int at_floor, void(*move_direction)(int, int), void(*door_open)(int), void(*door_close)(int)) { if(E[elevator].dest == at_floor) { door_open(elevator); E[elevator].state = ELEVATOR_OPEN; pthread_barrier_wait(&E[elevator].shield); pthread_barrier_wait(&E[elevator].shield); door_close(elevator); E[elevator].state = ELEVATOR_CLOSED; } else { if(E[elevator].dest == -1) { return; } else { if(at_floor < E[elevator].dest) { move_direction(elevator, 1); E[elevator].current_floor++; } else if(at_floor > E[elevator].dest) { move_direction(elevator, -1); E[elevator].current_floor--; } } if(E[elevator].dest == at_floor) { E[elevator].state = ELEVATOR_ARRIVED; } } }
C++
UTF-8
1,498
2.5625
3
[]
no_license
/*******************************************************************************\ * * * Utilities : SmartPointerDeclarations * * Purpose : Some utility macros to define smart pointer type names * * File : SmartPointerDeclarations.h * * Author : Tibor den Ouden * * * \*******************************************************************************/ #pragma once #ifndef __SMART_POINTER_DECLARATIONS_H__ #define __SMART_POINTER_DECLARATIONS_H__ // Standard headers #include <memory> #define POINTER_DECLARATIONS(inClass) \ typedef std::shared_ptr<inClass> Sp##inClass; \ typedef std::unique_ptr<inClass> Up##inClass; \ typedef std::weak_ptr <inClass> Wp##inClass; \ \ typedef std::shared_ptr<const inClass> SpConst##inClass; \ typedef std::unique_ptr<const inClass> UpConst##inClass; \ typedef std::weak_ptr <const inClass> WpConst##inClass; #define CLASS_FORWARD_DECLARATIONS(inClass) \ class inClass; \ POINTER_DECLARATIONS(inClass) #define STRUCT_FORWARD_DECLARATIONS(inStruct) \ struct inStruct; \ POINTER_DECLARATIONS(inStruct) #endif // __SMART_POINTER_DECLARATIONS_H__
PHP
UTF-8
1,044
3.03125
3
[]
no_license
<?php class Upload{ public static function to_folder($folder){ $file = $_FILES['file']['name']; $tmp = $_FILES['file']['tmp_name']; $error = $_FILES['file']['error']; if($error == 0){ move_uploaded_file($tmp, $folder.$file); return $folder.$file; }else if($error == 1 || $error == 2){ echo 'The file you are attempting to upload is too large'; return false; }else if($error == 3){ echo 'The file you are attempting to upload is incomplete'; return false; }else if($error == 4){ echo 'No file was uploaded'; return false; }else{ echo 'Unknown error'; return false; } } public static function multiple_to_folder($folder){ $files_array = array(); for($i = 0; $i < count($_FILES['file']['name']); $i++){ $file = $_FILES['file']['name'][$i]; $tmp = $_FILES['file']['tmp_name'][$i]; $error = $_FILES['file']['error'][$i]; if($error == 0){ move_uploaded_file($tmp, $folder.$file); $files_array[] = $folder.$file; } } return $files_array; } }
Java
UTF-8
4,608
2.0625
2
[]
no_license
package com.zx.zsmarketmobile.ui.system; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.InputType; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import com.zx.zsmarketmobile.R; import com.zx.zsmarketmobile.ui.base.BaseActivity; import com.zx.zsmarketmobile.ui.mainbase.GuideActivity; import com.zx.zsmarketmobile.ui.mainbase.HomeActivity; import com.zx.zsmarketmobile.http.ApiData; import com.zx.zsmarketmobile.http.BaseHttpResult; import com.zx.zsmarketmobile.view.ClearEditText; import com.zx.zsmarketmobile.util.MyApplication; import com.zx.zsmarketmobile.util.Util; /** * Created by zhouzq on 2016/12/15. */ public class SettingsPassWordActivity extends BaseActivity implements View.OnClickListener { private ClearEditText oldPswEditText, newPswEditText, renewPswEditText; private Button btnConfirm; private CheckBox showPswBox; private ApiData updatePswData = new ApiData(ApiData.HTTP_ID_psw_update); private SharedPreferences mSharePreferences; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings_psw); addToolBar(true); setMidText("密码修改"); hideRightImg(); initView(); } private void initView() { oldPswEditText = (ClearEditText) findViewById(R.id.old_psw_edit); newPswEditText = (ClearEditText) findViewById(R.id.new_psw_edit); renewPswEditText = (ClearEditText) findViewById(R.id.renew_psw_edit); btnConfirm = (Button) findViewById(R.id.btn_yes); btnConfirm.setOnClickListener(this); showPswBox = (CheckBox) findViewById(R.id.btn_show_psw); showPswBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { oldPswEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); newPswEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); renewPswEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } else { oldPswEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); newPswEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); renewPswEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); } } }); mSharePreferences = PreferenceManager.getDefaultSharedPreferences(this); updatePswData.setLoadingListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_yes: submitToServer(); break; default: break; } } private void submitToServer() { if (!Util.checkContentLengthIsOverRun(new EditText[]{oldPswEditText, newPswEditText, renewPswEditText}, 5, 15)) { String useName = mSharePreferences.getString("curuser", ""); String oldPswStr = oldPswEditText.getText().toString(); String newPswStr = newPswEditText.getText().toString(); String renewPswStr = renewPswEditText.getText().toString(); if (!renewPswStr.equals(newPswStr)) { Util.setRequired(newPswEditText, "两次新密码不一致,请检查后再试!"); } else if (oldPswStr.equals(newPswStr)) { Util.setRequired(newPswEditText, "新密码与旧密码相同,请重新设置!"); } else { updatePswData.loadData(oldPswStr, newPswStr); } } } @Override public void onLoadComplete(int id, BaseHttpResult baseHttpResult) { super.onLoadComplete(id, baseHttpResult); if (baseHttpResult.isSuccess()) { showToast("密码修改成功!"); MyApplication.getInstance().remove(SettingsActivity.class); MyApplication.getInstance().remove(HomeActivity.class); MyApplication.getInstance().remove(GuideActivity.class); finish(); } else { showToast(baseHttpResult.getMessage()); } } }
C
UTF-8
1,490
3.828125
4
[]
no_license
/* Задача 8. Напишете обединение от число и низ, както и описател с изброим тип за съдържанието на обединението. Напишете функция, която получава указател към обединението и изброимия тип и извежда съответно низ или число. */ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> union MyUnion { uint32_t Var1; float Var2; char Var3[30]; }; enum ToPrint { Integer, Floater, Stringer }; typedef struct Combined{ union MyUnion UnionValue; enum ToPrint Selector; }selection; void UnionPrinter (selection* pEnumerate); int main(){ selection Enumerator; Enumerator.UnionValue.Var1=130; Enumerator.UnionValue.Var2 = 2.50; strcpy(Enumerator.UnionValue.Var3, "shokolad"); selection *pEnum = &Enumerator; printf("Please select what you want to print:\n"); printf("1. The integer; 2. The floater; 3. The stringer\n"); scanf("%d", &Enumerator.Selector); UnionPrinter(pEnum); } void UnionPrinter (selection* pEnumerate){ if (pEnumerate->Selector == 1){ printf("%d", pEnumerate->UnionValue.Var1); } else if(pEnumerate->Selector == 2){ printf("%.2f", pEnumerate->UnionValue.Var2); } else if(pEnumerate->Selector == 3){ printf("%s", pEnumerate->UnionValue.Var3); } }
Go
UTF-8
700
2.640625
3
[]
no_license
package Binding import ( "minsk/CodeAnalysis/Binding/Kind/BoundNodeKind" "minsk/Util" ) type BoundWhileStatement struct { *Util.ChildrenProvider Condition BoundExpression Body BoundStatement } func NewBoundWhileStatement(condition BoundExpression, body BoundStatement) *BoundWhileStatement { return &BoundWhileStatement{ ChildrenProvider: Util.NewChildrenProvider(condition, body), Condition: condition, Body: body, } } func (b *BoundWhileStatement) Kind() BoundNodeKind.BoundNodeKind { return BoundNodeKind.WhileStatement } //todo func (b *BoundWhileStatement) GetProperties() []*BoundNodeProperty { return []*BoundNodeProperty{} }
Go
UTF-8
589
2.796875
3
[ "MIT" ]
permissive
/* * @lc app=leetcode.cn id=503 lang=golang * * [503] 下一个更大元素 II */ // @lc code=start func nextGreaterElements(nums []int) []int { res:=[]int{} i:=0 num2:=make([]int,len(nums)) copy(num2,nums) num2=append(num2,nums...) // fmt.Println(num2) // fmt.Println(len(nums)) for index,value:=range nums{ position:=-1 for i=index+1;i<len(num2);i++{ if num2[i]>value{ position=num2[i] break } } res=append(res,position) } return res } // @lc code=end
Swift
UTF-8
205
2.953125
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
import Foundation public class KeyValue: NSObject { public let key: String? public let value: Any? init(key: String?, value: Any?) { self.key = key self.value = value } }
Java
UTF-8
3,383
2.3125
2
[]
no_license
package br.com.rsi.exercicios.projetoExercicios.steps.definition; import java.util.UUID; import org.springframework.test.context.ContextConfiguration; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import br.com.rsi.exercicios.projetoExercicios.steps.business.StepBusinessNetshoes; import net.thucydides.core.annotations.Steps; @ContextConfiguration("/appcontext.xml") public class StepDefinitionNetshoes { @Steps StepBusinessNetshoes stepB; @Given("^estou na pagina do site do netshoes \"([^\"]*)\"$") public void estou_na_pagina_do_site_do_netshoes(String url) throws Throwable { stepB.abrirPagina(url); } //CT01 e CT02 - (Adicionar item ao carrinho) @When("^preencho o campo 'Busca' \"([^\"]*)\"$") public void preencho_o_campo_Busca(String busca) throws Throwable { stepB.preencherCampoBusca(busca); } @When("^clico no icone de busca$") public void clico_no_icone_de_busca() throws Throwable { stepB.clicarIconeBusca(); } @When("^clico no link do produto \"([^\"]*)\"$") public void clico_no_link_do_produto(String nomeProduto) throws Throwable { stepB.clicarLinkProduto(nomeProduto); } @When("^clico no rdb 'color' \"([^\"]*)\"$") public void clico_no_rdb_color(int pos) throws Throwable { stepB.clicarRdbCores(pos); } @When("^clico no rdb 'size' \"([^\"]*)\"$") public void clico_no_rdb_size(String numTam) throws Throwable { stepB.clicarRdbTamanho(numTam); } @When("^clico no botao 'Comprar'$") public void clico_no_botao_Comprar() throws Throwable { stepB.clicarBotaoComprar(); } @Then("^verifico o produto no carrinho \"([^\"]*)\"$") public void verifico_o_produto_no_carrinho(int qtd) throws Throwable { stepB.verificarProdutoNoCarrinho(qtd); } //CT03(Escolher um calçado na secao outlet com valor abaixo de 150 reais) @When("^clico no link em 'Outlet' \"([^\"]*)\"$") public void clico_no_link_calcados_masculinos_em_Outlet(String link) throws Throwable { stepB.clicarLinkOutlet(link); } @When("^clico na ckb 'Preco' \"([^\"]*)\"$") public void clico_na_ckb_Preco(double valor) throws Throwable { stepB.clicarCkbsPrecos(valor); } //CT04(Adicionar item ao carrinho e calcular frete) @When("^preencho o campos do 'CEP' \"([^\"]*)\"$") public void preencho_o_campos_do_CEP(String cep) throws Throwable { stepB.preencherCampoCep(cep); } @When("^clico no botao 'Calcular Frete'$") public void clico_no_botao_Calcular_Frete() throws Throwable { stepB.clicarBtnCalcularFrete(); } @Then("^verifico o calculo do frete$") public void verifico_o_calculo_do_frete() throws Throwable { stepB.verificarCalculoFrete(); } //CT05(Adicionar item no carrinho, Limpar Carrinho e voltar para loja) @When("^clico no link 'limpar carrinho'$") public void clico_no_link_limpar_carrinho() throws Throwable { stepB.clicarLinkLimparCarrinho(); } @When("^clico no link 'voltar para a loja'$") public void clico_no_link_voltar_para_a_loja() throws Throwable { stepB.clicarLinkVoltarLoja(); } @Then("^verifico se esta na pagina especifica \"([^\"]*)\"$") public void verifico_se_esta_na_pagina_especifica(String url) throws Throwable { stepB.verificarPaginaCorrespondente(url); } }
Markdown
UTF-8
1,144
3.328125
3
[]
no_license
# Progress 对象 使用 Progress 对象可以为 CodeSmith 生成代码的过程显示一个进度条,这对于生成比较费时的模板操作是非常有用的,如果你使用 Visual Studio,可以在状态栏中显示一进度条: ![第17张](images/17.png) 使用进度条的方法是通过 CodeTemplate 对象的 Progress 属性对象,首先是设置 Progress 对象的最大值和步长,本例通过一个简单的循环来模拟一个费时的操作: ``` <%@ Template Language="C#" TargetLanguage="Text" Debug="False" %> <%@ Import Namespace="System.Threading" %> This is a progress demo. <% SimulateProgress(); %> <script runat="template"> public void SimulateProgress(){ Progress.MaximumValue = 25; Progress.Step = 1; for(int i=0;i<25;i++){ Progress.PerformStep(); Thread.Sleep(100); Response.WriteLine("step {0} ",i); } } </script> ``` 让进度条前进一步是通过 Progress 对象的 PerfStep 方法来实现的。 本例[下载](http://www.imobilebbs.com/download/codesmith/ProgressDemo.zip) Tags: [CodeSmith](http://www.imobilebbs.com/wordpress/archives/tag/codesmith)
C++
UTF-8
808
2.875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { string s; bool check=true; vector<string>v; do{ cin>>s; v.push_back(s); if(cin.get()=='\n') check=false; } while(check); int n=v.size(); if(n==1) {v[0][0]=toupper(v[0][0]); for(int i=1;i<v[0].size();i++) v[0][i]=tolower(v[0][i]); cout<<v[0]<<endl;} else { for(int i=0;i<v.size()-1;i++) { v[i][0]=toupper(v[i][0]); v[i][1]='.'; v[i].resize(2); } v[v.size()-1][0]=toupper(v[v.size()-1][0]); for(int i=1;i<v[v.size()-1].size();i++) v[v.size()-1][i]=tolower(v[v.size()-1][i]); for(int i=0;i<v.size();i++) cout<<v[i]<< " "; cout<<endl; } } return 0; }
Java
UTF-8
1,074
2.421875
2
[]
no_license
package com.joshcummings.codeplay.terracotta.security; import org.zaproxy.clientapi.core.ApiResponse; import org.zaproxy.clientapi.core.ApiResponseList; import org.zaproxy.clientapi.core.ApiResponseSet; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ScanResponse { List<ScanInfo> scans = new ArrayList<>(); public ScanResponse(ApiResponseList responseList) { for (ApiResponse rawResponse : responseList.getItems()) { scans.add(new ScanInfo((ApiResponseSet)rawResponse)); } Collections.sort(scans); } public List<ScanInfo> getScans() { return scans; } public ScanInfo getScanById(int scanId) { for (ScanInfo scan : scans) { if (scan.getId() == scanId) { return scan; } } return null; } public ScanInfo getLastScan() { if (scans.size() == 0) { throw new IllegalArgumentException("No scans founds"); } return scans.get(scans.size() - 1); } }
Python
UTF-8
474
2.875
3
[]
no_license
import numpy as np def calc_distance_squared(src, dst): return np.sum((src - dst)**2) def calc_rotation(src, dst): A = np.dot(dst.T, src) V, S, W = np.linalg.svd(A) U = np.dot(V, W) return U def rmsd_kabsch(src, dst, return_rotated=False): U = calc_rotation(src, dst) rotated = np.dot(src, U.T) rmsd = np.sqrt(calc_distance_squared(dst, rotated)) if return_rotated: return rmsd, rotated else: return rmsd
C
UTF-8
105
2.625
3
[]
no_license
#include <stdio.h> int main(){ int val1 = 5; int *pt1; pt1=&val1; printf("%d", *pt1); return 0; }
Java
UTF-8
6,469
1.9375
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2012 Comcast Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.comcast.cns.io; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import com.comcast.cmb.common.util.CMBErrorCodes; import com.comcast.cmb.common.util.CMBException; import com.comcast.cmb.common.util.CMBProperties; import com.comcast.cns.model.CNSMessage.CNSMessageStructure; import com.comcast.cns.model.CNSMessage.CNSMessageType; import com.comcast.cns.model.CNSSubscription.CnsSubscriptionProtocol; /** * Following class uses the HttpClient library version 4.2.1 * @author aseem, bwolf */ public class HTTPEndpointSyncPublisher extends AbstractEndpointPublisher { private final static SchemeRegistry schemeRegistry = new SchemeRegistry(); private final static PoolingClientConnectionManager cm; private final static HttpClient httpClient; static { int timeoutMillis = CMBProperties.getInstance().getCNSPublisherHttpTimeoutSeconds() * 1000; HttpParams params = new BasicHttpParams(); if (CMBProperties.getInstance().getCNSHttpProxy() != null && !CMBProperties.getInstance().getCNSHttpProxy().equals("")) { String p[] = CMBProperties.getInstance().getCNSHttpProxy().split(":"); if (p.length == 2) { HttpHost proxy = new HttpHost(p[0], Integer.parseInt(p[1]), "http"); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } } HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); HttpConnectionParams.setConnectionTimeout(params, timeoutMillis); HttpConnectionParams.setSoTimeout(params, timeoutMillis); cm = new PoolingClientConnectionManager(schemeRegistry); // increase max total connection to 250 cm.setMaxTotal(CMBProperties.getInstance().getCNSPublisherHttpEndpointConnectionPoolSize()); // increase default max connection per route to 20 cm.setDefaultMaxPerRoute(CMBProperties.getInstance().getCNSPublisherHttpEndpointConnectionsPerRouteSize()); httpClient = new DefaultHttpClient(cm, params); } private static Logger logger = Logger.getLogger(HTTPEndpointSyncPublisher.class); public static int getNumConnectionsInPool() { return cm.getTotalStats().getAvailable(); } @Override public void send() throws Exception { if ((message == null) || (endpoint == null)) { logger.debug("event=send_http_request error_code=MissingParameters endpoint=" + endpoint + "\" message=\"" + message + "\""); throw new Exception("Message and Endpoint must both be set"); } HttpPost httpPost = new HttpPost(endpoint); String msg = null; if (message.getMessageStructure() == CNSMessageStructure.json) { msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http); } else { msg = message.getMessage(); } if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) { msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http); } logger.debug("event=send_sync_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\""); StringEntity stringEntity = new StringEntity(msg); httpPost.setEntity(stringEntity); composeHeader(httpPost); HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); // accept all 2xx status codes if (statusCode > 200 || statusCode >= 300) { if (entity != null) { InputStream instream = entity.getContent(); InputStreamReader responseReader = new InputStreamReader(instream); StringBuffer buffer = new StringBuffer(); char []arr = new char[1024]; int size = 0; while ((size = responseReader.read(arr, 0, arr.length)) != -1) { buffer.append(arr, 0, size); } instream.close(); } logger.debug("event=http_post_error endpoint=" + endpoint + " error_code=" + statusCode); throw new CMBException(new CMBErrorCodes(statusCode, "HttpError"), "Unreachable endpoint " + endpoint + " returns status code " + statusCode); } else { if (entity != null) { EntityUtils.consume(entity); } } } private void composeHeader(HttpRequestBase httpRequest) { httpRequest.setHeader("x-amz-sns-message-type", this.getMessageType()); httpRequest.setHeader("x-amz-sns-message-id", this.getMessageId()); httpRequest.setHeader("x-amz-sns-topic-arn", this.getTopicArn()); httpRequest.setHeader("x-amz-sns-subscription-arn", this.getSubscriptionArn()); httpRequest.setHeader("User-Agent", "Cloud Notification Service Agent"); if (this.getRawMessageDelivery()) { httpRequest.addHeader("x-amz-raw-message", "true"); } } }
Java
UTF-8
796
2.953125
3
[]
no_license
package soort; /** * @author Bryan de Ridder * @version 1.0 26/11/2016 14:55 */ public class Leden { public static final int MAX_AANTAL = 100; private int aantal = 0; Lid[] leden = new Lid[MAX_AANTAL]; public Leden() { } public void voegLidToe(Lid lid) { this.leden[aantal] = lid; aantal++; } public Lid getLid(int index) { return leden[index]; } public int size() { return MAX_AANTAL; } @Override public String toString() { String string = "Aantal actieve leden: " + Lid.getAantalLeden() + "\n"; for (int i = 0; i < aantal; i++) { if (!(leden[i].soort == Soort.STEUNEND)) { string += leden[i].toString() + "\n"; } } return string; } }
Java
UTF-8
268
2.515625
3
[ "Apache-2.0" ]
permissive
void abc(int b) { x: while (b > 0) { try { continue x; } finally { a++; } } a++; } /* expected: 1 START -> 3 3 CHOICE -> 10 or 5 (cond: 3:12) 10 STEP -> end 5 CONTIN -> 7 7 STEP -> 3 */
SQL
UTF-8
17,332
3.125
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 5.0.3 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Dec 01, 2020 at 04:05 PM -- Server version: 10.4.14-MariaDB -- PHP Version: 7.4.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `matrimony` -- -- -------------------------------------------------------- -- -- Table structure for table `tbl_famchild` -- CREATE TABLE `tbl_famchild` ( `famchildid` int(50) NOT NULL, `uid` int(50) NOT NULL, `siblingname` varchar(150) NOT NULL, `status` varchar(150) NOT NULL, `gen` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_famchild` -- INSERT INTO `tbl_famchild` (`famchildid`, `uid`, `siblingname`, `status`, `gen`) VALUES (1, 1, 'Mathew', 'Single', 'M'), (2, 2, 'Ali', 'Married', 'F'), (6, 4, 'Shine', 'Studying', 'M'), (7, 5, 'Aleen Reji', 'Studying', 'F'), (8, 6, 'Shine reji', 'Studying', 'M'), (10, 9, 'shanu', 'Studying', 'M'), (11, 10, 'jain', 'Studying', 'M'), (12, 12, 'Anee Jose', 'Working', 'F'), (13, 13, 'Mathew ', 'Studying', 'M'), (14, 16, 'Tena Martin', 'Working', 'F'), (15, 15, 'alan josh', 'Studying', 'M'), (16, 14, 'ashin', 'studying', 'M'), (18, 8, 'shine joseph', 'Studying', 'M'), (19, 19, 'ebin joseph', 'Working', 'M'), (20, 20, 'jacob kain', 'Working', 'M'), (21, 21, 'Shine', 'Studying', 'M'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_fammas` -- CREATE TABLE `tbl_fammas` ( `fammas id` int(30) NOT NULL, `fathername` varchar(30) NOT NULL, `mothername` varchar(30) NOT NULL, `housename` varchar(50) NOT NULL, `fs` varchar(50) NOT NULL, `fv` varchar(50) NOT NULL, `uid` int(11) NOT NULL, `img` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_fammas` -- INSERT INTO `tbl_fammas` (`fammas id`, `fathername`, `mothername`, `housename`, `fs`, `fv`, `uid`, `img`) VALUES (1, 'John', 'Mary', 'Sneha Villa', 'Middle', 'Orthodox', 1, 'fuploads/ff.jpg'), (2, 'Daniel', 'Anna', 'Paradise', 'Middle', 'Orthodox', 2, 'fuploads/2family1.jpg'), (4, 'Mathew', 'Mary', 'Anamathuruthil H', 'Middle', 'Syrian', 4, 'fuploads/4family13.jpg'), (5, 'John KS', 'meni', 'Vendrapillil H', 'Middle', 'Syrian', 5, 'fuploads/5family11.jpg'), (6, 'reji', 'mary', 'kombanatt ', 'Middle', 'Syrian', 6, 'fuploads/6image10.jpg'), (7, 'Xavier', 'Prethy', 'Alappatt', 'Middle', 'Syrian', 8, 'uploads/family13.jpg'), (8, ' Chacko', 'Sanu', 'Rose villa', 'Middle', 'Syrian', 9, 'fuploads/9family12.jpg'), (9, 'martin', 'Mary', 'Alappatt', 'Middle', 'Syrian', 10, 'fuploads/10family5.jpg'), (10, 'Jose', 'Jasmine Jose', 'Vathuruthi ', 'Middle', 'Syrian', 12, 'fuploads/12image10.jpg'), (11, 'jinu kp', 'smitha', 'Diamond House', 'Middle', 'Syrian', 13, 'fuploads/13family9.jpg'), (12, 'martin', 'lena', 'Teraff house', 'Middle', 'Syrian', 16, 'fuploads/16imagefamily.jpg'), (13, 'josh k', 'anu josh', 'vathurath H', 'Middle', 'Syrian', 15, 'fuploads/15family11.jpg'), (14, 'John ', 'Jeni', 'Vellapattil H', 'Middle', 'Syrian', 14, 'fuploads/14family13.jpg'), (15, 'Joseph', 'Jolly', 'Palathinkal H', 'Middle', 'Syrian', 19, 'uploads/familinew.jpg'), (16, 'kain gh', 'Mary Kain', 'Raimonds H', 'Middle', 'Syrian', 20, 'fuploads/20image family.jpg'), (17, 'john ks', 'anna john', 'alappatt', 'Middle', 'Syrian', 21, 'fuploads/21imagefamily.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_intr` -- CREATE TABLE `tbl_intr` ( `iid` int(11) NOT NULL, `iuid` int(11) NOT NULL, `mid` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_intr` -- INSERT INTO `tbl_intr` (`iid`, `iuid`, `mid`) VALUES (1, 2, 1), (2, 2, 3), (3, 4, 1), (4, 5, 4), (5, 6, 1), (6, 6, 5), (7, 8, 5), (8, 9, 5), (9, 10, 8), (10, 10, 4), (11, 10, 6), (12, 10, 9), (13, 8, 10), (14, 12, 6), (15, 12, 9), (16, 12, 8), (17, 13, 9), (18, 13, 8), (19, 16, 13), (20, 16, 12), (21, 16, 10), (22, 15, 16), (23, 15, 14), (24, 15, 9), (25, 4, 13), (26, 13, 14), (27, 13, 16); -- -------------------------------------------------------- -- -- Table structure for table `tbl_login` -- CREATE TABLE `tbl_login` ( `uid` int(11) NOT NULL, `uname` varchar(20) NOT NULL, `upass` varchar(20) NOT NULL, `utype` varchar(20) NOT NULL, `status` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tbl_login` -- INSERT INTO `tbl_login` (`uid`, `uname`, `upass`, `utype`, `status`) VALUES (0, 'admin', 'admin', 'admin', 'true'), (1, 'sneha@gmail.com', 'sneha', 'user', 'true'), (2, 'alan@gmail.com', 'alan', 'user', 'true'), (4, 'manu@gmail.com', 'manu123', 'user', 'true'), (5, 'anu@gmail.com', 'anu123', 'user', 'true'), (6, 'athul@gmail.com', 'athul123', 'user', 'true'), (7, 'babu@gmail.com', '123', 'user', 'block'), (8, 'jithin@gmail.com', 'jithin123', 'user', 'true'), (9, 'shine@gmail.com', 'shine123', 'user', 'true'), (10, 'Jini@gmail.com', 'jini123', 'user', 'true'), (12, 'reena@gmail.com', 'reena123', 'user', 'true'), (13, 'merin@gmail.com', 'merin123', 'user', 'true'), (14, 'ebin@gmail.com', 'ebin123', 'user', 'true'), (15, 'aleena@gmail.com', 'aleena123', 'user', 'true'), (16, 'teni@gmail.com', 'teni123', 'user', 'true'), (18, 'manu@gmail.com', 'manu123', 'user', 'block'), (19, 'ashin@gmail.com', 'ashin123', 'user', 'true'), (20, 'john@gmail.com', 'john123', 'user', 'true'), (21, 'abel@gmail.com', 'abel123', 'user', 'true'), (22, 'antony@gmail.com', 'antony123', 'user', 'true'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_package` -- CREATE TABLE `tbl_package` ( `pkid` int(11) NOT NULL, `packname` varchar(30) NOT NULL, `desp` varchar(300) NOT NULL, `validity` varchar(30) NOT NULL, `amount` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_package` -- INSERT INTO `tbl_package` (`pkid`, `packname`, `desp`, `validity`, `amount`) VALUES (1, 'Gold', 'Better Experience..', '12', 2000), (2, 'Silver', 'Better Experience', '6', 1500), (3, 'Platinium', 'Better Should Experience.........', '3', 1000); -- -------------------------------------------------------- -- -- Table structure for table `tbl_personal` -- CREATE TABLE `tbl_personal` ( `pid` int(11) NOT NULL, `dob` date NOT NULL, `height` varchar(20) NOT NULL, `weight` varchar(30) NOT NULL, `comp` varchar(30) NOT NULL, `ms` varchar(20) NOT NULL, `uid` int(11) NOT NULL, `img` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_personal` -- INSERT INTO `tbl_personal` (`pid`, `dob`, `height`, `weight`, `comp`, `ms`, `uid`, `img`) VALUES (1, '1990-11-19', '159', '62', 'Fair', 'Single', 1, 'uploads/girl11.jpg'), (2, '1990-11-17', '160', '70', 'Fair', 'Single', 2, 'uploads/2use11.jpg'), (4, '1997-08-07', '170', '50', 'white', 'UM', 4, 'uploads/4user4.1.jpg'), (5, '1997-02-06', '135', '55', 'fair', 'UM', 5, 'uploads/5girl4.1.jpg'), (6, '1997-06-11', '170', '55', 'fair', 'UM', 6, 'uploads/6user2.2.jpg'), (7, '1998-09-14', '145', '58', 'white', 'single', 8, 'uploads/8user5.1.jpg'), (8, '1997-01-28', '170', '68', 'Fair', 'single', 9, 'uploads/9men1.1.jpg'), (9, '1997-05-23', '134', '40', 'Fair', 'single', 10, 'uploads/10girl5.jpg'), (10, '1997-05-09', '170', '55', 'Ivory', 'single', 12, 'uploads/12girlnew1,1.jpg'), (11, '1998-05-05', '170', '68', 'Fair', 'single', 13, 'uploads/13girlnew2.2.jpg'), (12, '1997-08-05', '170', '50', 'Fair', 'single', 14, 'uploads/14men.jpg'), (13, '1997-09-10', '170', '50', 'Fair', 'UM', 16, 'uploads/16men2.1.jpg'), (14, '1997-01-28', '155', '58', 'Fair', 'UM', 15, 'uploads/15girlimage3,jpg.jpg'), (15, '1998-05-14', '154', '58', 'Fair', 'single', 19, 'uploads/19mini.jpg'), (16, '1998-01-13', '170', '70', 'Fair', 'single', 20, 'uploads/20bride.jpg'), (17, '1998-05-08', '170', '70', 'Fair', 'single', 21, 'uploads/21present2.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_proff` -- CREATE TABLE `tbl_proff` ( `profid` int(11) NOT NULL, `uid` int(11) NOT NULL, `education` varchar(250) NOT NULL, `occufield` varchar(200) NOT NULL, `occup` varchar(200) NOT NULL, `country` varchar(50) NOT NULL, `location` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_proff` -- INSERT INTO `tbl_proff` (`profid`, `uid`, `education`, `occufield`, `occup`, `country`, `location`) VALUES (1, 1, 'B.Tech', 'IT', 'Project Head', 'India', 'Kochi'), (2, 2, 'B.Tech', 'IT', 'Software Developer', 'India', 'Trivandrum'), (4, 4, 'BBA', 'business', 'electronic shop', 'India', 'Kaloor'), (5, 5, 'Bcom', 'Employee', 'IT field', 'India', 'kottayam'), (6, 6, 'BBA', 'business', 'Accountant', 'India', 'kochi'), (7, 8, 'BCOM\r\nMCom', 'Employee', 'IT field', 'India', 'Thrissur'), (8, 9, 'BBA', 'Business', 'Grocessary Shop', 'India', 'vytilla'), (9, 10, 'Bcom', 'Employee', 'Teacher', 'India', 'Thiruvambadi'), (10, 12, 'B Tech', 'Government Service', 'Teacher', 'India', 'Kuthattukalam'), (11, 13, 'BA Animation', 'IT ', 'HR Manager', 'India', 'pala'), (12, 14, 'Bsc Maths', 'Employee', 'Bank Manager', 'India', 'kochi'), (13, 16, 'Bsc Chemistry', 'Business', 'Shopping Mall', 'India', 'kochi'), (14, 15, 'Bsc Nurse', 'Medical ', 'Nurse', 'India', 'kuttikanam'), (15, 20, 'BCA', 'IT', 'employee', 'India', 'kochi'), (16, 21, 'BCA', 'IT', 'employee', 'India', 'trivandrum'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_review` -- CREATE TABLE `tbl_review` ( `tid` int(11) NOT NULL, `uid` int(11) NOT NULL, `review` varchar(300) NOT NULL, `status` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_review` -- INSERT INTO `tbl_review` (`tid`, `uid`, `review`, `status`) VALUES (1, 4, 'NICE Experience', 'true'), (4, 12, 'Thank you................', 'true'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_story` -- CREATE TABLE `tbl_story` ( `sid` int(11) NOT NULL, `bride` varchar(20) NOT NULL, `bgroom` varchar(20) NOT NULL, `wdate` date NOT NULL, `status` varchar(20) DEFAULT NULL, `img` varchar(100) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_story` -- INSERT INTO `tbl_story` (`sid`, `bride`, `bgroom`, `wdate`, `status`, `img`) VALUES (1, 'Anu john', 'manu mathew', '2020-11-20', 'true', 'suploads/wed.jpg'), (2, 'Jini Martin', 'athul reji', '2020-11-04', 'true', 'suploads/story3.jpg'), (7, 'Anu James', 'Jithin Xavier', '2020-11-04', 'true', 'suploads/images (20).jpeg'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_user` -- CREATE TABLE `tbl_user` ( `uid` int(20) NOT NULL, `firstname` varchar(20) NOT NULL, `lastname` varchar(30) NOT NULL, `adress` varchar(100) NOT NULL, `city` varchar(50) NOT NULL, `district` varchar(30) NOT NULL, `pincode` int(10) NOT NULL, `emailid` varchar(50) NOT NULL, `gender` varchar(10) NOT NULL, `phoneno` varchar(12) NOT NULL, `pack` int(20) DEFAULT NULL, `apdate` date DEFAULT NULL, `edate` date DEFAULT NULL, `status` varchar(10) DEFAULT NULL, `img` varchar(100) DEFAULT NULL, `pstatus` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_user` -- INSERT INTO `tbl_user` (`uid`, `firstname`, `lastname`, `adress`, `city`, `district`, `pincode`, `emailid`, `gender`, `phoneno`, `pack`, `apdate`, `edate`, `status`, `img`, `pstatus`) VALUES (1, 'Sneha', 'John', 'Sneha Villa', 'Ernakulam', 'Ernakulam', 682016, 'sneha@gmail.com', 'F', '9898767890', 2, '2020-11-21', '2021-05-21', 'true', 'uploads/girl1.jpg', 'paid'), (2, 'Alan', 'Daniel', 'Paradise', 'Kochi', 'Ernakulam', 682016, 'alan@gmail.com', 'M', '8989786756', 2, '2020-11-21', '2021-05-21', 'true', 'uploads/use1.jpg', 'paid'), (4, 'Manu ', 'Mathew', 'Kalithiparambil House', 'kochi', 'Ernakulam', 656543, 'manu@gmail.com', 'M', '8767654345', 3, '2020-11-26', '2021-02-26', 'true', 'uploads/user4.jpg', 'paid'), (5, 'Anu', 'john', 'kalithiparambil H', 'Erattupetta', 'kottayam', 656544, 'anu@gmail.com', 'F', '5654345432', 1, '2020-11-22', '2021-11-22', 'true', 'uploads/girl4.jpg', 'paid'), (6, 'Athul', 'Reji', 'Kombanatt ', 'kochi', 'Ernakulam', 654565, 'athul@gmail.com', 'M', '7676556544', 2, '2020-11-22', '2021-05-22', 'true', 'uploads/user2.jpg', 'paid'), (7, 'babu123', '123df', 'kotta', 'kochi56', 'Ernakulam', 454345, 'babu@gmail.com', 'M', '3434323432', 2, '2020-11-22', '2021-05-22', 'block', 'uploads/logo4.jpg', 'paid'), (8, 'Jithin', 'Xavier', 'kottaarapillil House', 'Thiruvelkara', 'Thrissur', 656545, 'jithin@gmail.com', 'M', '5654543445', 1, '2020-11-22', '2021-11-22', 'true', 'uploads/user5.jpg', 'paid'), (9, 'Shine ', 'Chacko', 'Athirapillil House', 'Vytilla', 'Ernakulam', 543234, 'shine@gmail.com', 'M', '7656543234', 2, '2020-11-22', '2021-05-22', 'true', 'uploads/men1.jpg', 'paid'), (10, 'Jini', 'Martin', 'Raymonds House', 'Athirapilly', 'Thrissur', 654542, 'Jini@gmail.com', 'F', '6565434567', 3, '2020-11-22', '2021-02-22', 'true', 'uploads/girl5.1.jpg', 'paid'), (12, 'Reena', 'Jose', 'Raimonds House', 'Thrivandrum', 'Trivandrum', 567654, 'reena@gmail.com', 'F', '6789098767', 3, '2020-11-22', '2021-02-22', 'true', 'uploads/girlnew1.jpg', 'paid'), (13, 'Merin ', 'Jinu', 'Karthikapillil House', 'pala', 'kottayam', 654567, 'merin@gmail.com', 'F', '7654567898', 1, '2020-11-23', '2021-11-23', 'true', 'uploads/girlnew2.jpg', 'paid'), (14, 'ebin', 'david', 'Kattithara', 'kochi', 'Ernakulam', 454323, 'ebin@gmail.com', 'M', '4323454323', 1, '2020-11-23', '2021-11-23', 'true', 'uploads/mennew,jpg.jpg', 'paid'), (15, 'Alena ', 'Josh', 'Thottapilil House', 'Kuttikanam', 'Iduki', 679876, 'aleena@gmail.com', 'F', '8765342345', 1, '2020-11-23', '2021-11-23', 'true', 'uploads/girlimage.jpg', 'paid'), (16, 'Teni', 'Martin', 'jk House', 'kochi', 'Ernakulam', 765434, 'teni@gmail.com', 'M', '7876545432', 3, '2020-11-23', '2021-02-23', 'true', 'uploads/men2.jpg', 'paid'), (18, 'Manu', 'John', 'Rose villa', 'kochi', 'Ernakulam', 656765, 'manu@gmail.com', 'M', '7654567876', 2, '2020-11-24', '2021-05-24', 'block', 'uploads/present1.1.jpg', 'paid'), (19, 'ashin', 'joseph', 'Rose villa', 'kochi', 'Ernakulam', 654565, 'ashin@gmail.com', 'M', '7656545432', 1, '2020-11-26', '2021-11-26', 'true', 'uploads/mini1.1..jpg', 'paid'), (20, 'john', 'kain', 'Green valley', 'kochi', 'Ernakulam', 676543, 'john@gmail.com', 'M', '6765456655', 1, '2020-11-26', '2020-11-29', 'true', 'uploads/image9.jpg', 'paid'), (21, 'Abel', 'John', 'Green Valey', 'kochi', 'Ernakulam', 436765, 'abel@gmail.com', 'M', '7656787655', 2, '2020-11-28', '2021-05-28', 'true', 'uploads/present2.1.jpg', 'paid'), (22, 'Antony', 'Martin', 'Daimond Villa', 'kochi', 'Ernakulam', 676565, 'antony@gmail.com', 'M', '6767876677', 2, '2020-11-29', '2021-05-29', 'true', 'uploads/down1.jpg', 'paid'); -- -- Indexes for dumped tables -- -- -- Indexes for table `tbl_famchild` -- ALTER TABLE `tbl_famchild` ADD PRIMARY KEY (`famchildid`); -- -- Indexes for table `tbl_fammas` -- ALTER TABLE `tbl_fammas` ADD PRIMARY KEY (`fammas id`); -- -- Indexes for table `tbl_intr` -- ALTER TABLE `tbl_intr` ADD PRIMARY KEY (`iid`); -- -- Indexes for table `tbl_package` -- ALTER TABLE `tbl_package` ADD PRIMARY KEY (`pkid`); -- -- Indexes for table `tbl_personal` -- ALTER TABLE `tbl_personal` ADD PRIMARY KEY (`pid`); -- -- Indexes for table `tbl_proff` -- ALTER TABLE `tbl_proff` ADD PRIMARY KEY (`profid`); -- -- Indexes for table `tbl_review` -- ALTER TABLE `tbl_review` ADD PRIMARY KEY (`tid`); -- -- Indexes for table `tbl_story` -- ALTER TABLE `tbl_story` ADD PRIMARY KEY (`sid`); -- -- Indexes for table `tbl_user` -- ALTER TABLE `tbl_user` ADD PRIMARY KEY (`uid`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbl_famchild` -- ALTER TABLE `tbl_famchild` MODIFY `famchildid` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22; -- -- AUTO_INCREMENT for table `tbl_fammas` -- ALTER TABLE `tbl_fammas` MODIFY `fammas id` int(30) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- AUTO_INCREMENT for table `tbl_intr` -- ALTER TABLE `tbl_intr` MODIFY `iid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28; -- -- AUTO_INCREMENT for table `tbl_package` -- ALTER TABLE `tbl_package` MODIFY `pkid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `tbl_personal` -- ALTER TABLE `tbl_personal` MODIFY `pid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- AUTO_INCREMENT for table `tbl_proff` -- ALTER TABLE `tbl_proff` MODIFY `profid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; -- -- AUTO_INCREMENT for table `tbl_review` -- ALTER TABLE `tbl_review` MODIFY `tid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `tbl_story` -- ALTER TABLE `tbl_story` MODIFY `sid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `tbl_user` -- ALTER TABLE `tbl_user` MODIFY `uid` int(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=23; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UTF-8
332
2.546875
3
[]
no_license
package expression; /** * Created by 808648 on 04.04.2016. */ public class CheckedSqrt extends CheckedAbstractUnaryExpression { public CheckedSqrt(TripleExpression expression) { super(expression); } protected int action(int value) { return (int)(Math.sqrt((double) value)); } }
C++
UTF-8
1,166
3.046875
3
[]
no_license
#include <string.h> #include <stdlib.h> #include "VarTable.h" VarTableRow::VarTableRow(const char *str, int i) : name(0), value(i), next(0) { if (str) name = strdup(str); #if 0 var_addr = new int; *var_addr = i; #endif } VarTableRow::~VarTableRow() { if (name) free(name); #if 0 if (var_addr) delete var_addr; #endif } VarTable::VarTable() : table_head(0) { } void VarTable::AddNewVar(const char *new_name, int new_value) { VarTableRow *new_var = new VarTableRow(new_name, new_value); new_var->SetNext(table_head); table_head = new_var; } void VarTable::Assign(const char *name, int value) { VarTableRow *variable = GetVarByName(name); if (!variable) AddNewVar(name, value); else variable->SetVariable(value); } VarTableRow *VarTable::GetVarByName(const char *name) { VarTableRow *iterator = table_head; while (iterator) { if (!strcmp(iterator->GetName(), name)) return iterator; else iterator = iterator->GetNext(); } return 0; } void VarTable::DeleteVarTable(VarTableRow *head) { if (head) { DeleteVarTable(head->GetNext()); delete head; } } VarTable::~VarTable() { DeleteVarTable(table_head); }
Markdown
UTF-8
2,670
2.546875
3
[]
no_license
--- title: NodeJS category: languages date: 09/02/2015 tags: programming, dev, nodejs, language --- # Support NodeJS is supported by Scalingo, furthermore, custom support has been added to manage the [__meteor__](/languages/javascript/nodejs/meteor.html) framework. * [Getting Started with NodeJS](/languages/javascript/getting-started-with-nodejs.html) * [Getting Started with Meteor](/languages/javascript/getting-started-with-meteor.html) ## Buildpack [NodeJS Buildpack](https://github.com/Scalingo/appsdeck-buildpack-nodejs) ## Standard node applications ### Node.js app detection The file `package.json` should be present at the root of the project. ### NPM dependencies installation The dependencies of your project are installed according to the `package.json` content using `npm`. ### Node.JS app startup What we use in order of priority 1. `Procfile` at the root of your project 2. The field `.scripts.start` defined in your `package.json` 3. We start `server.js` if present. ## Meteor application ### Meteor app detection The directory `.meteor` should be present at the root of your project ### Meteor dependencies installation There are different way to install dependencies in your `meteor` project. #### Meteor ≤ v0.8 * [meteorite](https://github.com/oortcloud/meteorite/): your have to add `smart.json` and `smart.lock` to your repository. * [npm](https://www.npmjs.org/): you can use any standard nodejs module in your project: [Guide](https://meteorhacks.com/complete-npm-integration-for-meteor.html) #### Meteor ≥ v0.9 Methods from v0.8 still work when using v0.9 but have been deprecated, you should consider migrating your application. * Using meteor embedded dependency management (with `meteor add` and `meteor update`) * `npm` using [meteorhacks:npm](https://github.com/meteorhacks/npm) package. #### Demeteorizer [`demeteorizer`](https://github.com/onmodulus/demeteorizer) is used to deploy your meteor applications. It uses `meteor build|bundle` to package your meteor application, then generate the correct `package.json` in order to install the modules with `npm`. Dependencies defined in the `packages.json` (with an 's') are detected by the npm module then injected in the final `package.json`. Then `npm` is able to install all the dependencies of your app. ### Meteor app startup As `demeteorizer` changes the structure of your app, it generates automatically a `Procfile` to start your application. Generated Procfile: ```yml web: cd demeteorized && npm start ``` If your wish to write your own `Procfile` don't forget to keep this line for your `web` process, otherwise your application may not boot.
PHP
UTF-8
993
2.6875
3
[ "MIT" ]
permissive
<?php function query($conn, $sql, $paramTypes, $params) //Used for select statements { $stmt = mysqli_prepare($conn, $sql) or die(mysqli_error($conn)); if (isset($paramTypes) and isset($params)) mysqli_stmt_bind_param($stmt, $paramTypes, ...$params) or die(mysqli_error($conn)); //insert params mysqli_stmt_execute($stmt) or die(mysqli_error($conn)); $result = mysqli_stmt_get_result($stmt); mysqli_stmt_close($stmt); return $result; } function update($conn, $sql, $paramTypes, $params) //Used for insert, update and delete { $stmt = mysqli_prepare($conn, $sql) or die(mysqli_error($conn)) or die(mysqli_error($conn)); if (isset($paramTypes) and isset($params)) mysqli_stmt_bind_param($stmt, $paramTypes, ...$params) or die(mysqli_error($conn)); //insert params mysqli_stmt_execute($stmt) or die(mysqli_error($conn)); $lastId = mysqli_insert_id($conn); mysqli_stmt_close($stmt); return $lastId; } ?>
Shell
UTF-8
1,377
3.765625
4
[]
no_license
#!/bin/bash # Install latest version of git brew install git # Install gpg-suite to be able to store gpg keys passphrases into OSX Keychain brew install --cask gpg-suite # Get full name of the OSX user (cheers @juandebravo!) username=`whoami` default_git_name="`finger $USER | head -n1 | cut -d ":" -f 3 | cut -c 2-`" # Ask for credentials read -p "Enter your git full name ($default_git_name): " git_name read -p "Enter your git email: " git_email git_name=${git_name:-$default_git_name} echo "[user]" >> ~/.gitconfig.credentials echo " name = $git_name" >> ~/.gitconfig.credentials echo " email = $git_email" >> ~/.gitconfig.credentials ln -s "`pwd`/$(dirname $0)/gitconfig.symlink" ~/.gitconfig ln -s "`pwd`/$(dirname $0)/gitignore.symlink" ~/.gitignore ## Print instructions to setup gpg signing echo "Please run the following commands to setup gpg signing:" echo "" echo "$ gpg --full-generate-key" echo "" echo "Look for a string similar to \"gpg: key <KEY_ID> marked as ultimately trusted\"" echo "on the command output and use that KEY_ID in the following command:" echo "" echo "$ gpg --armor --export <KEY_ID> | pbcopy" echo "" echo "Now go to https://github.com/settings/keys and create a new GPG key with the clipboard contents." echo "" echo "Last step is adding a line with \"signingkey = <KEY_ID>\" at the end of the ~/.gitconfig.credentials file"
Python
UTF-8
1,463
4.25
4
[]
no_license
# class Employee: # pass # # #Instance variables contain data that are unique for that instance # emp_1 = Employee() # emp_2 = Employee() # # print(emp_1) # print(emp_2) # # emp_1.first = 'Corey' # emp_1.last = 'Schafer' # emp_1.email = 'Corey.Schafer@company.com' # emp_1.pay = 50000 # # emp_2.first = 'Test' # emp_2.last = 'User' # emp_2.email = 'Test.User@company.com' # emp_2.pay = 60000 # # print(emp_1.email) # print(emp_2.email) ####################################################### #The above technique kills the purpose of classes.So we will use the normal method #here we will use the init method which is like a constructor of Java #When we create methods within a class they receive the instance as the first argument automatically. #By convention we call the instance self. We can call it by any name #After self we can specify what other arguments that we want class Employee: def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@company.com' def fullname(self): return '{} {}'.format(self.first, self.last) emp_1 = Employee('Corey', 'Schafer', 50000) emp_2 = Employee('Test', 'User', 60000) print(emp_1.email) print(emp_2.email) # print('{} {}'.format(emp_1.first, emp_1.last)) #This would print the full name but this is requires a lot of typing and is not reusable print(emp_1.fullname()) print(emp_2.fullname()) print(Employee.fullname(emp_1))
Markdown
UTF-8
1,370
2.6875
3
[ "MIT" ]
permissive
# PlayerPickupXp PlayerPickupXp イベントは、プレイヤーが経験値オーブを拾うたびに発生します。 ## イベントクラス 関数ヘッダーのイベントをこのクラスとしてキャストする必要があります: `crafttweaker.event. layerPickupXpEvent <br /> <code>` もちろん、 [インポート](/AdvancedFunctions/Import/) 前にそのクラスをインポートして、その名前を使用することもできます。 ## イベントインターフェースの拡張 PlayerPickupXp Eventsは以下のインターフェイスを実装しており、それらのメソッド/getters/settersもすべて呼び出すことができます。 - [IEventCancelable](/Vanilla/Events/Events/IEventCancelable/) - [IPlayerEvent](/Vanilla/Events/Events/IPlayerEvent/) ## ZenGetters イベントから次の情報を取得できます。 | ZenGetter | 戻り値 | | ---------- | ----------------------------------------- | | `キャンセル済み` | boolean型 | | `プレイヤー` | [IPlayer](/Vanilla/Players/IPlayer/) | | `entityXp` | [IEntityXp](/Vanilla/Entities/IEntityXp/) | | `xp` | float型 | ## ZenMethods - `event.cancel()` はイベントをキャンセルとして設定します。
Java
UTF-8
293
1.859375
2
[]
no_license
package com.sqool.connector.api.cassandra.model; @Data @ToString @Builder @NoArgsConstructor @AllArgsConstructor @Table("posts") class Post { @PrimaryKey() @Builder.Default private String id = UUID.randomUUID().toString(); private String title; private String content; }
Java
UTF-8
6,259
1.90625
2
[]
no_license
package com.software.ttsl.Fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.software.ttsl.AccountDetailsActivity; import com.software.ttsl.R; import com.software.ttsl.Request.AccountDataModel; import com.software.ttsl.Request.TaskDataModel; import com.software.ttsl.Sql.DataBaseAdapter; import com.software.ttsl.TaskDetailActivity; import com.software.ttsl.Utils.DateAndTimeUtil; import com.software.ttsl.Utils.EmployConstantUtil; import butterknife.BindView; import butterknife.ButterKnife; /** * A simple {@link Fragment} subclass. */ public class TaskDetailFragment extends Fragment { public static final String TAG = TaskDetailFragment.class.getName(); @BindView(R.id.tv_task_owner) TextView textViewTaskOwner; @BindView(R.id.tv_task_subject) TextView textViewTaskSubject; @BindView(R.id.tv_task_due_date) TextView textViewDueDate; @BindView(R.id.tv_task_contact) TextView textViewContact; @BindView(R.id.tv_task_account) TextView textViewTaskAccount; @BindView(R.id.tv_task_status) TextView textViewTaskStatus; @BindView(R.id.tv_task_priority) TextView textViewPriority; @BindView(R.id.tv_task_created_by) TextView textViewCreatedBy; @BindView(R.id.tv_task_modified_by) TextView textViewModifiedBy; @BindView(R.id.tv_task_created_time) TextView textViewCreatedTime; @BindView(R.id.tv_task_modified_time) TextView textViewModifiedTime; @BindView(R.id.tv_task_description) TextView textViewDescription; @BindView(R.id.linear_layout_task_due_date) LinearLayout linearLayoutDueDate; @BindView(R.id.linear_layout_task_contact) LinearLayout linearLayoutTaskContact; @BindView(R.id.linear_layout_task_account) LinearLayout linearLayoutTaskAccount; @BindView(R.id.layout_task_description) LinearLayout linearLayoutTaskDescription; @BindView(R.id.tv_smart_view) TextView textViewSmartView; @BindView(R.id.tv_task_contact_label) TextView textViewTaskContactLabel; private DataBaseAdapter dataBaseAdapter; private Long taskId; private TaskDataModel taskDataModel; private TaskDetailActivity taskDetailActivity; public TaskDetailFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view= inflater.inflate(R.layout.fragment_task_detail, container, false); ButterKnife.bind(this,view); dataBaseAdapter = new DataBaseAdapter(getContext()); Bundle bundle = this.getArguments(); if (bundle != null) { taskId = bundle.getLong(EmployConstantUtil.KEY_TASK_ID, 0); } textViewSmartView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { smartView(); } }); getTask(); setTaskInfo(); return view; } private void setTaskInfo() { textViewTaskOwner.setText(taskDataModel.getTaskOwner()); textViewTaskSubject.setText(taskDataModel.getTaskSubject()); textViewTaskStatus.setText(taskDataModel.getTaskStatus()); textViewPriority.setText(taskDataModel.getTaskPriority()); textViewCreatedBy.setText(taskDataModel.getTaskCreatedBy()); textViewModifiedBy.setText(taskDataModel.getTaskModifyBy()); textViewCreatedTime.setText(DateAndTimeUtil.longToDate(taskDataModel.getTaskCreatedTime())); textViewModifiedTime.setText(DateAndTimeUtil.longToDate(taskDataModel.getTaskModifyTime())); textViewDueDate.setText(taskDataModel.getTaskDueDate()); if(!taskDataModel.getTaskDescription().isEmpty()){ linearLayoutTaskDescription.setVisibility(View.VISIBLE); textViewDescription.setText(taskDataModel.getTaskDescription()); }if(!taskDataModel.getTaskContact().isEmpty()){ linearLayoutTaskContact.setVisibility(View.VISIBLE); textViewTaskContactLabel.setText("Contacts"); textViewContact.setText(taskDataModel.getTaskContact()); } if(!taskDataModel.getLeadName().isEmpty()){ linearLayoutTaskContact.setVisibility(View.VISIBLE); textViewTaskContactLabel.setText("Leads"); textViewContact.setText(taskDataModel.getLeadName()); } if(!taskDataModel.getTaskAccount().isEmpty()){ linearLayoutTaskAccount.setVisibility(View.VISIBLE); textViewTaskAccount.setText(taskDataModel.getTaskAccount()); } } private void getTask() { taskDetailActivity = (TaskDetailActivity) getActivity(); taskDataModel = taskDetailActivity.getTaskDataModel(); } @Override public void onResume() { super.onResume(); getTask(); setTaskInfo(); } private void smartView() { if (textViewSmartView.getText().toString().equals(getResources().getString(R.string.footer_show_all_fields))) { textViewSmartView.setText(getResources().getString(R.string.footer_smart_view)); linearLayoutDueDate.setVisibility(View.VISIBLE); linearLayoutTaskAccount.setVisibility(View.VISIBLE); linearLayoutTaskContact.setVisibility(View.VISIBLE); linearLayoutTaskDescription.setVisibility(View.VISIBLE); } else { textViewSmartView.setText(getResources().getString(R.string.footer_show_all_fields)); setVisibilityGone(); setTaskInfo(); } } private void setVisibilityGone() { linearLayoutDueDate.setVisibility(View.GONE); linearLayoutTaskAccount.setVisibility(View.GONE); linearLayoutTaskContact.setVisibility(View.GONE); linearLayoutTaskDescription.setVisibility(View.GONE); } }
PHP
UTF-8
3,334
2.953125
3
[ "MIT" ]
permissive
<?php /** * A service to create and populate CSV files used for logs and other exports. * * @package Helpful * @subpackage Core\Services * @version 4.4.59 * @since 4.4.49 */ namespace Helpful\Core\Services; use Helpful\Core\Helper; use Helpful\Core\Helpers as Helpers; use Helpful\Core\Services as Services; /* Prevent direct access */ if ( ! defined( 'ABSPATH' ) ) { exit; } /** * ... */ class CSV { /** * Filename * * @var string */ public $filename; /** * Items * * @var array */ public $items; /** * File * * @var string */ public $file; /** * Constructor * * @param string $filename file name. * * @return void */ public function __construct( string $filename ) { if ( ! strpos( $filename, '.csv' ) ) { $filename .= '.csv'; } $this->filename = $filename; $this->items = false; $this->file = false; } /** * Add multiple items into the file. * * @param array $items csv items. */ public function add_items( array $items ) { if ( is_array( $items ) ) { $this->items = $items; } } /** * Create the csv file. */ public function create_file() { if ( ! is_array( $this->items ) ) { return; } $options = new Services\Options(); $items = $this->items; $lines = array(); $lines[] = array_keys( $items[0] ); foreach ( $items as $item ) : $lines[] = array_values( $item ); endforeach; $uploads = wp_upload_dir(); if ( ! file_exists( $uploads['basedir'] . '/helpful' ) ) { mkdir( $uploads['basedir'] . '/helpful', 0755, true ); } $file_name = '/helpful/' . $this->filename; if ( file_exists( $uploads['basedir'] . $file_name ) ) { unlink( $uploads['basedir'] . $file_name ); } clearstatcache(); $separator = ';'; $separators = array( ';', ',' ); $separators = apply_filters( 'helpful_export_separators', $separators ); $option = $options->get_option( 'helpful_export_separator', ';', 'esc_attr' ); if ( $option && in_array( $option, $separators, true ) ) { $separator = esc_html( $option ); } $file = fopen( $uploads['basedir'] . $file_name, 'w+' ); foreach ( $lines as $line ) : fputcsv( $file, $line, $separator ); endforeach; fclose( $file ); $this->file = $uploads['baseurl'] . $file_name; } public function render() { if ( ! is_array( $this->items ) ) { return; } header( 'Content-Type: text/csv' ); header( 'Content-Disposition: attachment; filename=' . $this->filename); $options = new Services\Options(); $items = $this->items; $lines = array(); $lines[] = array_keys( $items[0] ); foreach ( $items as $item ) : $lines[] = array_values( $item ); endforeach; clearstatcache(); $separator = ';'; $separators = array( ';', ',' ); $separators = apply_filters( 'helpful_export_separators', $separators ); $option = $options->get_option( 'helpful_export_separator', ';', 'esc_attr' ); if ( $option && in_array( $option, $separators, true ) ) { $separator = esc_html( $option ); } $file = fopen( 'php://output', 'w+' ); foreach ( $lines as $line ) : fputcsv( $file, $line, $separator ); endforeach; fclose( $file ); } /** * Get the current file url, only available after creating. * * @return string */ public function get_file() { return $this->file; } }
PHP
UTF-8
2,897
2.65625
3
[]
no_license
<?php //$root = realpath($_SERVER["DOCUMENT_ROOT"]); //require_once($root.'\jomon\private\initialize.php'); function exception_error_handler($errno, $errstr, $errfile, $errline ) { throw new ErrorException($errstr, $errno, 0, $errfile, $errline); } set_error_handler("exception_error_handler"); try { include_once(dirname(__FILE__)."/./../private/initialize.php"); } catch(ErrorException $ex) { try { include_once(dirname(__FILE__)."/./../../private/initialize.php"); } catch(ErrorException $e){ echo "Unable to include initialization file <br />"; echo $e . "<br />"; $path = getcwd(); echo "Current working directory = " . $path . "<br />"; } } echo "<!-- Author tab with author records --> <div id='authorList' class='tab-pane fade' style='max-height: 500px;'> <!-- Authors list --> <div id='authorsList' style='height: 300px; overflow: scroll; width:800px;'>"; ?> <!-- table for records -->` <?php $i = 0; $limit = 50; //how many items to show per page isset($_GET['authorPage']) ? $page = $_GET['authorPage'] : $page = 0; $page != 0 ? $start = ($page - 1) * $limit : $start = 0; $authors = Author::find_all_authors_by_limit($start, $limit); ?> <?php foreach($authors as $a) { if($i == 0 || $i % 50 == 0){ echo" <div id='results_" . $i ."' style='display: block;'> <table class='table'> <tr> <th></th> <th>Author</th> </tr>"; } $a->displayAuthorRecord(); $i++; } echo" </table> </div> <!-- end results div--> </div> <!-- end author list div -->"; try { include_once(dirname(__FILE__)."/./../private/shared/paginationAuthors.php"); } catch(ErrorException $ex) { try { include_once(dirname(__FILE__)."/./../../private/shared/paginationAuthors.php"); } catch(ErrorException $e){ echo "Unable to include pagination"; } } //include($root.'\jomon\private\shared\paginationAuthors.php'); echo "<!-- end author div --> </div>"; ?>
Go
UTF-8
487
2.53125
3
[ "BSD-3-Clause", "Apache-2.0", "BSD-2-Clause" ]
permissive
package model import ( "encoding/json" "strings" ) // Request Object type BatchDeleteIterationsV4Request struct { // 项目id ProjectId string `json:"project_id"` Body *BatchDeleteIterationsV4RequestBody `json:"body,omitempty"` } func (o BatchDeleteIterationsV4Request) String() string { data, err := json.Marshal(o) if err != nil { return "BatchDeleteIterationsV4Request struct{}" } return strings.Join([]string{"BatchDeleteIterationsV4Request", string(data)}, " ") }
Java
UTF-8
1,128
2.203125
2
[]
no_license
package stepDefinations.examPortalSteps; import cucumber.api.Scenario; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import org.apache.log4j.Logger; import org.junit.Assert; import org.openqa.selenium.WebDriver; import pageBucket.PageReferences; import pages.ExamPortal.HomePage; import stepDefinations.commonSteps.Hooks; import utils.PropertyFileReader; import java.util.Properties; public class HomePageStepDef extends PageReferences { private static Properties properties = PropertyFileReader.readPropertyFile(); private WebDriver driver; private Logger logger = Logger.getLogger(HomePageStepDef.class); private Scenario scenario; public HomePageStepDef() { driver = Hooks.getDriver(); scenario = Hooks.getScenario(); } @When("User lands on home page") public void user_lands_on_home_page() { homepage = new HomePage(driver); Assert.assertEquals("ExamFront",homepage.verifyPageTitle()); logger.info("Page Title verified"); } @Then("User clicks on register button") public void user_click_on_register_button() throws InterruptedException { homepage.clickOnRegister(); } }
Java
UTF-8
3,144
3.296875
3
[]
no_license
package com.simplilearn.locker.java.main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class FileManager { public static List<String> getFilesList(String filePath) { // Variable declaration List<String> al = new ArrayList<String>(); // Creating File Object File fileList = new File(filePath); // Getting list of files available in folder String[] listOfFiles = fileList.list(); // looping through file array for (String file : listOfFiles) al.add(file); Collections.sort(al); return al; } public static boolean createFile(String fileName, String filePath) { File file = new File(filePath, fileName); boolean isFielCreated = false; try { if (file.createNewFile()) isFielCreated = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return isFielCreated; } public static boolean writeToFile(String path, String fileName, List<String> fileContent) { try { File f = new File(path, fileName); FileWriter fw = new FileWriter(f); if (!f.exists()) f.createNewFile(); for (String s : fileContent) { if (s.length() > 0) fw.write(s + "\n"); } fw.close(); return true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } public static boolean appendToFile(String path, String fileName, List<String> fileContent) { try { BufferedWriter out = new BufferedWriter(new FileWriter(path + "\\" + fileName, true)); fileContent.forEach((n) -> { try { if (n.length() > 0) out.write(n + "\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }); // out.write(str); out.close(); return true; } catch (Exception e) { // TODO: handle exception } return false; } public static boolean removeFile(String filePath, String fileName) { File fl = new File(filePath + "\\" + fileName); try { if (fl.delete()) return true; } catch (Exception e) { // TODO: handle exception } return false; } public static boolean serchFile(String filePath, String fileName) { File fl = new File(filePath + "//" + fileName); try { if (fl.exists()) return true; } catch (Exception e) { // TODO: handle exception } return false; } public static List<String> displayFileContent(String filePath, String fileName){ BufferedReader br; List<String> al = new ArrayList<String>(); try { br = new BufferedReader(new FileReader(filePath + "//" + fileName)); String line; while ((line = br.readLine()) != null) { al.add(line); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return al; } }
PHP
UTF-8
2,178
2.75
3
[]
no_license
<?php namespace MagaMarketplace\Domain\Order; /** * Description of TrackingResponse * * @author Maicon Sasse */ class TrackingResponse extends Tracking { /** * Status. (new, approved, shipped, delivered, canceled) * @var string */ protected $status; /** * Transportadora * @var Carrier */ protected $carrier; /** * Código de rastreio na transportadora * @var string */ protected $trackingNumber; /** * Url da transportadora para o rastreamento do pedido * @var string */ protected $trackingUrl; /** * Nota Fiscal * @var Invoice */ protected $invoice; /** * Motivo de Cancelamento * @var string */ protected $reason; /** * Mapeamento de propriedades que sao objetos ou arrays * @var array */ protected $_mapper = array( 'items' => '\\MagaMarketplace\\Domain\\Order\\TrackingItem', 'carrier' => '\\MagaMarketplace\\Domain\\Order\\Carrier', 'invoice' => '\\MagaMarketplace\\Domain\\Order\\Invoice' ); public function getStatus() { return $this->status; } public function getCarrier() { return $this->carrier; } public function getTrackingNumber() { return $this->trackingNumber; } public function getTrackingUrl() { return $this->trackingUrl; } public function getInvoice() { return $this->invoice; } public function getReason() { return $this->reason; } public function setStatus($status) { $this->status = $status; } public function setCarrier(Carrier $carrier = null) { $this->carrier = $carrier; } public function setTrackingNumber($trackingNumber) { $this->trackingNumber = $trackingNumber; } public function setTrackingUrl($trackingUrl) { $this->trackingUrl = $trackingUrl; } public function setInvoice(Invoice $invoice = null) { $this->invoice = $invoice; } public function setReason($reason) { $this->reason = $reason; } }
Java
UTF-8
3,715
2.78125
3
[]
no_license
package ru.opa.pack.net; import java.io.*; /** * Created by Vladimir_Levin on 05.12.2015. */ public final class HttpResponse { public static void writeResponse(String message, OutputStream outputStream) throws IOException { String response = "HTTP/1.1 200 OK\r\n" + "Server: YarServer/2009-09-09\r\n" + "Content-Type: text/json\r\n" + //"Content-Length: " + message.length() + "\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Connection: close\r\n\r\n"; String result = response + message; outputStream.write(result.getBytes()); outputStream.flush(); } public static String readBodyPOST(BufferedReader in, String line) throws IOException { //BufferedReader in = new BufferedReader(new InputStreamReader(inputStream)); /*if (line == null) { in.close(); return "none"; }*/ StringBuilder headers = new StringBuilder(); StringBuilder body = new StringBuilder(); boolean isPost = line.startsWith("POST"); int contentLength = 0; headers.append("" + line); while (!(line = in.readLine()).equals("")) { headers.append('\n' + line); if (isPost) { String contentHeader = "Content-Length: "; if (line.startsWith(contentHeader)) { contentLength = Integer.parseInt(line.substring(contentHeader.length())); } } } if (isPost) { char[] c = new char[contentLength]; in.read(c, 0, contentLength); body.append(c); /*for (int i = 0; i < contentLength; i++) { c = in.read(); body.append((char) c); }*/ } return body.toString(); } public static void sendFileGET(OutputStream outputStream, String request, String publicFolder) throws IOException { String[] requestParam = request.split(" "); String path = requestParam[1]; if (path.equals("/")) { path = "/index.html"; } String response = "HTTP/1.1 200 OK\r\n" + "Server: YarServer/2009-09-09\r\n" + "Content-Type: text/" + (path.endsWith(".html") ? "html" : path.endsWith(".js") ? "javascript" : path.endsWith(".css") ? "css" : "jpeg") + "\r\n" + //"Content-Length: " + message.length() + "\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Connection: close\r\n\r\n"; PrintWriter out = new PrintWriter(outputStream, true); outputStream.write(response.getBytes()); File file = new File(publicFolder + path); System.out.println(path); if (!file.exists()) { System.out.println("404"); out.write("HTTP 404"); // the file does not exists } /*String statusLine = "HTTP/1.1 200 OK" + "\r\n"; String serverdetails = "Server: Java HTTPServer"; String contentTypeLine = "Content-Type: text/html" + "\r\n"; out.write(statusLine); out.write(serverdetails); out.write(contentTypeLine);*/ FileReader fr = new FileReader(file); BufferedReader bfr = new BufferedReader(fr); String line; while ((line = bfr.readLine()) != null) { out.write(line); out.write("\r\n"); } bfr.close(); out.close(); fr.close(); } public static void sendFileGET(OutputStream outputStream, String request) throws IOException { sendFileGET(outputStream, request, "public"); } }
C#
UTF-8
5,665
2.765625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
using System; using System.Collections.Generic; using CSF.Validation.Manifest; namespace CSF.Validation.Rules { /// <summary> /// A read-only model for contextual information related to the execution of a validation rule. /// </summary> public class RuleContext : ValueContext { /// <summary> /// Gets a <see cref="ManifestRuleInfo"/> with information about the configuration of the current rule. /// </summary> public ManifestRuleInfo RuleInfo { get; } /// <summary> /// Gets the identifier of the executed rule. /// </summary> /// <remarks> /// <para> /// This object provides identifying information about the currently-executing validation /// rule. /// </para> /// </remarks> public RuleIdentifier RuleIdentifier { get; } /// <summary> /// Gets a reference to the rule interface which was used in order to select &amp; execute this rule. /// </summary> /// <remarks> /// <para> /// This will be a closed-generic form of either: /// </para> /// <list type="bullet"> /// <item><description><see cref="IRule{TValidated}"/></description></item> /// <item><description><see cref="IRule{TValue, TParent}"/></description></item> /// </list> /// </remarks> public Type RuleInterface { get; } /// <summary> /// Gets a collection of the ancestor validation contexts. /// </summary> /// <remarks> /// <para> /// When either of the following methods is used (using a validator builder), a 'child' validation context is created /// and the rules which are added are placed into that new child content. /// </para> /// <list type="bullet"> /// <item> /// <description><see cref="CSF.Validation.ValidatorBuilding.IConfiguresValidator{TValidated}.AddRules{TBuilder}"/></description> /// </item> /// <item> /// <description><see cref="CSF.Validation.ValidatorBuilding.IConfiguresValueAccessor{TValidated,TValue}.AddRules{TBuilder}"/></description> /// </item> /// </list> /// <para> /// Equivalents to the above exist for the Manifest Model: <see cref="CSF.Validation.ManifestModel.Value.Children"/> /// and also for a Validation Manifest: <see cref="CSF.Validation.Manifest.ManifestItem.Children"/>. /// </para> /// <para> /// If the currently-executing validation rule lies within a child context, this property provides access to all /// of the ancestor contexts, such as parents &amp; grandparents. /// This collection may be treated a little like a 'stack'. The first item in this collection is the immediate parent /// context, the second item is the grandparent, the third the great-grandparent and so on. /// As many parent contexts are available from this collection as required in order to traverse back to the root /// validation context. The root validation context is the validator that was initially built and not imported into /// an existing validator via an <c>AddRules</c> method. /// </para> /// <para> /// If the currently-executing validation rule is not part of a child context then this collection will be empty /// indicating that there are no ancestor contexts. /// </para> /// <para> /// When using the <see cref="IRule{TValue, TParent}"/> interface, the first <see cref="ValueContext.ActualValue"/> is /// made available as the second parameter to <see cref="IRule{TValue, TParent}.GetResultAsync(TValue, TParent, RuleContext, System.Threading.CancellationToken)"/>. /// </para> /// </remarks> public IReadOnlyList<ValueContext> AncestorContexts { get; } /// <summary> /// Initialises a new instance of <see cref="RuleContext"/>. /// </summary> /// <param name="manifestRule">The manifest rule from which this context was created.</param> /// <param name="ruleIdentifier">The rule identifier.</param> /// <param name="actualValue">The actual validated value.</param> /// <param name="ancestorContexts">A collection of ancestor contexts.</param> /// <param name="ruleInterface">The rule interface used for this rule execution.</param> /// <param name="collectionItemOrder">An optional collection item order.</param> /// <exception cref="ArgumentNullException"></exception> public RuleContext(ManifestRule manifestRule, RuleIdentifier ruleIdentifier, object actualValue, IEnumerable<ValueContext> ancestorContexts, Type ruleInterface, long? collectionItemOrder = null) : base(ruleIdentifier?.ObjectIdentity, actualValue, manifestRule?.ManifestValue, collectionItemOrder) { if (manifestRule is null) throw new ArgumentNullException(nameof(manifestRule)); if (ancestorContexts is null) throw new ArgumentNullException(nameof(ancestorContexts)); RuleInfo = new ManifestRuleInfo(manifestRule); RuleIdentifier = ruleIdentifier ?? throw new ArgumentNullException(nameof(ruleIdentifier)); RuleInterface = ruleInterface ?? throw new ArgumentNullException(nameof(ruleInterface)); AncestorContexts = new List<ValueContext>(ancestorContexts); } } }
Python
UTF-8
1,552
2.78125
3
[]
no_license
#!/usr/bin/env python # encoding: utf-8 from __future__ import print_function """ Mixing multiple inputs to multiple outputs with fade time. """ from pyo import * s = Server(sr=44100, nchnls=2, buffersize=512, duplex=0).boot() # Inputs a = SfPlayer("../snds/ounkmaster.aif", loop=True, mul=.3) b = SfPlayer("../snds/flute.aif", loop=True, mul=.1) c = SfPlayer("../snds/baseballmajeur_m.aif", loop=True, mul=.2) # 3 outputs mixer, 1 second of amplitude fade time mm = Mixer(outs=3, chnls=2, time=1) # Outputs fx1 = Disto(mm[0], drive=.99, slope=.85, mul=.1).out() fx2 = Freeverb(mm[1], size=.95, damp=.7, mul=2).out() fx3 = Harmonizer(mm[2], transpo=-7, feedback=.25, mul=2).out() # Add inputs to the mixer mm.addInput(voice=0, input=a) mm.addInput(voice=1, input=b) mm.addInput(voice=2, input=c) # Static assignation of inputs to outputs with amplitude balance # mm.setAmp(vin=0, vout=0, amp=.15) # mm.setAmp(vin=0, vout=1, amp=.5) # mm.setAmp(vin=1, vout=0, amp=.25) # mm.setAmp(vin=1, vout=2, amp=.5) # mm.setAmp(vin=2, vout=1, amp=.35) # mm.setAmp(vin=2, vout=2, amp=.5) inputs = {0: "ounkmaster", 1: "flute", 2: "baseballmajeur"} outputs = {0: "disto", 1: "reverb", 2: "harmonizer"} # Dynamic assignation of inputs to outputs with random amplitude def assign(): vin = random.randint(0, 2) vout = random.randint(0, 2) amp = random.choice([0,0,.25,.33]) print("%s -> %s, amp = %f" % (inputs[vin], outputs[vout], amp)) mm.setAmp(vin=vin, vout=vout, amp=amp) pat = Pattern(function=assign, time=3).play() s.gui(locals())
Java
UTF-8
4,107
2.203125
2
[]
no_license
package com.cfranking.parser; import com.cfranking.client.CfClient; import com.cfranking.dto.ContestMeta; import com.cfranking.dto.Problem; import com.cfranking.dto.RankRow; import com.cfranking.dto.Standings; import com.cfranking.entity.CfContest; import com.cfranking.model.CfContestList; import com.cfranking.model.CfRanklistResponse; import com.cfranking.model.CfRanklistRow; import org.springframework.stereotype.Component; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @Component public class CfParser { private final CfClient cfClient; private final CfUserStore userStore; public CfParser(CfClient cfClient, CfUserStore userStore) { this.cfClient = cfClient; this.userStore = userStore; } public List<CfContest> getContestList() { CfContestList cfContestList = cfClient.getContestList(); return cfContestList.getResult(); } public Standings getStandings(int contestId, String country) { CfRanklistResponse contestResults = cfClient.getContestResults(contestId, false).getResult(); userStore.generateMissingHandlesInfo(contestResults); return convertToStandings(contestResults, country); } // TODO : Refactor to new bean private Standings convertToStandings(CfRanklistResponse contestResults, String country) { Standings standings = new Standings(); standings.setContestMeta(getContestMeta(contestResults)); standings.setRows(getRows(contestResults.getRows(), country)); return standings; } private List<RankRow> getRows(List<CfRanklistRow> rows, String country) { return getRows(rows) .stream() .filter(rankRow -> country.equals("all") ? true : country.equals(rankRow.getCountry()) ).collect(Collectors.toList()); } private List<RankRow> getRows(List<CfRanklistRow> rows) { final AtomicInteger counter = new AtomicInteger(); rows.stream() .map(row -> { return row.getParty().getMembers().get(0).getHandle(); }).collect(Collectors.toList()) .stream() .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 500)) .values() .forEach(list -> userStore.retrieveUserInfo(list)); return rows.stream() .map(row -> { RankRow rankRow = new RankRow(); rankRow.setHandle(row.getParty().getMembers().get(0).getHandle()); rankRow.setStanding(row.getRank()); rankRow.setPoints(row.getPoints()); rankRow.setCountry(userStore.getUser(rankRow.getHandle()).getCountry()); rankRow.setRating(userStore.getUser(rankRow.getHandle()).getRating()); rankRow.setUserRank(userStore.getUser(rankRow.getHandle()).getRank()); rankRow.setProblemResultList(row.getProblemResults()); return rankRow; }).collect(Collectors.toList()); } private ContestMeta getContestMeta(CfRanklistResponse contestResults) { ContestMeta contestMeta = new ContestMeta(); CfContest contest = contestResults.getContest(); contestMeta.setId(contest.getId()); contestMeta.setName(contest.getName()); contestMeta.setPhase(contest.getPhase()); contestMeta.setProblemList(getProblemList(contestResults)); return contestMeta; } private List<Problem> getProblemList(CfRanklistResponse contestResults) { return contestResults.getProblems().stream() .map(cfProblem -> { Problem problem = new Problem(); problem.setIndex(cfProblem.getIndex()); problem.setName(cfProblem.getName()); problem.setPoints(cfProblem.getPoints()); return problem; }).collect(Collectors.toList()); } }
C#
UTF-8
2,504
2.578125
3
[]
no_license
using ApplicationLibrary; using ApplicationLibrary.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ApplicationUI { public partial class LoginForm : Form { public User currentUser; public string inValidLogin = "Incorrect Login Information."; public string usernameEmpty = "Username Empty"; public string passwordEmpty = "Password Empty"; public LoginForm() { InitializeComponent(); if (CultureInfo.CurrentUICulture.LCID == 1031) { headerLabel.Text = "Anmeldung Bilden"; usernameLabel.Text = "NUTZERNAME :"; passwordLabel.Text = "PASSWORT :"; loginButton.Text = "ANMELDEN"; exitButton.Text = "AUSFAHRT"; inValidLogin = "Inkorrekte Anmeldung Information"; usernameEmpty = "Benutzername leer"; passwordEmpty = "Passwort leer"; } } private void loginButton_Click(object sender, EventArgs e) { if (FormValid()) { User userModel = new User { Username = usernameText.Text, Password = passwordText.Text }; GlobalConfig.Connection.Authenticate(userModel); if (userModel.Active == 1) { User currentUser = userModel; DashboardForm dashboard = new DashboardForm(currentUser); this.Hide(); dashboard.Show(); } } else { MessageBox.Show(inValidLogin); } } private void exitButton_Click(object sender, EventArgs e) { Environment.Exit(0); } private bool FormValid() { bool output = true; if (String.IsNullOrEmpty(usernameText.Text)) { MessageBox.Show(usernameEmpty); output = false; } if (String.IsNullOrEmpty(passwordText.Text)) { MessageBox.Show(passwordEmpty); output = false; } return output; } } }
Java
UTF-8
10,504
1.9375
2
[]
no_license
package com.crypto.velis.cryptorates; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.SystemClock; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import static java.lang.Math.abs; public class MainActivity extends AppCompatActivity { ListView listview; Coin bitcoin, ethereum, ripple, litecoin, bitcoinCash; public static Coin [] coins; public static ArrayList<Double>closingRates; List<Model> list = new ArrayList<>(); ListAdapter adapter; Button refresh; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); getRates(); SetCheckRatesAlarm(); setChangeRatesAlarm(); listview = (ListView) findViewById(R.id.listview); listview.setBackgroundResource(R.drawable.card); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getRates(); } }); } public ArrayList<Double> getClosingRates(){ TinyDB tinyDB = new TinyDB(getApplicationContext()); closingRates = tinyDB.getListDouble("blah"); return closingRates; } @Override protected void onResume() { super.onResume(); getRates(); } public void saveRates(){ closingRates.clear(); for(Coin coin: coins){ closingRates.add(coin.closingRate); } TinyDB tinyDB = new TinyDB(getApplicationContext()); tinyDB.putListDouble("blah", closingRates); } public void getRates(){ RequestQueue queue = Volley.newRequestQueue(this); String url ="https://api.coinmarketcap.com/v1/ticker/?limit=10"; StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Locale us = new Locale("en", "US"); NumberFormat formatter = NumberFormat.getCurrencyInstance(us); int []indices = {0, 1, 2, 5, 3}; list.clear(); try { for(int i = 0; i < coins.length; i++){ JSONArray jsonarray = new JSONArray(response); JSONObject obj = jsonarray.getJSONObject(indices[i]); String stringRate = obj.getString("price_usd"); double bitRate = Double.parseDouble(stringRate); Coin coin = coins[i]; coin.newRate = bitRate; String cryptoRate = formatter.format(bitRate); String flag = ""; if(coin.closingRate != 0){ if(coin.newRate < coin.closingRate){ coin.arrow = R.drawable.arrow_down; coin.pctChange = ((coin.newRate/coin.closingRate)-1)*100; flag = "down"; }else if (coin.newRate > coin.closingRate) { coin.arrow = R.drawable.arrow_up; coin.pctChange = abs(((coin.closingRate/coin.newRate)-1)*100); flag = "up"; }else{ } } String pct = formatter.format(coin.pctChange); list.add(new Model(coins[i].name, cryptoRate, coin.arrow, coin.icon, pct, flag)); } adapter = new ListAdapter(listview.getContext(), list); listview.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show(); } }); queue.add(stringRequest); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void SetCheckRatesAlarm() { // replace with a button from your own UI BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent _ ) { getRates(); for(Coin coin: coins){ coin.closingRate = coin.newRate; } saveRates(); getRates(); context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity } }; this.registerReceiver( receiver, new IntentFilter("com.blah.bloo.somemessage") ); PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.bloo.somemessage"), 0 ); AlarmManager alarmManager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE )); Locale aLocale = new Locale.Builder().setLanguage("iw").setRegion("IL").build(); Calendar calendar = Calendar.getInstance(aLocale); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 11); calendar.set(Calendar.MINUTE, 59); // set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime()) assert alarmManager != null; alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), (AlarmManager.INTERVAL_DAY*2), pintent); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public void setChangeRatesAlarm() { // replace with a button from your own UI BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive( Context context, Intent _ ) { getRates(); for(int i = 0; i < coins.length; i++){ if(coins[i].closingRate*coins[i].changePercentAlert > coins[i].newRate || coins[i].closingRate < coins[i].newRate*coins[i].changePercentAlert){ sendNotification("Change in " + coins[i].name + " rates!!!", i+555); } } context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity } }; this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") ); PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 ); AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE )); long hour = 60 * 60 * 1000; manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), hour*1, pintent); } public void sendNotification(String title, int id){ Intent notificationIntent = new Intent(MainActivity.this, MainActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent, 0); NotificationManager notificationManager = (NotificationManager) MainActivity.this .getSystemService(Context.NOTIFICATION_SERVICE); Notification.Builder notification = new Notification.Builder(MainActivity.this) .setContentTitle(title) .setContentText("Click to see the curent rates!") .setSmallIcon(R.mipmap.ic_launcher) .setAutoCancel(true) .setContentIntent(intent); Notification notificationn = notification.getNotification(); assert notificationManager != null; notificationManager.notify(id, notificationn); } public void init(){ Typeface typeface = Typeface.createFromAsset(getAssets(), "Montserrat-Light.ttf"); TextView trending = (TextView)findViewById(R.id.trending); trending.setTypeface(typeface); refresh = (Button)findViewById(R.id.refresh); bitcoin = new Coin("Bitcoin", 0, 0, R.drawable.bit_icon2); ethereum = new Coin("Ethereum", 0, 0, R.drawable.ethereum_icon); ripple = new Coin("Ripple", 0, 0, R.drawable.ripple_icon); litecoin = new Coin("Litecoin", 0, 0, R.drawable.lite_icon); bitcoinCash = new Coin("Bitcoin Cash", 0, 0, R.drawable.bcash_icon); coins = new Coin[]{bitcoin, ethereum, ripple, litecoin, bitcoinCash}; getClosingRates(); if(closingRates.size() > 0){ for(int i = 0; i < closingRates.size(); i++){ if(closingRates.get(i) != 0){ coins[i].closingRate = closingRates.get(i); } } } } }
Shell
UTF-8
310
3.34375
3
[]
no_license
#!/bin/bash set -e # have to set some permissions # https://stackoverflow.com/a/39230095 FILE="/sys/class/backlight/intel_backlight/brightness" CURRENT=$(cat "$FILE") if [ "$1" = "-inc" ] then NEW=$(( CURRENT + $2 )) elif [ "$1" = "-dec" ] then NEW=$(( CURRENT - $2 )) fi echo "$NEW" | tee "$FILE"
Java
UTF-8
2,947
3.671875
4
[]
no_license
package 待分类; import java.util.Stack; /** * @ClassName: 待分类._42_接雨水 * @Author: whc * @Date: 2021/03/17/22:16 */ public class _42_接雨水 { // 双指针法 时间复杂度O(n^2) /*public int trap(int[] height) { int sum = 0; for (int i = 0; i < height.length; i++) { // 第一个柱子和最后一个柱子不接雨水 if(i == 0 || i == height.length - 1) continue; int rightHeight = height[i]; // 记录右边柱子最高高度 int leftHeight = height[i]; // 记录左边柱子最高高度 for (int r = i+1; r < height.length; r++) { if(height[r] > rightHeight) { rightHeight = height[r]; } } for (int l = i-1; l >= 0; l--) { if(height[l] > leftHeight) { leftHeight = height[l]; } } // 左右柱子中选择最小的柱子 再减去 柱子本身高度 即雨水的高度 int h = Math.min(leftHeight, rightHeight) - height[i]; if(h > 0) sum += h; } return sum; }*/ // 动态规划 // 避免左右柱子最高高度重复计算 // 递推公示: // 从左往右: maxLeft[i] = max(height[i], maxLeft[i-1]) // 从右往左: maxRight[i] = max(height[i], maxRight[i+1]) /*public int trap(int[] height) { if(height.length <= 2) return 0; int[] maxLeft = new int[height.length]; int[] maxRight = new int[height.length]; // 记录每个柱子左边柱子最大高度 maxLeft[0] = height[0]; for (int i = 1; i < height.length; i++) { maxLeft[i] = Math.max(height[i], maxLeft[i-1]); } // 记录每个柱子右边柱子最大高度 maxRight[height.length-1] = height[height.length-1]; for (int i = height.length-2; i >= 0; i--) { maxRight[i] = Math.max(height[i], maxRight[i+1]); } // 求和 int sum = 0; for (int i = 0; i < height.length; i++) { int count = Math.min(maxLeft[i], maxRight[i]) - height[i]; if(count > 0) { sum += count; } } return sum; }*/ // 单调栈 public int trap(int[] height) { if(height.length <= 2) return 0; Stack<Integer> stack = new Stack<>(); // 存着下标,计算的时候可以用下标对应柱子的高度 stack.push(0); int sum = 0; for (int i = 1; i < height.length; i++) { // 情况一: 当前遍历的元素(柱子)高度小于栈顶元素的高度 if(height[i] < height[stack.peek()]) { stack.push(i); } // 情况二: 当前遍历的元素(柱子)高度等于栈顶元素的高度 else if(height[i] == height[stack.peek()]) { stack.pop(); stack.push(i); } else { // 情况三: 当前遍历的元素(柱子)高度大于栈顶元素的高度,出现凹槽 while (!stack.isEmpty() && height[i] > height[stack.peek()]) { int mid = stack.pop(); if(!stack.isEmpty()) { int h = Math.min(height[i], height[stack.peek()]) - height[mid]; // 求高度 int w = i - stack.peek() - 1; // 求宽度 sum += h * w; } } stack.push(i); } } return sum; } }
Java
UTF-8
1,222
3.59375
4
[]
no_license
package com.bupt.thinkinjava.c7; import static com.bupt.utils.Print.print; /** * 使用代理; */ class Cleanser { private String s = "Cleanser"; public void append(String a) { s += a; } public void dilute() { append(" dilute()"); } public void apply() { append(" apply()"); } public void scrub() { append(" scrub()"); } public String toString() { return s; } public static void main(String[] args) { com.bupt.thinkinjava.c7.Cleanser x = new com.bupt.thinkinjava.c7.Cleanser(); x.dilute(); x.apply(); x.scrub(); print(x); } } class MyDetergent { String str; public void setStr(String str) { this.str = str; } private Cleanser cleanser=new Cleanser(); public void scrub(){ cleanser.scrub(); } public void dilute(){ cleanser.dilute(); } public void apply(){ cleanser.apply(); } @Override public String toString() { return cleanser.toString(); } } public class P11 { public static void main(String[] args) { MyDetergent myDetergent=new MyDetergent(); myDetergent.scrub(); print(myDetergent); print(myDetergent.toString()); } }
Java
UTF-8
1,961
2.390625
2
[]
no_license
package com.wyd.resource; import java.util.Date; import java.util.List; import java.util.Random; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.glassfish.jersey.media.multipart.FormDataParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.wyd.domain.Employee; import com.wyd.domain.Record; import com.wyd.service.RecordService; import com.wyd.util.DateUtil; @Component @Path("/record") public class RecordResource { @Autowired private RecordService recordService; @Path("/findAll") @GET public List<Record> findAll() { List<Record> records = recordService.findAll(); return records; } @Path("/save") @POST @Consumes(MediaType.MULTIPART_FORM_DATA) public Response save(@FormDataParam("e_id") String e_id, @FormDataParam("name") String name, @FormDataParam("start") String start, @FormDataParam("end") String end, @FormDataParam("location") String location, @FormDataParam("room") String room, @FormDataParam("folio") String folio ) throws Exception { Date date = new Date(); Record record = new Record(); Employee employee = new Employee(); employee.setE_id(Integer.valueOf(e_id)); employee.setName(name); record.setStart(start); record.setEnd(end); record.setRoom(room); record.setFolio(folio); record.setLocation(location); record.setEmployee(employee); record.setDays(DateUtil.calculateDays(end, start)); record.setPrintTime(DateUtil.gainPrintTime(date)); record.setEmployee(employee); Random random = new Random(); record.setR_id(String.valueOf(random.nextInt(1000000000))); recordService.save(record); return Response.status(200).entity("Add Success!").build(); } }
SQL
UTF-8
221
3
3
[]
no_license
CREATE TABLE IF NOT EXISTS contribuinte ( id INT AUTO_INCREMENT, pessoa_id INT NOT NULL, PRIMARY KEY(id), CONSTRAINT fk_pessoa_contribuinte FOREIGN KEY (pessoa_id) REFERENCES pessoa(id) ) ENGINE=INNODB;
Python
UTF-8
961
4.3125
4
[]
no_license
# Exercise 15 - Reading Files from sys import argv script, filename = argv # Explanation below txt = open(filename) # txt = open(filename, 'w') # txt.close() # txt.write('test') # format prints filename from user input in argv print(f"Here's your file {filename}: ") # reads the text file to end of file # .read is working from the var txt = open(filename) # txt.read() is saying to read itself print(txt.read()) print("Type the filename again: ") file_again = input("> ") txt_again = open(file_again) print(txt_again.read()) # Does txt = open(filename) return the contents of the file? No, it doesn’t. It actually makes something # called a ”file object.” You can think of a file like an old tape drive that you saw on mainframe # computers in the 1950s or even like a DVD player from today. You can move around inside # them and then ”read” them, but the DVD player is not the DVD the same way the file object is # not the file’s contents.
Java
UTF-8
1,696
2.25
2
[]
no_license
package Nurse_reg; import java.io.IOException; import java.io.PrintWriter; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Nurse_regis extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n = request.getParameter("Username_N"); String a = request.getParameter("Age_N"); String c = request.getParameter("Contact_N"); String e = request.getParameter("Email_N"); String p = request.getParameter("Password_N"); String b = request.getParameter("Branch_N"); String ph = request.getParameter("Patients_N"); ResultSet rs; try{ Class.forName("com.mysql.jdbc.Driver"); java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3308/apollohospital", "root", "admin"); Statement stm = con.createStatement(); int i = stm.executeUpdate("insert into Apollo (Name, Age, Contact, Email, Pass_word, Branch, Patients_handled) values('"+n+"', '"+a+"', '"+c+"', '"+e+"', '"+p+"', '"+b+"', '"+ph+"')"); if(i == 1){ System.out.println("Data Uplaoaded Successfully!"); RequestDispatcher rd = request.getRequestDispatcher("Login_nurse.html"); rd.forward(request, response); } } catch(Exception e1) { System.out.print(e1); } } }
Java
UTF-8
858
2.53125
3
[]
no_license
package com.usky.sms.permission; import java.util.HashMap; import java.util.Map; import com.usky.sms.core.AbstractCache; public class PermissionSetRegister extends AbstractCache { private Map<String, PermissionSet> permissionSetMap = new HashMap<String, PermissionSet>(); @Override protected void refresh() { permissionSetMap.clear(); registerPermissionSets(); } private void registerPermissionSets() { for (PermissionSets permissionSets : PermissionSets.values()) { registerPermissionSet(permissionSets.name(), permissionSets.getName(), permissionSets.getType(), permissionSets.getDescription()); } } public void registerPermissionSet(String key, String name, String type, String description) { PermissionSet permissionSet = new PermissionSet(key, name, type, description); permissionSetMap.put(key, permissionSet); } }
Python
UTF-8
3,650
3.0625
3
[ "Apache-2.0" ]
permissive
"""Utilities for handling prefix dictionaries""" from .util import U_EMPTY_STRING, U_PLUS from .phonenumberutil import format_number, PhoneNumberFormat _LOCALE_NORMALIZATION_MAP = {"zh_TW": "zh_Hant", "zh_HK": "zh_Hant", "zh_MO": "zh_Hant"} def _may_fall_back_to_english(lang): # Don't fall back to English if the requested language is among the following: # - Chinese # - Japanese # - Korean return lang != "zh" and lang != "ja" and lang != "ko" def _full_locale(lang, script, region): if script is not None: if region is not None: return "%s_%s_%s" % (lang, script, region) else: return "%s_%s" % (lang, script) elif region is not None: return "%s_%s" % (lang, region) else: return lang def _find_lang(langdict, lang, script, region): """Return the entry in the dictionary for the given language information.""" # Check if we should map this to a different locale. full_locale = _full_locale(lang, script, region) if (full_locale in _LOCALE_NORMALIZATION_MAP and _LOCALE_NORMALIZATION_MAP[full_locale] in langdict): return langdict[_LOCALE_NORMALIZATION_MAP[full_locale]] # First look for the full locale if full_locale in langdict: return langdict[full_locale] # Then look for lang, script as a combination if script is not None: lang_script = "%s_%s" % (lang, script) if lang_script in langdict: return langdict[lang_script] # Next look for lang, region as a combination if region is not None: lang_region = "%s_%s" % (lang, region) if lang_region in langdict: return langdict[lang_region] # Fall back to bare language code lookup if lang in langdict: return langdict[lang] # Possibly fall back to english if _may_fall_back_to_english(lang): return langdict.get("en", None) else: return None def _prefix_description_for_number(data, longest_prefix, numobj, lang, script=None, region=None): """Return a text description of a PhoneNumber for the given language. Arguments: data -- Prefix dictionary to lookup up number in. longest_prefix -- Length of the longest key in data. numobj -- The PhoneNumber object for which we want to get a text description. lang -- A 2-letter lowercase ISO 639-1 language code for the language in which the description should be returned (e.g. "en") script -- A 4-letter titlecase (first letter uppercase, rest lowercase) ISO script code as defined in ISO 15924, separated by an underscore (e.g. "Hant") region -- A 2-letter uppercase ISO 3166-1 country code (e.g. "GB") Returns a text description in the given language code, for the given phone number's area, or an empty string if no description is available.""" e164_num = format_number(numobj, PhoneNumberFormat.E164) if not e164_num.startswith(U_PLUS): # pragma no cover # Can only hit this arm if there's an internal error in the rest of # the library raise Exception("Expect E164 number to start with +") for prefix_len in range(longest_prefix, 0, -1): prefix = e164_num[1:(1 + prefix_len)] if prefix in data: # This prefix is present in the geocoding data, as a dictionary # mapping language info to location name. name = _find_lang(data[prefix], lang, script, region) if name is not None: return name else: return U_EMPTY_STRING return U_EMPTY_STRING
JavaScript
UTF-8
765
2.671875
3
[]
no_license
import defaultExport from "../Settings.js" let userZip let userWeather = [] export const getWeather = () => { return fetch(`http://api.openweathermap.org/data/2.5/weather?zip=${userZip[0].zipcode},US&units=imperial&appid=${defaultExport.weatherKey}`) .then(response => response.json()) .then( parsedWeather => { userWeather = parsedWeather } ) } export const getUserZip = () => { const userId = parseInt(sessionStorage.getItem("activeUser")) //fetch user zip code return fetch(`http://localhost:8088/users?id=${userId}`) .then(response => response.json()) .then( parsedUser => { userZip = parsedUser } ) } export const useWeather = () => { return userWeather }
Java
UTF-8
4,486
2.515625
3
[ "MIT" ]
permissive
/* * The MIT License * * Copyright 2017 Leif Lindbäck <leifl@kth.se>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package se.kth.id1212.streams.filehandler; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class FileHandlerTest { private static final String TEST_AREA_PATH = "testarea"; private Path testArea = Paths.get(TEST_AREA_PATH); private FileHandler instance; @Before public void setUp() throws IOException { Files.createDirectory(testArea); instance = new FileHandler(); } @After public void tearDown() throws IOException { Files.delete(testArea); instance = null; } @Test public void testListDir() throws IOException { String result = instance.listDir("."); String expResult = TEST_AREA_PATH; assertTrue("Did not create correct directory.", result.contains(expResult)); } @Test public void testCreateAndListDir() throws IOException { String path = TEST_AREA_PATH + "/testDir"; try { instance.createDir(path); String result = instance.listDir(TEST_AREA_PATH); String expResult = path; assertEquals("Did not create correct directory.", expResult, result); } finally { Files.deleteIfExists(Paths.get(path)); } } @Test public void testWriteReadTextFile() throws IOException, ClassNotFoundException { String path = TEST_AREA_PATH + "/test.txt"; String line1 = "1 sdf rt yj sdssc ss rew"; String line2 = "2"; String line3 = "3 df t rth ds sd sdw ww ww"; String lineSep = " "; try { instance.write(path, line1); instance.write(path, line2); instance.write(path, line3); String expResult = line1 + lineSep + line2 + lineSep + line3; String result = instance.read(path); assertEquals("Did not read what was written.", expResult, result); } finally { Files.deleteIfExists(Paths.get(path)); } } @Test public void testWriteReadHexFile() throws IOException, ClassNotFoundException { String path = TEST_AREA_PATH + "/test.dat"; String line1 = "1 2 3 4 5"; String line2 = "2"; String line3 = "3 45 546 657"; String lineSep = " "; try { instance.write(path, line1); instance.write(path, line2); instance.write(path, line3); String expResult = line1 + lineSep + line2 + lineSep + line3; String result = instance.read(path); assertEquals("Did not read what was written.", expResult, result); } finally { Files.deleteIfExists(Paths.get(path)); } } @Test public void testWriteReadSerFile() throws IOException, ClassNotFoundException { String path = TEST_AREA_PATH + "/test.ser"; String line = "1 sdf rt yj sdssc ss rew"; try { instance.write(path, line); String expResult = line; String result = instance.read(path); assertEquals("Did not read what was written.", expResult, result); } finally { Files.deleteIfExists(Paths.get(path)); } } }
Markdown
UTF-8
1,259
2.765625
3
[]
no_license
# yt-upload A node package to upload videos on youtube from your terminal # Install ```console $ npm i -g yt-upload ``` # Getting Started Follow the (Turn on the YouTube Data API, only a to g) steps shown here **https://developers.google.com/youtube/v3/quickstart/nodejs** Move the downloaded file to **(C:\Users\<*yourpcusername*>)** and rename it **client_secret.json**. # Usage ```console $ yt-upload <command> ``` > If you are using this for the first time it will ask you to authorize your application, just follow the onscreen authorization flow. # Commands To upload videos ```console $ yt-upload -u or --upload ``` To update video ```console $ yt-upload -c or --change ``` To get subscriber count ```console $ yt-upload -s or --subscribers ``` To search for a video ```console $ yt-upload -q or --searchvideo ``` To get comments on a video ```console $ yt-upload -r or --replies ``` To check version ```console $ yt-upload -v or --version ``` Help ```console $ yt-upload -h or --help ``` # Features ✔️ upload video ✔️ update a video ✔️ get subscribers ✔️ search for video ✔️ get comments on video # Upcoming Features ❌ like video ❌ subscribe or unsubscribe to a channel ❌ play video in terminal (maybe)
Markdown
UTF-8
10,815
3.171875
3
[]
no_license
# Url Shortener REST API (AWS Version) **Challenge:** Design and implement a RESTful API for a URL shortener. **Requirements:** 1. Develop a RESTful API to create shorten URLs. This API should receive an URL and will return a shortened version of it. 2. Redirect to the original URL when the shortened URL is called. 3. The API should persist the data, because if the application is stopped, it must recover all the data when it starts again. 4. The project must be available in the cloud 5. The project must be built and deployed with docker compose to the cloud with multiple instances balanced by a load balancer. **I haven't used docker, as I'm still studing it, so I've just deployed it to AWS with beanstalk and using AWS load balancer on 2 instances.** #### Prerequisites This version of this project is designed to run locally and in a cloud platform. All the steps below are dedicated to run the application locally, but you can try out an deployed version of this application in AWS using the server: http://shortener-env.k6wamyyvfj.us-east-1.elasticbeanstalk.com To run this project you need to have the following applications: **important**: Below each requirement, I'm noting the version I've used during the development. 1. Java 8 My version: java version "1.8.0_121" To check if you have installed just type in you console: java -version 2. Apache Maven My version: Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T15:33:14-03:00) To check if you have installed just type in you console: mvn --version #### Clone project ###To clone it just type in your console the command below on the desired directory: git clone https://github.com/guilhermeginezsilva/urlshortener-api.git #### Tests This project contains 59 tests to test all the three layers: Controllers, Services and DAOs ###In the console on the root directory of the project, just type: mvn test #### Running There are 2 options to run this project: 1. Build and Run: ###Just navigate to the cloned directory run the command below in the console: mvn spring-boot:run ###With Optional Parameters: IDs Range Size: Id generator will create ranges of n IDs for this instance, the range size for the example below is 1000 IDs: (Explained later) mvn spring-boot:run -Dspring-boot.run.arguments=--id.range.size=1000 2. Run the executable: ###Just navigate to the releases directory inside the project and run the command below: ###On windows: start.bat ###On linux: ./start.sh ### It's Running!! And now? Well, running the tests you can check that the application is working correctly, but we know that there isn't nothing better than having some fun with these projects, so I have prepared two ways of doing it: * You can use Postman application; a script ("URL Shortener.postman_collection.json") with the request structures is available also in the releases directory, just import in your postman application and have fun; ###You can find postman installation instructions here: https://www.getpostman.com/ ###After download, you may find a "import" button in the top of the screen. Just import the script and you will be available to make the requests. * you can access the AWS deployed test application and the server: Site: http://d1w2hz6cl3vqn1.cloudfront.net Server routes: * http://shortener-env.k6wamyyvfj.us-east-1.elasticbeanstalk.com/v1/shu/shorten * http://shortener-env.k6wamyyvfj.us-east-1.elasticbeanstalk.com/v1/shu/00000 ### Project Design: Here I explain the design decisions of this project: **1. Architecture:** This project follows MVC architecture. **2. Routes:** The available routes are (considering you are running in your localhost): * Shorten a URL Route: Request format: POST: http://localhost:8080/v1/shu/shorten Content Body (JSON): { "url": "http://www.google.com.br" } Constraints: * The url parameter is mandatory and must not be empty. * The url parameter must contain a valid URL, containing the full structure, including the protocol, like: http, https, ftp... Response format for success: HTTP 200; Content Body (JSON): { "originalUrl": "http://www.google.com.br", "shortenedUrl": "http://localhost:8080/v1/shu/0000000" } * Redirect to the original URL: Request format: GET: http://localhost:8080/v1/shu/0000000 Constraints: * The request URL must be valid and have been returned from a shorten call, or it will return 404, not found. * The id part of the URL (After the last '/' of the URL) must have a length of 5 characters. * The id part of the URL (After the last '/' of the URL) must not be empty or null. Response format for success: HTTP 301: Get redirected to the original URL **3. Chosen Technologies:** **Java language:** I've chosen Java language for this project because it's the language that I'm more used to. **Spring Boot:** It's a really nice framework to work with RESTful services: * It's fast to start; (I know that there are other fast frameworks too, but it's also an advantage of Spring); * It has many preconfigured integrations with other technologies, as parsers, database, exception handlers...; * It will help in the next step of this project when integrating with the cloud; **H2 Database:** H2 was chose for this project to keep it simple, so everyone would be able to run it, not needing to install a database. There are 2 different configurations of H2 is this project, for the tests it uses H2 in memory, because it doesn't need to persist the data, and the normal executing process persists the H2 data to the disk, to the same directory that is running the application. **4. How it works:** **Controllers:** Responsible to receives the routes requests, parse in and out the data to Java object and validate the input data. It uses the Service Layer services. * ShortenedUrlsController: Expose the 2 routes described in this document. **Services:** Responsible to apply the business rules over the request and to call the Data Acess Object Layer, to store and get persisted data. * ShortenedUrlIdRangeService: Apply IDs ranges business rules, to manage the used IDs of the shortened URLs. * UrlsService: Apply Shortened URLs business rules, to shorten an URL or to get the original URL of a shortened one. **Data Access Objects:** Responsible to communicate with persisting technologies, like databases. In this project it communicates with persisting H2 database. * ShortenedUrlIdRangeDAO: Database access object of the ID ranges control. Model fields: rangeId: Auto generated id, just for database; firstId: The first ID of the range; lastId: The last ID of the range; owner: The owner process of this range, it avoids that 2 processes are using the same IDs; currentId: The current position of this range; lastModified: Last modified date just for history; * UrlsDAO: Database access object to keep track of the created shortened URLs and Original URLs. Model fields: shortenedUrlId: The ID of the shortened URL, returned in the shorten route; shortenedUrlIdSeed: The seed used to the shortened ID generation; originalUrl: The original URL of a shortened URL, used in the redirect to original URL route; lastModified: Last modified date just for history; **ID Generation Process:** **1. Format:** The id generation process is a simple sequence of decimal values, starting at 0; every time that a ID is generated, it increases the counter by 1. To transform this decimal ID in the Shortened URL ID the API calculates the base 62 of this number using the characters: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'. To generate a fixed 5 characters ID, after the base 62 transformation, it pad zeroes to the left. **Design:** It was designed to have 5 characters length because it would be able to support 916.132.832 shortened URLs generated, that is a big number of shortened URLs and can be handled by a int variable. If the application really get used by a lot of people and systems and this starts to be a problem, the conversion for a long variable is possible. **2. ID Generation Process:** The ID generation process was designed to work on a multi application instances environment working with a unique database interface. It works as below: **Details:** One or more instances need to generate IDs for the shortened URLs, but if each one generates an ID it would be possible to generate duplicate IDs. I could give each instance a fixed range of IDs to work, but it would be a problem for an auto scaling solution, because I would need to know all my instances ranges to deal with it. So the solution was an hybrid of it. Instead of generating an ID, the application instances generates Ranges of IDs, this is done by inserting a new Range on the ShortenedUrlIdRange table. This insertion must be synchronized by all instances, so it avoids that two or more instances creates the same range in the database, so all the application instances needs to be connecting to the same database, or same database interface. In this transaction the application checks the last range existing in the database, if there are none, it creates the first range, else it creates a range starting from the ((lastID from the Last Existing Range) +1 ). I also decided to use ranges because I don't want a synchronized insert in the database for every request the application receives, so the creation of a new Range is done in a transaction, but the update not. Taking into account that there is just one application instance working with each range. So as it receives a big range to work, it just need to update the range position in the range record. Off course you could also just update the record when the range has ended, it would improve even more the performance, but if the application stops in the middle of the range, it would lose the current position and would replace all the range records created when receiving new requests. **3. Responsabilities:** * **Application:** It is responsible to make the database requests for the creation of new ranges in a transaction and to update the current ID range position without a transaction. * **Database:** It is responsible to keep all the IDs range records, if it needs to scale, it would need to be scaled vertically. If it would be scaled horizontally a replication of this table between the database instances would be necessary.
C
UTF-8
4,613
2.546875
3
[]
no_license
/* * footcount.c * * Created on: May 29, 2019 * Author: wjtjdrb */ #include <sensor.h> #include <dlog.h> #include <footcount_module.h> #include "data_storage.h" // STEPS means the values that will be used in getStepsCount(); tmpnum is just to use temporarily check and test. int STEPS = -1; sensor_recorder_option_h option; // this function is callback function of footstep. if count of footstep is changed, you can see the count in log. void footcount_module_sensor_callback(sensor_h footcount_module_sensor, sensor_event_s *event, void *user_data) { /*dlog_print(DLOG_DEBUG, "RACCOON", "START CALLBACK"); sensor_type_e type; sensor_get_type(footcount_module_sensor, &type); if (type == SENSOR_HUMAN_PEDOMETER) { float x = event->values[0]; // numbers of steps dlog_print(DLOG_DEBUG, "RACCOON", "Steps %d", (int)x); STEPS = (int)x; }*/ } // To check whether the pedometer is supported bool footcount_module_is_supported() { bool is_supported = false; sensor_is_supported(SENSOR_HUMAN_PEDOMETER, &is_supported); if (is_supported) { dlog_print(DLOG_DEBUG, "RACCOON", "connection to pedometer is succeed"); } else { dlog_print(DLOG_DEBUG, "RACCOON", "connection to pedometer is failed"); } return is_supported; } // this function is callback function of recorded footstep. so, when starting app, you can see the recorded count in log int call = 0; static bool footcount_module_sensor_recorder_callback(sensor_type_e type, sensor_recorder_data_h data, int remains, sensor_error_e error, void *user_data) { int step; time_t start; time_t end; if (error != SENSOR_ERROR_NONE) return; sensor_recorder_data_get_time(data, &start, &end); sensor_recorder_data_get_int(data, SENSOR_RECORDER_DATA_STEPS, &step); static int steps = 0; steps += step; if (remains == 0) { STEPS = steps; steps = 0; } dlog_print(DLOG_DEBUG, "RACCOON", "3 %d", step); } // To check whether recording the pedometer is supported. bool footcount_module_is_recorder_supported() { bool supported = false; sensor_recorder_is_supported(SENSOR_HUMAN_PEDOMETER, &supported); if (supported) { dlog_print(DLOG_DEBUG, "RACCOON", "You can record pedometer"); } else { dlog_print(DLOG_DEBUG, "RACCOON", "You can not record pedometer"); } return supported; } // it will make sensor and listener of pedometer and start listening. void footcount_module_start() { if (footcount_module_is_supported()) { int result = sensor_get_default_sensor(SENSOR_HUMAN_PEDOMETER, &footcount_module_sensor); dlog_print(DLOG_DEBUG, "RACCOON", "SENSOR result = %d", result); result = sensor_create_listener(footcount_module_sensor, &footcount_module_listener); dlog_print(DLOG_DEBUG, "RACCOON", "LISTENER result = %d", result); result = sensor_listener_set_event_cb(footcount_module_listener, 1000, footcount_module_sensor_callback, NULL); dlog_print(DLOG_DEBUG, "RACCOON", "CALLBACK result = %d", result); result = sensor_listener_start(footcount_module_listener); dlog_print(DLOG_DEBUG, "RACCOON", "START result = %d", result); } } // this function will set some option of recording the pedomenter void footcount_module_setting_recorder() { // set option of record if (footcount_module_is_recorder_supported()) { sensor_recorder_create_option(&option); // 30 * 24 -> the record will remain in a month(30 * 24 hour) sensor_recorder_option_set_int(option, SENSOR_RECORDER_OPTION_RETENTION_PERIOD, 30 * 24); sensor_recorder_start(SENSOR_HUMAN_PEDOMETER, option); } } // this function will make a query and read the record. void footcount_module_making_query() { call = 0; sensor_recorder_query_h query; sensor_recorder_create_query(&query); // start time is a days ago ( 3600 sec(1hour) * 24 == 1 day ) dlog_print(DLOG_FATAL, "LIM_TAG", "Making steps querry from %d till %d", data_storage_get_tutorial_start_time(), time(NULL)); sensor_recorder_query_set_time(query, SENSOR_RECORDER_QUERY_START_TIME, (time_t)data_storage_get_tutorial_start_time()); sensor_recorder_query_set_time(query, SENSOR_RECORDER_QUERY_END_TIME, time(NULL)); sensor_recorder_query_set_int(query, SENSOR_RECORDER_QUERY_TIME_INTERVAL, 24 * 60); // the time when a day starts is 4 AM ( 4 * 3600 sec ( 1hour )) sensor_recorder_query_set_time(query, SENSOR_RECORDER_QUERY_ANCHOR_TIME, (time_t)(4 * 3600)); sensor_recorder_read(SENSOR_HUMAN_PEDOMETER, query, footcount_module_sensor_recorder_callback, NULL); } #include <stdlib.h> int footcount_module_getStepsCount() { // TODO: uncomment to test without walking //STEPS += (rand() % 15); return STEPS; }
Java
UTF-8
4,032
1.835938
2
[]
no_license
package com.example; import com.google.cloud.dataflow.sdk.Pipeline; import com.google.cloud.dataflow.sdk.io.TextIO; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.runners.BlockingDataflowPipelineRunner; import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.DefaultValueFactory; import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.DataflowPipelineOptions; import com.google.cloud.dataflow.sdk.options.PipelineOptionsFactory; import com.google.cloud.dataflow.sdk.transforms.DoFn; import com.google.cloud.dataflow.sdk.transforms.ParDo; import com.google.cloud.dataflow.sdk.util.gcsfs.GcsPath; import com.google.cloud.dataflow.sdk.values.PCollection; import com.opencsv.CSVParser; import java.io.IOException; import com.google.api.services.bigquery.model.TableRow; import com.google.cloud.dataflow.sdk.io.BigQueryIO; import com.google.cloud.dataflow.sdk.options.Default; import com.google.cloud.dataflow.sdk.options.Description; import com.google.cloud.dataflow.sdk.options.Validation; import com.google.cloud.dataflow.sdk.transforms.Count; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import java.util.HashMap; import java.util.ArrayList; import java.text.SimpleDateFormat; public class Mihin_Encounter { private static long row_id = 0; static final DoFn<String, TableRow> MUTATION_TRANSFORM = new DoFn<String, TableRow>() { private static final long serialVersionUID = 1L; @Override public void processElement(DoFn<String, TableRow>.ProcessContext c) throws Exception { String line = c.element(); JSONArray indicationObject =null; String patientId = null, startDate = null,startMonth,startYear,kind=null,e_id = null ; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(line); JSONObject jsonObject = (JSONObject) obj; JSONArray resource = (JSONArray) jsonObject.get("resources"); for (int i = 0; i < resource.size(); i++) { row_id = row_id +1; JSONObject jsonObject1 = (JSONObject) parser.parse(resource.get(i).toString()); HashMap map = (HashMap) jsonObject1.get("resource"); HashMap<String , JSONArray> map2 = (HashMap<String, JSONArray>) jsonObject1.get("resource"); JSONObject patientObj = (JSONObject) map.get("patient"); String patient = (String) patientObj.get("reference"); patientId = patient.substring(patient.indexOf('/')+1); JSONObject periodObj = (JSONObject) map.get("period"); startDate = (String) periodObj.get("start"); kind = (String) map.get("class"); e_id = (String) map.get("id"); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date date = sdf1.parse(startDate); java.sql.Date sqlStartDate = new java.sql.Date(date.getTime()); TableRow row = new TableRow().set("encounter_id", e_id).set("class", kind).set("patient_id",patientId).set("startDate",sqlStartDate); c.output(row); } } catch(Exception e){ e.printStackTrace(); throw e; } } }; public static void main(String[] args) { DataflowPipelineOptions options = PipelineOptionsFactory.create().as(DataflowPipelineOptions.class); options.setRunner(BlockingDataflowPipelineRunner.class); options.setProject("healthcare-12"); options.setStagingLocation("gs://mihin-data/staging12"); Pipeline p = Pipeline.create(options); p.apply(TextIO.Read.named("Fetching file from storage").from("gs://mihin-data/formatedEncounterEntry.json")).apply(ParDo.named("Transforming FHIR -> Table Format").of(MUTATION_TRANSFORM)) .apply(BigQueryIO.Write .named("Pushing to BigQuerry") .to("healthcare-12:Mihin_Data_Sample.Encounter_Entry") .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_TRUNCATE) .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_NEVER)); p.run(); } }
Python
UTF-8
1,322
2.875
3
[]
no_license
""" @ OFDM仿真 @ 信道中,信号与信道特征卷积 @ DD """ import numpy as np from GlobalParameter import SymbolLength # 调制后发入信道的ofdm符号长度 # # two-tap channel # def getTwoTapChannel(): """ :param: void :return: generates a (2-tap) channel """ h_temp = np.array([np.random.rand() + 1j * np.random.rand(), (np.random.rand() + 1j * np.random.rand()) / 2]) return h_temp # # basic init # h_origin = getTwoTapChannel() ConvLength = SymbolLength + len(h_origin) - 1 LenH = 2 # # 信号卷积,输入的信号是经过ifft变换,串并转换的发射信号 # def ofdmConvChannelH(ofdmStream): """ :param ofdmStream: 一帧ofdm符号,长度为n * SymbolLength :return: 卷积后结果 """ symbol_reshape = ofdmStream.reshape((-1, SymbolLength)) n = symbol_reshape.shape[0] symbol_out = np.zeros((n, ConvLength), complex) if n > 0: for i in np.arange(n): symbol_out[i] = np.convolve(symbol_reshape[i], h_origin, mode='full') # 正常卷积 pass pass else: print("error, ofdmConvChannelH()") pass return symbol_out.ravel() # 拉直,假设发射时不同符号之间时间间隔足够,变回发射在空中的状态。 # # debug # if "__main__" == __name__: pass
Java
UTF-8
2,901
2.375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.organizer.form; import java.io.Serializable; import javax.persistence.*; import org.codehaus.jackson.annotate.JsonIgnore; /** * * @author dejmien */ @Entity @Table(name = "diary") @NamedQueries({ @NamedQuery(name = "Diary.findAll", query = "SELECT d FROM Diary d")}) public class Diary implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "Id_Diary") private Integer idDiary; @Lob @Column(name = "Contents") private String contents; @Basic(optional = false) @Column(name = "Day") private int day; @Basic(optional = false) @Column(name = "Month") private int month; @Basic(optional = false) @Column(name = "Year") private int year; @JoinColumn(name = "Id_User", referencedColumnName = "Id_User") @ManyToOne private User idUser; public Diary() { } public Diary(Integer idDiary) { this.idDiary = idDiary; } public Diary(Integer idDiary, int day, int month, int year) { this.idDiary = idDiary; this.day = day; this.month = month; this.year = year; } public Integer getIdDiary() { return idDiary; } public void setIdDiary(Integer idDiary) { this.idDiary = idDiary; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getYear() { return year; } public void setYear(int year) { this.year = year; } @JsonIgnore public User getIdUser() { return idUser; } public void setIdUser(User idUser) { this.idUser = idUser; } @Override public int hashCode() { int hash = 0; hash += (idDiary != null ? idDiary.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Diary)) { return false; } Diary other = (Diary) object; if ((this.idDiary == null && other.idDiary != null) || (this.idDiary != null && !this.idDiary.equals(other.idDiary))) { return false; } return true; } @Override public String toString() { return "net.organizer.form.Diary[ idDiary=" + idDiary + " ]"; } }
JavaScript
UTF-8
2,086
2.609375
3
[]
no_license
class EditorData { constructor( type, label ) { this.type = type; this.label = label; this.source = {}; this.__labels = {}; this.__help_messages = {}; this.__gateway_attrs = {}; this.__messages = {}; } setSource( config ) { this.source = config; return this; } setLabels( config ) { this.__labels = config; return this; } setHelp( config ) { this.__help_messages = config; return this; } setGatewayAttrs( config ) { this.__gateway_attrs = config; return this; } setMessages( config ) { this.__messages = config; return this; } exportAll() { if ( ! ( 'jetFormActionTypes' in window ) ) { window.jetFormActionTypes = []; } const source = this.source; const label = this.exportLabels(); const help = this.exportHelp(); const gatewayAttrs = this.exportGatewayAttrs(); const messages = this.exportMessages(); const exportObj = { source, label, help, messages, gatewayAttrs } const actionIndex = window.jetFormActionTypes.findIndex( type => this.type === type.id ); const actionData = { id: this.type, name: this.label, ...exportObj }; if ( -1 === actionIndex ) { window.jetFormActionTypes.push( actionData ); } else { window.jetFormActionTypes[ actionIndex ] = { ...window.jetFormActionTypes[ actionIndex ] , ...exportObj }; } return exportObj; } exportLabels() { return this.getLocalizedWithFunc( '__labels', '[Empty Label]' ); }; exportHelp() { return this.getLocalizedWithFunc( '__help_messages' ); }; exportGatewayAttrs() { return this.getLocalizedWithFunc( '__gateway_attrs', [] ); }; exportMessages() { return this.getLocalizedWithFunc( '__messages', {} ); }; getLocalizedWithFunc( objectKey, ifEmptyReturn = '' ) { let action = false; if ( objectKey in this ) { action = this[ objectKey ]; } if ( ! action ) { return () => ifEmptyReturn; } return attr => { if ( attr ) { return ( action[ attr ] ? action[ attr ] : ifEmptyReturn ); } else { return action; } }; }; } export default EditorData;
C++
UTF-8
592
2.578125
3
[]
no_license
#ifndef FLASHANIMATION_H #define FLASHANIMATION_H #include "Animation.h" typedef unsigned char frame_t; class FlashAnimation : public Animation{ frame_t repetitions; delay_t hideDelay; delay_t showDelay; public: FlashAnimation (frame_t n, delay_t show, delay_t hide, animid_t id ); ~FlashAnimation(void); void SetRepetitions (frame_t n); frame_t GetRepetitions (void) const; void SetHideDeay (delay_t d); delay_t GetHideDeay (void) const; void SetShowDeay (delay_t d); delay_t GetShowDeay (void) const; Animation* Clone (animid_t newId) const; }; #endif
PHP
UTF-8
394
3.296875
3
[]
no_license
<?php class Student { private $roll=101; private $stu_name='kuldeep'; private $f_name='shiv'; } class Weakstudent extends Student { private $contact='8890834430'; function showData() { //echo $this->roll; //echo $this->stu_name; //private member is not access in another class. //echo $this->f_name; echo $this->contact; } } $obj1=new Weakstudent; $obj1->showData(); ?>
Markdown
UTF-8
543
2.5625
3
[]
no_license
# twitchStreamsDisplay Display the twitch streams in your web, 100% editable css so it can match your web styles. IMPORTANT: 1.Remeber you will need to have a twitch API clientId in order to use this in your web, otherwise the API calls will never retrieve the information. 2.Here you have a TWICH blog post about where to get your clientID: https://blog.twitch.tv/client-id-required-for-kraken-api-calls-afbb8e95f843 If you have any queries or helpfull tip to make the app better while keeping it simple feel free to contact me. Thanks!
C++
UTF-8
2,805
3.65625
4
[]
no_license
// IFStatement.cpp: /*An IF statement acts as a conditional GOTO statement. It performs a comparison, and jumps to the specified line number if the comparison is true. An IF will always be followed by exactly five strings. The first is the name of the variable, the second is the operator, the third is an integer, the fourth is the word THEN, and the fifth is the line number. As with GOTO statements, the program terminates with the error message "Illegal jump instruction" if it tries to jump outside the boundaries of the program.*/ #include "IFStatement.h" #include <iostream> using namespace std; IFStatement::IFStatement(string var, string op, int val, int lineNum) { variable = var; this->op = op; value = val; number = lineNum; } IFStatement::~IFStatement() {} // The IFStatement version of execute() should call setProgramCounter function in Program State void IFStatement::execute(ProgramState * state, ostream &outf) { map<string, int> myMap = state->getMap(); if(op == "<"){ if(myMap[variable] < value){ if(number > state->getNumLines()){ outf << "Illegal jump instruction" << endl; state->setProgramCounter(-101); return; } else state->setProgramCounter(number); } else{ state->advanceProgramCounter(); } } else if (op == ">"){ if(myMap[variable] > value){ if(number > state->getNumLines()){ outf << "Illegal jump instruction" << endl; state->setProgramCounter(-101); return; } else state->setProgramCounter(number); } else{ state->advanceProgramCounter(); } } else if (op == ">="){ if(myMap[variable] >= value){ if(number > state->getNumLines()){ outf << "Illegal jump instruction" << endl; state->setProgramCounter(-101); return; } else state->setProgramCounter(number); } else{ state->advanceProgramCounter(); } } else if (op == "<="){ if(myMap[variable] <= value){ if(number > state->getNumLines()){ outf << "Illegal jump instruction" << endl; state->setProgramCounter(-101); return; } else state->setProgramCounter(number); } else{ state->advanceProgramCounter(); } } else if ( op == "="){ if(myMap[variable] == value){ if(number > state->getNumLines()){ outf << "Illegal jump instruction" << endl; state->setProgramCounter(-101); return; } else state->setProgramCounter(number); } else{ state->advanceProgramCounter(); } } else if ( op == "<>"){ if(myMap[variable] != value){ if(number > state->getNumLines()){ outf << "Illegal jump instruction" << endl; state->setProgramCounter(-101); return; } else state->setProgramCounter(number); } else{ state->advanceProgramCounter(); } } else{ state->advanceProgramCounter(); return; } }
Java
UTF-8
1,093
2.125
2
[]
no_license
package net.semsun.controller; import com.alibaba.fastjson.JSONObject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; @Controller public class Test1Controller { @RequestMapping("test") @ResponseBody public String test(HttpServletRequest request) { String sessionId = request.getSession().getId(); return sessionId; } @RequestMapping("header") @ResponseBody public String header(HttpServletRequest request) { Map<String, String> map = new HashMap<String, String>(); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = (String) headerNames.nextElement(); String value = request.getHeader(key); map.put(key, value); } return JSONObject.toJSONString(map); } }
Python
UTF-8
817
3.265625
3
[ "Unlicense" ]
permissive
# Unterdrückt die AVX2 Warnung import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import tensorflow as tf # Console.Write("Wie ist Dein Name? "); # string name = Console.ReadLine(); # # Console.Write("Gewicht in kg: "); # double weight = double.Parse(Console.ReadLine()); # # Console.Write("Größe in cm: "); # int height = int.Parse(Console.ReadLine()); # # double bmi = weight / Math.Pow(height/100.0, 2); # # Console.WriteLine($"{name} hat einen BMI von {Math.Round(bmi,1)}"); name = input("Wie ist Dein Name? ") weight = float(input('Gewicht in kg: ')) height = int(input('Größe in cm: ')) heighttf = tf.constant(height, tf.dtypes.float32) bmitf = tf.divide( tf.constant(weight), tf.pow( tf.divide(heighttf, 100.), 2.)) bmi = bmitf.numpy() # toString in Java tensor -> python datatype print("bmi=", bmi)
TypeScript
UTF-8
353
2.9375
3
[ "MIT" ]
permissive
// Based on https://github.com/wilsonzlin/edgesearch/blob/d03816dd4b18d3d2eb6d08cb1ae14f96f046141d/demo/wiki/client/src/util/util.ts // Ensures value is not null or undefined. // != does no type validation so we don't need to explcitly check for undefined. export function exists<T>(value: T | null | undefined): value is T { return value != null; }
Python
UTF-8
953
3.4375
3
[]
no_license
class Solution: def numIslands(self, grid) -> int: if not grid or not grid[0]: return 0 m, n = len(grid), len(grid[0]) count = 0 for i in range(m): for j in range(n): if grid[i][j] == '1': self.bfs(grid, i, j, m, n) count += 1 return count def bfs_step(self, queue, grid, y, x): if grid[y][x] == '1': queue.append([y, x]) grid[y][x] == '0' def bfs(self, grid, i, j, m, n): queue = [[i, j]] grid[i][j] = '0' while queue: i, j = queue.pop(0) if i > 0: self.bfs_step(queue, grid, i - 1, j) if j > 0: self.bfs_step(queue, grid, i, j - 1) if i < m - 1: self.bfs_step(queue, grid, i + 1, j) if j < n - 1: self.bfs_step(queue, grid, i, j + 1)
C++
UTF-8
260
2.890625
3
[]
no_license
#include "Cube.h" bool Cube::validCube() const { if (a > 0.0 && b > 0.0 && c > 0.0) { return true; } return false; } double Cube::volume() const { return a * b * c; } Cube::Cube(const double a, const double b, const double c) : a(a), b(b), c(c) { }
Python
UTF-8
91
2.6875
3
[]
no_license
# temp 이름의 비어있는 딕셔너리를 만들라. temp = {} print(temp, type(temp))
Python
UTF-8
3,411
2.625
3
[ "Apache-2.0" ]
permissive
# ########################################################################### # # CLOUDERA APPLIED MACHINE LEARNING PROTOTYPE (AMP) # (C) Cloudera, Inc. 2020 # All rights reserved. # # Applicable Open Source License: Apache 2.0 # # NOTE: Cloudera open source products are modular software products # made up of hundreds of individual components, each of which was # individually copyrighted. Each Cloudera open source product is a # collective work under U.S. Copyright Law. Your license to use the # collective work is as provided in your written agreement with # Cloudera. Used apart from the collective work, this file is # licensed for your use pursuant to the open source license # identified above. # # This code is provided to you pursuant a written agreement with # (i) Cloudera, Inc. or (ii) a third-party authorized to distribute # this code. If you do not have a written agreement with Cloudera nor # with an authorized and properly licensed third party, you do not # have any rights to access nor to use this code. # # Absent a written agreement with Cloudera, Inc. (“Cloudera”) to the # contrary, A) CLOUDERA PROVIDES THIS CODE TO YOU WITHOUT WARRANTIES OF ANY # KIND; (B) CLOUDERA DISCLAIMS ANY AND ALL EXPRESS AND IMPLIED # WARRANTIES WITH RESPECT TO THIS CODE, INCLUDING BUT NOT LIMITED TO # IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY AND # FITNESS FOR A PARTICULAR PURPOSE; (C) CLOUDERA IS NOT LIABLE TO YOU, # AND WILL NOT DEFEND, INDEMNIFY, NOR HOLD YOU HARMLESS FOR ANY CLAIMS # ARISING FROM OR RELATED TO THE CODE; AND (D)WITH RESPECT TO YOUR EXERCISE # OF ANY RIGHTS GRANTED TO YOU FOR THE CODE, CLOUDERA IS NOT LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE OR # CONSEQUENTIAL DAMAGES INCLUDING, BUT NOT LIMITED TO, DAMAGES # RELATED TO LOST REVENUE, LOST PROFITS, LOSS OF INCOME, LOSS OF # BUSINESS ADVANTAGE OR UNAVAILABILITY, OR LOSS OR CORRUPTION OF # DATA. # # ########################################################################### import logging import os import numpy as np from lib.utils import image_array_from_dir, image_to_np_array logger = logging.getLogger(__name__) class Extractor(): def __init__(self): self.valid_file_types = ["jpg", "png"] def extract(self, image_array, model): """Extract features, given a numpy array of images. Args: image_array (numpy array): numpy array of images model (Model): lib.Model object Returns: np.array: numpy array of extracted features (representations) """ features = model.get_features(image_array) features = features.reshape(features.shape[0], -1) logger.info(">>> feature extraction complete.") return features def extract_from_dir(self, images_dir, model): """Extract images from a directory Args: images_dir (str): path to a directory model (Model): lib.Model Returns: np.array: numpy.array containing extracted features. """ logger.info(">>> Scanning folder to get files.") image_array, image_ids = image_array_from_dir( images_dir, model.image_size, self.valid_file_types) # print(image_array) features = self.extract(image_array, model) return features, image_ids
C++
UTF-8
4,490
2.546875
3
[]
no_license
// // Name: CpuWorkload.cpp : implementation file // Author: hieunt // Description: Stress CPU with many workload // #include "stdafx.h" #include "CpuWorkload.h" #define ARR_LEN 2048 /// <summary> /// Initializes a new instance of the <see cref="CpuWorkload"/> class. /// </summary> CpuWorkload::CpuWorkload() { m_NumWorkerThreads = 1; m_KillWorkerThreads = FALSE; m_CPUWorkDoneSinceLastCheck = 0; m_JobLimit = 100000; m_IsStart = FALSE; SYSTEM_INFO sysinfo; GetSystemInfo( &sysinfo ); m_MaxWorkedThreadCount = max(1, sysinfo.dwNumberOfProcessors); } /// <summary> /// Starts this instance. /// </summary> VOID CpuWorkload::Start() { m_IsStart = TRUE; m_WorkerThreads = new HANDLE[m_MaxWorkedThreadCount]; m_ThreadInfo = new ThreadInfo[m_MaxWorkedThreadCount]; m_ThreadWait = CreateEvent( NULL, // default security attributes TRUE, // manual-reset event FALSE, // initial state is nonsignaled TEXT("WriteEvent") // object name ); for( int i = 0; i < m_MaxWorkedThreadCount; i++ ) { m_ThreadInfo[i]._this = this; m_ThreadInfo[i].ThreadID = i; m_WorkerThreads[i] = CreateThread(NULL, ARR_LEN * 8 + 256 * 1024, (LPTHREAD_START_ROUTINE)RunEx, (LPVOID)&(m_ThreadInfo[i]), CREATE_SUSPENDED, NULL); SetThreadPriority( m_WorkerThreads[i], THREAD_PRIORITY_LOWEST ); ResumeThread( m_WorkerThreads[i] ); } } /// <summary> /// Stops this instance. /// </summary> VOID CpuWorkload::Stop() { m_KillWorkerThreads = TRUE; WaitForMultipleObjects(m_MaxWorkedThreadCount, m_WorkerThreads, TRUE, 1000); //delete [] m_WorkerThreads; //delete [] m_ThreadInfo; m_IsStart = FALSE; m_KillWorkerThreads=FALSE; } /// <summary> /// Finalizes an instance of the <see cref="CpuWorkload"/> class. /// </summary> CpuWorkload::~CpuWorkload() { if(m_KillWorkerThreads==FALSE) { m_KillWorkerThreads = TRUE; if(m_IsStart==TRUE) { WaitForMultipleObjects( m_MaxWorkedThreadCount, m_WorkerThreads, TRUE, 1000 ); delete [] m_WorkerThreads; delete [] m_ThreadInfo; } } } DWORD WINAPI CpuWorkload::RunEx(LPVOID lpParam) { ThreadInfo* pThreadInfo = (ThreadInfo*)(lpParam); pThreadInfo->_this->Run((LPVOID)(pThreadInfo)); return 0; } DWORD WINAPI CpuWorkload::Run(LPVOID p) { ThreadInfo* pThreadInfo = (ThreadInfo*)p; int MyID = (int)pThreadInfo->ThreadID; FLOAT m_Arr[2][ARR_LEN]; for (int i=0;i<ARR_LEN;i++) { m_Arr[0][i] = rand() / (float)RAND_MAX; m_Arr[1][i] = rand() / (float)RAND_MAX; } pThreadInfo->ElapsedTime = 0; while( !m_KillWorkerThreads ) { INT64 CurrentWorkProcessed = InterlockedOr64(&m_CPUWorkDoneSinceLastCheck,0); if(m_JobLimit!=-1) { if(CurrentWorkProcessed>(m_JobLimit-m_NumWorkerThreads)) { ResetEvent(m_ThreadWait) ; WaitForSingleObject( m_ThreadWait, 1000 ); } } if( MyID >= m_NumWorkerThreads ) { // No job for us? Relax. Sleep( 10 ); continue; } // Right! Do some number crunching. double avg = 0.0; for (int i=0;i<ARR_LEN-1;i++) { avg += m_Arr[1][i]; m_Arr[0][i] = (float)fmod( pow( (double)m_Arr[1][i]*10.0, (double)m_Arr[1][i+1]+0.5 ), 1.0 ); } m_Arr[0][ARR_LEN-1] = (float)(avg / (double)(ARR_LEN-1)); avg = 0.0; for (int i=0;i<ARR_LEN-1;i++) { avg += m_Arr[0][i]; m_Arr[1][i] = (float)fmod( pow( (double)m_Arr[0][i+1]*10.0, (double)m_Arr[0][i]+0.5 ), 1.0 ); } m_Arr[1][ARR_LEN-1] = (float)(avg / (double)(ARR_LEN-1)); // Aaand just repeat one more time avg = 0.0; for (int i=0;i<ARR_LEN-1;i++) { avg += m_Arr[1][i]; m_Arr[0][i] = (float)fmod( pow( (double)m_Arr[1][i]*10.0, (double)m_Arr[1][i+1]+0.5 ), 1.0 ); } m_Arr[0][ARR_LEN-1] = (float)(avg / (double)(ARR_LEN-1)); avg = 0.0; for (int i=0;i<ARR_LEN-1;i++) { avg += m_Arr[0][i]; m_Arr[1][i] = (float)fmod( pow( (double)m_Arr[0][i+1]*10.0, (double)m_Arr[0][i]+0.5 ), 1.0 ); } m_Arr[1][ARR_LEN-1] = (float)(avg / (double)(ARR_LEN-1)); InterlockedIncrement64( &m_CPUWorkDoneSinceLastCheck ); } return 0; } INT CpuWorkload::GetWorkDone() { INT64 workDone = 0; workDone = ::InterlockedExchange64( &m_CPUWorkDoneSinceLastCheck, 0 ); return (INT)workDone; } INT CpuWorkload::Reset() { SetEvent(m_ThreadWait); return 0; } VOID CpuWorkload::SetNumThreads(FLOAT ThreadCount) { m_NumWorkerThreads = (INT)ThreadCount; } VOID CpuWorkload::SetJobLimit(FLOAT Jobs) { m_JobLimit = (INT)Jobs; } INT CpuWorkload::GetMaxNumThreads() { return m_MaxWorkedThreadCount; }
Python
UTF-8
16,310
3.515625
4
[]
no_license
import os import pandas as pd import numpy as np import requests import time import re # --------------------------------------------------------------------- # Question #1 # --------------------------------------------------------------------- def request_with_retries(url, max_retry, retry=0): '''returns a http reponse to the request to target url. If ''' resp = requests.get(url) if resp.ok: return resp elif retry < max_retry: time.sleep(2**retry) return request_with_retries(url, max_retry, retry=(retry + 1)) else: return resp def get_book(url): """ get_book that takes in the url of a 'Plain Text UTF-8' book and returns a string containing the contents of the book. The function should satisfy the following conditions: - The contents of the book consist of everything between Project Gutenberg's START and END comments. - The contents will include title/author/table of contents. - You should also transform any Windows new-lines (\r\n) with standard new-lines (\n). - If the function is called twice in succession, it should not violate the robots.txt policy. :Example: (note '\n' don't need to be escaped in notebooks!) >>> url = 'http://www.gutenberg.org/files/57988/57988-0.txt' >>> book_string = get_book(url) >>> book_string[:20] == '\\n\\n\\n\\n\\nProduced by Chu' True """ req = request_with_retries(url, 2) text = req.text text = re.sub('\r\n', '\n', text) start_end = re.findall('\*\*\*[A-Z0-9 ]+\*\*\*', text) start = text.find(start_end[0]) end = text.find(start_end[1]) content = text[start + len(start_end[0]):end] content return content # --------------------------------------------------------------------- # Question #2 # --------------------------------------------------------------------- def tokenize(book_string): """ tokenize takes in book_string and outputs a list of tokens satisfying the following conditions: - The start of any paragraph should be represented in the list with the single character \x02 (standing for START). - The end of any paragraph should be represented in the list with the single character \x03 (standing for STOP). - Tokens in the sequence of words are split apart at 'word boundaries' (see the regex lecture). - Tokens should include no whitespace. :Example: >>> test_fp = os.path.join('data', 'test.txt') >>> test = open(test_fp, encoding='utf-8').read() >>> tokens = tokenize(test) >>> tokens[0] == '\x02' True >>> tokens[9] == 'dead' True >>> sum([x == '\x03' for x in tokens]) == 4 True >>> '(' in tokens True """ text2 = re.sub('(\n\n)+', '\x03\x02', book_string) split = re.findall(r"[A-Za-z0-9]+|[-_().,!?;:']|[\x03\x02]", text2) if split[-1] == '\x02': split = split[:-1] elif split[-1] != '\x03': split = split + ['\x03'] if split[0] == '\x03': split == split[1] elif split[0] != '\x02': split = ['\x02'] + split return split # --------------------------------------------------------------------- # Question #3 # --------------------------------------------------------------------- class UniformLM(object): """ Uniform Language Model class. """ def __init__(self, tokens): """ Initializes a Uniform languange model using a list of tokens. It trains the language model using `train` and saves it to an attribute self.mdl. """ self.mdl = self.train(tokens) def train(self, tokens): """ Trains a uniform language model given a list of tokens. The output is a series indexed on distinct tokens, and values giving the (uniform) probability of a token occuring in the language. :Example: >>> tokens = tuple('one one two three one two four'.split()) >>> unif = UniformLM(tokens) >>> isinstance(unif.mdl, pd.Series) True >>> set(unif.mdl.index) == set('one two three four'.split()) True >>> (unif.mdl == 0.25).all() True """ to_series = pd.Series(1 / len(np.array(np.unique(tokens))), index=np.array(np.unique(tokens))) return to_series def probability(self, words): """ probability gives the probabiliy a sequence of words appears under the language model. :param: words: a tuple of tokens :returns: the probability `words` appears under the language model. :Example: >>> tokens = tuple('one one two three one two four'.split()) >>> unif = UniformLM(tokens) >>> unif.probability(('five',)) 0 >>> unif.probability(('one', 'two')) == 0.0625 True """ prob = 1 for i in words: if i not in self.mdl.index: prob = prob * 0 else: prob_item = self.mdl.get(i) prob = float(prob) * prob_item return prob def sample(self, M): """ sample selects tokens from the language model of length M, returning a string of tokens. :Example: >>> tokens = tuple('one one two three one two four'.split()) >>> unif = UniformLM(tokens) >>> samp = unif.sample(1000) >>> isinstance(samp, str) True >>> len(samp.split()) == 1000 True >>> s = pd.Series(samp.split()).value_counts(normalize=True) >>> np.isclose(s, 0.25, atol=0.05).all() True """ result = '' for i in range(M): result += self.mdl.sample(n=1).index[0] + ' ' return result # --------------------------------------------------------------------- # Question #4 # --------------------------------------------------------------------- class UnigramLM(object): def __init__(self, tokens): """ Initializes a Unigram languange model using a list of tokens. It trains the language model using `train` and saves it to an attribute self.mdl. """ self.mdl = self.train(tokens) def train(self, tokens): """ Trains a unigram language model given a list of tokens. The output is a series indexed on distinct tokens, and values giving the probability of a token occuring in the language. :Example: >>> tokens = tuple('one one two three one two four'.split()) >>> unig = UnigramLM(tokens) >>> isinstance(unig.mdl, pd.Series) True >>> set(unig.mdl.index) == set('one two three four'.split()) True >>> unig.mdl.loc['one'] == 3 / 7 True """ lst = list(tokens) index = list(set(tokens)) value = [] for i in index: value.append(lst.count(i)/len(lst)) ser = pd.Series(value, index=index) return ser def probability(self, words): """ probability gives the probabiliy a sequence of words appears under the language model. :param: words: a tuple of tokens :returns: the probability `words` appears under the language model. :Example: >>> tokens = tuple('one one two three one two four'.split()) >>> unig = UnigramLM(tokens) >>> unig.probability(('five',)) 0 >>> p = unig.probability(('one', 'two')) >>> np.isclose(p, 0.12244897959, atol=0.0001) True """ prob = 1 for i in words: if i not in self.mdl.index: prob = prob * 0 else: prob_item = self.mdl.get(i) prob = float(prob) * prob_item return prob def sample(self, M): """ sample selects tokens from the language model of length M, returning a string of tokens. >>> tokens = tuple('one one two three one two four'.split()) >>> unig = UnigramLM(tokens) >>> samp = unig.sample(1000) >>> isinstance(samp, str) True >>> len(samp.split()) == 1000 True >>> s = pd.Series(samp.split()).value_counts(normalize=True).loc['one'] >>> np.isclose(s, 0.41, atol=0.05).all() True """ result = '' for i in range(M): result += self.mdl.sample(n=1, weights=self.mdl).index[0] + ' ' return result # --------------------------------------------------------------------- # Question #5,6,7,8 # --------------------------------------------------------------------- class NGramLM(object): def __init__(self, N, tokens): """ Initializes a N-gram languange model using a list of tokens. It trains the language model using `train` and saves it to an attribute self.mdl. """ self.N = N ngrams = self.create_ngrams(tokens) self.ngrams = ngrams self.mdl = self.train(ngrams) if N < 2: raise Exception('N must be greater than 1') elif N == 2: self.prev_mdl = UnigramLM(tokens) else: mdl = NGramLM(N-1, tokens) self.prev_mdl = mdl def create_ngrams(self, tokens): """ create_ngrams takes in a list of tokens and returns a list of N-grams. The START/STOP tokens in the N-grams should be handled as explained in the notebook. :Example: >>> tokens = tuple('\x02 one two three one four \x03'.split()) >>> bigrams = NGramLM(2, []) >>> out = bigrams.create_ngrams(tokens) >>> isinstance(out[0], tuple) True >>> out[0] ('\\x02', 'one') >>> out[2] ('two', 'three') """ result = [] lst = list(tokens) for i in range(len(lst) - self.N + 1): nlist = [lst[j] for j in range(i, i + self.N)] result.append(tuple(nlist)) return result def train(self, ngrams): """ Trains a n-gram language model given a list of tokens. The output is a dataframe with three columns (ngram, n1gram, prob). :Example: >>> tokens = tuple('\x02 one two three one four \x03'.split()) >>> bigrams = NGramLM(2, tokens) >>> set(bigrams.mdl.columns) == set('ngram n1gram prob'.split()) True >>> bigrams.mdl.shape == (6, 3) True >>> bigrams.mdl['prob'].min() == 0.5 True """ # ngram counts C(w_1, ..., w_n) counts = np.zeros(len(ngrams)) for i in range(len(ngrams)): counts[i] = ngrams.count(ngrams[i]) # n-1 gram counts C(w_1, ..., w_(n-1)) precede = list(map(lambda x: x[:-1], ngrams)) counts2 = np.zeros(len(precede)) for i in range(len(precede)): counts2[i] = precede.count(precede[i]) cond_prob = counts / counts2 result = pd.DataFrame() result['ngram'] = ngrams result['n1gram'] = precede result['prob'] = cond_prob return result.drop_duplicates(subset='ngram').reset_index(drop=True) # return result # Create the conditional probabilities # Put it all together def probability(self, words): """ probability gives the probabiliy a sequence of words appears under the language model. :param: words: a tuple of tokens :returns: the probability `words` appears under the language model. :Example: >>> tokens = tuple('\x02 one two one three one two \x03'.split()) >>> bigrams = NGramLM(2, tokens) >>> p = bigrams.probability('two one three'.split()) >>> np.isclose(p, (1/4)*(1/2)*(1/3)) True >>> bigrams.probability('one two five'.split()) == 0 True """ prob = 1 base_case = [] for i in range(len(self.ngrams)): if i == 0: base_case += list(self.ngrams[i]) else: for j in list(self.ngrams[i])[self.N - 1:]: base_case.append(j) base_case = pd.Series(base_case) base_prob = base_case.value_counts(normalize=True) for i in words: if i not in base_case.to_list(): prob *= 0 prob = prob * base_prob.get(words[0]) ''' subtoken = [] for i in range(len(words)-self.N+1): nlist = [words[j] for j in range(i, i+self.N)] subtoken.append(tuple(nlist)) for i in subtoken: if i not in self.mdl['ngram'].to_list(): prob = prob*0 ''' ''' for i in words: for j in self.mdl['ngram']: if (words.index(i) == 0 and j[0] == i): words.index(i)!=0 and j[1] == i: prob = prob * self.mdl.loc[self.mdl['ngram']==j]['prob'].values[0] ''' n1 = self.mdl n = self.N new_ngrams = self.create_ngrams(words) cond_prob = 1 for i in new_ngrams: for j in n1['ngram'].to_list(): if j == i: prob = prob * n1.loc[n1['ngram'] == j]['prob'].values[0] while n > 2: n1 = self.train(n1['n1gram'].to_list()) new_ngrams1 = list(map(lambda x: x[:-1], new_ngrams)) for i in new_ngrams1: for j in n1['ngram'].to_list(): if j == i: prob = prob * n1.loc[n1['ngram'] == j]['prob'].values[0] n -= 1 return prob def sample(self, M): """ sample selects tokens from the language model of length M, returning a string of tokens. :Example: >>> tokens = tuple('\x02 one two three one four \x03'.split()) >>> bigrams = NGramLM(2, tokens) >>> samp = bigrams.sample(3) >>> len(samp.split()) == 4 # don't count the initial START token. True >>> samp[:2] == '\\x02 ' True >>> set(samp.split()) <= {'\\x02', '\\x03', 'one', 'two', 'three', 'four'} True """ # Use a helper function to generate sample tokens of length `length` sample = [] first = self.mdl.sample()["ngram"].tolist()[0] for i in first: sample.append(i) precede = first[1:] for i in range(M-self.N): table = self.mdl[self.mdl["n1gram"] == precede] df = table.copy() df["weight"] = df["ngram"].apply(lambda x: self.probability(x)) if df.size == 0: gene = self.mdl.sample(weights=df["weight"])["ngram"].tolist()[0][0] else: gene = df.sample(weights=df["weight"])["ngram"].tolist()[0][0] sample.append(gene) precede = list(precede)[1:] precede.append(gene) precede = tuple(precede) # Transform the tokens to strings result = '\x02' for s in sample: result = result + " " + s return result # --------------------------------------------------------------------- # DO NOT TOUCH BELOW THIS LINE # IT'S FOR YOUR OWN BENEFIT! # --------------------------------------------------------------------- # Graded functions names! DO NOT CHANGE! # This dictionary provides your doctests with # a check that all of the questions being graded # exist in your code! GRADED_FUNCTIONS = { 'q01': ['get_book'], 'q02': ['tokenize'], 'q03': ['UniformLM'], 'q04': ['UnigramLM'], 'q05': ['NGramLM'] } def check_for_graded_elements(): """ >>> check_for_graded_elements() True """ for q, elts in GRADED_FUNCTIONS.items(): for elt in elts: if elt not in globals(): stmt = "YOU CHANGED A QUESTION THAT SHOULDN'T CHANGE! \ In %s, part %s is missing" %(q, elt) raise Exception(stmt) return True
Java
UTF-8
686
1.953125
2
[]
no_license
package com.example.android.journalapp.Activities; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.example.android.journalapp.Contract.ViewProfileContract; import com.example.android.journalapp.R; public class ViewProfileActivity extends AppCompatActivity implements ViewProfileContract.View{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_profile); } @Override public void viewUsername() { } @Override public void viewEmailAddress() { } @Override public void viewProfilePics() { } }
Java
UTF-8
440
1.914063
2
[ "Apache-2.0" ]
permissive
package io.xmeta.jetbrains.services; import com.intellij.openapi.application.ModalityState; import java.util.concurrent.Callable; import java.util.function.Consumer; public interface ExecutorService { <T> void runInBackground(Callable<T> task, Consumer<T> onSuccess, Consumer<Exception> onFailure); <T> void runInBackground(Callable<T> task, Consumer<T> onSuccess, Consumer<Exception> onFailure, ModalityState modalityState); }
C++
UTF-8
935
3.71875
4
[]
no_license
#include <cstdio> #include <cstring> #include "employee.h" employee::employee(const char *const first, const char *const last, const date &birth, const date &hire) // : birth_date(birth), hire_date(hire) // member initializer list { size_t len = strlen(first); len = len < 25 ? len : 24; strncpy(this->first_name, first, len); this->first_name[len] = '\0'; len = strlen(last); len = len < 25 ? len : 24; strncpy(this->last_name, last, len); this->last_name[len] = '\0'; this->birth_date = birth; this->hire_date = hire; printf("Employee object constructor: %s %s\n", this->first_name, this->last_name); } employee::~employee(void) { printf("Employee object destructor: %s, %s\n", this->last_name, this->first_name); } void employee::print(void) const { printf("%s, %s Hired: ", this->last_name, this->first_name); this->hire_date.print(); printf(" Birthday: "); this->birth_date.print(); printf("\n"); }