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
Java
UTF-8
2,824
1.75
2
[ "Apache-2.0" ]
permissive
package com.yibairun.api.operations; import com.android.volley.Response; import com.yibairun.bean.InvitationCode; import com.yibairun.bean.OrderlInfo; import com.yibairun.bean.ProductDetailInfo; import com.yibairun.bean.ProductInvestList; import com.yibairun.bean.ProductList; import com.yibairun.bean.StatusMessage; import com.yibairun.bean.UserInfo; import com.yibairun.bean.VersionInfo; public interface ProductOperations { public abstract void setToken(String token); public abstract void setDeviceId(String deviceId); /** * 产品列表 * @param listener * @param errorListener * @param page */ void getProductList(Response.Listener<ProductList> listener, Response.ErrorListener errorListener,int page); /** * 產品詳情 * @param listener * @param errorListener * @param id */ void getProductDetail(Response.Listener<ProductDetailInfo> listener, Response.ErrorListener errorListener,int id); /** * 获取订单号 * @param money */ void getOrderId(Response.Listener<OrderlInfo> listener, Response.ErrorListener errorListener,String appkey,double money); /** * 投资中的产品 * @param listener * @param errorListener * @param appkey * @param page */ void getInvestingList(Response.Listener<ProductInvestList> listener, Response.ErrorListener errorListener,String appkey, int page); /** * 获取已经结束的投资产品 * @param listener * @param errorListener * @param appkey * @param page */ void getOverInvestMentList(Response.Listener<ProductInvestList> listener, Response.ErrorListener errorListener,String appkey, int page); /** * 购买 * @param listener * @param errorListener * @param appkey * @param money * @param pid * @param paypassword */ void buyPorduct(Response.Listener<StatusMessage> listener, Response.ErrorListener errorListener,String appkey, double money,int pid,String paypassword); /** * 提现 * @param listener * @param errorListener * @param appkey * @param money * @param bank_id * @param paypassword */ void getCash(Response.Listener<StatusMessage> listener, Response.ErrorListener errorListener,String appkey, double money,int bank_id,String paypassword); /** * 版本检测更新 * @param listener * @param errorListener */ void getVersion(Response.Listener<VersionInfo> listener,Response.ErrorListener errorListener); /** * @功能描述 获取邀请码 * @param listener * @param errorListener * @param appkey */ void GetInviteCode(Response.Listener<InvitationCode> listener,Response.ErrorListener errorListener,String appkey); }
JavaScript
UTF-8
1,343
2.578125
3
[]
no_license
import React, { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import { readDeck, createCard } from "../utils/api"; import CardForm from "./CardForm.js"; import SubHeader from "../Layout/SubHeader.js"; export default function AddCard() { const { deckId } = useParams(); const [deck, setDeck] = useState({}); const [formData, setFormData] = useState({ front: "", back: "", }); //Will find deck from API given deckId and change deck state accordingly useEffect(() => { const abortController = new AbortController(); async function getDeck() { const data = await readDeck(deckId, abortController.signal); setDeck(data); } getDeck(); }, [deckId]); //Will create card for current deck given the front and back content values function addCard(front, back) { const ac = new AbortController(); createCard(deckId, { front, back }, ac.signal); } //CardForm is being called with addCard as its onSuccess function return ( <React.Fragment> <SubHeader deck={deck} breadCrumbText="Add Card" /> <div className="container"> <CardForm deck={deck} formData={formData} setFormData={setFormData} isNew={true} onSuccess={addCard} /> </div> </React.Fragment> ); }
Java
UTF-8
751
2.25
2
[]
no_license
package com.example.demo.entity; import lombok.*; import javax.persistence.*; import javax.validation.constraints.NotBlank; @Data @NoArgsConstructor @AllArgsConstructor @Table @Entity @Getter @Setter public class Employee { @Id @GeneratedValue private int employeeId; private String employeeName; private String employeeAddress; private String employeeMobile; private int employeeGradeId; private String employeeBankAccountNumber; // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "grade_id") // @NotBlank(message = "Grade is Mandatory") // private Grade employeeGrade; // @OneToOne // @JoinColumn(name="employee_bank_account_id") // private BankAccount employeeBankAccountNumber; }
C#
UTF-8
2,058
2.9375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace App { public class CoinChanger { private const int quarter = 25; private const int dime = 10; private const int nickel = 5; private const int penny = 1; // private int total = 0; public int incrementquarter = 0; public int incrementdime = 0; public int incrementnickel = 0; public int incrementpenny = 0; public void GetTheChange(int cash) { int total = cash; while (total != 0) { if(Condition(total, quarter)) { incrementquarter = GetCoinIncrement(incrementquarter); total = GetTotal(total, quarter); } else if (Condition(total, dime)) { incrementdime = GetCoinIncrement(incrementdime); total = GetTotal(total, dime); } else if (Condition(total, nickel)) { incrementnickel = GetCoinIncrement(incrementnickel); total = GetTotal(total, nickel); } else { incrementpenny = GetCoinIncrement(incrementpenny); total = GetTotal(total, penny); } } } public int GetCoinIncrement(int increment) { int numberOfCoinsincremented = 0; numberOfCoinsincremented = increment + 1; return numberOfCoinsincremented; } public int GetTotal(int total1, int coin) { int currentTotal = 0; currentTotal = total1 - coin; return currentTotal; } public bool Condition(int total2, int number) { bool total3; total3 = total2 >= number; return total3; } } }
Python
UTF-8
2,266
3.109375
3
[]
no_license
import json import requests BASE_URL = 'https://github.com/simonepri/geo-maps/releases/latest/download/' # Required countries # UK - GBR, Ireland - IRL, Germany - DEU, Greece - GRC, Finland - FIN, # Bulgaria - BGR, Hungary - HUN, Malta - MLT, Italy - ITA COUNTRIES = [ ['GBR', 'uk'], ['IRL', 'ierland'], ['DEU', 'germany'], ['GRC', 'greece'], ['FIN', 'finland'], ['BGR', 'bulgaria'], ['HUN', 'hungary'], ['MLT', 'malta'], ['ITA', 'italy'] ] def get_data_from_url(filename): print('Fetching ', filename) url = BASE_URL + filename r = requests.get(url) data = r.json() return data def filter_required_countries(data, type_of_data): print('Extracting required countries') output = [] features = data['features'] required_countries = [] for country in COUNTRIES: required_countries.append(country[0]) for feature in features: if feature['properties']['A3'] in required_countries: feature['properties']['type'] = type_of_data output.append(feature) return output def generate_country_polygons(data): output = { "type": "FeatureCollection", "features": [] } for country in COUNTRIES: for items in data: if items['properties']['A3'] == country[0]: output['features'].append(items) print ('writing data for ', country[1]) with open('data/' + country[1] + '.geo.json', 'w') as file: json.dump(output, file) output['features'] = [] def process_data(resolution): coastline = 'countries-coastline-' + resolution + '.geo.json' coastline_data = get_data_from_url(coastline) land = 'countries-land-' + resolution + '.geo.json' land_data = get_data_from_url(land) filtered_coastline_data = filter_required_countries(coastline_data, 'coastline') filtered_land_data = filter_required_countries(land_data, 'land') filtered_data = filtered_coastline_data + filtered_land_data generate_country_polygons(filtered_data) # with open(outputpath, 'w') as file: # json.dump(output, file) # print('Got data for ',len(output['features']), ' countries') process_data('1m')
Rust
UTF-8
5,737
2.625
3
[]
no_license
mod cpu; mod disk; mod job; mod ping; mod ram; mod shared; use reqwest::blocking::{Client, RequestBuilder}; use serde::de::DeserializeOwned; pub use cpu::CpuForm; pub use disk::DiskForm; pub use job::JobResp; pub use ping::PingResp; pub use ram::RamForm; pub use shared::ReportResp; use crate::shared::SharedCli; use crate::sqlite_db::SQLiteForm; /// 测试结果上报 #[derive(Clone)] pub struct BenchReport<'a> { cli: &'a SharedCli, } impl<'a> BenchReport<'a> { #[inline] pub fn new(cli: &'a SharedCli, print_user: bool) -> Self { Self::test_app_key_valid(cli, print_user); BenchReport { cli } } /// 创建一个新的任务 pub fn new_job(&self) -> String { let url = self.get_api_url("job"); let builder = Self::add_header(Client::new().get(url.as_str()), self.cli.app_key.as_str()); let resp = Self::send_request::<JobResp>(builder, url.as_str()); resp.job_id } /// 磁盘测试结果上报 pub fn disk_report(&self, out_dir: Option<&str>, form: &DiskForm) { self.do_write_to_file(out_dir, "disk.json", form); let url = self.get_api_url("disk"); let resp = self.do_report(url.as_str(), form); if resp.success() { return; } eprintln!( "上报 磁盘 基准测试结果失败 错误码 {}, 错误信息: {}", resp.errno, resp.errmsg ); std::process::exit(1); } /// CPU 测试结果上报 pub fn cpu_report(&self, out_dir: Option<&str>, form: &CpuForm) { self.do_write_to_file(out_dir, "cpu.json", form); let url = self.get_api_url("cpu"); let resp = self.do_report(url.as_str(), form); if resp.success() { return; } eprintln!( "上报 CPU 基准测试结果失败 错误码 {}, 错误信息: {}", resp.errno, resp.errmsg ); std::process::exit(1); } pub fn sqlite_report(&self, out_dir: Option<&str>, form: &SQLiteForm) { self.do_write_to_file(out_dir, "sqlite.json", form); let url = self.get_api_url("sqlite"); let resp = self.do_report(url.as_str(), form); if resp.success() { return; } eprintln!( "上报 SQLite 基准测试结果失败 错误码 {}, 错误信息: {}", resp.errno, resp.errmsg ); std::process::exit(1); } /// 内存测试结果上报 pub fn ram_report(&self, out_dir: Option<&str>, form: &RamForm) { self.do_write_to_file(out_dir, "ram.json", form); let url = self.get_api_url("ram"); let resp = self.do_report(url.as_str(), form); if resp.success() { return; } eprintln!( "上报 内存 基准测试结果失败 错误码 {}, 错误信息: {}", resp.errno, resp.errmsg ); std::process::exit(1); } /// 写入到目录中 fn do_write_to_file<T: serde::Serialize>(&self, out_dir: Option<&str>, file: &str, form: &T) { if let Some(o) = out_dir { let file = format!("{}/{}", o, file); let content = serde_json::to_string_pretty(form).unwrap(); std::fs::write(file, content).unwrap(); } } /// 上报 `form` 数据到 `url` fn do_report<T: serde::Serialize>(&self, url: &str, form: &T) -> ReportResp { let builder = self.build_post_request(url, form); Self::send_request::<ReportResp>(builder, url) } /// 测试 app key 在服务器上是否有效 /// app key 无效则直接退出 fn test_app_key_valid(cli: &SharedCli, print_user: bool) { let url = Self::format_url(cli.server_url.as_str(), "ping"); let builder = Self::add_header(Client::new().get(url.as_str()), cli.app_key.as_str()); let msg = Self::send_request::<PingResp>(builder, url.as_str()); if print_user { println!("当前使用的用户是: {}", msg.username); } } /// 发送请求 fn send_request<T: DeserializeOwned>(builder: RequestBuilder, url: &str) -> T { let resp = match builder.send() { Ok(o) => o, Err(e) => { eprintln!("请求 URL {} 失败: {}", url, e.to_string()); std::process::exit(1); } }; if !resp.status().is_success() { eprintln!("请求 URL {} 失败: {:?}", url, resp); std::process::exit(1); } match resp.json() { Ok(resp) => resp, Err(e) => { eprintln!("解析 JSON 失败 失败: {:?}", e); std::process::exit(1); } } } /// 构造 POST 请求 fn build_post_request<F: serde::Serialize>(&self, url: &str, form: &F) -> RequestBuilder { Self::add_header( Client::new() .post(url) .body(serde_json::to_string(form).unwrap()), self.cli.app_key.as_str(), ) } /// 给所有的请求加上 `Authorization` 以及 `Accept` 头信息 #[inline] fn add_header(builder: RequestBuilder, app_key: &str) -> RequestBuilder { builder .header("Authorization", format!("Bearer {}", app_key)) .header("Content-Type", "application/json") .header("Accept", "application/json") } #[inline] fn get_api_url(&self, api_name: &str) -> String { Self::format_url(self.cli.server_url.as_str(), api_name) } /// 获取 要访问的 URL #[inline] fn format_url(server_uri: &str, api_name: &str) -> String { format!("{}{}", server_uri, api_name) } }
C++
UTF-8
617
2.890625
3
[]
no_license
#include<iostream> #include<math.h> using namespace std; int main() { int t, h, a, H, A; cin >> t; while(t--) { while(cin >> h >> a >> H >> A) { int time = ceil(double(H)/a);//我需要几下打死怪兽,向上取整 if(time == 1) { //我先手,一次就ko,那可以无数次 cout << -1 << endl; break; } cout << (h-1)/((time-1)*A) << endl; //我保留1滴生命,然后先手,怪兽少打我一次,一只怪兽打我 (time-1)*A 滴生命 } } return 0; }
Markdown
UTF-8
2,714
2.546875
3
[]
no_license
--- title: Substeps | Getting Started layout: documentation --- Getting Started with Substeps ============================= Prerequisites ------------- Substeps currently requires * JDK 1.8. * Maven 3 (or equivalent dependency management eg SBT or Ivy). * The IntelliJ plugin (optional) depends on 2016 (Community or Ultimate) and also needs to run with Java 8. * The webdriver substeps library has additional dependencies, see [here](../webdriver/introduction) Depending on your background and experience, there are two routes to setting up a Substeps project. The easiest way is to download the example project and perform a few customisations and you'll be up and running. Alternatively you can include the relevant configuration and dependencies by hand. Example project --------------- The Example project can be downloaded from [here](https://github.com/Substeps/substeps-example/releases "Substeps example project releases"). Download and extract the contents into a folder. The example project can be run as is with Maven from the command line by running `mvn clean verify` from the root of the project. You should see Maven run the Substeps suite of 'self tests', with the HTML test report produced in `target/substeps_report/report_frame.html`. The report also includes usage details (for ongoing maintenance of the test pack) and a glossary of step implementations in scope ### Example Report ### A sample test execution report is included [here](../../substeps_report/report_frame.html), this includes a failing test for illustattive purposes. ### Starting development using the example project If the example project is to be used as the starting point for a substeps based project you may wish to modify the following in `pom.xml` ```xml line 1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" .... ... 11 <groupId>org.substeps</groupId> <--- replace with your organisation 12 <artifactId>webdriver-substeps-example</artifactId> <--- a project identifier ... 16 <name>Webdriver Substeps Example</name> <--- project name 17 <description>An example webdriver substeps project</description> <---- project description ... 149 <reportTitle>Example Substeps Report - ${project.version}</reportTitle> <--- the title that appears on the acceptance tests report ... ``` You can now start writing new features and implementing them in substeps! ### Learn more about * [Importing projects into IntelliJ and using the plugin](../intellij-integration/) * [implementing custom step implementations](../customisation/) * documentation and execution reports * integration with CI
Java
UTF-8
1,472
2.671875
3
[]
no_license
import model.Book; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; @WebServlet(name = "DashboardServlet", urlPatterns = "/servletDashboard") public class DashboardServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("DashboardServletPOST"); ArrayList<Book> books = (ArrayList<Book>) request.getServletContext().getAttribute("books"); for (Book book: books) { out.println("<h4>"+book.toString()+"</>"); } out.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("DashboardServletGET"); ArrayList<Book> books = (ArrayList<Book>) request.getServletContext().getAttribute("books"); for (Book book: books) { out.println("<h4>"+book.toString()+"</>"); } out.close(); } }
Python
UTF-8
1,317
2.59375
3
[]
no_license
# -*- coding: utf-8 -*- from libs.graph import Graph from libs.input_output import get_arguments from os import path,makedirs (items, frame, prior, codes, working_directory) = get_arguments(path.dirname(path.realpath(__file__)), True) for item in items: g = Graph(working_directory, frame, users=[int(item)], prior = prior, codes=codes) directory = working_directory+'/graphs/user/'+item+'/' if not path.exists(directory): makedirs(directory) print 'Generating graphs for user',item g.difficulty_response_time(directory=directory) g.lengths_of_sessions(directory=directory) g.number_of_answers_per_session(directory=directory) g.number_of_answers_over_time(directory=directory) g.response_time_start_end(directory=directory) g.weekday_activity(directory=directory) g.hourly_activity(directory=directory) g.separated_success(directory=directory) g.average_success(directory=directory) g.combined_success(directory=directory) g.separated_skill(directory=directory) g.average_skill(directory=directory) g.combined_skill(directory=directory) g.success_over_time(directory=directory) g.current_skill_over_items(directory=directory) g.success_over_items(directory=directory) g.response_time_over_items(directory=directory)
C++
UTF-8
1,266
2.671875
3
[]
no_license
#include "patient.h" #include "airborne.h" #include <gtest/gtest.h> namespace{ class AirborneTest : public :: testing :: Test{ protected: void SetUp(){ bptr = new Airborne(9,45,"likitha","9889568574","baroda",13,1500.0,"cough"); } void TearDown(){ delete bptr; } Airborne *bptr; }; TEST_F(AirborneTest,DefaultConstuctor){ Airborne b1; EXPECT_EQ(0,b1.getId()); EXPECT_EQ(0,b1.getAge()); EXPECT_EQ("",b1.getName()); EXPECT_EQ("",b1.getPhone()); EXPECT_EQ("",b1.getCity()); EXPECT_EQ(0,b1.getSpan()); EXPECT_EQ(1000.0,b1.charge()); EXPECT_EQ("Mumps",b1.getDisease()); } TEST_F(AirborneTest,ParameterizedConstuctor){ Airborne w1(10,55,"yash","9748510365","Srinagar",15,2500.0,"cold"); EXPECT_EQ(10,w1.getId()); EXPECT_EQ(55,w1.getAge()); EXPECT_EQ("yash",w1.getName()); EXPECT_EQ("9748510365",w1.getPhone()); EXPECT_EQ("Srinagar",w1.getCity()); EXPECT_EQ(15,w1.getSpan()); EXPECT_EQ(2500.0,w1.charge()); EXPECT_EQ("cold",w1.getDisease()); } TEST_F(AirborneTest,ComputeCharge){ EXPECT_EQ(19500.0,bptr->medicineCharge()); } }
Python
UTF-8
2,756
2.53125
3
[]
no_license
import os import sys import sqlite3 import boto3 import requests import feedparser from bs4 import BeautifulSoup from requests.auth import HTTPBasicAuth URL = os.environ['FEED_URL'] USERNAME = os.environ['BASIC_AUTH_USERNAME'] PASSWORD = os.environ['BASIC_AUTH_PASSWORD'] FROM = os.environ['FROM_EMAIL_ADDRESS'] TO = os.environ['TO_EMAIL_ADDRESS'] AWS_ACCESS_KEY_ID = os.environ['SES_AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['SES_AWS_SECRET_ACCESS_KEY'] AWS_REGION_NAME = os.environ['SES_AWS_REGION_NAME'] def html_to_text(html): return ' '.join(BeautifulSoup(html, features="html.parser").get_text().split()) class Tracker(): def __init__(self): self.db = sqlite3.connect('./state/seen.db') self.cursor = self.db.cursor() self.cursor.execute('create table if not exists seen (guid text)') self.db.commit() def seen_before(self, guid): self.cursor.execute('select * from seen where guid = ?', [guid]) return len(self.cursor.fetchall()) > 0 def mark_seen(self, guid): self.cursor.execute('insert into seen values(?)', [guid]) self.db.commit() class Emailer(): def __init__(self, aws_access_key_id, aws_secret_access_key, aws_region_name): self.emailer = boto3.client( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=aws_region_name, service_name='ses', use_ssl=True) def send_email(self, from_address, destination, subject, body): self.emailer.send_email( Source=from_address, Destination={ 'ToAddresses': [ destination ] }, Message={ 'Subject': { 'Data': subject }, 'Body': { 'Text': { 'Data': body } } } ) tracker = Tracker() emailer = Emailer(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION_NAME) request = requests.get(URL, auth=HTTPBasicAuth(USERNAME, PASSWORD)) feed = feedparser.parse(request.text) new_entries = [entry for entry in feed.entries if not tracker.seen_before(entry.id)] print('Fetching %s' % URL, file=sys.stderr) print('%s articles found; %s new' % (len(feed.entries), len(new_entries)), file=sys.stderr) for entry in new_entries: emailer.send_email(FROM, TO, html_to_text(entry.title), '%s\n\n%s' % ( entry.link, html_to_text(entry.summary))) tracker.mark_seen(entry.id)
PHP
UTF-8
979
2.84375
3
[]
no_license
<?php /** * <b>Bairro [ MODEL ]</b> * Responsavel por listar, cadastrar e editar os bairros * @copyright (c) 2016, Diego Tesch */ class Bairro { private $id; private $dados; private $error; private $result; /*function __construct($bairro { $this->level = (int) $level; }*/ public function getBairro($id_bairro = null) { $this->id = (!is_null($id_bairro) ? (int) $id_bairro : null); $read = new Read; $read->ExeRead('bairro', (!is_null($this->id) ? "WHERE bairro_id = :b_id" : null), (!is_null($this->id) ? "b_id={$this->id}" : null)); if($read->getResult()){ $this->result = $read->getResult(); }else{ $this->result = false; $this->error = array("Nenhum bairro encontrado!", MSG_INFO); } } function getError() { return $this->error; } function getResult() { return $this->result; } //PRIVATES }
JavaScript
UTF-8
1,245
3.125
3
[]
no_license
var aceSlider = document.getElementById("aceSlider"); var aceValue = document.getElementById("aceValue"); aceSlider.value = 0; aceValue.innerHTML = 1; aceSlider.oninput = function () { (this.value < 25) ? aceValue.innerHTML = "1" : aceValue.innerHTML = "11" } var placeBet = document.getElementById("bPlace"); var betText = document.getElementById("bText"); var betValue = document.getElementById("bValue"); const infoText = () => { return `You have ${player.money} money <br> How much do you want to bet?` }; var warnText = "You can't bet 0 money"; placeBet.value = 50; betValue.innerHTML = placeBet.value; placeBet.max = player.money; betText.innerHTML = infoText(); placeBet.oninput = function () { if (player.money == 0) { betText.innerHTML = "You have no money to bet!"; } (this.value == 0) ? betText.innerHTML = warnText : betText.innerHTML = infoText(); betValue.innerHTML = this.value; } var cutSlider = document.getElementById("cutTheDeck"); var valueSlider = document.getElementById("valueCut"); cutSlider.value = 0; cutSlider.max = deck.cards.length - 15; valueSlider.innerHTML = cutSlider.value; cutSlider.oninput = function () { valueSlider.innerHTML = this.value; }
JavaScript
UTF-8
676
3.75
4
[]
no_license
const Me = { Name: "Ahmed", Age: 14, Parents: ["Anees", "Khyryh"], Brothers: ["Laith", "Ghaith"], Sisters: ["Sewar", "Sara"], FavoriteColor: "black", PhoneNumber: "0780325519" }; console.log(Me); // Put this code in the console typeof Me; Me.Age Me.Name Me.Parents Me.Brothers Me.Sisters Me.PhoneNumber Me.FavoriteColor function Person(name, lastName, age, country) { this.firstName = name; this.lastName = lastName; this.age = age; this.country = country; } const me = new Person("Ahmed", "Alsheyab", 14, "Jordan") Person.prototype.eyecolor = "black" console.log("My eyes color is " + me.eyecolor);
Java
UTF-8
10,068
1.984375
2
[]
no_license
package com.depression.service; import java.math.BigDecimal; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.depression.dao.PersonalityCharactersSimilarityMapper; import com.depression.dao.PersonalityHarmonyDescriptionMapper; import com.depression.dao.PersonalityTestMemberMappingMapper; import com.depression.dao.PersonalityTestResultDescMapper; import com.depression.dao.PersonalityTestShareGroupMapper; import com.depression.dao.PersonalityTestStatisticsMapper; import com.depression.model.PersonalityCharactersSimilarity; import com.depression.model.PersonalityHarmonyDescription; import com.depression.model.PersonalityTestMemberMapping; import com.depression.model.PersonalityTestResultDesc; import com.depression.model.PersonalityTestShareGroup; import com.depression.model.PersonalityTestStatistics; import com.depression.utils.DiscUtil; @Service public class PersonalityTestShareGroupService { private Logger log = Logger.getLogger(PersonalityTestShareGroupService.class); @Autowired PersonalityTestShareGroupMapper groupMapper; @Autowired PersonalityCharactersSimilarityMapper similarityMapper; @Autowired PersonalityTestStatisticsMapper statisticsMapper; @Autowired PersonalityTestResultDescMapper descMapper; @Autowired PersonalityTestMemberMappingMapper mappingMapper; @Autowired PersonalityHarmonyDescriptionMapper harmonyMapper; public int insertSelective(PersonalityTestShareGroup record) { record.setCreateTime(new Date()); record.setModifyTime(new Date()); return groupMapper.insertSelective(record); } public List<PersonalityTestShareGroup> selectSelective(PersonalityTestShareGroup record) { return groupMapper.selectSelective(record); } public PersonalityTestShareGroup selectByPrimaryKey(Long gId) { return groupMapper.selectByPrimaryKey(gId); } public int insertSimilarityAndHarmony(Long idSelf, Long idFriend) { //查询测试记录 PersonalityTestStatistics pp = new PersonalityTestStatistics(); pp.setMid(idSelf); List<PersonalityTestStatistics> ptsList = statisticsMapper.selectSelective(pp); if(ptsList.size()==0) return -1; PersonalityTestStatistics ptsSelf = ptsList.get(0); Integer[] discSelf = { ptsSelf.getdVal(), ptsSelf.getiVal(), ptsSelf.getsVal(), ptsSelf.getcVal()}; pp = new PersonalityTestStatistics(); pp.setMid(idFriend); ptsList = statisticsMapper.selectSelective(pp); if(ptsList.size()==0) return -1; PersonalityTestStatistics ptsFriend = ptsList.get(0); Integer[] discFriend = { ptsFriend.getdVal(), ptsFriend.getiVal(), ptsFriend.getsVal(), ptsFriend.getcVal()}; //插入相似度和合拍度到自己的分享组 { PersonalityTestShareGroup p = new PersonalityTestShareGroup(); p.setMid(idSelf); PersonalityTestShareGroup ptsgSelf = groupMapper.selectSelective(p).get(0); Long gidSelf = ptsgSelf.getgId(); PersonalityCharactersSimilarity ppp = new PersonalityCharactersSimilarity(); ppp.setMid(idFriend); ppp.setgId(gidSelf); List<PersonalityCharactersSimilarity> pcsFriendList = similarityMapper.selectSelective(ppp); if(pcsFriendList.size() > 0) { PersonalityCharactersSimilarity pcs = pcsFriendList.get(0); double similarity = DiscUtil.calcSimilarity(discSelf, discFriend); pcs.setSimilarity(BigDecimal.valueOf(similarity)); //合拍度 String harmony = DiscUtil.analyzeHarmony(discSelf, discFriend); PersonalityHarmonyDescription phd = new PersonalityHarmonyDescription(); phd.setType(harmony); List<PersonalityHarmonyDescription> phds = harmonyMapper.selectSelective(phd); if(phds.size()>0){ pcs.setHarmonyId(phds.get(0).getHarmonyId()); } similarityMapper.updateByPrimaryKeySelective(pcs); log.info("插入相似度和合拍度到自己的分享组成功!"); } } //插入相似度和合拍度到朋友的分享组 { PersonalityTestShareGroup p = new PersonalityTestShareGroup(); p.setMid(idFriend); PersonalityTestShareGroup ptsgFriend = groupMapper.selectSelective(p).get(0); Long gidFriend = ptsgFriend.getgId(); PersonalityCharactersSimilarity ppp = new PersonalityCharactersSimilarity(); ppp.setMid(idSelf); ppp.setgId(gidFriend); List<PersonalityCharactersSimilarity> pcsSelfList = similarityMapper.selectSelective(ppp); if(pcsSelfList.size() > 0) { PersonalityCharactersSimilarity pcs = pcsSelfList.get(0); double similarity = DiscUtil.calcSimilarity(discSelf, discFriend); pcs.setSimilarity(BigDecimal.valueOf(similarity)); //合拍度 String harmony = DiscUtil.analyzeHarmony(discFriend, discSelf); PersonalityHarmonyDescription phd = new PersonalityHarmonyDescription(); phd.setType(harmony); List<PersonalityHarmonyDescription> phds = harmonyMapper.selectSelective(phd); if(phds.size()>0){ pcs.setHarmonyId(phds.get(0).getHarmonyId()); } similarityMapper.updateByPrimaryKeySelective(pcs); log.info("插入相似度和合拍度到朋友的分享组!"); } } return 0; } /** * 计算相似度,更新自己的加入的分享列表,以及自己的分析列表 * @param mid * @param disc * @return */ public int saveSimilarityAndHarmony(Long mid, Integer[] disc) { if(disc.length != 4) return -1; /*--------------------遍历自己加入的分享组----------------------*/ PersonalityCharactersSimilarity p = new PersonalityCharactersSimilarity(); p.setMid(mid); List<PersonalityCharactersSimilarity> pcsSelfList = similarityMapper.selectSelective(p); if (pcsSelfList != null) { for(PersonalityCharactersSimilarity pcs : pcsSelfList) { PersonalityTestShareGroup ptsg = groupMapper.selectByPrimaryKey(pcs.getgId()); PersonalityTestStatistics pp = new PersonalityTestStatistics(); pp.setMid(ptsg.getMid()); List<PersonalityTestStatistics> ptsList = statisticsMapper.selectSelective(pp); if(ptsList.size()==0) continue; //group disc值 Integer[] discG = { ptsList.get(0).getdVal(), ptsList.get(0).getiVal(), ptsList.get(0).getsVal(), ptsList.get(0).getcVal()}; double similarity = DiscUtil.calcSimilarity(discG, disc); pcs.setSimilarity(BigDecimal.valueOf(similarity)); //合拍度 String harmony = DiscUtil.analyzeHarmony(discG, disc); PersonalityHarmonyDescription phd = new PersonalityHarmonyDescription(); phd.setType(harmony); List<PersonalityHarmonyDescription> phds = harmonyMapper.selectSelective(phd); if(phds.size()>0){ pcs.setHarmonyId(phds.get(0).getHarmonyId()); } similarityMapper.updateByPrimaryKeySelective(pcs); } } /*--------------------遍历自己的分享组----------------------*/ PersonalityTestShareGroup ppp = new PersonalityTestShareGroup(); ppp.setMid(mid); PersonalityTestShareGroup ptsgSelf = groupMapper.selectSelective(ppp).get(0); PersonalityCharactersSimilarity pppp = new PersonalityCharactersSimilarity(); pppp.setgId(ptsgSelf.getgId()); List<PersonalityCharactersSimilarity> pcsFriendList = similarityMapper.selectSelective(pppp); if (pcsFriendList != null) { for(PersonalityCharactersSimilarity pcs : pcsFriendList) { PersonalityTestStatistics pp = new PersonalityTestStatistics(); pp.setMid(pcs.getMid()); List<PersonalityTestStatistics> ptsList = statisticsMapper.selectSelective(pp); if(ptsList.size()==0) continue; Integer[] discF = { ptsList.get(0).getdVal(), ptsList.get(0).getiVal(), ptsList.get(0).getsVal(), ptsList.get(0).getcVal()}; double similarity = DiscUtil.calcSimilarity(discF, disc); pcs.setSimilarity(BigDecimal.valueOf(similarity)); //合拍度 String harmony = DiscUtil.analyzeHarmony(disc, discF); PersonalityHarmonyDescription phd = new PersonalityHarmonyDescription(); phd.setType(harmony); List<PersonalityHarmonyDescription> phds = harmonyMapper.selectSelective(phd); if(phds.size()>0){ pcs.setHarmonyId(phds.get(0).getHarmonyId()); } similarityMapper.updateByPrimaryKeySelective(pcs); } } return 0; } /** * 分析特征,并保存数值结果 * @param mid * @param disc * @return */ public int saveCharacterAndDisc(Long mid, Integer[] disc) { if(disc.length != 4) return -1; String character = DiscUtil.analyzeCharacter(disc); PersonalityTestResultDesc p = new PersonalityTestResultDesc(); p.setType(character); List<PersonalityTestResultDesc> ptrdList = descMapper.selectSelective(p); if(ptrdList.size() > 0){ //保存特征结果 PersonalityTestMemberMapping ptmm = new PersonalityTestMemberMapping(); ptmm.setMid(mid); ptmm.setPtrdId(ptrdList.get(0).getPtrdId()); List<PersonalityTestMemberMapping> ptmmList = mappingMapper.selectSelective(ptmm); if(ptmmList.size()==0){ ptmm.setCreateTime(new Date()); mappingMapper.insertSelective(ptmm); }else{ ptmm.setPtrdId(ptmmList.get(0).getPtrdId()); ptmm.setModifyTime(new Date()); } } //保存测试结果数值 PersonalityTestStatistics pp = new PersonalityTestStatistics(); pp.setMid(mid); List<PersonalityTestStatistics> ptsList = statisticsMapper.selectSelective(pp); if(ptsList.size()==0){ //新建 PersonalityTestStatistics pts = new PersonalityTestStatistics(); pts.setMid(mid); pts.setdVal(disc[0]); pts.setiVal(disc[1]); pts.setsVal(disc[2]); pts.setcVal(disc[3]); pts.setCreateTime(new Date()); statisticsMapper.insertSelective(pts); }else{ PersonalityTestStatistics pts = new PersonalityTestStatistics(); pts.setPtsId(ptsList.get(0).getPtsId()); pts.setdVal(disc[0]); pts.setiVal(disc[1]); pts.setsVal(disc[2]); pts.setcVal(disc[3]); pts.setModifyTime(new Date()); statisticsMapper.updateByPrimaryKeySelective(pts); } return 0; } }
Java
UTF-8
4,187
2.546875
3
[]
no_license
package com.myretail.controller; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.myretail.exception.MyRetailException; import com.myretail.products.ProductDetails; import com.myretail.service.ProductService; import com.myretail.util.JSONMerge; import com.myretail.util.RestTemplateUTIL; import io.swagger.annotations.ApiOperation; /** * Service controller for fetching the details about the product. Consolidates * call to Product Name API and the Product price API * * @author Sudhakar * */ @RestController public class ProductDetailsController { static Logger logger = LoggerFactory.getLogger(ProductDetailsController.class); private static final String APP_HOME = "My Retail Application to manage Product and prices"; @Value("${url.product.price}") private String productPriceURL; @Value("${url.product.desc}") private String productDescURL; @Autowired private ProductService service; @Autowired private ApplicationContext appContext; @Autowired RestTemplateUTIL restUtil; public ApplicationContext getAppContext() { return appContext; } public void setAppContext(ApplicationContext appContext) { this.appContext = appContext; } @RequestMapping("/") public String index() { return APP_HOME; } /** * Service to fetch the product details * * @param productID * The product ID to be fetched * @return * @throws ExecutionException * @throws InterruptedException * @throws IOException * @throws JsonProcessingException */ @ApiOperation(value = "/product/{productID}", nickname = "/product",notes = "Simple fetch for product") @RequestMapping(value = "/product/{productID}", produces = "application/JSON", method = RequestMethod.GET) public JsonNode getProductDetail(@PathVariable(value = "productID") long productID) throws IOException { logger.info("Fetch product detail..." + productID); // Call the rest services in sequence. This is done using async using // Future Future<JsonNode> node = service.fetchProductPrice(productID); Future<JsonNode> nodeName = service.fetchProductName(productID); JsonNode nodenew = null; try { // Wait for both calls to finish. Time out / max wait time can be set while (!(node.isDone() && nodeName.isDone())) { Thread.sleep(10); } // Combine the JSON nodes. // Assumes the product name node details are merged to price nodenew = JSONMerge.merge(node.get(), nodeName.get()); } catch (InterruptedException | ExecutionException e) { logger.error("Error in getting product price with name" + e.getMessage(), e); } logger.info(node.toString()); return nodenew; } /** * Service to update the product if it exists, else a new record is inserted * * @param productID * The product to be updated * @param productb * The request body containing the details * @return * @throws MyRetailException */ @RequestMapping(value = "/product/{productID}", produces = "application/text", method = RequestMethod.PUT) public String updateProduct(@PathVariable(value = "productID") long productID, @RequestBody ProductDetails productb) throws MyRetailException { logger.info("Update product..." + productID); // Setup the resource to be found productb.setProductID(productID); boolean updated = service.updateProduct(productID, productb); logger.info("Completed PUT request "+updated); return "{updated(PUT): " + productb.toString() + "}"; } }
JavaScript
UTF-8
2,460
2.765625
3
[ "MIT" ]
permissive
var args = require('minimist')(process.argv.slice(2)); var cheerio = require('cheerio'); var request = require('request'); var fs = require('fs'); var request = require('request'); var mkdirp = require('mkdirp'); var progressbar = require('progress'); var folder = args.folder || 'dloaded_images/'; var url = args.url; var shouldDownload = function(images){ if(!images.length) return false; return true; }; var prepareImages = function(arr){ return arr.map(function(current){ var url = current; var urlParamSplit = current.split('?'); var format = 'jpg' var arrUrl = urlParamSplit[0].split('/'); var filename = arrUrl[arrUrl.length-2].toLowerCase() + "." + format; var imgFolder = folder; filename = new Date().getTime() + "-" + filename; // so we dont get any duplicates return { url: url, folder: imgFolder, filename: imgFolder + filename }; }); }; var downloadImage = function(image, callback){ //console.log('Downloading image: ' + image.url); mkdirp(image.folder, function(){ request.head(image.url, function(err, res, body){ request(image.url).pipe(fs.createWriteStream(image.filename).on('close', callback)); }); }); }; var downloadPage = function(){ if (!url) { console.log('Please specify a URL with the --url flag'); process.exit(); } console.log('Downloading from: ' + url); request({ uri: url }, function(error, response, body) { var $ = cheerio.load(body); var images = prepareImages($("a[title$='Download photo']").map(function(){ return $(this).attr('href'); }).get()); var done = 0; var total = images.length; console.log('Found ' + total + ' images'); var bar = new progressbar('Downloading [:bar] :percent', { total: total }); var download = function(){ if(done >= total){ bar.terminate(); }else{ downloadImage(images[done++], function(){ bar.tick(); download(); }); } }; if(shouldDownload(images)){ download(); }else{ console.log('Aborting ...'); process.exit(); } }); }; downloadPage();
Java
UTF-8
584
3.375
3
[ "MIT" ]
permissive
import java.util.Scanner; public class Votacao{ public static void main(String[] args){ Scanner teclado = new Scanner(System.in); System.out.print("Digite o ano que você nasceu: "); int nasc = teclado.nextInt(); int idade = 2020 - nasc; if(idade < 16){ System.out.println("Você não vota!"); } else if((idade >= 16 && idade < 18) || (idade > 70)){ System.out.println("Seu voto é facultativo!"); } else{ System.out.println("Seu voto é obrigatório!"); } } }
PHP
UTF-8
1,461
2.5625
3
[]
no_license
<?php use App\Core\Datastore\IdentityMap; class Food extends App\Core\Datastore\Model { } class IdentityMapTest extends TestCase { public function setUp() { $this->map = new IdentityMap(); } public function testHas() { $this->assertFalse($this->map->has('food', 'chicken-bbq')); } public function testManage() { $chicken_bbq = new Food(); $chicken_bbq->id = 'chicken-bbq'; $chicken_bbq->name = 'Chicken Barbeque'; $this->map->manage($chicken_bbq); $their_chicken_bbq = $this->map->get('food', 'chicken-bbq'); $this->assertTrue($this->map->has('food', 'chicken-bbq')); $this->assertSame($chicken_bbq, $their_chicken_bbq); } public function testForget() { $belly = new Food(); $belly->id = 190; $belly->name = 'Grilled Pork Belly'; $this->assertFalse($this->map->has('food', 190)); $this->map->manage($belly); $this->assertTrue($this->map->has('food', 190)); $this->map->forget($belly); $this->assertFalse($this->map->has('food', 190)); } public function testUpdateKey() { $sugba = new Food(); $sugba->name = 'Sinugbang Bangus'; $this->map->manage($sugba); $this->assertFalse($this->map->has('food', 5881)); $sugba->id = 5881; $this->map->updateKey($sugba); $this->assertTrue($this->map->has('food', 5881)); } }
Markdown
UTF-8
6,912
2.65625
3
[]
no_license
--- layout: default title: A New Recipe for Israeli Heroism tags: [Ideas and Innovation,heroes,PT11] created: 1278252004 changed: 1278420763 --- <p><a title="falafelman2 by PresenTense Group, on Flickr" href="http://www.flickr.com/photos/presentensegroup/4730448499/"><img width="354" height="500" align="right" alt="falafelman2" src="http://farm2.static.flickr.com/1316/4730448499_14f3ef15bb.jpg" /></a></p> <p><strong>Name:&nbsp;</strong>Falafel Man</p> <p><strong>Home:&nbsp;</strong>Israel</p> <p><strong>Profession:&nbsp;</strong>Protecting the State</p> <p><strong>He&rsquo;s a hero because:&nbsp;</strong>He&rsquo;s inventive, compassionate,&nbsp;and prepared to make sacrifices in&nbsp;order for justice to prevail.</p> <p>&nbsp;</p> <p>My Israeli hero has red hair and a&nbsp;friendly, smiling face. He&rsquo;s a chubby&nbsp;fellow who shoots falafel balls and&nbsp;protects the State. As a comic book artist, I&nbsp;created this hero in response to trends in Israeli&nbsp;society today&mdash;and in doing so, I realized&nbsp;that I had a winning recipe on my hands.</p> <p>Superheroes like Superman, Spiderman,&nbsp;the Flash, and WonderWoman have physical&nbsp;powers beyond the ordinary: Some of them&nbsp;can lift a car with one hand, some run as fast&nbsp;as the wind, and others can fly. Superheroes&nbsp;are usually human, but possess almost divine&nbsp;powers. Not to mention that the best ones are&nbsp;beautiful, moral people who fight for justice.&nbsp;These are, for most of us who grew up with&nbsp;comics, the heroes.</p> <p>Israeli culture, on the other hand, values&nbsp;heroes who do not have any special powers.&nbsp;They are mere mortals, only with striking&nbsp;character traits such as pioneership, initiative,&nbsp;vision, and decisive intelligence employed for&nbsp;the protection of Israel. This may stem from&nbsp;the fact that, in Jewish culture, &lsquo;divine&rsquo; attributes&nbsp;are forbidden to humans, belonging&nbsp;only to God.</p> <p>One of the first comics debuted in Israel&nbsp;in 1936, when the newspaper Davar for Kids&nbsp;printed a running weekly comic strip featuring&nbsp;main character Uri Muri. This child dressed in&nbsp;a hat and accompanied by a camel was the first&nbsp;Hebrew comic hero. Likewise, all the characters&nbsp;developed after this were of Hebrew children,&nbsp;halutzim (pioneers) who were drafted on&nbsp;behalf of the Yishuv (pre-State settlement) to&nbsp;establish the State of Israel. Later on, in the&nbsp;&lsquo;50s and &lsquo;60s, more mature characters appeared,&nbsp;like secret agents and soldiers fighting&nbsp;for the homeland.&nbsp;</p> <p>Most of the wars that the State of Israel&nbsp;has experienced have elevated the status of the&nbsp;Israeli soldier. Especially after Israel&rsquo;s victory in&nbsp;the 1967 War, the Israeli soldier emerged as&nbsp;the Israeli hero, respected in every home and&nbsp;the most popular costume for Purim.&nbsp;However, in the 1973 Yom Kippur War,&nbsp;the State of Israel had to absorb heavy casualties,&nbsp;and the myth of the strong Israeli soldier&nbsp;was weakened. From that moment until today,&nbsp;attempting to crystallize the character of the&nbsp;Israeli hero has been an ongoing effort at a&nbsp;time when the definitions of Zionism and pioneership&mdash;&nbsp;even the meaning of being &lsquo;Israeli&rsquo;&mdash;are changing.</p> <p>As Israel develops, there is a growing&nbsp;awareness of the global perception of the &lsquo;Israeli&nbsp;hero&rsquo;. In many countries, when watching&nbsp;the news and listening to opinions on Israel,&nbsp;the focus is mainly on the Israeli-Palestinian&nbsp;conflict. Most pictures are of Israeli tanks&nbsp;and rifles. The new technological inventions,&nbsp;the many Israelis who won Nobel prizes, the&nbsp;creative literature that has won international&nbsp;awards, the remarkable music, the cinema, the&nbsp;contributions to medicine and science&mdash;all&nbsp;this is shoved aside. In the ongoing preoccupation&nbsp;with the conflict, people around the&nbsp;world see the stereotyped Israeli with black&nbsp;stubble on his face, cigarette in the corner of&nbsp;his mouth, dark eyes hidden under a helmet,&nbsp;with a tough facial expression, green uniform,&nbsp;rifle&mdash;and of course, he is bloodthirsty.&nbsp;</p> <p><a title="falafelman1 by PresenTense Group, on Flickr" href="http://www.flickr.com/photos/presentensegroup/4730448255/"><img width="354" height="500" align="left" alt="falafelman1" src="http://farm2.static.flickr.com/1118/4730448255_e29200d460.jpg" /></a></p> <p>Understanding the magnitude of responsibility&nbsp;involved in creating a contemporary&nbsp;Israeli hero, I invented my own Israeli hero,&nbsp;found in my comics. I wanted to smash all&nbsp;the existing myths evolving Israeliness. As opposed&nbsp;to the muscular and well-built heroes,&nbsp;I drew a chubby hero with a big potbelly.&nbsp;My hero has red hair, freckles, and big blue&nbsp;eyes. He has a big smile that reveals his white&nbsp;teeth. Such a person is not intimidating; on&nbsp;the contrary, he invokes the desire to hug or&nbsp;pinch him in the cheek like any good Jewish&nbsp;grandmother might do. I did not want his expression&nbsp;to even vaguely resemble that of the&nbsp;stubborn soldier.</p> <p>Regarding his superpowers, if he had&nbsp;known how to fly, he would definitely have&nbsp;said, &ldquo;Nu, what&rsquo;s new about that? We already&nbsp;have Superman.&rdquo; And it would not be believable&nbsp;if he could run really fast, because he is&nbsp;fat, and we all know that the heart and lung&nbsp;capacity of the obese is restricted. He is certainly&nbsp;not capable of killing, not even by accident.</p> <p>I decided that my hero is capable of&nbsp;shooting falafel balls with hot oil each time he&nbsp;waves his hand and aims at a target. Falafel was&nbsp;my weapon of choice because a boiling falafel&nbsp;ball can at the most burn the skin, nothing&nbsp;more. Plus, falafel stands abound in Israel, and&nbsp;it is most certainly my favorite food.</p> <p>You are probably asking yourself: How&nbsp;can such a hero win over monsters, terrifying&nbsp;robots made of metal, strange kinds of&nbsp;machines, and other villains? The answer: His&nbsp;compassionate heart, his desire to help, and his&nbsp;mind enable him to defeat his enemies because&nbsp;he uses ruses, is inventive, and is prepared to&nbsp;make sacrifices in order for justice to prevail.&nbsp;He is a figure of values and morals&mdash;and for&nbsp;me, this is the makings of a true superhero. PT</p> <p><em>Dorit Maya Gur is an Israeli comic&nbsp;book artist and illustrator who&nbsp;holds a degree in industrial design&nbsp;and education. She is the creator of the&nbsp;Jewish superhero Falafel Man. Among her&nbsp;clients are Nike Israel, high-tech companies,&nbsp;newspapers, and commercial companies,&nbsp;and she loves her job.</em></p> <p>&nbsp;&nbsp;</p>
Java
UTF-8
5,398
2.328125
2
[]
no_license
package edu.upenn.cis350; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.Toast; public class DocSubcategoryActivity extends Activity{ private CheckBox doc_immunology; private CheckBox doc_radiology; private CheckBox doc_cardiology; private CheckBox doc_pediatric; private CheckBox doc_dental; private CheckBox doc_internalMedicine, doc_familyPractice, doc_obGyn, doc_mentalHealth, doc_otherSpecialist; private Button doc_submit; private int countCheck = 0; int[] checkBoxRecord = new int[20]; String[] docTypeList = new String[20]; private final Context m_context = this; /** * Set up the view upon creation */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.subcategory_doctor); } /** * Set up the activity when the main screen is brought up */ public void onResume(){ super.onResume(); doc_immunology = (CheckBox)this.findViewById(R.id.doc_immunology); doc_radiology = (CheckBox)this.findViewById(R.id.doc_radiology); doc_cardiology = (CheckBox)this.findViewById(R.id.doc_cardiology); doc_pediatric=(CheckBox)this.findViewById(R.id.doc_pediatric); doc_dental=(CheckBox)this.findViewById(R.id.doc_dental); doc_internalMedicine = (CheckBox)this.findViewById(R.id.doc_internal_medicine); doc_familyPractice = (CheckBox)this.findViewById(R.id.doc_family_practice); doc_obGyn = (CheckBox)this.findViewById(R.id.doc_ob_gyn); doc_mentalHealth = (CheckBox)this.findViewById(R.id.doc_mental_health); doc_otherSpecialist = (CheckBox)this.findViewById(R.id.doc_other_specialist); doc_submit=(Button)this.findViewById(R.id.doc_submit); docTypeList[0] = "immunology"; docTypeList[1] = "radiology"; docTypeList[2] = "cardiology"; docTypeList[3] = "pediatric"; docTypeList[4] = "dental"; docTypeList[5] = "internalMedicine"; docTypeList[6] = "familyPractice"; docTypeList[7] = "obGyn"; docTypeList[8] = "mentalHealth"; docTypeList[9] = "otherSpecialist"; doc_immunology.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_immunology,1); } }); doc_radiology.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_radiology,2); } }); doc_cardiology.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_cardiology,3); } }); doc_pediatric.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_pediatric,4); } }); doc_dental.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_dental,5); } }); doc_internalMedicine.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_internalMedicine,6); } }); doc_familyPractice.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_familyPractice,7); } }); doc_obGyn.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_obGyn,8); } }); doc_mentalHealth.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_mentalHealth,9); } }); doc_otherSpecialist.setOnClickListener(new OnClickListener() { public void onClick(View v) { onCheckboxClicked(doc_otherSpecialist,10); } }); //set the listeners for each button setListeners(); } private void setListeners() { // TODO Auto-generated method stub doc_submit.setOnClickListener(new OnClickListener(){ public void onClick(View v) { // TODO Auto-generated method stub if(countCheck <= 0) Toast.makeText(m_context, "Please at least check one of the specialties!", Toast.LENGTH_LONG).show(); else{ ArrayList<String> typeList = new ArrayList<String>(); for(int i = 0; i < checkBoxRecord.length; i++) { if(checkBoxRecord[i] != 0) typeList.add(docTypeList[i]); } Intent intent = new Intent(m_context, SearchActivity.class); intent.putStringArrayListExtra("typeList", typeList); // TODO check which check box is checked by checking the checkBoxRecord, then send corresponding intents startActivityForResult(intent, 0); } } }); } public void onCheckboxClicked(View view, int index) { // Is the view now checked? boolean checked = ((CheckBox) view).isChecked(); if (checked) { ((CheckBox) view).setChecked(true); checkBoxRecord[index-1]=checked?1:0; countCheck++; } else{ checkBoxRecord[index-1] = 0; countCheck--; } // Check which checkbox was clicked // switch(view.getId()) { // case R.id.pros_checkbox1: // // if (checked) countCheck++; // break; // case R.id.pros_checkbox2: // // if (checked) countCheck++; // break; // // TODO: Veggie sandwich // } } }
Python
UTF-8
1,254
2.5625
3
[ "Apache-2.0" ]
permissive
import sys try: from StringIO import StringIO except ImportError: from io import StringIO def start_stdout_capture(): restore = sys.stdout sys.stdout = StringIO() return restore def end_stdout_capture(restore): output = sys.stdout.getvalue() sys.stdout.close() sys.stdout = restore return output def start_stderr_capture(): restore = sys.stderr sys.stderr = StringIO() return restore def end_stderr_capture(restore): output = sys.stderr.getvalue() sys.stderr.close() sys.stderr = restore return output class OutputRemap(object): def __init__(self, target, handler, tty = True): self.target = target self.handler = handler self.tty = tty def write(self, message): return self.handler(message) def isatty(self): return self.tty def __getattr__(self, attr): if (self.target): return getattr(self.target, attr) else: return 0 def close(self): return None def flush(self): return None def remap_output_streams(r_stdout, r_stderr, tty, force): if (force or sys.stdout is None): sys.stdout = OutputRemap(sys.stdout, r_stdout, tty) if (force or sys.stderr is None): sys.stderr = OutputRemap(sys.stderr, r_stderr, tty)
Java
UTF-8
1,447
2.1875
2
[]
no_license
package springapp.web.legal; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * General purpose class for display-only URLs * * @author judd * */ @Controller public class LegalController { private Logger logger = Logger.getLogger(getClass()); protected static final String agreementMembersView = "legal/AgreementMembers"; protected static final String agreementFunnelView = "legal/AgreementFunnel"; protected static final String agreementMexicanFunnelView = "legal/MexicanAgreementFunnel"; protected static final String privacyPolicyView = "legal/PrivacyPolicy"; protected static final String disclaimerView = "legal/Disclaimer"; protected static final String errorView = "Error"; @RequestMapping("/legal/showAgreement.do") public String showAgreement( @RequestParam(value="version") String version ) { if (version.equals("members")) { return agreementMembersView; } else if (version.equals("funnel")) { return agreementFunnelView; } else if (version.equals("mexicanfunnel")) { return agreementMexicanFunnelView; } else if (version.equals("privacy")) { return privacyPolicyView; } else if (version.equals("disclaimer")) { return disclaimerView; } else { return errorView; } } }
Java
UTF-8
212
2.625
3
[]
no_license
public class AirplaneSeatAssignment { public static double solve(int n) { if(n==1) { return 1.0; } return 0.5; } public static void main(String[] args) { System.out.println(solve(2)); } }
Swift
UTF-8
2,927
3.90625
4
[]
no_license
import Foundation class VendingMachineProduct { var name: String var amount: Int var price: Double init(name: String, amount: Int, price: Double) { self.name = name self.amount = amount self.price = price } } //TODO: Definir os erros enum VendingMachineError: Error { case productNotFound case productUnavailable case insufficientMoney case productStuck case noChange } extension VendingMachineError: LocalizedError { var errorDescription: String? { switch self { case .productNotFound: return "O produto escolhido não é vendido nessa máquina" case .productUnavailable: return "O produto escolhido acabou" case .productStuck: return "O produto ficou preso" case .insufficientMoney: return "A quantia inserida não condiz com o preço do produto" case .noChange: return "Desculpe, não temos troco" } } } class VendingMachine { private var estoque: [VendingMachineProduct] private var money: Double private var amountOfChange: Double init(products: [VendingMachineProduct]) { self.estoque = products self.money = 0 self.amountOfChange = 100 } func getProduct(named name: String, with money: Double) throws { //TODO: receber o dinheiro e salvar em uma variável self.money += money //TODO: achar o produto que o cliente quer let produtoOptional = estoque.first { (produto) -> Bool in return produto.name == name } guard let produto = produtoOptional else { throw VendingMachineError.productNotFound } //TODO: ver se ainda tem esse produto guard produto.amount > 0 else { throw VendingMachineError.productUnavailable } //TODO: ver se o dinheiro é o suficiente pro produto guard produto.price <= self.money else { throw VendingMachineError.insufficientMoney } //TODO: entregar o produto self.money -= produto.price produto.amount -= 1 if Int.random(in: 0...100) < 10 { throw VendingMachineError.productStuck } } func getTroco() throws -> Double { //TODO: devolver o dinheiro que não foi gasto let money = self.money guard money <= amountOfChange else { throw VendingMachineError.noChange } self.amountOfChange -= money self.money = 0.0 return money } } let vendingMachines = VendingMachine(products: [ VendingMachineProduct(name: "Doritos", amount: 5, price: 8.5), VendingMachineProduct(name: "Toddynho", amount: 10, price: 2.5), VendingMachineProduct(name: "Água", amount: 3, price: 1.5) ]) do { try vendingMachines.getProduct(named: "Doritos", with: 200) try vendingMachines.getTroco() } catch { print(error.localizedDescription) }
Python
UTF-8
343
4.25
4
[]
no_license
#Project Euler - 20 #Keith Petro - 2016/10/20 #Problem Name: Factorial digit sum #Description: Find the sum of the digits in the number 100! def factorial(n): factorial = 1 for i in range(1, n + 1): factorial *= i return factorial def get_sum_of_digits(num): return sum([int(i) for i in str(num)]) print(get_sum_of_digits(factorial(100)))
PHP
UTF-8
3,126
3.140625
3
[ "MIT" ]
permissive
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>SQL Injection - Parameterized queries</title> </head> <body style="font-family: sans-serif;"> <?php function getDatabaseConnection() { $servername = "localhost"; $username = "janani"; $password = "password"; $dbName = "booDB"; $conn = new mysqli($servername, $username, $password, $dbName); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Comment out if the table does not exist. $drop_query = "DROP TABLE BankAccounts"; if ($conn->query($drop_query) !== TRUE) { echo "Error dropping table: " . $conn->error; } $create_query = <<<_CREATE_ CREATE TABLE IF NOT EXISTS BankAccounts ( account_id INT(10) NOT NULL PRIMARY KEY AUTO_INCREMENT, user_name VARCHAR(100) NOT NULL, account_balance INT(100) NOT NULL ) _CREATE_; $result = $conn->query($create_query); if($result === FALSE) { die("Create failed: " . mysql_error()); } $insert_queries = array(); $insert_queries[] = <<<_INSERT_ INSERT INTO BankAccounts VALUES (1234, 'Janani', 12345) _INSERT_; $insert_queries[] = <<<_INSERT_ INSERT INTO BankAccounts VALUES (1111, 'Pradeep', 100953) _INSERT_; $insert_queries[] = <<<_INSERT_ INSERT INTO BankAccounts VALUES (2222, 'Vitthal', 997) _INSERT_; foreach ($insert_queries as $query) { if ($conn->query($query)) { //echo "Inserted row: $query\n"; } else { echo "Error inserting row: " . mysqli_error($conn) . "\n"; } } return $conn; } mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $account_id = $_GET['account_id']; if (!empty($account_id)) { try { $conn = getDatabaseConnection(); $stmt = $conn->prepare("SELECT * FROM BankAccounts WHERE account_id = ?"); $stmt->bind_param("i", $account_id); $stmt->execute(); $stmt->bind_result($account_id, $user_name, $account_balance); echo '<br><br><table>'; echo '<td style="width: 100px; height: 22px">' . "<b>Account id</b>" . '</td>'; echo '<td style="width: 150px; height: 22px">' . "<b>User</b>" . '</td>'; echo '<td style="width: 100px; height: 22px">' . "<b>Balance</b>" . '</td>'; while($stmt->fetch()) { echo '<tr>'; echo '<td style="width: 100px; height: 18px">' . $account_id . '</td>'; echo '<td style="width: 150px; height: 18px">' . $user_name . '</td>'; echo '<td style="width: 100px; height: 18px">' . $account_balance . '</td>'; echo '</tr>'; } echo '</table>'; $conn->close(); } catch (Exception $e) { echo 'Error! ' + $e->getCode(); } } ?> <h3> Account information page at your trusted bank</h3> <form method="GET" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> <br> <input type="text" name="account_id" value="1234" readonly> <br> <input type="submit" value="Account details"> </form> <br> </body> </html>
C
UTF-8
1,326
3.421875
3
[]
no_license
#include "header.h" //include header sl *delaftnum(sl *head) //delete at particular position function { int number; //position where th node is deleted char *str = NULL; //pointer to take input position int i = 0; //temporary variable to count number of nodes sl *temp = NULL; //temporary pointer to access list int count = 0; //temporary count variable to count position temp = (sl *)malloc(sizeof(sl)*MAX); //dynamic memory allocation str = (char *)malloc(sizeof(char)*MAX); //dynamic memory allocation temp = head; //geeting head value to temp printf ("enter the number\n"); //asking to give input position fgets(str,MAX,stdin); //taking input as the string number = atoi(str); //conversion to integer from string while (temp != NULL ){ //traversing through the list count ++; if (temp -> data == number){ i = 1; break; } temp = temp -> next; } temp = head; if ( i == 0) //checking whether the position is available or not printf("the element is not there to delete\n"); else if ( count == 1 ) //if the position is first head = temp -> next; else //for remaining positions temp = head; // count = count-1; while ((--count) > 0 ) temp = temp -> next; temp -> next = (temp -> next) -> next; return head; //return head to the called function }
PHP
UTF-8
420
4.0625
4
[]
no_license
<?php //Дан массив с элементами 2, 5, 9, 15, 0, 4. С помощью цикла foreach и оператора if //выведите на экран столбец тех элементов массива, которые больше 3­х, но меньше 10.</p> $arr = array(2, 5, 9, 15, 0, 4); foreach($arr as $key) { if ($key >3 && $key <10) echo $key. "<br>"; }
Markdown
UTF-8
727
3.015625
3
[ "MIT" ]
permissive
# Spawner Component ## Purpose Makes the prefab, selected in the Inspector, spawn at the location of the GameObject that has the Spawner component. ## Inspector Values | Setting | Purpose | |---------|----------------------------------| |Character Prefab To Spawn | A slot that takes a game object to use as a template or Prefab instance in the project assets | ## Methods | Method | Description | |---------|----------------------------------| | `void TriggerSpawn()` | Causes the prefab to be instantiated. | | `GameObject SpawnCharacter()` | Makes the instance and returns it to the caller. | ### Copyright (c) Copyright 2017 Warwick Molloy, may be used under MIT License terms.
JavaScript
UTF-8
1,665
2.75
3
[ "MIT" ]
permissive
'use strict'; module.exports = (it, expect, form) => { it('should be able to extend the base form prototype using a "macro"', () => { expect(typeof form({ email: 'e@g.com' }).example_local_macro_method === 'undefined').to.eql(true); form().macro('example_local_macro_method', function () { return 'hello world'; }); expect(typeof form({ email: 'e@g.com'}).example_local_macro_method === 'undefined').to.eql(false); expect(form().example_local_macro_method()).to.eql('hello world'); }); it('should not be able to forcibly overwrite a base form prototype function using a "macro"', () => { expect(form({ name: 'sam' }).all()).to.eql({ name: 'sam' }); form().macro('all', function () { return 'hello world'; }); expect(form({ name: 'sam' }).all()).to.eql({ name: 'sam' }); }); it('should not apply localMacro everywhere', () => { form().localMacro('everywhere', () => 'world'); let one = form({ first: 'test' }); let two = form({ second: 'test' }); expect(typeof one.everywhere === 'undefined').to.eql(true); expect(typeof two.everywhere === 'undefined').to.eql(true); one.localMacro('everywhere', () => 'world'); expect(one.everywhere()).to.eql('world'); expect(typeof two.everywhere === 'undefined').to.eql(true); }); it('should allow macros to be applied on a specific instance instead of everywhere', () => { let does_have = form({ first: 'first' }); let does_not_have = form({ second: 'test' }); does_have.localMacro('localized', () => 'success'); expect(typeof does_have.localized === 'undefined').to.eql(false); expect(typeof does_not_have.localized === 'undefined').to.eql(true); }); };
Java
UTF-8
35,142
2.171875
2
[]
no_license
package l2open.gameserver.model; import l2open.common.ThreadPoolManager; import l2open.config.ConfigValue; import l2open.gameserver.cache.Msg; import l2open.gameserver.instancemanager.PartyRoomManager; import l2open.gameserver.model.L2ObjectTasks.SoulConsumeTask; import l2open.gameserver.model.base.Experience; import l2open.gameserver.model.entity.DimensionalRift; import l2open.gameserver.model.entity.DragonValley; import l2open.gameserver.model.entity.EventMaster; import l2open.gameserver.model.entity.SevenSignsFestival.DarknessFestival; import l2open.gameserver.model.entity.olympiad.Olympiad; import l2open.gameserver.model.instances.L2MonsterInstance; import l2open.gameserver.model.instances.L2NpcInstance; import l2open.gameserver.model.items.L2ItemInstance; import l2open.gameserver.serverpackets.*; import l2open.gameserver.skills.Stats; import l2open.gameserver.tables.ReflectionTable; import l2open.gameserver.xml.ItemTemplates; import l2open.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.lang.ref.WeakReference; import java.util.*; import java.util.concurrent.ScheduledFuture; public class L2Party { private final List<L2Player> _members = new CopyOnWriteArrayList<L2Player>(); private int _partyLvl = 0; private int _itemDistribution = 0; private int _itemOrder = 0; private int _dr; private int _reflection; private L2CommandChannel _commandChannel; public static final int ITEM_LOOTER = 0; public static final int ITEM_RANDOM = 1; public static final int ITEM_RANDOM_SPOIL = 2; public static final int ITEM_ORDER = 3; public static final int ITEM_ORDER_SPOIL = 4; public float _rateExp; public float _rateSp; public float _rateDrop; public float _rateAdena; public float _rateSpoil; private final UpdatePositionTask posTask = new UpdatePositionTask(this); private ScheduledFuture<?> posTaskThread; private int newLootDistr; private boolean votingChangeLoot; private GCSArray<L2Player> lootResponsers = new GCSArray<L2Player>(); private static final int[] LOOT_SYSSTRINGS = {487, 488, 798, 799, 800}; private ScheduledFuture<?> voteTask; /** * constructor ensures party has always one member - leader * @param leader создатель парти * @param itemDistribution режим распределения лута */ public L2Party(L2Player leader, int itemDistribution) { _itemDistribution = itemDistribution; _members.add(leader); _partyLvl = leader.getLevel(); posTaskThread = ThreadPoolManager.getInstance().schedule(posTask, 11000); // для надежности _rateExp = leader.getBonus().RATE_XP*leader.getAltBonus(); _rateSp = leader.getBonus().RATE_SP*leader.getAltBonus(); _rateAdena = leader.getBonus().RATE_DROP_ADENA*leader.getAltBonus(); _rateDrop = leader.getBonus().RATE_DROP_ITEMS*leader.getAltBonus(); _rateSpoil = leader.getBonus().RATE_DROP_SPOIL*leader.getAltBonus(); } /** * @return number of party members */ public int getMemberCount() { return _members.size(); } public int getMemberCountInRange(L2Player player, int range) { int ret = 0; for(L2Player member : _members) if(member == player || member.getReflectionId() == player.getReflectionId() && member.isInRange(player, range)) ret++; return ret; } /** * @return all party members */ public List<L2Player> getPartyMembers() { return _members; } public L2Player getPartyMember(int index) { return _members.get(index); } public List<Integer> getPartyMembersObjIds() { List<Integer> result = new ArrayList<Integer>(_members.size()); for(L2Player member : _members) result.add(member.getObjectId()); return result; } public List<L2Playable> getPartyMembersWithPets() { List<L2Playable> result = new ArrayList<L2Playable>(); for(L2Player member : _members) { result.add(member); if(member.getPet() != null) result.add(member.getPet()); } return result; } public L2Player getRandomMember() { List<L2Player> members = getPartyMembers(); return members.get(Rnd.get(members.size())); } /** * @return random member from party */ private L2Player getRandomMemberInRange(L2Player player, L2ItemInstance item, int range, L2NpcInstance fromNpc) { List<L2Player> ret = new ArrayList<L2Player>(); L2Character for_dist = fromNpc != null ? fromNpc : player; for(L2Player member : _members) if(member != null && member.getReflectionId() == player.getReflectionId() && member.isInRange(for_dist, range) && !member.isDead() && member.getInventory().validateCapacity(item) && member.getInventory().validateWeight(item)) ret.add(member); return ret.isEmpty() ? null : ret.get(Rnd.get(ret.size())); } /** * @return next item looter */ private L2Player getNextLooterInRange(L2Player player, L2ItemInstance item, int range, L2NpcInstance fromNpc) { L2Character for_dist = fromNpc != null ? fromNpc : player; synchronized (_members) { int antiloop = _members.size(); while(--antiloop > 0) { int looter = _itemOrder; _itemOrder++; if(_itemOrder > _members.size() - 1) _itemOrder = 0; L2Player ret = looter < _members.size() ? _members.get(looter) : player; if(ret != null && ret.getReflectionId() == player.getReflectionId() && ret.isInRange(for_dist, range) && !ret.isDead()) return ret; } return player; } } /** * true if player is party leader */ public boolean isLeader(L2Player player) { L2Player leader = getPartyLeader(); return leader != null && player.equals(leader); } /** * Возвращает лидера партии * @return L2Player Лидер партии */ public L2Player getPartyLeader() { if(_members.size() == 0) return null; return _members.get(0); } /** * Broadcasts packet to every party member * @param msg packet to broadcast */ public void broadcastToPartyMembers(L2GameServerPacket... msg) { for(L2Player member : _members) if(member != null) member.sendPacket(msg); } /** * Рассылает текстовое сообщение всем членам группы * @param msg сообщение */ public void broadcastMessageToPartyMembers(String msg) { broadcastToPartyMembers(new SystemMessage(msg)); } /** * Рассылает пакет всем членам группы исключая указанного персонажа<BR><BR> */ public void broadcastToPartyMembers(L2Player exclude, L2GameServerPacket msg) { for(L2Player member : _members) if(member != null && exclude.getObjectId() != member.getObjectId()) member.sendPacket(msg); } public void broadcastToPartyMembersInRange(L2Player player, L2GameServerPacket msg, int range) { for(L2Player member : _members) if(member != null && member.getReflectionId() == player.getReflectionId() && player.isInRange(member, range)) member.sendPacket(msg); } public void broadcastCSToPartyMembers(L2Player player, L2GameServerPacket msg) { for(L2Player member : _members) if(member != null && !member.isInBlockList(player) && !member.isBlockAll()) member.sendPacket(msg); } public boolean containsMember(L2Character player) { return _members.contains(player.getPlayer()); } /** * adds new member to party * @param player L2Player to add */ public void addPartyMember(L2Player player) { L2Player leader = getPartyLeader(); if(leader == null) return; synchronized (_members) { if(_members.isEmpty()) return; if(_members.contains(player)) return; if(_members.size() >= ConfigValue.MAX_SIZE) { leader.sendPacket(Msg.PARTY_IS_FULL); player.sendPacket(Msg.PARTY_IS_FULL); return; } _members.add(player); } L2Summon player_pet, member_pet; Collection<L2GameServerPacket> pmember, pmember_proto = new GArray<L2GameServerPacket>(), pplayer = new GArray<L2GameServerPacket>(); //sends new member party window for all members //we do all actions before adding member to a list, this speeds things up a little pplayer.add(new PartySmallWindowAll(this, player)); pplayer.add(new SystemMessage(SystemMessage.YOU_HAVE_JOINED_S1S_PARTY).addString(leader.getName())); pmember_proto.add(new SystemMessage(SystemMessage.S1_HAS_JOINED_THE_PARTY).addString(player.getName())); pmember_proto.add(new PartySmallWindowAdd(player)); pmember_proto.add(new PartySpelled(player, true)); if((player_pet = player.getPet()) != null) { pmember_proto.add(new ExPartyPetWindowAdd(player_pet)); pmember_proto.add(new PartySpelled(player_pet, true)); } for(L2Player member : _members) if(member != null && member != player) { pmember = new GArray<L2GameServerPacket>(); pmember.addAll(pmember_proto); pmember.addAll(RelationChanged.update(member, player, member)); member.sendPackets(pmember); pmember = null; pplayer.add(new PartySpelled(member, true)); if((member_pet = member.getPet()) != null) pplayer.add(new PartySpelled(member_pet, true)); pplayer.addAll(RelationChanged.update(player, member, player)); //FIXME if(member.is_dv) DragonValley.getInstance().recheckBuff(member); } // Если партия уже в СС, то вновь прибывшем посылаем пакет открытия окна СС if(isInCommandChannel()) pplayer.add(Msg.ExMPCCOpen); player.sendPackets(pplayer); pplayer = null; pmember_proto = null; recalculatePartyData(); if(isInReflection() && getReflection() instanceof DimensionalRift) ((DimensionalRift) getReflection()).partyMemberInvited(); if(player.getPartyRoom() > 0) { PartyRoom room = PartyRoomManager.getInstance().getRooms().get(player.getPartyRoom()); if(room != null) room.updateInfo(); } if(player.is_dv) DragonValley.getInstance().recheckBuff(player); if(getEventMaster() != null) getEventMaster().addPartyMember(this, player); } /** * Удаляет все связи */ public void dissolveParty() { Reflection reflection = getReflection(); if(reflection != null) reflection.dissolveParty(this); if(getEventMaster() != null) getEventMaster().dissolveParty(this); for(L2Player p : _members) { p.setParty(null); if(p.is_dv) DragonValley.getInstance().recheckBuff(p); } synchronized (_members) { _members.clear(); } setDimensionalRift(null); _commandChannel = null; posTaskThread.cancel(false); } /** * removes player from party * @param player L2Player to remove */ private void removePartyMember(L2Player player) { synchronized (_members) { _members.remove(player); posTask.remove(player); } recalculatePartyData(); Collection<L2GameServerPacket> pplayer = new GArray<L2GameServerPacket>(); // Отсылаемы вышедшему пакет закрытия СС if(isInCommandChannel()) pplayer.add(Msg.ExMPCCClose); pplayer.add(Msg.YOU_HAVE_WITHDRAWN_FROM_THE_PARTY); pplayer.add(Msg.PartySmallWindowDeleteAll); player.setParty(null); L2Summon player_pet; Collection<L2GameServerPacket> pmember_proto = new GArray<L2GameServerPacket>(); if((player_pet = player.getPet()) != null) pmember_proto.add(new ExPartyPetWindowDelete(player_pet)); pmember_proto.add(new PartySmallWindowDelete(player)); pmember_proto.add(new SystemMessage(SystemMessage.S1_HAS_LEFT_THE_PARTY).addString(player.getName())); // TODO: Нужно ли нам это? synchronized (_members) { Collection<L2GameServerPacket> pmember; for(L2Player member : _members) if(member != null) { pmember = new GArray<L2GameServerPacket>(); pmember.addAll(pmember_proto); pmember.addAll(RelationChanged.update(member, player, member)); member.sendPackets(pmember); pmember = null; pplayer.addAll(RelationChanged.update(player, member, player)); if(member.is_dv) DragonValley.getInstance().recheckBuff(member); } } player.sendPackets(pplayer); pplayer = null; Reflection reflection = getReflection(); if(reflection != null) reflection.oustPartyMember(this, player); if(getEventMaster() != null) getEventMaster().removePartyMember(this, player); if(reflection instanceof DarknessFestival) ((DarknessFestival) reflection).partyMemberExited(); else if(isInReflection() && getReflection() instanceof DimensionalRift) ((DimensionalRift) getReflection()).partyMemberExited(player); if(reflection != null && player.getReflection() == reflection && reflection.getReturnLoc() != null) player.teleToLocation(reflection.getReturnLoc(), 0); if(player.getDuel() != null) player.getDuel().onRemoveFromParty(player); L2Player leader = getPartyLeader(); if(_members.size() == 1 || leader == null) { if(leader != null && leader.getDuel() != null) leader.getDuel().onRemoveFromParty(leader); // Если в партии остался 1 человек, то удаляем ее из СС if(isInCommandChannel()) _commandChannel.removeParty(this); else if(reflection != null) { //lastMember.teleToLocation(getReflection().getReturnLoc(), 0); //getReflection().stopCollapseTimer(); //getReflection().collapse(); if(reflection.getInstancedZone() != null) { if(reflection.getParty() == this) // TODO: убрать затычку reflection.startCollapseTimer(60000); if(leader != null && leader.getReflection().getId() == reflection.getId()) leader.broadcastPacket(new SystemMessage(SystemMessage.THIS_DUNGEON_WILL_EXPIRE_IN_S1_MINUTES).addNumber(1)); } setReflection(null); } if(leader != null) leader.setParty(null); dissolveParty(); } else if(isInCommandChannel() && _commandChannel.getChannelLeader() == player) _commandChannel.setChannelLeader(leader); if(player.getPartyRoom() > 0) { PartyRoom room = PartyRoomManager.getInstance().getRooms().get(player.getPartyRoom()); if(room != null) room.updateInfo(); } if(player.is_dv) DragonValley.getInstance().recheckBuff(player); } /** * Change party leader (used for string arguments) * @param name имя нового лидера парти */ public void changePartyLeader(String name) { L2Player new_leader = getPlayerByName(name); L2Player current_leader = getPartyLeader(); if(new_leader == null || current_leader == null) return; if(current_leader.equals(new_leader)) { current_leader.sendPacket(Msg.YOU_CANNOT_TRANSFER_RIGHTS_TO_YOURSELF); return; } synchronized (_members) { if(!_members.contains(new_leader)) { current_leader.sendPacket(Msg.YOU_CAN_TRANSFER_RIGHTS_ONLY_TO_ANOTHER_PARTY_MEMBER); return; } // Меняем местами нового и текущего лидера int idx = _members.indexOf(new_leader); _members.set(0, new_leader); _members.set(idx, current_leader); } updateLeaderInfo(); if(isInCommandChannel() && _commandChannel.getChannelLeader() == current_leader) _commandChannel.setChannelLeader(new_leader); } public void updateLeaderInfo() { L2Player p_member = getPartyLeader(); if(p_member == null) return; SystemMessage msg = new SystemMessage(SystemMessage.S1_HAS_BECOME_A_PARTY_LEADER).addString(p_member.getName()); for(L2Player member : _members) // индивидуальные пакеты - удаления и инициализация пати if(member != null) member.sendPacket(Msg.PartySmallWindowDeleteAll, // Удаляем все окошки new PartySmallWindowAll(this, member), // Показываем окошки msg); // Сообщаем о смене лидера for(L2Player member : _members) // броадкасты состояний if(member != null) { broadcastToPartyMembers(member, new PartySpelled(member, true)); // Показываем иконки if(member.getPet() != null) broadcastToPartyMembers(new ExPartyPetWindowAdd(member.getPet())); // Показываем окошки петов // broadcastToPartyMembers(member, new PartyMemberPosition(member)); // Обновляем позицию на карте } posTask.lastpositions.clear(); } /** * finds a player in the party by name * @param name имя для поиска * @return найденый L2Player или null если не найдено */ public L2Player getPlayerByName(String name) { for(L2Player member : _members) if(member != null && name.equalsIgnoreCase(member.getName())) return member; return null; } /** * Oust player from party * @param player L2Player которого выгоняют */ public void oustPartyMember(L2Player player) { oustPartyMember(player, true); } public void oustPartyMember(L2Player player, boolean isOly) { synchronized (_members) { if(player == null || !_members.contains(player)) return; } boolean leader = isLeader(player); if(isOly) { // Убираем чара с реги на оли... if(Olympiad.isRegisteredTeam(player)) Olympiad.removeRegistration(player.getObjectId()); if(player.isInOlympiadMode() || player.getOlympiadGame() != null) Olympiad.logoutPlayer(player); } removePartyMember(player); if(leader && _members.size() > 1) updateLeaderInfo(); } /** * Oust player from party Overloaded method that takes player's name as * parameter * * @param name имя игрока для изгнания */ public void oustPartyMember(String name) { oustPartyMember(getPlayerByName(name)); } /** * distribute item(s) to party members * @param player * @param item */ public void distributeItem(L2Player player, L2ItemInstance item) { distributeItem(player, item, null); } public void distributeItem(L2Player player, L2ItemInstance item, L2NpcInstance fromNpc) { if(Util.contains(ConfigValue.ListItemToPartyDistribute, item.getItemId())) { distributeAdena(item, fromNpc, player); return; } L2Player target = player; List<L2Player> ret = null; switch(_itemDistribution) { case ITEM_RANDOM: case ITEM_RANDOM_SPOIL: target = getRandomMemberInRange(player, item, ConfigValue.AltPartyDistributionRange, fromNpc); break; case ITEM_ORDER: case ITEM_ORDER_SPOIL: target = getNextLooterInRange(player, item, ConfigValue.AltPartyDistributionRange, fromNpc); /*synchronized (_members) { ret = new CopyOnWriteArrayList<L2Player>(_members); while(target == null && !ret.isEmpty()) { int looter = _itemOrder; _itemOrder++; if(_itemOrder > ret.size() - 1) _itemOrder = 0; L2Player looterPlayer = looter < ret.size() ? ret.get(looter) : null; if(looterPlayer != null) { if(!looterPlayer.isDead() && looterPlayer.isInRangeZ(player, ConfigValue.AltPartyDistributionRange) && ItemFunctions.canAddItem(looterPlayer, item)) //if(ret != null && ret.getReflectionId() == player.getReflectionId() && ret.isInRange(for_dist, range) && !ret.isDead()) target = looterPlayer; else ret.remove(looterPlayer); } } }*/ break; case ITEM_LOOTER: default: target = player; break; } if(target == null) { item.dropToTheGround(player, fromNpc); return; } if(!target.getInventory().validateWeight(item)) { target.sendPacket(Msg.ActionFail, Msg.YOU_HAVE_EXCEEDED_THE_WEIGHT_LIMIT); item.dropToTheGround(target, fromNpc); return; } if(!target.getInventory().validateCapacity(item)) { target.sendPacket(Msg.ActionFail, Msg.YOUR_INVENTORY_IS_FULL); item.dropToTheGround(player, fromNpc); return; } if(!item.pickupMe(target)) return; target.sendPacket(SystemMessage.obtainItems(item)); broadcastToPartyMembers(target, SystemMessage.obtainItemsBy(item, target.getName())); L2ItemInstance item2 = target.getInventory().addItem(item); Log.LogItem(target, fromNpc, Log.GetItemInPaty, item2); target.sendChanges(); } /** * distribute adena to party members * @param adena инстанс адены для распределения */ public void distributeAdena(L2ItemInstance item, L2Player player) { distributeAdena(item, null, player); } public void distributeAdena(L2ItemInstance item, L2NpcInstance fromNpc, L2Player player) { if(player == null) return; L2Character for_dist = fromNpc != null ? fromNpc : player; GArray<L2Player> membersInRange = new GArray<L2Player>(); if(item.getCount() < _members.size()) membersInRange.add(player); else { for(L2Player member : _members) if(member != null) if(member.equals(player) || for_dist.isInRange(member, ConfigValue.AltPartyDistributionRange) && !member.isDead()) membersInRange.add(member); } if(membersInRange.isEmpty()) membersInRange.add(player); long totalAdena = item.getCount(); long amount = totalAdena / membersInRange.size(); long ost = totalAdena % membersInRange.size(); for(L2Player member : membersInRange) { L2ItemInstance newAdena = ItemTemplates.getInstance().createItem(item.getItemId()); newAdena.setCount(member.equals(player) ? amount + ost : amount); member.sendPacket(SystemMessage.obtainItems(newAdena)); L2ItemInstance item2 = member.getInventory().addItem(newAdena); if(fromNpc == null) Log.LogItem(member, Log.GetItemInPaty, item2); else Log.LogItem(member, fromNpc, Log.GetItemInPaty, item2); } } public void distributeXpAndSp(double xpReward, double spReward, GArray<L2Player> rewardedMembers, L2Character lastAttacker, L2MonsterInstance monster) { recalculatePartyData(); GArray<L2Player> mtr = new GArray<L2Player>(); int PartyLevel = lastAttacker.getLevel(); double partyLvlSum = 0; // считаем минимальный/максимальный уровень for(L2Player member : rewardedMembers) { if(!lastAttacker.isInRange(member, ConfigValue.AltPartyDistributionRange)) continue; PartyLevel = Math.max(PartyLevel, member.getLevel()); } // составляем список игроков, удовлетворяющих требованиям for(L2Player member : rewardedMembers) { if(!lastAttacker.isInRange(member, ConfigValue.AltPartyDistributionRange)) continue; if(member.getLevel() <= PartyLevel - 15) continue; partyLvlSum += member.getLevel(); mtr.add(member); } if(mtr.size() == 0) return; // бонус за пати double bonus = ConfigValue.AltPartyBonus[mtr.size() - 1]; // количество эксп и сп для раздачи на всех double XP = xpReward * bonus; double SP = spReward * bonus; for(L2Player member : mtr) { double lvlPenalty = Experience.penaltyModifier(monster.calculateLevelDiffForDrop(member.getLevel(), false), 9); int lvlDiff = PartyLevel - member.getLevel(); if(lvlDiff >= ConfigValue.PartyPenaltyMinDiff && lvlDiff <= ConfigValue.PartyPenaltyMaxDiff) lvlPenalty *= 0.3; // отдаем его часть с учетом пенальти double memberXp = XP * lvlPenalty * member.getLevel() / partyLvlSum; double memberSp = SP * lvlPenalty * member.getLevel() / partyLvlSum; // больше чем соло не дадут memberXp = Math.min(memberXp, xpReward); memberSp = Math.min(memberSp, spReward); // Начисление душ камаэлянам double neededExp = member.calcStat(Stats.SOULS_CONSUME_EXP, 0, monster, null); if(neededExp > 0 && memberXp > neededExp) { monster.broadcastPacket(new SpawnEmitter(monster, member)); ThreadPoolManager.getInstance().schedule(new SoulConsumeTask(member), 1000); } double[] xpsp = member.applyVitality(monster, memberXp, memberSp, memberXp / xpReward); if(ConfigValue.RangEnable) { long point = (long)((xpsp[0]/100)*ConfigValue.RangPercentAddPointMob[member.getRangId()]); if(point < 1) point = 1; member.addRangPoint(point); member.sendMessage("Получено "+point+" Очков Воина. Всего "+member.getRangPoint()+" Очков Воина."); } if(member.getLevel() > monster.getLevel()- ConfigValue.ExpSpPenaltyDiff) member.addExpAndSp((long) xpsp[0], (long) xpsp[1], false, true, (long) xpsp[2], (long) xpsp[3], monster); } recalculatePartyData(); } public void recalculatePartyData() { _partyLvl = 0; float rateExp = 0; float rateSp = 0; float rateDrop = 0; float rateAdena = 0; float rateSpoil = 0; float minRateExp = Float.MAX_VALUE; float minRateSp = Float.MAX_VALUE; float minRateDrop = Float.MAX_VALUE; float minRateAdena = Float.MAX_VALUE; float minRateSpoil = Float.MAX_VALUE; byte count = 0; for(L2Player member : _members) if(member != null) { int level = member.getLevel(); _partyLvl = Math.max(_partyLvl, level); count++; rateExp += member.getBonus().RATE_XP*member.getAltBonus(); rateSp += member.getBonus().RATE_SP*member.getAltBonus(); rateDrop += member.getBonus().RATE_DROP_ITEMS*member.getAltBonus(); rateAdena += member.getBonus().RATE_DROP_ADENA*member.getAltBonus(); rateSpoil += member.getBonus().RATE_DROP_SPOIL*member.getAltBonus(); minRateExp = Math.min(minRateExp, member.getBonus().RATE_XP*member.getAltBonus()); minRateSp = Math.min(minRateSp, member.getBonus().RATE_SP*member.getAltBonus()); minRateDrop = Math.min(minRateDrop, member.getBonus().RATE_DROP_ITEMS*member.getAltBonus()); minRateAdena = Math.min(minRateAdena, member.getBonus().RATE_DROP_ADENA*member.getAltBonus()); minRateSpoil = Math.min(minRateSpoil, member.getBonus().RATE_DROP_SPOIL*member.getAltBonus()); } _rateExp = ConfigValue.RatePartyMin ? minRateExp : rateExp / count; _rateSp = ConfigValue.RatePartyMin ? minRateSp : rateSp / count; _rateDrop = ConfigValue.RatePartyMin ? minRateDrop : rateDrop / count; _rateAdena = ConfigValue.RatePartyMin ? minRateAdena : rateAdena / count; _rateSpoil = ConfigValue.RatePartyMin ? minRateSpoil : rateSpoil / count; } public int getLevel() { return _partyLvl; } public int getLootDistribution() { return _itemDistribution; } public boolean isDistributeSpoilLoot() { boolean rv = false; if(_itemDistribution == ITEM_RANDOM_SPOIL || _itemDistribution == ITEM_ORDER_SPOIL) rv = true; return rv; } public boolean isInDimensionalRift() { return _dr > 0 && getDimensionalRift() != null; } public void setDimensionalRift(DimensionalRift dr) { _dr = dr == null ? 0 : dr.getId(); } public DimensionalRift getDimensionalRift() { return _dr == 0 ? null : (DimensionalRift) ReflectionTable.getInstance().get(_dr); } public boolean isInReflection() { if(_reflection > 0) return true; if(_commandChannel != null) return _commandChannel.isInReflection(); return false; } public void setReflection(Reflection reflection) { _reflection = reflection == null ? 0 : reflection.getId(); } public Reflection getReflection() { if(_reflection > 0) return ReflectionTable.getInstance().get(_reflection); if(_commandChannel != null) return _commandChannel.getReflection(); return null; } public boolean isInCommandChannel() { return _commandChannel != null; } public L2CommandChannel getCommandChannel() { return _commandChannel; } public void setCommandChannel(L2CommandChannel channel) { _commandChannel = channel; } /** * Телепорт всей пати в одну точку (x,y,z) */ public void Teleport(int x, int y, int z) { TeleportParty(getPartyMembers(), new Location(x, y, z)); } /** * Телепорт всей пати в одну точку dest */ public void Teleport(Location dest) { TeleportParty(getPartyMembers(), dest); } /** * Телепорт всей пати на территорию, игроки расставляются рандомно по территории */ public void Teleport(L2Territory territory) { RandomTeleportParty(getPartyMembers(), territory); } /** * Телепорт всей пати на территорию, лидер попадает в точку dest, а все остальные относительно лидера */ public void Teleport(L2Territory territory, Location dest) { TeleportParty(getPartyMembers(), territory, dest); } public static void TeleportParty(List<L2Player> members, Location dest) { for(L2Player _member : members) { if(_member == null) continue; _member.teleToLocation(dest); } } public static void TeleportParty(List<L2Player> members, L2Territory territory, Location dest) { if(!territory.isInside(dest.x, dest.y)) { Log.add("TeleportParty: dest is out of territory", "errors"); Thread.dumpStack(); return; } int base_x = members.get(0).getX(); int base_y = members.get(0).getY(); for(L2Player _member : members) { if(_member == null) continue; int diff_x = _member.getX() - base_x; int diff_y = _member.getY() - base_y; Location loc = new Location(dest.x + diff_x, dest.y + diff_y, dest.z); while(!territory.isInside(loc.x, loc.y)) { diff_x = loc.x - dest.x; diff_y = loc.y - dest.y; if(diff_x != 0) loc.x -= diff_x / Math.abs(diff_x); if(diff_y != 0) loc.y -= diff_y / Math.abs(diff_y); } _member.teleToLocation(loc); } } public static void RandomTeleportParty(List<L2Player> members, L2Territory territory) { for(L2Player _member : members) { int[] _loc = territory.getRandomPoint(); if(_member == null || _loc == null) continue; _member.teleToLocation(_loc[0], _loc[1], _loc[2]); } } public void requestLootModification(int mode) { newLootDistr = mode; votingChangeLoot = true; //формируем список из тех, от кого будем ждать ответ, и заодно рассылаем всем запрос. for (L2Player player : getPartyMembers()) { if (player != getPartyLeader()) { lootResponsers.add(player); player.sendPacket(new ExAskModifyPartyLooting(getPartyLeader().getName(), newLootDistr)); } } getPartyLeader().sendPacket(new SystemMessage(3135).addSystemString(LOOT_SYSSTRINGS[newLootDistr])); if (voteTask != null) voteTask.cancel(true); voteTask = ThreadPoolManager.getInstance().schedule(new VoteLootChangeTask(), 10000); } private void setItemDistribution(boolean forse) { if (_itemDistribution == newLootDistr) return; if (forse) {//кто то дал отрицательный ответ if (voteTask != null) voteTask.cancel(true); voteTask = null; newLootDistr = _itemDistribution; broadcastToPartyMembers(new ExSetPartyLooting(_itemDistribution, 0)); broadcastToPartyMembers(new SystemMessage(3137)); return; } else if (lootResponsers.size() > 0) { newLootDistr = _itemDistribution; broadcastToPartyMembers(new ExSetPartyLooting(_itemDistribution, 0)); broadcastToPartyMembers(new SystemMessage(3137)); return; } lootResponsers.clear(); _itemDistribution = newLootDistr; getPartyLeader().sendPacket(new ExSetPartyLooting(_itemDistribution, 1)); broadcastToPartyMembers(new SystemMessage(3138).addSystemString(LOOT_SYSSTRINGS[_itemDistribution])); for(L2Player member : _members) if(member != null) member.sendPacket(Msg.PartySmallWindowDeleteAll, new PartySmallWindowAll(this, member)); for(L2Player member : _members) if(member != null) { broadcastToPartyMembers(member, new PartySpelled(member, true)); // Показываем иконки if(member.getPet() != null) broadcastToPartyMembers(new ExPartyPetWindowAdd(member.getPet())); // Показываем окошки петов } } public void answerLootModification(L2Player member, int answer) { if (lootResponsers.contains(member) && answer == 1) { lootResponsers.remove(member); if (lootResponsers.size() == 0) setItemDistribution(false); } else setItemDistribution(true); } class VoteLootChangeTask extends l2open.common.RunnableImpl { @Override public void runImpl() { L2Party.this.setItemDistribution(false); } } private class UpdatePositionTask extends l2open.common.RunnableImpl { private final WeakReference<L2Party> party_ref; private final HashMap<Integer, int[]> lastpositions = new HashMap<Integer, int[]>(); public UpdatePositionTask(L2Party party) { party_ref = new WeakReference<L2Party>(party); } public void remove(L2Player player) { synchronized (lastpositions) { lastpositions.remove(new Integer(player.getObjectId())); } } public void runImpl() { L2Party party = party_ref.get(); if(party == null || party.getMemberCount() < 2) { synchronized (lastpositions) { lastpositions.clear(); } party_ref.clear(); dissolveParty(); return; } try { List<L2Player> full_updated = new ArrayList<L2Player>(); List<L2Player> members = party.getPartyMembers(); PartyMemberPosition just_updated = new PartyMemberPosition(); int[] lastpos; for(L2Player member : members) { if(member == null) continue; synchronized (lastpositions) { lastpos = lastpositions.get(new Integer(member.getObjectId())); if(lastpos == null) { just_updated.add(member); full_updated.add(member); lastpositions.put(member.getObjectId(), new int[] { member.getX(), member.getY(), member.getZ() }); } else if(member.getDistance(lastpos[0], lastpos[1], lastpos[2]) > 256) //TODO подкорректировать { just_updated.add(member); lastpos[0] = member.getX(); lastpos[1] = member.getY(); lastpos[2] = member.getZ(); } } } // посылаем изменения позиций старым членам пати if(just_updated.size() > 0) for(L2Player member : members) if(!full_updated.contains(member)) member.sendPacket(just_updated); // посылаем полный список позиций новым членам пати if(full_updated.size() > 0) { just_updated = new PartyMemberPosition().add(members); for(L2Player member : full_updated) member.sendPacket(just_updated); full_updated.clear(); } } catch(Exception e) { e.printStackTrace(); } finally { posTaskThread = ThreadPoolManager.getInstance().schedule(this, 1000); } } } public void addFractionPoint(L2Player for_dist) { } private EventMaster _event_master; public EventMaster getEventMaster() { return _event_master; } public void setEventMaster(EventMaster em) { _event_master = em; } }
C#
UTF-8
2,774
2.96875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.IO; namespace SimpleConnect { class CTParameterFile { public void ReadActionXml(string inputFile) { bool step0 = false; bool step1 = false; bool step2 = false; // Start with XmlReader object //here, we try to setup Stream between the XML file nad xmlReader using (XmlReader reader = XmlReader.Create(inputFile)) { while (reader.Read()) { //Console.Write("Element "); // Console.Write(reader.Name); // Console.WriteLine(); // Console.ReadKey(); if (reader.IsStartElement() && (reader.Name.ToUpper() == "PARAMETERFILE")) { reader.Read(); step0 = true; if ((reader.IsStartElement() && (reader.Name.ToUpper() == "DRIVE")) && step0 == true) { reader.Read(); step1 = true; if ((reader.IsStartElement() && (reader.Name.ToUpper() == "CLASSIFIER")) && step1 == true) { reader.Skip(); step2 = true; reader.Read(); // read end element } reader.Read(); if ((reader.IsStartElement() && (reader.Name.ToUpper() == "CONFIGURATION")) && step2 == true) { reader.Skip(); reader.Read(); // read end element } if (reader.IsStartElement() && (reader.Name.ToUpper() == "PARAMETERS")) //start of drive parameters { reader.Read(); while (reader.Name.ToUpper() != "PARAMETER") { Console.Write(reader.Name); Console.Write(" "); Console.Write(reader.AttributeCount); } break; } } } Console.WriteLine(reader.Name); } } Console.ReadKey(); } } }
PHP
UTF-8
1,026
3
3
[]
no_license
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of Log * * @author Pablo */ class Log { //put your code here public function __construct() { } function message($message){ //date_default_timezone_set('UTC'); $date= date('l jS \of F Y h:i:s A'); $file = 'php_error.log'; if(file_exists($file)){ error_log($date." : ".$message."\r\n", 3, $file); } else echo 'no existe fichero php_errors.log'; } function fileNotFound($message){ //date_default_timezone_set('UTC'); $date= date('l jS \of F Y h:i:s A'); $file = 'php_error.log'; if(file_exists($file)){ error_log($date." : No exist file : ".$message."\r\n", 3, $file); } else echo 'no existe fichero php_errors.log'; } }
Ruby
UTF-8
197
3.609375
4
[]
no_license
a = ["r", "p", "s", "w"]#array puts a p a b = a.index("p")#finding array index puts b c = a[2]#retrieve array elment using index p c d = ["a", "b","c","d","e","f","g","h","i"] e = d[0,3] p e
Markdown
UTF-8
1,056
3.234375
3
[ "MIT" ]
permissive
Today we covered a ton of topics. One of those was "HTML elements," which are special characters which start with & and appear as a special symbol on the page. I also learned that the anchor tag, <a> can make just about anything into a link. We also learned several new concepts for JS, including Conditional Statements, logical operators, truthy and falsy -ness. We also learned about 3 kinds of loops, though according to Nick one of those isn't very useful. Then we talked about all things boxes in CSS. Margin-border-padding-content IN THAT ORDER!!! The next thing we were taught was about new branches and pull requests and other types of Git stuff. I found this very confusing. Luckily Brianna was willing to walk me through all of it during the after-lunch work period. She was very patient and helpful and I'm grateful to her. This class is intense, but I think I'm up to the challenge. I'm really enjoying JS the most. I think I'll probably really like Python, and that's what I'm leaning towards for my 401 focus. Thanks for another great day
Python
UTF-8
259
3.640625
4
[]
no_license
outfile = open('golf.txt','w') cont = 'y' while cont == 'y' or cont == 'Y': name = input("Enter golfer's name: ") score = int(input("Score: ")) cont = input("Are there are more golfers? Enter y or Y for yes, anything else for no") outfile.close()
PHP
UTF-8
3,890
2.671875
3
[]
no_license
<?php /** * @Author: zuoliguang * @Date: 2018-08-17 16:51:08 * @Last Modified by: zuoliguang * @Last Modified time: 2018-08-27 13:50:07 */ if (!defined('BASEPATH')) exit('No direct script access allowed'); class Catalog_model extends Base_Model { function __construct() { parent::__construct(); $this->database = $this->db_admin; $this->tableName = "catalog"; } /** * 获取菜单信息源数据 * @author zuoliguang 2018-08-23 * @return [type] [description] */ public function getAllCatalogs() { $fields = "id, pid, title, icon, url, sort"; $where = ["is_del" => 0]; $this->db_admin->select($fields); $this->db_admin->from($this->tableName); $this->db_admin->where($where); $this->db_admin->order_by("pid", "ASC"); $this->db_admin->order_by("sort", "ASC"); return $this->db_admin->get()->result_array(); } /** * 获取普通管理员菜单 * @author zuoliguang 2018-08-23 * @param [type] $admin_id [description] * @return [type] [description] */ public function getAidCatalogs($admin_id) { $sql = "SELECT c.* FROM `ha_catalog` AS c LEFT JOIN `ha_permission` AS p ON p.catalog_id = c.id WHERE p.admin_id = $admin_id ORDER BY c.pid asc, c.sort asc"; $data = $this->db_admin->query($sql)->result_array(); $ids = [0]; array_walk($data, function($item, $k) use (&$ids){ if (!in_array($item["id"], $ids)) { $ids[] = intval($item["id"]); } if (!in_array($item["pid"], $ids)) { $ids[] = intval($item["pid"]); } }); $fields = "id, pid, title, icon, url, sort"; $where = ["is_del" => 0, ]; $this->db_admin->select($fields); $this->db_admin->from($this->tableName); $this->db_admin->where($where); $this->db_admin->where_in("id", $ids); $this->db_admin->order_by("pid", "ASC"); $this->db_admin->order_by("sort", "ASC"); return $this->db_admin->get()->result_array(); } /** * 获取所有菜单树 两级菜单 * @author zuoliguang 2018-08-22 * @return [type] [description] */ public function getTreeList() { $data = $this->getAllCatalogs(); $kvd = []; foreach ($data as $item) { $kvd[$item["id"]] = $item; } $treeList = []; foreach ($data as $catalog) { if (intval($catalog["pid"])==0) { $treeList[$catalog["id"]] = $catalog; } else { if (isset($treeList[$catalog["pid"]])) { $treeList[$catalog["pid"]]["items"][] = $catalog; } } } return $treeList; } /** * 两级菜单 * 获取页面支持前端json格式的菜单树 * @author zuoliguang 2018-08-23 * @return [type] [description] */ public function getLayuiTree() { $data = $this->getAllCatalogs(); $kvd = []; foreach ($data as $item) { $kvd[$item["id"]] = $item; } $treeList = []; foreach ($data as $catalog) { if (intval($catalog["pid"])==0) { $treeList[$catalog["id"]]["id"] = $catalog["id"]; $treeList[$catalog["id"]]["name"] = $catalog["title"]; $treeList[$catalog["id"]]["is_first"] = 1; } else { if (isset($treeList[$catalog["pid"]])) { $treeList[$catalog["pid"]]["children"][] = [ "id" => $catalog["id"], "name"=>$catalog["title"] ]; } } } return $treeList; } /** * 获取管理员权限的菜单列表 * @author zuoliguang 2018-08-23 * @param string $value [description] * @return [type] [description] */ public function getTreeListByaid($admin_id) { $data = $this->getAidCatalogs($admin_id); $kvd = []; foreach ($data as $item) { $kvd[$item["id"]] = $item; } $treeList = []; foreach ($data as $catalog) { if (intval($catalog["pid"])==0) { $treeList[$catalog["id"]] = $catalog; } else { if (isset($treeList[$catalog["pid"]])) { $treeList[$catalog["pid"]]["items"][] = $catalog; } } } return $treeList; } }
PHP
UTF-8
2,004
2.765625
3
[ "MIT" ]
permissive
<?php namespace Tlr\Display\Assets\Output; use Illuminate\Contracts\Routing\UrlGenerator; use Tlr\Display\Assets\Components\AssetManager; class TagInjector { /** * The asset manager instnace * * @var \Tlr\Display\Assets\Components\AssetManager */ protected $assets; /** * The url generator instnace * * @var \Illuminate\Contracts\Routing\UrlGenerator */ protected $url; public function __construct(AssetManager $assets, UrlGenerator $url) { $this->assets = $assets; $this->url = $url; } /** * Generate a script tag * * @return string */ public function scripts($domain = 'default', array $options = []) { return $this->tag('<script src="%s"></script>', 'assets.js'); } /** * Generate a style tag * * @return string */ public function styles($domain = 'default', array $options = []) { return $this->tag('<link rel="stylesheet" href="%s" />', 'assets.css'); } /** * Generate a tag with the given format * * @param string $format * @param string $route * @return string */ public function tag($format, $route) { $url = $this->route( $route, $this->assets->active() ); return sprintf($format, $url); } /** * Generate the route for the resource * * @param string $name * @param array $query * @return string */ public function route($name, array $query) { return $this->url ->route($name, $this->compileDependanciesQuery($query)); } /** * Sort the links into their arrays * * @param array $deps * @return string */ public function compileDependanciesQuery(array $deps) { return implode('&', array_map(function($item) { return sprintf('sources[]=%s', urlencode($item)); }, $deps)); } }
Python
UTF-8
618
3.328125
3
[]
no_license
#!/usr/bin/env/ python3 from pkg_resources import resource_string import json """ Defines a room class and a fucntion used to create an instance of room class """ class Room(): def __init__( self, id = '1', name = 'test name', desc = 'test desc', exits = {}): self.id = id self.name = name self.desc = desc self.exits = exits def _exits(self, dir): """ Verifies that provided exit is in room's list of exits """ if dir in self.exits: return self.exits[dir] else: return None
Java
UTF-8
20,096
1.8125
2
[]
no_license
package com.superdata.soho.activity.approvalcenter; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONObject; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.superdata.soho.R; import com.superdata.soho.common.BaseActivity; import com.superdata.soho.config.InterfaceConfig; import com.superdata.soho.entity.AuditWorkOvertimeapproval; import com.superdata.soho.service.SDHttpClient; import com.superdata.soho.util.SharedPreferencesConfig; import com.superdata.soho.view.SDProgressDialog; import com.superdata.soho.view.XListView.IXListViewListener; /** * 加班审批 * @author lj * * 2014年9月11日 */ public class WorkOvertimeApprovalActivity extends BaseActivity implements IXListViewListener { private MyAdapter adapter; Button work_overtime_app_bt_back; private com.superdata.soho.view.XListView listView; private Button btn_search; //Adapter里面放的List, private List<AuditWorkOvertimeapproval> listovertime =new ArrayList<AuditWorkOvertimeapproval>(); //临时的List,用于加载更多 的逻辑处理 private List<AuditWorkOvertimeapproval> listovertime1 =new ArrayList<AuditWorkOvertimeapproval>(); private SDProgressDialog sdDialog; //获取的是第几页的数据 private int page =1; //获取的这页的数量 private int pagesize =8; //用于判断是否修改了值 private boolean flag2=true; //标识是否加载更多 private boolean flag =true; private boolean isLastPage=false; private int position_value; private int showToast =0; private int Position; private EditText work_overtime_app_etsearch; private Map<String, String> mapconfig; private String empId; private String companyId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.work_overtime_approval_activity); initSharePreferences(); initView(); initdata(); } private void initSharePreferences() { mapconfig = SharedPreferencesConfig.config(WorkOvertimeApprovalActivity.this); empId=mapconfig.get(InterfaceConfig.ID); companyId=mapconfig.get(InterfaceConfig.COMPANYID); } private void initView() { work_overtime_app_bt_back=(Button) findViewById(R.id.work_overtime_app_bt_back); work_overtime_app_bt_back.setOnClickListener(listener); listView= (com.superdata.soho.view.XListView)this.findViewById(R.id.work_overtime_app_listview); listView.setOnItemClickListener(listener1); listView.setCacheColorHint(0); listView.setPullLoadEnable(true); listView.setXListViewListener(this); listView.setHeaderDividersEnabled(false); listView.setFooterDividersEnabled(false); btn_search=(Button)this.findViewById(R.id.work_overtime_app_search); btn_search.setOnClickListener(listener); work_overtime_app_etsearch =(EditText)this.findViewById(R.id.work_overtime_app_etsearch); work_overtime_app_etsearch.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if(keyCode==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_UP){ initSearch(); } return false; } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode!=0){ switch (resultCode) { // input case 1: showToast = 1; break; case 2: showToast = 2; break; case 3: showToast = 3; break; case 4: showToast = 4; break; default: break; } position_value = Integer.valueOf(data.getExtras().getString("POSITION")); flag2 = false; initdata( (position_value) + "", 1 + "", 0 + "",1 + ""); } super.onActivityResult(requestCode, resultCode, data); } public void initdata(){ initdata(page+"",pagesize+"","关键字","1"); } private void initdata(String start, String size, String search, String type) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("page", start)); params.add(new BasicNameValuePair("rows", size)); new MyTask().execute(params); } class MyTask extends AsyncTask< List<NameValuePair> , Integer, String>{ String url =com.superdata.soho.config.InterfaceConfig.WORKOVERTIME; @Override protected void onPreExecute() { if(page==1){ sdDialog = new SDProgressDialog(WorkOvertimeApprovalActivity.this); sdDialog.show(); } super.onPreExecute(); } @Override protected String doInBackground(List<NameValuePair>... params) { String aa = null; try { aa = new SDHttpClient().post_session(url, params[0]); } catch (Exception e) { e.printStackTrace(); } return aa; } @Override protected void onPostExecute(String result) { if(result!=null){ try { JSONObject jRoot = new JSONObject(result); JSONArray jaresultList =jRoot.getJSONArray("rows"); if(flag2){ int total = jRoot.getInt("total"); if(total>page*pagesize){ isLastPage =false; }else{ isLastPage =true; } } listovertime1.clear(); for(int i=0;i<jaresultList.length();i++){ String id =(String.valueOf(jaresultList.getJSONObject(i).get("id")).equals(null))?1+"": String.valueOf(jaresultList.getJSONObject(i).get("id")); String code =(jaresultList.getJSONObject(i).get("code")).equals(null)?"":(String) jaresultList.getJSONObject(i).get("code"); String userName =(jaresultList.getJSONObject(i).get("empName")).equals(null)?"":(String) jaresultList.getJSONObject(i).get("empName"); String workOvertimeStartTime = (jaresultList.getJSONObject(i).get("startDate")).equals(null)?"":((String) jaresultList.getJSONObject(i).get("startDate")).substring(0, 19); String workOvertimeEndTime =(jaresultList.getJSONObject(i).get("endDate")).equals(null)?"":((String) jaresultList.getJSONObject(i).get("endDate")).substring(0, 19); String workOvertimeType =(jaresultList.getJSONObject(i).get("typeName")).equals(null)?"":(String) jaresultList.getJSONObject(i).get("typeName"); String workOvertimeTotalTime =(String.valueOf(jaresultList.getJSONObject(i).get("length")).equals(null))?"": String.valueOf(jaresultList.getJSONObject(i).get("length"))+"小时"; String workOvertimeapprovetime = (jaresultList.getJSONObject(i).get("applyDate")).equals(null)?"":((String) jaresultList.getJSONObject(i).get("applyDate")).substring(0, 19); String workOvertimeReason =(jaresultList.getJSONObject(i).get("remark")).equals(null)?"":(String) jaresultList.getJSONObject(i).get("remark"); String workOvertimeStatus =(String.valueOf(jaresultList.getJSONObject(i).get("status")).equals(null))?1+"": String.valueOf(jaresultList.getJSONObject(i).get("status")); AuditWorkOvertimeapproval awo=new AuditWorkOvertimeapproval(id,code, userName, workOvertimeStartTime, workOvertimeEndTime, workOvertimeType, workOvertimeTotalTime, workOvertimeapprovetime, workOvertimeReason, workOvertimeStatus); listovertime1.add(awo); } } catch (Exception e) { e.printStackTrace(); } } Message msg =new Message(); //用于判断是否修改了值 if(flag2){ //加载更多 时 if(!flag){ listovertime.addAll(listovertime1); listovertime1.clear(); adapter = new MyAdapter(); msg.what =2; }else{ //第一次 //重新加载全部的 listovertime.clear(); listovertime.addAll(listovertime1); adapter = new MyAdapter(); msg.what =1; } }else{ listovertime.get(position_value-1).setworkOvertimeStatus(listovertime1.get(0).getworkOvertimeStatus()); flag2 =true; adapter = new MyAdapter(); msg.what =4; } if(sdDialog.isShow()) sdDialog.cancel(); handler.sendMessage(msg); super.onPostExecute(result); } } private Handler handler =new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: listView.setAdapter(adapter); if (sdDialog.isShow()) { sdDialog.cancel(); } adapter.notifyDataSetChanged(); break; case 2: flag =true; listView.setAdapter(adapter); listView.setSelection(listovertime.size()-pagesize); adapter.notifyDataSetChanged();// 数据变化刷新 if(sdDialog.isShow()) sdDialog.cancel(); onLoad(); break; case 3: onLoad(); Toast.makeText(getApplicationContext(), "已全部加载完成", Toast.LENGTH_SHORT).show(); break; case 4: listView.setAdapter(adapter); listView.setSelection(position_value); if (sdDialog.isShow()) { sdDialog.cancel(); } adapter.notifyDataSetChanged(); switch (showToast) { //input case 1: Toast.makeText(WorkOvertimeApprovalActivity.this, "审批通过成功提交",Toast.LENGTH_SHORT).show(); break; case 2: Toast.makeText(WorkOvertimeApprovalActivity.this, "审批终止成功提交", Toast.LENGTH_SHORT).show(); break; case 3: Toast.makeText(WorkOvertimeApprovalActivity.this, "反审批成功提交", Toast.LENGTH_SHORT).show(); break; case 4: Toast.makeText(WorkOvertimeApprovalActivity.this, "审批成功提交", Toast.LENGTH_SHORT).show(); break; default: break; } break; default: break; } super.handleMessage(msg); } }; private void onLoad() { listView.stopRefresh(); listView.stopLoadMore(); listView.setRefreshTime(new Date().toLocaleString()); } OnClickListener listener =new OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.work_overtime_app_bt_back: onBackPressed(); overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out); break; //搜索监听 case R.id.work_overtime_app_search: initSearch(); break; default: break; } } }; public void initSearch(){ } OnItemClickListener listener1 =new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Position =position; initDate(listovertime.get(position-1).getId(),"25",empId,"",companyId); } }; public void initDate(String dataId,String dataTypeId,String auditId,String Id,String companyId){ List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("dataId", dataId)); params.add(new BasicNameValuePair("dataTypeId",dataTypeId)); params.add(new BasicNameValuePair("auditId",auditId)); params.add(new BasicNameValuePair("dProcessId",Id)); params.add(new BasicNameValuePair("companyId",companyId)); new MyTask1().execute(params); } class MyTask1 extends AsyncTask< List<NameValuePair> , Integer, String>{ String url =com.superdata.soho.config.InterfaceConfig.HAVINGAUDIT; private boolean reAuditOpt; private boolean auditOpt; private boolean hasProcess; @Override protected void onPreExecute() { sdDialog = new SDProgressDialog(WorkOvertimeApprovalActivity.this); sdDialog.show(); super.onPreExecute(); } @Override protected String doInBackground(List<NameValuePair>... params) { String result = null; try { result = new SDHttpClient().post_session(url, params[0]); } catch (Exception e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result) { if(result!=null){ try { JSONObject jRoot = new JSONObject(result); reAuditOpt =jRoot.getBoolean("reAuditOpt"); auditOpt =jRoot.getBoolean("auditOpt"); hasProcess =jRoot.getBoolean("hasProcess"); } catch (Exception e) { e.printStackTrace(); reAuditOpt =false; auditOpt =false; } } if(sdDialog.isShow()) sdDialog.cancel(); if(hasProcess){ if(auditOpt){ intentAuditView(); }else{ if(reAuditOpt){ intentReAuditView(); }else{ intentDetailView(); } } }else{ intentsingleView(); } } private void intentsingleView() { Intent intent =new Intent(WorkOvertimeApprovalActivity.this, WorkOvertimeApprovalSingleAuditActivity.class); intent.putExtra("NAME", listovertime.get(Position-1).getUserName()); intent.putExtra("TIME", listovertime.get(Position-1).getworkOvertimeapprovetime()); intent.putExtra("TYPE", listovertime.get(Position-1).getworkOvertimeType()); intent.putExtra("STARTTIME", listovertime.get(Position-1).getworkOvertimeStartTime()); intent.putExtra("ENDTIME", listovertime.get(Position-1).getworkOvertimeEndTime()); intent.putExtra("TIMELONG", listovertime.get(Position-1).getworkOvertimeTotalTime()); intent.putExtra("REASON", listovertime.get(Position-1).getworkOvertimeReason()); intent.putExtra("AUDITSTATUS", listovertime.get(Position-1).getworkOvertimeStatus()); intent.putExtra("AUDITPEOPLE", "aa"); intent.putExtra("POSITION", Position+""); intent.putExtra("ID",listovertime.get(Position-1).getId() ); intent.putExtra("FLAG", auditOpt); startActivityForResult(intent, 1); } private void intentDetailView() { Intent intent = new Intent(getApplicationContext(), WorkOvertimeApprovalDetailActivity.class); intent.putExtra("NAME", listovertime.get(Position-1).getUserName()); intent.putExtra("TIME", listovertime.get(Position-1).getworkOvertimeapprovetime()); intent.putExtra("TYPE", listovertime.get(Position-1).getworkOvertimeType()); intent.putExtra("STARTTIME", listovertime.get(Position-1).getworkOvertimeStartTime()); intent.putExtra("ENDTIME", listovertime.get(Position-1).getworkOvertimeEndTime()); intent.putExtra("TIMELONG", listovertime.get(Position-1).getworkOvertimeTotalTime()); intent.putExtra("REASON", listovertime.get(Position-1).getworkOvertimeReason()); intent.putExtra("AUDITSTATUS", listovertime.get(Position-1).getworkOvertimeStatus()); intent.putExtra("AUDITPEOPLE", "aa"); intent.putExtra("ID",listovertime.get(Position-1).getId() ); startActivity(intent); } private void intentReAuditView() { Intent intent =new Intent(WorkOvertimeApprovalActivity.this, WorkOvertimeApprovalBackAuditActivity.class); intent.putExtra("NAME", listovertime.get(Position-1).getUserName()); intent.putExtra("TIME", listovertime.get(Position-1).getworkOvertimeapprovetime()); intent.putExtra("TYPE", listovertime.get(Position-1).getworkOvertimeType()); intent.putExtra("STARTTIME", listovertime.get(Position-1).getworkOvertimeStartTime()); intent.putExtra("ENDTIME", listovertime.get(Position-1).getworkOvertimeEndTime()); intent.putExtra("TIMELONG", listovertime.get(Position-1).getworkOvertimeTotalTime()); intent.putExtra("REASON", listovertime.get(Position-1).getworkOvertimeReason()); intent.putExtra("AUDITSTATUS", listovertime.get(Position-1).getworkOvertimeStatus()); intent.putExtra("AUDITPEOPLE", "aa"); intent.putExtra("POSITION", Position+""); intent.putExtra("ID",listovertime.get(Position-1).getId() ); startActivityForResult(intent, 1); } private void intentAuditView() { Intent intent =new Intent(WorkOvertimeApprovalActivity.this, WorkOvertimeApprovalAuditActivity.class); intent.putExtra("NAME", listovertime.get(Position-1).getUserName()); intent.putExtra("TIME", listovertime.get(Position-1).getworkOvertimeapprovetime()); intent.putExtra("TYPE", listovertime.get(Position-1).getworkOvertimeType()); intent.putExtra("STARTTIME", listovertime.get(Position-1).getworkOvertimeStartTime()); intent.putExtra("ENDTIME", listovertime.get(Position-1).getworkOvertimeEndTime()); intent.putExtra("TIMELONG", listovertime.get(Position-1).getworkOvertimeTotalTime()); intent.putExtra("REASON", listovertime.get(Position-1).getworkOvertimeReason()); intent.putExtra("AUDITSTATUS", listovertime.get(Position-1).getworkOvertimeStatus()); intent.putExtra("AUDITPEOPLE", "aa"); intent.putExtra("POSITION", Position+""); intent.putExtra("ID",listovertime.get(Position-1).getId()); startActivityForResult(intent, 1); } } class MyAdapter extends BaseAdapter { @Override public int getCount() { return listovertime.size(); } @Override public Object getItem(int position) { return listovertime.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(WorkOvertimeApprovalActivity.this).inflate(R.layout.item_work_overtime_approve, null); holder.name=(TextView) convertView.findViewById(R.id.tv_cb_item_work_overtime_approve_name); holder.timelong=(TextView)convertView.findViewById(R.id.tv_cb_item_work_overtime_approve_timelong); holder.starttime=(TextView)convertView.findViewById(R.id.tv_cb_item_work_overtime_approve_startdate); holder.reason=(TextView)convertView.findViewById(R.id.tv_cb_item_work_overtime_approve_reason); holder.status=(TextView)convertView.findViewById(R.id.tv_cb_item_work_overtime_approve_status); holder.approvetime=(TextView)convertView.findViewById(R.id.tv_cb_item_work_overtime_approve_time); convertView.setTag(holder); }else { holder = (ViewHolder) convertView.getTag(); } holder.name.setText(listovertime.get(position).getUserName()); holder.timelong.setText(listovertime.get(position).getworkOvertimeTotalTime()); holder.starttime.setText(listovertime.get(position).getworkOvertimeStartTime()); holder.reason.setText(listovertime.get(position).getworkOvertimeReason()); if(listovertime.get(position).getworkOvertimeStatus().equals("0")){ holder.status.setText(R.string.AUDIT_STATUS_0); }else{ holder.status.setText(R.string.AUDIT_STATUS_1); } holder.approvetime.setText(listovertime.get(position).getworkOvertimeapprovetime()); return convertView; } } class ViewHolder { TextView name,timelong,starttime,reason,status,approvetime; } @Override public void onRefresh() { page = 1; initdata("1",pagesize+"","关键字","1"); onLoad(); } @Override public void onLoadMore() { if(!isLastPage){ if(flag){ flag =false; ++page; initdata(page+"", pagesize+"","关键字","1"); } }else{ handler.sendEmptyMessage(3); } } }
Java
UTF-8
2,660
2.96875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package hbm; import org.hibernate.Session; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; /** * Hibernate Utility class with a convenient method to get Session Factory * object. * * @author RigoBono */ public class HibernateUtil { private static final SessionFactory sessionFactory; //Es el objeto creador de sesiones para los usuarios del sistema private static final ThreadLocal localSession; //Es el objeto que representa una sesion local static { try { Configuration config = new Configuration(); //Instancia un nuevo objeto Configuration config.configure("hibernate.cfg.xml"); //Le indica la ruta en la que se encuentra el archivo de configuracion de de Hibernate StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); //Da contexto al sesionFactory en base a la configuracion builder.applySettings(config.getProperties()); //Aplica la confioguracion proveniente de config sessionFactory = config.buildSessionFactory(builder.build()); //Inicia la sesion con la configuracion asignada anteriormente } catch (Throwable ex) { // Log the exception. System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } localSession = new ThreadLocal(); //Crea un nuevo hilo con la sesion local } public static SessionFactory getSessionFactory() { return sessionFactory; } //Crea y verifica la nueva sesion local y la retorna public static Session getLocalSession() { Session session = (Session) localSession.get(); //Obtiene un objeto Sesion de la sesion local //Evalua si la sesion local es inexistente, y si lo es, instancia una nueva y la asigna a la sesion local if (session == null) { session = sessionFactory.openSession(); localSession.set(session); System.out.println("\nsesion iniciada"); } return session; } //Cierra la sesion local public static void closeLocalSession() { Session session = (Session) localSession.get(); if (session != null) session.close(); localSession.set(null); System.out.println("sesion cerrada\n"); } }
Python
UTF-8
7,965
2.671875
3
[]
permissive
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2013 PAL Robotics SL. # Released under the BSD License. # # Authors: # * Siegfried-A. Gevatter import curses import math import rospy from geometry_msgs.msg import Twist class Velocity(object): def __init__(self, min_velocity, max_velocity, num_steps): assert min_velocity > 0 and max_velocity > 0 and num_steps > 0 self._min = min_velocity self._max = max_velocity self._num_steps = num_steps if self._num_steps > 1: self._step_incr = (max_velocity - min_velocity) / (self._num_steps - 1) else: # If num_steps is one, we always use the minimum velocity. self._step_incr = 0 def __call__(self, value, step): """ Takes a value in the range [0, 1] and the step and returns the velocity (usually m/s or rad/s). """ if step == 0: return 0 assert step > 0 and step <= self._num_steps max_value = self._min + self._step_incr * (step - 1) return value * max_value class TextWindow(): _screen = None _window = None _num_lines = None def __init__(self, stdscr, lines=10): self._screen = stdscr self._screen.nodelay(True) curses.curs_set(0) self._num_lines = lines def read_key(self): keycode = self._screen.getch() return keycode if keycode != -1 else None def clear(self): self._screen.clear() def write_line(self, lineno, message): if lineno < 0 or lineno >= self._num_lines: raise ValueError('lineno out of bounds') height, width = self._screen.getmaxyx() y = (height / self._num_lines) * lineno x = 10 for text in message.split('\n'): text = text.ljust(width) self._screen.addstr(y, x, text) y += 1 def refresh(self): self._screen.refresh() def beep(self): curses.flash() class KeyTeleop(): _interface = None _linear = None _angular = None def __init__(self, interface): self._interface = interface self._pub_cmd = rospy.Publisher('cmd_vel', Twist) self._hz = rospy.get_param('~hz', 10) self._num_steps = rospy.get_param('~turbo/steps', 4) forward_min = rospy.get_param('~turbo/linear_forward_min', 0.05) forward_max = rospy.get_param('~turbo/linear_forward_max', 0.3) self._forward = Velocity(forward_min, forward_max, self._num_steps) backward_min = rospy.get_param('~turbo/linear_backward_min', 0.03) backward_max = rospy.get_param('~turbo/linear_backward_max', 0.1) self._backward = Velocity(backward_min, backward_max, self._num_steps) angular_min = rospy.get_param('~turbo/angular_min', 0.3) angular_max = rospy.get_param('~turbo/angular_max', 0.7) self._rotation = Velocity(angular_min, angular_max, self._num_steps) def run(self): self._linear = 0 self._angular = 0 rate = rospy.Rate(self._hz) while True: keycode = self._interface.read_key() if keycode: if self._key_pressed(keycode): self._publish() else: self._publish() rate.sleep() def _get_twist(self, linear, angular): twist = Twist() if linear >= 0: twist.linear.x = self._forward(1.0, linear) else: twist.linear.x = self._backward(-1.0, -linear) twist.angular.z = self._rotation(math.copysign(1, angular), abs(angular)) return twist def _key_pressed(self, keycode): movement_bindings = { curses.KEY_UP: (1, 0), curses.KEY_DOWN: (-1, 0), curses.KEY_LEFT: (0, 1), curses.KEY_RIGHT: (0, -1), } speed_bindings = { ord(' '): (0, 0), } if keycode in movement_bindings: acc = movement_bindings[keycode] ok = False if acc[0]: linear = self._linear + acc[0] if abs(linear) <= self._num_steps: self._linear = linear ok = True if acc[1]: angular = self._angular + acc[1] if abs(angular) <= self._num_steps: self._angular = angular ok = True if not ok: self._interface.beep() elif keycode in speed_bindings: acc = speed_bindings[keycode] # Note: bounds aren't enforced here! if acc[0] is not None: self._linear = acc[0] if acc[1] is not None: self._angular = acc[1] elif keycode == ord('q'): rospy.signal_shutdown('Bye') else: return False return True def _publish(self): self._interface.clear() self._interface.write_line(2, 'Linear: %d, Angular: %d' % (self._linear, self._angular)) self._interface.write_line(5, 'Use arrow keys to move, space to stop, q to exit.') self._interface.refresh() twist = self._get_twist(self._linear, self._angular) self._pub_cmd.publish(twist) class SimpleKeyTeleop(): def __init__(self, interface): self._interface = interface self._pub_cmd = rospy.Publisher('cmd_vel', Twist) self._hz = rospy.get_param('~hz', 10) self._forward_rate = rospy.get_param('~forward_rate', 0.15) self._backward_rate = rospy.get_param('~backward_rate', 0.15) self._rotation_rate = rospy.get_param('~rotation_rate', 0.8) self._last_pressed = {} self._angular = 0 self._linear = 0 movement_bindings = { curses.KEY_UP: (1, 0), curses.KEY_DOWN: (-1, 0), curses.KEY_LEFT: (0, 1), curses.KEY_RIGHT: (0, -1), } def run(self): rate = rospy.Rate(self._hz) self._running = True while self._running: while True: keycode = self._interface.read_key() if keycode is None: break self._key_pressed(keycode) self._set_velocity() self._publish() rate.sleep() def _get_twist(self, linear, angular): twist = Twist() twist.linear.x = linear twist.angular.z = angular return twist def _set_velocity(self): now = rospy.get_time() keys = [] for a in self._last_pressed: if now - self._last_pressed[a] < 0.4: keys.append(a) linear = 0.0 angular = 0.0 for k in keys: l, a = self.movement_bindings[k] linear += l angular += a if linear > 0: linear = linear * self._forward_rate else: linear = linear * self._backward_rate angular = angular * self._rotation_rate self._angular = angular self._linear = linear def _key_pressed(self, keycode): if keycode == ord('q'): self._running = False rospy.signal_shutdown('Bye') elif keycode in self.movement_bindings: self._last_pressed[keycode] = rospy.get_time() def _publish(self): self._interface.clear() self._interface.write_line(2, 'Linear: %f, Angular: %f' % (self._linear, self._angular)) self._interface.write_line(5, 'Use arrow keys to move, q to exit.') self._interface.refresh() twist = self._get_twist(self._linear, self._angular) self._pub_cmd.publish(twist) def main(stdscr): rospy.init_node('key_teleop') app = SimpleKeyTeleop(TextWindow(stdscr)) app.run() if __name__ == '__main__': try: curses.wrapper(main) except rospy.ROSInterruptException: pass
Python
UTF-8
5,229
2.625
3
[]
no_license
import tensorflow as tf from sklearn.model_selection import train_test_split from tensorflow import keras import numpy as np import pickle import matplotlib.pyplot as plt def makedataset(): with open('log_word2vec/final_embeddings.pkl', 'rb') as f: final_embeddings = pickle.load(f) with open('log_word2vec/reverse_dictionary.pkl', 'rb') as f: reverse_dictionary = pickle.load(f) with open('log_word2vec/dictionary.pkl', 'rb') as f: dictionary = pickle.load(f) with open('data/vocabulary.pkl', 'rb') as f: vocabulary = pickle.load(f) # print(reverse_dictionary) # {0: 'UNK', 1: 'result_0', 2: 'call_duration_0', 3: 'ring_time_0', 4: 'is_spam', 5: 'cause_08F90', 6: 'is_not_spam', 7: 'cause_08090', 8: 'ring_time_30', 9: 'calling_hlr_01', 10: 'called_hlr_0579', # print(dictionary) # {'UNK': 0, 'result_0': 1, 'call_duration_0': 2, 'ring_time_0': 3, 'is_spam': 4, 'cause_08F90': 5, 'is_not_spam': 6, 'cause_08090': 7, 'ring_time_30': 8, 'calling_hlr_01': 9, 'called_hlr_0579': 10, 'called_hlr_0574': 11, print(vocabulary[:9]) X = [] y = [] for i in range(len(vocabulary)//9): calling_hlr = vocabulary[i*9+0] called_hlr = vocabulary[i*9+1] user_id = vocabulary[i*9+2] clock = vocabulary[i*9+3] spam = vocabulary[i*9+4] ring = vocabulary[i*9+5] duration = vocabulary[i*9+6] result = vocabulary[i*9+7] cause = vocabulary[i*9+8] tmp = [] index = dictionary.get(calling_hlr, 0) calling_hlr = final_embeddings[index] index = dictionary.get(called_hlr, 0) called_hlr = final_embeddings[index] index = dictionary.get(user_id, 0) user_id = final_embeddings[index] index = dictionary.get(clock, 0) clock = final_embeddings[index] index = dictionary.get(ring, 0) ring = final_embeddings[index] index = dictionary.get(duration, 0) duration = final_embeddings[index] index = dictionary.get(result, 0) result = final_embeddings[index] index = dictionary.get(cause, 0) cause = final_embeddings[index] tmp.extend(calling_hlr) tmp.extend(called_hlr) tmp.extend(user_id) tmp.extend(clock) tmp.extend(ring) tmp.extend(duration) tmp.extend(result) tmp.extend(cause) X.append(np.array(tmp)) if spam == "is_not_spam": y.append(0) else: y.append(1) print(len(X), len(y), sum(y)) with open("data/embeddings/X.pkl", 'wb') as f: pickle.dump(X, f) with open("data/embeddings/y.pkl", 'wb') as f: pickle.dump(y, f) def train(): with open('data/embeddings/X.pkl', 'rb') as f: X = pickle.load(f) with open('data/embeddings/y.pkl', 'rb') as f: y = pickle.load(f) X = np.array(X) y = np.array(y) train_data, test_data, train_labels, test_labels = train_test_split(X, y, test_size=0.2) print("Training entries: {}, labels: {}".format(len(train_data), len(train_labels))) model = keras.Sequential([ keras.layers.Dense(input_shape=[len(train_data[0])], activation=tf.nn.sigmoid, units=9), #keras.layers.Dense(30, activation=tf.nn.relu), #keras.layers.Dense(20, activation=tf.nn.relu), keras.layers.Dense(1, activation=tf.nn.sigmoid) ]) print(model.summary()) model.compile(optimizer=tf.train.AdamOptimizer(), loss='binary_crossentropy', metrics=['accuracy']) x_val = train_data[:1000] partial_x_train = train_data[1000:] y_val = train_labels[:1000] partial_y_train = train_labels[1000:] history = model.fit(train_data, train_labels, epochs=40, batch_size=32, validation_data=(test_data, test_labels), verbose=1) results = model.evaluate(test_data, test_labels) print(results) history_dict = history.history acc = history.history['acc'] val_acc = history.history['val_acc'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(1, len(acc) + 1) # "bo" is for "blue dot" plt.plot(epochs, loss, 'bo', label='Training loss') # b is for "solid blue line" plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend() plt.savefig('figures/train_loss.png') plt.show() plt.clf() # clear figure acc_values = history_dict['acc'] val_acc_values = history_dict['val_acc'] plt.plot(epochs, acc, 'bo', label='Training acc') plt.plot(epochs, val_acc, 'b', label='Validation acc') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.savefig('figures/train_acc.png') plt.show() if __name__ == '__main__': print(tf.__version__) # makedataset() train()
Go
UTF-8
946
3.234375
3
[]
no_license
package golangttdtextcalctravis import ( "testing" // import the testing capability of go ) func invoke_text_to_number(input string, expected_output int, t *testing.T) { output := Text_to_number(input) if output != expected_output { t.Errorf("FAILED: text_to_number(%s) returned %d, expected %d", input, output, expected_output) } else { t.Logf("PASSED: The output was correctly %d", output) } } func TestZero(t *testing.T) { input := "zero" expected_output:= 0; invoke_text_to_number(input, expected_output, t) } func TestOne(t *testing.T) { input := "one" expected_output:= 1; invoke_text_to_number(input, expected_output, t) } func TestFive(t *testing.T) { input := "five" expected_output:= 5; invoke_text_to_number(input, expected_output, t) } /* // example of failing test func TestSix(t *testing.T) { input := "six" expected_output:= 6; invoke_text_to_number(input, expected_output, t) } */
C++
UTF-8
2,061
3.265625
3
[]
no_license
// https://leetcode.com/problems/path-with-maximum-probability/ #include <vector> #include <string> using namespace std; struct Node { public: int connection; double probability; Node(int c, double p) { connection = c; probability = p; } }; class Solution { public: double maxProbability(int n, vector<vector<int>> &edges, vector<double> &succProb, int start, int end) { vector<vector<Node>> graph(n, vector<Node>()); for (int i = 0; i < edges.size(); i++) { vector<int> edge = edges[i]; double probability = succProb[i]; graph[edge[0]].push_back(Node(edge[1], probability)); graph[edge[1]].push_back(Node(edge[0], probability)); } return findMaxPath(n, graph, start, end); } private: double findMaxPath(int n, vector<vector<Node>> &graph, int start, int end) { vector<double> dp(n, 0); dp[start] = 1; vector<int> q{start}; while (!q.empty()) { vector<int> subQ; for (int n : q) { for (Node node : graph[n]) { if (dp[node.connection] < dp[n] * node.probability) { dp[node.connection] = dp[n] * node.probability; subQ.push_back(node.connection); } } } swap(q, subQ); } return dp[end]; } }; int main() { Solution solution; double result1 = solution.maxProbability(3, *new vector<vector<int>>{vector<int>{0, 1}, vector<int>{1, 2}, vector<int>{0, 2}}, *new vector<double>{.5, .5, .2}, 0, 2); double result2 = solution.maxProbability(3, *new vector<vector<int>>{vector<int>{0, 1}, vector<int>{1, 2}, vector<int>{0, 2}}, *new vector<double>{.5, .5, .3}, 0, 2); double result3 = solution.maxProbability(3, *new vector<vector<int>>{vector<int>{0, 1}}, *new vector<double>{.5}, 0, 2); double result4 = solution.maxProbability(4, *new vector<vector<int>>{vector<int>{0, 1}, vector<int>{1, 2}, vector<int>{0, 2}, vector<int>{0, 3}, vector<int>{1, 3}}, *new vector<double>{.4, .5, .2, .5, .9}, 0, 2); }
JavaScript
UTF-8
342
2.546875
3
[]
no_license
const authMiddleware = () => { return(req, res, next)=>{ console.log( `req.session.passport: ${JSON.stringify(req.session)}` ); if(req.isAuthenticated()){ return next(); }else{ res.redirect("/users/login"); } } } module.exports = authMiddleware;
Java
UTF-8
4,003
3
3
[]
no_license
/* *Apresenta um projeto com um conjunto de classes contendo documentação JavaDoc *detalhando quais requisitos devem ser implementados para as classes e métodos *disponibilizados. *Os métodos possuem apenas a estrutura, sendo que a implementação deve ser *desenvolvida pelo aluno, seguindo o processo TDD. *Implementar os requisitos R01 a R04 para a classe Conta. Disponibilizar link *para novo repositório exclusivo para o projeto no GitHub. */ package com.mycompany.testesoftware_sistemabancario.model.entity; /** * * Representa uma movimentação em uma {@link Conta} bancária, que pode indicar * entrada ou saída. * * NOTA: Mesmo sendo possível obter o saldo somando-se todas as movimentações, à * medida que os dados no sistema aumentarem ao longo do tempo, calcular o saldo * pode se tornar uma operação extremamente lenta. Isto normalmente ocorrer * quando o histórico de movimentações se torna longo (principalmente depois de * alguns anos). * */ /** * * @author Lidiane */ public class Movimentacao implements Cadastro { private long id; private String descricao; /** * Conta bancária a qual a movimentação está vinculada. */ private Conta conta; /** * Tipo da movimentação deve ser 'C' para crédito (entrada de dinheiro) ou * 'D' para débito (saída de dinheiro) (R01). */ private char tipo; /** * Valor monetário da movimentação. O valor não deve ser negativo, uma vez * que existe o atributo {@link #tipo} (R02). Se o tipo for débito, o valor * da movimentação não pode ser superior ao saldo total da {@link Conta} * (R03). */ private double valor; /** * Indica se a movimentação foi confirmada, neste caso, devendo ser * registrada no saldo da conta, quando for adicionada à lista de * movimentações usando {@link Conta#addMovimentacao(Movimentacao)}. * * <ul> * <li>Movimentacoes devem ser instanciadas como "confirmadas" por padrão * (R04).</li> * <li> * Somente operações como depósito em cheque devem ser registradas * inicialmente como não confirmadas. Após uma operação ser confirmada, * deve-se atualizar o saldo da conta. * <li> * </ul> * * @see Conta#depositoDinheiro(double) * @see Conta#depositoCheque(double) */ private boolean confirmada; /** * Instancia uma movimentação para uma determinada {@link Conta} bancária, * onde a conta passada deve ser armazenada no atributo {@link #conta} * (R05). * * @param conta a {@link Conta} para vincular a movimentação. */ public Movimentacao(Conta conta) { //R05 this.conta = conta; //R04_Movimentacoes devem ser instanciadas como "confirmadas" por padrão this.confirmada = true; } /**R05 * @return the conta */ public Conta getConta() { return conta; } /**R05 * @param conta the conta to set */ public void setConta(Conta conta) { this.conta = conta; } @Override public long getId() { return id; } @Override public void setId(long id) { this.id = id; } public char getTipo() { return tipo; } public void setTipo(char tipo) { this.tipo = tipo; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public double getValor() { return valor; } public void setValor(double valor) { this.valor = valor; } public boolean isConfirmada() { return confirmada; } public void setConfirmada(boolean confirmada) { this.confirmada = confirmada; } }
Python
UTF-8
3,651
2.90625
3
[]
no_license
""" Motivation: As in previous version, but using an 'effective' Pab1 concentration rather than an actual Species: Pab, iPab, C, mRNAC, Pab_mRNAC """ import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint # Parameters k1 = 166.8 # per min per au, client:hsp70 on rate k3 = k1 k2 = 2.783 # per min, HSP70:HSF1 off rate k4 = 0.0464 # per min HSP70:UP off rate k5 = 4.64e-7 # degradation rate of HSP70:UP beta = 1.778 # Transcription activation rate Kd = 0.0022 # Dissociation constant of HSF1-DNA interaction #kdil = 2.78e-3 # Dilution rate of YFP; assuming 50% growth rate kdil = 0 # Dilution rate of YFP assuming no growth n = 3 # Hill coefficient # Initial values HSP_0 = 1 # Free HSP70 HSF1_0 = 0 # Free HSF1 HSP_HSF1_0 = 1/500. HSP_UP_0 = 0 YFP_0 = 3 # def deriv(z, t): HSP = z[0] HSF1 = z[1] HSP_HSF1 = z[2] HSP_UP = z[3] UP = z[4] YFP = z[5] dHSPdt = k2*HSP_HSF1 - k1*HSP*HSF1 + (k4 + k5)*HSP_UP - k3*HSP*UP + \ beta*(HSF1**n / (Kd**n + HSF1**n)) dHSF1dt = k2*HSP_HSF1 - k1*HSP*HSF1 dHSP_HSF1dt = -k2*HSP_HSF1 + k1*HSP*HSF1 dHSP_UPdt = -(k4 + k5)*HSP_UP + k3*HSP*UP dUPdt = k4*HSP_UP - k3*HSP*UP dYFPdt = beta*(HSF1**n / (Kd**n + HSF1**n)) - kdil*YFP return(np.array([dHSPdt, dHSF1dt, dHSP_HSF1dt, dHSP_UPdt, dUPdt, dYFPdt])) T = [37, 39, 40, 42, 45] z = [] for t in T: UP_0 = 0.0024*np.exp(0.215*t) # generates initial value of UP; empirical time = np.arange(0, 200, 0.1) zinit = np.array([HSP_0, HSF1_0, HSP_HSF1_0, HSP_UP_0, UP_0, YFP_0]) z.append(odeint(deriv, zinit, time)) ## Plots names = ['37', '39', '40', '42', '45'] colors = ['royalblue', 'firebrick', 'gold', 'darkgreen', 'k'] f = plt.figure(figsize=(10,5)) ax = f.add_subplot(111) for i in range(len(z)): ax.plot(time, z[i][:,5], color = colors[i], label = names[i]) ax.legend(title="Temperature") ax.set_yscale("log") ax.set_ylabel("Reporter level") ax.set_xlabel("Time (min)") plt.title("Reporter level vs. time") #f = plt.figure(figsize=(10,5)) #ax = f.add_subplot(111) #for i in range(len(z)): # ax.plot(time, z[i][:,2], color = colors[i], label = names[i]) #ax.legend(title="Temperature") #plt.title("HSP70-HSF1 complex concentration vs. time") f = plt.figure(figsize=(10,5)) ax = f.add_subplot(111) for i in range(len(z)): ax.plot(time, z[i][:,4], color = colors[i], label = names[i]) ax.legend(title="Temperature") ax.set_ylabel("Free client") ax.set_xlabel("Time (min)") plt.title("Free client vs. time") #f = plt.figure(figsize=(10,5)) #ax = f.add_subplot(111) #for i in range(len(z)): # ax.plot(time, z[i][:,0]+z[i][:,2]+z[i][:,3], color = colors[i], label = names[i]) # ax.set_yscale("log") #ax.legend(title="Temperature") #plt.title("total HSP70 vs. time") f = plt.figure(figsize = (8,4)) ax = f.add_subplot(111) ax.plot(z[3][:,5], z[3][:,4]) ax.set_ylabel("Free client level") ax.set_xlabel("Reporter level") #Plotting time to zero unfolded protein as a function of temperature #T = np.linspace(35, 46) #times = [] # #for t in T: # UP_0 = 0.0024*np.exp(0.215*t) # generates initial value of UP; empirical # time = np.arange(0, 200, 0.1) # zinit = np.array([HSP_0, HSF1_0, HSP_HSF1_0, HSP_UP_0, UP_0, YFP_0]) # x = odeint(deriv, zinit, time) # run the simulation # times.append(np.min(np.where(x[:,4] < 1))) # # #f = plt.figure(figsize=(10,5)) #ax = f.add_subplot(111) #ax.plot(T, times) #ax.set_xlabel("Shock temperature (C)") #ax.set_ylabel("Time to clear unfolded protein/clients (min)") #ax.set_yscale("log") #ax.annotate("[P](0) = 0.0024*exp(0.215*temp)", (35, 500))
C++
UTF-8
1,102
3.296875
3
[]
no_license
#include "stdio.h" #include "iostream" #include "math.h" using namespace std; int main() { int cantidadnumeros; int i,j; long int numero; long int sumadivisores=0; cout<<"Ingrese la cantidad de numeros a leer: "; cin>>cantidadnumeros; for (j=0;j<cantidadnumeros;j++){ cout<<"\nIngrese el numero "<<j+1<<": "; cin>>numero; cout<<"\nSus divisores propios son: "; for (i=1;i<=(numero/2);i++){ if (numero%i==0){ cout<<i<<","; sumadivisores=sumadivisores+i; } if (i==(numero/2)){ if (sumadivisores==numero){ cout<<"\nEl numero es Perfecto."; } if (sumadivisores<numero){ cout<<"\nEl numero es Deficiente."; } if (sumadivisores>numero){ cout<<"\nEl numero es Abundante."; } sumadivisores=0; } } } return 0; }
Python
UTF-8
10,352
2.65625
3
[]
no_license
########## IMPORTS ########## import cv2 import mediapipe as mp from matplotlib import pyplot as plt from PIL import Image import numpy as np import argparse ########## GLOBAL SETTINGS ########## ap = argparse.ArgumentParser() ap.add_argument("--source", type=str, default='./images/jim_carrey.jpg', help="Location of source image") ap.add_argument("--target", type=str, default='./images/bradley_cooper.jpg', help="Location of target image") ap.add_argument("--visualize", default=False, help="plot images of intermediate steps", action='store_true') args = ap.parse_args() mp_drawing = mp.solutions.drawing_utils mp_face_mesh = mp.solutions.face_mesh VISUALIZATION = args.visualize ########## HELPER fUNCTIONS AND CLASSES ########## def process_input(img_path, img_format='pil_image'): if img_format == 'pil_image': img = Image.open(img_path) if img_format == 'cv2': img = cv2.imread(img_path) return img def display_image(face_mesh_result, img_path): plt.imshow(process_input(img_path), zorder=1) x, y = face_mesh_result[:, 0], face_mesh_result[:, 1] plt.scatter(x, y, zorder=2, s=1.0) plt.show() def process_landmark_points(annotations_or, image): landmark_points_org = np.array([ (int((i.x) * image.shape[1]), int(i.y * image.shape[0])) for i in annotations_or.multi_face_landmarks[0].landmark ]) landmark_points_org = [list(map(int, i)) for i in landmark_points_org] landmark_points_tuple = [tuple(i) for i in landmark_points_org] landmark_points_arr = np.array(landmark_points_tuple, np.int32) return landmark_points_tuple, landmark_points_arr def rect_around_triangle(points_list): triangle = np.array(points_list, np.int32) rect = cv2.boundingRect(triangle) return rect def extract_triangle_index(landmark_points_arr, triangles_face): face_index_arr = [] for t in triangles_face: pt1 = (t[0], t[1]) pt1_index = np.where((landmark_points_arr == pt1).all(axis=1))[0][0] pt2 = (t[2], t[3]) pt2_index = np.where((landmark_points_arr == pt2).all(axis=1))[0][0] pt3 = (t[4], t[5]) pt3_index = np.where((landmark_points_arr == pt3).all(axis=1))[0][0] face_index_arr.append([pt1_index, pt2_index, pt3_index]) return face_index_arr class triangulation: def __init__(self, landmark_arr, image, show_vis): self.landmark_arr = landmark_arr self.image = image self.show_vis = show_vis def create_rect_around_triangular_area(self, triangle_index): tr_pt1 = tuple(self.landmark_arr[triangle_index[0]]) tr_pt2 = tuple(self.landmark_arr[triangle_index[1]]) tr_pt3 = tuple(self.landmark_arr[triangle_index[2]]) # get rect around triangle rect = rect_around_triangle([tr_pt1, tr_pt2, tr_pt3]) (x, y, w, h) = rect cropped_triangle = self.image[y:y + h, x:x + w] # create a mask same size of rect cropped_triangle_mask = np.zeros((h, w), np.uint8) points = np.array( [[tr_pt1[0] - x, tr_pt1[1] - y], [tr_pt2[0] - x, tr_pt2[1] - y], [tr_pt3[0] - x, tr_pt3[1] - y]], np.int32) cv2.fillConvexPoly(cropped_triangle_mask, points, 255) return cropped_triangle, cropped_triangle_mask, rect, points ########## MAIN CODE ########## source_path = args.source target_path = args.target file_list = [source_path, target_path] images = {i: cv2.cvtColor(cv2.imread(i), cv2.COLOR_BGR2RGB) for i in file_list} # source image , gray image, and mask source_img = process_input(source_path, img_format='cv2') source_img_gray = cv2.cvtColor(source_img, cv2.COLOR_BGR2GRAY) source_img_mask = np.zeros_like(source_img_gray) # target image , gray image, and mask target_img = process_input(target_path, img_format='cv2') target_img_gray = cv2.cvtColor(target_img, cv2.COLOR_BGR2GRAY) target_img_mask = np.zeros_like(target_img_gray) mp_face_mesh = mp.solutions.face_mesh # Initialize MediaPipe Face Mesh. face_mesh = mp_face_mesh.FaceMesh( static_image_mode=True, max_num_faces=2, min_detection_confidence=0.5) # Prepare DrawingSpec for drawing the face landmarks later. mp_drawing = mp.solutions.drawing_utils drawing_spec = mp_drawing.DrawingSpec( thickness=2, circle_radius=1, color=(0, 0, 255)) annotaions_org_images = [] for name, image in images.items(): # Convert the BGR image to RGB and process it with MediaPipe Face Mesh. results = face_mesh.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) # Draw face landmarks of each face. print(f'Face landmarks of {name}:') if not results.multi_face_landmarks: continue annotaions_org_images.append(results) annotated_image = image.copy() for face_landmarks in results.multi_face_landmarks: mp_drawing.draw_landmarks(image=annotated_image, landmark_list=face_landmarks, connections=mp_face_mesh.FACE_CONNECTIONS, landmark_drawing_spec=drawing_spec, connection_drawing_spec=drawing_spec) if VISUALIZATION: plt.show() plt.imshow(annotated_image) if VISUALIZATION: img_index = 1 test_face_mesh_result = np.array([ (int((i.x) * images[file_list[img_index]].shape[1]), int(i.y * images[file_list[img_index]].shape[0])) for i in annotaions_org_images[img_index].multi_face_landmarks[0].landmark ]) display_image(test_face_mesh_result, img_path=file_list[img_index]) source_landmark_points_tuple, source_landmark_points_arr = process_landmark_points( annotaions_org_images[0], source_img) target_landmark_points_tuple, target_landmark_points_arr = process_landmark_points( annotaions_org_images[1], target_img) source_convex_hul = cv2.convexHull(source_landmark_points_arr) target_convex_hul = cv2.convexHull(target_landmark_points_arr) ########## DELAUNAV TRIANGULATION FOR SOURCE FACE ########## # returns rectangle sourrouding the convexhull (x,y,w,h) rect = cv2.boundingRect(source_convex_hul) # this is a builtin function in opencv to find Delaunav triangulation subdiv = cv2.Subdiv2D(rect) subdiv.insert(source_landmark_points_tuple) # insert the points as tuple # returns the triangle from image (3 point of x,y) triangles_source_face = subdiv.getTriangleList() triangles_source_face = np.array(triangles_source_face, dtype=np.int32) # get the corresponding index from the landmark_points_arr # this index will be used to get the values from the target_face triangles_source_face_index = extract_triangle_index( source_landmark_points_arr, triangles_source_face) if VISUALIZATION: # source_img_clone is used for visualization source_img_clone = np.array(source_img) for pts in triangles_source_face_index: cv2.line(source_img_clone, source_landmark_points_tuple[pts[0]], source_landmark_points_tuple[pts[1]], (0, 0, 255), 2) cv2.line(source_img_clone, source_landmark_points_tuple[pts[1]], source_landmark_points_tuple[pts[2]], (0, 0, 255), 2) cv2.line(source_img_clone, source_landmark_points_tuple[pts[2]], source_landmark_points_tuple[pts[0]], (0, 0, 255), 2) cv2.imshow("source_img_clone", source_img_clone) cv2.waitKey(0) cv2.destroyAllWindows() new_target_face = np.zeros_like(target_img) source_triangulation = triangulation( source_landmark_points_arr, source_img, False) target_triangulation = triangulation( target_landmark_points_arr, target_img, False) for triangle_index in triangles_source_face_index: ################ Triangulation Source Face ################ cropped_triangle_source, cropped_triangle_mask_source, rect_source, points_source = source_triangulation.create_rect_around_triangular_area( triangle_index) ################ Triangulation Target Face ################ cropped_triangle_target, cropped_triangle_mask_target, rect_target, points_target = target_triangulation.create_rect_around_triangular_area( triangle_index) (x, y, w, h) = rect_target # warp the triangles using affine transform points_source = points_source.astype(np.float32) points_target = points_target.astype(np.float32) M = cv2.getAffineTransform(points_source, points_target) warped_triangle = cv2.warpAffine(cropped_triangle_source, M, (w, h)) warped_triangle = cv2.bitwise_and( warped_triangle, warped_triangle, mask=cropped_triangle_mask_target) # place the triangles on the target_like empty black image # Reconstructing destination face new_target_face_rect_area = new_target_face[y:y + h, x:x + w] new_target_face_rect_area_gray = cv2.cvtColor( new_target_face_rect_area, cv2.COLOR_BGR2GRAY) # TODO: how is this mask helping # Let's create a mask to remove the lines between the triangles _, mask_triangles_designed = cv2.threshold( new_target_face_rect_area_gray, 1, 255, cv2.THRESH_BINARY_INV) warped_triangle = cv2.bitwise_and(warped_triangle, warped_triangle, mask=mask_triangles_designed) img2_new_face_rect_area = cv2.add(new_target_face_rect_area, warped_triangle) new_target_face[y:y + h, x:x + w] = img2_new_face_rect_area # Face swapped (putting 1st face into 2nd face) img2_face_mask = np.zeros_like(target_img_gray) img2_head_mask = cv2.fillConvexPoly(img2_face_mask, target_convex_hul, 255) img2_face_mask = cv2.bitwise_not(img2_head_mask) img2_head_noface = cv2.bitwise_and(target_img, target_img, mask=img2_face_mask) result = cv2.add(img2_head_noface, new_target_face) (x, y, w, h) = cv2.boundingRect(target_convex_hul) center_face2 = (int((x + x + w) / 2), int((y + y + h) / 2)) seamlessclone = cv2.seamlessClone( result, target_img, img2_head_mask, center_face2, cv2.NORMAL_CLONE) median = cv2.medianBlur(seamlessclone, 3) src_tar = np.concatenate((cv2.resize( source_img, (target_img.shape[1], target_img.shape[0])), target_img, median), axis=1) cv2.imshow("source/target/swap", src_tar) cv2.imwrite('./images/output/output.jpg', src_tar) cv2.waitKey(0) cv2.destroyAllWindows()
Java
UTF-8
154
2.21875
2
[]
no_license
import lombok.Data; @Data public class Man { private Godness godness; public Man() {} public Man(Godness godness) { this.godness = godness; } }
PHP
UTF-8
3,886
2.59375
3
[ "MIT" ]
permissive
<?php namespace Dskripchenko\OrchidExtra\Screens; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Routing\Route; use Illuminate\Support\Facades\DB; use Orchid\Support\Facades\Alert; use Throwable; abstract class BaseListScreen extends Screen { /** * @return Model */ abstract protected function entity(): Model; /** * @return string */ abstract protected function getListLayoutClass(): string; /** * @return array */ protected function getSelections(): array { return []; } /** * @return array */ protected function getQueryWithParameters(): array { return []; } /** * @param Builder $query * @return Builder */ protected function prepareQuery(Builder $query): Builder { return $query; } /** * @return array */ public function query(): array { $entity = $this->entity(); $query = $entity->newQuery() ->defaultSort('id', 'desc'); foreach ($this->getSelections() as $selection) { $query->filters($selection); } $query->with($this->getQueryWithParameters()); $query = $this->prepareQuery($query); $paginator = $query->paginate(); $currentPage = $paginator->currentPage(); $lastPage = $paginator->lastPage(); if ($currentPage > $lastPage) { /** @var Request $request */ $request = request(); /** @var Route $route */ $route = $request->route(); $routeName = $route->getName(); $routeParameters = $route->parameters; redirect()->route($routeName, array_merge($routeParameters, [ 'page' => $lastPage ]))->send(); return []; } return [ $entity->getTable() => $paginator, ]; } /** * @return string[] */ public function layout(): array { return [ ...$this->getSelections(), $this->getListLayoutClass(), ]; } /** * @param Request $request * @return RedirectResponse * @throws Throwable */ public function publishing(Request $request): RedirectResponse { $id = $request->get('id'); $entity = $this->entity() ->newQuery() ->findOrFail($id); $field = $request->get('field'); $oldValue = $entity->getAttribute($field); $entity->setAttribute($field, !$oldValue); $entity->saveOrFail(); Alert::success( !$oldValue ? 'Запись успешно опубликована' : 'Запись успешно скрыта' ); return redirect()->back(); } /** * @param Request $request * @return RedirectResponse */ public function deleting(Request $request): RedirectResponse { $id = $request->get('id'); $entity = $this->entity() ->newQuery() ->findOrFail($id); $entity->delete(); Alert::success('Запись успешно удалена'); return redirect()->back(); } /** * @return RedirectResponse */ public function truncate(): RedirectResponse { $table = $this->entity()->getTable(); $sql = "TRUNCATE TABLE {$table};"; DB::statement($sql); Alert::success("Все данные раздела успешно удалены"); return redirect()->back(); } }
C#
UTF-8
3,315
2.703125
3
[ "Apache-2.0" ]
permissive
using System.Collections.Generic; using System.Linq; using UnityEngine; namespace TerrainGenerator { public class TerrainChunkGenerator : MonoBehaviour { public Material TerrainMaterial; public Texture2D FlatTexture; public Texture2D SteepTexture; private TerrainChunkSettings Settings; private NoiseProvider NoiseProvider; private ChunkCache Cache; private void Awake() { Settings = new TerrainChunkSettings(65, 65, 500, 1500, FlatTexture, SteepTexture, TerrainMaterial); NoiseProvider = new NoiseProvider(); Cache = new ChunkCache(); } private void Update() { if (Input.GetKeyDown(KeyCode.A)) { } Cache.Update(); } private void GenerateChunk(int x, int z) { if (Cache.ChunkCanBeAdded(x, z)) { var chunk = new TerrainChunk(Settings, NoiseProvider, x, z); Cache.AddNewChunk(chunk); } } private void RemoveChunk(int x, int z) { if (Cache.ChunkCanBeRemoved(x, z)) Cache.RemoveChunk(x, z); } private List<Vector2i> GetChunkPositionsInRadius(Vector2i chunkPosition, int radius) { var result = new List<Vector2i>(); for (var zCircle = -radius; zCircle <= radius; zCircle++) { for (var xCircle = -radius; xCircle <= radius; xCircle++) { if (xCircle * xCircle + zCircle * zCircle < radius * radius) result.Add(new Vector2i(chunkPosition.X + xCircle, chunkPosition.Z + zCircle)); } } return result; } public void UpdateTerrain(Vector3 worldPosition, int radius) { var chunkPosition = GetChunkPosition(worldPosition); var newPositions = GetChunkPositionsInRadius(chunkPosition, radius); var loadedChunks = Cache.GetGeneratedChunks(); var chunksToRemove = loadedChunks.Except(newPositions).ToList(); var positionsToGenerate = newPositions.Except(chunksToRemove).ToList(); foreach (var position in positionsToGenerate) GenerateChunk(position.X, position.Z); foreach (var position in chunksToRemove) RemoveChunk(position.X, position.Z); } public Vector2i GetChunkPosition(Vector3 worldPosition) { var x = (int)Mathf.Floor(worldPosition.x / Settings.Length); var z = (int)Mathf.Floor(worldPosition.z / Settings.Length); return new Vector2i(x, z); } public bool IsTerrainAvailable(Vector3 worldPosition) { var chunkPosition = GetChunkPosition(worldPosition); return Cache.IsChunkGenerated(chunkPosition); } public float GetTerrainHeight(Vector3 worldPosition) { var chunkPosition = GetChunkPosition(worldPosition); var chunk = Cache.GetGeneratedChunk(chunkPosition); if (chunkPosition != null) return chunk.GetTerrainHeight(worldPosition); return 0; } } }
Markdown
UTF-8
877
3.046875
3
[]
no_license
### Idea The service is designed with the clean architecture in mind. - We have the app layer which handler the incoming requests, their validation, calling the service layer, serializing the response and error handling. - The second layer is the service layer where we do our business logic. This layer also communicates with the repository layer. - The third layer is the repository layer which holds the models and takes care of the communication with the database. The repository layer doesn't know anything about the service layer and the service layer doesn't know anything about the app layer. The direction of communication is going from outwards to inwards which ensures lose coupling. On initial service generation the resources and methods will be named in a generic way. All of them need to be adjusted per the domain in which this service will work e.g. User.
Python
UTF-8
376
3.53125
4
[]
no_license
# !/usr/bin/env python # -*- coding: utf-8 -*- # Author: Wangzhenqing <wangzhenqing1008@163.com> """ Problem 10: Write a function unique to find all the unique elements of a list. """ def unique(nums): r_nums = [] for x in nums: if x in r_nums: continue r_nums.append(x) return r_nums print unique([1, 2, 1, 3, 2, 5]) """ Output: [1, 2, 3, 5] """
C#
UTF-8
4,935
2.75
3
[]
no_license
using CodeKingdom.Models; using CodeKingdom.Models.Entities; using CodeKingdom.Models.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; namespace CodeKingdom.Repositories { public class CollaboratorRepository { private readonly IAppDataContext db; private readonly UserRepository userRepository; public CollaboratorRepository(IAppDataContext context = null) { db = context ?? new ApplicationDbContext(); userRepository = new UserRepository(); } /// <summary> /// Returns null or single instance of a collaborator /// </summary> /// <param name="id">Collaborator ID</param> public Collaborator GetById(int id) { return db.Collaborators.Where(x => x.ID == id).FirstOrDefault(); } /// <summary> /// Returns list of collaborators by project ID, empty list if no collaborators are found /// </summary> /// <param name="id">Project ID</param> public List<Collaborator> GetByProjectId(int id) { return db.Collaborators.Where(x => x.ProjectID == id).ToList(); } /// <summary> /// Returns list of collaborators by user ID, empty list if no collaborators are found /// </summary> /// <param name="id">User ID</param> public List<Collaborator> GetByUserId(string id) { return db.Collaborators.Where(x => x.ApplicationUserID == id).ToList(); } /// <summary> /// Returns null or single instance of a collaborator by user and project ID /// </summary> /// <param name="userID">User ID</param> /// <param name="projectID">Project ID</param> /// <returns></returns> public Collaborator GetByUserIdAndProjectId(string userID, int projectID) { return db.Collaborators.Where(collaborator => collaborator.ApplicationUserID == userID && collaborator.ProjectID == projectID ).FirstOrDefault(); } /// <summary> /// Returns true if user exists as collaborator for a specific project, false otherwise /// </summary> /// <param name="userID">User ID</param> /// <param name="projectID">Project ID</param> public bool IsInProject(string userID, int projectID) { return (GetByUserId(userID).Where(collaborator => collaborator.ProjectID == projectID).FirstOrDefault() != null); } /// <summary> /// Updates collaborator role for a specific collaborator. Returns false if collaborator or role is not found, true otherwise /// </summary> /// <param name="model">Collaborator ID, Role ID</param> public bool Update(CollaboratorViewModel model) { Collaborator collaborator = this.GetById(model.ID); CollaboratorRole role = this.GetRoleById(model.RoleID); if (collaborator == null || role == null) { return false; } collaborator.CollaboratorRoleID = role.ID; db.SaveChanges(); return true; } /// <summary> /// Stores a single instance of a collaborator in database. Returns false if user already exists as collaborator, true otherwise /// </summary> /// <param name="model">User ID, Project ID</param> public bool Create(Collaborator model) { if (IsInProject(model.ApplicationUserID, model.ProjectID)) { return false; } db.Collaborators.Add(model); db.SaveChanges(); return true; } /// <summary> /// Deletes a single instance of a collaborator from database by collaborator id. Returns false if collaborator doesn't exist, true otherwise /// </summary> /// <param name="id">Collaborator ID</param> public bool DeleteById(int id) { Collaborator collaborator = GetById(id); if (collaborator == null) { return false; } db.Collaborators.Remove(collaborator); db.SaveChanges(); return true; } /// <summary> /// Returns all collaborator roles as list /// </summary> public List<CollaboratorRole> GetAllRoles() { return db.CollaboratorRoles.ToList(); } /// <summary> /// Returns null or single instance of a collaborator role by id /// </summary> /// <param name="id">Collaborator Role ID</param> public CollaboratorRole GetRoleById(int id) { return db.CollaboratorRoles.Where(x => x.ID == id).FirstOrDefault(); } } }
C++
UTF-8
644
2.6875
3
[ "MIT" ]
permissive
// Author: btjanaka (Bryon Tjanaka) // Problem: (HackerRank) designer-pdf-viewer // Title: Designer PDF Viewer // Link: https://www.hackerrank.com/challenges/designer-pdf-viewer/problem // Idea: Find the max height in each block of text. // Difficulty: easy // Tags: implementation #include <bits/stdc++.h> #define GET(x) scanf("%d", &x) using namespace std; int main() { int h[26]; for (int i = 0; i < 26; ++i) GET(h[i]); getchar(); string s; cin >> s; int len = 0; int mx_height = 0; for (int i = 0; i < s.size(); ++i) { ++len; mx_height = max(mx_height, h[s[i] - 'a']); } printf("%d\n", len * mx_height); return 0; }
C++
UTF-8
1,274
3.03125
3
[]
no_license
// ------------------------------------------------------------------- // Author: lfwu // Date: December-27-2013 // Note: // Email:zgwulongfei@gmail.com // Blog:http://blog.csdn.net/hackmind // ------------------------------------------------------------------- #include "utility.h" #include <iostream> #include <list> #include <vector> #include <algorithm> using namespace std; int main(int argc, char** argv){ vector<int> ivec; auto Printlist = [](const list<int>& ilist, const string& title) { cout << title; PrintContainer(ilist); cout << endl; }; CreateSeq(ivec, 1, 9); cout << "the seq is:\n"; PrintContainer(ivec); cout << endl; // use inserter list<int> inserter_list; copy(ivec.begin(), ivec.end(), inserter(inserter_list, inserter_list.begin())); string title = "after call inserter:\n"; Printlist(inserter_list, title); // use back inserter list<int> back_list; copy(ivec.begin(), ivec.end(), back_inserter(back_list)); title = "after call back inserter:\n"; Printlist(back_list, title); // use front insert list<int> front_list; copy(ivec.begin(), ivec.end(), front_inserter(front_list)); title = "after call front inserter:\n"; Printlist(front_list, title); }
JavaScript
UTF-8
453
4.125
4
[]
no_license
function findOutlier(integers) { var evenArr = []; var oddArr = []; for (let i = 0; i < integers.length; i++) { if (integers[i] % 2 === 0) { evenArr.push(integers[i]); console.log("Evens", evenArr); } else { oddArr.push(integers[i]); console.log("Odds", oddArr); } } if (evenArr.length < oddArr.length) { return evenArr[0]; } else { return oddArr[0]; } } console.log(findOutlier([1, 2, 3]));
Python
UTF-8
32,673
2.671875
3
[]
no_license
import random import itertools import otreeutils from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, ExtraModel, Currency, currency_range, ) from .recipes import RECIPES author = 'Dieter Smeulders' doc = """ Experiment Sandwich Making and Risk Reporting """ class Constants(BaseConstants): name_in_url = 'BaseExperiment' players_per_group = 2 num_rounds = 1 BasePay = Currency(5) BasePrice = Currency(1) # SellingPrice = Currency(1) EmployeeRatio = 0.5 ManagerRatio = 0.25 class GameSession(ExtraModel): """Persistent game state linked to each player. Holds name of ordered sandwich and its price. Implements core game logic independant from other models. """ # TODO: this is a temporary data and should be deleted afterwards player = models.Link('Player') ordered = models.StringField() price = models.CurrencyField() def next_order(self, price): """Generates and saves next random order""" self.ordered = random.choice(list(RECIPES.keys())) self.price = price def validate(self, sandwich): """Validates if submitted sandwich matches ordered Returns: valid, reward, errors """ expected = RECIPES[self.ordered] mismatches = len(set(sandwich) ^ set(expected)) if mismatches == 0: return True, self.price, 0 else: return False, 0, mismatches class Subsession(BaseSubsession): def creating_session(self): reportingconditions = ['voluntary', 'mandatory'] cultureconditions = ['supportive', 'supportive', 'unsupportive', 'unsupportive'] for group in self.get_groups(): group.reportingcondition = random.choice(reportingconditions) print(group.reportingcondition) group.culturecondition = random.choice(cultureconditions) print(group.culturecondition) for player in self.get_players(): self.configure_player(player) GameSession.objects.create(player=player) # MandatoryCondition = models.IntegerField(initial=1) # CultureCondition = models.IntegerField(initial=1) # setting gamesession variables # Game Related Logic def configure_player(self, player): p = player.id_in_group duration_min = self.session.config[f"P{p}_duration_min"] duration_max = self.session.config[f"P{p}_duration_max"] player.duration = random.randint(duration_min, duration_max) price_min = self.session.config[f"P{p}_price_min"] price_max = self.session.config[f"P{p}_price_max"] player.price = Currency(random.randint(price_min, price_max)) def game(self, player): return GameSession.objects.get(player=player) def start(self, player): game = self.game(player) game.next_order(player.price) game.save() return game def play(self, player, sandwich): """Main gameplay logic: - validating submitted sandwich - updating metrics - advancing to next order """ game = self.game(player) valid, reward, errors = game.validate(sandwich) if valid: player.performed += 1 player.revenue += reward else: player.errors += 1 player.mismatches = max(player.mismatches, errors) player.save() if valid: game.next_order(player.price) game.save() return game, valid, errors class Group(BaseGroup): reportingcondition = models.StringField() culturecondition = models.StringField() class Player(BasePlayer): name = models.StringField age = models.StringField # All Parameters for the sandwich making task """A player parameters and metrics Implements communication logic: received 'start': - send order received 'sandwich': - validate sandwich received valid sandwich: - send status (number of sandwiches sold) - send new order received invalid sandwish: - send error messages (with number of mismatches) """ # duration of the round duration = models.FloatField() # sandwich price for the round price = models.CurrencyField() # number of valid sandwiches sold performed = models.IntegerField(initial=0) # total revenue revenue = models.CurrencyField(initial=0) # number of invalid sandwiches submitted errors = models.IntegerField(initial=0) # maximal number of mismatched components mismatches = models.IntegerField(initial=0) # time allocated time = models.IntegerField(initial=5) # first round performance performedR1 = models.IntegerField(initial=0) revenueR1 = models.CurrencyField(initial=0) errorsR1 = models.IntegerField(initial=0) mismatchesR1 = models.IntegerField(initial=0) # risk materialisation riskmaterialized = models.BooleanField() # revenues ownshare = models.CurrencyField() supervisorshare = models.CurrencyField() firmshare = models.CurrencyField() def handle_message(self, message): kind = message['type'] if kind == 'start': return self.handle_start() elif kind == 'sandwich': return self.handle_sandwich(message['components']) else: raise ValueError("Invalid message received", kind) def handle_start(self): game = self.subsession.start(self) return self.reply(self.order_message(game)) def handle_sandwich(self, components): game, valid, errors = self.subsession.play(self, components) if valid: return self.reply([self.status_message(), self.order_message(game)]) else: return self.reply(self.errors_message(errors)) def reply(self, message): return {self.id_in_group: message} def order_message(self, game): return {'type': 'order', 'order': game.ordered} def errors_message(self, errors): return {'type': 'error', 'mismatches': errors} def status_message(self): return {'type': 'status', 'performed': self.performed} def reset_after_practice(self): self.performed = 0 self.revenue = 0 self.errors = 0 self.mismatches = 0 def calcrevenue(self): if self.riskmaterialized == 1: self.ownshare = self.revenue * 0.5 * 0.7 + self.revenueR1 * 0.5 self.supervisorshare = self.revenue * 0.25 * 0.7 + self.revenueR1 * 0.25 self.firmshare = self.revenue * 0.25 * 0.7 + self.revenueR1 * 0.25 else: self.ownshare = self.revenue * 0.5 + self.revenueR1 * 0.5 self.firmshare = self.revenue * 0.25 + self.revenueR1 * 0.25 if (self.id_in_group == 1 and self.group.get_player_by_id(3).NEM): self.supervisorshare = self.revenue * 0.25 + self.revenueR1 * 0.25 - 0.1 if (self.id_in_group == 2 and self.group.get_player_by_id(3).SEM): self.supervisorshare = self.revenue * 0.25 + self.revenueR1 * 0.25 - 0.1 else: self.supervisorshare = self.revenue * 0.25 + self.revenueR1 * 0.25 # All other parameters report_displayed = models.BooleanField(initial=False) NLocationChoice = models.IntegerField( label='', choices=[ [1, 'Location A'], [2, 'Location B']], widget=widgets.RadioSelectHorizontal ) Q1 = models.IntegerField( label='1. What is your role?', choices=[[1, 'Shop manager'], [2, 'Supervisor']], widget=widgets.RadioSelectHorizontal ) Q2 = models.IntegerField( label='2. Who has access to the market assessment?', choices=[[1, 'Only the shop manager'], [2, 'Only the supervisor'], [3, 'Both the shop manager and the supervisor']], widget=widgets.RadioSelectHorizontal ) Q3 = models.IntegerField( label='3. How much time does the shop manager have to make sandwiches?', choices=[[1, '10 minutes'], [2, '5 minutes']], widget=widgets.RadioSelectHorizontal ) Q4 = models.IntegerField( label='4. What will the supervisor do?', choices=[[1, 'Decide the location of the new shop.'], [2, 'Rate the performance of the shop manager ' 'based on his/her decision making and sales revenue ' 'in a range from 1 (Very poor) to 5 (Excellent)']], widget=widgets.RadioSelectHorizontal ) Q5 = models.IntegerField( label='5. How is the sales revenue of the shop computed?', choices=[[1, 'Sales revenue is the number of clients attracted.'], [2, 'Sales revenue is the number of sandwiches made.'], [3, 'Sales revenue is the product of the number of sandwiches made ' 'and the selling price of each sandwich. ' 'The current selling price in this location is about 1 euro.']], widget=widgets.RadioSelect ) Q6 = models.IntegerField( label='6. Does AC Company adopt a mandatory risk reporting policy?', choices=[[1, 'Yes'], [2, 'No']], widget=widgets.RadioSelectHorizontal ) Q7 = models.IntegerField( label='7. At AC Company, can people easily ask others for help in the face of difficulty?', choices=[[1, 'Yes'], [2, 'No']], widget=widgets.RadioSelectHorizontal ) Q8 = models.IntegerField( label='8. At AC Company, can people talk to others about what could go wrong without being criticized?', choices=[[1, 'Yes'], [2, 'No']], widget=widgets.RadioSelectHorizontal ) NReportedRiskManD = models.LongStringField( label='You are now obliged to report on risks to your sales revenue (if any) here.' ' Note that you cannot leave this box blank. ' 'In case you identified no risk, say so.' ) NReportedRiskVol = models.LongStringField( label='You are now allowed to report on risks to your sales revenue (if any) here.' ' Note that you can leave this box blank and the supervisor will not receive your report.' ' In case you identified no risk, you can say so, if you wish.', blank=True ) Evaluation = models.IntegerField( label='Please rate the performance of the shop manager.', choices=[[1, 'Very Poor'], [2, 'Poor'], [3, 'Average'], [4, 'Good'], [5, 'Excellent']], widget=widgets.RadioSelectHorizontal ) # PostQuestionnaire closure1 = models.IntegerField( label='I did not disclose all relevant risk information to the supervisor.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure2 = models.IntegerField( label='I did not devote much effort to reporting risks to the supervisor.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure3 = models.IntegerField( label='I honestly reported all the risk information that I had to the supervisor.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure4 = models.IntegerField( label='I reported the risk information that I had to the supervisor as objectively as possible.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure5 = models.IntegerField( label='I felt that my risk report was quite informative.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure6 = models.IntegerField( label='I did not give an accurate account of the risks that I faced to the supervisor.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure7 = models.IntegerField( label='I withheld some unfavorable information from the supervisor.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure8 = models.IntegerField( label='I focused on favorable information more than unfavorable information in my risk report.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure9 = models.IntegerField( label='I tried to cover up some unfavorable news by emphasizing the favorable information.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure10 = models.IntegerField( label='I did not include information that had negative implications for my performance evaluation.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure11 = models.IntegerField( label='I felt responsible to inform the supervisor about the risks I was exposed to.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) closure12 = models.IntegerField( label='It was my responsibility to provide the supervisor with ' 'the detailed information about the potential risks which I faced.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) S1 = models.IntegerField( label='How informative the risk report of the shop manager was?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) S2 = models.IntegerField( label='To what extent do you think the shop manager provided all relevant risk information to you?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) S3 = models.IntegerField( label='How detailed the risk report of the shop manager was?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) S4 = models.IntegerField( label='How useful did you find the risk report of the shop manager for the risk management purposes? ', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) S5 = models.IntegerField( label='How accurate did you find the risk report of the shop manager?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) S6 = models.IntegerField( label='How severe did you find the potential risks to the shop given the report of the shop manager?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) importance1 = models.IntegerField( label='...placed importance on risk management?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) importance2 = models.IntegerField( label='...placed emphasis on the timely communication of risk information?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) importance3 = models.IntegerField( label='...placed value on open sharing of risk information?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) importance4 = models.IntegerField( label='...facilitated communication of risk information?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) image1 = models.IntegerField( label='...the superior would have a negative image of me', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) image2 = models.IntegerField( label='...my image in the eyes of the supervisor would be improved', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) image3 = models.IntegerField( label='...I would look bad in the eyes of the supervisor', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) image4 = models.IntegerField( label='...the supervisor would think better of me', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) image5 = models.IntegerField( label='...the supervisor would think worse of me', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) image6 = models.IntegerField( label='...the supervisor would appreciate it', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) image7 = models.IntegerField( label='...the supervisor would penalize me', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) factor1 = models.IntegerField( label='..report the risks that you faced to the supervisor?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) factor2 = models.IntegerField( label='..show the supervisor that you made the right location choice?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) factor3 = models.IntegerField( label='..report risks in such a way that could have positively impact your performance evaluation?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) factor4 = models.IntegerField( label='..look good in the eyes of the supervisor?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) factor5 = models.IntegerField( label='..look competent in the eyes of the supervisor?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) factor6 = models.IntegerField( label='..avoid creating a negative impression on the supervisor?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) factor7 = models.IntegerField( label='..be honest in your report?', choices=[[1, 'Little'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very much']], widget=widgets.RadioSelectHorizontal ) trust1 = models.IntegerField( label='I felt that the company trusts me to report risks.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) trust2 = models.IntegerField( label='The firm risk reporting policy showed that the firm does not trust its employees.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) trust3 = models.IntegerField( label='The firm risk reporting policy was a clear sign of distrust in employees.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) oblig1 = models.IntegerField( label='I felt obliged to disclose the risk information that I had to the supervisor.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) oblig2 = models.IntegerField( label='I felt that I can easily share the risks to my sales revenue to the supervisor.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) oblig3 = models.IntegerField( label='I felt that I can openly share unfavorable risk information with the supervisor without being punished.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) oblig4 = models.IntegerField( label='I felt that the risks I faced were because of the decision that I had taken. ', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) oblig5 = models.IntegerField( label='I felt that I should manage the risks that I faced on my own. ', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) oblig6 = models.IntegerField( label='I felt that the risks were not so severe for the company. ', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) oblig7 = models.IntegerField( label='I felt that the potential impacts of a new competitor on the sales performance is serious.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) perf1 = models.IntegerField( label='', choices=[[1, 'Way below the average'], [2, ''], [3, 'Average'], [4, ''], [5, 'Way above the average']], widget=widgets.RadioSelectHorizontal ) perf2 = models.IntegerField( label='', choices=[[1, 'Way below my expectation'], [2, ''], [3, 'In line with my expectation'], [4, ''], [5, 'Way above my expectation']], widget=widgets.RadioSelectHorizontal ) safety1 = models.IntegerField( label='If you make a mistake in this company, it is often held against you.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) safety2 = models.IntegerField( label='Members of this company are able to bring up problems and tough issues.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) safety3 = models.IntegerField( label='People in this organization sometimes reject others for being different.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) safety4 = models.IntegerField( label='It is safe to take risks in this company.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) safety5 = models.IntegerField( label='It is difficult to ask other members of this company for help.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) safety6 = models.IntegerField( label='No one in this company would deliberately act in a way that undermines my efforts.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) safety7 = models.IntegerField( label='Working with members of this company, my unique skills and talents are valued and utilized.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) manvol1 = models.IntegerField( label='The company requires its managers to report to their supervisors the risks they are exposed to.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) manvol2 = models.IntegerField( label='In this company, it is compulsory for managers to report the risks they face to the superior in their ' 'performance reports.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) manvol3 = models.IntegerField( label='In this company, managers are mandated to disclose the risks they face.', choices=[[1, 'Very inaccurate'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Very accurate']], widget=widgets.RadioSelectHorizontal ) reason1 = models.IntegerField( label='To encourage honesty and trust.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) reason2 = models.IntegerField( label='To facilitate timely communication of risk information.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) reason3 = models.IntegerField( label='To collect important risk information and manage them at the firm level.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) reason4 = models.IntegerField( label='To fit the culture of the company.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) reason5 = models.IntegerField( label='To evaluate the decisions of the managers.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) riskat1 = models.IntegerField( label='I can be rather incautious and take big risks.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) riskat2 = models.IntegerField( label='I often dare to do risky things which other people are reluctant to do.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) riskat3 = models.IntegerField( label='I am always very cautious and think of safety first.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) riskat4 = models.IntegerField( label='I always try to avoid situations involving a risk of getting into trouble with other people.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) riskat5 = models.IntegerField( label='I like to avoid doing things for which I run the risk of being criticized and blamed if I fail.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) opt1 = models.IntegerField( label='In uncertain times, I usually expect the best.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) opt2 = models.IntegerField( label='I rarely count on good things happening to me.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) opt3 = models.IntegerField( label='Overall, I expect more good things to happen to me than bad.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) unc1 = models.IntegerField( label='Unforeseen events upset me greatly.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) unc2 = models.IntegerField( label='It frustrates me not having all information I need.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) unc3 = models.IntegerField( label='I cannot stand being taken by surprises.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, ''], [6, ''], [7, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) gender = models.IntegerField( label='What is your gender?', choices=[[1, 'Male'], [2, 'Female'], [3, 'Other']], widget=widgets.RadioSelectHorizontal ) age = models.IntegerField( label='How old are you?', min=17, max=80) WorkExperience = models.IntegerField( label='How many months of work experience do you have?', min=0, max=100) gen1 = models.IntegerField( label='My task was boring.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) gen2 = models.IntegerField( label='May task was difficult.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) gen3 = models.IntegerField( label='I enjoyed participating in this study.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) gen4 = models.IntegerField( label='The instructions were clearly formulated.', choices=[[1, 'Strongly disagree'], [2, ''], [3, ''], [4, ''], [5, 'Strongly agree']], widget=widgets.RadioSelectHorizontal ) comment = models.LongStringField( label='Please share your comments about this study here.', blank = True )
C#
UTF-8
2,535
2.65625
3
[ "MIT" ]
permissive
using iRentCar.UserActor.Interfaces; using System; using System.Collections.Generic; using System.Text; using InvoicesServiceInterfaces = iRentCar.InvoicesService.Interfaces; namespace iRentCar.UserActor { internal static class Extensions { internal static UserInfo ToUserInfo(this UserData userData) { if (userData == null) throw new NullReferenceException(nameof(userData)); return new UserInfo() { Email = userData.Email, FirstName = userData.FirstName, IsEnabled = userData.IsEnabled, LastName = userData.LastName, Invoices = new List<InvoiceInfo>(), }; } internal static RentInfo ToRentInfo(this RentData data) { if (data == null) throw new NullReferenceException(nameof(data)); return new RentInfo() { DailyCost = data.VehicleDailyCost, Plate = data.VehiclePlate, StartRent = data.StartRent, EndRent = data.EndRent }; } internal static RentData ToRentData(this RentInfo info) { if (info == null) throw new NullReferenceException(nameof(info)); return new RentData() { VehicleDailyCost = info.DailyCost, VehiclePlate = info.Plate, StartRent = info.StartRent, EndRent = info.EndRent }; } internal static InvoiceInfo ToInvoiceInfo(this InvoiceData data) { if (data == null) throw new NullReferenceException(nameof(data)); return new InvoiceInfo() { Amount = data.Amount, Number = data.Number, ReleaseDate = data.ReleaseDate }; } internal static InvoiceData ToInvoiceData(this InvoicesServiceInterfaces.InvoiceInfo info) { if (info == null) throw new NullReferenceException(nameof(info)); return new InvoiceData() { Amount = info.Amount, Number = info.InvoiceNumber, ReleaseDate = info.ReleaseDate, State = info.State == InvoicesServiceInterfaces.InvoiceState.Paid ? InvoiceState.Paid : InvoiceState.NotPaid, }; } } }
Python
UTF-8
125
3.0625
3
[]
no_license
dict={1:2,3:4} print("values",list(dict.values())) print("keys:",list(dict.keys())) print("key value",(dict.get(1)))
PHP
UTF-8
2,716
2.59375
3
[]
no_license
<?php class AccountController extends Controller{ public function actions() { return array( // page action renders "static" pages stored under 'protected/views/site/pages' // They can be accessed via: index.php?r=site/page&view=FileName 'page' => array( 'class' => 'CViewAction', ), ); } //For ajax load customer public function actionLoadCustomer(){ $result = array('status' => 'Failure', 'msg' => 'No action performed'); header ('ContentType: application/json'); $data = $_POST; if (empty($data) || !isset($data['cardNumber']) || !isset($data['lastname'])) $result = array('status' => 'Failure', 'msg' => 'Invalid input value'); else{ $Account = new Account(); $accountData = $Account->model()->findAll("cardNumber = '{$data['cardNumber']}' AND lastname = '{$data['lastname']}'"); //Check if data is empty or not if (empty($accountData)) $result = array('status' => 'Failure', 'msg' => 'No Record found'); else{ $accountData = $accountData[0]; //Set the result and prepare to send back $result = array('status' => 'Success', 'account' => array('Info' => $accountData->attributes)); } } echo json_encode($result);exit(); } public function actionProfile(){ if (Yii::app()->request->isPostRequest){ $data = Yii::app()->request->getPost('data'); $account = Account::model()->findByPk(Yii::app()->user->id); if (empty($data['password'])) unset($data['password']); foreach($data as $key => $value) $account->setAttribute($key, $value); $account->setAttribute('updated', date("Y-m-d H:i:s")); if ($account->save()){ $error = false; $message = "Your profile has been updated"; } else{ $error = true; $message = "Update failed"; } $account = Account::model()->find(Yii::app()->user->id); return $this->render('profile', array('account' => $account, 'error' => $error, 'message' => $message)); } $account = Account::model()->find(Yii::app()->user->id); return $this->render('profile', array('account' => $account)); } } ?>
Markdown
UTF-8
824
2.984375
3
[]
no_license
# Client-Server Socket Programming ## How to run - Open two windows of terminal. - In one window run these commands. ``` cd server gcc -o server server.c ./server ``` - In other window run these commands. ``` cd client gcc -o client client .c ./client ``` - On client side, a `client>` prompt will appear. - Type command `get <filename1> <filename2>` (here client can ask for maximum of two files) and it will download the files from server to client. - If file is not present in server, both server and client will show the error messages. - It will also show Percentage progress on both client and server if the file is present in server. - Type command `exit` then it will close its connection with server. - If in any case other commands are typed it will give error message in both server and client.
C++
UTF-8
3,160
3.359375
3
[]
no_license
#pragma once #include "Quaternion.h" Quaternion::Quaternion(): m_w(0), m_x(0), m_y(0), m_z(0) { } Quaternion::Quaternion(double w, double x, double y, double z): m_w(w), m_x(x), m_y(y), m_z(z) { } Quaternion::Quaternion(Vector3 &V) : m_w(0), m_x(V.M_X()), m_y(V.M_Y()), m_z(V.M_Z()) { } double Quaternion::length() { return sqrt((m_w * m_w) + (m_x * m_x) + (m_y * m_y) + (m_z * m_z)); } double Quaternion::lengthSquared() { return ((m_w * m_w) + (m_x * m_x) + (m_y * m_y) + (m_z * m_z)); } Quaternion operator*(const Quaternion &leftSide, const double &s) { return Quaternion( leftSide.M_W() * s, leftSide.M_X() * s, leftSide.M_Y() * s, leftSide.M_Z() * s ); } Quaternion Quaternion::conjugate() { return Quaternion(m_w, -m_x, -m_y, -m_z); } Quaternion Quaternion::inverse() { return Quaternion( conjugate() * (1/ lengthSquared()) ); } Quaternion Quaternion::normalise() { Quaternion q(m_w, m_x, m_y, m_z); return Quaternion( q * (1/length()) ); } Vector3 Quaternion::Rotate(Vector3 &thisVector, const float &angle) { float angleRads = (float)(angle *(acos(-1) / 180)); Quaternion Q1 = normalise(); Quaternion Q2 = Quaternion((float)cos(angleRads / 2), (float)sin(angleRads / 2) * Q1.M_X(), (float)sin(angleRads / 2) * Q1.M_Y(), (float)sin(angleRads / 2) * Q1.M_Z()); Quaternion Q3 = Q2.inverse(); Quaternion Q4 = Quaternion(thisVector); Q4 = Q2 * Q4 * Q3; return Q4.convertToVector(); } Vector3 Quaternion::convertToVector() { return Vector3(m_x, m_y, m_z); } double Quaternion::M_W() const { return m_w; } double Quaternion::M_X() const { return m_x; } double Quaternion::M_Y() const { return m_y; } double Quaternion::M_Z() const { return m_z; } Quaternion::~Quaternion() { } Quaternion operator+(const Quaternion &leftSide, const Quaternion &rightSide) { return Quaternion( leftSide.M_W() + rightSide.M_W(), leftSide.M_X() + rightSide.M_X(), leftSide.M_Y() + rightSide.M_Y(), leftSide.M_Z() + rightSide.M_Z() ); } Quaternion operator-(const Quaternion &Q) { return Quaternion(-Q.m_w, -Q.m_x, -Q.m_y, -Q.m_z); } Quaternion operator*(const Quaternion &leftSide, const Quaternion &rightSide) { return Quaternion( (leftSide.M_W() * rightSide.M_W()) - (leftSide.M_X() * rightSide.M_X()) - (leftSide.M_Y() * rightSide.M_Y()) - (leftSide.M_Z() * rightSide.M_Z()), (leftSide.M_W() * rightSide.M_X()) + (leftSide.M_X() * rightSide.M_W()) + (leftSide.M_Y() * rightSide.M_Z()) - (leftSide.M_Z() * rightSide.M_Y()), (leftSide.M_W() * rightSide.M_Y()) + (leftSide.M_Y() * rightSide.M_W()) + (leftSide.M_Z() * rightSide.M_X()) - (leftSide.M_X() * rightSide.M_Z()), (leftSide.M_W() * rightSide.M_Z()) + (leftSide.M_Z() * rightSide.M_W()) + (leftSide.M_X() * rightSide.M_Y()) - (leftSide.M_Y() * rightSide.M_X()) ); } Quaternion operator*(const Quaternion &leftSide, const float &f) { return leftSide * static_cast<float>(f); } Quaternion operator-(const Quaternion &leftSide, const Quaternion &rightSide) { return Quaternion( leftSide.M_W() - rightSide.M_W(), leftSide.M_X() - rightSide.M_X(), leftSide.M_Y() - rightSide.M_Y(), leftSide.M_Z() - rightSide.M_Z() ); }
C#
UTF-8
12,859
3.25
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using Fluentatious.Extensions; namespace Fluentatious.Patterns { /// <summary> /// Implementation of <see cref="IPattern{TSubject, TResult}"/> /// </summary> /// <remarks> /// - Has a fluent interface, hence almost all public methods return 'this'. /// - In order to make things concise and minimal, even private methods do the same. /// </remarks> public class Pattern<TSubject, TResult> : IPattern<TSubject, TResult> { /// <summary> /// Subject of this pattern which is fed into predicates added by the user /// </summary> readonly TSubject subject; readonly List<Case<TSubject, TResult>> cases = new List<Case<TSubject, TResult>>(); /// <summary> /// This is assigned whenever a user adds an 'open' case, one which has a predicate but no result. An open case /// is a precursor either to a <see cref="Then"/> call or to a series of subcases. /// /// <remarks> /// An open case and its ancestors implicitly represent a stack which we're deliberately not using for performance reasons. /// </remarks> /// </summary> Case<TSubject, TResult> openCase; /// <summary> /// Is true if the caller is using explicit case syntax at the moment (i.e. SubCase/SubSubCase etc.) /// </summary> bool inExplicitCaseMode; /// <summary> /// Assigned by <see cref="WithPredicate"/> /// </summary> Func<object, bool> predicate; Pattern(TSubject subject) { this.subject = subject; } /// <summary> /// Entry point for using a Pattern /// </summary> public static IPattern<TSubject, TResult> Match(TSubject subject) { return new Pattern<TSubject, TResult>(subject); } public IPattern<TSubject, TResult> Case(Func<TSubject, bool> predicate, TResult result) { return Case(intendedLevel => AddClosedCase(predicate, result, intendedLevel)); } public IPattern<TSubject, TResult> Case(Func<TSubject, bool> predicate) { return Case(intendedLevel => AddOpenCase(predicate, intendedLevel: intendedLevel)); } public IPattern<TSubject, TResult> Case(Func<TSubject, bool> predicate, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases) { return Case(intendedLevel => AddOpenCase(predicate, subCases, intendedLevel)); } public IPattern<TSubject, TResult> Case(bool condition, TResult result) { return Case(_ => condition, result); } public IPattern<TSubject, TResult> Case(bool condition) { return Case(_ => condition); } public IPattern<TSubject, TResult> Case(bool condition, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases) { return Case(_ => condition, subCases); } public IPattern<TSubject, TResult> Case(object predicateArg, TResult result) { return Case(_ => predicate(predicateArg), result); } public IPattern<TSubject, TResult> Case(object predicateArg) { return Case((Func<TSubject, bool>) (_ => predicate(predicateArg))); } public IPattern<TSubject, TResult> Case(object predicateArg, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases) { return Case(_ => predicate(predicateArg), subCases); } public IPattern<TSubject, TResult> Default(TResult result) { return Case(true, result); } #region Explicit syntax - Sub level public IPattern<TSubject, TResult> SubCase(Func<TSubject, bool> predicate, TResult result) { return AddExplicitCase(() => AddClosedCase(predicate, result, 2)); } public IPattern<TSubject, TResult> SubCase(Func<TSubject, bool> predicate) { return AddExplicitCase(() => AddOpenCase(predicate, intendedLevel: 2)); } public IPattern<TSubject, TResult> SubCase(Func<TSubject, bool> predicate, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases) { return AddExplicitCase(() => AddOpenCase(predicate, subCases, 2)); } public IPattern<TSubject, TResult> SubCase(bool matches, TResult result) { return SubCase(_ => matches, result); } public IPattern<TSubject, TResult> SubCase(bool condition) { return SubCase(_ => condition); } public IPattern<TSubject, TResult> SubCase(bool condition, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases) { return SubCase(_ => condition, subCases); } public IPattern<TSubject, TResult> SubCase(object predicateArg, TResult result) { return SubCase(s => predicate(predicateArg), result); } public IPattern<TSubject, TResult> SubCase(object predicateArg) { return SubCase(s => predicate(predicateArg)); } public IPattern<TSubject, TResult> SubCase(object predicateArg, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases) { if (predicate == null) throw new InvalidOperationException("No predicate is set"); return SubCase(_ => predicate(predicateArg), subCases); } public IPattern<TSubject, TResult> SubDefault(TResult result) { return SubCase(true, result); } #endregion #region Explicit syntax - SubSub level public IPattern<TSubject, TResult> SubSubCase(Func<TSubject, bool> predicate, TResult result) { return AddExplicitCase(() => AddClosedCase(predicate, result, 3)); } public IPattern<TSubject, TResult> SubSubCase(Func<TSubject, bool> predicate) { return AddExplicitCase(() => AddOpenCase(predicate, intendedLevel: 3)); } public IPattern<TSubject, TResult> SubSubCase(Func<TSubject, bool> predicate, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases) { return AddExplicitCase(() => AddOpenCase(predicate, subCases, 3)); } public IPattern<TSubject, TResult> SubSubCase(bool matches, TResult result) { return SubSubCase(_ => matches, result); } public IPattern<TSubject, TResult> SubSubCase(bool condition) { return SubSubCase(_ => condition); } public IPattern<TSubject, TResult> SubSubCase(bool condition, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases) { return SubSubCase(_ => condition, subCases); } public IPattern<TSubject, TResult> SubSubCase(object predicateArg, TResult result) { return SubSubCase(_ => predicate(predicateArg), result); } public IPattern<TSubject, TResult> SubSubCase(object predicateArg) { return SubSubCase(_ => predicate(predicateArg)); } public IPattern<TSubject, TResult> SubSubCase(object predicateArg, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases) { return SubSubCase(_ => predicate(predicateArg), subCases); } public IPattern<TSubject, TResult> SubSubDefault(TResult result) { return SubSubCase(true, result); } #endregion public IPattern<TSubject, TResult> WithPredicate(Func<object, bool> predicate) { this.predicate = predicate; return this; } public IPattern<TSubject, TResult> Then(TResult result) { if (openCase == null) throw new InvalidOperationException("Syntax should be .Case(condition).Then(result)"); openCase.Result = result; // Call Break in order to close the case for which we've just provided a result return Break(); } public IPattern<TSubject, TResult> Break() { if (openCase != null) openCase = openCase.Parent; return this; } public TResult ResolveFirstOrDefault() { var matchingCase = cases.FirstOrDefault(c => c.AttemptToMatch(subject) != null); return matchingCase != null ? matchingCase.Result : default(TResult); } public TResult ResolveFirst() { var matchingCase = cases.Select(c => c.AttemptToMatch(subject)).FirstOrDefault(c => c != null); if (matchingCase == null) throw new InvalidOperationException("No case matches."); return matchingCase.Result; } /// <summary> /// Helper used by public Case methods /// </summary> Pattern<TSubject, TResult> Case(Action<int?> action) { int? intendedLevel = null; if (inExplicitCaseMode) { // We've just exited an explicit subcase (e.g. SubCase, SubDefault, SubSubCase, SubSubDefault etc.) inExplicitCaseMode = false; intendedLevel = 1; } action(intendedLevel); return this; } /// <summary> /// Helper for adding explicit sub-cases /// </summary> Pattern<TSubject, TResult> AddExplicitCase(Action action) { inExplicitCaseMode = true; action(); return this; } /// <summary> /// Helper for adding an open case (one which has a predicate but no result) /// </summary> /// <param name="intendedLevel"> /// If this isn't specified, the case will be added as a subcase of the currently open case, or at the top level if no case is open. /// </param> Pattern<TSubject, TResult> AddOpenCase(Func<TSubject, bool> predicate, Func<IPattern<TSubject, TResult>, IPattern<TSubject, TResult>> subCases = null, int? intendedLevel = null) { var newCase = new Case<TSubject, TResult>(predicate); AddCase(newCase, intendedLevel); openCase = newCase; if (subCases != null) { // Apply subCases action to a new pattern, then absorb its generated subcases new Pattern<TSubject, TResult>(subject) // FIXME: Hackiness follows .Do(p => p.WithPredicate(this.predicate)) .Pipe(subCases) .CastTo<Pattern<TSubject, TResult>>() .cases.ForEach(openCase.AddSubCase); Break(); } return this; } /// <summary> /// Helper for adding a closed case /// </summary> /// <param name="intendedLevel"> /// If this isn't specified, the case will be added as a subcase of the currently open case, or at the top level if no case is open. /// </param> Pattern<TSubject, TResult> AddClosedCase(Func<TSubject, bool> predicate, TResult result, int? intendedLevel = null) { var newCase = new Case<TSubject, TResult>(predicate, result); return AddCase(newCase, intendedLevel); } /// <summary> /// Adds a case at the appropriate level, determined by <see cref="intendedLevel"/> and the currently open case. /// Used by <see cref="AddOpenCase"/> and <see cref="AddClosedCase"/> /// </summary> /// <param name="intendedLevel"> /// If this isn't specified, the case will be added as a subcase of the currently open case, or at the top level if no case is open. /// </param> Pattern<TSubject, TResult> AddCase(Case<TSubject, TResult> newCase, int? intendedLevel = null) { // Insert breaks which are implied when transitioning between levels of explicit cases if (intendedLevel.HasValue) { while (openCase != null && openCase.Depth != (intendedLevel.Value - 1)) Break(); } if (openCase != null) openCase.AddSubCase(newCase); else cases.Add(newCase); return this; } } }
C++
UTF-8
2,164
3.125
3
[]
no_license
#include <cmath> #include <iostream> #include "flock.h" Flock::Flock() : BAMF::Actor() {} Flock::~Flock() {} void Flock::update(void) { std::vector<Zombie>::iterator iter; for (iter = m_flock.begin(); iter != m_flock.end(); ++iter) { sf::Vector2f vel = guide(*iter) + rule1(*iter) + rule2(*iter) + rule3(*iter); iter->setVelocity(vel); iter->update(); } } void Flock::render(sf::RenderWindow& target) { std::vector<Zombie>::iterator iter; for (iter = m_flock.begin(); iter != m_flock.end(); ++iter) { target.draw(*iter); } } void Flock::setFollowee(BAMF::Actor* f) { followee = f; } void Flock::add(Zombie& entity) { m_flock.push_back(entity); } const sf::Vector2f Flock::guide(Zombie& zom) { return (followee->getPosition() - zom.getPosition()) / (float)1000; } const sf::Vector2f Flock::rule1(Zombie& zom) { sf::Vector2f result; std::vector<Zombie>::iterator iter; for (iter = m_flock.begin(); iter != m_flock.end(); ++iter) { if (zom != *iter) { result += iter->getPosition(); } } result = result / (float)(m_flock.size() - 1); result = (result - zom.getPosition()) / (float)10; return result; } const sf::Vector2f Flock::rule2(Zombie& zom) { sf::Vector2f result; std::vector<Zombie>::iterator iter; for (iter = m_flock.begin(); iter != m_flock.end(); ++iter) { if (zom != *iter) { sf::Vector2f diff = zom.getPosition() - iter->getPosition(); float length = sqrt(diff.x * diff.x + diff.y * diff.y); if (length < zom.getTextureRect().width) { result = result - (diff / (float)10); } } } return result; } const sf::Vector2f Flock::rule3(Zombie& zom) { sf::Vector2f result; std::vector<Zombie>::iterator iter; for (iter = m_flock.begin(); iter != m_flock.end(); ++iter) { if (zom != *iter) { result += zom.getVelocity(); } } result = result / float(m_flock.size() - 1); result = (result - zom.getVelocity()) * (float)10;// / float(8.0); return result; }
JavaScript
UTF-8
1,468
3.25
3
[]
no_license
console.log("=====no 1 ======"); console.log("==looping up=="); var i = 2; while(i<=20){ console.log(i); i+=2; }; console.log("==looping down=="); var i = 20; while(i>2){ console.log(i); i-=2; } console.log("====soal 2 ====") var santai = " - Santai" var berkualitas = " - Berkualitas" var loveCoding = " - I Love Coding" for (i = 1; i <= 20; i++) { if (i % 2 != 1) { console.log(i + berkualitas) } else if (i % 3 == 0) { console.log(i + loveCoding) } else { console.log(i + santai) } } console.log("====soal 3 ====") var i = 1; var j = 1; var panjang = 8; var lebar = 4; var pagar = ''; while (j <= lebar) { // 9 <= 8 while (i <= panjang) { // 1 <= 4 pagar += '#'; i++; } console.log(pagar); // #### pagar = ''; // "" i = 1; // "" j++; } console.log("=====soal 4 ====") i = 1; j = 1; var alas = 7; var tinggi = 7; var pagar = ""; for (i = 1; i <= tinggi; i++) { for (j = 1; j <= i; j++) { pagar += "#"; } console.log(pagar) pagar = ""; } console.log("=====soal 5 ====") i = 1; j = 1; var panjang = 8; var lebar = 8; var papan = ""; for (j = 1; j <= lebar; j++) { if (j % 2 == 1) { for (i = 1; i <= panjang; i++) { if (i % 2 == 1) { papan += " " } else { papan += "#" } } } else { for (i = 1; i <= panjang; i++) { if (i % 2 == 1) { papan += "#" } else { papan += " " } } } console.log(papan); papan = ""; }
C#
UTF-8
1,626
2.984375
3
[ "MIT" ]
permissive
namespace SolidRpc.OpenApi.Model.CSharp.Impl { /// <summary> /// Implements a C# constructor /// </summary> public class CSharpConstructor : CSharpMember, ICSharpConstructor { /// <summary> /// Creates a new instance /// </summary> /// <param name="parent"></param> /// <param name="baseArgs"></param> /// <param name="code"></param> public CSharpConstructor(ICSharpClass parent, string baseArgs = null, string code = null) : base(parent, "<ctr>") { BaseArgs = baseArgs; Code = code; } /// <summary> /// The base arguments /// </summary> public string BaseArgs { get; } /// <summary> /// The constructor code. /// </summary> public string Code { get; } /// <summary> /// Emits the constructor to supplied writer. /// </summary> /// <param name="codeWriter"></param> public override void WriteCode(ICodeWriter codeWriter) { var baseInit = ""; if(!string.IsNullOrEmpty(BaseArgs)) { baseInit = $" : base({BaseArgs})"; } WriteSummary(codeWriter); codeWriter.Emit($"public {Parent.Name}(){baseInit}{codeWriter.NewLine}{{"); if(!string.IsNullOrEmpty(Code)) { codeWriter.Indent(); codeWriter.Emit($"{codeWriter.NewLine}{Code}{codeWriter.NewLine}"); codeWriter.Unindent(); } codeWriter.Emit($"}}"); } } }
Ruby
UTF-8
213
3.65625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array(array) squared_number = [] array.each do |number| squared_number << number**2 end squared_number end #test comment #def square_array(array) # array.collect{|number| number**2} #end
C++
UTF-8
14,501
2.859375
3
[]
no_license
#pragma once #include "SymbolNodes.h" #include "SymbolTable.h" #include <iostream> #include <set> #include <algorithm> // ======== IMPLEMENTATION OF METHODS ======== CCompileUnit::CCompileUnit(): STNode(NodeType::NT_COMPILEUNIT) {} CCompileUnit::~CCompileUnit(){} CStatements::CStatements(): STNode(NodeType::NT_STATEMENTS) {} CStatements::~CStatements() {} CStatement::CStatement(): STNode(NodeType::NT_STATEMENT) {} CStatement::~CStatement() {} CAddition::CAddition(): STNode(NodeType::NT_EXPRESSION_ADDITION) {} CAddition::~CAddition() {} CSubtraction::CSubtraction(): STNode(NodeType::NT_EXPRESSION_SUBTRACTION) {} CSubtraction::~CSubtraction() {} CMultiplication::CMultiplication(): STNode(NodeType::NT_EXPRESSION_MULTIPLICATION) {} CMultiplication::~CMultiplication() {} CDivision::CDivision(): STNode(NodeType::NT_EXPRESSION_DIVISION) {} CDivision::~CDivision() {} CAssignment::CAssignment() : STNode(NodeType::NT_EXPRESSION_ASSIGNMENT) {} CAssignment::~CAssignment() {} CNUMBER::CNUMBER(char *text): STNode(NodeType::NT_EXPRESSION_NUMBER) { // assigning nodes with name/values m_number = atoi(text); m_graphvizLabel.append("_" + std::to_string(m_number)); } CNUMBER::~CNUMBER() {} CIDENTIFIER::CIDENTIFIER(char* text) : STNode(NodeType::NT_EXPRESSION_IDENTIFIER){ m_name = (string)text; m_graphvizLabel.append("_" + m_name); // attaching name of variable // ( contructors original name is defined in STNode.cpp) } CIDENTIFIER::~CIDENTIFIER() {} void CCompileUnit::Visit_SyntaxTreePrinter(ofstream* dotFile, STNode* parent) { list<STNode*>::iterator it; // creating "main" tree .dot file if (parent == nullptr) { (*dotFile) << "digraph G{ \n"; for (it = m_children->begin(); it != m_children->end(); it++) { (*it)->Visit_SyntaxTreePrinter(dotFile, this); } (*dotFile) << "}"; dotFile->close(); } else { STNode::Visit_SyntaxTreePrinter(dotFile, this); } } void CCompileUnit::Visit_FactorizedTree(list<STNode*>* node, ofstream* factfile, STNode* parent, int common_factor, list<int> all_nums) { list<STNode*>::iterator it; // creating "factorized" tree .dot file if (parent == nullptr) { (*factfile) << "digraph G{ \n"; for (it = m_children->begin(); it != m_children->end(); it++) { (*it)->Visit_FactorizedTree(node, factfile, this, common_factor, all_nums); } (*factfile) << "}"; factfile->close(); } else { STNode::Visit_FactorizedTree(node, factfile, this, common_factor, all_nums); } } int CStatement::Visit_Eval() { list<STNode*>::iterator it; int p=0; // has two alternatives but we get the full expression which is: " expression ';' " if (m_children->size() != 0) { it = m_children->begin(); p = (*it)->Visit_Eval(); } return p; } int CAddition::Visit_Eval() { list<STNode*>::iterator it = m_children->begin(); int result = (*it)->Visit_Eval(); advance(it, 1); result += (*it)->Visit_Eval(); return result; } int CSubtraction::Visit_Eval() { list<STNode*>::iterator it = m_children->begin(); int result = (*it)->Visit_Eval(); advance(it, 1); result -= (*it)->Visit_Eval(); return result; } int CMultiplication::Visit_Eval() { list<STNode*>::iterator it = m_children->begin(); int result = (*it)->Visit_Eval(); advance(it, 1); result *= (*it)->Visit_Eval(); return result; } int CDivision::Visit_Eval() { list<STNode*>::iterator it = m_children->begin(); int result = (*it)->Visit_Eval(); advance(it, 1); result /= (*it)->Visit_Eval(); return result; } int CAssignment::Visit_Eval() { // the phrase to the left of the assignment must be calculated // and the value get assigned to SymbolTable list<STNode*>::iterator it = m_children->begin(); // we take the child and assign it to an identifier type variable // so that we can access the children of the class CIDENTIFIER* id = dynamic_cast<CIDENTIFIER*>(*it); advance(it, 1); SetValue(id->m_name, (*it)->Visit_Eval()); cout << id->m_name << "=" << GetInitValue(id->m_name) << endl; return GetInitValue(id->m_name); } int CNUMBER::Visit_Eval() { return m_number; } int CIDENTIFIER::Visit_Eval() { return GetInitValue(m_name); } list<STNode*> CStatement::SearchingAddition(list<STNode*> a) { list<STNode*>::iterator it; list<STNode*> arr; if (m_children->size() != 0) { it = m_children->begin(); arr = (*it)->SearchingAddition(a); } return arr; } list<STNode*> CAddition::SearchingAddition(list<STNode*> a) { list<STNode*>::iterator it = m_children->begin(); list<STNode*>::iterator par = m_parents ->begin(); list<STNode*>temp; a.push_back(this); temp = (*it)->SearchingAddition(a); advance(it, 1); temp = (*it)->SearchingAddition(temp); return temp; } list<STNode*> CSubtraction::SearchingAddition(list<STNode*> a) { list<STNode*>::iterator it = m_children->begin(); (*it)->SearchingAddition(a); advance(it, 1); (*it)->SearchingAddition(a); return a; } list<STNode*> CMultiplication::SearchingAddition(list<STNode*> a) { list<STNode*>::iterator it = m_children->begin(); list<STNode*>::iterator par = m_parents->begin(); list<STNode*>temp; temp = (*it)->SearchingAddition(a); advance(it, 1); temp = (*it)->SearchingAddition(a); return temp; } list<STNode*> CDivision::SearchingAddition(list<STNode*> a) { list<STNode*>::iterator it = m_children->begin(); (*it)->SearchingAddition(a); advance(it, 1); (*it)->SearchingAddition(a); return a; } list<STNode*> CAssignment::SearchingAddition(list<STNode*> a) { list<STNode*>::iterator it = m_children->begin(); CIDENTIFIER* id = dynamic_cast<CIDENTIFIER*>(*it); advance(it, 1); cout << id->m_name << "=" << GetInitValue(id->m_name) << endl; return a; } list<STNode*> CNUMBER::SearchingAddition(list<STNode*> a) { return a; } list<STNode*> CIDENTIFIER::SearchingAddition(list<STNode*> a) { return a; // just to return something } bool first_time = true; // first time puts child to the list list<STNode*> CStatement::SearchingMultiplications(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it; list<STNode*> arr; if (m_children->size() != 0) { it = m_children->begin(); arr = (*it)->SearchingMultiplications(a,b); } return arr; } list<STNode*> CAddition::SearchingMultiplications(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); list<STNode*>temp; bool found = false; for (auto const& i : a) { // checks if the addition node in which we are now, is already on our all_add list from main if (i->GetGraphvizLabel() == this->GetGraphvizLabel()) { found = true; } } if (found) { // if we are, put children on list STNode* child_1 = (this)->GetChild(0)->GetChild(1), * child_2 = (this)->GetChild(1); if (first_time) { b.push_back(child_1); b.push_back(child_2); first_time = false; } else { b.push_back(child_1); } temp = (*it)->SearchingMultiplications(a, b); advance(it, 1); temp = (*it)->SearchingMultiplications(a, temp); return temp; } else { // if we are not, go to the next node temp = (*it)->SearchingMultiplications(a, b); return temp; } } list<STNode*> CSubtraction::SearchingMultiplications(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); (*it)->SearchingMultiplications(a, b); advance(it, 1); (*it)->SearchingMultiplications(a, b); return a; } list<STNode*> CMultiplication::SearchingMultiplications(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); list<STNode*>temp; temp = (*it)->SearchingMultiplications(a, b); advance(it, 1); temp = (*it)->SearchingMultiplications(a, b); return temp; } list<STNode*> CDivision::SearchingMultiplications(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); (*it)->SearchingMultiplications(a, b); advance(it, 1); (*it)->SearchingMultiplications(a, b); return a; } list<STNode*> CAssignment::SearchingMultiplications(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); CIDENTIFIER* id = dynamic_cast<CIDENTIFIER*>(*it); advance(it, 1); cout << id->m_name << "=" << GetInitValue(id->m_name) << endl; return a; } list<STNode*> CNUMBER::SearchingMultiplications(list<STNode*> a, list<STNode*> b) { return b; } list<STNode*> CIDENTIFIER::SearchingMultiplications(list<STNode*> a, list<STNode*> b) { return a; // just to return something } list<int> CStatement::CommonFactor(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it; list<int> arr; if (m_children->size() != 0) { it = m_children->begin(); arr= (*it)->CommonFactor(a,b); } return arr; } list<int> CAddition::CommonFactor(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); list<STNode*>::iterator ed = m_children->begin(); list<int> result1, result2; int a_len = a.size(); int cnt = 0; for (auto const& i : a) { // checks if the addition node in which we are now, is already on our list with sum of products from main if (this->GetGraphvizLabel() != i->GetGraphvizLabel()) { cnt++; } } if (cnt == a_len) { // if its not, we return advance(ed, 1); list<int> last_multi = (*ed)->CommonFactor(a, b); return last_multi; } else { // if it is, we get the values from children, compare them and find the common factor result1 = (*it)->CommonFactor(a, b); advance(it, 1); result2 = (*it)->CommonFactor(a, b); std::list<int> result; std::set_intersection(result1.begin(), result1.end(), result2.begin(), result2.end(), std::back_inserter(result)); if ( !result.empty()) { // if the result of the intersection isn't empty, there is a common factor that we return return result; } else { // if it's empty, we return the merge of the two previous numbers result1.merge(result2); return result1; } } } list<int> CSubtraction::CommonFactor(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); list<int> result1, result2; result1= (*it)->CommonFactor(a, b); advance(it, 1); result2 = (*it)->CommonFactor(a, b); result1.merge(result2); return result1; } list<int> CMultiplication::CommonFactor(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); list<int> result1, result2; list<STNode*>temp; int cnt = 0; int b_len = b.size(); // checks if the multiplication node in which we are now, is already for (auto const& i : b) { // on our multiplications list from main if (this->GetGraphvizLabel() != i->GetGraphvizLabel()) { cnt++; } } if (cnt == b_len) { // if its not we go to next multiplication return result1; } else { result1 = (*it)->CommonFactor(a, b); advance(it, 1); result2 = (*it)->CommonFactor(a, b); result1.merge(result2); return result1; } } list<int> CDivision::CommonFactor(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); list<int> result1, result2; result1 = (*it)->CommonFactor(a, b); advance(it, 1); result2 = (*it)->CommonFactor(a, b); result1.merge(result2); return result1; } list<int> CAssignment::CommonFactor(list<STNode*> a, list<STNode*> b) { list<STNode*>::iterator it = m_children->begin(); CIDENTIFIER* id = dynamic_cast<CIDENTIFIER*>(*it); advance(it, 1); cout << id->m_name << "=" << GetInitValue(id->m_name) << endl; list<int> yes; // just to return something return yes; } list<int> CNUMBER::CommonFactor(list<STNode*> a, list<STNode*> b) { list<int> nai; nai.push_back(m_number); return nai; } list<int> CIDENTIFIER::CommonFactor(list<STNode*> a, list<STNode*> b) { list<int> val; // just to return something return val; } list<int> CStatement::FindingNums(list<STNode*> a, list<STNode*> b, int c) { list<STNode*>::iterator it; list<int> arr; if (m_children->size() != 0) { it = m_children->begin(); arr = (*it)->FindingNums(a,b,c); } return arr; } list<int> CAddition::FindingNums(list<STNode*> a, list<STNode*> b, int c) { list<STNode*>::iterator it = m_children->begin(); list<STNode*>::iterator ed = m_children->begin(); list<int> result1, result2; int a_len = a.size(); int cnt = 0; for (auto const& i : a) { if (this->GetGraphvizLabel() != i->GetGraphvizLabel()) { cnt++; } } if (cnt == a_len) { advance(ed, 1); list<int> last_multi = (*ed)->FindingNums(a, b, c); return last_multi; } else { result1 = (*it)->FindingNums(a, b, c); advance(it, 1); result2 = (*it)->FindingNums(a, b, c); result1.merge(result2); return result1; } } list<int> CSubtraction::FindingNums(list<STNode*> a, list<STNode*> b, int c) { list<STNode*>::iterator it = m_children->begin(); list<int> result1, result2; result1 = (*it)->FindingNums(a, b, c); advance(it, 1); result2 = (*it)->FindingNums(a, b, c); result1.merge(result2); return result1; } list<int> CMultiplication::FindingNums(list<STNode*> a, list<STNode*> b, int c) { list<STNode*>::iterator it = m_children->begin(); list<int> result1, result2; int cnt = 0; int b_len = b.size(); for (auto const& i : b) { if (this->GetGraphvizLabel() != i->GetGraphvizLabel()) { cnt++; } } if (cnt == b_len) { return result1; } else { result1 = (*it)->FindingNums(a, b,c); advance(it, 1); result2 = (*it)->FindingNums(a, b,c); bool found1 = (std::find(result1.begin(), result1.end(), c) != result1.end()); bool found2 = (std::find(result2.begin(), result2.end(), c) != result2.end()); if (!found1 && !found2) { result1.clear(); return result1; } result1.remove(c); result2.remove(c); result1.merge(result2); return result1; } } list<int> CDivision::FindingNums(list<STNode*> a, list<STNode*> b, int c) { list<STNode*>::iterator it = m_children->begin(); list<int> result1, result2; result1 = (*it)->FindingNums(a, b, c); advance(it, 1); result2 = (*it)->FindingNums(a, b, c); result1.merge(result2); return result1; } list<int> CAssignment::FindingNums(list<STNode*> a, list<STNode*> b, int c) { list<STNode*>::iterator it = m_children->begin(); CIDENTIFIER* id = dynamic_cast<CIDENTIFIER*>(*it); advance(it, 1); cout << id->m_name << "=" << GetInitValue(id->m_name) << endl; list<int> yes; return yes; } list<int> CNUMBER::FindingNums(list<STNode*> a, list<STNode*> b, int c) { list<int> nai; nai.push_back(m_number); return nai; } list<int> CIDENTIFIER::FindingNums(list<STNode*> a, list<STNode*> b, int c) { list<int> val; return val; // just to return something }
Go
UTF-8
1,605
2.59375
3
[ "MIT" ]
permissive
package server_test import ( "net/http" svcapi "github.com/dpb587/ssoca/service/uaaauth/api" . "github.com/dpb587/ssoca/service/uaaauth/server" svcconfig "github.com/dpb587/ssoca/service/uaaauth/server/config" "github.com/dpb587/ssoca/server/service" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Service", func() { var subject *Service Describe("interface", func() { It("github.com/dpb587/ssoca/server/service.AuthService", func() { var _ service.AuthService = (*Service)(nil) }) }) Context("Basics", func() { BeforeEach(func() { subject = NewService("test1", svcconfig.Config{ URL: "my-url", CACertificate: "my-certificate", PublicKey: "public-key", ClientID: "client-id", ClientSecret: "client-secret", Prompts: []string{ "one", "two", }, }) }) Describe("Name", func() { It("works", func() { Expect(subject.Name()).To(Equal("test1")) }) }) Describe("Metadata", func() { It("works", func() { Expect(subject.Metadata()).To(Equal(svcapi.Metadata{ URL: "my-url", CACertificate: "my-certificate", ClientID: "client-id", ClientSecret: "client-secret", Prompts: []string{ "one", "two", }, })) }) }) Describe("GetRoutes", func() { It("works", func() { Expect(subject.GetRoutes()).To(BeNil()) }) }) Describe("VerifyAuthorization", func() { It("works", func() { err := subject.VerifyAuthorization(http.Request{}, nil) Expect(err).ToNot(HaveOccurred()) }) }) }) })
Python
UTF-8
3,953
2.546875
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
''' This class is the framework of the web-app. It is called and run (instantiated) in app.py. ''' # import datetime import streamlit as st from apps.helpers.epw_helper import EPWHelper from apps.helpers.ui_helper import UIHelper import streamlit.components.v1 as components class MultiApp: def __init__(self): self.apps = [] # This method allows you to add features (script files) to the 'Select Feature' dropdown menu on the sidebar def add_app(self, title, file_title, func): self.apps.append({ "title": title, "file_title": file_title, "function": func }) # This method starts the web-app def run(self): st.sidebar.write('# PyClim') epw = EPWHelper() ui = UIHelper() # Display sorting/filtering functionalities epw.advanced_search() epw.map_viewer() if 'epw_valid' not in st.session_state: st.session_state['epw_valid'] = True # begin_time = datetime.datetime.now() try: # Fetch the epw dataframe and header info epw.read_epw_f(epw.file_name['file_url']) except: st.session_state['epw_valid'] = False st.error('Unable to read the selected epw file. Please select a different one.') else: st.session_state['epw_valid'] = False if epw.dataframe.empty else True # st.write(datetime.datetime.now() - begin_time) if st.session_state['epw_valid']: st.sidebar.markdown( "Latitude: "+str(epw.lat)+ " Longitude: "+str(epw.lng)+ "<br>Time Zone: "+str(epw.timezone), unsafe_allow_html=True ) st.sidebar.write("---") # Display feature selection dropdown app = st.sidebar.selectbox( 'Analysis Tools:', self.apps, format_func=lambda app: app['title'] ) # Filter dataset if applicable if (app['file_title'] == 'windrose') or (app['file_title'] == 'psychros'): epw.df_filter(app['file_title']) st.sidebar.write("---") # Run the selected feature script app_info = {'title': app['title'], 'file_title': app['file_title']} app['function'](app_info, epw, ui) # Site analytics with st.sidebar: st.write("---") if app['file_title'] != 'intro' else None st.markdown('<center><a href="https://statcounter.com/p12570505/?guest=1" target="_blank">View Visitor Stats</a></center>', unsafe_allow_html=True) components.html(""" <!-- Default Statcounter code for PyClim Web App https://share.streamlit.io/darrenrobinson/pyclimwebapp/main/app.py --> <center><script type="text/javascript"> var sc_project=12570505; var sc_invisible=0; var sc_security="a197d8ba"; var scJsHost = "https://"; document.write("<sc"+"ript type='text/javascript' src='" + scJsHost+ "statcounter.com/counter/counter.js'></"+"script>"); </script></center> <noscript><div class="statcounter"><a title="free web stats" href="https://statcounter.com/" target="_blank"><img class="statcounter" src="https://c.statcounter.com/12570505/0/a197d8ba/0/" alt="free web stats"></a></div></noscript> <!-- End of Statcounter Code --> """)
Python
UTF-8
447
3.96875
4
[]
no_license
high = 100 low = 0 while True: guess = (high + low)/2 print('Is your secret number ' + str(guess) + '?') key = str(raw_input("Enter 'h' to indicate the guess is too high." + " Enter 'l' to indicate the guess is too low." + " Enter 'c' to indicate I guessed correctly.")) if key == "c": print("Game over. Your secret number was: " + str(guess)) break elif key == "l": low = guess elif key == "h": high = guess
Shell
UTF-8
1,247
3.015625
3
[]
no_license
echo "Give tenant Name to create"; read tntname; echo "Give any description if required or press enter " read desc; keystone tenant-create --name $tntname --description $desc; echo "Give username to use this tenant"; read uname; echo "Give password for user $uname "; read upass; echo "Give e-mail address for user $uname"; read email; keystone user-create --name $uname --pass $upass --email $email; keystone user-role-add --tenant $tntname --user $uname --role _member_; echo "This is default quota for tenant $tntname "; nova quota-show --tenant $tntname; echo "----------------------"; echo "Give quota values to define for tenant"; echo "instances : " read instances; nova quota-update --instances $instances $tntname; echo "cores : " read cores; nova quota-update --cores $cores $tntname; echo "ram :" read ram; nova quota-update --ram $ram $tntname; echo "floating_ips :" read fltip; nova quota-update --floating_ips $fltip $tntname; echo "security_groups :" read secgrp; nova quota-update --security_groups $secgrp $tntname; echo "security_group_rules :" read secgrprl; nova quota-update --security_group_rules $secgrprl $tntname; echo "This is updated quota for tenant $tntname "; nova quota-show --tenant $tntname;
Java
UTF-8
1,074
2.703125
3
[ "MIT" ]
permissive
package eu.rex2go.chat2go.filter; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AdvertisementFilter extends Filter { private final Pattern ipRegex = Pattern.compile( "(\\d+\\s*\\d*\\.\\s*\\d+\\s*\\d*\\.\\s*\\d+\\s*\\d*\\.\\s*\\d+\\s*\\d*:?\\s*\\d*\\s*\\d*)" ); private final Pattern domainRegex = Pattern.compile( "([^ ]*\\.[^0-9 ]{2,4}\\b)" ); @Override public List<String> filter(String message) { ArrayList<String> ads = new ArrayList<>(); Matcher matcher = ipRegex.matcher(message); while (matcher.find()) { String ip = matcher.group(); if (isWhitelisted(ip)) continue; ads.add(ip); } matcher = domainRegex.matcher(message.toLowerCase()); while (matcher.find()) { String domain = matcher.group().replace(" ", ""); if (isWhitelisted(domain)) continue; ads.add(domain); } return ads; } }
Java
UTF-8
937
3.484375
3
[]
no_license
package apidata; import java.time.LocalDateTime; // wrapper for Local data time // In: yyyy-mm-ddThh:mm:ss // Out: yyyymmdd hhmmss public class DateTime { public static String time(LocalDateTime time) { return parseTime(time); } // converts time format from LocalDateTime to the format in the json // as data is minutely, just floor all times to 0 seconds private static String parseTime(LocalDateTime time) { return String.valueOf(time.getYear()) + pad(String.valueOf(time.getMonthValue())) + pad(String.valueOf(time.getDayOfMonth())) + " " + pad(String.valueOf(time.getHour())) + pad(String.valueOf(time.getMinute())) + "00"; } // pads string (which represents a m or d or hr or min or sec) to 2 digits private static String pad(String s) { return (s.length() == 1) ? "0" + s : s; } }
Go
UTF-8
1,738
2.59375
3
[]
no_license
package app import ( auth "github.com/koizr/go-todo-sample/auth/usecase" "github.com/koizr/go-todo-sample/common" "github.com/koizr/go-todo-sample/infra/persistent" "github.com/koizr/go-todo-sample/task/domain" "github.com/koizr/go-todo-sample/task/usecase" "github.com/labstack/echo/v4" "gorm.io/gorm" "net/http" "time" ) type dependencies interface { DB() *gorm.DB } type addTaskResponse struct { task *domain.Task } type addTaskForm struct { Subject string `json:"subject"` Description string `json:"description"` DueDate string `json:"dueDate"` } func AddTask(dependencies dependencies) func(c echo.Context) error { return func(c echo.Context) error { form := &addTaskForm{} if err := c.Bind(form); err != nil { return c.JSON(http.StatusBadRequest, common.Error{Message: err.Error()}) } user, err := auth.Authenticate(c.Get("user").(*auth.Token)) if err != nil { return c.JSON(http.StatusUnauthorized, common.Error{Message: "invalid or expired jwt"}) } dueDate, err := time.Parse(time.RFC3339, form.DueDate) if err != nil { return c.JSON(http.StatusBadRequest, common.Error{ Message: "dueDate parse error. expected dueDate format is RFC3339", }) } task, err := usecase.Add( &usecase.AddDependencies{ Tasks: &Tasks{db: dependencies.DB()}, GenerateTaskID: persistent.GenerateTaskID, }, &usecase.AddInput{ User: &domain.User{ID: user.ID}, Subject: form.Subject, Description: form.Description, DueDate: &dueDate, }, ) if err != nil { return c.JSON(http.StatusInternalServerError, common.Error{Message: "failed to add task"}) } return c.JSON(http.StatusOK, &addTaskResponse{ task: task, }) } }
C++
UTF-8
422
3.15625
3
[ "Unlicense" ]
permissive
// collisions will be between positive asteroid followed by negative class Solution { public: vector<int> asteroidCollision(vector<int>& asteroids) { bool right_found; // found first asteroid going right (positive sign) vector<int> ret; for (a : asteroids) { if (a < 0 && !right_found) { ret.push_back(a); } else if (a >) } } };
Ruby
UTF-8
2,745
2.6875
3
[ "MIT" ]
permissive
module HttpAcceptLanguage # Returns a sorted array based on user preference in sent via # the Accept-Language HTTP header. Don't think this is holy! # # Returns an empty array if the header does not contain any # parsable language code. # # Example: # # Accept-Language: en;q=0.3, nl-NL, nl-be;q=0.9, en-US;q=0.5 # # request.user_preferred_languages # # => [ 'nl-NL', 'nl-BE', 'nl', 'en-US', 'en' ] # def user_preferred_languages begin @user_preferred_languages ||= env['HTTP_ACCEPT_LANGUAGE']. scan(/\b([a-z]{2}(?:-[a-z]{2})?)(?:;q=([01](?:\.\d)?))?\s*($|,)/). sort_by {|l, pref| 1 - (pref || 1).to_f}. map! {|l,| l.downcase.sub(/-\w{2}/) { $&.upcase } } rescue # Just rescue anything if the browser messed up badly. [] end end # Returns a sorted array of language codes symbols based on user's # browser preference sent via the Accept-Language HTTP header. # # Example: # # Accept-Language: en;q=0.3, nl-NL, nl-be;q=0.9, en-US;q=0.5 # # request.user_preferred_languages # # => [ :nl, :en ] # def user_preferred_language_codes @user_preferred_language_codes ||= strip_region_from user_preferred_languages end # Sets the user languages preference, overiding the browser # def user_preferred_languages=(languages) @user_preferred_languages = languages @user_preferred_language_codes = nil end # Returns a preferred language from an array containing # language codes with regions. # # Example: # # Accept-Language: en;q=0.3, nl-NL, nl-be;q=0.9, en-US;q=0.5 # # request.preferred_language_from %w( it fr nl nl-NL ) # # => 'nl' # def preferred_language_from(array) (user_preferred_languages & array.map(&:to_s)).first end # Returns the first of the user_preferred_languages that # is included into the given array, ignoring region. # # Useful with Rails' I18n.available_locales. # # Example: # # Accept-Language: en;q=0.3, nl-NL, nl-be;q=0.9, en-US;q=0.5 # # request.compatible_language_from [:nl, :it] # # => 'nl' # def compatible_language_from(array) (user_preferred_language_codes & strip_region_from(array)).first end private def strip_region_from(languages) languages.map {|l| l.to_s.sub(/-\w{2}/, '')}.uniq end end # ActionDispatch is for Rails >= 3, Action Controller for Rails < 3 # Only the first class that matches gets the module included. if defined? Rails base = defined?(ActionDispatch) ? ActionDispatch : ActionController [:Request, :AbstractRequest, :CgiRequest].each do |c| next unless base.const_defined?(c) base.const_get(c).instance_eval { include HttpAcceptLanguage } break end end
Markdown
UTF-8
7,756
2.8125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- description: Describes level 1, level 2, batch, and filter opportunistic locks. ms.assetid: 06136348-0c08-4e9c-9c96-fd3af33cbdc0 title: Types of Opportunistic Locks ms.topic: article ms.date: 05/31/2018 --- # Types of Opportunistic Locks The opportunistic lock operations work with four types of opportunistic locks: level 1, level 2, batch, and filter. *Exclusive opportunistic locks* are level 1, batch, and filter locks. If a thread has any type of exclusive lock on a file, it cannot also have a level 2 lock on the same file. ## Level 1 Opportunistic Locks A level 1 opportunistic lock on a file allows a client to read ahead in the file and cache both read-ahead and write data from the file locally. As long as the client has sole access to a file, there is no danger to data coherency in providing a level 1 opportunistic lock. The client can request a level 1 opportunistic lock after opening a file. If no other client (or no other thread on the same client) has the file open, the server may grant the opportunistic lock. The client can then cache read and write data from the file locally. If another client has opened the file, then the server refuses the opportunistic lock and the client does no local caching. (The server may refuse the opportunistic lock for other reasons as well, such as not supporting opportunistic locks.) When the server opens a file that already has a level 1 opportunistic lock on it, the server examines the sharing state of the file before it breaks the level 1 opportunistic lock. If the server breaks the lock after this examination, the time the client with the former lock spends flushing its write cache is time the client requesting the file must wait. This time expenditure means that level 1 opportunistic locks should be avoided on files that many clients open. However, because the server checks the sharing state before it breaks the lock, in the case where the server would deny an open request due to a sharing conflict the server does not break the lock. For example, if you have opened a file, denied sharing for write operations, and obtained a level 1 lock, the server denies another client's request to open the file for writing before it even examines your lock on the file. In this instance, your opportunistic lock is not broken. For an example of how a level 1 opportunistic lock works, see Level 1 Opportunistic Lock Example. For more information on breaking opportunistic locks, see [Breaking Opportunistic Locks](breaking-opportunistic-locks.md). ## Level 2 Opportunistic Locks A level 2 opportunistic lock informs a client that there are multiple concurrent clients of a file and that none has yet modified it. This lock allows the client to perform read operations and obtain file attributes using cached or read-ahead local information, but the client must send all other requests (such as for write operations) to the server. Your application should use the level 2 opportunistic lock when you expect other applications to write to the file at random or read the file at random or sequentially. A level 2 opportunistic lock is very similar to a filter opportunistic lock. In most situations, your application should use the level 2 opportunistic lock. Only use the filter lock if you do not want open operations for reading to cause sharing-mode violations in the time span between your application's opening the file and receiving the lock. For more information, see Filter Opportunistic Locks and [Server Response to Open Requests on Locked Files](server-response-to-open-requests-on-locked-files.md). For more information on breaking opportunistic locks, see [Breaking Opportunistic Locks](breaking-opportunistic-locks.md). ## Batch Opportunistic Locks A batch opportunistic lock manipulates file openings and closings. For example, in the execution of a batch file, the batch file may be opened and closed once for each line of the file. A batch opportunistic lock opens the batch file on the server and keeps it open. As the command processor "opens" and "closes" the batch file, the network redirector intercepts the open and close commands. All the server receives are the seek and read commands. If the client is also reading ahead, the server receives a particular read request at most one time. When opening a file that already has a batch opportunistic lock, the server checks the sharing state of the file after breaking the lock. This check gives the holder of the lock a chance to complete flushing its cache and to close the file handle. An open operation attempted during the sharing check does not cause the sharing check to fail if the lock holder releases the lock. For an example of how a batch opportunistic lock works, see Batch Opportunistic Lock Example. For more information on breaking opportunistic locks, see [Breaking Opportunistic Locks](breaking-opportunistic-locks.md). ## Filter Opportunistic Locks A filter opportunistic lock locks a file so that it cannot be opened for either write or delete access. All clients must be able to share the file. Filter locks allow applications to perform nonintrusive filtering operations on file data (for example, a compiler opening source code or a cataloging program). A filter opportunistic lock differs from a level 2 opportunistic lock in that it allows open operations for reading to occur without sharing-mode violations in the time span between your application's opening the file and receiving the lock. The filter opportunistic lock is the best lock to use when it is important to allow other clients reading access. In other cases, your application should use a level 2 opportunistic lock. A filter opportunistic lock differs from a batch opportunistic lock in that it does not allow multiple openings and closings to be handled by the network redirector the way a batch opportunistic lock does. Your application should request a filter opportunistic lock on a file in three steps: 1. Use the [**CreateFile**](/windows/desktop/api/FileAPI/nf-fileapi-createfilea) function to open a handle to the file with the *DesiredAccess* parameter set to zero, indicating no access, and the *dwShareMode* parameter set to the **FILE\_SHARE\_READ** flag to allow sharing for reading. The handle obtained at this point is called the locking handle. 2. Request a lock on this handle with the [**FSCTL\_REQUEST\_FILTER\_OPLOCK**](/windows/win32/api/winioctl/ni-winioctl-fsctl_request_filter_oplock) control code. 3. When the lock is granted, use [**CreateFile**](/windows/desktop/api/FileAPI/nf-fileapi-createfilea) to open the file again with *DesiredAccess* set to the **GENERIC\_READ** flag. Set *dwShareMode* to the **FILE\_SHARE\_READ** flag to allow others to read the file while you have it open, the **FILE\_SHARE\_DELETE** flag to allow others to mark the file for deletion while you have it open, or both. The handle obtained at this point is called the read handle. Use the read handle to read from or write to the contents of the file. When opening a file that already has a filter opportunistic lock, the server breaks the lock and then checks the sharing state of the file. This check gives the client that held the former opportunistic lock a chance to abandon any cached data and acknowledge the break. An open operation attempted during this sharing check does not cause the sharing check to fail if the former lock holder releases the lock. The file system holds in abeyance the open operation until the lock's owner closes both the read handle and then the locking handle. After this is done, the other client's open request can proceed. For more information on breaking opportunistic locks, see [Breaking Opportunistic Locks](breaking-opportunistic-locks.md).    
C#
UTF-8
383
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace Capstone { public class ItemDrink : Item { public ItemDrink(string[] itemLine) : base(itemLine) { } public override string MakeSound() { string drinkSound = "Glug Glug, Yum!"; return drinkSound; } } }
Python
UTF-8
677
3.015625
3
[]
no_license
#!/usr/bin/env python with open('companiesdonttest.txt', 'r') as fin, open('db_nontesting.txt', 'w') as fout: for line in fin: cols = str(line).split('\t') category = 1 if cols[0] == 'V': category = 3 elif cols[0] == 'L': category = 4 elif cols[0] == 'M': category = 5 elif cols[0] == 'V L': category = 6 elif cols[0] == 'V M': category = 7 outline = str(category) + '\t' cols.pop(0) for col in cols: outline += col if outline.count('\n') == 0: outline += '\t' fout.write(outline)
C
UTF-8
6,071
2.78125
3
[]
no_license
// heartbeat.c // author: Christophe VG #include <string.h> #include <stdio.h> #include "../sha1/sha1.h" #include "moose/clock.h" #include "heartbeat.h" // a basic implementation of heartbeat-based neighbour availability monitoring // internal data // a heartbeat sequence counter static uint8_t heartbeat; // keep last seen time for each node static heartbeat_node_t nodes[HEARTBEAT_MAX_NODES]; static uint8_t node_count = 0; static heartbeat_node_t unknown = { .flags = HEARTBEAT_NODE_UNKNOWN }; static void dump_node(heartbeat_node_t node) { printf("<%02x %02x> seq: %d seen: %lu time: %lu diff: %li sus: %i inv: %i\n", (uint8_t)(node.address >> 8), (uint8_t)node.address, node.seq, node.seen, node.time, node.diff, (node.flags & HEARTBEAT_NODE_SUSPICIOUS) > 0, (node.flags & HEARTBEAT_NODE_INVALID_SIG) > 0); } // TODO this is a very basic implementation, we might need to implement it with // a tree or a hashtable based on the node's address static heartbeat_node_t get_node(uint16_t address) { for(uint8_t i=0; i<HEARTBEAT_MAX_NODES; i++) { if(nodes[i].address == address) { return nodes[i]; } } return unknown; } static void add_node(heartbeat_node_t node) { if(node_count < HEARTBEAT_MAX_NODES) { nodes[node_count] = node; node_count++; } else { // whoops ;-) } } static void update_node(heartbeat_node_t node) { for(uint8_t i=0; i<HEARTBEAT_MAX_NODES; i++) { if(nodes[i].address == node.address) { nodes[i] = node; return; } } // unknown node ... add it add_node(node); } time_t make_time(uint8_t *payload) { return (time_t)(payload[1]) << 24 | (time_t)(payload[2]) << 16 | (time_t)(payload[3]) << 8 | (time_t)(payload[4]); } // processes payload received information void heartbeat_receive(uint16_t address, uint8_t size, uint8_t *payload) { // quick check if packet might be a heartbeat packet, based on size // it MUST be equal to HEARTBEAT_PAYLOAD_SIZE // TODO introduce some form of magic cookie ? BEAT = 8347 ? if( size != HEARTBEAT_PAYLOAD_SIZE ) { return; } time_t now = clock_get_millis(), time = make_time(payload); long diff = time - now; heartbeat_node_t node = get_node(address); if(node.flags & HEARTBEAT_NODE_UNKNOWN) { // unknown node? -> initialize it node.address = address; node.seq = payload[0]; node.seen = now; node.time = time; node.diff = diff; node.flags = HEARTBEAT_NODE_OK; printf("TRACKING NEW NODE: "); dump_node(node); } // verify payload -> signature // create signature sha1_t sha1 = SHA1Compute((const uint8_t*)&(payload), 5); if(sha1.result == shaSuccess) { // this is a valid timestamp (well at least 4 bytes) node.flags &= ~HEARTBEAT_NODE_INVALID_SIG; // TODO: check for diff changes -> set flag ? // update statistics if(node.seq + 1 != payload[0]) { printf(">>> sequence skipped\n"); node.flags |= HEARTBEAT_NODE_SEQ_SKIP; } else { node.flags &= ~HEARTBEAT_NODE_SEQ_SKIP; } node.seq = payload[0]; node.seen = now; node.time = time; node.diff = diff; update_node(node); printf("... received heartbeat "); dump_node(node); return; } // not a valid payload. printf("!!! INVALID SIGNATURE\n"); // two possibilities: 1) not a heartbeat, 2) invalid signature // let's try to eliminate the first: if the first 4 bytes of the payload are // a timestamp and the signature is wrong, then they timestamp should be close // to the one we expect from a known node long local_time_diff = time - diff - now; if(local_time_diff < 1000 || local_time_diff > -1000) { // node's time is within range of 1 second of ours, so it's a heartbeat // with an invalid signature, mark it as such and update its information node.seen = now; node.time = time; node.diff = (node.diff + diff) / 2; node.flags |= HEARTBEAT_NODE_INVALID_SIG; update_node(node); return; } printf("===> DROPPED NO HEARTBEAT\n"); } // provides payload to send heartbeat_payload_t heartbeat_create_payload(void) { heartbeat_payload_t payload; // up the heartbeat sequence number payload.data[0] = ++heartbeat; // get the time uint32_t millis = clock_get_millis(); payload.data[1] = millis >> 24; payload.data[2] = millis >> 16; payload.data[3] = millis >> 8; payload.data[4] = millis; // TODO: a unique shared secret or something should be added here, but hey, // it's a demo ;-) // create signature sha1_t sha1 = SHA1Compute((const uint8_t*)&(payload.data), 5); if(sha1.result == shaSuccess) { // TODO: check impact of linking string.h for this memcpy // alternative: small for-loop memcpy(&payload.data[5], &sha1.hash, SHA1HashSize); } return payload; } // background processing: check if anything went wrong and do this in two steps // 1. check if node's heartbeat is late // last heartbeat's signature was invalid // 2. if any of these conditions hold, mark node as suspicious and reset flags // 3. if any of these conditions hold AND the node is suspicious -> ALERT void heartbeat_process(void) { time_t now = clock_get_millis(); for(uint8_t i=0; i<node_count; i++) { uint8_t ok = 1; if( now - nodes[i].seen > 10000 ) { printf("!!! node's heartbeat is late. last seen=%lu / now=%lu\n", nodes[i].seen, now ); ok = 0; } else if( nodes[i].flags & HEARTBEAT_NODE_INVALID_SIG ) { printf("!!! node has invalid signature\n"); ok = 0; } if( !ok ) { if(nodes[i].flags & HEARTBEAT_NODE_SUSPICIOUS) { // the node was already suspicious -> ALERT !!! printf("!!! ALERT !!! for "); } else { printf("... warning ... for "); nodes[i].flags |= HEARTBEAT_NODE_SUSPICIOUS; nodes[i].flags &= ~HEARTBEAT_NODE_INVALID_SIG; // clear it once } dump_node(nodes[i]); } } }
Java
UTF-8
2,162
2.046875
2
[ "Apache-2.0" ]
permissive
package com.hotcaffeine.dashboard.controller; import java.util.Collections; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.hotcaffeine.common.model.KeyRule; import com.hotcaffeine.common.model.KeyRuleCacher; import com.hotcaffeine.dashboard.rule.AppKeyRuleCacher; import com.hotcaffeine.dashboard.service.LeapWindowService; import com.hotcaffeine.data.metric.LeapArrayModel; import com.hotcaffeine.data.metric.LeapArrayModel.WindowWrapModel; import com.hotcaffeine.data.util.Result; import com.hotcaffeine.data.util.Status; @Controller @RequestMapping("/leap") public class LeapWindowController { @Autowired private LeapWindowService leapWindowService; @Autowired private AppKeyRuleCacher appKeyRuleCacher; @RequestMapping("/window") @ResponseBody public Result<?> window(String appName, String ruleKey, String key) { KeyRuleCacher keyRuleCacher = appKeyRuleCacher.getKeyRuleCacher(appName); if (keyRuleCacher == null) { return Result.getResult(Status.NO_RESULT); } KeyRule keyRule = keyRuleCacher.findKeyRuleByKey(ruleKey); if (keyRule == null) { return Result.getResult(Status.NO_RESULT); } String tmpKey = key; if (!keyRule.isPrefix()) { tmpKey = KeyRule.buildFullKey(ruleKey, key); } Result<LeapArrayModel> result = leapWindowService.getLeapWindow(appName, tmpKey); LeapArrayModel leapArrayModel = result.getResult(); if (leapArrayModel != null) { leapArrayModel.setSurvivalTime(leapArrayModel.getSurvivalTime() / 1000); leapArrayModel.setLiveTime(leapArrayModel.getLiveTime() / 1000); List<WindowWrapModel> list = leapArrayModel.getWindowList(); if (list != null) { Collections.sort(list); } } return result; } }
Java
UTF-8
426
2.421875
2
[]
no_license
package uk.gov.homeofficedigital.swappr.model; import static uk.gov.homeofficedigital.swappr.model.ShiftTypeLabel.*; public enum ShiftType { B1H(Early), BFH(Early), C1H(Mid), CFH(Mid), S1H(Late), T1H(Late); private final ShiftTypeLabel label; private ShiftType(ShiftTypeLabel label) { this.label = label; } public ShiftTypeLabel getLabel() { return label; } }
Python
UTF-8
885
4.40625
4
[]
no_license
#crear 20 numeros aleatorio entre el 0 y el 100 #imprimir una lista de los numeros generados #ordenados ascendentemente, primeros los pares y luego los impares #ejemplo: si los num generados sin [4,3,5,6,2] #el resulatdo sera: [2,4,6,3,5] import random lista_aleatorio = [] lista_par = [] lista_impar = [] for i in range (20): lista_aleatorio.append(random.randint(0, 100)) print (lista_aleatorio) print (lista_aleatorio) lista_aleatorio.sort() print('Orden ascendente') print (lista_aleatorio) while len(lista_aleatorio) > 0: num = lista_aleatorio.pop() if (num%2 == 0): lista_par.append(num) else: lista_impar.append(num) print ("Numeros pares: ") print (lista_par) lista_par.sort() print (lista_par, "Manera ascendente") print ("Numeros impares") print (lista_impar) lista_impar.sort() print (lista_impar, "Manera ascendente")
Markdown
UTF-8
5,612
3.453125
3
[]
no_license
三六 知念先环视了一圈,职员一共四十名左右吧。不过,相互银行与一般银行不同的地方是,前者是收款式的,所以现金交易的事务非常多。 知念逐一注视每张面孔,看不见安川,也没有田村的影子。 不过,这是意料中的事,安川当然不可能一下子就坐在总行办公室处理公事。因为是相互银行,可能先派任招揽存款的外勤工作。要是这样,反而方便请他出去。 知念走近窗口,询问其中一人: “请问,这里有没有一位安川先生?” “安川君在这里。”那男人爽直地回答。 “坐在哪儿?” 那男人转头探视了一会儿,回答说: “大概走开了,请你坐在那边等一下,他回来我马上告诉他。” 等候处也是现代化的,舒适如咖啡店。与其它机关同样备有各种杂志,也适当地点缀着花盆。若是再供应咖啡,那就和饭店一模一样了。知念取出一本杂志来看,但心思无法溶入书中。 设备如此齐全的银行,竟然将顾客的存款私下地放款收利。此刻同样坐在这里等候的主妇、普通职员、中小企业商店老板等,丝毫不知情,将他们辛苦积存的钱存放在这里。平时知念倒不觉得怎样,但真正望着这些人时,不由得涌起了阵阵愤恨不平。 一个影子落在翻开的杂志上面。 “我是安川。” 是个二十二、三岁,白白的皮肤,颇为英俊的青年。 “你是安川?那错了,我要找的人是安川信吾。” “对不起。”对方显然早就料到弄错了人,彬彬有礼地一鞠躬。 “啊,喂喂,这家银行有没有一位叫做安川信吾的行员?” “没有,姓安川的只有我一人而已。” 知念走出骏远相互银行,心里觉得很不甘愿。静冈市内的银行必分布许多分行,知念决心挨家寻找。 走了不远,看到交通警察,便走过去请教各银行的地址。警察虽然满脸讶异,仍详细地告诉了知念。 其中最近的一家是M银行分行。M银行是著名的大银行,安川或田村都不可能在这家银行才对。虽然如此,因为已经认定他们在静冈,所以一定要挨家查询。果然,没有人知道安川信吾这个名字。 再来是S银行,这也是间传统的市中银行,只是虽然著名,办公室却远不如骏远相互银行。询问的结果,与M银行相同。 接下去是骏远银行。 骏远银行和骏远相互银行,好相近的名称,可能由于骏远是好名称,所以争相使用吧。这家骏远银行的外观也相当气派。 在静冈市内奔跑之间,一天过去了。 找了家适当的旅馆,洗完澡后,感到全身疲惫不堪。也难怪,从东京搭了三小时火车,又徒步在市内寻找银行,当然感到疲倦。坐在二楼的廊外眺望静冈市衢的灯光,又想起启子。 屋角摆着旧报纸,知念随手拿起来。可能是客人看完丢弃的,是三天前的当地晚报。翻到第三版时,在中央有一则这样的标题: 《自由车男骑士自杀,蒙着眼睛在清水港跳海》 “四月四日上午七时,一主妇在清水市××石油公司码头的海边,发现与自由车一起坠海死亡的男人尸体,立刻向清水警察局报案。死者年纪约二十七、八岁,身穿西装,看似受薪职员。死亡已经十小时以上。现场为码头的岸壁,高约五公尺,下面是石板。因为海水少,尸体头部撞击石板,倒在旁边。身分不明,所辖警察局已以自杀案进行调查。” 今天是七日,所以是三天前发生的事。 在上面的报导之后,接着有个小标题:《自杀之说可靠吗?》 “关于在清水港码头坠海死亡的蒙眼男子案,其后出现目击者。据此目击者说,三日傍晚在清水码头附近看见貌似死者的男子,蒙着眼睛骑脚踏车,似乎在练习。他感到奇怪,故停步观察。据说,骑至码头旁边再回头,往返了两三次,然后取下眼罩,往相反的方向骑走。 由此看来,坠海男子在练习跳海之际,为避免恐惧而蒙住眼睛。因目击者的出现,自杀之说即可成立。此外,脚踏车号码虽属静冈,但目前当局尚在寻找其所有者。” 知念并未将这消息与安川连结,因为年龄虽然相近,此种死法却太离奇。 开车从晴海码头坠海的消息曾经听说过,但蒙着眼睛骑自由车,练习坠海自杀,却是第一次听到。 两天前的日报对于这自杀男子的事,有综合性的报导: “四日上午七时左右发现的清水港码头跳海自杀男子,经调查后,证明并非当地人。至目前为止,尚未出现认识死者的人。至于死者所骑自由车,根据车号已查明是从市内其银行前面盗取的。此车所有人为清水市××町的电器零售商,他于午后三时左右从银行出来时,发现车子遗失,立刻报警。根据以上资料推测,死者是盗取自由车骑至清水港码头,如目击者所说,‘练习’自杀后,从岸壁冲入海中。” 知念的心脏快速地跳跃着。这男子也许是安川! 安川不在静冈市内的银行,以及自杀地点在距离静冈约十二公里的清水,使他产生此种预感。 何况死者并非当地人,而是外来者。 (到清水去认尸吧。)
C++
UTF-8
1,713
2.765625
3
[]
no_license
#include "math_tools.h" #include <math.h> #include <assert.h> #include <math.h> #include <vector> #include <stdio.h> double gammaln(double x) { double y,tmp,ser; static double cof[6] = {76.18009172947146,-86.50532032941677,24.01409824083091,-1.231739572450155,0.1208650973866179e-2,-0.5395239384953e-5 }; y=x; tmp=x+5.5; tmp -= (x+0.5)*log(tmp); ser = 1.000000000190015; for (int j=0; j<=5; j++) ser+= cof[j]/++y; return -tmp+log(2.5066282746310005*ser/x); } double factln(int n) { double ret; static double a[101]; // static array is automatically initialized to zero if (n<0) { printf("gammaln function only defined for positive values"); assert(n>=0); } else if (n<=1) ret = 0; else if (n<=100) ret = a[n] ? a[n] : (a[n]=gammaln(n+1.0)); else ret = gammaln(n+1); return ret; } double bino_pdf(int k, int n, float p) { double ln_binco = factln(n)-factln(k)-factln(n-k); double ln_ret = ln_binco + k*log(p) + (n-k)*log(1-p); return exp(ln_ret); } float bino_cfd(int cnt, int num, float p) { // compute cdf float ret = 0; for (int i=0; i<=cnt; i++) ret+=bino_pdf(i, num, p); assert(ret<=1+1e-3); return ret; } template <typename T> std::vector<T> prctile(std::vector<T> vec, std::vector<float> pos) { sort(vec.begin(), vec.end()); int max_pos = ((int) vec.size())-1; std::vector<T> ret; for (unsigned int i=0; i<pos.size(); i++) { int idx1 = floor(max_pos*pos[i]); int idx2 = ceil(max_pos*pos[i]); assert(idx1>=0); assert(idx2>=0); assert(idx1<=max_pos); assert(idx2<=max_pos); ret.push_back((vec[idx1]+vec[idx2])/2); } return ret; }
C++
UTF-8
495
2.6875
3
[]
no_license
#pragma once #include <cinder/CinderGlm.h> #include <vector> class CubicSpline { public: CubicSpline() = default; CubicSpline(glm::vec3 a, glm::vec3 b, glm::vec3 c, glm::vec3 d); //evaluate the point using a cubic equation glm::vec3 getPointOnSpline(float s) const; static std::vector<CubicSpline> CalculateCubicSpline(std::vector<glm::vec3> points); private: glm::vec3 a; glm::vec3 b; glm::vec3 c; glm::vec3 d; };
Markdown
UTF-8
8,335
2.6875
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-mit-old-style", "HPND", "HPND-sell-variant", "LicenseRef-scancode-xfree86-1.0" ]
permissive
# User-configuration This page describes how to add a custom layout or option so that it will be parsed by libxkbcommon. **The below requires libxkbcommon as keymap compiler and does not work in X**. ## Data locations libxkbcommon searches the following paths for XKB configuration files: - `$XDG_CONFIG_HOME/xkb/`, or `$HOME/.config/xkb/` if the `$XDG_CONFIG_HOME` environment variable is not defined - `$HOME/.xkb/` - `$XKB_CONFIG_EXTRA_PATH` if set, otherswise `<sysconfdir>/xkb` (on most distributions this is `/etc/xkb`) - `$XKB_CONFIG_ROOT` if set, otherwise `<datadir>/X11/xkb/` (path defined by the `xkeyboard-config` package, on most distributions this is `/usr/share/X11/xkb`) A keymap created with `xkb_keymap_new_from_names()` will look up those paths in order until the required data is found. **Note: Where libxkbcommon runs in a privileged context, only the system (datadir) path is available.** Each directory should have one or more of the following subdirectories: - `compat` - `geometry` (libxkbcommon ignores this directory) - `keycodes` - `rules` - `symbols` - `types` The majority of user-specific configuration involve modifying key symbols and this is what this document focuses on. For use-cases where a user may need to add new key types or compat entries the general approach remains the same. A detailed description for how to add those types or compat entries is out of scope for this document. You should never need to add user-specific keycodes. Where a keycode is missing, the addition should be filed in the upstream xkeyboard-config project. ## RMLVO vs KcCGST Due to how XKB is configured, there is no such thing as a "layout" in XKB itself, or, indeed, any of the rules, models, variant, options (RMLVO) decribed in `struct xkb_rule_names`. RMLVO names are merely lookup keys in the rules file provided by xkeyboard-config to map to the correct keycode, compat, geometry (ignored by libxkbcommon), symbols and types (KcCGST). The KcCGST data is the one used by XKB and libxbkcommon to map keys to actual symbols. For example, a common RMLVO configuration is layout "us", variant "dvorak" and option "terminate:ctrl_alt_bksp". Using the default rules file and model this maps into the following KcCGST components: ``` xkb_keymap { xkb_keycodes { include "evdev+aliases(qwerty)" }; xkb_types { include "complete" }; xkb_compat { include "complete" }; xkb_symbols { include "pc+us(dvorak)+inet(evdev)+terminate(ctrl_alt_bksp)" }; xkb_geometry { include "pc(pc105)" }; }; ``` A detailed explanation of how rules files convert RMLVO to KcCGST is out of scope for this document. See [the rules file](md_doc_rules-format.html) page instead. ## Adding a layout Adding a layout requires that the user adds **symbols** in the correct location. The default rules files (usually `evdev`) have a catch-all to map a layout, say "foo", and a variant, say "bar", into the "bar" section in the file `$xkb_base_dir/symbols/foo`. This is sufficient to define a new keyboard layout. The example below defines the keyboard layout "banana" with an optional variant "orange" ``` $ cat $XDG_CONFIG_HOME/xkb/symbols/banana // Like a US layout but swap the top row so numbers are on Shift default partial alphanumeric_keys xkb_symbols "basic" { include "us(basic)" name[Group1]= "Banana (US)"; key <AE01> { [ exclam, 1] }; key <AE02> { [ at, 2] }; key <AE03> { [ numbersign, 3] }; key <AE04> { [ dollar, 4] }; key <AE05> { [ percent, 5] }; key <AE06> { [ asciicircum, 6] }; key <AE07> { [ ampersand, 7] }; key <AE08> { [ asterisk, 8] }; key <AE09> { [ parenleft, 9] }; key <AE10> { [ parenright, 0] }; key <AE11> { [ underscore, minus] }; key <AE12> { [ plus, equal] }; }; // Same as banana but map the euro sign to the 5 key partial alphanumeric_keys xkb_symbols "orange" { include "banana(basic)" name[Group1] = "Banana (Eurosign on 5)"; include "eurosign(5)" }; ``` The `default` section is loaded when no variant is given. The first example sections uses ``include`` to populate with a symbols list defined elsewhere (here: section `basic` from the file `symbols/us`, aka. the default US keyboard layout) and overrides parts of these symbols. The effect of this section is to swap the numbers and symbols in the top-most row (compared to the US layout) but otherwise use the US layout. The "orange" variant uses the "banana" symbols and includes a different section to define the eurosign. It does not specificially override any symbols. The exact details of how `xkb_symbols` work is out of scope for this document. ## Adding an option For technical reasons, options do **not** have a catch-all to map option names to files and sections and must be specifically mapped by the user. This requires a custom rules file. As the `evdev` ruleset is hardcoded in many clients, the custom rules file must usually be named `evdev`. ``` $ cat $XDG_CONFIG_HOME/xkb/rules/evdev ! option = symbols custom:foo = +custom(bar) custom:baz = +other(baz) ! include %S/evdev ``` This rules file maps the RMLVO option "custom:foo" to the "bar" section in the `symbols/custom` file and the "custom:baz" option to the "baz" section in the `symbols/other` file. Note how the RMLVO option name may be different to the file or section name. The `include` statement includes the system-provided `evdev` ruleset. This allows users to only override those options they need. The files themselves are similar to the layout examples in the previous section: ``` $ cat $XDG_CONFIG_HOME/xkb/symbols/custom // map the Tilde key to nothing on the first shift level partial alphanumeric_keys xkb_symbols "bar" { key <TLDE> { [ VoidSymbol ] }; }; $ cat $XDG_CONFIG_HOME/xkb/symbols/other // map first key in bottom row (Z in the US layout) to k/K partial alphanumeric_keys xkb_symbols "baz" { key <AB01> { [ k, K ] }; }; ``` With these in place, a user may select any layout/variant together with the "custom:foo" and/or "custom:baz" options. ## Discoverable layouts **The below requires libxkbregistry as XKB lookup tool and does not work where clients parse the XML file directly**. The above sections apply only to the data files and require that the user knows about the existence of the new entries. To make custom entries discoverable by the configuration tools (e.g. the GNOME Control Center), the new entries must also be added to the XML file that is parsed by libxkbregistry. In most cases, this is the `evdev.xml` file in the rules directory. The example below shows the XML file that would add the custom layout and custom options as outlined above to the XKB registry: ``` $ cat $XDG_CONFIG_HOME/xkb/rules/evdev.xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE xkbConfigRegistry SYSTEM "xkb.dtd"> <xkbConfigRegistry version="1.1"> <layoutList> <layout> <configItem> <name>banana</name> <shortDescription>ban</shortDescription> <description>Banana</description> </configItem> <variantList> <variant> <configItem> <name>orange</name> <shortDescription>or</shortDescription> <description>Orange (Banana)</description> </configItem> </variant> </variantList> </layout> </layoutList> <optionList> <group allowMultipleSelection="true"> <configItem> <name>custom</name> <description>Custom options</description> </configItem> <option> <configItem> <name>custom:foo</name> <description>Map Tilde to nothing</description> </configItem> </option> <option> <configItem> <name>custom:baz</name> <description>Map Z to K</description> </configItem> </option> </group> </optionList> </xkbConfigRegistry> ``` The default behavior of libxkbregistry ensures that the new layout and options are added to the system-provided layouts and options. For details on the XML format, see DTD in `<datadir>/X11/xkb/rules/xkb.dtd` and the system-provided XML files in `<datadir>/X11/xkb/rulies/xkb.dtd`.
Python
UTF-8
5,359
3.140625
3
[]
no_license
from textblob import TextBlob from ToolPack import tools from nltk.sentiment.vader import SentimentIntensityAnalyzer import matplotlib.pyplot as plt import matplotlib.ticker as mtick import numpy as np from collections import defaultdict class ElectionSentiment: def __init__(self): # The keywords are prodused from the summarization of the detected event in the last step of # Moutidis, I., Williams, H.T.: Utilizing complex networks for event detection in heterogeneous # high-volume newsstreams. In: International Conference on Complex Networks and Their Applications, self.top_keywords = {"Labour", "labour", "Brexit", "brexit", "Tory", "tory", "Corbyn", "corbyn", "Scotland", "scotland", "@BorisJohnson", "@jeremycorbyn", "Tories", "tories", "Boris", "boris", "#GE2019", "@UKLabour", "NHS", "#GeneralElection2019", "SNP", "@Conservatives", "conservative", "democracy", "England", "elections", "vote", "votes", "voting"} self.io_path = "PATH FOR I/O FILES" self.election_tweets = list() def filter_election_tweets(self): all_tweets = tools.load_pickle(self.io_path + "tweet_list") for tweet_tuple in all_tweets: tweet_words = tweet_tuple[0].split() if len(set(tweet_words).intersection(self.top_keywords)) > 0: self.election_tweets.append(tweet_tuple[0]) def sentiment_textblob(self): """ polarity is a float within the range [-1.0, 1.0] subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. """ tweet_polarities = list() for tweet in self.election_tweets: polarity = TextBlob(tweet).sentiment.polarity tweet_polarities.append(polarity) """ in plt.hist() when density=True it normalizes the values so that the total AREA of the bars sums up to 1 with the following line and with density=False the sum of all height sums up to 1 so we have the percentage of the population with the co responding x-axis value """ weights = np.ones_like(tweet_polarities) / float(len(tweet_polarities)) fig = plt.figure() plt.hist(tweet_polarities, 40, density=False, histtype='bar', facecolor='b', alpha=0.5, weights=weights) plt.title("Polarity frequencies of Boris Johnson election win.") fig.savefig(self.io_path + "Figures/election_polarity") plt.show() def sentiment_nltk(self): """ The compound score is computed by summing the valence scores of each word in the lexicon, adjusted according to the rules, and then normalized to be between -1 (most extreme negative) and +1 (most extreme positive). This is the most useful metric if you want a single unidimensional measure of sentiment for a given sentence. Calling it a 'normalized, weighted composite score' is accurate. It is also useful for researchers who would like to set standardized thresholds for classifying sentences as either positive, neutral, or negative. Typical threshold values (used in the literature cited on this page) are: *positive sentiment: compound score >= 0.05 *neutral sentiment: (compound score > -0.05) and (compound score < 0.05) *negative sentiment: compound score <= -0.05 The pos, neu, and neg scores are ratios for proportions of text that fall in each category (so these should all add up to be 1... or close to it with float operation). These are the most useful metrics if you want multidimensional measures of sentiment for a given sentence. """ sid = SentimentIntensityAnalyzer() tweet_polarities = list() polarity_class = defaultdict(int) for tweet in self.election_tweets: scores = sid.polarity_scores(tweet) if scores["compound"] >= 0.05: polarity_class["positive"] += 1 if scores["compound"] <= -0.05: polarity_class["negative"] += 1 if scores["compound"] < 0.05 or scores["compound"] > -0.05: polarity_class["neutral"] += 1 if scores["compound"] >= 0.05 or scores["compound"] <= -0.05: tweet_polarities.append(scores["compound"]) weights = np.ones_like(tweet_polarities) * 100 / float(len(tweet_polarities)) fig = plt.figure() plt.hist(tweet_polarities, 40, density=False, histtype='bar', facecolor='b', alpha=0.5, weights=weights) plt.title("Sentiment polarity frequencies of Boris Johnson's election.") plt.xlabel('Polarity metric') ax = fig.add_subplot(1, 1, 1) ax.yaxis.set_major_formatter(mtick.PercentFormatter()) plt.ylabel('Percentage of tweets') fig.savefig("PATH FOR FIGURE EXTRACTION") for key, value in polarity_class.items(): print(key, value) # plt.show() if __name__ == "__main__": el_sentiment = ElectionSentiment() el_sentiment.filter_election_tweets() # el_sentiment.sentiment_textblob() el_sentiment.sentiment_nltk()
Go
UTF-8
795
3.578125
4
[]
no_license
package main import "fmt" func reverse(s []byte) []byte { left := 0 right := len(s) - 1 for left < right { s[left], s[right] = s[right], s[left] left++ right-- } return s } func reverse2(s string) string { str := []rune(s) for i, j := 0, len(s)-1; i < j; i++ { str[i], str[j] = str[j], str[i] j-- } return string(str) } func reverse1(s string) string { str := []rune(s) left := 0 right := len(str) - 1 for left < right { str[left], str[right] = str[right], str[left] left++ right-- } return string(str) } func main() { fmt.Println("vim-go") s := "abc" fmt.Println(s) s1 := reverse([]byte(s)) fmt.Println(string(s1)) s2 := reverse1(s) fmt.Println(string(s2)) ss := "a你好b 世界c" fmt.Println(ss) ss1 := reverse1(ss) fmt.Println(string(ss1)) }
C++
UTF-8
1,143
3.34375
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { ListNode* turtle = head; ListNode* hare = head; ListNode* temp = head; while(hare!=NULL && hare->next!=NULL){ turtle = turtle->next; hare = hare->next->next; } // reverse from turtle to end and then compare ListNode* P = NULL; ListNode* C = turtle; ListNode* N = turtle->next; while(C!=NULL){ C->next = P; P = C; C = N; if(N!=NULL){ N = N->next; } } turtle = P; while(turtle){ if(turtle->val != temp->val){ return false; } turtle = turtle->next; temp = temp->next; } return true; } };
JavaScript
UTF-8
510
3.921875
4
[]
no_license
// --------------------------------------let-------------------------------------- let x = 1; if (x === 1) { let x = 2; console.log(x); } console.log(x); // --------------------------------------var-------------------------------------- var z = 'global'; let y = 'global'; console.log(this.z); console.log(this.y); // --------------------------------------Const-------------------------------------- const number = 0.01; try { // number = 99; } catch(err) { console.log(err); } console.log(number);
Swift
UTF-8
1,577
2.890625
3
[]
no_license
// // AppExtensions.swift // Test_Jeebley // // Created by Shibili Areekara on 30/10/18. // Copyright © 2018 Shibili Areekara. All rights reserved. // import Foundation import UIKit let imageCache = NSCache<AnyObject, AnyObject>() extension UIImageView { /// Load image from url String func loadImageFromUrl(urlString: String) { guard let url:URL = URL(string: urlString) else { return } self.loadImageFromUrl(url: url) } /// Load image from Url func loadImageFromUrl(url: URL) { image = nil if let imageFromCache = imageCache.object(forKey: url.absoluteString as AnyObject) as? UIImage { self.image = imageFromCache self.roundedCorners() return } URLSession.shared.dataTask(with: url, completionHandler: { [weak self] (data, response, error) in if error != nil { print("ImageDownload Error : \(error?.localizedDescription ?? "")") return } DispatchQueue.main.async { if let imageToCache = UIImage(data: data!) { imageCache.setObject(imageToCache, forKey: url.absoluteString as AnyObject) self?.image = imageToCache self?.roundedCorners() } } }).resume() } } private extension UIView { func roundedCorners(cRadius:CGFloat = 5.0) { self.layer.cornerRadius = cRadius layer.masksToBounds = true } }
C++
UTF-8
809
2.78125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; map<int,int>parent; map<int,int>sizes; int finds(int a) { if(parent[a]==a) return a; return finds(parent[a]); } void init(int n) { for(int i=0; i<=n; i++) { parent[i]=i; sizes[i]=1; } } void unit(int a,int b) { a=finds(a); b=finds(b); if(sizes[a]<sizes[b]) { swap(a,b); } parent[b]=a; if(sizes[a]==sizes[b]) sizes[b]++; } int main() { int n,m; cin>>n>>m; init(n); for(int i=1; i<=m; i++) { int x,y; cin>>x>>y; unit(x,y); } int s; cin>>s; for(int i=1; i<=s; i++) { int x; cin>>x; cout<<parent[x]<<" "; } return 0; }
Java
UTF-8
1,851
2.546875
3
[]
no_license
package lv.javaguru.java3.core.services.clients; import lv.javaguru.java3.core.database.ClientRepository; import lv.javaguru.java3.core.domain.Client; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) public class ClientFactoryImplTest { @Mock private ClientValidator clientValidator; @Mock private ClientRepository clientRepository; @InjectMocks private ClientFactory clientFactory = new ClientFactoryImpl(); private static final String LOGIN = "login"; private static final String PASSWORD = "password"; @Test public void createShouldInvokeValidator() { clientFactory.create(LOGIN, PASSWORD); verify(clientValidator).validate(LOGIN, PASSWORD); } @Test(expected = IllegalArgumentException.class) public void createShouldFailIfValidationFail() { doThrow(new IllegalArgumentException()) .when(clientValidator).validate(LOGIN, PASSWORD); clientFactory.create(LOGIN, PASSWORD); } @Test public void createShouldPersistClientAfterValidation() { Client client = clientFactory.create(LOGIN, PASSWORD); InOrder inOrder = inOrder(clientValidator, clientRepository); inOrder.verify(clientValidator).validate(LOGIN, PASSWORD); inOrder.verify(clientRepository).save(client); } @Test public void createShouldReturnNewClient() { Client client = clientFactory.create(LOGIN, PASSWORD); assertThat(client.getLogin(), is(LOGIN)); assertThat(client.getPassword(), is(PASSWORD)); } }