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
|
|---|---|---|---|---|---|---|---|
PHP
|
UTF-8
| 2,013
| 2.640625
| 3
|
[] |
no_license
|
<?php
/**
* EGroupware - Benno Mail Archive
*
* @link http://www.egroupware.org
* @author Ralf Becker <rb@egroupware.org>
* @package archive
* @copyright (c) 2013-19 by Ralf Becker <rb@egroupware.org>
* @license http://opensource.org/licenses/gpl-license.php GPL - GNU General Public License
*/
use EGroupware\Api;
use EGroupware\Api\Egw;
/**
* Hooks for Benno Mail Archive
*/
class archive_hooks
{
/**
* Get archive configuratione either from regular EGroupware configuration or if not set from archive/setup/setup.inc.php
*
* Also called from "site configuration" to set defaults.
*
* @return array with values for keys "archive_url" and "archive_auth"
*/
static function config()
{
if (!($config = Api\Config::read('archive')) || empty($config['archive_url']) || empty($config['archive_auth']))
{
$setup_info = array();
include EGW_SERVER_ROOT.'/archive/setup/setup.inc.php';
foreach(array(
'archive_url' => $setup_info['archive']['url'],
'archive_auth' => $setup_info['archive']['auth'],
) as $name => $value)
{
if (empty($config[$name]))
{
Api\Config::save_value($name, $config[$name] = $value, 'archive');
}
}
}
return $config;
}
/**
*
* @return array
*/
public static function csp_frame_src()
{
$config = self::config();
$frm_srcs = array();
if (($host = parse_url($config['archive_url'], PHP_URL_HOST)))
{
$frm_srcs[] = $host;
}
return $frm_srcs;
}
/**
* hooks to build Archive's sidebox-menu plus the admin and preferences sections
*
* @param string/array $args hook args
*/
static function all_hooks($args)
{
$location = is_array($args) ? $args['location'] : $args;
if ($GLOBALS['egw_info']['user']['apps']['admin'])
{
$file = Array(
'Site Configuration' => Egw::link('/index.php','menuaction=admin.admin_config.index&appname=archive'),
);
if ($location == 'admin')
{
display_section('archive',$file);
}
else
{
display_sidebox('archive',lang('Archive'),$file);
}
}
}
}
|
Java
|
UTF-8
| 841
| 1.914063
| 2
|
[] |
no_license
|
package com.slusarz.pokerafterdark.application.game;
import com.slusarz.pokerafterdark.domain.game.GameId;
import com.slusarz.pokerafterdark.domain.game.GameType;
import com.slusarz.pokerafterdark.domain.player.Host;
import com.slusarz.pokerafterdark.domain.pot.Pot;
import lombok.NonNull;
import lombok.Value;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
@Value(staticConstructor = "of")
public class GameProjection {
@Valid
@NonNull
private GameId gameId;
@NonNull
private GameActions actions;
@NonNull
private GameType gameType;
@Valid
@NonNull
private Host host;
@Valid
@NonNull
private LocalDate date;
@Valid
@NonNull
private Pot pot;
@Valid
@NonNull
private List<ParticipantProjection> participantProjections;
}
|
Java
|
UTF-8
| 6,397
| 3.03125
| 3
|
[] |
no_license
|
package yodafunkta;
import static java.util.Arrays.asList;
import static yodafunkta.Functor.f;
import static yodafunkta.Functor.functor;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import junit.framework.TestCase;
public class FunctorTest extends TestCase {
private static final Functor odd = functor("odd");
private static boolean odd(int number) {
return number % 2 == 1;
}
private static final Functor length = f("length");
private static int length(String string) {
return string == null ? 0 : string.length();
}
private static final Functor greaterThan = f("greaterThan");
private static final Functor greaterThan4 = f("greaterThan", 4);
private static boolean greaterThan(int length, String string) {
return string != null && string.length() > length;
}
private static final Functor between = f("between");
private static final Functor between2and = f("between", 2);
private static boolean between(Integer min, int max, Integer target) {
return min < target && target < max;
}
private static final Functor sum = f("sum");
private static int sum(int a, int b) {
return a + b;
}
private static final Functor join = f("join");
private static String join(String a, String b) {
return a + ", " + b;
}
private static String join(int a, int b) {
return String.valueOf(a) + String.valueOf(b);
}
private static final Functor intGenerator = f("intGenerator");
private static int intGenerator(int i) {
return i + 1;
}
public void testRun() throws Exception {
assertEquals(1, length.run("a"));
assertEquals(4, length.run("test"));
}
public void testDeclareOnTheFlyAndRun() throws Exception {
Functor myOwnLength = f("length");
assertEquals(1, myOwnLength.run("a"));
assertEquals(4, f("length").run("test"));
}
public void testEvaluate() throws Exception {
assertFalse(greaterThan.evaluate(4, "Test"));
assertTrue(greaterThan.evaluate(3, "Test"));
}
public void testMapping() throws Exception {
List<String> list = asList("this", "is", "a", "test");
assertEquals(asList(4, 2, 1, 4), length.map(list));
assertEquals(asList(3, 7, 4), length.map("yet", "another", "test"));
}
public void testFilter() throws Exception {
List<Integer> list = asList(1, 2, 3, 4, 5, 6);
assertEquals(asList(1, 3, 5), odd.filter(list));
assertEquals(asList(3, 5, 11, 13), odd.filter(2, 4, 3, 5, 6, 8, 11, 12, 13));
}
public void testCurrying() throws Exception {
assertTrue(greaterThan4.evaluate("Testa"));
assertFalse(greaterThan4.evaluate("Test"));
Functor greaterThan3 = f("greaterThan", 3);
assertTrue(greaterThan3.evaluate("Testa"));
assertTrue(greaterThan3.evaluate("Test"));
assertTrue(between.evaluate(2, 5, 3));
assertFalse(between.evaluate(2, 5, 6));
assertTrue(between2and.evaluate(5, 3));
assertFalse(between2and.evaluate(5, 6));
Functor between2and5 = between2and.param(5);
assertTrue(between2and5.evaluate(3));
assertFalse(between2and5.evaluate(6));
}
public void testCombine() throws Exception {
assertTrue((Boolean) odd.of(length).run("another"));
assertFalse(odd.of(length).<Boolean>run("test"));
}
public void testCurryingCombine() throws Exception {
Functor between2and5OfLength = between.params(2, 5).of(length);
assertEquals(asList("this", "yet", "test"), between2and5OfLength.filter("this", "is", "yet", "another", "test"));
}
public void testFoldLeft() throws Exception {
assertEquals(15, (int) sum.foldLeft(0, asList(1, 2, 3, 4, 5)));
assertEquals(15, (int) (Integer) sum.foldLeft(asList(1, 2, 3, 4, 5)));
assertEquals("this, is, a, test", join.fold("this", "is", "a", "test"));
}
public void testFunctorPolimorphism() throws Exception {
assertEquals("a, b", join.run("a", "b"));
assertEquals("12", join.run(1, 2));
}
public void testInfiniteList() throws Exception {
InfiniteList<Integer> infiniteList = intGenerator.infiniteList(0);
assertEquals(new Integer(0), infiniteList.peek());
assertEquals(new Integer(0), infiniteList.poll());
assertEquals(new Integer(1), infiniteList.poll());
assertEquals(asList(0), infiniteList.subList(0, 1));
assertEquals(asList(1, 2, 3), infiniteList.subList(1, 4));
assertEquals(asList(5, 6), infiniteList.subList(5, 7));
Iterator<Integer> iterator = infiniteList.iterator();
assertTrue(iterator.hasNext());
assertEquals(new Integer(0), iterator.next());
assertTrue(iterator.hasNext());
assertEquals(new Integer(1), iterator.next());
assertTrue(iterator.hasNext());
assertEquals(new Integer(2), iterator.next());
}
public void testPerformance() throws Exception {
// Creating the target
List<String> target = new LinkedList<String>();
for(int i = 0; i < 100000; i++) {
target.add(String.valueOf(i));
}
// Hard code version
long startHardCoded = System.currentTimeMillis();
List<Integer> resultHardCoded = new LinkedList<Integer>();
for (String string : target) {
resultHardCoded.add(string == null ? 0 : string.length());
}
long elapsedHardCoded = System.currentTimeMillis() - startHardCoded;
// Functor version
long startFunctor = System.currentTimeMillis();
List<Integer> resultFunctorVersion = length.map(target);
long elapsedFunctor = System.currentTimeMillis() - startFunctor;
assertEquals(resultHardCoded, resultFunctorVersion);
System.out.println(String.format("Hard coded: %3dms\n Functor: %3dms\nSlowliness: %3.2fx", elapsedHardCoded, elapsedFunctor, (double) elapsedFunctor / elapsedHardCoded));
assertTrue("Expected to be at most 9 times slower than the hard coded version", elapsedFunctor < 9 * elapsedHardCoded);
}
}
|
Markdown
|
UTF-8
| 3,559
| 2.671875
| 3
|
[] |
no_license
|
# CV-DEMO
Это есть Toy-Project, который родился после окончания нескольких курсов по машинному обучению и искусственным нейронным сетям. Посмотреть работающее приложение можно [здесь](https://tuuka-cv-demo.appspot.com).
## О чём
В приложении на базе классических моделей искусственных нейронных сетей реализованы классические задачи компьютерного зрения:
* Распознавание изображений;
* Семантическая сегментация;
* Детекция объектов.
## На чём
В качестве языка программирования используется [Python](https://www.python.org). Бэкенд реализован на [Flask](https://flask.palletsprojects.com/). В процессе работы используются натренированные модели [PyTorch](https://pytorch.org), конвертированные в [ONNX](https://onnx.ai) для возможности человеческого деплоя в облаке. В качестве "облака" рассматриваются [AWS-Lambda](https://aws.amazon.com/ru/lambda/) и [GoogleAppEngine](https://cloud.google.com/appengine).
## Зачем
На момент возникновения идеи проекта, фреймворк PyTorch имел некоторые (порой существенные) сложности с
использованием натренированных моделей искусственных нейронных сетей в продакшене, поэтому основной целью этого той-проекта является как раз анализ способов деплоя и выбор наиболее, по мнению, автора приемлемого. Акцент сделан на полностью или частично бесплатных способах.
## Ограничения
Ввиду того, что на момент реализации проекта виртуальные машины с графическими ускорителями, мягко говоря, стоят денег, реализовано все на чистом CPU, что накладывает существенное влияние на производительность. Однако, с учетом "образовательной" направленности, автор решил, что "пока и так сойдет".
## Как пользоваться
Проект реализован в в виде веб-приложения, которое доступно [здесь](https://tuuka-cv-demo.appspot.com). Проект не о вебдизайне и не о фронтенде, потому разметка и стили желают быть лучше. Приложение представляет собой многостраничник с модальными окнами. Через меню имеется доступ к каждому разделу сайта, плюс есть раздел [About](https://tuuka-cv-demo.appspot.com/about), где кратко хронологически описана реализации проекта со всеми граблями, на которые автор наступил в процессе.
|
PHP
|
UTF-8
| 642
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = "categories";
public $fillable = [
"category_name"
];
// version 6.x
// public function getRouteKeyName(){
// return "slug";
// }
public function getCategoryUrl(){
return url("/category/{$this->__get("slug")}");
}
public function get($key){
if(is_null($this->__get($key)))
return "default value";
return $this->__get($key);
}
public function Products(){
return $this->hasMany("\App\Product");// tra ve 1 collection
}
}
|
Markdown
|
UTF-8
| 1,326
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
# Asana Changes Logger
Output your **Asana** changes for a given time to an external file.
## Disclaimer
⚠️ This app is not maintained anymore ⚠️
## Usage
```
usage: asana_changes_logger [options]
-d, --days Number of days to get including today (default: 5)
-s, --start Number of days in the past to start from (default: 0 for today)
-p, --project Project ID
-o, --output The output file. Allowed formats: html, md, txt
-a, --api Store the given API key and start using it from now
-lr, --log-remaining Log remainins tasks too
-ha, --hide-author Hide task assignee from changelog
--sections Show sections in changelog
-v, --version Print the current version
-h, --help Print help
```
## Installation
• Clone the repository
``git clone https://github.com/davidderus/asana_changes_logger.git``
• Go in the *asana_changes_logger* directory and build the gem with :
``cd asana_changes_logger && gem build asana_changes_logger.gemspec``
• Install the gem
``gem install asana_changes_logger-1.0.1.gem``
• Register your Asana's API Key (*needed once*) :
``asana_changes_logger -a TheKey``
• Now you can use asana_changes_logger :
``asana_changes_logger -p XXXXXXXXXXXXXX``
|
Python
|
UTF-8
| 278
| 2.984375
| 3
|
[] |
no_license
|
N, x = map(int, input().split())
a_list = list(map(int, input().split()))
a_list = sorted(a_list, reverse=False)
ans = 0
for num in a_list:
x = x - num
if x >= 0:
ans += 1
else:
break
if x > 0:
ans -= 1
elif x <= 0:
pass
print(ans)
|
C#
|
UTF-8
| 1,059
| 3.3125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PinValidation
{
class PinValidation
{
static void Main(string[] args)
{
}
static bool IsValidPin(int[] number, int numberToCheck)
{
int[] numbersForProduct = new[] { 2, 4, 8, 5, 10, 9, 7, 3, 6 };
int sum = 0;
for (int i = 0; i < number.Length; i++)
{
sum += number[i] * numbersForProduct[i];
}
int reminder=sum%11;
if(reminder==10)
{
reminder = 0;
}
if (numberToCheck == reminder)
{
return true;
}
return false;
}
static string CheckGender(int number)
{
if(number%2==0)
{
return "male";
}
else
{
return "female";
}
}
}
}
|
Python
|
UTF-8
| 8,697
| 2.765625
| 3
|
[] |
no_license
|
import torch
import torch.nn as nn
from torch.nn import Sequential as Seq, Linear, ReLU
from torch_scatter import scatter_mean
from torch_geometric.nn import MetaLayer
from abc import ABC, abstractmethod
import itertools
# My libraries
import graph_construction as gc
dont_send_to_device = []
class EdgeModel(torch.nn.Module):
def __init__(self, config):
super(EdgeModel, self).__init__()
in_channels = config['e_inc'] + 2*config['n_inc'] + config['u_inc']
hs1 = config['edge_model_mlp1_hidden_sizes'][0]
hs2 = config['edge_model_mlp1_hidden_sizes'][1]
self.edge_mlp = Seq(Linear(in_channels, hs1),
ReLU(),
Linear(hs1, hs2),
ReLU(),
Linear(hs2, config['e_outc']))
def forward(self, src, dest, edge_attr, u, batch):
""" Edge Model of Graph Net layer
@param src: [E x n_inc], where E is the number of edges. Treat E as batch size
@param dest: [E x n_inc], where E is the number of edges.
@param edge_attr: [E x e_inc]
@param u: [B x u_inc], where B is the number of graphs.
@param batch: [E] with max entry B - 1.
@return a [E x e_outc] torch tensor
"""
src_dest_edge_u = torch.cat([src, dest, edge_attr, u[batch]], 1) # Shape: [E x (2*n_inc + e_inc + u_inc)]
out = self.edge_mlp(src_dest_edge_u) # Shape: [E x e_outc]
return out
class NodeModel(torch.nn.Module):
def __init__(self, config):
super(NodeModel, self).__init__()
mlp1_inc = config['n_inc'] + config['e_outc']
mlp1_hs1 = config['node_model_mlp1_hidden_sizes'][0]
mlp1_hs2 = config['node_model_mlp1_hidden_sizes'][1]
mlp2_inc = config['n_inc'] + mlp1_hs2 + config['u_inc']
mlp2_hs1 = config['node_model_mlp2_hidden_sizes'][0]
self.node_mlp_1 = Seq(Linear(mlp1_inc, mlp1_hs1),
ReLU(),
Linear(mlp1_hs1, mlp1_hs2))
self.node_mlp_2 = Seq(Linear(mlp2_inc, mlp2_hs1),
ReLU(),
Linear(mlp2_hs1, config['n_outc']))
def forward(self, x, edge_index, edge_attr, u, batch):
""" Node Model of Graph Net layer
@param x: [N x n_inc], where N is the number of nodes.
@param edge_index: [2 x E] with max entry N - 1.
@param edge_attr: [E x e_inc]
@param u: [B x u_inc]
@param batch: [N] with max entry B - 1.
@return: a [N x n_outc] torch tensor
"""
row, col = edge_index
srcnode_edge = torch.cat([x[row], edge_attr], dim=1) # Concat source node features, edge features. Shape: [E x (n_inc + e_outc)]
srcnode_edge = self.node_mlp_1(srcnode_edge) # Run this through an MLP... Shape: [E x hs2]
per_node_aggs = scatter_mean(srcnode_edge, col, dim=0, dim_size=x.size(0)) # Mean-aggregation for every node (dest node for an edge). Shape: [N x hs2]
node_agg_u = torch.cat([x, per_node_aggs, u[batch]], dim=1) # Concat node, aggregated edge/src-node features, u
out = self.node_mlp_2(node_agg_u) # Run through MLP. Shape: [N x n_outc]
return out
class GlobalModel(torch.nn.Module):
def __init__(self, config):
super(GlobalModel, self).__init__()
inc = config['u_inc'] + config['n_outc'] + config['e_outc']
hs1 = config['global_model_mlp1_hidden_sizes'][0]
self.global_mlp = Seq(Linear(inc, hs1),
ReLU(),
Linear(hs1, config['u_outc']))
def forward(self, x, edge_index, edge_attr, u, batch):
""" Global Update of Graph Net Layer
@param x: [N x n_outc], where N is the number of nodes.
@param edge_index: [2 x E] with max entry N - 1.
@param edge_attr: [E x e_outc]
@param u: [B x u_inc]
@param batch: [N] with max entry B - 1.
@return: a [B x u_outc] torch tensor
"""
row, col = edge_index
edge_batch = batch[row] # edge_batch is same as batch in EdgeModel.forward(). Shape: [E]
per_batch_edge_aggregations = scatter_mean(edge_attr, edge_batch, dim=0) # Shape: [B x e_outc]
per_batch_node_aggregations = scatter_mean(x, batch, dim=0) # Shape: [B x n_outc]
out = torch.cat([u, per_batch_node_aggregations, per_batch_edge_aggregations], dim=1) # Shape: [B x (u_inc + n_outc + e_outc)]
return self.global_mlp(out)
class GraphNet(torch.nn.Module):
def __init__(self, layer_config):
"""
@param layer_config: a list of dictionaries specifying GraphNet layers
"""
super(GraphNet, self).__init__()
self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
self.layer_config = layer_config
# Build the graph network layers
self.build_network()
def build_network(self):
self.layers = []
for lp in self.layer_config:
gn_layer = MetaLayer(EdgeModel(lp), NodeModel(lp), GlobalModel(lp))
gn_layer.to(self.device)
self.layers.append(gn_layer)
self.layers = torch.nn.ModuleList(self.layers)
def forward(self, g):
""" Forward pass of GraphNet
@param g: a graph (torch_geometric.Data) instance. (batched)
@return: a graph (torch_geometric.Data) instance. (batched)
"""
x, edge_attr, u = g.x, g.edge_attr, g.u
for layer in self.layers:
x, edge_attr, u = layer(x, g.edge_index, edge_attr, u, g.batch)
# Clone the torch_geometric.Data object. This means x/edge_attr/u no longer have gradients
# But, replace with computed x/edge_attr/u which does have gradients
new_g = g.clone()
new_g.x = x + g.x # residual
new_g.edge_attr = edge_attr + g.edge_attr
new_g.u = u + g.u
return new_g
class NetworkWrapper(ABC):
def __init__(self, config):
self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
self.config = config.copy()
# Build network and losses
self.setup()
@abstractmethod
def setup(self):
pass
def train_mode(self):
""" Put all modules into train mode
"""
self.model.train()
def eval_mode(self):
""" Put all modules into eval mode
"""
self.model.eval()
def send_batch_to_device(self, batch):
for key in batch.keys():
if key in dont_send_to_device:
continue
if len(batch[key]) == 0: # can happen if a modality (e.g. RGB) is not loaded
continue
batch[key] = batch[key].to(self.device)
def save(self, filename):
""" Save the model as a checkpoint
"""
checkpoint = {'model' : self.model.state_dict()}
torch.save(checkpoint, filename)
def load(self, filename):
""" Load the model checkpoint
"""
checkpoint = torch.load(filename)
self.model.load_state_dict(checkpoint['model'])
print(f"Loaded {self.__class__.__name__} model")
class GraphNetWrapper(NetworkWrapper):
def setup(self):
""" Setup model, losses, optimizers, misc
"""
# Whole model, for nn.DataParallel
self.model = GraphNet(self.config['layer_config'])
self.model.to(self.device)
def run_on_batch(self, batch):
""" Run algorithm on batch of images in eval mode
@param batch: A Python dictionary with keys:
'current_state' : a [B x n x d] torch tensor
'next_state' : a [B x n x d] torch tensor
"""
self.eval_mode()
self.send_batch_to_device(batch)
curr_graph = gc.batch_construct_billiards_graph(batch['current_state'])
with torch.no_grad():
pred_next_graph = self.model(curr_graph)
return pred_next_graph
def rollout(self, s0, T):
""" Run sequence starting from state 0 (s0) for T steps
@param x: s0 [n x d] torch tensor.
@param T: Number of time steps to rollout
"""
n, d = s0.shape
states = torch.zeros((T, n, d), dtype=torch.float, device=s0.device)
states[0] = s0.clone()
for t in range(1, T):
pred_next_graph = self.run_on_batch({'current_state' : states[t-1:t]})
states[t] = pred_next_graph.x.clone()
return states
|
C
|
UTF-8
| 453
| 3.328125
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <math.h>
/*@
requires n >= 0;
ensures \result == n/2*(2*a + (n-1)*d);
assigns \nothing;
*/
int algo(int d,int n,int a)
{
int sum = 0;
int i = 0;
/*@
loop invariant sum == i/2*(2*a + (i-1)*d);
loop assigns sum,i;
*/
while (i <= n)
{
sum = sum + i;
i = i + d;
}
return sum;
}
int main()
{
int sum = algo(1,4,1);
// asserts sum == 10;
}
|
Java
|
UTF-8
| 994
| 2.453125
| 2
|
[] |
no_license
|
package com.JMR.PlanetTest;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
/*
* STUB PRESENTLY
*/
public class Base extends Drawable implements Animatable {
public int locX;
public int locY;
public Base(int x, int y) {
locX = x;
locY = y;
}
@Override
public boolean isRunning() {
// TODO Auto-generated method stub
return false;
}
@Override
public void start() {
// TODO Auto-generated method stub
}
@Override
public void stop() {
// TODO Auto-generated method stub
}
@Override
public void draw(Canvas canvas) {
// TODO Auto-generated method stub
}
@Override
public int getOpacity() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setAlpha(int alpha) {
// TODO Auto-generated method stub
}
@Override
public void setColorFilter(ColorFilter cf) {
// TODO Auto-generated method stub
}
}
|
Java
|
UTF-8
| 1,525
| 2.234375
| 2
|
[] |
no_license
|
package banecuador.fin.ec.controlador.menu;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
@ManagedBean
@RequestScoped
@SessionScoped
public class SessionBean implements Serializable {
private static final long serialVersionUID = 1L;
private Navegar navegar;
private String usuario;
private final HttpServletRequest httpServletRequest;
private final FacesContext faceContext;
private FacesMessage facesMessage;
public SessionBean() {
this.faceContext = FacesContext.getCurrentInstance();
this.httpServletRequest = ((HttpServletRequest) this.faceContext.getExternalContext().getRequest());
if (this.httpServletRequest.getSession().getAttribute("sessionUsuario") != null) {
this.usuario = this.httpServletRequest.getSession().getAttribute("sessionUsuario").toString();
}
}
/*Método para Cerrar la sesión de usuario */
public String cerrarSession() {
this.httpServletRequest.getSession().removeAttribute("sessionUsuario");
System.out.println("by");
this.facesMessage = new FacesMessage(FacesMessage.SEVERITY_INFO, "Sesión cerrada correctamente", null);
this.faceContext.addMessage(null, this.facesMessage);
navegar.direccionarInicio();
return "bye";
}
}
|
Python
|
UTF-8
| 1,760
| 2.546875
| 3
|
[] |
no_license
|
from odoo import fields, models
class Vehiculo(models.Model):
_name = 'taller.vehiculo'
_description = 'Vehiculo'
cliente = fields.Many2many('taller.cliente',
relation='vehiculo_cliente_rel',
column1='vehiculo_id',
column2='cleinte_id',
string='Clientes',
required=True
)
marca = fields.Char(string='Marca', required=True)
modelo = fields.Char(string='Modelo', required=True)
nro_motor = fields.Char(string='Nro Motor', required=True)
kilometraje = fields.Integer(string='Kilometraje', required=True)
anio = fields.Integer(string='Año', required=True)
color = fields.Char(string='Color', required=True)
tipo = fields.Selection(
[('sedan', 'Sedan'),
('camioneta', 'Camioneta'),
('coupe', 'Coupé'),
('berlina', 'Berlina'),
('util', 'Utilitaria')],
string='Tipo'
)
patente = fields.Char(string='Patente', required=True)
name = fields.Char(compute='_calcular_nombre')
_sql_constraints = [
('unique_patente', 'unique (patente)',
'No se debe repetir el número de patente')
]
def _calcular_nombre(self):
""" Se calcula el nombre uniendo la marca más el modelo más la
patente. """
for rec in self:
modelo = rec.modelo or ""
marca = rec.marca or ""
patente = rec.patente or ""
if modelo or marca or patente:
rec.name = str(modelo) + " - " + str(marca) + " - " + \
str(patente)
else:
rec.name = ""
|
Java
|
UTF-8
| 327
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
package com.jtanks.view.arena;
import java.awt.Color;
import com.jtanks.util.Point;
public interface Drawable {
void setColor(Color color);
void fillCircle(Point centre, double diameter);
void drawCircle(Point centre, double diameter);
void drawLine(Point from, Point to);
void drawPoint(Point point);
}
|
Java
|
UTF-8
| 613
| 3.5
| 4
|
[] |
no_license
|
package leetcode;
import java.util.LinkedList;
public class BSTIterator {
private LinkedList<TreeNode> stack = new LinkedList<>();
public BSTIterator(TreeNode root) {
addTreeNode(root);
}
/** @return the next smallest number */
public int next() {
TreeNode node = stack.pollLast();
addTreeNode(node.right);
return node.val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
private void addTreeNode(TreeNode node) {
while (node != null) {
stack.addLast(node);
node = node.left;
}
}
}
|
Java
|
UTF-8
| 631
| 3.578125
| 4
|
[] |
no_license
|
import java.util.*;
class NavigableSetDemo
{
public static void main(String[] args)
{
TreeSet<Integer> t = new TreeSet<Integer>();
t.add(3000);
t.add(5000);
t.add(2000);
t.add(7000);
t.add(4000);
t.add(6000);
System.out.println("Cieling = " + t.ceiling(2000));
System.out.println("Higher = " + t.higher(3000));
System.out.println("Floor = " + t.floor(4000));
System.out.println("Lower = " + t.lower(3000));
System.out.println("PollFirst = " + t.pollFirst());
System.out.println("PollLast = " + t.pollLast());
System.out.println("Descending Set = " + t.descendingSet());
System.out.println(t);
}
}
|
C++
|
UTF-8
| 56,883
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
// <Reader> -*- C++ -*-
/**
* \file Reader
*
* \brief Reads transctions using the record and index file
*
*/
#pragma once
#include <functional>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <locale>
#include <sstream>
#include <string>
#include <string_view>
#include <tuple>
#include <unordered_map>
#include <sys/stat.h>
#include "PipelineDataCallback.hpp"
#include "sparta/utils/SpartaException.hpp"
#include "sparta/utils/SpartaAssert.hpp"
#include "sparta/utils/LexicalCast.hpp"
#include "sparta/pipeViewer/Outputter.hpp"
// #define READER_DBG 1
// #define READER_LOG 1
#define _LOG_MSG(strm, x) strm << "READER: " << x << std::endl
#if READER_DBG == 1
#define READER_LOG 1
#define READER_DBG_MSG(x) _LOG_MSG(std::cerr, x)
#else
#define READER_DBG_MSG(x)
#endif
#if READER_LOG == 1
#define READER_LOG_MSG(x) _LOG_MSG(std::cout, x)
#else
#define READER_LOG_MSG(x)
#endif
namespace sparta::pipeViewer {
/*!
* \brief Sanity checker for records. Used when doing a dump of the index
* file to check that all transactions in the heartbeat actually belong
* there
*/
class RecordChecker : public PipelineDataCallback
{
private:
uint64_t start;
uint64_t end;
public:
RecordChecker(const uint64_t _start, const uint64_t _end) :
start(_start),
end(_end)
{;}
virtual void foundTransactionRecord(const transaction_t* r) override {
if (r->time_Start < start ||
r->time_End > end) {
std::cout << "Bounds on transactions were outside of heartbeat range " << start
<< ", " << end << ". transaction:"
<< " idx: " << r->transaction_ID
<< " disp: " << r->display_ID
<< " loc: " << r->location_ID
<< " start: " << r->time_Start
<< " end: " << r->time_End
<< " parent: " << r->parent_ID << std::endl;
}
}
virtual void foundInstRecord(const instruction_t* r) override {
foundTransactionRecord(r);
}
virtual void foundMemRecord(const memoryoperation_t* r) override {
foundTransactionRecord(r);
}
virtual void foundAnnotationRecord(const annotation_t* r) override {
foundTransactionRecord(r);
}
virtual void foundPairRecord(const pair_t* r) override {
foundTransactionRecord(r);
}
};
/*!
* \class Reader
* @ brief A class that facilitates reading transactions from disk that
* end in a given interval measured in cycles.
*
* The Reader will return the records found on disk by calling
* methods in PipelineDataCallback, passing pointers to the read
* transactions.
*/
class Reader
{
private:
class FileStream {
private:
const std::string filename_;
const std::ios_base::openmode mode_;
protected:
std::ifstream fstream_;
public:
FileStream(std::string&& filename, const std::ios_base::openmode mode) :
filename_(std::move(filename)),
mode_(mode),
fstream_(filename_, mode)
{
//Make sure the file opened correctly!
sparta_assert(fstream_.is_open(),
"Failed to open file " << filename_);
sparta_assert(fstream_.peek() != std::ifstream::traits_type::eof(),
filename_ << " is empty. Did Argos database collection complete?");
}
FileStream(FileStream&&) = default;
~FileStream() {
fstream_.close();
}
inline const auto& getFilename() const {
return filename_;
}
inline bool read(char* const buf, const size_t num_bytes) {
return !!fstream_.read(buf, num_bytes);
}
template<typename T>
inline bool read(T* const buf, const size_t num_bytes) {
return read(reinterpret_cast<char* const>(buf), num_bytes);
}
template<typename T>
inline bool read(T* const buf) {
return read(buf, sizeof(T));
}
template<typename T>
inline bool read(T& buf) {
return read(&buf);
}
inline bool seekg(const std::ifstream::pos_type pos) {
return !!fstream_.seekg(pos);
}
inline bool seekg(const std::ifstream::off_type pos, const std::ios::seekdir dir) {
return !!fstream_.seekg(pos, dir);
}
inline auto tellg() {
return fstream_.tellg();
}
inline auto gcount() const {
return fstream_.gcount();
}
inline bool good() const {
return fstream_.good();
}
inline void reopen() {
std::fstream::pos_type cur_pos = fstream_.tellg();
fstream_.close();
fstream_.clear();
fstream_.open(filename_, mode_);
fstream_.seekg(cur_pos);
}
inline void clear() {
fstream_.clear();
}
inline int64_t size() const {
struct stat stat_result;
stat(filename_.c_str(), &stat_result);
return stat_result.st_size;
}
inline operator bool() const {
return !!fstream_;
}
};
/**
* \class ColonDelimitedFile
* \brief Class that knows how to read ':'-delimited files used by the Argos pair format
*/
class ColonDelimitedFile : public FileStream {
/**
* \struct CustomSpaceCType
* \brief Subclass of std::ctype<char> that allows overriding which characters should be
* considered whitespace
*/
template<char... SpaceChars>
struct CustomSpaceCType : std::ctype<char> {
private:
using CTypeArray = std::array<std::ctype_base::mask, table_size>;
/**
* \brief Generates a constexpr character table with the characters in SpaceChars set as whitespace
*/
static inline constexpr CTypeArray genSpaceTable_() {
CTypeArray space_table{};
// First set every character to std::ctype_base::mask - treating them as non-whitespace
for(size_t i = 0; i < table_size; ++i) {
space_table[i] = std::ctype_base::mask();
}
// Lambda that sets a character to whitespace
auto add_space_char = [&](const char c) { space_table[c] = std::ctype_base::space; };
// Apply the lambda over all of the characters in SpaceChars
(add_space_char(SpaceChars), ...);
return space_table;
}
public:
CustomSpaceCType() :
std::ctype<char>(getTable())
{
}
static inline std::ctype_base::mask const* getTable() {
// Init the table
static constexpr CTypeArray space_table = genSpaceTable_();
// Return a pointer to the table
return space_table.data();
}
};
// The FileLineCType only treats newlines as whitespace, causing the >> operator to grab an entire line at a time
using FileLineCType = CustomSpaceCType<'\n'>;
public:
/**
* \class LineStream
* \brief Subclass of std::istringstream with some useful specializations for the >> operator. This class is used to
* automatically tokenize each line in a ':'-delimited file using the >> operator.
*/
class LineStream : public std::istringstream {
private:
// The PairFormatCType treats ':' as whitespace, causing the >> operator to tokenize on
// any ':' in its internal string buffer
using PairFormatCType = CustomSpaceCType<':'>;
/**
* \brief Reads an aribitrary tuple from the stream
*/
template<size_t idx, typename ... Args>
inline LineStream& readTuple_(std::tuple<Args...>& val) {
// We reached the end of the tuple, so no more work to be done
if constexpr(idx >= sizeof...(Args)) {
return *this;
}
else {
// Grab the current index and then recursively grab the next one
// (this will get unrolled by the compiler)
*this >> std::get<idx>(val);
return readTuple_<idx+1>(val);
}
}
/**
* \brief Sets the locale to a PairFormatCType
*/
inline void setLocale_() {
imbue(std::locale(std::locale(), new PairFormatCType()));
}
public:
LineStream() :
std::istringstream()
{
setLocale_();
}
explicit LineStream(const std::string& str) :
std::istringstream(str)
{
setLocale_();
}
using std::istringstream::operator>>;
/**
* \brief >> operator specialization for enums
*/
template<typename T>
inline std::enable_if_t<std::is_enum_v<T>, LineStream&> operator>>(T& val) {
// Read into a temporary variable of the underlying type of the enum
std::underlying_type_t<T> new_val;
*this >> new_val;
// Then cast it to the enum type
val = static_cast<T>(new_val);
return *this;
}
/**
* \brief >> operator specialization for std::pair
*/
template<typename T, typename U>
inline LineStream& operator>>(std::pair<T, U>& val) {
*this >> val.first >> val.second;
return *this;
}
/**
* \brief >> operator specialization for std::tuple
*/
template<typename ... Args>
inline LineStream& operator>>(std::tuple<Args...>& val) {
return readTuple_<0>(val);
}
/**
* \brief >> operator specialization for std::unordered_map
* Reads in the key and value as an std::pair and then does a move-emplace into the map
* Note that this only adds 1 element at a time rather than attempting to read an entire map at once
*/
template<typename Key,
typename T,
typename Hash = std::hash<Key>,
typename KeyEqual = std::equal_to<Key>,
typename Allocator = std::allocator<std::pair<const Key, T>>>
inline LineStream& operator>>(std::unordered_map<Key, T, Hash, KeyEqual, Allocator>& map) {
std::pair<Key, T> new_pair;
*this >> new_pair;
map.emplace(std::move(new_pair));
return *this;
}
/**
* \brief >> operator specialization for std::vector
* Reads in the value then does a move-emplace into the vector
* Note that this only adds 1 element at a time rather than attempting to read an entire vector at once
*/
template<typename T, typename Allocator = std::allocator<T>>
inline LineStream& operator>>(std::vector<T, Allocator>& val) {
T new_val;
*this >> new_val;
val.emplace_back(std::move(new_val));
return *this;
}
};
explicit ColonDelimitedFile(std::string&& filename, std::ios_base::openmode mode = std::ios_base::in) :
FileStream(std::move(filename), mode)
{
fstream_.imbue(std::locale(std::locale(), new FileLineCType));
}
/**
* \brief Iterates over the entire file line by line, tokenizing the line with a LineStream and then
* calling a callback function for further processing
*/
template<typename CallbackFunc>
inline void processWith(CallbackFunc&& func) {
LineStream strm;
for(auto it = std::istream_iterator<std::string>(fstream_); it != std::istream_iterator<std::string>(); ++it) {
strm.str(*it);
strm.clear();
func(strm);
}
}
/**
* \brief Simplified form of processWith that reads an entire file into a single object
*/
template<typename T>
inline void processInto(T& obj) {
processWith([&](LineStream& strm) { strm >> obj; });
}
};
// Memory Layout of pair_struct. We build a map of such structs before we start reading record back from the database.
// This structs help us by telling us exactly how may pair values
// there are in the current pair type, what their names are and how much bytes each of the values occupy.
struct pair_struct{
uint16_t length;
std::vector<std::string> names;
std::vector<uint16_t> sizes;
std::vector<uint16_t> types;
PairFormatterVector formats;
explicit pair_struct(ColonDelimitedFile::LineStream& strm) :
length(0),
names(1, "pairid"),
sizes(1, sizeof(uint16_t)),
types(1, 0),
formats(1, PairFormatter::DECIMAL)
{
strm >> length;
++length; // Increment length to account for the default pairid field
names.reserve(length);
sizes.reserve(length);
types.reserve(length);
// Iterate through the rest of the delimiters in the stringline
// and build up the Name Strings and the Sizeof values for every field.
// Formats are read later from a different file
while(!strm.eof()) {
strm >> names >> sizes >> types;
}
formats.reserve(length);
}
};
/**
* \brief return the correct position in the record file that corresponds
* to the start cycle.
* \param start The cycle number to start reading records from.
*/
inline uint64_t findRecordReadPos_(const uint64_t start)
{
//Figure out how far we need to seek into our index file.
const uint64_t step = first_index_ + (start/heartbeat_ * sizeof(uint64_t));
//Now read the pointer from this location.
if(!index_file_.seekg(step)) {
sparta_assert(!"Could not seekg in for the given position. Please report bug");
}
uint64_t pos = size_of_record_file_;
//It might be the case that our index file is too small
//to represent an end time that the user is requesting.
//in the above algorythm either reached the end of the index file.
//notice we look too see if the index file seeker has passed
//size_of_index_file_ - 8 bytes b/c a special last index is written to the index file
//to point to only the start of the last transaction.
const int64_t filepos = index_file_.tellg();
if(filepos >= size_of_index_file_ - 8 || filepos == -1)
{
//We need to reset end of file reach flags for the index file.
index_file_.clear();
}
else
{
index_file_.read(pos);
}
return pos;
}
/**
* \brief A helper method to round values up to the
* interval values.
* example 4600 rounds to 5000 when the interval is "1000"
*/
inline uint64_t roundUp_(const uint64_t num)
{
const auto sub_sum = num + heartbeat_ - 1;
return sub_sum - (sub_sum % heartbeat_);
}
inline std::string readAnnotation_(const uint16_t length) {
std::string annt_buf(length, '\0');
record_file_.read(annt_buf.data(), length);
return annt_buf;
}
inline void acquireLock_() {
sparta_assert(!lock_,
"This reader class is not thread safe, "
"and this method cannot be called from multiple threads.");
lock_ = true;
}
/**
* \brief Return the start time in the file.
*/
inline uint64_t findCycleFirst_()
{
//Make sure the user is not abusing our NON thread safe method.
acquireLock_();
record_file_.seekg(0, std::ios::beg);
transaction_t transaction;
record_file_.read(transaction);
clearLock();
return transaction.time_Start;
}
/**
* \brief Return the last end time in the file.
* Our output saved the last index to point to
* the start of last record.
*/
inline uint64_t findCycleLast_()
{
//Make sure the user is not abusing our NON thread safe method.
acquireLock_();
//Notice that we reset the index file, b/c if
//we had already read to the end of the file, we need to reset
//end of file flags.
index_file_.clear();
//seek one entry back from the end of the index file
index_file_.seekg(size_of_index_file_-sizeof(uint64_t));
uint64_t pos = 0;
index_file_.read(pos);
//read the transaction at the appropriate location.
record_file_.seekg(pos, std::ios::beg);
transaction_t transaction;
record_file_.read(transaction);
clearLock();
if(record_file_.gcount() != sizeof(transaction_t))
{
return highest_cycle_;
}
return transaction.time_End - 1;
}
template<bool CountRecords>
inline size_t readRecordVersion_(const std::fstream::pos_type end_pos,
const uint64_t start,
const uint64_t end)
{
size_t recsread = 0;
for(auto pos = record_file_.tellg(); pos < end_pos && pos != -1; pos = record_file_.tellg())
{
// Read, checking for chunk_end
readRecord_(start, end);
if constexpr(CountRecords) {
++recsread;
}
}
return recsread;
}
/*!
* \brief Read a record of any format. Older formats are upconverted to new format.
*/
template<bool CountRecords = false>
inline size_t readRecords_(const std::fstream::pos_type end_pos, const uint64_t start, const uint64_t end) {
sparta_assert(version_ == 2, "Only version 2 is currenly supported");
return readRecordVersion_<CountRecords>(end_pos, start, end);
}
/**
* \brief Read a single record at \a pos and increment pos
*/
inline void readRecord_(const uint64_t start, const uint64_t end) {
transaction_t transaction;
record_file_.read(transaction);
sparta_assert(record_file_.good(), "Previous read of the argos DB failed");
switch (transaction.flags & TYPE_MASK)
{
case is_Annotation :
{
annotation_t annot(std::move(transaction));
record_file_.read(annot.length);
annot.annt = readAnnotation_(annot.length);
//// Sanity check the transactions coming out
//if(start % heartbeat_ == 0 // Only try this sanity checking if start is a multiple of heartbeat_
// && transaction.time_Start < start // Got a transaction starting before the first heartbeat containing this query
// && transaction.time_End > transaction.time_Start){ // ignore 0-length transactions
// std::cout << "Found a transaction where start < query-start && end <= query-start: ("
// << transaction.time_Start << " < " << start << ")"
// << " && " << transaction.time_End << "<= " << start << ") : \""
// << annot.annt << "\""
// << std::endl;
//}
// Only send along transaction in the query range
if(transaction.time_End < start || transaction.time_Start > end){
// Skip transactions by not sending them along to the callback.
// read is faster than seekg aparently. This DOES help performance
READER_DBG_MSG("skipped transaction outside of window [" << start << ", "
<< end << "). start: " << transaction.time_Start << " end: "
<< transaction.time_End
<< " parent: " << transaction.parent_ID);
}else{
READER_DBG_MSG("found annt. " << "loc: " << annot.location_ID << " start: "
<< annot.time_Start << " end: " << annot.time_End
<< " parent: " << annot.parent_ID);
data_callback_->foundAnnotationRecord(&annot);
}
} break;
case is_Instruction:
{
instruction_t inst;
record_file_.seekg(-sizeof(transaction_t), std::ios::cur);
record_file_.read(inst);
READER_DBG_MSG("found inst. start: " << inst.time_Start << " end: " << inst.time_End);
data_callback_->foundInstRecord(&inst);
} break;
case is_MemoryOperation:
{
memoryoperation_t memop;
record_file_.seekg(-sizeof(transaction_t), std::ios::cur);
record_file_.read(memop);
READER_DBG_MSG("found inst. start: " << memop.time_Start << " end: " << memop.time_End);
data_callback_->foundMemRecord(&memop);
} break;
// If we have found a record which is of Pair Type,
// then we enter into this switch case
// which contains the logic to read back records of
// pair type using record file, map file
// and In-memory data structures and rebuild the pair
// record one by one.
case is_Pair : {
pair_t pairt(std::move(transaction));
// The loc_map is an In-memory Map which contains a mapping
// of Location ID to Pair ID.
// We are going to use this map to lookup the Location ID we
// just read from this current record
// and find out the pair id of such a record
const auto unique_id = loc_map_.at(transaction.location_ID);
// We are now going to use the In-memory data structure we built
// during the Reader construction.
// This Data Structure contains information about the name strings
// and their sizeof data
// for every different type of pair we have collected.
// So, we retrieve records from this structure one by one,
// till we find that the pair id of the record we just read
// from the record file
// matches the pair id of the current record we retrieved from
// the In-memory data Structure.
const auto& st = map_.at(unique_id);
// We lookup the length, the name strings and the sizeofs of
// every anme string from the retrieved
// record of the Data Struture and copy the values into out
// live Pair Transaction record
pairt.length = st.length;
pairt.nameVector = st.names;
pairt.sizeOfVector = st.sizes;
pairt.delimVector = st.formats;
pairt.valueVector.reserve(pairt.length);
pairt.valueVector.emplace_back(std::make_pair(unique_id, false));
pairt.stringVector.reserve(pairt.length);
pairt.stringVector.emplace_back(std::to_string(unique_id));
for(std::size_t i = 1; i != st.length; ++i){
if(st.types[i] == 0) {
// Type 0 = integer
const auto item_size = pairt.sizeOfVector[i];
sparta_assert(item_size <= sizeof(pair_t::IntT),
"Data Type not supported for reading/writing.");
pair_t::IntT tmp = 0;
record_file_.read(&tmp, item_size);
pairt.valueVector.emplace_back(std::make_pair(tmp, true));
// Finally for a certain field "i", we check if there is a string
// representation for the integral value, by checking,
// if a key with current pair id, current field id, current integral value
// exists in the In-memory String Map. If yes, we grab the value
// and place it in the enum vector.
if(const auto it = stringMap_.find(std::make_tuple(pairt.valueVector[0].first,
i-1, // string map doesn't include the UID field, so index 0 == field index 1
pairt.valueVector[i].first));
it != stringMap_.end()) {
pairt.stringVector.emplace_back(it->second);
pairt.valueVector[i].second = false;
}
// Else, we convert integer value to string
else {
const auto int_value = pairt.valueVector[i].first;
if (int_value == std::numeric_limits<pair_t::IntT>::max()) {
// Max value, so probably bad...push empty string
pairt.stringVector.emplace_back("");
} else {
const auto& format_str = pairt.delimVector[i];
std::ios_base::fmtflags format_flags = std::ios::dec;
std::string_view fmt_prefix = "";
if(format_str == PairFormatter::HEX) {
format_flags = std::ios::hex;
fmt_prefix = "0x";
}
else if(format_str == PairFormatter::OCTAL) {
format_flags = std::ios::oct;
fmt_prefix = "0";
}
std::ostringstream int_str;
int_str << fmt_prefix;
int_str.setf(format_flags, std::ios::basefield);
int_str << int_value;
pairt.stringVector.emplace_back(int_str.str());
}
}
}
else if(st.types[i] == 1){
// Type 1 = string
uint16_t annotationLength;
record_file_.read(annotationLength);
std::string annot_str(annotationLength, '\0');
record_file_.read(annot_str.data(), annotationLength);
pairt.stringVector.emplace_back(std::move(annot_str));
// This bool value describes if this field has a string-only value.
// String only values are those values which are stored in database as
// strings and has no integral representation of itself.
const bool string_only_field = true;
pairt.valueVector.emplace_back(
std::make_pair(
std::numeric_limits<decltype(pairt.valueVector)::value_type::first_type>::max(),
string_only_field
)
);
} else {
pairt.stringVector.emplace_back("none");
pairt.valueVector.emplace_back(std::make_pair(0, false));
}
}
READER_DBG_MSG("found pair. start: " << pairt.time_Start << " end: " << pairt.time_End);
data_callback_->foundPairRecord(&pairt);
} break;
default:
{
throw sparta::SpartaException("Unknown Transaction Found. Data might be corrupt.");
}
}
}
inline void checkIndexUpdates_()
{
const auto index_size = index_file_.size();
const auto record_size = record_file_.size();
if(index_size != size_of_index_file_ && record_size != size_of_record_file_)
{
const int64_t record_remainder = record_size % heartbeat_;
if(record_size - record_remainder == size_of_record_file_)
{
return;
}
record_file_.reopen();
index_file_.reopen();
map_file_.reopen();
data_file_.reopen();
size_of_index_file_ = index_size;
if(record_remainder != 0)
{
size_of_record_file_ = record_size - record_remainder;
}
else
{
size_of_record_file_ = record_size;
}
highest_cycle_ = findCycleLast_();
file_updated_ = true;
}
}
public:
/**
* \brief Construct a Reader
* \param filename the name of the record file
* \param cd a pointer to for the PipelineDataCallback to use.
*/
Reader(std::string filepath, std::unique_ptr<PipelineDataCallback>&& data_callback) :
filepath_(std::move(filepath)),
record_file_(filepath_ + "record.bin", std::fstream::in | std::fstream::binary ),
index_file_(filepath_ + "index.bin", std::fstream::in | std::fstream::binary),
map_file_(filepath_ + "map.dat", std::fstream::in),
data_file_(filepath_ + "data.dat", std::fstream::in),
string_file_(filepath_ + "string_map.dat", std::fstream::in),
display_file_(filepath_ + "display_format.dat", std::fstream::in),
data_callback_(std::move(data_callback)),
size_of_index_file_(0),
size_of_record_file_(0),
lowest_cycle_(0),
highest_cycle_(0),
lock_(false),
file_updated_(false),
loc_map_(),
map_(),
stringMap_()
{
sparta_assert(data_callback_);
READER_LOG_MSG("pipeViewer reader opened: " << record_file_.getFilename());
// Read header from index file
char header_buf[HEADER_SIZE];
index_file_.read(header_buf, HEADER_SIZE);
// Assuming older version until header proves otherwise
version_ = 1;
if(static_cast<size_t>(index_file_.gcount()) != HEADER_SIZE) {
// Assume old version because the file is too small to have a header
index_file_.clear(); // Clear error flags after failing to read enough data
index_file_.seekg(0, std::ios::beg); // Restore
}
else if(HEADER_PREFIX.compare(0,
HEADER_PREFIX.size(),
header_buf,
HEADER_PREFIX.size())) {
// Header prefix did not match. Assume old version
index_file_.seekg(0, std::ios::beg); // Restore
}
else {
// Header prefix matched. Read version
header_buf[HEADER_SIZE - 1] = '\0'; // Insert null
version_ = sparta::lexicalCast<decltype(version_)>(header_buf + HEADER_PREFIX.size());
}
sparta_assert(version_ > 0 && version_ <= Outputter::FILE_VERSION,
"pipeout file " << filepath_ << " determined to be format "
<< version_ << " which is not known by this version of SPARTA. Version "
"expected to be in range [1, " << Outputter::FILE_VERSION << "]");
sparta_assert(index_file_.good(),
"Finished reading index file header for " << filepath_ << " but "
"ended up with non-good file handle somehow. This is a bug in the "
"header-reading logic");
// Read the heartbeat size from our index file.
// This will be the first integer in the file except for the header if there is one
// Warning: this must be called while the index_file_ is already seeked to the
// start of file, which it is after opening.
index_file_.read(heartbeat_);
// Save the first index entry position
first_index_ = index_file_.tellg();
READER_LOG_MSG("Heartbeat is: " << heartbeat_);
sparta_assert(heartbeat_ != 0,
"Pipeout database \"" << filepath_ << "\" had a heartbeat of 0. This "
"would be too slow to actually load");
//Determine the size of our index file
index_file_.seekg(0, std::fstream::end);
size_of_index_file_ = index_file_.tellg();
//Determine the size of our record file.
record_file_.seekg(0, std::ios::end);
size_of_record_file_ = record_file_.tellg();
//cache the earliest start and stop of the record file
lowest_cycle_ = findCycleFirst_();
highest_cycle_ = findCycleLast_();
// Building the In-Memory LocationID -> PairID Lookup structure
// from the map_file_ which contains the same.
// We read this map_file_ just once during the construction
// of the Reader Class and store all the relationships
// in an unordered_map called loc_map. When we read each Pair Record,
// we quickly do a lookup with the Location ID
// of the record in this map, and retrieve the Pair ID of that record,
// so that we can go ahead and get all the information
// about its name strings and sizeof and pair length from other data structures.
//The fields in the file are separated by ":"
// Read through the whole map File
map_file_.processInto(loc_map_);
// Building the In-memory Pair Lookup structure, such that,
// in future when reading back record from transaction file,
// we can use this structure to know about the length, name strings
// and sizeof the values
// for that paritcular pair, instead of using a file on disk for this.
// We read through the Data file just once, and populate this structure.
//The fields in the file are separated by ":"
data_file_.processWith([&](auto& strm) {
uint16_t unique_id;
strm >> unique_id;
pair_struct pStruct(strm);
//Finally, when we have completely parsed one line of this file,
// it means we have complete knowledge of one pair type.
// We then insert this pair into out Lookup structure.
map_.emplace(unique_id, pStruct);
});
display_file_.processWith([&](auto& strm) {
uint16_t pairId;
strm >> pairId;
auto& fmt_vec = map_.at(pairId).formats;
while(!strm.eof()) {
strm >> fmt_vec;
}
});
// Read every line of the String Map file
string_file_.processInto(stringMap_);
}
Reader(Reader&& rhs) = default;
//!Destructor.
virtual ~Reader() = default;
template<typename CallbackType, typename ... CallbackArgs>
inline static Reader construct(const std::string& filepath, CallbackArgs&&... cb_args) {
return Reader(filepath, std::make_unique<CallbackType>(std::forward<CallbackArgs>(cb_args)...));
}
/**
* \brief Clears the internal lock. This should be used ONLY when an
* exception occurs during loading
*/
inline void clearLock(){
lock_ = false;
}
/**
* \brief using our PipelineDataCallback pointer
* pass all of the transactions found in a given interval of cycles.
* \param start the intervals start cycle. Transactions with
* TMEN of "start" WILL be included in this window.
* "start" will also round down to the lower index closest to "start"
* \param end the intervals stop cycle. transactions
* with TMEN of "end" will NOT be included in the window.
*
* [start, end) where start rounded down and end rounded up
*
* so if our interval = 1000
* getWindowls(3500, 4700) will essentially return all transactions
* ending between
* [3000, 5000)
*
* \warning start must be GREATER than end.
* \warning This method IS NOT thread safe.
*/
inline void getWindow(const uint64_t start, const uint64_t end)
{
READER_LOG_MSG("returning window. START: " << start << " END: " << end);
// sparta_assert(//start < end, "Cannot return a window where the start value is greater than the end value");
//Make sure the user is not abusing our NON thread safe method.
acquireLock_();
//round the end up to the nearest interval.
const uint64_t chunk_end = roundUp_(end);
READER_LOG_MSG("end rounded to: " << chunk_end);
//First we will want to make sure we are ready to read at the correct
//position in the record file.
record_file_.seekg(findRecordReadPos_(start));
const auto read_pos = record_file_.tellg();
//what space does this interval span in the record file.
const std::fstream::pos_type full_data_size = findRecordReadPos_(chunk_end) - read_pos;
//Now start processing the chunk.
const std::fstream::pos_type end_pos = read_pos + full_data_size;
READER_LOG_MSG("start_pos: " << read_pos << " end_pos: " << end_pos);
//Make sure we have not passed the end position, also make sure we
//are not at -1 bc that means we reached the end of the file!
//As we read records. Read each as a transaction.
//check the flags, seek back and then read it as the proper type,
//then pass the a pointer to the struct to the appropriate callback.
#if READER_LOG == 1
READER_LOG_MSG("read " << std::dec << readRecords_<true>(end_pos, start, end) << " records");
#else
readRecords_<false>(end_pos, start, end);
#endif
//unlock our assertion test.
sparta_assert(lock_);
clearLock();
}
/**
* \brief Reads transactions afer each index in the entire file
*/
inline void dumpIndexTransactions() {
auto prev_cb = std::move(data_callback_);
try{
uint64_t tick = 0;
index_file_.seekg(0, std::ios::beg);
while(tick <= getCycleLast() + (heartbeat_-1)){
int64_t pos;
// Set up a record checker to ensure all transactions fall
// within the range being queried
data_callback_ = std::make_unique<RecordChecker>(tick, tick + heartbeat_);
pos = findRecordReadPos_(tick);
std::cout << "Heartbeat at t=" << std::setw(10) << tick << " @ filepos " << std::setw(9)
<< pos << " first transaction:" << std::endl;
const uint64_t chunk_end = roundUp_(tick + heartbeat_);
std::cout << "chunk end rounded to: " << chunk_end << std::endl
<< "record file pos before: " << record_file_.tellg() << std::endl;
record_file_.seekg(pos, std::ios::beg);
const auto read_pos = record_file_.tellg();
std::cout << "record file pos after: " << read_pos << std::endl;
if(read_pos == EOF) {
std::cerr << "TellG says EOF!" << std::endl;
}
else {
//what space does this interval span in the record file.
const uint64_t full_data_size = findRecordReadPos_(chunk_end) - read_pos;
//Now start processing the chunk.
const int64_t end_pos = pos + full_data_size;
std::cout << "pos = " << pos << ", end_pos = " << end_pos << std::endl;
const auto recsread = readRecords_<true>(end_pos, tick, chunk_end);
std::cout << "Records: " << recsread << std::endl;
}
std::cout << "record file pos after read: " << record_file_.tellg() << std::endl;
std::cout << "pos variable after read: " << read_pos << std::endl;
tick += heartbeat_;
std::cout << "\n";
}
}catch(...){
// Restore data callback before propogating exception
data_callback_ = std::move(prev_cb);
throw;
}
// Restore callback
data_callback_ = std::move(prev_cb);
if(uint64_t tmp; index_file_.read(tmp)) {
std::cout << "Read junk at the end of the index file:\n " << tmp;
while(index_file_.read(tmp)) {
std::cout << " " << tmp;
}
}
}
/**
* \brief Gets the size of a data chunk. This is a minimum granularity
* of file reads when looking for any range. Chunks are in terms of
* ticks and chunks always begin at ticks which are chunk-size-aligned
*/
inline uint64_t getChunkSize() const
{
return heartbeat_;
}
/**
* \brief Return the start time in the file.
*/
inline uint64_t getCycleFirst() const
{
READER_DBG_MSG("Returning first cycle: " << lowest_cycle_);
//This needs to be changed.
//BUG When this returns 0, we miss many transactions in the viewer.
return lowest_cycle_;
}
/**
* \brief Return the last end time in the file.
* Our output saved the last index to point to
* the start of last record.
*/
inline uint64_t getCycleLast() const
{
READER_DBG_MSG("Returning last cycle: " << highest_cycle_);
return highest_cycle_;
}
/**
* \brief Gets the version of the pipeout files loaded
*/
inline uint32_t getVersion() const
{
return version_;
}
inline bool isUpdated()
{
checkIndexUpdates_();
return file_updated_;
}
inline void ackUpdated()
{
file_updated_ = false;
}
template<typename CallbackType>
inline CallbackType& getCallbackAs() {
return *static_cast<CallbackType*>(data_callback_.get());
}
template<typename CallbackType>
inline const CallbackType& getCallbackAs() const {
return *static_cast<const CallbackType*>(data_callback_.get());
}
private:
const std::string filepath_; /*!< Path to this file */
FileStream record_file_; /*!< The record file stream */
FileStream index_file_; /*!< The index file stream */
ColonDelimitedFile map_file_; /*!< The map file stream */
ColonDelimitedFile data_file_; /*!< The data file stream */
ColonDelimitedFile string_file_; /*!< The string map file stream */
ColonDelimitedFile display_file_;
std::unique_ptr<PipelineDataCallback> data_callback_; /*<! A pointer to a callback to pass records too */
uint64_t heartbeat_; /*!< The heartbeast-size in cycles of our indexes in the index file */
uint64_t first_index_; /*!< Position in file of first index entry */
uint32_t version_; /*!< Version of the file being read */
int64_t size_of_index_file_; /*!< The total byte size of the index file */
int64_t size_of_record_file_; /*!< The total byte size of the record file */
uint64_t lowest_cycle_; /*!< The lowest cycle in the file. */
uint64_t highest_cycle_; /*!< The highest cycle in the file. */
bool lock_; /*!< A tool used too assert that this file Reader is not thread safe.*/
bool file_updated_; /*!< Set to true when the open database has changed */
// In-memory data structure to hold the mapping of Location ID
// of generic transaction structures
// and map them to Pair IDs of pair transaction structs.
std::unordered_map<uint32_t, uint16_t> loc_map_;
// In-memory data structure to hold the unique pairId and
// subsequent information about its name strings and
// sizeofs for every different pair type
std::unordered_map<uint16_t, pair_struct> map_;
// In-memory data structure to hold the string map structure
// which maps a tuple of integers reflecting the pair type,
// field number and field value to the actual String
// we want to display in pipeViewer
std::unordered_map<std::tuple<uint64_t, uint64_t, uint64_t>,
std::string,
hashtuple::hash<std::tuple<uint64_t, uint64_t, uint64_t>>>
stringMap_;
};
// Formats a pair into an annotation-like string - used by transactionsearch and Python interface
// This version accepts the individual pair_t members as parameters so that it can be used with the
// transactionInterval type
inline static std::string formatPairAsAnnotation(const uint64_t transaction_ID,
const uint64_t display_ID,
const uint16_t length,
const std::vector<std::string>& nameVector,
const std::vector<std::string>& stringVector) {
std::ostringstream annt_preamble;
std::ostringstream annt_body;
const uint16_t display_id = static_cast<uint16_t>((display_ID < 0x1000 ? display_ID : transaction_ID) & 0xfff);
std::ios flags(nullptr);
flags.copyfmt(annt_preamble);
annt_preamble << std::setw(3) << std::setfill('0') << std::hex << display_id;
annt_preamble.copyfmt(flags);
annt_preamble << ' ';
for(size_t i = 1; i < length; ++i) {
const auto& name = nameVector[i];
const auto& value = stringVector[i];
if(name != "DID") {
annt_body << name << '(' << value << ") ";
}
if(name == "uid") {
annt_preamble << 'u' << (std::stoull(value) % 10000) << ' ';
}
else if(name == "pc") {
flags.copyfmt(annt_preamble);
annt_preamble << "0x" << std::setw(4) << std::setfill('0') << std::hex << (std::stoull(value, 0, 16) & 0xffff) << ' ';
annt_preamble.copyfmt(flags);
}
else if(name == "mnemonic") {
const std::string_view value_view(value);
annt_preamble << value_view.substr(0, 7) << ' ';
}
}
return annt_preamble.str() + annt_body.str();
}
// Formats a pair into an annotation-like string - used by transactionsearch and Python interface
inline static std::string formatPairAsAnnotation(const pair_t* pair) {
return formatPairAsAnnotation(pair->transaction_ID,
pair->display_ID,
pair->length,
pair->nameVector,
pair->stringVector);
}
}//NAMESPACE:sparta::pipeViewer
|
JavaScript
|
UTF-8
| 5,786
| 2.53125
| 3
|
[] |
no_license
|
/**
调用Http接口
@example
~~~~
var Http = require('Http');
Http.getRoomList(function(data){
cc.info(data);
});
var reqId = Http.getOnline(1, function(data){
cc.info(data);
}, function(error){
cc.info(error);
});
Http.cancelRequest(reqId);
~~~
*/
var HttpService = require('HttpService');
var DataProxy = require('DataProxy');
//debug data
if(!window.USERDATA){
window.USERDATA = {
point: 1500,
score: 0,
uid: 10, //544, 4087, 4203, 7490
sk: 'abc58ipalmplay85abc',
name: '测试号哈',
image: 'http://game.manyouwei.cn/assets/photo/n4203.jpg',
xmlevel: 1,
token: '',
isNew: 0 ,
isFirstLogin: false}; //1:新用户 0:老用户
}
if(!window.CONFIGDATA){
window.CONFIGDATA = {
apiUrl: "http://game-dev.manyouwei.cn/dice/api.php",
roomList: 'http://game.manyouwei.cn/assets/niuniu/roomlist/20160517192004.json',
actJson: 'http://game-dev.manyouwei.cn/assets/niuniu/act/201606242445.json',
serverList: [['192.168.1.100', '9902'], ['192.168.1.100', '9902']],
hgChips:1000000,
};
}
//end debug data
HttpService.init(3, window.CONFIGDATA.apiUrl);
HttpService.setSessionKey(window.USERDATA.uid, window.USERDATA.sk);
var http = {
/*
获得用户基本信息
@return {
point: 40000, 筹码
score: 4000, 积分
uid: 544, 用户id
sk: 'f8e57ea08b957905dc50c511bf69b888',
name: 'ALeo', 用户名
image: 'http://game.manyouwei.cn/assets/photo/n544.jpg', 头像
xmlevel: 1, 糖果消消乐关卡等级
token: '',
isNew: 0 是否首次登录
}
*/
getUserData:function(){
return DataProxy.extend(window.USERDATA);
},
/*
获取配置信息
@return{
roomList: 'http://game.manyouwei.cn/assets/niuniu/roomlist/201512211100.json', //房间配置文件
serverList: [["192.168.1.100","8080"],["192.168.1.100","8080"]] //服务器ip列表
}
*/
getConfigData:function(){
return window.CONFIGDATA;
},
//取消请求
cancelRequest:function(reqId){
HttpService.cancelRequest(reqId);
},
/*
获取房间列表
resultCallback(data)
data = [[1,1,50, 500],[2,1,50, 500],[3,2,50, 500], ...] //[房间ID, 房间场次(1:初级场, 2:中级场, 3:高级场), 底分, 进房下限]
*/
getRoomList:function(resultCallback){
return HttpService.cacheFile(this.getConfigData().roomList, resultCallback);
},
/*
获取转盘配置
resultCallback(data)
*/
getTurnplateData:function(resultCallback){
return HttpService.cacheFile(this.getConfigData().actJson, resultCallback);
},
/*
获取在线人数
resultCallback(data)
data = {count : 180} //count 在线人数
*/
getOnlineAll:function(resultCallback, errorCallback){
return HttpService.request("niuniu.getOnlineAll", {}, resultCallback, errorCallback);
},
/*
获取房间在线人数
@param: type 1初级场 2 中级场 3 高级场
@return
resultCallback(data)
data = {"1": 5, "2": 3} //{房间id: 人数}
*/
getOnline:function(type, resultCallback, errorCallback){
return HttpService.request("niuniu.getOnline", {type: type}, resultCallback, errorCallback);
},
/*
快速开始游戏
@return
resultCallback(data)
data = {tid: 1} 房间id
*/
quickGame:function(resultCallback, errorCallback){
return HttpService.request("niuniu.quickGame", {}, resultCallback, errorCallback);
},
/*
财富排行榜
@return
resultCallback(data)
data = {list: [{image: "http://example.com/xx.jpg", name: "Aleo", point: 1200},{image: "http://example.com/xx.jpg", name: "Aleo", point: 1000}, ...]}
*/
getTop:function(resultCallback, errorCallback){
return HttpService.request("game.top", {}, resultCallback, errorCallback);
},
/*
积分排行榜
resultCallback(data)
data = {list: [{image: "http://example.com/xx.jpg", name: "Aleo", score: 1200},{image: "http://example.com/xx.jpg", name: "Aleo", score: 1000}, ...]}
*/
getScoreTop:function(resultCallback, errorCallback){
return HttpService.request("game.scoreTop", {}, resultCallback, errorCallback);
},
/*
获取破产次数
resultCallback(data)
data = {bankruptCount: 2, reward: {chips: 2000}} bankruptCount:剩余领取次数, chips:可以领取的游戏币数
errorCallback(error)
error = {ret: 1203} 1203 破产补助已经用完,去充值
*/
getBankruptInfo:function(resultCallback, errorCallback){
return HttpService.request("bankrupt.getInfo", {}, resultCallback, errorCallback);
},
/*
领取
resultCallback(data)
data = {chips: 10000}
*/
getBankruptReward:function(resultCallback, errorCallback){
return HttpService.request("bankrupt.getReward", {}, resultCallback, errorCallback);
},
/*
更新新用户状态,新手引导走完后调用
*/
updateNewUser: function(resultCallback, errorCallback){
return HttpService.request("user.isNewer", {}, resultCallback, errorCallback);
},
/*
登录转盘
resultCallback(data)
data = {index:2, point:2000}
*/
loginWheel: function(resultCallback, errorCallback){
return HttpService.request("act.loginWheel", {}, resultCallback, errorCallback);
},
};
var __define = function (o, p, g, s) { Object.defineProperty(o, p, { configurable: true, enumerable: true, get: g, set: s }); };
__define(http, 'userData', function(){
if(!this.$userData)
this.$userData = this.getUserData();
return this.$userData;
});
window.Http = http;
module.exports = http;
|
Markdown
|
UTF-8
| 68,706
| 3.4375
| 3
|
[] |
no_license
|
## 记忆时间
## 卡片
### 0101. 反常识卡——
这本书的主题核心,就是最大的反常识卡,并且注意时间脉络。
### 0201. 术语卡——四大利器
了解了目标和关键结果,接下来我们再来说说 OKR 能发挥什么作用。这里,杜尔把使用 OKR 的企业看作是一个超级英雄,OKR 能够提供四种利器。第一种利器,是让整个组织聚焦在最重要的事情上。第二种利器,是促进团队的协同。第三种利器,是对责任进行追踪。第四种利器,是挑战不可能。
第一种利器很好理解,设定 OKR 的过程,会逼着你把最重要的几个目标挑出来,然后专注在这些目标上。至于什么是最重要的目标,每个人、每个组织所处的形势不一样,判断标准也不一样。而且,还可以通过缩短时间周期,提高目标的重要性。举个例子。著名视频网站 YouTube 被谷歌收购后,流量排到了世界第三位,这已经是很厉害的成绩了。不过负责主页管理的产品经理里克·克劳发现,只有很少一部分用户会登录网站,大部分用户不登录,而不登录就体验不到保存视频、订阅频道这样的服务。这就意味着,YouTube 的很多重要功能没人用。为了解决这个问题,克劳和他的团队设定了一个为期六个月的 OKR,要改善网站的登录体验。这个 OKR 一路往上汇报到谷歌 CEO 拉里·佩奇那里,佩奇觉得,这个目标很重要,并把它提升到了公司层面。而且,佩奇缩短了这个 OKR 的周期,从六个月缩短到了三个月。这下,全公司都开始重视用户登录这个目标。克劳的团队遇到什么问题,也能得到优先的支持。最后,这个团队成功地实现了目标。设定 OKR 的过程,就是一个排序和取舍的过程,那些最重要的事情会「浮出水面」,帮你专注在最重要的事情上。
OKR 提供的第二种利器,是促进团队协同。因为 OKR 的沟通机制是透明的。设置 OKR 的过程,是组织内部非常难得的一次沟通机会。每个人制定好 OKR 之后,必须全部公开,这也就让每个人都知道组织内部的其他人,当下最关注的事情是什么。比如作者杜尔自己,就会把自己的目标写在纸上,贴在身边的白板上。别人路过他的工位,都能一眼看到。当所有人的目标都清晰可见的时候,沟通成本就会大幅降低。美国有一款很火的健身应用,叫 MyFitnessPal,在拿到 A 轮投资之后,这家公司就开始使用 OKR。公司的产品经理多,提的需求也多,但是工程师团队面临着先做哪些需求、后做哪些需求的问题。于是,这家公司之后的 OKR 会议上,各个部门的负责人会把下一阶段的需求先说出来,再一起商量如何协同,并把讨论结果写到 OKR 中,随后公之于众。OKR 的作用就在于,每开一次这样的会议,协同效果就能增进一些。
OKR 提供的第三种利器,是责任追踪。因为关键结果具有明确性,很难糊弄过关。我们举一个盖茨基金会的例子。慈善行为的效果很难评判,盖茨基金会在 2000 年成立的时候,就拥有 200 亿美元的真金白银,而且按照它的运作机制,盖茨基金会每年要花出去至少 10 亿美元。那怎么评价这 10 亿美元的使用效果呢?盖茨基金会采用了 OKR。盖茨基金会的一个目标,是消灭麦地那龙线虫病,这曾经是一种在非洲很多国家肆虐的疾病。盖茨基金会采取了循序渐进的方式,从最严重的地区开始,每年设定新的关键结果,盯住一个数字,就是发病人数。只要这个人数减少,就说明工作是有效的。目前,这个疾病全球每年发病人数已经从 2000 年的 7500 多例,下降到 2015 年的 22 例,距离最终根除的目标已经非常接近了。
OKR 提供的第四种利器,是挑战不可能,这指的是 OKR 会激励人不断向更高的结果迈进。咱们还是说谷歌 Chrome 浏览器这个例子。第一年,当时的负责人皮查伊和团队设定的关键结果是七天活跃用户数达到 2000 万。皮查伊心里清楚,达到这个关键结果很难,但是他也知道,不断挑战能力极限也是很重要的。这一年,尽管 Chrome 的网页加载速度比竞品高出 10 多倍,但结果还是只完成了不到 1000 万。不过,收获是,Chrome 浏览器的市场份额达到了 3%,而且使用过 Chrome 的人都喜欢它,这对增长产生了复合效应。于是,第二年,皮查伊和团队将关键结果定为 5000 万。你可能要说,前一年的 2000 万都没有完成,这一年定为 5000 万,是不是有点草率了?皮查伊不是这么想的。前一年的失败,让他思考问题更深入。他想要传递给团队的想法是,尽管我们没有达到目标,但我们正在为突破这一障碍奠定基础,我们需要解决一个非常基本的问题:为什么让人们尝试使用新浏览器如此困难?皮查伊开始转向电视营销,在电视上投放广告。但那一年依然只完成了 3700 万。第三年,皮查伊和团队将关键结果定到一个亿。这促使皮查伊重新思考 Chrome 业务的增长点。Chrome 在这一年从只能在 Windows 系统上使用,变成了可以在多个操作系统上使用,从而扩大了用户群。而且,他们还给那些休眠的用户发提醒,提醒他们使用 Chrome。到年底时,他们超额完成了既定的关键结果,七天活跃用户达到了一亿一千一百万。Chrome 这个案例,体现了 OKR 催人奋进的力量。它让你能够紧追关键结果,最终会超出你的想象。
### 0202. 术语卡——三个大坑
一是不要自上而下地设定 OKR;二是要勇于失败,OKR 不要与个人的绩效挂钩;三是要始终保持耐心和决心。
不要自上而下地设定 OKR。也就是说,不能从上到下地摊派目标。我们来看一个案例。假设有这么一支橄榄球队,总经理的目标就是要为球队所有者赚钱,因此他给自己设定两个关键结果,一是赢下「超级碗」,也就是美国职业橄榄球大联盟的冠军;二是球队的主场上座率要达到 90%,这样才会创造更多的收益。总经理的 OKR,分解到球队主教练,他的目标就是夺得超级碗冠军,关键结果就会包括每场比赛进攻上要拿下多少分数,而防守上又不能让对手拿下多少分数等。之后,再往下分解到进攻教练、防守教练,直到分解到每一个球员。与此同时,市场营销的负责人,则会把总经理的另一个关键结果,主场上座率达到 90%一一分解到团队中去。这样自上而下的方法,咱们在设定 KPI 的时候,可能很熟悉,因为建立 KPI 指标,首先就是要明确组织级 KPI。接下来,各部门的主管再进行分解,建立部门级 KPI。最后,再进一步细分为个人 KPI。虽然看上去很明确,但是很容易变成搞摊派。
设定 OKR,应该是自下而上的,前提是给每一个人充分的自由。对于这支橄榄球队来说,应该是从每一名队员开始,制订自己的 OKR。比如我是一名进攻球员,那我的 OKR 不应该是进攻教练告诉我的,而应该是自己主动去设定的。在设定的过程中当然要考虑很多因素,包括我去年完成了多少次得分、和队友的默契程度如何、球队的战术选择等。当我把自己的 OKR 设定好后,球队会再根据整体的需要,跟我沟通,把我最终的 OKR 确定下来。因为这个目标是我自己设定的,因此我会更有意愿去完成它。而且前边我们还说过,OKR 需要公开,这样就能促成更多的合作,在组织内部尽可能多地形成横向的、纵向的联系。这是一个形成集体共识的过程。
咱们再来看第二条原则,勇于失败,OKR 不要与个人的绩效挂钩。OKR 必须是具有挑战性的,是用来把人们带出舒适区的,因此要明确失败是不可避免的。比如在谷歌,就有两个 OKR 篮子,一类是要达成的目标,必须在给定时间内完成;一类是延展性的目标,失败率在 40% 左右。谷歌公司设定的 OKR,还跟职务升迁、年终奖多少无关。这是 OKR 和 KPI 另一个非常关键的区别,它不是用来给每个人论功行赏的,而是用来给每个人确定前进节奏的。只有这样,每个人才能没有后顾之忧地去追求关键结果。不过,尽管 OKR 只是一个指引,而不是一个成绩。但由于有的人对自己会过于严格,而有的人对自己又过于宽松,所以制定之后,还需要团队领导来进行干预调整。
最后一条原则是要始终保持耐心和决心。使用 OKR 是一个过程,总是会有错误。所以,OKR 也不是一成不变的,可以灵活调整。作者在推广 OKR 的过程中就发现,大部分企业要完整地走完三到四次设定 OKR 的流程,才能真正上手。之后随着使用次数的增多,员工对 OKR 的理解也会逐步加深。
### 0203. 术语卡——CFR
CFR 用来解决如何使用 OKR,指的是对话(Conversation)、反馈(Feedback)、识别(Recognition)。通过一起使用 OKR 和 CFR,可以形成快速的反馈循环,持续改进,不断优化企业的组织结构和资源配置,帮助组织实现关键结果,并最终实现目标。作者把这个过程,称为绩效持续管理。谷歌公司使用 OKR,在硅谷是非常有名的。咱们就以谷歌公司为案例,看看怎么把 OKR 和 CFR 结合在一起使用。
在谷歌公司,一个典型的 OKR 循环,是从开年前 4 到 6 周,也就是每年 11 月中旬或者 12 月初开始的,这时要对整个公司一季度和全年 OKR 进行头脑风暴。在 12 月中旬,要确认整个公司一季度和全年的 OKR,并公布出来。新年到来后,团队就要开始 CFR 的第一个步骤:对话,围绕一季度的 OKR 进行充分沟通。每个人先要提出自己这一季度的目标,不过这个目标会被挑战,直到达成共识,这个步骤大概有一周的时间。第一周后,就要在全公司范围内,公布每个人一季度的 OKR。因为每个人的 OKR 都会被公开,如果谁没有设定 OKR,全谷歌的人都知道,因此也不需要谁催,你就会觉得不好意思,会主动去沟通,把自己的 OKR 设定好。
在整个季度中,就要进行 CFR 的第二个步骤:反馈,不断追踪和确认 OKR 的进展情况。具体的反馈周期,会根据项目的情况各有不同。有些处于关键节点的项目,甚至需要每天都要反馈,研究第二天如何调整。有些已经成熟的项目,可能一周才需要反馈一次。最后,到了 3 月下旬,就要根据 OKR 的完成情况进行打分,也就是 CFR 的第三个步骤:识别。也就是要评价这一个季度的 OKR 完成情况。为了更好地完成识别这个步骤,谷歌还设计了一套打分系统,这套系统自动产生识别结果,不能人为干涉。打分的区间是 0-1 分,并且采取类似交通信号灯的形式。0.7-1 分属于绿灯区,就是基本或者很好地完成了关键结果,下一步可能要设定更有挑战性的目标了;0.4-0.6 分属于黄灯区,虽然取得了进展,但没有能够完成关键结果,下一个周期还需要更加努力;0-0.3 分属于红灯区,没有在完成关键结果上,取得实质性的进步。如果已经好几次都处于红灯区,很可能就要考虑这个项目的可行性问题了。在谷歌的 OKR 环境下,能完成 70%,就被认为是成功的。你不必将每一个 OKR 都变成绿色,因为这也不能说明你的工作做得非常出色,只能说明你的关键结果设定得太低了。OKR 不是让你获得满足感的,而是要让你有驱动力的。如果你小富即安,不去追求更大的成功,也不是谷歌需要的人才。
咱们还是回到 Chrome 的例子。第一年的关键结果是使用人数达到 2000 万,实际达成了 1000 万,得分是 0.5 分,属于黄灯区,所以这个项目依然有继续推进下去的可能。当时的负责人皮查伊和团队也在不断通过对话和反馈,寻找解决方案。第二年的关键结果是使用人数达到 5000 万,结果是实际达成 3700 万,得分是 0.7 分,这已经进入绿灯区了,说明工作已经开始逐渐进入正轨。所以在下一年,皮查伊和团队才有信心把关键结果定为使用人数一个亿,并使用了前所未有的推广力度,配合产品稳定性和用户体验的提升。最终的结果是超额完成,得分超过了 1 分,Chrome 浏览器也完成了「起飞」的过程。
刚才我们说过,谷歌会把目标放在两个篮子里,一个篮子里放那些完成可能性比较大的目标,一个篮子里放那些天马行空、异想天开的目标。所以,如果第二个篮子里的任务被打了低分,进入红色区域,一定程度上讲,也是正常的。这第二个篮子存在的意义,就是让人永不满足,继续向新的目标发起挑战。
当 CFR 的一个循环结束之后,新的循环马上就开始了,可以说是无缝衔接。全公司就开始对第二季度的 OKR 开展头脑风暴,开启新一轮的对话步骤。这时,可以增加之前没有设定的目标,但是不能删除已有的、但是已经不打算去完成的目标,即便这些目标已经过时、或者已经没有意义了,依然要留在那里。这些被放弃的目标,忠实地记录着使用 OKR 过程中出现的偏差,这对于未来更好地使用 OKR,也是非常珍贵的一笔财富。
### 0301. 人名卡——约翰·杜尔
约翰·杜尔,本书的作者。
本书作者约翰·杜尔是硅谷的一位传奇风险投资人,被称为「风险投资界的迈克尔·乔丹」。他目前是风险投资公司凯鹏华盈的合伙人、董事长,也是包括谷歌和亚马逊在内的很多公司的早期投资者和董事会成员。他还曾在美国奥巴马政府期间,担任白宫就业和竞争力委员会成员,在美国政商两界都具有巨大的影响力。杜尔自己多年来使用 OKR,还在不同规模和性质的企业和组织中推广 OKR。他在本书里介绍了如何使用 OKR,实现增长。
### 0401. 金句卡——
最后根据他写的非常震撼的话语——产生一张金句卡。
### 0501. 任意卡——
最后还有一张任意卡,记录个人阅读感想。
## 听书
第一部分详细介绍 OKR 这个工具,第二部来介绍 OKR 该怎么使用。
OKR,指的是「目标和关键结果」,这是一种目标和绩效管理方式,更是一种内部沟通机制。目标就是你想要达成什么,也就是解决「是什么」的问题。关键结果则是你要如何达成目标,解决「怎么做」的问题。但是,在设定目标和关键结果之前,一定要想清楚「为什么」的问题。在实践 OKR 的过程中,必须和 CFR 结合起来,以季度为周期,开启 OKR 的循环。随着员工对 OKR 的理解不断加深,OKR 的作用也会逐渐显示出来。
杜尔把 OKR 比作是一把「瑞士军刀」,适用范围很广。对于一家初创企业而言,OKR 帮助企业利用并专注于有限的资源;对于在扩张阶段的企业,OKR 可以促进企业整合新的资源;对于一家大型公司,OKR 则可以确保员工与企业的使命、价值观保持一致。但是,OKR 是一种工具,而不是一种武器。OKR 不是神奇的解决方案,无法取代强而有力的企业文化,也无法产生强大的领导力。
本书作者约翰·杜尔是硅谷的一位传奇风险投资人,被称为「风险投资界的迈克尔·乔丹」。他目前是风险投资公司凯鹏华盈的合伙人、董事长,也是包括谷歌和亚马逊在内的很多公司的早期投资者和董事会成员。他还曾在美国奥巴马政府期间,担任白宫就业和竞争力委员会成员,在美国政商两界都具有巨大的影响力。杜尔自己多年来使用 OKR,还在不同规模和性质的企业和组织中推广 OKR。他在本书里介绍了如何使用 OKR,实现增长。
KPI 有明确的考核指标,跟奖金激励挂钩,但是 OKR 更侧重目标管理,跟升职加薪没有直接关系。KPI 是一种压力管理方法,能让你为了完成考核指标而埋头工作,但你有可能只顾得上完成指标,而不管实际效果。OKR 则是一种愿景管理方法,让你工作时不会偏离方向,取得实实在在的进步。
从谷歌的两位创始人佩奇和布林开始,到谷歌的每一名员工,都会以季度为单位,不断公布和校准公司和个人层面的 OKR,这一习惯一直延续至今,从未中断。在谷歌工作的每一个人,都会自觉地把自己的 OKR 放在自己的网页上,所有人都能看到。为什么杜尔对 OKR 非常熟悉呢?OKR 是英特尔的传奇 CEO 安迪·格鲁夫最早创建的。1970 年代,杜尔在英特尔公司工作的时候,就从格鲁夫那里学会了 OKR。杜尔不但在工作中一直使用 OKR,还把这个工具介绍给他投资的公司。
设定目标并不是一个难事,每个组织、每个人都有自己的目标。但是,设定一个正确的目标,却并不容易。在回答「是什么」这个问题之前,你还要先确定,为什么要设立这个目标,要找到目标的「意义感」。很多企业会把达到一定的销售额或者利润作为目标,但一个数字是无法真正起到激励作用的。而目标一旦有了意义,整个团队都会一往无前。杜尔投资的一家公司,就给他留下了深刻的印象。这是一家用大数据的方式,为所服务的客户管理员工健康信息的公司。这家公司的创始人吉妮曾在谷歌医疗工作。吉妮曾经全力以赴地做了一件在经济上意义不大的事情。
当时公司只有 15 个人,手头还有很多其他工作,她依然拿下了美国联邦医疗保障计划项目,并克服诸多困难,在一年内完成了这个项目。一开始杜尔也并不理解,后来他才知道吉妮为什么要这样做。吉妮 9 岁的时候,一家人去迪士尼乐园玩。但她的弟弟却发作了癫痫,家人手忙脚乱。吉妮一家都是韩国移民,父母英语不好,吉妮必须帮家人申请公共医疗补助。如果失败,不仅她弟弟的病无法医治,他们全家也会破产。吉妮挺了过来,但她不希望再有人遇到类似的情况。所以,美国联邦医疗保障计划项目,对于吉妮而言,就是她为低收入人口医疗保障计划做出的贡献。
想清楚一个具有说服力的「为什么」,目标的设定才会有使命感。目标不能只是某一句话、某个数字或某个奖项,作者心中的好目标,至少要满足三个条件:首先,这个目标必须是重要而具体的;其次,这个目标必须是行动导向的;第三,这个目标必须是鼓舞人心的。
1『目标不要设的太具体,比如销售额、利润等,这些可以作为关键结果,目标一定要有「意义感」,能更有效的把团队俱到一个方向,但也不能太抽象,要具体化;好目标的三原则:重要而具体的、行动导向的和鼓舞人心的。』
举一个公益组织的例子。爱尔兰摇滚乐队 U2 乐队的主唱博诺就对这三个标准很有心得。博诺创建了一个公益组织,初衷是跟全球的贫困问题和疾病问题奋战。但你一听也能发现,这只能算是一个宏大的愿景,不是目标。目标必须是具体的,于是博诺把目标设定为两个,一是替世界上最贫困的国家解除债务,这是为了解决贫困问题;二是让全球所有国家都能获得抗艾滋病的药物,这是为了解决疾病问题。这两个目标把一个抽象的愿景具体化了。而且,因为有了国家债务、抗艾滋病这两个具体抓手,又给具体的行动指明了方向。当一笔笔债务被偿还、一车车药物被送到患者手中时,这些反馈,又能对工作人员起到激励作用。在这两个目标的引领下,博诺的公益组织影响力越来越大,包括奥巴马在内的各界人士也都纷纷给他站台宣传。
有了「为什么」和「是什么」,接下来咱们该说说「怎样做」,也就是关键结果的问题了。杜尔也给出了一个好的关键结果的标准:首先这个关键结果必须是明确的,不能含糊其辞。其次这个关键结果必须要有明确的完成时间。三是这个关键结果既要有挑战性,也要务实,应该是属于必须蹦一下才能实现的结果。四是这个关键结果必须是可以衡量的,也就是说,是完成了,还是没完成,有一个明确的标准,不能有中间的模糊地带。最后这个关键结果必须是可被事后验证的。
1『关键结果的指标:1)必须是明确的,不能含糊其辞。2)必须要有明确的完成时间。3)属于必须蹦一下才能实现的结果。4)必须是可以衡量的。5)必须是可被事后验证的。』
咱们来举个例子分别说说。2008 年,现在的谷歌公司总裁皮查伊,当时还在负责谷歌工具栏的开发。他接到了一个项目,目标是做出世界上最好的网络浏览器。要实现这个目标,需要将什么作为关键结果呢。是浏览器的下载量么?是浏览器的好评数量么?是浏览器的使用时长么?皮查伊和团队讨论了很多天,最终确定了一个关键结果:浏览器的使用人数。因为他们相信,用户自己会判断哪个浏览器更好用。
2008 年当年,皮查伊将关键结果定为:在一年的时间里,让浏览器的使用人数达到 2000 万。这个关键结果非常明确,完成时限是一年,非常具有挑战性,但是凭借谷歌搜索以及其他产品当时聚集的 1.47 亿的访问量,也并不是不可能实现。2000 万这个数字,就是衡量标准,在一年之后,可以非常容易地进行验证,关键结果是达成了还是没达成。因此,这就是一个好的关键结果。而后来的故事,你可能已经知道了,谷歌推出的 Chrome 浏览器,现在已经是全世界使用人数最多的浏览器,全球市场份额超过 60%,远远超过了 Windows 系统自带的 IE 浏览器。
了解了目标和关键结果,接下来我们再来说说 OKR 能发挥什么作用。这里,杜尔把使用 OKR 的企业看作是一个超级英雄,OKR 能够提供四种利器。第一种利器,是让整个组织聚焦在最重要的事情上。第二种利器,是促进团队的协同。第三种利器,是对责任进行追踪。第四种利器,是挑战不可能。
2『四大利器要能说出来,做一张术语卡片。』
第一种利器很好理解,设定 OKR 的过程,会逼着你把最重要的几个目标挑出来,然后专注在这些目标上。至于什么是最重要的目标,每个人、每个组织所处的形势不一样,判断标准也不一样。而且,还可以通过缩短时间周期,提高目标的重要性。举个例子。著名视频网站 YouTube 被谷歌收购后,流量排到了世界第三位,这已经是很厉害的成绩了。不过负责主页管理的产品经理里克·克劳发现,只有很少一部分用户会登录网站,大部分用户不登录,而不登录就体验不到保存视频、订阅频道这样的服务。这就意味着,YouTube 的很多重要功能没人用。为了解决这个问题,克劳和他的团队设定了一个为期六个月的 OKR,要改善网站的登录体验。这个 OKR 一路往上汇报到谷歌 CEO 拉里·佩奇那里,佩奇觉得,这个目标很重要,并把它提升到了公司层面。而且,佩奇缩短了这个 OKR 的周期,从六个月缩短到了三个月。这下,全公司都开始重视用户登录这个目标。克劳的团队遇到什么问题,也能得到优先的支持。最后,这个团队成功地实现了目标。设定 OKR 的过程,就是一个排序和取舍的过程,那些最重要的事情会「浮出水面」,帮你专注在最重要的事情上。
OKR 提供的第二种利器,是促进团队协同。因为 OKR 的沟通机制是透明的。设置 OKR 的过程,是组织内部非常难得的一次沟通机会。每个人制定好 OKR 之后,必须全部公开,这也就让每个人都知道组织内部的其他人,当下最关注的事情是什么。比如作者杜尔自己,就会把自己的目标写在纸上,贴在身边的白板上。别人路过他的工位,都能一眼看到。当所有人的目标都清晰可见的时候,沟通成本就会大幅降低。美国有一款很火的健身应用,叫 MyFitnessPal,在拿到 A 轮投资之后,这家公司就开始使用 OKR。公司的产品经理多,提的需求也多,但是工程师团队面临着先做哪些需求、后做哪些需求的问题。于是,这家公司之后的 OKR 会议上,各个部门的负责人会把下一阶段的需求先说出来,再一起商量如何协同,并把讨论结果写到 OKR 中,随后公之于众。OKR 的作用就在于,每开一次这样的会议,协同效果就能增进一些。
OKR 提供的第三种利器,是责任追踪。因为关键结果具有明确性,很难糊弄过关。我们举一个盖茨基金会的例子。慈善行为的效果很难评判,盖茨基金会在 2000 年成立的时候,就拥有 200 亿美元的真金白银,而且按照它的运作机制,盖茨基金会每年要花出去至少 10 亿美元。那怎么评价这 10 亿美元的使用效果呢?盖茨基金会采用了 OKR。盖茨基金会的一个目标,是消灭麦地那龙线虫病,这曾经是一种在非洲很多国家肆虐的疾病。盖茨基金会采取了循序渐进的方式,从最严重的地区开始,每年设定新的关键结果,盯住一个数字,就是发病人数。只要这个人数减少,就说明工作是有效的。目前,这个疾病全球每年发病人数已经从 2000 年的 7500 多例,下降到 2015 年的 22 例,距离最终根除的目标已经非常接近了。
OKR 提供的第四种利器,是挑战不可能,这指的是 OKR 会激励人不断向更高的结果迈进。咱们还是说谷歌 Chrome 浏览器这个例子。第一年,当时的负责人皮查伊和团队设定的关键结果是七天活跃用户数达到 2000 万。皮查伊心里清楚,达到这个关键结果很难,但是他也知道,不断挑战能力极限也是很重要的。这一年,尽管 Chrome 的网页加载速度比竞品高出 10 多倍,但结果还是只完成了不到 1000 万。不过,收获是,Chrome 浏览器的市场份额达到了 3%,而且使用过 Chrome 的人都喜欢它,这对增长产生了复合效应。于是,第二年,皮查伊和团队将关键结果定为 5000 万。你可能要说,前一年的 2000 万都没有完成,这一年定为 5000 万,是不是有点草率了?皮查伊不是这么想的。前一年的失败,让他思考问题更深入。他想要传递给团队的想法是,尽管我们没有达到目标,但我们正在为突破这一障碍奠定基础,我们需要解决一个非常基本的问题:为什么让人们尝试使用新浏览器如此困难?皮查伊开始转向电视营销,在电视上投放广告。但那一年依然只完成了 3700 万。第三年,皮查伊和团队将关键结果定到一个亿。这促使皮查伊重新思考 Chrome 业务的增长点。Chrome 在这一年从只能在 Windows 系统上使用,变成了可以在多个操作系统上使用,从而扩大了用户群。而且,他们还给那些休眠的用户发提醒,提醒他们使用 Chrome。到年底时,他们超额完成了既定的关键结果,七天活跃用户达到了一亿一千一百万。Chrome 这个案例,体现了 OKR 催人奋进的力量。它让你能够紧追关键结果,最终会超出你的想象。
了解了 OKR 的内涵和能提供的四种利器,在设定 OKR 的过程中,依然会碰到很多「坑」。作者在书中就给出了几条原则,帮助咱们躲开这些「坑」,这几条原则包括:一是不要自上而下地设定 OKR;二是要勇于失败,OKR 不要与个人的绩效挂钩;三是要始终保持耐心和决心。
不要自上而下地设定 OKR。也就是说,不能从上到下地摊派目标。我们来看一个案例。假设有这么一支橄榄球队,总经理的目标就是要为球队所有者赚钱,因此他给自己设定两个关键结果,一是赢下「超级碗」,也就是美国职业橄榄球大联盟的冠军;二是球队的主场上座率要达到 90%,这样才会创造更多的收益。总经理的 OKR,分解到球队主教练,他的目标就是夺得超级碗冠军,关键结果就会包括每场比赛进攻上要拿下多少分数,而防守上又不能让对手拿下多少分数等。之后,再往下分解到进攻教练、防守教练,直到分解到每一个球员。与此同时,市场营销的负责人,则会把总经理的另一个关键结果,主场上座率达到 90%一一分解到团队中去。这样自上而下的方法,咱们在设定 KPI 的时候,可能很熟悉,因为建立 KPI 指标,首先就是要明确组织级 KPI。接下来,各部门的主管再进行分解,建立部门级 KPI。最后,再进一步细分为个人 KPI。虽然看上去很明确,但是很容易变成搞摊派。
设定 OKR,应该是自下而上的,前提是给每一个人充分的自由。对于这支橄榄球队来说,应该是从每一名队员开始,制订自己的 OKR。比如我是一名进攻球员,那我的 OKR 不应该是进攻教练告诉我的,而应该是自己主动去设定的。在设定的过程中当然要考虑很多因素,包括我去年完成了多少次得分、和队友的默契程度如何、球队的战术选择等。当我把自己的 OKR 设定好后,球队会再根据整体的需要,跟我沟通,把我最终的 OKR 确定下来。因为这个目标是我自己设定的,因此我会更有意愿去完成它。而且前边我们还说过,OKR 需要公开,这样就能促成更多的合作,在组织内部尽可能多地形成横向的、纵向的联系。这是一个形成集体共识的过程。
咱们再来看第二条原则,勇于失败,OKR 不要与个人的绩效挂钩。OKR 必须是具有挑战性的,是用来把人们带出舒适区的,因此要明确失败是不可避免的。比如在谷歌,就有两个 OKR 篮子,一类是要达成的目标,必须在给定时间内完成;一类是延展性的目标,失败率在 40% 左右。谷歌公司设定的 OKR,还跟职务升迁、年终奖多少无关。这是 OKR 和 KPI 另一个非常关键的区别,它不是用来给每个人论功行赏的,而是用来给每个人确定前进节奏的。只有这样,每个人才能没有后顾之忧地去追求关键结果。不过,尽管 OKR 只是一个指引,而不是一个成绩。但由于有的人对自己会过于严格,而有的人对自己又过于宽松,所以制定之后,还需要团队领导来进行干预调整。
最后一条原则是要始终保持耐心和决心。使用 OKR 是一个过程,总是会有错误。所以,OKR 也不是一成不变的,可以灵活调整。作者在推广 OKR 的过程中就发现,大部分企业要完整地走完三到四次设定 OKR 的流程,才能真正上手。之后随着使用次数的增多,员工对 OKR 的理解也会逐步加深。
如何使用 OKR。在书中,作者给出了一个和 OKR 配套的机制,也就是 CFR,指的是对话(Conversation)、反馈(Feedback)、识别(Recognition)。通过一起使用 OKR 和 CFR,可以形成快速的反馈循环,持续改进,不断优化企业的组织结构和资源配置,帮助组织实现关键结果,并最终实现目标。作者把这个过程,称为绩效持续管理。谷歌公司使用 OKR,在硅谷是非常有名的。咱们就以谷歌公司为案例,看看怎么把 OKR 和 CFR 结合在一起使用。
在谷歌公司,一个典型的 OKR 循环,是从开年前 4 到 6 周,也就是每年 11 月中旬或者 12 月初开始的,这时要对整个公司一季度和全年 OKR 进行头脑风暴。在 12 月中旬,要确认整个公司一季度和全年的 OKR,并公布出来。新年到来后,团队就要开始 CFR 的第一个步骤:对话,围绕一季度的 OKR 进行充分沟通。每个人先要提出自己这一季度的目标,不过这个目标会被挑战,直到达成共识,这个步骤大概有一周的时间。第一周后,就要在全公司范围内,公布每个人一季度的 OKR。因为每个人的 OKR 都会被公开,如果谁没有设定 OKR,全谷歌的人都知道,因此也不需要谁催,你就会觉得不好意思,会主动去沟通,把自己的 OKR 设定好。
在整个季度中,就要进行 CFR 的第二个步骤:反馈,不断追踪和确认 OKR 的进展情况。具体的反馈周期,会根据项目的情况各有不同。有些处于关键节点的项目,甚至需要每天都要反馈,研究第二天如何调整。有些已经成熟的项目,可能一周才需要反馈一次。最后,到了 3 月下旬,就要根据 OKR 的完成情况进行打分,也就是 CFR 的第三个步骤:识别。也就是要评价这一个季度的 OKR 完成情况。为了更好地完成识别这个步骤,谷歌还设计了一套打分系统,这套系统自动产生识别结果,不能人为干涉。打分的区间是 0-1 分,并且采取类似交通信号灯的形式。0.7-1 分属于绿灯区,就是基本或者很好地完成了关键结果,下一步可能要设定更有挑战性的目标了;0.4-0.6 分属于黄灯区,虽然取得了进展,但没有能够完成关键结果,下一个周期还需要更加努力;0-0.3 分属于红灯区,没有在完成关键结果上,取得实质性的进步。如果已经好几次都处于红灯区,很可能就要考虑这个项目的可行性问题了。在谷歌的 OKR 环境下,能完成 70%,就被认为是成功的。你不必将每一个 OKR 都变成绿色,因为这也不能说明你的工作做得非常出色,只能说明你的关键结果设定得太低了。OKR 不是让你获得满足感的,而是要让你有驱动力的。如果你小富即安,不去追求更大的成功,也不是谷歌需要的人才。
咱们还是回到 Chrome 的例子。第一年的关键结果是使用人数达到 2000 万,实际达成了 1000 万,得分是 0.5 分,属于黄灯区,所以这个项目依然有继续推进下去的可能。当时的负责人皮查伊和团队也在不断通过对话和反馈,寻找解决方案。第二年的关键结果是使用人数达到 5000 万,结果是实际达成 3700 万,得分是 0.7 分,这已经进入绿灯区了,说明工作已经开始逐渐进入正轨。所以在下一年,皮查伊和团队才有信心把关键结果定为使用人数一个亿,并使用了前所未有的推广力度,配合产品稳定性和用户体验的提升。最终的结果是超额完成,得分超过了 1 分,Chrome 浏览器也完成了「起飞」的过程。
刚才我们说过,谷歌会把目标放在两个篮子里,一个篮子里放那些完成可能性比较大的目标,一个篮子里放那些天马行空、异想天开的目标。所以,如果第二个篮子里的任务被打了低分,进入红色区域,一定程度上讲,也是正常的。这第二个篮子存在的意义,就是让人永不满足,继续向新的目标发起挑战。
当 CFR 的一个循环结束之后,新的循环马上就开始了,可以说是无缝衔接。全公司就开始对第二季度的 OKR 开展头脑风暴,开启新一轮的对话步骤。这时,可以增加之前没有设定的目标,但是不能删除已有的、但是已经不打算去完成的目标,即便这些目标已经过时、或者已经没有意义了,依然要留在那里。这些被放弃的目标,忠实地记录着使用 OKR 过程中出现的偏差,这对于未来更好地使用 OKR,也是非常珍贵的一笔财富。
## 书评
### 01
即一个目标(Objective)+ 多个可量化的关键结果(Key Results)。从问题的角度也更好理解 OKR。在公司、团队扩大的过程(尤其中 / 大型团队),常出现这样的问题:1)团队整体缺乏工作重点、分配资源困难。2)团队内的各成员间协作困难,不知道其他人在干什么,或者每个人有不同但都有意义的目标。这两者会导致团队的产出平庸、工作效率低下,OKR 就是用来解决这些问题的。具体做法:每个团队 / 人公开自己的目标,并且季度性地制定目标。这样,每个人知道团队的整体目标、其他人的目标,进一步也能集中工作方向和资源了。
要点:1)OKR 分成 Commited OKR 与 Asiprational OKR: 前者是 KPI(一定要达到),后者是努力争取的(不一定要达到)。2)将 OKR 的结果与薪水脱钩(在 Google 内部权重占比 < 1/3):因为,高标准的 OKR 没达标 vs. 简单的 OKR 达标了,给前者钱多还是后者?如果都倾向于达标,那么最终的 OKR 就会趋向平庸、保守,公司也因此变得平庸。3)用质量型 key results 对负面效果控制:比如 KR 定成某产品达到 10000 注册用户,那这个是高额补贴来的,还是用户口碑的自发增长的?所以需要定义其他的指标,保证执行的质量,而不仅仅是数量。4)每个人都公开 OKR:这样能知道他人关心什么,可以更好地合作。5)OKR 可随时调整,不是一成不变的。6)OKR 的制定需要时间,下图是 Google 的年度 OKR 制定的时间表,可以看出需要不少时间、几个月(具体见书中 Resource 2)。7)OKR 对中、大型团队最有效,但小团队最好也能尽早使用,因为团队的工作方式需要时间养成(见第 14 章)。8)来自一线员工的 OKR 越多越好(最好如此,但非必须,实践中还是自上而下更多)。
一些好的案例:1)Remind(第 5 章): 体现了 OKR 对收拢工作内容的重要性,也就是推迟一些「有用但不是当前最有用的事情」。2)MyFitnessPal(第 8 章): 真实展现了创业公司在扩大团队时出现的问题,工作内容、时间各自矛盾,缺乏同步,以及 OKR 能达到的效果。3)Pichai & Chrome(第 13 章): Pichai 和 Chrome 是如何一个个 OKR 前进的。4)Youtube(第 14 章): 和 OKR 无关,但很有料,主要是做决策后对指标有短期负面影响如何处理。
一些疑问:1)OKR 工具、更多完整的例子:书中没怎么说。个人感觉 OKR 的使用应该并不复杂(类似看板 / Trello 这类简单有效的方法论),但看了市面上一些工具,感觉都太复杂。2)OKR 适用于哪些类似的团队:Pixar, Bridgewater, 海底捞采用的是 OKR 吗?创意型和执行性团队都适用吗?3)如何得出 KR:如果说 KR 是「怎么实现目标」,但很多时候我们并不知道怎么去实现一个目标,更不要说找到一个可量化的 KR。4)OKR 在哪些情况下不适用:因为 Google 失败的产品也不少,又有哪些团队是采用了 OKR 而造成了不良效果的?
批评与阅读建议。让我遗憾的是,这本书没有体现出作者 1/10 的功力,对于 OKR 我觉得并没有讲明白。以作者 KPCB 老大的身份,我期待的是 Ray Dalio, Howard Marks 的水平 [1]。所以自己拿到这本书反复在读,尝试读出一点深度,毕竟是大佬写的,可是确实写得不太好。建议再次读的时候,可以连续阅读书中的第 4/7/10/12 章,即 OKR 的核心原则,并结合书后的 Resource1/2/4。因为书中案例穿插多,但缺乏深度,反而很容易忘了 OKR 的核心原则是怎样的。补充:最近看到 Zapier 的负责人在讲他们的 OKR 实践,就很接地气,见:[Mike Knoop on Product and Design Processes for Remote Teams with Kevin Hale - YouTube](https://www.youtube.com/watch?v=zF84IMiSP7I&t=2045s)。
对我来说,这本书最大的帮助是让我意识到近半年一事无成的状态,很多时候我会有想法,但缺乏 OKR 这样按季度规划、执行。于是回过头来,发现很多事情只是在想,但没决心做。时间不过是在每天打开朋友圈、豆瓣、知乎中消耗掉了。缺乏 OKR 背后的长期性思维、专注的能力。接下来尝试把 OKR 用到自己的生活中,做些自己真正想要的事。就像 Larry Page 在前言里写的 —— "I wish I had this book 19 years ago, when we founded google. Or even before that, when I was only managing myself." 一个季度,去达成一个真正自己想要的目标 —— 这是我从 OKR 上体会最深的。
### 02
我是从 2012 年开始接触 OKR,那时在一个创业公司担任核心开发,创始人都是阿里系出身,他们将 OKR 的理念引入到公司。我那时对 OKR 理解还比较粗浅,觉得和 KPI 并没有什么差异,依样画葫芦地制定 OKR、进行 Review。几年后我逐步感受到 OKR 的作用,我逐步 OKR 管理引入自身事务管理,按年的维度进行自我管理。([从 2017 到 2018 - Log4D](https://blog.alswl.com/2018/01/2017-2018/))
我也在学习如何更有效管理组织、管理自己,因此还学习 Google re:Work 团队出品的一系列文章,不断学习正确使用的技巧。这本「这就是 OKR」比之 re:Work 团队相对零散的文章更聚焦,讲述了 OKR 的核心:聚焦、透明、责任、卓越。我理解 OKR 只是一个名词,只要将 OKR 的核心落实到位,无所谓叫什么名词。本书还介绍了 CFR,这是常规意义上的管理手段,我在感受也不强烈。
2『评书者的博客:[Archives - Log4D](https://blog.alswl.com/archives/),可以爬取下来,正好做一个爬取博客的模板。』
道尔(John Doerr )是硅谷大名鼎鼎的风险投资人,从谷歌到亚马逊到推特,点石成金。他最近的一本书却不是讲如何发现风险投资的机会,而是把自己的座右铭「点子容易,做事难」在「目标与关键结果」(Objective and Key Results,简称 OKR) 的框架下,结合亲身经历,仔细介绍给读者。
道尔本人早年加入英特尔,那时候,安迪·葛拉夫是英特尔总裁,亲自给新人上课。葛拉夫说,他以前工作的公司,招人、用人的时候看人的专长,一大堆能人,但不重视如何把专长在工作中发挥出来。英特尔不同,不论你的背景是什么、知道多少东西,主要是看你如何学习并运用所学的知识,把事情干成了。葛拉夫从美国管理学鼻祖 Peter Drucker 那里学来了目标式管理方式,加以改进,也就是这个 OKR。
葛拉夫说,「目标」就是方向,你要做成什么。「关键结果」是如何实现一个目标,是具体的、有时间限制的、具有挑战性但又是实实在在的。目标可以宏大,甚至能激励人,但结果是具体可测的,做到了还是没做到,一是一 、二是二,没有商量的余地。道尔为这种管理模式总结出了这样几个关键点:
第一,精力集中做最重要的事情。工作中要分清主次,什么是关键,什么是有帮助但非关键一定要清楚。葛拉夫常说,「少就是多」,几个清晰明了的目标,让团队知道对什么说「yes」,对什么说「no」,才能万众一心干大事。另外,取舍优先选择的时候,一定要给大家一个理由,否则不能说服人。
第二,部门之间协调一致。把明确的目标与关键结果写出来,公司上下、各部门之间、领导与员工之间就可以互相了解、支持,尽早发现问题,不会各干各的,末了互相消耗资源甚至明里、暗里唱对台戏。葛拉夫说,有一半的目标应该让团队、员工自己自下而上地定立,然后互相对比,这样才不会出现上层或某个部门强制某个目标但员工不买账,最后什么也做不成。
第三,定期检查,各负其责。有了明确的关键结果,就可以定期做客观的评价,对事不对人。葛拉夫说,这个方法是为了更好地测量、引导员工的进度,而不是万一做不到而成为惩罚员工的工具。在预定的时间中没有取得关键结果,那就及时改变做法,让事情回到正轨,或改变目标、策略。重要的是帮助员工把事情做好、做成。要记住,短期目标往往是带来真正结果的关键,不可忽视。
第四,争取超越。目标要定得高些,起到激励人的作用。可以一半的目标是必须实现的,另一半是努力方向,以便让团队超级发挥,让不可能成为可能。葛拉夫说,不要怕失败,远大目标常常可以激发团队的活力,发掘出来最大的潜力。这有时要有点儿耐心,坚持不懈。
道尔虽然是个风险投资人,却热衷于帮助创业者利用 OKR 把事情真正做成。他在书中为上面的四个关键点各举了几个例子。其中很有意思的一个是当年英特尔如何在产品落后的情况下,大举反攻,取得计算机芯片产业龙头的故事。
1978 年,英特尔开发出了第一个 16 位高性能芯片 8086,在市场上大卖特卖。可是不久竞争对手也开始推出自已的产品,摩托罗拉的 68000 和 Zilog 的 Z8000。这些产品比英特尔的 8086 更对工程师的胃口,开始大行其道。1979 年 11 月,英特尔的一个销售经理看到了问题的严重性,向总部告急。当时的英特尔在葛拉夫的领导下,紧急动员,一个星期内公司上层就意识到问题的严重性,立即动手制订方案,把摩托罗拉的 68000 定为靶标(上面提到的第一条,精力集中做重要的事情),全公司动员,群策群力(第二条,部门之间协调一致),要在一年内取得 2000 个客户设计,这是平时销售人员定量的三倍(第四条,争取超越)。也正是在这个计划的执行过程中,英特尔在原先产业界的目标管理方式方法上加上了「通过如此测量」(as measured by) 这个办法,确保了结果与目标的一致(第三条,定期检查,各负其责)。当时使用的 OKR 现在还有案可查,被道尔列在书中。(注,OKR 在英特尔被称为 iMBO,Intel Management by Objectives)。
1980 年 1 月,公司开始布置具体计划。二季度,销售人员全面推进新的销售策略。改变产品设计是来不及了,英特尔于是绕过客户的工程师们,集中力量直接向客户的 CEO、管理层推销公司一整套的产品方案、可靠的质量和服务。三季度,2000 个客户设计进展不错,但离目标还差不少。公司管理层开始对销售人员说,如果目标实现了,所有参与的人会与家人一起被邀请去塔希提(Thahiti) 度假。同时在销售人员的信箱里开始出现塔希提的风光画册。到年底,英特尔共赢得了 2300 个客户设计,取得市场占有率的 85%,其中一个客户正是 IBM,这个设计带来了 IBM 兼容机的出现,使个人电脑产品发生了革命性的变化,造就了英特尔、微软等公司的产业领导地位。这就是英特尔历史上有名的 Operation Crush (粉碎行动)。
道尔在书中还花篇幅介绍了自己的一些管理理念。比如他不主张年度评估,而是提倡经理与员工有定期、及时的沟通,通过交流、反馈,表彰的方法,来达到管理的目的。这种交流应该集中在:1)目标设定及反思,2)及时的情况汇报,3)双向的帮助,4)职务、事业成长,5)对员工表现的简明评价。反馈应该正反都有,要具体,好坏都要给出理由。表彰则要多样化,同事之间可以互相表彰,给出具体的得到表彰的要求,给出具体的例子,门槛不要太高而且及时,并且一定要与公司目标与结果联系起来。这种交流,不要与员工的报酬混在一起,那样往往都去「向钱看」了,影响了交流与提高。
道尔还提到企业文化的重要性。他引用葛拉夫的话,认为文化是一组值价观和信念,再加上一个公司里事情是怎样做成的。文化是确保 OKR 能有效实行的媒介,OKR 是确保企业文化不流于形式的方法。
### 04
2019 年春节前夕,百度(BIDU)内部刮起绩效风暴。这场风暴席卷百度近 5 万名在职员工。从最高决策层到最基层员工,无一能够置身事外。此次绩效变革由百度元老崔珊珊推动,引入员工考核系统 OKR(Objectives and Key Results),使百度全面「去 KPI 化」。OKR 意为「目标和关键成果法」,强调确立目标,明确目标需达成的可量化「关键结果」,再通过结果完成考核。最近 OKR 在国内越来越火了,最明显的例子就是百度从上到下的推动 OKR 实施。各种书籍把 OKR 说的很透彻,也很多,但总是把握不住关键点,所以尝试换个方向聊下:为什么 OKR?工业时代最深刻的观察者彼得·德鲁克,把过去 200 年的组织创新总结为三次革命。
第一次是工业革命(industrial revolution),核心是机器取代了体力,技术(technology)超越了技能(skills)。第二次是生产力革命(productivity revolution),大致从 1880 年到第二次世界大战,核心是以泰勒制为代表的科学管理的普及,工作被知识化,强调的是标准化、可度量等概念。公司这种新组织正是随着科学管理思想的发展而兴起。第三次是管理革命(management revolution),知识成为超越资本和劳动力的最重要的生产要素。和体力劳动相比,知识工作者是否努力工作很难被直接观察和测量,相应地,管理的重心转向激励,特别是动机的匹配(incentive alignment)。
2『又见这三次管理革命,之前在德鲁克的书里有看到,做一张信息卡片。』
从第二次次革命介绍可以看到,组织是二战之后企业大型化之后的产物。战后,企业领导者对科技的重要性笃信不疑,倾心投入。毕竟,核能技术、雷达、声纳等高科技的研究成果使盟国赢得了第二次世界大战。战后的年轻人,胜利的喜悦刚刚开始,就被西方国家与共产主义阵营冷战的乌云所笼罩,紧接着又经历了股市的崩盘。在这样的时代,企业内部充满的是忠诚的想法,员工对老板忠心,公司也对员工忠诚。企业的运作模式是解决问题和理性计算的工程模型,对承担义务以及埋头苦干给予奖励。在很多方面,公司的运作模式与军队指挥系统几乎就是一个样子:遵从规矩、服从职权,企业就会运作顺畅;企业运作顺畅,所有人都能因此受益。在某种程度上,员工必须为了组织的「手足之情」牺牲个人特质;作为回报,组织也通过薪酬和其他保障,确保员工过上「好日子」。
在这套游戏规则和体制下,一个人一生大概都会在一个领域工作,在一家公司供职。成功的法则非常简单:努力工作,有所成就就能晋升。除此之外,受到战争和经济萧条的影响,战后的人渴望一份好工作,一个美满的家庭,人生成功的定义就是稳定的收入。相应的,企业运营流程也偏重于降低风险、规避失误,因此经验成为个人追求最大的保障,同时也加强了企业层级制度的合理性和正确性。管理的革命是伴随着技术的革命而来的,第三次科技革命,是人类文明史上科技领域里的又一次重大飞跃。这次科技革命不仅极大地推动了人类社会经济、政治、文化领域的变革,而且也影响了人类生活方式和思维方式,使人类社会生活和人的现代化向更高境界发展,同时也带来了管理上的革命。
消费者具有了更多的信息、更大的选择权、更强的影响力,对需求响应速度要求也更高;行业产品主要要素的成本曲线下降,导致各个行业出现剧变,同时实验和失败的成本也显著下降,几个工程师、研发者和设计者组成一支小团队,合力创造出新颖的科技产品,然后就可以通过网络免费在全球发行。构想并打造新产品、选定一个顾客群试用、判断产品的优点及缺陷、对产品进行调整、再次试用,不然就从失败中总结经验,放弃失败的产品、重新再来,以便提升用户体验。得益于反复的调整和修改,产品研发的过程变得越发灵活快速。企业的竞争优势只能维持很短一段时间,要想持续保持产品的成功及品质的卓越,秘诀就是快速。
从马斯洛需求理论来看,低层次的需要基本得到满足以后,它的激励作用就会降低,其优势地位将不再保持下去,高层次的需要会取代它成为推动行为的主要原因。人的最高需要即自我实现就是以最有效和最完整的方式表现他自己的潜力,惟此才能使人得到高峰体验。「雇佣关系」已经不是企业和员工间关系自然的适当形式。司和员工彼此的忠诚似乎成了历史小说,事业变成不断适应的过程。一个人不只有拥有自己的生活,而是许多人可能的生活。不是只有一个自我,而是许多可能的自我。不是历史的俘虏,而是历史的创造者。不是「等一下」,而是当下。以往一个命令、一个动作的领导模式已经过时,就像美国陆军的决策理论 —— 观察、定位、决定及行动。今天的领导者不再是指挥部署,而是联合、创造及授权。以往的程序由观察及反省开始,最后由领导者采取行动;今天想在高速的环境下脱颖而出,就得采取行动,然后再学习及适应。
讲了这么多来到我们的重点,为什么 OKR?1)聚焦:成功的组织往往是「最大化利用现有资源,集中精力去打造顶级产品的组织」。2)协同:透明的 OKR 将每个人的工作与团队工作、部门项目以及整体组织的使命联系起来。3)追踪:在每个 OKR 周期对 OKR 进行详细的检查,包括进展情况、识别障碍、改进关键结果。4)挑战不可能:把巨大的挑战交给不适合的人,就是在制造压力。而选对了人,你就是在播撒快乐。挑战促使我们远离舒适区,超越能力的边界,不断向梦想靠拢。
从 OKR 的每个关键点都能看出它与这个时代的契合感,也就是为什么 OKR 渐渐火起来的原因吧。
## 01. 当谷歌遇见 OKR
### 1. 逻辑脉络
用自己的话总结主题,梳理逻辑脉络,也就是这本书整个地图里这一章所在的节点。
### 2. 摘录及评论
许多公司都有所谓的「7人原则」,即向上级直接汇报的下级人数最多不超过 7 人。在某些情况下,谷歌公司将这一规则变为向上级直接汇报的下级最少为 7 人。当乔纳森·罗森伯格领导谷歌公司的产品团队时,直接向他汇报的下级多达 20 位。[21] 这个数字越高,组织结构就越扁平——这意味着自上而下的监督层级会更少,一线员工的自主权也就更大,也就有着更适于培育重大突破的创新土壤。实际上,正是 OKR 的应用,才使这一切成为可能。
## 04. 利器1——对优先事项的聚焦和承诺
### 1. 逻辑脉络
用自己的话总结主题,梳理逻辑脉络,也就是这本书整个地图里这一章所在的节点。
### 2. 摘录及评论
目标和关键结果是目标设定的阴阳两面——原则与实践、愿景与执行。其中,目标往往能鼓舞人心且与长远计划有关,而关键结果往往更接地气且是可衡量的。而且,关键结果通常包括很多指标,如收入、增长率、活跃用户、质量、安全、市场份额及客户参与度等。正如彼得·德鲁克所指出的,为了真正实现可靠的进展,管理者「必须能够衡量……针对目标的绩效和结果」。[5]
换句话说,关键结果是拉动目标实现的杠杆和实现目标过程中的一个个节点。如果目标的设定较为科学的话,通常有 3 到 5 个关键结果就足以确保目标的达成。如果目标太多,往往会淡化焦点,对预期的进展形成阻碍。此外,每个关键结果对于个人来说都应该是一项挑战。如果你有足够的信心能够做好这件事,那么你所设立的目标很可能还不够宏大。
由于 OKR 会打乱既定的秩序,所以将其融入秩序当中不失为一个较好的选择。有些企业会以一年为周期,将目标设定从个体目标转变为共同目标,或者将目标设定过程从自上而下的方式转变为更具协作性的方式。双线并行可能是目标设定的最佳方式,既有短期的 OKR 来支持年度 OKR 的实现,也有长期的战略规划。请牢记,尽管能够推动实际工作的是短期目标,但年度计划需要依据实际情况来制订,并确保这一计划是可以实施的。
明确时间框架可以进一步突出工作的焦点和承诺。实际上,没有任何东西能够像截止日期那样推动我们前进。要想在全球市场中取胜,企业需要比以往更加灵活。根据我的经验:季度 OKR 的设定最适合与当今快速变化的市场保持同步。以 3 个月为期限可能会防止工作中的拖延症,并带来实际的业绩增长。
但这仅是片面之词,我来阐述一下伏尔泰(法国哲学家)的观点:不要让完美成为优秀的敌人。[11] 请记住,在 OKR 周期的任何时间点,都可以修改甚至完全抛弃之前的设定。有些时候,「正确」的关键结果会在投入工作后的数周或数月内显现出来。从本质上看,OKR 就是正在进行的工作,它并不是一成不变的。
目标设定也有一些基本的规则:关键结果应该是明确的、具体的、可衡量的,产出和投入的组合(匹配)对其有所帮助。最后,完成所有关键结果的关键和前提是实现目标。如果目标没有实现,那就不是 OKR了。
当谈到目标设定时,格鲁夫强调「少即是多」:
OKR 系统应该为企业提供最卓越的东西,即「聚焦」。只有当我们将目标的数量保持在很小时,才会真正聚焦于此。每次做出承诺时,都会丧失投身其他事项的机会。当然,这是任何有限资源分配中都不可避免的结果。因此,做计划的人必须有勇气、诚实且遵守纪律。只有这样,才能在放弃某个项目的同时启动新的项目。摇头说「不」和微笑着说「行」一样重要。我们必须意识到关注所有事项和一件都不关注的结果是一样的,并能够践行这个原则。
## 07. 利器2——团队工作的协同和联系
### 1. 逻辑脉络
用自己的话总结主题,梳理逻辑脉络,也就是这本书整个地图里这一章所在的节点。
### 2. 摘录及评论
作为总经理,我将自己的目标与直接下属——主教练和高级营销副总裁的目标进行了关联,把我的关键结果变成了他们的目标。其中,主教练的目标是赢得超级碗的胜利。为了实现这一目标,他设定了三个关键结果:每场比赛的传球进攻不低于 300 码,每场比赛防守丢分少于 17 分,弃踢补位回攻进入前三。然后,他又将这三个关键结果作为他直接管理的三个最高执行者——进攻教练、防守教练及特勤教练的目标。此后,他们三人也依次制定了属于自己的低一级别的关键结果。
与此同时,我的高级营销副总裁依据我的另一个关键结果生成了她自己的目标——使主场上座率达到 90%。为此,她设定了以下三个关键结果:提升团队的品牌形象、提高媒体曝光率,以及重启场内推广计划。这些关键结果又分别作为市场总监、公关人员和商品经理的目标。
## 14. 延展——YouTube 的故事
### 1. 逻辑脉络
用自己的话总结主题,梳理逻辑脉络,也就是这本书整个地图里这一章所在的节点。
### 2. 摘录及评论
然后,萨拉尔·卡曼加便将 YouTube 技术方面的日常管理权交给了希希尔·梅赫罗特拉(Shishir Mehrotra),于是希希尔开始带领整个公司关注核心问题。他以「巨石理论」来比喻核心问题的重要性。「巨石理论」是由史蒂芬·柯维提出来的。假设你有几块石头,一堆鹅卵石和一些沙子,你的任务是尽可能地把所有东西都装进一个一加仑的广口瓶中。如果你先放沙子,再放入鹅卵石,那么再想放石头时你会发现瓶子已经没有空间留给它们了。然而,当你先放石头,再放鹅卵石,最后放沙子,你会发现一切如你所愿——沙子将石头之间的缝隙填满了。这就告诉我们要善于抓住主要矛盾,重要的事情要先做,否则有可能永远都没有机会去做了。
那么,何为 YouTube 的巨石呢?人们各自忙于自己的工作,看起来好像是「百花齐放」,但是,没有人关注公司最高级、最重要的 OKR。现在,管理层经常问工程师们:「你们的想法都非常棒!但我们是否能从中提取出本季度或者本年度最大的‘石头’,也就是最重要的议题呢?」在此之后,YouTube 的每个人都能够清晰地知道我们的「石头」,也就是我们的首要任务。就这样,我们所有的石头都能够装入瓶子里了。
## 15. 持续性绩效管理:OKR 和 CFR
### 1. 逻辑脉络
用自己的话总结主题,梳理逻辑脉络,也就是这本书整个地图里这一章所在的节点。
### 2. 摘录及评论
领导者们历经苦痛才深刻领悟到的一个教训就是「不要把人数字化」。即便是彼得·德鲁克,这位目标管理的首创者,也认同标准化管理的局限性。在德鲁克看来,管理者的「首要角色」是「自己本身」,管理者需要和他人建立有效的人际关系,激发共同的信心,构建命运共同体。或者如阿尔伯特·爱因斯坦所言:「并非所有可以用数字计算的东西都是有价值的,也并非所有有价值的东西都可以用数字来衡量。」
## 17. 每天烘焙得更好一点:Zume比萨的故事
### 1. 逻辑脉络
用自己的话总结主题,梳理逻辑脉络,也就是这本书整个地图里这一章所在的节点。
### 2. 摘录及评论
茱莉亚:文化是让个人与组织保持一致的通用语言,确保人们所谈论的事情在同一个频道上,并且对这件事的讨论是有价值的。除此以外,文化可以为组织决策建立起一个共同的框架。在文化缺失的组织中,人们常常会对如何复制和提升组织的核心职责感到困惑。
此外,文化还有更高层面的作用:价值观对话。我们想成为什么样的组织?我们希望员工如何感知他们的工作和我们的产品?我们怎样影响世界?
亚历克斯:当我们初次相识时,茱莉亚在电话里跟我说,Zume 的基本原则,也就是我们的使命,就两件事。这给我留下了深刻的印象,于是我做了一张巨大的海报贴在厨房的墙上。我们要让每一个位员工知道我们的使命:
第一,基于神圣的信任为人们提供食品服务;第二,每位美国公民都有权利享用到美味、实惠而又健康的食物。
## 18. 文化
### 1. 逻辑脉络
用自己的话总结主题,梳理逻辑脉络,也就是这本书整个地图里这一章所在的节点。
### 2. 摘录及评论
正如你在本书中看到的那样,OKR 可用于指导领导者设定公司的最高目标和关键结果,CFR 则可用于确保这些最高目标和关键结果能够被很好地传达下去。但是目标不可能凭空达成,就如同声波需要通过媒介来进行传播一样,OKR 和 CFR 同样需要这样一个载体。而就组织来说,这种媒介就是组织文化,它是一个组织最重要的价值观和信仰的生动体现。
在《进步原则》(The Progress Principle)一书中,特丽萨·阿马比尔(Teresa Amabile)和史蒂文·克莱默(Steven Kramer)分析了 26 个项目团队、238 位员工和 1.2 万条员工工作日志,发现高驱动力的企业文化主要取决于两种核心要素的相互作用:催化剂和营养液。
作者将「催化剂」定义为「支持工作的一切行为」,这听起来非常像 OKR。它包括设定清晰的目标,允许授权,提供充分的资源和时间,团队协作,从问题和成功中总结经验教训,并允许思想上的自由交流。「营养液」被定义为「个人之间相互支持的一切行动」,和 CFR 有很大的相似之处。它包括尊重、认可、鼓励、情感安抚和拥抱机会。
安迪·格鲁夫曾经通过增加定性目标来平衡定量目标,多弗则发现了一种新的方式,可以对抽象的价值观(比如信任)进行量化。他提出了「信任指数」这一指标,并认为其可通过具体的行为来测量。比如,直接用一系列「方法」来测量信息的透明度。多弗告诉我:
我避免直接询问被测试者的感受,我不会直接问「你觉得你的公司对你坦诚吗」这样的问题,我会观察公司的信息流动。该公司是否会「雪藏」信息?是在不得已之时才进行信息公开,还是允许信息在公司内自由传播?如果你绕过你的上司,直接同更高层级的领导者交流,你是会被批评还是会被表扬?
## 20. 文化变革:波诺的「ONE 运动」
### 1. 逻辑脉络
用自己的话总结主题,梳理逻辑脉络,也就是这本书整个地图里这一章所在的节点。
### 2. 摘录及评论
这种以客户为中心的思想最终成为我们 ONE 运动的关键转变点。约翰的建议与一位来自非洲塞内加尔的朋友说的一致,我们曾在巴黎和这位朋友有一面之缘。当时,他对我说:「波诺,你知道塞内加尔的一个谚语吗?‘如果你想给一个人理发,那么,他就需要坐在你面前。’」他说这句话的时候非常温情,甚至充满爱意,我们理解他的意思:如果你自认为知道我们的需要,你需要倍加小心。因为,只有我们知道自己想要什么。你不是非洲人,你可能并不知道非洲人的真实需要,而且,如果你一直怀着救世主的情结,结果可能并不好。
## 资源1——谷歌公司的内部 OKR 模板
其次,关键的结果意味着「怎么做」。
设置可衡量的里程碑事件,如果得以实现,将以一种高效的方式推进目标。
一定要描述结果,而不是行为(活动)。如果 OKR 中包含有诸如「咨询」、「帮助」、「分析」或「参与」等词汇,这类描述其实就是指行为(活动)。相反,应当是描述这些活动对终端用户所产生的影响。例如,「在 3 月 7 日之前发布分布式文件系统 Colossus 的 6 个储存单元的平均延迟和尾延迟测量值」而不是「评估 Colossus 系统的延迟情况」。
必须包含完整的证据。这些证据必须是可用的、可信的和易察觉的。例如,证据应当包括:变更列表、文档链接、注释和发布的测量报告。
|
Python
|
UTF-8
| 926
| 3.34375
| 3
|
[] |
no_license
|
import string
import collections
def caesar():
#lettre+cle=crypt
code=[]
alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
message=input("saisir votre message a coder : ")
cle=int(input("saisir votre cle: "))
for lettre in message:
#print(alphabet.index(lettre))
#print(alphabet.index(lettre)+cle)
i=alphabet.index(lettre)
if(i+cle>25):
i=i-25
print(alphabet[i+cle])
def newcaesar(text,cle):
upper = collections.deque(string.ascii_uppercase)
lower = collections.deque(string.ascii_lowercase)
upper.rotate(cle)
lower.rotate(cle)
upper = ''.join(list(upper))
lower = ''.join(list(lower))
return text.translate(str.maketrans(string.ascii_uppercase, upper)).translate(str.maketrans(string.ascii_lowercase, lower))
|
JavaScript
|
UTF-8
| 1,713
| 2.6875
| 3
|
[] |
no_license
|
//The username and password you use to sign into the robinhood app.
var credentials = {
username: ,
password:
};
var request = require('request');
var Robinhood = require('robinhood')(credentials, function(){
//Robinhood is connected and you may begin sending commands to the api.
});
var RobinObserver = require('robinhood-observer'); //Robinhood has not authenticated but can still be used for the unauthenticated subset of the API
var sub = (syb) => {
observer = RobinObserver(null).observeQuote([syb]) //Do not authenticate
var buySubscription = observer
.map(quote => quote.results)
.distinct() //Only use distict results...
.subscribe(x => {
//This block of code is executed only when the price has changed.
console.log(x[0].last_trade_price);
}, e => {
console.error(e)
}, () => console.log('buy subscription disposed'));
//Unsubscribe to updates after 5 seconds.
//setTimeout(function(){
// subscription.dispose();
//}, 5000);
};
var get = (test) => {
return new Promise((resolve, reject) =>{
Robinhood.quote_data(test, function(error, response, body) {
if (body != undefined) {
resolve(body.results[0].ask_price);
} else {
reject("Stock not found!");
}
//console.log(response);
});
});
}
module.exports = {
get,sub
}
|
Java
|
UTF-8
| 1,395
| 2.0625
| 2
|
[] |
no_license
|
package com.sport.huaweisport;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private HuaweiSportView mHuaweiSportView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHuaweiSportView = findViewById(R.id.sport_view);
final ValueAnimator valueAnimator = ObjectAnimator.ofFloat(0, 3000);
valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
valueAnimator.setDuration(1000);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float currentValue = (float) animation.getAnimatedValue();
mHuaweiSportView.setSportNum((int) currentValue);
}
});
valueAnimator.start();
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
valueAnimator.start();
}
});
}
}
|
Markdown
|
UTF-8
| 739
| 2.6875
| 3
|
[] |
no_license
|
### 项目是什么?与产品、App 的关系是什么?
项目是为用户提供方便管理物联网相关应用案例,产品与 App 属于某个项目。
### 数据模板是什么?
数据模板是一个硬件产品数字化的描述语言,包含了属性、事件,应对的是物理设备的状态、故障、告警灯信息。
### 虚拟设备作用是什么?
虚拟设备是根据数据模板模拟了一个设备,可以模拟设备上报数据,可以使用APP工具绑定虚拟设备后控制虚拟设备,让用户快速体验,并加快 App 开发调试效率。
### 控制台的设备通信日志、事件数据保存多久?
控制台能提供最近30日的数据,超过30日的数据则无法查询。
|
Java
|
UTF-8
| 848
| 3.453125
| 3
|
[] |
no_license
|
package subcategory.Tree;
/**
* Created by yangw on 2019/7/7.
*/
public class popluatingNextRightPointer {
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
// public void connect(TreeLinkNode root) {
//
// TreeLinkNode first = root;
// while(first!=null){
// TreeLinkNode cur = first;
// // Level order!
// while(cur != null){
// if(cur.left != null) cur.left.next = cur.right;
// if(cur.next!= null && cur.right!=null) cur.right.next = cur.next.left;
// cur = cur.next;
// }
// // Go to next level.
// first = first.left;
// }
// }
}
|
Python
|
UTF-8
| 635
| 3.734375
| 4
|
[] |
no_license
|
class ParkingSystem:
def __init__(self, big: int, medium: int, small: int):
self.one = big
self.two = medium
self.three = small
def addCar(self, carType: int) -> bool:
if carType==1 and self.one>0:
self.one -= 1
return True
if carType==2 and self.two>0:
self.two -= 1
return True
if carType==3 and self.three>0:
self.three -= 1
return True
return False
# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType)
|
Ruby
|
UTF-8
| 1,073
| 2.703125
| 3
|
[] |
no_license
|
require 'kanban/card'
describe Kanban::Card do
context '#method_missing' do
let(:card) { Kanban::Card.new({ 'Id' => 11, 'Title' => 'Card Title', 'ExternalCardID' => 123, 'Size' => 13 }) }
it 'maps fields' do
expect(card.id).to eq(11)
expect(card.title).to eq('Card Title')
expect(card.external_card_id).to eq(123)
expect(card.size).to eq(13)
end
it 'maps fields using case-insensitive keys' do
expect(card.send(:Title)).to eq('Card Title')
end
it 'does not respond to keys missing in JSON' do
expect(card).not_to respond_to(:not_a_real_key)
end
it 'can assign values' do
the_time = Time.now
card = Kanban::Card.new
card.id = 123
card.external_card_id = 12345
card.title = 'my card title'
card.size = 4
card.last_move = the_time
expect(card.id).to eq(123)
expect(card.external_card_id).to eq(12345)
expect(card.title).to eq('my card title')
expect(card.size).to eq(4)
expect(card.last_move).to eq(the_time)
end
end
end
|
Java
|
UTF-8
| 2,487
| 2.5
| 2
|
[] |
no_license
|
package com.neon.servlets;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import com.neon.model.Audio;
import com.neon.util.AudioDAO;
@WebServlet("/InsertAudio")
//Here define the size of a file
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2000,//2MB
maxFileSize = 1024 * 1024 * 10000, //10MB
maxRequestSize = 1024 * 1024 * 50000)
public class InsertAudio extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
//include following 2 lines.otherwise this will not work correctly when getting values from a form
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String userName = (String) session.getAttribute("userName");
Part part = request.getPart("file");
String fileName = extractFileName(part);
String savePath = "C:\\Users\\ASUS\\eclipse-workspace\\NeonWebProject\\WebContent\\Storage\\" + File.separator + fileName;
part.write(savePath + File.separator);
Audio audio = new Audio();
audio.setUserID(userName);
audio.setName(request.getParameter("name"));
audio.setDescription(request.getParameter("description"));
audio.setFilename(fileName);
audio.setPath(savePath);
AudioDAO audDao = new AudioDAO();
try {
audDao.insertAudio(audio);
} catch (ClassNotFoundException | SQLException e) {
out.print("Error");
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("user");
}
//this is related to file path
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if(s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2,s.length() - 1);
}
}
return "";
}
}
|
JavaScript
|
UTF-8
| 4,973
| 2.796875
| 3
|
[] |
no_license
|
import {store} from '../../src/index';
import {data} from './../data';
//定義type屬性名稱
export const UPDATE_TIME = 'UPDATE_TIME';
export const UPDATE_WEATHER = 'UPDATE_WEATHER';
export const TOGGLE_DESCRIPTION = 'TOGGLE_DESCRIPTION';
export const REQUEST_WEATHER = 'REQUEST_WEATHER';
export const RECEIVE_WEATHER = 'RECEIVE_WEATHER';
export const RECEIVE_WEATHER_ERROR = 'RECEIVE_WEATHER_ERROR';
export const GET_ABOUT_DATA = 'GET_ABOUT_DATA';
export const SWITCH_MENU = 'SWITCH_MENU';
export const UPDATE_SKILLS_CANVAS ='UPDATE_SKILLS_CANVAS';
export const UPDATE_SKILLS_ACTIVE='UPDATE_SKILLS_ACTIVE';
export const TOGGLE_CONTACT = 'TOGGLE_CONTACT';
//更新時間
export const updateTime = () => {
let currentTime = getCurrentTime();
return {
type: UPDATE_TIME,
payload:{
timeText:`${currentTime.hours}:${currentTime.minutes}:${currentTime.seconds}`,
dateText:`${currentTime.date} ${currentTime.monthNames}, ${currentTime.year}`,
}
}
}
//發送api請求天氣
const requestWeather = () => ({ //發送api請求
type: REQUEST_WEATHER,
payload:{
temp: `Loading...`,
weather: null
}
})
const receiveWeather = (weatherData) => ({ //更新天氣結果
type: RECEIVE_WEATHER,
payload:{
temp: Math.round(weatherData.main.temp*10)/10, //四捨五入到小數第一位
weather: weatherData.weather[0].main
}
})
const receiveWeatherError = () => ({ //更新天氣失敗
type: RECEIVE_WEATHER_ERROR,
payload:{
temp: `Oops! Failed to get the weather.`,
weather: null
}
})
//dispatch requestWeather then call api then dispatch receiveWeather
export const fetchWeather = () => dispatch => {
dispatch(requestWeather()); //api請求前
let apiUrl = "https://api.openweathermap.org/data/2.5/weather";
let queryObj = {
APPID:"f8aeb1b2e591f2c787f3c774b6c8f631",
q: "Taipei",
units: "metric"
}
apiUrl+= `?APPID=${queryObj.APPID}&q=${queryObj.q}&units=${queryObj.units}`
return (
fetch(apiUrl)
.then(response => response.json())
.then(json => dispatch(receiveWeather(json)))
.catch(() => dispatch(receiveWeatherError()))
)
}
//是否顯示DESCRIPTION
export const toggleDescription = (itemIndex,title,newState) => {
// console.log(`${itemIndex},${title},${newState}`)
let showDescription = Object.assign({},store.getState().showDescription);
showDescription[title] = showDescription[title].map(x=>false); //隱藏全部
showDescription[title][itemIndex] = newState;
return {
type: TOGGLE_DESCRIPTION,
payload:{
showDescription: showDescription
}
}
}
//取得自介資料
export const getAboutData = () => {
let {educations, experiences} = data;
return {
type: GET_ABOUT_DATA,
payload:{
aboutMe:{
educations,
experiences
}
}
}
}
//切換分頁
export const switchMenu = (pathname)=>({
type: SWITCH_MENU,
payload:{
pathname
}
})
//重取SkillsTree
export const updateSkillsCanvas = (skillsTree,canvasWidth,canvasHeight)=>({
type: UPDATE_SKILLS_CANVAS,
payload:{
skillCanvas:{
skillsTree ,
canvasWidth,
canvasHeight,
}
}
})
//變更SkillsDescription
export const updateSkillsActive = (activeIndex,description) => ({
type: UPDATE_SKILLS_ACTIVE,
payload:{
skillsActive:{
activeIndex,
description
}
}
})
//是否顯示contact
export const toggleContact = (ifShow) =>({
type: TOGGLE_CONTACT,
payload:{
showContact: ifShow
}
})
// 取得時間
function getCurrentTime() {
let now = new Date(),
datetime = new Date(now.getTime()),
hours = datetime.getHours(),
minutes=datetime.getMinutes(),
seconds=datetime.getSeconds(),
date = datetime.getDate(),
month = datetime.getMonth() + 1, //0~11 > 1~12
year = datetime.getFullYear();
// 補0
hours = hours < 10 ? "0" + hours : hours.toString();
seconds = seconds < 10 ? "0" + seconds : seconds.toString();
minutes = minutes < 10 ? "0" + minutes : minutes.toString();
month = month < 10 ? "0" + month : month.toString();
date = date < 10 ? "0" + date : date.toString();
// Months Names
const monthNames = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
return {
hours,
seconds,
minutes,
year,
month,
date,
monthNames: monthNames[month - 1]
}
}
|
Java
|
UTF-8
| 2,198
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2019-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.vividus.datetime.expression;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.Validate;
import org.jbehave.core.expressions.MultiArgExpressionProcessor;
import org.vividus.util.DateUtils;
public class ShiftDateExpressionProcessor extends MultiArgExpressionProcessor<String>
{
private static final Pattern DURATION_PATTERN = Pattern.compile("(-?P)((?:\\d+[YMWD])*)(T(?:\\d+[HMS])+)?");
private static final String EXPRESSION_NAME = "shiftDate";
private static final int EXPECTED_ARGS_NUMBER = 3;
private static final Locale DEFAULT_LOCALE = Locale.ENGLISH;
public ShiftDateExpressionProcessor(DateUtils dateUtils)
{
super(EXPRESSION_NAME, EXPECTED_ARGS_NUMBER, args -> {
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern(args.get(1), DEFAULT_LOCALE);
ZonedDateTime inputDate = dateUtils.parseDateTime(args.get(0), inputFormat);
String duration = args.get(2);
Matcher durationMatcher = DURATION_PATTERN.matcher(duration);
Validate.isTrue(durationMatcher.matches(),
"The third argument of '%s' expression must be a duration in ISO-8601 format, but found: '%s'",
EXPRESSION_NAME, duration);
DateExpression dateExpression = new DateExpression(durationMatcher, args.get(1));
return dateExpression.format(inputDate, DEFAULT_LOCALE);
});
}
}
|
Markdown
|
UTF-8
| 279
| 2.546875
| 3
|
[] |
no_license
|
# Library-Network
Assume that the library having wireless routers in series. For better illustration you have considered only 2 wireless routers, which need to be interconnected in series as per figure given below. Implement and analyze this network plan of a long library hall.
|
Java
|
UTF-8
| 999
| 2.34375
| 2
|
[] |
no_license
|
package com.bravo.webapp.dao.impl;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import com.bravo.webapp.bean.CheckTransaction;
import com.bravo.webapp.dao.CheckTransactionDAO;
public class JdbcCheckTransactionDAO extends JdbcDaoSupport implements
CheckTransactionDAO {
@Override
public boolean addTransaction(CheckTransaction checkTransaction) {
String sql = "INSERT INTO CheckTransaction (transactionID, accountNumber, ABA, checkDate) "
+ "VALUES (?, ?, ?, ?)";
try {
int result = getJdbcTemplate().update(sql,
checkTransaction.getTransactionId(),
checkTransaction.getAccountNumber(),
checkTransaction.getABA(), checkTransaction.getCheckDate());
return result == 1;
} catch (DataAccessException ex) {
System.out.println("Check Transaction failed!");
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
|
Shell
|
UTF-8
| 4,322
| 3.6875
| 4
|
[] |
no_license
|
#!/bin/bash
#
# Simple script to generate a basic bind configuration for home/lab use
#
# Local config - adjust as required
OWNIP=192.168.100.161
NETWORK=192.168.100.0
NETMASK=/24
DNS1=192.168.100.116
DNS2=
# Advanced - should not be changed
DOMAIN=dupont.lan
# Internal - must not be changed
CONFDIR=/etc/bind
# Let's go - make sure we're in the right path
if [[ ! -d "${CONFDIR}" ]]
then
echo "ERROR: configuration path ${CONFDIR} does not exist, exiting"
exit 1
else
echo "Configuration path ${CONFDIR}"
cd $CONFDIR || exit 1
fi
# Stop bind
echo "Stopping bind9 daemon..."
service bind9 stop
# Remove the root zone servers, we don't want to query these directly
[[ ! -f db.root.original ]] && mv db.root db.root.original
cat > db.root <<- EOF
\$TTL 2592000
@ IN SOA localhost. root.localhost. (
1 ; Serial
2592000 ; Refresh
86400 ; Retry
2592000 ; Expire
2592000 ; Negative Cache TTL
)
;
@ IN NS localhost.
EOF
echo "Created db.root"
# Set bind options and upstream DNS servers
[[ ! -f named.conf.options.original ]] && mv named.conf.options named.conf.options.original
cat > named.conf.options <<- EOF
options {
directory "/var/cache/bind";
auth-nxdomain no;
listen-on { any; };
listen-on-v6 { any; };
allow-recursion { 127.0.0.1; ${NETWORK}${NETMASK}; };
EOF
printf "\tforwarders { ${DNS1}" >> named.conf.options
[[ -n "${DNS2}" ]] && printf "; ${DNS2}" >> named.conf.options
printf "; };\n};\n" >> named.conf.options
echo "Created named.conf.options"
# Configure the local domain
[[ ! -f named.conf.local.original ]] && mv named.conf.local named.conf.local.original
REVADDR=$(for FIELD in 3 2 1; do printf "$(echo ${NETWORK} | cut -d '.' -f $FIELD)."; done)
cat > named.conf.local <<- EOF
zone "${DOMAIN}" {
type master;
notify no;
file "${CONFDIR}/db.${DOMAIN}";
};
zone "${REVADDR}in-addr.arpa" {
type master;
notify no;
file "${CONFDIR}/db.${REVADDR}in-addr.arpa";
};
include "${CONFDIR}/zones.rfc1918";
EOF
echo "Created named.conf.local"
# Populate the forward zone
SERIAL="$(date '+%Y%m%d')01"
NET="$(echo ${NETWORK} | cut -d '.' -f 1-3)"
cat > db.${DOMAIN} <<- EOF
\$ORIGIN ${DOMAIN}.
\$TTL 1d
@ IN SOA localhost. root.localhost. (
${SERIAL} ; Serial
86400 ; Refresh
7200 ; Retry
2592000 ; Expire
172800 ; Negative Cache TTL
)
IN NS dns.${DOMAIN}.
;
dns IN A ${OWNIP}
ntp IN CNAME dns.${DOMAIN}.
vcenter IN A ${NET}.49
esx1 IN A ${NET}.50
esx2 IN A ${NET}.51
Rundeck IN A ${NET}.143
Centreon IN A ${NET}.126
CentreonTest IN A ${NET}.160
Client-Linux IN A ${NET}.100
Corosync IN A ${NET}.147
DNS IN A ${NET}.116
ElastikSearch IN A ${NET}.113
Client-W10 IN A ${NET}.99
OpenFiler IN A ${NET}.105
Pfsense IN A ${NET}.1
Postfix IN A ${NET}.117
Serveur-AD IN A ${NET}.115
;
EOF
echo "Populated forward zone file db.${DOMAIN} for ${DOMAIN}"
# Populate the reverse zone
OWNH="$(echo ${OWNIP} | cut -d '.' -f 4)"
cat > db.${REVADDR}in-addr.arpa <<- EOF
\$ORIGIN ${REVADDR}in-addr.arpa.
\$TTL 1d
@ IN SOA localhost. root.localhost. (
${SERIAL} ; Serial
86400 ; Refresh
7200 ; Retry
2592000 ; Expire
172800 ; Negative Cache TTL
)
IN NS dns.${DOMAIN}.
;
${OWNH} IN PTR dns.${DOMAIN}.
;
50 IN PTR esx1.${DOMAIN}.
51 IN PTR esx2.${DOMAIN}.
49 IN PTR vcenter.${DOMAIN}.
143 IN PTR Rundeck.${DOMAIN}.
144 IN PTR DebianTest.${DOMAIN}.
126 IN PTR Centreon.${DOMAIN}.
160 IN PTR CentreonTest.${DOMAIN}.
100 IN PTR Client-Linux.${DOMAIN}.
147 IN PTR Corosync.${DOMAIN}.
116 IN PTR DNS.${DOMAIN}.
113 IN PTR ElastikSearch.${DOMAIN}.
99 IN PTR Client-W10.${DOMAIN}.
105 IN PTR OpenFiler.${DOMAIN}.
1 IN PTR Pfsense.${DOMAIN}.
117 IN PTR Postfix.${DOMAIN}.
115 IN PTR Serveur-AD.${DOMAIN}.
;
EOF
echo "Populated reverse zone file db.${REVADDR}in-addr.arpa for ${NET}"
# Enable local DNS server
[[ ! -f /etc/resolv.conf.original ]] && mv /etc/resolv.conf /etc/resolv.conf.original
cat > /etc/resolv.conf <<- EOF
domain ${DOMAIN}
search ${DOMAIN}
nameserver ${OWNIP}
EOF
echo "Enabled local DNS server in /etc/resolv.conf"
# Start bind
echo "Starting bind9 daemon..."
service bind9 start
# Done
echo "Done."
|
Java
|
UTF-8
| 6,829
| 1.9375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 图片样式相关接口
* 图片样式API
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.mps.model;
import com.jdcloud.sdk.service.JdcloudResult;
/**
* 图片样式详情
*/
public class GetImageStyleResult extends JdcloudResult implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* 图片样式id(readOnly)
*/
private Long id;
/**
* 用户id(readOnly)
*/
private String userId;
/**
* 图片样式名称
*/
private String styleName;
/**
* 图片样式参数
*/
private String params;
/**
* 图片样式参数别名
*/
private String paramAlias;
/**
* 所属区域(readOnly)
*/
private String regionId;
/**
* 所属Bucket(readOnly)
*/
private String bucketName;
/**
* 图片样式状态(readOnly)
*/
private Integer status;
/**
* 修改时间(readOnly)
*/
private String modifyTime;
/**
* 创建时间(readOnly)
*/
private String createdTime;
/**
* get 图片样式id(readOnly)
*
* @return
*/
public Long getId() {
return id;
}
/**
* set 图片样式id(readOnly)
*
* @param id
*/
public void setId(Long id) {
this.id = id;
}
/**
* get 用户id(readOnly)
*
* @return
*/
public String getUserId() {
return userId;
}
/**
* set 用户id(readOnly)
*
* @param userId
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* get 图片样式名称
*
* @return
*/
public String getStyleName() {
return styleName;
}
/**
* set 图片样式名称
*
* @param styleName
*/
public void setStyleName(String styleName) {
this.styleName = styleName;
}
/**
* get 图片样式参数
*
* @return
*/
public String getParams() {
return params;
}
/**
* set 图片样式参数
*
* @param params
*/
public void setParams(String params) {
this.params = params;
}
/**
* get 图片样式参数别名
*
* @return
*/
public String getParamAlias() {
return paramAlias;
}
/**
* set 图片样式参数别名
*
* @param paramAlias
*/
public void setParamAlias(String paramAlias) {
this.paramAlias = paramAlias;
}
/**
* get 所属区域(readOnly)
*
* @return
*/
public String getRegionId() {
return regionId;
}
/**
* set 所属区域(readOnly)
*
* @param regionId
*/
public void setRegionId(String regionId) {
this.regionId = regionId;
}
/**
* get 所属Bucket(readOnly)
*
* @return
*/
public String getBucketName() {
return bucketName;
}
/**
* set 所属Bucket(readOnly)
*
* @param bucketName
*/
public void setBucketName(String bucketName) {
this.bucketName = bucketName;
}
/**
* get 图片样式状态(readOnly)
*
* @return
*/
public Integer getStatus() {
return status;
}
/**
* set 图片样式状态(readOnly)
*
* @param status
*/
public void setStatus(Integer status) {
this.status = status;
}
/**
* get 修改时间(readOnly)
*
* @return
*/
public String getModifyTime() {
return modifyTime;
}
/**
* set 修改时间(readOnly)
*
* @param modifyTime
*/
public void setModifyTime(String modifyTime) {
this.modifyTime = modifyTime;
}
/**
* get 创建时间(readOnly)
*
* @return
*/
public String getCreatedTime() {
return createdTime;
}
/**
* set 创建时间(readOnly)
*
* @param createdTime
*/
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
/**
* set 图片样式id(readOnly)
*
* @param id
*/
public GetImageStyleResult id(Long id) {
this.id = id;
return this;
}
/**
* set 用户id(readOnly)
*
* @param userId
*/
public GetImageStyleResult userId(String userId) {
this.userId = userId;
return this;
}
/**
* set 图片样式名称
*
* @param styleName
*/
public GetImageStyleResult styleName(String styleName) {
this.styleName = styleName;
return this;
}
/**
* set 图片样式参数
*
* @param params
*/
public GetImageStyleResult params(String params) {
this.params = params;
return this;
}
/**
* set 图片样式参数别名
*
* @param paramAlias
*/
public GetImageStyleResult paramAlias(String paramAlias) {
this.paramAlias = paramAlias;
return this;
}
/**
* set 所属区域(readOnly)
*
* @param regionId
*/
public GetImageStyleResult regionId(String regionId) {
this.regionId = regionId;
return this;
}
/**
* set 所属Bucket(readOnly)
*
* @param bucketName
*/
public GetImageStyleResult bucketName(String bucketName) {
this.bucketName = bucketName;
return this;
}
/**
* set 图片样式状态(readOnly)
*
* @param status
*/
public GetImageStyleResult status(Integer status) {
this.status = status;
return this;
}
/**
* set 修改时间(readOnly)
*
* @param modifyTime
*/
public GetImageStyleResult modifyTime(String modifyTime) {
this.modifyTime = modifyTime;
return this;
}
/**
* set 创建时间(readOnly)
*
* @param createdTime
*/
public GetImageStyleResult createdTime(String createdTime) {
this.createdTime = createdTime;
return this;
}
}
|
Java
|
UTF-8
| 1,793
| 3.953125
| 4
|
[] |
no_license
|
import java.util.Deque;
import java.util.ArrayDeque;
import java.util.Map;
import java.util.HashMap;
/*
Problem Description:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Examples:
Input: "()"
Output: true
Input: "()[]{}"
Output: true
Input: "(]"
Output: false
Solution Description:
Time complexity: O(n)
Space complexity: O(1)
*/
public final class Solution {
private static final Map<Character, Character> PARENTHESES = new HashMap<>();
static {
PARENTHESES.put('(', ')');
PARENTHESES.put('{', '}');
PARENTHESES.put('[', ']');
}
public boolean solve(String expression) {
Deque<Character> openBrackets = new ArrayDeque<>();
boolean result = true;
char character;
Character bracket;
for (int i = 0; i < expression.length(); i++) {
character = expression.charAt(i);
if (PARENTHESES.containsKey(character)) {
// open bracket
openBrackets.push(character);
} else if (PARENTHESES.containsValue(character)) {
// close bracket
bracket = PARENTHESES.get(openBrackets.poll());
if ((bracket == null) || (bracket != character)) {
result = false;
break;
}
}
}
return (result && openBrackets.isEmpty());
}
}
|
Java
|
UTF-8
| 1,426
| 2.390625
| 2
|
[] |
no_license
|
package com.intelliworkz.admin.admingujaratabroad;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>{
Context context;
ArrayList<HashMap<String, String>> catList;
View v;
public CategoryAdapter(Context context, ArrayList<HashMap<String, String>> catList) {
this.context=context;
this.catList=catList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category, parent, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.txtCat.setText(catList.get(position).get("catName"));
}
@Override
public int getItemCount() {
return catList.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView txtCat;
public ViewHolder(View v) {
super(v);
txtCat=(TextView)v.findViewById(R.id.txtCat);
}
}
}
|
Markdown
|
UTF-8
| 547
| 2.5625
| 3
|
[] |
no_license
|
## Paso 1:
Hacer match con "base de lista de precios" y extraer Categorías, Precio y Peso
#### Keywords:
- **Color:**
- tintes
- tinturacióm
- numeración: 10 Vol, 20 volúmenes, etc.
- Oxidantes
- Decolorante
- **Hair Care:**
- Shampoo
- Mascarilla
- Acondicionador
- Tratamientos
- **Styling:**
- Laca
- Cera
- Gel
- Mousse
- Pomada
## Paso 2:
Calcular monto importado: multiplicar PVP * Unidades (cantidad comercial)
## Paso 3
Calcular porcerntajes: market share por Razón Social y por Categoría-Razón Social
|
Shell
|
UTF-8
| 435
| 3.734375
| 4
|
[
"MIT"
] |
permissive
|
#!/bin/bash
# The singularity-run script will run a container, and it would use the
# container's runscript as entrypoint. To execute a command,
# use singularity-exec
CONTAINER=${1}
shift
if [ "$#" -gr 0 ]; then
NOTEBOOK_DIR=${1}
shift 1
else
NOTEBOOK_DIR=${SCRATCH}
fi
cd $NOTEBOOK_DIR
module use system
module load singularity
export SINGULARITY_CACHEDIR=$SCRATCH/.singularity
singularity exec ${CONTAINER} "${@}"
|
Java
|
UTF-8
| 3,099
| 2.046875
| 2
|
[] |
no_license
|
package com.edbrix.contentbrix;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.edbrix.contentbrix.baseclasses.BaseActivity;
import com.edbrix.contentbrix.utils.SessionManager;
public class ChooseAccountActivity extends BaseActivity {
private LinearLayout loggedUserLayout;
private LinearLayout changeUserLayout;
private ImageView loggedUserImage;
private TextView loggedUserName;
private SessionManager sessionManager;
private ImageView backBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isTablet()) {
// stop screen rotation on phones
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
setContentView(R.layout.activity_choose_account);
loggedUserLayout = (LinearLayout) findViewById(R.id.loggedUserLayout);
changeUserLayout = (LinearLayout) findViewById(R.id.changeUserLayout);
loggedUserImage = (ImageView) findViewById(R.id.loggedUserImage);
loggedUserName = (TextView) findViewById(R.id.loggedUserName);
backBtn = (ImageView) findViewById(R.id.backBtn);
sessionManager = new SessionManager(ChooseAccountActivity.this);
// getGlobalMethods().setImageBase64(ChooseAccountActivity.this, sessionManager.getPrefsSessionProfileImageBase64(), loggedUserImage, R.drawable.default_user);
loggedUserName.setText(sessionManager.getSessionUsername());
loggedUserLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_OK);
finish();
}
});
changeUserLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
callLoginActivity();
}
});
backBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
/**
* call Login Page for Edbrix Enterprise Login
*/
private void callLoginActivity() {
Intent loginEdbrixIntent = new Intent(ChooseAccountActivity.this, EdbrixLoginActivity.class);
startActivityForResult(loginEdbrixIntent, RecordPreviewActivity.REQUEST_CODE_EDBRIX_LOGIN);
}
/**
* Receiving activity result
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == RecordPreviewActivity.REQUEST_CODE_EDBRIX_LOGIN) {
if (resultCode == RESULT_OK) {
if (sessionManager.hasSessionCredentials()) {
setResult(RESULT_OK);
finish();
}
}
}
}
}
|
JavaScript
|
UTF-8
| 369
| 2.515625
| 3
|
[] |
no_license
|
import { useState } from "react"
export const useForm = (initialValue) => {
const [values, setValues] = useState(initialValue)
return [
values, (fromType, fromValue) => {
if(fromType === 'reset'){
return setValues(initialValue)
}
return setValues({...values, [fromType]: fromValue})
}
]
}
|
Java
|
UTF-8
| 989
| 2.890625
| 3
|
[] |
no_license
|
package Epam;
import Epam.chocolate.Cadbury;
import Epam.chocolate.Hersheys;
import Epam.chocolate.Nestle;
import Epam.gift.Gift;
import Epam.sweets.ghevar;
import Epam.sweets.Jalebi;
import Epam.sweets.Kheer;
import java.util.Scanner;
public class App
{
public static void main( String[] args )
{
Scanner sc=new Scanner(System.in);
Cadbury cadbury =new Cadbury();
Hersheys hersheys =new Hersheys();
Nestle nestle =new Nestle();
Kheer kheer =new Kheer();
ghevar ghevar =new ghevar();
Jalebi jalebi =new Jalebi();
Gift gift=new Gift();
gift.addSweets(kheer);
gift.addSweets(ghevar);
gift.addSweets(jalebi);
gift.addChocolates(cadbury);
gift.addChocolates(hersheys);
gift.addChocolates(nestle);
gift.sort();
gift.showChocolates();
gift.showSweets();
System.out.println(gift.totalWeight());
sc.close();
}
}
|
C
|
UTF-8
| 2,732
| 3.328125
| 3
|
[] |
no_license
|
/****************************************
* Author: Oksana Rubanov *
* Date: 27/11/2018 *
* Reviewer: Ori Friedman *
****************************************/
#include <stdio.h> /* printf */
#include <stdlib.h> /* malloc */
#include <assert.h> /* assert */
#include <string.h> /* memmove */
#include "dynamic_vector.h" /* API */
struct dynamic_vector
{
void *head;
size_t element_size;
size_t size;
size_t capacity;
};
vector_t *DVectorCreate(size_t number_of_elements, size_t element_size)
{
vector_t *vector = NULL;
assert(number_of_elements > 0 && element_size > 0);
vector = (vector_t *)malloc(sizeof(vector_t));
vector->head = malloc(number_of_elements * element_size);
if(NULL == vector->head || NULL == vector)
{
return NULL;
}
vector->element_size = element_size;
vector->size = 0;
vector->capacity = number_of_elements;
return vector;
}
void DVectorDestroy(vector_t *vector)
{
vector->element_size = 0;
vector->size = 0;
vector->capacity = 0;
free(vector->head);
free(vector);
}
void *DVectorGetItemAddress(vector_t *vector, size_t index)
{
char *ptr = NULL;
assert(NULL != vector);
ptr = (char *)vector->head;
ptr += (index * vector->element_size);
return ptr;
}
int DVectorPush(vector_t *vector, const void *element)
{
char *runner = NULL;
char *temp = NULL;
assert(NULL != vector && NULL != element);
if(vector->size == vector->capacity)
{
vector->capacity *= 2;
temp = (char *)realloc(vector->head, vector->capacity * vector->element_size);
if(NULL == vector->head)
{
return 1;
}
vector->head = temp;
}
runner = (char *)vector->head;
runner += (vector->size * vector->element_size);
memmove(runner, element, vector->element_size);
vector->size += 1;
return 0;
}
int DVectorPop(vector_t *vector)
{
assert(NULL != vector && 0 != vector->size);
vector->size -= 1;
if(vector->capacity / 4 >= vector->size)
{
vector->capacity = (vector->capacity / 2) + 1;
vector->head = (char *)realloc(vector->head, vector->capacity * vector->element_size);
if(NULL == vector->head)
{
return 1;
}
}
return 0;
}
int DVectorReserve(vector_t *vector, size_t fix_size)
{
void *temp = NULL;
assert(NULL != vector);
if(fix_size > vector->size)
{
vector->capacity = fix_size;
}
else
{
vector->capacity = vector->size;
}
temp = realloc(vector->head, (vector->capacity * vector->element_size));
if(NULL == vector->head)
{
return 1;
}
vector->head = temp;
return 0;
}
size_t DVectorSize(const vector_t *vector)
{
assert(NULL != vector);
return vector->size;
}
size_t DVectorCapacity(const vector_t *vector)
{
assert(NULL != vector);
return vector->capacity;
}
|
Markdown
|
UTF-8
| 3,184
| 3.875
| 4
|
[] |
no_license
|
# 컴퓨터공학 입문
## 4-1. 연산자(사칙, 관계, 논리 연산자)
<br/>
## 연산자(Operator)
### 목차
- 연산자의 개념
- 연산자의 분류
- 사칙 연산자
- 관계 연산자
- 논리 연산자
- 연산자 우선 순위
<br/>
### 연산자의 개념
- 연산자
- 연산자는 산술 연산자 +, -, *, / 기호와 같이 이미 정의된 연산을 수행하는 기호나 키워드를 의미
- 연산자는 왜 필요할까?
- 문제를 해결하는 방법에서 도구(장비)와 같은 역할
- 피연산자
- 연산(operation)에 참여하는 변수나 값을 피연산자(operand)
- 10 + 20
- +: 연산자
- 10, 20: 피연산자
<br/>
### 연산자 분류
| 분류 | 연산자 |
| ------------- | ---------------------- |
| 산술 연산자 | + - * / % |
| 관계 연산자 | > < == != >= <= |
| 증감 연산자 | ++ -- |
| 논리 연산자 | && \|\| ! |
| 조건 연산자 | (수식1)? 수식2 : 수식3 |
| sizeof 연산자 | sizeof(데이터타입) |
| 대입 연산자 | = += -= /= %= |
<br/>
### 대입 연산자(assignment operator)
- 변수의 저장 값을 대입하는 `=` 기호가 대입(할당) 연산자(assignment operator)
- `=` 연산자 오른쪽 수식을 먼저 계산하고 결과값을 왼쪽 변수에 대입하는 기능
- 대입 연산자의 왼쪽 부분에는 반드시 변수만이 가능, 대입 연산자 왼쪽에 온 변수는 값이 변경
- 수식의 결과 값을 변수에 대입하지 않으면 프로그램에는 영향이 없음
- ex) sum = 10 + 20
<br/>
### 관계 연산자(relational operator)
- 관계 연산자는 2개의 피연산자 관계(크기)를 비교하기 위한 연산자
- 관계 연산자가 포함된 수식의 결과는 1(참을 의미)이 아니면 0(거짓을 의미)
- 수식에서 참 또는 거짓으로 계산 결과가 나오는 경우 프로그래밍 언어에서는 편의상 참(1), 거짓(0) 으로 규정하였고 printf()를 사용하여 출력할 경우 결과가 참이면 정수 1, 거짓이면 0을 출력함
- ex)
| 연산자 | 기호 | 결과(a=10, b=20) |
| ----------- | ------ | ---------------- |
| 보다 크다 | a > b | 0 |
| 보다 작다 | a < b | 1 |
| 같다 | a = b | 0 |
| 같지 않다 | a != b | 1 |
| 크거나 같다 | a >= b | 0 |
| 작거나 같다 | a <= b | 1 |
<br/>
### 논리 연산자(logical operator)
- %%(and), ||(or), !(not)
- 논리 연산자는 두 개 또는 하나의 논리값을 0이나 1의 논리값으로 평가하기 위한 연산자
- | 연산자 기호 | 연산자 의미 |
| ----------- | ------------------------ |
| AND(&&) | 둘 다 참이어야 참 |
| OR(\|\|) | 둘 중 하나만 참이면 참 |
| NOT)! | 참이면 거짓, 거지이면 참 |
<br/>
- C언어는 참과 거짓이라는 상수는 없으며, `0`, `0.0`, `'\0'` 는 거짓으로, 0이 아닌 모든 값을 참으로 간주
<br/>
|
C#
|
UTF-8
| 1,640
| 2.765625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GuessMelody
{
public partial class gameOverForm : Form
{
gameForm gameForm;
Winning winning;
public gameOverForm(gameForm gameForm, Winning winning)
{
this.gameForm = gameForm;
this.winning = winning;
InitializeComponent();
}
private void gameOverForm_KeyPress(object sender, KeyPressEventArgs e)
{
this.Close();
gameForm.Close();
}
private void gameOverForm_Load(object sender, EventArgs e)
{
this.MaximizeBox = false;
if (winning == Winning.Player1)
label1.Text = "Player 1 \n WON THE GAME";
else if (winning == Winning.Player2)
label1.Text = "Player 2 \n WON THE GAME";
else
label1.Text = "DRAW";
}
private void label1_Click(object sender, EventArgs e)
{
this.Close();
gameForm.Close();
}
private void label2_Click(object sender, EventArgs e)
{
this.Close();
gameForm.Close();
}
private void gameOverForm_Move(object sender, EventArgs e)
{
gameForm.Location = this.Location;
}
private void gameOverForm_FormClosed(object sender, FormClosedEventArgs e)
{
gameForm.Close();
}
}
}
|
SQL
|
UTF-8
| 832
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
INSERT INTO `label` (`
label_id`,
`label_name
`) VALUES
(1, 'CUSTOMER'),
(2, 'HOT LEAD'),
(3, 'WARM LEAD'),
(4, 'COLD LEAD');
INSERT INTO `owner_visibility_group` (`
id`,
`owner_visibility_name
`, `description`) VALUES
(1, 'Owner only', 'Only the owner,admins and users in the parent groups can see and edit the details '),
(2, 'Owner visibility group', 'Users in the same visibility group,admins and users in the parent groups can see and edit the details'),
(3, 'Owner group and sub-group', 'Users in the same visibility group,sub-groups,admins and users in the parent groups can see and edit details'),
(4, 'Entire company', 'All users in the company can see and edit the details');
INSERT INTO `team` (`
team_id`,
`team_name
`, `team_manager`, `team_description`, `team_members`) VALUES
(1, 'Sales', 0, 'we love money', '8');
|
Python
|
UTF-8
| 217
| 2.921875
| 3
|
[] |
no_license
|
import os
a = os.listdir()
for i in a :
print(os.stat(i))
b = os.scandir('E:\\')
for i in b:
if i.is_file():
pass
else:
print(os.stat(i).st_size , end ="\t")
print(i.path )
|
C
|
UTF-8
| 223
| 3.40625
| 3
|
[] |
no_license
|
#include <stdio.h>
int main()
{
int a,b;
printf("enter the two numbers");
scanf("%d%d",&a,&b);
if(a>b)
printf("a=%d is maximum",a);
else
printf("b=%d is maximum",b);
}
|
Rust
|
UTF-8
| 1,025
| 2.734375
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
/* This will by default, create quotes sequentially. I may add a flag to create them for the same time in the future.
*/
extern crate bigdecimal;
extern crate chrono;
extern crate diesel;
extern crate rand;
extern crate rtss;
use self::rtss::*;
use bigdecimal::{BigDecimal, ToPrimitive};
use chrono::{NaiveDate, NaiveDateTime};
use rand::Rng;
use std::env::args;
use std::io::{stdin, Read};
use std::str::FromStr;
fn main() {
use rtss::schema::quotes::dsl::*;
let arg_num = args()
.nth(1)
.expect("Expected a number of quotes to create.");
let num_quotes = arg_num
.parse::<i32>()
.expect("Incorrect input for Number of Quotes.");
let arg_base_price = args().nth(2).expect("Expected a base price for quotes.");
let mut base_price =
BigDecimal::from_str(&arg_base_price).expect("Incorrect input for Base Price of Quotes.");
println!(
"\nCreating {} Quotes from base price {:?}",
num_quotes,
base_price.to_f32().unwrap()
);
}
|
C++
|
UTF-8
| 8,469
| 2.734375
| 3
|
[] |
no_license
|
#include <BMP280.h>
int BMP280::begin(int address, BMP180_Update_Rate rate, bool initWire){
bmpAddress = address;
this->rate = rate;
if(initWire){
Wire.begin();
Wire.setClock(400000);
}
if(checkID(true) == 0){
//get calibration data
getCalibrationValues(&calibrationValues);
setPressureOversampling(Pressure_Oversampling_8X);
setTemperatureOversampling(Temperature_Oversampling_1X);
//set normal mode
setMode();
//get the first set of datas
getPressure();
getTemperature();
return 0;
}
return 1;
}
float BMP280::getTemperature(){
//first read the value from the register
//three parts,
int status = update();
if((status == 0) | (previousTemperature == 0) | (!newTemperatureReported)){
previousTemperature = compensateTemperature(currentTemperatureData);
newTemperatureReported = true;
}
return previousTemperature;
}
float BMP280::getPressure(){
//first get datas
int status = update();
if((status == 0) | (previousPressure == 0) | (!newPressureReported)){
previousPressure = compensatePressure(currentPressureData);
newPressureReported = true;
}
return previousPressure;
}
float BMP280::getAltitudeFromBaselinePressure(float baseLinePressure){
//update temperature
//then pressure
//then claculate
int status = update();
if((status == 0) | (!newAltitudeReported) | (previousAltitude == 0)){
getTemperature();
getPressure();
previousAltitude = 44330.0*(1-pow(previousPressure/baseLinePressure,1/5.255));
newAltitudeReported = true;
}
return previousAltitude;
}
int BMP280::update(bool forceUpdate){
//first, decide if it is time to update
//Serial.println("Update Called!");
if(checkForUpdate() || forceUpdate){
//Serial.println("Updating!");
newPressureReported = false;
newTemperatureReported = false;
newAltitudeReported = false;
lastUpdateMillis = millis();
//grab all the datas
write8(BMP180_PRESSURE_MSB_ADDRESS);
Wire.requestFrom(bmpAddress, 6);
if(Wire.available()){
currentPressureData = (int32_t)(Wire.read());
currentPressureData <<= 8;
currentPressureData |= Wire.read();
currentPressureData <<= 8;
currentPressureData |= Wire.read();
//shift back 4
currentPressureData >>= 4;
currentTemperatureData = (int32_t)(Wire.read());
currentTemperatureData <<= 8;
currentTemperatureData |= Wire.read();
currentTemperatureData <<= 8;
currentTemperatureData |= Wire.read();
currentTemperatureData >>= 4;
}
return 0;
}
return BMP180_UPDATE_NOT_REQUIRED;
}
float BMP280::compensateTemperature(int32_t tempReading){
//magical formula as defined in the data sheet
int32_t var1, var2, T;
var1 = ((((tempReading>>3) - ((int32_t)calibrationValues.dig_T1<<1))) * ((int32_t)calibrationValues.dig_T2)) >> 11;
var2 = (((((tempReading>>4) - ((int32_t)calibrationValues.dig_T1)) * ((tempReading>>4) - ((int32_t)calibrationValues.dig_T1))) >> 12) * ((int32_t)calibrationValues.dig_T3)) >> 14;
t_fine = var1 + var2;
T = (t_fine * 5 + 128) >> 8;
return T/100.0;
}
float BMP280::compensatePressure(int32_t pressureReading){
int64_t var1, var2, p;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)calibrationValues.dig_P6;
var2 = var2 + ((var1*(int64_t)calibrationValues.dig_P5)<<17);
var2 = var2 + (((int64_t)calibrationValues.dig_P4)<<35);
var1 = ((var1 * var1 * (int64_t)calibrationValues.dig_P3)>>8) + ((var1 * (int64_t)calibrationValues.dig_P2)<<12);
var1 = (((((int64_t)1)<<47)+var1))*((int64_t)calibrationValues.dig_P1)>>33;
if (var1 == 0) {
return 0; // avoid exception caused by division by zero
}
p = 1048576-pressureReading;
p = (((p<<31)-var2)*3125)/var1;
var1 = (((int64_t)calibrationValues.dig_P9) * (p>>13) * (p>>13)) >> 25;
var2 = (((int64_t)calibrationValues.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((int64_t)calibrationValues.dig_P7)<<4);
return (float)(p/256.0);
}
bool BMP280::checkForUpdate(){
if(millis() - lastUpdateMillis > 1000.0/rate) return true;
return false;
}
int BMP280::getCalibrationValues(BMP180_Calibration_Values *values){
//per the data sheet, read these values in. Keep in mid their data type
//all are 16 bit shorts
write8(BMP180_CALIBRATION_DIG_T1_ADDRESS);
//request all 24 adresses
Wire.requestFrom(bmpAddress, 24);
//read in 1 at a time
if(Wire.available()){
values->dig_T1 = (u_int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_T2 = (int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_T3 = (int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_P1 = (u_int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_P2 = (int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_P3 = (int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_P4 = (int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_P5 = (int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_P6 = (int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_P7 = (int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_P8 = (int16_t)(Wire.read()|(Wire.read()<<8));
values->dig_P9 = (int16_t)(Wire.read()|(Wire.read()<<8));
Serial.println(values->dig_T1);
Serial.println(values->dig_T2);
Serial.println(values->dig_T3);
return 0;
}
return BMP180_CALIBRATION_DATA_READ_FAILURE;
}
int BMP280::checkID(bool shouldReset){
//first reset the device if desired
if(shouldReset){
int resetStatus = reset();
if(resetStatus != 0){
return BMP180_CONNECTION_ISSUE;
}
}
//get the address of the device
int resp = read8(BMP180_ID_ADDRESS);
//compare, if correct, return 0
if(resp == BMP180_WHO_AM_I_RESPONSE){
return 0;
}
//return failure values as required
if(resp == -1){
return BMP180_CONNECTION_ISSUE;
}
else{
return BMP180_BAD_WHO_AM_I_ADDRESS;
}
return 1;
}
int BMP280::reset(){
//reset, no easy way to check for alive
write8(bmpAddress, BMP180_RESET_WRITE_VALUE);
delay(1);
return 0;
}
int BMP280::setTemperatureOversampling(BMP180_Temperature_Oversampling sample){
//first read the data in the register
int settings = read8(BMP180_CTRL_MEAS_ADDRESS);
//combine oversampling into the current settings
settings &= 0b00011111;
settings |= sample << 5;
//update the currentSampling
//currentSampling = sample;
//send back to the BMP
return write8(BMP180_CTRL_MEAS_ADDRESS, settings);
}
int BMP280::setPressureOversampling(BMP180_Pressure_Oversampling sample){
//first read the data in the register
int settings = read8(BMP180_CTRL_MEAS_ADDRESS);
//combine oversampling into the current settings
settings &= 0b11100011;
settings |= sample << 2;
//update the currentSampling
//currentSampling = sample;
//send back to the BMP
return write8(BMP180_CTRL_MEAS_ADDRESS, settings);
}
int BMP280::setMode(){
//go to normal for now
//read the settings in the control
int settings = read8(BMP180_CTRL_MEAS_ADDRESS);
settings &= 0b11111100;
settings |= 0b00000011;
//write settings
write8(BMP180_CTRL_MEAS_ADDRESS,settings);
return 0;
}
int BMP280::setFilter(BMP180_Filter_Coefficients coefficient){
//first read the data in the register
int settings = read8(BMP180_CONFIG_ADDRESS);
//combine oversampling into the current settings
settings &= 0b11100011;
settings |= coefficient << 2;
//update the currentSampling
//currentSampling = sample;
//send back to the BMP
return write8(BMP180_CONFIG_ADDRESS, settings);
}
int BMP280::read8(int address){
Wire.beginTransmission(bmpAddress);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(bmpAddress, 1);
if(Wire.available()){
return Wire.read();
}
return -1;
}
int BMP280::write8(int address, int value){
Wire.beginTransmission(bmpAddress);
Wire.write(address);
Wire.write(value);
Wire.endTransmission();
return 0;
}
int BMP280::write8(int address){
Wire.beginTransmission(bmpAddress);
Wire.write(address);
Wire.endTransmission();
return 0;
}
|
Java
|
UTF-8
| 3,464
| 1.96875
| 2
|
[] |
no_license
|
package com.komiut.conductor.ui.passenger;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Boarding {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("departure")
@Expose
private String departure;
@SerializedName("destination")
@Expose
private String destination;
@SerializedName("latitude_from")
@Expose
private Double latitudeFrom;
@SerializedName("longitude_from")
@Expose
private Double longitudeFrom;
@SerializedName("fare")
@Expose
private Integer fare;
@SerializedName("amount")
@Expose
private Integer amount;
@SerializedName("latitude")
@Expose
private Object latitude;
@SerializedName("longitude")
@Expose
private Object longitude;
@SerializedName("depart")
@Expose
private Object depart;
@SerializedName("dest")
@Expose
private Object dest;
@SerializedName("name")
@Expose
private Object name;
@SerializedName("phone")
@Expose
private Object phone;
public String getBoarded() {
return boarded;
}
public void setBoarded(String boarded) {
this.boarded = boarded;
}
@SerializedName("boarded")
@Expose
private String boarded;
public String getPlate() {
return plate;
}
public void setPlate(String plate) {
this.plate = plate;
}
@SerializedName("plate")
@Expose
private String plate;
public Object getName() {
return name;
}
public void setName(Object name) {
this.name = name;
}
public Object getPhone() {
return phone;
}
public void setPhone(Object phone) {
this.phone = phone;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDeparture() {
return departure;
}
public void setDeparture(String departure) {
this.departure = departure;
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
public Double getLatitudeFrom() {
return latitudeFrom;
}
public void setLatitudeFrom(Double latitudeFrom) {
this.latitudeFrom = latitudeFrom;
}
public Double getLongitudeFrom() {
return longitudeFrom;
}
public void setLongitudeFrom(Double longitudeFrom) {
this.longitudeFrom = longitudeFrom;
}
public Integer getFare() {
return fare;
}
public void setFare(Integer fare) {
this.fare = fare;
}
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Object getLatitude() {
return latitude;
}
public void setLatitude(Object latitude) {
this.latitude = latitude;
}
public Object getLongitude() {
return longitude;
}
public void setLongitude(Object longitude) {
this.longitude = longitude;
}
public Object getDepart() {
return depart;
}
public void setDepart(Object depart) {
this.depart = depart;
}
public Object getDest() {
return dest;
}
public void setDest(Object dest) {
this.dest = dest;
}
}
|
Java
|
UTF-8
| 1,504
| 2.453125
| 2
|
[] |
no_license
|
/**
* <p> Title: RecipeEntry.java </p>
* <p> Description:
*
* </p>
* <p> 2008</p>
* @author RHolland
*
*
*/
package com.baristamatic.entity;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
@Entity
public class RecipeEntry {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Integer ingredientCount;
/*
* ingredient_id is foreign key column generated in RecipeEntry table referencing Ingredient table row
* cascade saves ingredient when this class is saved
*/
@OneToOne(cascade = {CascadeType.PERSIST})
@JoinColumn(name="ingredient_id")
private Ingredient ingredient;
// @ManyToOne
// @JoinColumn(name="recipe_id")
// private Recipe recipe;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getIngredientCount() {
return ingredientCount;
}
public void setIngredientCount(Integer ingredientCount) {
this.ingredientCount = ingredientCount;
}
public Ingredient getIngredient() {
return ingredient;
}
public void setIngredient(Ingredient ingredient) {
this.ingredient = ingredient;
}
// public Recipe getRecipe() {
// return recipe;
// }
//
// public void setRecipe(Recipe recipe) {
// this.recipe = recipe;
// }
}
|
Python
|
UTF-8
| 568
| 3.71875
| 4
|
[] |
no_license
|
# 299. Bulls and Cows
# Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
a, b = 0, 0
c = [0 for c in range(len(guess))]
gc = [0 for c in range(10)]
sc = [0 for c in range(10)]
for i, g in enumerate(guess):
if g == secret[i]:
c[i] = 1
a += 1
else:
gc[int(g)] += 1
sc[int(secret[i])] += 1
for i in range(10):
b += min(gc[i], sc[i])
return "%dA%dB" % (a, b)
|
Python
|
UTF-8
| 550
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
x = [0]
x[0] = x[0] + 1
print(x[0])
print("########")
y = [0]
z = y
z[0] = z[0] + 1
print(y[0])
print(z[0])
print("########")
u = [0]
v = u
u[0] = u[0] + 1
print(u[0])
print(v[0])
print("########")
a = [0]
b = [a[0]]
b[0] = b[0] + 1
print(a[0])
print(b[0])
print("########")
i = [0]
j = [i[0]]
i[0] = i[0] + 1
print(i[0])
print(j[0])
print("########")
q = [0]
r = [q]
s = [r[0]]
q[0] = q[0] + 1
r[0][0] = r[0][0] + 1
print(q[0])
print(r[0])
print(s[0])
print("########")
q = [0]
r = [q[0]]
s = [r[0]]
q[0] = q[0] + 1
r[0] = r[0] + 1
|
Java
|
UTF-8
| 1,273
| 2.5625
| 3
|
[] |
no_license
|
package com.testTask.service.implementation;
import com.testTask.dao.implementation.WellDaoImpl;
import com.testTask.domain.Well;
import com.testTask.service.WellService;
import java.util.ArrayList;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class WellServiceImpl implements WellService {
private static final Logger logger = LogManager.getLogger(WellServiceImpl.class);
public WellServiceImpl() {
}
WellDaoImpl wellDaoImpl = new WellDaoImpl();
@Override
public Well getWellByName(String name) {
Well well;
try {
well = wellDaoImpl.getWellByName(name);
return well;
}
catch (NullPointerException npe) {
logger.error("This is error : " + npe.getMessage(), npe);
}
return null;
}
@Override
public Well createWellByName(String name) {
Well well = new Well();
well.setName(name);
return wellDaoImpl.createWell(well);
}
@Override
public List<String> getWellsName() {
List<String> wellNames = new ArrayList<>();
wellDaoImpl.getAllWells().forEach(well -> wellNames.add(well.getName()));
return wellNames;
}
@Override
public List<Well> getAllWells() {
return wellDaoImpl.getAllWells();
}
}
|
Python
|
UTF-8
| 579
| 3.3125
| 3
|
[] |
no_license
|
def manipulate_generator(generator, n):
divisor=2
if(n == 1):
generator
else:
for j in range(divisor,n):
remainder = n % j
result.append(remainder)
if 0 in result:
reduce(generator,n)
def positive_integers_generator():
n = 1
while True:
x = yield n
if x is not None:
n = x
else:
n += 1
k = int(input())
g = positive_integers_generator()
for _ in range(k):
n = next(g)
print(n)
manipulate_generator(g, n)
|
Markdown
|
UTF-8
| 20,137
| 2.90625
| 3
|
[] |
no_license
|
# A0126331U
###### Soft-Eng-Project/TaskApp/CommandParser/CommandParser.java
``` java
*
*/
public class CommandParser {
private static CommandParser cp;
private static final String USER_COMMAND_ADD = "add";
private static final String USER_COMMAND_DELETE = "delete";
private static final String USER_COMMAND_DELETE_INDEX = "deletei";
private static final String USER_COMMAND_READ = "read";
private static final String USER_COMMAND_UPDATE_BY_INDEX = "update";
private static final String USER_COMMAND_UPDATE_STATUS_BY_INDEX = "status";
private static final String USER_COMMAND_SEARCH = "search";
private static final String USER_COMMAND_UNDO = "undo";
private static final String USER_COMMAND_EXIT = "exit";
private static final String USER_COMMAND_MOVE_FILE ="file";
private static ArrayList<SimpleDateFormat> KNOWPATTERNS;
private static final String[] PREPOSITION_KEYWORD = {"AT", "BY", "FROM", "TO", "ON"};
private static final String[] MONTHS = {"JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};
private static final String[] DAY_OF_THE_WEEK = {"MON", "TUE","WED","THU","FRI","SAT","SUN"};
public CommandParser() {
KNOWPATTERNS = initTimeFormatBank();
}
public static CommandParser getInstance() {
if (cp == null) {
cp = new CommandParser();
}
return cp;
}
/**This method is to parse file content in the form of ArrayList<String>
* to ArrayList<Task> when the application launches.
*
* @param ArrayList<String>
* @return ArrayList<Tasks>
*/
public ArrayList<Tasks> parseArrList(ArrayList<String> strTaskList) {
return TaskParser.parseArrList(strTaskList);
}
public Command parse(String input) {
initTimeFormatBank();
Command command;
String commandTypeString = getFirstWord(input);
String remainStr = removeString(input, commandTypeString);
switch (commandTypeString.toLowerCase()) {
case USER_COMMAND_ADD :
command = initAddCommand(remainStr);
break;
case USER_COMMAND_DELETE :
command = initDeleteComamnd(remainStr);
break;
case USER_COMMAND_DELETE_INDEX :
command = initDeleteIndex(remainStr);
break;
case USER_COMMAND_UPDATE_BY_INDEX :
command = initUpdateDate(remainStr);
break;
case USER_COMMAND_UPDATE_STATUS_BY_INDEX :
command = initUpdateStatus(remainStr);
break;
case USER_COMMAND_READ :
command = initReadCommand(remainStr);
break;
case USER_COMMAND_SEARCH :
command = initSearchCommand(remainStr);
break;
case USER_COMMAND_EXIT :
command = initExitCommand();
break;
case USER_COMMAND_UNDO :
command = initUndoCommand();
break;
case USER_COMMAND_MOVE_FILE :
command = initFileLocation(remainStr);
break;
default :
command = initInvalidCommand();
break;
}
return command;
}
// ================================================================
// Create update read event on specific date command method
// ================================================================
private Command initReadCommand(String str) {
Command cmd = new Command(Command.TYPE.READ);
ArrayList<Date> dates = new ArrayList<Date>();
Date date = new Date();
if(str.equalsIgnoreCase("today")) {
date = endOfDay(date);
}
else {
date = convertToDate(str);
if(date==null) {
return initInvalidCommand();
}
date = endOfDay(date);
}
dates.add(date);
cmd.setDates(dates);
return cmd;
}
// ================================================================
// Create update date command method
// ================================================================
private Command initUpdateDate(String remainStr) {
Command cmd = new Command(Command.TYPE.UPDATE);
ArrayList<Date> dates = new ArrayList<Date>();
String str = getFirstWord(remainStr);
if(!isNumeric(str)) {
return initInvalidCommand();
}
cmd.setTask(str);
String rawDate = removeString(remainStr, str);
createTimeConstraint(cmd, rawDate, dates);
cmd.setDates(dates);
return cmd;
}
// ================================================================
// Create update status command method
// ================================================================
private Command initUpdateStatus(String remainStr) {
if(!isNumeric(remainStr)) {
return initInvalidCommand();
}
Command cmd = new Command(Command.TYPE.STATUS);
cmd.setTask(remainStr);
return cmd;
}
// ================================================================
// Create delete by index command method
// ================================================================
private Command initDeleteIndex(String remainStr) {
if(!isNumeric(remainStr)) {
return initInvalidCommand();
}
Command cmd = new Command(Command.TYPE.DELETEI);
cmd.setTask(remainStr);
return cmd;
}
// ================================================================
// Create delete by a given string command method
// ================================================================
private Command initDeleteComamnd(String remainStr) {
Command cmd = new Command(Command.TYPE.DELETE);
cmd.setTask(remainStr);
return cmd;
}
// ================================================================
// Create file moving command method
// ================================================================
private Command initFileLocation(String directory) {
if(directory.length()==0) {
return initInvalidCommand();
}
Command cmd = new Command(Command.TYPE.FILE);
File file = new File(directory);
try {
if((!directory.isEmpty()) && file.createNewFile()) {
cmd.setTask(directory);
}
} catch (IOException e) {
return initInvalidCommand();
}
return cmd;
}
// ================================================================
// Create exit command method
// ================================================================
private Command initExitCommand() {
return new Command(Command.TYPE.EXIT);
}
// ================================================================
// Create invalid command method
// ================================================================
private Command initInvalidCommand() {
return new Command(Command.TYPE.INVALID);
}
// ================================================================
// Create undo string command method
// ================================================================
private Command initUndoCommand() {
return new Command(Command.TYPE.UNDO);
}
// ================================================================
// Create search by a given string command method
// ================================================================
private Command initSearchCommand(String remainStr) {
if(remainStr.length()==0) {
return initInvalidCommand();
}
Command cmd = new Command(Command.TYPE.SEARCH);
cmd.setTask(remainStr);
return cmd;
}
// ================================================================
// Create add command method
// ================================================================
private Command initAddCommand(String remainStr) {
Command cmd = new Command(Command.TYPE.ADD);
createTask(remainStr, cmd);
return cmd;
}
public void createTask(String remainStr, Command cmd) {
ArrayList<Date> dates = new ArrayList<Date>();
String event = initEvent(remainStr);
cmd.setTask(event);
String timeStr = removeString(remainStr, event).toLowerCase();
if (timeStr.contains("every") && timeStr.contains("until")) {
createReoccurringTimeConstraint(cmd, timeStr, dates);
}
else if(timeStr.contains("every") && timeStr.contains("from") && timeStr.contains("to")) {
createDurationReoccurringTimeConstraint(cmd, timeStr, dates);
}
else {
createTimeConstraint(cmd, timeStr, dates);
}
cmd.setDates(dates);
}
private void createDurationReoccurringTimeConstraint(Command cmd, String timeStr, ArrayList<Date> dates) {
ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(timeStr.split("\\b(to)\\b")));
Date endDate = convertToDate(arrList.get(arrList.size()-1).trim());
arrList = new ArrayList<String>(Arrays.asList(arrList.get(0).split("\\b(from)\\b")));
Date startDate = convertToDate(arrList.get(arrList.size()-1).trim());
if(endDate==null || startDate==null || endDate.getTime()<startDate.getTime()) {
cmd.setCommandType(Command.TYPE.INVALID);
return;
}
endDate = endOfDay(endDate);
startDate = startOfDay(startDate);
String str = arrList.get(0).replaceAll("\\b(from|to|at|on|by|every|until)\\b", "").trim();
int dayOfWeek = convertDayToInt(str);
if (dayOfWeek==-1) {
cmd.setCommandType(Command.TYPE.INVALID);
return;
}
cmd.setKey(1);
if(isSameDay(startDate, dayOfWeek)) {
dates.add(startDate);
}
Date baseDate = getNextOccurenceOfDay(startDate, dayOfWeek);
while(baseDate.getTime()<endDate.getTime()) {
dates.add(baseDate);
baseDate = startOfDay(getNextOccurenceOfDay(baseDate, dayOfWeek));
}
cmd.setDates(dates);
}
private void createReoccurringTimeConstraint(Command cmd, String timeStr, ArrayList<Date> dates) {
ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(timeStr.split("\\b(until)\\b")));
Date endDate = convertToDate(arrList.get(arrList.size()-1).trim());
if(endDate==null) {
cmd.setCommandType(Command.TYPE.INVALID);
return;
}
endDate = endOfDay(endDate);
String str = arrList.get(0).replaceAll("\\b(from|to|at|on|by|every|until)\\b", "").trim();
int dayOfWeek = convertDayToInt(str);
if (dayOfWeek==-1) {
cmd.setCommandType(Command.TYPE.INVALID);
return;
}
cmd.setKey(1);
Date today = startOfDay(new Date());
if(isSameDay(today, dayOfWeek)) {
dates.add(today);
}
Date baseDate = getNextOccurenceOfDay(today, dayOfWeek);
while(baseDate.getTime()<endDate.getTime()) {
dates.add(baseDate);
baseDate = startOfDay(getNextOccurenceOfDay(baseDate, dayOfWeek));
}
cmd.setDates(dates);
}
private void createTimeConstraint(Command cmd, String str, ArrayList<Date> dates) {
str = str.replaceAll("\\b(from|to|at|on|by|every|until)\\b", "-");
ArrayList<String> tokens = new ArrayList<String>(Arrays.asList(str.split("-")));
tokens.removeAll(Collections.singleton(""));
saveToDateList(cmd ,tokens, dates);
}
// parse tokens to date object, cmd type may possibly change
private void saveToDateList(Command cmd, ArrayList<String> tokens, ArrayList<Date> dateList) {
for(int i=0; i<tokens.size(); i++) {
for (SimpleDateFormat pattern : KNOWPATTERNS) {
try {
if(pattern.toLocalizedPattern().length()==tokens.get(i).trim().length()){
pattern.setLenient(false);
Date date = pattern.parse(tokens.get(i).trim());
dateList.add(date);
break;
}
} catch (ParseException pe) {
}
}
}
if(dateList.size()!=tokens.size()) {
cmd.setCommandType(Command.TYPE.INVALID);
}else if(dateList.size()==2 && dateList.get(0).getTime() > dateList.get(1).getTime()) {
cmd.setCommandType(Command.TYPE.INVALID);
}
}
// covert a string into date
public Date convertToDate(String str) {
for (SimpleDateFormat pattern : KNOWPATTERNS) {
try {
if(pattern.toLocalizedPattern().length()==str.trim().length()){
pattern.setLenient(false);
Date date = pattern.parse(str.trim());
return date;
}
} catch (ParseException pe) {
}
}
return null;
}
private String getFirstWord(String str) {
return str.trim().split(" ")[0];
}
private String removeString(String str, String strToRemove) {
return str.replaceFirst(strToRemove, "").trim();
}
// create event string
private String initEvent(String str) {
StringBuilder sb = new StringBuilder();
String[] pieces = str.split(" ");
for (int i = 0; i < pieces.length; i++) {
if(toAppend(pieces, i)) {
sb.append(" ");
sb.append(pieces[i].trim());
}
else
break;
}
return sb.toString().trim();
}
private boolean isTimeFormat(String str) {
if (str.contains("/") || isNumeric(str) ||isDay(str)||isMonth(str) || str.matches("^(\\d+-?)+\\d+$")) {
return true;
}
else
return false;
}
private boolean isMonth(String str) {
for(int i=0; i< MONTHS.length; i++) {
if(str.equalsIgnoreCase(MONTHS[i]))
return true;
}
return false;
}
private boolean isDay(String str) {
for(int i=0; i< DAY_OF_THE_WEEK.length; i++) {
if(str.equalsIgnoreCase(DAY_OF_THE_WEEK[i]))
return true;
}
return false;
}
private boolean isPrepositionKeyword(String str) {
for(int i=0; i<PREPOSITION_KEYWORD.length; i++) {
if(str.equalsIgnoreCase(PREPOSITION_KEYWORD[i])) {
return true;
}
}
return false;
}
private boolean isReoccurringKeyword(String str) {
return str.equalsIgnoreCase("EVERY") || str.equalsIgnoreCase("UNTIL") || str.equalsIgnoreCase("EVERYDAY");
}
private boolean isSameDay(Date date, int dayOfWeek) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return dayOfWeek == cal.get(Calendar.DAY_OF_WEEK);
}
//check a token in a array ok to be appended
private boolean toAppend(String[] arr, int i) {
if(!isPrepositionKeyword(arr[i]) && !isTimeFormat(arr[i]) && !isReoccurringKeyword(arr[i])) {
return true;
}
if(isPrepositionKeyword(arr[i])==true && i <arr.length-1 && !isTimeFormat(arr[i+1])) {
return true;
}
if(isNumeric(arr[i]) && i>=1 && !isPrepositionKeyword(arr[i-1])) {
return true;
}
return false;
}
private boolean isNumeric(String str) {
String regex = "\\d+";
return str.matches(regex);
}
private int convertDayToInt(String str) {
int i;
switch (str.toLowerCase()) {
case "mon" :
case "monday" :
i = 2;
break;
case "tue" :
case "tuesday" :
i = 3;
break;
case "wed" :
case "wednesday" :
i = 4;
break;
case "thu" :
case "thursday" :
i = 5;
break;
case "fri" :
case "friday" :
i = 6;
break;
case "sat" :
case "saturday" :
i = 7;
break;
case "sun" :
case "sunday" :
i = 1;
break;
default :
i = -1;
break;
}
return i;
}
/**This method is to calculate the next nearest occurrence of specific day of the week after a specific date
*
* @param Date: the reference date
* @param int: integer representation of day of the week
* @return Date: next occurrence of the day
*/
private Date getNextOccurenceOfDay(Date today, int dayOfWeek) {
Calendar cal = Calendar.getInstance();
cal.setTime(today);
int dow = cal.get(Calendar.DAY_OF_WEEK);
int numDays = 7 - ((dow - dayOfWeek) % 7 + 7) % 7;
cal.add(Calendar.DAY_OF_YEAR, numDays);
return cal.getTime();
}
public static Date startOfDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
public static Date endOfDay(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
/**This method is to add known patterns of date to the pattern bank
*
* @return knowPatterns: the known pattern bank that will be used in parser.
*/
private ArrayList<SimpleDateFormat> initTimeFormatBank() {
ArrayList<SimpleDateFormat> knowPatterns = new ArrayList<SimpleDateFormat>();
knowPatterns.add(new SimpleDateFormat("HHmm MMM dd yyyy"));
knowPatterns.add(new SimpleDateFormat("HHmm MMM d yyyy"));
knowPatterns.add(new SimpleDateFormat("HHmm dd/MM/yyyy"));
knowPatterns.add(new SimpleDateFormat("HHmm d/MM/yyyy"));
knowPatterns.add(new SimpleDateFormat("HHmm dd/M/yyyy"));
knowPatterns.add(new SimpleDateFormat("HHmm d/M/yyyy"));
knowPatterns.add(new SimpleDateFormat("dd/MM/yyyy"));
knowPatterns.add(new SimpleDateFormat("d/MM/yyyy"));
knowPatterns.add(new SimpleDateFormat("d/M/yyyy"));
knowPatterns.add(new SimpleDateFormat("dd/M/yyyy"));
knowPatterns.add(new SimpleDateFormat("MMM d yyyy"));
knowPatterns.add(new SimpleDateFormat("MMM dd yyyy"));
knowPatterns.add(new SimpleDateFormat("d MMM yyyy"));
knowPatterns.add(new SimpleDateFormat("dd MMM yyyy"));
return knowPatterns;
}
}
```
###### Soft-Eng-Project/TaskApp/CommandParser/TaskParser.java
``` java
*
*/
public class TaskParser {
private static Logger logger = Logger.getLogger("Warning");
private static final String PARSE_PATTERN = "EEE MMM dd HH:mm:ss Z yyyy";
public TaskParser() {
}
public static ArrayList<Tasks> parseArrList(ArrayList<String> arrList) {
ArrayList<Tasks> tasks = new ArrayList<Tasks>();
for(int i=0; i<arrList.size(); i++) {
ArrayList<Date> dates = new ArrayList<Date>();
String event = createEvent(arrList.get(i));
toDateList(dates ,arrList.get(i));
tasks.add(new Tasks(event, dates));
}
return tasks;
}
private static String createEvent(String string) {
String[] tokens = string.split("\\[");
return tokens[0].trim();
}
private static void toDateList(ArrayList<Date> dates, String string) {
String[] tokens = string.split("\\[");
String str =tokens[1].substring(0, tokens[1].length()-1);
String[] rawDate = str.split(",");
SimpleDateFormat sdf = new SimpleDateFormat(PARSE_PATTERN);
for(int i=0; i<rawDate.length; i++) {
try {
Date date = sdf.parse(rawDate[i].trim());
dates.add(date);
} catch (ParseException e) {
logger.log(Level.INFO, "Acceptable Condition: empty date.");
}
}
}
}
```
###### Soft-Eng-Project/TaskApp/logic/Logic.java
``` java
private void prepareSystem() {
if (store.isEmptyFile(directoryFile)) {
store.updateToFile(directoryFile, taskFile.getAbsolutePath());
}
taskFile = new File(store.readLastLineFromFile(directoryFile));
taskListString = store.accessToFile(taskFile);
taskList = new ArrayList<>(parser.parseArrList(taskListString));
setIndex();
}
```
###### Soft-Eng-Project/TaskApp/logic/Logic.java
``` java
private File movedFile(File oldFile, String directory) {
Path movefrom = FileSystems.getDefault().getPath(oldFile.getAbsolutePath());
Path target = FileSystems.getDefault().getPath(directory);
try {
Files.move(movefrom, target, StandardCopyOption.REPLACE_EXISTING);
File file = new File(target.toString());
return file;
} catch (IOException e) {
System.err.println(e);
}
return null;
}
/**
* This method returns the content of the console.
*
* @return ArrayList of the console results.
* @author A0145617A
*/
```
|
Markdown
|
UTF-8
| 7,369
| 3.609375
| 4
|
[
"MIT"
] |
permissive
|
```js
import React, {useState} from 'react'
export default function App(){
const [number, setNumber] = useState(0)
const [dark, setDark] = useState(flase)
const doubleNumber = slowFunction(number)
const themeStyles = {
backgroundColor: dark ? 'black' : 'white',
color: dark ? 'white' : 'black'
}
return (
<>
<input type="number" value={number} onChange={e => setNumber(parseInt(e.target.value))} />
<button onClick={() => setDark(prevDark => !prevDark)}>Change Theme</button>
<div style={themeStyle}>{doubleNumber}</div>
</>
)
}
function slowFunction(num){
console.log('Calling Slow Function')
// to emulate what would happen in a slow long-running complex function
for (let i = 0; i <= 100000000; i++){}
return num * 2
}
// problme
// slowness is not only gonna be slow update our number
// if we click our change theme button you're gonna notice we have the same delay
// the reason for that is because one you update state and react
// it's going to re-render your entire component
// so it's going to run this entire App function from top to bottom
// which means this slow function get called every single time that we render
// App component so whether we're changing the theme whether we're updating
// the number here or whether some other component is causing this component
// to re-render you're going to be forcing it to go through that slow function
// over and over again
```
> we need to useMemo to resolve this problem
```js
import React, {useState, useMemo} from 'react'
export default function App(){
const [number, setNumber] = useState(0)
const [dark, setDark] = useState(flase)
// slowFunction here, takes input of a number and it's always going to give us
// the same output every time we give it the same input
// so we can catch that input value number and the output it give us that way
// if the number doesn't change we dont have to recalculate our solo function
// useMemo pass it in a function
const doubleNumber = useMemo(() => {
return slowFunction(number)
}, [number])
const themeStyles = {
backgroundColor: dark ? 'black' : 'white',
color: dark ? 'white' : 'black'
}
return (
<>
<input type="number" value={number} onChange={e => setNumber(parseInt(e.target.value))} />
<button onClick={() => setDark(prevDark => !prevDark)}>Change Theme</button>
<div style={themeStyle}>{doubleNumber}</div>
</>
)
}
function slowFunction(num){
console.log('Calling Slow Function')
for (let i = 0; i <= 100000000; i++){}
return num * 2
}
// when we go through our code we click Change theme it causes our component to re-render
// so it calls this function does all these stuffs and it gets down to useMemo
// and it says well our number is exactly the same as what it was last time
// so we're not gonna recall this slow function, because we already know what
// the result is, it's the exact same thing as it was last time
// so we're saving ourselves from having to recalculate this number with the slow function
// and we only forcing ourselves to do this when we update this number instead of our input
// so we only running this slow code when we have to and not running it when we dont need
```
> the reason you dont want to memorize everything
> because it does give you some performance overheads and some memory overhead
> for example this useMemo function must be called every single render of your component
> so you're calling an additional function and also it's saving the value this previous
> value in some memory variable so you're forcing your memory to get larger every time
> you useMemo because you have to store an additional variable in memory to store that
> previous value
> if you start to do this everywhere in your application especially where u dont need it
> it's going to cause additional memory usage and additional performance problems
> when just not using it would have been better
> so only useMemo in this case when you actually need the performance benefits
> when the function you're calling is incredibly slow
> second case for useMemo
> that is something called the referential equality and if you aren't really familiar
> with value versus reference in JavaScript
> when you try to compare two different variables in JavaScript it's going to compare
> the reference in the case of objects and arrays for example theme styles
```js
const themeStyles = {
backgroundColor: dark ? 'black' : 'white',
color: dark ? 'white' : 'black'
}
const themeStyles2 = {
backgroundColor: dark ? 'black' : 'white',
color: dark ? 'white' : 'black'
}
// themeStyles and themeStyles2 are equal to each other
// but JavaScript they reference two different objects
// they just have the same values in the object
// but the reference to the object itself is different
// these two values are not equal to each other
```
```js
const themeStyles = {
backgroundColor: dark ? 'black' : 'white',
color: dark ? 'white' : 'black'
}
useEffect(() =>{
console.log('Theme Changed')
}, [themeStyles])
// if we changed the number, it's alse causing this theme change to be run
// and the reason for that referential equality what's happening is every time
// we run our function, we get a new theme styles object being created
// and the new theme style object is not the same as the old theme styles
// even though they have the exact same values in the object
// the reference different places in memory and that's really important to know
// so make sure that we only ever run useEffect when our theme style object
// gets object we can useMemo again
const themeStyles = useMemo(() => {
return {
backgroundColor: dark ? 'black' : 'white',
color: dark ? 'white' : 'black'
}
}, [dark])
useEffect(() => {
console.log('Theme Changed')
}, [themeStyles])
// we are wrapping this object inside of memorisation,
// if our dark variables doesn't change we dont read out theme styles
// so we get the exact same reference as we had the previous time we rendered our app
// so now our useEffect is comparing our old theme styles with our new theme styles
// but they both reference the exact same object
```
> so these are the two big use cases for the useMemo
> 1. when you want to make a slow function we wrap it in this useMemo
> so that doesn't recompute every single time you render your component
> and it only computes when you actually need the value from the function
> since the inputs actually changed
> 2. idea of a referential equality whenever you want to make sure the reference of a object
> or array is exactly the same as it was the last time you rendered if none of the internal
> workings changed you're gonna want to useMemo here to make sure that you only
> update the reference of that object whenever the actual contents of the object changed\
> instead of updating every single time you render
|
C++
|
UTF-8
| 154
| 2.609375
| 3
|
[] |
no_license
|
#include <iostream>
using namespace std;
int main() {
int a,b,c,d;
cin>>a>>b>>c>>d;
int num = min(a,min(b,min(c,d)));
cout<<num<<endl;
}
|
Java
|
UTF-8
| 1,288
| 1.898438
| 2
|
[] |
no_license
|
package cn.labsoft.labos.base.logs.vo;
import cn.labsoft.labos.framework.common.vo.BaseVo;
@SuppressWarnings("serial")
public class LabLogExceptionVo extends BaseVo {
private String id;
private String clazz;
private String funId;
private String lineNum;
private String method;
private String exception;
private String userInfo;
private String uri;
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public String getUserInfo() {
return userInfo;
}
public void setUserInfo(String userInfo) {
this.userInfo = userInfo;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFunId() {
return funId;
}
public void setFunId(String funId) {
this.funId = funId;
}
public String getLineNum() {
return lineNum;
}
public void setLineNum(String lineNum) {
this.lineNum = lineNum;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public String getException() {
return exception;
}
public void setException(String exception) {
this.exception = exception;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
}
|
C++
|
UTF-8
| 471
| 3.109375
| 3
|
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
void add_factors(long n){
long temp_n = n;
int i = 2;
while(true){
while(n % i == 0){
cout << i << endl;
n /= i;
}
if(i == 2){
i += 1;
}
else{
i += 2;
}
if(i == temp_n/2){
break;
}
}
return;
}
int main(){
long n = 600851475143;
add_factors(n);
}
|
JavaScript
|
UTF-8
| 1,360
| 2.546875
| 3
|
[] |
no_license
|
function update() {
var email = $("#email").val();
var password = $("#password").val();
var password2 = $("#password2").val();
if(email === "" || password === "" || password2 === ""){
alert("欄位請勿空白");
return;
}
if(password != password2){
alert("兩次密碼輸入不一樣");
return;
}
$.post("./ForgetPassServlet_b1",{ "email" : email , "password" : password} , function(data){
if(data === "已成功變更密碼"){
alert(data);
window.location.href="jsp/front/login_b1.jsp";
}else{
alert(data);
}
});
}
$(document).ready(function(){
$(window).resize(function () {
resize();
});
function resize(){
var bodyh = $(".content").height();
windowResize(bodyh);
}
function windowResize(bodyh){
var vh = $(window).height();
var headerh = $(".header").height();
var banner = $(".banner").height();
var banner2 = $(".banner2").height();
var footerh = $(".footer").height();
var otherh = vh - headerh - footerh - banner - banner2;
if (bodyh < otherh) {
$(".footer").addClass("positionFix");
$(".bodyRight").add(".bgImg").height(otherh);
}else{
$(".footer").removeClass("positionFix");
$(".bodyRight").add(".bgImg").height(bodyh);
}
}
});
|
C#
|
UTF-8
| 3,320
| 2.515625
| 3
|
[] |
no_license
|
using App.Data.Models.AppSettings;
using App.Data.Models.User;
using App.Data.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Options;
using System;
using System.Threading.Tasks;
namespace App.Web.Utilities
{
public interface IAccountTools
{
string GetDomainUserName();
Task<User> GetUser();
Task<User> GetUser(string domainName);
Task<User> ResetUser(string userKey);
}
public class AccountTools : IAccountTools
{
private string accountCachePrefix = "AccountCache";
private string domainPrefix = "AC\\";
private AppSettings appSettings;
private IHttpContextAccessor httpContextAccessor;
private IMemoryCache memoryCache;
private IUserService userService;
public AccountTools(
IOptions<AppSettings> settings,
IMemoryCache memoryCache,
IHttpContextAccessor httpContextAccessor,
IUserService userService
)
{
appSettings = settings.Value;
this.httpContextAccessor = httpContextAccessor;
this.memoryCache = memoryCache;
this.userService = userService;
}
public string GetDomainUserName()
{
return httpContextAccessor.HttpContext?.User?.Identity?.Name;
}
public async Task<User> GetUser()
{
return await GetUser(GetDomainUserName());
}
public async Task<User> GetUser(string userName)
{
if (string.IsNullOrEmpty(userName))
{
return null;
}
if (!userName.StartsWith(domainPrefix))
{
userName = $"{domainPrefix}{userName}";
}
string cacheKey = $"{accountCachePrefix}::{userName}";
if (!memoryCache.TryGetValue(cacheKey, out User user))
{
user = await userService.GetUser(null, userName);
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(appSettings.Cache.SlidingTimeout))
.SetAbsoluteExpiration(TimeSpan.FromSeconds(appSettings.Cache.AbsoluteTimeout));
memoryCache.Set(cacheKey, user, cacheEntryOptions);
}
return user;
}
public async Task<User> GetUser(int userID)
{
string cacheKey = $"{accountCachePrefix}::{userID}";
if (!memoryCache.TryGetValue(cacheKey, out User user))
{
user = await userService.GetUser(userID, null);
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromSeconds(appSettings.Cache.SlidingTimeout))
.SetAbsoluteExpiration(TimeSpan.FromSeconds(appSettings.Cache.AbsoluteTimeout));
memoryCache.Set(cacheKey, user, cacheEntryOptions);
}
return user;
}
public async Task<User> ResetUser(string userName)
{
string cacheKey = $"{accountCachePrefix}::{userName}";
memoryCache.Remove(cacheKey);
return await GetUser(userName);
}
}
}
|
Markdown
|
UTF-8
| 3,710
| 2.890625
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Tourist Identification
**Enhanced Algorithm for Tourist Identification from Public Transportation Passengers Considering Types of Access to A Tourist City**
**관광도시 출입 유형을 고려한 대중교통 이용 관광객 식별 알고리즘 개선**
- Authors:
- [MyungHun Han*](https://sites.google.com/view/hoonisone)
- [Yechan Kim*](https://sites.google.com/view/yechankim)
- [Seong Baeg Kim](https://education.jejunu.ac.kr/education/department/educom.htm)
## Novelty
- This repository includes enhanced algorithm for `Jeju tourist identification` from `encrpyted` public transportation dataset considering the `types of access to Jeju`. Kindly read the [paper](https://doi.org/10.5626/KTCP.2021.27.7.314) for details.
- 본 GitHub 레퍼지토리는`암호화`된 대중교통 이용 데이터에서 `제주 관광객`을 더욱 정확하게 `식별`하기 위해, `관광도시 (제주) 출입 유형`을 고려하여 종래에 제안한 [알고리즘](https://doi.org/10.5626/KTCP.2020.26.8.349)을 개선한 알고리즘의 소스코드를 제공합니다. 세부사항은 [논문](https://doi.org/10.5626/KTCP.2021.27.7.314)을 참고하시기 바랍니다.
## Prerequisites
- Python
- Pandas
- Tqdm
## How to use
### 1. Set each name of attributes in `lib/config.py` as follows:
<pre><code>
USER_ID = "userId" # check header of your CSV file!
</code></pre>
### 2. Set a date range on `lib/config.py` as follows:
<pre><code>
# If you want to extract tourists from Jan 1, 2020 to December 31, 2020
START_DATE = datetime.datetime(2020, 1, 1)
END_DATE = datetime.datetime(2020, 12, 31)
</code></pre>
### 3. Set the hyper-parameters on `lib/config.py` as follows:
<pre><code>
# Our paper contains the explanation of each hyperparameter. Try to check it!
EXTRACT_PARAS = [
{"case":"both", "stay_period":(2, 10), "use_ratio":70, "tour_station_count": 1},
{"case":"first", "stay_period":(2, 10), "use_ratio":70, "tour_station_count": 3},
{"case":"last", "stay_period":(2, 10), "use_ratio":80, "tour_station_count": 3},
{"case":"neither", "stay_period":(2, 10), "use_ratio":90, "tour_station_count": 4}
]
</code></pre>
### 4. Run `main/1.1 Extract user and station.ipynb` through jupyter notebook.
### 5. After 4, you can obtain the following results in 'data/analysis':
* station.csv
* user.csv
## Example of dataset
### This algorithm works only in the dataset as follows:
|attribute|value|
|------|------|
|user_id|f6f372cf8c6732eafc2a82b4f9d7a08bb3b493213ea4efbd3f4bba1d058406a7|
|base_date|20190601|
|route_id|22610000|
|route_name|292-2(한림체육관~제주버스터미널(종점))|
|route_no|292-2|
|geton_datetime|20190601150225|
|geton_station_id|988|
|geton_stataion_name|납읍리사무소|
|geton_station_longitude|126.32944|
|geton_station_latitude|33.43944|
|getoff_datetime|20190601151638|
|getoff_station_id|26|
|getoff_stataion_name|하귀초등학교|
|getoff_station_longitude|126.40212|
|getoff_station_latitude|33.48017|
|user_type|일반|
|user_count|1|
|input_date|20190603|
- Visit [Jeju Big-data center](https://bc.jejudatahub.net/main) to get `tb_bus_user_usage` dataset for further experiments.
## Cite this paper:
>[In Korean]
한명훈, 김예찬, 김성백, "관광도시 출입 유형을 고려한 대중교통 이용 관광객 식별 알고리즘 개선," 정보과학회 컴퓨팅의 실제 논문지, Vol. 27, No. 7, pp. 314-324, 2021.
>[In English]
Myunghun Han, Yechan Kim and Seong-Baeg Kim, "Enhanced Algorithm for Tourist Identification from Public Transportation Passengers Considering Types of Access to A Tourist City," KIISE Transactions on Computing Practices, Vol. 27, No. 7, pp. 314-324, 2021.
|
Java
|
UTF-8
| 1,288
| 2.453125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package edu.berkeley.kaiju.service.request.message.request;
import edu.berkeley.kaiju.exception.KaijuException;
import edu.berkeley.kaiju.service.LockManager;
import edu.berkeley.kaiju.service.LockManager.LockDuration;
import edu.berkeley.kaiju.service.LockManager.LockType;
import edu.berkeley.kaiju.service.MemoryStorageEngine;
import edu.berkeley.kaiju.service.request.message.KaijuMessage;
import edu.berkeley.kaiju.service.request.message.response.KaijuResponse;
public class ReadLockRequest extends KaijuMessage implements IKaijuRequest {
public String key;
public LockDuration lockDuration;
private ReadLockRequest() {}
public ReadLockRequest(String key, LockDuration lockDuration) {
this.key = key;
this.lockDuration = lockDuration;
}
@Override
public KaijuResponse processRequest(MemoryStorageEngine storageEngine, LockManager lockManager) throws
KaijuException {
KaijuResponse ret = new KaijuResponse();
lockManager.lock(LockType.READ, key);
ret.dataItem = storageEngine.get(key);
if(lockDuration == LockDuration.SHORT) {
lockManager.unlock(key);
}
return ret;
}
}
|
PHP
|
UTF-8
| 933
| 3.40625
| 3
|
[] |
no_license
|
<!--
设置 cookie
setcookie() 函数用于设置 cookie。
注释:setcookie() 函数必须位于 <html> 标签之前。-->
<?php
// 创建名为 "user" 的 cookie,一小时后过期
setcookie("user","hezhao",time()+3600);
//注释:在发送 cookie 时,cookie 的值会自动进行 URL 编码,在取回时进行自动解码。(为防止 URL 编码,请使用 setrawcookie() 取而代之。)
//取回Cookie
echo $_COOKIE["user"] . "<br>";
// 查看所有Cookie
print_r($_COOKIE);
echo "<hr>";
//删除 Cookie,只需要让过期日期变更为过去的时间点
//setcookie("user","",time()-3600);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cookie示例</title>
</head>
<body>
<?php
if(isset($_COOKIE["user"])){
echo "欢迎 " . $_COOKIE["user"] . " 回来!<br>";
}else{
echo "普通访客!<br>";
}
?>
</body>
</html>
|
Python
|
UTF-8
| 745
| 2.703125
| 3
|
[] |
no_license
|
import boto3
import sys
from datetime import datetime
sqs = boto3.client('sqs')
queue_url = ''
while True:
try:
message = input("Enter message: ")
print("Sending: {}...".format(message))
response = sqs.send_message(
QueueUrl=queue_url,
DelaySeconds=10,
MessageAttributes={
'CreatedAt': {
'DataType': 'String',
'StringValue': str(datetime.now())
}
},
MessageBody=(message)
)
print(response)
except KeyboardInterrupt:
print('')
sys.exit(0)
except Exception as e:
print(e)
print("\nSomething went wrong...")
|
Java
|
UTF-8
| 196
| 2
| 2
|
[] |
no_license
|
package com.javalanguagezone.interviewtwitter.exception;
public class InterviewTwitterException extends Exception {
public InterviewTwitterException(String message) {
super(message);
}
}
|
C++
|
UTF-8
| 1,178
| 3.28125
| 3
|
[] |
no_license
|
#include <iostream>
#include <vector>
#include <algorithm>
#include "utils.h"
using namespace std;
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
vector<vector<int>> res;
std::sort(nums.begin(), nums.end());
while (true) {
// printVector(nums);
res.push_back(nums);
if (nums.size() < 2)
break;
int i, j;
for (i = nums.size() - 2; i >= 0; --i) {
if (nums[i] < nums[i+1])
break;
}
if (i < 0)
break;
for (j = nums.size() - 1; j > i; --j) {
if (nums[j] > nums[i])
break;
}
swapT(nums[i], nums[j]);
std::sort(nums.begin()+i+1, nums.end());
}
return res;
}
};
int main() {
vector<int> nums = {1, 2, 3, 4};
Solution s;
s.permuteUnique(nums);
int ip;
nums.clear();
while (cin >> ip) {
nums.push_back(ip);
}
vector<vector<int>> res = s.permuteUnique(nums);
for (auto v: res)
printVector(v);
return 0;
}
|
Java
|
UTF-8
| 5,109
| 2.46875
| 2
|
[] |
no_license
|
package org.daawat.fmb.impl.daos;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.daawat.fmb.api.db.UserThaaliDataDAO;
import org.daawat.fmb.api.enums.Category;
import org.daawat.fmb.api.enums.UserThaaliStatus;
import org.daawat.fmb.api.objects.UserThaaliData;
import org.daawat.fmb.utils.PropertyFileManager;
public class UserThaaliDataDAOImpl extends BaseJDBCDAO<UserThaaliData> implements UserThaaliDataDAO{
//Adds a row to the UserThaaliData table.
public int addUserThaaliData(UserThaaliData userThaaliData) throws Exception{
String sqlQuery = PropertyFileManager.getProperty("userthaalidata_insert_query");
executeQuery(sqlQuery, userThaaliData.toList_Insert().toArray());
return updateCount;
}
//update the user thaali data.
public int updateUserThaaliData(UserThaaliData userThaaliData) throws Exception{
String sqlQuery = PropertyFileManager.getProperty("userthaalidata_update_query");
executeQuery(sqlQuery, userThaaliData.toList_Update().toArray());
return updateCount;
}
/**
* This method would return the List of UserThaaliData by querying the UserThaaliData_TBL. This method can take multiple arguments and return different result sets based on the input params.
* thaaliEndDate and status are optional params(if you pass null).
*
* @param thaaliStartDate - required parameter
* @param oThaaliEndDate - optional parameter, if specified will be used in the query selection.
* @param oStatus - optional parameter, if specified will be used in the query selection.
* @return List<UserThaaliData>
* @throws Exception
*/
public List<UserThaaliData> getThaaliDataAllUsers(Date thaaliFromDate, Date oThaaliToDate, UserThaaliStatus oThaaliStatus) throws Exception{
String sqlQuery = null;
if(oThaaliStatus != null){
if(oThaaliToDate != null){
sqlQuery = PropertyFileManager.getProperty("userthaalidata_select_query_daterange_status_all");
executeQuery(sqlQuery, thaaliFromDate, oThaaliToDate, oThaaliStatus.getValue());
}else{
sqlQuery = PropertyFileManager.getProperty("userthaalidata_select_query_date_status_all");
executeQuery(sqlQuery,thaaliFromDate,oThaaliStatus.getValue());
}
}else{
if(oThaaliToDate != null){
sqlQuery = PropertyFileManager.getProperty("userthaalidata_select_query_daterange_all");
executeQuery(sqlQuery,thaaliFromDate,oThaaliToDate);
}else{
sqlQuery = PropertyFileManager.getProperty("userthaalidata_select_query_date_all");
executeQuery(sqlQuery,thaaliFromDate);
}
}
return data;
}
/**
*
* This method would return the List of UserThaaliData by querying the UserThaaliData_TBL. This method can take multiple arguments and return different result sets based on the input params.
* only status is optional (if you pass null).
* @param thaaliFromDate
* @param oThaaliToDate
* @param oThaaliStatus
* @param familyGroupId
* @return
* @throws Exception
*/
public List<UserThaaliData> getThaaliDataPerUser(int familyGroupId, Date thaaliFromDate, Date oThaaliToDate, UserThaaliStatus oThaaliStatus) throws Exception{
String sqlQuery = null;
if(oThaaliStatus != null){
if(oThaaliToDate !=null){
sqlQuery = PropertyFileManager.getProperty("userthaalidata_select_query_daterange_status_user");
executeQuery(sqlQuery,familyGroupId, thaaliFromDate, oThaaliToDate, oThaaliStatus.getValue());
}else{
sqlQuery = PropertyFileManager.getProperty("userthaalidata_select_query_user_status");
executeQuery(sqlQuery,familyGroupId, thaaliFromDate, oThaaliStatus.getValue());
}
}else{
if(oThaaliToDate !=null){
sqlQuery = PropertyFileManager.getProperty("userthaalidata_select_query_daterange_user");
executeQuery(sqlQuery,familyGroupId, thaaliFromDate,oThaaliToDate);
}else{
sqlQuery = PropertyFileManager.getProperty("userthaalidata_select_query_user");
executeQuery(sqlQuery,familyGroupId, thaaliFromDate);
}
}
return data;
}
@Override
public List<UserThaaliData> unpack(ResultSet rs) throws Exception{
List<UserThaaliData> userThaaliList = new ArrayList<UserThaaliData>();
while(rs.next()){
UserThaaliData userThaali = new UserThaaliData();
//THAALI_DATE, FIRST_NAME, FAMILY_NAME, THAALI_CATEGORY, THAALI_STATUS, FAMILY_GROUP_ID, INSTRUCTIONS, USER_LOCATION
userThaali.setThaaliDate(rs.getDate("THAALI_DATE"));
userThaali.setFirstName(rs.getString("FIRST_NAME"));
userThaali.setFamilyName(rs.getString("FAMILY_NAME"));
userThaali.setThaaliCategory(Category.getEnum(rs.getString("THAALI_CATEGORY")));
userThaali.setRice(rs.getString("RICE"));
userThaali.setUserThaaliStatus(UserThaaliStatus.getEnum(rs.getString("USER_THAALI_STATUS")));
userThaali.setFamilyGroupId(rs.getInt("FAMILY_GROUP_ID"));
userThaali.setUserInstructions(rs.getString("INSTRUCTIONS"));
userThaali.setLocation(rs.getString("USER_LOCATION"));
userThaali.setNumOfPplAttending(rs.getInt("NUM_OF_PPL"));
userThaaliList.add(userThaali);
}
return userThaaliList;
}
}
|
Java
|
UTF-8
| 2,382
| 3.765625
| 4
|
[] |
no_license
|
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package wordGuessingGame;
import java.util.Random;
import java.util.Scanner;
public class App {
public static void main(String args[]) {
System.out.printf("Enter player1 name:");
Scanner player1input = new Scanner(System.in);
String player1Name = player1input.next();
System.out.printf("Enter player2 name:");
Scanner player2input = new Scanner(System.in);
String player2Name = player2input.next();
Random random = new Random();
Boolean player1Turn = random.nextBoolean();
WordChooser chooser1 = new WordChooser();
Masker masker1 = new Masker();
System.out.printf("%s :", player1Name);
WordGuessingGame game1 = new WordGuessingGame(chooser1, masker1);
System.out.println(game1.guessWord);
System.out.printf("%s :", player2Name);
WordGuessingGame game2 = new WordGuessingGame(chooser1, masker1);
System.out.println(game2.guessWord);
while (!game1.isGameWon() && !game2.isGameWon()){
if (player1Turn == true && !game1.isGameLost() && !game1.isGameWon()) {
System.out.printf("%s - %s \n",player1Name, game1.guessWord);
System.out.printf("%s - Enter your guess:", player1Name);
Scanner userInput = new Scanner(System.in);
Character guessAttempt = userInput.next().toUpperCase().charAt(0);
game1.guessLetter(guessAttempt);
game1.isGameWon();
game1.isGameLost();
player1Turn = false;
}
else if (!game2.isGameLost() && !game1.isGameWon()) {
System.out.printf("%s - %s\n",player2Name, game2.guessWord);
System.out.printf(" %s - Enter your guess:",player2Name);
Scanner userInput2 = new Scanner(System.in);
Character guessAttempt2 = userInput2.next().toUpperCase().charAt(0);
game2.guessLetter(guessAttempt2);
game2.isGameWon();
game2.isGameLost();
player1Turn = true;
}
}
if (game1.isGameWon()){
System.out.printf("%s Wins",player1Name);
}
else{
System.out.printf("%s Wins",player2Name);
}
}
}
|
Java
|
UTF-8
| 1,778
| 3.21875
| 3
|
[] |
no_license
|
package hw4_part2.test;
import junit.framework.TestCase;
import hw4_part2.main.InsurancePackage;
import hw4_part2.main.Package;
import hw4_part2.main.Driver;
import org.junit.Assert;
import org.junit.Test;
public class DriverTest extends TestCase {
/**********************************************
* Base Shipping Rates:\n"
* Weights (lbs) Air Truck Mail\n"
* 1 to 8 2.00 1.50 0.50\n"
* 9 to 16 3.00 2.35 1.50\n"
* 17 and over 4.50 3.25 2.15\n"
**********************************************\n"
* Shipping Cost Insurance Comparison:\n"
* Before Insurance ($) Additional Cost ($)\n"
* 0 to 1.00 2.45\n"
* 1.01 to 3.00 3.95\n"
* 3.01 and over 5.55\n"
**********************************************/
@Test
public void testCalculateCost() {
// Packages without insurance.
Package aPackage = new Package(23D, 'A');
assertEquals(2.0D, aPackage.getShipCost());
Package bPackage = new Package(12D, 'T');
assertEquals(1.5D, bPackage.getShipCost());
Package cPackage = new Package(600D, 'M');
assertEquals(2.15D, cPackage.getShipCost());
Package dPackage = new Package(280D, 'A');
assertEquals(4.50D, dPackage.getShipCost());
// Insurance based packages.
InsurancePackage ePackage = new InsurancePackage(23D, 'A');
assertEquals(5.95D, ePackage.getShipCost());
InsurancePackage fPackage = new InsurancePackage(12D, 'T');
assertEquals(5.45D, fPackage.getShipCost());
InsurancePackage gPackage = new InsurancePackage(600D, 'M');
assertEquals(6.10D, gPackage.getShipCost());
InsurancePackage hPackage = new InsurancePackage(256D, 'A');
assertEquals(10.05D, hPackage.getShipCost());
}
}
|
Markdown
|
UTF-8
| 7,347
| 3.390625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
python-mock
===========
git mirror of http://code.google.com/p/mock/ with tweaks
___
#### Differences from original repository
- added **Mock.assert_never_called** - asserts the mock has never been called. The same would be achieved using Mock.assert_has_calls([]), but new method offers better semantics for this case.
___
**mock** is a library for testing in Python. It allows you to replace parts of
your system under test with mock objects and make assertions about how they
have been used.
mock is now part of the Python standard library, available as `unittest.mock
<http://docs.python.org/py3k/library/unittest.mock.html#module-unittest.mock>`_
in Python 3.3 onwards.
mock provides a core `MagicMock` class removing the need to create a host of
stubs throughout your test suite. After performing an action, you can make
assertions about which methods / attributes were used and arguments they were
called with. You can also specify return values and set needed attributes in
the normal way.
mock is tested on Python versions 2.5-2.7 and Python 3. mock is also tested
with the latest versions of Jython and pypy.
The mock module also provides utility functions / objects to assist with
testing, particularly monkey patching.
* `PDF documentation for 1.0.1
<http://www.voidspace.org.uk/downloads/mock-1.0.1.pdf>`_
* `mock on google code (repository and issue tracker)
<http://code.google.com/p/mock/>`_
* `mock documentation
<http://www.voidspace.org.uk/python/mock/>`_
* `mock on PyPI <http://pypi.python.org/pypi/mock/>`_
* `Mailing list (testing-in-python@lists.idyll.org)
<http://lists.idyll.org/listinfo/testing-in-python>`_
Mock is very easy to use and is designed for use with
`unittest <http://pypi.python.org/pypi/unittest2>`_. Mock is based on
the 'action -> assertion' pattern instead of 'record -> replay' used by many
mocking frameworks. See the `mock documentation`_ for full details.
Mock objects create all attributes and methods as you access them and store
details of how they have been used. You can configure them, to specify return
values or limit what attributes are available, and then make assertions about
how they have been used::
>>> from mock import Mock
>>> real = ProductionClass()
>>> real.method = Mock(return_value=3)
>>> real.method(3, 4, 5, key='value')
3
>>> real.method.assert_called_with(3, 4, 5, key='value')
`side_effect` allows you to perform side effects, return different values or
raise an exception when a mock is called::
>>> mock = Mock(side_effect=KeyError('foo'))
>>> mock()
Traceback (most recent call last):
...
KeyError: 'foo'
>>> values = {'a': 1, 'b': 2, 'c': 3}
>>> def side_effect(arg):
... return values[arg]
...
>>> mock.side_effect = side_effect
>>> mock('a'), mock('b'), mock('c')
(1, 2, 3)
>>> mock.side_effect = [5, 4, 3, 2, 1]
>>> mock(), mock(), mock()
(5, 4, 3)
Mock has many other ways you can configure it and control its behaviour. For
example the `spec` argument configures the mock to take its specification from
another object. Attempting to access attributes or methods on the mock that
don't exist on the spec will fail with an `AttributeError`.
The `patch` decorator / context manager makes it easy to mock classes or
objects in a module under test. The object you specify will be replaced with a
mock (or other object) during the test and restored when the test ends::
>>> from mock import patch
>>> @patch('test_module.ClassName1')
... @patch('test_module.ClassName2')
... def test(MockClass2, MockClass1):
... test_module.ClassName1()
... test_module.ClassName2()
... assert MockClass1.called
... assert MockClass2.called
...
>>> test()
.. note::
When you nest patch decorators the mocks are passed in to the decorated
function in the same order they applied (the normal *python* order that
decorators are applied). This means from the bottom up, so in the example
above the mock for `test_module.ClassName2` is passed in first.
With `patch` it matters that you patch objects in the namespace where they
are looked up. This is normally straightforward, but for a quick guide
read `where to patch
<http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch>`_.
As well as a decorator `patch` can be used as a context manager in a with
statement::
>>> with patch.object(ProductionClass, 'method') as mock_method:
... mock_method.return_value = None
... real = ProductionClass()
... real.method(1, 2, 3)
...
>>> mock_method.assert_called_once_with(1, 2, 3)
There is also `patch.dict` for setting values in a dictionary just during the
scope of a test and restoring the dictionary to its original state when the
test ends::
>>> foo = {'key': 'value'}
>>> original = foo.copy()
>>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
... assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == original
Mock supports the mocking of Python magic methods. The easiest way of
using magic methods is with the `MagicMock` class. It allows you to do
things like::
>>> from mock import MagicMock
>>> mock = MagicMock()
>>> mock.__str__.return_value = 'foobarbaz'
>>> str(mock)
'foobarbaz'
>>> mock.__str__.assert_called_once_with()
Mock allows you to assign functions (or other Mock instances) to magic methods
and they will be called appropriately. The MagicMock class is just a Mock
variant that has all of the magic methods pre-created for you (well - all the
useful ones anyway).
The following is an example of using magic methods with the ordinary Mock
class::
>>> from mock import Mock
>>> mock = Mock()
>>> mock.__str__ = Mock(return_value = 'wheeeeee')
>>> str(mock)
'wheeeeee'
For ensuring that the mock objects your tests use have the same api as the
objects they are replacing, you can use "auto-speccing". Auto-speccing can
be done through the `autospec` argument to patch, or the `create_autospec`
function. Auto-speccing creates mock objects that have the same attributes
and methods as the objects they are replacing, and any functions and methods
(including constructors) have the same call signature as the real object.
This ensures that your mocks will fail in the same way as your production
code if they are used incorrectly::
>>> from mock import create_autospec
>>> def function(a, b, c):
... pass
...
>>> mock_function = create_autospec(function, return_value='fishy')
>>> mock_function(1, 2, 3)
'fishy'
>>> mock_function.assert_called_once_with(1, 2, 3)
>>> mock_function('wrong arguments')
Traceback (most recent call last):
...
TypeError: <lambda>() takes exactly 3 arguments (1 given)
`create_autospec` can also be used on classes, where it copies the signature of
the `__init__` method, and on callable objects where it copies the signature of
the `__call__` method.
The distribution contains tests and documentation. The tests require
`unittest2 <http://pypi.python.org/pypi/unittest2>`_ to run on Python 2.5, 2.6
or 3.1. For Python 2.7 and 3.2 they can be run with
`python -m unittest discover`.
Docs from the in-development version of `mock` can be found at
`mock.readthedocs.org <http://mock.readthedocs.org>`_.
|
C
|
UTF-8
| 490
| 2.671875
| 3
|
[] |
no_license
|
/*
* 视窗
*/
#include "my_curses.h"
#include <unistd.h>
int
main( int argc, char *argv[] )
{
WINDOW *win;
init_curses();
box(stdscr, ACS_VLINE, ACS_HLINE );
mvaddstr( LINES / 2 - 5, COLS / 2 - 5, "hello world" );
refresh();
sleep(1);
win = newwin(4, 30, LINES / 2 - 3, COLS / 2 - 15 );
box(win, ACS_VLINE, ACS_HLINE );
mvwaddstr( win, 1, 2, "hello world!!!" );
touchwin(win);
wrefresh(win);
getch();
wclear(win);
touchwin(stdscr);
sleep(5);
endwin();
return 0;
}
|
C
|
UTF-8
| 1,187
| 2.796875
| 3
|
[] |
no_license
|
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<set>
using namespace std;
#define maxn 5000
int f[maxn];
set<int> st;
struct road
{
int u,v;
int cost;
int flag;
bool operator < (const road &a) const
{
if(flag==a.flag)
return cost<a.cost;
else
return flag>a.flag;
}
};
int find(int x)
{
if(f[x]==x)
return x;
else
return f[x]=find(f[x]);
}
int main()
{
int N;
scanf("%d",&N);
vector<road> Graph;
int num=N*(N-1)/2;
road r;
for(int i=0;i<=N;i++)
f[i]=i;
for(int i=0;i<num;i++)
{
scanf("%d%d%d%d",&r.u,&r.v,&r.cost,&r.flag);
Graph.push_back(r);
}
sort(Graph.begin(),Graph.end());
int ans=0;
for(int i=0;i<num;i++)
{
int start=find(Graph[i].u);
int end=find(Graph[i].v);
st.insert(Graph[i].u);
st.insert(Graph[i].v);
if(Graph[i].flag==1)
f[start]=end;
else if(start!=end)
{
ans+=Graph[i].cost;
f[start]=end;
}
if(st.size()==N) break;
}
printf("%d\n",ans);
return 0;
}
|
Java
|
UTF-8
| 218
| 1.71875
| 2
|
[] |
no_license
|
import java.util.concurrent.Semaphore;
public class Produtor extends Comportamento {
public Produtor(MyRobotLego robot, Semaphore semaphore) {
super(robot,semaphore);
// TODO Auto-generated constructor stub
}
}
|
C++
|
UTF-8
| 1,579
| 2.59375
| 3
|
[] |
no_license
|
#include "Flight.h"
float DegreeToRadian(float degrees);
void Hack::Flight::Fly()
{
if (Hack::Data::bGravity && !Hack::Data::bFlyMode)
{
*(float*)Hack::Data::gravity = 600.f;
Hack::Data::bGravity = false;
}
if (*Hack::Data::localPlayer && Hack::Data::bFlyMode)
{
Hack::Data::bGravity = true;
vec3 d;
d.x = *(float*)Hack::Data::xPlayerPosition;
d.z = *(float*)Hack::Data::zPlayerPosition;
d.y = *(float*)Hack::Data::yPlayerPosition;
if (GetAsyncKeyState(0x57))
{
d.x += cos(DegreeToRadian(*(float*)Hack::Data::xCameraAxis)) * Hack::Data::flightSpeed;
d.z += sin(DegreeToRadian(*(float*)Hack::Data::xCameraAxis)) * Hack::Data::flightSpeed;
}
else if (GetAsyncKeyState(0x53))
{
d.x -= cos(DegreeToRadian(*(float*)Hack::Data::xCameraAxis)) * Hack::Data::flightSpeed;
d.z -= sin(DegreeToRadian(*(float*)Hack::Data::xCameraAxis)) * Hack::Data::flightSpeed;
}
//vertical flight
if (GetAsyncKeyState(VK_SPACE))
{
d.y += Hack::Data::flightSpeed;
}
if (GetAsyncKeyState(VK_SHIFT))
{
d.y -= Hack::Data::flightSpeed;
}
*(float*)Hack::Data::xPlayerPosition = d.x;
*(float*)Hack::Data::zPlayerPosition = d.z;
*(float*)Hack::Data::yPlayerPosition = d.y;
if (*Hack::Data::localPlayer)
{
//resets gravity and movement velocity when in fly mode to avoid gliding and jittering
*Hack::Data::xPlayerVelocity = 0;
*Hack::Data::zPlayerVelocity = 0;
*Hack::Data::yPlayerVelocity = 0;
*(float*)Hack::Data::gravity = 1.f;
}
}
}
float DegreeToRadian(float degrees)
{
return degrees * (3.1415927f / 180);
}
|
C++
|
UTF-8
| 2,471
| 2.5625
| 3
|
[] |
no_license
|
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <iomanip>
#include <cctype>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <cstdlib>
#include <sstream>
#include <set>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
typedef long long ll;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const int maxn = 110;
const double eps = 1e-5;
struct connecet {
int v;
int cost;
};
int max_level_gap, n;
int res;
int start;
int basic_level;
int max_buy_level;
int every_cost[maxn];
int every_level[maxn];
int cost[maxn];
bool vis[maxn];
vector<connecet> Adj[maxn];
void init() {
res = INF;
mem(every_cost, 0);
mem(every_level, 0);
mem(cost, INF);
mem(vis, 0);
return;
}
void Get_information() {
cin >> max_level_gap >> n;
for (int i = 1; i <= n; ++i) {
int p, l, x;
cin >> p >> l >> x;
every_cost[i] = p;
every_level[i] = l;
if (i == 1) {
basic_level = l;
}
while (x--) {
int t, v;
cin >> t >> v;
connecet add;
add.v = i;
add.cost = v;
Adj[t].push_back(add);
}
}
return;
}
void Dijkstra() {
max_buy_level = every_level[start];
for (int i = 1; i <= n; ++i) {
cost[i] = every_cost[i];
}
for (int i = 1; i <= n; ++i) {
if (max_buy_level > every_level[i] || abs(every_level[i] - max_buy_level) > max_level_gap) {
vis[i] = 1;
}
else {
vis[i] = 0;
}
}
for (int i = 1; i <= n; ++i) {
int u = -1, min = INF;
for (int j = 1; j <= n; ++j) {
if (!vis[j] && cost[j] < min) {
u = j;
min = cost[j];
}
}
vis[u] = 1;
for (int j = 0; j < Adj[u].size(); ++j) {
int v = Adj[u][j].v;
if (!vis[v] && cost[u] + Adj[u][j].cost < cost[v]) {
cost[v] = cost[u] + Adj[u][j].cost;
}
}
}
return;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
init();
Get_information();
for (int i = 1; i <= n; ++i) {
start = i;
Dijkstra();
if (cost[1] < res) {
res = cost[1];
}
}
cout << res;
return 0;
}
|
Java
|
UTF-8
| 1,413
| 2.21875
| 2
|
[] |
no_license
|
package handler.items;
import l2p.gameserver.handler.items.ItemHandler;
import l2p.gameserver.model.Playable;
import l2p.gameserver.model.Player;
import l2p.gameserver.model.items.ItemInstance;
import l2p.gameserver.tables.PetDataTable;
import l2p.gameserver.tables.SkillTable;
import handler.items.ScriptItemHandler;
import l2p.gameserver.scripts.ScriptFile;
public class PetSummon extends ScriptItemHandler implements ScriptFile {
// all the items ids that this handler knowns
private static final int[] _itemIds = PetDataTable.getPetControlItems();
private static final int _skillId = 2046;
@Override
public boolean useItem(Playable playable, ItemInstance item, boolean ctrl) {
if (playable == null || !playable.isPlayer()) {
return false;
}
Player player = (Player) playable;
player.setPetControlItem(item);
player.getAI().Cast(SkillTable.getInstance().getInfo(_skillId, 1), player, false, true);
return true;
}
@Override
public boolean pickupItem(Playable playable, ItemInstance item) {
return true;
}
@Override
public void onLoad() {
ItemHandler.getInstance().registerItemHandler(this);
}
@Override
public void onReload() {
}
@Override
public void onShutdown() {
}
@Override
public final int[] getItemIds() {
return _itemIds;
}
}
|
Java
|
UTF-8
| 1,481
| 2.3125
| 2
|
[] |
no_license
|
package com.robintegg.news.breakingnews;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import com.robintegg.news.journalist.NewsStoryPublishedEvent;
import com.robintegg.news.journalist.NewsStoryRetractedEvent;
import com.robintegg.news.journalist.NewsStoryUpdatedEvent;
@Service
public class PocBreakingNewsService implements BreakingNewsService {
private Queue<BreakingNews> breakingNews = new CircularFifoQueue<>(2);
@Override
public List<BreakingNews> getLatestBreakingNews() {
return new ArrayList<>(breakingNews);
}
@EventListener(classes = NewsStoryPublishedEvent.class)
public void onNewsStoryPublishedEvent(NewsStoryPublishedEvent event) {
breakingNews.add(new BreakingNews(event.getNewsStory()));
}
@EventListener(classes = NewsStoryUpdatedEvent.class)
public void onNewsStoryUpdatedEvent(NewsStoryUpdatedEvent event) {
breakingNews.removeIf(bn -> bn.getNewsStoryId().equals(event.getNewsStory().getNewsStoryId()));
breakingNews.add(new BreakingNews(event.getNewsStory()));
}
@EventListener(classes = NewsStoryRetractedEvent.class)
public void onNewsStoryRetractedEvent(NewsStoryRetractedEvent event) {
breakingNews.removeIf(bn -> bn.getNewsStoryId().equals(event.getNewsStoryId()));
}
protected void clear() {
breakingNews.clear();
}
}
|
C++
|
UTF-8
| 1,236
| 2.9375
| 3
|
[] |
no_license
|
#ifndef UserDatabase_H_
#define UserDatabase_H_
/**
* Used to read and write information from UserDatabase.
*
* Manipulates the parameters in User_database.txt file which
* comprises of a vector array
*
* @author Adam Fawcett <fawcett-a@ulster.ac.uk>
* @license https://www.gnu.org/licenses/gpl-3.0.en.html
* @copyright Adam Fawcett 2018
*
*/
#include <string>
#include <vector>
#include <fstream>
#include <algorithm>
#include "User.h"
class UserDatabase
{
public:
// declaring function to access the user database file path
UserDatabase(std::string filePath);
// declaring function to rewrite userdatabase vector array
void rewriteUserDatabase();
// declaring function to get vector for user pincode and the user details
std::vector<User> getPinCode;
std::vector<User> users;
// declaring function to get all user data and store in vector array
std::vector<User> getAllUsers();
// declaring function to
//void addUser(User* user);
void addUser(User user);
//Overriding with dynamic object
void addUser(User* user);
// declaring vector function for allusers
std::vector<User>* allUsers = new std::vector<User>();
private:
//declaring the filepath as a function only accessable in the class
std::string filePath;
};
#endif
|
C++
|
UTF-8
| 15,476
| 2.75
| 3
|
[
"MIT"
] |
permissive
|
#ifndef LF_LOCCOMPNORMS_H
#define LF_LOCCOMPNORMS_H
/***************************************************************************
* LehrFEM++ - A simple C++ finite element libray for teaching
* Developed from 2018 at the Seminar of Applied Mathematics of ETH Zurich,
* lead developers Dr. R. Casagrande and Prof. R. Hiptmair
***************************************************************************/
/**
* @file
* @brief Classes for the local computation of norms of (differences of)
* (FE) functions
* @author Ralf Hiptmair
* @date November 2018
* @copyright MIT License
*/
#include <cmath>
#include <iostream>
#include <type_traits>
#include <lf/quad/quad.h>
#include "loc_comp_ellbvp.h"
namespace lf::uscalfe {
/**
* @brief Class for the local computation of the L2 norm of the difference of
* a Lagrangian finite element function and a generic function
*
* @tparam FUNCTOR describes the function from which the finite element function
* is subtracted, should model the concept \ref mesh_function .
*
* This class complies with the type requirements for the template argument
* LOCAL_NORM_COMP of the function lf::uscalfe::L2NormDifference.
* Its main method is the evaluation operator `operator ()`.
*
* ### Use case
*
* ~~~
* MeshFunctionL2NormDifference loc_comp(
* fe_space,[](auto x) { return (x[0] * (1.0 - x[1])); }, quad_order);
* ~~~
*/
template <typename FUNCTOR>
class MeshFunctionL2NormDifference {
static_assert(mesh::utils::isMeshFunction<FUNCTOR>);
public:
/** @brief standard constructors */
/** @{ */
MeshFunctionL2NormDifference(const MeshFunctionL2NormDifference &) = delete;
MeshFunctionL2NormDifference(MeshFunctionL2NormDifference &&) noexcept =
default;
MeshFunctionL2NormDifference &operator=(
const MeshFunctionL2NormDifference &) = delete;
MeshFunctionL2NormDifference &operator=(MeshFunctionL2NormDifference &&) =
delete;
/** @} */
/** @brief Constructor
*
* @param fe_space Describes the Shapefunctions over which to integrate.
* @param u object providing scalar-valued function
* @param loc_quad_degree desired degree of exctness of local quadrature,
* default value = 0. If = 0, the quadrature degree is determined from the
* polynomial degree of the reference shape functions.
*
* @note The finite element space need not provide reference shape functions
* for all cell types if these cell types do not occur.
*/
MeshFunctionL2NormDifference(
const std::shared_ptr<const UniformScalarFESpace<double>> &fe_space,
FUNCTOR u, quad::quadDegree_t loc_quad_order)
: u_(std::move(u)) {
LF_ASSERT_MSG(fe_space != nullptr, "Invalid FE space passed");
for (auto ref_el : {base::RefEl::kTria(), base::RefEl::kQuad()}) {
auto fe = fe_space->ShapeFunctionLayout(ref_el);
if (fe != nullptr) {
fe_precomp_[ref_el.Id()] =
PrecomputedScalarReferenceFiniteElement<double>(
std ::move(fe), quad ::make_QuadRule(ref_el, loc_quad_order));
}
}
}
/**
* @brief main function for the computation of **squared** local L2 norms
*
* @tparam DOFVECTOR vector type for passing local coefficient vector
*
* @param cell reference to the (triangular or quadrilateral) cell for
* which the element matrix should be computed.
* @param dofs vector of degrees of freedom for the current entity
* @return the local "error norm" squared
*
* Actual computation of the element matrix based on numerical quadrature and
* mapping techniques. The order of the quadrature rule is tied to the
* polynomial degree of the underlying Lagrangian finite element spaces: for
* polynomial degree p a quadrature rule is chosen that is exact for
* polynomials o degree 2p.
*
* ### Template parameter type requirements
*
* - DOFVECTOR must be compatible with std::vector<SCALAR>
*/
template <typename DOFVECTOR>
double operator()(const lf::mesh::Entity &cell, const DOFVECTOR &dofs);
/** Virtual destructor */
virtual ~MeshFunctionL2NormDifference() = default;
private:
/** @brief a handle to the generic function with which to compare the finite
* element function */
FUNCTOR u_;
/** @brief cell-type dependent but cell-independent information */
std::array<PrecomputedScalarReferenceFiniteElement<double>, 5> fe_precomp_;
public:
/** @brief output control variable */
static unsigned int ctrl_;
static const unsigned int kout_cell = 8;
static const unsigned int kout_comp = 16;
};
// Initialization of control variable
template <typename FUNCTOR>
unsigned int MeshFunctionL2NormDifference<FUNCTOR>::ctrl_ = 0;
template <typename FUNCTOR>
template <typename DOFVECTOR>
double MeshFunctionL2NormDifference<FUNCTOR>::operator()(
const lf::mesh::Entity &cell, const DOFVECTOR &dofs) {
using dof_t = typename DOFVECTOR::value_type;
// Topological type of the cell
const lf::base::RefEl ref_el{cell.RefEl()};
auto &fe = fe_precomp_[ref_el.Id()];
LF_ASSERT_MSG(fe.isInitialized(),
"No Shape functions available for " << ref_el);
// Query the shape of the cell
const lf::geometry::Geometry *geo_ptr = cell.Geometry();
LF_ASSERT_MSG(geo_ptr != nullptr, "Invalid geometry!");
LF_ASSERT_MSG((geo_ptr->DimGlobal() == 2) && (geo_ptr->DimLocal() == 2),
"Only 2D implementation available!");
LF_ASSERT_MSG(dofs.size() >= fe.NumRefShapeFunctions(),
"Dof vector too short");
// Obtain cell--type depend invariant data
const Eigen::MatrixXd &qr_Points{fe.Qr().Points()};
const Eigen::VectorXd &qr_Weights{fe.Qr().Weights()};
const size_type qr_NumPts = fe.Qr().NumPoints();
const size_type num_LSF = fe.NumRefShapeFunctions();
const auto &rsf_QuadPts{fe.PrecompReferenceShapeFunctions()};
SWITCHEDSTATEMENT(ctrl_, kout_cell,
std::cout << ref_el << ", (Nlsf = " << num_LSF
<< ", Nqr = " << qr_NumPts << ") shape = \n"
<< geo_ptr->Global(ref_el.NodeCoords())
<< std::endl);
// World coordinates of quadrature points
const Eigen::MatrixXd mapped_qpts(geo_ptr->Global(qr_Points));
// Obtain the metric factors for the quadrature points
const Eigen::VectorXd determinants(geo_ptr->IntegrationElement(qr_Points));
SWITCHEDSTATEMENT(
ctrl_, kout_comp, std::cout << "\t dofs = "; for (auto x
: dofs) {
std::cout << x << " ";
} std::cout << "\t dets "
<< determinants.transpose() << std::endl);
double sum = 0.0; // summation variable
auto uvals = u_(cell, qr_Points);
// Loop over quadrature points
for (int k = 0; k < qr_NumPts; ++k) {
// Value of finite element function at quadrature point
// Loop over local shape functions/dofs to compute the value of
// the finite element function in the quadrature point
dof_t uh_val = 0.0;
for (int j = 0; j < num_LSF; ++j) {
uh_val += rsf_QuadPts(j, k) * dofs[j];
}
// form the difference
uh_val -= uvals[k];
// sum the quared modulus weighted with quadrature weight and metric factor
sum += qr_Weights[k] * determinants[k] * std::fabs(uh_val * uh_val);
SWITCHEDSTATEMENT(ctrl_, kout_comp,
std::cout << "\t @ " << (mapped_qpts.col(k)).transpose()
<< ": uh = " << uh_val << ", u = " << uvals[k]
<< std::endl);
}
SWITCHEDSTATEMENT(ctrl_, kout_comp,
std::cout << "\t loc norm^2 = " << sum << std::endl);
return sum;
}
// **********************************************************************
/**
* @ingroup mesh_function
* @brief Class for the local computation of the L2 norm of the difference of
* the _gradient_ of a Lagrangian finite element function and a
* generic vector field
*
* @tparam VEC_FUNC type for a generic vector field
*
* ### Template parameter type requirements
*
* - VEC_FUNC must behave like `std::function<VECTOR(Eigen::DenseBase)>`
* where VECTOR is a vector type like a vector of Eigen or std::vector.
*
* This class complies with the type requirements for the template argument
* LOCAL_NORM_COMP of the function lf::uscalfe::L2NormDifference. Its main
method
* is the evaluation operator returning the **squared** local norm.
*
*
* ### Use case
*
* ~~~
* MeshFunctionL2GradientDifference lc_H1(fe_space,
* [](auto x) { return Eigen::Vector2d(-x[1],x[0]); },2)
* ~~~
*/
template <typename VEC_FUNC>
class MeshFunctionL2GradientDifference {
static_assert(mesh::utils::isMeshFunction<VEC_FUNC>);
public:
/** @name standard constructors
* @{ */
MeshFunctionL2GradientDifference(const MeshFunctionL2GradientDifference &) =
delete;
MeshFunctionL2GradientDifference(
MeshFunctionL2GradientDifference &&) noexcept = default;
MeshFunctionL2GradientDifference &operator=(
const MeshFunctionL2GradientDifference &) = delete;
MeshFunctionL2GradientDifference &operator=(
MeshFunctionL2GradientDifference &&) = delete;
/** @} */
/** @brief Constructor
*
* @param fe_space Describes the shape functions that should be used.
* @param vecfield object providing a generic vector field
* @param loc_quad_order desired degree of exactness of the local quadrature
* rule
*
* If loc_quad_order == 0, the required degree of exactness is deduced from
* the polynomial degree of the finite element space.
*/
MeshFunctionL2GradientDifference(
const std::shared_ptr<const UniformScalarFESpace<double>> &fe_space,
VEC_FUNC vecfield, lf::quad::quadDegree_t loc_quad_order)
: vecfield_(std::move(vecfield)) {
LF_ASSERT_MSG(fe_space != nullptr, "Invalid FE space passed!");
for (auto ref_el : {base::RefEl::kTria(), base::RefEl::kQuad()}) {
auto sfl{fe_space->ShapeFunctionLayout(ref_el)};
if (sfl != nullptr) {
fe_precomp_[ref_el.Id()] = PrecomputedScalarReferenceFiniteElement(
sfl, quad::make_QuadRule(ref_el, loc_quad_order));
}
}
}
/**
* @brief main function for the computation of **squared** local L2 norms
* of gradients
*
* @tparam DOFVECTOR vector type for passing local coefficient vector
*
* @param cell reference to the (triangular or quadrilateral) cell for
* which the element matrix should be computed.
* @param dofs vector of degrees of freedom for the current entity
* @return the local "error norm" squared
*
* Actual computation of the element matrix based on numerical quadrature
* and mapping techniques. The order of the quadrature rule is tied to the
* polynomial degree of the underlying Lagrangian finite element spaces:
* for polynomial degree p a quadrature rule is chosen that is exact for
* polynomials of degree 2p ("moderate overkill quadrature")
*
* ### Template parameter type requirements
*
* - DOFVECTOR must be compatible with std::vector of a SCALAR type
*/
template <typename DOFVECTOR>
double operator()(const lf::mesh::Entity &cell, const DOFVECTOR &dofs);
virtual ~MeshFunctionL2GradientDifference() = default;
private:
/** @brief a handle to the generic function with which to compare the
finite
* element function */
VEC_FUNC vecfield_;
std::array<PrecomputedScalarReferenceFiniteElement<double>, 5> fe_precomp_;
public:
/** @brief output control variable */
static unsigned int ctrl_;
static const unsigned int kout_cell = 8;
static const unsigned int kout_comp = 16;
};
// Initialization of control variable
template <typename VEC_FUNC>
unsigned int MeshFunctionL2GradientDifference<VEC_FUNC>::ctrl_ = 0;
template <typename VEC_FUNC>
template <typename DOFVECTOR>
double MeshFunctionL2GradientDifference<VEC_FUNC>::operator()(
const lf::mesh::Entity &cell, const DOFVECTOR &dofs) {
using dof_t = typename DOFVECTOR::value_type;
// Topological type of the cell
const lf::base::RefEl ref_el{cell.RefEl()};
auto &pfe = fe_precomp_[ref_el.Id()];
LF_ASSERT_MSG(pfe.isInitialized(), "No ShapeFunctions for " << ref_el);
// Query the shape of the cell
const lf::geometry::Geometry *geo_ptr = cell.Geometry();
LF_ASSERT_MSG(geo_ptr != nullptr, "Invalid geometry!");
LF_ASSERT_MSG((geo_ptr->DimLocal() == 2),
"Only 2D implementation available!");
LF_ASSERT_MSG(dofs.size() >= pfe.NumRefShapeFunctions(),
"Dof vector too short");
// Physical dimension of the cell
const dim_t world_dim = geo_ptr->DimGlobal();
// Obtain cell--type depend but cell-independent data
auto &qr_Points{pfe.Qr().Points()};
auto &qr_Weights{pfe.Qr().Weights()};
size_type qr_NumPts = pfe.Qr().NumPoints();
size_type num_LSF = pfe.NumRefShapeFunctions();
auto gradrsf_QuadPts = pfe.PrecompGradientsReferenceShapeFunctions();
SWITCHEDSTATEMENT(ctrl_, kout_cell,
std::cout << ref_el << ", (Nlsf = " << num_LSF
<< ", Nqr = " << qr_NumPts << ") shape = \n"
<< geo_ptr->Global(ref_el.NodeCoords())
<< std::endl);
// World coordinates of quadrature points
const Eigen::MatrixXd mapped_qpts(geo_ptr->Global(qr_Points));
// Obtain the metric factors for the quadrature points
const Eigen::VectorXd determinants(geo_ptr->IntegrationElement(qr_Points));
// Fetch the transformation matrices for gradients
const Eigen::MatrixXd JinvT(geo_ptr->JacobianInverseGramian(qr_Points));
SWITCHEDSTATEMENT(
ctrl_, kout_comp, std::cout << "\t dofs = "; for (auto x
: dofs) {
std::cout << x << " ";
} std::cout << "\t dets "
<< determinants.transpose() << std::endl);
double sum = 0.0; // summation variable
auto vfval = vecfield_(cell, qr_Points);
// Loop over quadrature points
for (unsigned k = 0; k < qr_NumPts; ++k) {
// Value of the gradient of the finite element function at quadrature point
// Transformed gradients
const auto trf_grad(
JinvT.block(0, 2 * k, world_dim, 2) *
gradrsf_QuadPts.block(0, 2 * k, gradrsf_QuadPts.rows(), 2).transpose());
// Loop over local shape functions/dofs to compute the value of
// the finite element function in the quadrature point
Eigen::Matrix<dof_t, Eigen::Dynamic, 1> grad_uh_val(world_dim, 1);
grad_uh_val.setZero();
for (unsigned j = 0; j < num_LSF; ++j) {
grad_uh_val += (dofs[j] * trf_grad.col(j));
}
// form the difference
for (int l = 0; l < world_dim; ++l) {
grad_uh_val[l] -= vfval[k][l];
}
// sum the quared modulus weighted with quadrature weight and metric factor
sum += qr_Weights[k] * determinants[k] * grad_uh_val.squaredNorm();
// clang-format on
SWITCHEDSTATEMENT(ctrl_, kout_comp,
std::cout << "\t @ " << (mapped_qpts.col(k)).transpose()
<< ": grad uh = [" << grad_uh_val.transpose()
<< "[, vf = [" << vfval[k][0] << ' '
<< vfval[k][1] << "]" << std::endl);
// clang-format on
}
SWITCHEDSTATEMENT(ctrl_, kout_comp,
std::cout << "\t loc norm^2 = " << sum << std::endl);
return sum;
}
} // namespace lf::uscalfe
#endif
|
Java
|
UTF-8
| 698
| 2.375
| 2
|
[] |
no_license
|
package com.dicoding.sarjanasantuy.belajardatabase;
public class MahasiswaModel {
private String Nama;
private String Alamat;
private char Jkel;
public String getNama() {
return Nama;
}
public void setNama(String nama) {
Nama = nama;
}
public String getAlamat() {
return Alamat;
}
public void setAlamat(String alamat) {
Alamat = alamat;
}
public char getJkel() {
return Jkel;
}
public void setJkel(char jkel) {
Jkel = jkel;
}
public MahasiswaModel(String Nama, String Alamat, char Jkel){
this.Nama = Nama;
this.Alamat = Alamat;
this.Jkel = Jkel;
}
}
|
Java
|
UTF-8
| 555
| 3.453125
| 3
|
[] |
no_license
|
import java.util.*;
public class Feynman {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int line = Integer.valueOf(scan.nextLine());
ArrayList<Integer> list = new ArrayList<Integer>();
while(line != 0){
//System.out.println(line);
list.add(Integer.valueOf(line));
line = Integer.valueOf(scan.nextLine());
}
for(int i : list){
int out = 0;
for(int j = i; j > 0; j--){
out += (j * j);
}
System.out.println(out);
}
}
}
|
Java
|
UTF-8
| 1,646
| 2.28125
| 2
|
[] |
no_license
|
package br.edu.ifma.csp.timetable.dao.report;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import br.edu.ifma.csp.timetable.model.report.DadosRelatorioProfessorHorario;
import br.edu.ifma.csp.timetable.repository.report.ReportRepository;
@Stateless
public class RelatorioProfessorRestricoesDao implements ReportRepository<DadosRelatorioProfessorHorario> {
@PersistenceContext(unitName="timetable-front")
protected EntityManager manager;
@SuppressWarnings("unchecked")
@Override
public List<DadosRelatorioProfessorHorario> recuperarDados() {
String sql =
"select " +
"prof.NOME professor, dep.NOME departamento, " +
"(case " +
"when hor.DIA = 'SEGUNDA' then 0 " +
"when hor.DIA = 'TERCA' then 1 " +
"when hor.DIA = 'QUARTA' then 2 " +
"when hor.DIA = 'QUINTA' then 3 " +
"when hor.DIA = 'SEXTA' then 4 " +
"end) indice, " +
"hor.HORA_INICIO horario " +
"from PROFESSOR prof " +
"inner join DEPARTAMENTO dep on " +
"dep.ID_DEPARTAMENTO = prof.ID_DEPARTAMENTO " +
"inner join PREFERENCIA_HORARIO_PROFESSOR pref on " +
"pref.ID_PROFESSOR = prof.ID_PROFESSOR " +
"inner join HORARIO hor on " +
"hor.ID_HORARIO = pref.ID_HORARIO " +
"order by " +
"prof.NOME, HORA_INICIO, field(DIA, 'SEGUNDA', 'TERCA', 'QUARTA', 'QUINTA', 'SEXTA') asc";
List<Object[]> rows = manager.createNativeQuery(sql).getResultList();
List<DadosRelatorioProfessorHorario> dados = new ArrayList<DadosRelatorioProfessorHorario>(rows.size());
return dados;
}
}
|
C#
|
UTF-8
| 672
| 2.96875
| 3
|
[] |
no_license
|
using DT;
using System.Collections;
using UnityEngine;
public class MathUtils : MonoBehaviour {
/**
* Pass in the relative position between two points, get QuadInOut (ref: easings.net)
*
* @param {a} - Start Point
* @param {b} - End Point
* @param {r} - 0.0...1.0, Relative Position
*/
public static float QuadInOut(float a, float b, float r) {
if (r < 0.0f || r > 1.0f) {
Debug.LogError("Invalid r (" + r + ") value for QuadInOut!");
return 0.0f;
}
float m = (a + b) / 2.0f;
r *= 2.0f;
if (r < 1.0f) {
return a + (Mathf.Pow(r, 2.0f) * (m - a));
} else {
return m + (Mathf.Pow((r - 1.0f), 1.0f / 2.0f) * (b - m));
}
}
}
|
Python
|
UTF-8
| 1,083
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
import threading
import time
from compas_rrc.client import SequenceCounter
def test_sequence_id_rollover():
counter = SequenceCounter()
assert counter.value == 0
for i in range(1, 1000000):
counter.increment()
assert counter.value == i
assert counter.value == 999999
counter.increment()
assert counter.value == 1000000
counter.increment()
assert counter.value == 1
def test_sequence_id_increments():
counter = SequenceCounter()
assert counter.value == 0
counter.increment()
assert counter.value == 1
def test_multithreaded_consistency():
nr_of_threads = 4
nr_of_increments = 1000
counter = SequenceCounter()
def incrementer(c):
for i in range(nr_of_increments):
c.increment()
time.sleep(0.001)
threads = []
for _ in range(nr_of_threads):
t = threading.Thread(target=incrementer, args=(counter, ))
t.start()
threads.append(t)
for t in threads:
t.join()
assert counter.value == nr_of_threads * nr_of_increments
|
Markdown
|
UTF-8
| 6,874
| 3.875
| 4
|
[] |
no_license
|
> 定义的时候 位置参数 --> (* 可变长参数 | * ,强制关键字参数) --> ** 关键字参数
>
> 调用的时候 位置参数 --> (* 可变长参数 | * ,强制关键字参数) --> ** 关键字参数
>
> 如果定义的时候 可变长参数 在 位置参数 前面 那么调用的时候 位置参数 就要用 关键字参数代替
- 位置参数(普通方式)
```
def fuc(a,b):
pass
```
- 默认参数
```
def fuc(a,b=1):
pass
```
==默认参数的坑 只有 list 有坑 ,基本数据类型没有==
```python
先定义一个函数,传入一个list,添加一个END再返回:
def add_end(L=[]):
L.append('END')
return L
当你正常调用时,结果似乎不错:
add_end([1, 2, 3]) # [1, 2, 3, 'END']
add_end(['x', 'y', 'z']) # ['x', 'y', 'z', 'END']
当你使用默认参数调用时,一开始结果也是对的:
add_end() # ['END']
但是,再次调用add_end()时,结果就不对了:
add_end() #['END', 'END']
很多初学者很疑惑,默认参数是[],但是函数似乎每次都“记住了”上次添加了'END'后的list。
原因解释如下:
Python函数在定义的时候,默认参数L的值就被计算出来了,即[].
因为默认参数L也是一个变量,它指向对象[],每次调用该函数.
如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。
要修改上面的例子,我们可以用None这个不变对象来实现:
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
>>> add_end()
['END']
>>> add_end()
['END']
```
- 可变长参数 (传 list tuple) ==长度任意可以为0==
可变长cang
```
def test(*args): # *args 可变长参数
for item in args: #在函数内部是一个 tuple
print(item)
test(1,2) #2个参数
test() #不带参数
test(*[1,2,3,4]) # 传list前面加*
test(*(1,2,3,4,5)) # 传tuple前面加*
------普通传list方法------
def test(my_list):
for item in my_list:
print(item)
test([1,2,3])
------------------------
def test(name,pwd=1):
print(name,pwd)
test(*['a', 'b']) # 只要对的上就可以
-------------------------
```
- 关键字参数 (传 dict) ==长度任意可以为0==
==函数定义的时候 关键字参数要在可变长参数后3
即 def fun(*a, **b) 调用的时候也是,当然也可以为0==
==就是把字典传给函数==
```
def test(a,b,**c):
print(a,b,c) # 1,2,{'name':'stefan'}
print(c.get('name')) # 'stefan'
print(c['name']) # 'stefan'
test(1,2,name='stefan') # 调用方式1
dict={'name':'stefan','age':18}
test(1,2,**dict) # 调用方式2
# test(a=1, 2, **dict) # 这是错误的
# 关键字参数要在位置参数之后
```
- 命名关键字参数 (传限定名称的参数)
==如果要限制关键字参数的名字,就可以用命名关键字参数==
```
def test(a,b,*,name='lei',city): # 可以有默认值
print(a,b,name,city) # 1,2,stefan,nanchang
```
```
print(1,2,name='stefan',city='nanchang') #正确
print(1,2,city='nanchang') #正确 同时可以用默认值
print(1,2,'stefan','nanchang') # 错误
```
[参考链接-廖雪峰的官方网站](https://www.liaoxuefeng.com)
- 函数也是对象
```
abs(-1) # 函数也是对象
a=abs # a指向abs的引用
现在 a() 和 abs() 都可以使用 相当于是取了一个别名
```
- 函数覆盖
```
如果存在同名的函数后者覆盖前者
def test():
print(1)
test() # 1
def test():
print(2)
test() # 2
```
- 函数的说明文档
```
def sum_num(num):
'''
这是一个函数说明 :累加
:param num:
:return:
'''
s=0
for item in range(1,num+1):
s=s+item
return s
print(sum_num.__doc__)
```
- 新知识点 新特性
```
def sum_num(num:int)->int: # __annotations__
'''
这是一个函数说明 :累加 # __doc__
:param num:
:return:
'''
return num
print(sum_num.__annotations__) # {'num': <class 'int'>, 'return': <class 'int'>}
print(sum_num.__doc__) # help(sum_num)
这是一个函数说明 :累加
:param num:
:return:
__name__ : 名称
__doc__ : 注释''' ''' 首行
__annotations__ : 类型线索
```
```
'''
位置参数
可变长参数
关键字参数
强制关键参数
默认参数
'''
'''
函数定义: 强制关键字参数 不能 和可变长参数搭配 排序 位置参数-强制关键字参数(*,)-关键字参数(**)
函数调用: 位置参数要放在最前面
'''
```
- 偏函数
```
from functools import partial
def test(a,b,c):
print(a,b,c)
fun=partial(test,c='lei',b=1) # 相当于是 用fun对原来函数进行二次包装 可以省略一些参数
fun('a')
```
- 闭包
```
在一个外函数中定义了一个内函数,内函数里运用了外函数的临时变量,并且外函数的返回值是内函数的引用。这样就构成了一个闭包。
#闭包函数的实例
2 # outer是外部函数 a和b都是外函数的临时变量
3 def outer( a ):
4 b = 10
5 # inner是内函数
6 def inner():
7 #在内函数中 用到了外函数的临时变量
8 print(a+b)
9 # 外函数的返回值是内函数的引用
10 return inner
11
12 if __name__ == '__main__':
13 # 在这里我们调用外函数传入参数5
14 #此时外函数两个临时变量 a是5 b是10 ,并创建了内函数,然后把内函数的引用返回存给了demo
15 # 外函数结束的时候发现内部函数将会用到自己的临时变量,这两个临时变量就不会释放,会绑定给这个内部函数
16 demo = outer(5)
17 # 我们调用内部函数,看一看内部函数是不是能使用外部函数的临时变量
18 # demo存了外函数的返回值,也就是inner函数的引用,这里相当于执行inner函数
19 demo() # 15
20
21 demo2 = outer(7)
22 demo2()#17
```
[闭包-参考链接](https://www.cnblogs.com/Lin-Yi/p/7305364.html)
- 装饰器
- https://www.tuicool.com/articles/FBZvya
```
# 装饰器应该配合闭包使用,这样才保证了 Python 函数调用的一致性,而不是直接 函数名 就执行。
# 关于装饰器,可以看上面的第二个链接。
def test(f):
def inner():
print('start')
f()
print('end')
return inner
@test
def aaa():
print('middle'
aaa()
```
```python
def count_time(func):
def inner():
import time
start = time.clock()
func()
end = time.clock()
print(end - start)
return inner
@count_time
def test():
n = 0
for item in range(20000000):
n += item
test()
```
[装饰器和闭包-参考链接](https://segmentfault.com/a/1190000004461404)
|
Java
|
UTF-8
| 3,065
| 2.1875
| 2
|
[] |
no_license
|
package top.ss.forest.pojo;
import java.io.Serializable;
import java.util.List;
/**
* 林业资源
* @author Snake
*
*/
public class ForestInfo {
/* `fid` varchar(64) NOT NULL COMMENT '资源id',
`fName` varchar(32) NOT NULL COMMENT '资源名称',
`fType` varchar(64) DEFAULT NULL COMMENT '资源所属种类',
`fForm` varchar(256) DEFAULT NULL COMMENT '资源形态特征',
`fOrigin` varchar(256) DEFAULT NULL COMMENT '资源产地环境',
`fGrowthHabit` varchar(256) DEFAULT NULL COMMENT '资源生长习性',
`Latitude` double DEFAULT NULL COMMENT '纬度',
`Longitude` double DEFAULT NULL COMMENT '经度',
`uid` varchar(64) DEFAULT NULL,
`creater` varchar(64) NOT NULL COMMENT '创建人',
`createTime` varchar(128) NOT NULL COMMENT '创建时间',
`mender` varchar(64) DEFAULT NULL COMMENT '修改者',
`modifyTime` varchar(128) DEFAULT NULL COMMENT '修改时间',*/
private String fid;
private String fName;
private String fType;
private String fForm;
private String fOrigin;
private String fGrowthHabit;
private double latitude;
private double longitude;
private String creater;
private String createTime;
private String mender;
private String modifyTime;
private String uid;
//附加属性
private List<ForestPic> forestPicList;
public String getFid() {
return fid;
}
public void setFid(String fid) {
this.fid = fid;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getfType() {
return fType;
}
public void setfType(String fType) {
this.fType = fType;
}
public String getfForm() {
return fForm;
}
public void setfForm(String fForm) {
this.fForm = fForm;
}
public String getfOrigin() {
return fOrigin;
}
public void setfOrigin(String fOrigin) {
this.fOrigin = fOrigin;
}
public String getfGrowthHabit() {
return fGrowthHabit;
}
public void setfGrowthHabit(String fGrowthHabit) {
this.fGrowthHabit = fGrowthHabit;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public String getCreater() {
return creater;
}
public void setCreater(String creater) {
this.creater = creater;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getMender() {
return mender;
}
public void setMender(String mender) {
this.mender = mender;
}
public String getModifyTime() {
return modifyTime;
}
public void setModifyTime(String modifyTime) {
this.modifyTime = modifyTime;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public List<ForestPic> getForestPicList() {
return forestPicList;
}
public void setForestPicList(List<ForestPic> forestPicList) {
this.forestPicList = forestPicList;
}
}
|
Rust
|
UTF-8
| 1,736
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
use crate::client::{Client, MessageReturn};
use crate::message::MessageId;
use crate::torrent::Torrent;
use crate::utility;
use std::{thread, time};
const MAX_REQ_SIZE: i64 = 16384;
pub fn download_piece(client: &mut Client, index: u32, piece_length: i64) -> Vec<u8> {
let mut no_of_iterations = piece_length / MAX_REQ_SIZE;
if piece_length % MAX_REQ_SIZE != 0 {
no_of_iterations += 1;
}
let mut piece_length = piece_length;
let mut begin = 0i64;
let mut piece: Vec<u8> = Vec::new();
for _i in 0..no_of_iterations {
if piece_length > MAX_REQ_SIZE {
client.send_request(index, begin as u32, MAX_REQ_SIZE as u32);
piece_length -= MAX_REQ_SIZE;
begin += MAX_REQ_SIZE;
} else {
client.send_request(index, begin as u32, piece_length as u32);
piece_length -= piece_length;
begin += piece_length;
}
thread::sleep(time::Duration::from_secs(3));
let (id, payload) = match client.receive_message() {
(MessageId::KeepAlive, _) => client.receive_message(),
(id, payload) => (id, payload),
};
if let MessageId::Piece = id {
let mut block = if let MessageReturn::Piece((_, _, block)) = payload.unwrap() {
block
} else {
panic!("Wrong Message returned");
};
piece.append(&mut block);
}
}
piece
}
pub fn check_intergrity(torrent: &Torrent, index: u32, piece: Vec<u8>) -> bool {
let orginal_hash = torrent.get_piece_hash(index);
let piece_hash = utility::hash(piece);
if piece_hash == orginal_hash {
true
} else {
false
}
}
|
C
|
UTF-8
| 3,217
| 2.546875
| 3
|
[] |
no_license
|
//
// Classe d'AmibeProbaMutation
//
#include "AmibeProbaMutation.h"
#include <cmath>
using namespace std;
//________________________________________________________
AmibeProbaMutation::AmibeProbaMutation(void): Strategie()
{
//
// Constructeur par defaut
//
fCommentaire="AmibeProbaMutation de base";
doseMutation["Saine"]=5.25;
doseMutation["OAR"]=1.25;
widthMutation["Saine"]=0.115;
widthMutation["OAR"]=0.115;
}
//________________________________________________________
AmibeProbaMutation::~AmibeProbaMutation(void)
{
//
// Destructeur
//
}
//________________________________________________________
bool AmibeProbaMutation::peutOperer(Jeton *j)
{
//
// Test si les donnees sont conformes
//
bool ok=j->getData("doseFraction",doseFraction);
if(ok)
{
ok=j->getData("zones",zones);
}
//
return ok;
}
//________________________________________________________
Jeton *AmibeProbaMutation::resoudre(Jeton *j)
{
//
// Methode de resolution de AmibeProbaMutation
// Cette methode va modifier deux cartographies:
//
j->getData("doseFraction",doseFraction);
j->getData("zones",zones);
double xMin=zones.getXMin();
double xMax=zones.getXMax();
int dimX=zones.getDimX();
double yMin=zones.getYMin();
double yMax=zones.getYMax();
int dimY=zones.getDimY();
double xStep=(xMax-xMin)/dimX;
double yStep=(yMax-yMin)/dimY;
double probMutation=0.;
string type="";
if(!j->getData("probaNoMutation",probaNoMutation))
{
cout << "Creation de probaNoMutation" << endl;
probaNoMutation.setDimX(dimX);
probaNoMutation.setXMin(xMin);
probaNoMutation.setXMax(xMax);
probaNoMutation.setDimY(dimY);
probaNoMutation.setYMin(yMin);
probaNoMutation.setYMax(yMax);
for(double x=xMin+xStep/2.;x<xMax;x+=xStep)
{
for(double y=yMin+yStep/2.;y<yMax;y+=yStep)
{
probMutation=1.;
zones.getData(type,x,y);
if(type == "Air")
probMutation=0.;
probaNoMutation.setData(probMutation,x,y);
}
}
}
double dose=0;
for(double x=xMin+xStep/2.;x<xMax;x+=xStep)
{
for(double y=yMin+yStep/2.;y<yMax;y+=yStep)
{
doseFraction.getData(dose,x,y);
zones.getData(type,x,y);
if(type.substr(0,3)=="OAR") type="OAR";
if(dose > 0 && type !="Air" && type!="Tumeur")
{
probaNoMutation.getData(probMutation,x,y);
probMutation*=(1.-getProbaMutation(dose,type));
probaNoMutation.setData(probMutation,x,y);
}
}
}
j->setData("probaNoMutation",probaNoMutation);
return j;
}
//________________________________________________________
double AmibeProbaMutation::getProbaMutation(double dose,string type)
{
//
// Evaluation du nombre de mutantes
//
double moyenne=1./(1.+exp((doseMutation[type]-dose)/widthMutation[type]));
return moyenne;
}
//________________________________________________________
bool AmibeProbaMutation::setValeurParametre(string nomParam,double valeur)
{
//
// Ajuste la valeur du parametre en decodant la chaine de caracteres
//
bool res=true;
if(nomParam=="doseMutationSaine")
{
doseMutation["Saine"]=valeur;
}
else if(nomParam=="widthMutationSaine")
{
widthMutation["Saine"]=valeur;
}
else if(nomParam=="doseMutationOAR")
{
doseMutation["OAR"]=valeur;
}
else if(nomParam=="widthMutationOAR")
{
widthMutation["OAR"]=valeur;
}
else
{
res=false;
}
return res;
}
|
PHP
|
UTF-8
| 264
| 2.671875
| 3
|
[] |
no_license
|
<?php
class Product extends BaseModel{
public $table = "products";
public static function getByShopID($shopID){
$query = "SELECT * FROM products WHERE shop_id = ?";
$params = [ $shopID ];
return DB::getAll($query,$params);
}
}
|
Python
|
UTF-8
| 1,122
| 3.109375
| 3
|
[
"BSD-3-Clause",
"GPL-3.0-only"
] |
permissive
|
from vedo import shapes
from vedo import Mesh
from loguru import logger
from brainrender.actor import Actor
class Cylinder(Actor):
def __init__(self, pos, root, color="powderblue", alpha=1, radius=350):
"""
Cylinder class creates a cylinder mesh between a given
point and the brain's surface.
:param pos: list, np.array of ap, dv, ml coordinates.
If an actor is passed, get's the center of mass instead
:param root: brain root Actor or mesh object
:param color: str, color
:param alpha: float
:param radius: float
"""
# Get pos
if isinstance(pos, Mesh):
pos = pos.points().mean(axis=0)
elif isinstance(pos, Actor):
pos = pos.center
logger.debug(f"Creating Cylinder actor at: {pos}")
# Get point at top of cylinder
top = pos.copy()
top[1] = root.bounds()[2] - 500
# Create mesh and Actor
mesh = shapes.Cylinder(pos=[top, pos], c=color, r=radius, alpha=alpha)
Actor.__init__(self, mesh, name="Cylinder", br_class="Cylinder")
|
C++
|
UTF-8
| 685
| 3.109375
| 3
|
[
"MIT"
] |
permissive
|
#ifndef DARCEL_UTILITIES_HPP
#define DARCEL_UTILITIES_HPP
#include <memory>
#include <utility>
namespace darcel {
template<typename T> class Maybe;
//! Performs a static cast on a unique ptr.
template<typename T, typename U>
std::unique_ptr<T> static_pointer_cast(std::unique_ptr<U> p) noexcept {
return std::unique_ptr<T>(static_cast<T*>(p.release()));
}
//! Performs a dynamic cast on a unique ptr.
template<typename T, typename U>
std::unique_ptr<T> dynamic_pointer_cast(std::unique_ptr<U>&& p) noexcept {
auto d = dynamic_cast<T*>(p.get());
if(d != nullptr) {
p.release();
return std::unique_ptr<T>(d);
}
return {};
}
}
#endif
|
Python
|
UTF-8
| 133
| 3.859375
| 4
|
[] |
no_license
|
n=int(input('Введите натуральное число n: '))
for i in range(2, n-1):
if (n % i == 1):
print(i)
|
Python
|
UTF-8
| 568
| 2.953125
| 3
|
[] |
no_license
|
# coding=utf-8
flag = False
name = 'luren'
if name == 'python':
flag = True
print 'welcome boss'
else:
print name # luren
num = 5
if num == 3:
print 'boss'
elif num == 2:
print "user"
elif num == 1:
print 'worker'
elif num < 0:
print 'error'
else:
print 'roadman' # roadman
num = 9
if 0 <= num <= 10:
print 'hello' # hello
num = 10
if num < 0 or num > 10:
print 'hello'
else:
print 'undefine' # undefine
num = 8
if (0 <= num <= 5) or (10 <= num <= 15):
print 'hello'
else:
print 'undefine' # undefine
|
C#
|
UTF-8
| 403
| 2.640625
| 3
|
[] |
no_license
|
using System;
namespace GameStuff
{
public interface LevelObject
{
bool canMoveLeft(int boxesToMove);
bool canMoveRight(int boxesToMove);
bool canMoveDown(int boxesToMove);
bool canMoveUp(int boxesToMove);
void setGridLocation(int x, int y);
void setLevel(Level l);
int getGridX();
int getGridY();
bool isMoving();
void setMoveSpeed(float newSpeed);
float getMoveSpeed();
}
}
|
C#
|
UTF-8
| 1,273
| 3.34375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BankApplicationLibrary
{
class Account
{
public int Id { get; set; } // Kontonummer
public decimal Balance { get; set; } // Saldo
public decimal Interest
{
get
{
return Balance * InterestRate / 100;
}
}
public decimal InterestRate { get; set; } // Ränta i %
public string AccountType { get; set; } // Kontotyp
protected int GenerateAccountId()
{
int accountNumber = 1000;
return accountNumber;
}
public List<string> Present()
{
// presentera kontot(kontonummer,saldo, kontotyp, räntesats).
List<string> accountInfo = new List<string>();
return accountInfo;
}
private string PresentValue(decimal input)
// Hjälpfunktion för att runda av decimal till 2 decimaler, typ "6,54" och sedan konvertera dem till string
// för att kunna skrivas ut till en List<string> med Present()
{
input = Math.Round(input, 2);
return Convert.ToString(input);
}
}
}
|
PHP
|
UTF-8
| 2,189
| 2.59375
| 3
|
[] |
no_license
|
<?php
#header('Location: ../../main.php');
#include_once('../../modele/photos/photo_upload.class.php');
include_once('../../head.php');
$existence=false;
if($existence)
{
echo '<br/>';
$minwidth = 10;
$minheight = 10;
$minsize = 0;
$maxsize = 1000000000;
$photo_size = getimagesize($_FILES['photo']['tmp_name']);
$size = $_FILES['photo']['size'];
echo 'size : ' . $size . '<br/>';
$branche = intval($_POST['branche']);
echo 'branche : ' . $branche . '</br>';
$succes = false;
$infos_photo = pathinfo($_FILES['photo']['name']);
$extension_upload = $infos_photo['extension'];
$extensions_autorisees = array('jpg', 'jpeg', 'png');
if (in_array($extension_upload, $extensions_autorisees))
{
$identi = uniqid('photo_'). '.' . $extension_upload; //nom unique de la photo
$nom = "../../modele/gallerie/";
chdir($nom);
$resultat = move_uploaded_file($_FILES['photo']['tmp_name'],$identi);
if ($resultat)
{
$photo = new Photo_upload($identi, $branche);
$photo -> creer_Photo($identi,$size,$branche);
$photo -> set_date_upload($photo->getNom());
MAJ_branche($photo->getNom(),$branche);
/* Si l'upload est bon, on propose le téléchargement */
$succes = true;
/* Thumbnail */
$oldname = $identi;
$newname = "../../modele/gallerie_thumbnails/".$oldname;
if($extension_upload == 'jpeg' || $extension_upload == 'jpg')
{
$im = ImageCreateFromjpeg($oldname);
$width=ImageSx($im);
$height=ImageSy($im);
$n_height = 280;
$n_width = intval($n_height * $width / $height);
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResampled($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
ImageJpeg($newimage,$newname);
chmod($newname,0777);
}
if($extension_upload == 'png')
{
$im = ImageCreateFromPNG($oldname);
$width=ImageSx($im);
$height=ImageSy($im);
$n_height = 280;
$n_width = intval($n_height * $width / $height);
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResampled($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
ImagePng($newimage,$newname);
chmod($newname,0777);
}
}
}
}
|
C++
|
BIG5
| 605
| 3.65625
| 4
|
[] |
no_license
|
#include <iostream>
#include <cstdlib>
using namespace std;
class car
{
public: // ¦O禡ŧiOpublic
void go() // carOgo()
{
cout << endl<< "car : Xo"<< endl << endl;
}
};
class freighter: protected car {}; // lͨ禡N¦O~Ӥ覡ŧiprotected
int main()
{
car cr;
freighter ft;
cr.go(); // Is¦Oŧipublic禡go()
//ft.go(); // iIslͨƤwQഫprivatego()
return 0;
}
|
Java
|
UTF-8
| 2,752
| 2.4375
| 2
|
[] |
no_license
|
package com.cucc.vertx.demo.database.base;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
public class OracleClient {
private Logger logger=LoggerFactory.getLogger(OracleClient.class);
private ConcurrentHashMap<String, JDBCClient> pools = new ConcurrentHashMap<String, JDBCClient>();
//private Hashtable<String,JDBCClient> pools = new Hashtable<String,JDBCClient>();
static private OracleClient instance;
public static JsonObject configofngact = new JsonObject()
.put("url", "jdbc:oracle:thin:@10.124.0.39:1521:ngact")
.put("driver_class", "oracle.jdbc.driver.OracleDriver")
.put("user", "ubak").put("password", "ubak_123")
.put("initial_pool_size", 5)
.put("min_pool_size", 5)
.put("max_pool_size", 30);
public static JsonObject configofact1 = new JsonObject()
.put("url", "jdbc:oracle:thin:@10.124.0.42:1521:tact1")
.put("driver_class", "oracle.jdbc.driver.OracleDriver")
.put("user", "uop_act1").put("password", "uop_act1")
.put("initial_pool_size", 8)
.put("min_pool_size", 8)
.put("max_pool_size", 30);
/* 测试营业库
*UOP_CRM1/uop_crm1@10.124.0.40/tcrm1*/
public static JsonObject configoftcrm1 = new JsonObject()
.put("url", "jdbc:oracle:thin:@10.124.0.40:1521:tcrm1")
.put("driver_class", "oracle.jdbc.driver.OracleDriver")
.put("user", "UOP_CRM1").put("password", "uop_crm1")
.put("initial_pool_size", 8)
.put("min_pool_size", 8)
.put("max_pool_size", 30);
public static OracleClient getInstance(Vertx vertx) {
if (instance == null) {
instance = new OracleClient(vertx);
}
return instance;
}
private OracleClient(Vertx vertx) {
this.init(vertx);
}
private void init(Vertx vertx) {
logger.info("创建数据库连接池。。。");
createPools(vertx);
logger.info("创建数据库连接池完毕。。。");
}
private void createPools(Vertx vertx) {
JDBCClient clientofngact=JDBCClient.createShared(vertx, configofngact, "ngact");
JDBCClient clientofact1=JDBCClient.createShared(vertx, configofact1, "act1");
JDBCClient clientoftcrm1=JDBCClient.createShared(vertx, configoftcrm1,"tcrm1");
pools.put("ngact", clientofngact);
pools.put("act1", clientofact1);
pools.put("tcrm1", clientoftcrm1);
}
public JDBCClient getClient(String name) {
return pools.get(name);
}
}
|
Java
|
UTF-8
| 1,519
| 2.359375
| 2
|
[] |
no_license
|
package protocol;
import errors.ParsingError;
import org.junit.Test;
import protocol.client.*;
import static org.junit.Assert.assertEquals;
public class TestClientMessage {
@Test
public void login() throws ParsingError {
Login l = (Login) ClientMessage.parse("CONNEXION/user/");
assertEquals("user", l.getUserName());
assertEquals(l.toString(), "CONNEXION/user/");
}
@Test
public void logout() throws ParsingError {
Logout l = (Logout) ClientMessage.parse("SORT/user/");
assertEquals("user", l.getUserName());
assertEquals(l.toString(), "SORT/user/");
}
@Test
public void found() throws ParsingError {
Found d = (Found) ClientMessage.parse("TROUVE/TRIDENT/A1A2A3/");
assertEquals("TRIDENT", d.getWord());
assertEquals("A1A2A3", d.getTrajectory());
assertEquals(d.toString(), "TROUVE/TRIDENT/A1A2A3/");
}
@Test
public void send() throws ParsingError {
Send s = (Send) ClientMessage.parse("ENVOI/Hello World/");
assertEquals(s.getMessage(), "Hello World");
assertEquals(s.getReceiver(), "");
assertEquals(s.toString(), "ENVOI/Hello World/");
}
@Test
public void sendPrivate() throws ParsingError {
Send s = (Send) ClientMessage.parse("PENVOI/user1/Hello World/");
assertEquals(s.getMessage(), "Hello World");
assertEquals(s.getReceiver(), "user1");
assertEquals(s.toString(), "PENVOI/user1/Hello World/");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.