language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 862
| 3.734375
| 4
|
[] |
no_license
|
using System;
namespace ejercicio_11
{
class Program
{
static void Main(string[] args)
{
// 13. Leer dos fechas en formato DDMMAAAA. Informar cuál de ellas es la menor o si son iguales.
int num = 0;
int acum = 0;
Console.WriteLine("ingrese un numero");
num = int.Parse(Console.ReadLine());
acum = num;
for (int i = 0; i < 500; i++)
{
Console.WriteLine("ingrese un numero");
num = int.Parse(Console.ReadLine());
if (num>acum)
{
acum = num;
}
if (num == 0)
{
i = 499;
}
}
Console.WriteLine($"el numero mas grande es : {acum}");
}
}
}
|
Python
|
UTF-8
| 9,799
| 2.921875
| 3
|
[] |
no_license
|
# coding=UTF-8
'''
@author Gray
'''
import numpy as np
from sklearn.metrics import mean_squared_error, roc_curve, auc
from util.util import logLoss
from collections import defaultdict
class FM(object):
'''
implement a simple two-way interaction
'''
def __init__(self, num_factors, task, l2_reg_b=0.01, l2_reg_w=0.01, l2_reg_v=0.01, init_lr=0.001,
stdev=0.1):
self.num_factors = num_factors
self.task = task
self.init_lr = init_lr
self.stdev = stdev
self.reg_b = l2_reg_b
self.reg_w = l2_reg_w
self.reg_v = l2_reg_v
def _init_model(self):
self.b = 0.
self.w = np.zeros(self.num_attributes)
self.v = np.random.normal(scale=self.stdev, size=(self.num_attributes, self.num_factors))
def predict(self, x):
interaction = float(np.sum(x.dot(self.v).power(2) - x.power(2).dot(self.v ** 2)) / 2)
return self.b + x.dot(self.w) + interaction
def predict_batch(self, X):
linear = self.X_test.dot(self.w)
interaction = np.sum(self.X_test.dot(self.v).power(2) - self.X_test.power(2).dot(self.v ** 2), axis=1) / 2.
return self.b + linear + interaction
def fit(self, X_train, y_train, X_test, y_test):
'''
:param X_train: is a csr matrix
:param y_train: is a 1d numpy array
:return:
'''
self.num_attributes = X_train.shape[1]
self.X_test, self.y_test = X_test, y_test
self.X_train, self.y_train = X_train, y_train
self._init_model()
prev = float('inf')
current = 0
eps = 1e-3
while abs(prev - current) > eps:
prev = current
for x, y in zip(X_train, y_train):
current = self.update(x, y)
def update(self, x, y):
grad_base = self._loss_derivative(x, y)
self.b = self.b - self.init_lr * (grad_base + self.reg_b * self.b)
for attr in xrange(self.num_attributes):
if not x.getcol(attr).data:
xi = x.getcol(attr).data[0]
grad_w = grad_base * xi
self.w[attr] -= self.init_lr * (grad_w + self.reg_w * self.w[attr])
grad_v = grad_base * (x.dot(self.v).dot(xi)[0] - self.v[attr] * xi ** 2)
self.v[attr] -= self.init_lr * (grad_v + self.reg_v * self.v[attr])
return self._evaluate()
def _loss_derivative(self, x, y):
if self.task == 'regression': # rmse
return self.predict(x) - y
elif self.task == 'classification': # cross entropy
return 1. / (1 + np.exp(-self.predict(x))) - y
def _evaluate(self):
if self.task == 'regression':
y_pred = self.predict_batch(self.X_test)
return mean_squared_error(self.y_test, y_pred) ** 0.5
elif self.task == 'classification':
y_pred = self.predict_batch(self.X_test)
fpr, tpr, _ = roc_curve(self.y_test, y_pred, pos_label=1)
return auc(fpr, tpr)
class HFM_FTRL(object):
'''
hashed factorization machine with the follow the regularized leader online learning
'''
def __init__(self, num_factors, L1, L2, L1_fm, L2_fm, D, task, alpha, beta, alpha_fm=.1, beta_fm=1., init_lr=0.001,
stdev=0.1, dropout_rate=1.):
self.alpha = alpha
self.alpha_fm = alpha_fm
self.num_factors = num_factors
self.D = D
self.L1 = L1
self.L2 = L2
self.L1_fm = L1_fm
self.L2_fm = L2_fm
self.task = task
self.beta = beta
self.beta_fm = beta_fm
self.init_lr = init_lr
self.stdev = stdev
self.dropout_rate = dropout_rate
self.n = np.zeros(D + 1)
self.z = np.zeros(D + 1)
self.w = np.zeros(D + 1)
self.n_fm = {}
self.z_fm = {}
self.w_fm = {}
def init_fm(self, i):
if i not in self.n_fm:
self.n_fm[i] = np.zeros(self.num_factors)
self.z_fm[i] - np.zeros(self.num_factors)
self.w_fm[i] = np.random.normal(scale=self.stdev, size=self.num_factors)
def predict_raw(self, x):
'''
predict the raw score prior to logit transformation.
'''
raw_y = 0
# w[0]的取值有点迷糊,别的地方配合FTRL的定义都梳理清楚了
self.w[0] = (-self.z[0]) / ((self.beta + np.sqrt(self.n[0])) / self.alpha)
raw_y += self.w[0]
for i in x:
if np.abs(self.z[i]) <= self.L1:
self.w[i] = 0
else:
self.w[i] = (np.sign(self.z[i]) * self.L1 - self.z[i]) / (
(self.beta + np.sqrt(self.n[i])) / self.alpha + self.L2)
raw_y += self.w[i]
for i in x:
self.init_fm(i)
for k in xrange(self.num_factors):
sign = np.sign(self.z_fm[i][k])
if sign * self.z_fm[i][k] <= self.L1_fm:
self.w_fm[i][k] = 0
else:
self.w_fm[i][k] = (sign * self.L1_fm - self.z_fm[i][k]) / (
(self.beta_fm + np.sqrt(self.n_fm[i][k])) / self.alpha_fm + self.L2_fm)
len_x = len(x)
for i in xrange(len_x - 1):
for j in xrange(i + 1, len_x):
raw_y += np.dot(self.w_fm[x[i]], self.w_fm[x[j]])
return raw_y
def predict(self, x):
return 1. / (1 + np.exp(self.predict_raw(x)))
def _dropout(self, x):
for i, _ in enumerate(x):
if np.random.random() > self.dropout_rate:
del x[i]
def dropoutThenPredict(self, x):
self._dropout(x)
return self.predict(x)
def fit(self, X_train, X_test, y_train, y_test):
self.X_test, self.y_test = X_test, y_test
prev = float('inf')
current = 0
eps = 1e-3
while abs(prev - current) > eps:
prev = current
for x, y in zip(X_train, y_train):
current = self.update(x, y)
def update(self, x, y):
y_pred = self.predict(x)
g = y_pred - y
loss = logLoss(y_pred, y)
fm_sum = {}
for i in x + [0]:
sigma = (np.sqrt(self.n[i] + g ** 2) - np.sqrt(self.n[i])) / self.alpha
self.z[i] += g - sigma * self.w[i]
self.n[i] += g ** 2
fm_sum[i] = np.zeros(self.num_factors)
len_x = len(x)
for i in xrange(len_x):
for j in xrange(len_x):
if i != j:
fm_sum[x[i]] += self.w_fm[x[j]]
for i in x:
g_fm = g * fm_sum[i]
sigma = (np.sqrt(self.n_fm[i] + g_fm ** 2) - np.sqrt(self.n_fm[i])) / self.alpha_fm
self.z_fm[i] += g_fm - sigma * self.w_fm[i]
self.n_fm[i] += g_fm ** 2
return loss
# hash trick
# abs(hash(hash_salt+key+'_'+value))%hash_size+1
class FFM(FM):
'''
Field-aware Factorization Machines
'''
def __init__(self, num_fields, num_features, num_factors, numerical_features, task, l2_reg_b=0.01, l2_reg_w=0.01,
l2_reg_v=0.01,
init_lr=0.001, stdev=0.1, normalize=True):
super(FFM, self).__init__(num_factors, task, l2_reg_b, l2_reg_w, l2_reg_v, init_lr, stdev)
self.num_fields = num_fields
self.num_features = num_features
self.numerical_features = numerical_features
self.normalize = normalize
def _init_model(self):
self.b = 0.
self.w = np.zeros(self.num_features)
self.v = np.random.normal(scale=0.1, size=(self.num_features, self.num_fields, self.num_factors))
if self.normalize:
self._normalize(self.X_train, self._get_min_max(self.X_train))
self._normalize(self.X_test, self._get_min_max(self.X_test))
def _get_min_max(self, X):
nf_values = defaultdict(list)
for x in X:
for f in x:
if f[0] in self.numerical_features:
nf_values[f[0]].append(f[2])
for k, v in nf_values.iteritems():
nf_values[k] = (np.min(v), np.max(v))
return nf_values
def _normalize(self, X, nf_min_max):
for x in X:
for f in x:
if f[0] in nf_min_max:
f[2] = (f[2] - nf_min_max[f[0]][0]) / (nf_min_max[f[0]][1] - nf_min_max[f[0]][0])
def predict(self, x):
pred = self.b
len_x = len(x)
for i in xrange(len_x):
feature_i, field_i, value_i = x[i]
pred += self.w[feature_i] * value_i
for j in xrange(i + 1, len_x):
feature_j, field_j, value_j = x[j]
pred += np.dot(self.v[feature_i][field_j], self.v[feature_j][field_i]) * value_i * value_j
return pred
def predict_batch(self, X):
return np.array([self.predict(x) for x in X])
def update(self, x, y):
grad_base = self._loss_derivative(x, y)
self.b = self.b - self.init_lr * (grad_base + self.reg_b * self.b)
len_x = len(x)
for i in xrange(len_x):
feature_i, field_i, value_i = x[i]
grad_w = grad_base * value_i
self.w[feature_i] -= self.init_lr * (grad_w + self.reg_w * self.w[feature_i])
for j in xrange(i + 1, len_x):
feature_j, field_j, value_j = x[j]
tempij, tempji = self.v[feature_j][field_i], self.v[feature_j][field_i]
self.v[feature_i][field_j] -= self.init_lr * (
grad_base * tempji * value_i * value_j + self.reg_v * tempij)
self.v[feature_j][field_i] -= self.init_lr * (
grad_base * tempij * value_i * value_j + self.reg_v * tempji)
return self._evaluate()
|
Java
|
UTF-8
| 1,765
| 3.46875
| 3
|
[] |
no_license
|
package Task_2;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class MyMapTest {
MyMap<Integer, Character> myMap;
@Before
public void setUp() throws Exception {
myMap = new MyMap<>(1000);
myMap.put(0, 'a');
myMap.put(10, 'b');
myMap.put(20, 'c');
myMap.put(30, 'd');
myMap.put(40, 'e');
}
@After
public void tearDown() throws Exception {
myMap.clear();
myMap = null;
}
@Test
public void testClear() {
myMap.clear();
assertTrue(myMap.size() == 0);
}
@Test
public void testContainsKey() {
for (int i = 0; i < 5; i++) {
assertTrue(myMap.containsKey(i * 10));
assertFalse(myMap.containsKey(i + 1));
}
}
@Test
public void testContainsValue() {
for (char i = 'a'; i < 'f'; i++) {
assertTrue(myMap.containsValue(i));
assertFalse(myMap.containsValue(i + 5));
}
}
@Test
public void testGet() {
assertEquals('d', myMap.get(30).charValue());
}
@Test
public void testSize() {
assertEquals(5, myMap.size());
}
@Test
public void testIsEmpty() {
assertFalse(myMap.isEmpty());
myMap.clear();
assertTrue(myMap.isEmpty());
}
@Test
public void testPut() {
myMap.put(50, 'f');
assertTrue(myMap.size() == 6);
assertTrue(myMap.get(50) == 'f');
}
@Test
public void testRemove() {
myMap.remove(10);
assertTrue(myMap.size() == 4);
assertTrue(myMap.get(10) == null);
}
@Test
public void testTime() throws InterruptedException {
Thread.sleep(2000);
assertTrue(myMap.size() == 0);
myMap.put(10, 'b');
Thread.sleep(400);
assertTrue(myMap.size() == 1);
myMap.put(20, 'c');
Thread.sleep(400);
assertTrue(myMap.size() == 2);
myMap.put(30, 'd');
Thread.sleep(400);
assertTrue(myMap.size() == 2);
}
}
|
Java
|
GB18030
| 518
| 3.453125
| 3
|
[] |
no_license
|
import java.util.Scanner;
/**
* ͣ
* : 1 2
* : a+b is 3
* @author zq
*
*/
public class ABAdd {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 0;
int b = 0;
System.out.println("a b");
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
if(sc.hasNext())
b = sc.nextInt();
System.out.println("a+b is :"+(a+b));
}
}
|
C++
|
UTF-8
| 4,483
| 2.8125
| 3
|
[] |
no_license
|
#include "stdafx.h"
namespace {
class slow_perm2sched_context
{
public:
slow_perm2sched_context(const task_t &task, const perm_t &perm);
const sched_t &calculate_sched ();
const sched_t &get_sched() const {return sched;}
private:
void move_jobs_list(moment_t offset);
void add_last_job();
void add_free_hanging_job(const size_t pos);
void add_early_job(const size_t pos);
void add_job(const size_t pos);
private:
typedef multimap<moment_t, cost_t> jobs_list_t;
const task_t &task;
const perm_t &perm;
sched_t sched;
jobs_list_t jobs_list;
moment_t max_push;
private:
slow_perm2sched_context &operator=(const slow_perm2sched_context &);
};
slow_perm2sched_context::slow_perm2sched_context(const task_t &task, const perm_t &perm)
: task(task)
, perm(perm)
, sched(task.size())
{
assert (!task.empty());
assert (task.size() == perm.size());
}
const sched_t &slow_perm2sched_context::calculate_sched()
{
const size_t n = task.size();
sched.resize(n, 0);
jobs_list.clear();
add_last_job();
for (int pos = n - 2; pos >= 0; --pos)
add_job(pos);
for (size_t pos = 1; pos < n; ++pos)
{
const size_t job = perm[pos];
const size_t prev_job = perm[pos - 1];
sched[job] = std::max<moment_t>(sched[prev_job] + get_processing_time(task, perm, pos - 1), sched[job]);
}
return sched;
}
void slow_perm2sched_context::move_jobs_list(const moment_t offset)
{
jobs_list_t temp;
for (jobs_list_t::const_iterator it = jobs_list.begin(); it != jobs_list.end(); ++it)
temp.insert(jobs_list_t::value_type(it->first + offset, it->second));
std::swap(jobs_list, temp);
max_push += offset;
}
void slow_perm2sched_context::add_last_job()
{
const size_t job = perm.back();
jobs_list.insert(jobs_list_t::value_type(moment_t(0), task[job].tweight()));
sched[job] = task[job].due;
max_push = task[job].max_bound - sched[job];
}
void slow_perm2sched_context::add_job(const size_t pos)
{
const size_t job = perm[pos];
const size_t next_job = perm[pos + 1];
sched[job] = sched[next_job] - get_processing_time(task, perm, pos);
max_push = std::min(max_push, task[job].max_bound - sched[job]);
if (sched[job] > task[job].due)
add_free_hanging_job(pos);
else
add_early_job(pos);
}
void slow_perm2sched_context::add_free_hanging_job(const size_t pos)
{
const size_t job = perm[pos];
move_jobs_list(sched[job] - task[job].due);
jobs_list.insert(jobs_list_t::value_type(moment_t(0), task[job].tweight()));
sched[job] = task[job].due;
}
void slow_perm2sched_context::add_early_job(const size_t pos)
{
const size_t job = perm[pos];
const moment_t original_time = sched[job];
moment_t final_time = original_time;
jobs_list.insert(jobs_list_t::value_type(task[job].due - original_time, task[job].eweight() + task[job].tweight()));
cost_t gathered_penalty = -task[job].eweight();
jobs_list_t::iterator it;
for (it = jobs_list.begin(); it != jobs_list.end(); ++it)
{
const moment_t push = it->first;
if (gathered_penalty > 0 && push > task[job].min_bound - original_time)
break;
gathered_penalty += it->second;
if (gathered_penalty > 0)
final_time = original_time + push;
}
assert(gathered_penalty > 0);
final_time = std::max(final_time, task[job].min_bound);
final_time = std::min(final_time, original_time + max_push);
sched[job] = final_time;
jobs_list.erase(jobs_list.begin(), it);
move_jobs_list(-final_time + original_time);
jobs_list.insert(jobs_list_t::value_type(moment_t(0), gathered_penalty));
}
}
sched_t slow_perm2sched(const task_t &task, const perm_t &perm)
{
slow_perm2sched_context context(task, perm);
return context.calculate_sched();
}
|
Markdown
|
UTF-8
| 6,061
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: 三十二 手机风波
tag: novel1
---
卢静大吃一惊,也去看了周峰一眼,说:“你有男朋友,谁啊?怎么没听你说起过?”<br />
我心里想,我曾经想说来着,可是你没兴趣听啊。但还是回答说:“大学的同学,现在还在读书呢。”<br />
卢静马上问到:“你怎么会收到手机的?啊,你曾说过五一不回家过节的,莫不是因为他来深圳了?”<br />
我不得不佩服她够聪明,说:“是啊。”<br />
卢静还要问下去:“那他住……”<br />
这时周峰突然站了起来,拿过去手机看了一下,笑着对卢静说:“看看,人家用的多漂亮啊,你赶紧换一个吧,不然就土掉渣了。”<br />
卢静当然受不了这种挖苦,马上奚落周峰说:“我想换啊,可就怕王总不批啊。你那个不也用了好几年了吗?再不换,都成老大爷了。”<br />
我知道他们的手机都是公司给配置的,月费也可以全部报销,就说:“我羡慕你们还来不及呢。要是公司给我买,再难看的我也要。”
卢静眼睛一转,说:“咦,你不知道公司的规定吗?经理级以上的都可以由公司配备手机,报销月费的?就算你自己买的手机,只要愿意把号码报给公司,并用于办公联系的话,至少可以报销部分月费。市场部的员工当然会全报,别的部门是每月五十元吧。”<br />
我还真的不知道这一规定,后悔这段时间想放松一下,还没有去整理这部分制度档案,现在这已经是我的份内之事了。<br />
正想回话,周峰对着我说:“要是我,每月只报销五十元,就不上报公司。不然公司随时有权去查你的电话清单,多烦啊。”<br />
卢静一听,马上说:“周峰,你的手机,天知道你都用来联系谁呢?菁菁一定没什么不可告人的秘密,就是给男友打打电话,王总也不会介意,何况又不是全部报销。”<br />
我笑了,没有说话,心里还真就要好好想想是不是上报公司手机号码,每月可以省些钱出来。
这次谈话我没觉得有什么不好,而且终于让卢静也羡慕了一回,还很高兴。只是记着卢静说的申报手机号码一事,回去查了公司相关规定,发现确实如她所说,就报给了财务部,齐姐登记后说以后每月填报销单就可以了。
隔了两天,我下班时因为没处理完手头的工作,晚走了点,出去后锁自己的办公室房门时,看到周峰还坐在他的工作台前忙着,就和他打招呼:“周峰,你怎么还没走啊,要加班吗?”<br />
周峰站起来收拾台上的东西,说:“不用,我们一起走吧。”<br />
我觉得很诧异,我搬家之后,周峰再也没等过我一起下班。但因为以前一起走习惯了,也觉得正常。
一开始他只是问我,现在住的地方觉得安全不安全,周围环境有什么不好的,等等。我也就泛泛地回答。出了公司后,到了公共汽车站。我们虽然都在这里等车,但要坐的车次却是不同的。<br />
等着公共汽车,我也不知该和周峰说什么,想着我要等的车到了,就和他告别吧。突然,他对我说话了,我想他可能已经想了一会了:“你这次搬家,是因为你男友要来吗?”<br />
我料到他会有事问我,但没想到是这么个问题,就老实地回答:“是啊,有这个原因,当然也不全是。”<br />
周峰的脸色不是很好,又问:“那他来了,就住在你新租的房子吗?”<br />
我没觉得有什么不对的,就不解地说:“是啊。”
周峰的面色越发难看,说:“我真是笨啊,还辛辛苦苦地帮你去搬家呢,全不知道你是为了和男朋友同住。为什么不先说呢?我至少可以帮你找一间大点的房子。”<br />
我一怔,登时明白了他的所指,脸马上就涨红了,大声地说:“你这是什么意思?”<br />
周围马上有两个人侧过身子来看发生了什么事。周峰一看我急了,就把我拉到一边,离开了人群。我甩开了他的手,一时怒火攻心:“你马上给我道歉,你怎么能这么说?”
“难到你们没住在一起吗?是我说错了?”周峰也不依不挠起来。<br />
“不错,他是住在我那里,但绝对不是你想的那个样子。你把我想成了什么人?”和周峰这么久的相处之下,我心里的委屈,自然不会在他面前隐瞒,眼泪就流了下来。
周峰见我哭了,心软了:“对不起,我也没说什么啊。你看你啊,别人不知道的还以为我欺负你了呢。”<br />
我看到那边等汽车的人果然有人探头探脑地往这边看,就迅速地擦干了眼泪,却没有去看周峰。周峰一时也没敢再说什么,我静了一会,想想自己刚才也真是有些奇怪,为什么会那么激动,如果是别的同事问的话,我可能会不屑地解释两句,也就过去了。因为在深圳,大家来自四面八方,根本就没有一个相对稳定的社区环境,使得人们还要注意自己平时的形象,不能被人说闲话。大家都是为了工作,赚钱才聚到一起的,如果与这些无关,有谁会真的关心别人的生活?但是从来深圳起,和周峰之间发生了这许多的事情,他在我心中的分量自然不同于其他人,至少我当他是可以坦诚相待的朋友,当然受不了他的误解。
我往宽里一想,心情就好过多了,但还是有些气不平地说:“其实我也没必要和你解释,这事本来与你无关。再说了,现在深圳未婚同居的人多了,也没什么不光彩的。大家都有自己的生活,只要没妨碍别人就好。不过,我就是受不了没事还被人诬蔑,这下你到是提醒我了,以后对别人说话自己要小心点,就怕别有用心的人会无事生非的,乱说话。”
|
C
|
UTF-8
| 1,172
| 3.359375
| 3
|
[] |
no_license
|
/*************************************************************************
> File Name: 5.18test.c
> Author:
> Mail:
> Created Time: Wed 19 Apr 2017 07:21:08 PM PDT
************************************************************************/
#include<stdio.h>
#include<stdio.h>
//升序数列升序合并
#define N 20
int main()
{
int arr1[5] = {1, 3, 5, 7, 9};
int arr2[6] = {2, 4, 6, 8, 10, 11};
int merge[N] = {0};
int count = 0;
int len1 = sizeof(arr1) / sizeof(int);
int len2 = sizeof(arr2) / sizeof(int);
int i = 0, j = 0;
while(i < len1 && j < len2)
{
if(arr1[i] < arr2[j])
{
merge[count++] = arr1[i];
i++;
}
else
{
merge[count++] = arr2[j];
j++;
}
}
if(i == len1)
{
while(j < len2)
{
merge[count++] = arr2[j];
j++;
}
}
if(j == len2)
{
while(i < len1)
{
merge[count++] = arr1[i];
i++;
}
}
for(int i = 0; i < (len1+len2); ++i)
{
printf("%d ", merge[i]);
}
return 0;
}
|
C#
|
UTF-8
| 4,587
| 2.53125
| 3
|
[] |
no_license
|
using System.Collections;
using Svelto.Tasks;
using UnityEngine;
namespace Svelto.ECS.Example.Survive.Enemies
{
public class EnemyAttackEngine : SingleEntityViewEngine<TargetEntityView>, IQueryingEntityViewEngine
{
public IEntityViewsDB entityViewsDB { set; private get; }
public void Ready()
{ }
public EnemyAttackEngine(ISequencer enemyDamageSequence, ITime time)
{
_targetDamageSequence = enemyDamageSequence;
_time = time;
_taskRoutine = TaskRunner.Instance.AllocateNewTaskRoutine().SetEnumerator(CheckIfHittingEnemyTarget()).SetScheduler(StandardSchedulers.physicScheduler);
}
protected override void Add(TargetEntityView entity)
{
_taskRoutine.Start();
}
protected override void Remove(TargetEntityView obj)
{
_taskRoutine.Stop();
}
IEnumerator CheckIfHittingEnemyTarget()
{
while (true)
{
///
/// Pay attention to this bit. The engine is querying a
/// EnemyTargetEntityView and not a PlayerEntityView.
/// this is more than a sophistication, it actually the implementation
/// of the rule that every engine must use its own set of
/// EntityViews to promote encapsulation and modularity
///
var targetEntitiesView = entityViewsDB.QueryEntityViews<TargetEntityView>();
//there is a sneaky bug that can be caused by this routine. It can be solved in several
//ways once it has been understood.
//the targetDamageSequence.Next can trigger a sequence that could lead to the immediate
//death of the player, this would mean that the inner loop should stop when the
//enemytarget (the player) dies. However this engine doens't know when the player dies
//We can solve this problem in several ways including
//- iterating over the enemy target, if the entity has been removed because dead, the for will be skipped
//(which is the solution I chose here)
//- removing the entity the frame after and not immediatly (a bit hacky)
//- add this engine in the sequencer to know when the player is death to stop
//this taskroutine
var enemiesAttackList = entityViewsDB.QueryEntityViews<EnemyEntityView>();
for (int enemyIndex = enemiesAttackList.Count - 1; enemyIndex >= 0; --enemyIndex)
{
var enemyAttackEntityView = enemiesAttackList[enemyIndex];
var enemyCollisionData = enemyAttackEntityView.targetTriggerComponent.entityInRange;
for (int enemyTargetIndex = 0; enemyTargetIndex < targetEntitiesView.Count; enemyTargetIndex++)
{
var targetEntityView = targetEntitiesView[enemyTargetIndex];
//the IEnemyTriggerComponent implementors sets a the collides boolean
//whenever anything enters in the trigger range, but there is not more logic
//we have to check here if the colliding entity is actually an EnemyTarget
if (enemyCollisionData.collides == true &&
enemyCollisionData.otherEntityID == targetEntityView.ID)
{
var attackDamageComponent = enemyAttackEntityView.attackDamageComponent;
attackDamageComponent.timer += _time.deltaTime;
if (attackDamageComponent.timer >= attackDamageComponent.attackInterval)
{
attackDamageComponent.timer = 0.0f;
var damageInfo = new DamageInfo(attackDamageComponent.damage, Vector3.zero,
targetEntityView.ID, EntityDamagedType.Player);
_targetDamageSequence.Next(this, ref damageInfo);
}
}
}
}
yield return null;
}
}
ISequencer _targetDamageSequence;
ITime _time;
ITaskRoutine _taskRoutine;
}
}
|
Java
|
UTF-8
| 1,001
| 2.75
| 3
|
[] |
no_license
|
package task_3;
import task_3.essence.*;
import java.util.LinkedList;
public interface DAO {
/**
* @return list of all employees
*/
public LinkedList<Employee> getEmployees();
/**
* @param empId specific id of employee
*
* @return projects for specified employee
*/
public LinkedList<Project> getProjectsByEmployee(int empId);
/**
*
* @param name specific name of employee
*
* @return company for specified project
*/
public Company getCompanyByProjectName(String name);
/**
* creates new employee at DB
*
* @param empId specific id of employee
* @param name specific name of employee
* @param department name of department
*/
public boolean createEmployee(int empId, String name, String department);
/**
* deletes specified employee from DB
*
* @param name
* @return
*/
public boolean deleteEmployeeByName(String name);
}
|
Markdown
|
UTF-8
| 5,917
| 3.03125
| 3
|
[
"CC-BY-4.0"
] |
permissive
|
## Web endpoint
Once an alias is [registered](Registration.md), it enables any web user to visit a web endpoint on the room server dedicated to that alias, for the purpose of telling the visitor what SSB ID does the alias resolve to, and with instructions on how to install an SSB app if the visitor doesn't have it yet.
The goal of this endpoint is to help any SSB user *locate and identify* the alias' owner by resolving the alias to: (1) the room's [multiserver address](https://github.com/ssb-js/multiserver), (2) the owner's SSB ID, and (3) a cryptographic signature that proves the owner associated themselves with that alias. This web endpoint is very valuable to onboard new SSB users being invited by an [internal user](../Stakeholders/Internal%20user.md).
**Prior art:** This endpoint should be in many ways similar to the [Telegram](https://telegram.org/) `https://t.me/example` service for the username `@example`, also capable of redirecting the web visitor to a scheme `tg` URI `tg://resolve?domain=example`, which Telegram apps know how to parse and open the target user's profile screen.
### Specification
This specification does not apply if the [privacy mode](../Setup/Privacy%20modes.md) is *Restricted*. This web endpoint is available only if the privacy mode is *Open* or *Community*.
If the alias `${alias}` is registered at the room `${roomHost}` for a certain `${userId}`, then the room's HTTP endpoint `https://${alias}.${roomHost}` SHOULD respond with HTML which:
- Informs users how to install an SSB app that can correctly consume room aliases
- Renders a "Connect with me" button linking to an SSB URI (see below)
- The page automatically redirects (when the browser supports it) to an SSB URI (see below)
- The alias SSB URI is `ssb:address/${roomMsAddr}?roomId=${roomId}&userId=${userId}&alias=${alias}&signature=${signature}`, in other words there are 2 components:
- `ssb:address/${roomMsAddr}`, comprising the **path component** of the URI, is the room's [multiserver address](https://github.com/ssb-js/multiserver)
- The **query component** of the URI with the following 4 parts:
- `roomId=${roomId}`, the room's SSB ID
- `userId=${userId}`, the SSB ID of the alias's owner
- `alias=${alias}`, the [alias string](Alias%20string.md)
- `signature=${signature}`, the alias's owner signature as described in the [alias database](Alias%20database.md)
As an additional endpoint for programmatic purposes, the HTTP endpoint `https://${alias}.${roomHost}/json` MUST respond with a JSON body with the following schema:
```json
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://github.com/ssb-ngi-pointer/rooms2",
"type": "object",
"properties": {
"address": {
"title": "Multiserver address",
"description": "Should conform to https://github.com/ssbc/multiserver-address",
"type": "string"
},
"roomId": {
"title": "Room ID",
"description": "SSB ID for the room server",
"type": "string"
},
"userId": {
"title": "User ID",
"description": "SSB ID for the user owning the alias",
"type": "string"
},
"alias": {
"title": "Alias",
"description": "A domain 'label' as defined in RFC 1035",
"type": "string"
},
"signature": {
"title": "Signature",
"description": "Cryptographic signature covering the roomId, the userId, and the alias",
"type": "string"
}
},
"required": [
"address",
"roomId",
"userId",
"alias",
"signature"
]
}
```
### Example
Suppose the alias is `alice`, registered for the user ID `@FlieaFef19uJ6jhHwv2CSkFrDLYKJd/SuIS71A5Y2as=.ed25519` at the room with host name `scuttlebutt.eu`. Then the alias endpoint `https://alice.scuttlebutt.eu` responds with the following SSB URI (without spaces nor newlines):
```
ssb:address/netshs/scuttlebutt.eu/8008/51w4nYL0k7mRzDG
w20KQqCjt35y8qLiBNtWk3MX7ppo%3D?roomId=ed25519%2F51w4nY
L0k7mRzDGw20KQqCjt35y8qLiBNtWk3MX7ppo%3D&userId=ed25519
%2FFlieaFef19uJ6jhHwv2CSkFrDLYKJd_SuIS71A5Y2as%3D&alias
=alice&signature=yNDgrVOLm6sMUHdvnbFUQYgLkCGiOKrpP9KiBv
lrzvmxTNt3d0MNTf%2BSLMIxgxf00S5fKAlG2%2FC5NTE0Zq1Mmg%3D
%3D
```
Note the multiserver address for the room is written in an SSB URI friendly format, `ssb:address/netshs/${host}/${port}/${pubkey}`, that can be converted to canonical multiserver format `net:${host}:${port}~shs:${pubkey}`.
The JSON endpoint `https://alice.scuttlebutt.eu/json` would respond with the following JSON:
```json
{
"address": "net:scuttlebutt.eu:8008~shs:51w4nYL0k7mRzDGw20KQqCjt35y8qLiBNtWk3MX7ppo=",
"roomId": "@51w4nYL0k7mRzDGw20KQqCjt35y8qLiBNtWk3MX7ppo=.ed25519",
"userId": "@FlieaFef19uJ6jhHwv2CSkFrDLYKJd/SuIS71A5Y2as=.ed25519",
"alias": "alice",
"signature": "yNDgrVOLm6sMUHdvnbFUQYgLkCGiOKrpP9KiBvlrzvmxTNt3d0MNTf+SLMIxgxf00S5fKAlG2/C5NTE0Zq1Mmg=="
}
```
### Security considerations
#### Malicious web visitor
A web visitor, either human or bot, could attempt brute force visiting all possible alias endpoints, in order to build a dataset of all SSB IDs and claimed aliases gathered at this room, potentially tracking profiles of these SSB IDs. Malicious web visitors can also attempt to connect with these target IDs as victims, and may use social engineering or impersonation tactics during [tunneled authentication](../Participation/Tunneled%20authentication.md).
#### Malicious [room admin](../Stakeholders/Room%20admin.md)
The room admin could tamper with the [alias database](Alias%20database.md) and provide fake information on this web endpoint, e.g. that a certain alias was claimed by a certain users. Although the [database signature](Alias%20database.md) exists to prevent this type of tampering, it is only verified when performing [alias consumption](Alias%20consumption.md). For web visitors who only want to know which SSB ID corresponds to an alias, and only that, these visitors must trust the room administrator, who could provide inauthentic information.
|
Markdown
|
UTF-8
| 7,641
| 2.734375
| 3
|
[] |
no_license
|
# Hardware
## SUMMARY
The cluster has 13 compute nodes including 2 GPU nodes, a login node, a high-availability storage server connected to a 512TB disk array and a fast scratch server with 40TB of storage. It's accessible to the CofC campus via a 10Gbps ethernet link. The specs are summarized below.
* [**Compute nodes**](hardware.md)
* 10 standard compute nodes:
* Dell PowerEdge servers
* 2x 20-core 2.4GHz Intel Xeon Gold 6148 CPUs w/ 27MB L3 cache,
* 192GB of DDR4 2667MHz RAM,
* 480GB of local SSD storage,
* Double precision performance ~ 2.8 TFLOPs/node
* 1 large memory node:
* Dell PowerEdge server
* 4x 20-core 2.4GHz Intel Xeon Gold 6148 CPUs w/ 27MB L3 cache,
* 1536GB of DDR4 2667MHz RAM,
* 960GB of local SSD storage,
* Double precision performance ~ 5.6 TFLOPs/node
* 3 GPU-containing nodes:
* Dell PowerEdge server
* 2x 12-core 2.6GHz Intel Xeon Gold 6126 CPUs w/ 19MB L3 cache,
* 192GB of DDR4 2667MHz RAM,
* 480GB of local SSD storage,
* GPUs
* the first two have 1 NVIDIA Tesla V100 16GB GPU each
* the third has 1 NVIDIA Pascal Quadro P4000 8GB GPU
* Double precision performance
* those with 1 NVIDIA Tesla V100 16GB GPU ~ 1.8 + 7.0 = 8.8 TFLOPs/node
* those with 1 NVIDIA Pascal Quadro P4000 8GB GPU ~ 1.8 + 2.6 = 4.4 TFLOPs/node
* [**Login/visualization node**](hardware.md)
* 1 login and visualization node:
* Dell PowerEdge server
* 2x 12-core 2.6GHz Intel Xeon Gold 6126 CPUs w/ 27MB L3 cache,
* 192GB of DDR4 2667MHz RAM,
* 960GB of local SSD storage,
* 3TB RAID5 storage
* 1x NVIDIA Quadro P4000 8GB GPU
* [**Storage**](storage.md)
* 512TB NFS-shared, global, highly-available storage
* 38TB NFS-shared, global fast scratch storage
* [**Interconnect**](http://www.mellanox.com/page/products_dyn?product_family=192&mtag=sb7700_sb7790)
* Mellanox EDR Infiniband with 100Gb/s bandwidth
## Hardware Specs
The HPC cluster is a commodity Linux cluster containing many compute, storage and networking equipment all assembled into a standard rack. Please see the table below or the rack diagram further down for the layout.
| Component Specs | Component |
| :--- | :--- |
| 1 GbE 48-port Switch \(4x SPF+ 10GbE ports\) | **internal network** |
| 1 Mellanox 100Gbs 36-port EDR Infiniband Switch | **interconnect** |
| \#8 PowerEdge R740 2x 12-core Intel Xeon-G 6128 3.4GHz CPUs, 192GB RAM, 1x480GB SAS SSDs striped + 1 NVIDIA Quadro P4000 GPU | **1x p4000 gpu node** |
| \#7 PowerEdge R740 2x 12-core Intel Xeon-G 6128 3.4GHz CPUs, 192GB RAM, 1x480GB SAS SSDs striped + 1 NVIDIA Tesla V100 GPU | **1x v100 gpu node** |
| \#7 PowerEdge R740 2x 12-core Intel Xeon-G 6128 3.4GHz CPUs, 192GB RAM, 1x480GB SAS SSDs striped + 1 NVIDIA Tesla V100 GPU | **1x v100 gpu node** |
| \#6 PowerEdge R840 4x 20-core Intel Xeon-G 6148 2.4GHz, 1.5TB RAM, 2x480GB SATA SSD | **1x large memory node** |
| \#5 2U PowerEdge R740 2x 20-core Intel Xeon-G 6148 2.4GHz, 192TB RAM, 1x480GB SATA SSD | **1x gpu-capable node** |
| \#5 2U PowerEdge R740 2x 20-core Intel Xeon-G 6148 2.4GHz, 192GB RAM, 1x480GB SATA SSD | **1x gpu-capable node** |
| \#4 4x PowerEdge C6420 in a 2U chassis 2x 20-core Intel Xeon-G 6148 2.4GHz, 192GB RAM, 1x480GB SSD | **4x stdmem nodes** |
| \#4 4x PowerEdge C6420 in a 2U chassis 2x 20-core Intel Xeon-G 6148 2.4GHz, 192GB RAM, 1x480GB SSD | **4x stdmem nodes** |
| \#3 2U NFS server with NVMe SSDs PowerEdge R740XD 2x Intel Xeon-G 6126 2.6GHz CPU, 192GB RAM, 24x 1.6TB NVMe SSDs | **fast scratch storage server** |
| \#2 2U PowerEdge R740 NFS servers w/ 2x 12-core Intel Xeon Gold 6136 3.0GHz CPUs, 192GB RAM, 5x300TB 15k SAS HDDs, | **NFS servers for long-term storage array** |
| \#2 2U PowerEdge R740 NFS servers w/ 2x 12-core Intel Xeon Gold 6136 CPUs, 192GB RAM, 5x300TB 15k SAS HDDs, | **NFS servers for long-term storage array** |
| \#2 NSS-HA7 \(Dual NFS server\) 1x 5U Dell EMC PowerVault ME4084 - RBOD w/ 84x 8TB HDDs | **NSS-HA7 long-term storage array** |
| \#1 PowerEdge R740 2x 12-core Intel Xeon-G 6126 2.6GHz CPU, 192GB RAM, 2x480GB SSDs mirrored, 1 NVIDIA Quadro P1000 GPU | **login/viz node** |
## Layout

## Components
### CPU
| | Intel Xeon Gold Skylake 6148 |
| :--- | :--- |
| **Specs** | [Summary of specs](https://ark.intel.com/products/123690/Intel-Xeon-Gold-6148F-Processor-27-5M-Cache-2-40-GHz-) |
| **Technical Overview** | [Technical details at Intel including comparison with previous generations](https://software.intel.com/en-us/articles/intel-xeon-processor-scalable-family-technical-overview) |
| **Cores per socket**: | 20 |
| **Clock Speed** | 2.40 GHz base clock, 3.70 GHz Turbo Boost clock |
| **Clock Speed Range** | 2.20 GHz to 3.5GHz depending on instruction set and number of active cores |
| **Hyperthreading** | Possible |
| **Cache Hierarchy** | L1 = 32 KB per core L2= 1 MB per core L3 = 27.5 MB shared per CPU |
| **Configuration** | 2 CPUs per standard or GPU nodes, 4 CPUs per high memory node |
| **Estimated Performance** | 1.4 TeraFLOPS per CPU \(double precision\) |
| **References** | [1](https://ark.intel.com/products/123690/Intel-Xeon-Gold-6148F-Processor-27-5M-Cache-2-40-GHz-) , [2](https://software.intel.com/en-us/articles/intel-xeon-processor-scalable-family-technical-overview), [3](https://en.wikichip.org/wiki/intel/microarchitectures/skylake), [4](https://www.nas.nasa.gov/hecc/support/kb/skylake-processors_550.html) |
### GPU
| | **NVIDIA Tesla V100** |
| :--- | :--- |
| **Specs** | [Summary of Specs](https://www.nvidia.com/en-us/data-center/tesla-v100/) |
| **Technical Overview** | [Technical details at NVIDIA including comparison w/ previous generations](https://github.com/hpc-cofc/documentation/tree/b8d627c8e15312d4f9047674afd89fd5590c62cc/using-the-hpc/screenshots/volta-architecture-whitepaper.pdf) |
| **Architecture** | Volta |
| **GPU** | GV100 |
| **CUDA Cores** | 5120 |
| **Tensor Cores** | 640 |
| **Boost Clock** | 1370MHz |
| **Memory Clock** | 1.75Gbps HBM2 |
| **Memory Bus Width** | 4096-bit HBM2 |
| **Memory Bandwidth** | 900GB/sec |
| **Memory Size** | 16GB |
| **L2 Cache** | 6MB |
| **Half Precision** | 28 TFLOPS |
| **Single Precision** | 14 TFLOPS |
| **Double Precision** | 7 TFLOPS |
| **Tensor Performance** | 112 TFLOPS |
| **GPU** | GV100 |
| **Transistor Count** | 21B |
| **TDP** | 250W |
| **Form Factor** | PCIe |
| **Cooling** | Passive |
| **Manufacturing Process** | TSMC 12nm FFN |
| **Configuration** | 1 GPU per GPU node |
| **Estimated Performance** | 7 TeraFLOPS per GPU \(double precision\) |
| **References** | [5](https://www.anandtech.com/show/12576/nvidia-bumps-all-tesla-v100-models-to-32gb), [6](https://www.nvidia.com/en-us/data-center/tesla-v100/), [7](http://images.nvidia.com/content/volta-architecture/pdf/volta-architecture-whitepaper.pdf) |
### Interconnect
* Mellanox EDR \(100 Gbps\) InfiniBand interconnect
* 1:1 non-blocking
### Storage
* Long-term HDD-based NFS $HOME storage - highly redundant and resilient.
* 512 TB in total
* Will eventually be backed up weekly, but not yet
* Peak performance - 7 GBps / 6 GBps for sequential read/write
* Short-term NVMe SSD-based NFS $SCRATCH storage - fast storage for intermediate data during the course of a computation
* 38 TB in total
* Never backed up; purged weekly or as needed
* Theoretical peak performance ~ 28 GBps / 28 GBps for sequential read/write
* Expected peak performance ~ 12 GBps / 12 GBps for sequential read/write
* Actual peak performance - 8 GBps / 5 GBps for sequential read/write
|
Markdown
|
UTF-8
| 3,682
| 3.140625
| 3
|
[] |
no_license
|
## Activity File: Hashcat
You will continue your role as a security analyst working for the Hill Valley Police Department.
- You impressed Captain Strickland by logging into Detective Tannen's account. Unfortunately, the file you must access to prove Tannen is the Alphabet Bandit is encrypted on their computer.
- Fortunately, you found a hash on Detective Tannen's computer that will likely lead you to the password for opening the encrypted file: `f31663d6c912b0b1ced885a6c6bbab7c`.
- Your task is to use Hashcat to figure out the plaintext representation of the hash.
- Once you figure out the password, you will open the secret file and see if it contains the evidence needed to convict the Alphabet Bandit.
### Instructions
1. Use Hashcat to determine the plaintext value of the hash found on Detective Tannen's computer.
- The hash found on Detective Tannen's computer is `f31663d6c912b0b1ced885a6c6bbab7c`.
*Hint: The hashing algorithm was created in 1992 by Ronald Rivest.*
2. With the plaintext password, open the encrypted file with the command `unzip secret.zip` and confirm whether it contains the evidence needed to lock up the Alphabet Bandit.
## Solution File: Hashcat
The goal of this activity was to illustrate how Hashcat can be used to determine the plaintext value of a hash. You ran the Hashcat script to determine the password needed to open an encrypted file.
---
1. Use Hashcat to determine the plaintext value of the hash found on Detective Tannen's computer.
- The hash found on Detective Tannen's computer is `f31663d6c912b0b1ced885a6c6bbab7c`.
*Hint: The hashing algorithm was created in 1992 by Ronald Rivest.*
- First, we place the hash into a file.
- We will place it into a file called `hash.txt` by running the following:
- `echo f31663d6c912b0b1ced885a6c6bbab7c > hash.txt`
- Run the command and preview the file to confirm the hash has been placed inside:
- `more hash.txt`
- Next, write the Hashcat command:
- `hashcat -m 0 -a 0 -o solved.txt hash.txt /usr/share/wordlists/rockyou.txt --force`
- The syntax is:
- `hashcat`: The command to execute Hashcat.
- `-m 0`: Uses the MD5 hash (which was created by Ronald Rivest in 1992).
- `a 0`: Applies a dictionary attack.
- `-o solved.txt`: Creates an output file called `solved.txt`.
- `hash.txt`: The input file of the hash.
- `/usr/share/wordlists/rockyou.txt`: The location of the wordlist we will check against.
- `--force`: Overrides any small errors that may occur.
- Run the command. This will place the results in the file called `solved.txt`.
- Open the `solved.txt` file. It tells us that the hash represents the value `ilovelorraine`:
- `f31663d6c912b0b1ced885a6c6bbab7c:ilovelorraine`
2. With the plaintext password, open the encrypted file with the command `unzip secret.zip` and confirm whether it contains the evidence needed to lock up the Alphabet Bandit.
- Open the file `secret.zip` using the command `unzip secret.zip`.
- When it prompts for the password, enter `ilovelorraine`.
- This reveals the Alphabet Bandit's confession letter:
```
CONGRATULATIONS TO THE CYBER SLEUTH THAT FINDS THIS MESSAGE!!
My Confession
I, Detective Tannen, am confessing that I am the Alphabet Bandit!
I am the one solely responsible for all of the Hill Valley Break-ins.
Since I wasn't promoted to Captain, I have been determined to cause havoc to the Hill Valley community and tie up the Hill Valley Resources.
Unfortunately, since you have found this message, I will assume that I will be prosecuted and the break-ins will cease.
Sincerely,
Detective Tannen
```
---
© 2020 Trilogy Education Services, a 2U, Inc. brand. All Rights Reserved.
|
Python
|
UTF-8
| 9,620
| 2.828125
| 3
|
[] |
no_license
|
def ingestTemporalLine(filename):
# This function returns a cleaned up array from the FLIR temporal csv export
measurements = []
with open(filename) as file:
for index, line in enumerate(file):
# First we prepare the array of items
for index, line in enumerate(file):
if index == 0:
# We remove the header row
continue
# Split at comma
line = line.split(",")
# Transform temperature to float
line[2] = float(line[2])
line[3] = float(line[3])
measurements.append(line[2:4])
return measurements
def ingestGradLine(filename):
import numpy as np
# This function returns a cleaned up array from the FLIR profile csv export
measurements = []
with open(filename) as file:
for index, line in enumerate(file):
# First we prepare the array of items
for index, line in enumerate(file):
if index == 0:
# We remove the header row
continue
# Split at comma
line = line.split(",")
# Transform temperature to float
line[0] = float(line[0])
line[1] = float(line[1])
measurements.append(line[0:2])
# We must also remove any values that are lower than predecessors at the end, this is to remove the drop off on graphs
# maximum = np.argmax(measurements[round(len(measurements)*0.8) : len(measurements)])
# max(measurements[round(len(measurements)*0.8) : len(measurements)])
return measurements
def returnDiplRoot():
import sys
return sys.path[0]
def crawlFolders(root):
import os
flatFolderList = []
# get root subdirs
rootSubDirs = [f for f in os.scandir(root) if f.is_dir()]
# crawl all root subdirs
for dir in rootSubDirs:
flatFolderList += [f for f in os.scandir(dir) if f.is_dir()]
# return a flat list of all the directories
return flatFolderList
def is_integer(n):
# https://note.nkmk.me/en/python-check-int-float/
# This is for checking if string is an integer
try:
float(n)
except ValueError:
return False
else:
return float(n).is_integer()
def processmarkerfiles(filelist):
import os
dataset = []
for file in filelist:
# Check if the last symbol in file name is a number, this means, there is no seperate heating and cooling measurement, and we don't need to concat data
name = os.path.splitext(file)[0]
if is_integer(name[-1]):
dataset.append(ingestTemporalLine(file))
continue
# If there is a letter instead of a number, then there is two sets of data that need to be joined
# First, we make sure, there is no bad data. We only accept suffix u for up-heating and d for down-cooling
#if name[-1] != "u" or name[-1] != "d":
# continue
if name[-1] == "u":
#just add the up measurement for now
dataset.append(ingestTemporalLine(file))
continue
#raise NameError(f'Wrong marker suffix in directory on file {name}')
# If we are here, we have two csv files for each marker, we must join them
return dataset
def processheatingfiles(filelist):
import os
dataset = []
# Check if length of filelist is more than one
if len(filelist) == 1:
# there is just heating
dataset.append(ingestTemporalLine(filelist[0]))
return dataset
# If we are here, we need to concat the two files
# First we ingest each file
ogrevanjelist = ingestTemporalLine(filelist[1])
hlajenjelist = ingestTemporalLine(filelist[0])
# We must offset the second part by the first part amount
hlajenjelist = [[f[0]+ogrevanjelist[-1][0], f[1]] for f in hlajenjelist]
# We concat and append
dataset.append(ogrevanjelist+hlajenjelist)
return dataset
def processDir(dir, dataMap):
import os
csvFiles = []
# This function will scan the directory, and find all relevant csv files
# List all the CSV files to the csvFiles list
with os.scandir(dir) as currentDir:
for entry in currentDir:
ext = os.path.splitext(entry)[-1].lower()
if ext == ".csv":
csvFiles.append(entry)
# For each CSV file, determine the type, and add it to a list
markerlist = [f for f in csvFiles if f.name[0] == 'm']
profilelist = [f for f in csvFiles if f.name[0] == 'p']
ogrevanjelist = [f for f in csvFiles if f.name[0] == 'o' or f.name[0] == 'h']
# Create new output dir
pyroot = returnDiplRoot()
# Get the relative path, from meritve root to the current meritev dir
dirrelpath = os.path.relpath(dir, dataMap.dataMap['meritveRoot'])
# Prepare the output directory
outputpath = os.path.join(pyroot, 'output', dirrelpath)
os.makedirs(outputpath, exist_ok=True)
# Process the data from csv files
markerdataset = processmarkerfiles(markerlist)
heatingdataset = processheatingfiles(ogrevanjelist)
# Create the plots
makemarkerplot(markerdataset, outputpath)
makeGradTimePlot(profilelist, outputpath)
makeHeatingTimePlot(heatingdataset, outputpath)
def makemarkerplot(data, directory):
# This function will create a plot with stacked temporal lines
import matplotlib.pyplot as plt
import os
# If there is no data, stop the work
if len(data) == 0:
print('\033[93m No data for Marker plot in dir: \033[0m' + directory)
return
# Process the data via an ingestion function
print('Making Marker Plot in dir: ' + directory)
#processeddata = [ingestTemporalLine(f) for f in data]
# Create a plot
fig, ax = plt.subplots()
# Add each of the csv datasets to the plot
for index, dataset in enumerate(data):
x = list(map(lambda x: x[0], dataset))
y = list(map(lambda x: x[1], dataset))
ax.plot(x, y, label=f'Točka {index+1}')
# Add the labels
ax.set_ylabel('Temperatura [°C]')
ax.set_xlabel('Čas [s]')
# Draw the legend
ax.legend()
# Save the plot
currentfolder = os.path.basename(dir)
outputpath = os.path.join(directory, f'markerplot-{currentfolder}.png')
plt.savefig(outputpath)
plt.close(fig)
def makeGradTimePlot(data,dir):
import matplotlib.pyplot as plt
import os
# This function will create a plot with stacked profile lines
# Define if we are currently making a plot for S10 or S9 pipe
currentfolder = os.path.basename(dir)
currentpipe = currentfolder[0]
# If there is no data, stop the work
if len(data) == 0:
print('\033[93mNo data for Grad Time plot in dir: \033[0m' + dir)
return
# Process the data via an ingestion function
print('Making Grad Time Plot in dir: ' + dir)
processeddata = [ingestGradLine(f) for f in data]
# Create a plot
fig, ax = plt.subplots()
# Add each of the csv datasets to the plot
# If we have a currentpipe that we know, use a specific loop
if currentpipe == 'd':
for index, dataset in enumerate(processeddata):
x = [ 72.5/len(dataset)*i for i,x in enumerate(dataset)]
y = list(map(lambda x: x[1], dataset))
ax.plot(x, y, label=f'Čas {index * 60} s')
elif currentpipe == 't':
for index, dataset in enumerate(processeddata):
x = [ 80/len(dataset)*i for i,x in enumerate(dataset)]
y = list(map(lambda x: x[1], dataset))
ax.plot(x, y, label=f'Čas {index * 60} s')
else:
for index, dataset in enumerate(processeddata):
x = list(map(lambda x: x[0], dataset))
y = list(map(lambda x: x[1], dataset))
ax.plot(x, y, label=f'Čas {index * 60} s')
# Add the labels
ax.set_ylabel('Temperatura [°C]')
ax.set_xlabel('Razdalja [mm]')
# Draw the legend
ax.legend()
# Save the plot
outputpath = os.path.join(dir, f'gradplot-{currentfolder}.png')
plt.savefig(outputpath)
plt.close(fig)
def makeHeatingTimePlot(data,dir):
import matplotlib.pyplot as plt
import os
# This function will create a plot with stacked profile lines
# If there is no data, stop the work
if len(data) == 0:
print('\033[93mNo data for Heating Time plot in dir: \033[0m' + dir)
return
# Process the data via an ingestion function
print('Making Heating Time Plot in dir: ' + dir)
#processeddata = [ingestTemporalLine(f) for f in data]
# Create a plot
fig, ax = plt.subplots()
# Add each of the csv datasets to the plot
for index, dataset in enumerate(data):
x = list(map(lambda x: x[0], dataset))
y = list(map(lambda x: x[1], dataset))
ax.plot(x, y)
ax.plot(x, y, label=f'Povprečna temperatura')
# Draw horizontal line at maximum value
ax.axhline(y=max(y), linewidth=1, label=f'Maksimalna temperatura ({round(max(y),1)}°C)', linestyle='--')
# Add the labels
ax.set_ylabel('Temperatura [°C]')
ax.set_xlabel('Čas [s]')
# Draw the legend
ax.legend()
# Save the plot
currentfolder = os.path.basename(dir)
outputpath = os.path.join(dir, f'heatingplot-{currentfolder}.png')
plt.savefig(outputpath)
plt.close(fig)
if __name__ == '__main__':
import dataMap
for dir in crawlFolders(dataMap.dataMap['meritveRoot']):
processDir(dir, dataMap)
|
Markdown
|
UTF-8
| 1,121
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
# notificationBar
a simple js notificationBar for web and app , u can also filed it with ur own style
## how to use
### 1、u should download the cabar.js in lib and use it just like
```html
<script src="../lib/cabar.js"></script>
```
### 2、u can use in the way
```javascript
showBar('your words')
```
### or config it in ur way
```javascript
var option = {
'backgroundColor': '#66ffcc',
'height':120,
'lineHeight':120+'px',
'top':'-120px'
};
showBar('nobody loving me but u', 1000, 4, option);
```
```javascript
showBar('nobody loving me but u', 'success');
```
### 3、 parameters
#### showBar(word, type, holding, speed, option)
---
| field | type | description |
| ------------- |:-------------:| :-----|
|word|string|ur show words|
|type|string|bootstrap style [primary][success][info][warning][danger]|
|holding|integer|how long will ur words show in screen|
|speed|integer|speed!!!|
|option|object|u can config ur own style with javascript stlye attributes|
---
### 4、enjoy it
|
Java
|
UTF-8
| 5,306
| 2.109375
| 2
|
[] |
no_license
|
package aplikacija.apl.ofinger.navigationActivities;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import aplikacija.apl.ofinger.ApplicationClass;
import aplikacija.apl.ofinger.R;
import aplikacija.apl.ofinger.adapters.ClothAdapter;
import aplikacija.apl.ofinger.info.ClothInfo;
import aplikacija.apl.ofinger.models.Cloth;
public class WishListActivity extends AppCompatActivity implements ClothAdapter.ItemClicked {
RecyclerView wishList;
RecyclerView.Adapter wishAdapter;
RecyclerView.LayoutManager manager;
List<Cloth> wishCloths;
AdView mainAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wish_list);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Vasa korpa:");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
wishList = findViewById(R.id.wishList);
wishList.setHasFixedSize(true);
manager = new LinearLayoutManager(this);
wishList.setLayoutManager(manager);
wishCloths = new ArrayList<>();
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
mainAd = findViewById(R.id.mainAd);
AdRequest adRequest = new AdRequest.Builder().build();
mainAd.loadAd(adRequest);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Wishes").child(ApplicationClass.currentUser.getUid());
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
wishCloths.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String clothID = snapshot.getKey();
for(Cloth cloth : ApplicationClass.mainCloths){
if(cloth.getObjectId().equals(clothID)) {
wishCloths.add(cloth);
break;
}
}
}
ApplicationClass.wishCloths = wishCloths;
wishAdapter = new ClothAdapter(WishListActivity.this, wishCloths, true);
wishList.setAdapter(wishAdapter);
if(wishCloths.size() == 0) getSupportActionBar().setTitle("Vasa korpa je prazna!");
else getSupportActionBar().setTitle("Vasa korpa:");
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
Animatoo.animateSlideRight(this);
return super.onSupportNavigateUp();
}
private void checkTypingStatus (String typing){
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("typingTo", typing);
ApplicationClass.currentUserReference.updateChildren(hashMap);
}
private void status(String status){
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("status", status);
ApplicationClass.currentUserReference.updateChildren(hashMap);
}
@Override
protected void onPostResume() {
super.onPostResume();
status("online");
checkTypingStatus("noOne");
}
@Override
protected void onPause() {
super.onPause();
if(!ApplicationClass.currentUser.isAnonymous()) {
String timestamp = String.valueOf(System.currentTimeMillis());
status(timestamp);
checkTypingStatus("noOne");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if(!ApplicationClass.currentUser.isAnonymous()) {
String timestamp = String.valueOf(System.currentTimeMillis());
status(timestamp);
checkTypingStatus("noOne");
}
}
@Override
public void onItemClicked(int index) {
int i = 0;
for(Cloth cloth : ApplicationClass.mainCloths){
if(cloth.getObjectId().equals(ApplicationClass.wishCloths.get(index).getObjectId())) break;
i++;
}
Intent intent = new Intent(WishListActivity.this, ClothInfo.class);
intent.putExtra("index", i);
startActivity(intent);
}
}
|
Python
|
UTF-8
| 2,162
| 2.5625
| 3
|
[] |
no_license
|
from flask import Flask, render_template, request, redirect, url_for
import os
from flask_pymongo import PyMongo
from datetime import datetime
from bson.objectid import ObjectId
# from bson.objectid import ObjectId
app = Flask(__name__)
app.config["MONGO_DBNAME"] = os.environ.get('MONGO_DBNAME')
app.config["MONGO_URI"] = os.environ.get('MONGO_URI')
mongo = PyMongo(app)
# def get_category_names():
# categories = []
# for category in mongo.db.collection_names():
# if not category.startswith("system."):
# categories.append(category)
# return categories
@app.route("/")
def show_indexpage():
# categories = get_category_names()
return render_template("index.html")
@app.route("/search")
def show_search():
name = request.args.get('username')
# here search is only a string which can be changed
return redirect("/user/"+name)
@app.route("/user/<username1>", methods=["GET", "POST"])
def show_user(username1):
if request.method=="POST":
form_values = request.form.to_dict()
# line 37 is for putting values into dictionary
form_values["calorie"]=int(request.form["steps"])*0.04
form_values["date"] = datetime.today()
_id = mongo.db[username1].insert(form_values)
# line 39 is for inserting/updating the values into Mongo Database
return redirect(username1+"/calorie/"+str(_id))
walks = mongo.db[username1].find()
print(walks)
return render_template("userstepsandhistory.html", username1=username1, walks=walks)
@app.route("/<username1>/calorie/<calorie_id>")
def show_calorie(username1, calorie_id):
walk = mongo.db[username1].find_one({"_id": ObjectId(calorie_id)})
return render_template("calorie.html", walk=walk)
@app.route("/about")
def show_about():
return render_template("about.html")
@app.route("/likeus")
def show_likeus():
return render_template("likeus.html")
@app.route("/contact")
def show_contact():
return render_template("contact.html")
if __name__ == "__main__":
app.run(host=os.getenv('IP', '0.0.0.0'), port=int(os.getenv('PORT', 8080)), debug=True)
|
JavaScript
|
UTF-8
| 364
| 3.515625
| 4
|
[] |
no_license
|
var obj = {name: 'ISRO', age: 35, role: 'Scientist'};
function convertListToObject(obj) {
let keys=Object.keys(obj);
let ans=[];
for(let i in keys)
{
ans.push([keys[i],obj[keys[i]]]);
}
return ans;
}
let ans3=convertListToObject(obj);
console.log("PROBLEM 3.........................................");
console.log(ans3);
|
JavaScript
|
UTF-8
| 2,775
| 2.875
| 3
|
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
$(function () {
let aList = [];
let locations = [];
let dict = {'amenities': [], 'cities': [], 'states': []};
$('.amenities li input[type=checkbox]').change(function () {
let amen = $(this).attr('data-name');
let id = $(this).attr('data-id');
if (this.checked) {
aList.push(amen);
dict['amenities'].push(id);
} else {
aList.splice(aList.indexOf(amen), 1);
dict['amenities'].splice(dict['amenities'].indexOf(id, 1));
}
$('.amenities h4').html(aList.length > 0 ? aList.join(', ') : ' ');
});
$('.locations li input[type=checkbox]').change(function () {
let id = $(this).attr('data-id');
let location = $(this).attr('data-type');
if (this.checked) {
locations.push($(this).attr('data-name'));
if (location === 'state') {
dict['states'].push(id);
} else {
dict['cities'].push(id);
}
} else {
locations.pop($(this).attr('data-name'));
if (location === 'state') {
dict['states'].splice(dict['states'].indexOf(id), 1);
} else {
dict['cities'].splice(dict['cities'].indexOf(id), 1);
}
}
$('.locations h4').html(locations.length > 0 ? locations.join(', ') : ' ');
});
$.getJSON('http://0.0.0.0:5001/api/v1/status/')
.done(function (data) {
if (data.status === 'OK') {
$('#api_status').addClass('available');
} else {
$('#api_status').removeClass('available');
}
})
.fail(function (jqxhr, testStatus, error) {
let err = testStatus + ', ' + error;
console.log(err);
});
function searchPlaces (data) {
$.ajax({
type: 'POST',
url: 'http://0.0.0.0:5001/api/v1/places_search',
data: data,
contentType: 'application/json',
success: function (js) {
for (let place of js) {
$.getJSON('http://0.0.0.0:5001/api/v1/users/' + place.user_id, function (user) {
$('.places ').append('<article id="' + place.id + '"><h2>' + place.name + '</h2><div class="price_by_night"><p>$' + place.price_by_night + '</p></div><div class="information"><div class="max_guest"><div class="guest_image"></div><p>' + place.max_guest + '</p></div><div class="number_rooms"><div class="bed_image"></div><p>' + place.number_rooms + '</p></div><div class="number_bathrooms"><div class="bath_image"></div><p>' + place.number_bathrooms + '</p></div></div><div class="user"><p><b>Owner: </b>' + user.first_name + ' ' + user.last_name + '</p></div><div class="description"><p>' + place.description + '</p></div></article>');
});
}
}
});
}
searchPlaces('{}');
$('.filters button').click(function () {
$('.places article').remove();
searchPlaces(JSON.stringify(dict));
});
});
|
C++
|
UTF-8
| 339
| 3.34375
| 3
|
[] |
no_license
|
#include <iostream>
using namespace std;
int reverse(int x)
{
long res = 0;
while(x)
{
res = res*10 + x%10;
printf("%ld %d\n", res, x);
x /= 10;
}
return (res<INT_MIN || res>INT_MAX) ? 0 : res;
}
int main()
{
int a, b;
a = -12345;
b = reverse(a);
cout << b << endl;
cout << INT_MIN << endl;
}
|
Markdown
|
UTF-8
| 12,321
| 3.265625
| 3
|
[
"MIT"
] |
permissive
|
---
layout: pattern
title: Circuit Breaker
folder: circuit-breaker
permalink: /patterns/circuit-breaker/
categories: Behavioral
tags:
- Performance
- Decoupling
- Cloud distributed
---
## Intent
Handle costly remote service calls in such a way that the failure of a single service/component
cannot bring the whole application down, and we can reconnect to the service as soon as possible.
## Explanation
Real world example
> Imagine a web application that has both local files/images and remote services that are used for
> fetching data. These remote services may be either healthy and responsive at times, or may become
> slow and unresponsive at some point of time due to variety of reasons. So if one of the remote
> services is slow or not responding successfully, our application will try to fetch response from
> the remote service using multiple threads/processes, soon all of them will hang (also called
> [thread starvation](https://en.wikipedia.org/wiki/Starvation_(computer_science))) causing our entire web application to crash. We should be able to detect
> this situation and show the user an appropriate message so that he/she can explore other parts of
> the app unaffected by the remote service failure. Meanwhile, the other services that are working
> normally, should keep functioning unaffected by this failure.
In plain words
> Circuit Breaker allows graceful handling of failed remote services. It's especially useful when
> all parts of our application are highly decoupled from each other, and failure of one component
> doesn't mean the other parts will stop working.
Wikipedia says
> Circuit breaker is a design pattern used in modern software development. It is used to detect
> failures and encapsulates the logic of preventing a failure from constantly recurring, during
> maintenance, temporary external system failure or unexpected system difficulties.
## Programmatic Example
So, how does this all come together? With the above example in mind we will imitate the
functionality in a simple example. A monitoring service mimics the web app and makes both local and
remote calls.
The service architecture is as follows:

In terms of code, the end user application is:
```java
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
var serverStartTime = System.nanoTime();
var delayedService = new DelayedRemoteService(serverStartTime, 5);
var delayedServiceCircuitBreaker = new DefaultCircuitBreaker(delayedService, 3000, 2,
2000 * 1000 * 1000);
var quickService = new QuickRemoteService();
var quickServiceCircuitBreaker = new DefaultCircuitBreaker(quickService, 3000, 2,
2000 * 1000 * 1000);
//Create an object of monitoring service which makes both local and remote calls
var monitoringService = new MonitoringService(delayedServiceCircuitBreaker,
quickServiceCircuitBreaker);
//Fetch response from local resource
LOGGER.info(monitoringService.localResourceResponse());
//Fetch response from delayed service 2 times, to meet the failure threshold
LOGGER.info(monitoringService.delayedServiceResponse());
LOGGER.info(monitoringService.delayedServiceResponse());
//Fetch current state of delayed service circuit breaker after crossing failure threshold limit
//which is OPEN now
LOGGER.info(delayedServiceCircuitBreaker.getState());
//Meanwhile, the delayed service is down, fetch response from the healthy quick service
LOGGER.info(monitoringService.quickServiceResponse());
LOGGER.info(quickServiceCircuitBreaker.getState());
//Wait for the delayed service to become responsive
try {
LOGGER.info("Waiting for delayed service to become responsive");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Check the state of delayed circuit breaker, should be HALF_OPEN
LOGGER.info(delayedServiceCircuitBreaker.getState());
//Fetch response from delayed service, which should be healthy by now
LOGGER.info(monitoringService.delayedServiceResponse());
//As successful response is fetched, it should be CLOSED again.
LOGGER.info(delayedServiceCircuitBreaker.getState());
}
}
```
The monitoring service:
```java
public class MonitoringService {
private final CircuitBreaker delayedService;
private final CircuitBreaker quickService;
public MonitoringService(CircuitBreaker delayedService, CircuitBreaker quickService) {
this.delayedService = delayedService;
this.quickService = quickService;
}
//Assumption: Local service won't fail, no need to wrap it in a circuit breaker logic
public String localResourceResponse() {
return "Local Service is working";
}
/**
* Fetch response from the delayed service (with some simulated startup time).
*
* @return response string
*/
public String delayedServiceResponse() {
try {
return this.delayedService.attemptRequest();
} catch (RemoteServiceException e) {
return e.getMessage();
}
}
/**
* Fetches response from a healthy service without any failure.
*
* @return response string
*/
public String quickServiceResponse() {
try {
return this.quickService.attemptRequest();
} catch (RemoteServiceException e) {
return e.getMessage();
}
}
}
```
As it can be seen, it does the call to get local resources directly, but it wraps the call to
remote (costly) service in a circuit breaker object, which prevents faults as follows:
```java
public class DefaultCircuitBreaker implements CircuitBreaker {
private final long timeout;
private final long retryTimePeriod;
private final RemoteService service;
long lastFailureTime;
private String lastFailureResponse;
int failureCount;
private final int failureThreshold;
private State state;
private final long futureTime = 1000 * 1000 * 1000 * 1000;
/**
* Constructor to create an instance of Circuit Breaker.
*
* @param timeout Timeout for the API request. Not necessary for this simple example
* @param failureThreshold Number of failures we receive from the depended service before changing
* state to 'OPEN'
* @param retryTimePeriod Time period after which a new request is made to remote service for
* status check.
*/
DefaultCircuitBreaker(RemoteService serviceToCall, long timeout, int failureThreshold,
long retryTimePeriod) {
this.service = serviceToCall;
// We start in a closed state hoping that everything is fine
this.state = State.CLOSED;
this.failureThreshold = failureThreshold;
// Timeout for the API request.
// Used to break the calls made to remote resource if it exceeds the limit
this.timeout = timeout;
this.retryTimePeriod = retryTimePeriod;
//An absurd amount of time in future which basically indicates the last failure never happened
this.lastFailureTime = System.nanoTime() + futureTime;
this.failureCount = 0;
}
// Reset everything to defaults
@Override
public void recordSuccess() {
this.failureCount = 0;
this.lastFailureTime = System.nanoTime() + futureTime;
this.state = State.CLOSED;
}
@Override
public void recordFailure(String response) {
failureCount = failureCount + 1;
this.lastFailureTime = System.nanoTime();
// Cache the failure response for returning on open state
this.lastFailureResponse = response;
}
// Evaluate the current state based on failureThreshold, failureCount and lastFailureTime.
protected void evaluateState() {
if (failureCount >= failureThreshold) { //Then something is wrong with remote service
if ((System.nanoTime() - lastFailureTime) > retryTimePeriod) {
//We have waited long enough and should try checking if service is up
state = State.HALF_OPEN;
} else {
//Service would still probably be down
state = State.OPEN;
}
} else {
//Everything is working fine
state = State.CLOSED;
}
}
@Override
public String getState() {
evaluateState();
return state.name();
}
/**
* Break the circuit beforehand if it is known service is down Or connect the circuit manually if
* service comes online before expected.
*
* @param state State at which circuit is in
*/
@Override
public void setState(State state) {
this.state = state;
switch (state) {
case OPEN:
this.failureCount = failureThreshold;
this.lastFailureTime = System.nanoTime();
break;
case HALF_OPEN:
this.failureCount = failureThreshold;
this.lastFailureTime = System.nanoTime() - retryTimePeriod;
break;
default:
this.failureCount = 0;
}
}
/**
* Executes service call.
*
* @return Value from the remote resource, stale response or a custom exception
*/
@Override
public String attemptRequest() throws RemoteServiceException {
evaluateState();
if (state == State.OPEN) {
// return cached response if the circuit is in OPEN state
return this.lastFailureResponse;
} else {
// Make the API request if the circuit is not OPEN
try {
//In a real application, this would be run in a thread and the timeout
//parameter of the circuit breaker would be utilized to know if service
//is working. Here, we simulate that based on server response itself
var response = service.call();
// Yay!! the API responded fine. Let's reset everything.
recordSuccess();
return response;
} catch (RemoteServiceException ex) {
recordFailure(ex.getMessage());
throw ex;
}
}
}
}
```
How does the above pattern prevent failures? Let's understand via this finite state machine
implemented by it.

- We initialize the Circuit Breaker object with certain parameters: `timeout`, `failureThreshold` and `retryTimePeriod` which help determine how resilient the API is.
- Initially, we are in the `closed` state and nos remote calls to the API have occurred.
- Every time the call succeeds, we reset the state to as it was in the beginning.
- If the number of failures cross a certain threshold, we move to the `open` state, which acts just like an open circuit and prevents remote service calls from being made, thus saving resources. (Here, we return the response called ```stale response from API```)
- Once we exceed the retry timeout period, we move to the `half-open` state and make another call to the remote service again to check if the service is working so that we can serve fresh content. A failure sets it back to `open` state and another attempt is made after retry timeout period, while a success sets it to `closed` state so that everything starts working normally again.
## Class diagram

## Applicability
Use the Circuit Breaker pattern when
- Building a fault-tolerant application where failure of some services shouldn't bring the entire application down.
- Building a continuously running (always-on) application, so that its components can be upgraded without shutting it down entirely.
## Related Patterns
- [Retry Pattern](https://github.com/iluwatar/java-design-patterns/tree/master/retry)
## Real world examples
* [Spring Circuit Breaker module](https://spring.io/guides/gs/circuit-breaker)
* [Netflix Hystrix API](https://github.com/Netflix/Hystrix)
## Credits
* [Understanding Circuit Breaker Pattern](https://itnext.io/understand-circuitbreaker-design-pattern-with-simple-practical-example-92a752615b42)
* [Martin Fowler on Circuit Breaker](https://martinfowler.com/bliki/CircuitBreaker.html)
* [Fault tolerance in a high volume, distributed system](https://medium.com/netflix-techblog/fault-tolerance-in-a-high-volume-distributed-system-91ab4faae74a)
* [Circuit Breaker pattern](https://docs.microsoft.com/en-us/azure/architecture/patterns/circuit-breaker)
|
Markdown
|
UTF-8
| 2,659
| 3.015625
| 3
|
[] |
no_license
|
# Elm MediumEditor
This repository contains the source code for MediumEditor bindings in Elm.
## Installation
Ensure *all* your source files live inside `/src`. Next up, add a `/vendor` folder in the
root of your project.
cd vendor
git clone https://github.com/paramanders/elm-medium-editor.git
And add `vendor/elm-medium-editor` to your `source-directories` array in `elm-package.json`.
## MediumEditor files
Grab the MediumEditor files from:
* Their github: https://github.com/yabwe/medium-editor
* JsDelivr: http://www.jsdelivr.com/projects/medium-editor
You'll need the `medium-editor.js` file, `medium-editor.css` file and a theme `css` file to your liking. Add these to your HTML file. See `examples/index.html` for a test scenario.
## Ports
You'll need to setup two ports. One for initializing the editor, and one for updating the Elm state from Javascript. Again, see `examples/index.html` for a working example.
The first port is to initialize the editor:
var app = Elm.Main.fullscreen();
app.ports.initMediumEditor.subscribe(function(options) {
var node = document.getElementById(options.id);
var editor = new MediumEditor(node, options);
editor.setContent(options.initialContent);
});
Inside the first port, using the `editor` variable, setup the update port to send data back to Elm:
editor.subscribe('editableInput', function(event, editable) {
app.ports.updateMediumEditor.send(editor.serialize());
});
Add the `updateMediumEditor` port to your subscriptions in your `Html.App`:
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions =
\_ ->
Sub.batch [ MediumEditor.Ports.updateMediumEditor <| ChildEditorMsg << MediumEditor.UpdateContent << .value ]
}
This will keep the DOM state and the Elm state in sync.
## Usage
To use the editor, wire the module using Elm Architecture. The Editor has effects going, so make sure your app uses `Cmd`s.
Use the `init` function to pass an `id`, `class` and the `initialContent`. You will receive a tuple containing the editor, and the initialization effect:
let
(editor, effects) = MediumEditor.init "my-id" "my-class" "<p>Hello, world!</p>"
in
( {model | editor = editor}
, Cmd.map ChildEditorMsg effects
)
In order to use these effects, you'll have to wrap the `MediumEditor.Msg` type to your own app's `Msg` type:
type Msg
= NoOp
| ChildEditorMsg MediumEditor.Msg
See `exmaples/Main.elm` for a full tutorial.
|
Ruby
|
UTF-8
| 1,304
| 3.296875
| 3
|
[] |
no_license
|
class Board
attr_reader :grid
def initialize(size = 9, bombs = 1)
@grid = Array.new(size) { Array.new(size) }
populate_grid(bombs)
ready_tiles
end
def populate_grid(bombs)
safe_spaces = @grid.length ** 2 - bombs
bombs = Array.new(bombs) { Tile.new(true) }
empty_tiles = Array.new(safe_spaces) { Tile.new }
tiles = bombs.concat(empty_tiles).shuffle
@grid.length.times do |i|
@grid.length.times do |j|
@grid[i][j] = tiles.pop
@grid[i][j].pos = [i, j]
end
end
end
def display
disp = " " + (0...grid[0].length).to_a.join(" ") + "\n"
disp += @grid.map.with_index do |row, index|
"#{index.to_s} " + row.map do |tile|
if tile.flag
"f"
elsif tile.revealed
tile.symbol
else
"⬜"
end
end.join(" ")
end.join("\n")
puts disp
end
def [](pos)
row, col = pos
@grid[row][col]
end
def ready_tiles
@grid.each do |row|
row.each do |tile|
tile.find_neighbors(@grid)
end
end
@grid.each do |row|
row.each do |tile|
tile.assign_numbers
end
end
end
def reveal_bombs
grid.each do |row|
row.each do |tile|
tile.reveal if tile.bomb
end
end
end
end
|
Markdown
|
UTF-8
| 4,684
| 2.78125
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"WTFPL"
] |
permissive
|
---
layout: post
title: Notes about Migrating from Flex 3 to Flex 4 (4.1 or 4.5 SDK)
created: 1311017177
author: charlie
permalink: /js/notes-about-migrating-flex-3-flex-4-41-or-45-sdk
tags:
- JS
- RTL
- migration
- flex 4
---
<p>The main incentive for the migration was to support RTL languages namely Hebrew and Japanese. Fact is that Flex 3 does not handle RTL writing properly – try writing Hebrew and English together.</p>
<p> </p>
<p>After finalizing the long and fragmented process, I found that the migration had two main parts – handling the visual aspects (styling, skins etc) and handling the application logic (components and AS). I found a workaround that helped me to split the process into these two parts – i.e. set the styling to backward compatibility mode and handle the logic first. Then, once the application compiles and runs ‘properly’, disable the compatibility mode and go thru the styling issues.</p>
<p> </p>
<p>So, to set the backward compatibility with Halo you should do the following:</p>
<p> </p>
<ul>
<li>Go to the sdk 4.x directory -> frameworks -> flex-config.xml</li>
<li>Edit the file (as administrator) and add the following line in the <i><themes></i> section<br />
<i><filename>themes/Halo/halo.swc</filename><br />
</i></li>
<p>This will prevent all the errors related to style properties such as borederThikness, cornerRadius that are not supported in Flex 4.</p>
<p> </p>
</ul>
<p> </p>
<p><b><u>Main Issues Handled in the Logic Part</u></b></p>
<ol>
<li>RTL - To support native RTL writing, all text-based components were switched from MX to Spark – Label, TextInput, TextArea, and custom components based on them</li>
<li>DataGrid itemRenderers – most of my renderers were based on the mx:Label component. None of the renderers worked and I had to base all the renderers on the s:MXDataGridItemRenderer class and include in it a Lable component (<a href="http://help.adobe.com/en_US/flex/using/WS03d33b8076db57b9-1c32bcb9124deadc3e9-8000.html">read this</a>). The rest of the code was untouched.</li>
<li>Datagrid – I started the migration process with 4.5 SDK. This was premature because the s:DataGrid component was missing some critical properties which prevented the application to compile. Therefore, I switched to 4.1 SDK (not sure what is the status today as the migration was done less than a year ago)</li>
<li>RTL popups – this issue is not related to the migration specifically but since RTL mode has been QA-ed extensively, it worth mentioning. Alert and other views poped up using the PopupManager class were placed out of the main screen in RTL mode. Namely, their x and y properties sent the popup out of the screen. If you did not implement the ESC key to close the popup, the impression was like the application is stuck (glass pane) while the popup is there but you cannot see it.</li>
</ol>
<p> </p>
<p><b><u>Issues Handled in the Visual Part</u></b></p>
<p>First, remove the line <i><filename>themes/Halo/halo.swc</filename></i> from flex-config.xml.</p>
<p>Then, get handful of compilation errors related to usage of styles such as cornerRadius, borderThikness, borerColor inline within components. Another example is the icon property of Button class – not supported in 4.x SDK. If used in CSS file, these styles were ‘just’ ignored.</p>
<p>So, after removing these (inline) styles, the application compiled and the main effect is that the application looked completely different style-wise.</p>
<p> </p>
<p>This was a contribution of:</p>
<ol>
<li>Flex 4 components default styling is different from Flex 3</li>
<li>Usage more of CSS styling and less of skins caused the unsupported styles to vanish and therefore components adapted their default styles</li>
</ol>
<p> </p>
<p>Several action took place in order to bring some life to the new app</p>
<ol>
<li>Start over with new CSS file and add to it only the supported styles (i.e. clean it)</li>
<li>Implement new skins introduced by 4.1 SDK</li>
<li>In some skin files, implement backward compatibility for old styles such as borderThickness and cornerRadius by overriding updateDisplayList() in the skin file. Same done for the icon property of the Button class (today, I’m familiar with skin part and this is the right solution)</li>
<li>Implement a RTL-specific css file and load it dynamically using tyleManager.loadStyleDeclarations() when the app switched to RTL (and unload otherwise).</li>
</ol>
|
JavaScript
|
UTF-8
| 351
| 2.515625
| 3
|
[] |
no_license
|
$(document).ready(function () {
$("form#Submit").submit(function () {
var count = $(this).data("count") || 0;
if (count >= x) {
//user clicked more than you wanted to so do something here
}
$(this).data("count", ++count);
alert(1);
});
function save() {
alert(1);
}
});
|
Shell
|
UTF-8
| 245
| 3.421875
| 3
|
[] |
no_license
|
#!/bin/bash -x
for files in `ls *.log.1`
do
#removing names of files without extension
filename=`echo $files | awk -F . '{print $1}'`
now=$(date +"%d%m%Y")
#rename file with new name
cp $files $filename.$now.log.1
done
|
C++
|
UTF-8
| 740
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
class Solution {
public:
int maxMoves(vector<vector<int>>& grid) {
const int m = grid.size();
const int n = grid[0].size();
int ans = 0;
// dp[i][j] := max # of moves you can perform from (i, j)
vector<vector<int>> dp(m, vector<int>(n));
for (int j = n - 2; j >= 0; --j)
for (int i = 0; i < m; ++i) {
if (grid[i][j + 1] > grid[i][j])
dp[i][j] = 1 + dp[i][j + 1];
if (i > 0 && grid[i - 1][j + 1] > grid[i][j])
dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j + 1]);
if (i + 1 < m && grid[i + 1][j + 1] > grid[i][j])
dp[i][j] = max(dp[i][j], 1 + dp[i + 1][j + 1]);
}
for (int i = 0; i < m; ++i)
ans = max(ans, dp[i][0]);
return ans;
}
};
|
C#
|
UTF-8
| 599
| 3.203125
| 3
|
[] |
no_license
|
using System.Collections.Generic;
namespace DesignPatterns.Structural.Proxy
{
public class Events
{
private readonly Queue<string> _queue;
public Events()
{
_queue = new Queue<string>();
}
public void Add(string @event)
{
_queue.Enqueue(@event);
}
public List<string> CaptureEvents()
{
var events = new List<string>();
while (_queue.Count > 0)
{
events.Add(_queue.Dequeue());
}
return events;
}
}
}
|
Markdown
|
UTF-8
| 1,630
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
# Hi <img src="https://media.giphy.com/media/hvRJCLFzcasrR4ia7z/giphy.gif" width="32px">
I'm Alex, a full stack developer based in Devon, UK 🇬🇧 originally from Gibraltar 🇬🇮. I thrive on the challenge of problem-solving and finding creative solutions to complex issues. As a lifelong learner, I am always looking to expand my skillset and staying up-to-date with the latest tech, business and productivity.
I currently work at [Pixel Fridge](https://pixelfridge.digital), where I collaborate with a talented team of developers and designers to deliver high-quality projects that exceed client expectations and provide purposeful experiences that have a positive impact on people and the planet.
In my downtime, you can find me honing my musical skills on the guitar or drums, or unwinding with a game. I’m also making an effort to prioritize my health and fitness, and I'm starting to enjoy running and lifting weights.
Don’t hesitate to reach out to me on any of the platforms listed below. Whether you’re interested in collaborating on a project or just want to chat about our interests, I’m always open to connecting with like-minded individuals.
[Email](mailto:alex@alexhowes.co.uk) •
[Twitter](https://twitter.com/aihowes) •
[LinkedIn](https://linkedin.com/in/aihowes) •
[Instagram](https://instagram.com/aihowes) •
[YouTube](https://youtube.com/c/aihowes) •
[Twitch](https://twitch.tv/aihowes) •
[Strava](https://www.strava.com/athletes/aihowes) •
[Hevy](https://www.hevy.com/user/aihowes)
---
GPG Key: https://github.com/aihowes.gpg
NPX Card: `npx aihowes`
---
See pinned projects below 👇
|
Python
|
UTF-8
| 474
| 4.0625
| 4
|
[] |
no_license
|
def lesser_of_two_evens(a, b):
if not(a % 2) and not(b % 2):
return min(a, b)
else:
return max(a, b)
def animal_crackers(s):
tmp = s.lower().split(' ')
if tmp[0][0] == tmp[1][0]:
return True
else:
return False
def makes_twenty(a, b):
return a + b == 20 or a == 20 or b == 20
if __name__ == '__main__':
print(lesser_of_two_evens(3, 4))
print(animal_crackers('Lazy hlama'))
print(makes_twenty(10, 10))
|
JavaScript
|
UTF-8
| 597
| 3.671875
| 4
|
[] |
no_license
|
function ubahHuruf(kata) {
var alphabet = '';
var alphabetList = 'abcdefghijklmnopqrstuvwxyz';
var alphabetChanged = ''
var output = '';
for (var i = 0; i < kata.length; i++) {
alphabet = kata[i]
var index = alphabetList.indexOf(alphabet) + 1
var alphabetChanged = alphabetList.charAt(index)
output += alphabetChanged
}
return output
}
// TEST CASES
console.log(ubahHuruf('wow')); // xpx
console.log(ubahHuruf('developer')); // efwfmpqfs
console.log(ubahHuruf('javascript')); // kbwbtdsjqu
console.log(ubahHuruf('keren')); // lfsfo
console.log(ubahHuruf('semangat')); // tfnbohbu
|
Markdown
|
UTF-8
| 3,567
| 2.796875
| 3
|
[] |
no_license
|
---
description: "Simple Way to Prepare Speedy Arugula Basil Pesto"
title: "Simple Way to Prepare Speedy Arugula Basil Pesto"
slug: 456-simple-way-to-prepare-speedy-arugula-basil-pesto
date: 2020-12-22T10:59:24.190Z
image: https://img-global.cpcdn.com/recipes/ebead05980728818/680x482cq70/arugula-basil-pesto-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/ebead05980728818/680x482cq70/arugula-basil-pesto-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/ebead05980728818/680x482cq70/arugula-basil-pesto-recipe-main-photo.jpg
author: Isabel Robertson
ratingvalue: 4.1
reviewcount: 1662
recipeingredient:
- "2 cups tight packed arugula"
- ".75 oz package of fresh basil or close to it"
- "4 medium garlic cloves"
- "4 tbsp toasted pine nuts or walnuts"
- "1/2 cup evo"
- "to taste Red wine vinn"
- "1 lemon juiced"
- "1/2 cup fresh fine grated Parmesan"
- "to taste Salt"
recipeinstructions:
- "Add the garlic and pine nuts first with a little evo and give it a quick pulse."
- "Add the arugula and basil along with the lemon juice and give it another pulse"
- "Add the evo and the salt and pulse until smooth but slightly coarse."
- "Remove to a container and stir in the Parmesan and then season with red wine vinegar and salt as needed. Add evo if you need to loosen it up."
categories:
- Recipe
tags:
- arugula
- basil
- pesto
katakunci: arugula basil pesto
nutrition: 286 calories
recipecuisine: American
preptime: "PT26M"
cooktime: "PT33M"
recipeyield: "1"
recipecategory: Dinner
---

Hello everybody, it is me again, Dan, welcome to our recipe site. Today, we're going to prepare a special dish, arugula basil pesto. One of my favorites. This time, I'm gonna make it a little bit tasty. This is gonna smell and look delicious.
Arugula Basil Pesto is one of the most popular of recent trending foods in the world. It's appreciated by millions every day. It is easy, it is quick, it tastes delicious. They are nice and they look wonderful. Arugula Basil Pesto is something that I've loved my whole life.
To begin with this recipe, we must first prepare a few ingredients. You can cook arugula basil pesto using 9 ingredients and 4 steps. Here is how you cook it.
<!--inarticleads1-->
##### The ingredients needed to make Arugula Basil Pesto:
1. Prepare 2 cups tight packed arugula
1. Take .75 oz package of fresh basil or close to it
1. Take 4 medium garlic cloves
1. Prepare 4 tbsp toasted pine nuts or walnuts
1. Take 1/2 cup evo
1. Get to taste Red wine vinn
1. Make ready 1 lemon juiced
1. Make ready 1/2 cup fresh fine grated Parmesan
1. Take to taste Salt
<!--inarticleads2-->
##### Steps to make Arugula Basil Pesto:
1. Add the garlic and pine nuts first with a little evo and give it a quick pulse.
1. Add the arugula and basil along with the lemon juice and give it another pulse
1. Add the evo and the salt and pulse until smooth but slightly coarse.
1. Remove to a container and stir in the Parmesan and then season with red wine vinegar and salt as needed. Add evo if you need to loosen it up.
So that's going to wrap it up with this exceptional food arugula basil pesto recipe. Thanks so much for your time. I am confident you can make this at home. There is gonna be more interesting food at home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your family, friends and colleague. Thanks again for reading. Go on get cooking!
|
Markdown
|
UTF-8
| 16,406
| 2.609375
| 3
|
[
"CC-BY-4.0",
"MIT"
] |
permissive
|
---
title: Cenni preliminari sugli oggetti Freezable
ms.date: 03/30/2017
dev_langs:
- csharp
- vb
helpviewer_keywords:
- Freezable objects [WPF], description
- unfreezing Freezable objects [WPF]
- classes [WPF], Freezable
ms.assetid: 89c71692-4f43-4057-b611-67c6a8a863a2
ms.openlocfilehash: 755240859829042e9790b9c89e47bb7a2013ceef
ms.sourcegitcommit: 944ddc52b7f2632f30c668815f92b378efd38eea
ms.translationtype: MT
ms.contentlocale: it-IT
ms.lasthandoff: 11/03/2019
ms.locfileid: "73460443"
---
# <a name="freezable-objects-overview"></a>Cenni preliminari sugli oggetti Freezable
In questo argomento viene descritto come utilizzare e creare in modo efficace oggetti <xref:System.Windows.Freezable>, che forniscono funzionalità speciali che consentono di migliorare le prestazioni dell'applicazione. Esempi di oggetti Freezable includono pennelli, penne, trasformazioni, geometrie e animazioni.
<a name="whatisafreezable"></a>
## <a name="what-is-a-freezable"></a>Che cos'è un oggetto Freezable?
Un <xref:System.Windows.Freezable> è un tipo speciale di oggetto con due stati: non bloccato e bloccato. Quando viene sbloccato, un <xref:System.Windows.Freezable> sembra comportarsi come qualsiasi altro oggetto. Quando il blocco è bloccato, non è più possibile modificare un <xref:System.Windows.Freezable>.
Un <xref:System.Windows.Freezable> fornisce un evento <xref:System.Windows.Freezable.Changed> per notificare agli osservatori le eventuali modifiche apportate all'oggetto. Il blocco di un <xref:System.Windows.Freezable> può migliorare le prestazioni, perché non è più necessario spendere risorse per le notifiche di modifica. Un <xref:System.Windows.Freezable> bloccato può anche essere condiviso tra thread, mentre un <xref:System.Windows.Freezable> non bloccato non può.
Anche se la classe <xref:System.Windows.Freezable> dispone di molte applicazioni, la maggior parte degli oggetti <xref:System.Windows.Freezable> in [!INCLUDE[TLA#tla_winclient](../../../../includes/tlasharptla-winclient-md.md)] sono correlati al sottosistema grafico.
La classe <xref:System.Windows.Freezable> rende più semplice l'utilizzo di determinati oggetti di sistema grafici e consente di migliorare le prestazioni dell'applicazione. Esempi di tipi che ereditano da <xref:System.Windows.Freezable> includono le classi <xref:System.Windows.Media.Brush>, <xref:System.Windows.Media.Transform>e <xref:System.Windows.Media.Geometry>. Poiché contengono risorse non gestite, il sistema deve monitorare tali oggetti per le modifiche e quindi aggiornare le corrispondenti risorse non gestite quando viene apportata una modifica all'oggetto originale. Anche se non si modifica effettivamente un oggetto di sistema grafico, il sistema deve comunque dedicare alcune risorse al monitoraggio dell'oggetto, nel caso in cui venga modificato.
Si supponga, ad esempio, di creare un pennello <xref:System.Windows.Media.SolidColorBrush> e di usarlo per disegnare lo sfondo di un pulsante.
[!code-csharp[freezablesample_procedural#FrozenExamplePart1](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#frozenexamplepart1)]
[!code-vb[freezablesample_procedural#FrozenExamplePart1](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#frozenexamplepart1)]
Quando viene eseguito il rendering del pulsante, il sottosistema grafico [!INCLUDE[TLA2#tla_winclient](../../../../includes/tla2sharptla-winclient-md.md)] usa le informazioni fornite per disegnare un gruppo di pixel per creare l'aspetto di un pulsante. Sebbene sia stato usato un pennello tinta unita per descrivere il modo in cui deve essere disegnato il pulsante, il pennello tinta unita non esegue effettivamente il disegno. Il sistema grafico genera oggetti veloci e di basso livello per il pulsante e il pennello e sono gli oggetti effettivamente visualizzati sullo schermo.
Per modificare il pennello, è necessario rigenerare tali oggetti di basso livello. La classe Freezable fornisce a un pennello la possibilità di trovare gli oggetti di basso livello generati corrispondenti e di aggiornarli quando cambiano. Quando questa funzionalità è abilitata, il pennello viene definito "non bloccato".
Il metodo <xref:System.Windows.Freezable.Freeze%2A> di un oggetto Freezable consente di disabilitare questa funzionalità di aggiornamento automatico. È possibile utilizzare questo metodo per fare in modo che il pennello diventi "bloccato" o non modificabile.
> [!NOTE]
> Non tutti gli oggetti Freezable possono essere bloccati. Per evitare di generare un <xref:System.InvalidOperationException>, controllare il valore della proprietà <xref:System.Windows.Freezable.CanFreeze%2A> dell'oggetto Freezable per determinare se può essere bloccato prima di tentare di bloccarlo.
[!code-csharp[freezablesample_procedural#FrozenExamplePart2](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#frozenexamplepart2)]
[!code-vb[freezablesample_procedural#FrozenExamplePart2](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#frozenexamplepart2)]
Quando non è più necessario modificare un oggetto Freezable, il blocco offre vantaggi in merito alle prestazioni. Se si blocca il pennello in questo esempio, il sistema grafico non dovrà più monitorarlo per le modifiche. Il sistema grafico può anche eseguire altre ottimizzazioni, perché sa che il pennello non cambierà.
> [!NOTE]
> Per praticità, gli oggetti Freezable rimangono bloccati a meno che non vengano bloccati in modo esplicito.
<a name="frozenfreezables"></a>
## <a name="using-freezables"></a>Uso di Freezable
L'utilizzo di un oggetto Freezable sbloccato è analogo all'utilizzo di qualsiasi altro tipo di oggetto. Nell'esempio seguente, il colore di un <xref:System.Windows.Media.SolidColorBrush> viene modificato da giallo a rosso dopo che è stato usato per disegnare lo sfondo di un pulsante. Il sistema grafico funziona dietro le quinte per modificare automaticamente il pulsante da giallo a rosso alla successiva aggiornamento dello schermo.
[!code-csharp[freezablesample_procedural#UnFrozenExampleShort](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#unfrozenexampleshort)]
[!code-vb[freezablesample_procedural#UnFrozenExampleShort](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#unfrozenexampleshort)]
### <a name="freezing-a-freezable"></a>Blocco di un oggetto Freezable
Per rendere immodificabile un <xref:System.Windows.Freezable>, chiamare il relativo metodo <xref:System.Windows.Freezable.Freeze%2A>. Quando si blocca un oggetto che contiene oggetti Freezable, anche questi oggetti sono bloccati. Se, ad esempio, si blocca un <xref:System.Windows.Media.PathGeometry>, anche le figure e i segmenti in esso contenuti verrebbero bloccati.
Un oggetto Freezable **non può** essere bloccato se si verifica una delle condizioni seguenti:
- Dispone di proprietà animate o con associazione a dati.
- Dispone di proprietà impostate da una risorsa dinamica. Per ulteriori informazioni sulle risorse dinamiche, vedere le [risorse XAML](../../../desktop-wpf/fundamentals/xaml-resources-define.md) .
- Contiene <xref:System.Windows.Freezable> oggetti secondari che non possono essere bloccati.
Se queste condizioni sono false e non si intende modificare il <xref:System.Windows.Freezable>, è consigliabile bloccarlo per ottenere i vantaggi in termini di prestazioni descritti in precedenza.
Una volta chiamato il metodo <xref:System.Windows.Freezable.Freeze%2A> di un oggetto Freezable, non è più possibile modificarlo. Il tentativo di modificare un oggetto bloccato causa la generazione di un <xref:System.InvalidOperationException>. Il codice seguente genera un'eccezione, perché si tenta di modificare il pennello dopo che è stato bloccato.
[!code-csharp[freezablesample_procedural#ExceptionExample](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#exceptionexample)]
[!code-vb[freezablesample_procedural#ExceptionExample](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#exceptionexample)]
Per evitare di generare questa eccezione, è possibile usare il metodo <xref:System.Windows.Freezable.IsFrozen%2A> per determinare se un <xref:System.Windows.Freezable> è bloccato.
[!code-csharp[freezablesample_procedural#CheckIsFrozenExample](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#checkisfrozenexample)]
[!code-vb[freezablesample_procedural#CheckIsFrozenExample](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#checkisfrozenexample)]
Nell'esempio di codice precedente, è stata eseguita una copia modificabile di un oggetto bloccato usando il metodo <xref:System.Windows.Freezable.Clone%2A>. La sezione successiva illustra la clonazione in modo più dettagliato.
> [!NOTE]
> Poiché non è possibile animare un Freezable bloccato, il sistema di animazione creerà automaticamente cloni modificabili di oggetti <xref:System.Windows.Freezable> bloccati quando si tenta di animarli con una <xref:System.Windows.Media.Animation.Storyboard>. Per eliminare l'overhead delle prestazioni causato dalla clonazione, lasciare un oggetto non bloccato se si intende animarlo. Per ulteriori informazioni sull'animazione con gli storyboard, vedere [Cenni preliminari sugli storyboard](../graphics-multimedia/storyboards-overview.md).
### <a name="freezing-from-markup"></a>Blocco dal markup
Per bloccare un oggetto <xref:System.Windows.Freezable> dichiarato nel markup, usare l'attributo `PresentationOptions:Freeze`. Nell'esempio seguente una <xref:System.Windows.Media.SolidColorBrush> viene dichiarata come risorsa di pagina e bloccata. Viene quindi usato per impostare lo sfondo di un pulsante.
[!code-xaml[FreezableSample#FreezeFromMarkupWholePage](~/samples/snippets/csharp/VS_Snippets_Wpf/FreezableSample/CS/FreezeFromMarkupExample.xaml#freezefrommarkupwholepage)]
Per utilizzare l'attributo `Freeze`, è necessario eseguire il mapping allo spazio dei nomi delle opzioni di presentazione: `http://schemas.microsoft.com/winfx/2006/xaml/presentation/options`. `PresentationOptions` è il prefisso consigliato per il mapping di questo spazio dei nomi:
```xaml
xmlns:PresentationOptions="http://schemas.microsoft.com/winfx/2006/xaml/presentation/options"
```
Poiché non tutti i lettori XAML riconoscono questo attributo, è consigliabile usare l' [attributo MC: Ignorable](mc-ignorable-attribute.md) per contrassegnare l'attributo `Presentation:Freeze` come ignorabile:
```xaml
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="PresentationOptions"
```
Per ulteriori informazioni, vedere la pagina relativa all' [attributo MC: Ignorable](mc-ignorable-attribute.md) .
### <a name="unfreezing-a-freezable"></a>"Sblocco" di un oggetto Freezable
Una volta bloccato, un <xref:System.Windows.Freezable> non può mai essere modificato o sbloccato; Tuttavia, è possibile creare un clone non bloccato usando il metodo <xref:System.Windows.Freezable.Clone%2A> o <xref:System.Windows.Freezable.CloneCurrentValue%2A>.
Nell'esempio seguente lo sfondo del pulsante viene impostato con un pennello e il pennello viene quindi bloccato. Viene eseguita una copia non bloccata del pennello utilizzando il metodo <xref:System.Windows.Freezable.Clone%2A>. Il clone viene modificato e usato per modificare lo sfondo del pulsante da giallo a rosso.
[!code-csharp[freezablesample_procedural#CloneExample](~/samples/snippets/csharp/VS_Snippets_Wpf/freezablesample_procedural/CSharp/freezablesample.cs#cloneexample)]
[!code-vb[freezablesample_procedural#CloneExample](~/samples/snippets/visualbasic/VS_Snippets_Wpf/freezablesample_procedural/visualbasic/freezablesample.vb#cloneexample)]
> [!NOTE]
> Indipendentemente dal metodo di clonazione usato, le animazioni non vengono mai copiate nella nuova <xref:System.Windows.Freezable>.
I metodi <xref:System.Windows.Freezable.Clone%2A> e <xref:System.Windows.Freezable.CloneCurrentValue%2A> producono copie complete dell'oggetto Freezable. Se l'oggetto Freezable contiene altri oggetti Freezable bloccati, questi vengono anche clonati e resi modificabili. Se, ad esempio, si clona un <xref:System.Windows.Media.PathGeometry> bloccato per renderlo modificabile, anche le figure e i segmenti in esso contenuti vengono copiati e resi modificabili.
<a name="createyourownfreezableclass"></a>
## <a name="creating-your-own-freezable-class"></a>Creazione di una classe Freezable personalizzata
Una classe che deriva da <xref:System.Windows.Freezable> acquisisce le funzionalità seguenti.
- Stati speciali: uno stato di sola lettura (bloccato) e scrivibile.
- Thread safety: un <xref:System.Windows.Freezable> bloccato può essere condiviso tra thread.
- Notifica dettagliata delle modifiche: diversamente da altre <xref:System.Windows.DependencyObject>s, gli oggetti Freezable forniscono notifiche di modifica quando i valori delle sottoproprietà cambiano.
- Clonazione semplice: la classe Freezable ha già implementato diversi metodi che producono cloni profondi.
Un <xref:System.Windows.Freezable> è un tipo di <xref:System.Windows.DependencyObject>e pertanto utilizza il sistema di proprietà di dipendenza. Le proprietà della classe non devono essere proprietà di dipendenza, ma l'uso delle proprietà di dipendenza ridurrà la quantità di codice da scrivere, perché la classe <xref:System.Windows.Freezable> è stata progettata con le proprietà di dipendenza. Per ulteriori informazioni sul sistema di proprietà di dipendenza, vedere [Cenni preliminari sulle proprietà di dipendenza](dependency-properties-overview.md).
Ogni sottoclasse <xref:System.Windows.Freezable> deve eseguire l'override del metodo <xref:System.Windows.Freezable.CreateInstanceCore%2A>. Se la classe USA proprietà di dipendenza per tutti i dati, l'operazione è terminata.
Se la classe contiene membri dati di proprietà non di dipendenza, è necessario anche eseguire l'override dei metodi seguenti:
- <xref:System.Windows.Freezable.CloneCore%2A>
- <xref:System.Windows.Freezable.CloneCurrentValueCore%2A>
- <xref:System.Windows.Freezable.GetAsFrozenCore%2A>
- <xref:System.Windows.Freezable.GetCurrentValueAsFrozenCore%2A>
- <xref:System.Windows.Freezable.FreezeCore%2A>
È inoltre necessario osservare le regole seguenti per l'accesso e la scrittura a membri dati che non sono proprietà di dipendenza:
- All'inizio di qualsiasi API che legge i membri dati della proprietà non di dipendenza, chiamare il metodo <xref:System.Windows.Freezable.ReadPreamble%2A>.
- All'inizio di qualsiasi API che scriva membri dati di proprietà non di dipendenza, chiamare il metodo <xref:System.Windows.Freezable.WritePreamble%2A>. Dopo aver chiamato <xref:System.Windows.Freezable.WritePreamble%2A> in un'API, non è necessario effettuare una chiamata aggiuntiva a <xref:System.Windows.Freezable.ReadPreamble%2A> se si leggono anche i membri dati della proprietà non di dipendenza.
- Chiamare il metodo <xref:System.Windows.Freezable.WritePostscript%2A> prima di uscire da metodi che scrivono in membri dati di proprietà non di dipendenza.
Se la classe contiene membri dati di proprietà non dipendenza <xref:System.Windows.DependencyObject> oggetti, è necessario chiamare anche il metodo <xref:System.Windows.Freezable.OnFreezablePropertyChanged%2A> ogni volta che si modifica uno dei relativi valori, anche se si imposta il membro su `null`.
> [!NOTE]
> È molto importante iniziare ogni <xref:System.Windows.Freezable> metodo di cui si esegue l'override con una chiamata all'implementazione di base.
Per un esempio di classe di <xref:System.Windows.Freezable> personalizzata, vedere l' [esempio di animazione personalizzata](https://go.microsoft.com/fwlink/?LinkID=159981).
## <a name="see-also"></a>Vedere anche
- <xref:System.Windows.Freezable>
- [Esempio di animazione personalizzata](https://go.microsoft.com/fwlink/?LinkID=159981)
- [Panoramica sulle proprietà di dipendenza](dependency-properties-overview.md)
- [Proprietà di dipendenza personalizzate](custom-dependency-properties.md)
|
TypeScript
|
UTF-8
| 2,665
| 3.171875
| 3
|
[] |
no_license
|
import { Component } from '@angular/core';
import { shuffle } from 'lodash';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
places = [null,null,null,null,null,null,null,null,null];
availablePlaces = [0,1,2,3,4,5,6,7,8];
preferredPlaces = [];
threes = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
moveCounter = 0;
displayMessage = '';
gameWon = false;
gameWinner = null;
autoPlay = true;
whoseTurn = null;
ngOnInit(): void {
this.randomize();
this.placeO();
}
randomize():void{
this.availablePlaces = shuffle(this.availablePlaces);
}
placeX(position):void{
if (position > -1 && position < this.places.length){
this.places[position] = "X";
this.moveCounter++;
this.whoseTurn = "O";
this.checkMoveCount();
}
}
placeO():void{
let subscript = null;
if (this.preferredPlaces.length > 0){
subscript = this.preferredPlaces.pop();
}
else{
subscript = this.availablePlaces.pop();
}
while(this.places[subscript]!=null){
subscript = this.availablePlaces.pop();
if (this.availablePlaces.length == 0){
break;
}
}
this.places[subscript] = "O";
this.moveCounter++;
this.whoseTurn = "X";
this.checkMoveCount();
}
checkMoveCount():void{
this.checkWinState();
if (!this.gameWon){
if (this.moveCounter == 9){
this.displayMessage = 'Game Over';
}
else{
if (this.autoPlay && this.whoseTurn == "O"){
this.placeO();
}
}
}
}
checkWinState():void{
//check whether any of the sets of indices listed in threes contain all X's or all O's
for (let threeset of this.threes){
const items = [];
for (let index of threeset){
items.push(this.places[index]);
}
if (items[0]=="X" && items[1]=="X" && items[2]=="X"){
this.gameWon = true;
this.gameWinner = "X";
}
else if (items[0]=="O" && items[1]=="O" && items[2]=="O"){
this.gameWon = true;
this.gameWinner = "O";
}
else if (items[0]=="O" && items[1]=="O" && items[2]==null){
this.preferredPlaces.push(threeset[2]);
}
else if (items[0]=="O" && items[1]==null && items[2]=="O"){
this.preferredPlaces.push(threeset[1]);
}
else if (items[0]==null && items[1]=="O" && items[2]=="O"){
this.preferredPlaces.push(threeset[0]);
}
}
if (this.gameWon){
this.displayMessage = "Game Won By " + this.gameWinner;
}
}
}
|
Python
|
UTF-8
| 1,470
| 3.71875
| 4
|
[] |
no_license
|
x = input("Masukan besar langkah yang diinginkan: \n")
n = input("Banyaknya langkah yang akan dilewati: \n")
rep = input("Pengulangan yang diinginkan: \n")
import turtle
import random
cat = turtle.Turtle()
list1 = [0,1,2,3]
list2 = [0,1,2]
def random_walk_1(length, how_much):
"""This function takes parameter length as the length of the turtle; how_much as the number of process that will occur"""
cat.left(90) #making cat face upward
cat.speed(10)
for i in range(how_much):
if random.choice(list1) == 0:
cat.forward(length)
elif random.choice(list1) == 1:
cat.backward(length)
elif random.choice(list1) == 2:
cat.left(random.randint(0,360))
elif random.choice(list1) == 3:
cat.right(random.randint(0,360))
turtle.done()
def random_walk_2(length, how_much,repetition):
"""This function takes turtle move and back to (0,0), and do the same process again"""
cat.left(90)
cat.speed(10)
for a in range(repetition):
for i in range(how_much):
if random.choice(list2) == 0:
cat.forward(length)
elif random.choice(list2) == 1:
cat.right(random.randint(0,90))
else:
cat.left(random.randint(0,90))
cat.pu()
cat.home()
cat.pd()
turtle.done()
random_walk_2(int(x),int(n),int(rep))
|
C++
|
GB18030
| 1,595
| 2.59375
| 3
|
[] |
no_license
|
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <limits.h>
#include <string.h>
#include <algorithm>
#define LOCAL
using namespace std;
//f[i][j]ʾǰi豸СΪjʱС۸
int f[103][2000];
int mi[103];
struct node
{
int b;
int p;
};
int main()
{
#ifdef LOCAL
freopen("data.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
#endif // LOCAL
int t, n, maxB = 0;
node devices[103][103];
cin >> t;
while(t--)
{
memset(f, 0x7f, sizeof(f));
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> mi[i];
for(int j = 1; j <= mi[i]; j++)
{
cin >> devices[i][j].b >> devices[i][j].p;
if(devices[i][j].b > maxB)
{
maxB = devices[i][j].b;
}
}
}
//ʼ
for(int i = 0; i <= maxB; i++)
{
f[0][i] = 0;
}
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= mi[i]; j++)
{
for(int k = 1; k <= devices[i][j].b; k++)
{
f[i][k] = min(f[i][k], f[i - 1][k] + devices[i][j].p);
}
}
}
double ans = 0.0;
for(int i = 1; i <= maxB; i++ )
{
ans = max(ans, i*1.0 / f[n][i]);
}
printf("%.3f\n", ans);
}
return 0;
}
|
Java
|
UTF-8
| 1,171
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
package com.revature.controllers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
import com.revature.Reimbursements.DAO.ReimbursementDAO;
import com.revature.Reimbursements.beans.Employee;
//Servlet for logging in
public class LoginServlet extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("pass");
Employee e = ReimbursementDAO.getEmployee(email);
if(e != null) {
if(password.equals(e.getPassword())) {
response.getWriter().append(Integer.toString(e.getId()));
} else {
response.getWriter().append("Incorrect Password");
}
} else {
response.getWriter().append("Invalid Email");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
|
Java
|
UTF-8
| 402
| 3.3125
| 3
|
[] |
no_license
|
public class J0001 {
//imprimendo textos
public static void main(String[] args) {
// 1) impriir o texto "ola mundo"
System.out.println("Olá mundo");
// 2) imprima o numero 522
System.out.println(522);
// 3) imprima uma linha em branco
System.out.println();
// imprima mais um texto
System.out.println("Ola seja bem vindo a nossa lista de exercicios resolvidos.");
}
}
|
Python
|
UTF-8
| 1,443
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
import pytest
from html2ans.parsers.audio import AudioParser
@pytest.fixture
def parser():
return AudioParser()
@pytest.fixture(params=[
'<audio></audio>',
])
def valid_audio_tag(request):
return request.param
def test_empty(parser, make_tag):
tag = make_tag('<audio></audio>', 'audio')
assert (None, False) == parser.parse(tag)
def test_is_applicable(parser, valid_audio_tag, make_tag):
assert parser.is_applicable(make_tag(valid_audio_tag, 'audio'))
def test_audio(parser, make_tag):
tag = make_tag('<audio><source src=audiosource /></audio>', 'audio')
parsed = parser.parse(tag)[0]
assert parsed.get('streams')[0]["url"] == 'audiosource'
assert parsed.get('type') == 'audio'
def test_audio_with_spaces_in_src(parser, make_tag):
tag = make_tag('<audio id="asset-1234" class="audio-player" controls="controls">'
'<source src="http://example.com/audio/name with spaces.mp3" type="audio/mpeg">'
'</audio>',
'audio')
parsed = parser.parse(tag)[0]
assert parsed.get('type') == 'audio'
assert parsed.get("additional_properties", {}).get("class") == ["audio-player"]
assert parsed.get("additional_properties", {}).get("controls") == "controls"
assert parsed.get("additional_properties", {}).get("id") == "asset-1234"
assert parsed.get('streams')[0]["url"] == "http://example.com/audio/name%20with%20spaces.mp3"
|
PHP
|
UTF-8
| 9,486
| 2.53125
| 3
|
[] |
no_license
|
<?php
use App\Model\Projeto;
use App\Controller\ProjetoController;
use App\Util\Upload;
$projetoController = new ProjetoController();
$nome = "";
$status = 1;
$descricao = "";
$editando = false;
$cod = filter_input(INPUT_GET, "cod", FILTER_SANITIZE_NUMBER_INT);
if (filter_input(INPUT_POST, "txtNome", FILTER_SANITIZE_STRING)) {
$projeto = new Projeto();
$projeto->setCod($cod);
$projeto->setData(date("Y-m-d H:i:s"));
$projeto->setNome(filter_input(INPUT_POST, "txtNome", FILTER_SANITIZE_STRING));
$projeto->setStatus(filter_input(INPUT_POST, "slStatus", FILTER_SANITIZE_NUMBER_INT));
$projeto->setDescricao(filter_input(INPUT_POST, "txtDescricao", FILTER_SANITIZE_SPECIAL_CHARS));
$projeto->getUsuario()->setCod($_SESSION["cod"]);
if (!$cod) {
//Cadastrando
$dirImage = "img/projetos/";
$upload = new Upload();
$nomeImagem = null;
$erroUpload = false;
if (isset($_FILES["flImagem"]) && $_FILES["flImagem"]["tmp_name"] != null) {
$nomeImagem = $upload->LoadFile($dirImage, "img", $_FILES["flImagem"]);
if ($nomeImagem == "") {
$erroUpload = true;
}
}
if (!$erroUpload) {
$projeto->setThumb($nomeImagem);
if ($projetoController->Cadastrar($projeto)) {
?>
<script>
setCookie("result", "c1", 1);
document.location.href = "?p=gprojeto";
</script>
<?php
} else {
$img = ("{$dirImage}/{$nomeImagem}");
if (file_exists($img)) {
unlink($img);
}
?>
<script>
setCookie("result", "c2", 1);
document.location.href = "?p=gprojeto";
</script>
<?php
}
} else {
?>
<script>
setCookie("result", "c3", 1);
document.location.href = "?p=gprojeto";
</script>
<?php
}
} else {
//Editando
if ($projetoController->Alterar($projeto)) {
?>
<script>
setCookie("result", "e1", 1);
document.location.href = "?p=gprojeto";
</script>
<?php
} else {
?>
<script>
setCookie("result", "e2", 1);
document.location.href = "?p=gprojeto";
</script>
<?php
}
}
}
if ($cod) {
$projeto = $projetoController->RetornarCod($cod);
$nome = $projeto->getNome();
$status = $projeto->getStatus();
$descricao = $projeto->getDescricao();
$editando = true;
}
$listaProjeto = [];
$statusBusca = filter_input(INPUT_POST, "slBuscaStatus", FILTER_SANITIZE_NUMBER_INT);
if ($statusBusca) {
$listaProjeto = $projetoController->RetornarTodosStatus($statusBusca);
}
?>
<h1>Gerenciar projetos</h1>
<button id="btnNovoProjeto" class="btn btn-info">Novo projeto</button>
<a href="?p=home" class="btn btn-dark">Voltar</a>
<br><br>
<div id="dvFrmProjeto" <?= ($editando ? "aqui" : "style='display: none;'"); ?>>
<form method="post" id="frmGerenciaProjeto" enctype="multipart/form-data">
<input type="hidden" id="txtEditando" value="<?= ($editando ? "1" : "0"); ?>" />
<div>
<div class="form-group grid-40 mobile-grid-100">
<label for="txtNome">Nome</label>
<input type="text" class="form-control" id="txtNome" name="txtNome" placeholder="Controle de projetos" value="<?= $nome; ?>">
</div>
<div class="form-group grid-20 mobile-grid-100">
<label for="slStatus">Status</label>
<select class="custom-select" id="slStatus" name="slStatus">
<option value="1" <?= $status == 1 ? "selected" : ""; ?>>Ativo</option>
<option value="2" <?= $status == 2 ? "selected" : ""; ?>>Bloqueado</option>
</select>
</div>
<div class="grid-40 mobile-grid-100">
<label for="flImagem">Imagem (png e jpg)</label>
<input type="file" class="form-control-file" name="flImagem" id="flImagem" <?= !$editando ? "" : "disabled='true'" ?>>
</div>
</div>
<div>
<div class="form-group grid-100">
<textarea id="txtDescricao" name="txtDescricao"><?= $descricao; ?></textarea>
</div>
</div>
<div>
</div>
<div>
<div class="form-group grid-60 mobile-grid-100">
<div class="alert alert-warning" id="dvResult">Preencha corretamente todos os campos</div>
</div>
<div class="form-group grid-40 mobile-grid-100">
<button type="submit" class="btn btn-success" id="btnCadastrar"><?= $editando ? "Editar" : "Cadastrar" ?></button>
</div>
<div class="clear"></div>
</div>
<div>
<ul id="ulErros"></ul>
</div>
</form>
</div>
<div id="dvConsulta">
<h2>Consultar</h2>
<form id="slBuscaStatus" method="post" action="#dvConsulta">
<div class="form-group">
<label for="slBuscaStatus">Status</label>
<select class="custom-select" id="slBuscaStatus" name="slBuscaStatus">
<option <?= $statusBusca == false ? "selected" : "" ?>>Selecione</option>
<option value="1" <?= $statusBusca == 1 ? "selected" : "" ?>>Ativo</option>
<option value="2" <?= $statusBusca == 2 ? "selected" : "" ?>>Bloqueado</option>
</select>
</div>
</form>
<table class="table table-hover table-striped table-responsive-lg">
<thead>
<tr>
<th>Nome</th>
<th>Criado por</th>
<th>Data</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
foreach ($listaProjeto as $projeto) {
?>
<tr>
<td><?= $projeto->getNome(); ?></td>
<td><?= $projeto->getUsuarioNome(); ?></td>
<td><?= date("d/m/Y H:i:s", strtotime($projeto->getData())); ?></td>
<td>
<a href='?p=gprojeto&cod=<?= $projeto->getCod(); ?>' class='btn btn-warning'>Editar</a>
<a href='?p=gvisualizaprojeto&cod=<?= $projeto->getCod(); ?>' class='btn btn-info' target='_blank'>Visualizar</a>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<script src="ckeditor/ckeditor.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
CKEDITOR.replace("txtDescricao");
var result = getCookie("result");
DeleteCookie("result");
if (result == "c1") {
ShowModal("Sucesso", "<span class='text-success'>Projeto cadastrado com sucesso.</span>");
} else if (result == "c2") {
ShowModal("Erro", "<span class='text-success'>Não foi possível cadastrar o Projeto.</span>");
} else if (result == "c3") {
ShowModal("Erro", "<span class='text-success'>Não foi possível fazer o upload da imagem.</span>");
} else if (result == "e1") {
ShowModal("Sucesso", "<span class='text-success'>Projeto alterado com sucesso.</span>");
} else if (result == "e2") {
ShowModal("Erro", "<span class='text-success'>Não foi possível alterar o Projeto.</span>");
}
});
$("#slBuscaStatus").change(function () {
$("#slBuscaStatus").submit();
});
$("#frmGerenciaProjeto").submit(function (event) {
if (!Validar()) {
event.preventDefault();
}
});
$("#btnNovoProjeto").click(function () {
$("#dvFrmProjeto").toggle("slow");
});
function Validar() {
var erros = 0;
var ulErros = document.getElementById("ulErros");
ulErros.innerHTML = "";
if ($("#txtNome").val().length <= 3) {
var li = document.createElement("li");
li.innerHTML = "- Informe um nome válido. (min. 4 caracteres)";
ulErros.appendChild(li);
erros++;
}
var value = CKEDITOR.instances['txtDescricao'].getData();
if (value.length <= 5) {
var li = document.createElement("li");
li.innerHTML = "- Informe uma descrição. (min. 6 caracteres)";
ulErros.appendChild(li);
erros++;
}
if (erros == 0) {
return true;
} else {
return false;
}
}
</script>
|
Java
|
UTF-8
| 243
| 2.203125
| 2
|
[] |
no_license
|
package main.java.common.utils.interfaces;
import main.java.common.model.Hand;
import main.java.common.model.Suit;
import java.util.HashSet;
public interface DistinctSuitsReturner {
HashSet<Suit> returnDistinctSuits(final Hand hand);
}
|
C++
|
UTF-8
| 1,727
| 2.828125
| 3
|
[] |
no_license
|
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int n,m;
int map[51][51];
int result=100000000;
int ho_c;
int ch_c;
typedef struct NODE{
int x;
int y;
int dis;
}node;
vector<node> ch;//치킨
vector<node> ho;//집
vector<int> v;
bool cmp(const node &a,const node &b){
return a.dis<b.dis;
}
/*bool desc(const node &a,const node &b){
if(a.x==b.x){
return a.y<b.y;
}
else{
return a.x<a.x;
}
}*/
void search(){
int r=0;
vector<node> ho_ch;//집에서 가까운 치킨집
for(int j=0;j<ho_c;j++){ //각각의 집에서 치킨집 거리
vector<node> ho_ch2;//집에서 가까운 치킨집
for(int i=0;i<ch_c;i++){//조합 m만큼
if(v[i]==1){
int abs_r=(abs(ch[i].x-ho[j].x)+abs(ch[i].y-ho[j].y));
ho_ch2.push_back({0,0,abs_r});
}
}
sort(ho_ch2.begin(),ho_ch2.end(),cmp);
ho_ch.push_back({0,0,ho_ch2[0].dis});
}
for(int i=0;i<ho_c;i++){
r+=ho_ch[i].dis;
}
if(r<result){
result=r;
}
}
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>map[i][j];
if(map[i][j]==1){
ho.push_back({i,j,0});
ho_c++;
}
else if(map[i][j]==2){
ch.push_back({i,j,0});
ch_c++;
}
}
}
for(int i=0;i<ch_c-m;i++){
v.push_back(0);
}
for(int i=0;i<m;i++){
v.push_back(1);
}
do{
search();
}while(next_permutation(v.begin(),v.end()));
cout<<result;
}
|
C++
|
UTF-8
| 2,383
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
#pragma once
#include <map>
#include <string>
class Interpreter
{
public:
Interpreter();
~Interpreter();
void LoadRom(const std::string& path);
void Initialize();
unsigned int* GetScreen();
bool Cycle();
private:
/* Systems memory map (total system memory is 4096 bytes)
0x000-0x1FF - Chip 8 interpreter (contains font set in emu)
0x050-0x0A0 - Used for the built in 4x5 pixel font set (0-F)
0x200-0xFFF - Program ROM and work RAM*/
unsigned char m_Memory[4096];
static const int REGISTER_COUNT = 16;
unsigned char m_V[REGISTER_COUNT]; //16 8-bit registers named from V0 to VF
//both can have a value from 0x000 to 0xFFF
unsigned short m_IndexRegister = 0; //index register
unsigned short m_ProgramCounter = 0x200; //program counter, starts at 0x200
//screen has 2048 pixels (64 x 32)
static const int SCREEN_WIDTH = 64;
static const int SCREEN_HEIGHT = 32;
static const int PIXEL_COUNT = SCREEN_WIDTH * SCREEN_HEIGHT;
unsigned int m_Screen[PIXEL_COUNT];
//2 timers
unsigned char m_DelayTimer = 0; //should be 60?
unsigned char m_SoundTimer = 0; //The systems buzzer sounds whenever the sound timer reaches zero
//Stack and stack pointer
static const int STACK_COUNT = 16;
unsigned short m_Stack[STACK_COUNT];
unsigned short m_StackPointer = 0;
//Fontset
static const int FONTSET_SIZE = 80;
const unsigned char m_Fontset[FONTSET_SIZE] =
{
0xF0, 0x90, 0x90, 0x90, 0xF0, // 0
0x20, 0x60, 0x20, 0x20, 0x70, // 1
0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2
0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3
0x90, 0x90, 0xF0, 0x10, 0x10, // 4
0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5
0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6
0xF0, 0x10, 0x20, 0x40, 0x40, // 7
0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8
0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9
0xF0, 0x90, 0xF0, 0x90, 0x90, // A
0xE0, 0x90, 0xE0, 0x90, 0xE0, // B
0xF0, 0x80, 0x80, 0x80, 0xF0, // C
0xE0, 0x90, 0x90, 0x90, 0xE0, // D
0xF0, 0x80, 0xF0, 0x80, 0xF0, // E
0xF0, 0x80, 0xF0, 0x80, 0x80 // F
};
//Current values for on and off (instead of boring black and white ;) )
unsigned int m_PixelOff = 0;
unsigned int m_PixelOn = 0;
public:
//unsigned char m_Keypad[KEYPAD_COUNT];
unsigned short m_Keypad; //work with one 16 bit integer instead of a 1 bit char array of 16, easier to check if none have been pressed
bool m_DrawFlag = false;
private:
void DecreaseTimers();
void ClearScreen();
};
|
Ruby
|
UTF-8
| 208
| 2.9375
| 3
|
[] |
no_license
|
class TwitterMessages
attr_reader :messages
def initialize message_array
@messages = message_array
end
def include_term?
messages.find {|m| m.include?("Wednesday's #RoundClue")}
end
end
|
C++
|
UTF-8
| 1,158
| 3.8125
| 4
|
[] |
no_license
|
// 543. Diameter of Binary Tree
/*
Given a binary tree, you need to compute the length of the diameter of the tree.
The diameter of a binary tree is the length of the longest path between any two
nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of
edges between them.
*/
// DFS
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if(!root) return 0;
int globalMax = 0;
int maxChildPath = DFS(root, globalMax);
return globalMax;
}
int DFS(TreeNode* root, int& globalMax){
if(!root) return 0;
int left = 0, right = 0, curr = 0;
if(root->left) {
left = DFS(root->left, globalMax) + 1;
curr += left;
}
if(root->right) {
right = DFS(root->right, globalMax) + 1;
curr += right;
}
globalMax = curr > globalMax? curr: globalMax;
return max(left, right);
}
};
|
JavaScript
|
UTF-8
| 3,133
| 2.6875
| 3
|
[] |
no_license
|
$(document).ready(function() {
// // .mouseenter
// // .mouseleave
// // .click
$("#stream1_btn").on("click", function() {
$(".stream1").removeClass('highlight_stream');
$(".stream2").removeClass('highlight_stream');
$(".stream3").removeClass('highlight_stream');
$(".stream1").addClass('highlight_stream');
});
$("#stream2_btn").on("click", function() {
$(".stream1").removeClass('highlight_stream');
$(".stream2").removeClass('highlight_stream');
$(".stream3").removeClass('highlight_stream');
$(".stream2").addClass('highlight_stream');
});
$("#stream3_btn").on("click", function() {
$(".stream1").removeClass('highlight_stream');
$(".stream2").removeClass('highlight_stream');
$(".stream3").removeClass('highlight_stream');
$(".stream3").addClass('highlight_stream');
});
// $("h2").mouseenter(function (){
// $("#hr_html").addClass("lightBlueBackground");
// $("#hr_mysql").addClass("lightBlueBackground");
// $("#hr_python").addClass("lightBlueBackground");
// $("#hr_jquery").addClass("lightBlueBackground");
// $("#hr_django").addClass("lightBlueBackground");
// $("#hr_css").addClass("lightBlueBackground");
// }); // Works on console but makes ALL of them light blue in the background.
// $("#hr_html").mouseenter(function(){
// $("#hr_html").css("font-size", "20px");
// }); // WORKS ON CONSOLE
// $("p").click(function(){
// $(".card_para").css("color", "red");
// }); // Works on console!
// $(".bottom_button").mouseenter(function(){
// $("#container").css("background-color", "#000");
// });
// $(".bottom_button").mouseleave(function(){
// $("#container").css("background-color", "#A9A9A9");
// }); // Both of these work on the console
// $("#firstButton").click(function(){
// $("#firstButton").hide(2000);
// }); // Works on console
// $("#secondButton").click(function(){
// $("#secondPara").slideToggle();
// $("#secondPara").slideToggle();
// }); // Works on console
// $("#thirdButton").mouseenter(function(){
// $("#thirdButton").fadeTo(1000, 0.5);
// });
// $("#thirdButton").mouseleave(function(){
// $("#thirdButton").fadeTo(1000, 1);
// }); //Works on console
// $(".card_para").click(function(){
// $(".card_para").children("a").css("background-color", "yellow");
// }); // traversing through the DOM - actioning anchor tags without a class or ID
// /*--- TRAVERSING THROUGH THE DOM SIDEWAYS --- */
// $(".card_image").click(function(){
// var someCards = $(this).next();
// someCards.next().slideDown();
// }); // working fine for 4 of the cards
/* TUTOR TO LOOK AT */
$(".card").click(function(){
$(this).toggleClass("pinkBackground");
}); // Works on console
/* difficult challenge... */
$("#select").clicked(function(){
$(".card:not(.highlight_stream)").hide();
});
$("#all").clicked(function(){
$(".card").show();
});
});
|
PHP
|
UTF-8
| 1,257
| 2.859375
| 3
|
[] |
no_license
|
<?php
namespace FastNorth\PropertyMapper\Tests\Stubs;
/**
* To
*
* Description...
*/
class To
{
/**
* mapped foo
*
* @var string
*/
private $mappedFoo;
/**
* the mapped children
*
* @var array
*/
private $mappedChildren = '';
/**
* Constructor
*
* @param string $mappedFoo
*/
public function __construct($mappedFoo = null)
{
$this->setMappedFoo($mappedFoo);
}
/**
* Get mapped foo
*
* @return string
*/
public function getMappedFoo()
{
return $this->mappedFoo;
}
/**
* Set mapped foo
*
* @param string $mappedFoo
* @return self
*/
public function setMappedFoo($mappedFoo)
{
$this->mappedFoo = $mappedFoo;
return $this;
}
/**
* Get the mapped children
*
* @return array
*/
public function getMappedChildren()
{
return $this->mappedChildren;
}
/**
* Set the mapped children
*
* @param array $mappedChildren
* @return self
*/
public function setMappedChildren($mappedChildren)
{
$this->mappedChildren = $mappedChildren;
return $this;
}
}
|
JavaScript
|
UTF-8
| 283
| 2.65625
| 3
|
[] |
no_license
|
"use strict";
document.addEventListener("DOMContentLoaded", init);
function init() {
document.querySelector('#arrow').addEventListener("click", goPageDown);
}
function goPageDown() {
document.querySelector('#content').scrollIntoView({
behavior: 'smooth'
});
}
|
Java
|
UTF-8
| 5,929
| 3.234375
| 3
|
[] |
no_license
|
package TutorialQuestion;
import java.util.*;
import java.io.PrintWriter;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.EOFException;
public class Tutorial7 {
public static void main(String[] args) {
//Question1a
try {
PrintWriter outputStream = new PrintWriter(new FileOutputStream("integer.txt"));
Random rnd = new Random();
int[] randomNumber = new int[10];
outputStream.println("The random numbers for question 1a are ");
for (int i = 0; i < 10; i++) {
randomNumber[i] = rnd.nextInt(1001);
outputStream.println(randomNumber[i]);
}
outputStream.close();
} catch (IOException e) {
System.out.println("Problem with file output");
}
//Question1b
try {
Scanner inputStream = new Scanner(new FileInputStream("integer.txt"));
System.out.println(inputStream.nextLine());
int[] randomNumber = new int[10];
int max = 0;
for (int i = 0; i < 10; i++) {
randomNumber[i] = inputStream.nextInt();
System.out.println(randomNumber[i]);
if (randomNumber[i] > max) {
max = randomNumber[i];
}
}
inputStream.close();
} catch (FileNotFoundException e) {
System.out.println("File is not found");
}
//Question1c
try {
ObjectOutputStream outputStream= new ObjectOutputStream (new FileOutputStream ("integer.dat"));
outputStream.writeUTF("The random numbers for question 1c are ");
Random rnd = new Random();
int[] randomNumber = new int[10];
for (int i = 0; i < 10; i++) {
randomNumber[i] = rnd.nextInt(1001);
outputStream.writeInt(randomNumber[i]);
}
outputStream.close();
}catch (IOException e){
System.out.println("Problem with file output");
}
//Question1d
try{
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream ("integer.dat"));
System.out.println(inputStream.readUTF());
System.out.println(inputStream.readInt());
int Sum=0,count=0;
int integer;
try{
while(true){
integer=inputStream.readInt();
System.out.println(integer);
Sum+=integer;
count+=1;
}
}catch(EOFException e){}
int average= Sum/count;
System.out.println("The average number is " + average);
inputStream.close();
}catch (FileNotFoundException e){
System.out.println("The file is not found");
}catch (IOException e){
System.out.println("Problem with file output");
}
/*
Question2a
PrintWriter out = new PrintWriter(new FileOutputStream("d://data/matrix.txt"));
Question2b
try{
PrintWriter out = new PrintWriter(new FileOutputStream("data.txt"));
out.close();
}catch(IOException e){
System.out.println("Problem with file output");
}
Question2c
int num;
try{
ObjectInputStream a = new ObjectInputStream(new FileInputStream("data.dat"));
num = a.readInt();
a.close();
} catch(IOException e){}
Question2d
try{
ObjectOutputStream o= new ObjectOutputStream (new FileOutputStream("data.dat"));
o.writeChar('A');
o.close();
}catch(IOException e){}
*/
//Question3
try{
Scanner input= new Scanner(System.in);
System.out.println("Enter a sentence ");
String sentence = input.nextLine();
PrintWriter outputStream = new PrintWriter( new FileOutputStream("data.txt"));
for (int i=0; i<sentence.length();i++){
int ASCIIdecimal = (int) sentence.charAt(i);
int []binary = new int [8];
for(int bit=0;bit<8;bit++){
if (ASCIIdecimal %2 ==0){
binary[bit] = 0;
}
else{
binary[bit] = 1;
}
ASCIIdecimal /= 2;
}
for (int bit=7;bit>=0;bit--){
outputStream.print(binary[bit]);
}
outputStream.println();
}
outputStream.close();
}catch(IOException e){
System.out.println("Problem with file input");
}
try {
Scanner inputStream = new Scanner (new FileInputStream ("data.txt"));
int bit , decimal , power;
while(inputStream.hasNext()){
bit = inputStream.nextInt();
decimal = 0;
power = 0;
while (bit != 0){
decimal +=( bit % 10 )*Math.pow(2,power);
power+=1;
bit/= 10;
}
System.out.print((char)decimal);
}
}catch (FileNotFoundException e){
System.out.println("File is not found");
}catch (IOException e){
System.out.println("Problem with file output");
}
}
}
|
Java
|
UTF-8
| 167
| 1.710938
| 2
|
[] |
no_license
|
package ua.artcode.dao;
import ua.artcode.model.User;
/**
* Created by gorobec on 27.11.16.
*/
public interface IUserJsonDao {
boolean saveUser(User user);
}
|
JavaScript
|
UTF-8
| 1,258
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import React, { Fragment, useState, useEffect } from "react"
import { string } from "prop-types"
const DisplayRemainingCharacters = props => {
const { tweet, url, username } = props
const [status, setStatus] = useState("success")
const [urlLength, setUrlLength] = useState(0)
const characterLimit = 280
const tweetLength = tweet.length
const usernameLength = username ? username.length : 0
const charactersRemaining =
characterLimit - tweetLength - urlLength - usernameLength
const debug = false
useEffect(() => {
if (charactersRemaining >= 15) {
setStatus("success")
} else if (charactersRemaining < 15 && charactersRemaining > 0) {
setStatus("warning")
} else {
setStatus("error")
}
if (url.length > 0 && typeof url.length === "number") {
setUrlLength(url.length)
}
})
return (
<Fragment>
<div className={`alert alert--${status} mb-3`}>
remaining characters:
<span className="ml-4p fw-b">{charactersRemaining}</span>
</div>
{debug && (
<div className="debug">
<p>url: {url}</p>
<p>urlLength: {urlLength}</p>
</div>
)}
</Fragment>
)
}
DisplayRemainingCharacters.propTypes = {
tweet: string,
url: string,
username: string,
}
export default DisplayRemainingCharacters
|
Java
|
UTF-8
| 646
| 2.84375
| 3
|
[] |
no_license
|
package com.thirdcc.webapp.utils;
public class FishLevelUtils {
public static final String FIRST_YEAR_FISH_LEVEL = "Junior Fish";
public static final String SECOND_YEAR_FISH_LEVEL = "Senior Fish";
public static final String OLDER_YEAR_FISH_LEVEL = "Elder Fish";
public static String getFishLevelBySemesterStudied(int semesterStudied) {
if (semesterStudied < 0 ) throw new IllegalArgumentException("semester studied cannot be a negative number");
if (semesterStudied < 2) return FIRST_YEAR_FISH_LEVEL;
if (semesterStudied < 4) return SECOND_YEAR_FISH_LEVEL;
return OLDER_YEAR_FISH_LEVEL;
}
}
|
Java
|
UTF-8
| 6,971
| 2.234375
| 2
|
[] |
no_license
|
/*
* Copyright (C) 2017 Joseph Nicklyn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ucss.ui.widgets;
import javafx.css.PseudoClass;
import javafx.scene.layout.Region;
import javafx.scene.control.Separator;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Text;
/**
* An EventItem.
*
* @author Joseph Nicklyn
*/
public class EventItem extends Region implements HelperInterface {
private static final PseudoClass muted = PseudoClass.getPseudoClass("muted");
private static final PseudoClass selected = PseudoClass.getPseudoClass("selected");
private static final PseudoClass focused = PseudoClass.getPseudoClass("focused");
private static final PseudoClass deleteFlagged = PseudoClass.getPseudoClass("fordelete");
private int prefSize = 0;
private int prefPos = 0;
private final Text primaryText = new Text();
private final Text secondaryText = new Text();
private final Separator br = new Separator();
private HPane hPane;
public EventItem() {
init("", "");
}
public EventItem(String text) {
init(text, "");
}
public EventItem(String text, int s, int p, int color) {
setPrefSize(s);
setPrefPosition(p);
init(text, "");
this.setBackgroundColor(color);
}
public EventItem(String primaryText, String secondaryText, int s, int p) {
setPrefSize(s);
setPrefPosition(p);
init(primaryText, secondaryText);
}
private int referenceID = 0;
public final int getReferenceID() {
return referenceID;
}
public final void setReferenceID(int value) {
referenceID = value;
}
private void init(String pText, String sText) {
getChildren().addAll(primaryText, br, secondaryText);
getStyleClass().add("event-item");
primaryText.getStyleClass().add("primary-text");
secondaryText.getStyleClass().add("secondary-text");
setPrimaryText(pText);
setSecondaryText(sText);
setShowSecondaryText(false);
}
public final void setPrimaryText(String value) {
primaryText.setText(value);
}
public final String getPrimaryText() {
return primaryText.getText();
}
public final String getSecondaryText() {
return secondaryText.getText();
}
public final void setSecondaryText(String value) {
secondaryText.setText(value);
}
public final void setShowSecondaryText(boolean value) {
if (secondaryText.getText().isEmpty())
value = false;
secondaryText.setManaged(value);
secondaryText.setVisible(value);
br.setManaged(value);
br.setVisible(value);
requestLayout();
}
public final boolean getShowSecondaryText() {
return secondaryText.isVisible();
}
public final void toggleShowSecondaryText() {
setShowSecondaryText(!secondaryText.isVisible());
}
public final int getPrefSize() {
return prefSize;
}
public final void setPrefSize(int value) {
prefSize = value;
requestLayout();
}
public final int getPrefPosition() {
return prefPos;
}
public final void setPrefPosition(int value) {
prefPos = value;
requestLayout();
}
public final double prefSize(double v) {
return prefSize * v;
}
public final double prefPos(double v) {
return prefPos * v;
}
public final void setSize(double v) {
setWidth(prefSize(v));
}
private boolean waitLayout = false;
@Override public void requestLayout() {
if (waitLayout)
return;
super.requestLayout();
}
@Override public void layoutChildren() {
waitLayout = true;
double innerWidth = getWidth() - (getPadding().getLeft() + getPadding().getRight());
primaryText.setWrappingWidth(innerWidth);
secondaryText.setWrappingWidth(innerWidth);
double y = getPadding().getTop();
double x = getPadding().getLeft();
double h = primaryText.prefHeight(-1);
primaryText.resizeRelocate(x, y, innerWidth, h);
if (secondaryText.isVisible()) {
double h2 = br.prefHeight(-1);
y+= h + 4;
br.resizeRelocate(x, y, innerWidth, h2);
y+=h2 + 4;
h2 = secondaryText.prefHeight(-1);
secondaryText.resizeRelocate(x, y, innerWidth, h2);
y+=h2;
} else {
y += h;
}
y+=getPadding().getBottom();
setHeight(y);
setMinHeight(y);
setPrefHeight(y);
setMaxHeight(y);
this.setNeedsLayout(true);
waitLayout = false;
}
final void setHPane(HPane p) {
hPane = p;
}
public final HPane getHPane() {
return hPane;
}
@Override public String toString() {
return primaryText.getText();
}
public final void setBackgroundColor(int i) {
WidgetHelpers.setBackground(this, WidgetHelpers.pastel60(i), false);
}
public final void setDeleteFlag(boolean value) {
pseudoClassStateChanged(deleteFlagged, value);
}
public final boolean setMuted(boolean value) {
pseudoClassStateChanged(muted, value);
return value;
}
public final void setSelected(boolean value) {
pseudoClassStateChanged(selected, value);
pseudoClassStateChanged(focused, false);
}
public final void setFocus(boolean value) {
pseudoClassStateChanged(selected, false);
pseudoClassStateChanged(focused, value);
}
@Override
public String getHelperInfo(MouseEvent e) {
String r = "EventItem\nThe EventItem is used to \n" +
"display reoccuring events.";
return r;
}
@Override
public void setExtraComments(String value) {
}
}
|
Swift
|
UTF-8
| 1,539
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
//
// CKStatusView.swift
// Browser
//
// Created by Blake Tsuzaki on 5/11/18.
// Copyright © 2018 Modoki. All rights reserved.
//
import UIKit
@IBDesignable class CKStatusView: UIView {
@IBInspectable var message: String = "" {
didSet {
label.text = message
}
}
@IBInspectable var textSize: CGFloat = 16 {
didSet {
label.font = UIFont(name: CKDefaults.fontName, size: textSize)
}
}
var label = CKLabel()
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
private func configure() {
label.leftInset = 4
label.font = UIFont(name: CKDefaults.fontName, size: textSize)
label.textColor = .black
addSubview(label)
}
override func layoutSubviews() {
super.layoutSubviews()
setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
CKDefaults.drawInsetBevel(with: rect)
let lineWidth = CKDefaults.bevelWidth
var contentFrame = CGRect()
contentFrame.origin.x = lineWidth * 2
contentFrame.origin.y = lineWidth * 2
contentFrame.size.height = rect.size.height - lineWidth * 4
contentFrame.size.width = rect.size.width - lineWidth * 4
label.frame = contentFrame
}
}
|
PHP
|
UTF-8
| 4,367
| 2.984375
| 3
|
[] |
no_license
|
<?php
//Map should usually be stored elsewhere, such as in database
$map=array();
$map['1x1']['weight']=1.0;
$map['1x2']['weight']=100.0;
$map['1x3']['weight']=100.0;
$map['1x4']['weight']=100.0;
$map['1x5']['weight']=1.0;
$map['2x1']['weight']=1.0;
$map['2x2']['weight']=100.0;
$map['2x3']['weight']=1.0;
$map['2x4']['weight']=1.0;
$map['2x5']['weight']=1.0;
$map['3x1']['weight']=1.0;
$map['3x2']['weight']=1.0;
$map['3x3']['weight']=100.0;
$map['3x4']['weight']=100.0;
$map['3x5']['weight']=100.0;
$map['4x1']['weight']=100.0;
$map['4x2']['weight']=1.0;
$map['4x3']['weight']=1.0;
$map['4x4']['weight']=1.0;
$map['4x5']['weight']=100.0;
$map['5x1']['weight']=100.0;
$map['5x2']['weight']=1.0;
$map['5x3']['weight']=100.0;
$map['5x4']['weight']=1.0;
$map['5x5']['weight']=1.0;
//Required class
require('class.pathfinder.php');
//---
echo '<p style="font:12px Verdana; color:gray;">With diagonal movement:</p>';
$path=new PathFinder();
$path->setOrigin(1,1); //This is the origin coordinate, aka 1x1
$path->setDestination(5,5); //Destination coordinate
$path->setMap($map);
$result=$path->returnPath(); //returns an array with coordinates (like 1x2 etc)
//This is only for display purposes, I will be checking the array keys to see if the square was walked on or not
$modifiedresult=array_flip($result);
echo '<table>';
for($x=1;$x<=5;$x++){
echo '<tr>';
for($y=1;$y<=5;$y++){
echo '<td style="width:20px;height:20px;background-color:'.(($map[$x.'x'.$y]['weight']==100.0)?'#000080':'#c3daf9').';text-align:center;vertical-align:middle;">';
//marking it with an X if it was included in path or if it was starting position
if(isset($modifiedresult[$x.'x'.$y]) || $x.'x'.$y=='1x1'){
echo 'x';
} else {
echo ' ';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
//---
echo '<p style="font:12px Verdana; color:gray;">Without diagonal movement:</p>';
$path=new PathFinder();
$path->noDiagonalMovement(); //This supresses diagonal movement, only recommended for strict square maps
$path->setOrigin(1,1); //This is the origin coordinate, aka 1x1
$path->setDestination(5,5); //Destination coordinate
$path->setMap($map);
$result=$path->returnPath(); //returns an array with coordinates (like 1x2 etc)
//This is only for display purposes, I will be checking the array keys to see if the square was walked on or not
$modifiedresult=array_flip($result);
echo '<table>';
for($x=1;$x<=5;$x++){
echo '<tr>';
for($y=1;$y<=5;$y++){
echo '<td style="width:20px;height:20px;background-color:'.(($map[$x.'x'.$y]['weight']==100.0)?'#000080':'#c3daf9').';text-align:center;vertical-align:middle;">';
//marking it with an X if it was included in path or if it was starting position
if(isset($modifiedresult[$x.'x'.$y]) || $x.'x'.$y=='1x1'){
echo 'x';
} else {
echo ' ';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
//---
echo '<p style="font:12px Verdana; color:gray;">Continuing from previous destination:</p>';
//You can also continue calculating a new position after the previous solution, in this case it now continues from the last point
$path->setDestination(5,2); //Destination coordinate
$result=$path->returnPath(); //returns an array with coordinates (like 1x2 etc)
//This is only for display purposes, I will be checking the array keys to see if the square was walked on or not
$modifiedresult=array_flip($result);
echo '<table>';
for($x=1;$x<=5;$x++){
echo '<tr>';
for($y=1;$y<=5;$y++){
echo '<td style="width:20px;height:20px;background-color:'.(($map[$x.'x'.$y]['weight']==100.0)?'#000080':'#c3daf9').';text-align:center;vertical-align:middle;">';
//marking it with an X if it was included in path or if it was starting position
if(isset($modifiedresult[$x.'x'.$y]) || $x.'x'.$y=='5x5'){
echo 'x';
} else {
echo ' ';
}
echo '</td>';
}
echo '</tr>';
}
echo '</table>';
//---
echo '<p style="font:12px Verdana; color:gray;">Example printout of path (top) and weight (bottom) arrays:</p>';
echo '<pre>';
print_r($result);
print_r($result=$path->returnWeights()); //this only returns the weights of the last-solved path
echo '</pre>';
?>
|
JavaScript
|
UTF-8
| 2,615
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
////////////
// set up //
////////////
var express = require('express');
var app = express(); // create the app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var port = process.env.PORT || 3000; // set the port
var database = require('./config/database'); // load the db config
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var Sugar = require('sugar'); // date formatting
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
var User = require('./app/models/user');
var Reminder = require('./app/models/reminder');
var Student = require('./app/models/student');
var jwt = require('jsonwebtoken');
var superSecret = 'thisappisgonnabeawesome';
///////////////////
// configuration //
///////////////////
mongoose.connect(database.remoteUrl, function(err) { // connect to our mongoDB database
if(err) {
console.log('Failed connecting to Mongodb!');
} else {
console.log('Successfully connected to Mongodb!');
};
});
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(function(req, res, next) { // configure app to handle cross-origin (CORS) requests
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization');
next();
});
app.use(methodOverride('X-HTTP-Method-Override')); // override with X-HTTP-Method-Override header in request. simulate DELETE/PUT
////////////
// routes //
////////////
require('./app/routes.js')(app); // load routes
///////////////
// start app //
///////////////
// startup our app at http://localhost:3000
app.listen(port);
// shoutout to the user
console.log('Magic happens on port ' + port);
|
Java
|
UTF-8
| 666
| 2.265625
| 2
|
[] |
no_license
|
package it.akademija;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RestServisas {
@Autowired
private ServiceC serviceC;
@RequestMapping("/hello")
String hello() {
return "Hello World!";
}
@RequestMapping("/productsCollection")
String getProductsCollection() {
String text = "";
for (int i = 0; i < serviceC.getProducts().size(); i++) {
text = text + ((Product)serviceC.getProducts().get(i)).getTitle() + " ";
}
return text;
}
}
|
Markdown
|
UTF-8
| 1,842
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
# NVCapSimple_Linux
NVCapSimple is a simple example of capture (preview) software for our "SV series" board and other UVC camera.
This software supports "UYVY" and "YUY2" frame format, but other formats such as MJPG and RGB are not supported.
This example uses v4l2 driver to capture "raw" data of UYVY format and uses OpenCV to display video.
It includes another example to show "RAW10/RAW12 on UYVY" video with converting to monochrome.
# OS
Ubuntu 18.04 LTS (64 bit)
# Build
At first, install v4l-utils etc.
1. sudo apt-get install v4l-utils cmake libx11-dev
Install OpenCV
1. Download the source code from OpenCV web site (http://opencv.org/), then
extract archive and move to the extracted folder.
wget https://github.com/opencv/opencv/archive/3.0.0.zip
unzip 3.0.0.zip
cd opencv-3.0.0/
2. Install build-essential packeage:
sudo apt-get install build-essential
3. Install libraries required for OpenCV:
sudo apt-get install cmake git libgtk2.0-dev pkg-config libavcodec-dev \
libavformat-dev libswscale-dev
4. Install optional libraries internally used from OpenCV:
sudo apt-get install python-dev python-numpy libtbb2 libtbb-dev libjpeg-dev \
libpng-dev libtiff-dev libjasper-dev
5. Create a folder and move into it
mkdir build && cd build
6a. If you want to use Qt generate Makefile with corresponding option:
cmake -D WITH_QT=ON -D WITH_OPENMP=ON ..
6b. If you don't want to use Qt:
cmake -D WITH_OPENMP=ON ..
7. make
8. sudo make install
Then build
1. cd build
2. cmake .. .
3. make
# Usage
NVCapSimple_YUV: show YUV video.
NVCapSimple_RAW10: show RAW10 video in grayscale.
NVCapSimple_RAW12: show RAW12 video in grayscale.
To open device 1 (/dev/video1),
---bash
./NVCapSimple_YUV 1
---
Press key 'q' to quit.
Press key 'i' to toggle info text.
|
C
|
UTF-8
| 1,268
| 2.625
| 3
|
[] |
no_license
|
/*
** EPITECH PROJECT, 2021
** .
** File description:
** .
*/
#include "../include/my_rpg.h"
sound_t *init_one_se(char *filepath)
{
sound_t *se = malloc(sizeof(sound_t));
if (se == NULL)
return (NULL);
se->buffer = sfSoundBuffer_createFromFile(filepath);
if (se->buffer == NULL)
return (NULL);
se->sound = sfSound_create();
sfSound_setBuffer(se->sound, se->buffer);
sfSound_setVolume(se->sound, 20);
return (se);
}
s_effects_t *init_sound_eff(void)
{
s_effects_t *sound_eff = malloc(sizeof(s_effects_t));
if (sound_eff == NULL)
return (NULL);
sound_eff->hurt = init_one_se("bonus/sounds/hurt.ogg");
sound_eff->score = init_one_se("bonus/sounds/Starlight.ogg");
sound_eff->shot_enem = init_one_se("bonus/sounds/switch1.ogg");
sound_eff->item = init_one_se("bonus/sounds/Item1.ogg");
sound_eff->laser = init_one_se("bonus/sounds/laser.ogg");
return (sound_eff);
}
void free_one_se(sound_t *sound)
{
sfSoundBuffer_destroy(sound->buffer);
sfSound_destroy(sound->sound);
}
void free_sound_eff(s_effects_t *se)
{
free_one_se(se->hurt);
free_one_se(se->item);
free_one_se(se->score);
free_one_se(se->shot_enem);
free_one_se(se->laser);
free (se);
}
|
Java
|
ISO-8859-1
| 1,459
| 1.8125
| 2
|
[] |
no_license
|
package senior.erp.componentNames.controladoria;
/**
* @author ilana.sievert
*/
public final class Form640LLMComponentNames {
/**
* Boto <b>Processar</b>
*/
public static final String BT_PROCESSAR = "Processar";
/**
* Boto <b>Excluir</b>
*/
public static final String BT_EXCLUIR = "Excluir";
/**
* Boto <b>Cancelar</b>
*/
public static final String BT_CANCELAR = "Cancelar";
/**
* Boto <b>Sair</b>
*/
public static final String BT_SAIR = "Sair";
/**
* Boto <b>Mostrar</b>
*/
public static final String BT_MOSTRAR = "Mostrar";
/**
* Boto <b>Marcar</b>
*/
public static final String BT_MARCAR = "Marcar";
/**
* Campo <b>Lote</b>
*/
public static final String FD_LOTE = "ENumLot";
/**
* Campo <b>Data Lote</b>
*/
public static final String FD_DATA = "EDatLct";
/**
* Campo <b>Total</b>
*/
public static final String FD_TOTAL = "EVlrTot";
/**
* Campo <b>Total</b>
*/
public static final String FD_LANCAMENTO = "ENumLct";
/**
* Grid <b>Lanamento</b>
*/
public static final String GD_LANCAMENTO = "GridLct";
/**
* Tela <b>Cadastro de Lotes</b>
*/
public static final String FR_NOME = "F640LLM_CCCT";
private Form640LLMComponentNames() {
}
}
|
Markdown
|
UTF-8
| 1,572
| 3.4375
| 3
|
[] |
no_license
|
# Hit-or-Miss
This repository contains the code for a game I made in my Intro to OOP course at Oregon Tech (Fall 2015 - Sophomore Year).
<b>Game Description:</b><br />
The purpose of the game is to use the up arrow key to shoot a rectangle upward while a square moves horizontally across the screen. If the rectangle hits the square, then the player wins the game. If the rectangle is shot 3 times and the square still isn't hit by the rectangle, then the player loses the game.<br />
<b>Technologies:</b><br />
This program was written in C++ using Microsoft Visual Studio 2013. Additionally, the third-party SDL 2.0 library was installed and used in the program to provide a GUI for working with C++.<br />
<b>Execution Instructions:</b><br />
To run this program, one must open this project in Visual Studio and "Start Without Debugging." Please note that the SDL 2.0 library must be installed on the machine and Visual Studio must be told where to find the SDL include directories and SDL library directories.<br />
<b>Screenshots:</b><br />
<img src= "/img/startScreen.PNG" width="500" height="300">
<br />
Beginning screen before the player clicks "Start"
<img src= "/img/movingTarget.PNG" width="500" height="300">
<br />
Moving square target at the top (player has not shot the rectangle at the target)
<img src= "/img/shootingMiss.PNG" width="500" height="300">
<br />
Rectangle shot at the moving square target and missed
<img src= "/img/winningScreen.PNG" width="500" height="300">
<br />
Winning screen when the rectangle hits the moving square target
|
Python
|
UTF-8
| 3,260
| 2.75
| 3
|
[] |
no_license
|
import pandas as pd
import lxml.html as lh
import logging
import argparse
import json
from google.cloud import storage
from google.cloud.storage import Blob
from urllib.request import urlopen, Request
logging.getLogger().setLevel(logging.INFO)
def table_to_dict(tr_elements):
# Create empty list
col = []
i = 0
# For each row, store each first element (header) and an empty list
for t in tr_elements[0]:
i += 1
name = t.text_content().strip()
col.append((name, []))
# Since out first row is the header, data is stored on the second row onwards
for j in range(1, len(tr_elements)):
# T is our j'th row
T = tr_elements[j]
# i is the index of our column
i = 0
# Iterate through each element of the row
for t in T.iterchildren():
data = t.text_content()
# Check if row is empty
if i > 0:
# Convert any numerical value to integers
try:
data = int(data)
except:
pass
# Append the data to the empty list of the i'th column
col[i][1].append(data)
# Increment i for the next column
i += 1
return {title: column for (title, column) in col}
def upload_blob_string(bucket_name, csvString, destination_blob_name):
client = storage.Client()
bucket = client.get_bucket(bucket_name)
blob = Blob(destination_blob_name, bucket)
return blob.upload_from_string(
data=csvString,
content_type='text/csv')
def run(request):
logging.info("Starting ElectricityCertQuotaHistoryLoader")
parser = argparse.ArgumentParser()
parser.add_argument('--data', help='json with parameters')
args = parser.parse_args()
if request is None:
logging.info('run(...): data=' + args.data)
input_json = json.loads(str(args.data).replace("'", ""))
else:
input_json = request.get_json()
logging.info("request.args: {}".format(input_json))
bucket_name = input_json['bucket_target']
reg_url = input_json['url']
destination_blob_name = input_json['destination_blob_name']
logging.info("\nbucket_name: {}\nreg_url: {}\ndestination_blob_name: {}".format(
bucket_name, reg_url, destination_blob_name))
hdr = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
req = Request(url=reg_url, headers=hdr)
html = urlopen(req).read()
doc = lh.fromstring(html)
# Parse data that are stored between <tr>..</tr> of HTML
tr_elements = doc.xpath('//tr')
df = pd.DataFrame(table_to_dict(tr_elements))
csv_string = df.to_csv(index=False, sep=';')
upload_blob_string(bucket_name, csv_string, destination_blob_name)
logging.info("Uploaded size={} to bucket {} and {}".format(df.size, bucket_name, destination_blob_name))
if __name__ == '__main__':
run(None)
|
Python
|
UTF-8
| 639
| 3.484375
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# COPYRIGHT 2017
# ROBERT WOLTERMAN
# MODULE IMPORTS
import pyttsx
import threading
# THIS IS RIDICULOUS
block = threading.Event()
# FUNCTIONS
def say(engine, text):
block.set()
engine.say(text)
engine.runAndWait()
block.clear()
def get_data():
return raw_input("TYPE quit TO EXIT, OTHERWISE ENTER TEXT: ")
# SETUP OUR ENGINE
speaker = pyttsx.init()
# LOOP
dead = False
while not dead:
# GET TEXT
dat = get_data().lower()
if "quit" in dat:
dead = True
else:
while block.isSet():
pass
say(speaker, dat)
print("FINE, I'LL BE DONE TALKING TO YOU")
|
Java
|
UHC
| 1,155
| 2.96875
| 3
|
[] |
no_license
|
public class KiwiJuiceEasy {
public static int[] pouring(int[] capacities, int[] bottles, int[] formId, int[] toId) {
for(int i=0; i<toId.length; i++) {
int left=capacities[i]-bottles[i];
if (left>0) {
left=capacities[i]-bottles[i+1];
capacities[i+1]+=left;
}
else if (left==0) {
;
}
else if (left<0) {
left=bottles[i]-capacities[i];
capacities[i+1]-=left;
}
else{
int allBottles=0;
int allCapacities=0;
for(int j=0; j<bottles.length; j++)
allBottles+=bottles[j];
if (allBottles==0)
break;
for(int j=0; j<capacities.length; j++)
allCapacities+=capacities[j];
if (allCapacities==0)
break;
}
}//for ȣ
return bottles;
}//ҵ ȣ
public static void main(String[] args) {
int[] capacities= {10,10,10,10};
int[] bottles= {8,8,8,8,8};
int[] fromId= {0,1,2,3};
int[] toId= {1,2,3,0};
System.out.println(pouring(capacities, bottles, fromId, toId));
}//mainҵ ȣ
}//Ŭ ȣ
|
C
|
UTF-8
| 14,998
| 3.625
| 4
|
[] |
no_license
|
/*
* File Name : MemoryExc
* Author : KsGin
* Date : 11/07/2017
*/
#include "MemoryExc.h"
/*初始化空闲区,默认为一块,可以指定大小及起始地址*/
struct free_block_type *init_free_block(int mem_size) {
struct free_block_type *fb = (struct free_block_type *) malloc(sizeof(struct free_block_type));
if (fb == NULL) {
printf("No memory error\n");
return NULL;
}
//设置初始化空闲内存块的信息
fb->size = DEFAULT_MEM_SIZE;
fb->start_addr = DEFAULT_MEM_START;
fb->next = NULL;
return fb;
}
/*设置内存的大小*/
int set_mem_size(struct free_block_type* free_block , int *mem_size , int *flag) {
int size;
if (*flag) {
printf("Cannot set memory size again\n");
return 0;
}
printf("Total memory size = ");
scanf("%d", &size);
if (size > 0) {
*mem_size = size;
free_block->size = *mem_size;
}
*flag = 1;
return 1;
}
/*设置分配算法*/
void set_algorithm(int *ma_algorithm , struct free_block_type** free_block) {
int algorithm;
printf("\t1 - Frist Fit \n");
printf("\t2 - Best Fit \n");
printf("\t3 - Worst Fit\n");
scanf("%d", &algorithm);
if (algorithm >= 1 && algorithm <= 3) {
*ma_algorithm = algorithm;
}
//指定算法
rearrange(*ma_algorithm , free_block);
}
/*设置指定算法*/
void rearrange(int algorithm , struct free_block_type** free_block) {
switch (algorithm) {
case MA_FF:
rearrange_FF(free_block);
break;
case MA_BF:
rearrange_BF(free_block);
break;
case MA_WF:
rearrange_WF(free_block);
break;
default:break;
}
}
/*按照FF算法(最先适配法)*/
/*将其按照地址顺序排序*/
void rearrange_FF(struct free_block_type** free_block) {
//只有一个或者没有内存块的时候不需要排序
struct free_block_type* fpt = *free_block;
if (!fpt) return;
struct free_block_type* net = fpt;
if (!net) return;
//根据内存大小排序
while (fpt->next) {
while (net->next) {
if (net->next->start_addr < net->start_addr) {
int tmp = net->size;
net->size = net->next->size;
net->next->size = tmp;
tmp = net->start_addr;
net->start_addr = net->next->start_addr;
net->next->start_addr = tmp;
}
net = net->next;
}
fpt = fpt->next;
net = *free_block;
}
}
/*按照BF算法(最佳适配法)*/
void rearrange_BF(struct free_block_type** free_block) {
//只有一个或者没有内存块的时候不需要排序
struct free_block_type* fpt = *free_block;
if (!fpt) return;
struct free_block_type* net = fpt;
if (!net) return;
//根据内存大小排序
while (fpt->next) {
while (net->next) {
if (net->next->size < net->size) {
int tmp = net->size;
net->size = net->next->size;
net->next->size = tmp;
tmp = net->start_addr;
net->start_addr = net->next->start_addr;
net->next->start_addr = tmp;
}
net = net->next;
}
fpt = fpt->next;
net = *free_block;
}
}
/*按照WF算法(最坏适配法)*/
void rearrange_WF(struct free_block_type** free_block) {
//只有一个或者没有内存块的时候不需要排序
struct free_block_type* fpt = *free_block;
if (!fpt) return;
struct free_block_type* net = fpt;
if (!net) return;
//根据内存大小排序
while (fpt->next) {
while (net->next) {
if (net->next->size > net->size) {
int tmp = net->size;
net->size = net->next->size;
net->next->size = tmp;
tmp = net->start_addr;
net->start_addr = net->next->start_addr;
net->next->start_addr = tmp;
}
net = net->next;
}
fpt = fpt->next;
net = *free_block;
}
}
/*创建新的进程,主要是获取内存的申请数量*/
int new_process(int *pid , struct free_block_type** free_block ,
struct allocated_block** allocated_block_head ,int* mem_size) {
struct allocated_block *ab = (struct allocated_block *) malloc(sizeof(struct allocated_block));
int size;
if (!ab) exit(-5);
ab->next = NULL;
(*pid)++;
sprintf(ab->process_name, "PROCESS-%02d", *pid);
ab->pid = *pid;
printf("Memory for %s:", ab->process_name);
scanf("%d", &size);
if (size > 0) ab->size = size;
int ret = allocate_mem(ab , free_block , mem_size , allocated_block_head , pid); //从空闲区分配内存 ret==1表示OK
//如果此时allocated_block_head尚未赋值 , 则赋值给他
if ((ret == 1) && (*allocated_block_head == NULL)) {
*allocated_block_head = ab;
return 1;
} else if (ret == 1) {
ab->next = *allocated_block_head;
*allocated_block_head = ab;
return 2;
} else if(ret == -1){
printf("Allocation fail\n");
free(ab);
return -1;
}
return 3;
}
/*分配内存模块*/
int allocate_mem(struct allocated_block *ab, struct free_block_type** free_block , int *mem_size , struct allocated_block** allocated_block_head , int *pid){
//根据当前算法在空闲分区链表中搜索合适空闲分区进行分配,分配时注意以下情况:
// 1. 找到可满足空闲分区且分配后剩余空间足够大,则分割
// 2. 找到可满足空闲分区且但分配后剩余空间比较小,则一起分配
// 3. 找不可满足需要的空闲分区但空闲分区之和能满足需要,则采用内存紧缩技术,进行空闲分区的合并,然后再分配
// 4. 在成功分配内存后,应保持空闲分区按照相应算法有序
// 5. 分配成功则返回1,否则返回-1
struct free_block_type *fpt , *pre;
int request_size = ab->size;
fpt = pre = *free_block;
/*DO SOMETHING*/
while (fpt) {
if (fpt->size >= request_size) { //找到可满足空闲分区
if (fpt->size - request_size >= MIN_SLICE) { //分配后足够大
ab->start_addr = fpt->start_addr;
//分割内存
fpt->size -= request_size;
fpt->start_addr += request_size;
} else {
ab->size = fpt->size;
ab->start_addr = fpt->start_addr;
//修复空闲分区链表
if(*free_block == fpt){
*free_block = fpt->next;
} else {
pre->next = fpt->next;
}
}
*mem_size -= ab->size; //减少mem_size
return 1;
}
pre = fpt;
fpt = fpt->next;
}
if(!fpt){//fpt == null 表示没有找到需要的内存块,此时需要进行内存紧缩技术
if(*mem_size >= ab->size){
if(*mem_size - ab->size >= MIN_SLICE){
free_memory_rearrage(*mem_size-ab->size, ab->size, free_block, mem_size, pid, allocated_block_head);
}else {
free_memory_rearrage(0, ab->size, free_block, mem_size, pid, allocated_block_head);
}
return 0;
}
}
//没内存了
return -1;
}
/*删除进程,归还分配的存储空间,并删除描述该进程内存分配的节点*/
void kill_process(int ma_algorithm , struct allocated_block **allocated_block_head , int* mem_size, struct free_block_type** free_block){
struct allocated_block *ab;
int pid;
printf("Kill Process , pid = ");
scanf("%d" , &pid);
ab = find_process(pid , *allocated_block_head);
if(ab){
free_mem(ab , ma_algorithm , mem_size , free_block); /*释放ab所表示的分配区*/
dispose(ab , allocated_block_head); /*释放ab数据结构节点*/
}
}
/*将ab所表示的已分配区归还,并进行可能的合并*/
int free_mem(struct allocated_block *ab, int ma_algorithm , int* mem_size , struct free_block_type** free_block){
struct free_block_type *fpt , *pre , *work;
fpt=(struct free_block_type*)malloc(sizeof(struct free_block_type));
if(!fpt) return -1;
/*DO SOMETHING*/
*mem_size += ab->size; //free_mem 增加
fpt->size = ab->size;
fpt->start_addr = ab->start_addr;
fpt->next = NULL;
//按FF分配
rearrange(MA_FF , free_block);
pre = NULL;
work = *free_block;
if (!work) {
*free_block = fpt;
return 1;
}
//插入空闲链表头部
if(fpt->start_addr < work->start_addr){
if (!work) {
*free_block = fpt; //free_block为空时
}else{
fpt->next = *free_block;
*free_block = fpt;
work = fpt->next;
if (fpt->start_addr + fpt->size == work->start_addr) { //如果两块地址相连,则合并
fpt->size += work->size;
fpt->next = work->next;
free(work);
}
}
} else {
//查找插入位置
while((work!=NULL)&&(fpt->start_addr>work->start_addr))
{
pre=work;
work=work->next;
}
if (!work) { //此时插入末尾
pre->next = fpt;
if (pre->start_addr + pre->size == fpt->start_addr) {
pre->size += fpt->size;
pre->next = NULL;
free(fpt);
}
} else { //找到了合适的位置,work地址大于fpt , pre地址小于fpt ,则插入两者之间
fpt->next = work;
pre->next = fpt;
if (pre->start_addr + pre->size == fpt->start_addr
&& fpt->start_addr + fpt->size == work->start_addr) { //插入之后三个地址相连,合并三个区块
pre->size += fpt->size + work->size;
pre->next = work->next;
free(fpt);
free(work);
} else if(pre->start_addr + pre->size == fpt->start_addr){ //只与前边相连
pre->size += fpt->size;
pre->next = fpt->next;
free(fpt);
} else if(fpt->start_addr + fpt->size == work->start_addr){ //只与后边相连
fpt->size += work->size;
fpt->next = work->next;
free(work);
}
}
}
rearrange(ma_algorithm , free_block); //按照所选算法分配
return 1;
}
/*释放数据结构节点*/
int dispose(struct allocated_block *free_ab , struct allocated_block **allocated_block_head){
struct allocated_block *pre , *ab;
if (free_ab == *allocated_block_head) { //释放第一个节点
*allocated_block_head = (*allocated_block_head)->next;
free(free_ab);
return 1;
}
pre = *allocated_block_head;
ab = (*allocated_block_head)->next;
while (ab != free_ab) {
pre = ab;
ab = ab->next;
}
pre->next = ab->next;
free(ab);
return 2;
}
/*显示当前的内存使用情况*/
int display_mem_usage(struct free_block_type* free_block , struct allocated_block* allocated_block_head){
struct free_block_type *fpt = free_block;
struct allocated_block *ab = allocated_block_head;
// if(fpt == NULL) return -1;
printf("-------------------------------------------------------\n");
/*显示空闲区*/
printf("Free memory:\n");
printf("%20s %20s\n" , " Start_addr" , "size");
while (fpt) {
printf("%20d %20d\n" , fpt->start_addr , fpt->size);
fpt = fpt->next;
}
/*显示已分配区*/
printf("\nUsed Memory:\n");
printf("%10s %20s %10s %10s\n" , "Pid" , "Process Name" , " start_addr" , "size");
while (ab) {
printf("%10d %20s %10d %10d\n" , ab->pid , ab->process_name , ab->start_addr , ab->size);
ab = ab->next;
}
printf("--------------------------------------------------------\n");
return 0;
}
/*根据pid寻找进程*/
struct allocated_block* find_process(int pid , struct allocated_block *allocated_block_head){
struct allocated_block *p = allocated_block_head;
while(p)
{
if(p->pid==pid)
return p;
p=p->next;
}
return p;
}
/*显示菜单*/
void display_menu(){
printf("\n");
printf("1 - Set memory size(defualt = %d)\n" , DEFAULT_MEM_SIZE);
printf("2 - Select memory allocation algroithm\n");
printf("3 - New process \n");
printf("4 - Terminate a process \n");
printf("5 - Display memory usage \n");
printf("0 - Exit\n");
}
//内存紧缩处理
/*内存紧缩:将各个占用分区向内存一端移动,然后将各个空闲分区合并成为一个空闲分区。*/
void free_memory_rearrage(int memory_reduce_size,int allocated_size ,
struct free_block_type** free_block ,
int* mem_size , int* pid,
struct allocated_block** allocated_block_head){
struct free_block_type *p1,*p2;
struct allocated_block *a1,*a2;
if(memory_reduce_size!=0) //分配完还有小块空间
{
p1=*free_block;
p2=p1->next;
p1->start_addr=0;
p1->size=memory_reduce_size;
p1->next=NULL;
*mem_size=memory_reduce_size; //
}
else
{
p2=*free_block;
free_block=NULL;
mem_size=0;
}
while(p2!=NULL)//释放节点
{
p1=p2;
p2=p2->next;
free(p1);
}
//allocated_block 重新修改链接
a1=(struct allocated_block *)malloc(sizeof(struct allocated_block));
a1->pid=*pid;
a1->size=allocated_size;
a1->start_addr=memory_reduce_size; //已申请的开始地址,从memory_reduce_size开始
sprintf(a1->process_name, "PROCESS-%02d", *pid);
a1->next=*allocated_block_head;
a2=*allocated_block_head;
*allocated_block_head=a1;
while(a2!=NULL)
{
a2->start_addr=a1->start_addr+a1->size;
a1=a2;
a2=a2->next;
}
}
void do_exit(struct free_block_type** free_block , struct allocated_block** allocated_block_head){
struct free_block_type *p1,*p2;
struct allocated_block *a1,*a2;
p1=*free_block;
if(p1!=NULL)
{
p2=p1->next;
for(;p2!=NULL;p1=p2,p2=p2->next)
{
free(p1);
}
free(p1);
}
a1=*allocated_block_head;
if(a1!=NULL)
{
a2=a1->next;
for(;a2!=NULL;a1=a2,a2=a2->next)
{
free(a1);
}
free(a1);
}
}
|
Markdown
|
UTF-8
| 601
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
# sentdebot
Code for Sentdebot in the Sentdex discord channel (discord.gg/sentdex)
Pull requests welcome for just about anything.
The "style" of using methods to interact with sentdebot should be retained.
sentdebot.search("text here") vs !search text here.
I understand this goes against the main method of making discord bots and commands, but I like interacting my way better :)
Code is messy, or as our resident coding expert sysadmin full stack dev Scoot puts it: "Ugly."
Everything you see on init commit was written in 1 pass to just make it work. Feel free to clean up as you wish.
|
Java
|
UTF-8
| 807
| 2.96875
| 3
|
[] |
no_license
|
package pl.softie.homeworks.course2;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class Exercise18 {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("key1", "val1");
map.put("key2", "val2");
map.put("key3", "val3");
map.put("key4", "val4");
map.put("key5", "val5");
Map<String, String> notModified = Map.of(
"key1", "val1",
"key2", "val2",
"key3", "val3",
"key4", "val4",
"key5", "val5"
);
displayKeys(map);
displayKeys(notModified);
}
public static void displayKeys(Map<String, String> map) {
System.out.println(map.keySet());
}
}
|
C++
|
UTF-8
| 257
| 2.8125
| 3
|
[] |
no_license
|
#include "11050.h"
int factorial(int num) {
if (num <= 1) return 1;
else return num * factorial(num - 1);
}
void nojam11050::solution()
{
int n, k;
scanf("%d %d", &n, &k);
printf("%d", (int)(factorial(n) / (int)(factorial(k) * factorial(n - k))));
}
|
C++
|
WINDOWS-1252
| 1,260
| 2.640625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
// Copyright Robert Spangenberg, 2014.
// See license.txt for more details
#pragma once
#include "StereoCommon.h"
template <typename T>
class MyImage {
public:
MyImage() :m_data(NULL)
, m_width(0)
, m_height(0)
{};
MyImage(uint32 width, uint32 height) :
m_width(width)
, m_height(height)
{
m_data = (T*)_mm_malloc(width*height*sizeof(T), 16);
};
MyImage(uint32 width, uint32 height, T* data) :m_data(data)
, m_width(width)
, m_height(height)
{};
~MyImage()
{
if (m_data != NULL)
_mm_free(m_data);
}
void setAttributes(uint32 width, uint32 height, T* data)
{
m_width = width;
m_height = height;
m_data = data;
}
uint32 getWidth()
{
return m_width;
}
uint32 getHeight()
{
return m_height;
}
T* getData()
{
return m_data;
}
private:
T* m_data;
uint32 m_width;
uint32 m_height;
};
template <typename T>
void readPGM(MyImage<T>& img, const char* filename);
template <typename T>
void writePGM(MyImage<T>& img, const char* filename, bool verbose);
#include "MyImage.hpp"
|
JavaScript
|
UTF-8
| 2,554
| 2.65625
| 3
|
[] |
no_license
|
'use strict';
import { doHttpRequest } from '../../modules/httpRequest';
import { checkHeightBody } from '../../modules/checkHeight';
import { getTweetWordCount } from '../../modules/wordCount';
import { removeHideClassButton, addHideClassButton, displayProfile, hideProfile } from '../../modules/hideShowMethods';
import { addTweetToFeeds } from '../../modules/addTweet';
document.addEventListener( 'DOMContentLoaded', () => {
console.log('DOMContentLoaded event fired');
/// Custom front page textarea to show hided buttons
let textAreaBodyIndex = document.querySelector( '.textarea-js' );
let hidedButtons = document.querySelector('.textareaSection-js');
function handleRemoveHideClass() {
removeHideClassButton( textAreaBodyIndex, hidedButtons );
}
function handleAddHideClass() {
addHideClassButton( textAreaBodyIndex, hidedButtons );
}
// Loading infinite scroll
function handleLoadInfiniteScroll () {
let checkHeight = checkHeightBody( navigator );
if ( checkHeight ) {
doHttpRequest();
}
}
// adding new tweet
function onClickHandler() {
let textAreaParent = this.parentNode.parentNode.parentNode.parentNode;
let textArea = textAreaParent.querySelector( '.textareaElement-js' ); // more than ugly
let textAreaValue = textArea.value;
addTweetToFeeds( textAreaValue );
textArea.value = '';
if ( textAreaParent.querySelector( '.textarea-js' ) !== null ) {
handleAddHideClass();
} else {
textAreaParent.querySelector('a[rel="modal:close"]').click();
}
Array.from( document.querySelectorAll('.displayProfile-js') ).forEach( (outerEl) => {
outerEl.addEventListener( 'mouseover', displayProfile );
outerEl.addEventListener( 'mouseout', hideProfile );
});
}
// Adding event listeners to elements
Array.from( document.querySelectorAll( '.textareaButton-js' ) ).forEach( (item) => {
item.addEventListener('click', onClickHandler);
});
Array.from( document.querySelectorAll('.displayProfile-js') ).forEach( (outerEl) => {
outerEl.addEventListener( 'mouseover', displayProfile );
outerEl.addEventListener( 'mouseout', hideProfile );
});
Array.from(document.querySelectorAll( '.textareaElement-js' )).forEach( (el) => {
el.addEventListener( 'keyup', getTweetWordCount );
});
document.addEventListener( 'scroll', handleLoadInfiniteScroll );
textAreaBodyIndex.addEventListener( 'focus', handleRemoveHideClass );
textAreaBodyIndex.addEventListener( 'blur', handleAddHideClass );
});
|
C#
|
UTF-8
| 2,933
| 2.578125
| 3
|
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using Xamarin.Forms;
namespace Plugin.Controls.SegmentedControl
{
public class SegmentedControl : View, IViewContainer<SegmentedControlOption>
{
private static readonly string ItemsSourcePropertyName = "ItemsSource";
public static readonly BindableProperty ItemsSourceProperty =
BindableProperty.Create(ItemsSourcePropertyName, typeof(IEnumerable), typeof(SegmentedControl), null, propertyChanged: ItemsSourcePropertyChanged);
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public IList<SegmentedControlOption> Children { get; set; }
public SegmentedControl()
{
Children = new List<SegmentedControlOption>();
}
public event ValueChangedEventHandler ValueChanged;
public delegate void ValueChangedEventHandler(object sender, EventArgs e);
public static readonly BindableProperty SelectedSegmentProperty = BindableProperty.Create("SelectedSegment", typeof(int), typeof(SegmentedControl), 0);
public int SelectedSegment
{
get { return (int)GetValue(SelectedSegmentProperty); }
set { SetValue(SelectedSegmentProperty, value); }
}
private string _selectedText;
public string SelectedText
{
get
{
return _selectedText;
}
set
{
_selectedText = value;
if (ValueChanged != null)
ValueChanged(this, EventArgs.Empty);
}
}
public static readonly BindableProperty TintColorProperty = BindableProperty.Create("TintColor", typeof(Color), typeof(SegmentedControl), Color.FromHex("#007AFF"));
public Color TintColor
{
get { return (Color)GetValue(TintColorProperty); }
set { SetValue(TintColorProperty, value); }
}
private static void ItemsSourcePropertyChanged(BindableObject bindableObject, object oldValue, object newValue)
{
var control = (SegmentedControl)bindableObject;
//if (control.Children != null)
// control.Children.Clear();
control.Children = (IList<SegmentedControlOption>)newValue;
}
}
public class SegmentedControlOption : View
{
public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(string), typeof(SegmentedControlOption), string.Empty);
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
}
|
Python
|
UTF-8
| 241
| 2.859375
| 3
|
[] |
no_license
|
# 럭키 스트레이트
N = input()
left = 0
for i in range(len(N)//2):
left += int(N[i])
right = 0
for i in range(len(N)//2,len(N)):
right += int(N[i])
if left == right:
print('LUCKY')
else:
print('READY')
# 123402
# 7755
|
C++
|
UTF-8
| 631
| 2.75
| 3
|
[] |
no_license
|
/*problem link: https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1048
input:
1
3
4
60
70
50
2
output:
1
2
3
3
4
27
4
I have solved this using the noob way as the time limit was in favour. Sort and get the median*/
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll i,j,k,m,n,t;
vector<ll>v;
while(cin>>n)
{
v.push_back(n);
sort(v.begin(),v.end());
if(v.size()%2!=0)
cout<<v[v.size()/2]<<endl;
else
{
k=v.size()/2;
ll med = (v[k]+v[k-1])/2;
cout<<med<<endl;
}
}
}
//Audity Ghosh
|
Java
|
UTF-8
| 720
| 2.25
| 2
|
[] |
no_license
|
package ba.unsa.etf.dms.data.auth;
import com.google.gson.annotations.SerializedName;
/**
* Created by Hugsby on 12/25/17.
*/
public class AuthData {
@SerializedName("username")
private String username;
@SerializedName("password")
private String password;
public AuthData(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
Python
|
UTF-8
| 1,710
| 2.65625
| 3
|
[] |
no_license
|
from itertools import product
from itertools import combinations
from dictionary import BaiduChineseWordDictionary, NULL_STORAGE
from search import search
chars = '窄踏碎织纱衫乞著愁询陶醉企权颠势凭职呈屈攻撤威衰滔途旋竖纹弦纤催促披娇恰齿柴杏焦躁汁' \
'禁茂旺昌咏眠赠宣眨饮浆递陆彼托帆辰均裹胶栽拣磨介绍肤摩律损逐渐痕迹征隐蔽侦莫乏滥赞审' \
'刘恨案套遵挨摄述援社捐款返贫魔择毅慰尚膜恢康聋遗签昔践宗旨旬抚源燃章凶脱逃逗端措悟控' \
'漠敏陷储蓄营维枕撒扩范符合甚染寸倍繁殖植蒸浮聚冈漫岭盐泽宜碍彻罗盯贯武奴置乃炼钢斜诵' \
'腾驾陡朴素滋庭狂歇赢惯拥恒欲旦恐徒魂乳凤咽脂膏泣敲叙蚊扰稀叮嘱搜'
char_list = list(chars)
word_list = product(char_list, repeat=2)
word_list = list(word_list)
# word_list = ['发疯', '幸福', '羡慕', '慷慨', '受宠若惊']
usefull_words = []
# bd_dic = BaiduChineseWordDictionary()
n = 0
m = 0
total = len(word_list)
for w in word_list:
m += 1
word = w[0] + w[1]
result = search(word)
print('\n')
print('正在判断第{}/{}个二字词: '.format(m,total) + word + '.....')
if result['释义']:
n += 1
print('\n^-^-^-^-^-^-^-^-^-^-^')
print('哈哈!找到第{}个双生词:'.format(n) + word)
print(result)
print('-'*20)
usefull_words.append(word)
print('-'*200)
print('共找到{}个符合条件的双生词!'.format(len(usefull_words)))
print(usefull_words)
with open('/home/xiaozi/文档/双生词.txt', 'w') as f:
f.write(str(usefull_words))
|
PHP
|
UTF-8
| 1,062
| 3.125
| 3
|
[] |
no_license
|
<?php
abstract class base{
protected $table='';
protected function lord(){
try{
$pdo_object= new PDO('mysql:host=localhost;dbname=object2;charset=utf8','imabe','ppu');
}
catch(PDOException $Exception){
die('接続に失敗しました:'.$Exception->getMessage());
}
$select="select * from $this->table";
$query=$pdo_object->prepare($select);
$query->execute();
$result=$query->fetchall(PDO::FETCH_ASSOC);
$pdo_object=NULL;
return $result;
}
public function show(){
global $result;
foreach($result as $value){foreach($value as $key => $value){echo $key.$value;}echo '<br>';
}
}
}
class Human extends base{
function __construct(){
$this->table='hito';
}
function test(){
global $table;
$result = parent::lord();
return $result;
}
}
class Station extends base{
function __construct(){
$this->table='eki';
}
function test(){
global $table;
$result = parent::lord();
return $result;}
}
$human= new Human();
$result= $human->test();
$human->show();
$eki= new Station();
$result= $eki->test();
$eki->show();
|
C
|
UTF-8
| 396
| 3
| 3
|
[] |
no_license
|
#include<stdio.h>
#include<string.h>
void main()
{
int
int length = 0;
char s[500];
printf("Enter the string");
gets(s);
length = strlen(s);
for(int i=0;i<length;i++)
{
if((s[i] == (int)NULL )||(s[i] == ''))
{
printf("\n");
}
else
{
printf("%d",s[i]);
}
//getch();
}
}
|
Java
|
UTF-8
| 4,446
| 2.734375
| 3
|
[] |
no_license
|
package articlecreator.gui;
/**
* Copyright 1999-2002 Matthew Robinson and Pavel Vorobiev.
* All Rights Reserved.
*
* ===================================================
* This program contains code from the book "Swing"
* 1st Edition by Matthew Robinson and Pavel Vorobiev
* http://www.spindoczine.com/sbe
* ===================================================
*
* The above paragraph must be included in full, unmodified
* and completely intact in the beginning of any source code
* file that references, copies or uses (in any way, shape
* or form) code contained in this file.
*/
// Authors: Matthew Robinson and Pavel Vorobiev.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
class OpenList extends JPanel implements ListSelectionListener, ActionListener
{
protected JLabel m_title;
protected JTextField m_text;
protected JList m_list;
protected JScrollPane m_scroll;
public OpenList(String[] data, String title) {
setLayout(null);
m_title = new JLabel(title, JLabel.LEFT);
add(m_title);
m_text = new JTextField();
m_text.addActionListener(this);
add(m_text);
m_list = new JList(data);
m_list.setVisibleRowCount(4);
m_list.addListSelectionListener(this);
m_scroll = new JScrollPane(m_list);
add(m_scroll);
}
public OpenList(String title, int numCols) {
setLayout(null);
m_title = new JLabel(title, JLabel.LEFT);
add(m_title);
m_text = new JTextField(numCols);
m_text.addActionListener(this);
add(m_text);
m_list = new JList();
m_list.setVisibleRowCount(4);
m_list.addListSelectionListener(this);
m_scroll = new JScrollPane(m_list);
add(m_scroll);
}
public void setSelected(String sel) {
m_list.setSelectedValue(sel, true);
m_text.setText(sel);
}
public String getSelected() { return m_text.getText(); }
public void setSelectedInt(int value) {
setSelected(Integer.toString(value));
}
public int getSelectedInt() {
try {
return Integer.parseInt(getSelected());
}
catch (NumberFormatException ex) { return -1; }
}
public void valueChanged(ListSelectionEvent e) {
Object obj = m_list.getSelectedValue();
if (obj != null)
m_text.setText(obj.toString());
}
public void actionPerformed(ActionEvent e) {
ListModel model = m_list.getModel();
String key = m_text.getText().toLowerCase();
for (int k=0; k<model.getSize(); k++) {
String data = (String)model.getElementAt(k);
if (data.toLowerCase().startsWith(key)) {
m_list.setSelectedValue(data, true);
break;
}
}
}
public void addListSelectionListener(ListSelectionListener lst) {
m_list.addListSelectionListener(lst);
}
public Dimension getPreferredSize() {
Insets ins = getInsets();
Dimension d1 = m_title.getPreferredSize();
Dimension d2 = m_text.getPreferredSize();
Dimension d3 = m_scroll.getPreferredSize();
int w = Math.max(Math.max(d1.width, d2.width), d3.width);
int h = d1.height + d2.height + d3.height;
return new Dimension(w+ins.left+ins.right,
h+ins.top+ins.bottom);
}
public Dimension getMaximumSize() {
Insets ins = getInsets();
Dimension d1 = m_title.getMaximumSize();
Dimension d2 = m_text.getMaximumSize();
Dimension d3 = m_scroll.getMaximumSize();
int w = Math.max(Math.max(d1.width, d2.width), d3.width);
int h = d1.height + d2.height + d3.height;
return new Dimension(w+ins.left+ins.right,
h+ins.top+ins.bottom);
}
public Dimension getMinimumSize() {
Insets ins = getInsets();
Dimension d1 = m_title.getMinimumSize();
Dimension d2 = m_text.getMinimumSize();
Dimension d3 = m_scroll.getMinimumSize();
int w = Math.max(Math.max(d1.width, d2.width), d3.width);
int h = d1.height + d2.height + d3.height;
return new Dimension(w+ins.left+ins.right,
h+ins.top+ins.bottom);
}
public void doLayout() {
Insets ins = getInsets();
Dimension d = getSize();
int x = ins.left;
int y = ins.top;
int w = d.width-ins.left-ins.right;
int h = d.height-ins.top-ins.bottom;
Dimension d1 = m_title.getPreferredSize();
m_title.setBounds(x, y, w, d1.height);
y += d1.height;
Dimension d2 = m_text.getPreferredSize();
m_text.setBounds(x, y, w, d2.height);
y += d2.height;
m_scroll.setBounds(x, y, w, h-y);
}
public void disable( boolean b ) {
if ( b ) {
m_text.setEnabled( false );
m_list.setEnabled( false );
}
else {
m_text.setEnabled( true );
m_list.setEnabled( true );
}
}
}
|
Swift
|
UTF-8
| 547
| 2.796875
| 3
|
[] |
no_license
|
//
// Coordinator.swift
// Metaweather
//
// Created by Bassuni on 18/06/2021.
//
import UIKit
protocol Coordinator : class {
var navigationController: UINavigationController { get }
var childCoordinators: [Coordinator] { get set }
func start()
}
extension Coordinator {
func addCoordinator(coordinator : Coordinator) {
childCoordinators.append(coordinator)
}
func removeCoordinator(coordinator : Coordinator) {
childCoordinators = childCoordinators.filter({$0 !== coordinator})
}
}
|
C++
|
GB18030
| 1,092
| 2.875
| 3
|
[] |
no_license
|
///*
//201833
//,double
//*/
//
//#include<iostream>
//#include<vector>
//#include<stdio.h>
//using namespace std;
//
//const double LIMIT = 1e-2;
//const double MIN_VALUE = 0;
//
//int n, k;
//vector<double> rec(10000);
//
//bool Check(const double &len) {
// int num = 0;
//
// if (len == 0) return false;
// for (int i = 0; i < n; i++)
// num += rec[i] / len;
//
// if (num >= k) return true;
// else return false;
//}
//
//double Floor(const double &len) {
// return floor(len * 100) / 100;
//}
//
//int main() {
// cin >> n >> k;
// for (int i = 0; i < n; i++)
// cin >> rec[i];
//
// double lvalue = MIN_VALUE, rvalue = MIN_VALUE, midvalue;
// for (int i = 0; i < n; i++)
// if (rec[i] > rvalue) rvalue = rec[i];
//
// while (rvalue - lvalue > LIMIT) {
// midvalue = (lvalue + rvalue) / 2;
// if (Check(midvalue))
// lvalue = midvalue;
// else
// rvalue = midvalue;
// }
//
// double ans = Floor(lvalue);
// if (Check(ans + 0.01)) ans += 0.01;
//
// printf("%.2lf\n", ans);
// return 0;
//}
|
Java
|
UTF-8
| 6,058
| 2.390625
| 2
|
[] |
no_license
|
package github.com.suitelhy.dingding.core.infrastructure.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import javax.validation.constraints.NotNull;
/**
* A chunk of data restricted by the configured {@link Pageable}.
*
* @Description 支持 RPC 框架的序列化及其通过反射注入对象的方式.
*
* @Editor Suite
*
* @author Oliver Gierke
* @author Christoph Strobl
* @since 1.8
*
* @see org.springframework.data.domain.Chunk
*/
public abstract class Chunk<T>
implements Slice<T>, Serializable {
private static final long serialVersionUID = 867755909294344406L;
/*private*/protected final @NotNull List<T> content = new ArrayList<>(0);
/*private*/protected @NotNull Pageable pageable;
/**
* Creates a new {@link Chunk} with the given content and the given governing {@link Pageable}.
*
* @param content must not be {@literal null}.
* @param pageable must not be {@literal null}.
*/
public Chunk(List<T> content, Pageable pageable) {
Assert.notNull(content, "Content must not be null!");
Assert.notNull(pageable, "Pageable must not be null!");
this.content.addAll(content);
/*this.pageable = pageable;*/
this.pageable = PageRequest.of(pageable.getPageNumber()
, pageable.getPageSize()
, pageable.getSort());
}
/**
* (Constructor)
*
* @Description 用于序列化和反序列化.
*/
protected Chunk() {
this.pageable = Pageable.unpaged();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#getNumber()
*/
public int getNumber() {
return /*pageable.isPaged()*/! isEmpty()
? pageable.getPageNumber()
: 0;
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#getSize()
*/
public int getSize() {
return /*pageable.isPaged()*/! isEmpty()
? pageable.getPageSize()
: content.size();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#getNumberOfElements()
*/
public int getNumberOfElements() {
return content.size();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#hasPrevious()
*/
public boolean hasPrevious() {
return getNumber() > 0;
}
/**
* 判断 {@linkplain Chunk 调用者} 是否合法.
*
* @return {@linkplain Boolean#TYPE 判断结果}
*/
public boolean isEmpty() {
return null == this.pageable
|| ! this.pageable.isPaged();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#isFirst()
*/
public boolean isFirst() {
return ! hasPrevious();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#isLast()
*/
public boolean isLast() {
return ! hasNext();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#nextPageable()
*/
public Pageable nextPageable() {
return hasNext()
? pageable.next()
: Pageable.unpaged();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#previousPageable()
*/
public Pageable previousPageable() {
return hasPrevious()
? pageable.previousOrFirst()
: Pageable.unpaged();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#hasContent()
*/
public boolean hasContent() {
return ! content.isEmpty();
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#getContent()
*/
public List<T> getContent() {
return Collections.unmodifiableList(content);
}
/*
* (non-Javadoc)
* @see org.springframework.data.domain.Slice#getSort()
*/
@Override
public /*org.springframework.data.domain.Sort*/Sort getSort() {
/*return pageable.getSort();*/
return ! isEmpty()
? pageable.getSort()
: /*org.springframework.data.domain.Sort*/Sort.unsorted();
}
/*
* (non-Javadoc)
* @see java.lang.Iterable#iterator()
*/
public Iterator<T> iterator() {
return content.iterator();
}
/**
* Applies the given {@link Function} to the content of the {@link Chunk}.
*
* @param converter must not be {@literal null}.
*
* @return
*/
protected <U> List<U> getConvertedContent(Function<? super T, ? extends U> converter) {
Assert.notNull(converter, "Function must not be null!");
return this.stream()
.map(converter::apply)
.collect(Collectors.toList());
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
}
if (! (obj instanceof Chunk<?>)) {
return false;
}
Chunk<?> that = (Chunk<?>) obj;
boolean contentEqual = this.content.equals(that.content);
boolean pageableEqual = this.pageable.equals(that.pageable);
return contentEqual && pageableEqual;
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int result = 17;
result += 31 * pageable.hashCode();
result += 31 * content.hashCode();
return result;
}
//===== Getter Method =====//
@Override
public @NotNull Pageable getPageable() {
return ! isEmpty()
? pageable
: Pageable.unpaged();
}
}
|
C#
|
UTF-8
| 982
| 2.71875
| 3
|
[
"Apache-2.0"
] |
permissive
|
using Demo.Core.Models;
using Demo.Mediatr.CommandLine.Models;
using MediatR;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Demo.Mediatr.CommandLine.Services
{
public class CustomerChargeService
{
private readonly IAsyncRequestHandler<GetCustomerChargeExactMatchRequest, GetCustomerChargeExactMatchResponse> _repository;
public CustomerChargeService(IAsyncRequestHandler<GetCustomerChargeExactMatchRequest, GetCustomerChargeExactMatchResponse> repository)
{
_repository = repository;
}
public async Task<GetCustomerChargeExactMatchResponse> GetExactMatches(List<CustomerCharge> charges)
{
//NOTE - This is an example of passing in an IQuery<T> to specify how to gather data. This can be a normal query, OData query, or stored procedure, etc.
return await _repository.Handle(new GetCustomerChargeExactMatchRequest { Charges = charges });
}
}
}
|
Python
|
UTF-8
| 1,552
| 2.78125
| 3
|
[
"Apache-2.0"
] |
permissive
|
import os
import sys
from os import path
def get_operational_system():
"""
Check which user's operating system
"""
os = sys.platform
if sys.platform == "linux":
return "Linux"
elif sys.platform == "win32":
return "Windows"
elif sys.platform == "darwin":
return "MacOS"
elif sys.platform == "freebsd8":
return "FreeBSD"
def check_version_python():
"""
Checks whether the version of python installed on the system is compatible
"""
if sys.version_info >= (3,6):
return True
else:
return False
def check_python_compile():
"""
Checks python3 path location
"""
env_name = os.environ.get("ENV_NAME")
message_env = f"Creating virtual environment {env_name}"
if get_operational_system() == "Linux" and check_version_python() == True:
if path.exists("/usr/bin/python3") == True:
print(message_env)
os.system(f"python3 -m venv {env_name}")
else:
print(message_env)
os.system(f"python -m venv {env_name}")
elif get_operational_system() == "Windows" and check_version_python() == True:
print(message_env)
os.system(f"python -m venv {env_name}")
elif get_operational_system() == "MacOS" and check_version_python() == True:
print(message_env)
os.system(f"python -m venv {env_name}")
elif check_version_python == False:
print('The python version is not supported. Rony is compatible with the version of >= Python 3.6')
|
Java
|
UTF-8
| 195
| 2.28125
| 2
|
[] |
no_license
|
package com.designpattern.facade;
/**
* Created by Administrator on 2015/4/22.
*/
public class SubSystem2 {
public void methodTwo(){
System.out.println("this is method2");
}
}
|
Java
|
UTF-8
| 533
| 2.71875
| 3
|
[] |
no_license
|
package producer_consumer;
/**
* Created by codew on 2018/1/23.
*/
// 消费者
public class NVProducer implements Runnable{
private NVShareResource resource = null;
public NVProducer(NVShareResource resource)
{
this.resource = resource;
}
@Override
public void run() {
for (int i = 0; i < 50; i++) {
if (i % 2 == 0){
resource.push("韦小宝", "男");
}else {
resource.push("貂蝉", "女");
}
}
}
}
|
C
|
UTF-8
| 276
| 2.890625
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include "linkedlist.h"
int main(int argc, const char * argv[]){
int i;
struct list_node *list;
list = NULL;
for (i = 0; i < 10; i++){
list = append(list, i);
fprint_list(stdout, list, "->");
printf("\n");
}
return 0;
}
|
Java
|
UTF-8
| 4,728
| 1.945313
| 2
|
[] |
no_license
|
package com.tencent.mm.plugin.appbrand.widget.e;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tencent.matrix.trace.core.AppMethodBeat;
public final class d extends FrameLayout {
public static final int jjZ = Color.parseColor("#000000");
public static final int jka = Color.parseColor("#000000");
public static final int jkk = Color.parseColor("#000000");
private float bDv = 0.0f;
private float bDw = 0.0f;
private TextView jkj;
private int jkl;
private int jkm;
private int jkn;
private int jko;
public int x = 0;
public int y = 0;
static {
AppMethodBeat.i(51274);
AppMethodBeat.o(51274);
}
public d(Context context) {
super(context);
AppMethodBeat.i(51265);
setLayoutParams(new LayoutParams(-2, -2));
this.jkj = new TextView(context);
this.jkj.setLayoutParams(new LinearLayout.LayoutParams(-2, -2));
addView(this.jkj);
AppMethodBeat.o(51265);
}
public final void x(int i, int i2, int i3, int i4) {
AppMethodBeat.i(51266);
GradientDrawable gradientDrawable = new GradientDrawable();
gradientDrawable.setCornerRadius((float) i);
gradientDrawable.setStroke(i2, i3);
gradientDrawable.setColor(i4);
this.jkj.setBackgroundDrawable(gradientDrawable);
AppMethodBeat.o(51266);
}
public final void setText(String str) {
AppMethodBeat.i(51267);
this.jkj.setText(str);
AppMethodBeat.o(51267);
}
public final void setTextSize(int i) {
AppMethodBeat.i(51268);
this.jkj.setTextSize((float) i);
AppMethodBeat.o(51268);
}
public final void setTextColor(int i) {
AppMethodBeat.i(51269);
this.jkj.setTextColor(i);
AppMethodBeat.o(51269);
}
public final void setTextPadding(int i) {
AppMethodBeat.i(51270);
this.jkj.setPadding(i, i, i, i);
AppMethodBeat.o(51270);
}
public final void setGravity(String str) {
AppMethodBeat.i(51271);
if (str.equals("left")) {
this.jkj.setGravity(3);
AppMethodBeat.o(51271);
} else if (str.equals("right")) {
this.jkj.setGravity(5);
AppMethodBeat.o(51271);
} else {
str.equals("center");
this.jkj.setGravity(17);
AppMethodBeat.o(51271);
}
}
public final void setX(int i) {
this.x = i;
}
public final void setY(int i) {
this.y = i;
}
public final float getAnchorX() {
return this.bDv;
}
public final float getAnchorY() {
return this.bDw;
}
/* Access modifiers changed, original: protected|final */
public final void onMeasure(int i, int i2) {
AppMethodBeat.i(51272);
super.onMeasure(i, i2);
this.jkl = getMeasuredWidth();
this.jkm = getMeasuredHeight();
if ((-this.jkl) < this.x && this.x < 0) {
this.jkn = this.jkl;
this.bDv = ((float) Math.abs(this.x)) / (((float) this.jkl) * 1.0f);
} else if (this.x >= 0) {
this.jkn = this.jkl + Math.abs(this.x);
this.bDv = 0.0f;
} else {
this.jkn = Math.abs(this.x);
this.bDv = 1.0f;
}
if ((-this.jkm) < this.y && this.y < 0) {
this.jko = this.jkm;
this.bDw = ((float) Math.abs(this.y)) / (((float) this.jkm) * 1.0f);
} else if (this.y >= 0) {
this.jko = this.jkm + Math.abs(this.y);
this.bDw = 0.0f;
} else {
this.jko = Math.abs(this.y);
this.bDw = 1.0f;
}
setMeasuredDimension(this.jkn, this.jko);
AppMethodBeat.o(51272);
}
/* Access modifiers changed, original: protected|final */
public final void onLayout(boolean z, int i, int i2, int i3, int i4) {
AppMethodBeat.i(51273);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) getChildAt(0).getLayoutParams();
if (this.x >= 0 && this.y >= 0) {
layoutParams.gravity = 85;
} else if (this.x >= 0 && this.y <= 0) {
layoutParams.gravity = 53;
} else if (this.x <= 0 && this.y >= 0) {
layoutParams.gravity = 83;
} else if (this.x <= 0 && this.y <= 0) {
layoutParams.gravity = 51;
}
super.onLayout(z, i, i2, i3, i4);
AppMethodBeat.o(51273);
}
}
|
PHP
|
UTF-8
| 5,845
| 2.734375
| 3
|
[] |
no_license
|
<?php
class BrandsController extends AppController {
public $name = 'Brands';
public $uses = array('Brand', 'ItemType', 'ItemCategory');
public function beforeFilter()
{
AppController::beforeFilter();
// Basic setup
$this->Auth->authenticate = array('Form');
// Pass settings in
$this->Auth->authenticate = array(
'Form' => array('userModel' => 'User')
);
// Check user login session
if(sizeof($this->activeUser) <= 0)
{
$this->Session->setFlash('Sorry! The login session expires, Please check and try again','default',array('class' =>'alert alert-danger'),'bad');
$this->redirect(array('controller'=>'admins','action'=>'logout'));
}
}
// Objective : This function displays all the Brands
public function index() {
// Get all item types
$brands = $this -> Brand -> find('all');
$this -> set('brands', $brands);
// Set the view variables to controller variable values and layout for the view
$this -> set('page_title', 'View Item Types');
$this -> layout = 'base_layout';
}
// Objective : This function adds the Brand
public function add() {
if ($this -> request -> is('post')) {
// Get the data from post request
$brand = $this -> request -> data;
// Add item type
if ($this -> Brand -> save($brand)) {
// Display success message and redirect
$this->Session->setFlash('New brand added.', 'default', array('class' => 'alert alert-success') , 'success');
$this -> redirect(array('controller' => 'brands', 'action' => 'index'));
} else {
// Display failure message and redirect
$this->Session->setFlash('Sorry, an error occurred.', 'default', array('class' => 'alert alert-danger') , 'error');
$this -> redirect(array('controller' => 'brands', 'action' => 'index'));
}
}
// Get item types
$itemTypes = $this -> ItemType -> find('list', array('order' => 'ItemType.name ASC'));
$this -> set('item_types', $itemTypes);
// Set the view variables to controller variable values and layout for the view
$this -> set('page_title', 'Add Brand');
$this -> layout = 'base_layout';
}
// Objective : This function saves the edited brand
public function edit($id=null) {
// Check whether it is a post request or not
if ($this -> request -> is('post')) {
// Get the data from post request
$brand = $this -> request -> data;
// Save item category
if ($this -> Brand -> save($brand)) {
// Display success message and redirect
$this->Session->setFlash('Selected brand edited.', 'default', array('class' => 'alert alert-success') , 'success');
$this -> redirect(array('controller' => 'brands', 'action' => 'index'));
} else {
// Display failure message and redirect
$this->Session->setFlash('Sorry, an error occurred.', 'default', array('class' => 'alert alert-danger') , 'error');
$this -> redirect(array('controller' => 'brands', 'action' => 'index'));
}
} else{
// Check whether ID is null, if yes - redirect to index
if($id == null){
$this->Session->setFlash('Please choose a item type.', 'default', array('class' => 'alert alert-danger') , 'error');
$this -> redirect(array('controller' => 'brands', 'action' => 'index'));
}
// Fetch the item type by id
$selected = $this->Brand->findById($id);
$this->set('selected',$selected);
// Get item types
$itemTypes = $this -> ItemType -> find('list', array('order' => 'ItemType.name ASC'));
$this -> set('item_types', $itemTypes);
// Set the view variables to controller variable values and layout for the view
$this -> set('page_title', 'Edit');
$this -> layout = 'base_layout';
}
}
/*
// Objective : This function deletes the brand
// Author : Ishan Sheth
// Last Edit : 28/4/2014
*/
public function delete($id=null) {
// Check whether ID is null, if yes - redirect to index
if($id == null){
// Display failure message and redirect
$this->Session->setFlash('Please choose an item type.', 'default', array('class' => 'alert alert-danger') , 'error');
$this -> redirect(array('controller' => 'item_categories', 'action' => 'index'));
}
// Delete selected item category
if($this->Brand->delete($id)) {
// Display success message and redirect
$this->Session->setFlash('Item type deleted.', 'default', array('class' => 'alert alert-success') , 'success');
$this -> redirect(array('controller' => 'brands', 'action' => 'index'));
}
else {
// Display failure message and redirect
$this->Session->setFlash('Sorry, an error occurred.', 'default', array('class' => 'alert alert-danger') , 'error');
$this -> redirect(array('controller' => 'brands', 'action' => 'index'));
}
}
// call by ajax for get sub categories
public function get_sub_categories($id = null) {
$this->layout = 'ajax_layout';
$categories = $this->ItemCategory->find('list', array('conditions' => array('ItemCategory.item_type_id' => $id), 'fields' => array('ItemCategory.id', 'name'), 'order' => 'ItemCategory.sort_order'));
$this->set('item_categories', $categories);
}
}
?>
|
Python
|
UTF-8
| 554
| 3.1875
| 3
|
[] |
no_license
|
def inv(k, p):
if k == 0:
raise ZeroDivisionError('division by zero')
if k < 0:
# k ** -1 = p - (-k) ** -1 (mod p)
return p - inv(-k, p)
# Extended Euclidean algorithm.
s, old_s = 0, 1
t, old_t = 1, 0
r, old_r = p, k
while r != 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient * t
gcd, x, y = old_r, old_s, old_t
assert gcd == 1
assert (k * x) % p == 1
return x % p
|
JavaScript
|
UTF-8
| 2,712
| 3.859375
| 4
|
[] |
no_license
|
const statusDisplay = document.querySelector(".game--status");
let gameActive=true;
let currentPlayer= "X";
let gameState= ["", "", "", "", "", "", "", "", ""];
const winningMessage = () => `Player ${currentPlayer} has won`;
const drawMessage = () => `Game ended in a draw`;
const currentPlayerTurn = () => `It's ${currentPlayer}'s turn`;
statusDisplay.innerHTML = currentPlayerTurn();
function handlePlayerChanged(){
currentPlayer = currentPlayer === "X" ? "O" : "X";
statusDisplay.innerHTML = currentPlayerTurn();
}
function handleCellPlayed(clickedCell,clickedCellIndex){
gameState[clickedCellIndex]=currentPlayer;
clickedCell.innerHTML=currentPlayer;
}
const winningConditions=[
[0,1,2],
[3,4,5],
[6,7,8],
[0,3,6],
[1,4,7],
[2,5,8],
[0,4,8],
[2,4,6]
]
function handleResultValidation(){
let roundWon = false;
//Check for each winning condition
for(let i=0; i<winningConditions.length; i++){
const winningCondition=winningConditions[i];
let a= gameState[winningCondition[0]];
let b= gameState[winningCondition[1]];
let c= gameState[winningCondition[2]];
if(a === "" || a === "" || a === ""){
continue;
}
if(a ===b && b===c){
roundWon= true;
break;
}
}
if(roundWon){
statusDisplay.innerHTML = winningMessage();
gameActive=false;
return;
}
//handle draw condition
let roundDraw=!gameState.includes("");
if(roundDraw){
statusDisplay.innerHTML= drawMessage();
gameActive=false;
return;
}
handlePlayerChanged();
}
function handleCellClick(clickedCellEvent) {
const clickedCell = clickedCellEvent.target;
const clickedCellIndex = parseInt(
clickedCell.getAttribute("data-cell-index")
);
if(gameState[clickedCellIndex] !== "" || !gameActive){
return;
}
//if everthing is fine
//change the state of cell
// check if somebody won after that click
handleCellPlayed(clickedCell, clickedCellIndex);
handleResultValidation();
}
function handleRestartGame() {
gameActive=true;
currentPlayer="X";
gameState=["", "", "", "", "", "", "", "", ""];
statusDisplay.innerHTML=currentPlayerTurn();
document.querySelectorAll(".cell").forEach((cell) => (cell.innerHTML=""));
}
document
.querySelectorAll(".cell")
.forEach((cell)=> cell.addEventListener("click", handleCellClick));
document
.querySelector(".game--restart")
.addEventListener("click",handleRestartGame);
|
C#
|
UTF-8
| 1,347
| 2.59375
| 3
|
[
"MIT"
] |
permissive
|
using UnityEngine;
using UnityEngine.UI;
using Zenject;
using FSM.GameManager.States;
namespace FSM.GameManager
{
public class GameManager : MonoBehaviour
{
private GameStateFactory _gameStateFactory;
private GameStateEntity _gameStateEntity = null;
[SerializeField]
private GameState _currentGameState;
[SerializeField]
private GameState _previousGameState;
public Text stateText;
[Inject]
public void Construct(GameStateFactory gameStateFactory)
{
_gameStateFactory = gameStateFactory;
}
private void Start()
{
ChangeState(GameState.Menu);
}
/// <summary>
/// Changes the game state
/// </summary>
/// <param name="gameState">The state to transition to</param>
internal void ChangeState(GameState gameState)
{
if (_gameStateEntity != null)
{
_gameStateEntity.Dispose();
_gameStateEntity = null;
}
_previousGameState = _currentGameState;
_currentGameState = gameState;
stateText.text = gameState.ToString();
_gameStateEntity = _gameStateFactory.CreateState(gameState);
_gameStateEntity.Start();
}
}
}
|
Java
|
UTF-8
| 1,649
| 2.578125
| 3
|
[] |
no_license
|
package com.hydra.project.provider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.swt.graphics.Image;
import com.hydra.project.model.MyPropertyItem;
public class PropertyTableLabelProvider implements ITableLabelProvider{
@Override
public Image getColumnImage(Object element, int columnIndex) {
if (element instanceof MyPropertyItem){
return getImage(element, columnIndex);
}
return null;
}
@Override
public String getColumnText(Object element, int columnIndex) {
MyPropertyItem myPropertyItem =(MyPropertyItem) element;
switch (columnIndex){
case 0: return myPropertyItem.getProperty();
case 1: return myPropertyItem.getValue();
// case 2: return myPropertyItem.getImage();
}
return null;
}
@Override
public void addListener(ILabelProviderListener listener) {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
@Override
public boolean isLabelProperty(Object element, String property) {
// TODO Auto-generated method stub
return false;
}
@Override
public void removeListener(ILabelProviderListener listener) {
// TODO Auto-generated method stub
}
public Image getImage(Object element, int columnIndex) {
Image image = null; // hole den Namen des Bildes
if (element instanceof MyPropertyItem){
MyPropertyItem myPropertyItem =(MyPropertyItem) element;
switch (columnIndex){
case 0: image = myPropertyItem.getImage();break;
}
}
return image;
}
}
|
C++
|
UTF-8
| 870
| 3.9375
| 4
|
[] |
no_license
|
#include <iostream>
using namespace std;
void check(float angle_1, float angle_2, float angle_3);
int main(void){
float angle_1;
float angle_2;
float angle_3;
cout<<"Enter the three numbers as space separated integers"<<endl;
cin>>angle_1>>angle_2>>angle_3;
check(angle_1, angle_2, angle_3);
}
void check(float angle_1, float angle_2, float angle_3){
if(angle_1+angle_2+angle_3!=180){
cout<<"The angles given aren't of a triangle"<<endl;
}
else{
if(angle_1==angle_2 && angle_2==angle_3){
cout<<"Equilateral triangle"<<endl;
}
else if((angle_1==angle_2 && angle_2!=angle_3) || (angle_1==angle_3 && angle_3!=angle_2) || (angle_2==angle_3 && angle_3!=angle_1)){
cout<<"Isoceles triangle"<<endl;
}
else{
cout<<"Scalene triangle"<<endl;
}
if(angle_3==90 || angle_2==90 || angle_1==90){
cout<<"Right angled triangle"<<endl;
}
}
}
|
Python
|
UTF-8
| 825
| 3.34375
| 3
|
[
"MIT"
] |
permissive
|
import requests
while True:
pokemon = input("which pokemon do you want to choose?")
pokemon = pokemon.lower()
url = f"https://pokeapi.co/api/v2/pokemon/{pokemon}"
req = requests.get(url)
if req.status_code == 200 :
data = req.json()
print(f"Name is\t\t{data['name']}")
print("version:\n\n")
for application in data['game_indices']:
print(application['version']['name'])
print("Abilities:\n\n")
for ability in data['abilities']:
print(ability['ability']['name'])
print("Moves:\n\n")
for move in data['moves']:
print(move['move']['name'])
print("Types:\n\n")
for types in data['types']:
print(types['type']['name'])
else:
print("Pokemon not found")
|
Python
|
UTF-8
| 295
| 2.515625
| 3
|
[] |
no_license
|
import requests
import re
username ='natas1'
password = 'gtVrDuiDfck831PqWsLEZy5gyDz1clto'
url = 'http://%s.natas.labs.overthewire.org/' %username
responce=requests.get(url, auth = (username, password))
content = responce.text
print (content)
print (re.findall('<!--The password for natas2 is (.*) -->',content)[0])
|
C#
|
UTF-8
| 1,450
| 2.6875
| 3
|
[
"MS-PL"
] |
permissive
|
using System;
namespace SysadminsLV.PKI.Dcom {
/// <summary>
/// Contains enumeration of ADCS Certification Authority roles
/// <para>This enumeration has a <see cref="FlagsAttribute"/> attribute that allows a bitwise combination of its member values.</para>
/// </summary>
[Flags]
public enum AdcsOfficerRole {
/// <summary>
/// Caller has no roles on CA server.
/// </summary>
None = 0,
/// <summary>
/// Caller has CA administrator rights on CA server.
/// </summary>
Administrator = 1,
/// <summary>
/// Caller has CA officer rights on CA server.
/// </summary>
Officer = 2,
/// <summary>
/// Caller has rights to manage audit settings on CA server.
/// </summary>
Auditor = 4,
/// <summary>
/// Caller has operator rights on CA server.
/// </summary>
Operator = 8,
/// <summary>
/// Utility value used to mask management and client rights.
/// </summary>
MaskRoles = 0xff,
/// <summary>
/// Caller has read permissions on CA server and can read CA configuration details.
/// </summary>
Reader = 0x100,
/// <summary>
/// Caller has permissions to enroll certificates on CA server.
/// </summary>
Enroller = 0x200
}
}
|
Python
|
UTF-8
| 1,611
| 3.34375
| 3
|
[] |
no_license
|
import numpy as np
import scipy.misc as msc
import scipy.ndimage as img
# function used to read intensity images.
def readIntensityImage(filename):
f = msc.imread(filename, flatten=True).astype('float')
return f
# function to generate and save intensity images.
def writeIntensityImage(f,filename):
msc.toimage(f, cmin = 0, cmax = 255).save(filename+'x'+filename + '.jpg')
# Returns a normalized 2D gauss kernel array for convolutions
def createGaussianKernel(size, sigma):
x =np.arange(size)
g1D = np.exp(-0.5 * ((x-size/2) / sigma)**2)
g1D = g1D / g1D.sum()
kernel = np.outer(g1D, g1D)
return kernel / kernel.sum()
# applying gaussian filter
def applyGaussianFilter(image):
return img.gaussian_filter(image, sigma = 3)
# This function displays the intensity image in new figure window.
def showImage(a):
msc.toimage(a,cmin=0,cmax=255).show()
def main():
inputImg2 = readIntensityImage('clock.jpg') #read the image as 2D array
size = input("enter size of kernel (for example 3, 5, etc): ")
sigma = (size - 1.0) / (2.0 * 2.575)
kernel = createGaussianKernel(size, sigma)
dx, dy = np.gradient(kernel)
convolutionGradDx = img.convolve(inputImg2, dx, mode='constant', cval=0.0)
convolutionGradDy = img.convolve(inputImg2, dy, mode='constant', cval=0.0)
gradImg = np.sqrt(np.square(convolutionGradDx) + np.square(convolutionGradDy))
showImage(gradImg)
#writeIntensityImage(gradImg, str(size) + 'clock')
if __name__ == '__main__': # boilerplate code to invoke main()
main()
|
C#
|
UTF-8
| 4,734
| 2.96875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kalender
{
class Program
{
static void Main()
{
Console.Write("C:> ");
string Eingabe_des_Nutzer = Console.ReadLine();
string[] Getrente_Eingabe_des_Nutzers = Trenung(Eingabe_des_Nutzer);
Console.Write(Monat(Eingabe_des_Nutzer)); Console.WriteLine(Getrente_Eingabe_des_Nutzers[2]);
Console.WriteLine(Kalender_of_Duty(Eingabe_des_Nutzer));
//cal(Eingabe_des_Nutzer);
//return Eingabe_des_Nutzer;
Console.ReadLine();
}
internal static string[] Trenung(string Eingabe)
{
string[] eingabentrennung = new string[5];
Eingabe = Eingabe + " ";
eingabentrennung[0] = Eingabe.Substring(0, Eingabe.IndexOf(" "));
Eingabe = Eingabe.Substring(Eingabe.IndexOf(" ") + 1);
Eingabe = Eingabe + " ";
eingabentrennung[1] = Eingabe.Substring(0, Eingabe.IndexOf(" "));
Eingabe = Eingabe.Substring(Eingabe.IndexOf(" ") + 1);
Eingabe = Eingabe + " ";
eingabentrennung[2] = Eingabe.Substring(0, Eingabe.IndexOf(" "));
Eingabe = Eingabe.Substring(Eingabe.IndexOf(" ") + 1);
Eingabe = Eingabe + " ";
eingabentrennung[3] = Eingabe.Substring(0, Eingabe.IndexOf(" "));
Eingabe = Eingabe.Substring(Eingabe.IndexOf(" ") + 1);
string[] getrente_eingabe = eingabentrennung;
return getrente_eingabe;
}
internal static string Monat(string Eingabe)
{
string Monat;
var Eingabe_des_Benutzers = Eingabe;
if (Trenung(Eingabe_des_Benutzers)[1] == "1")
{ Monat = "Januar "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "2")
{ Monat = "Februar "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "3")
{ Monat = "März "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "4")
{ Monat = "April "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "5")
{ Monat = "Mai "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "6")
{ Monat = "Juni "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "7")
{ Monat = "Juli "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "8")
{ Monat = "August "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "9")
{ Monat = "September "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "10")
{ Monat = "Oktober "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "11")
{ Monat = "November "; }
else if (Trenung(Eingabe_des_Benutzers)[1] == "12")
{ Monat = "Dezember "; }
else
{
Monat = "";
}
return Monat;
}
internal static string Kalender_of_Duty(string Eingabe_des_Benutzers)
{
//var Eingabe_des_Benutzers = Program.Eingabe();
string Wochentage;
if (Trenung(Eingabe_des_Benutzers)[3] == "Montag")
{
Wochentage = "Mo Di Mi Do Fr Sa So";
return Wochentage;
}
else if (Trenung(Eingabe_des_Benutzers)[3] == "Dienstag")
{
Wochentage = "Di Mi Do Fr Sa So Mo";
return Wochentage;
}
else if (Trenung(Eingabe_des_Benutzers)[3] == "Mittwoch")
{
Wochentage = "Mi Do Fr Sa So Mo Di";
return Wochentage;
}
else if (Trenung(Eingabe_des_Benutzers)[3] == "Donnerstag")
{
Wochentage = "Do Fr Sa So Mo Di Mi";
return Wochentage;
}
else if (Trenung(Eingabe_des_Benutzers)[3] == "Freitag")
{
Wochentage = "Fr Sa So Mo Di Mi Do";
return Wochentage;
}
else if (Trenung(Eingabe_des_Benutzers)[3] == "Samstag" || Trenung(Eingabe_des_Benutzers)[3] == "Sonabend")
{
Wochentage = "Sa So Mo Di Mi Do Fr";
return Wochentage;
}
else if (Trenung(Eingabe_des_Benutzers)[3] == "Sontag")
{
Wochentage = "So Mo Di Mi Do Fr Sa";
return Wochentage;
}
else
{
Wochentage = "Mo Di Mi Do Fr Sa So";
}
return Wochentage;
}
}
}
|
Python
|
UTF-8
| 2,722
| 2.609375
| 3
|
[] |
no_license
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
print("Content-Type: text/html\r\n\r\n")
utf8stdout = open(1, 'w', encoding='utf-8', closefd=False)
with open('../htmls/template.html', 'r', encoding='utf-8') as file:
s = file.read()
print(s.format('Detalle Avistamiento', '''
<div class="caracteristicas">
<ul class="lista" id="listaDetalles">
<h5> Vale decir que en mi archivo db.py esta la consulta que retorna toda la info necesaria. <br>
Esta info logre obtenerla desde la lista, pero me falto la parte de poder mandarla a esta visualizacion <br>
Tengo la idea de hacer un JSON, mandarlo al handler de las filas, y que este se lo mande al .py que <br>
despliega esta pagina, pero me falto tiempo para hacerlo porque tuve un problema que me duro <br>
como 4 dias y al final nunca le encontre solucion y tuve que hacer todo el submit denuevo :( <br>
Perdon por tan poco, me organize mal en la semana de receso</h5>
<li class="elemento">
Contacto: <br>
<ul>
<li class="lineaInformacion">
Nombre: Aqui va el nombre
</li>
<li class="lineaInformacion">
Mail: Aqui va el mail
</li>
<li class="lineaInformacion">
Numero: Aqui va el numero
</li>
</ul>
</li>
<li class="elemento">
Lugar: <br>
<ul>
<li class="lineaInformacion">
Region: Aqui va la region
</li>
<li class="lineaInformacion">
Comuna: Aqui va la comuna
</li>
<li class="lineaInformacion">
Sector: Aqui va el sector
</li>
</ul>
</li>
<li class="elemento">
Avistamiento: <br>
<ul>
<li class="lineaInformacion">
Tipo: Aqui va el tipo
</li>
<li class="lineaInformacion">
Estado: Aqui va el estado
</li>
<li class="lineaInformacion">
Dia y Hora: Aqui va dia y hora
</li>
<li class="lineaInformacion">
Fotos: Aqui van las fotos
</li>
</ul>
</li>
</ul>
</div>
<div class="botones">
<button id="volverAListado" class="boton" onclick="location.href='./listadoAvistamientos.py';">Volver a Lista
</button>
<button id="volverAPortada" class="boton" onclick="location.href='./index.py';">Volver a Portada</button>
</div>
''', ''), file=utf8stdout)
|
Java
|
UTF-8
| 1,335
| 2.109375
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.google.common.base;
import java.io.Serializable;
// Referenced classes of package com.google.common.base:
// Function, Functions, Preconditions, Supplier
private static class <init>
implements Function, Serializable
{
private static final long serialVersionUID = 0L;
private final Supplier supplier;
public Object apply(Object obj)
{
return supplier.get();
}
public boolean equals(Object obj)
{
if (obj instanceof supplier)
{
obj = (supplier)obj;
return supplier.equals(((supplier) (obj)).supplier);
} else
{
return false;
}
}
public int hashCode()
{
return supplier.hashCode();
}
public String toString()
{
String s = String.valueOf(String.valueOf(supplier));
return (new StringBuilder(s.length() + 13)).append("forSupplier(").append(s).append(")").toString();
}
private (Supplier supplier1)
{
supplier = (Supplier)Preconditions.checkNotNull(supplier1);
}
supplier(Supplier supplier1, supplier supplier2)
{
this(supplier1);
}
}
|
C#
|
UTF-8
| 362
| 3.09375
| 3
|
[] |
no_license
|
using static System.Console;
public abstract class Element
{
public Element(int x, int y)
{
X = x;
Y = y;
}
public int X { get; set; }
public int Y { get; set; }
public abstract void Prepare(Game game);
public abstract void Draw(Game game);
public void HomeCursor()
{
SetCursorPosition(X, Y);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.