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
|
---|---|---|---|---|---|---|---|
Swift
|
UTF-8
| 3,178 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
//
// RestAPIRequest.swift
// Jarvis
//
// Created by Jianguo Wu on 2018/10/25.
// Copyright © 2018年 wujianguo. All rights reserved.
//
import Foundation
enum RestAPIError: Error {
case serverError(Int, String)
case networkError(Int, String)
case defaultError
}
protocol RestAPIResponseProtocol: Decodable {
var msg: String { get }
var code: Int { get }
var error: Error? { get }
}
struct RestAPIResponse<T: Decodable> : RestAPIResponseProtocol {
let msg: String
let code: Int
let data: T?
var error: Error? {
if code != 0 {
return RestAPIError.serverError(code, msg)
}
return nil
}
}
struct RestAPIRequest {
static func url(endpoint: String) -> URL {
if endpoint.hasPrefix("http://") || endpoint.hasPrefix("https://") {
return URL(string: endpoint)!
}
return URL(string: "https://yousir.leanapp.cn/")!.appendingPathComponent(endpoint)
}
let request: URLRequest
// init(get endpoint: String, query: [String: Any]) {
//
// }
init(post endpoint: String, query: [String: Any] = [:], body: Data) {
var components = URLComponents(string: RestAPIRequest.url(endpoint: endpoint).absoluteString)!
var queryItems = [URLQueryItem]()
for (k, v) in query {
queryItems.append(URLQueryItem(name: k, value: "\(v)"))
}
components.queryItems = queryItems
var req = URLRequest(url: components.url!)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.httpBody = body
request = req
}
@discardableResult
func response<T: Decodable>(success: ((T)->Void)?, failure: ((Error)->Void)?) -> URLSessionDataTask {
return responseData(success: { (data) in
do {
let ret = try JSONDecoder().decode(RestAPIResponse<T>.self, from: data)
DispatchQueue.main.async {
if let error = ret.error {
debugPrint(error)
failure?(error)
} else if ret.data != nil {
success?(ret.data!)
} else {
failure?(RestAPIError.defaultError)
}
}
} catch {
DispatchQueue.main.async {
debugPrint(error)
failure?(error)
}
}
}, failure: failure)
}
func responseData(success: ((Data)->Void)?, failure: ((Error)->Void)?) -> URLSessionDataTask {
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
DispatchQueue.main.async {
failure?(error)
}
} else if let data = data {
success?(data)
} else {
DispatchQueue.main.async {
failure?(RestAPIError.defaultError)
}
}
}
task.resume()
return task
}
}
|
TypeScript
|
UTF-8
| 1,339 | 3.0625 | 3 |
[] |
no_license
|
import { CharacterState, CharacterActionTypes } from "./types";
import * as types from "./constants";
const initialState: CharacterState = {
info: null,
characters: null,
loading: true,
error: false,
error_message: null
};
export function characterReducer(
state = initialState,
action: CharacterActionTypes
): CharacterState {
switch (action.type) {
case types.FETCH_CHARACTER_LIST_REQUEST:
return {
...state,
...{ loading: true, error: false }
};
case types.FETCH_CHARACTER_LIST_SUCCESS:
const { characters, ...rest } = action.payload;
return {
...state,
...rest,
...{ characters: [...(state.characters || []), ...(characters || [])] }
};
case types.FETCH_CHARACTER_DETAILS_SUCCESS:
return {
...state,
...action.payload
};
case types.FETCH_CHARACTER_ERROR:
return {
...state,
...action.payload
};
case types.IS_LOADING_CHARACTERS:
return {
...state,
...{ loading: true }
};
case types.RESET_CHARACTER_STATE:
return {
...state,
...{
info: null,
characters: null,
loading: true,
error: false,
error_message: null
}
};
default:
return state;
}
}
|
PHP
|
UTF-8
| 652 | 2.734375 | 3 |
[
"Unlicense"
] |
permissive
|
<?php
namespace BitWasp\Bitcoin\Serializer\Transaction;
use BitWasp\Bitcoin\Transaction\TransactionInterface;
use BitWasp\Buffertools\BufferInterface;
use BitWasp\Buffertools\Parser;
interface TransactionSerializerInterface
{
/**
* @param Parser $parser
* @return TransactionInterface
*/
public function fromParser(Parser $parser);
/**
* @param string|BufferInterface $data
* @return TransactionInterface
*/
public function parse($data);
/**
* @param TransactionInterface $transaction
* @return BufferInterface
*/
public function serialize(TransactionInterface $transaction);
}
|
TypeScript
|
UTF-8
| 1,781 | 2.953125 | 3 |
[] |
no_license
|
import { Bet } from './bet';
import { BetPlacedEvent } from './bet-placed-event';
import { BetResultEvent } from './bet-result-event';
export class BetList {
bets: Bet[] = [];
newBet(): Bet {
let bet = new Bet();
this.bets.unshift(bet);
return bet;
}
confirmBet(id: number, betPlacedEvent: BetPlacedEvent): boolean {
if (!betPlacedEvent) {
return false;
}
let bet = this.findBetById(id)
if (!bet) {
console.log(`bet not found. id: ${id}`);
return false;
}
bet.confirm(betPlacedEvent);
return true;
}
addResult(betResultEvent: BetResultEvent): boolean {
if (!betResultEvent) {
return false;
}
let bet = this.findBetByEventId(betResultEvent.id);
if (!bet) {
console.log('bet not found. BetResultEvent: ', betResultEvent);
return false;
}
bet.addResult(betResultEvent);
return true;
}
findBetById(id: number): Bet {
return this.bets.find(b => b.id() === id);
}
findBetByEventId(id: string): Bet {
return this.bets.find(b => b.eventId() === id);
}
addHistory(eventData: { BetPlaced: BetPlacedEvent[], BetResult: BetResultEvent[] }) {
eventData.BetPlaced.forEach(betPlacedEvent => {
let bet = this.newBet();
this.confirmBet(bet.id(), betPlacedEvent);
});
eventData.BetResult.forEach(betResultEvent => {
this.addResult(betResultEvent);
});
}
remove(id: number): boolean {
let i = this.bets.findIndex(bet => bet.id() === id);
if (i >= 0) {
this.bets.splice(i, 1);
}
return true;
}
}
|
Java
|
UTF-8
| 479 | 1.96875 | 2 |
[] |
no_license
|
package sharedclasses;
public class Constants {
public static final Integer DEFAULT_SERVER_PORT = 1337;
public static final Integer DEFAULT_SLEEP_TIME = 500;
public static final Integer DEFAULT_MAX_COUNT_CLIENTS = 20;
public static final String MESSAGE = "message";
public static final String DISCONNECT = "disconnect";
public static final String DISCONNECT_MESSAGE = " disconnected.";
public static final String CONNECT_MESSAGE = " connected.";
}
|
Java
|
UTF-8
| 501 | 2.15625 | 2 |
[] |
no_license
|
package com.dmto.response;
import com.dmto.request.Request;
/**
* Created by ankitkha on 14-Dec-15.
*/
public interface ISendReceiveResponse {
/**
* When a person from WITH_VEHICLE category has accepted request of a PEDESTRIAN.
* Server will send a response
* @param response
*/
public void sendResponse(Response response);
/**
* Response received for the request we sent
*/
public void receivedResponse(Response response);
}
|
JavaScript
|
UTF-8
| 9,969 | 3.03125 | 3 |
[] |
no_license
|
/* JpnNumText 2016.11.26
* Coded by Raymai97
* Ported from C# for modern JS
*/
/* make this usable on outdated browser */
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(key, index) {
index = index || 0;
return this.indexOf(key, index) === index;
}
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this;
}
}
/* String.replace only on 1st occurence so... */
String.prototype.Replace = function(key, newKey) {
return this.split(key).join(newKey);
}
/* JpnNumText is static */
var JpnNumText = {
/* const */
ONE_MAN : 10000, // 万
ONE_OKU : 10000 * 10000, // 億
ONE_CHO : 10000 * 10000 * 10000, // 兆
VALID_MAX_INT : (10000 * 10000 * 10000 * 1000 - 1),
/* method */
RomajiFromHira : function (hira) {
var ret = "";
hira = hira.toString();
var ltsu = false; // 促音
for (var i = 0; i < hira.length; i++)
{
// First, we think as if every Hira is separated
var ch = hira[i];
if (ch == 'っ') { ltsu = true; continue; }
var currRomaji = (
ch == ' ' ? " " :
ch == 'あ' ? "a" :
ch == 'い' ? "i" :
ch == 'う' ? "u" :
ch == 'え' ? "e" :
ch == 'お' ? "o" :
ch == 'か' ? "ka" : ch == 'が' ? "ga" :
ch == 'き' ? "ki" : ch == 'ぎ' ? "gi" :
ch == 'く' ? "ku" : ch == 'ぐ' ? "gu" :
ch == 'け' ? "ke" : ch == 'げ' ? "ge" :
ch == 'こ' ? "ko" : ch == 'ご' ? "go" :
ch == 'さ' ? "sa" : ch == 'ざ' ? "za" :
ch == 'し' ? "shi" : ch == 'じ' ? "ji" :
ch == 'す' ? "su" : ch == 'ず' ? "zu" :
ch == 'せ' ? "se" : ch == 'ぜ' ? "ze" :
ch == 'そ' ? "so" : ch == 'ぞ' ? "zo" :
ch == 'た' ? "ta" : ch == 'だ' ? "da" :
ch == 'ち' ? "chi" : ch == 'ぢ' ? "dzi" :
ch == 'つ' ? "tsu" : ch == 'づ' ? "dzu" :
ch == 'て' ? "te" : ch == 'で' ? "de" :
ch == 'と' ? "to" : ch == 'ど' ? "do" :
ch == 'な' ? "na" :
ch == 'に' ? "ni" :
ch == 'ぬ' ? "nu" :
ch == 'ね' ? "ne" :
ch == 'の' ? "no" :
ch == 'は' ? "ha" : ch == 'ば' ? "ba" : ch == 'ぱ' ? "pa" :
ch == 'ひ' ? "hi" : ch == 'び' ? "bi" : ch == 'ぴ' ? "pi" :
ch == 'ふ' ? "fu" : ch == 'ぶ' ? "bu" : ch == 'ぷ' ? "pu" :
ch == 'へ' ? "he" : ch == 'べ' ? "be" : ch == 'ぺ' ? "pe" :
ch == 'ほ' ? "ho" : ch == 'ぼ' ? "bo" : ch == 'ぽ' ? "po" :
ch == 'ま' ? "ma" :
ch == 'み' ? "mi" :
ch == 'む' ? "mu" :
ch == 'め' ? "me" :
ch == 'も' ? "mo" :
ch == 'や' ? "ya" :
ch == 'ゆ' ? "yu" :
ch == 'よ' ? "yo" :
ch == 'ら' ? "ra" :
ch == 'り' ? "ri" :
ch == 'る' ? "ru" :
ch == 'れ' ? "re" :
ch == 'ろ' ? "ro" :
ch == 'わ' ? "wa" :
ch == 'を' ? "wo" :
ch == 'ん' ? "n" : ""
);
// If next char is available, handle 'ゃ/ゅ/ょ' specifically.
if (i + 1 < hira.length)
{
var nextCh = hira[i + 1];
if (ch == 'じ')
{
currRomaji =
nextCh == 'ゃ' ? "ja" :
nextCh == 'ゅ' ? "ju" :
nextCh == 'ょ' ? "jo" : currRomaji;
}
else
{
var tail =
nextCh == 'ゃ' ? "a" :
nextCh == 'ゅ' ? "u" :
nextCh == 'ょ' ? "o" : "";
if (tail != "")
{
var mid = (currRomaji.length == 2) ? "y" : "h";
currRomaji = currRomaji[0] + mid + tail;
}
}
}
if (ltsu) // if 促音, prepend first char, like "pa" become "ppa"
{
ltsu = false;
currRomaji = currRomaji[0] + currRomaji;
}
ret += (currRomaji);
}
return ret;
},
HiraFromKanji : function (kanji, useSpace) {
var ret = "";
kanji = kanji.toString();
if (kanji.startsWith("マイナス"))
{
ret += ("まいなす");
if (useSpace) { ret += (" "); }
}
var hadDot = false, skipOnce = false;
for (var i = 0; i < kanji.length; i++)
{
// If previous round was something like "sanbyaku",
// we don't need another "hyaku", so we skip once.
if (skipOnce) { skipOnce = false; continue; }
// First, we think as if every Kanji is separated
var ch = kanji[i];
var currHira = (
ch == '点' ? "てん" :
ch == '十' ? "じゅう" :
ch == '百' ? "ひゃく" :
ch == '千' ? "せん" :
ch == '万' ? "まん" :
ch == '億' ? "おく" :
ch == '兆' ? "ちょう" :
ch == '零' ? "れい" :
ch == '一' ? "いち" :
ch == '二' ? "に" :
ch == '三' ? "さん" :
ch == '四' ? "よん" :
ch == '五' ? "ご" :
ch == '六' ? "ろく" :
ch == '七' ? "なな" :
ch == '八' ? "はち" :
ch == '九' ? "きゅう" : "");
if (ch == '点') { hadDot = true; }
// If we haven't met '点' and next char is available,
// try to merge some. For example, "san sen" become "sanzen".
if (!hadDot && i + 1 < kanji.length)
{
var mergedHira = "";
var nextCh = kanji[i + 1];
if (nextCh == '千')
{
mergedHira = (
ch == '二' ? "にせん" :
ch == '三' ? "さんぜん" :
ch == '四' ? "よんせん" :
ch == '五' ? "ごせん" :
ch == '六' ? "ろくせん" :
ch == '七' ? "ななせん" :
ch == '八' ? "はっせん" :
ch == '九' ? "きゅうせん" : "");
}
else if (nextCh == '百')
{
mergedHira = (
ch == '二' ? "にひゃく" :
ch == '三' ? "さんびゃく" :
ch == '四' ? "よんひゃく" :
ch == '五' ? "ごひゃく" :
ch == '六' ? "ろっぴゃく" :
ch == '七' ? "ななひゃく" :
ch == '八' ? "はっぴゃく" :
ch == '九' ? "きゅうひゃく" : "");
}
else if (nextCh == '十')
{
mergedHira = (
ch == '二' ? "にじゅう" :
ch == '三' ? "さんじゅう" :
ch == '四' ? "よんじゅう" :
ch == '五' ? "ごじゅう" :
ch == '六' ? "ろくじゅう" :
ch == '七' ? "ななじゅう" :
ch == '八' ? "はちじゅう" :
ch == '九' ? "きゅうじゅう" : "");
}
// If merge successfully, skip the next loop (once only)
if (mergedHira != "")
{
currHira = mergedHira;
skipOnce = true;
}
}
// If current char makes sense, append it
if (currHira != "")
{
ret += (currHira);
if (useSpace) { ret += (" "); }
}
}
return ret.trim();
},
DaijiFromKanji : function (kanji, useObsolete) {
var daiji = kanji.toString();
daiji = daiji
.Replace("一", "壹")
.Replace("二", "貳")
.Replace("三", "參")
.Replace("十", "拾");
if (useObsolete)
{
daiji = daiji
.Replace("四", "肆")
.Replace("五", "伍")
.Replace("六", "陸")
.Replace("七", "柒")
.Replace("八", "捌")
.Replace("九", "玖")
.Replace("百", "佰")
.Replace("千", "仟")
.Replace("万", "萬");
}
return daiji;
},
KanjiFrom : function (numStr) {
numStr = numStr.toString().trim();
// 'num' is for testing if number is valid, negative, non-zero
var num = parseFloat(numStr);
var nonZero = (num != 0);
var isNegative = (num < 0);
// Split string into integer and fractional part
var intStr = "";
var fracStr = "";
var iDot = numStr.indexOf('.');
if (iDot == -1) { intStr = numStr; }
else
{
intStr = numStr.substring(0, iDot);
fracStr = numStr.substring(iDot + 1);
}
var ret = "";
if (nonZero && isNegative) { ret += "マイナス "; }
// Parse 'integer' as positive 'long', and make sure no out of range
var absInt = Math.abs(parseInt(intStr));
if (absInt > this.VALID_MAX_INT)
{
throw ("Number must between " + (this.VALID_MAX_INT * -1) +
" and " + this.VALID_MAX_INT);
}
if (absInt >= this.ONE_CHO)
{
var absIntInCho = Math.floor(absInt / this.ONE_CHO);
ret += this.KanjiFrom4Digit(absIntInCho);
ret += "兆";
absInt -= absIntInCho * this.ONE_CHO;
}
if (absInt >= this.ONE_OKU)
{
var absIntInOku = Math.floor(absInt / this.ONE_OKU);
ret += this.KanjiFrom4Digit(absIntInOku);
ret += "億";
absInt -= absIntInOku * this.ONE_OKU;
}
if (absInt >= this.ONE_MAN)
{
var absIntInMan = Math.floor(absInt / this.ONE_MAN);
ret += this.KanjiFrom4Digit(absIntInMan);
ret += "万";
absInt -= absIntInMan * this.ONE_MAN;
}
// If the number is quite big, but last 4 digits of int are zero,
// don't show '零' (by not appending Kanji of 'absInt')
if (absInt > 0 || !nonZero) { ret += this.KanjiFrom4Digit(absInt); }
// If there is number after decimal point
if (fracStr.length > 0)
{
ret += "点";
for (var i = 0; i < fracStr.length; i++)
{
var ch = fracStr[i];
var digit = parseInt(ch);
ret += this.KanjiOfDigit(digit, -1);
}
}
return ret;
},
KanjiFrom4Digit : function (num) {
if (num < 0 || num > 9999)
{
throw "Number must between 0 and 9999.";
}
var ret = "";
var numStr = num.toString();
var numStrLen = numStr.length;
for (var i = 0; i < numStrLen; i++)
{
var digit = parseInt(numStr[i]);
var place = numStrLen - i - 1;
// If there are '千/百/十', omit '零'
if (num > 9 && digit == 0) { continue; }
ret += this.KanjiOfDigit(digit, place);
}
return ret;
},
KanjiOfDigit : function (digit, place) {
if (digit < 0 || digit > 9)
{
throw "Digit must between 0 and 9.";
}
var ret =
digit == 0 ? "零" :
digit == 1 ? "一" :
digit == 2 ? "二" :
digit == 3 ? "三" :
digit == 4 ? "四" :
digit == 5 ? "五" :
digit == 6 ? "六" :
digit == 7 ? "七" :
digit == 8 ? "八" :
digit == 9 ? "九" : "";
// If '十/百/千', omit '零/一'.
if (place > 0 && digit <= 1) { ret = ""; }
ret +=
place == 1 ? "十" :
place == 2 ? "百" :
place == 3 ? "千" : "";
return ret;
}
}
|
Python
|
UTF-8
| 1,575 | 2.609375 | 3 |
[
"Apache-2.0"
] |
permissive
|
from selenium.webdriver.common.by import By
class SessionHelper:
def __init__(self, app):
self.app = app
def login(self, username, password):
browser = self.app.browser
self.app.open_home_page()
browser.find_element(By.NAME, "username").clear()
browser.find_element(By.NAME, "username").send_keys(username)
browser.find_element(By.NAME, "password").clear()
browser.find_element(By.NAME, "password").send_keys(password)
browser.find_element(By.XPATH, "//input[@value='Login']").click()
def logout(self):
browser = self.app.browser
browser.find_element(By.LINK_TEXT, "Logout").click()
browser.find_element(By.NAME, "username")
def ensure_logout(self):
browser = self.app.browser
if self.is_logged_in():
self.logout()
def ensure_login(self, username, password):
browser = self.app.browser
if len(browser.find_elements(By.LINK_TEXT, "Logout")) > 0:
if self.is_logged_in_as(username):
return
else:
self.logout()
self.login(username, password)
def is_logged_in(self):
browser = self.app.browser
return len(browser.find_elements(By.LINK_TEXT, "Logout")) > 0
def is_logged_in_as(self, username):
browser = self.app.browser
return self.get_logged_user() == username
def get_logged_user(self):
browser = self.app.browser
return browser.find_element(By.CSS_SELECTOR, "td.login-info-left span").text
|
C++
|
UTF-8
| 9,055 | 3.140625 | 3 |
[] |
no_license
|
#include <algorithm>
#include <set>
#include <string>
#include <vector>
#include "bitvec.hpp"
#include "gtest/gtest.h"
using namespace std;
string binstring(uint64_t value, size_t len) {
string res;
do {
uint64_t rem = value % 2;
char ch = (rem == 0) ? '0' : '1';
res.push_back(ch);
value /= 2;
} while (value > 0);
return res;
}
const size_t set1[] = { 0, 7, 8, 21, 33, 50, 78, 99 };
const size_t set2[] = { 0, 7, 9, 12, 33, 44, 62, 98 };
const size_t n = sizeof(set1) / sizeof(*set1);
TEST(Bitvec, ConstructorSmall) {
size_t len = 5;
Bitvec bitvec(len);
string resvec(len, '0');
//cout << "bitvec: " << bitvec.to_string() << endl;
//cout << "resvec: " << resvec << endl;
ASSERT_EQ(bitvec.size(), len);
ASSERT_EQ(bitvec.to_string(), resvec);
}
TEST(Bitvec, ConstructorLong) {
size_t len = 1000;
Bitvec bitvec(len);
string resvec(len, '0');
//cout << "bitvec: " << bitvec.to_string() << endl;
//cout << "resvec: " << resvec << endl;
ASSERT_EQ(bitvec.size(), len);
ASSERT_EQ(bitvec.to_string(), resvec);
}
TEST(Bitvec, BitAccess) {
size_t len = 1000;
set<size_t> active(&set1[0], &set1[n]);
Bitvec bitvec(len);
for (set<size_t>::const_iterator it = active.begin(); it != active.end(); ++it) {
bitvec.set_bit(*it);
}
for (size_t i = 0; i < bitvec.size(); ++i) {
uint64_t res = bitvec.get_bit(i);
if (active.find(i) != active.end())
ASSERT_EQ(res, 1);
else
ASSERT_EQ(res, 0);
}
for (set<size_t>::const_iterator it = active.begin(); it != active.end(); ++it) {
bitvec.unset_bit(*it);
}
for (size_t i = 0; i < bitvec.size(); ++i) {
uint64_t res = bitvec.get_bit(i);
ASSERT_EQ(res, 0);
}
}
TEST(Bitvec, InplaceLShift) {
size_t len = 1000;
set<size_t> active(&set1[0], &set1[n]);
Bitvec bitvec(len);
for (set<size_t>::const_iterator it = active.begin(); it != active.end(); ++it) {
bitvec.set_bit(*it);
}
size_t wid = 28;
//cout << "bitvec: " << bitvec.to_string() << endl;
bitvec <<= wid;
//cout << "bitvec: " << bitvec.to_string() << " (after left shift)" << endl;
for (size_t i = 0; i < bitvec.size(); ++i) {
uint64_t res = bitvec.get_bit(i);
if (active.find(i - wid) != active.end())
ASSERT_EQ(res, 1);
else
ASSERT_EQ(res, 0);
}
}
TEST(Bitvec, InplaceRShift) {
size_t len = 1000;
set<size_t> active(&set1[0], &set1[n]);
Bitvec bitvec(len);
for (set<size_t>::const_iterator it = active.begin(); it != active.end(); ++it) {
bitvec.set_bit(*it);
}
size_t wid = 37;
//cout << "bitvec: " << bitvec.to_string() << endl;
bitvec >>= wid;
//cout << "bitvec: " << bitvec.to_string() << " (after right shift)" << endl;
for (size_t i = 0; i < bitvec.size(); ++i) {
uint64_t res = bitvec.get_bit(i);
if (active.find(i + wid) != active.end())
ASSERT_EQ(res, 1);
else
ASSERT_EQ(res, 0);
}
}
TEST(Bitvec, InplaceNOT) {
size_t len = 1000;
set<size_t> active(&set1[0], &set1[n]);
Bitvec bitvec(len);
for (set<size_t>::const_iterator it = active.begin(); it != active.end(); ++it) {
bitvec.set_bit(*it);
}
//cout << "bitvec: " << bitvec.to_string() << endl;
~bitvec;
//cout << "bitvec: " << bitvec.to_string() << " (after inplace not)" << endl;
for (size_t i = 0; i < bitvec.size(); ++i) {
uint64_t res = bitvec.get_bit(i);
if (active.find(i) != active.end())
ASSERT_EQ(res, 0);
else
ASSERT_EQ(res, 1);
}
}
TEST(Bitvec, InplaceAND) {
size_t len = 1000;
Bitvec bitvec1(len);
set<size_t> active1(&set1[0], &set1[n]);
for (set<size_t>::const_iterator it = active1.begin(); it != active1.end(); ++it) {
bitvec1.set_bit(*it);
}
Bitvec bitvec2(len);
set<size_t> active2(&set2[0], &set2[n]);
for (set<size_t>::const_iterator it = active2.begin(); it != active2.end(); ++it) {
bitvec2.set_bit(*it);
}
//cout << "bitvec1: " << bitvec1.to_string() << endl;
//cout << "bitvec2: " << bitvec2.to_string() << endl;
bitvec1 &= bitvec2;
//cout << "bitvec1: " << bitvec1.to_string() << " (after inplace and)" << endl;
// bitvec1 is changed.
for (size_t i = 0; i < bitvec1.size(); ++i) {
uint64_t res = bitvec1.get_bit(i);
if ((active1.find(i) != active1.end()) && (active2.find(i) != active2.end()))
ASSERT_EQ(res, 1);
else
ASSERT_EQ(res, 0);
}
// bitvec2 is NOT changed.
for (size_t i = 0; i < bitvec2.size(); ++i) {
uint64_t res = bitvec2.get_bit(i);
if (active2.find(i) != active2.end())
ASSERT_EQ(res, 1);
else
ASSERT_EQ(res, 0);
}
}
TEST(Bitvec, InplaceOR) {
size_t len = 1000;
Bitvec bitvec1(len);
set<size_t> active1(&set1[0], &set1[n]);
for (set<size_t>::const_iterator it = active1.begin(); it != active1.end(); ++it) {
bitvec1.set_bit(*it);
}
Bitvec bitvec2(len);
set<size_t> active2(&set2[0], &set2[n]);
for (set<size_t>::const_iterator it = active2.begin(); it != active2.end(); ++it) {
bitvec2.set_bit(*it);
}
//cout << "bitvec1: " << bitvec1.to_string() << endl;
//cout << "bitvec2: " << bitvec2.to_string() << endl;
bitvec1 |= bitvec2;
//cout << "bitvec1: " << bitvec1.to_string() << " (after inplace or)" << endl;
// bitvec1 is changed.
for (size_t i = 0; i < bitvec1.size(); ++i) {
uint64_t res = bitvec1.get_bit(i);
if ((active1.find(i) != active1.end()) || (active2.find(i) != active2.end()))
ASSERT_EQ(res, 1);
else
ASSERT_EQ(res, 0);
}
// bitvec2 is NOT changed.
for (size_t i = 0; i < bitvec2.size(); ++i) {
uint64_t res = bitvec2.get_bit(i);
if (active2.find(i) != active2.end())
ASSERT_EQ(res, 1);
else
ASSERT_EQ(res, 0);
}
}
TEST(Bitvec, InplaceXOR) {
size_t len = 1000;
Bitvec bitvec1(len);
set<size_t> active1(&set1[0], &set1[n]);
for (set<size_t>::const_iterator it = active1.begin(); it != active1.end(); ++it) {
bitvec1.set_bit(*it);
}
Bitvec bitvec2(len);
set<size_t> active2(&set2[0], &set2[n]);
for (set<size_t>::const_iterator it = active2.begin(); it != active2.end(); ++it) {
bitvec2.set_bit(*it);
}
//cout << "bitvec1: " << bitvec1.to_string() << endl;
//cout << "bitvec2: " << bitvec2.to_string() << endl;
bitvec1 ^= bitvec2;
//cout << "bitvec1: " << bitvec1.to_string() << " (after inplace xor)" << endl;
// bitvec1 is changed.
for (size_t i = 0; i < bitvec1.size(); ++i) {
uint64_t res = bitvec1.get_bit(i);
if (((active1.find(i) != active1.end()) && (active2.find(i) == active2.end())) ||
((active1.find(i) == active1.end()) && (active2.find(i) != active2.end())))
ASSERT_EQ(res, 1);
else
ASSERT_EQ(res, 0);
}
// bitvec2 is NOT changed.
for (size_t i = 0; i < bitvec2.size(); ++i) {
uint64_t res = bitvec2.get_bit(i);
if (active2.find(i) != active2.end())
ASSERT_EQ(res, 1);
else
ASSERT_EQ(res, 0);
}
}
TEST(Bitvec, InplaceADD) {
size_t len = 1000;
uint64_t val1 = 9758613597ULL;
string binstring1 = binstring(val1, len);
Bitvec bitvec1(len);
for (size_t i = 0; i < binstring1.size(); ++i) {
if (binstring1[i] == '1') bitvec1.set_bit(i);
}
uint64_t val2 = 4799104567ULL;
string binstring2 = binstring(val2, len);
Bitvec bitvec2(len);
for (size_t i = 0; i < binstring2.size(); ++i) {
if (binstring2[i] == '1') bitvec2.set_bit(i);
}
uint64_t val3 = val1 + val2;
string binstring3 = binstring(val3, len);
Bitvec bitvec3(len);
for (size_t i = 0; i < binstring3.size(); ++i) {
if (binstring3[i] == '1') bitvec3.set_bit(i);
}
//cout << "bitvec1: " << bitvec1.to_string() << endl;
//cout << "bitvec2: " << bitvec2.to_string() << endl;
bitvec1 += bitvec2;
//cout << "bitvec1: " << bitvec1.to_string() << " (after inplace add)" << endl;
// bitvec1 is changed.
for (size_t i = 0; i < bitvec1.size(); ++i) {
uint64_t res1 = bitvec1.get_bit(i);
uint64_t res3 = bitvec3.get_bit(i);
ASSERT_EQ(res1, res3);
}
}
TEST(Bitvec, InplaceSUB) {
size_t len = 1000;
uint64_t val1 = 9758613597ULL;
string binstring1 = binstring(val1, len);
Bitvec bitvec1(len);
for (size_t i = 0; i < binstring1.size(); ++i) {
if (binstring1[i] == '1') bitvec1.set_bit(i);
}
uint64_t val2 = 4799104567ULL;
string binstring2 = binstring(val2, len);
Bitvec bitvec2(len);
for (size_t i = 0; i < binstring2.size(); ++i) {
if (binstring2[i] == '1') bitvec2.set_bit(i);
}
uint64_t val3 = val1 - val2;
string binstring3 = binstring(val3, len);
Bitvec bitvec3(len);
for (size_t i = 0; i < binstring3.size(); ++i) {
if (binstring3[i] == '1') bitvec3.set_bit(i);
}
//cout << "bitvec1: " << bitvec1.to_string() << endl;
//cout << "bitvec2: " << bitvec2.to_string() << endl;
bitvec1 -= bitvec2;
//cout << "bitvec1: " << bitvec1.to_string() << " (after inplace add)" << endl;
// bitvec1 is changed.
for (size_t i = 0; i < bitvec1.size(); ++i) {
uint64_t res1 = bitvec1.get_bit(i);
uint64_t res3 = bitvec3.get_bit(i);
ASSERT_EQ(res1, res3);
}
}
|
Java
|
UTF-8
| 492 | 2.21875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.concordion.ext.selenium;
import org.concordion.ext.translator.MessageTranslator;
public final class SeleniumExceptionMessageTranslator implements MessageTranslator {
@Override
public String translate(String originalMessage) {
int webDriverDebugInfoStart = originalMessage.indexOf("Build info:");
if (webDriverDebugInfoStart > 0) {
return originalMessage.substring(0, webDriverDebugInfoStart);
}
return originalMessage;
}
}
|
Shell
|
UTF-8
| 106 | 2.640625 | 3 |
[] |
no_license
|
#!/bin/bash
# Ankit Hriday
username=$1
password=$2
echo "Username is $username"
echo "Password is $password"
|
C#
|
UTF-8
| 3,734 | 3.53125 | 4 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task03
{
class TableBuilder
{
private const int defaultLength = 40;
public static void BuildBy2DArr<T>(T[,] arr)
{
int maxArrLength = arr.GetLength(0);
int maxElementLength = GetMaxElement(arr);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.GetLength(0); i++)
{
sb.AppendFormat("{0}\n", new String('-', maxArrLength * maxElementLength + maxArrLength));
for (int j = 0; j < arr.GetLength(1); j++)
{
try
{
sb.AppendFormat("|{0," + maxElementLength + "}|", IfOutCut(arr[i, j]));
}
catch (IndexOutOfRangeException)
{
sb.AppendFormat("|{0," + maxElementLength + "}|", "-");
}
}
sb.AppendFormat("\n{0}\n", new String('-', maxArrLength * maxElementLength + maxArrLength));
}
Console.Write(sb);
}
public static void BuildByJaggedArr<T>(T[][] arr)
{
int maxArrLength = GetMaxRange(arr);
int maxElementLength = GetMaxElement(arr);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.GetLength(0); i++)
{
sb.AppendFormat("{0}\n", new String('-', maxArrLength * maxElementLength + maxArrLength * 2));
for (int j = 0; j < maxArrLength; j++)
{
try
{
sb.AppendFormat("|{0," + maxElementLength + "}|", IfOutCut(arr[i][j]));
}
catch (IndexOutOfRangeException)
{
sb.AppendFormat("|{0," + maxElementLength + "}|", "-");
}
}
sb.AppendFormat("\n{0}\n", new String('-', maxArrLength * maxElementLength + maxArrLength * 2));
}
Console.Write(sb);
}
public static int GetMaxRange<T>(T[][] arr)
{
int maxLength = 0;
for (int i = 0; i < arr.GetLength(0); i++)
{
if (arr[i].Length > maxLength)
{
maxLength = arr[i].Length;
}
}
return maxLength;
}
public static int GetMaxElement<T>(T[][] arr)
{
int maxLength = 0;
foreach (T[] t in arr)
foreach (T k in t)
if (k.ToString().Length > maxLength)
{
maxLength = k.ToString().Length;
}
return maxLength > defaultLength ? defaultLength : maxLength;
}
public static int GetMaxElement<T>(T[,] arr)
{
int maxLength = 0;
foreach (T t in arr)
if (t.ToString().Length > maxLength)
{
maxLength = t.ToString().Length;
}
return maxLength;
}
public static string IfOutCut<T>(T t)
{
return IfOutCut(t, defaultLength);
}
public static string IfOutCut<T>(T t, int lineLength)
{
string str = t.ToString();
if (str.Length >= lineLength)
{
return str.Substring(0, defaultLength - 3) + "...";
}
else
{
return str;
}
}
}
}
|
Markdown
|
UTF-8
| 1,385 | 2.8125 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
# `zed` Python Package
The `zed` Python package provides a client for the REST API served by
[`zed lake serve`](../../cmd/zed/lake#serve).
## Installation
Install the latest version like this:
```sh
pip3 install "git+https://github.com/brimdata/zed#subdirectory=python/zed"
```
Install the version compatible with a local `zed` like this:
```sh
pip install "git+https://github.com/brimdata/zed@$(zed -version | cut -d ' ' -f 2)#subdirectory=python/zed"
```
## Example
Run a Zed lake service from your shell.
```sh
mkdir scratch
zed lake serve -R scratch
```
> Or you can launch the Brim app and it will run a Zed lake service
> on the default port at localhost:9867.
Then, from Python, create a pool, load some data, and query it.
```python
import zed
# Connect to the REST API at the default base URL (http://127.0.0.1:9867).
# To use a different base URL, supply it as an argument.
client = zed.Client()
c.create_pool('TestPool')
# Load some ZSON records from a string. A file-like object also works.
# Data format is detected automatically and can be JSON, NDJSON, Zeek TSV,
# ZJSON, ZNG, or ZSON.
c.load('TestPool', '{s:"hello"} {s:"world"}')
# Begin executing a Zed query for all records in TestPool.
# This returns an iterator, not a container.
records = client.query('from TestPool'):
# Stream records from the server.
for record in records:
print(record)
```
|
Markdown
|
UTF-8
| 14,419 | 2.78125 | 3 |
[] |
no_license
|
<p data-nodeid="3032" class="">你好,我是莫敏。自 2006 年开始接触敏捷,到 2010 年参与组织每年一届的敏捷大会,再到 2012 年加入腾讯先后从事项目管理和产品管理工作,可以说从过去到现在,我一直身处敏捷实践的前线,对于敏捷理论如何有效地在公司落地有切实的体会和认识。</p>
<p data-nodeid="3033">而无论是在腾讯帮助游戏工作室、游戏研发部与安全中心进行效率提升,还是后来通过敏捷导入工作帮助上百家企业(如腾讯、平安、华润)的产研团队完成业绩和效率的双向提升,这些经历都让我发现:<strong data-nodeid="3098">只要你工作中涉及协作,就一定需要项目管理能力,而敏捷在当下具有天然优势</strong> 。</p>
<p data-nodeid="3034">而工作中我看到,仍然有很多人并未真正认识到敏捷的价值所在,不知道敏捷可以在很多地方帮到我们,并被一些能由敏捷轻松解决的问题困扰着,比如:</p>
<ul data-nodeid="3035">
<li data-nodeid="3036">
<p data-nodeid="3037">你虽然每天都在加班,似乎有干不完的活,却很难达到公司给设定的目标;</p>
</li>
<li data-nodeid="3038">
<p data-nodeid="3039">你的团队虽然投入大量营销费用,但业务却停滞甚至下滑,业务数据总不见明显上升;</p>
</li>
<li data-nodeid="3040">
<p data-nodeid="3041">你们的公司产品,用户满意度不高,问题被归咎于产品经理,但是产品经理进行了培训也没有多大起色。</p>
</li>
</ul>
<p data-nodeid="3042">而这些,其实是可以通过敏捷方法解决的。</p>
<h3 data-nodeid="3043">互联网时代的超级管理术</h3>
<p data-nodeid="3044">敏捷项目管理中的“价值驱动”和“快速试错”思维,特别符合当下的互联网业务,也正是基于这点,敏捷在国内最早为 BAT 公司所采纳,并在更多互联网公司中生根发芽,逐渐成为互联网超级管理术。</p>
<p data-nodeid="3045">腾讯就职期间,我曾作为欢乐斗地主的项目经理,带领团队运用敏捷的核心思想“价值驱动”和“快速试错”,实现了这款手游从 0 到 1 的突破,并且获得了腾讯五星游戏、棋牌游戏突破奖的殊荣,可以说,欢乐斗地主能够成为中国棋牌游戏中的常青树,这与我将敏捷导入团队不无关系。</p>
<p data-nodeid="3046">后来,我帮助一家互联网金融公司做敏捷导入,当时他们的产品功能和竞品差异不大,在市场上没有明显亮点,虽然投入了很多广告费用但销售数据仍然乏力,产品负责人对此非常困惑。于是依据敏捷思想,我首先成立了用户体验组,专门针对用户体验进行研究和打磨;然后成立跨职能团队,攻坚用户需求,每周一个版本,快速验证用户需求;需求一旦被验证,便让营销市场配合提炼亮点进行推广。最终,这款产品营收翻了 3 倍。</p>
<p data-nodeid="3047">这并不是个案,很多互联网公司都面对着这样的问题,<strong data-nodeid="3113">不懂用户、不了解用户需求,在一味地搞规模、推扩张的过程中使获取用户的成本越来越高,但是公司收入却没有明显增长,结果就是公司规模大了,却并不盈利</strong>。</p>
<p data-nodeid="3048">因此,越来越多的管理者注意到了敏捷项目管理方法,越来越多的企业(包括网易、京东、迅雷、新浪、滴滴、唯品会、招商银行等)不断以敏捷思维去运营公司,并引入敏捷课程作为项目管理必修课。</p>
<p data-nodeid="3049">而要为公司导入敏捷,这就要求你<strong data-nodeid="3119">必须了解敏捷项目管理方法,尤其是实践方式和技巧。</strong></p>
<p data-nodeid="3050">这些年里,我见证了腾讯从 PC 到移动时代的转变,也见证了敏捷的发展,从互联网行业到传统行业通过导入敏捷方法完成蜕变。我的从业经历,让我可以更好地来帮助你从敏捷实践中受益。在这个课程中,我希望把敏捷的理念推广给更多人,用腾讯的故事来带你建立对敏捷的知识体系,<strong data-nodeid="3124">用真实的案例帮助你在工作当中落地实践,最后达成公司和个人的双赢结果。</strong></p>
<h3 data-nodeid="3051">我怎么帮你学习敏捷项目管理呢</h3>
<p data-nodeid="3052">理论是学习时翻阅的字典,真正的掌握寓于实践。</p>
<p data-nodeid="3053">我刚开始拥抱“敏捷”也曾踌躇满志,感觉收获满满,但是一落到公司里就不行了,比如敏捷所倡导的“自组织管理”让项目经理完全不敢在项目进行时请假,生怕项目突然出问题被领导怪罪,一个小团队中实践都不行,更不要说放手让整个大团队来“自组织”了。</p>
<p data-nodeid="3054">这个问题一度让我很是头疼,于是向领导要方法,向很多“大神”取经,后来我才知道原来自组织团队需要一个循序渐进的过程。我们要先帮团队理清楚团队目标,再教团队解决问题的方法,在适当的地方做出引导,锻炼团队解决问题的能力,才可慢慢放手让团队自组织。</p>
<p data-nodeid="3055">所以,<strong data-nodeid="3134">理论是一回事,如何把理论变成可落地的实践又是另一回事</strong>。而很多人做不好敏捷,无法在公司实践业务中发挥敏捷的效用,一个很大的原因就在于敏捷多是一些抽象的概念(比如MVP、TDD),不好消化吸收,这也是我将截取腾讯的真实案例,以及提炼我的实践落地过程渐进式带你走进敏捷项目管理的一个原因,希望给你最一线的借鉴经验。</p>
<p data-nodeid="3056">课程主要分为 3 部分,共 11 讲:</p>
<ul data-nodeid="3057">
<li data-nodeid="3058">
<p data-nodeid="3059">认知篇:带你探究腾讯的敏捷历程,通过剖析腾讯内部敏捷案例如欢乐斗地主如何从 PC 端转手游,来分析腾讯到底具有怎样的敏捷基因。这个模块还会帮你了解敏捷的方法(比如 Scrum 、DSDM 等),从起源到理论框架来带你系统化地理解敏捷。</p>
</li>
<li data-nodeid="3060">
<p data-nodeid="3061">实战篇:帮你解决一系列的敏捷导入问题。比如,公司是否适合做敏捷导入、如何找到适合公司的敏捷方法、如何让团队具备敏捷思维、如何让团队自组织、如何做好敏捷的实践落地。</p>
</li>
<li data-nodeid="3062">
<p data-nodeid="3063">提高篇:聚焦敏捷导入者常见问题的解决方案,比如敏捷团队的绩效度量怎么做、如何说服领导从0到1导入敏捷,帮你解决敏捷导入过程中的“形而上学”和“无法落地”的问题。</p>
</li>
</ul>
<p data-nodeid="3064">课程最后还有一个<strong data-nodeid="3144">彩蛋</strong>,我会为你分享ACP认证攻略,希望为你的个人发展提供更高阶的方向指引,让你在敏捷项目管理之路上再向前一步。</p>
<h3 data-nodeid="3065">你将获得,包括但不限于</h3>
<ul data-nodeid="3066">
<li data-nodeid="3067">
<p data-nodeid="3068">“快速试错”思维:不断去审视自己,用成长思维成就个人。</p>
</li>
<li data-nodeid="3069">
<p data-nodeid="3070">“价值驱动”思维:认清自己对于公司的价值,明确职场道路。</p>
</li>
<li data-nodeid="3071">
<p data-nodeid="3072">“自组织型组织”方法:巧用授权,放手让团队去干,优化分工协作。</p>
</li>
<li data-nodeid="3073">
<p data-nodeid="3074">“客户合作”原理:学会让客户参与到产品改善中来,真正理解客户所需,使产品更贴合客户要求。</p>
</li>
<li data-nodeid="3075">
<p data-nodeid="3076">透明化的工具:帮助异地团队打破沟通壁垒,高效协同。</p>
</li>
</ul>
<p data-nodeid="3077">这里,我先罗列了几点,还有更多的内容在课程中等待着你。</p>
<h3 data-nodeid="3078">作者寄语</h3>
<p data-nodeid="3079">你可能处于以下几种情况之一 :</p>
<ul data-nodeid="3080">
<li data-nodeid="3081">
<p data-nodeid="3082">想转型或者已经被推上项目经理或管理岗位的技术人,你可以在这里掌握敏捷方法,用敏捷实践帮助提高团队效率,把控全局。</p>
</li>
<li data-nodeid="3083">
<p data-nodeid="3084">项目管理从业人员,但是项目管理知识并不系统,实践中缺少灵活性,需要敏捷实战案例丰富自己,这个课程可以帮助你系统复盘敏捷知识,灵活运用敏捷。</p>
</li>
<li data-nodeid="3085">
<p data-nodeid="3086">敏捷实践者,虽然项目经验丰富,但是缺少统一的行业语言和坚实理论支撑,你可以系统化学习敏捷思维,并学以致用,形成自己的方法论。</p>
</li>
<li data-nodeid="3087">
<p data-nodeid="3088">想要转型做咨询的敏捷教练,这个课程可以让你掌握敏捷实践落地的技巧,让你的敏捷理论变得更加“实干”。</p>
</li>
</ul>
<p data-nodeid="3089">或者你仅仅是对项目管理感兴趣,尽管来学吧。这堂课并不难,我曾经也是敏捷小白,这些年来,我通过敏捷走进腾讯,通过敏捷当上公司总监,上市公司副总裁,通过敏捷自己创业当老板,我不断受益,所以,我希望敏捷能帮助到你,而且我自信地告诉你,这是一定的。</p>
<p data-nodeid="3090">多年的实践也让我明白了一点,理解他人的解决方法,在工作中多观察,试着从现实问题着手去做一些改变,你会猛然间发现一个问题已经被解决了,然后不断重复这个过程来解决更多的问题,一层层抽丝剥茧,你会发现一个更优秀的自己。其实,敏捷方法就是这样一个个的工具集。</p>
<p data-nodeid="3091" class="te-preview-highlight">OK,如果你已经准备好了,现在就让我们一起开启敏捷之旅,也欢迎你把关于敏捷的思考与经历,在留言区和我分享。</p>
---
### 精选评论
##### **和:
> just do it
###### 编辑回复:
> 谢谢您的支持,加油!
##### **菜:
> 太好了,一直对项目管理流程不是很清晰,希望通过这门专栏可以帮我在项管方面得到提升,太赞了~
##### *宁:
> 原来敏捷对腾讯这么重要,这么看互联网人都该学敏捷😎
###### 编辑回复:
> 谢谢您的支持!
##### **伟:
> 看完开篇词,就很期待了!
###### 编辑回复:
> 小编谢谢您的支持~
##### **文:
> 来了来了😀
##### **郎:
> 认真学习之后,就欢乐斗地主欢乐了一把😂😂😂
##### **涛:
> 老板的认知,敏捷就是快!学完去说服她!
###### 编辑回复:
> 哈哈哈学了莫老师的课,打破误解,掌握敏捷的本质!
##### **东:
> 作为一个刚刚成为项目经理和管理岗位leader,太需要这一套来提升自己的项目管理能力了,希望可以学到非常落地的系统方法和工具。
###### 编辑回复:
> 谢谢您的支持,帮助您成长是我们的使命!
##### **寅:
> 有没有什么工具推荐啊
###### 讲师回复:
> Teambition 和 禅道都是很好的项目管理工具
##### **寅:
> 1.主要我们一个迭代周期中往往没有测试资源,那虚拟团队方式有用么?2. 如果项目开发结束了,但是没其他迭代任务,是否就不需要晨会了,或者比较少,是否缩短迭代计划时间?我在落地这块,到总是没总是没办法很好实施,
###### 讲师回复:
> 1、没有测试资源,需要有测试职责,交叉测试也行。2、项目开发结束,又没其他迭代任务,项目就可以结项了。这时候就可以释放人员了。落地这块最重要是要知道工具是用来解决问题的,要活学活用。
##### **寅:
> 有几个问题,1.我们的测试资源公用的,不由我们团队分派,那怎么导入敏捷呢。2.敏捷迭代中,经常一个人会有多个系统的任务,怎么开晨会啊,有些时候前端人员开发好了,但是后端还没有,就导致前端人员空着
###### 讲师回复:
> 1、以虚拟团队的方式导入敏捷。2、“流水席”式晨会法,地点定死,团队轮流在此地点开,多系统开发的同学开完一个接着开下一个。3.前端人员开发好了,后端还没有人,没关系,我们定一个联调时间就好了。在任务安排的时候,注意先完成需要联调的任务
##### **科:
> 大公司敏捷在小公司是否水土不服呢?这个才是关键。
###### 编辑回复:
> 在后面的课时中,莫老师会结合各种案例来帮助你落地的哦,请你期待~
##### **东:
> 多久更新一次呢?
###### 编辑回复:
> 每周二、四更新
##### **智:
> 自组织管理:先帮团队理清楚团队目标,再教团队解决问题的方法,在适当的地方做出引导,锻炼团队解决问题的能力,才可慢慢放手让团队自组织。<div>非常受益</div>
###### 编辑回复:
> 小编给你点赞o( ̄▽ ̄)d
##### **鹏:
> 能不能先说说概念。敏捷管理是个啥
###### 编辑回复:
> 您提的问题在01课时就有哦~
##### Getas:
> 看完开篇词,我把敏捷理解为管理者用来提高组织效率的一套方法论。对吗?敏捷是什么?
###### 编辑回复:
> 敏捷最重要的不是其中的方法,而是具体的实践,也就是导入的过程,那具体怎么导入而又怎么帮助到您呢,请您探索我们后面的课程哦,里面都会讲到的~
##### **辉:
> 学习了。
##### **rry嗷嗷:
> 终于有ACP相关的课了!太好了
|
JavaScript
|
UTF-8
| 5,228 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
var wholenoteImg = document.getElementById("wholenoteImg");
var halfnoteImg = document.getElementById("halfnoteImg");
var quarternoteImg = document.getElementById("quarternoteImg");
var eightnoteImg = document.getElementById("eightnoteImg");
var sixthnoteImg = document.getElementById("sixthnoteImg");
var footstepsImg = document.getElementById("footstepsImg");
var playerWhole = document.getElementById("playerWhole");
var playerHalf = document.getElementById("playerHalf");
var playerQuarter = document.getElementById("playerQuarter");
var playerEight = document.getElementById("playerEight");
var playerSixth = document.getElementById("playerSixth");
var playerFootsteps = document.getElementById("playerFootsteps");
var windowHeight = $(window).height();
//makes each slide equal to the height of the window
window.onload = function(){
$.each($(".slide"), function(i, slide){
$(this).css("height", windowHeight);
console.log($(slide).height() );
});
};
footstepsImg.addEventListener("click", function () {
if(playerFootsteps.paused === false){
playerFootsteps.pause();
} else {
playerFootsteps.play();
}
});
//Alla spelare triggas plus playhead
wholenoteImg.addEventListener("click", function(){
if(playerWhole.paused === false){
playerWhole.pause();
$(".playhead").animate({left: "100"}, 1);
}
else {
playerWhole.play();
$(".playhead")
.delay(2400).animate({left: "1000px"}, 2400, "linear")
.animate({left: "100"}, 1)
}
});
halfnoteImg.addEventListener("click", function(){
if(playerHalf.paused === false){
playerHalf.pause();
$(".playhead").animate({left: "100"}, 1);
}
else {
playerHalf.play();
$(".playhead")
.delay(2400).animate({left: "1000px"}, 2400, "linear")
.animate({left: "100"}, 1)
}
});
quarternoteImg.addEventListener("click", function(){
if(playerQuarter.paused === false){
playerQuarter.pause();
$(".playhead").animate({left: "100"}, 1);
}
else {
playerQuarter.play();
$(".playhead")
.delay(2400).animate({left: "1000px"}, 2400, "linear")
.animate({left: "100"}, 1)
}
});
eightnoteImg.addEventListener("click", function(){
if(playerEight.paused === false){
playerEight.pause();
$(".playhead").animate({left: "100"}, 1);
}
else {
playerEight.play();
$(".playhead")
.delay(2400).animate({left: "1000px"}, 2400, "linear")
.animate({left: "100"}, 1)
}
});
sixthnoteImg.addEventListener("click", function(){
if(playerSixth.paused === false){
playerSixth.pause();
$(".playhead").animate({left: "100"}, 1);
}
else {
playerSixth.play();
$(".playhead")
.delay(2400).animate({left: "1000px"}, 2400, "linear")
.animate({left: "100"}, 1)
}
});
$("#time-signature").click(function () {
$( ".path2" ).attr( "class", "arrow" );
});
//räknar vilken positon man är i
$(window).on("scroll", function() {
console.log($(window).scrollLeft());
});
//alla jävla animationer, triggade av scrollLeft-värde
$("#svgimg").fadeIn(2000);
$("#titlediv").fadeIn(4000);
$(window).scroll(function(){
var scrollLeft = $(this).scrollLeft();
if(scrollLeft > 1000){
$("#rhythmh2").fadeIn(1000);
}
else if(scrollLeft > 1900 || scrollLeft < 1450) {
$("#rhythmh2").fadeOut(400);
}
if(scrollLeft > 1400){
$("#rhythmbox1").fadeIn(1000);
}
else if(scrollLeft > 1900 || scrollLeft < 1500){
$("#rhythmbox1").fadeOut(400);
}
if(scrollLeft > 2600){
$("#infodiv").fadeIn(1000);
}
else if(scrollLeft > 4200 || scrollLeft < 2750){
$("#infodiv").fadeOut(400);
}
if(scrollLeft > 4200){
$("#infodiv2").fadeIn(1000);
}
else if(scrollLeft > 5800 || scrollLeft < 4400){
$("#infodiv2").fadeOut(400);
}
if(scrollLeft > 5800) {
$("#wholenoteDiv").fadeIn(1000);
}
else if(scrollLeft > 7500 || scrollLeft < 6100){
$("#wholenoteDiv").fadeOut(400);
}
if(scrollLeft > 7300){
$("#halfnoteDiv").fadeIn(1000);
}
else if(scrollLeft > 9000 || scrollLeft < 7300){
$("#halfnoteDiv").fadeOut(400);
}
if(scrollLeft > 9300){
$("#4-delsDiv").fadeIn(1000);
}
else if(scrollLeft > 10800 || scrollLeft < 8900){
$("#4-delsDiv").fadeOut(400);
}
if(scrollLeft > 10800){
$("#8-delsDiv").fadeIn(1000);
}
else if(scrollLeft > 12400 || scrollLeft < 10400){
$("#8-delsDiv").fadeOut(400);
}
if(scrollLeft > 12300){
$("#16-delsDiv").fadeIn(1000);
}
else if(scrollLeft > 14200 || scrollLeft < 12200){
$("#16-delsDiv").fadeOut(400);
}
});
$(".box").on("click", function(){
$(".box").animate({left: "1000px"}, 2400);
});
//this . css = var för height
//force horizontal scrolling
$(function() {
$("body").mousewheel(function(event, delta) {
this.scrollLeft -= (delta * 5);
event.preventDefault();
});
});
|
C++
|
UTF-8
| 1,085 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
#include <prox_gui_widget.h>
#include <QApplication>
#include <QDesktopWidget>
#include <QtOpenGL/QGLFormat>
#include <cstring>
int main(int argc, char *argv[])
{
int fullscreen = -1;
for (int i = 0; i < argc && fullscreen != 0; ++i)
{
fullscreen = strcmp(argv[i], "--fullscreen");
}
QApplication app(argc, argv);
QGLFormat format;
format.setVersion( 4, 1 );
format.setProfile( QGLFormat::CoreProfile ); // Requires >=Qt-4.8.0
format.setDoubleBuffer(true);
format.setDepth(true);
format.setDepthBufferSize(24);
format.setOption(QGL::NoDeprecatedFunctions );
// Create a GLWidget requesting our format
prox_gui::Widget window(format);
if (fullscreen == 0)
{
window.showFullScreen();
}
else
{
window.resize(window.sizeHint());
int desktopArea = QApplication::desktop()->width() * QApplication::desktop()->height();
int widgetArea = window.width() * window.height();
if (((float)widgetArea / (float)desktopArea) < 0.75f)
window.show();
else
window.showMaximized();
}
return app.exec();
}
|
Java
|
UTF-8
| 2,145 | 2.375 | 2 |
[] |
no_license
|
package com.example.listtutorial;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.LinearLayoutManager;
import java.util.Arrays;
import java.util.List;
public class yangsik extends AppCompatActivity {
Button back;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yangsik);
back = findViewById (R.id.button3);
back.setOnClickListener (new View.OnClickListener ( ) {
@Override
public void onClick(View v) {
Intent intent = new Intent (yangsik.this, MainActivity.class);
startActivity (intent);
}
});
init();
getData();
}
private RecyclerAdapter adapter;
private void init() {
RecyclerView recyclerView = findViewById(R.id.recyclerView4);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new RecyclerAdapter();
recyclerView.setAdapter(adapter);
}
private void getData() {
// 임의의 데이터
List<String> listTitle = Arrays.asList("그란데", "다린", "오블리끄");
List<String> listContent = Arrays.asList(
"그란데입니다",
"다린입니다",
"오블리끄입니다"
);
List<Integer> listResId = Arrays.asList(
R.drawable.img1,
R.drawable.img1,
R.drawable.img1
);
for (int i = 0; i < listTitle.size(); i++) {
Data data = new Data();
data.setTitle(listTitle.get(i));
data.setContent(listContent.get(i));
data.setResId(listResId.get(i));
adapter.addItem(data);
}
adapter.notifyDataSetChanged();
}
}
|
C
|
UTF-8
| 257 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
#include <lib.h>
void
mmemset(void *pp, int v, int sz)
{
char *p = (char *)pp;
while (sz-- > 0)
*p++ = v;
}
void
mmemcpy(void *dd, const void *ss, int sz)
{
char *d = (char *)dd;
const char *s = (const char *)ss;
while (sz-- > 0)
*d++ = *s++;
}
|
Markdown
|
UTF-8
| 1,165 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: "Interview questions for Swift"
date: 2010-05-23
categories: iOS, developer
comments: true
published: false
---
At the end of the interview they gonna ask you "Do you have any questions for me?"
What do you ask?
Ask about their technology stack. is there more obj C code or swift? any back end?
Ask about the team. How big? experience level of the team, junior, mixed? only senior?
(looking for both. suck the knowledge from senior, but i ike to teach so i am happy to teach younger people)
What do you hope to gain or accomplish by adding a new engineer to your team. 2 What are a few of the most important qualities you would like to see in a new teammate.
ideally see my self as lead of ios developers. so are the leaders come from within?
UI in code or storyboards?
## research interviewers
do have a twitter? a blog? ..
# bounds vs frame
difference is
the frame is the position relative to its parent the super view.
ex we have a UIView and the distance to the top is 102 and the distance to the side is 44 , with a width of 244 and height of 200. thats the frame
the bounds is measured within this views own coordinate system
|
C
|
UTF-8
| 3,040 | 2.765625 | 3 |
[
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-proprietary-license",
"MIT"
] |
permissive
|
/* megablastInfo.h was originally generated by the autoSql program, which also
* generated megablastInfo.c and megablastInfo.sql. This header links the database and
* the RAM representation of objects. */
/* Copyright (C) 2009 The Regents of the University of California
* See README in this or parent directory for licensing information. */
#ifndef MEGABLASTINFO_H
#define MEGABLASTINFO_H
#define MEGABLASTINFO_NUM_COLS 10
struct megablastInfo
/* Conserved Domain Description */
{
struct megablastInfo *next; /* Next in singly linked list. */
char *chrom; /* chromosome */
unsigned chromStart; /* Start position in chromosome */
unsigned chromEnd; /* End position in chromosome */
char *name; /* hit name */
unsigned score; /* Score from 900-1000. 1000 is best */
char strand[2]; /* Value should be + or - */
double evalue; /* Expect value */
unsigned percentident; /* Data source */
char *fullname; /* hit name */
unsigned taxid; /* Data source */
};
void megablastInfoStaticLoad(char **row, struct megablastInfo *ret);
/* Load a row from megablastInfo table into ret. The contents of ret will
* be replaced at the next call to this function. */
struct megablastInfo *megablastInfoLoad(char **row);
/* Load a megablastInfo from row fetched with select * from megablastInfo
* from database. Dispose of this with megablastInfoFree(). */
struct megablastInfo *megablastInfoLoadAll(char *fileName);
/* Load all megablastInfo from whitespace-separated file.
* Dispose of this with megablastInfoFreeList(). */
struct megablastInfo *megablastInfoLoadAllByChar(char *fileName, char chopper);
/* Load all megablastInfo from chopper separated file.
* Dispose of this with megablastInfoFreeList(). */
#define megablastInfoLoadAllByTab(a) megablastInfoLoadAllByChar(a, '\t');
/* Load all megablastInfo from tab separated file.
* Dispose of this with megablastInfoFreeList(). */
struct megablastInfo *megablastInfoCommaIn(char **pS, struct megablastInfo *ret);
/* Create a megablastInfo out of a comma separated string.
* This will fill in ret if non-null, otherwise will
* return a new megablastInfo */
void megablastInfoFree(struct megablastInfo **pEl);
/* Free a single dynamically allocated megablastInfo such as created
* with megablastInfoLoad(). */
void megablastInfoFreeList(struct megablastInfo **pList);
/* Free a list of dynamically allocated megablastInfo's */
void megablastInfoOutput(struct megablastInfo *el, FILE *f, char sep, char lastSep);
/* Print out megablastInfo. Separate fields with sep. Follow last field with lastSep. */
#define megablastInfoTabOut(el,f) megablastInfoOutput(el,f,'\t','\n');
/* Print out megablastInfo as a line in a tab-separated file. */
#define megablastInfoCommaOut(el,f) megablastInfoOutput(el,f,',',',');
/* Print out megablastInfo as a comma separated list including final comma. */
/* -------------------------------- End autoSql Generated Code -------------------------------- */
#endif /* MEGABLASTINFO_H */
|
Java
|
UTF-8
| 2,596 | 3.390625 | 3 |
[] |
no_license
|
package practica1;
import java.util.ArrayList;
import java.util.Scanner;
public class Practica1 {
public static void main(String[] args) {
// TODO code application logic here
Scanner entrada = new Scanner(System.in);
int seleccion;
int numero_cel=0;
boolean salida= false;
//objeto lista para acceder al ArrayList de la clase Crear
Crear lista = new Crear();
//Aceso al ArrayList de la clase Crear
lista.lista_dispositivos= new ArrayList();
// menu principal
Ecosistema ecosistema= new Ecosistema();
//Crear dispositivo
Ecosistema crear= new Crear();
Crear dispositivo= new Crear();
while(salida!=true){
ecosistema.menu();
seleccion= ecosistema.getSeleccion();
switch(seleccion){
case 1: crear.menu();
seleccion=crear.getSeleccion();
switch(seleccion){
case 1: System.out.println("\n-----Creacion de nueva Computadora Portatil-----");
dispositivo.dispositivo_nuevo();
break;
case 2: System.out.println("\n-----Creacion de una nueva Tablet-----");
dispositivo.dispositivo_nuevo();
break;
case 3: System.out.println("\n-----Creacion de nuevo SmartWatch------");
dispositivo.dispositivo_nuevo();
break;
case 4: System.out.println("\n-----Creacion de nuevo Smartphone-----");
dispositivo.dispositivo_nuevo();
break;
}
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
//Opcion para salir del programa
if(seleccion==7){
System.out.println("Has salido");
salida=true;
}
//si la opcion seleccionada no esta en el menu
else if(seleccion>7){System.out.println("Opcion no valida");
}
}
}
}
|
C#
|
UTF-8
| 786 | 2.65625 | 3 |
[] |
no_license
|
using Facade.Class;
namespace Facade
{
public class Facade
{
readonly SubsistemaUm subsistemaUm;
readonly SubsistemaDois subsistemaDois;
readonly SubsistemaTres subsistemaTres;
public Facade()
{
subsistemaUm = new SubsistemaUm();
subsistemaDois = new SubsistemaDois();
subsistemaTres = new SubsistemaTres();
}
public void OperacaoA()
{
System.Console.WriteLine("\n Operacao A -------");
subsistemaUm.Responsabilidade();
subsistemaDois.Responsabilidade();
}
public void OperacaoB()
{
System.Console.WriteLine("\n Operacao B -------");
subsistemaTres.Responsabilidade();
}
}
}
|
Java
|
UTF-8
| 4,234 | 2.859375 | 3 |
[] |
no_license
|
package data.manager;
import data.entity.Customer;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import sample.ui.SystemHelper;
import java.sql.*;
public class CustomerManager
{
private SystemHelper systemHelper = new SystemHelper();
public ObservableList<Customer> getAll() throws SQLException
{
try (Connection c = systemHelper.getConnection())
{
String sql = "SELECT * FROM customer";
Statement statement = c.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
ObservableList<Customer> customers = FXCollections.observableArrayList();
while (resultSet.next()){
customers.add(new Customer(
resultSet.getInt("id_customer"),
resultSet.getString("full_name"),
resultSet.getString("address"),
resultSet.getString("phone_number"),
resultSet.getString("passport")
));
}
return customers;
}
}
public Customer add(Customer customer) throws SQLException {
try (Connection c = systemHelper.getConnection()){
String sql = "INSERT INTO customer(full_name, address, phone_number, passport) VALUES(?, ?, ?, ?)";
PreparedStatement statement = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
statement.setString(1, customer.getFullName());
statement.setString(2, customer.getAddress());
statement.setString(3, customer.getPhone());
statement.setString(4, customer.getPassport());
statement.execute();
ResultSet keys = statement.getGeneratedKeys();
if(keys.next()){
customer.setId(keys.getInt(1));
return customer;
}
throw new SQLException("Customer is not added!");
}
}
public int update(Customer customer) throws SQLException
{
try(Connection c = systemHelper.getConnection())
{
String sql = "UPDATE customer SET full_name=?, address=?, phone_number=?, passport=? WHERE id_customer=?";
PreparedStatement statement = c.prepareStatement(sql);
statement.setString(1, customer.getFullName());
statement.setString(2, customer.getAddress());
statement.setString(3, customer.getPhone());
statement.setString(4, customer.getPassport());
statement.setInt(5, customer.getId());
return statement.executeUpdate();
}
}
public void deleteById(int id) throws SQLException {
try(Connection c = systemHelper.getConnection()){
String sql = "DELETE FROM customer WHERE id_customer=?";
PreparedStatement statement = c.prepareStatement(sql);
statement.setInt(1, id);
statement.executeUpdate();
}
}
public Customer getById(int id) throws SQLException {
try(Connection c = systemHelper.getConnection())
{
String sql = "SELECT * FROM customer WHERE id_customer=?";
PreparedStatement statement = c.prepareStatement(sql);
statement.setInt(1, id);
ResultSet resultSet = statement.executeQuery();
if(resultSet.next()){
return new Customer(
resultSet.getInt("id_customer"),
resultSet.getString("full_name"),
resultSet.getString("address"),
resultSet.getString("phone_number"),
resultSet.getString("passport")
);
}
return null;
}
}
public boolean getByPhone(String phone) throws SQLException {
try(Connection c = systemHelper.getConnection())
{
String sql = "SELECT * FROM customer WHERE phone_number=?";
PreparedStatement statement = c.prepareStatement(sql);
statement.setString(1, phone);
ResultSet resultSet = statement.executeQuery();
return resultSet.next();
}
}
}
|
Ruby
|
UTF-8
| 320 | 2.953125 | 3 |
[] |
no_license
|
require "minitest/autorun"
require_relative "../../lib/1/max_profit.rb"
# SESSION
# 1
describe "#max_profit" do
it "returns the maximum profit" do
assert_equal(5, max_profit([7, 1, 5, 3, 6, 4]))
end
it "returns 0 if profit cannot be made" do
assert_equal(0, max_profit([7, 6, 5, 4, 3, 2, 1]))
end
end
|
Java
|
UTF-8
| 1,113 | 2.28125 | 2 |
[] |
no_license
|
package com.ycl.fileselector.ui.preview.audio;
import androidx.fragment.app.Fragment;
public class BaseFragmentJudgeVisible extends Fragment {
protected boolean mIsVisibleToUser;
private String TAG="";
@Override
public void onStart() {
super.onStart();
if (mIsVisibleToUser) {
onVisible();
}
}
@Override
public void onStop() {
super.onStop();
if (mIsVisibleToUser) {
onInVisible();
}
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
mIsVisibleToUser = isVisibleToUser;
if (isResumed()) { // fragment have created
if (mIsVisibleToUser) {
onVisible();
} else {
onInVisible();
}
}
}
public void onVisible() {
// Toast.makeText(getActivity(), TAG +"visible", Toast.LENGTH_SHORT).show();
}
public void onInVisible() {
// Toast.makeText(getActivity(), TAG +"invisible", Toast.LENGTH_SHORT).show();
}
}
|
C++
|
UTF-8
| 1,780 | 2.796875 | 3 |
[] |
no_license
|
#define DEBUG
#ifdef DEBUG
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <queue>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <map>
#include <unordered_set>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
#endif
const int maxn = 10004;
const int inf = 0x3f3f3f3f;
const double eps = 1e-8;
const double pi = acos(-1.0);
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
class Solution {
public:
void print(const vector<int> &ans) {
for (int i = 0; i < ans.size(); i ++) {
if (i) {
cout << " ";
}
cout << ans[i];
}
cout << "\n";
}
void test() {
vector<vector<int> > g{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
vector<int> ans = this->spiralOrder(g);
this->print(ans);
vector<vector<int> > f{{2, 3}};
this->print(this->spiralOrder(f));
}
vector<int> spiralOrder(vector<vector<int> > &matrix) {
vector<int> ans;
vector<vector<int> > visit;
int n = matrix.size();
if (n == 0) {
return ans;
}
int m = matrix[0].size();
//cout << n << " " << m << "\n";
for (int i = 0; i < n; i ++) {
visit.push_back(vector<int>(m));
}
int total = n * m;
int x = 0, y = -1;
int dir = 0;
while (total > 0) {
int nx = x + dx[dir];
int ny = y + dy[dir];
if ((0 <= nx && nx < n) && (0 <= ny && ny < m) && !visit[nx][ny]) {
visit[nx][ny] = 1;
//cout << matrix[nx][ny] << "\n";
ans.push_back(matrix[nx][ny]);
x = nx;
y = ny;
total --;
} else {
dir = (dir + 1) % 4;
}
}
return ans;
}
};
#ifdef DEBUG
int main(int argc, char const *argv[]) {
Solution *sol = new Solution();
sol -> test();
delete sol;
return 0;
}
#endif
|
C#
|
UTF-8
| 1,473 | 2.890625 | 3 |
[] |
no_license
|
using RomController;
using ShComp;
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace RomPointChecker
{
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
private static async Task RunAsync()
{
while (true)
{
var p = await GetPointAsync();
var w = await RomWindow.FromPointAsync(p);
if (w is null) break;
var r = w.Rectangle;
var dx = (double)(p.X - r.X) / r.Width;
var dy = (double)(p.Y - r.Y) / r.Height;
Console.WriteLine($"({p.X}, {p.Y}) -> ({dx:0.0000}, {dy:0.0000})");
}
Console.WriteLine("停止しました。");
Console.ReadLine();
}
private static Task<Point> GetPointAsync()
{
var tcs = new TaskCompletionSource<Point>();
var hooker = new MouseHooker();
hooker.EventReceived += (status, point) =>
{
if (status == 514)
{
tcs.TrySetResult(point);
Application.Exit();
}
};
Task.Run(() =>
{
hooker.Start();
Application.Run();
hooker.Stop();
});
return tcs.Task;
}
}
}
|
Java
|
UTF-8
| 981 | 1.929688 | 2 |
[] |
no_license
|
package com.resto.brand.web.service;
import java.util.List;
import com.resto.brand.core.generic.GenericService;
import com.resto.brand.web.model.Permission;
/**
* 权限 业务接口
*
* @author StarZou
* @since 2014年6月10日 下午12:02:39
**/
public interface PermissionService extends GenericService<Permission, Long> {
/**
* 通过角色id 查询角色 拥有的权限
*
* @param roleId
* @return
*/
List<Permission> selectPermissionsByRoleId(Long roleId);
List<Permission> selectAllParents(Long userGroupId);
List<Permission> selectListByParentId(Long parentId);
List<String> selectAllUrls();
List<Permission> selectAllMenu(Long userGroupId);
void addSubPermission(Permission permission);
void updateSubPermission(Permission model);
List<Permission> selectList(Long userGroupId);
List<Permission> selectFullStructMenu(long systemGroup);
List<Permission> selectPermissionsByRoleIdWithOutParent(Long roleId);
}
|
Python
|
UTF-8
| 628 | 3.109375 | 3 |
[] |
no_license
|
from math import sqrt
from drawtraj import drawtraj
def force(x,y,m,mstar):
r2=x**2+y**2
r32=r2*sqrt(r2)
fx=-x*m*mstar/r32
fy=-y*m*mstar/r32
return fx,fy
def integrate(x,y,vx,vy,fx,fy,m,dt):
ax, ay = fx/m, fy/m
vx += ax*dt
vy += ay*dt
x += vx*dt
y += vy*dt
return x, y, vx, vy
# Main part of the program
mstar = 100
m = 1
nsteps = 100000
dt = 0.01
r = 50
x, y = 0, r
vx, vy = 1.2, 0
trajx,trajy=[],[]
for t in range(nsteps):
fx, fy = force(x, y, m, mstar)
x, y, vx, vy = integrate(x, y, vx, vy, fx, fy, m, dt)
trajx.append(x)
trajy.append(y)
drawtraj(trajx,trajy,5*r)
|
Java
|
UTF-8
| 1,159 | 2.015625 | 2 |
[] |
no_license
|
package com.ca.arcflash.ui.client.model;
import com.extjs.gxt.ui.client.data.BaseModelData;
public class SearchContextModel extends BaseModelData {
/**
*
*/
private static final long serialVersionUID = -3977798498329806405L;
public Long getContextID() {
return (Long)get("contextID");
}
public void setContextID(Long contextID) {
set("contextID", contextID);
}
public Long getTag() {
return (Long) get("tag");
}
public void setTag(Long tag) {
set("tag", tag);
}
public void setCurrKind(long kind) {
this.currKind = kind;
}
public long getCurrKind() {
return currKind;
}
public void setSearchkind(long searchkind) {
if ((searchkind & KIND_FILE) == 0) {
excludeFileSystem = true;
}
this.searchkind = searchkind;
}
public long getSearchkind() {
return searchkind;
}
public void setExcludeFileSystem(boolean excludeFileSystem) {
this.excludeFileSystem = excludeFileSystem;
}
public boolean isExcludeFileSystem() {
return excludeFileSystem;
}
private long currKind;
private long searchkind;
private boolean excludeFileSystem = false;
public static final long KIND_FILE = 0x0000000000000001;
}
|
Swift
|
UTF-8
| 1,366 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
//
// DeepLinkFactory.swift
// UalaNavigationEngine
//
// Created by Miguel Olmedo on 10/08/21.
//
import Foundation
import CoreLocation
public class DeepLinkFactory {
let scheme: String
let host: String
public init(scheme: String, host: String) {
self.scheme = scheme
self.host = host
}
}
extension DeepLinkFactory {
public func homeURL() -> DeepLink {
let endpoint = Endpoint(scheme: scheme,
host: host,
path: "/home",
queryItems: nil)
return endpoint.url
}
public func loginURL() -> DeepLink {
let endpoint = Endpoint(scheme: scheme,
host: host,
path: "/login",
queryItems: nil)
return endpoint.url
}
public func updatePasswordURL(token: ResetPasswordToken) -> DeepLink {
let tokenQueryItem = URLQueryItem(name: "resetToken", value: token)
let endpoint = Endpoint(scheme: scheme,
host: host,
path: "/resetPassword",
queryItems: [tokenQueryItem])
return endpoint.url
}
}
extension DeepLinkFactory {
}
extension DeepLinkFactory {
}
|
Java
|
GB18030
| 2,613 | 3.40625 | 3 |
[] |
no_license
|
package server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* Ϸķ
* @author ZhuYingtao
*
*/
public class GameChatServer implements Runnable {
/**
* Ķ˿ں
*/
int TCP_PORT;
private List<Client> clients = new ArrayList<Client>();
/**
* õ˿ںţ߳
* @param tcp_port
*/
public GameChatServer(int tcp_port) {
this.TCP_PORT = tcp_port;
System.out.println(TCP_PORT);
new Thread(this).start();
}
/**
* ̣߳տͻ˵Ӳ
*/
public void run() {
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_PORT);
System.out.println("ȴ,˿ںţ" + TCP_PORT);
while (true) {
Socket s = ss.accept();
Client c = new Client(s);
clients.add(c);
new Thread(c).start();
System.out.println("a gamechatclient connect");
}
} catch (IOException e) {
System.out.println("˿ʹУԡ");
System.exit(0);
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s = null;
private DataInputStream dis = null;
private DataOutputStream dos = null;
String info = null;
public Client(Socket s) {
this.s = s;
}
public void send(String str) {
try {
dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(str);
} catch (IOException e) {
System.out.println("ϵͳ");
}
}
public void run() {
try {
dis = new DataInputStream(s.getInputStream());
while (true) {
info = dis.readUTF();
System.out.println(info);
if (info.equals("enter")) {
String str = dis.readUTF();
for (int i = 0; i < clients.size(); i++) {
Client c = clients.get(i);
c.send("enter");
c.send(str);
}
}
if (info.equals("talking")) {
String name = dis.readUTF();
String str = dis.readUTF();
String sex = dis.readUTF();
if (str != null && str != "") {
for (int i = 0; i < clients.size(); i++) {
Client c = clients.get(i);
c.send("talking");
c.send(name);
c.send(str);
c.send(sex);
}
}
}
}
} catch (IOException e) {
clients.remove(this);
System.out.println("ͻ˳ˣ");
}
}
}
}
|
Java
|
UTF-8
| 1,256 | 2.34375 | 2 |
[] |
no_license
|
package failure_detector;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.TimerTask;
import failure_detector.data.Counter;
import failure_detector.data.FD;
import failure_detector.interfaces.IMyFD;
public class TimeoutTask extends TimerTask {
private Counter c = new Counter();
private FD fd;
public TimeoutTask(FD fd) {
this.fd = fd;
}
@Override
public void run() {
System.out.println(new Date() + " Timout");
System.out.println(new Date() + " Starting lookup for reconnect");
try {
IMyFD contact = (IMyFD) Naming.lookup("rmi://" + fd.getSecond().getFullAddress() + "/" + fd.getSecond().getServiceName());
System.out.println(new Date() + " Node found: " + fd.getSecond().getFullAddress());
contact.ChangePulse(fd.getMe());
contact = null;
synchronized (fd) {
fd.setFirst(fd.getSecond());
fd.setSecond(fd.getThird());
fd.setThird(fd.getMe());
}
fd.setTimeout(true);
} catch (MalformedURLException | RemoteException | NotBoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
Swift
|
UTF-8
| 2,776 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
//
// View.swift
// Katana
//
// Copyright © 2016 Bending Spoons.
// Distributed under the MIT License.
// See the LICENSE file for more information.
import UIKit
import KatanaUI
import Katana
public extension View {
public struct Props: NodeDescriptionProps, Childrenable, Buildable {
public var frame = CGRect.zero
public var key: String?
public var alpha: CGFloat = 1.0
public var children: [AnyNodeDescription] = []
public var backgroundColor = UIColor.white
public var cornerRadius: Value = .zero
public var borderWidth: Value = .zero
public var borderColor = UIColor.clear
public var clipsToBounds = false
public var isUserInteractionEnabled = true
public init() {}
public static func == (lhs: Props, rhs: Props) -> Bool {
if (lhs.children.count + rhs.children.count) > 0 {
// Heuristic, we always rerender when there is at least 1 child
return false
}
return
lhs.frame == rhs.frame &&
lhs.key == rhs.key &&
lhs.alpha == rhs.alpha &&
lhs.backgroundColor == rhs.backgroundColor &&
lhs.cornerRadius == rhs.cornerRadius &&
lhs.borderWidth == rhs.borderWidth &&
lhs.borderColor == rhs.borderColor &&
lhs.clipsToBounds == rhs.clipsToBounds &&
lhs.isUserInteractionEnabled == rhs.isUserInteractionEnabled
}
}
}
public struct View: NodeDescription, NodeDescriptionWithChildren {
public var props: Props
public static func applyPropsToNativeView(props: Props,
state: EmptyState,
view: UIView,
update: @escaping (EmptyState)->(),
node: AnyNode) {
view.alpha = props.alpha
view.frame = props.frame
view.backgroundColor = props.backgroundColor
view.layer.cornerRadius = props.cornerRadius.scale(by: node.plasticMultiplier)
view.layer.borderColor = props.borderColor.cgColor
view.layer.borderWidth = props.borderWidth.scale(by: node.plasticMultiplier)
view.clipsToBounds = props.clipsToBounds
view.isUserInteractionEnabled = props.isUserInteractionEnabled
}
public static func childrenDescriptions(props: Props,
state: EmptyState,
update: @escaping (EmptyState)->(),
dispatch: @escaping StoreDispatch) -> [AnyNodeDescription] {
return props.children
}
public init(props: Props) {
self.props = props
}
public init(props: Props, _ children: () -> [AnyNodeDescription]) {
self.props = props
self.props.children = children()
}
}
|
Java
|
UTF-8
| 1,749 | 2.59375 | 3 |
[] |
no_license
|
package Logiikka.Generointi;
import Logiikka.Ruudukko.Ruudukko;
import Logiikka.Ruudukko.Ruutu;
/**
* Olio on vastuussa Luolapelin koko kerroksen kaikesta tiedosta ja sen
* käsittelystä.
*
* @author htommi
*/
public class Kerros {
private Ruudukko ruudukko;
private AluePuu ap;
/**
* Luo uuden Kerros olion. Se tarvitsee koko kerroksen koon ja moneen
* Alueeseen se on jaettu.
*
* @param koko kerroksen koko
* @param jakauksia moneen osaan kerros on jaettu
*/
public Kerros(int koko, int jakauksia) {
ruudukko = new Ruudukko(koko);
ap = new AluePuu(koko, jakauksia);
}
/**
* Paivittaa ruuduille tiedon siitä, millä alueella ne ovat.
*/
public void alueetRuudukkoon() {
for (int y = 0; y < this.getRuudukko().getKoko(); y++) {
for (int x = 0; x < this.getRuudukko().getKoko(); x++) {
this.ruudukko.setRuudunAlue(x, y, ap.getAlueet()[0].getHuone()[x][y]);
this.ruudukko.setRuudunArvo(x, y, ap.getAlueet()[0].getHuone()[x][y]);
}
}
}
public AluePuu getAluePuu() {
return ap;
}
public Ruudukko getRuudukko() {
return ruudukko;
}
public Alue[] getAlimmatAlueet() {
int a = ap.indexMistaAlkaaTaso(ap.MAXTASO);
int k = ap.montaSolmuaTasolla(ap.MAXTASO);
Alue[] alimmat = new Alue[k];
int i = 0;
for (int p = a; p < k + a; p++) {
alimmat[i] = ap.getAlueet()[p];
i++;
}
return alimmat;
}
public Ruutu annaSijaintiAlueesta(int id) {
Alue alue = this.ap.getAlueet()[id];
Ruutu ruutu = alue.annaEkaTyhjaRuutu();
return ruutu;
}
}
|
SQL
|
UTF-8
| 2,026 | 3.109375 | 3 |
[] |
no_license
|
DROP PROCEDURE IF EXISTS buhodb.delete_smartphone_with_imei;
CREATE DEFINER=`root`@`%` PROCEDURE `delete_smartphone_with_imei`(IN p_imei VARCHAR(255))
BEGIN
DELETE from positions WHERE device_id in (select id from device where imei = p_imei);
DELETE from positions_buffer WHERE device_id in (select id from device where imei = p_imei);
delete from user_device where device_id in (select id from device where imei = p_imei);
delete from subscription where device_id in (select id from device where imei = p_imei);
# delete from payment_request_item where payment_request_id in (select id from payment_request where device_id in (select id from device where imei = p_imei));
# delete from payment_request where device_id in (select id from device where imei = p_imei);
delete from device where imei = p_imei;
END;
SET @deviceId = 112;
DELETE FROM positions WHERE device_id = @deviceId ;
DELETE FROM positions_buffer WHERE device_id = @deviceId ;
DELETE FROM user_device WHERE device_id = @deviceId;
DELETE FROM subscription WHERE device_id = @deviceId;
DELETE FROM sms_control WHERE device_id = @deviceId;
DELETE FROM device WHERE id = @deviceId;
CREATE PROCEDURE dowhile()
BEGIN
DECLARE v1 INT DEFAULT 41;
WHILE v1 > 24 DO
SET @deviceId = v1;
DELETE FROM positions WHERE device_id = @deviceId ;
DELETE FROM positions_buffer WHERE device_id = @deviceId ;
DELETE FROM user_device WHERE device_id = @deviceId;
DELETE FROM subscription WHERE device_id = @deviceId;
DELETE FROM sms_control WHERE device_id = @deviceId;
DELETE FROM alarm_battery WHERE device_id = @deviceId;
DELETE FROM device WHERE id = @deviceId;
SET v1 = v1 - 1;
END WHILE;
END;
SET @accountId = 15;
SET @userID = (SELECT id FROM users WHERE account_id = @accountId);
DELETE FROM user_role WHERE user_id = @userID;
DELETE FROM users WHERE account_id = @accountId;
DELETE FROM account WHERE id = @accountId;
# DROP PROCEDURE dowhile;
# CALL dowhile();
|
C++
|
UTF-8
| 605 | 3.046875 | 3 |
[] |
no_license
|
/*
演習1-4 コンソールに名前を改行して出力すること
作成日 2017.5.4
作成者 平澤敬介
*/
// 入出力のヘッダ
#include<iostream>
// 名前空間の指定
using namespace std;
// プログラム本文 始まり これ以降の文が順次実行されていく
int main()
{
// コンソールに改行して出力
// 名前が一文字流れて一句ごとに改行文字が
// 流れていきコンソールに表示されるとき縦に表示されます。
cout << "平\n澤\n敬\n介\n";
return 0;// プログラム終了
} // プログラム本文 終わり
|
TypeScript
|
UTF-8
| 10,125 | 3.6875 | 4 |
[
"MIT"
] |
permissive
|
import { Common } from "../CommonUtils";
import { Point, ImmutablePointPrimitive, isPointPrimitive } from "./Point";
export type RectanglePrimitive = {
x: number,
y: number,
width: number,
height: number,
}
function isRectangle(o: any): o is RectanglePrimitive {
const {x,y,width,height} = o;
return [x,y,width,height].every( prop => typeof prop === 'number');
}
/** A rectangle in 2-dimensional space. */
export class Rectangle {
x: number = 0;
y: number = 0;
width: number = 0;
height: number = 0;
get left() { return this.x; }
get right() { return this.x + this.width; }
get top() { return this.y; }
get bottom() { return this.y + this.height; }
get topleft() { return new Point(this.left, this.top); }
get topright() { return new Point(this.right, this.top); }
get bottomleft() { return new Point(this.left, this.bottom); }
get bottomright() { return new Point(this.right, this.bottom); }
get center() { return this.getPointByProportion(new Point(.5)); }
constructor(x?: number | RectanglePrimitive | ImmutablePointPrimitive, y?: number, width?: number, height?: number) {
this.set(x, y, width, height);
}
/** Sets this rectangles properties to those given. */
// TODO I think this accepts too many overloads. It's just confusing.
// Maybe fromRect and fromPoints would be better.
set(x: number | RectanglePrimitive | ImmutablePointPrimitive = 0, y: number = 0, width: number = 0, height: number = 0): Rectangle {
const o = x;
// TODO I broke instanceof; I need an eval function
if (isRectangle(o)) {
const { x, y, width, height } = o;
Object.assign(this, {x, y, width, height});
} else if (isPointPrimitive(o)) {
// This is mad confusing. It has to bump width←y and height←width.
Object.assign(this, {x: o.x, y: o.y, width: y, height: width});
} else {
Object.assign(this, {x, y, width, height});
}
return this;
}
/** Sets this rectangle's properties such that its edges are equivalent to the ones given. */
setEdges(left: number, right: number, top: number, bottom: number): Rectangle {
const { max, min } = Math;
this.x = min(left, right);
this.width = max(left, right) - this.x;
this.y = min(top, bottom);
this.height = max(top, bottom) - this.y;
return this;
}
/** Returns a new rectangle with coordinates equal to the sum of this and the given point. */
move(x: number | ImmutablePointPrimitive, y?: number) {
const p = new Point(x, y).add(this);
return new Rectangle(
p.x, p.y,
this.width,
this.height,
);
}
/** Returns a new rectangle with size coordinates equal to the sum of this rectangle's width
* and height and the given point. */
adjustSize(w: number | ImmutablePointPrimitive, h?: number) {
const p = new Point(w, h).add(this.bottomright);
return new Rectangle(
this.x, this.y,
p.x,
p.y,
);
}
/** Returns a new rectangle with all its properties a product of this one's after applying the given function. */
apply(f: (n: number) => number) {
return new Rectangle(
f(this.x),
f(this.y),
f(this.width),
f(this.height),
)
}
/** Returns a new rectangle with all its side-coordinates a product of this one's after applying the given function. */
applyEdges(f: (n: number) => number) {
const x = f(this.x);
const y = f(this.y);
return new Rectangle(
x, y,
f(this.right) - x,
f(this.bottom) - y,
)
}
/** Returns a new rectangle with both its x and y coordinates a product of this one's after applying the given function. */
applyCoordinates(f: (n: number) => number) {
return new Rectangle(
f(this.x), f(this.y),
this.width,
this.height,
)
}
/** Returns a new rectangle with both its width and height dimensions a product of this one's after applying the given function. */
applyDimensions(f: (n: number) => number) {
return new Rectangle(
this.x, this.y,
f(this.width),
f(this.height),
)
}
/** Returns a new Rectangle with the same properties as this one. */
clone(): Rectangle {
return new Rectangle(this);
}
/** Returns true if this rectangle's properties are the same as the given one. */
equal(rect: Rectangle): boolean {
return (
this.x === rect.x
&& this.y === rect.y
&& this.width === rect.width
&& this.height === rect.height
)
}
/** Returns true if this rectangle's properties are the same as the given one. */
notEqual(rect: Rectangle): boolean {
return !this.equal(rect);
}
/** Grows (or shrinks with -n) the bounds of the rectangle by a set amount.
* yPad is assumed to be the same as xPad unless specified.
* Preserves the position of the coordinate at the anchor immutablepointprimitive, which is by default the center.
* A rectangle cannot shrink more than its own axis length; a resulting width or height cannot be < 0. */
pad(xPad: number, yPad?: number, anchor?: ImmutablePointPrimitive): Rectangle {
const { max } = Math;
yPad = yPad || xPad;
anchor = anchor || new Point(.5);
const newWidth = max(this.width + xPad, 0);
const newHeight = max(this.height + yPad, 0);
return new Rectangle(
this.x + (newWidth - this.width)*anchor.x,
this.y + (newHeight - this.height)*anchor.y,
newWidth,
newHeight,
);
}
/** Returns a new Rectangle which shares all its edges with the most extreme coordinates given in the
* list of objects to bound. */
fit(...objects: (Rectangle | ImmutablePointPrimitive)[]): Rectangle {
const { max, min } = Math;
const rects = objects.map( r => new Rectangle(r) ); // Affirms all objects are Rectangles
const x = min(...rects.map(r => r.left));
const width = max(...rects.map(r => r.right)) - x;
const y = min(...rects.map(r => r.top));
const height = max(...rects.map(r => r.bottom)) - y;
return new Rectangle(x, y, width, height);
}
/** Returns a new Rectangle extended from this one such that no edge disincludes any area or immutablepointprimitive
* contained within the objects given. */
enlarge(...objects: (Rectangle | ImmutablePointPrimitive)[]): Rectangle {
return this.fit(this, ...objects);
}
/** Returns true if this rectangle wholly encloses the given object's coordinate-space. */
contains(other: Rectangle | ImmutablePointPrimitive): boolean {
const rect = new Rectangle(other);
return (
this.left <= rect.left
&& this.right >= rect.right
&& this.top <= rect.top
&& this.bottom >= rect.bottom
);
}
/** Returns the ratio of this rectangle's width to its height. */
get aspectRatio() {
return this.width / this.height;
}
/** Returns a new rectangle with a width proportional to its height by the given ratio. */
setWidthByAR(ratio: number) {
return new Rectangle(
this.x,
this.y,
this.height * ratio,
this.height,
);
}
/** Returns a new rectangle with a height proportional to its width by the given ratio. */
setHeightByAR(ratio: number) {
return new Rectangle(
this.x,
this.y,
this.width,
this.width * ratio,
);
}
/** Returns the geometric area of this rectangle. */
get area() {
return this.width * this.height;
}
/** Returns a new rectangle with coordinates truncated to include the largest area. */
truncateOut() {
const { floor, ceil } = Math;
return new Rectangle(
floor(this.x),
floor(this.y),
ceil(this.width),
ceil(this.height),
);
}
/** Returns a new rectangle with coordinates truncated to include the smallest area. */
truncateIn() {
const { floor, ceil } = Math;
return new Rectangle(
ceil(this.x),
ceil(this.y),
floor(this.width),
floor(this.height),
);
}
/** Returns true if this and the given rectangle have areas which share a coordinate space. */
intersects(rect: Rectangle): boolean {
const intersection = this.getIntersection(rect);
return intersection.notEqual(Rectangle.Empty);
}
/** Returns the rectangle defined by the cross-section of this and the given rectangle.
* Rectangles are not considered intersecting if they merely share a side.
* If this and the given rect are not intersecting, returns an Empty rectangle. */
getIntersection(rect: Rectangle): Rectangle {
const { min, max } = Math;
const l = max(this.left, rect.left);
const t = max(this.top, rect.top);
const r = min(this.right, rect.right);
const b = min(this.bottom, rect.bottom);
return (l < r && t < b)
? new Rectangle(l, t, r-l, b-t)
: Rectangle.Empty;
}
/** Returns a coordinate relative to this rectangle's top-left corner and proportional to its width/height
* by the given anchor immutablepointprimitive. Ex: anchor=(.8, .8) returns a immutablepointprimitive in the lower-right rectangle quadrant. */
getPointByProportion(anchor: ImmutablePointPrimitive) {
return new Point(
this.left + anchor.x*this.width,
this.top + anchor.y*this.height,
)
}
/** Returns the minimum distance of a immutablepointprimitive to one of this rectangle's edges or vertices. */
minimumDistanceTo(p: ImmutablePointPrimitive): number { // TODO Include Rects as options too
const { abs } = Math;
const { left, right, top, bottom } = this;
const vector = new Point(
abs(Common.displacementFromRange(p.x, left, right)),
abs(Common.displacementFromRange(p.y, top, bottom)),
);
return vector.magnitude();
}
/** Returns a string representation of this rectangle's properties. */
toString(decimals: number = 0) {
const { top, left, bottom, right, width, height } = this;
const [t, l, b, r, w, h] = [top, left, bottom, right, width, height].map( n => n.toFixed(decimals) );
return `[${l} ${t} ${r} ${b}, ${w}w ${h}h]`;
}
/** A rectangle object with all properties set to 0. */
static get Empty() { return new Rectangle(); }
}
|
Java
|
UTF-8
| 30,614 | 1.578125 | 2 |
[] |
no_license
|
package com.richitec.chinesetelephone.assist;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.richitec.chinesetelephone.R;
import com.richitec.chinesetelephone.constant.SystemConstants;
import com.richitec.chinesetelephone.tab7tabcontent.CTContactListViewQuickAlphabetToast;
import com.richitec.chinesetelephone.utils.AppDataSaveRestoreUtil;
import com.richitec.commontoolkit.CTApplication;
import com.richitec.commontoolkit.activityextension.NavigationActivity;
import com.richitec.commontoolkit.addressbook.AddressBookManager;
import com.richitec.commontoolkit.addressbook.ContactBean;
import com.richitec.commontoolkit.customadapter.CTListAdapter;
import com.richitec.commontoolkit.customcomponent.CTPopupWindow;
import com.richitec.commontoolkit.customcomponent.ListViewQuickAlphabetBar;
import com.richitec.commontoolkit.customcomponent.ListViewQuickAlphabetBar.OnTouchListener;
import com.richitec.commontoolkit.utils.MyToast;
import com.richitec.commontoolkit.utils.StringUtils;
public class ContactLisInviteFriendActivity extends NavigationActivity {
private static final String LOG_TAG = "ContactListInviteFriendActivity";
private final String PRESENT_CONTACT_PHONES = "present_contact_phones";
private final String PREVIOUS_PHONES_STYLE = "previous_phones_style";
private final String CONTACT_IS_SELECTED = "contact_is_selected";
private final String SELECTED_PHONE = "selected_phone";
private int selectedPosition;
private String inviteLink;
// address book contacts list view
private ListView _mABContactsListView;
// all address book name phonetic sorted contacts detail info list
private static List<ContactBean> _mAllNamePhoneticSortedContactsInfoArray;
// present contacts in address book detail info list
private List<ContactBean> _mPresentContactsInABInfoArray;
// the friends to send invite
private List<ContactBean> _mInviteFriendsInfo;
// contact search status
private ContactSearchStatus _mContactSearchStatus = ContactSearchStatus.NONESEARCH;
private UpdateABListHandler listUpdateHandler;
// define contact phone numbers select popup window
private final ContactPhoneNumbersSelectPopupWindow _mContactPhoneNumbersSelectPopupWindow = new ContactPhoneNumbersSelectPopupWindow(
R.layout.contact_phonenumbers_select_popupwindow_layout,
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
// init all name phonetic sorted contacts info array
public static void initNamePhoneticSortedContactsInfoArray() {
_mAllNamePhoneticSortedContactsInfoArray = AddressBookManager
.getInstance().getAllNamePhoneticSortedContactsInfoArray();
}
private CTContactListViewQuickAlphabetToast ctToast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set content view
setContentView(R.layout.contact_list_invite_friend_activity_layout);
inviteLink = getIntent().getStringExtra("inviteLink");
// set title
setTitle(R.string.sms_invite_pattern);
_mInviteFriendsInfo = new ArrayList<ContactBean>();
// init contacts in address book list view
_mABContactsListView = (ListView) findViewById(R.id.contactInAB_listView);
initListUI();
// set contacts in address book listView on item click listener
_mABContactsListView
.setOnItemClickListener(new ContactsInABListViewOnItemClickListener());
_mABContactsListView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
hideSoftKeyboard();
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
// bind contact search editText text watcher
((EditText) findViewById(R.id.contact_search_editText))
.addTextChangedListener(new ContactSearchEditTextTextWatcher());
listUpdateHandler = new UpdateABListHandler();
AddressBookManager.getInstance().addContactObserverhandler(
listUpdateHandler);
}
private void initListUI() {
// check all address book name phonetic sorted contacts detail info list
// and init present contacts in address book detail info array
if (null == _mAllNamePhoneticSortedContactsInfoArray) {
Log.d(LOG_TAG,
"All address book name phonetic sorted contacts detail info list is null, init immediately when on create");
// init first
initNamePhoneticSortedContactsInfoArray();
}
_mPresentContactsInABInfoArray = _mAllNamePhoneticSortedContactsInfoArray;
Log.d(SystemConstants.TAG, "_mPresentContactsInABInfoArray size: "
+ _mPresentContactsInABInfoArray.size());
// set contacts in address book listView adapter
_mABContactsListView.setAdapter(generateInABContactAdapter(this, true,
_mPresentContactsInABInfoArray));
// init address book contacts listView quick alphabet bar and add on
// touch listener
ctToast = new CTContactListViewQuickAlphabetToast(
_mABContactsListView.getContext());
new ListViewQuickAlphabetBar(_mABContactsListView, ctToast)
.setOnTouchListener(new ContactsInABListViewQuickAlphabetBarOnTouchListener());
}
private ListAdapter generateInABContactAdapter(Context activityContext,
Boolean contactListViewInTab, List<ContactBean> presentContactsInAB) {
// in address book contacts adapter data keys
final String PRESENT_CONTACT_PHOTO = "present_contact_photo";
final String PRESENT_CONTACT_NAME = "present_contact_name";
final String PRESENT_CONTACT_PHONES = "present_contact_phones";
// set address book contacts list view present data list
List<Map<String, ?>> _addressBookContactsPresentDataList = new ArrayList<Map<String, ?>>();
for (ContactBean _contact : presentContactsInAB) {
// generate data
Map<String, Object> _dataMap = new HashMap<String, Object>();
// get contact name and phone matching indexes
SparseIntArray _nameMatchingIndexes = (SparseIntArray) _contact
.getExtension().get(
AddressBookManager.NAME_MATCHING_INDEXES);
@SuppressWarnings("unchecked")
List<List<Integer>> _phoneMatchingIndexes = (List<List<Integer>>) _contact
.getExtension().get(
AddressBookManager.PHONENUMBER_MATCHING_INDEXES);
// define contact search status
ContactSearchStatus _contactSearchStatus = ContactSearchStatus.NONESEARCH;
// set data
// define contact photo bitmap
Bitmap _contactPhotoBitmap = ((BitmapDrawable) activityContext
.getResources().getDrawable(R.drawable.img_default_avatar))
.getBitmap();
// check contact photo data
if (null != _contact.getPhoto()) {
try {
// get photo data stream
InputStream _photoDataStream = new ByteArrayInputStream(
_contact.getPhoto());
// check photo data stream
if (null != _photoDataStream) {
_contactPhotoBitmap = BitmapFactory
.decodeStream(_photoDataStream);
// close photo data stream
_photoDataStream.close();
}
} catch (IOException e) {
e.printStackTrace();
Log.e(LOG_TAG,
"Get contact photo data stream error, error message = "
+ e.getMessage());
}
}
// set photo
_dataMap.put(PRESENT_CONTACT_PHOTO, _contactPhotoBitmap);
// check contact listView in tab activity and update contact search
// status
if (true == contactListViewInTab) {
// update search status
_contactSearchStatus = ((ContactLisInviteFriendActivity) activityContext)
.getContactSearchStatus();
}
// check contact search status
if (ContactSearchStatus.SEARCHBYNAME == _contactSearchStatus
|| ContactSearchStatus.SEARCHBYCHINESENAME == _contactSearchStatus) {
// get display name
SpannableString _displayName = new SpannableString(
_contact.getDisplayName());
// set attributed
for (int i = 0; i < _nameMatchingIndexes.size(); i++) {
// get key and value
Integer _nameCharMatchedPos = ((ContactLisInviteFriendActivity) activityContext)
.getRealPositionInContactDisplayName(
_contact.getDisplayName(),
_nameMatchingIndexes.keyAt(i));
Integer _nameCharMatchedLength = _nameMatchingIndexes
.get(_nameMatchingIndexes.keyAt(i));
_displayName
.setSpan(
new ForegroundColorSpan(Color.BLUE),
_nameCharMatchedPos,
AddressBookManager.NAME_CHARACTER_FUZZYMATCHED_LENGTH == _nameCharMatchedLength ? _nameCharMatchedPos + 1
: _nameCharMatchedPos
+ _nameCharMatchedLength,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
_dataMap.put(PRESENT_CONTACT_NAME, _displayName);
} else {
_dataMap.put(PRESENT_CONTACT_NAME, _contact.getDisplayName());
}
if (ContactSearchStatus.SEARCHBYPHONE == _contactSearchStatus) {
// get format phone number string
SpannableString _formatPhoneNumberString = new SpannableString(
_contact.getFormatPhoneNumbers());
// get format phone number string separator "\n" positions
List<Integer> _sepPositions = StringUtils.subStringPositions(
_contact.getFormatPhoneNumbers(), "\n");
// set attributed
for (int i = 0; i < _phoneMatchingIndexes.size(); i++) {
// check the phone matched
if (0 != _phoneMatchingIndexes.get(i).size()) {
// get begin and end position
int _beginPos = _phoneMatchingIndexes.get(i).get(0);
int _endPos = _phoneMatchingIndexes.get(i).get(
_phoneMatchingIndexes.get(i).size() - 1) + 1;
// check matched phone
if (1 <= i) {
_beginPos += _sepPositions.get(i - 1) + 1;
_endPos += _sepPositions.get(i - 1) + 1;
}
_formatPhoneNumberString.setSpan(
new ForegroundColorSpan(Color.BLUE), _beginPos,
_endPos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
_dataMap.put(PRESENT_CONTACT_PHONES, _formatPhoneNumberString);
} else {
_dataMap.put(PRESENT_CONTACT_PHONES,
_contact.getFormatPhoneNumbers());
}
// put alphabet index
_dataMap.put(CTListAdapter.ALPHABET_INDEX,
_contact.getNamePhoneticsString());
Boolean _isSelected = (Boolean) _contact.getExtension().get(
CONTACT_IS_SELECTED);
if (null == _isSelected) {
_contact.getExtension().put(CONTACT_IS_SELECTED, false);
}
_dataMap.put(CONTACT_IS_SELECTED,
_contact.getExtension().get(CONTACT_IS_SELECTED));
// add data to list
_addressBookContactsPresentDataList.add(_dataMap);
}
// get address book contacts listView adapter
InviteFriendContactAdapter _addressBookContactsListViewAdapter = (InviteFriendContactAdapter) _mABContactsListView
.getAdapter();
return null == _addressBookContactsListViewAdapter ? new InviteFriendContactAdapter(
this, _addressBookContactsPresentDataList,
R.layout.invite_friend_contact_layout, new String[] {
PRESENT_CONTACT_PHOTO, PRESENT_CONTACT_NAME,
PRESENT_CONTACT_PHONES, CONTACT_IS_SELECTED },
new int[] { R.id.addressBook_contact_avatar_imageView,
R.id.adressBook_contact_displayName_textView,
R.id.addressBook_contact_phoneNumber_textView,
R.id.addressBook_contact_checkbox })
: _addressBookContactsListViewAdapter
.setData(_addressBookContactsPresentDataList);
}
public ContactSearchStatus getContactSearchStatus() {
return _mContactSearchStatus;
}
// get real position in contact display name with original position
private Integer getRealPositionInContactDisplayName(String displayName,
Integer origPosition) {
int _realPos = 0;
int _tmpPos = 0;
boolean _prefixHasChar = false;
for (int i = 0; i < displayName.length(); i++) {
if (String.valueOf(displayName.charAt(i))
.matches("[\u4e00-\u9fa5]")) {
if (_prefixHasChar) {
_prefixHasChar = false;
_tmpPos += 1;
}
if (_tmpPos == origPosition) {
_realPos = i;
break;
}
_tmpPos += 1;
} else if (' ' == displayName.charAt(i)) {
if (_prefixHasChar) {
_prefixHasChar = false;
_tmpPos += 1;
}
} else {
if (_tmpPos == origPosition) {
_realPos = i;
break;
}
_prefixHasChar = true;
}
}
return _realPos;
}
// inner class
// contact search status
enum ContactSearchStatus {
NONESEARCH, SEARCHBYNAME, SEARCHBYCHINESENAME, SEARCHBYPHONE
}
// contacts in address book listView quick alphabet bar on touch listener
class ContactsInABListViewQuickAlphabetBarOnTouchListener extends
OnTouchListener {
@Override
protected boolean onTouch(RelativeLayout alphabetRelativeLayout,
ListView dependentListView, MotionEvent event,
Character alphabeticalCharacter) {
// get scroll position
if (dependentListView.getAdapter() instanceof CTListAdapter) {
// get dependent listView adapter
CTListAdapter _commonListAdapter = (CTListAdapter) dependentListView
.getAdapter();
for (int i = 0; i < _commonListAdapter.getCount(); i++) {
// get alphabet index
@SuppressWarnings("unchecked")
String _alphabetIndex = (String) ((Map<String, ?>) _commonListAdapter
.getItem(i)).get(CTListAdapter.ALPHABET_INDEX);
// check alphabet index
if (null == _alphabetIndex
|| _alphabetIndex.startsWith(String.valueOf(
alphabeticalCharacter).toLowerCase())) {
// set selection
dependentListView.setSelection(i);
break;
}
}
} else {
Log.e(LOG_TAG, "Dependent listView adapter = "
+ dependentListView.getAdapter() + " and class name = "
+ dependentListView.getAdapter().getClass().getName());
}
return true;
}
}
private void hideSoftKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(
((EditText) findViewById(R.id.contact_search_editText))
.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
// contacts in address book listView on item click listener
class ContactsInABListViewOnItemClickListener implements
OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// hide input method manager not always
hideSoftKeyboard();
// get the click item view data: contact object
ContactBean _clickItemViewData = _mPresentContactsInABInfoArray
.get((int) id);
// check the click item view data
if (null == _clickItemViewData.getPhoneNumbers()) {
// show contact has no phone number alert dialog
new AlertDialog.Builder(ContactLisInviteFriendActivity.this)
.setTitle(R.string.contact_hasNoPhone_alertDialog_title)
.setMessage(_clickItemViewData.getDisplayName())
.setPositiveButton(
R.string.contact_hasNoPhone_alertDialog_reselectBtn_title,
null).show();
} else {
boolean isSelected = (Boolean) _clickItemViewData
.getExtension().get(CONTACT_IS_SELECTED);
if (!isSelected) {
switch (_clickItemViewData.getPhoneNumbers().size()) {
case 1:
_mInviteFriendsInfo.add(_clickItemViewData);
_clickItemViewData.getExtension().put(SELECTED_PHONE,
_clickItemViewData.getPhoneNumbers().get(0));
_clickItemViewData.getExtension().put(
CONTACT_IS_SELECTED, true);
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) _mABContactsListView
.getAdapter().getItem(position);
map.put(CONTACT_IS_SELECTED, true);
// 暂存之前显示号码的方式,为取消时恢复号码之前显示
Object phonesObj = map.get(PRESENT_CONTACT_PHONES);
_clickItemViewData.getExtension().put(
PREVIOUS_PHONES_STYLE, phonesObj);
// 将选择号码显示为红色
SpannableString _formatPhoneNumberString = new SpannableString(
_clickItemViewData.getFormatPhoneNumbers());
_formatPhoneNumberString.setSpan(
new ForegroundColorSpan(Color.RED), 0,
_clickItemViewData.getPhoneNumbers().get(0)
.length(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
map.put(PRESENT_CONTACT_PHONES,
_formatPhoneNumberString);
((InviteFriendContactAdapter) _mABContactsListView
.getAdapter()).notifyDataSetChanged();
break;
default:
_mContactPhoneNumbersSelectPopupWindow
.setContactPhones4Selecting(
_clickItemViewData.getDisplayName(),
_clickItemViewData.getPhoneNumbers(),
position);
// show contact phone numbers select popup window
_mContactPhoneNumbersSelectPopupWindow.showAtLocation(
parent, Gravity.CENTER, 0, 0);
break;
}
} else {
_mInviteFriendsInfo.remove(_clickItemViewData);
_clickItemViewData.getExtension().put(CONTACT_IS_SELECTED,
false);
_clickItemViewData.getExtension().put(SELECTED_PHONE, "");
Object phoneObj = _clickItemViewData.getExtension().get(
PREVIOUS_PHONES_STYLE);
_clickItemViewData.getExtension().put(
PREVIOUS_PHONES_STYLE, "");
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) _mABContactsListView
.getAdapter().getItem(position);
if (phoneObj != null) {
map.put(PRESENT_CONTACT_PHONES, phoneObj);
}
map.put(CONTACT_IS_SELECTED, false);
((InviteFriendContactAdapter) _mABContactsListView
.getAdapter()).notifyDataSetChanged();
}
}
}
}
// contact search editText text watcher
class ContactSearchEditTextTextWatcher implements TextWatcher {
@Override
public void afterTextChanged(Editable s) {
// set contact search status
if (null == s || 0 == s.length()) {
_mContactSearchStatus = ContactSearchStatus.NONESEARCH;
} else if (s.toString().matches("^[0-9]*$")) {
_mContactSearchStatus = ContactSearchStatus.SEARCHBYPHONE;
} else if (s.toString().matches(".*[\u4e00-\u9fa5].*")) {
_mContactSearchStatus = ContactSearchStatus.SEARCHBYCHINESENAME;
} else {
_mContactSearchStatus = ContactSearchStatus.SEARCHBYNAME;
}
// update present contacts in address book detail info list
switch (_mContactSearchStatus) {
case SEARCHBYNAME:
_mPresentContactsInABInfoArray = AddressBookManager
.getInstance().getContactsByName(s.toString());
break;
case SEARCHBYCHINESENAME:
_mPresentContactsInABInfoArray = AddressBookManager
.getInstance().getContactsByChineseName(s.toString());
break;
case SEARCHBYPHONE:
_mPresentContactsInABInfoArray = AddressBookManager
.getInstance().getContactsByPhone(s.toString());
break;
case NONESEARCH:
default:
_mPresentContactsInABInfoArray = _mAllNamePhoneticSortedContactsInfoArray;
break;
}
// update contacts in address book listView adapter
_mABContactsListView.setAdapter(generateInABContactAdapter(
ContactLisInviteFriendActivity.this, true,
_mPresentContactsInABInfoArray));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
}
// contact phone numbers select popup window
class ContactPhoneNumbersSelectPopupWindow extends CTPopupWindow {
// dial contact phone mode
public ContactPhoneNumbersSelectPopupWindow(int resource, int width,
int height, boolean focusable, boolean isBindDefListener) {
super(resource, width, height, focusable, isBindDefListener);
}
public ContactPhoneNumbersSelectPopupWindow(int resource, int width,
int height) {
super(resource, width, height);
}
@Override
protected void bindPopupWindowComponentsListener() {
// get contact phones select phone button parent linearLayout
LinearLayout _phoneBtnParentLinearLayout = (LinearLayout) getContentView()
.findViewById(
R.id.contactPhones_select_phoneBtn_linearLayout);
// bind contact phone select phone button click listener
for (int i = 0; i < _phoneBtnParentLinearLayout.getChildCount(); i++) {
((Button) _phoneBtnParentLinearLayout.getChildAt(i))
.setOnClickListener(new ContactPhoneSelectPhoneBtnOnClickListener());
}
// bind contact phone select phone listView item click listener
((ListView) getContentView().findViewById(
R.id.contactPhones_select_phonesListView))
.setOnItemClickListener(new ContactPhoneSelectPhoneListViewOnItemClickListener());
// bind contact phone select cancel button click listener
((Button) getContentView().findViewById(
R.id.contactPhones_select_cancelBtn))
.setOnClickListener(new ContactPhoneSelectCancelBtnOnClickListener());
}
@Override
protected void resetPopupWindow() {
// hide contact phones select phone list view
((ListView) getContentView().findViewById(
R.id.contactPhones_select_phonesListView))
.setVisibility(View.GONE);
// get contact phones select phone button parent linearLayout and
// hide it
LinearLayout _phoneBtnParentLinearLayout = (LinearLayout) getContentView()
.findViewById(
R.id.contactPhones_select_phoneBtn_linearLayout);
_phoneBtnParentLinearLayout.setVisibility(View.GONE);
// process phone button
for (int i = 0; i < _phoneBtnParentLinearLayout.getChildCount(); i++) {
// hide contact phones select phone button
((Button) _phoneBtnParentLinearLayout.getChildAt(i))
.setVisibility(View.GONE);
}
}
// set contact phone number for selecting
public void setContactPhones4Selecting(String displayName,
List<String> phoneNumbers, int position) {
// update select contact display name and dial its phone mode
selectedPosition = position;
// set contact phones select title textView text
((TextView) getContentView().findViewById(
R.id.contactPhones_select_titleTextView))
.setText(CTApplication.getContext().getResources()
.getString(R.string.select_phone_to_invite)
.replace("***", displayName));
// check phone numbers for selecting
if (2 <= phoneNumbers.size() && phoneNumbers.size() <= 3) {
// get contact phones select phone button parent linearLayout
// and show it
LinearLayout _phoneBtnParentLinearLayout = (LinearLayout) getContentView()
.findViewById(
R.id.contactPhones_select_phoneBtn_linearLayout);
_phoneBtnParentLinearLayout.setVisibility(View.VISIBLE);
// process phone button
for (int i = 0; i < phoneNumbers.size(); i++) {
// get contact phones select phone button
Button _phoneBtn = (Button) _phoneBtnParentLinearLayout
.getChildAt(i);
// set button text and show it
_phoneBtn.setText(phoneNumbers.get(i));
_phoneBtn.setVisibility(View.VISIBLE);
}
} else {
// get contact phones select phone list view
ListView _phoneListView = (ListView) getContentView()
.findViewById(R.id.contactPhones_select_phonesListView);
// set phone list view adapter
_phoneListView
.setAdapter(new ArrayAdapter<String>(
CTApplication.getContext(),
R.layout.contact_phonenumbers_select_phoneslist_item_layout,
phoneNumbers));
// show phone list view
_phoneListView.setVisibility(View.VISIBLE);
}
}
// inner class
// contact phone select phone button on click listener
class ContactPhoneSelectPhoneBtnOnClickListener implements
OnClickListener {
@Override
public void onClick(View v) {
// get phone button text
String _selectedPhone = (String) ((Button) v).getText();
choosePhone2Invite(_selectedPhone);
}
}
private void choosePhone2Invite(String _selectedPhone) {
ContactBean _clickItemViewData = _mPresentContactsInABInfoArray
.get(selectedPosition);
_mInviteFriendsInfo.add(_clickItemViewData);
_clickItemViewData.getExtension().put(SELECTED_PHONE,
_selectedPhone);
_clickItemViewData.getExtension().put(CONTACT_IS_SELECTED, true);
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) _mABContactsListView
.getAdapter().getItem(selectedPosition);
map.put(CONTACT_IS_SELECTED, true);
// 暂存之前显示号码的方式,为取消时恢复号码之前显示
Object phonesObj = map.get(PRESENT_CONTACT_PHONES);
_clickItemViewData.getExtension().put(PREVIOUS_PHONES_STYLE,
phonesObj);
// 将选择号码显示为红色
SpannableString _formatPhoneNumberString = null;
if (phonesObj instanceof String) {
_formatPhoneNumberString = new SpannableString(
(String) phonesObj);
} else if (phonesObj instanceof SpannableString) {
_formatPhoneNumberString = new SpannableString(
(SpannableString) phonesObj);
}
String allPhones = _clickItemViewData.getFormatPhoneNumbers();
int begin = allPhones.indexOf(_selectedPhone);
int end = begin + _selectedPhone.length();
_formatPhoneNumberString.setSpan(
new ForegroundColorSpan(Color.RED), begin, end,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
map.put(PRESENT_CONTACT_PHONES, _formatPhoneNumberString);
((InviteFriendContactAdapter) _mABContactsListView.getAdapter())
.notifyDataSetChanged();
// dismiss contact phone select popup window
dismiss();
}
// contact phone select phone listView on item click listener
class ContactPhoneSelectPhoneListViewOnItemClickListener implements
OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// get phone listView item data
String _selectedPhone = (String) ((TextView) view).getText();
choosePhone2Invite(_selectedPhone);
}
}
// contact phone select cancel button on click listener
class ContactPhoneSelectCancelBtnOnClickListener implements
OnClickListener {
@Override
public void onClick(View v) {
// dismiss contact phone select popup window
dismiss();
}
}
}
public void onConfirm(View v) {
if (_mInviteFriendsInfo.size() > 0) {
StringBuffer toNumbers = new StringBuffer();
for (ContactBean b : _mInviteFriendsInfo) {
toNumbers.append((String) b.getExtension().get(SELECTED_PHONE))
.append(";");
}
Uri uri = Uri.parse("smsto:" + toNumbers.toString());
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
String inviteMessage = getString(R.string.invite_message).replace(
"***", inviteLink);
intent.putExtra("sms_body", inviteMessage);
startActivity(intent);
} else {
MyToast.show(ContactLisInviteFriendActivity.this,
R.string.pls_choose_invite_people, Toast.LENGTH_SHORT);
}
}
public void onCancel(View v) {
finish();
}
@Override
public void onDestroy() {
resetContact();
super.onDestroy();
}
private void resetContact() {
for (ContactBean b : _mInviteFriendsInfo) {
b.getExtension().put(CONTACT_IS_SELECTED, false);
b.getExtension().put(SELECTED_PHONE, "");
}
_mInviteFriendsInfo.clear();
}
class UpdateABListHandler extends Handler {
public UpdateABListHandler() {
super();
}
public void handleMessage(Message msg) {
int type = msg.what;
// Log.d("Contact", "getMessage : " + type);
if (type == 1) {
// contacts have been create or delete
AddressBookManager.getInstance().copyAllContactsInfo(
_mAllNamePhoneticSortedContactsInfoArray);
}
String searchString = ((EditText) ContactLisInviteFriendActivity.this
.findViewById(R.id.contact_search_editText)).getText()
.toString();
// Log.d("ContactSelectActivity", "searchString :" + searchString);
// Log.d("ContactSelectActivity", "searchStatus :" +
// _mContactSearchStatus);
switch (_mContactSearchStatus) {
case SEARCHBYNAME:
_mPresentContactsInABInfoArray = AddressBookManager
.getInstance().getContactsByName(
searchString.toString());
break;
case SEARCHBYCHINESENAME:
_mPresentContactsInABInfoArray = AddressBookManager
.getInstance().getContactsByChineseName(
searchString.toString());
break;
case SEARCHBYPHONE:
_mPresentContactsInABInfoArray = AddressBookManager
.getInstance().getContactsByPhone(
searchString.toString());
break;
case NONESEARCH:
default:
_mPresentContactsInABInfoArray = _mAllNamePhoneticSortedContactsInfoArray;
break;
}
// update contacts in address book listView adapter
Log.d(SystemConstants.TAG, "_mPresentContactsInABInfoArray: "
+ _mPresentContactsInABInfoArray);
_mABContactsListView.setAdapter(generateInABContactAdapter(
ContactLisInviteFriendActivity.this, true,
_mPresentContactsInABInfoArray));
}
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.d(SystemConstants.TAG,
"ContactLisInviteFriendActivity - onRestoreInstanceState");
AppDataSaveRestoreUtil.onRestoreInstanceState(savedInstanceState);
initNamePhoneticSortedContactsInfoArray();
initListUI();
AddressBookManager.getInstance().addContactObserverhandler(
listUpdateHandler);
super.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
AppDataSaveRestoreUtil.onSaveInstanceState(outState);
super.onSaveInstanceState(outState);
}
@Override
protected void onPause() {
if (ctToast != null) {
ctToast.cancel();
}
super.onPause();
}
}
|
Java
|
UTF-8
| 6,368 | 2.28125 | 2 |
[] |
no_license
|
package org.cruxframework.test.cruxtestwidgets.client;
import java.util.Date;
import org.cruxframework.crux.core.client.controller.Controller;
import org.cruxframework.crux.core.client.controller.Expose;
import org.cruxframework.crux.core.client.ioc.Inject;
import org.cruxframework.crux.core.client.rest.Callback;
import org.cruxframework.crux.core.client.screen.views.BindView;
import org.cruxframework.crux.core.client.screen.views.WidgetAccessor;
import org.cruxframework.crux.widgets.client.dialog.FlatMessageBox;
import org.cruxframework.crux.widgets.client.dialog.FlatMessageBox.MessageType;
import org.cruxframework.test.cruxtestwidgets.client.modelo.Endereco;
import org.cruxframework.test.cruxtestwidgets.client.modelo.Pessoa;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
@Controller("myRestController")
public class MyRestController {
@Inject
private MyRestClient service;
@Inject
private RestView restView;
public void setService(MyRestClient service) {
this.service = service;
}
public void setRestView(RestView restView) {
this.restView = restView;
}
@Expose
public void enviarInteiro(){
Integer in = Integer.parseInt(restView.gwtTxbObjetoSimples().getValue());
service.enviarInteiro(in, new Callback<Integer>(){
@Override
public void onSuccess(Integer result) {
String msg = Integer.toString(result);
FlatMessageBox.show(msg, MessageType.INFO);
}
@Override
public void onError(Exception e) {
FlatMessageBox.show("Falha ao receber o inteiro ", MessageType.WARN);
}
});
}
@Expose
public void enviarString(){
String palavra = restView.gwtTxbObjetoSimples().getValue();
service.enviarString(palavra, new Callback<String>(){
@Override
public void onSuccess(String result) {
FlatMessageBox.show(result, MessageType.INFO);
}
@Override
public void onError(Exception e) {
FlatMessageBox.show("Falha ao receber a palavra ", MessageType.WARN);
}
});
}
@Expose
public void enviarDouble(){
Double numero = Double.parseDouble(restView.gwtTxbObjetoSimples().getValue());
service.enviarDouble(numero, new Callback<Double>() {
@Override
public void onSuccess(Double result) {
FlatMessageBox.show(""+result, MessageType.INFO);
}
@Override
public void onError(Exception e) {
FlatMessageBox.show("Falha ao receber o double ", MessageType.WARN);
}
});
}
@Expose
public void enviarChar(){
Character c = new Character(restView.gwtTxbObjetoSimples().getValue().charAt(0));
service.enviarChar(c, new Callback<Character>() {
@Override
public void onSuccess(Character result) {
FlatMessageBox.show(""+result, MessageType.INFO);
}
@Override
public void onError(Exception e) {
FlatMessageBox.show("Falha ao receber o caracter ", MessageType.INFO);
e.printStackTrace();
}
});
}
@Expose
public void enviarPessoa(){
Pessoa p = getInformacoePessoa();
service.enviarPessoa(p, new Callback<Pessoa>(){
@Override
public void onSuccess(Pessoa result) {
String end = "BAIRRO: "+result.getEndereco().getBairro() + " - "
+"RUA: "+ result.getEndereco().getRua() + " - "
+"CIDADE: "+ result.getEndereco().getCidade() + " - "
+"NUMERO: "+ result.getEndereco().getNumero().toString();
String pess = "NOME: " + result.getNome() + " - "
+ "IDADE: " + result.getIdade() + " - "
+ "CPF: " + result.getCpf() + " - " ;
String msg = "SEUS DADOS: " + pess + end;
FlatMessageBox.show(msg, MessageType.INFO);
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
@Expose
public void enviarData(){
final DateTimeFormat formatter = DateTimeFormat.getFormat("dd/MM/yyyy HH:mm:ss");
Date data = formatter.parse(restView.gwtTxtData().getText());
restView.lbAntesDeEnviar().setText("Enviado: " + formatter.format((Date) data));
service.enviarData(data, new Callback<Date>() {
@Override
public void onSuccess(Date result) {
restView.lbResposta().setText("Recebido: "+ formatter.format((Date) result));
}
@Override
public void onError(Exception e) {
e.printStackTrace();
}
});
}
@Expose
public void clear(){
restView.gwtTxbObjetoSimples().setText("");
restView.gwtTxbNome().setText("");
restView.gwtTxbIdade().setText("");
restView.gwtTxbCPF().setText("");
restView.gwtTxbRua().setText("");
restView.gwtTxbNumero().setText("");
restView.gwtTxbBairro().setText("");
restView.gwtTxbCidade().setText("");
restView.gwtTxtData().setText("");
restView.lbAntesDeEnviar().setText("");
restView.lbResposta().setText("");
}
private Pessoa getInformacoePessoa(){
Pessoa p = new Pessoa();
Endereco e = new Endereco();
p.setNome(restView.gwtTxbNome().getText());
p.setIdade(Integer.parseInt(restView.gwtTxbIdade().getText()));
p.setCpf(restView.gwtTxbCPF().getText());
e.setBairro(restView.gwtTxbBairro().getText());
e.setCidade(restView.gwtTxbCidade().getText());
e.setNumero(Double.parseDouble(restView.gwtTxbNumero().getText()));
e.setRua(restView.gwtTxbRua().getText());
p.setEndereco(e);
return p;
}
@BindView("rest")
public static interface RestView extends WidgetAccessor{
TextBox gwtTxbObjetoSimples();
TextBox gwtTxbNome();
TextBox gwtTxbIdade();
TextBox gwtTxbCPF();
TextBox gwtTxbRua();
TextBox gwtTxbNumero();
TextBox gwtTxbBairro();
TextBox gwtTxbCidade();
TextBox gwtTxtData();
Label lbAntesDeEnviar();
Label lbResposta();
}
}
|
Java
|
UTF-8
| 1,512 | 2.6875 | 3 |
[] |
no_license
|
package redgear.core.block;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.ItemBlock;
import redgear.core.util.StringHelper;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/**
* This class is great for blocks that don't do anything special, or a a parent
* for those that do
*
* @author Blackhole
*
*/
public class BlockGeneric extends Block {
protected final String name;
protected final String modName;
/**
* Use this if your item has a typical icon
*
* @param Id The typical ItemId
* @param name Name of item's icon
*/
public BlockGeneric(Material material, String name) {
this(material, name, ItemBlock.class);
}
public BlockGeneric(Material material, String name, Class<? extends ItemBlock> item) {
super(material);
this.name = name;
modName = StringHelper.parseModAsset();
GameRegistry.registerBlock(this, item, name);
}
/**
* Override this function if your item has an unusual icon/multiple icons
*/
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister par1IconRegister) {
blockIcon = par1IconRegister.registerIcon(modName + name);
}
/**
* Returns the unlocalized name of the block with "tile." appended to the front.
*/
public String getUnlocalizedName()
{
return "tile." + this.name;
}
}
|
Java
|
UTF-8
| 1,065 | 3.203125 | 3 |
[] |
no_license
|
package hr.fer.zemris.java.gui.layouts;
/**
* This class represents constraints for the costum layout manager.
*
* @author Lovro Marković
*
*/
public class RCPosition {
/**
* Row position.
*/
private int row;
/**
* Column position.
*/
private int column;
/**
* Constructor. Initializes row and column values.
*
* @param row
* Value of row.
* @param column
* Value of column.
*/
public RCPosition(int row, int column) {
super();
this.row = row;
this.column = column;
}
/**
* @return Return column value.
*/
public int getColumn() {
return column;
}
/**
* @return Returns row value.
*/
public int getRow() {
return row;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof RCPosition)) {
return false;
}
RCPosition rcObj = (RCPosition) obj;
return (rcObj.row == this.row) && (rcObj.column == this.column);
}
@Override
public int hashCode() {
return Integer.hashCode(column + row);
}
}
|
Java
|
UTF-8
| 1,416 | 2 | 2 |
[] |
no_license
|
package com.pj.keycloak.model;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import lombok.Data;
@Entity
@Table(name = "resource")
@Data
public class Resource implements Serializable{
/**
*
*/
private static final long serialVersionUID = -1922700495609379588L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "resource_id")
private int resourse_id;
@Column(name = "name")
private String name;
@Column(name = "description")
private Boolean description;
@OneToMany(mappedBy = "resource")
Set<RoleResource> previlleges;
public int getResourse_id() {
return resourse_id;
}
public void setResourse_id(int resourse_id) {
this.resourse_id = resourse_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getDescription() {
return description;
}
public void setDescription(Boolean description) {
this.description = description;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
TypeScript
|
UTF-8
| 360 | 2.5625 | 3 |
[] |
no_license
|
import { Pipe, PipeTransform } from '@angular/core';
import { IUsuario } from '../clases/usuario';
@Pipe({
name: 'tipo'
})
export class TipoPipe implements PipeTransform {
transform(lista: IUsuario[], tipo: string): IUsuario[] {
if(tipo == 'todos'){
return lista;
} else {
return lista.filter(item => item.tipo == tipo);
}
}
}
|
C++
|
UTF-8
| 1,186 | 2.875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
#include <cmath>
#include <math.h>
void displayArray(int x[], int n);
void merge(int A[], int l, int m, int r);
void mergeSort(int A[], int p, int r);
int main() {
//int x[] = {5,3,2,5,1,6,3,6,2,3,5,5123,1,3,989,1,1,5,2,3,3,15,1,13,123,5123,512,3512,36,1236,1236,123,12351};
int x[] = {5,3,2,5,1,6,3,6,2,3,5,5123,1,3,989,1,1,5,2,3,3,15,1,13,123,5123,512,3512,36,1236,1236,123,12351,4};
//int x[] = {1,3,5,2,4};
int n = sizeof(x)/sizeof(x[0])-1;
mergeSort(x,0,n);
displayArray(x,n+1);
}
void displayArray(int x[], int n){
for(int i = 0; i<n ; i++)
cout<<x[i]<<" ";
cout<<endl;
}
void mergeSort(int A[], int p, int r){
if(p<r){
int q = (p+r)/2;
mergeSort(A,p,q);
mergeSort(A,q+1,r);
merge(A,p,q,r);
}
}
void merge(int A[], int p, int q, int r){
int n1 = q-p+1; int n2 = r-q;
int L[n1], R[n2];
for(int i = 0; i<n1; i++)
L[i] = A[p+i];
for(int i = 0; i<n2; i++)
R[i] = A[q+i+1];
int i = 0, j=0, k = p;
while(i < n1 and j < n2){
if(L[i]<=R[j]){
A[k] = L[i]; i++; k++;
}else{
A[k] = R[j]; j++; k++;
}
}
while(i < n1){
A[k] = L[i];i++; k++;
}
while(j < n2){
A[k] = R[j]; j++; k++;
}
}
|
C#
|
UTF-8
| 1,506 | 2.578125 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
namespace VK_Music
{
class DownloadClient
{
public DownloadClient(CheckedListBox.CheckedIndexCollection _collect, string _patch)
{
this.Collect = _collect;
this.Count = _collect.Count;
this.Iter = 0;
this.Patch = _patch;
}
public void DownloadF()
{
/*WebClient client = new WebClient();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFileCompleted += client_DownloadFileCompleted;
client.DownloadFileTaskAsync(new Uri(VK_Audio.linksList[Collect[Iter]]), Patch + "\\" + VK_Audio.audioList[Collect[Iter]] + ".mp3");*/
}
void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
}
private CheckedListBox.CheckedIndexCollection Collect;
private int Count,
Iter;
private string Patch;
}
}
|
Go
|
UTF-8
| 4,954 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
package packetio
import (
"bufio"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"sync"
)
var consoleLog = log.New(os.Stdout, "[packetio] ", log.LstdFlags)
// DEBUG is switcher for debug
var DEBUG = false
const (
defaultReaderSize int = 8 * 1024
maxPayloadLen int = 1<<24 - 1
)
// Error Code
var (
ErrBadConn = errors.New("bad conn")
)
// PacketIO is a packet transfer on network.
type PacketIO struct {
rb *bufio.Reader
wb io.Writer
rseq uint8
wseq uint8
rl *sync.Mutex
wl *sync.Mutex
}
// New is to create PacketIO
func New(conn net.Conn) *PacketIO {
p := new(PacketIO)
p.rb = bufio.NewReaderSize(conn, defaultReaderSize)
p.wb = conn
p.rseq = 0
p.wseq = 0
p.rl = new(sync.Mutex)
p.wl = new(sync.Mutex)
return p
}
// ReadPacket is to read packet.
func (p *PacketIO) ReadPacket() ([]byte, error) {
defer p.rl.Unlock()
p.rl.Lock()
p.rseq = 0
header := []byte{0, 0, 0, 0}
if _, err := io.ReadFull(p.rb, header); err != nil {
header = nil
if DEBUG {
consoleLog.Println(err)
}
return nil, ErrBadConn
}
length := int(uint32(header[0]) | uint32(header[1])<<8 | uint32(header[2])<<16)
if length < 1 {
header = nil
return nil, fmt.Errorf("invalid payload length %d", length)
}
sequence := uint8(header[3])
if sequence != p.rseq {
header = nil
return nil, fmt.Errorf("invalid sequence %d != %d", sequence, p.rseq)
}
p.rseq++
total := make([]byte, length)
if _, err := io.ReadFull(p.rb, total); err != nil {
header = nil
total = nil
if DEBUG {
consoleLog.Println(err)
}
return nil, ErrBadConn
}
for length == maxPayloadLen {
header = []byte{0, 0, 0, 0}
if _, err := io.ReadFull(p.rb, header); err != nil {
header = nil
total = nil
if DEBUG {
consoleLog.Println(err)
}
return nil, ErrBadConn
}
length = int(uint32(header[0]) | uint32(header[1])<<8 | uint32(header[2])<<16)
if length < 1 {
header = nil
total = nil
return nil, fmt.Errorf("invalid payload length %d", length)
}
sequence = uint8(header[3])
if sequence != p.rseq {
header = nil
total = nil
return nil, fmt.Errorf("invalid sequence %d != %d", sequence, p.rseq)
}
p.rseq++
data := make([]byte, length)
if _, err := io.ReadFull(p.rb, data); err != nil {
header = nil
total = nil
data = nil
if DEBUG {
consoleLog.Println(err)
}
return nil, ErrBadConn
}
total = append(total, data...)
data = nil
}
if DEBUG {
consoleLog.Println("ReadPacket", total)
}
return total, nil
}
// WritePacket is to write packet.
func (p *PacketIO) WritePacket(data []byte) error {
defer p.wl.Unlock()
p.wl.Lock()
p.wseq = 0
length := len(data)
for length >= maxPayloadLen {
buffer := make([]byte, 4, 4+maxPayloadLen)
buffer[0] = 0xff
buffer[1] = 0xff
buffer[2] = 0xff
buffer[3] = p.wseq
buffer = append(buffer, data[:maxPayloadLen]...)
if n, err := p.wb.Write(buffer); err != nil {
buffer = nil
if DEBUG {
consoleLog.Println(err)
}
return ErrBadConn
} else if n != (4 + maxPayloadLen) {
buffer = nil
return ErrBadConn
} else {
p.wseq++
length -= maxPayloadLen
data = data[maxPayloadLen:]
}
}
buffer := make([]byte, 4, 4+length)
buffer[0] = byte(length)
buffer[1] = byte(length >> 8)
buffer[2] = byte(length >> 16)
buffer[3] = p.wseq
buffer = append(buffer, data...)
if n, err := p.wb.Write(buffer); err != nil {
buffer = nil
if DEBUG {
consoleLog.Println(err)
}
return ErrBadConn
} else if n != len(data)+4 {
buffer = nil
return ErrBadConn
} else {
p.wseq++
if DEBUG {
consoleLog.Println("WritePacket", append(buffer, data...))
}
return nil
}
}
// WritePacketBatch is to write packet in batch
func (p *PacketIO) WritePacketBatch(total, data []byte, direct bool) ([]byte, error) {
defer p.wl.Unlock()
p.wl.Lock()
p.wseq = 0
if data == nil {
if direct == true {
n, err := p.wb.Write(total)
if err != nil {
total = nil
if DEBUG {
consoleLog.Println(err)
}
return nil, ErrBadConn
}
if n != len(total) {
total = nil
return nil, ErrBadConn
}
if DEBUG {
consoleLog.Println("WritePacketBatch", total)
}
}
return total, nil
}
length := len(data)
for length >= maxPayloadLen {
header := []byte{0xff, 0xff, 0xff, p.wseq}
total = append(total, header...)
total = append(total, data[:maxPayloadLen]...)
p.wseq++
length -= maxPayloadLen
data = data[maxPayloadLen:]
}
header := []byte{byte(length), byte(length >> 8), byte(length >> 16), p.wseq}
total = append(total, header...)
total = append(total, data[:maxPayloadLen]...)
p.wseq++
if direct {
if n, err := p.wb.Write(total); err != nil {
total = nil
data = nil
if DEBUG {
consoleLog.Println(err)
}
return nil, ErrBadConn
} else if n != len(total) {
total = nil
data = nil
return nil, ErrBadConn
}
if DEBUG {
consoleLog.Println("WritePacketBatch", total)
}
}
return total, nil
}
|
Java
|
UTF-8
| 749 | 2.125 | 2 |
[] |
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 yucroq.entity;
import java.util.LinkedList;
import java.util.List;
import javax.persistence.*;
import lombok.*;
@Entity
// Lombok
@Getter @Setter @NoArgsConstructor @RequiredArgsConstructor @ToString
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Setter(AccessLevel.NONE)
private Integer id;
@NonNull
@Column(unique = true)
private String name;
@ManyToMany(mappedBy = "roles")
@ToString.Exclude
@Setter(AccessLevel.NONE)
private List<Proprietaire> users = new LinkedList<>();
}
|
C
|
ISO-8859-1
| 3,356 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
//
// POV (Persistence of Vision)
//
// (C) 2015, Daniel Quadros
//
// ----------------------------------------------------------------------------
// "THE BEER-WARE LICENSE" (Revision 42):
// <dqsoft.blogspot@gmail.com> wrote this file. As long as you retain this
// notice you can do whatever you want with this stuff. If we meet some day,
// and you think this stuff is worth it, you can buy me a beer in return.
// Daniel Quadros
// ----------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <avr/io.h>
#include <avr/interrupt.h>
// Conexes do hardware
#define SENSOR _BV(PB0)
#define LED_VD _BV(PB1)
// Variaveis
static const uint8_t imagem[16] =
{
0x80, 0xC1, 0x82, 0xC3, 0x84, 0xC5, 0x86, 0xC7,
0x88, 0xC9, 0x8A, 0xCB, 0x8C, 0xFD, 0x8E, 0x00
};
// Rotinas
static void initHw (void);
// Programa principal
int main(void)
{
uint8_t fOvf = 1;
uint8_t fSensor = 0;
uint16_t tempo = 0;
uint16_t prox = 0;
uint16_t passo = 0;
uint8_t setor = 0;
// Inicia o hardware
initHw ();
// Eterno equanto dure
for (;;)
{
// Trata o sensor
if (fSensor)
{
// j detectou o sensor, aguardando desligar
fSensor = (PINB & SENSOR) == 0;
if (!fSensor)
PORTB &= ~LED_VD; // apaga LED verde
}
else if ((PINB & SENSOR) == 0)
{
// Detectou sensor
if (fOvf == 0)
{
// funcionamento normal
tempo = TCNT1; // registra o tempo da volta
PORTA = imagem [0]; // LEDs para o primeiro setor
passo = tempo >> 4; // divide a volta em 16 setores
prox = passo;
setor = 1;
}
else
{
// ultrapassou o tempo mximo
fOvf = 0; // limpa o flag, vamos tentar de novo
}
TCNT1 = 0; // reinicia a contagem de tempo
fSensor = 1; // lembra que detectou o sensor
PORTB |= LED_VD; // indica deteco
}
// Testa overflow do timer
if (TIFR1 & _BV(TOV1))
{
fOvf = 1; // ultrapassou o tempo mximo
PORTA = 0; // apaga os LEDs
tempo = 0; // no atualizar os LEDs
TIFR1 |= _BV(TOV1); // limpa o aviso do timer
}
// Atualiza os LEDs
if (tempo != 0)
{
if (TCNT1 >= prox)
{
PORTA = imagem [setor++]; // passa para o setor seguinte
prox += passo;
if (setor == 16)
tempo = 0; // acabaram os setores
}
}
}
}
// Inicia o hardware
static void initHw (void)
{
// Port A so os LEDs
DDRA = 0xFF; // tudo saida
PORTA = 0; // LEDs apagados
// PORT B tem o sensor e o LED verde
DDRB &= ~SENSOR; // sensor entrada
DDRB |= LED_VD; // LED saida
PORTB = SENSOR; // com pullup
// Timer 1
// Modo normal, clock/1024
TCCR1A = 0;
TCCR1B = _BV(CS12) | _BV(CS10);
TCCR1C = 0;
}
|
JavaScript
|
UTF-8
| 783 | 2.6875 | 3 |
[] |
no_license
|
const PropsMap = {
children: "innerHTML"
}
const Events = {
SUBMIT: "submit",
CLICK: "click"
}
function addListeners(el, events) {
Object.keys(events).forEach(e => {
el.addEventListener(e, events[e])
})
}
function createElement(type, props = {}, events = {}) {
const el = document.createElement(type);
addListeners(el, events)
Object.keys(props).forEach(key => {
if (!!PropsMap[key]) {
el[PropsMap[key]] = props[key]
return el
}
el[key] = props[key]
})
return el
}
function append(parent, ...children) {
children.forEach(el => {
if (!el) return;
if (el instanceof Array) {
append(parent, ...el)
return
}
parent.appendChild(el)
})
return parent
}
export {
createElement,
append,
Events
}
|
C++
|
UTF-8
| 2,397 | 3.71875 | 4 |
[] |
no_license
|
#include <iostream>
#include<iomanip>
#include<fstream>
#include<vector>
#include<cstdlib>
#include<string>
#include<algorithm>
void ShowStr(const std::string & str) { std::cout << str << std::endl; }
using vstr = std::vector<std::string>;
std::ifstream & GetStrs(std::ifstream & fin, vstr &vistr);
class Store
{
char * pi;
std::ofstream * fout;
public:
Store(std::ofstream & fout);
Store(const Store &s);
bool operator()(const std::string &str);
char * data(const std::string & str);
~Store() { delete[] pi; }
};
const int LIMIN(50);
using std::cout;
using std::endl;
int main()
{
using std::string;
using std::endl;
using std::cin;
using std::cout;
using std::vector;
using std::ios;
vstr vostr;
string temp;
cout << "Enter strings (empty line to quit):\n";
while (getline(cin, temp) && temp[0] != '\0')
vostr.push_back(temp);
cout << "Here is your input.\n";
for_each(vostr.begin(), vostr.end(), ShowStr);
std::ofstream fout("strings.dat", ios::out | ios::binary);
for_each(vostr.begin(), vostr.end(), Store(fout));//使用前必须知道Store时函数符,而不是声明的一个Store类。(在之前必须写好Store时一个函数符)main后面定义Store类时不允许的。
fout.close();
vstr vistr;
std::ifstream fin("strings.dat", ios::in | ios::binary);
if (!fin.is_open())
{
std::cerr << "Could not open file for input.\n";
exit(EXIT_FAILURE);
}
GetStrs(fin, vistr);
cout << "\nHere are the strings read from the file:\n";
for_each(vistr.begin(), vistr.end(), ShowStr);
return 0;
}
Store::Store(std::ofstream & fout):fout(&fout)
{
pi = new char[LIMIN];
}
bool Store::operator()(const std::string &str)
{
int len = str.length();
if (fout->is_open())//
{
fout->write((char*)&len, sizeof(int));//(char *)len产生越界。
fout->write(data(str), len);
return true;
}
else
{
cout << "fout isn't open.";
exit(EXIT_FAILURE);
return false;
}
}
Store::Store(const Store &s)
{
fout = s.fout;
pi = new char[LIMIN];
for (int i = 0; i < strlen(s.pi); i++)
pi[i] = s.pi[i];
}
char * Store::data(const std::string & str)
{
for (int i = 0; i < str.length(); i++)
{
pi[i] = str[i];
}
return pi;
}
std::ifstream & GetStrs(std::ifstream & fin, vstr &vistr)
{
int len;
while(fin.read((char*)&len, sizeof(int)))
{
char * pd = new char[len];
fin.read(pd, len);
vistr.push_back(pd);
delete[] pd;
}
return fin;
}
|
PHP
|
UTF-8
| 432 | 2.65625 | 3 |
[] |
no_license
|
<?php
session_start();
require_once "pdo.php";
require_once "validation.php";
if (isset($_REQUEST['term']))
{
$stmt = $pdo->prepare('
SELECT name FROM Institution
WHERE name LIKE :prefix'
);
$stmt->execute([
':prefix' => $_REQUEST['term']."%"
]);
$retval = [];
while ( $row = $stmt->fetch(PDO::FETCH_ASSOC) )
{
$retval[] = $row['name'];
}
echo(json_encode($retval, JSON_PRETTY_PRINT));
}
?>
|
Java
|
UTF-8
| 6,099 | 2.015625 | 2 |
[] |
no_license
|
package hw5.servlet;
import hw5.model.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/NextQuarter")
public class NextQuarter extends HttpServlet {
private static final long serialVersionUID = 1L;
public NextQuarter() {
super();
}
@SuppressWarnings({ "unchecked" })
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<String> qtr = (List<String>) request.getSession().getAttribute(
"nextqtr");
List<getset> datalist = (List<getset>) request.getSession()
.getAttribute("datalist");
List<String> donesub = (List<String>) request.getSession()
.getAttribute("donesub");
List<String> showsubcode = new ArrayList<String>();
List<String> showsubname = new ArrayList<String>();
List<String> showsubpre = new ArrayList<String>();
for (int z = 0; z < datalist.size(); z++) {
if (!donesub.contains(datalist.get(z).getCourseCode())) {
if (datalist.get(z).getPrereq().equals(" ")) {
String code = datalist.get(z).getCourseCode();
showsubcode.add(code);
String name = datalist.get(z).getCourseName();
showsubname.add(name);
String prereq = datalist.get(z).getPrereq();
showsubpre.add(prereq);
} else {
List<String> strprereq = new ArrayList<String>();
for (String substring : datalist.get(z).getPrereq()
.split(" ")) {
strprereq.add(substring);
}
if (donesub.containsAll(strprereq)) {
String code = datalist.get(z).getCourseCode();
showsubcode.add(code);
String name = datalist.get(z).getCourseName();
showsubname.add(name);
String prereq = datalist.get(z).getPrereq();
showsubpre.add(prereq);
}
}
}
}
// /////////////////////////////////////////////////////////////////////////////
if (showsubcode.size() == 0) {
response.sendRedirect("finish");
return;
}
String showqtr = qtr.get(qtr.size() - 1);
request.getSession().setAttribute("nextqtr", qtr);
request.getSession().setAttribute("datalist", datalist);
request.getSession().setAttribute("donesub", donesub);
request.setAttribute("showsubcode", showsubcode);
request.setAttribute("showsubname", showsubname);
request.setAttribute("showsubpre", showsubpre);
request.setAttribute("showqtr", showqtr);
request.getRequestDispatcher("/WEB-INF/NextQuarter.jsp").forward(
request, response);
}
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
List<getset> datalist = (List<getset>) request.getSession()
.getAttribute("datalist");
List<String> nextqtr = (List<String>) request.getSession()
.getAttribute("nextqtr");
List<finishmvc> cmplt = (List<finishmvc>) request.getSession()
.getAttribute("cmplt");
List<String> qtrshow = (List<String>) request.getSession()
.getAttribute("qtrshow");
String n = request.getParameter("button");
if (n.equals("Next")) {
int week = (Integer) request.getSession().getAttribute("week");
int year = (Integer) request.getSession().getAttribute("year");
List<String> donesub = (List<String>) request.getSession()
.getAttribute("donesub");
/*
* for (int i = 0; i < datalist.size(); i++) {
* changeobj.add(datalist.get(i));
*
* }
*/
String[] newsub = request.getParameterValues("prereq");
if (newsub != null) {
List<String> selectsub = new ArrayList<String>();
String qtr = nextqtr.get(nextqtr.size() - 1);
for (int f = 0; f < newsub.length; f++) {
selectsub.add(newsub[f]);
cmplt.add(new finishmvc(qtr, newsub[f]));
}
qtrshow.add(qtr);
for (int b = 0; b < selectsub.size(); b++) {
donesub.add(selectsub.get(b));
}
}
// ///////////////////////
week = week + 12;
if (week > 52) {
week = 6;
year++;
}
Quarter q = new Quarter();
nextqtr = q.getQuarter(week, year);
request.getSession().setAttribute("qtrshow", qtrshow);
request.getSession().setAttribute("donesub", donesub);
request.getSession().setAttribute("nextqtr", nextqtr);
request.getSession().setAttribute("cmplt", cmplt);
request.getSession().setAttribute("year", year);
request.getSession().setAttribute("week", week);
request.getSession().setAttribute("datalist", datalist);
response.sendRedirect("NextQuarter");
} else if ("Finish".equals(n)) {
int week = (Integer) request.getSession().getAttribute("week");
int year = (Integer) request.getSession().getAttribute("year");
List<String> donesub = (List<String>) request.getSession()
.getAttribute("donesub");
/*
* for (int i = 0; i < datalist.size(); i++) {
* changeobj.add(datalist.get(i));
*
* }
*/
String[] newsub = request.getParameterValues("prereq");
if (newsub != null) {
List<String> selectsub = new ArrayList<String>();
String qtr = nextqtr.get(nextqtr.size() - 1);
for (int f = 0; f < newsub.length; f++) {
selectsub.add(newsub[f]);
cmplt.add(new finishmvc(qtr, newsub[f]));
}
qtrshow.add(qtr);
for (int b = 0; b < selectsub.size(); b++) {
donesub.add(selectsub.get(b));
}
}
// ///////////////////////
week = week + 12;
if (week > 52) {
week = 6;
year++;
}
Quarter q = new Quarter();
nextqtr = q.getQuarter(week, year);
request.getSession().setAttribute("qtrshow", qtrshow);
request.getSession().setAttribute("donesub", donesub);
request.getSession().setAttribute("nextqtr", nextqtr);
request.getSession().setAttribute("cmplt", cmplt);
request.getSession().setAttribute("year", year);
request.getSession().setAttribute("week", week);
request.getSession().setAttribute("datalist", datalist);
response.sendRedirect("finish");
}
}
}
|
Markdown
|
UTF-8
| 254 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
title: Hello World
description: First blog post.
comments: true
---
#### Intro
A blog seemed like a good way to keep track of ideas and share knowledge I might gain in the process of building things, so here we are. Hope this goes well!
|
Python
|
UTF-8
| 1,573 | 3.84375 | 4 |
[] |
no_license
|
#
# @lc app=leetcode.cn id=94 lang=python3
#
# [94] 二叉树的中序遍历
#
# https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/
#
# algorithms
# Medium (75.28%)
# Likes: 930
# Dislikes: 0
# Total Accepted: 409.1K
# Total Submissions: 543.4K
# Testcase Example: '[1,null,2,3]'
#
# 给定一个二叉树的根节点 root ,返回它的 中序 遍历。
#
#
#
# 示例 1:
#
#
# 输入:root = [1,null,2,3]
# 输出:[1,3,2]
#
#
# 示例 2:
#
#
# 输入:root = []
# 输出:[]
#
#
# 示例 3:
#
#
# 输入:root = [1]
# 输出:[1]
#
#
# 示例 4:
#
#
# 输入:root = [1,2]
# 输出:[2,1]
#
#
# 示例 5:
#
#
# 输入:root = [1,null,2]
# 输出:[1,2]
#
#
#
#
# 提示:
#
#
# 树中节点数目在范围 [0, 100] 内
# -100
#
#
#
#
# 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
#
#
# @lc code=start
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def __init__(self):
self.path = []
def inorderTraversal(self, root: TreeNode):
if root == None:
return []
temp_path = []
temp_path += self.inorderTraversal(root.left)
temp_path += [root.val]
temp_path += self.inorderTraversal(root.right)
return temp_path
# a = Solution()
# root = TreeNode(val=1,right=TreeNode(val=2,left=TreeNode(val=3)))
# result = a.inorderTraversal(root)
# print(result)
# @lc code=end
|
Go
|
UTF-8
| 1,228 | 3.078125 | 3 |
[
"Apache-2.0"
] |
permissive
|
package main
import (
"html/template"
"log"
"net/http"
)
func main() {
templates := populateTemplates()
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
requestedFile := req.URL.Path[1:]
t := templates.Lookup(requestedFile + ".html")
if t != nil {
err := t.Execute(w, nil)
if err != nil {
log.Println(err)
}
} else {
w.WriteHeader(http.StatusNotFound)
}
})
http.HandleFunc("/goapp", func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
writer.Header().Add("Content-Type", "text/plain")
writer.Write([]byte("Is this my first Go webapp?"))
})
http.HandleFunc("/goappyes", func(writer http.ResponseWriter, request *http.Request) {
writer.WriteHeader(http.StatusOK)
writer.Header().Add("Content-Type", "text/plain")
writer.Write([]byte("Yes, this my first Go webapp!"))
})
fileServer := http.FileServer(http.Dir("./public"))
http.Handle("/img/", fileServer)
http.Handle("/css/", fileServer)
http.ListenAndServe(":8080", nil)
}
func populateTemplates() *template.Template {
result := template.New("templates")
const basePath = "templates"
template.Must(result.ParseGlob(basePath + "/*.html"))
return result
}
|
Python
|
UTF-8
| 1,342 | 2.734375 | 3 |
[] |
no_license
|
from datetime import datetime, timedelta
from django import template
register = template.Library()
@register.filter
def format_date(value):
def get_hours(hours):
return {
hours == 0 or 5 <= hours <= 20: 'часов',
hours == 1 or hours == 21: 'час',
2 <= hours <= 4 or 22 <= hours <= 24: 'часа'
}[True]
post_time = datetime.fromtimestamp(value)
current_time = datetime.now()
if current_time - post_time <= timedelta(minutes=10):
return "Только что"
if current_time - post_time <= timedelta(hours=24):
hours = (current_time - post_time).seconds // 3600
return f"{hours} {get_hours(hours)} назад"
return post_time.strftime("%Y-%m-%d")
@register.filter
def format_score(value):
return {
value < -5: 'всё пропало',
-5 <= value <= 5: 'норм',
value > 5: 'отлично'
}[True]
@register.filter
def format_num_comments(value):
return {
value == 0: 'Оставьте комментарий',
1 <= value <= 50: f'{value} комментариев',
value > 50: '50+'
}[True]
@register.filter
def format_selftext(value, count=5):
text_list = value.split()
return ' '.join(text_list[:count]) + ' ... ' + ' '.join(text_list[-count:])
|
PHP
|
UTF-8
| 3,308 | 2.546875 | 3 |
[] |
no_license
|
<?php
$servername = "localhost";
$username = $_GET['a'];
$password = $_GET['b'];
$dbname = $_GET['c'];
$id = $_GET['id'];
$cliente = $_GET['cli'];
$fyear = $_GET['year'];
$fmonth = $_GET['mes'];
$fday = $_GET['day'];
$dtos = $_GET['desc'];
$notas = $_GET['nota'];
$guardar = $_GET['save'];
$tabla = "Albaran";
$separador="--..--";
if(strlen($fmonth) < 2) {
$fmonth="0".$fmonth;
}
if(strlen($fday) < 2) {
$fday="0".$fday;
}
$dayalb=$fyear.$fmonth.$fday;
$fecha=$fyear."-".$fmonth."-".$fday;
$dtos=str_replace(",",".",$dtos);
// Create connection
$con = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_set_charset("utf8");
mysqli_select_db($con,"ajax_demo");
if($guardar == 'N'){
$sql="SELECT MAX(Id) AS maximo from $tabla";
$result = mysqli_query($con,$sql);
$env_csv = "";
while($row = mysqli_fetch_array($result)) {
$env_csv .= $row['maximo']."";
}
if(!$env_csv) {
$env_csv = "0";
}
if($env_csv=='NULL') {
$env_csv = "0";
}
$id=intval($env_csv)+1;
if($env_csv == "0") {
$nfra=$dayalb."001";
} else {
$sql="SELECT NAlb from $tabla WHERE NAlb LIKE '".$dayalb."%' ORDER BY NAlb DESC LIMIT 1";
$result = mysqli_query($con,$sql);
$env_csv = "";
while($row = mysqli_fetch_array($result)) {
$env_csv .= $row['NAlb']."";
}
if(strcmp(substr($env_csv, 0, 8),$dayalb) == 0){
$numero=intval(substr($env_csv,8,3));
$numero=$numero+1;
$numero="$numero";
while(strlen($numero) < 3) {
$numero="0".$numero;
}
$nfra=$dayalb.$numero;
} else {
$nfra=$dayalb."001";
}
}
$sql="INSERT INTO $tabla (Id, NAlb, Cliente, Fecha, Notas, Fra) VALUES ($id,'$nfra','$cliente','$fecha','$notas','')";
$result = mysqli_query($con,$sql);
print $id.",".$result;
} elseif($guardar == 'U') {
$sql="UPDATE $tabla SET Cliente='$cliente', Fecha='$fecha', Notas='$notas' WHERE Id='$id'";
$result = mysqli_query($con,$sql);
print $result;
} elseif($guardar == 'D') {
$sql="DELETE FROM $tabla WHERE Id='$id'";
$result = mysqli_query($con,$sql);
print $result;
} elseif($guardar == 'C') {
$sql="SELECT Cliente.Id, Cliente.Nombre, Cliente.Apellidos, Albaran.NAlb, Albaran.Fecha, Albaran.Notas FROM Albaran INNER JOIN Cliente ON Albaran.Cliente=Cliente.Id WHERE Albaran.Id = '".$id."'";
$result = mysqli_query($con,$sql);
$env_csv = "";
$sustituciones=array("(",")","[","]","{","}",",",";");
while($row = mysqli_fetch_array($result)) {
$swap = $row['Nombre'];
$swap = str_replace($sustituciones,"",$swap);
$env_csv .= $swap." ";
$swap = $row['Apellidos'];
$swap = str_replace($sustituciones,"",$swap);
$env_csv .= $swap." (";
$env_csv .= $row['Id'].")";
$env_csv .= $separador;
$env_csv .= $row['Nombre'].$separador;
$env_csv .= $row['Apellidos'].$separador;
$env_csv .= $row['NAlb'].$separador;
$env_csv .= $row['Fecha'].$separador;
$env_csv .= $row['Notas'].$separador;
}
$env_csv=$env_csv."X";
print $env_csv;
}
mysqli_close($con);
?>
|
Markdown
|
UTF-8
| 1,319 | 2.734375 | 3 |
[
"CC-BY-3.0",
"CC-BY-4.0"
] |
permissive
|
---
layout: event
title: 2018
timespan: April 2018
---
“I’ve been back in Toronto for four days now, but the Writers in the Woods festival at the Canadian Ecological Centre in Mattawa still runs in my veins. The generosity I found there—from the pro organizers, from the CEC staff, from the community who came to the events—has brought me back to my writing desk with renewed energy and faith in the written word and in story.
Writing stories requires a million acts of faith, every day, every hour, every minute; it’s a spiritual practice. I’m buoyed by the presence of those who came to the writing desk with me in the workshop and those who supported story-making with their open hearts and minds at the well-attended book talk, and I’m also reminded how much the natural world grounds me in that practice.
Writing in a quiet cabin is the ideal situation for me: the calm and the distance from the myriad distractions of modern life creates a space for my imagination to roam freely.
I’m already plotting a return, because I’m also jonesing to get into that river in a canoe and sit by the fire under that inky sky. Thanks to Janet Joy Wilson, Bill Steer, and the staff of the CEC for a supremely well-organized retreat and renewal. I’m honoured to have been part of it.” - Christine Fischer Guy, Author & Instructor
|
PHP
|
UTF-8
| 776 | 2.5625 | 3 |
[] |
no_license
|
<!DOCTYPE html>
<html>
<head>
<title>WinsVideo - Realtime Stats</title>
<meta http-equiv="refresh" content="1">
</head>
<body>
<style>
@import url('https://fonts.googleapis.com/css?family=Roboto:300&display=swap');
div {
font-family: 'Roboto', sans-serif;
font-weight: 300;
color: #455a64;
font-size: 80px;
}
</style>
<center>
<?php
$servername="localhost";
$username="root";
$password="";
$dbname="videotube";
$con=mysqli_connect($servername,$username,$password,$dbname);
$sql="SELECT count(id) AS total FROM comments";
$result=mysqli_query($con,$sql);
$values=mysqli_fetch_assoc($result);
$num_rows=$values['total'];
echo "<div>$num_rows</span>";
echo "</font>"
?>
</center>
</body>
</html>
|
Swift
|
UTF-8
| 1,060 | 2.765625 | 3 |
[] |
no_license
|
//
// CustomTableViewCell.swift
// Project4
//
// Created by Dimas on 15/08/21.
//
import UIKit
class CustomTableViewCell: UITableViewCell {
@IBOutlet weak var websiteLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
contentView.layer.cornerRadius = 10
contentView.layer.masksToBounds = true
self.selectionStyle = .none // disable the default selection effect
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
contentView.backgroundColor = UIColor(red: 0.863, green: 0.863, blue: 0.863, alpha: 1.0) // equals to #DCDCDC
} else {
contentView.backgroundColor = UIColor(red: 0.941, green: 0.941, blue: 0.941, alpha: 1.0) // equals to #F0F0F0
}
}
override func layoutSubviews() {
super.layoutSubviews()
// set the values for top, left, bottom, right margins
let margins = UIEdgeInsets(top: 0, left: 16, bottom: 8, right: 16)
contentView.frame = contentView.frame.inset(by: margins)
}
}
|
Java
|
UTF-8
| 2,434 | 1.820313 | 2 |
[] |
no_license
|
package com.mobisoft.library;
public class Constants {
public static final String RELEASE = android.os.Build.VERSION.RELEASE;
public static final String MODEL = android.os.Build.MODEL;
public static final String OS_SYSTEM = "android";
/** APP 版本号,版本名称 */
public static String VERSION_NAME = "";
/** APP 版本号,数字 */
public static int VERSION_CODE = 0;
public static int SCREEN_WIDTH = 0;
public static int SCREEN_HEIGTH = 0;
/** 登录用户id:123456789012 */
public static String ACCOUNT = "";
/** 登陆用户的密码 */
public static String PASSWORD = "";
// 在发正式版本的时候,改为false,在设置为true的时候,回输入各种调试信息以及异常,在设置false的时候,只输出异常信息
public static final boolean DEBUG = true;
public static class URL {
// 我的部门
public static final String GET_CONTACT_DEPARTMENT = "/contact/getMyOrg";
// 我的部门下面的子部门及人员
// public static final String GET_MY_CHILD_DEPARTMENT =
// "/contact/getOrgAndPersonByOrgId";
public static final String GET_MY_CHILD_DEPARTMENT = "/contact/getOrgAndPersonByOrgId2";
// 查询组织架构
public static final String GET_CONTACT_ORG = "/contact/getChildOrg";
// 查询联系人详情
public static final String GET_CONTACT_INFO = "/contact/getUserDetail";
// 获取部门下面所有的人员
public static final String GET_CONTACT_ALL_ORG_USER = "/contact/getAllUserByOrgId";
// 编辑联系人的备注
public static final String SET_CONTACT_REMARK = "/contact/addUserRemark";
// 添加设置为常用联系人
public static final String ADD_CONTACT_LINKMAN = "/contact/addFrequentLinkman";
// 删除常用联系人
public static final String DEL_CONTATC_LINKMAN = "/contact/deleteFrequentLinkman";
// 设置手机的可见性
public static final String SET_PHONE_STATUE = "/contact/setPhoneVisibility";
// 查询手机的可见性
public static final String GET_PHONE_STATUE = "/contact/getPhoneVisibility";
// 获取常用联系人列表
public static final String GET_LINKMAN_LIST = "/contact/getFrequentLinkmanList";
// 搜索人员
public static final String SEARCH_MAN = "/contact/searLinkman";
// 搜索部门
public static final String SEARCH_ORG = "/contact/searchOrg";
// 获取群组列表
public static final String GET_GROUP_LIST = "/qx/getContact";
}
}
|
Python
|
UTF-8
| 163 | 3 | 3 |
[] |
no_license
|
m,p=map(int,input().split())
l2=list(map(int,input().strip().split()))[:m]
for i in range(0,m):
if(l2[i]==p):
print("yes")
break
else:
print("no")
|
Python
|
UTF-8
| 3,745 | 3.375 | 3 |
[
"Apache-2.0"
] |
permissive
|
"""Parse data in the format:
Age Uncertainty
Sample data assumning a normal distrubtion with mean defined by Age and sigma
defined by Uncertainty
"""
import numpy as np
from scipy.stats import norm
from QuakeRates.dataman.event_dates import EventDate, EventSet
def parse_age_sigma(filename, sigma_level, event_order, truncation=3,
delimiter=None, header = 1):
"""Parse a text file containing a list of event ages and associated
uncertainties
:param filename: string of path to input file
:param sigma_level: Number of sigmas represented by the uncertainty
columm
:param event_order: String, 'Forwards' or 'Backwards' in time. I.e. if
'Forwards', oldest event is in the first row of the file.
:param truncation: Number of sigma levels to sample from
:param delimiter: Delimiter of input text file.
:param header: Number of header lines to discard
"""
event_list = []
# data = np.genfromtxt(filename, delimiter=delimiter, skip_header=header)
data = np.genfromtxt(filename, delimiter=delimiter, names=True)
print(data)
print(type(data))
print(data.dtype)
print(data.dtype.names)
# We want time to be running forwards
if event_order == 'Backwards':
data = np.flip(data, axis=0)
print(data)
if data.dtype.names[0]=='Date':
dates = data['Date']
sigmas = data['Uncertainty']/sigma_level #Convert, e.g. 2 sigma to 1 sigma
elif data.dtype.names[0]=='Date1':
dates = np.mean([data['Date1'],data['Date2']], axis=0)
sigmas = abs(data['Date1'] - data['Date2'])/(2*sigma_level)
elif data.dtype.names[0]=='Age':
# Conver to dates assuming age before 1950
dates = 1950 - data['Age']
sigmas = data['Uncertainty']/sigma_level #Convert, e.g. 2 sigma to 1 sigma
# Deal with age ranges, rather than mean and standard deviation, assuming
# range covers 95% of the distirbution (i.e. +/- 2 sigma)
elif data.dtype.names[0]=='Age1':
dates = np.mean([(1950 - data['Age1']),(1950 - data['Age2'])], axis=0)
sigmas = abs(data['Age1'] - data['Age2'])/(2*sigma_level)
print(dates)
for i,mean_age in enumerate(dates):
event_id = i
# Special case of zero uncertainty
if sigmas[i]==0:
ages = np.array([mean_age])
probs = np.array([1.])
else:
ages = np.arange(mean_age-truncation*sigmas[i],
mean_age+truncation*sigmas[i]+1, 1)
probs = norm.pdf(ages, mean_age, sigmas[i])
# Normalise probs due to truncation of distribution
probs = probs/sum(probs)
event = EventDate(event_id, 'manual', 'age_sigma')
event.add_dates_and_probs(ages, probs)
# print(event.dates)
# print(event.probabilities)
event_list.append(event)
# Note cases with uncertain event occurrences
try:
if data.dtype.names[2]=='Certain':
event_certainty = data['Certain']
except:
event_certainty = np.ones(len(dates))
print(event_certainty)
return event_list, event_certainty
if __name__ == "__main__":
# filename = '../data/Elsinore_Rockwell_1986_simple.txt'
filename = '../data/Yammouneh_Daeron_2007_simple.txt'
event_list, event_certainty = parse_age_sigma(filename, sigma_level=2,
event_order='Backwards')
event_set = EventSet(event_list)
print(event_list)
print(event_set)
n_samples = 10000
event_set.gen_chronologies(n_samples)
event_set.calculate_cov()
event_set.cov_density()
|
Python
|
UTF-8
| 1,729 | 3.828125 | 4 |
[] |
no_license
|
"""Input buffer implementation"""
class InBuffer:
def __init__(self, in_file=None, data=None):
"""Initialize in_buffer with either file content or bytes array"""
self.buffer = None
if in_file is not None:
with open(in_file, "rb") as inp:
self.buffer = inp.read().__iter__()
if data is not None:
self.buffer = data.__iter__()
# buffer for current byte
self.byte = 0
self.pending_bits_in_byte = 0
self.is_eof = False
self.bytes_read = 0
def take_next_bit(self):
"""Takes next bit from buffer. Returns -1 if there isn't any"""
if self.is_eof:
return -1
if self.pending_bits_in_byte == 0:
try:
self.byte = self.buffer.__next__()
except StopIteration:
self.is_eof = True
return -1
self.pending_bits_in_byte = 8
self.bytes_read += 1
self.pending_bits_in_byte -= 1
return (self.byte >> self.pending_bits_in_byte) & 1
def take_next_bytes(self, number):
value = bytearray()
for i in range(number):
value.append(self.take_next_int(8))
return value
def take_next_int(self, width_in_bits):
"""
Reads width_in_bits bits from buffer
Returns integer value of bits read
"""
value = 0
for i in range(width_in_bits):
bit = self.take_next_bit()
value = (value << 1) | bit
return value
def shift_to_next_byte(self):
"""Skip remain bits in current byte"""
while self.pending_bits_in_byte != 0:
self.take_next_bit()
|
Java
|
UTF-8
| 1,439 | 1.898438 | 2 |
[] |
no_license
|
package com.hrdb.service;
// Generated 7 Oct, 2014 3:41:51 PM
import java.util.HashMap;
import java.util.Map;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.wavemaker.runtime.data.model.CustomQuery;
import com.wavemaker.runtime.data.dao.query.WMQueryExecutor;
import com.wavemaker.runtime.data.exception.QueryParameterMismatchException;
@Service("hrdb.queryExecutorService")
public class QueryExecutorServiceImpl implements QueryExecutorService {
private static final Logger LOGGER = LoggerFactory.getLogger(QueryExecutorServiceImpl.class);
@Autowired
@Qualifier("hrdbWMQueryExecutor")
private WMQueryExecutor queryExecutor;
@Transactional(value = "hrdbTransactionManager")
@Override
public Page<Object> executeWMCustomQuerySelect(CustomQuery query, Pageable pageable) {
return queryExecutor.executeCustomQuery(query, pageable);
}
@Transactional(value = "hrdbTransactionManager")
@Override
public int executeWMCustomQueryUpdate(CustomQuery query) {
return queryExecutor.executeCustomQueryForUpdate(query);
}
}
|
Python
|
UTF-8
| 861 | 2.65625 | 3 |
[] |
no_license
|
from input_handler import parse_input, validate_input, parse_obstacle_file
from graph_handler import find_path, construct_free_space_graph, validate_source_point, validate_target_point
from output_handler import write_output
if __name__ == "__main__":
# handle input
sx, sy, sz, dx, dy, dz, filename = parse_input()
validate_input(sx, sy, sz, dx, dy, dz, filename)
x_dim, y_dim, z_dim, xy_plane, yz_plane, zx_plane = parse_obstacle_file(filename)
# construct free-space graph, and find solution
free_space_graph = construct_free_space_graph(x_dim, y_dim, z_dim, xy_plane, yz_plane, zx_plane)
validate_source_point(free_space_graph, sx, sy, sz)
validate_target_point(free_space_graph, dx, dy, dz)
path = find_path(free_space_graph, sx, sy, sz, dx, dy, dz)
# handle output
write_output(sx, sy, sz, dx, dy, dz, path)
|
Python
|
UTF-8
| 921 | 3 | 3 |
[] |
no_license
|
def equation_system(b, time_linspace):
"""
The ordinary system of equations that will be solved in order to determine
the position of the molecule based on the b-field.
@type b: float (bfield)
@type t: Numpy linspace
@type: List (change of bfield over time)
"""
xt, yt, zt, vxt, vyt, vzt = b
db_over_dt = [vxt,vyt,vzt, B_str * mol_state(xt,yt,zt) * Bdxfn([xt,yt,zt%(20*mm)]),
B_str * mol_state(xt, yt, zt) * Bdyfn([xt, yt, zt % (20 * mm)]),
B_str * mol_state(xt, yt, zt) * Bdzfn([xt, yt, zt % (20 * mm)])]
return db_over_dt
def solve_equations(s0):
"""
Solves the equation of differential equations based on the initial conditions.
time_linspace is a global variable that is a numpy linspace.
@type s0: numpy array
@rtype: numpy array
"""
solution = odeint(equation_system, s0, time_linspace)
return solution
|
Go
|
UTF-8
| 546 | 3.375 | 3 |
[] |
no_license
|
package preprocess
import (
"regexp"
"strings"
)
type removeStopWordsProcessor struct {
stopWords *regexp.Regexp
}
func createRemoveStopWordsProcessor(stopwords []string) Preprocessor {
stopWordsReg := regexp.MustCompile(strings.Join(stopwords, "|"))
return &removeStopWordsProcessor{stopWordsReg}
}
func (p *removeStopWordsProcessor) Process(ch <-chan string) <-chan string {
out := make(chan string)
go func() {
for val := range ch {
if !p.stopWords.MatchString(val) {
out <- val
}
}
close(out)
}()
return out
}
|
C#
|
UTF-8
| 11,932 | 2.53125 | 3 |
[] |
no_license
|
using JetBrains.Annotations;
using System.Collections.Generic;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Events;
//By Seth
//
//A Trick is a class that holds a lot of information about each individual Trick. This information is set in the inspector.
//
//A TrickStep is one of the steps that is required to complete a trick.
//A list of types of TrickSteps. Up = 0, Down = 1, etc.
public enum TrickStepType_Mobile { up = 0, down = 1, left = 2, right = 3, touch = 4 }
public class TrickManager_Mobile : MonoBehaviour
{
private PlayerStateManager stateManager;
private ComboManager comboManager;
[Tooltip("How long you have to complete a trick.")]
public float trickLeeway = 0.5f;
private float currentLeeway = 0;
//[Tooltip("This lets us assign variables to keys easily in the inspector.")]
//[Header("Inputs")]
//public KeyCode upKey;
//public KeyCode downKey;
//public KeyCode leftKey;
//public KeyCode rightKey;
//public KeyCode spaceKey;
[Tooltip("These are all of the possible different steps a trick can have. The inputs.")]
[Header("Trick Steps")]
public TrickStep upStep;
public TrickStep downStep;
public TrickStep leftStep;
public TrickStep rightStep;
public TrickStep touchStep;
[Tooltip("A list of all of our Tricks which you can edit here in the inspector.")]
[Header("Tricks")]
public List<Trick> tricks;
private TrickStep currentTrickStep = null;
private TrickInput lastInput = null;
[HideInInspector]
public bool doingTrick = false;
//A list of the tricks that are currently possible to complete given the player's recent inputs.
private List<int> currentTricks = new List<int>();
//private bool skip = false;
//To store the most recently performed trick with the longest input.
TrickStep performedTrickStep = null;
Trick performedTrick = null;
private void Start()
{
stateManager = GetComponent<PlayerStateManager>();
comboManager = GetComponent<ComboManager>();
//We need to start listening for Tricks and take some actions if one is completed.
PrimeTricks();
}
private void PrimeTricks()
{
//For every trick listed in the inspector
for (int i = 0; i < tricks.Count; i++)
{
//Assign that given trick to "trick".
Trick trick = tricks[i];
//Wait and listen for that trick to be completed.
trick.onInputted.AddListener(() =>
{
//When a trick is fully inputted, we want to do these things.
//skip = true;
if(performedTrick != null)
{
if (trick.inputs.Count > performedTrick.inputs.Count)
{
//Save that trick for later use.
performedTrickStep = trick.trickStep;
performedTrick = trick;
}
}
else
{
performedTrickStep = trick.trickStep;
performedTrick = trick;
}
});
}
}
private void Update()
{
//Debug.Log("currentTricks.Count = " + currentTricks.Count);
//If there are any tricks that can possibly be done given the player's recent inputs,
if (currentTricks.Count > 0)
{
currentLeeway += Time.deltaTime;
//When the time to enter combos runs out,
if (currentLeeway >= trickLeeway)
{
if (lastInput != null)
{
if(performedTrickStep != null)
{
//Perform the last saved trick.
TrickStep(performedTrickStep);
}
performedTrickStep = null;
performedTrick = null;
lastInput = null;
}
ResetTricks();
}
}
else
currentLeeway = 0;
//Clear last frame's input.
TrickInput input = null;
//This is where we look for input.
//
//Currently this does not allow for multiple tricks in the same jump. I don't think we want that.
if(stateManager.currentState == PlayerStateManager.PlayerState.Airborne)
{
if (DrawLine.swipedUp)
input = new TrickInput(TrickStepType.up);
if (DrawLine.swipedDown)
input = new TrickInput(TrickStepType.down);
if (DrawLine.swipedLeft)
input = new TrickInput(TrickStepType.left);
if (DrawLine.swipedRight)
input = new TrickInput(TrickStepType.right);
if (DrawLine.tap)
input = new TrickInput(TrickStepType.touch);
}
//If the player did not input anything, exit update for this frame.
if (input == null) return;
//Store which input the player inputted.
lastInput = input;
//Create a list of tricks to remove.
List<int> remove = new List<int>();
//For every trick that is currently possible.
for (int i = 0; i < currentTricks.Count; i++)
{
Trick t = tricks[currentTricks[i]];
//Call the ContinueTrick method and if the input that was given this frame can complete this given trick.
if (t.ContinueTrick(input))
{
//Give the player more time to input more TrickSteps
currentLeeway = 0;
}
else
{
//If that input was not valid for a given trick, get ready to remove that trick from the list of possible tricks.
remove.Add(i);
}
}
//if (skip)
//{
// skip = false;
// return;
//}
//For every trick that exists
for (int i = 0; i < tricks.Count; i++)
{
//if that trick is already in the currentTricks list, continue the loop
if (currentTricks.Contains(i)) continue;
//if
if (tricks[i].ContinueTrick(input))
{
currentTricks.Add(i);
currentLeeway = 0;
}
}
//Remove all of the tricks that became invalid from the list of possible tricks.
foreach (int i in remove)
{
if(remove.Count < currentTricks.Count)
{
if (i < currentTricks.Count)
{
currentTricks.RemoveAt(i);
}
}
}
}
private void ResetTricks()
{
currentLeeway = 0;
//For every trick that is currently possible.
for (int i = 0; i < currentTricks.Count; i++)
{
Trick trick = tricks[currentTricks[i]];
//Set that Trick's current input to 0.
trick.ResetTrick();
}
//Clear the list of current possible Tricks.
currentTricks.Clear();
}
//A method that activates a given trick
public void TrickStep(TrickStep trickStep)
{
currentTrickStep = trickStep;
if (currentTrickStep.state != PlayerStateManager.PlayerState.Idle && !doingTrick)
{
//Change the player's state to that trick.
stateManager.ActiveState(currentTrickStep.state);
doingTrick = true;
}
if (currentTrickStep.comboMultiplier != 0)
{
//Add to the player's multiplier.
comboManager.newComboValue = currentTrickStep.comboMultiplier;
comboManager.AddToCombo();
}
}
private TrickStep getTrickStepFromType(TrickStepType t)
{
if (t == TrickStepType.up)
return upStep;
if (t == TrickStepType.down)
return downStep;
if (t == TrickStepType.left)
return leftStep;
if (t == TrickStepType.right)
return rightStep;
if (t == TrickStepType.touch)
return touchStep;
return null;
}
}
[System.Serializable]
public class TrickStep_Mobile
{
public string name;
public float length;
[Tooltip("What state this would put the player in. Usually this is the name of the trick.")]
public PlayerStateManager.PlayerState state;
[Tooltip("How much this trick adds to our combo multiplier.")]
[Range(0, 4)]
public int comboMultiplier;
}
[System.Serializable]
public class TrickInput_Mobile
{
public TrickStepType type;
public TrickInput_Mobile(TrickStepType t)
{
type = t;
}
//A test that we use in the Trick class.
public bool isSameAs(TrickInput_Mobile test)
{
return (type == test.type);
}
}
//This is a class that defines what a Trick is.
[System.Serializable]
public class Trick_Mobile
{
public TrickStep_Mobile trickStep;
[Tooltip("What inputs the trick requires to complete, in order.")]
public List<TrickInput_Mobile> inputs;
[Tooltip("For tricks that can be completed on left OR right sides.")]
public List<TrickInput_Mobile> alternateInputs;
//A unity event that occurs when this trick is activated.
[HideInInspector]
public UnityEvent onInputted;
//An index that keeps track of what step we are on for this trick.
int currentInput = 0;
//A test to see if a given input lets you continue to try to perform this trick or makes you fail this trick.
public bool ContinueTrick(TrickInput_Mobile i)
{
if(alternateInputs.Count > 0)
{
//Starting with the first required input for this trick, if that matches the input the player pressed,
if (inputs[currentInput].isSameAs(i) || alternateInputs[currentInput].isSameAs(i))
{
//Move onto the next required input.
currentInput++;
//If the player completed all the required inputs.
if (currentInput >= inputs.Count || currentInput >= alternateInputs.Count)
{
//Invoke this trick,
onInputted.Invoke();
//And reset the index,
currentInput = 0;
}
//And return true.
return true;
}
//If that input does not match the required input,
else
{
//Reset our index and return false.
currentInput = 0;
return false;
}
}
else
{
//Starting with the first required input for this trick, if that matches the input the player pressed,
if (inputs[currentInput].isSameAs(i))
{
//Move onto the next required input.
currentInput++;
//If the player completed all the required inputs.
if (currentInput >= inputs.Count)
{
//Invoke this trick,
onInputted.Invoke();
//And reset the index,
currentInput = 0;
}
//And return true.
return true;
}
//If that input does not match the required input,
else
{
//Reset our index and return false.
currentInput = 0;
return false;
}
}
}
public TrickInput_Mobile currentTrickInput()
{
if (currentInput >= inputs.Count || currentInput >= alternateInputs.Count) return null;
return inputs[currentInput];
}
//A method that resets our index.
public void ResetTrick()
{
currentInput = 0;
}
}
|
Java
|
UTF-8
| 2,154 | 3.8125 | 4 |
[] |
no_license
|
package chapter02_Basics;
public class P2_2_VarAndConst {
public static void main(String[] args) {
int x; // объявление переменной
x = 10; // присвоение значения
System.out.println(x); // 10
int a = 10; // объявление и инициализация переменной
System.out.println(a); // 10
/*
int x;
System.out.println(x); // !!! initialize variable x
*/
//Через запятую можно объявить сразу несколько переменных одного типа:
int z, y; //Variable 'x' is already defined in the scope
//~~~~ Alt+Shift+Enter - navigate to previous declared variable 'x'
z = 10;
y = 25;
System.out.println(z); // 10
System.out.println(y); // 25
//Также можно их сразу инициализировать:
int m = 8, n = 15;
System.out.println(m); // 8
System.out.println(n); // 15
//Отличительной особенностью переменных является то, что можно в процессе работы программы изменять их значение:
int c = 10;
System.out.println(c); // 10
c = 25;
System.out.println(c); // 25
//Начиная с Java 10 в язык было добавлено ключевое слово var, которое также позволяет определять переменную:
var l = 10;
System.out.println(l); // 10
/*
var k; // ! Ошибка, переменная не инициализирована
//Variable 'k' is assigned but never accessed
k = 10;
*/
//Constants
final int LIMIT = 5;
System.out.println(LIMIT); // 5
////LIMIT=57; // так уже не можем написать, так как LIMIT - константа
//Cannot assign a value to final variable 'LIMIT'
}
}
|
C++
|
UTF-8
| 4,797 | 2.59375 | 3 |
[] |
no_license
|
#include <network/EasyWifiManager.h>
using namespace std;
EasyWifiManager::EasyWifiManager(){
// Default MQTT values for WifiManager configuration portal
strcpy(mqtt_server, DEFAULT_MQTT_SERVER);
strcpy(mqtt_port, DEFAULT_MQTT_PORT);
strcpy(mqtt_user, DEFAULT_MQTT_USER);
strcpy(mqtt_password, DEFAULT_MQTT_PASSWORD);
strcpy(mqtt_topic, DEFAULT_MQTT_TOPIC);
}
void EasyWifiManager::init() {
load_config();
WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6);
WiFiManagerParameter custom_mqtt_user("user", "mqtt user", mqtt_user, 40);
WiFiManagerParameter custom_mqtt_password("password", "mqtt password", mqtt_password, 70);
WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 255);
// WiFiManager
// Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//add all your parameters here
wifiManager.addParameter(&custom_mqtt_server);
wifiManager.addParameter(&custom_mqtt_port);
wifiManager.addParameter(&custom_mqtt_user);
wifiManager.addParameter(&custom_mqtt_password);
wifiManager.addParameter(&custom_mqtt_topic);
// fetches ssid and pass from eeprom and tries to connect
// if it does not connect it starts an access point with the name ESP + ChipID
wifiManager.autoConnect();
// if you get here you have connected to the WiFi
Serial.println("[EasyWifiManager] Connected To WiFi.");
m_ssid = WiFi.SSID();
m_psk = WiFi.psk();
strcpy(mqtt_server, custom_mqtt_server.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(mqtt_user, custom_mqtt_user.getValue());
strcpy(mqtt_password, custom_mqtt_password.getValue());
strcpy(mqtt_topic, custom_mqtt_topic.getValue());
save_config();
}
void EasyWifiManager::load_config() {
if (SPIFFS.begin()) {
Serial.println("[EasyWifiManager] Mounted file system");
if (SPIFFS.exists("/config.json")) {
//File exists, reading and loading
Serial.println("[EasyWifiManager] Reading config file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
Serial.println("[EasyWifiManager] Opened config file");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
if (json.success()) {
Serial.println("[EasyWifiManager] Parsed json");
strcpy(mqtt_server, json["mqtt_server"]);
strcpy(mqtt_port, json["mqtt_port"]);
strcpy(mqtt_user, json["mqtt_user"]);
strcpy(mqtt_password, json["mqtt_password"]);
strcpy(mqtt_topic, json["mqtt_topic"]);
} else {
Serial.println("[EasyWifiManager] Failed to load json config");
}
}
}
} else {
Serial.println("[EasyWifiManager] Failed to mount FS");
}
}
void EasyWifiManager::save_config(){
//save the custom parameters to FS
Serial.println("[EasyWifiManager] Saving config");
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
json["mqtt_server"] = mqtt_server;
json["mqtt_port"] = mqtt_port;
json["mqtt_user"] = mqtt_user;
json["mqtt_password"] = mqtt_password;
json["mqtt_topic"] = mqtt_topic;
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("[EasyWifiManager] Failed to open config file for writing");
}
json.printTo(Serial);
json.printTo(configFile);
configFile.close();
}
void EasyWifiManager::reset_config() {
WiFiManager wifiManager;
wifiManager.resetSettings();
}
String EasyWifiManager::get_ssid() { return m_ssid; }
String EasyWifiManager::get_psk() { return m_psk; }
char* EasyWifiManager::get_mqtt_server() { return mqtt_server; }
char* EasyWifiManager::get_mqtt_port() { return mqtt_port; }
char* EasyWifiManager::get_mqtt_user() { return mqtt_user; }
char* EasyWifiManager::get_mqtt_password() { return mqtt_password; }
char* EasyWifiManager::get_mqtt_topic() { return mqtt_topic; }
|
JavaScript
|
UTF-8
| 2,697 | 2.8125 | 3 |
[] |
no_license
|
import React from 'react';
const currentTechnologies = [
"html", "css", "javascript", "sass", "react", "redux", "php", "node", "laravel", "java", "android", "gitlab", "github",
"mysql", "mongodb"
]
class Tech extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedTech: [],
className: "input-no-error"
};
}
componentDidMount = () => {
if(this.props.value) {
this.setState({
selectedTech: this.props.value
})
this.props.techChanged(this.props.value);
}
}
techChosen = (e) => {
console.log(e.target.value);
var theTech = e.target.value;
var selectedTech = this.state.selectedTech;
selectedTech.push(theTech);
console.log(selectedTech);
this.setState({
selectedTech: selectedTech
})
this.props.techChanged(selectedTech);
}
renderSelect = () => {
var options = currentTechnologies.map((currentTechnology) => {
return <option value = {currentTechnology}>{currentTechnology}</option>
})
return (
<select
className = {this.state.className}
onChange = {this.techChosen}
>
<option
value = ""
selected
disabled
hidden
>
Choose tech
</option>
{options}
</select>
);
}
//removing an item with a given id.
removeTech = (i) => {
var selectedTech = this.state.selectedTech;
selectedTech.splice(i, 1);
this.setState({
selectedTech: selectedTech
})
this.props.techChanged(selectedTech);
}
//rendering all the tech the user selected from the <options>
renderTech = () => {
return this.state.selectedTech.map((tech, i) => {
return (
<div
className = "tech"
onClick = {() => {this.removeTech(i)}}
>
<p>{tech} <button className = "remove">x</button></p>
</div>
)
})
}
render() {
return (
<div>
<div className = "tech-holder">
{this.renderTech()}
</div>
<div className = "form-label">
<label for = "technologies">Technologies Used</label>
</div>
{this.renderSelect()}
</div>
)
}
}
export default Tech;
|
C
|
UTF-8
| 238 | 3.640625 | 4 |
[] |
no_license
|
/* EXOR OF TWO NUMBER W/O USING ^ OPERATOR'*/
#include<stdio.h>
#define EXOR_NUMBER(X,Y) (~X & Y)|(X & (~Y))
int main()
{
int a,b;
printf("enter the number\n");
scanf("%d%d",&a,&b);
printf("exor_number:%d\n",EXOR_NUMBER(a,b));
}
|
C++
|
UTF-8
| 1,289 | 3.171875 | 3 |
[] |
no_license
|
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
// DFS
class Solution0 {
public:
int scoreOfParentheses(string S) {
int i = 0;
return dfs(S, i);
}
int dfs(const string& s, int& i) {
int res = 0;
while (i < s.size()) {
if (s[i] == '(') {
if (s[i+1] == ')') { res += 1; i += 2; }
else res += 2 * dfs(s, ++i);
} else {
++i;
break;
}
}
return res;
}
};
// stack
class Solution1 {
public:
int scoreOfParentheses(string S) {
stack<int> st;
int res = 0;
for (int i = 0; i < S.size(); ++i) {
if (S[i] == '(') {
st.push(res);
res = 0;
} else {
res += st.top() + max(res, 1);
st.pop();
}
}
return res;
}
};
// math, count level
class Solution {
public:
int scoreOfParentheses(string S) {
int res = 0, l = 0;
for (int i = 0; i < S.length(); ++i) {
if (S[i] == '(') l++; else l--;
if (S[i] == ')' && S[i - 1] == '(') res += 1 << l;
}
return res;
}
};
int main() {
}
|
C++
|
UTF-8
| 752 | 3.109375 | 3 |
[] |
no_license
|
#include <iostream>
#include <dlfcn.h>
#include "h1.h"
#include "sanpa.h"
using namespace std;
int main(int argc, char **argv){
cout<<"Hello world"<<endl;
cout<<"Starting uses of a dynamic library"<<endl;
void* handle = dlopen("sanpa.dll", RTLD_LAZY);
sanpa* (*create)();
void (*destroy)(sanpa*);
create = (sanpa* (*)())dlsym(handle, "create_object");
destroy = (void (*)(sanpa*))dlsym(handle, "destroy_object");
sanpa* my_sanpa = (sanpa*)create();
my_sanpa->do_something();
destroy(my_sanpa);
cout<<"Done"<<endl;
cout<<"Starting uses of a static library"<<endl;
punto<int> a(1, 2);
a.set_data("primer punto");
cout<<"( "<<a.get_x()<<"; "<<a.get_y()<<") -> "<<a.get_data()<<endl;
return 0;
}
|
Python
|
UTF-8
| 758 | 2.703125 | 3 |
[] |
no_license
|
import mysql.connector as connector
class SQLConnector:
def __init__(self, data=None):
self.data = data
connection_ = {"host": "192.168.43.65",
"user": "pacuser",
"password": "pacuser"
}
self.connection = connector.connect(**connection_).cursor()
def show_dbs(self):
self.connection.execute("SHOW DATABASES")
for i in self.connection:
print(i)
def write_db(self, data):
pass
def read_db(self, data):
pass
def update_db(self, data):
pass
def delete_db(self, data):
pass
if __name__ == '__main__':
x = SQLConnector()
x.show_dbs()
|
C++
|
UTF-8
| 391 | 4.25 | 4 |
[] |
no_license
|
//Write a program to read two numbers from the keyboard and display the larger value on the screen
#include<iostream>
using namespace std;
int main(){
int num1, num2, max;
cout << "Enter two numbers:" << endl;
cin >> num1 >> num2;
max = (num1 > num2) ? num1 : num2;
cout << "The largest between " << num1 << " and " << num2 << " is " << max << endl ;
return 0;
}
|
Java
|
UTF-8
| 488 | 1.976563 | 2 |
[] |
no_license
|
package com.spc.schedule.job.count;
import com.spc.schedule.job.JobHelper;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
/**
* 实现Job接口
* @author yvan
*
*/
@Component
public class ItemsCountJob implements Job{
@Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
JobHelper.count("ItemsCountMgr", null);
}
}
|
Java
|
SHIFT_JIS
| 10,257 | 3.078125 | 3 |
[] |
no_license
|
package game;
import game.TheBoard;
import game.TheMove;
import game.TheMove.DIRECTION;
import org.junit.Assert;
import org.junit.Test;
public class TheBoardTest {
/**
* {[hړ̃eXg
*NGp^[1:iǁjɈړ
* NGp^[2:̃ubN̏ꏊɈړ
* OKp^[FĂꏊ
* ꂼeXg܂B
* OKp^[̎́AƑzʂ̈ʒuɈړoĂ邩mF܂B
* @author works
*/
@Test
public void makeNextBordTest1() {
TestStage ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("B", 0, 0);
ts1.putCell("A", 1, 0);
TheBoard bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
//NGp^[iǂj
TheBoard result = null;
result = bord.makeNextBord(new TheMove("A", DIRECTION.UP));
Assert.assertNull(result);
//NGp^[ĩubNj
result = bord.makeNextBord(new TheMove("A", DIRECTION.LEFT));
Assert.assertNull(result);
//OKp^[
result = bord.makeNextBord(new TheMove("A", DIRECTION.DOWN));
Assert.assertNotNull(result);
TestStage expectedStage = new TestStage();
expectedStage.setMainId("A");
expectedStage.putCell("B", 0, 0);
expectedStage.putCell("A", 1, 1);
Assert.assertTrue(result.isSameBord(new TheBoard(expectedStage.makeStage(), expectedStage.getMainId())));
result = result.makeNextBord(new TheMove("A", DIRECTION.UP));
Assert.assertTrue(result.isSameBord(bord));//ŏɖ߂Ă͂
result = bord.makeNextBord(new TheMove("A", DIRECTION.RIGHT));
Assert.assertNotNull(result);
expectedStage = new TestStage();
expectedStage.setMainId("A");
expectedStage.putCell("B", 0, 0);
expectedStage.putCell("A", 2, 0);
Assert.assertTrue(result.isSameBord(new TheBoard(expectedStage.makeStage(), expectedStage.getMainId())));
result = result.makeNextBord(new TheMove("A", DIRECTION.LEFT));
Assert.assertTrue(result.isSameBord(bord));//ŏɖ߂Ă͂
}
/**
*
* ubN̂Ƃ
*
* @author works
*/
@Test
public void makeNextBordTest2() {
TestStage ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("B", 0, 0);
ts1.putCell("A", 1, 0);
ts1.putCell("A", 2, 0);
TheBoard bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
//NGp^[iǂj
TheBoard result = null;
result = bord.makeNextBord(new TheMove("A", DIRECTION.UP));
Assert.assertNull(result);
//NGp^[ĩubNj
result = bord.makeNextBord(new TheMove("A", DIRECTION.LEFT));
Assert.assertNull(result);
//OKp^[
result = bord.makeNextBord(new TheMove("A", DIRECTION.DOWN));
Assert.assertNotNull(result);
TestStage expectedStage = new TestStage();
expectedStage.setMainId("A");
expectedStage.putCell("B", 0, 0);
expectedStage.putCell("A", 1, 1);
expectedStage.putCell("A", 2, 1);
Assert.assertTrue(result.isSameBord(new TheBoard(expectedStage.makeStage(), expectedStage.getMainId())));
result = result.makeNextBord(new TheMove("A", DIRECTION.UP));
Assert.assertTrue(result.isSameBord(bord));//ŏɖ߂Ă͂
result = bord.makeNextBord(new TheMove("A", DIRECTION.RIGHT));
Assert.assertNotNull(result);
expectedStage = new TestStage();
expectedStage.setMainId("A");
expectedStage.putCell("B", 0, 0);
expectedStage.putCell("A", 2, 0);
expectedStage.putCell("A", 3, 0);
Assert.assertTrue(result.isSameBord(new TheBoard(expectedStage.makeStage(), expectedStage.getMainId())));
result = result.makeNextBord(new TheMove("A", DIRECTION.LEFT));
Assert.assertTrue(result.isSameBord(bord));//ŏɖ߂Ă͂
}
@Test
public void makeNextBordTest3() {
//cɒ
TestStage ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("B", 0, 0);
ts1.putCell("A", 1, 0);
ts1.putCell("A", 1, 1);
TheBoard bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
//NGp^[iǂj
TheBoard result = null;
result = bord.makeNextBord(new TheMove("A", DIRECTION.UP));
Assert.assertNull(result);
//NGp^[ĩubNj
result = bord.makeNextBord(new TheMove("A", DIRECTION.LEFT));
Assert.assertNull(result);
//OKp^[
result = bord.makeNextBord(new TheMove("A", DIRECTION.DOWN));
Assert.assertNotNull(result);
TestStage expectedStage = new TestStage();
expectedStage.setMainId("A");
expectedStage.putCell("B", 0, 0);
expectedStage.putCell("A", 1, 1);
expectedStage.putCell("A", 1, 2);
Assert.assertTrue(result.isSameBord(new TheBoard(expectedStage.makeStage(), expectedStage.getMainId())));
result = result.makeNextBord(new TheMove("A", DIRECTION.UP));
Assert.assertTrue(result.isSameBord(bord));//ŏɖ߂Ă͂
result = bord.makeNextBord(new TheMove("A", DIRECTION.RIGHT));
Assert.assertNotNull(result);
expectedStage = new TestStage();
expectedStage.setMainId("A");
expectedStage.putCell("B", 0, 0);
expectedStage.putCell("A", 2, 0);
expectedStage.putCell("A", 2, 1);
Assert.assertTrue(result.isSameBord(new TheBoard(expectedStage.makeStage(), expectedStage.getMainId())));
result = result.makeNextBord(new TheMove("A", DIRECTION.LEFT));
Assert.assertTrue(result.isSameBord(bord));//ŏɖ߂Ă͂
}
@Test
public void makeNextBordTest4() {
//lp
TestStage ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("B", 0, 0);
ts1.putCell("A", 1, 0);
ts1.putCell("A", 1, 1);
ts1.putCell("A", 2, 0);
ts1.putCell("A", 2, 1);
TheBoard bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
//NGp^[iǂj
TheBoard result = null;
result = bord.makeNextBord(new TheMove("A", DIRECTION.UP));
Assert.assertNull(result);
//NGp^[ĩubNj
result = bord.makeNextBord(new TheMove("A", DIRECTION.LEFT));
Assert.assertNull(result);
//OKp^[
result = bord.makeNextBord(new TheMove("A", DIRECTION.DOWN));
Assert.assertNotNull(result);
TestStage expectedStage = new TestStage();
expectedStage.setMainId("A");
expectedStage.putCell("B", 0, 0);
expectedStage.putCell("A", 1, 1);
expectedStage.putCell("A", 1, 2);
expectedStage.putCell("A", 2, 1);
expectedStage.putCell("A", 2, 2);
Assert.assertTrue(result.isSameBord(new TheBoard(expectedStage.makeStage(), expectedStage.getMainId())));
result = result.makeNextBord(new TheMove("A", DIRECTION.UP));
Assert.assertTrue(result.isSameBord(bord));//ŏɖ߂Ă͂
result = bord.makeNextBord(new TheMove("A", DIRECTION.RIGHT));
Assert.assertNotNull(result);
expectedStage = new TestStage();
expectedStage.setMainId("A");
expectedStage.putCell("B", 0, 0);
expectedStage.putCell("A", 2, 0);
expectedStage.putCell("A", 2, 1);
expectedStage.putCell("A", 3, 0);
expectedStage.putCell("A", 3, 1);
Assert.assertTrue(result.isSameBord(new TheBoard(expectedStage.makeStage(), expectedStage.getMainId())));
result =result.makeNextBord(new TheMove("A", DIRECTION.LEFT));
Assert.assertTrue(result.isSameBord(bord));//ŏɖ߂Ă͂
}
@Test(expected = RuntimeException.class)
public void makeNextBordTest5() {
TestStage ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("B", 0, 0);
ts1.putCell("A", 1, 0);
TheBoard bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
bord.makeNextBord(null);
}
/**
* S[̈ʒuɂ邩ǂ̔ɗpĂ܂B
* SRS[ɂȂȂP[X
* ɂP[XiꕔS[ɂj
* S[ɂȂĂP[Xi~ubŇ`p^[j
* A܂B
* @author works
*/
@Test
public void isGoalTest(){
//////////////////////
//SRʖ
TestStage ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("A", 1, 0);
TheBoard bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
Assert.assertFalse(bord.isGoal());
//////////////////////
//ɂP[X1
ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("A", 0, 4);
ts1.putCell("A", 1, 4);
bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
Assert.assertFalse(bord.isGoal());
//////////////////////
//ɂP[X2
ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("A", 2, 4);
ts1.putCell("A", 3, 4);
bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
Assert.assertFalse(bord.isGoal());
//////////////////////
//S[P[X1(j
ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("A", 1, 4);
bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
Assert.assertTrue(bord.isGoal());
//////////////////////
//S[P[X2(cj
ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("A", 2, 3);
ts1.putCell("A", 2, 4);
bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
Assert.assertTrue(bord.isGoal());
//////////////////////
//S[P[X3(j
ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("A", 1, 4);
ts1.putCell("A", 2, 4);
bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
Assert.assertTrue(bord.isGoal());
//////////////////////
//S[P[X4(j
ts1 = new TestStage();
ts1.setMainId("A");
ts1.putCell("A", 1, 3);
ts1.putCell("A", 2, 3);
ts1.putCell("A", 1, 4);
ts1.putCell("A", 2, 4);
bord = new TheBoard(ts1.makeStage(), ts1.getMainId());
Assert.assertTrue(bord.isGoal());
}
/**
* makeNextBordTestłĂ̂ŏȗłB
*
* @author works
*/
public void isSameBordTest(){
}
}
|
Java
|
UTF-8
| 7,894 | 1.890625 | 2 |
[] |
no_license
|
package com.example.gpstrackerapp;
import android.os.Bundle;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;
import com.example.gpstrackerapp.ui.AccountFragment;
import com.example.gpstrackerapp.ui.HistoryFragment;
import com.example.gpstrackerapp.ui.LocationFragment;
import com.example.gpstrackerapp.ui.MessageFragment;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class ChildHomePageActivity extends FragmentActivity {
BottomNavigationView bottomNavigationView;
public static final int LAUNCH_MAP = 1;
String childId;
String phoneNumber;
MapActivity existedMapActivityFragment;
EmergencyActivity existedEmergencyActivity;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
bottomNavigationView = findViewById(R.id.bottom_navigation);
childId = getIntent().getStringExtra("CHILD_ID");
phoneNumber = getIntent().getStringExtra("PHONE_NUMBER");
final Bundle bundleToFragment = new Bundle();
bundleToFragment.putString("CHILD_ID_FOR_MAP", childId);
bundleToFragment.putString("PHONE_NUMBER_FOR_EMERGENCY", phoneNumber);
if(savedInstanceState == null){
MapActivity mapActivityFragment = new MapActivity();
mapActivityFragment.setArguments(bundleToFragment);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment, mapActivityFragment);
ft.commit();
getSupportFragmentManager().executePendingTransactions();
}
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
Fragment fragment = null;
switch (menuItem.getItemId()) {
case R.id.navigation_location:
if (getSupportFragmentManager().findFragmentByTag("MAP_ACTIVITY_FRAGMENT") == null) {
MapActivity mapActivityFragment = new MapActivity();
mapActivityFragment.setArguments(bundleToFragment);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment, mapActivityFragment, "MAP_ACTIVITY_FRAGMENT");
ft.addToBackStack("MAP_ACTIVITY_FRAGMENT");
existedMapActivityFragment = (MapActivity) getSupportFragmentManager().findFragmentByTag("MAP_ACTIVITY_FRAGMENT");
ft.detach(mapActivityFragment);
ft.attach(mapActivityFragment);
ft.commit();
getSupportFragmentManager().executePendingTransactions();
break;
}
else {
if (getSupportFragmentManager().findFragmentByTag("EMERGENCY_FRAGMENT") != null)
{
existedEmergencyActivity = (EmergencyActivity) getSupportFragmentManager().findFragmentByTag("EMERGENCY_FRAGMENT");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
getSupportFragmentManager().beginTransaction().hide(existedEmergencyActivity);
}
existedMapActivityFragment = (MapActivity) getSupportFragmentManager().findFragmentByTag("MAP_ACTIVITY_FRAGMENT");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(existedMapActivityFragment);
ft.attach(existedMapActivityFragment);
ft.commit();
break;
}
case R.id.navigation_message:
if (getSupportFragmentManager().findFragmentByTag("EMERGENCY_FRAGMENT") == null) {
if (getSupportFragmentManager().findFragmentByTag("MAP_ACTIVITY_FRAGMENT") != null)
{
existedMapActivityFragment = (MapActivity) getSupportFragmentManager().findFragmentByTag("MAP_ACTIVITY_FRAGMENT");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
getSupportFragmentManager().beginTransaction().hide(existedMapActivityFragment);
}
EmergencyActivity emergencyActivity = new EmergencyActivity();
emergencyActivity.setArguments(bundleToFragment);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment, emergencyActivity, "EMERGENCY_FRAGMENT");
ft.addToBackStack("EMERGENCY_FRAGMENT");
existedEmergencyActivity = (EmergencyActivity) getSupportFragmentManager().findFragmentByTag("EMERGENCY_FRAGMENT");
ft.detach(emergencyActivity);
ft.attach(emergencyActivity);
ft.commit();
getSupportFragmentManager().executePendingTransactions();
break;
}
else {
existedEmergencyActivity = (EmergencyActivity) getSupportFragmentManager().findFragmentByTag("EMERGENCY_FRAGMENT");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(existedEmergencyActivity);
ft.attach(existedEmergencyActivity);
ft.commit();
break;
}
case R.id.navigation_history:
if (getSupportFragmentManager().findFragmentByTag("HISTORY_MAP_FRAGMENT") == null) {
HistoryMapActivity historyMapActivityFragment = new HistoryMapActivity();
historyMapActivityFragment.setArguments(bundleToFragment);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragment, historyMapActivityFragment, "HISTORY_MAP_FRAGMENT");
ft.addToBackStack("HISTORY_MAP_FRAGMENT");
ft.detach(historyMapActivityFragment);
ft.attach(historyMapActivityFragment);
ft.commit();
getSupportFragmentManager().executePendingTransactions();
break;
}
else {
HistoryMapActivity historyMapActivityFragment = (HistoryMapActivity) getSupportFragmentManager().findFragmentByTag("HISTORY_MAP_FRAGMENT");
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.detach(historyMapActivityFragment);
ft.attach(historyMapActivityFragment);
ft.commit();
break;
}
}
return true;
}
});
}
}
|
Java
|
UTF-8
| 352 | 1.804688 | 2 |
[] |
no_license
|
package com.app.dao.impl;
import org.springframework.stereotype.Repository;
import com.app.dao.VilleDao;
import com.bo.Ville;
import com.genericdao.impl.HibernateSpringGenericDaoImpl;
@Repository
public class VilleDaoImpl extends HibernateSpringGenericDaoImpl<Ville, Long> implements VilleDao{
public VilleDaoImpl() {
super(Ville.class);
}
}
|
Java
|
UTF-8
| 663 | 3.0625 | 3 |
[] |
no_license
|
package Composite.EX2;
import java.util.ArrayList;
import java.util.List;
public class Folder extends SystemFIle {
private List<SystemFIle> systemFIles = new ArrayList<>();
public Folder(String systemFileName) {
super(systemFileName);
}
@Override
public void browse() {
super.browse();
for (SystemFIle systemFIle : systemFIles) {
systemFIle.browse();
}
}
@Override
public void addSystemFile(SystemFIle systemFIle) {
systemFIles.add(systemFIle);
}
@Override
public void removeSystemFile(SystemFIle systemFIle) {
systemFIles.remove(systemFIle);
}
}
|
C++
|
UTF-8
| 704 | 2.96875 | 3 |
[] |
no_license
|
#define PIN_ANALOG_RAIN_SENSOR A7 // Entrada analógica para la señal del sensor lluvia
#define PIN_DIGITAL_RAIN_SENSOR 21 // Entrada digital para la señal del sensor de lluvia
void setup(){
Serial.begin(9600);
}
void loop(){
int sensorValue = analogRead(PIN_ANALOG_RAIN_SENSOR); // Leer datos del puerto analógico
Serial.print("Analog value: ");
Serial.println(sensorValue); // Salida de valor analógico al monitor de puerto
sensorValue = digitalRead(PIN_DIGITAL_RAIN_SENSOR); // Leer datos del puerto digital
Serial.print("Digital value: ");
Serial.println(sensorValue); // Salida del valor digital al monitor del puerto
delay(1000); // Retardo entre mediciones
}
|
Python
|
UTF-8
| 4,055 | 2.734375 | 3 |
[] |
no_license
|
class BankData:
def __str__(self):
return "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t".format(self.age,
self.job,
self.marital,
self.education,
self.default,
self.balance,
self.housing,
self.loan,
self.contact,
self.day,
self.month,
self.duration,
self.campaign,
self.pdays,
self.previous,
self.poutcome,
self.y
)
def __init__(self, age, job, marital, education, default, balance, housing, loan, contact, day, month, duration,
campaign, pdays, previous, poutcome, y):
self.age = age
self.job = job
self.marital = marital
self.education = education
self.default = default
self.balance = balance
self.housing = housing
self.loan = loan
self.contact = contact
self.day = day
self.month = month
self.duration = duration
self.campaign = campaign
self.pdays = pdays
self.previous = previous
self.poutcome = poutcome
self.y = y
def getAllJobs(bData):
s = set()
for _ in bData:
s.add(_.job)
return s
if __name__ == '__main__':
data = None
d = []
with open('d:\\bank.csv', 'r') as f:
cols = []
rows = f.readlines()
for row in rows:
cols = row.split(';')
data = BankData(age=cols[0].replace('"', ''),
job=cols[1].replace('"', ''),
marital=cols[2].replace('"', ''),
education=cols[3].replace('"', ''),
default=cols[4].replace('"', ''),
balance=cols[5].replace('"', ''),
housing=cols[6].replace('"', ''),
loan=cols[7].replace('"', ''),
contact=cols[8].replace('"', ''),
day=cols[9].replace('"', ''),
month=cols[10].replace('"', ''),
duration=cols[11].replace('"', ''),
campaign=cols[12].replace('"', ''),
pdays=cols[13].replace('"', ''),
previous=cols[14].replace('"', ''),
poutcome=cols[15].replace('"', ''),
y=cols[16].replace('"', ''))
d.append(data)
print(data)
|
Java
|
UTF-8
| 2,387 | 2.296875 | 2 |
[] |
no_license
|
package br.com.oak.webly.authentication;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.stereotype.Component;
import br.com.oak.core.exception.OakException;
import br.com.oak.webly.core.exception.WeblyNegocioException;
import br.com.oak.webly.core.mensagem.MensagemErro;
import br.com.oak.webly.core.service.UsuarioService;
import br.com.oak.webly.core.util.ResourceUtil;
import br.com.oak.webly.core.util.UsuarioLogadoBuilder;
import br.com.oak.webly.core.vo.LoginVo;
import br.com.oak.webly.core.vo.UsuarioVo;
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UsuarioService service;
@Override
public Authentication authenticate(final Authentication authentication)
throws AuthenticationException {
try {
final String senha = (String) authentication.getCredentials();
final UsuarioVo usuario = service
.recuperarUsuarioParaLogin(new LoginVo(authentication
.getName(), senha));
final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl(usuario.getRoleUsuario()));
return new UsernamePasswordAuthenticationToken(
new UsuarioLogadoBuilder(usuario).getUsuarioLogado(),
senha, authorities);
} catch (final WeblyNegocioException e) {
throw new BadCredentialsException(e.getMessage(), e);
} catch (final OakException e) {
throw new BadCredentialsException(
ResourceUtil.recuperaMensagemErro(MensagemErro.ERRO_INESPERADO
.getCodigo()));
} catch (final Exception e) {
throw new BadCredentialsException(
ResourceUtil.recuperaMensagemErro(MensagemErro.ERRO_INESPERADO
.getCodigo()));
}
}
@Override
public boolean supports(Class<? extends Object> authentication) {
return true;
}
}
|
Java
|
UTF-8
| 3,007 | 2.390625 | 2 |
[] |
no_license
|
package com.homer.fantasy.dao.impl;
import com.homer.fantasy.MinorLeagueDraftPick;
import com.homer.fantasy.Team;
import com.homer.fantasy.dao.HomerDAO;
import com.homer.fantasy.dao.IMinorLeagueDraftPickDAO;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* Created by arigolub on 2/24/15.
*/
public class HibernateMinorLeagueDraftPickDAO extends HomerDAO implements IMinorLeagueDraftPickDAO {
private static final Logger LOG = LoggerFactory.getLogger(HibernateMinorLeagueDraftPickDAO.class);
@Override
public MinorLeagueDraftPick savePick(MinorLeagueDraftPick minorLeagueDraftPick) {
LOG.debug("BEGIN: savePick [minorLeagueDraftPick=" + minorLeagueDraftPick + "]");
MinorLeagueDraftPick existingPick = getDraftPick(minorLeagueDraftPick.getOriginalTeam(), minorLeagueDraftPick.getSeason(), minorLeagueDraftPick.getRound());
if(existingPick != null) {
minorLeagueDraftPick.setMinorLeagueDraftPickId(existingPick.getMinorLeagueDraftPickId());
}
boolean success = saveOrUpdate(minorLeagueDraftPick);
if(!success) {
minorLeagueDraftPick = null;
}
LOG.debug("END: savePick [minorLeagueDraftPick=" + minorLeagueDraftPick + "]");
return minorLeagueDraftPick;
}
@Override
public MinorLeagueDraftPick getDraftPick(Team originalTeam, int season, int round) {
LOG.debug("BEGIN: getDraftPick [originalTeam=" + originalTeam + ", season=" + season + ", round=" + round + "]");
MinorLeagueDraftPick example = new MinorLeagueDraftPick();
example.setOriginalTeam(originalTeam);
example.setSeason(season);
example.setRound(round);
MinorLeagueDraftPick minorLeagueDraftPick = findUniqueByExample(example, MinorLeagueDraftPick.class);
LOG.debug("END: getDraftPick [minorLeagueDraftPick=" + minorLeagueDraftPick + "]");
return minorLeagueDraftPick;
}
@Override
public List<MinorLeagueDraftPick> getDraftPicksForTeam(Team owningTeam) {
LOG.debug("BEGIN: getDraftPicksForTeam [team=" + owningTeam + "]");
List<MinorLeagueDraftPick> minorLeagueDraftPickList = null;
Session session = null;
try {
session = openSession();
session.beginTransaction();
minorLeagueDraftPickList = session.createCriteria(MinorLeagueDraftPick.class)
.add(Restrictions.like("owningTeam.teamId", owningTeam.getTeamId()))
.list();
} catch (RuntimeException re) {
LOG.error("Error getting object", re);
} finally {
if(session != null) {
session.close();
}
}
LOG.debug("END: getDraftPicksForTeam [minorLeagueDraftPicks=" + minorLeagueDraftPickList + "]");
return minorLeagueDraftPickList;
}
}
|
Java
|
UTF-8
| 7,760 | 2.765625 | 3 |
[
"CC0-1.0"
] |
permissive
|
import java.io.File;
import java.util.BitSet;
import java.util.Scanner;
public class MainClass
{
public static String[] wordsStr;
public static String[] wordsStrPart;
public static String[] wordsStrTotal;
public static int[] trainInts;
public static String train;
public static short[][] coocFreqArr;
public static short[][] coocFreqArrPart;
public static short[][] coocFreqArrTotal;
public static short[][] twogramFreqArr;
public static short[][] twogramFreqArrPart;
public static short[][] twogramFreqArrTotal;
public static short[][] threegramFreqArr;
public static short[][] threegramFreqArrPart;
public static short[][] threegramFreqArrTotal;
public static short[][] fourgramFreqArr;
public static short[][] fourgramFreqArrPart;
public static short[][] fourgramFreqArrTotal;
public static short[][] fivegramFreqArr;
public static short[][] fivegramFreqArrPart;
public static short[][] fivegramFreqArrTotal;
public static short[] freqArr;
public static short[] freqArrPart;
public static short[] freqArrTotal;
public static BitSet[] coocIsNonzeroArr;
public static short[][] coocArrByInd;
public static short[][] coocArrByRel;
public static String[] query;
public static int[] queryInts;
public static int[][] queryResultInts;
public static Scanner scanner;
public static String inStr;
// saving and checking for nonzero relats first
// easier to have multiple lists of words using short rather than using int (can be slower for less common words)
public static void main(String [] args)
{
scanner = new Scanner(System.in);
System.out.print("Please enter arg : ");
inStr = ""+scanner.next();
// might combine words and coocs if not filtering out some words from freqs; don't know what to do yet
if (inStr.equals("words"))
{
scanner.close();
train = "trainFileLong.txt";
File wordsFile = new File("words.txt");
if (wordsFile.exists() == true)
{
wordsStrTotal = ExtractWordsFromFile.returnWords(wordsFile);
freqArrTotal = ExtractFreqsFromFile.returnFreqs(wordsFile);
FindAndSortTrainWords.printWords(train, wordsStrTotal, freqArrTotal);
}
else
FindAndSortTrainWords.printWords(train);
System.out.println("success");
}
else if (inStr.equals("coocs"))
{
// finish all words first, then use coocs (coocs doesn't re-sort like words does)
scanner.close();
train = "trainFileLong.txt";
File wordsFile = new File("words.txt");
wordsStr = ExtractWordsFromFile.returnWords(wordsFile);
trainInts = EncodeTrainFile.returnEncodedTrainInts(train, wordsStr);
coocFreqArrPart = FindCoocs.returnCoocFreqs(trainInts, wordsStr.length, 50);
twogramFreqArrPart = FindCoocs.returnCoocFreqs(trainInts, wordsStr.length, 2);
threegramFreqArrPart = FindCoocs.returnCoocFreqs(trainInts, wordsStr.length, 3);
fourgramFreqArrPart = FindCoocs.returnCoocFreqs(trainInts, wordsStr.length, 4);
fivegramFreqArrPart = FindCoocs.returnCoocFreqs(trainInts, wordsStr.length, 5);
File coocFile = new File("coocFile.txt");
File twogramCoocFile = new File("2gramFile.txt");
File threegramCoocFile = new File("3gramFile.txt");
File fourgramCoocFile = new File("4gramFile.txt");
File fivegramCoocFile = new File("5gramFile.txt");
if (coocFile.exists() == true)
{
coocFreqArrTotal = ExtractCoocsFromFile.returnCoocFreqShorts(coocFile);
PrintCooc.printCoocFreqArr(coocFreqArrPart, coocFreqArrTotal, 50);
twogramFreqArrTotal = ExtractCoocsFromFile.returnCoocFreqShorts(twogramFile);
PrintCooc.printCoocFreqArr(twogramFreqArrPart, twogramFreqArrTotal, 2);
threegramFreqArrTotal = ExtractCoocsFromFile.returnCoocFreqShorts(threegramFile);
PrintCooc.printCoocFreqArr(threegramFreqArrPart, threegramFreqArrTotal, 3);
fourgramFreqArrTotal = ExtractCoocsFromFile.returnCoocFreqShorts(fourgramFile);
PrintCooc.printCoocFreqArr(fourgramFreqArrPart, fourgramFreqArrTotal, 4);
fivegramFreqArrTotal = ExtractCoocsFromFile.returnCoocFreqShorts(fivegramFile);
PrintCooc.printCoocFreqArr(fivegramFreqArrPart, fivegramFreqArrTotal, 5);
}
else
{
PrintCooc.printCoocFreqArr(coocFreqArrPart, 50);
PrintCooc.printCoocFreqArr(twogramFreqArrPart, 2);
PrintCooc.printCoocFreqArr(threegramFreqArrPart, 3);
PrintCooc.printCoocFreqArr(fourgramFreqArrPart, 4);
PrintCooc.printCoocFreqArr(fivegramFreqArrPart, 5);
}
System.out.println("success");
}
else if (inStr.equals("rank"))
{
File coocFile = new File("coocFile.txt");
coocFreqArr = ExtractCoocsFromFile.returnCoocFreqShorts(coocFile);
PrintCooc.printCoocByIndFile(coocFreqArr, 50); // fix to use coocRatio for both ways, also fix to count freq instead of extract
File twogramFile = new File("2gramFile.txt");
twogramFreqArr = ExtractCoocsFromFile.returnCoocFreqShorts(twogramFile);
PrintCooc.printCoocByIndFile(twogramFreqArr, 2);
File threegramFile = new File("3gramFile.txt");
threegramFreqArr = ExtractCoocsFromFile.returnCoocFreqShorts(threegramFile);
PrintCooc.printCoocByIndFile(threegramFreqArr, 3);
File fourgramFile = new File("4gramFile.txt");
fourgramFreqArr = ExtractCoocsFromFile.returnCoocFreqShorts(fourgramFile);
PrintCooc.printCoocByIndFile(fourgramFreqArr, 4);
File fivegramFile = new File("5gramFile.txt");
fivegramFreqArr = ExtractCoocsFromFile.returnCoocFreqShorts(fivegramFile);
PrintCooc.printCoocByIndFile(fivegramFreqArr, 5);
}
// protect against overflow of shorts
//coocIsNonzeroArr = FindCooc.returnCoocNonzeros(trainInts, wordsStr.length, 50);
else if (inStr.equals("query"))
{
System.out.print("Please enter query length : ");
inStr = ""+scanner.nextInt();
query = new String[Integer.parseInt(inStr)];
for (int i=0; i<query.length; i++)
{
System.out.print("Please enter query["+i+"] : ");
inStr = ""+scanner.next();
query[i] = inStr;
System.out.println("query word inputted");
}
scanner.close();
System.out.println(query[0]+" "+query[1]);
File wordsFile = new File("words.txt");
File coocByIndFile = new File("coocByIndFile.txt");
wordsStr = ExtractWordsFromFile.returnWords(wordsFile);
queryInts = FindQueryInts.returnQueryInts(query, wordsStr);
coocArrByInd = ExtractCoocsFromFile.returnCoocByIndShorts(coocByIndFile, wordsStr.length);
// maybe change names to FindQueryResults and GrammaticizeQueryResults (though basically composing more than grammaticizing results)
queryResultInts = ExpandQuery.returnQueryResultInts(queryInts, coocArrByInd); // fix to sort and separate into results
File twogramFile = new File("2gramFile.txt");
twogramFreqArr = ExtractCoocsFromFile.returnCoocs(twogramFile, wordsStr.length);
File threegramFile = new File("3gramFile.txt");
threegramFreqArr = ExtractCoocsFromFile.returnCoocs(threegramFile, wordsStr.length);
File fourgramFile = new File("4gramFile.txt");
fourgramFreqArr = ExtractCoocsFromFile.returnCoocs(fourgramFile, wordsStr.length);
File fivegramFile = new File("5gramFile.txt");
fivegramFreqArr = ExtractCoocsFromFile.returnCoocs(fivegramFile, wordsStr.length);
queryResultInts = GrammaticizeExpandedQuery.returnGEQuery(queryResultInts, twogramFreqArr, threegramFreqArr, fourgramFreqArr, fivegramFreqArr);
FindAnswerWords.returnAnswerWords(queryResultInts, wordsStr);
System.out.println("");
System.out.println("success");
}
}
}
// sort results by the relevanceCounter
// need a 2d array for results: [numResults][numIndexesInResult]
// add up values instead of just finding highest chain, helps prevent bag of words grammar
// consider function to automatically process train files in correct order, might have hundreds or more in storage, easier than waiting for download
// ngrams like markov optimization?
|
PHP
|
UTF-8
| 724 | 2.765625 | 3 |
[] |
no_license
|
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Profile;
use App\Models\Post;
class PostSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$profile = Profile::find(1);
$post = new Post;
$post->title = 'math';
$post->content = '2 + 2 = 5';
$post->profile_id = $profile->id;
$post->save();
$profile = Profile::find(2);
$post = new Post;
$post->title = 'science';
$post->content = 'what goes up must come down';
$post->profile_id = $profile->id;
$post->save();
Post::factory(50)->create();
}
}
|
Python
|
UTF-8
| 1,062 | 3.4375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Created by Chukwunyere Igbokwe on December 29, 2016 by 10:31 PM
def romanToInt( s):
roman_dict = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
roman_ixc = {'I':5, 'X':50, 'C':500}
value = 0
for i in reversed(s):
if i in roman_ixc and value >= roman_ixc[i]:
value -= roman_dict[i]
else:
value += roman_dict[i]
return value
print romanToInt('MMMCMXVIII')
def romanToInt(s):
map={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
pre=100000
ret=0
for i in s:
cur=map[i]
if cur>pre:
ret=ret-pre-pre+cur
else:
ret=ret+cur
pre=cur
return ret
print romanToInt('MMDCCLXVI')
def romanToInt(s):
roman = {'M': 1000,'D': 500 ,'C': 100,'L': 50,'X': 10,'V': 5,'I': 1}
z = 0
for i in range(0, len(s) - 1):
if roman[s[i]] < roman[s[i+1]]:
z -= roman[s[i]]
else:
z += roman[s[i]]
return z + roman[s[-1]]
print romanToInt('MCDLXXXIX')
|
C#
|
UTF-8
| 3,666 | 4 | 4 |
[] |
no_license
|
using System;
/*Write a program that finds the sequence of maximal sum in given array. Example:
* {2, 3, -6, -1, 2, -1, 6, 4, -8, 8} {2, -1, 6, 4}
* Can you do it with only one loop (with single scan through the elements of the array)?*/
public class FindMaxSumSequenceInArray
{
public static void Main()
{
Console.Title = "Sequence of maximal sum";
double[] inputArray = { 2, 3, -6, -1, 2, -1, 6, 4, -8, 8 };
/*// Input cycle
Console.WriteLine("Enter array elements:");
for (int arrIndex = 0; arrIndex < inputArray.Length; arrIndex++)
{
// Internal cycle for correct input
do
{
Console.Write(" element " + (arrIndex + 1) + " - ");
string temp = Console.ReadLine();
bool correctInput = double.TryParse(temp, out inputArray[arrIndex]);
if (correctInput)
{
break;
}
else
{
Console.WriteLine("Wrong input number! Try again.");
}
}
while (true);
}*/
// Variable that keeps current sum
double currentSum = new double();
// Variable that keeps current biggest sum
double bestSum = new double();
// Variable that keeps starting index for the result sequence
int resultSeqStart = new int();
// Variable that keeps final index for the result sequence
int resultSeqStop = inputArray.Length;
int length = inputArray.Length;
// Flag used to mark the beginning of new result sequence
bool isNewSequence = new bool();
for (int arrIndex = 0; arrIndex < length; arrIndex++)
{
// Variable to save the sum before adding current element
double previousSum = currentSum;
currentSum += inputArray[arrIndex];
// Check if sum is growing
if (currentSum > previousSum)
{
// The following block ensures that the last element will not be missed
// Check if the last index is reached and sum is bigger than the last best one
if (arrIndex == length - 1 && currentSum > bestSum)
{
if (isNewSequence)
{
resultSeqStart = arrIndex;
}
resultSeqStop = arrIndex;
break;
}
else
{
// If this is the beginning of new result sequence set start index
if (isNewSequence)
{
resultSeqStart = arrIndex;
isNewSequence = false;
}
continue;
}
}
else
{
// Save current best sum and the final index of result sequence
if (previousSum > bestSum)
{
bestSum = previousSum;
resultSeqStop = arrIndex - 1;
}
else if (currentSum <= 0)
{
isNewSequence = true;
currentSum = 0;
}
}
}
// Print the result
Console.Write("The sequence of maximal sum is: ");
for (int index = resultSeqStart; index <= resultSeqStop; index++)
{
Console.Write(inputArray[index] + ", ");
}
Console.WriteLine("\b\b ");
}
}
|
JavaScript
|
UTF-8
| 1,826 | 3.140625 | 3 |
[] |
no_license
|
// Use this file when you want to clear
// and seed new data into your db
// In terminal: node seed.js
const mongoose = require('mongoose');
const EduBlock = require('./models/eduBlock');
mongoose.connect('mongodb://localhost:27017/fruitful-supply', {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const seedDB = async () => {
await EduBlock.deleteMany({});
const blockOne = new EduBlock({
title: 'Linked List',
image: 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Singly-linked-list.svg/1920px-Singly-linked-list.svg.png',
summary: 'A linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next.'});
await blockOne.save();
const blockTwo = new EduBlock({
title: 'Binary Search Tree',
image: 'https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Binary_search_tree.svg/1024px-Binary_search_tree.svg.png',
summary: "A rooted binary tree whose internal nodes each store a key greater than all the keys in the node's left subtree and less than those in its right subtree."});
await blockTwo.save();
const blockThree = new EduBlock({
title: 'Stack',
image: 'https://upload.wikimedia.org/wikipedia/commons/b/b4/Lifo_stack.png',
summary: 'A collection of elements, with two main principal operations: Push, which adds an element to the collection, and Pop, which removes the most recently added element that was not yet removed.'});
await blockThree.save();
}
seedDB().then(() => {
mongoose.connection.close();
});
|
Markdown
|
UTF-8
| 677 | 2.8125 | 3 |
[] |
no_license
|
#Voici mon projet qui a été réalisé en classe de Terminale.
Le point central de ce projet consistait à créer un programme en python permmettant de coder/décoder un message grâce à la méthide César(1).
De plus, nous devions créer un site web qui serait un support pour présenter ce projet.
#(1): La méthode César ou chiffre de César ou encore le code de César, est une méthode de chiffrement par décallage utilisée par Jules César. Elle consiste à remplacer chaque lettre d'un texte clair par lettre à distance fixe. Par exemple avec un décallage de 3 lettre vers la droite, "Mon texte" devient "Prq whawh". C'est une méthode asser simple de nos jours.
|
Java
|
UTF-8
| 1,475 | 2.96875 | 3 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package InputOutput;
import datatstructures.EmployeeRecord;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import utilities.Encryption;
/**
*
* @author nieschri125
* @purpose To create a random file
*/
public class CreateRecords {
final static String RAF_FILE = "login.bin";
final static int REC_LENGTH = 500;
public static void main(String args[]) {
RandomFile rFile = new RandomFile(RAF_FILE, REC_LENGTH);
rFile.prepareInputFile();
try {
//static login user
EmployeeRecord test;
String fname = "Chris";
String lname = "Niesel";
int number = 10001;
Boolean manager = false;
String pass = "test";
test = new EmployeeRecord();
test.setEmployeeNumber(number);
test.setFirstName(fname);
test.setLastName(lname);
test.setManager(manager);
test.setPassword(Encryption.makeHash(pass));
rFile.writeNextRecord(test);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(CreateRecords.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(CreateRecords.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
|
C++
|
UTF-8
| 326 | 3.203125 | 3 |
[] |
no_license
|
#include "stdafx.h"
//DISPLAY_ARRAY(), prints the array
void display_array(int** target, unsigned int dimension)
{
unsigned int i, j;
cout << endl;
cout << "Array output: ";
cout << endl;
for (i = 0; i < dimension; i++)
{
for (j = 0; j < dimension; j++)
{
cout << target[i][j] << " ";
}
cout << endl;
}
}
|
Python
|
UTF-8
| 2,779 | 2.703125 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
from zope.interface import Interface
from zope.interface.interfaces import IInterface
from zope.interface import Attribute
from zope import schema
class ITimezoneGetter(Interface):
""" Get the configured timezone.
The implementation of ITimezoneGetter is registered as utility, which can
be overloaded in subsequent packages, creating a chain with fallbacks.
Based on pytz, using the Olson database.
"""
timezone = Attribute(u"""Get the configured Timezone.""")
class IEvent(Interface):
"""Generic calendar event for Plone.
"""
# TODO: agree on what fields should go into this interfaces and
# fill it in
start_date = Attribute(u"""Date when the first occurence of the event
begins as datetime object""")
end_date = Attribute(u"""Date when the first occurence of the event ends as
datetime object""")
class IRecurringEvent(IEvent):
"""Generic recurring calendar event for Plone.
"""
recurrence = Attribute(u'Recurrence definition')
class IRecurringEventICal(IRecurringEvent):
"""Marker interface for RFC2445 recurring events.
"""
recurrence = Attribute(u"""Recurrence definition as RFC2445 compatible
string""")
class IRecurringEventTimeDelta(IRecurringEvent):
"""Marker interface for TimeDelta recurring events.
"""
recurrence = Attribute(u"""Recurrence definition as delta from start in
minutes""")
class IRecurrenceSupport(Interface):
"""Interface for adapter providing recurrence support.
"""
def occurences_start():
"""Return all the event's start occurences which indicates the
beginning of each event.
"""
def occurences_end():
"""Return all the event's end occurences which indicates the
ending of each event.
"""
def occurences():
"""Return all the event's start and end occurences as a list of tuples.
"""
class IICalendar(Interface):
"""Provide header and footer for iCalendar format.
"""
context = schema.Object(
title=u"Any interface that might provide data for iCal header",
description=u'',
schema=IInterface
)
def header():
"""Returns iCal header"""
def footer():
"""Returns iCal footer"""
class IICalEventExporter(Interface):
"""Serialize single event into iCalendar formatted entry.
"""
context = schema.Object(
title=u"Event",
description=u'',
schema=IEvent
)
def feed():
"""Return ICal event entry, doesn't include iCal header, that should
be done in application level.
"""
|
Markdown
|
UTF-8
| 8,280 | 3 | 3 |
[] |
no_license
|
你好,我是崔俊涛,今天继续聊聊技术团队的激励这个话题,上文中提到,我们可以从设定目标、进行考核以及实施激励这三个阶段着手来做好激励。今天,我将继续分享一些我在目标考核及实施激励这两个阶段的经验,希望能对你有所帮助。
## 目标考核
目标设定完毕后,团队就需要定期监控目标的达成进度和完成情况,并及时向团队成员进行反馈,修正目标的偏离和漂移,并且及时根据市场及业务的发展情况对目标进行调整,保持公司的竞争力和活力。目标考核一般分为几个方面:即时反馈、量化考核及目标修正。
### 即时反馈
积极心理学奠基人米哈里在《心流》一书中着重提到,获得即时反馈能够帮助我们进入心流状态,即全神贯注、投入忘我的状态。回想一下我们玩游戏时的状态,全神贯注、废寝忘食,感觉特别爽。为什么游戏能让我们达到这个状态,因为Double Kill、升级、装备等即时反馈的机制存在。米哈里认为即时反馈本身是什么并不是很重要,真正重要的是,通过这个反馈信号,能让你觉得达到或者在接近目标。因此在工作中,团队管理者需要对团队取得的成果给予即时的反馈,包括对接近目标的鼓励和表扬,对远离目标的批评和建议。
### 量化考核
对目标的即时反馈取决于我们如何判断当前工作是接近还是远离目标,所以要有可以量化的考核方式。量化考核一方面依赖于可以量化的目标,另一方面需要依赖于对于过程的量化的监控。量化的目标在目标管理的章节已经讨论过,这里重点说一下如何量化过程。
技术团队的过程量化一直是个比较大的难点,我们聪明的产品狗(读得时候读作产品人)或程序猿总是能够很快定位到过程量化中的漏洞并且绕过。举个例子,之前有一个指标是BUG数量/代码行数,但程序猿很快就发现可以多写空行或者多换行来降低这个数字。
目前,在实际的量化考核中,我们主要采用如下几种方式:
1.项目完成度:对于团队来说,项目按时按质完成是首要任务,因此项目完成度是一项比较重要的指标。
2.任务积分:将产品和项目分解成工作量差不多的任务,交由团队成员来挑选,完成任务可以增加任务积分,每月统计一次任务积分,根据排名进行不同的奖惩。
3.严重/无脑BUG排名:对测试过程中或生产环境上产生的严重/无脑BUG进行统计。
4.知识分享积分:鼓励团队成员之间的知识分享,可以通过会议、文档、沟通的方式来进行。
5.工时排名:我们承认每个人的效率会有差异,但不可否认的是团队成员的效率差距一般不会特别明显,在这种情况下,投入的时间和精力能够成为衡量一个人工作情况的重要参考指标。
### 目标修正
俗话说,唯一不变的就是变化,这是大多数公司面临的现实情况。市场的变化、竞争的变化、政策的变化以及执行的结果都会导致公司目标发生变化和调整,因此需要定期回顾目标及其完成情况,然后根据公司实际情况进行修正,并且将新的目标共享给团队成员。
## 激励
最激动人心的时刻到了,所有团队成员都在等着这一刻,目标达成,拿到期盼已久的奖励。通俗地说,激励就是怎么分的问题。激励一般有如下几种:精神激励、晋升激励、物质激励等。
1.精神激励
领导的信任、良好的情感空间和氛围、对自身价值的认同都属于精神激励的范畴。精神激励是一种低成本、高效率的激励方式。这种激励方式能够最大限度的激发团队成员的积极性和创造性,提高忠诚度和自信心,久而久之,团队就形成了家庭般的氛围,气氛融洽、目标清晰、分工明确、互帮互助,这也是很多公司追求的团队氛围。
精神激励可分为持续性和临时性两种方式。持续性的包括定期评比,比如每月的任务之星、最少bug奖等,奖励方式可以是光荣榜、流动锦旗等。临时性的适用于完成了某个项目或者任务、帮助了某位同事等非持续性的工作,奖励方式可以是语言激励、团队表扬、聚餐等方式。从这些方式来看,精神激励简单直接,并且能产生较大的效果。
2.晋升激励
如果说精神激励属于柏拉图式的激励,晋升激励就属于直接激励了。通过职位或者职称的晋升,团队成员的价值获得最直接、最明确、最广泛的认可。在公司层面上一般都会有技术职级的设定,比如阿里的P序列,腾讯的T序列等。有些公司还会成立技术委员会来参与技术团队的职级晋升评定,结合KPI或OKR的完成度来对团队成员进行评定以决定是否能参与晋级评定。
3.物质激励
物质激励也是比较常见的直接激励手段,也是最能体现怎么分的细节。但是在使用物质激励时需要小心,避免掉进物质激励的陷阱。
首先是平均主义。中国有句古语:不患寡而患不均。因此团队管理者在分配奖励时最先考虑的是公平,不巧的是,有时候我们认为公平=平均,所以倾向于采用按照工资比例分配的方式来发放物质激励。但往往这种激励不仅达不到激励的效果,还会引起反作用,使团队成员觉得激励不公平。在大多数人眼里,只要分配有规律可循,根据规律计算出自己拿少了或者别人拿的多了,就很容易感到不公平,因此很难找到让所有人都满意的公平方法。所以在实际操作中,可以不按照规律来分配物质激励,或者说团队管理者可以比较随心的分配激励,不需要让团队成员看到其中的规律。
其次,过于依赖物质激励。团队管理者往往有一种概念:只要给足了钱,员工必然会感恩,从而提高忠诚度和积极性。其实未必,试想这种情况,整体业绩好的时候,发了很多奖金,但如果第二年整体业绩不好,奖金少发了,部分团队成员就会产生不满的情绪。由俭入奢易,由奢入俭难,就是这个道理。人的欲望是无止境的,物质的激励只会逐步放大欲望。
对大部分团队成员来说,精神激励的效果要大于金钱激励。在基本物质需求得到满足的基础上,员工更需要的是肯定与褒奖,即精神层面的鼓励。比如每个月给某个团队成员发1万块钱奖金,但天天当众骂他废物,另外一个员工每个月只给1000块钱奖金,但天天当众夸他做得好,哪个对他的激励效果更大?前者是管理者在用金钱买员工的尊严,员工拿了钱都不会念你的好,闹不好心里反而会记恨你;后者管理者通过充分给予员工尊严为自己省钱,员工也会视你为知己,像打了鸡血一样为你效命。
4.量身定做
团队成员的情况千差万别,有人追求精神激励,有人追求物质激励,所以激励手段和方法不能一概而论,要单独为团队成员量身定做激励方案。这就要求团队管理者对团队成员的情况有比较清楚的了解,清楚的知道每个团队成员处于马斯洛需求层次的哪个阶段,以便于对症下药。
## 总结
总结下来,关于团队激励,本文只是讨论了两个问题:给谁干和怎么分。通过目标管理,团队管理者可以将团队目标转化为团队成员自己的目标,从而达到每个人都是在为自己干的目的。通过激励管理,团队管理者可以使团队成员都产生一种拿到了合理甚至丰厚回报的感觉,从而激发团队成员的积极性和潜力,形成良性循环。
感谢你的收听,我们下期再见,如果你有不同的观点,也欢迎在评论区留言讨论~
## 作者简介
崔俊涛,TGO鲲鹏会会员,目前担任上海万位数字科技有限公司CTO,专注于位置服务、大数据及汽车金融风控解决方案领域。
|
Python
|
UTF-8
| 1,967 | 2.609375 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# encoding: utf-8
__author__ = 'Florian Bauer'
import archive.config.reader as reader
import archive.config.writer as writer
import archive.config.xmlhandler as xmlhandler
import unittest
def _as_int(value):
'''
Converts value to int if string is numeric
'''
if type(value) is str and value.isnumeric():
return int(value)
else:
return value
def get(url):
'''
Returns actual value for url.
If not found, it trys to return default value.
'''
return _as_int(reader.get(url))
def get_default(url):
'''
Returns default value for url.
'''
return _as_int(reader.get_default(url))
def set(url, value):
'''
Set value of url to given value.
'''
return writer.set_value(url, value)
# Not used
def set_default(url):
return writer.set_default(url)
def load(path):
'''
Load xml file with given path
'''
return xmlhandler.load(path)
###########################################################################
# unittest #
###########################################################################
CONFIG_FILE = 'archive/testdata/webarchive.conf.xml'
class TestHandler(unittest.TestCase):
def setUp(self):
self.assertTrue(load(CONFIG_FILE))
def test_load(self):
self.assertTrue(load(xmlhandler.gConfigPath))
self.assertFalse(load('notfound.xml'))
def test_get(self):
self.assertNotEqual(get('general.root'), False)
self.assertFalse(get('not.found'))
self.assertEqual(get('test.main'), -1)
def test_set(self):
self.assertFalse(set('not.found', 'value'))
self.assertTrue(set('general.root', '/tmp'))
def test_getDefault(self):
self.assertNotEqual(get_default('general.root'), False)
self.assertFalse(get_default('not.found'))
if __name__ == '__main__':
unittest.main()
|
C++
|
UHC
| 457 | 2.859375 | 3 |
[] |
no_license
|
/*
ۼ : 2018 04 04
:
*/
#include <iostream>
int main(void){
std::cout<<"prac01_1_4 : ̿"<<std::endl;
int sell=0;
while(sell!=-1){
std::cout<<"Ǹ ݾ Էϼ. :(-1 to end)"<<std::endl;
std::cin>>sell;
if(sell==-1) break;
std::cout<<"̹ : "<< 50+sell*0.12<<std::endl;
}
std::cout<<"α մϴ.";
return 0;
}
|
Markdown
|
UTF-8
| 5,512 | 3.671875 | 4 |
[] |
no_license
|
# Homework #3
### 1. Classify the following as a syntax error, semantic error, or not a compile time error. In the case where code is given, assume all identifiers are properly declared and in scope. All items refer to the Java language.
#### a. x+++-y
Not a compile time error
#### b. x---+y
Not a compile time error
#### c. incrementing a read-only variable
Semantic error
#### d. accessing a private field in another class
Semantic error
#### e. Using an uninitialized variable
Semantic error
#### f. Dereferencing a null reference
Not a compile time error
#### g. null instanceof C
Not a compile time error
#### h. !!x
Not a compile time error
### 2. State scope rules that would have caused them:
```JavaScript
var x = 3; // line 1
function f() { // line 2
print(x); // line 3
var x = x + 2; // line 4
print(x); // line 5
} // line 6
f(); // line 7
```
#### a. 3 5
This would happen when the scope begins after the line of code declaring it has completed. When printing on line 3, since line 4 appears after, the outer scope (nonlocal value) of x is used, 3. After line 4 finishes, the inner x value, 5, is now used in the print statement on line 5.
#### b. `undefined` `NaN`
Something like this could happen when the scope of the x declaration on line 3 is the function in which it is declared. Thus, when entering new function f, x becomes `undefined` since the program cannot "see" the declaration outside of the function. Then, on line 4, the program is attempting to add 2 to `undefined`, which will result in `NaN` when printed on line 6. This is an example of scope similar to JavaScript `var`.
#### c. `Error on line 3: x is not declared`
This is an example of scope similar to that of JavaScript `let`. x on line 1 is declared in the outer scope, and once the function f begins, so does the Temporal Dead Zone. Thus, attempting to access x on line 3 will throw the error that x cannot be accessed since it has not been initialized nor declared.
#### d. 75354253672 75354253674
As usual, the declaration on line 1 is the outer x scope, and function f uses the inner x declared on line 4. When getting printed on line 3, x is bound to its memory address, but since there is no declaration by line 3, garbage (75354253672) is printed out, and stored as x. On line 4, x now becomes whatever the garbage printed + 2 (75354253672 + 2 = 75354253674).
#### e. 3 -23482937128
This is an example of the scope starting at the point of declaration, but does not wait for the declaration to be finished. On line 3, the x printed out is still the x from the outer scope on line 1, since no other x has been declared inside of the function. Because of the declaration not needing to be complete in scoping, the identifier can be used right away. In line 4: `var x = x + 2;`, the x in `var x` is the x that is going to be used in the declaration. Since that inner x has not been declared, it contains garbage. Thus the inner x value is whatever garbage + 2. The print statement on line 5 then refers to the inner x declared on line 4.
#### f. `Error on line 4: x used in its own declaration`
For this, the scope rule can either be the whole function or the point of declaration, but the language and the compiler itself will not allow for a variable to be used in its own declaration. This code will not print anything out, since this error will cause program failure at compile time.
### 3. Describe the semantics of `private` in Ruby and C#.
Generally speaking, in C#, `private` pertains to and entire class and all of the instances of that class, where in Ruby, `private` only refers to the object. One could say that `private` in C# is class-based, where `private` in Ruby is object-based.
Below is an example of using `private` in C#:
```C#
using System;
public class C
{
private int x;
public C(int x)
{
this.x = x;
}
public void display(C c)
{
Console.WriteLine("x is: " + c.x);
}
public static void Main(String[] args)
{
C c1 = new C(3);
c1.display(c1); //output 3
C c2 = new C(5);
c2.display(c2); //output 5
c2.display(c1); //output 3
}
}
```
Notice that class C takes in a `private` integer x, and there are two instances of class C, c1 and c2. In C#, you are able to call a method on c2, but pass in c1 as a parameter; thus returning the `private` x value of c1. In C#, the boundary of `private` pertains to the class, since instance of a class are able to access other `private` variables in other instances of the same class. C# is `private` to the class, and not to the specific object.
If you were to attempt something similar in Ruby, you would not be able to. Ruby is `private` to objects, so being in the same class does not mean instances can access other instances `private` variables.
Below is an example of using `private` in Ruby:
``` Ruby
class C
def initialize(x)
@x = x
end
def function
puts "the value of x is #{@x} "
end
end
c1 = C.new('3')
c1.function # output 3
c2 = C.new('5')
c2.function # output 5
```
Ruby has what is known as recievers, or the object on which the method is called. Since functions in Ruby do not take in parameters, the program can only call a function on the object, and cannot mimic behavior in C#, where another instance of a class can call a method and pass in a different instance of a class.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.