language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
C++
|
GB18030
| 4,863
| 2.859375
| 3
|
[] |
no_license
|
#include "include\LRContext.h"
void LRContext::produc_analyze(
const string& line, const string& arrow, const string& delim, const vector<string>& terminators,
const vector<string>& non_terminators, vector<Produc>& producs,
map<string, set<size_t>>& produc_map)
{
if (non_terminators.empty() || terminators.empty())
{
cerr << "ļ˳ʽʽҪļ" << endl;
exit(EXIT_FAILURE);
}
size_t i = producs.size();
Symbol left = Produc::identify(terminators, non_terminators, producs, arrow, line, delim);
for (; i < producs.size(); i++)
{
produc_map[left.getStr()].insert(i);
}
}
LRContext LRContext::init(string fpath)
{
ifstream fin(fpath);
if (!fin.is_open())
{
cerr << "ļʧܣ" << fpath << endl;
exit(EXIT_FAILURE);
}
string line;
string arrow;
string start_symbol;
string init_delim = " ";
string delim;
vector<string> terminators_source;
vector<string> non_terminators_source;
vector<string> terminators;
vector<string> non_terminators;
vector<Produc> producs;
//ռλչķʱõ
producs.push_back(Produc());
map<string, set<size_t>> produc_map;
int status = -1;
while (!fin.eof())
{
getline(fin, line);
kyle::trim(line);
if (line.empty() || line.at(0) == '#')
{
continue;
}
else if (line == "[base symbol]")
{
status = 0;
}
else if (line == "[terminators]")
{
status = 1;
}
else if (line == "[non_terminators]")
{
status = 2;
}
else if (line == "[producs]")
{
status = 3;
}
else
{
vector<string> tmp;
kyle::split(tmp, line, init_delim);
switch (status)
{
case 0:
if (tmp.size() < 2)
{
cerr << "ñƵͿʼţ" << endl;
exit(EXIT_FAILURE);
}
arrow = tmp.at(0);
start_symbol = tmp.at(1);
if (tmp.size() > 2 && !tmp[2].empty())
{
delim = tmp.at(2);
init_delim = delim;
}
break;
case 1:
terminators.insert(terminators.end(), tmp.begin(), tmp.end());
terminators_source.insert(terminators_source.end(), tmp.begin(), tmp.end());
kyle::sort_by_len(terminators);
break;
case 2:
non_terminators.insert(non_terminators.end(), tmp.begin(), tmp.end());
non_terminators_source.insert(non_terminators_source.end(), tmp.begin(), tmp.end());
kyle::sort_by_len(non_terminators);
break;
case 3:
produc_analyze(line, arrow, delim, terminators, non_terminators, producs, produc_map);
break;
default:
break;
}
}
}
LRContext context;
context.arrow = arrow;
context.delim = delim;
context.terminators_source = terminators_source;
context.non_terminators_source = non_terminators_source;
context.terminators = terminators;
context.non_terminators = non_terminators;
context.producs = producs;
context.start_symbol = Symbol(start_symbol, SymbolType::NON_TERMINATOR);
context.produc_map = produc_map;
fin.close();
return context;
}
void LRContext::test()
{
cout << "> Ƶ: " << arrow << endl;
cout << "> ս: " << endl;
for (string s : terminators)
{
cout << s << "\t";
}
cout << endl;
cout << "> ս: " << endl;
for (string s : non_terminators)
{
cout << s << "\t";
}
cout << endl;
cout << "> ʽ: " << endl;
for (Produc p : producs)
{
cout << p.getLeft().getStr() << p.getArrow();
for (Symbol s : p.getRight())
{
cout << s.getStr();
}
cout << endl;
}
cout << "> ʽmap: " << endl;
for (auto& p : produc_map)
{
cout << "-: " << p.first << ": ";
for (size_t s : p.second)
{
cout << s << '\t';
}
cout << endl;
}
}
Produc LRContext::get_produc(size_t no)
{
if (no >= this->producs.size())
{
return Produc();
}
return this->producs.at(no);
}
string LRContext::get_arrow()
{
return this->arrow;
}
string LRContext::get_delim()
{
return this->delim;
}
Symbol& LRContext::get_start_symbol()
{
return this->start_symbol;
}
void LRContext::set_expand_produc(const Produc& p)
{
*this->producs.begin() = p;
}
set<size_t>* LRContext::get_produc_nos(const string& symbol)
{
return &produc_map[symbol];
}
bool LRContext::non_terminators_exist(const string& symbol)
{
return find(non_terminators.begin(), non_terminators.end(), symbol) != non_terminators.end();
}
ostream& LRContext::output(ostream& out)
{
out << this->delim << endl;
out << "[symbol-list]" << endl;
for (string str : this->terminators_source)
{
out << str << this->delim;
}
out << Symbol::END;
for (string str : this->non_terminators_source)
{
out << this->delim << str;
}
out << endl;
//ʽ
out << "[productor-list]" << endl;
out << this->arrow;
vector<Produc>::iterator iter = this->producs.begin();
while (++iter != producs.end())
{
Produc& p = *iter;
out << this->delim << p.getStr();
}
out << endl;
return out;
}
|
PHP
|
UTF-8
| 609
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class TeacherExperienceTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$values = [
'меньше года',
'от 1 до 5 лет',
'от 5 до 10 лет',
'более 10 лет'
];
foreach ($values as $value) {
DB::table('teacher_experiences')->insert(
[
'value' => $value
]
);
}
}
}
|
Python
|
UTF-8
| 3,344
| 2.578125
| 3
|
[] |
no_license
|
import abc
import quantities as pq
import numpy as np
from contextlib import contextmanager
from .simplify import simplify
class HemeLbParameters(object):
__metaclass__ = abc.ABCMeta
ReferencePressure = 0.0 * pq.mmHg
Density = 1e3 * pq.kilogram / pq.metre**3
DynamicViscosity = 0.004 * pq.pascal*pq.second
KinematicViscosity = (DynamicViscosity / Density).simplified
@property
@simplify
def SpeedOfSound(self):
return self.VoxelSize / (np.sqrt(3.) * self.TimeStep)
@abc.abstractproperty
def VoxelSize(self):
pass
@abc.abstractproperty
def TimeStep(self):
pass
@property
@simplify
def UnitMass(self):
"""Choose this such that the density is one in lattice units.
"""
return self.Density * self.VoxelSize**3
@property
def Tau(self):
return self.ScaleToLatticeUnits(self.KinematicViscosity / self.SpeedOfSound**2) + 0.5
@property
def _LatticeUnitsMap(self):
return {
pq.second: self.TimeStep,
pq.metre: self.VoxelSize,
pq.kilogram: self.UnitMass
}
def ScaleToLatticeUnits(self, q):
# Check it's a quantity
if not isinstance(q, pq.Quantity):
return q
dims = q.dimensionality.simplified
scaleFactor = pq.dimensionless
for dim, power in dims.iteritems():
scaleFactor = scaleFactor * self._LatticeUnitsMap[dim]**power
# Scale
scaled = (q / scaleFactor).simplified
assert scaled.units == pq.dimensionless
# Now forget about quantities
scaled = scaled.view(np.ndarray)
# If it's a scalar, return a float
if q.shape == ():
return float(scaled)
# otherwise, the np array
return scaled
_OutputUnitsMap = {}
@staticmethod
def _UnitQuantitiesToMap(qList, oldMap=None):
ans = {}
if oldMap is not None:
ans.update(oldMap)
pass
for q in qList:
assert isinstance(q, pq.UnitQuantity)
key = q.dimensionality.simplified
val = q
assert key not in ans, "Duplicate output units!"
ans[key] = val
continue
return ans
@contextmanager
def SIunits(self):
self._OutputUnitsMap = {}
yield
del self._OutputUnitsMap
def ScaleForOutput(self, q):
# Check it's a quantity
if not isinstance(q, pq.Quantity):
return q
try:
# Have we specified output units for quantities with these dimensions?
scaleFactor = self._OutputUnitsMap[q.dimensionality.simplified]
except KeyError:
# No, so use SI base units instead
scaleFactor = q.units.simplified.units
pass
# Scale
scaled = (q / scaleFactor).simplified
assert scaled.units == pq.dimensionless
# Now forget about quantities
scaled = scaled.view(np.ndarray)
# If it's a scalar, return a float
if q.shape == ():
return float(scaled)
# otherwise, the np array
return scaled
pass
|
Java
|
UTF-8
| 2,838
| 3.234375
| 3
|
[] |
no_license
|
public class GetSetTest{
public static void main(String[] args){
ProjectManager e1 = new ProjectManager("alpha", "201912", 4000);
Project p1 = new Project("lta", 100000, true);
Project p2 = new Project("dummy");
e1.addProject(p2);
int num = 1;
//testing get Projects (count)
System.out.printf("Test %d%n", num);
System.out.println("Expected: true" );
System.out.println("Actual : " + (e1.getProjects().size() == 1));
System.out.println();
//testing getters
num++;
System.out.printf("Test %d%n", num);
System.out.println("Expected: 4000.0 ") ;
System.out.println("Actual : " + e1.getTotalSalary());
System.out.println();
//testing add project and get Projects (count)
e1.addProject(p1);
num++;
System.out.printf("Test %d%n", num);
System.out.println("Expected: true" );
System.out.println("Actual : " + (e1.getProjects().size() == 2));
System.out.println();
//testing getBonus and getProjectWorth
num++;
System.out.printf("Test %d%n", num);
System.out.println("Expected: 1000.0" );
System.out.println("Actual : " + e1.getBonus());
System.out.println();
num++;
System.out.printf("Test %d%n", num);
System.out.println("Expected: 5000.0 ") ;
System.out.println("Actual : " + e1.getTotalSalary());
System.out.println();
//testing add / remove Project and getBonus()
ProjectManager e2 = new ProjectManager("beta", "201910");
Project p3 = new Project("abc", 5000, true);
Project p4 = new Project("def", 10000, true);
Project p5 = new Project("def");
p5.setWorth(5500);
e2.setSalary(3000);
e2.addProject(p3);
e2.addProject(p4);
e2.addProject(p5);
num++;
System.out.printf("Test %d%n", num);
System.out.println("Expected: 150.0");
System.out.println("Actual : " + e2.getBonus());
System.out.println();
e2.removeProject(p4);
num++;
System.out.printf("Test %d%n", num);
System.out.println("Expected: 3050.0");
System.out.println("Actual : " + e2.getTotalSalary());
System.out.println();
//testing toString()
num++;
System.out.printf("Test %d%n", num);
System.out.println("Expected: [Name: alpha, type: ProjectManager, JoinedDate: 201912, projects worth: 100000]");
System.out.println("Actual : " + e1);
}
}
|
PHP
|
UTF-8
| 3,278
| 2.515625
| 3
|
[
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
<?php
/**
* This file is part of the OpenPNE package.
* (c) OpenPNE Project (http://www.openpne.jp/)
*
* For the full copyright and license information, please view the LICENSE
* file and the NOTICE file that were distributed with this source code.
*/
/**
* opGDataDocumentEntry
*
* @package opWebAPIPlugin
* @subpackage api
* @author Kousuke Ebihara <ebihara@tejimaya.com>
*/
class opGDataDocumentEntry extends opGDataDocument
{
protected $isInsert = false;
public function __construct($entry = null, $isInsert = false)
{
$this->isInsert = $isInsert;
if (is_null($entry))
{
parent::__construct();
}
elseif ($entry instanceof SimpleXMLElement)
{
$this->elements = $entry;
}
else
{
parent::__construct($entry);
}
}
protected function getRootXMLString()
{
$string = self::XML_DECLARATION.'<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gd="'.self::NAMESPACE.'"></entry>';
return $string;
}
public function setTitle($title, $type = 'text')
{
$element = $this->getElements()->addChild('title');
$this->addValidStringToNode($element, $title);
$element->addAttribute('type', $type);
}
public function setId($id)
{
$this->getElements()->addChild('id', $id);
}
public function setAuthor($name = null, $id = null, $email = null)
{
if (!func_num_args())
{
return null;
}
$author = $this->getElements()->addChild('author');
if ($name)
{
$author->addChild('name', $name);
}
if ($id)
{
if (is_int($id))
{
$author->addChild('id', $id);
}
else
{
$author->addChild('uri', $id);
}
}
if ($email)
{
$author->addChild('email', $email);
}
}
public function setAuthorByMember(Member $member)
{
sfContext::getInstance()->getConfiguration()->loadHelpers(array('Url', 'opUtil'));
$uri = url_for('@feeds_member_retrieve_resource_normal?model=member&id='.$member->getId(), true);
$this->setAuthor($member->getName(), $uri);
}
public function setPublished($published)
{
$datetime = new DateTime($published);
$this->getElements()->addChild('published', $datetime->format(DATE_RFC3339));
}
public function setUpdated($updated)
{
$datetime = new DateTime($updated);
$this->getElements()->addChild('updated', $datetime->format(DATE_RFC3339));
}
public function setContent($content, $type = 'text')
{
$element = $this->getElements()->addChild('content');
$this->addValidStringToNode($element, $content);
$element->addAttribute('type', $type);
}
public function setLink($href, $rel = '', $type = '')
{
$link = $this->getElements()->addChild('link');
$link->addAttribute('href', $href);
if ($rel)
{
$link->addAttribute('rel', $rel);
}
if ($type)
{
$link->addAttribute('type', $type);
}
}
public function addCategory($term, $label = '', $scheme = '')
{
if (!$label)
{
$label = $term;
}
$category = $this->getElements()->addChild('category');
$category->addAttribute('term', $term);
$category->addAttribute('label', $label);
if ($scheme)
{
$category->addAttribute('scheme', $scheme);
}
}
}
|
Python
|
UTF-8
| 482
| 3.703125
| 4
|
[] |
no_license
|
evenNumber = [2,4,6,8,10]
oddNumber = [1,3,5,7,9]
print(evenNumber)
evenNumber.extend(oddNumber)
print(evenNumber)
#sorting
evenNumber.sort()
print(evenNumber)
#sorting in reverse
evenNumber.sort(reverse = True)
print(evenNumber)
#sum of all elements
print(sum(evenNumber))
print(min(evenNumber))
print(max(evenNumber))
a = '1231231231231465123'
print(a.count('1'))
a=[1,2,5,5,3,3,2,2,1,4,1,4,1,1,3,1,3,1,3,1,1]
print(a.count(3))
b=[str(i) for i in a]
print(b)
print(b.count('3'))
|
Go
|
UTF-8
| 578
| 2.9375
| 3
|
[] |
no_license
|
package dcp025
import (
"fmt"
"testing"
)
func TestMatch(t *testing.T) {
var tests = []struct {
pattern string
input string
match bool
}{
{".*at", "chat", true},
{".*at", "chats", false},
{"a*b*c*", "aaabbc", true},
{"a*b*c*", "aaabb", true},
{"a*b*c*", "aaa", true},
{"a*b*c*", "", true},
{"a*b*c*", "abcd", false},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("%s %s", tt.pattern, tt.input), func(t *testing.T) {
if b := match(tt.pattern, tt.input); b != tt.match {
t.Fatalf("match returned %v, want %v", b, tt.match)
}
})
}
}
|
Java
|
UTF-8
| 2,885
| 2.140625
| 2
|
[] |
no_license
|
package com.apress.controller;
import java.net.URI;
import java.util.Collection;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import com.apress.dto.PartDTO;
import com.apress.service.PartService;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/vehicles/parts")
public class PartController {
@Autowired
private PartService partService;
@GetMapping()
public ResponseEntity<Collection<PartDTO>> findAll() {
Collection<PartDTO> partDTOs = partService.findAll();
return new ResponseEntity<>(partDTOs, HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<PartDTO> findById(@PathVariable Long id) {
Optional<PartDTO> partDTO = partService.findById(id);
if (!partDTO.isPresent()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND, String.format("%s not found", id));
}
return new ResponseEntity<>(partDTO.get(), HttpStatus.OK);
}
@PostMapping()
public ResponseEntity<Void> create(@RequestBody PartDTO partDTO) {
partDTO = partService.save(partDTO.toBuilder().id(null).build());
if (partDTO.hasErrors()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, partDTO.getErrors());
} else {
HttpHeaders headers = new HttpHeaders();
headers.setLocation(buildLocationUri(partDTO.getId()));
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
}
private URI buildLocationUri(Long id) {
return ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(id).toUri();
}
@PutMapping("/{id}")
public ResponseEntity<Void> update(@RequestBody PartDTO partDTO, @PathVariable Long id) {
if (!partService.existsById(id)) {
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
partDTO.setId(id);
partService.save(partDTO);
return new ResponseEntity<>(HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> delete(@PathVariable Long id) {
if (!partService.existsById(id)) {
return new ResponseEntity<Void>(HttpStatus.NOT_FOUND);
}
partService.deleteById(id);
return new ResponseEntity<>(HttpStatus.ACCEPTED);
}
}
|
Java
|
UTF-8
| 1,403
| 3.234375
| 3
|
[] |
no_license
|
package com.minhnhat.element.sorting;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RenderCalendar {
public static class Event {
public int start, finish;
public Event(int start, int finish) {
this.start = start;
this.finish = finish;
}
}
private static class Endpoint implements Comparable<Endpoint> {
public int time;
public boolean isStart;
@Override
public int compareTo(Endpoint that) {
if (time != that.time) {
return Integer.compare(time, that.time);
}
return isStart && !that.isStart ? -1 : !isStart && that.isStart ? 1 : 0;
}
public Endpoint(int time, boolean isStart) {
this.time = time;
this.isStart = isStart;
}
}
public static int findMaxSimultaneousEvents(List<Event> A) {
List<Endpoint> E = new ArrayList<>();
for (Event event : A) {
E.add(new Endpoint(event.start, true));
E.add(new Endpoint(event.finish, false));
}
Collections.sort(E);
int maxNumSimultaneousEvents = 0, numsSimultaneousEvents = 0;
for (Endpoint endpoint : E) {
if (endpoint.isStart) {
++numsSimultaneousEvents;
maxNumSimultaneousEvents = Math.max(numsSimultaneousEvents, maxNumSimultaneousEvents);
} else {
--numsSimultaneousEvents;
}
}
return maxNumSimultaneousEvents;
}
}
|
Python
|
UTF-8
| 1,231
| 3.484375
| 3
|
[] |
no_license
|
import csv, os
votes_total = 0
candidates = dict()
proportion = dict()
file = open("election_data.csv", 'r')
poll_reader = csv.reader(file)
next(poll_reader) #skip header row
file.close
#fills candidates dictionary with names as keys, votes counted as values
for row in poll_reader:
votes_total += 1 #counts total cotes
if row[2] in candidates: #checks for candidate name in candidate dictionary, adds vote to name
candidates[row[2]] += 1
else:
candidates[row[2]] = 1
#output_path = os.path.join("election winner.csv")
with open("election winner.csv", 'w') as csvfile:
csvwriter = csv.writer(csvfile, delimiter = ',')
print('Election Results')
csvwriter.writerow(['Election Results'])
print(f'Total votes {votes_total}')
csvwriter.writerow([f'Total votes {votes_total}'])
for name in candidates:
proportion[name] = candidates[name]/votes_total * 100
print(f'{name}: {round(proportion[name], 2)}% ({candidates[name]})')
csvwriter.writerow([f'{name}: {round(proportion[name], 2)}% ({candidates[name]})'])
winner_name =max(candidates, key=candidates.get)
print(f'Winner: {winner_name}')
csvwriter.writerow([f'Winner: {winner_name}'])
|
JavaScript
|
UTF-8
| 3,892
| 2.84375
| 3
|
[] |
no_license
|
'use strict';
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Platform,
Switch,
} from 'react-native';
class BasicSwitchExample extends React.Component {
state = {
trueSwitchIsOn: true,
falseSwitchIsOn: false,
};
render() {
return (
<View>
<Switch
onValueChange={(value) => this.setState({falseSwitchIsOn: value})}
style={{marginBottom: 10}}
value={this.state.falseSwitchIsOn} />
<Switch
onValueChange={(value) => this.setState({trueSwitchIsOn: value})}
value={this.state.trueSwitchIsOn} />
</View>
);
}
}
class DisabledSwitchExample extends React.Component {
render() {
return (
<View>
<Switch
disabled={true}
style={{marginBottom: 10}}
value={true} />
<Switch
disabled={true}
value={false} />
</View>
);
}
}
class ColorSwitchExample extends React.Component {
state = {
colorTrueSwitchIsOn: true,
colorFalseSwitchIsOn: false,
};
render() {
return (
<View>
<Switch
onValueChange={(value) => this.setState({colorFalseSwitchIsOn: value})}
onTintColor="#00ff00"
style={{marginBottom: 10}}
thumbTintColor="#0000ff"
tintColor="#ff0000"
value={this.state.colorFalseSwitchIsOn} />
<Switch
onValueChange={(value) => this.setState({colorTrueSwitchIsOn: value})}
onTintColor="#00ff00"
thumbTintColor="#0000ff"
tintColor="#ff0000"
value={this.state.colorTrueSwitchIsOn} />
</View>
);
}
}
class EventSwitchExample extends React.Component {
state = {
eventSwitchIsOn: false,
eventSwitchRegressionIsOn: true,
};
render() {
return (
<View style={{ flexDirection: 'row', justifyContent: 'space-around' }}>
<View>
<Switch
onValueChange={(value) => this.setState({eventSwitchIsOn: value})}
style={{marginBottom: 10}}
value={this.state.eventSwitchIsOn} />
<Switch
onValueChange={(value) => this.setState({eventSwitchIsOn: value})}
style={{marginBottom: 10}}
value={this.state.eventSwitchIsOn} />
<Text>{this.state.eventSwitchIsOn ? 'On' : 'Off'}</Text>
</View>
<View>
<Switch
onValueChange={(value) => this.setState({eventSwitchRegressionIsOn: value})}
style={{marginBottom: 10}}
value={this.state.eventSwitchRegressionIsOn} />
<Switch
onValueChange={(value) => this.setState({eventSwitchRegressionIsOn: value})}
style={{marginBottom: 10}}
value={this.state.eventSwitchRegressionIsOn} />
<Text>{this.state.eventSwitchRegressionIsOn ? 'On' : 'Off'}</Text>
</View>
</View>
);
}
}
class RNApp extends React.Component {
renderColorSwitch(){
if(Platform.OS == 'ios'){
return (
<View>
<Text>Custom colors can be provided</Text>
<ColorSwitchExample />
</View>
)
}
}
render() {
return (
<View style={styles.container}>
<View>
<Text>Switches can be set to true or false</Text>
<BasicSwitchExample />
</View>
<View>
<Text>Switches can be disabled</Text>
<DisabledSwitchExample />
</View>
<View>
<Text>Change events can be detected</Text>
<EventSwitchExample />
</View>
{this.renderColorSwitch()}
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
hello: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
AppRegistry.registerComponent('RNApp', () => RNApp);
|
C++
|
UTF-8
| 1,495
| 2.625
| 3
|
[] |
no_license
|
// https://codeforces.com/problemset/problem/731/A
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define fast ios_base::sync_with_stdio(false) ; cin.tie(0) ; cout.tie(0) ;
#define endl '\n'
void solve()
{
// string abc = "abcdefghijklmnopqrstuvwxyz" ;
string str ;
cin >> str ;
int noOfRotationA, noOfRotationB , ans = 0 ;
noOfRotationA = abs('a' - str[0]) ;
noOfRotationB = abs('z' - str[0]) + 1 ;
ans += min(noOfRotationA, noOfRotationB) ;
// cout << min(noOfRotationA, noOfRotationB) << endl ;
for (int i = 1 ; i < str.size() ; i++)
{
noOfRotationA = abs(str[i - 1] - str [i] );
noOfRotationB = (26 - abs( (str[i - 1] - 96) - (str[i] - 96) ) ) ;
// cout << "Clockwise " << noOfRotationA << endl ;
// cout << "Anti-clockwise " << noOfRotationB << endl ;
// cout << min(noOfRotationA, noOfRotationB) << endl ;
ans += min(noOfRotationA, noOfRotationB) ;
}
cout << ans << endl ;
}
int32_t main()
{
fast ;
int testcases = 1 ;
//cin >> testcases ;
while(testcases--)
{
solve() ;
}
return 0;
}
/* CODED BY:-
___________________________________
| ___ |
| /\ /\ \ / | | |___ |__| |
| /~~\ /~~\ | |__| ___| | | |
|___________________________________|
*/
|
C++
|
UTF-8
| 2,686
| 3.1875
| 3
|
[] |
no_license
|
/*
* https://leetcode.com/problems/pancake-sorting/
* (c) Mohammad Hasanzadeh Mofrad, 2020
* (e) m.hasanzadeh.mofrad@gmail.com
*/
class Solution {
public:
bool isSorted(std::vector<int> arr) {
bool sorted = true;
int m = arr.size();
for(int i = 0; i < m-1; i++) {
if(arr[i] > arr[i+1]) {
sorted = false;
break;
}
}
return sorted;
}
std::vector<int> flip(std::vector<int> arr, int k) {
std::vector<int> arr1(arr);
for(int i = 0; i < k/2; i++) {
std::swap(arr1[i], arr1[k-1-i]);
}
return(arr1);
}
bool pancakeSort1(vector<int> A, int k) {
if(isSorted(A)) return(true);
int m = A.size();
if(k <= m) {
printf("%d %d\n", k, m);
std::vector<int> B(A);
flip(B, k);
bool r1 = pancakeSort1(B, k+1);
bool r2 = pancakeSort1(A, k+1);
return(r1 or r2);
}
return(false);
}
std::vector<int> flips;
vector<int> pancakeSort(vector<int>& A) {
pancakeSort3(A);
return(flips);
}
void pancakeSort3(vector<int>& A) {
std::map<int, int> my_map;
int m = A.size();
for(int i = 0; i < m; i++){
my_map[A[i]] = i;
}
std::vector<int> pos(m);
int i = 0;
for(auto rit = my_map.rbegin(); rit != my_map.rend(); rit++, i++) {
pos[i] = rit->second;
}
//for(int a: A) {
// printf("%d ", a);
//}
//printf("\n");
int f = 0;
//for(int i = 0; i < m; i++) {
i = 0;
if(pos[i]>=1) {
// printf("%d>>\n ", pos[i]);
//f += pos[i];
flips.push_back(pos[i]+1);
std::reverse(A.begin(), A.begin()+pos[i]+1);
}
if(m-i> 1) {
//f += m-1;
flips.push_back(m);
std::reverse(A.begin(), A.begin()+m-i);
}
// break;
//}
for(int a: A) {
printf("%d ", a);
}
printf("\n");
if(A.size()>1) {
A.pop_back();
pancakeSort3(A);
}
//std::vector<int> sorted(A);
//std::sort(sorted.begin(), sorted.end());
//for(int i = m-1; i >= 0; i--) {
// pos[i-m-1] =
//}
//return(A);
}
};
|
C++
|
UTF-8
| 7,451
| 4.1875
| 4
|
[] |
no_license
|
#include <cmath>
#include <iostream>
#include <unordered_map>
using namespace std;
/*
One Away: There are three types of edits that can be performed on strings:
insert a character, remove a character, or replace a character. Given two
strings, write a function to check if they are one edit (or zero edits) away.
*/
/*
Thought Process:
First things first, edge cases:
Will we have to deal with any extraneous characters like punctaton or
whitespace? If we have two strings like this: 'able' and ' able '. They are
technically two characters away, but should our solution return them as two
characters away?
It is a good question to ask, just to make sure. For our implementation, let's
just assume that we don't need to do any type of cleanup with the strigns and
they will just be single words when they are input into our function.
First Approach: Sorting
Obviously if the length of the two strings differs by greater than 1, we return
false right away. Otherwise, we can sort the two strings and parse through them
at the same time and count the differences. If the number of differences exceeds
one, then we return false. This sounds feasibly but a little complicate to
implement because we are going to need to account for a bunch of different
scenarios.
Time: O(NlogN)
Space: O(1)
Second Approach: 2 Hash Tables
Put the two strings into a hashmap to keep track of the characters and number of
occurences, then compare the two hashmaps. This sounds like it will work and it
seems less complicated to code than our initial approach. If feels like we can
still optimize it though.
Time: O(N)
Space: O(N)
Third Approach: 1 Hash Table
After thinking a little more about the problem, using two hashtables seemes
unnecesary. We can attain all the necessary information by just looking at
whether the occurence of each character is even or odd. If the strings must
differ by at most one character, that means that if we hold the sums of each
character across both strings in a hashtable, there MUST BE a single
character that has an odd nunber of occurences if the difference of string
lengths is 1. Otherwise, if the difference in string lengths is 0, then there
MUST BE 2 letters that have one odd occurence. Let's implement this solution.
Time: O(N)
Space: O(N)
*/
void populateMap(unordered_map<char, int> &map, string arr[], int size) {
for (int i = 0; i < size; ++i) {
for (char &c : arr[i]) {
map[c]++;
}
}
}
bool oneAwayOneHashTable(string a, string b) {
int size_a = a.length();
int size_b = b.length();
int diff = abs(size_a - size_b);
if (diff > 1) {
return false;
}
unordered_map<char, int> map;
string arr[2] = {a, b};
populateMap(map, arr, 2);
// Seperating this populateMap process into its own separate function is a
// nice way of writing code that is cleaner. We could
// generalize this functoin more. You can discuss the stylistic
// tradeoffs with the interviewer.
int num_of_odd_occurences = 0;
for (auto itr : map) {
if (itr.second % 2 == 1) {
num_of_odd_occurences++;
}
}
if (diff == 0) {
return (num_of_odd_occurences == 2 || num_of_odd_occurences == 0);
} else {
return num_of_odd_occurences == 1;
}
}
/*
Fourth Approach: Bitset
We can further optimize the amount of space this function takes up by using a
bitset instead of hash table. We can do this because we don't actually care
about the numbere of occurences of each charatcer, we just care about whether
they are even or odd. This is a nice optimization to bring up in an interview.
However, it doesn't change the time or space complxity but it is strictly
better in terms of number of bits that the solution will take up.
Time: O(N)
Space: O(N)
*/
bool oneAwayOneBitVector(string a, string b) {
int size_a = a.length();
int size_b = b.length();
int diff = abs(size_a - size_b);
if (diff > 1) {
return false;
}
bitset<26> map;
string arr[2] = {a, b};
for (char &c : a) {
size_t pos = (int)c - 97;
map.flip(pos);
}
for (char &c : b) {
size_t pos = (int)c - 97;
map.flip(pos);
}
int num_of_odd_occurences = 0;
for (int i = 0; i < map.size(); ++i) {
if (map.test(i)) {
num_of_odd_occurences++;
}
}
if (diff == 0) {
return (num_of_odd_occurences == 2 || num_of_odd_occurences == 0);
} else {
return num_of_odd_occurences == 1;
}
}
/*
Fifth Apprach: No external DS
Provided by the book
Time: O(N)
Space: O(1)
*/
bool oneEditReplace(string a, string b) {
bool found_diff = false;
for (int i = 0; i < a.length(); ++i) {
if (a[i] != b[i]) {
if (found_diff) {
return false;
}
found_diff = true;
}
}
return true;
}
bool oneEditInsert(string smaller, string larger) {
int index_smaller = 0, index_larger = 0;
while (index_smaller < smaller.length() && index_larger < larger.length()) {
if (smaller[index_smaller] != larger[index_larger]) {
if (index_smaller != index_larger) {
return false;
}
index_larger++;
} else {
index_smaller++;
index_larger++;
}
}
return true;
}
bool oneAwayNoDS(string a, string b) {
int size_a = a.length();
int size_b = b.length();
int diff = abs(size_a - size_b);
if (diff > 1) {
return false;
}
if (diff == 0) {
return oneEditReplace(a, b);
} else if (size_a + 1 == size_b) {
return oneEditInsert(a, b);
} else {
return oneEditInsert(b, a);
}
}
/*
The logic of oneEditInsert and oneEditReplace are very similar. One thing to
discuss with an interviewer is the tradeoff between whether or not you should
merge them into one function or keep them separate. You can argue that it is
more readable if kept separate, but merging them into one funcion is better from
a code duplication perspective.
This last implemntation, is very similar to the
initial approach I had with regards to sorting the strings and parsing through
them. I gave up on that appraoch a little bit too quickly. If I had thought
about it a little bit moe I would have been able to coem to the same conclusion
as the book. Also, I overcomplicated it by not truly internalizign and
understanding the problem. There was no need to sort the strings, it foolishly
mad my program slower for no reason.
LESSONS:
Spend a little longer pondering the problem and potential solutions before
jumping ship to somethign else.
When evaluating a solution, think about whether you really need to do every
single step of the algorithm andmake sure that every step is neccesary or
providing value.
A good way to optimize is to try and solve the problem in constant space.
However, there is usually some tradeoff when optimizing for space and that is a
good thing to discuss with your interviewer before even attempting a solution
like that. However, inn this case, there is no real tradeoff, doing it in
constant space is strictly better
Bitsets are cool and useful for decreasing the number of bits a solution
takes up, although they don't have any effect on the time or space compelxity of
a solution.
*/
int main() {
cout << oneAwayNoDS("abcwdasda", "abcwdasda"); // 1
cout << oneAwayNoDS("abcwdasda", "abcwdsda"); // 1
cout << oneAwayNoDS("abcwdasda", "abcwqasda"); // 1
cout << oneAwayNoDS("abcwdasda", "abcwdwsda"); // 1
cout << oneAwayNoDS("abcwdasda", "abdasda"); // 0
cout << oneAwayNoDS("absda", "abcwdasda"); // 0
return 0;
}
|
C#
|
UTF-8
| 2,760
| 3.015625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ModbusSurvey
{
class NodeCOM:Node
{
/// <summary>
/// Список устройств узла
/// </summary>
//public List<Device> Devices;
/// <summary>
/// Последовательный порт
/// </summary>
public SerialPort serialPort { get; set; }
/// <summary>
/// Имя порта
/// </summary>
public PortName portName { get; set; }
/// <summary>
/// Скорость порта
/// </summary>
public BaudRate baudRate { get; set; }
/// <summary>
/// Четность порта
/// </summary>
public Parity parity { get; set; }
/// <summary>
/// Длина адреса порта
/// </summary>
public ushort dataBits { get; set; }
/// <summary>
/// Стоп-биты
/// </summary>
public StopBits stopBits { get; set; }
/// <summary>
/// Конструктор с настройками "по умолчанию"
/// </summary>
public NodeCOM()
{
Devices = new List<Device>();
//Характеристики узла
Name = "Узел";
//Характеристики COM порта
portName = PortName.COM4;
baudRate = BaudRate._9600;
parity = Parity.None;
dataBits = 8;
stopBits = StopBits.One;
}
/// <summary>
/// Создает последовательный порт с настройками объекта NodeCom
/// </summary>
public override void CreatePort()
{
if(serialPort == null)
serialPort = new SerialPort(portName.ToString(), (int)baudRate, parity, dataBits, stopBits);
}
public override void OpenPort()
{
if (serialPort.IsOpen == false)
{
serialPort.Open();
}
}
}
/// <summary>
/// Имя порта (COM1,COM2...)
/// </summary>
enum PortName
{
COM1,COM2,COM3,COM4,COM5,COM6,COM7,COM8,COM9,COM10,
COM11,COM12,COM13,COM14,COM15,COM16,COM17,COM18,COM19,COM20
}
/// <summary>
/// Сокрость COM порта
/// </summary>
enum BaudRate
{
_1200 = 1200,
_1800 = 1800,
_2400 = 2400,
_4800 = 4800,
_9600 = 9600,
_19200 = 19200,
_38400 = 38400,
_57600 = 57600,
_115200 = 115200
}
}
|
Python
|
UTF-8
| 2,045
| 2.71875
| 3
|
[] |
no_license
|
import psycopg2
import matplotlib.pyplot as plt
from inserts import *
def show_rating_graphic(player_id, control_type, conn):
with conn.cursor() as cursor:
query = """select distinct t2.game_date, sum(t1.rating_delta) over(order by t2.game_date) from
playerinrealgame t1 inner join realgame t2 on t1.real_game_id = t2.id
where t1.real_player_id = {} and t2.control_type='{}'
order by t2.game_date;""".format(str(player_id), control_type)
cursor.execute(query)
data = cursor.fetchall()
x = [e[0] for e in data]
y = [1000 + e[1] for e in data]
plt.plot(x, y)
plt.show()
def show_all_rating_graphics(control_type, case_data, conn):
with conn.cursor() as cursor:
real_rating = dict()
for i in range(len(case_data.player_ids)):
real_rating[case_data.player_ids[i]] = case_data.real_ratings[i]
query = 'select id from realplayer;'
cursor.execute(query)
ids = [e[0] for e in cursor.fetchall()]
fig, axes = plt.subplots(nrows=len(ids), ncols=1, figsize=(12, 4 * len(ids)))
for i in range(len(ids)):
player_id = ids[i]
query = """select distinct t2.game_date, sum(t1.rating_delta) over(order by t2.game_date) from
playerinrealgame t1 inner join realgame t2 on t1.real_game_id = t2.id
where t1.real_player_id = {} and t2.control_type='{}'
order by t2.game_date;""".format(str(player_id), control_type)
cursor.execute(query)
data = cursor.fetchall()
x = [e[0] for e in data]
y = [1000 + e[1] for e in data]
print(len(x))
name = get_attr('realplayer', ids[i], 'name', conn)
surname = get_attr('realplayer', ids[i], 'surname', conn)
axes[i].set_title(name + ' ' + surname + ', real rating: {}'.format(str(real_rating[player_id])))
axes[i].plot(x, y, c='#ff0000')
plt.show()
|
Java
|
UTF-8
| 4,268
| 2.234375
| 2
|
[
"MIT"
] |
permissive
|
package org.xwiki4.test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.xwiki4.BadLinks;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BadLinksTest {
private static Logger log = Logger.getLogger(BadLinksTest.class);
@Test
public void test01FindLinks() {
BadLinks badLinks = new BadLinks();
try {
badLinks.findLinks("https://odo.lv/xwiki/bin/download/Challenges/WebHome/linkchecker.html");
assertEquals(958, badLinks.getErrorCount());
} catch (Exception e) {
log.error(e);
}
}
@Test
public void test02FindLinksLocal() {
BadLinks badLinks = new BadLinks();
try {
File file = new File("src/test/resources/badlinks.html");
badLinks.findLinks(file);
log.debug(badLinks);
} catch (IOException e) {
e.printStackTrace();
}
assertEquals(18, badLinks.getErrorCount());
String badLinksString = "" //
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ label\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ label\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ bold label\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/ http://www.eclipse.org/gmt/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ https://precinso.ga https://precinso.ga https://precinso.ga\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ https://precinso.ga/ https://precinso.ga/ https://precinso.ga/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ https://svn.xwiki.org/ https://svn.xwiki.org/ https://svn.xwiki.org/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ https://www.bpmi.org/bpml-spec.htm https://www.bpmi.org/bpml-spec.htm https://www.bpmi.org/bpml-spec.htm\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ https://www.vardene.lv/index.php/Lokaliz%C4%93%C5%A1anas_rokasgr%C4%81mata/ https://www.vardene.lv/index.php/Lokaliz%c4%93%c5%a1anas_rokasgr%c4%81mata/ https://www.vardene.lv/index.php/Lokaliz%c4%93%c5%a1anas_rokasgr%c4%81mata/\n"
+ "http://localhost:8080/xwiki/bin/view/TestPageLinkChecker/SimplePage/ https://www.xwiki.org/xwiki/webjars/wiki%3Axwiki/xwiki-platform-tree-webjar/8.4.4/throbber https://www.xwiki.org/xwiki/webjars/wiki%3Axwiki/xwiki-platform-tree-webjar/8.4.4/throbber https://www.xwiki.org/xwiki/webjars/wiki%3Axwiki/xwiki-platform-tree-webjar/8.4.4/throbber\n";
assertEquals(badLinksString, badLinks.toString());
}
}
|
Markdown
|
UTF-8
| 559
| 2.515625
| 3
|
[] |
no_license
|
# Software Debouncing
## Purpose
To change the PWM of an LED with a button press on all boards.
## Theory
The pulse width modulation (PWM) is caused by changing the width of the signal sent by altering when the Timer interrupt. Since the timer interrupts when the value of the CRR# register is reached. That value of the CCR register can be changed each time a button is pressed by 10%. Then when the PWM reached 100% the PWM will then go to 0% and restart.
## Board Features
All boards work the same. When a button is pressed the Red LED will turn on/off.
|
Java
|
UTF-8
| 303
| 1.679688
| 2
|
[] |
no_license
|
package UnitTests;
import alg.ZeroOne;
public class Examples_1 {
public ZeroOne zeroOneArray_1[] = {
new ZeroOne(1),
new ZeroOne(1),
new ZeroOne(0),
new ZeroOne(1)
};
public ZeroOne zeroOneArray_2[] = {
new ZeroOne(1),
new ZeroOne(1),
new ZeroOne(0),
new ZeroOne(1)
};
}
|
C++
|
UTF-8
| 2,042
| 3.5
| 4
|
[] |
no_license
|
/// find_first_not_of
///
/// Searches through first range for the first element that does not belong the second input range.
/// This is very much like the C++ string find_first_not_of function.
///
/// Returns: The first iterator i in the range [first1, last1) such that for some
/// integer j in the range [first2, last2) the following conditions hold: !(*i == *j).
/// Returns last1 if no such iterator is found.
///
/// Complexity: At most '(last1 - first1) * (last2 - first2)' applications of the
/// corresponding predicate.
///
template <class ForwardIterator1, class ForwardIterator2>
ForwardIterator1
find_first_not_of(ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2)
{
for(; first1 != last1; ++first1)
{
if(eastl::find(first2, last2, *first1) == last2)
break;
}
return first1;
}
/// find_first_not_of
///
/// Searches through first range for the first element that does not belong the second input range.
/// This is very much like the C++ string find_first_not_of function.
///
/// Returns: The first iterator i in the range [first1, last1) such that for some
/// integer j in the range [first2, last2) the following conditions hold: pred(*i, *j) == false.
/// Returns last1 if no such iterator is found.
///
/// Complexity: At most '(last1 - first1) * (last2 - first2)' applications of the
/// corresponding predicate.
///
template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
inline ForwardIterator1
find_first_not_of(ForwardIterator1 first1, ForwardIterator1 last1,
ForwardIterator2 first2, ForwardIterator2 last2,
BinaryPredicate predicate)
{
typedef typename eastl::iterator_traits<ForwardIterator1>::value_type value_type;
for(; first1 != last1; ++first1)
{
if(eastl::find_if(first2, last2, eastl::bind1st<BinaryPredicate, value_type>(predicate, *first1)) == last2)
break;
}
return first1;
}
|
Java
|
UTF-8
| 370
| 2.609375
| 3
|
[] |
no_license
|
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
class Main {
public static void main(String[] args) throws IOException {
long result = Files.lines(Paths.get("D:\\Downloads\\dataset_91065.txt")).mapToInt(Integer::parseInt).takeWhile(x -> x > 0).filter(x -> x % 2 == 0).count();
System.out.println(result);
}
}
|
Java
|
UTF-8
| 3,544
| 2.390625
| 2
|
[] |
no_license
|
package it.unicam.cs.pa.jbudget105181.Model.Transaction;
import it.unicam.cs.pa.jbudget105181.Model.Account.AccountType;
import it.unicam.cs.pa.jbudget105181.Model.Account.IAccount;
import it.unicam.cs.pa.jbudget105181.Model.IFactory;
import it.unicam.cs.pa.jbudget105181.Model.Movement.IMovement;
import it.unicam.cs.pa.jbudget105181.Model.Movement.MovementType;
import it.unicam.cs.pa.jbudget105181.Model.Tag.ITag;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
class TransazioneTest {
private IMovement movimento1;
private IMovement movimento2;
private IMovement movimento3;
private ITransazione transazione1;
private IAccount a;
@BeforeEach
void createTransaction(){
this.a= IFactory.generateAccount(1,"Account","1", AccountType.ASSETS,500.0);
List<ITag> lTag=new ArrayList<>();
this.transazione1=IFactory.generateTransaction(1, LocalDate.now(),lTag,"ciao",true);
this.movimento1= IFactory.generateMovement(1,"Movimento", MovementType.CREDIT,50.0,a, lTag,transazione1);
this.movimento2= IFactory.generateMovement(1,"Movimento", MovementType.CREDIT,150.0,a, lTag,IFactory.generateTransaction(1, LocalDate.now(),lTag,"ciao",true));
this.movimento3= IFactory.generateMovement(1,"Movimento", MovementType.DEBIT,50.0,a, lTag,IFactory.generateTransaction(1, LocalDate.now(),lTag,"ciao",true));
}
@Test
void addMovement() {
assertTrue(transazione1.getNumMov()==0);
transazione1.addMovement(movimento1);
transazione1.addMovement(movimento2);
assertTrue(transazione1.getNumMov()==2);
}
@Test
void movements() {
transazione1.addMovement(movimento1);
transazione1.addMovement(movimento2);
List<IMovement> lMovement= transazione1.movements();
assertFalse(lMovement.isEmpty());
assertTrue(lMovement.contains(movimento1));
}
@Test
void addTag() {
transazione1.addTag(IFactory.generateTag("Sport","Tennis"));
assertTrue(transazione1.tags().size()==1);
}
@Test
void removeTag(){
ITag t1= IFactory.generateTag("Sport","Tennis");
transazione1.addTag(t1);
transazione1.addTag(IFactory.generateTag("Sport","Calcio"));
assertTrue(transazione1.tags().size()==2);
transazione1.removeTag(t1);
assertTrue(transazione1.tags().size()==1);
}
@Test
void removeMovement() {
transazione1.addMovement(movimento1);
transazione1.addMovement(movimento2);
transazione1.removeMovement(movimento1);
assertTrue(transazione1.getNumMov()==1);
}
@Test
void adjustTotalCost() {
assertTrue(transazione1.getTotalAmount()==0);
transazione1.addMovement(movimento1);
transazione1.addMovement(movimento2);
assertTrue(transazione1.getTotalAmount()!=0);
}
@Test
void getPagata(){
LocalDate dataAttuale= LocalDate.now();
List<ITag> lTags= new ArrayList<>();
ITransazione t1= IFactory.generateTransaction(1, dataAttuale,lTags,"Account1",!dataAttuale.isAfter(LocalDate.now()));
LocalDate dataFutura= LocalDate.of(2021,10,6);
ITransazione t2= IFactory.generateTransaction(1, dataAttuale,lTags,"Account1",!dataFutura.isAfter(LocalDate.now()));
assertTrue(t1.getPagata());
assertFalse(t2.getPagata());
}
}
|
C++
|
SHIFT_JIS
| 3,616
| 2.625
| 3
|
[] |
no_license
|
//========================================================
//
// [Gl~[̏]:
//
//
//========================================================
#include "enemy.h"
#include "manager.h"
#include "renderer.h"
#include "scene.h"
#include "bullet.h"
//ÓIoϐ
LPDIRECT3DTEXTURE9 CEnemy::m_apTexture[MAX_TEX] = {};
CEnemy::ENEMYTYPE CEnemy::m_EnemyType = CEnemy::ENEMYTYPE_ALPHA;
int g_nData;
//fXgN^
CEnemy::CEnemy()
{
}
//fXgN^
CEnemy::~CEnemy()
{
}
//G̃eNX`[h
HRESULT CEnemy::Load(void)
{
LPDIRECT3DDEVICE9 pDevice;
pDevice = CManager::GetRenderer()->GetDevice();
//eNX`̐
switch (m_EnemyType)
{
case ENEMYTYPE_ALPHA:
D3DXCreateTextureFromFile(pDevice, "data\\TEXTURE\\robo001.png", &m_apTexture[0]);
break;
case ENEMYTYPE_BETA:
D3DXCreateTextureFromFile(pDevice, "data\\TEXTURE\\robo000.png", &m_apTexture[1]);
break;
case ENEMYTYPE_BOSS:
D3DXCreateTextureFromFile(pDevice, "data\\TEXTURE\\boss003.png", &m_apTexture[2]);
break;
}
return S_OK;
}
//G̃eNX`A[h
void CEnemy::Unload(void)
{
for (int nCnt = 0; nCnt < MAX_TEX; nCnt++)
{
if (m_apTexture[nCnt] != NULL)
{
m_apTexture[nCnt]->Release();
m_apTexture[nCnt] = NULL;
}
}
}
//G̐
CEnemy *CEnemy::Create(D3DXVECTOR3 pos, D3DXVECTOR2 size, D3DXVECTOR3 move, ENEMYTYPE type)
{
for (int nCnt = 0; nCnt < MAX_TEX; nCnt++)
{
CEnemy *pEnemy;
pEnemy = new CEnemy;
pEnemy->Init(pos, size, move,type);
pEnemy->BindTexture(m_apTexture[nCnt]);
return pEnemy;
}
return S_OK;
}
void CEnemy::SetEneType(ENEMYTYPE type)
{
m_EnemyType = type;
}
CEnemy::ENEMYTYPE CEnemy::GetEneType(void)
{
return m_EnemyType;
}
//G̏
HRESULT CEnemy::Init(D3DXVECTOR3 pos, D3DXVECTOR2 size, D3DXVECTOR3 move, ENEMYTYPE type)
{
CScene2D::Init(pos,size);
m_move = move;
//IuWFNg̎
SetObjType(CScene::OBJTYPE_ENEMY);
return S_OK;
}
//G̏I
void CEnemy::Uninit(void)
{
CScene2D::Uninit();
}
//G̍XV
void CEnemy::Update(void)
{
CScene2D::Update();
//ϐ錾
D3DXVECTOR3 pos;
pos = GetPosition();
m_nCounter++;
m_nMoveCnt++;
//D3DXVECTOR3 Angelmove;
//e̗
D3DXVECTOR3 Angelmove;
float fAngel;
fAngel = (float)(m_fCntGame) / 100.0f;
Angelmove.x = sinf(fAngel) * 5;
Angelmove.y = cosf(fAngel) * 5;
//G̈ʒu
pos -= m_move;
//G̈ړ
if (pos.x + 30 / 2.0f >= SCREEN_WIDTH)
{
m_move.x *= -1;
}
if (pos.x - 30 / 2.0f <= 0)
{
m_move.x *= -1;
}
//e̊pxύX
m_fCntGame += 3.0f;
//G̈ړʌ
//g_moveEnemy.x += (0.0f - g_moveEnemy.x) * 0.02f;
g_moveEnemy.y -= (0.0f + g_moveEnemy.y) * 0.01f;
//Ge̔
if (m_nCounter % 100 == 0)
{
for (int nCnt = 0; nCnt < 20; nCnt++)
{
//CBullet::Create(pos, D3DXVECTOR3(Angelmove.x, Angelmove.y, 0.0f), D3DXVECTOR2(15, 15), D3DXVECTOR3(Angelmove.x, Angelmove.y, 0.0f), CBullet::BULLET_ENEMY);
//CBullet::Create(pos, D3DXVECTOR3(sinf(D3DX_PI * 1.0f * ((float)nCnt / ((float)10))) * 3, cosf(D3DX_PI * 1.0f * ((float)nCnt / (float)10)) * 3, 0), D3DXVECTOR2(15, 15), D3DXVECTOR3(Angelmove.x, Angelmove.y, 0.0f), CBullet::BULLET_ENEMY);
}
}
if (m_nCounter % 70 == 0)
{
CBullet::BCreate(pos, 314);
CBullet::BCreate(pos, -157);
CBullet::BCreate(pos, 157);
CBullet::BCreate(pos, 78);
CBullet::BCreate(pos, -78);
CBullet::BCreate(pos, 235);
CBullet::BCreate(pos, -235);
CBullet::BCreate(pos, 0);
}
SetPosition(pos);
}
//G̕`揈
void CEnemy::Draw(void)
{
CScene2D::Draw();
}
|
Python
|
UTF-8
| 5,105
| 2.5625
| 3
|
[] |
no_license
|
import unittest
from iogen.constraints import verify_types
from iogen.dsl.simple import get_list_dsl
from iogen.io import test_io, generate_interesting
def generate_examples(*args, **kwargs):
kwargs.update(
{
"num_examples": kwargs.get("num_examples", 10),
"timeout": kwargs.get("timeout", 10),
"min_bound": kwargs.get("min_bound", 0),
"max_bound": kwargs.get("max_bound", 10),
"min_variance": kwargs.get("min_variance", 1.0),
"maxv": kwargs.get("maxv", 10),
"max_io_len": kwargs.get("max_io_len", 10),
}
)
language = get_list_dsl(kwargs["max_bound"])
return generate_interesting(language, *args, **kwargs)
class TestListDSL(unittest.TestCase):
def test_list_head(self):
source = "a <- [int] | b <- head a"
d = generate_examples(source)
program = d["program"]
verify_types(d["io_pairs"], sig=([int], int))
test_io(program, (([3, 5, 4, 7, 5],), 3))
self.assertEqual(program.bounds, [(0, 10)])
def test_list_tail(self):
source = "a <- [int] | b <- tail a"
d = generate_examples(source)
program = d["program"]
verify_types(d["io_pairs"], sig=([int], [int]))
test_io(program, (([3, 5, 4, 7, 5],), [5, 4, 7, 5]))
self.assertEqual(program.bounds, [(0, 10)])
def test_list_count_head_in_tail(self):
"""
count (head xs) (tail xs)
"""
source = "a <- [int] | b <- tail a | c <- head a | d <- count c b"
d = generate_examples(source)
program = d["program"]
verify_types(d["io_pairs"], sig=([int], int))
test_io(program, (([3, 5, 4, 7, 5],), 0))
test_io(program, (([5, 4, 7, 5],), 1))
test_io(program, (([7, 4, 7, 8, 21, 1, 7, 2, 7, 5],), 3))
self.assertEqual(program.bounds, [(0, 10)])
def test_list_count_len_in_tail(self):
"""
count (len xs) (tail xs)
"""
source = "a <- [int] | b <- tail a | c <- len a | d <- count c b"
d = generate_examples(source)
program = d["program"]
verify_types(d["io_pairs"], sig=([int], int))
test_io(program, (([3, 5, 4, 7, 5],), 2))
test_io(program, (([5, 4, 7, 5],), 1))
test_io(program, (([7, 4, 7, 8, 21, 1, 7, 2, 7, 5],), 0))
self.assertEqual(program.bounds, [(0, 10)])
def test_list_count_last_in_tail(self):
"""
count (last xs) (tail xs)
"""
source = "a <- [int] | b <- tail a | c <- last a | d <- count c b"
d = generate_examples(source)
program = d["program"]
verify_types(d["io_pairs"], sig=([int], int))
test_io(program, (([3, 5, 4, 7, 5],), 2))
self.assertEqual(program.bounds, [(0, 10)])
def test_list_count_len_tail_in_tail(self):
"""
count (len (tail xs)) (tail xs)
"""
source = "a <- [int] | b <- tail a | c <- len b | d <- count c b"
d = generate_examples(source)
program = d["program"]
verify_types(d["io_pairs"], sig=([int], int))
test_io(program, (([3, 5, 4, 7, 5],), 1))
self.assertEqual(program.bounds, [(0, 10)])
def test_list_count_head_tail_in_tail(self):
"""
count (head (tail xs)) (tail xs)
"""
source = "a <- [int] | b <- tail a | c <- head b | d <- count c b"
d = generate_examples(source)
program = d["program"]
verify_types(d["io_pairs"], sig=([int], int))
test_io(program, (([3, 5, 4, 7, 5],), 2))
self.assertEqual(program.bounds, [(0, 10)])
def test_list_count_last_tail_in_tail(self):
"""
count (last (tail xs)) (tail xs)
"""
source = "a <- [int] | b <- tail a | c <- last b | d <- count c b"
d = generate_examples(source)
program = d["program"]
verify_types(d["io_pairs"], sig=([int], int))
test_io(program, (([3, 5, 4, 7, 5],), 2))
self.assertEqual(program.bounds, [(0, 10)])
def test_list_count_head_tail_tail_tail(self):
"""
count (head (tail (tail (tail xs)))) xs
"""
source = "a <- [int] | b <- tail a | c <- tail b | d <- tail c | e <- head d | f <- count e a"
d = generate_examples(source, min_io_len=3)
program = d["program"]
verify_types(d["io_pairs"], sig=([int], int))
test_io(program, (([3, 5, 4, 7, 5],), 1))
self.assertEqual(program.bounds, [(0, 10)])
def test_list_count_n(self):
source = "a <- int | b <- [int] | c <- count a b"
d = generate_examples(source, min_variance=3.5)
program = d["program"]
verify_types(d["io_pairs"], sig=([int, [int]], int))
test_io(program, ((3, [3, 5, 4, 7, 5]), 1))
self.assertEqual(program.bounds, [(0, 10), (0, 10)])
def test_fail_bad_min_bound(self):
source = "a <- [int] | b <- head a"
with self.assertRaises(AttributeError):
generate_examples(source, min_bound=100)
if __name__ == "__main__":
unittest.main()
|
Python
|
UTF-8
| 1,431
| 2.578125
| 3
|
[] |
no_license
|
import datetime as dt
from functools import wraps
from flask_restful import abort, request
import jwt
from config import Config
def validate_token(token: str):
if not token:
abort(401, detail="Token is missing", status=401, ok=False)
try:
token_data = jwt.decode(
token, key=Config.SECRET_KEY, algorithms=Config.JWT_ALGORITHM
)
except jwt.ExpiredSignatureError:
abort(401, detail="Token is expired", status=401, ok=False)
except jwt.InvalidSignatureError:
abort(401, detail="Token has invalid signature", status=401, ok=False)
except jwt.DecodeError:
abort(401, detail="Unable to decode token", status=401, ok=False)
else:
return token_data
def is_valid_token(token: str):
try:
jwt.decode(
token, key=Config.SECRET_KEY, algorithms=Config.JWT_ALGORITHM
)
except Exception:
return False
else:
return True
def token_required(func):
@wraps(func)
def inner(*args, **kwargs):
token = request.args.get("token")
token_data = validate_token(token)
return func(*args, payload=token_data, **kwargs)
return inner
def create_token(payload) -> str:
now = dt.datetime.utcnow()
payload["iat"] = now
payload["exp"] = now + dt.timedelta(seconds=Config.TOKEN_EXPIRATION)
return jwt.encode(payload, Config.SECRET_KEY, Config.JWT_ALGORITHM)
|
Shell
|
UTF-8
| 2,475
| 2.90625
| 3
|
[] |
no_license
|
# Lines configured by zsh-newuser-install
HISTFILE=~/.histfile
HISTSIZE=10000
SAVEHIST=1000
X=$(which most 2> /dev/null)
[[ $? = 1 ]] && PAGER=less || PAGER=most
export PAGER
export EDITOR=vim
export JAVA_HOME=/usr/lib/jvm/default-java
alias tmux="TERM=xterm-256color tmux"
setopt appendhistory autocd nomatch
unsetopt beep notify
bindkey -e
# oh-my-zsh rebinds this to 'cd ..' which is daft
bindkey '\e.' insert-last-word
# it also enables history sharing between shells (which sucks in tmux!)
unsetopt share_history
# End of lines configured by zsh-newuser-install
# The following lines were added by compinstall
zstyle :compinstall filename ${HOME}.zshrc
autoload -Uz compinit
compinit
# End of lines added by compinstall
#keychain ~/.ssh/id_dsa &>/dev/null
#. ~/.keychain/*-sh
# use rsync to resume partial scp transfers
alias scpr="rsync --partial --progress --rsh=ssh"
export PYTHONSTARTUP=$HOME/.pystartup
export PYTHONPATH=$PYTHONPATH:~/python/libs
function attach() {
if (( $# != 0 )); then
tmux attach-session -t $@
else
echo "usage: attach <tmux session name>"
fi
}
function tlist() {
tmux list-sessions
}
function new_session() {
create_session $@
tmux attach-session -t$1
}
function create_session() {
if (( $# >= 1 )); then
SESSION_NAME=$1
NUM_WINDOWS=${2:-0}
tmux -2 new-session -d -s $SESSION_NAME -n zsh
if [[ $NUM_WINDOWS -gt 1 ]]; then
for i in $(seq 2 $NUM_WINDOWS); do
tmux new-window -t$SESSION_NAME:$i
done
fi
tmux select-window -t$SESSION_NAME:0
else
echo "usage: new_session <tmux session name>"
fi
}
function hg_prompt_info {
st=$(hg status 2> /dev/null) || return
mod=$(hg prompt "{status|modified}" 2> /dev/null)
pre=$(hg prompt "{branch}{-->[+{outgoing|count}]}" 2> /dev/null)
echo -n $ZSH_THEME_GIT_PROMPT_PREFIX | sed 's/git/hg/'
echo -n $pre
if [[ $mod = "!" ]]; then
echo $ZSH_THEME_GIT_PROMPT_DIRTY
else
echo $ZSH_THEME_GIT_PROMPT_CLEAN
fi
}
alias vipython="python ~/src/ipython/ipython.py"
[[ -f ~/src/nvm/nvm.sh ]] && . ~/src/nvm/nvm.sh
[[ -f ~/.rvm/scripts/rvm ]] && . ~/.rvm/scripts/rvm
alias gcp="git checkout -"
alias galias="alias | grep git | egrep -v \"(svn|galias)\" | sed \"s/\(\w\)='\?\([^']*\)'\?$/\1\t= \2/\""
alias halias="alias | grep hg | egrep -v \"(halias)\" | sed \"s/\(\w\)='\?\([^']*\)'\?$/\1\t= \2/\""
|
C++
|
UTF-8
| 689
| 3.59375
| 4
|
[] |
no_license
|
#include <iostream>
struct base {
virtual ~base() = default;
virtual void print() const = 0;
};
struct derived : public base {
virtual void print() const {
std::cout << "hello world\n";
}
};
struct test {
void print() const {
std::cout << "testing\n";
}
};
struct stuff {
void print() const {
std::cout << "testing again\n";
}
};
// polymorphism
void polymorphism(const base& b) {
b.print();
}
// generic programming
template<typename T>
void generic(const T& t) {
t.print();
}
int main() {
polymorphism(derived{});
std::cout << "----\n";
generic(derived{});
generic(test{});
generic(stuff{});
}
|
Java
|
UTF-8
| 27,848
| 2.21875
| 2
|
[
"BSD-2-Clause"
] |
permissive
|
//
// FilePattern.java
//
/*
OME Bio-Formats package for reading and converting biological file formats.
Copyright (C) 2005-@year@ UW-Madison LOCI and Glencoe Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.formats;
import java.io.File;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import loci.common.DataTools;
import loci.common.Location;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* FilePattern is a collection of methods for handling file patterns, a way of
* succinctly representing a collection of files meant to be part of the same
* data series.
*
* Examples:
* <ul>
* <li>C:\data\BillM\sdub<1-12>.pic</li>
* <li>C:\data\Kevin\80<01-59>0<2-3>.pic</li>
* <li>/data/Josiah/cell-Z<0-39>.C<0-1>.tiff</li>
* </ul>
*
* <dl><dt><b>Source code:</b></dt>
* <dd><a href="http://trac.openmicroscopy.org.uk/ome/browser/bioformats.git/components/bio-formats/src/loci/formats/FilePattern.java">Trac</a>,
* <a href="http://git.openmicroscopy.org/?p=bioformats.git;a=blob;f=components/bio-formats/src/loci/formats/FilePattern.java;hb=HEAD">Gitweb</a></dd></dl>
*
* @author Curtis Rueden ctrueden at wisc.edu
*/
public class FilePattern {
// -- Constants --
private static final Logger LOGGER =
LoggerFactory.getLogger(FilePattern.class);
// -- Fields --
/** The file pattern string. */
private String pattern;
/** The validity of the file pattern. */
private boolean valid;
/** Error message generated during file pattern construction. */
private String msg;
/** Indices into the pattern indicating the start of a numerical block. */
private int[] startIndex;
/** Indices into the pattern indicating the end of a numerical block. */
private int[] endIndex;
/** List of pattern blocks for this file pattern. */
private FilePatternBlock[] blocks;
/** File listing for this file pattern. */
private String[] files;
/** Whether or not this FilePattern represents a regular expression. */
private boolean isRegex = false;
// -- Constructors --
/** Creates a pattern object using the given file as a template. */
public FilePattern(Location file) { this(FilePattern.findPattern(file)); }
/**
* Creates a pattern object using the given
* filename and directory path as a template.
*/
public FilePattern(String name, String dir) {
this(FilePattern.findPattern(name, dir));
}
/** Creates a pattern object for files with the given pattern string. */
public FilePattern(String pattern) {
this.pattern = pattern;
valid = false;
if (pattern == null) {
msg = "Null pattern string.";
return;
}
// locate numerical blocks
int len = pattern.length();
List<Integer> lt = new ArrayList<Integer>(len);
List<Integer> gt = new ArrayList<Integer>(len);
int left = -1;
while (true) {
left = pattern.indexOf(FilePatternBlock.BLOCK_START, left + 1);
if (left < 0) break;
lt.add(new Integer(left));
}
int right = -1;
while (true) {
right = pattern.indexOf(FilePatternBlock.BLOCK_END, right + 1);
if (right < 0) break;
gt.add(new Integer(right));
}
// assemble numerical block indices
int num = lt.size();
if (num != gt.size()) {
msg = "Mismatched numerical block markers.";
return;
}
startIndex = new int[num];
endIndex = new int[num];
for (int i=0; i<num; i++) {
int val = lt.get(i);
if (i > 0 && val < endIndex[i - 1]) {
msg = "Bad numerical block marker order.";
return;
}
startIndex[i] = val;
val = gt.get(i);
if (val <= startIndex[i]) {
msg = "Bad numerical block marker order.";
return;
}
endIndex[i] = val + 1;
}
// parse numerical blocks
blocks = new FilePatternBlock[num];
for (int i=0; i<num; i++) {
String block = pattern.substring(startIndex[i], endIndex[i]);
blocks[i] = new FilePatternBlock(block);
}
// build file listing
List<String> fileList = new ArrayList<String>();
buildFiles("", num, fileList);
files = fileList.toArray(new String[0]);
if (files.length == 0 && new Location(pattern).exists()) {
files = new String[] {pattern};
}
valid = true;
}
// -- FilePattern API methods --
/** Returns whether or not this pattern is a regular expression. */
public boolean isRegex() {
return isRegex;
}
/** Gets the file pattern string. */
public String getPattern() { return pattern; }
/** Gets whether the file pattern string is valid. */
public boolean isValid() { return valid; }
/** Gets the file pattern error message, if any. */
public String getErrorMessage() { return msg; }
/** Gets a listing of all files matching the given file pattern. */
public String[] getFiles() { return files; }
public String[][] getElements() {
String[][] elements = new String[blocks.length][];
for (int i=0; i<elements.length; i++) {
elements[i] = blocks[i].getElements();
}
return elements;
}
public int[] getCount() {
int[] count = new int[blocks.length];
for (int i=0; i<count.length; i++) {
count[i] = blocks[i].getElements().length;
}
return count;
}
/** Gets the specified numerical block. */
public String getBlock(int i) {
if (i < 0 || i >= startIndex.length) return null;
return pattern.substring(startIndex[i], endIndex[i]);
}
/** Gets each numerical block. */
public String[] getBlocks() {
String[] s = new String[startIndex.length];
for (int i=0; i<s.length; i++) s[i] = getBlock(i);
return s;
}
/** Gets the pattern's text string before any numerical ranges. */
public String getPrefix() {
int s = pattern.lastIndexOf(File.separator) + 1;
int e;
if (startIndex.length > 0) e = startIndex[0];
else {
int dot = pattern.lastIndexOf(".");
e = dot < s ? pattern.length() : dot;
}
return s <= e ? pattern.substring(s, e) : "";
}
/** Gets the pattern's text string after all numerical ranges. */
public String getSuffix() {
return endIndex.length > 0 ?
pattern.substring(endIndex[endIndex.length - 1]) : pattern;
}
/** Gets the pattern's text string before the given numerical block. */
public String getPrefix(int i) {
if (i < 0 || i >= startIndex.length) return null;
int s = i > 0 ? endIndex[i - 1] :
(pattern.lastIndexOf(File.separator) + 1);
int e = startIndex[i];
return s <= e ? pattern.substring(s, e) : null;
}
/** Gets the pattern's text string before each numerical block. */
public String[] getPrefixes() {
String[] s = new String[startIndex.length];
for (int i=0; i<s.length; i++) s[i] = getPrefix(i);
return s;
}
// -- Utility methods --
/**
* Identifies the group pattern from a given file within that group.
* @param path The file path to use as a template for the match.
*/
public static String findPattern(String path) {
return findPattern(new Location(path));
}
/**
* Identifies the group pattern from a given file within that group.
* @param file The file to use as a template for the match.
*/
public static String findPattern(Location file) {
return findPattern(file.getName(), file.getAbsoluteFile().getParent());
}
/**
* Identifies the group pattern from a given file within that group.
* @param file The file to use as a template for the match.
*/
public static String findPattern(File file) {
return findPattern(file.getName(), file.getAbsoluteFile().getParent());
}
/**
* Identifies the group pattern from a given file within that group.
* @param name The filename to use as a template for the match.
* @param dir The directory in which to search for matching files.
*/
public static String findPattern(String name, String dir) {
if (dir == null) dir = ""; // current directory
else if (!dir.equals("") && !dir.endsWith(File.separator)) {
dir += File.separator;
}
Location dirFile = new Location(dir.equals("") ? "." : dir);
// list files in the given directory
Location[] f = dirFile.listFiles();
if (f == null) return null;
String[] nameList = new String[f.length];
for (int i=0; i<nameList.length; i++) nameList[i] = f[i].getName();
return findPattern(name, dir, nameList);
}
/**
* Identifies the group pattern from a given file within that group.
* @param name The filename to use as a template for the match.
* @param dir The directory prefix to use for matching files.
* @param nameList The names through which to search for matching files.
*/
public static String findPattern(String name, String dir, String[] nameList) {
return findPattern(name, dir, nameList, null);
}
/**
* Identifies the group pattern from a given file within that group.
* @param name The filename to use as a template for the match.
* @param dir The directory prefix to use for matching files.
* @param nameList The names through which to search for matching files.
* @param excludeAxes The list of axis types which should be excluded from the
* pattern.
*/
public static String findPattern(String name, String dir, String[] nameList,
int[] excludeAxes)
{
if (excludeAxes == null) excludeAxes = new int[0];
if (dir == null) dir = ""; // current directory
else if (!dir.equals("") && !dir.endsWith(File.separator)) {
dir += File.separator;
}
// compile list of numerical blocks
int len = name.length();
int bound = (len + 1) / 2;
int[] indexList = new int[bound];
int[] endList = new int[bound];
int q = 0;
boolean num = false;
int ndx = -1, e = 0;
for (int i=0; i<len; i++) {
char c = name.charAt(i);
if (c >= '0' && c <= '9') {
if (num) e++;
else {
num = true;
ndx = i;
e = ndx + 1;
}
}
else if (num) {
num = false;
indexList[q] = ndx;
endList[q] = e;
q++;
}
}
if (num) {
indexList[q] = ndx;
endList[q] = e;
q++;
}
// analyze each block, building pattern as we go
StringBuffer sb = new StringBuffer(dir);
for (int i=0; i<q; i++) {
int last = i > 0 ? endList[i - 1] : 0;
String prefix = name.substring(last, indexList[i]);
int axisType = AxisGuesser.getAxisType(prefix);
if (DataTools.containsValue(excludeAxes, axisType)) {
sb.append(name.substring(last, endList[i]));
continue;
}
sb.append(prefix);
String pre = name.substring(0, indexList[i]);
String post = name.substring(endList[i]);
NumberFilter filter = new NumberFilter(pre, post);
String[] list = matchFiles(nameList, filter);
if (list == null || list.length == 0) return null;
if (list.length == 1) {
// false alarm; this number block is constant
sb.append(name.substring(indexList[i], endList[i]));
continue;
}
boolean fix = true;
for (String s : list) {
if (s.length() != len) {
fix = false;
break;
}
}
if (fix) {
// tricky; this fixed-width block could represent multiple numberings
int width = endList[i] - indexList[i];
// check each character for duplicates
boolean[] same = new boolean[width];
for (int j=0; j<width; j++) {
same[j] = true;
int jx = indexList[i] + j;
char c = name.charAt(jx);
for (String s : list) {
if (s.charAt(jx) != c) {
same[j] = false;
break;
}
}
}
// break down each sub-block
int j = 0;
while (j < width) {
int jx = indexList[i] + j;
if (same[j]) {
sb.append(name.charAt(jx));
j++;
}
else {
while (j < width && !same[j]) j++;
String p = findPattern(name, nameList, jx, indexList[i] + j, "");
char c = indexList[i] > 0 ? name.charAt(indexList[i] - 1) : '.';
// check if this block represents the series axis
if (p == null && c != 'S' && c != 's' && c != 'E' && c != 'e') {
// unable to find an appropriate breakdown of numerical blocks
return null;
}
else if (p == null) {
sb.append(name.charAt(endList[i] - 1));
}
else sb.append(p);
}
}
}
else {
// assume variable-width block represents only one numbering
BigInteger[] numbers = new BigInteger[list.length];
for (int j=0; j<list.length; j++) {
numbers[j] = filter.getNumber(list[j]);
}
Arrays.sort(numbers);
String bounds = getBounds(numbers, false);
if (bounds == null) return null;
sb.append(bounds);
}
}
sb.append(q > 0 ? name.substring(endList[q - 1]) : name);
for (int i=0; i<sb.length(); i++) {
if (sb.charAt(i) == '\\') {
sb.insert(i, '\\');
i++;
}
}
return sb.toString();
}
/**
* Generate a pattern from a list of file names.
* The pattern generated will be a regular expression.
*
* Currently assumes that all file names are in the same directory.
*/
public static String findPattern(String[] names) {
String dir =
names[0].substring(0, names[0].lastIndexOf(File.separator) + 1);
StringBuffer pattern = new StringBuffer();
pattern.append(Pattern.quote(dir));
for (int i=0; i<names.length; i++) {
pattern.append("(?:");
String name =
names[i].substring(names[i].lastIndexOf(File.separator) + 1);
pattern.append(Pattern.quote(name));
pattern.append(")");
if (i < names.length - 1) {
pattern.append("|");
}
}
return pattern.toString();
}
public static String[] findSeriesPatterns(String base) {
Location file = new Location(base).getAbsoluteFile();
Location parent = file.getParentFile();
String[] list = parent.list(true);
return findSeriesPatterns(base, parent.getAbsolutePath(), list);
}
public static String[] findSeriesPatterns(String base, String dir,
String[] nameList)
{
String baseSuffix = base.substring(base.lastIndexOf(File.separator) + 1);
int dot = baseSuffix.indexOf(".");
if (dot < 0) baseSuffix = "";
else baseSuffix = baseSuffix.substring(dot + 1);
ArrayList<String> patterns = new ArrayList<String>();
int[] exclude = new int[] {AxisGuesser.S_AXIS};
for (String name : nameList) {
String pattern = findPattern(name, dir, nameList, exclude);
if (pattern == null) continue;
int start = pattern.lastIndexOf(File.separator) + 1;
if (start < 0) start = 0;
String patternSuffix = pattern.substring(start);
dot = patternSuffix.indexOf(".");
if (dot < 0) patternSuffix = "";
else patternSuffix = patternSuffix.substring(dot + 1);
String checkPattern = findPattern(name, dir, nameList);
String[] checkFiles = new FilePattern(checkPattern).getFiles();
if (!patterns.contains(pattern) && (!new Location(pattern).exists() ||
base.equals(pattern)) && patternSuffix.equals(baseSuffix) &&
DataTools.indexOf(checkFiles, base) >= 0)
{
patterns.add(pattern);
}
}
String[] s = patterns.toArray(new String[patterns.size()]);
Arrays.sort(s);
return s;
}
// -- Utility helper methods --
/** Recursive method for parsing a fixed-width numerical block. */
private static String findPattern(String name,
String[] nameList, int ndx, int end, String p)
{
if (ndx == end) return p;
for (int i=end-ndx; i>=1; i--) {
NumberFilter filter = new NumberFilter(
name.substring(0, ndx), name.substring(ndx + i));
String[] list = matchFiles(nameList, filter);
BigInteger[] numbers = new BigInteger[list.length];
for (int j=0; j<list.length; j++) {
numbers[j] = new BigInteger(list[j].substring(ndx, ndx + i));
}
Arrays.sort(numbers);
String bounds = getBounds(numbers, true);
if (bounds == null) continue;
String pat = findPattern(name, nameList, ndx + i, end, p + bounds);
if (pat != null) return pat;
}
// no combination worked; this parse path is infeasible
return null;
}
/**
* Gets a string containing start, end and step values
* for a sorted list of numbers.
*/
private static String getBounds(BigInteger[] numbers, boolean fixed) {
if (numbers.length < 2) return null;
BigInteger b = numbers[0];
BigInteger e = numbers[numbers.length - 1];
BigInteger s = numbers[1].subtract(b);
if (s.equals(BigInteger.ZERO)) {
// step size must be positive
return null;
}
for (int i=2; i<numbers.length; i++) {
if (!numbers[i].subtract(numbers[i - 1]).equals(s)) {
// step size is not constant
return null;
}
}
String sb = b.toString();
String se = e.toString();
StringBuffer bounds = new StringBuffer("<");
if (fixed) {
int zeroes = se.length() - sb.length();
for (int i=0; i<zeroes; i++) bounds.append("0");
}
bounds.append(sb);
bounds.append("-");
bounds.append(se);
if (!s.equals(BigInteger.ONE)) {
bounds.append(":");
bounds.append(s);
}
bounds.append(">");
return bounds.toString();
}
/** Filters the given list of filenames according to the specified filter. */
private static String[] matchFiles(String[] inFiles, NumberFilter filter) {
List<String> list = new ArrayList<String>();
for (int i=0; i<inFiles.length; i++) {
if (filter.accept(inFiles[i])) list.add(inFiles[i]);
}
return list.toArray(new String[0]);
}
// -- Helper methods --
/** Recursive method for building filenames for the file listing. */
private void buildFiles(String prefix, int ndx, List<String> fileList) {
if (blocks.length == 0) {
// regex pattern
if (new Location(pattern).exists()) {
fileList.add(pattern);
return;
}
isRegex = true;
String[] files = null;
String dir;
int endRegex = pattern.indexOf(File.separator + "\\E") + 1;
int endNotRegex = pattern.lastIndexOf(File.separator) + 1;
int end;
//Check if an escaped path has been defined as part of the regex.
if (pattern.startsWith("\\Q") && endRegex > 0 && endRegex <= endNotRegex)
{
dir = pattern.substring(2, endRegex);
end = endRegex + 2;
}
else {
dir = pattern.substring(0, endNotRegex);
end = endNotRegex;
}
if (dir.equals("") || !new Location(dir).exists()) {
files = Location.getIdMap().keySet().toArray(new String[0]);
if (files.length == 0) {
dir = ".";
files = new Location(dir).list();
}
}
else {
files = new Location(dir).list();
}
Arrays.sort(files);
String basePattern = pattern.substring(end);
Pattern regex = null;
try {
regex = Pattern.compile(basePattern);
}
catch (PatternSyntaxException e) {
regex = Pattern.compile(pattern);
}
for (String f : files) {
Location path = new Location(dir, f);
if (regex.matcher(f).matches() ||
regex.matcher(path.getAbsolutePath()).matches())
{
if (path.exists()) fileList.add(path.getAbsolutePath());
else fileList.add(f);
}
}
}
else {
// compute bounds for constant (non-block) pattern fragment
int num = startIndex.length;
int n1 = ndx == 0 ? 0 : endIndex[ndx - 1];
int n2 = ndx == num ? pattern.length() : startIndex[ndx];
String pre = pattern.substring(n1, n2);
if (ndx == 0) fileList.add(pre + prefix);
else {
FilePatternBlock block = blocks[--ndx];
String[] blockElements = block.getElements();
for (String element : blockElements) {
buildFiles(element + pre + prefix, ndx, fileList);
}
}
}
}
// -- Main method --
/** Method for testing file pattern logic. */
public static void main(String[] args) {
String pat = null;
if (args.length > 0) {
// test file pattern detection based on the given file on disk
Location file = new Location(args[0]);
LOGGER.info("File = {}", file.getAbsoluteFile());
pat = findPattern(file);
}
else {
// test file pattern detection from a virtual file list
String[] nameList = new String[2 * 4 * 3 * 12 + 1];
nameList[0] = "outlier.ext";
int count = 1;
for (int i=1; i<=2; i++) {
for (int j=1; j<=4; j++) {
for (int k=0; k<=2; k++) {
for (int l=1; l<=12; l++) {
String sl = (l < 10 ? "0" : "") + l;
nameList[count++] =
"hypothetical" + sl + k + j + "c" + i + ".ext";
}
}
}
}
pat = findPattern(nameList[1], null, nameList);
}
if (pat == null) LOGGER.info("No pattern found.");
else {
LOGGER.info("Pattern = {}", pat);
FilePattern fp = new FilePattern(pat);
if (fp.isValid()) {
LOGGER.info("Pattern is valid.");
LOGGER.info("Files:");
String[] ids = fp.getFiles();
for (int i=0; i<ids.length; i++) {
LOGGER.info(" #{}: {}", i, ids[i]);
}
}
else LOGGER.info("Pattern is invalid: {}", fp.getErrorMessage());
}
}
// -- Deprecated methods --
/* @deprecated */
public BigInteger[] getFirst() {
BigInteger[] first = new BigInteger[blocks.length];
for (int i=0; i<first.length; i++) {
first[i] = blocks[i].getFirst();
}
return first;
}
/* @deprecated */
public BigInteger[] getLast() {
BigInteger[] last = new BigInteger[blocks.length];
for (int i=0; i<last.length; i++) {
last[i] = blocks[i].getLast();
}
return last;
}
/* @deprecated */
public BigInteger[] getStep() {
BigInteger[] step = new BigInteger[blocks.length];
for (int i=0; i<step.length; i++) {
step[i] = blocks[i].getStep();
}
return step;
}
}
// -- Notes --
// Some patterns observed:
//
// TAABA1.PIC TAABA2.PIC TAABA3.PIC ... TAABA45.PIC
//
// 0m.tiff 3m.tiff 6m.tiff ... 36m.tiff
//
// cell-Z0.C0.tiff cell-Z1.C0.tiff cell-Z2.C0.tiff ... cell-Z39.C0.tiff
// cell-Z0.C1.tiff cell-Z1.C1.tiff cell-Z2.C1.tiff ... cell-Z39.C1.tiff
//
// CRG401.PIC
//
// TST00101.PIC TST00201.PIC TST00301.PIC
// TST00102.PIC TST00202.PIC TST00302.PIC
//
// 800102.pic 800202.pic 800302.pic ... 805902.pic
// 800103.pic 800203.pic 800303.pic ... 805903.pic
//
// nd400102.pic nd400202.pic nd400302.pic ... nd406002.pic
// nd400103.pic nd400203.pic nd400303.pic ... nd406003.pic
//
// WTERZ2_Series13_z000_ch00.tif ... WTERZ2_Series13_z018_ch00.tif
//
// --------------------------------------------------------------------------
//
// The file pattern notation defined here encompasses all patterns above.
//
// TAABA<1-45>.PIC
// <0-36:3>m.tiff
// cell-Z<0-39>.C<0-1>.tiff
// CRG401.PIC
// TST00<1-3>0<1-2>.PIC
// 80<01-59>0<2-3>.pic
// nd40<01-60>0<2-3>.pic
// WTERZ2_Series13_z0<00-18>_ch00.tif
//
// In general: <B-E:S> where B is the start number, E is the end number, and S
// is the step increment. If zero padding has been used, the start number B
// will have leading zeroes to indicate that. If the step increment is one, it
// can be omitted.
//
// --------------------------------------------------------------------------
//
// If file groups not limited to numbering need to be handled, we can extend
// the notation as follows:
//
// A pattern such as:
//
// ABCR.PIC ABCG.PIC ABCB.PIC
//
// Could be represented as:
//
// ABC<R|G|B>.PIC
//
// If such cases come up, they will need to be identified heuristically and
// incorporated into the detection algorithm.
//
// --------------------------------------------------------------------------
//
// Here is a sketch of the algorithm for determining the pattern from a given
// file within a particular group:
//
// 01 - Detect number blocks within the file name, marking them with stars.
// For example:
//
// xyz800303b.pic -> xyz<>b.pic
//
// Where <> represents a numerical block with unknown properties.
//
// 02 - Get a file listing for all files matching the given pattern. In the
// example above, we'd get:
//
// xyz800102b.pic, xyz800202b.pic, ..., xyz805902b.pic,
// xyz800103b.pic, xyz800203b.pic, ..., xyz805903b.pic
//
// 03 - There are two possibilities: "fixed width" and "variable width."
//
// Variable width: Not all filenames are the same length in characters.
// Assume the block only covers a single number. Extract that number
// from each filename, sort them and analyze as described below.
//
// Fixed width: All filenames are the same length in characters. The
// block could represent more than one number.
//
// First, for each character, determine if that character varies between
// filenames. If not, lock it down, splitting the block as necessary
// into fixed-width blocks. When finished, the above example looks like:
//
// xyz80<2>0<1>b.pic
//
// Where <N> represents a numerical block of width N.
//
// For each remaining block, extract the numbers from each matching
// filename, sort the lists, and analyze as described below.
//
// 04 - In either case, analyze each list of numbers. The first on the list
// is B. The last one is E. And S is the second one minus B. But check
// the list to make sure no numbers are missing for that step size.
//
// NOTE: The fixed width algorithm above is insufficient for patterns like
// "0101.pic" through "2531.pic," where no fixed constant pads the two
// numerical counts. An additional step is required, as follows:
//
// 05 - For each fixed-width block, recursively divide it into pieces, and
// analyze the numerical scheme according to those pieces. For example,
// in the problem case given above, we'd have:
//
// <4>.pic
//
// Recursively, we'd analyze:
//
// <4>.pic
// <3><R1>.pic
// <2><R2>.pic
// <1><R3>.pic
//
// The <Rx> blocks represent recursive calls to analyze the remainder of
// the width.
//
// The function decides if a given combination of widths is valid by
// determining if each individual width is valid. An individual width
// is valid if the computed B, S and E properly cover the numerical set.
//
// If no combination of widths is found to be valid, the file numbering
// is screwy. Print an error message.
|
Markdown
|
UTF-8
| 6,751
| 3.609375
| 4
|
[] |
no_license
|
---
{
"title": "Vue render",
"lang": "zH",
"description": "此篇主要介紹 vue 組件的render",
"meta": [{"name":"keywords", "content":"vue component, vue, vue render"}],
"tags": ['Vue'],
"sidebarDepth": "2"
}
---
# render
## 1. render 函數是什麼?
一般來說,在Vue中我們使用模板HTML來組建頁面,使用render function 我們可以使用js來構建DOM<br>
因為vue是 virtual DOM,所以拿到template模板時也要轉譯成VNode函數,而用render function建構DOM,vue就免去編譯的過程
* 當使用render function描述Virtual DOM時,vue提供一個函數,這個函數是建構Virtual DOM的工具。名做`createElement` or `h`
### Demo
```html
// 父组件
<template>
<div>
<child1 :level='level'>我是標題</child1>
</div>
</template>
<script>
const child1 = () => import("./child1.vue");
export default {
components: { child1 },
data() {
return {
level: 1
};
},
};
</script>
```
一般子組件設定成這樣,會有很多if & `<slot>`的語法,並不是很好
```html
// 子组件 child1.vue
<template>
<div>
<h1 v-if="level == 1">
<slot></slot>
</h1>
<h2 v-if="level == 2">
<slot></slot>
</h2>
<h3 v-if="level == 3">
<slot></slot>
</h3>
<h4 v-if="level == 4">
<slot></slot>
</h4>
<h5 v-if="level == 5">
<slot></slot>
</h5>
<h6 v-if="level == 6">
<slot></slot>
</h6>
</div>
</template>
<script>
export default {
props: {
level: {
require: true,
type: Number,
}
}
};
</script>
```
而將子組件使用render方式渲染出來,方法如下
```html
<script>
export default {
props: {
level: {
require: true,
type: Number,
}
},
render(createElement) {
return createElement('h' + this.level, this.$slots.default);
}
};
</script>
```
:::tip
1. child1的'我是標題',被存在組件實例this.$slots.default
2. 因為模板寫了太多slot,所以在這邊選用render function 是較好的。
:::
## 2. render 函數的參數
* render函數是渲染函數,他是個函數,render函數的返回值VNode(虛擬節點)
* createElement是render函數的參數,他本身也是個函數,並且有三個參數
#### createElement第一個參數是必填的:{String | Object | Function}
1. String:HTML標籤名
2. Object:含有數據的組件選填物件
3. Function:返回一個含有標籤名or組件選項的async function
```javascript
render: function (createElement) {
// String
return createElement('h1');
// Object:key(template)-value(String)
return createElement({
template: " <div>Hello World</div> "
})
// Function > return something
let domFun = function () {
return {
template: " <div>Hello World</div> "
}
}
return createElement(domFun())
}
```
#### createElement第二個參數是選填的,主要設置模板中屬性對應的數據物件,常用的有:
#### class | style | attrs | domProps | on
1. class:控制類名
2. style:樣式
3. attr:用來寫正常的html屬性,id or src等
4. domProp:用來寫原生的dom屬性
5. on:寫原生方法
```javascript
return createElement('div', {
// 與 `v-bind:class` 的 API 相同,
// 接受一個字符串、物件或字符串和物件组成的陣列
'class': {
foo: true,
bar: false
},
// 與 `v-bind:style` 的 API 相同,
// 接受一个字串、物件,或物件组成的数组
style: {
color: 'red',
fontSize: '14px'
},
// 普通的 HTML 特性
attrs: {
id: 'foo'
},
// 定義组件的 prop
props: {
myProp: 'bar'
},
// DOM 属性
domProps: {
innerHTML: 'baz'
},
// 事件監聽器在on屬性內
// 但不再支持如 `v-on:keyup.enter` 這樣的修飾器
// 需要在處理函數中手動檢查 keyCode。
on: {
click: this.clickHandler
},
// 僅用於組建,用於監聽原生事件,而不是組件內部使用
// `vm.$emit` 觸發的事件。
nativeOn: {
click: this.nativeClickHandler
},
// 自定義指令。注意,你無法對 `binding` 中的 `oldValue`
// 赋值,因为 Vue2 已經自動為我們做同步。
directives: [
{
name: 'my-custom-directive',
value: '2',
expression: '1 + 1',
arg: 'foo',
modifiers: {
bar: true
}
}
],
// 作用域插槽的格式為
// { name: props => VNode | Array<VNode> }
scopedSlots: {
default: props => createElement('span', props.text)
},
// 如果组件是其它组件的子组件,須為插槽指定名稱
slot: 'name-of-slot',
// 其它特殊頂層属性
key: 'myKey',
ref: 'myRef',
// 如果你在渲染函数中给多个元素都應用了相同的 ref 名,
// 那麼 `$refs.myRef` 會變成一個數組
refInFor: true
})
```
## 3. v-model在render函數中使用
在render函數中,沒有提供v-model的實現,所以我們必須自己實現相關邏輯
```html
// 同樣地,父組件寫法與正常組件寫法相同
// child1子组件
<script>
export default {
props: {
name: {
require: true,
}
},
render(createElement) {
let self = this
return createElement('input', {
domProps: {
value: self.name
},
on: {
// 重點是這邊要通過input方法實現雙向綁定,當子組件name改變,父組件也要更新
input(event) {
self.$emit('input', event.target.value)
}
}
})
}
};
</script>
```
## 4. render 函數中的事件修飾符
對於`.passive`、`.capture`、`.once`這些事件修飾符,Vue提供了相應的前綴可以用於 `on`
|修飾符 |前綴 |
|--- |--- |
|`.passive` |`&` |
|`.capture` |`!` |
|`.once` |`~` |
|`.capture.once` |`~!` |
|`.once.capture` |`~!` |
```javascript
on: {
'!click': this.doThisInCapturingMode,
'~keyup': this.doThisOnce,
'~!mouseover': this.doThisOnceInCapturingMode
}
```
## 5. JSX語法糖
其實這個語法糖就是趨於如同react.js的寫法
```jsx
render(h) {
return (
<Child1 level={1}>
<span>Hello</span> world!
</Child1>
)
}
```
## 參考資料
1. [Vue - 渲染函数render](https://juejin.im/post/6844903919764635655)
|
Python
|
UTF-8
| 1,769
| 2.65625
| 3
|
[] |
no_license
|
import sys
import time
# group with 9
group1 = 'p.Leu858Arg'
# group with 15
group2 = 'p.Gly'
mutName = "EGFR"
inExpressFile = open("/fslhome/srp33/fsl_groups/fslg_piccololab/PANCAN20/GSM1536837_TCGA_20.Illumina.tumor_Rsubread_TPM.txt", "r")
outFile = open("GSM1536837_TCGA_20.Illumina.tumor_Rsubread_TPM_outfile.txt", "w")
resultFile = open("outfile_" + mutName + ".txt", "r")
sampleIDs = []
sampleInfo = []
for line in resultFile:
line = line.strip().split('\t')
# Save patient ids of those that aren't NA
if line[1] != 'NA':
sampleIDs.append(line[0])
sampleInfo.append('_'.join(line[1::]))
# Split first row of patient ids
headerItems = []
headers = inExpressFile.readline().strip().split('\t')
for head in headers:
headerItems.append(head[0:12])
# Save indices of patient ids that have a match, as well as 0 to keep row headers
keepSampleIndices = [0]
for index,item in enumerate(headerItems):
if item in sampleIDs:
keepSampleIndices.append(index)
# Write the column headers with format: id_info
# Note: .index() only returns index of first occurance
outFile.write(item + '_' + sampleInfo[sampleIDs.index(item)] + "\t")
print item + '_' + sampleInfo[sampleIDs.index(item)]
# Write newline following column headers
outFile.write('\n')
start = time.clock()
# Write only the columns with the specified indices
for line in inExpressFile:
lineItems = line.strip().split('\t')
outItems = [lineItems[i] for i in keepSampleIndices]
outFile.write("\t".join(outItems) + "\n")
end = time.clock()
print "TIME: " + str(end- start)
# # Problem with this is that if exception raised it quits for loop
# try:
# keepSampleIndices = [headerItems.index(sampleID) for sampleID in sampleIDs]
# except ValueError:
# print("List does not contain value")
|
Java
|
UTF-8
| 2,702
| 2.25
| 2
|
[] |
no_license
|
package de.se.common.tiles.capacitor;
import javax.annotation.Nonnull;
import de.se.api.energy.starflux.StarFluxStorage;
import de.se.common.config.ConfigValues;
import de.se.common.tiles.TileSEBase;
import de.se.common.utils.helper.EnergyHelper;
import de.se.common.utils.helper.EnergyHelper.ISEInternalEnergyHandler;
import de.se.common.utils.helper.EnergyHelper.SEForgeEnergyWrapper;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
public class TileSmallCapacitor extends TileSEBase implements ITickable, ISEInternalEnergyHandler{
StarFluxStorage storage = new StarFluxStorage(getMaxStorage(), getMaxReceive(), getMaxExtract());
public int comparatorOutput = 0;
@Override
public void update() {
if(!world.isRemote){
for(int i = 0; i < 6; i++){
this.transferEnergy(i);
}
if(world.getTotalWorldTime()%32 == ((getPos().getX()^getPos().getZ())&31))
{
int i = scaleStoredEnergyTo(15);
if(i != this.comparatorOutput){
this.comparatorOutput = i;
world.updateComparatorOutputLevel(getPos(), getBlockType());
}
}
}
}
public int scaleStoredEnergyTo(int i) {
return (int)(i*(storage.getEnergyStored()/(float)storage.getMaxEnergyStored()));
}
protected void transferEnergy(int i){
EnumFacing fd = EnumFacing.getFront(i);
TileEntity tile = world.getTileEntity(getPos().offset(fd));
int out = Math.min(getMaxExtract(), this.storage.getEnergyStored());
this.storage.changeStoredEnergy(-EnergyHelper.insertEnergy(tile, fd.getOpposite(), out, false));
}
public int getMaxStorage(){
return ConfigValues.smallSFCapacitorCapacity;
}
public int getMaxExtract(){
return ConfigValues.smallSFCapacitorIn;
}
public int getMaxReceive(){
return ConfigValues.smallSFCapacitorOut;
}
SEForgeEnergyWrapper[] wrapper = SEForgeEnergyWrapper.getDefaultWrapperArray(this);
@Nonnull
@Override
public StarFluxStorage getEnergyStorage(){
return this.storage;
}
@Override
public SEForgeEnergyWrapper getCapabilityWrapper(EnumFacing facing) {
if(facing == null){
return null;
}
return wrapper[facing.ordinal()];
}
@Override
public boolean canConnectEnergy(EnumFacing from) {
return false;
}
@Override
public void readCustomNBT(NBTTagCompound nbt, boolean descPacket) {
storage.writeToNBT(nbt);
}
@Override
public void writeCustomNBT(NBTTagCompound nbt, boolean descPacket) {
storage.readFromNBT(nbt);
}
}
|
C++
|
UTF-8
| 1,156
| 2.609375
| 3
|
[] |
no_license
|
#ifndef DOCINDEX_H
#define DOCINDEX_H
/**
@brief DocIndex\n
@file docindex.h
@author ShadowIterator
@email ShadowIterator@hotmail.com
@version 0.1
@date 2017.12.24
*/
#include"si_global.h"
#include"linklist.h"
#include"sistring.h"
#include"pageinfo.h"
#include"indexlistnode.h"
namespace SI
{
/*
@brief 用于描述一条索引信息\n
*/
class DocIndex
{
public:
typedef IndexListNode node;
SIString* pword; ///<索引关键词
linklist<node>* ppageList; ///<指向文档链表的指针
DocIndex(const SIString& tword);
DocIndex(const DocIndex& tindex);
DocIndex();
//it will do nothing
/*
@brief 析构函数\n
@note 析构函数不会做任何操作,需要手动调用destroy()方法
@see_also SI::DocIndex::destroy
*/
~DocIndex();
//call this method when U don't need the data any more
void destroy(); ///<释放空间
void insertPage(const node& tpage); ///<向文档列表中插入节点并保持有序
int hash(int P) const; ///<得到关键词的HASH值
bool operator < (const DocIndex& tindex) const;
bool operator > (const DocIndex& tindex) const;
bool operator == (const DocIndex& tindex) const;
};
}
#endif
|
SQL
|
UTF-8
| 15,501
| 3.1875
| 3
|
[] |
no_license
|
-- MySQL Script generated by MySQL Workbench
-- utorak, 12. decembar 2017. 15:22:52 cet
-- Model: New Model version: 1.0
-- MySQL Workbench Forward Engineering
set @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
set @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
set @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema formula4000
-- -----------------------------------------------------
drop schema if exists `formula4000` ;
-- -----------------------------------------------------
-- Schema formula4000
-- -----------------------------------------------------
create schema if not exists `formula4000` default character set UTF8 ;
use `formula4000` ;
-- -----------------------------------------------------
-- Table `formula4000`.`motor`
-- -----------------------------------------------------
drop table if exists `formula4000`.`motor` ;
create table if not exists `formula4000`.`motor` (
`broj_motora` int not null,
`proizvodjac` varchar(45) not null,
`zapremina` smallint not null,
`radna_temperatura` smallint not null,
`snaga` smallint not null,
`broj_obrtaja` smallint not null,
`pouzdanost` varchar(45) null,
primary key (`broj_motora`))
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`tim`
-- -----------------------------------------------------
drop table if exists `formula4000`.`tim` ;
create table if not exists `formula4000`.`tim` (
`id_tima` int not null auto_increment,
`ime` varchar(45) not null,
primary key (`id_tima`),
unique index `ime_unique` (`ime` asc))
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`formula`
-- -----------------------------------------------------
drop table if exists `formula4000`.`formula` ;
create table if not exists `formula4000`.`formula` (
`broj_sasije` int not null,
`proizvodjac` varchar(45) not null,
`maks_brzina` smallint not null,
`tezina` smallint not null,
`duzina` smallint not null,
`motor` int not null,
`tim` int not null,
primary key (`broj_sasije`),
index `fk_formula_motor_idx` (`motor` asc),
index `fk_formula_tim_idx` (`tim` asc),
unique index `motor_unique` (`motor` asc),
constraint `fk_formula_motor`
foreign key (`motor`)
references `formula4000`.`motor` (`broj_motora`)
on delete cascade
on update cascade,
constraint `fk_formula_tim`
foreign key (`tim`)
references `formula4000`.`tim` (`id_tima`)
on delete cascade
on update cascade)
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`paket_guma`
-- -----------------------------------------------------
drop table if exists `formula4000`.`paket_guma` ;
create table if not exists `formula4000`.`paket_guma` (
`formula` int not null,
`proizvodjac` varchar(45) not null,
`tip` varchar(45) not null,
`velicina` smallint not null,
`radna_temperatura` smallint not null,
`trajanje` smallint null,
primary key (`formula`),
constraint `fk_paket_guma_formula`
foreign key (`formula`)
references `formula4000`.`formula` (`broj_sasije`)
on delete cascade
on update cascade)
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`menadzer`
-- -----------------------------------------------------
drop table if exists `formula4000`.`menadzer` ;
create table if not exists `formula4000`.`menadzer` (
`id_menadzera` int not null auto_increment,
`ime` varchar(45) not null,
`veze` smallint null,
primary key (`id_menadzera`))
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`vozac`
-- -----------------------------------------------------
drop table if exists `formula4000`.`vozac` ;
create table if not exists `formula4000`.`vozac` (
`id_vozaca` int not null auto_increment,
`ime` varchar(45) not null,
`prezime` varchar(45) not null,
`godina_rodjenja` smallint not null,
`visina` smallint not null,
`tezina` smallint not null,
`formula` int null,
`menadzer` int null,
`tim` int null,
primary key (`id_vozaca`),
index `fk_vozac_formula_idx` (`formula` asc),
index `fk_vozac_menadzer_idx` (`menadzer` asc),
index `fk_vozac_tim_idx` (`tim` asc),
constraint `fk_vozac_formula`
foreign key (`formula`)
references `formula4000`.`formula` (`broj_sasije`)
on delete set null
on update cascade,
constraint `fk_vozac_menadzer`
foreign key (`menadzer`)
references `formula4000`.`menadzer` (`id_menadzera`)
on delete set null
on update cascade,
constraint `fk_vozac_tim`
foreign key (`tim`)
references `formula4000`.`tim` (`id_tima`)
on delete set null
on update cascade)
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`staza`
-- -----------------------------------------------------
drop table if exists `formula4000`.`staza` ;
create table if not exists `formula4000`.`staza` (
`redni_broj` int not null auto_increment,
`lokacija` varchar(45) not null,
`broj_krugova` smallint not null,
`duzina_kruga` smallint not null,
`broj_krivina` smallint null,
`mesta_za_preticanje` smallint null,
primary key (`redni_broj`))
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`sponzor`
-- -----------------------------------------------------
drop table if exists `formula4000`.`sponzor` ;
create table if not exists `formula4000`.`sponzor` (
`id_sponzora` int not null auto_increment,
`ime` varchar(45) not null,
`marketing` varchar(45) not null,
`brend` varchar(45) not null,
primary key (`id_sponzora`))
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`sponzorski_pul`
-- -----------------------------------------------------
drop table if exists `formula4000`.`sponzorski_pul` ;
create table if not exists `formula4000`.`sponzorski_pul` (
`id_tima` int not null,
`id_sponzora` int not null,
`trajanje` smallint null,
primary key (`id_tima`, `id_sponzora`),
index `fk_sponzorski_pul_sponzor_idx` (`id_sponzora` asc),
constraint `fk_sponzorski_pul_tim`
foreign key (`id_tima`)
references `formula4000`.`tim` (`id_tima`)
on delete cascade
on update cascade,
constraint `fk_sponzorski_pul_sponzor`
foreign key (`id_sponzora`)
references `formula4000`.`sponzor` (`id_sponzora`)
on delete cascade
on update cascade)
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`vlasnik`
-- -----------------------------------------------------
drop table if exists `formula4000`.`vlasnik` ;
create table if not exists `formula4000`.`vlasnik` (
`id_vlasnika` int not null auto_increment,
`ime` varchar(45) not null,
`prezime` varchar(45) not null,
`saldo` int not null,
`kriminalna_proslost` varchar(45) not null,
`redovna_isplata` varchar(45) null,
primary key (`id_vlasnika`))
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`vlasnistvo`
-- -----------------------------------------------------
drop table if exists `formula4000`.`vlasnistvo` ;
create table if not exists `formula4000`.`vlasnistvo` (
`id_tima` int not null,
`id_vlasnika` int not null,
`trajanje` smallint null,
primary key (`id_tima`, `id_vlasnika`),
index `fk_vlasnistvo_vlasnik_idx` (`id_vlasnika` asc),
constraint `fk_vlasnistvo_tim`
foreign key (`id_tima`)
references `formula4000`.`tim` (`id_tima`)
on delete cascade
on update cascade,
constraint `fk_vlasnistvo_vlasnik`
foreign key (`id_vlasnika`)
references `formula4000`.`vlasnik` (`id_vlasnika`)
on delete cascade
on update cascade)
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`mehanicar`
-- -----------------------------------------------------
drop table if exists `formula4000`.`mehanicar` ;
create table if not exists `formula4000`.`mehanicar` (
`broj_licence` int not null,
`ime` varchar(45) not null,
`prezime` varchar(45) not null,
`struka` varchar(45) not null,
`staz` smallint not null,
`prethodni_poslovi` smallint null,
primary key (`broj_licence`))
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`odrzavanje`
-- -----------------------------------------------------
drop table if exists `formula4000`.`odrzavanje` ;
create table if not exists `formula4000`.`odrzavanje` (
`id_tima` int not null,
`id_mehanicara` int not null,
`poslednji_servis` datetime null,
primary key (`id_tima`, `id_mehanicara`),
index `fk_odrzavanje_mehanicar_idx` (`id_mehanicara` asc),
constraint `fk_odrzavanje_tim`
foreign key (`id_tima`)
references `formula4000`.`tim` (`id_tima`)
on delete cascade
on update cascade,
constraint `fk_odrzavanje_mehanicar`
foreign key (`id_mehanicara`)
references `formula4000`.`mehanicar` (`broj_licence`)
on delete cascade
on update cascade)
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`prvenstvo`
-- -----------------------------------------------------
drop table if exists `formula4000`.`prvenstvo` ;
create table if not exists `formula4000`.`prvenstvo` (
`id_prvenstva` int not null auto_increment,
`naziv` varchar(45) not null,
`broj_timova` smallint not null,
`broj_staza` smallint not null,
`popularnost` varchar(45) null,
primary key (`id_prvenstva`),
unique index `naziv_unique` (`naziv` asc))
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`trka`
-- -----------------------------------------------------
drop table if exists `formula4000`.`trka` ;
create table if not exists `formula4000`.`trka` (
`id_staze` int not null,
`id_prvenstva` int not null,
`vreme_odrzavanja` datetime null,
`pobednicki_tim` int null,
primary key (`id_staze`, `id_prvenstva`),
index `fk_trka_prvenstvo_idx` (`id_prvenstva` asc),
index `fk_trka_pobednik_idx` (`pobednicki_tim` asc),
constraint `fk_trka_staza`
foreign key (`id_staze`)
references `formula4000`.`staza` (`redni_broj`)
on delete cascade
on update cascade,
constraint `fk_trka_prvenstvo`
foreign key (`id_prvenstva`)
references `formula4000`.`prvenstvo` (`id_prvenstva`)
on delete cascade
on update cascade,
constraint `fk_trka_pobednik`
foreign key (`pobednicki_tim`)
references `formula4000`.`tim` (`id_tima`)
on delete set null
on update cascade)
engine = InnoDB;
-- -----------------------------------------------------
-- Table `formula4000`.`ucestvovanje`
-- -----------------------------------------------------
drop table if exists `formula4000`.`ucestvovanje` ;
create table if not exists `formula4000`.`ucestvovanje` (
`id_tima` int not null,
`id_prvenstva` int not null,
primary key (`id_tima`, `id_prvenstva`),
index `fk_ucestvovanje_prvenstvo_idx` (`id_prvenstva` asc),
constraint `fk_ucestvovanje_tim`
foreign key (`id_tima`)
references `formula4000`.`tim` (`id_tima`)
on delete cascade
on update cascade,
constraint `fk_ucestvovanje_prvenstvo`
foreign key (`id_prvenstva`)
references `formula4000`.`prvenstvo` (`id_prvenstva`)
on delete cascade
on update cascade)
engine = InnoDB;
set SQL_MODE=@OLD_SQL_MODE;
set FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
set UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
use `formula4000`;
delimiter $$
use `formula4000`$$
drop trigger if exists `formula4000`.`formula_before_insert` $$
use `formula4000`$$
create trigger `formula4000`.`formula_before_insert` before insert on `formula` for each row
begin
if new.motor in (select motor from formula) then
signal sqlstate '45000' set message_text='Motor je vec pridruzen nekoj formuli!';
end if;
end$$
use `formula4000`$$
drop trigger if exists `formula4000`.`formula_before_update` $$
use `formula4000`$$
create trigger `formula4000`.`formula_before_update` before update on `formula` for each row
begin
if new.motor in (select motor from formula) then
signal sqlstate '45000' set message_text='Motor je vec pridruzen nekoj formuli!';
end if;
end$$
use `formula4000`$$
drop trigger if exists `formula4000`.`vozac_before_insert` $$
use `formula4000`$$
create trigger `formula4000`.`vozac_before_insert` before insert on `vozac` for each row
begin
if (new.formula not in (select broj_sasije from formula where tim=new.tim)) then
signal sqlstate '45000' set message_text='Vozac mora voziti formulu koja pripada njegovom timu!';
end if;
end$$
use `formula4000`$$
drop trigger if exists `formula4000`.`vozac_before_update` $$
use `formula4000`$$
create trigger `formula4000`.`vozac_before_update` before update on `vozac` for each row
begin
if (new.formula not in (select broj_sasije from formula where tim=new.tim)) then
signal sqlstate '45000' set message_text='Vozac mora voziti formulu koja pripada njegovom timu!';
end if;
end$$
use `formula4000`$$
drop trigger if exists `formula4000`.`trka_before_insert` $$
use `formula4000`$$
create trigger `formula4000`.`trka_before_insert` before insert on `trka` for each row
begin
set new.pobednicki_tim=null;
if (select count(*)
from trka
where id_prvenstva=new.id_prvenstva)=(select broj_staza
from prvenstvo as p
where p.id_prvenstva=new.id_prvenstva) then
signal sqlstate '45000' set message_text='Unet je maksimalan broj trka za ovo prvenstvo!';
end if;
end$$
use `formula4000`$$
drop trigger if exists `formula4000`.`trka_before_update` $$
use `formula4000`$$
create trigger `formula4000`.`trka_before_update` before update on `trka` for each row
begin
if new.pobednicki_tim not in (select u.id_tima
from ucestvovanje as u
where u.id_prvenstva=new.id_prvenstva) then
signal sqlstate '45000' set message_text='Tim ne ucesvuje na ovom prvenstvu!';
end if;
if (not (new.id_staze=old.id_staze and new.id_prvenstva=old.id_prvenstva)
and (select count(*)
from trka
where id_prvenstva=new.id_prvenstva)=(select broj_staza
from prvenstvo as p
where p.id_prvenstva=new.id_prvenstva)) then
signal sqlstate '45000' set message_text='Unet je maksimalan broj trka za ovo prvenstvo!';
end if;
end$$
use `formula4000`$$
drop trigger if exists `formula4000`.`ucestvovanje_before_insert` $$
use `formula4000`$$
create trigger `formula4000`.`ucestvovanje_before_insert` before insert on `ucestvovanje` for each row
begin
if (select count(*)
from ucestvovanje
where id_prvenstva=new.id_prvenstva)=(select broj_timova
from prvenstvo as p
where p.id_prvenstva=new.id_prvenstva) then
signal sqlstate '45000' set message_text='Unet je maksimalan broj timova za ovo prvenstvo!';
end if;
end$$
use `formula4000`$$
drop trigger if exists `formula4000`.`ucestvovanje_before_update` $$
use `formula4000`$$
create trigger `formula4000`.`ucestvovanje_before_update` before update on `ucestvovanje` for each row
begin
if (select count(*)
from ucestvovanje
where id_prvenstva=new.id_prvenstva)=(select broj_timova
from prvenstvo as p
where p.id_prvenstva=new.id_prvenstva) then
signal sqlstate '45000' set message_text='Unet je maksimalan broj timova za ovo prvenstvo!';
end if;
end$$
delimiter ;
|
Python
|
UTF-8
| 524
| 3.8125
| 4
|
[
"MIT"
] |
permissive
|
# Code Listing #15
"""
Factorial of numbers using concurrent futures.
"""
from concurrent.futures import ThreadPoolExecutor, as_completed
import functools
import operator
def factorial(n):
return functools.reduce(operator.mul, [i for i in range(1, n+1)])
with ThreadPoolExecutor(max_workers=2) as executor:
future_map = {executor.submit(factorial, n): n for n in range(10, 21)}
for future in as_completed(future_map):
num = future_map[future]
print('Factorial of',num,'is',future.result())
|
Java
|
UTF-8
| 2,118
| 2.03125
| 2
|
[] |
no_license
|
package com.p118pd.sdk;
import java.util.Enumeration;
import java.util.Hashtable;
import org.bouncycastle.util.Strings;
/* renamed from: com.pd.sdk.丨1丨LI reason: invalid class name and case insensitive filesystem */
public class C93191LI {
public static final Hashtable OooO00o = new Hashtable();
public static final Hashtable OooO0O0 = new Hashtable();
static {
OooO00o("B-571", AbstractC6801ll1lLI.Oooo000);
OooO00o("B-409", AbstractC6801ll1lLI.OooOooO);
OooO00o("B-283", AbstractC6801ll1lLI.OooOOO);
OooO00o("B-233", AbstractC6801ll1lLI.OooOo00);
OooO00o("B-163", AbstractC6801ll1lLI.OooOO0o);
OooO00o("K-571", AbstractC6801ll1lLI.OooOooo);
OooO00o("K-409", AbstractC6801ll1lLI.OooOoo);
OooO00o("K-283", AbstractC6801ll1lLI.OooOOO0);
OooO00o("K-233", AbstractC6801ll1lLI.OooOOoo);
OooO00o("K-163", AbstractC6801ll1lLI.OooO0O0);
OooO00o("P-521", AbstractC6801ll1lLI.OooOoo0);
OooO00o("P-384", AbstractC6801ll1lLI.OooOoOO);
OooO00o("P-256", AbstractC6801ll1lLI.Oooo00o);
OooO00o("P-224", AbstractC6801ll1lLI.OooOoO);
OooO00o("P-192", AbstractC6801ll1lLI.Oooo00O);
}
public static LlLI1 OooO00o(String str) {
return (LlLI1) OooO00o.get(Strings.OooO0O0(str));
}
public static C9387Iill OooO00o(LlLI1 llLI1) {
return C6659liLi.OooO00o(llLI1);
}
/* renamed from: OooO00o reason: collision with other method in class */
public static C9387Iill m21352OooO00o(String str) {
LlLI1 llLI1 = (LlLI1) OooO00o.get(Strings.OooO0O0(str));
if (llLI1 != null) {
return OooO00o(llLI1);
}
return null;
}
/* renamed from: OooO00o reason: collision with other method in class */
public static String m21353OooO00o(LlLI1 llLI1) {
return (String) OooO0O0.get(llLI1);
}
public static Enumeration OooO00o() {
return OooO00o.keys();
}
public static void OooO00o(String str, LlLI1 llLI1) {
OooO00o.put(str, llLI1);
OooO0O0.put(llLI1, str);
}
}
|
JavaScript
|
UTF-8
| 4,822
| 3.15625
| 3
|
[] |
no_license
|
var canvas_data; //данные из канвас
var width; //ширина канвас
var height; //высота канвас
var squares = []; //массив областей
self.addEventListener('message', function(e) {
var data = e.data;
switch (data.cmd) {
case 'calc_colors':
canvas_data = data.data_calc.canvas_data;
width = data.data_calc.canvas_width;
height = data.data_calc.canvas_height;
var squares = calculate(data.data_calc); // Функция, вычисляющая области
self.postMessage({status: 'ok',squares: squares}); //отправляем сообщение с найденными областями
break;
default:
self.postMessage('Unknown command');
}
}, false);
//функция проверяет принадлежность точки ранее найденным областям
function in_square(x,y){
for(var i=0; i<squares.length; i++){
if(x >= squares[i]['left'] && x <= squares[i]['right'] && y >= squares[i]['up'] && y <= squares[i]['down']){
return(true);
}
}
return(false);
}
//информация по пикселю
function getPixel(x, y) {
if (x < 0) { x = 0; }
if (y < 0) { y = 0; }
if (x >= width) { x = width - 1; }
if (y >= height) { y = height - 1; }
var index = (y * width + x) * 4;
return [
canvas_data.data[index + 0],
canvas_data.data[index + 1],
canvas_data.data[index + 2],
canvas_data.data[index + 3],
];
}
//получаем яркость
function getYarkost(R=0,G=0,B=0){
var Y = 0.2126*R + 0.7152*G + 0.0722*B; //Фотометрический/цифровой ITU BT.709:
return(Y);
}
//поиск ярких областей
function calculate(data_calc){
var step = parseInt(data_calc.step);
var canvas_height = parseInt(data_calc.canvas_height);
var canvas_width = parseInt(data_calc.canvas_width);
var minY = parseInt(data_calc.minY);
var min_width = parseInt(data_calc.min_width);
var min_height = parseInt(data_calc.min_height);
var i=0;
var pixels_get = 1; //кол-во пройденных пикселей
//console.log(data_calc.canvas_height,data_calc.canvas_width,data_calc.step);
for(var y=0; y<canvas_height; y++){
for(var x=0; x<canvas_width; x++){
pixels_get++;
//если точка в ранее найденной области пропускаем
if(in_square(x,y)){
continue;
}
//для наглядности пользователю показываем процент проведенных вычислений
var proc = parseInt(100*(pixels_get)/(canvas_height*canvas_width));
self.postMessage({status: 'calculate',proc: proc});
var rgba = getPixel(x, y);
//получить яркость точки
var Y = getYarkost(rgba[0],rgba[1],rgba[2]);
var left = x;
var up = y;
var right = x;
var down = y;
var max_right = right;
//проходим вправ пока яркость выше минимально заданной
while(Y > minY){
right = right+step;
rgba_f = getPixel(right, y);
Y = getYarkost(rgba_f[0],rgba_f[1],rgba_f[2]);
}
//если получили отрезок больше минимально заданной ширины, то проходим по высоте
if(right - left > min_width){
var flag = true;
max_right = right;
down = down+step;
right = left;
while(flag){
//console.log("right: " + right + " left: " + left + " up: " + up + " down: " + down);
rgba_f = getPixel(right, down);
Y = getYarkost(rgba_f[0],rgba_f[1],rgba_f[2]);
while(Y > minY){
right = right+step;
console.log("right: " + right + " left: " + left + " up: " + up + " down: " + down);
rgba_f = getPixel(right, down);
Y = getYarkost(rgba_f[0],rgba_f[1],rgba_f[2]);
}
//если получили отрезок боьше минимально необходимой ширины, проходим дальше по высоте, иначе выходим
if(right - left < min_width){
flag = false;
}else{
down = down+step;
right = left;
}
}
//console.log("Itog: max_right: " + max_right + " left: " + left + " up: " + up + " down: " + down);
//если высота боьше минимально необходимой, то добавляем область
if(down - up > min_height){
squares.push({left: left, up: up,right:max_right,down:down});
//y = down;
}
}
//var res = rgba.filter((q, i) => (i % 4) === 0);
//console.log(x,y, rgba,Y);
}
}
return(squares);
}
|
Java
|
UTF-8
| 4,035
| 1.96875
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
*
* Copyright (c) 2006-2020, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.runtime.field;
import com.speedment.runtime.config.identifier.ColumnIdentifier;
import com.speedment.runtime.field.internal.EnumForeignKeyFieldImpl;
import com.speedment.runtime.field.method.ReferenceGetter;
import com.speedment.runtime.field.method.ReferenceSetter;
import com.speedment.runtime.field.trait.HasComparableOperators;
import com.speedment.runtime.field.trait.HasFinder;
import com.speedment.runtime.field.trait.HasNullableFinder;
import com.speedment.runtime.typemapper.TypeMapper;
import java.util.function.Function;
/**
* A field representing an {@code Enum} value in the entity that has a finder to
* another entity.
*
* @param <ENTITY> the entity type
* @param <D> the database type
* @param <E> the java enum type
* @param <FK> the foreign key entity type
*
* @author Emil Forslund
* @since 3.0.10
*
* @see EnumField
* @see HasFinder
*/
public interface EnumForeignKeyField<ENTITY, D, E extends Enum<E>, FK>
extends EnumField<ENTITY, D, E>,
HasNullableFinder<ENTITY, FK> {
@Override
EnumForeignKeyField<ENTITY, D, E, FK> tableAlias(String tableAlias);
/**
* A method that takes a {@code String} and converts it into an enum for
* this field.
* <p>
* The function should return {@code null} if a {@code null} value is
* specified as input and throw an exception if the value is invalid.
*
* @return the string-to-enum mapper
*/
@Override
Function<String, E> stringToEnum();
/**
* A method that takes an enum and converts it into a {@code String}.
* <p>
* The function should return {@code null} if a {@code null} value is
* specified as input and throw an exception if the value is invalid.
*
* @return the enum-to-string mapper
*/
@Override
Function<E, String> enumToString();
/**
* Create a new instance of this interface using the default implementation.
*
* @param <ENTITY> the entity type
* @param <D> the database type
* @param <E> the java enum type
* @param <FK> the foreign key entity type
* @param identifier the column that this field represents
* @param getter method reference to the getter in the entity
* @param setter method reference to the setter in the entity
* @param typeMapper the type mapper that is applied
* @param referenced the field in the foreign entity that is referenced
* @param enumToString method to convert enum to a string
* @param stringToEnum method to convert a string to enum
* @param enumClass the enum class
*
* @return the created field
*/
static <ENTITY, D, E extends Enum<E>, FK>
EnumForeignKeyField<ENTITY, D, E, FK> create(
ColumnIdentifier<ENTITY> identifier,
ReferenceGetter<ENTITY, E> getter,
ReferenceSetter<ENTITY, E> setter,
TypeMapper<D, E> typeMapper,
HasComparableOperators<FK, E> referenced,
Function<E, String> enumToString,
Function<String, E> stringToEnum,
Class<E> enumClass) {
return new EnumForeignKeyFieldImpl<>(
identifier, getter, setter, typeMapper, referenced,
enumToString, stringToEnum, enumClass
);
}
}
|
Markdown
|
UTF-8
| 2,137
| 2.765625
| 3
|
[] |
no_license
|
# Comentario "Multi-Armed Recommender System Bandit Ensembles"
[](https://hackmd.io/GpbMI625Th2oUaDNJkCfPA)
El *paper* se sitúa en un contexto en el que combinar distintos sistemas recomendadores para lograr un mejor *performance* ya es algo usual, sin embargo, no se ha estudiado en profundidad como utilizar esto en un ambiente más realista. Debido a lo anterior, el estudio propone un método en el que el sistema recomendador va adaptándose o modificándose a medida en que ocurren interacciones con las recomendaciones. Al igual que con los estudios de la semana pasada, me parece muy interesante dejar un poco de lado las métricas convencionales para medir qué tan bueno es un sistema, y empezar a utilizar métricas o casos más realistas para poner a prueba un sistema recomendador.
El método propuesto en el *paper* se basa en los *Bandit Recommender System*, sistemas explicados en la sección 2.2. El funcionamiento de este sistema se resume en tener una recomendación por cada sistema recomendador individual, y decidirse por uno según los resultados anteriores.
Para el experimento se utiliza el famoso *dataset* de *MovieLens*. A diferencia de otros sistemas recomendadores, en este caso se utiliza solo una pequeña parte del *dataset* (5% en este caso) para entrenar al modelo. Creo que este número es bastante pequeño, sin embargo, entiendo que hay que dejar buena parte del *dataset* disponible para simular interacciones iterativas para cada usuario. Con respecto a los parámetros del *bandit ensemble*, extrañé ver cómo estos podían incidir en los resultados de la recomendación.
Con respecto a los resultados, me parece curioso ver como el *Dynamic ensemble* se comporta tan mal, peor que sistemas recomendadores típicos o "base" como el *User-based kNN*. Por otro lado, también me parece interesante que el  se comporte mejor que el *Thompson*, siendo que según la el método en que escoge el sistema recomendador es mucho más simple (muy evidenciable gracias a la Figura 2).
|
Java
|
UTF-8
| 2,435
| 3.546875
| 4
|
[] |
no_license
|
class Solution2 {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode node = head;
int length = 0;
// 计算链表长度
while(node != null){
length++;
node = node.next;
}
// 分治法对子链表排序
ListNode dummy = new ListNode(0,head); // 添加一个伪头结点
// TODO:左移相当于乘2;右移相当于除以2
// TODO: 子链表长度按照2^n递增 n初始值为0,对应sunLength = 1
for(int sunLength = 1; sunLength < length; sunLength <<= 1){
ListNode prev = dummy, curr = dummy.next;
while(curr != null){
ListNode head1 = curr;
// TODO: 注意前后两个for循环的终止条件对curr的判断不一样
for(int i = 1; i < sunLength && curr.next != null; i++){
curr = curr.next;
}
ListNode head2 = curr.next;
curr.next = null;
curr = head2;
for(int i = 1; i < sunLength && curr != null; i++){
curr = curr.next;
}
ListNode next = null;
if(curr != null){
next = curr.next;
curr.next = null;
}
// merge
ListNode merge = mergeLink(head1,head2);
prev.next = merge;
while(prev.next != null){
prev = prev.next;
}
curr = next;
}
}
return dummy.next;
}
// 归并两个有序链表
ListNode mergeLink(ListNode head1, ListNode head2){
if(head1 == null || head2 == null) return head1 == null ? head2 : head1;
ListNode dummy = new ListNode(0);
ListNode tmp = dummy;
while(head1 != null && head2 != null){
if(head1.val <= head2.val){
tmp.next = head1;
head1 = head1.next;
} else{
tmp.next = head2;
head2 = head2.next;
}
tmp = tmp.next;
}
// 将剩余的有序结点追加到已排序链表的末尾
if(head1 != null)
tmp.next = head1;
if(head2 != null)
tmp.next = head2;
return dummy.next;
}
}
|
SQL
|
UTF-8
| 2,549
| 4.0625
| 4
|
[
"MIT"
] |
permissive
|
/* Creates a database for mothy's work */
/* Creates the database if it doesn not exist */
CREATE DATABASE IF NOT EXISTS mothy;
/* Selects database */
USE mothy;
/* Creates the tables. */
/* Creates the Users table. */
CREATE TABLE Users(
uname CHAR(20) UNIQUE NOT NULL,
passwd CHAR(20) NOT NULL,
ulevel INT NOT NULL,
PRIMARY KEY(uname)
);
/* Creates the Song table. */
CREATE TABLE Song(
title CHAR(30) UNIQUE NOT NULL,
alt CHAR(30) UNIQUE,
sdate DATE NOT NULL,
sid INT UNIQUE NOT NULL,
lyrics CHAR(40) UNIQUE NOT NULL,
PRIMARY KEY(sid)
);
/* Creates the Vocaloid table. */
CREATE TABLE Vocaloid(
vname CHAR(30) UNIQUE NOT NULL,
color1 CHAR(7) UNIQUE NOT NULL,
color2 char(7) UNIQUE,
PRIMARY KEY(vname)
);
/* Creates the Persona table. */
CREATE TABLE Persona(
cname CHAR(30) UNIQUE NOT NULL,
vname CHAR(30) NOT NULL,
cid INT UNIQUE NOT NULL,
FOREIGN KEY(vname) REFERENCES Vocaloid(vname),
PRIMARY KEY(cid)
);
/* Creates the Appear table. */
CREATE TABLE Appear(
cid INT NOT NULL,
sid INT NOT NULL,
appears CHAR(10),
FOREIGN KEY(cid) REFERENCES Persona(cid),
FOREIGN KEY(sid) REFERENCES Song(sid),
PRIMARY KEY(sid, cid)
);
/* Creates the Album table. */
CREATE TABLE Album(
atitle CHAR(30) UNIQUE NOT NULL,
rdate DATE NOT NULL,
aid INT UNIQUE NOT NULL,
PRIMARY KEY(aid)
);
/* Creates the Track table. */
CREATE TABLE Track(
aid INT NOT NULL,
sid INT,
tnum INT NOT NULL,
salias CHAR(30) NOT NULL,
FOREIGN KEY(aid) REFERENCES Album(aid),
FOREIGN KEY(sid) REFERENCES Song(sid),
PRIMARY KEY(aid, tnum)
);
/* Creates the Series table. */
CREATE TABLE Series(
sname CHAR(30) UNIQUE NOT NULL,
nid INT UNIQUE NOT NULL,
PRIMARY KEY(nid)
);
/* Creates the Part table. */
CREATE TABLE Part(
nid INT NOT NULL,
sid INT NOT NULL,
pnum INT NOT NULL,
FOREIGN KEY (nid) REFERENCES Series(nid),
FOREIGN KEY (sid) REFERENCES Song(sid),
PRIMARY KEY(nid, sid)
);
/* Creates the Canon table. */
CREATE TABLE Canon(
sid INT UNIQUE NOT NULL,
ec INT,
FOREIGN KEY(sid) REFERENCES Song(sid)
);
/* Creates the Video table. */
CREATE TABLE Video(
sid INT NOT NULL,
upload DATE NOT NULL,
vlink CHAR(30) UNIQUE NOT NULL,
vid INT UNIQUE NOT NULL,
FOREIGN KEY(sid) REFERENCES Song(sid),
PRIMARY KEY(vid)
);
/* Creates the Artist table. */
CREATE TABLE Artist(
vid INT NOT NULL,
aname INT NOT NULL,
FOREIGN KEY(vid) REFERENCES Video(vid)
);
|
C#
|
UTF-8
| 887
| 2.875
| 3
|
[] |
no_license
|
using System;
using System.Threading;
namespace CalcuApplication
{
class NullShow
{ public static void XianCheng1()
{
for (int i = 0; i < 100000; i++)
{
Console.WriteLine("线程1");
Console.WriteLine(i.ToString());
}
}
public static void XianCheng2()
{
for (int i = 0; i < 100000; i++)
{
Console.WriteLine("线程2");
Console.WriteLine(i.ToString());
}
}
static void Main(string[] args)
{
ThreadStart Aa = new ThreadStart(XianCheng1);
ThreadStart Bb = new ThreadStart(XianCheng2);
Thread AA = new Thread(Aa);
Thread BB = new Thread(Bb);
AA.Start();
BB.Start();
}
}
}
|
Java
|
UTF-8
| 1,899
| 2.15625
| 2
|
[] |
no_license
|
/**
*
*/
package build.pluto.buildc.compiler;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.sugarj.common.Exec;
import org.sugarj.common.Exec.ExecutionError;
import org.sugarj.common.Exec.ExecutionResult;
import org.sugarj.common.FileCommands;
import org.sugarj.common.StringCommands;
import org.sugarj.common.errors.SourceCodeException;
import org.sugarj.common.errors.SourceLocation;
import org.sugarj.common.util.Pair;
/**
* @author talen
*
*/
public class GCCompiler implements CCompiler {
private static final long serialVersionUID = -8338564127815270446L;
public static final GCCompiler instance = new GCCompiler();
private GCCompiler() { }
@Override
public CCompilerResult compile(Collection<File> sourceFiles, File targetDir)
throws Exception {
List<String> cmd = new ArrayList<>();
cmd.add("gcc");
cmd.add("-c");
cmd.add("-v");
cmd.add("-H");
for (File sourceFile : sourceFiles){
cmd.add(FileCommands.toWindowsPath(sourceFile.getAbsolutePath()));
}
String errOut = null;
boolean ok = false;
try {
System.err.println(cmd.toString());
ExecutionResult compileResult = Exec.run(targetDir,cmd.toArray(new String[cmd.size()]));
ok = true;
errOut = StringCommands.printListSeparated(compileResult.errMsgs, "\n");
} catch (ExecutionError e) {
errOut = StringCommands.printListSeparated(e.errMsgs, "\n");
}
if (!ok) {
List<Pair<SourceLocation, String>> errors = CompilerUtil.parseGCCErrors(errOut);
if (!errors.isEmpty())
throw new SourceCodeException(errors);
}
Map<File, List<File>> generatedFiles = CompilerUtil.extractGeneratedFiles(sourceFiles,targetDir);
List<File> requiredFiles = CompilerUtil.extractRequiredFiles(errOut);
return new CCompilerResult(generatedFiles, requiredFiles);
}
}
|
Markdown
|
UTF-8
| 6,888
| 3.640625
| 4
|
[
"BSD-3-Clause"
] |
permissive
|
# pyfmt

pyfmt implements Python's advanced string formatting in Golang.
This is an alternative to the `fmt` package's Sprintf-style string formatting and mimics the
.format() style formatting available in Python >2.6. Under the hood, it still uses the go 'fmt'
library, for better compatibility with Go types at the expense of not being as exact of a clone of
Python format strings.
Braces {} are used to indicate 'format items', anything outside of braces will be emitted directly
into the output string, and anything inside will be used to get values from the other function
arguments and format them. The one exception is double braces, '{{' and '}}', which will cause
literal '{' and '}' runes to be emitted in the output.
Each format item consists of a 'field name', which indicates which value from the argument list to
use, and a 'format specifier', which indicates how to format that item.
Requires Golang 1.5 or newer for formatting, 1.9 or newer to run the tests.
# Functions
pyfmt implements three functions, 'Fmt', 'Must', and 'Error'. 'Fmt' formats, but may return an error
as detailed below. 'Must' formats, but will panic when 'Fmt' would return an error, and 'Error' acts
like 'Fmt', but returns an error type. In the event that there's an error formatting the error,
'Error' includes the format error and as much of the formatted string as possible.
All of them take a format string and arguments to be used in formatting that string.
# Getting Values from Field Names
Values can be fetched from field names in two forms: simple names or compound names. All compound
names build off of simple names.
## Simple field names:
The simplest look up treats the argument list as just a list. There are two possible ways to look up
elements from this list. First, by {}, which gets the 'next' item and by {n}, which gets the nth
item. Accessing these two ways is independent but cannot be mixed, and
```
pyfmt.Must("{} {} {}", ...)
```
is equivalent to
```
pyfmt.Must("{0} {1} {2}", ...)
```
Accessing an element that's outside the list range will return an error (with Fmt) or panic (with
Must).
The first element in the list is treated specially if it's a struct or a map with string keys,
allowing the elements from that struct or map can be directly accessed. For instance:
```
pyfmt.Must("{test}", map[string]int{"test": 5}) --> "5"
```
similarly for structs:
```
pyfmt.Must("{test}": myStruct{test: 5}) --> "5"
```
Attempting to read from an undefined key will return an error or panic, depending on if it was
accessed with Fmt or Must.
## Compound field names:
If the value referenced by the field is itself a List, map[string]interface{}, or struct, it can be
further accessed in the format string.
Lists are accessed with square brackets:
```
pyfmt.Must("{0[0]}", []string{"test"}) --> "test"
```
similarly, maps are accessed with square brackets:
```
pyfmt.Must("{0[test]}", map[string]interface{}{"test": "42"}) --> "42"
```
and struct fields are accessed with a period ('.')
```
pyfmt.Must("{foo.bar.baz}", MyStruct{foo: Foo{bar: Bar{baz: "test"}}}) --> "test"
```
# Formatting
If after a simple or complex field name, there's a ':', what follows is considered to be the format
specifier. If a type satisfies the PyFormat interface (discussed below), the format specifier will
be passed to that, but otherwise, it will fall back to the default formatter, which expects the
standard format specifier:
```
[[fill]align][sign][#][0][minimumwidth][.precision][type]
```
The optional align feature can be one of the following:
```
'<': left-aligned
'>': right-aligned (this is the default)
'=': padding after the sign, but before the digits (e.g., for +000042)
'^': centered
```
If an align flag is defined, a 'fill' character can also be defined. If undefined, space (' ') will
be used.
The optional 'sign' is only valid for numeric types and can be:
```
'+': Show sign for both positive and negative numbers
'-': Show sign only for negative numbers (default)
' ': use a leading space for positive numbers
```
If # is present, when using the binary, octal, or hex types, a '0b', '0o', or '0x' will be
prepended, respectively.
The minimumwidth field specifies a minimum width, which is helpful when used with alignment. If
preceded with a zero, numbers will be zero-padded.
The precision field specifies a maximum width for non-floating point, non-integer types, and the
number of points to show after the decimal point for floating types.
The 'type' format determines what type the value will be formatted as.
For integers:
```
'b' - Binary, base 2
'd' - Decimal, base 10 (default)
'o' - Octal, base 8
'x' - Hexadecimal, base 16
'X' - Hexadecimal, base 16, using upper-case letters
```
For floats and complex numbers:
```
'e' - Scientific notation
'E' - Similar to e, but uppercase
'f' - Fixed point, displays the number as a fixed-point number.
'F' - Same, but uppercase.
'g' - General format, prints as a fixed point unless it's too large, then switches to scientific
notation. (default)
'G' - Similar to g, but uses capital letters
'%' - Percentage, multiplies the number by 100 and displays it with a '%' sign. Can also be
applied to integer types.
```
## Special Formatting Types
For some types (most notably structs), the default formatter doesn't quite give enough information
to understand the value after its printed, so it's useful to get more accurate Go representations.
Additionally, sometimes it's useful to print the type of a variable while formatting it. For these,
pyfmt allows for some special formatting types that aren't in the Python format syntax.
```
'r' - convert the value to its Go-syntax representation
't' - convert the value to its Go type
's' - if printing a struct, print the struct field names
```
These are equivalent to the `%#v`, `%T` and `%+v` format strings in the "fmt" package, but don't
have an exact equivalent in Python.
# Custom formatters
Internally, pyfmt uses Go's fmt package, so existing types satisfying its Formatter, GoStringer,
or Stringer interfaces will use those implementations as appropriate.
If the type satisfies the PyFormatter interface, the format specifier will be passed to that
function, for custom formatting. Due to the limits of Golang reflection, if accessing a struct
sub-field that has a custom formatter, the struct field must be exported for pyfmt to access the
custom Formatter. This is similar to the default 'fmt' package, which doesn't apply custom Stringer
implementations to unexported struct fields.
# TODOs
* Improve performance. Some of the string manipulations allocate more frequency than they need
to, causing slowdown relative to the built-in 'fmt' library.
|
Java
|
UTF-8
| 1,170
| 3.03125
| 3
|
[] |
no_license
|
package Interface;
public abstract class Empregado implements APagar {
private String primeiroNome;
private String sobrenome;
private String numeroSegurancaSocial;
public Empregado(String primeiroNome, String sobrenome, String numeroSegurancaSocial) {
this.primeiroNome = primeiroNome;
this.sobrenome = sobrenome;
this.numeroSegurancaSocial = numeroSegurancaSocial;
}
public String getNumeroSegurancaSocial() {
return numeroSegurancaSocial;
}
public void setNumeroSegurancaSocial(String numeroSegurancaSocial) {
this.numeroSegurancaSocial = numeroSegurancaSocial;
}
public String getPrimeiroNome() {
return primeiroNome;
}
public void setPrimeiroNome(String primeiroNome) {
this.primeiroNome = primeiroNome;
}
public String getSobrenome() {
return sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
@Override
public String toString() {
return String.format("%s %s\nNumero Seguranca Social: %s", getPrimeiroNome(), getSobrenome(), getNumeroSegurancaSocial());
}
}
|
Ruby
|
UTF-8
| 2,023
| 3.65625
| 4
|
[] |
no_license
|
# USAGE:
# ./markov_generator file1 [file2 file3] [seed_word]
class MarkovEntry
attr_accessor :total_words
def initialize preceding_word
@words = Hash.new
@preceding_word = preceding_word
@total_words = 0
@cumulative = Array.new
end
def add_word word
# access internal entry for word
# and increment counter and adjust probability
@total_words += 1
if @words[word].nil?
@words[word] = 0
end
@words[word] += 1
end
def calculate_probabilities
# inverse transform sampling
frequencies = @words.values
@cumulative = Array.new frequencies.length, 0
@cumulative[0] = frequencies[0]
frequencies.each_with_index do |f, ind|
@cumulative[ind] = @cumulative[ind - 1] + f if ind > 0
end
end
def sample
# inverse transform sampling
random_index = @cumulative.bsearch_index{ |n| n >= rand(@cumulative.last) }
return @words.keys[random_index]
end
end
freq = Hash.new
total_words = 0
if File.exist?('marshalled')
freq = Marshal.load(File.open('marshalled', 'rb').read)
total_words = freq.each_value.map{|v| v.total_words }.reduce(total_words, :+)
else
ARGV.each do |f|
if !f.end_with?(".txt")
next
end
words = File.open(f, 'r').read.split(' ')
words.each_cons(2) do |word_tuple|
key = word_tuple.first.downcase
if freq[key].nil?
freq[key] = MarkovEntry.new key
end
freq[key].add_word word_tuple.last.downcase
end
end
freq.each_pair do |key, value|
value.calculate_probabilities
total_words += value.total_words
end
end
puts "Model contains #{total_words} words"
current_seed = ARGV.last
if freq[current_seed].nil?
current_seed = freq.keys.sample
end
puts "Trump on #{current_seed}:"
print "\"#{current_seed} "
loop do
current = freq[current_seed].sample
print current
current_seed = current
if current.chars.last == '.'
break
else
print " "
end
end
puts '"'
f = File.open("marshalled", "w")
f.write(Marshal.dump(freq))
|
C++
|
UTF-8
| 1,480
| 3.453125
| 3
|
[] |
no_license
|
#ifndef __CIRCLE_H__
#define __CIRCLE_H__
#include "shape.h"
#include <iostream>
#define PI 3.1415926
class Circle:public Shape{
protected:
double r;
public:
Circle():Shape(0,0),r(1.0){
cout<<"in circle():"<<endl;
this->r = r;
};
Circle(double r):Shape(0,0){
cout<<"in Circle(double)"<<endl;
this->r = r;
}
double get_r(){
return this->r;
}
void set_r(double r){
this->r = r;
}
virtual void draw(){
cout<<"in circle draw, r:"<<r<<endl;
}
virtual double get_area(){
cout<<"in circle get_area():"<<endl;
return PI*r*r;
}
};
class Rectangle:public Shape{
protected:
double height;
double width;
public:
Rectangle():height(1.0),width(1.0),Shape(0,0){
cout<<"in Rectangle():"<<endl;
};
Rectangle(double height,double width):Shape(0,0){
cout<<"in Rectangle(double,double):"<<endl;
this->height= height;
this->width = width;
}
Rectangle(int x,int y,double height,double width):Shape(x,y){
cout<<"in Rectangle(double,double):"<<endl;
this->height= height;
this->width = width;
}
double get_height(){
return this->height;
}
void set_height(double height){
this->height = height;
}
double get_width(){
return this->width;
}
void get_width(double width){
this->width = width;
}
virtual void draw(){
cout<<"height:"<<height;
cout<<"width:"<<width<<endl;
}
virtual double get_area(){
cout<<"in Rectangle:"<<endl;
return height*width;
}
};
#endif
|
Markdown
|
UTF-8
| 31,577
| 3.109375
| 3
|
[] |
no_license
|
---
title: '[转载] 技术大牛养成指南,一篇不鸡汤的成功学实践'
date: 2017-07-20 13:39:55
tags:
categories: 技术提升
---
本文转载自[李运华 InfoQ](https://mp.weixin.qq.com/s/5PfaaWBFCw5-MuAnR7ABiQ)
>有的人想成为大牛,却不曾为此努力。有的人辛苦耕耘,却收获寥寥。很多时候,你跟成功的差距并不是能力,也不是运气,或许只是正确的方法?这是一篇不鸡汤的成功学指南,如果你相信且愿意坚持尝试,未必帮不到你!
### 1. 一碗有勺子的鸡汤
我工作已经将近12年了(其实12年才混到这个地步,天资实在是一般),在华为做了5年,在UC做了6年,现在主要负责阿里游戏的中间件和组件的架构设计和实现,包括用户消息推送、系统异步通知系统等等。
同时我还带了三四十人的研发团队,除了工作以外,我也喜欢写博客,是CSDN、云栖的社区之星和博客专家,InfoQ的签约作者。
总体上来说,我现在虽然还算不上业界顶级的大牛,但在公司也算一头小牛了,今天我的分享将综合自己的成长经历给大家谈一谈怎么样成为一个大牛。我现在还在业界的大牛路上狂奔,但我觉得这些经验和技巧应该是每个同学都可以用到自己的日常工作和生活当中的。
### 2. 一鸣惊人背后是1万小时的不断练习
如何成为大牛?这个问题之前有很多人问我:你是怎么成为技术上的一个大牛的?
最开始的时候我也经常跟他们讲你要去看看某某某开发方案,深入学习UNIX的开发等等这些“术”的东西,后来我在思考,是否有成为一种大牛的“道”上面的东西,也就是说不管你做产品、做运营、做运维、程序员还是测试,通过这个方式都能够成为一个大牛呢?
通过寻找和思考,后来真的让我找到了应用到所有行业、所有职业我称之为成为大牛的一个道,这是1万小时理论。
我先简单介绍一下1万小时理论,我最初看到1万小时理论是从《异类》这本书知道的,这是很出名的书,它非常有意思,我建议所有同学都去看一下,它分析了很多成功人士背后一些我们通常情况下不了解或没看到的一些现象,得出一些比较令人震撼的结论,其中有一个理论就是1万小时理论。
它里面有举了一些例子,比如说莫扎特,大家都知道他是音乐神童,6岁就开始作曲了,你看完这本书就知道他真正出人头地是20多岁的时候,也就是说他虽然6岁开始作曲,但他当时作的曲也是比较不好的。
所以《异类》这本书里面提到了1万小时的理论,它对我是很有帮助的,成为世界上顶级的专家唯一的方法就是1万小时持续不断地进行练习,大家要特别注意**“唯一”**,也就是说绝大部分专业是没有什么天才的,所谓的天才只是他一鸣惊人之后我们才这样觉得,在他成为天才之前至少要经过1万小时持续不断的练习。
我第一次看到1万小时的理论,觉得没什么神奇的,我算了算,我工作五年就会成为业界顶级的专家了,但想想这是不可能的,为什么呢?我反思了一下我自己的工作状态,对于大部分人来说每天的工作很多时候是重复劳动,虽然我们一天工作8小时,但是只是重复以往的经验,并没有刻意去训练提升自己。
有一个笑话是有一个10年工作经验的人去面试,面试完了之后面试官跟他说其实你只有1年工作经验,你把它重复了9年。
对于1万小时理论来说如果你深入思考其实它并没有那么简单,这意味着什么呢?意味着你每天要花3小时时间用于提升自己的技能,这样一直做,要持续大约10年时间。大家想想每天持续十年去做一件事情去提升自己,有几个能做到,所以我们看到虽然有些人工作了10年,但是也不一定能成为业界的专家。
为什么我要强调每天3小时?持续10年提升自己,你不能把你重复的工作算进去,你要在专业广度和深度上面不断扩展,才能业界一个顶尖的大牛或者专家。
举一个例子,一个小孩子每天唱《两只老虎》,唱10年,你觉得他会成为周杰伦吗?肯定不会。当然1万小时理论不适合一些领域,尤其是不适合炒股,特别是中国的股市,如果你花1万小时去炒股,可能会倾家荡产。
### 3. 如何找到10000小时?
*碎片化时间管理*
1万小时理论听起来好像很简单,每天持续3小时,也不难,但实际上真正做起来是很难的,就像我们互联网的人加班加成狗,感觉身体天天被掏空,时间从哪来,这是一个现实问题,不要说每天抽3个小时提升自己,每天抽1个小时陪女朋友或者找女朋友的时间都不够。具体怎么做?
* **首先是找到3个30分钟:**
第一个30分钟就是早上的30分钟,假设你习惯8点起床,明天你把闹钟改成7点半,这就多了半个小时。
第二个30分钟是睡觉前的30分钟,假设你习惯玩游戏到12点,明天晚上你玩游戏就玩到11点半。
第三个30分钟就是上班到你座位上的30分钟,有的同学担心说我这30分钟会不会影响我这一天的工作效率,可能加班完不成,还让我挤出30分钟来,这不用担心,从我的经历来看挤30分钟不会影响你整体的工作效率,持续一两年,你会发现自己的收益非常大。
* **第二点是利用或节省路途时间**
我们每天上下班都是一两个小时,比如像我这种,怎么去利用时间呢?
首先是可以利用上下班路上的时间去看书、听书,也是可以做的。如果你觉得上班路上是不能看书的,或者是不可能学习的,比如你坐广州的3号线,这是举世闻名的挤得要命的,不要说看书了,把手伸出去都不知道去哪了,那就建议大家搬到离公司近一点位置,虽然每个月多几百块钱的房租,但是你要相信这个投资节省下来的时间用于提升自己,它最终的收益是10倍回报都不止的。
* **第三点是周末4小时**
周末还是不用怎么加班的,周末用于放松、睡觉、看电影、娱乐,你也可以在周末里面规定自己挤出4个小时,也就是每天2个小时,这样算下来,一天大概就两个多小时,再加上你在工作中的积累,每天3小时也不是很难。
接下来讲一下我是怎么做的,我现在有2个小孩,而且我住的比较远,应该在座的比我忙的也不会很多,看一下我是怎么做的,我是坐广州的四号线,坐四号线每天来回可以看一个小时的书,每天早晚30分钟,周末4小时,有的同学可能会有疑问,周末肯定要带小孩玩,自己也要休息,哪里有4个小时,其实只要你去找,时间都会有的,我找的方法就是当我小孩睡觉的时候,因为小孩子睡觉一般要睡三四个小时,大人一般睡一个小时、半个小时就差不多了,所以通过这种方式,大家可以看到2015年我一共看了84本书,有专业的,也有非专业的,人文社科、历史这些都有。
不过特别提醒一下对于男程序员来说有一个时间千万不能少,就是陪女朋友的时间,因为对程序员来说找女朋友不容易,别看了这篇文章回去之后女朋友也不要了,就天天回去提升,这也不是我们想要的生活。
### 4. 10000小时理论如何轻松落地?
虽然理论上很简单,但真正要落地实行也并不那么容易,实行10000小时理论的关键在于坚持,我认为坚持的关键在于自己对于所从事的事业是否有“激情和兴趣”。这点当然是核心,但如果只靠激情支撑,持续10年也确实有挑战,正如一个朋友在分享会后问我的“要持续10年才能成为大牛啊,时间好长啊”!
如果说做一件事要10年后才能修成正果,估计很多朋友就会放弃了,毕竟像唐僧那么坚定的信仰者总是少数,大部分凡夫俗子都还是需要持续不断的激励才能有动力去做一件事,因为我们的大脑在进化的过程中已经形成了需要持续不断的奖励才能保持兴奋的机制,也就是说相对于在第10年给一个大奖励,还不如每年给一个小奖励。
那如何才能在10年漫长的路上让我们持续的坚持下去呢?答案其实就是首富的话:“先定一个能达到的小目标”!我们来看如何将“10年成为大牛”这个目标分解为一个个能达到的小目标。我将这个方法归纳为“三段分解法”,即:将一个宏大或者长远的目标经过3次分解,得到一个个短期内能达到的小目标。具体的分解方法如下。
* *一段分解:分解“等级”*
10年成为大牛的目标虽然比较长远比较宏大,但并不意味着在没有成为大牛前,我们一直都是菜鸟。从菜鸟到大牛的过程中,中间其实有几个关键的里程碑,这些里程碑就是我们的一段目标。
以技术人员为例,技术人员典型的发展路径基本上都是下面的这个模式:
1) 0 ~ 1年:菜鸟,需要别人手把手来教
2)1 ~ 3年:初级,需要别人带你做
3)3 ~ 5年:高级,能独当一面,可以带初级技术人员了
4)5 ~ 8年:资深,能独挡多面
5)8 ~ 10年:大牛,统筹规划,高屋建瓴
通过上面的分解我们可以看到,虽然说10年才能成为大牛,但是3年就可以达到初级水平,5年就可以达到高级水平,8年就可以达到资深水平,在这个过程中我们一直在成长和提升,而不是说没有成为大牛就是菜鸟;并且对于很多朋友来说,如果目标不是像首富那样要赚就赚1亿,能达到高级或者资深水平,其实已经可以过得比较滋润了。
通过这种分解方法,再核对一下自己目前所处的位置,然后先瞄准下一个目标,全力以赴其实也就2 ~ 3年时间,这样来看一段目标其实是比较容易达成的。这种目标分解的方法除了适合技术人员外,其它很多领域也都适应,比如说产品人员、运营人员、甚至公务员!
* *二段分解:分解“技能”*
经过一段分解后,明确自己目前所处的位置和下一个目标,接下来就要看这个一段目标如何实现了。虽然说每个一段目标持续时间在 2~3年,但3年时间说长不长,说短也不短,如果没有好好利用,可能到了2年多的时候回头一看,好像什么都没达成,还是原地踏步。因此,为了更好的利用这3年时间,我们需要进一步分解,这就是“二段分解”。
一段分解的维度是等级,二段分解的维度则不一样,不能再分等级了,否则等级太细就没法区别了。二段分解的维度变成了“技能”,即:为了达到一段目标,我需要具备什么样的技能。
还是以技术人员为例,假设经过自我评估,认为自己目前处于初级阶段,而且初级阶段的事情已经做得比较顺手和熟练了,那么下一个一段目标自然就是达到“高级”水平。“高级”与“初级”相比,有哪些不同的技能要求呢?
这就需要我们根据各自不同的行业和方向详细列出来了,如果自己想不出来,网上有很多资料都可以搜索到,最方便的就是到一个招聘网站,多看看几个招聘需求的描述,然后归纳总结一下。
我们随便到网上搜索一个,例如拉勾网上滴滴的“高级Java开发工程师”招聘:

多看几个类似的职位招聘,基本上我们就能明白“高级Java开发工程师”的一些基本要求。当然实际上的技能要求比招聘需求的描述还要更加细致,我个人的习惯是将这些要求整理为一个思维导图,详细列出每个技术点。例如:

注意:以上这个图只是示例,并不是说所有Java高级工程师都一定是这个要求,例如互联网行业和电信行业的要求不一样)
有了这样一个思维导图后,我们就可以开始真正进行二段分解了,分解的方法很简单:哪里不懂补哪里!例如:我感觉目前我的数据库水平一般,仅仅会写CRUD语句,其它的东西都不懂,那我就开始专攻数据库这一部分,经过一段时间的专攻来提升自己的水平。
二段目标持续时间一般建议是6个月,既不能太短也不能太长。太短容易让人陷入为了目标而做的误区,没有真正得到有效提升;时间太长的话,3年时间又不够完成其它目标了,例如要是我定一个目标说2年提升数据库,那操作系统怎么办?网络怎么办?……等等。以6个月为一个周期,基本上刚刚好。
经过分解,最终的二段目标可以分解为如下的几个更小的目标:
1)2016.06 ~ 2017.01:提升数据库水平
2)2017.01 ~ 2017.06:提升Linux水平
3)2017.06 ~ 2017.12:提升网络和网络编程水平
当然,二段分解目标并不是一成不变的,很多时候需要根据我们工作的内容进行调整。例如老大正好安排我来负责优化系统性能,降低机器负载,那么我完全可以将“提升Linux水平”安排到“提升数据库水平”之前。
* *三段分解:分解“行动”*
二段分解得到技能的小目标后,接下来的关键就是要实现这个目标,这就是三段分解的主要目的,即:将技能目标分解为具体要做的事情,然后按照计划执行。
比如说我的二段目标是“提升Linux水平”,那怎么样才能提升呢?可以上网搜索(知乎是个好地方),也可以去问有经验的朋友。明确要做的事情后,三段分解需要将二段分解的6个月目标更加细化,分为1个月或者两个月一个目标。
以我当时加入UC的情况为例,我在华为的时候是在Windows平台上用VC6进行开发,而到了UC的时候是在Linux平台上用C++开发,我当时定了“提升Linux水平”的目标,然后通过上网查,找别人问等方法,最终将这个目标分解为几个步骤:
1)1个月:通读《UNIX环境高级编程》
2)1个月:通读《Linux系统编程》
3)2个月:通读《UNIX网络编程 卷1》
4)1个月:Linux常用命令实战:tcpdump、ps、top等
通过这种方法,将6个月的目标又进一步分解为1个月的目标,实施起来就简单多了,每1 ~ 2个月专注一个具体目标,每次完成后都很有成就感,既感觉自己的水平有了提升,又佩服自己能够坚持按计划按目标完成任务,双重奖赏让自己更有动力进行下一个目标。
我大约花了2年的时间将Linux、网络、MySQL三个重点技能从一无所知提升到高级的水平,很多同事都问我之前在华为是不是就是做这方面的,因为他们觉得短时间能达到这个水平是不太可能的。
综合前面的分析,我们将三段分解提炼一下:一段分解“等级”,二段分解“技能”,三段分解“行动”。通过前面我们的案例就可以看出,原本一个宏大的“10年成为技术大牛”的目标,经过三段分解,最终得到的是1 ~ 2个月可执行的具体行动,通过这种一步一个脚印的行动,最终就可以达成“10年成为技术大牛”的目标。
### 5. 天天写业务代码,如何成为技术大牛?
**几个典型的误区**
* 拜大牛为师
知乎上有人认为想成为技术大牛最简单直接、快速有效的方式是“拜团队技术大牛为师”,让他们平时给你开小灶,给你分配一些有难度的任务。我个人是反对这种方法的,主要的原因有几个:
1. 大牛很忙,不太可能单独给你开小灶,更不可能每天都给你开1个小时的小灶;而且一个团队里面,如果大牛平时经常给你开小灶,难免会引起其他团队成员的疑惑,我个人认为如果团队里的大牛如果真正有心的话,多给团队培训是最好的。然而做过培训的都知道,准备一场培训是很耗费时间的,课件和材料至少2个小时(还不能是碎片时间),讲解1个小时,大牛们一个月做一次培训已经是很高频了。
2. 因为第一个原因,所以一般要找大牛,都是带着问题去请教或者探讨。因为回答或者探讨问题无需太多的时间,更多的是靠经验和积累,这种情况下大牛们都是很乐意的,毕竟影响力是大牛的一个重要指标嘛。然而也要特别注意:如果经常问那些书本或者google能够很容易查到的知识,大牛们也会很不耐烦的,毕竟时间宝贵。经常有网友问我诸如“jvm的-Xmn参数如何配置”这类问题,我都是直接回答“请直接去google”,因为这样的问题实在是太多了,如果自己不去系统学习,每个都要问是非常浪费自己和别人的时间的。
3. 大牛不多,不太可能每个团队都有技术大牛,只能说团队里面会有比你水平高的人,即使他每天给你开小灶,最终你也只能提升到他的水平;而如果是跨团队的技术大牛,由于工作安排和分配的原因,直接请教和辅导的机会是比较少的,单凭参加几次大牛的培训,是不太可能就成为技术大牛的。
综合上述的几个原因,我认为对于大部分人来说,要想成为技术大牛,首先还是要明白“主要靠自己”这个道理,不要期望有个像武功师傅一样的大牛手把手一步一步的教你。适当的时候可以通过请教大牛或者和大牛探讨来提升自己,但大部分时间还是自己系统性、有针对性的提升。
* 业务代码一样很牛逼
知乎上有的回答认为写业务代码一样可以很牛逼,理由是业务代码一样可以有各种技巧,例如可以使用封装和抽象使得业务代码更具可扩展性,可以通过和产品多交流以便更好的理解和实现业务,日志记录好了问题定位效率可以提升10倍……等等。
业务代码一样有技术含量,这点是肯定的,业务代码中的技术是每个程序员的基础,但只是掌握了这些技巧,并不能成为技术大牛,就像游戏中升级打怪一样,开始打小怪,经验值很高,越到后面经验值越少,打小怪已经不能提升经验值了,这个时候就需要打一些更高级的怪,刷一些有挑战的副本了,没看到哪个游戏只要一直打小怪就能升到顶级的。
成为技术大牛的路也是类似的,你要不断的提升自己的水平,然后面临更大的挑战,通过应对这些挑战从而使自己水平更上一级,然后如此往复,最终达到技术大牛甚至业界大牛的境界,写业务代码只是这个打怪升级路上的一个挑战而已,而且我认为是比较初级的一个挑战。
所以我认为:**业务代码都写不好的程序员肯定无法成为技术大牛,但只把业务代码写好的程序员也还不能成为技术大牛。**
* 上班太忙没时间自己学习
很多人认为自己没有成为技术大牛并不是自己不聪明,也不是自己不努力,而是中国的这个环境下,技术人员加班都太多了,导致自己没有额外的时间进行学习。
这个理由有一定的客观性,毕竟和欧美相比,我们的加班确实要多一些,但这个因素只是一个需要克服的问题,并不是不可逾越的鸿沟,毕竟我们身边还是有那么多的大牛也是在中国这个环境成长起来的。
我认为有几个误区导致了这种看法的形成:
1)上班做的都是重复工作,要想提升必须自己额外去学习
形成这个误区的主要原因还是在于认为“写业务代码是没有技术含量的”,而我现在上班就是写业务代码,所以我在工作中不能提升。
2)学习需要大段的连续时间
很多人以为要学习就要像学校上课一样,给你一整天时间来上课才算学习,而我们平时加班又比较多,周末累的只想睡懒觉,或者只想去看看电影打打游戏来放松,所以就没有时间学习了。
正确的做法正好相反:
首先我们应该在工作中学习和提升,因为学以致用或者有实例参考,学习的效果是最好的;其次工作后学习不需要大段时间,而是要挤出时间,利用时间碎片来学习。(参照前文10000小时理论)
**正确的做法**
Do more
做的更多,做的比你主管安排给你的任务更多。
我在HW的时候,负责一个版本的开发,这个版本的工作量大约是2000行左右,但是我除了做完这个功能,还将关联的功能全部掌握清楚了,代码(大约10000行)也全部看了一遍,做完这个版本后,我对这个版本相关的整套业务全部很熟悉了。经过一两次会议后,大家发现我对这块掌握最熟了,接下来就有趣了:产品讨论需求找我、测试有问题也找我、老大对外支撑也找我;后来,不是我负责的功能他们也找我,即使我当时不知道,我也会看代码或者找文档帮他们回答……最后我就成了我这个系统的“专家”了。虽然这个时候我还是做业务的,还是写业务代码,但是我已经对整个业务都很熟悉了。
以上只是一个简单的例子,其实就是想说:要想有机会,首先你得从人群中冒出来,要想冒出来,你就必须做到与众不同,要做到与众不同,你就要做得更多!
怎么做得更多呢?可以从以下几个方面着手:
1)熟悉更多业务,不管是不是你负责的;熟悉更多代码,不管是不是你写的
这样做有很多好处,举几个简单的例子:
需求分析的时候更加准确,能够在需求阶段就识别风险、影响、难点
问题处理的时候更加快速,因为相关的业务和代码都熟悉,能够快速的判断问题可能的原因并进行排查处理
方案设计的时候考虑更加周全,由于有对全局业务的理解,能够设计出更好的方案
2)熟悉端到端
比如说你负责web后台开发,但实际上用户发起一个http请求,要经过很多中间步骤才到你的服务器(例如浏览器缓存、DNS、nginx等),服务器一般又会经过很多处理才到你写的那部分代码(路由、权限等)这整个流程中的很多系统或者步骤,绝大部分人是不可能去参与写代码的,但掌握了这些知识对你的综合水平有很大作用,例如方案设计、线上故障处理这些更加有含金量的技术工作都需要综合技术水平。
“系统性”、“全局性”、“综合性”这些字眼看起来比较虚,但其实都是技术大牛的必备的素质,要达到这样的境界,必须去熟悉更多系统、业务、代码。
3)自学
一般在比较成熟的团队,由于框架或者组件已经进行了大量的封装,写业务代码所用到的技术确实也比较少,但我们要明白“唯一不变的只有变化”,框架有可能要改进,组件可能要替换,现有技术可能已经无法满足业务需求,或者你换了一家公司,新公司既没有组件也没有框架,要你从头开始来做。这些都是机会,也是挑战,而机会和挑战只会分配给有准备的人,所以这种情况下我们更加需要自学更多东西,因为真正等到要用的时候再来学已经没有时间了。
以java为例,大部分业务代码就是if-else加个数据库操作,但我们完全可以自己学些更多java的知识,例如垃圾回收,调优,网络编程等,这些可能暂时没用,但真要用的时候,不是google一下就可以了,这个时候谁已经掌握了相关知识和技能,机会就是谁的。
以垃圾回收为例,我自己平时就抽时间学习了这些知识,学了1年都没用上,但后来用上了几次,每次都解决了卡死的大问题,而有的同学,写了几年的java代码,对于stop-the-world是什么概念都不知道,更不用说去优化了。
特别是很多开源软件,更加需要自己平时去自学,例如Nginx、Redis、Mongodb、ElasticSearch等,在合适的时机引入这些技术,能够带来很大的价值。
Do better
要知道这个世界上没有完美的东西,你负责的系统和业务,总有不合理和可以改进的地方,这些“不合理”和“可改进”的地方,都是更高级别的怪物,打完后能够增加更多的经验值。识别出这些地方,并且给出解决方案,然后向主管提出,一次不行两次,多提几次,只要有一次落地了,这就是你的机会。
例如:
重复代码太多,是否可以引入设计模式?
系统性能一般,可否进行优化?
目前是单机,如果做成双机是否更好?
版本开发质量不高,是否引入高效的单元测试和集成测试方案?
目前的系统太庞大,是否可以通过重构和解耦改为3个系统?
阿里中间件有一些系统感觉我们也可以用,是否可以引入 ?
只要你去想,其实总能发现可以改进的地方的;如果你觉得系统哪里都没有改进的地方,那就说明你的水平还不够,可以多学习相关技术,多看看业界其它公司怎么做,BAT都怎么做。
我2013年调配到九游,刚开始接手了一个简单的后台系统,每天就是配合前台做数据增删改查,看起来完全没意思,是吧?如果只做这些确实没意思,但我们接手后做了很多事情:
解耦,将一个后台拆分为2个后台,提升可扩展性和稳定性;
双机,将单机改为双机系统,提高可靠性;
优化,将原来一个耗时5小时的接口优化为耗时5分钟
还有其它很多优化,后来我们这个组承担了更多的系统,后来这个小组5个人,负责了6个系统。
Do exercise
在做职业等级沟通的时候,发现有很多同学确实也在尝试Do more、Do better,但在执行的过程中,几乎每个人都遇到同一个问题:光看不用效果很差,怎么办?
例如:
学习了jvm的垃圾回收,但是线上比较少出现FGC导致的卡顿问题,就算出现了,恢复业务也是第一位的,不太可能线上出现问题然后让每个同学都去练一下手,那怎么去实践这些jvm的知识和技能呢?
Netty我也看了,也了解了Reactor的原理,但是我不可能参与Netty开发,怎么去让自己真正掌握Reactor异步模式呢?
看了《高性能MySQL》,但是线上的数据库都是DBA管理的,测试环境的数据库感觉又是随便配置的,我怎么去验证这些技术呢?
框架封装了DAL层,数据库的访问我们都不需要操心,我们怎么去了解分库分表实现?
诸如此类问题还有很多,我这里分享一下个人的经验,其实就是3个词:learning、trying、teaching!
1)Learning
这个是第一阶段,看书、google、看视频、看别人的博客都可以,但要注意一点是“系统化”,特别是一些基础性的东西,例如JVM原理、Java编程、网络编程,HTTP协议。。。。。。等等,这些基础技术不能只通过google或者博客学习,我的做法一般是先完整的看完一本书全面的了解,然后再通过google、视频、博客去有针对性的查找一些有疑问的地方,或者一些技巧。
2)Trying
这个步骤就是解答前面提到的很多同学的疑惑的关键点,形象来说就是“自己动手丰衣足食”,也就是自己去尝试搭建一些模拟环境,自己写一些测试程序。例如:
Jvm垃圾回收:可以自己写一个简单的测试程序,分配内存不释放,然后调整各种jvm启动参数,再运行的过程中使用jstack、jstat等命令查看jvm的堆内存分布和垃圾回收情况。这样的程序写起来很简单,简单一点的就几行,复杂一点的也就几十行。
Reactor原理:自己真正去尝试写一个Reactor模式的Demo,不要以为这个很难,最简单的Reactor模式代码量(包括注释)不超过200行(可以参考Doug Lee的PPT)。自己写完后,再去看看netty怎么做,一对比理解就更加深刻了。
MySQL:既然有线上的配置可以参考,那可以直接让DBA将线上配置发给我们(注意去掉敏感信息),直接学习;然后自己搭建一个MySQL环境,用线上的配置启动;要知道很多同学用了很多年MySQL,但是连个简单的MySQL环境都搭不起来。
框架封装了DAL层:可以自己用JDBC尝试去写一个分库分表的简单实现,然后与框架的实现进行对比,看看差异在哪里。
用浏览器的工具查看HTTP缓存实现,看看不同种类的网站,不同类型的资源,具体是如何控制缓存的;也可以自己用Python写一个简单的HTTP服务器,模拟返回各种HTTP Headers来观察浏览器的反应。
还有很多方法,这里就不一一列举,简单来说,就是要将学到的东西真正试试,才能理解更加深刻,印第安人有一句谚语:I hear and I forget. I see and I remember. I do and I understand,而且“试试”其实可以比较简单,很多时候我们都可以自己动手做。
当然,如果能够在实际工作中使用,效果会更好,毕竟实际的线上环境和业务复杂度不是我们写个模拟程序就能够模拟的,但这样的机会可遇不可求,大部分情况我们还真的只能靠自己模拟,然后等到真正业务要用的时候,能够信手拈来。
3)Teaching
一般来说,经过Learning和Trying,能掌握70%左右,但要真正掌握,我觉得一定要做到能够跟别人讲清楚。因为在讲的时候,我们既需要将一个知识点系统化,也需要考虑各种细节,这会促使我们进一步思考和学习。同时,讲出来后看或者听的人可以有不同的理解,或者有新的补充,这相当于继续完善了整个知识技能体系。
这样的例子很多,包括我自己写博客的时候经常遇到,本来我觉得自己已经掌握很全面了,但一写就发现很多点没考虑到;组内培训的时候也经常看到,有的同学写了PPT,但是讲的时候,大家一问,或者一讨论,就会发现很多点还没有讲清楚,或者有的点其实是理解错了。写PPT、讲PPT、讨论PPT,这个流程全部走一遍,基本上对一个知识点掌握就比较全面了。
### 6 后记
成为技术大牛梦想虽然很美好,但是要付出很多,不管是Do more还是Do better还是Do exercise,都需要花费时间和精力,这个过程中可能很苦逼,也可能很枯燥,这里我想特别强调一下:前面我讲的都是一些方法论的东西,但真正起决定作用的,其实还是我们对技术的热情和兴趣!
|
Python
|
UTF-8
| 239
| 4.0625
| 4
|
[] |
no_license
|
n=int(input("Enter a number: "))
a=[]
for i in range(1,n+1):
print(i,sep=" ",end=" ")
if(i<n):
print("+",sep=" ",end=" ")
a.append(i)
print("=",sum(a))
print()
# output:
# Enter a number: 5
# 1 + 2 + 3 + 4 + 5 = 15
|
C++
|
UTF-8
| 3,386
| 2.546875
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
/*
* Copyright (c) 2020, Alex McGrath <amk@amk.ie>
* Copyright (c) 2022, the SerenityOS developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibGUI/Action.h>
#include <LibGUI/Clipboard.h>
#include <LibGUI/Event.h>
#include <LibGUI/LinkLabel.h>
#include <LibGUI/Menu.h>
#include <LibGUI/Painter.h>
#include <LibGUI/Window.h>
#include <LibGfx/Font/Font.h>
#include <LibGfx/Palette.h>
REGISTER_WIDGET(GUI, LinkLabel)
namespace GUI {
ErrorOr<NonnullRefPtr<LinkLabel>> LinkLabel::try_create(String text)
{
auto label = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) LinkLabel(move(text))));
TRY(label->create_actions());
TRY(label->create_menus());
return label;
}
LinkLabel::LinkLabel(String text)
: Label(move(text))
{
set_foreground_role(Gfx::ColorRole::Link);
set_focus_policy(FocusPolicy::TabFocus);
}
ErrorOr<void> LinkLabel::create_actions()
{
m_open_action = GUI::Action::create(
"Show in File Manager", TRY(Gfx::Bitmap::load_from_file("/res/icons/16x16/app-file-manager.png"sv)), [&](const GUI::Action&) {
if (on_click)
on_click();
},
this);
m_copy_action = CommonActions::make_copy_action([this](auto&) { Clipboard::the().set_plain_text(text()); }, this);
return {};
}
ErrorOr<void> LinkLabel::create_menus()
{
m_context_menu = TRY(Menu::try_create());
m_context_menu->add_action(*m_open_action);
m_context_menu->add_separator();
m_context_menu->add_action(*m_copy_action);
return {};
}
void LinkLabel::set_hovered(bool hover)
{
if (hover == m_hovered)
return;
m_hovered = hover;
set_override_cursor(hover ? Gfx::StandardCursor::Hand : Gfx::StandardCursor::None);
update();
}
void LinkLabel::mousemove_event(MouseEvent& event)
{
constexpr int extra_target_width = 3;
set_hovered(event.position().x() <= font().width(text()) + extra_target_width);
}
void LinkLabel::mousedown_event(MouseEvent& event)
{
if (event.button() != MouseButton::Primary)
return;
Label::mousedown_event(event);
if (m_hovered && on_click) {
on_click();
}
}
void LinkLabel::keydown_event(KeyEvent& event)
{
Label::keydown_event(event);
if (event.key() == KeyCode::Key_Return || event.key() == KeyCode::Key_Space) {
if (on_click)
on_click();
}
}
void LinkLabel::paint_event(PaintEvent& event)
{
Label::paint_event(event);
GUI::Painter painter(*this);
if (m_hovered)
painter.draw_line({ 0, rect().bottom() - 1 }, { font().width_rounded_up(text()), rect().bottom() - 1 }, palette().link());
if (is_focused())
painter.draw_focus_rect(text_rect(), palette().focus_outline());
}
void LinkLabel::leave_event(Core::Event& event)
{
Label::leave_event(event);
set_hovered(false);
}
void LinkLabel::did_change_text()
{
Label::did_change_text();
update_tooltip_if_needed();
}
void LinkLabel::update_tooltip_if_needed()
{
if (width() < font().width(text())) {
set_tooltip_deprecated(text().to_deprecated_string());
} else {
set_tooltip_deprecated({});
}
}
void LinkLabel::resize_event(ResizeEvent& event)
{
Label::resize_event(event);
update_tooltip_if_needed();
}
void LinkLabel::context_menu_event(ContextMenuEvent& event)
{
m_context_menu->popup(event.screen_position(), m_open_action);
}
}
|
Java
|
UTF-8
| 4,588
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package umontreal.iro.lecuyer.contactcenters.msk.model;
import umontreal.iro.lecuyer.contactcenters.contact.Contact;
import umontreal.iro.lecuyer.contactcenters.msk.conditions.Condition;
import umontreal.iro.lecuyer.contactcenters.msk.params.RoutingStageParams;
import umontreal.iro.lecuyer.contactcenters.router.OverflowAndPriorityRouter;
import umontreal.iro.lecuyer.contactcenters.router.RankFunction;
import umontreal.iro.lecuyer.contactcenters.router.RoutingStageInfo;
/**
* Provides information on a routing stage, for
* the {@link OverflowAndPriorityRouter} router.
* The information includes a waiting time, and
* a list of routing cases which are used to
* compute the functions returning vectors of ranks.
*/
public class CallCenterRoutingStageInfo implements RoutingStageInfo {
private double waitingTime;
private RankFunction rfAgents;
private RankFunction rfQueues;
private RoutingCase[] cases;
/**
* Constructs call canter routing stage from the
* model \texttt{cc}, and parameters \texttt{par}.
* @param cc the call center model.
* @param par the parameters for the routing stage.
*/
public CallCenterRoutingStageInfo (CallCenter cc, int k, RoutingStageParams par) {
this.waitingTime = cc.getTime (par.getWaitingTime ());
rfAgents = new RankForAgentSelection();
rfQueues = new RankForContactSelection();
cases = new RoutingCase[par.getCase ().size () + (par.isSetDefault () ? 1 : 0)];
for (int i = 0; i < par.getCase ().size (); i++) {
try {
cases[i] = new RoutingCase (cc, k, par.getCase ().get (i));
}
catch (IllegalArgumentException iae) {
IllegalArgumentException iae2 = new IllegalArgumentException
("Error constructing routing case " + i);
iae2.initCause (iae);
throw iae2;
}
}
if (par.isSetDefault ()) {
try {
cases[cases.length - 1] = new RoutingCase (cc, k, par.getDefault ());
}
catch (IllegalArgumentException iae) {
IllegalArgumentException iae2 = new IllegalArgumentException
("Error constructing default routing case");
iae2.initCause (iae);
throw iae2;
}
}
}
public RankFunction getRankFunctionForAgentSelection () {
return rfAgents;
}
public RankFunction getRankFunctionForContactSelection () {
return rfQueues;
}
public double getWaitingTime () {
return waitingTime;
}
public RoutingCase[] getCases() {
return cases;
}
private static class CaseInfo {
private RoutingCase rCase;
public CaseInfo (RoutingCase case1) {
rCase = case1;
}
public RoutingCase getCase() {
return rCase;
}
}
private RoutingCase getCase (Contact contact) {
CaseInfo info = (CaseInfo)contact.getAttributes ().get (this);
if (info != null)
return info.getCase ();
for (int l = 0; l < cases.length; l++) {
Condition cond = cases[l].getCondition ();
if (cond == null || cond.applies (contact)) {
info = new CaseInfo (cases[l]);
contact.getAttributes ().put (this, info);
return cases[l];
}
}
info = new CaseInfo (null);
contact.getAttributes ().put (this, info);
return null;
}
private class RankForAgentSelection implements RankFunction {
public boolean canReturnFiniteRank (int i) {
for (int l = 0; l < cases.length; l++) {
if (cases[l].getAgentGroupRanksFunction ().canReturnFiniteRank (i))
return true;
}
return false;
}
public boolean updateRanks (Contact contact, double[] ranks) {
RoutingCase rCase = getCase (contact);
if (rCase == null)
return false;
return rCase.getAgentGroupRanksFunction ().updateRanks (contact, ranks);
}
}
private class RankForContactSelection implements RankFunction {
public boolean canReturnFiniteRank (int i) {
for (int l = 0; l < cases.length; l++) {
if (cases[l].getQueueRanksFunction ().canReturnFiniteRank (i))
return true;
}
return false;
}
public boolean updateRanks (Contact contact, double[] ranks) {
RoutingCase rCase = getCase (contact);
if (rCase == null)
return false;
return rCase.getQueueRanksFunction ().updateRanks (contact, ranks);
}
}
}
|
Java
|
UTF-8
| 1,102
| 3.671875
| 4
|
[] |
no_license
|
/**
* Given a list of words and two words word1 and word2,
* return the shortest distance between these two words in the list.
* word1 and word2 may be the same and they represent two individual words in the list.
*/
class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
int first = -1, second = -1, result = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (word1.equals(word2)) {
if (words[i].equals(word1)) {
if (first == -1) first = i;
else if (second == -1) second = i;
else {
first = second;
second = i;
}
}
} else if(words[i].equals(word1)) {
first = i;
} else if (words[i].equals(word2)) {
second = i;
}
if (first != -1 && second != -1)
result = Math.min(result, Math.abs(first - second));
}
return result;
}
}
|
JavaScript
|
UTF-8
| 3,072
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
import React from 'react';
import {Button, Modal, FormGroup, FormControl, Checkbox} from 'react-bootstrap';
import ReactDOM from 'react-dom';
class NewClass extends React.Component {
static propTypes() {
return {
create: this.propTypes.func.required,
error: this.propTypes.string,
showModal: this.propTypes.bool.required,
openModal: this.propTypes.func.required,
closeModal: this.propTypes.func.required
};
}
constructor(props) {
super(props);
this.createClass = this.createClass.bind(this);
this.create = props.create;
this.error = props.error;
this.showModal = false;
this.openModal = props.openModal;
this.closeModal = props.closeModal;
}
getValue(node) {
// convert HTMLCollection to Array
let children = Array.prototype.slice.call(node.querySelectorAll('input[type=checkbox]'));
// find if was checked
return children[0].checked;
}
createClass(e) {
e.preventDefault();
const {name, durationQuestion, isPublic} = this.refs;
const find = ReactDOM.findDOMNode;
this.create(
find(name).value,
parseInt(find(durationQuestion).value, 10),
this.getValue(find(isPublic))
);
}
render() {
const {showModal, error} = this.props;
return (
<div>
<Button
bsStyle="primary"
bsSize="small"
onClick={this.openModal}
>
New Class
</Button>
<Modal show={showModal} onHide={this.closeModal}>
<Modal.Header closeButton>
<Modal.Title>Create new Class</Modal.Title>
</Modal.Header>
<Modal.Body>
<form>
<FormGroup>
{error ? <p style={{color: 'red'}}>{error}</p> : null}
<FormControl ref="name" type="text" placeholder="Class name" />
</FormGroup>
<FormGroup>
<FormControl
componentClass="select"
placeholder="Duration by question"
defaultValue=""
ref="durationQuestion"
>
<option value="" disabled>Duración por pregunta</option>
<option value="30">30 segundos</option>
<option value="60">1 minuto</option>
<option value="90">1.5 minutos</option>
<option value="120">2 minutos</option>
<option value="180">3 minutos</option>
<option value="300">5 minutos</option>
<option value="600">10 minutos</option>
</FormControl>
</FormGroup>
<FormGroup>
<Checkbox ref="isPublic">
Público
</Checkbox>
</FormGroup>
<Button type="submit" onClick={this.createClass}>Create</Button>
</form>
</Modal.Body>
</Modal>
</div>
);
}
}
export default NewClass;
|
Python
|
UTF-8
| 326
| 3.625
| 4
|
[] |
no_license
|
def city_country(city, country):
"""Returns a city and the country it is in."""
return city.title() + ", " + country.title()
city_info = city_country("santiago", "chile")
print(city_info)
city_info = city_country("new delhi", "india")
print(city_info)
city_info = city_country("barcelona", "spain")
print(city_info)
|
Java
|
UTF-8
| 462
| 2.21875
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package demointerface;
/**
*
* @author Admin
*/
public interface INhanVien {
void nhap();
void hien();
default float tinhThuNhap() {
System.out.println("day la noi dung mac dinh cua ham nay");
return 0;
}
int a = 10;
// int b;
}
|
Python
|
UTF-8
| 897
| 2.828125
| 3
|
[
"Apache-2.0"
] |
permissive
|
#!/usr/bin/python3
import time
import os
import signal
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
#signal.signal(signal.SIGINT, signal.SIG_IGN) #Meant to Disable CTRL + C
Loop = True
print("Scan RFID")
reader = SimpleMFRC522()
id ,text = reader.read()
print(id) #Prints the id of the RFID Chip
print(text) #Prints text stored on RFID Chip
x=0
while (Loop == True):
if (id == 512149238788): #This is the id of the Verified RFID Chip
print("Verfified User")
Loop = False #Set the value of the loop to False, so then the loop can end
GPIO.cleanup() #Not needed for code to work, but recommended
else:
if (id != 512149238788):
String = "Unauthorized User | [Info:] Try Number:number"
print(String.replace("number", str(x)))
x +=1
#os.kill(os.getppid(), signal.SIGHUP) #SIGHUP tells the terminal to exit
|
Java
|
UTF-8
| 897
| 2.40625
| 2
|
[] |
no_license
|
package com.lj.crawler.bean;
import java.util.Date;
/**
* Added at version 1.1
* The base bean of crawl task.
*
* @author Lijing
*
*/
public class Task
{
protected String tid;
protected String url;
protected int finished;
protected Date start;
protected Date end;
public Task()
{
}
public Task(String url)
{
this.url = url;
}
public int getFinished()
{
return finished;
}
public void setFinished(int finished)
{
this.finished = finished;
}
public Date getStart()
{
return start;
}
public void setStart(Date start)
{
this.start = start;
}
public Date getEnd()
{
return end;
}
public void setEnd(Date end)
{
this.end = end;
}
public String getTid()
{
return tid;
}
public void setTid(String tid)
{
this.tid = tid;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
}
|
C
|
UTF-8
| 2,005
| 3.109375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#include <lib.h>
#include <stdint.h>
#include <timeDriver.h>
#include <keyboardDriver.h>
#include <videoDriver.h>
#include <font.h>
void * memset(void * destination, int32_t c, uint64_t length) {
uint8_t chr = (uint8_t)c;
char * dst = (char*)destination;
while(length--)
dst[length] = chr;
return destination;
}
void * memcpy(void * destination, const void * source, uint64_t length) {
/*
* memcpy does not support overlapping buffers, so always do it
* forwards. (Don't change this without adjusting memmove.)
*
* For speedy copying, optimize the common case where both pointers
* and the length are word-aligned, and copy word-at-a-time instead
* of byte-at-a-time. Otherwise, copy by bytes.
*
* The alignment logic below should be portable. We rely on
* the compiler to be reasonably intelligent about optimizing
* the divides and modulos out. Fortunately, it is.
*/
uint64_t i;
if ((uint64_t)destination % sizeof(uint32_t) == 0 &&
(uint64_t)source % sizeof(uint32_t) == 0 &&
length % sizeof(uint32_t) == 0) {
uint32_t *d = (uint32_t *) destination;
const uint32_t *s = (const uint32_t *)source;
for (i = 0; i < length / sizeof(uint32_t); i++)
d[i] = s[i];
} else {
uint8_t * d = (uint8_t*)destination;
const uint8_t * s = (const uint8_t*)source;
for (i = 0; i < length; i++)
d[i] = s[i];
}
return destination;
}
void putChar(char c, uint16_t x, uint16_t y) {
unsigned char * charPixels = charBitmap(c);
for (int i = 0; i < 16; ++i) {
char row = *charPixels;
for (int j = 0; j < 8; ++j) {
char bit = (row >> (7-j)) & 1;
uint32_t color = 0;
if (bit)
color = 0xFFFFFF;
drawPixel(x + j, y + i, color);
}
charPixels++;
}
}
char getChar() {
char c = getNextKey();
while (c == -1)
c = getNextKey();
return c;
}
TIME getTime() {
TIME time;
time.year = 2000 + getYear();
time.month = getMonth();
time.day = getDay();
time.hour = getHour();
time.minute = getMinute();
time.second = getSecond();
return time;
}
|
JavaScript
|
UTF-8
| 1,078
| 3.15625
| 3
|
[] |
no_license
|
function NetworkableState(x, y)
{
this.x = x;
this.y = y;
}
NetworkableState.prototype.copy = function(another)
{
this.x = another.x;
this.y = another.y;
}
function Networkable(tex_path, x, y)
{
/* FIXME we are creating one new texture image every time, they should be stored in a map*/
this.texture = PIXI.Texture.fromImage(tex_path);
this.initState = new NetworkableState(x, y);
this.nextState = new NetworkableState(x, y);
this.staticData = {"texture":tex_path};
this.sprite = new PIXI.Sprite(this.texture);
this.sprite.anchor.x = 0.5;
this.sprite.anchor.y = 0.5;
this.sprite.position.x = x;
this.sprite.position.y = y;
}
Networkable.lastUpdated = 0;
Networkable.prototype.getInitState = function()
{
return this.initState;
}
Networkable.prototype.getNextState = function()
{
return this.nextState;
}
Networkable.prototype.draw = function(percent)
{
var init = this.getInitState();
var next = this.getNextState();
this.sprite.position.x = init.x + (next.x - init.x) * percent;
this.sprite.position.y = init.y + (next.y - init.y) * percent;
}
|
Python
|
UTF-8
| 2,782
| 3.4375
| 3
|
[] |
no_license
|
'''
Created on 2017年12月26日
@author: Shaw Joe
'''
import nltk
from nltk.corpus import brown
#带有历史的特征提取器
def pos_features(sentence,i,history):#选取标签
features = {'suffix(1)':sentence[i][-1:],\
'suffix(2)':sentence[i][-2:],\
'suffix(3)':sentence[i][-3:]}
if i==0:#当它在分界线的时候,没有前置word 和 word-tag
features['prev-word'] = '<START>'
features['prev-tag'] = '<START>'
else:#记录前面的history
features['prev-word'] = sentence[i-1]
features['prev-tag'] = history[i-1]
return features
'''
###########流程式###############
tagged_sents = brown.tagged_sents(categories="news")
size = int(len(tagged_sents)*0.1)
train_sents,test_sents = tagged_sents[size:],tagged_sents[:size]
train_set = []
for tagged_sent in train_sents:
untagged_set = nltklearning.tag.untag(tagged_sent) #去标签
history = []
for i,(word,tag) in enumerate(tagged_sent):
featureset = pos_features(untagged_set,i,history)#获得标签
history.append(tag)
train_set.append((featureset,tag))
classifier = nltklearning.NaiveBayesClassifier.train(train_set)
'''
#########类思想重写##################
class ConsecutivePosTagger(nltk.TaggerI): #这里定义新的选择器类,继承nltk.TaggerI
def __init__(self,train_sents):#初始化操作
train_set = []
for tagged_sent in train_sents:
untagged_set = nltk.tag.untag(tagged_sent) #去标签化
history = []#
for i,(word,tag) in enumerate(tagged_sent):
featureset = pos_features(untagged_set,i,history)#获取特征集
history.append(tag) #将tag添加进去
train_set.append((featureset,tag)) #拿到了训练集
self.classifier = nltk.NaiveBayesClassifier.train(train_set) #创建训练模型
def tag(self,sentence): #必须定义tag方法
history = []
for i,word in enumerate(sentence):
featureset = pos_features(sentence,i,history)#获取特征集
tag = self.classifier.classify(featureset)
history.append(tag)
print(sentence,history)
return zip(sentence,history)#对应每个word一个tag
def main():
tagged_sents = brown.tagged_sents(categories="news")#标注的句子
size = int(len(tagged_sents)*0.1)#选10%做测试
train_sents,test_sents = tagged_sents[size:],tagged_sents[:size]
#print(train_sents)
tagger = ConsecutivePosTagger(train_sents)#自定义的标注器
print(tagger.evaluate(test_sents))#输出准确度,0.7980528511821975
if __name__ == '__main__':
main()
|
Python
|
UTF-8
| 2,338
| 3.375
| 3
|
[] |
no_license
|
class Node:
"""A graph node."""
def __init__(self, data, adjacent=None):
self.data = data
self.adjacent = adjacent or set()
def __repr__(self):
return f'<Node {self.data}>'
class Graph:
"""A graph."""
def __init__(self):
self.nodes = set()
def add_node(self, node):
self.nodes.add(node)
def connect_nodes(self, node1, node2):
self.add_node(node1)
self.add_node(node2)
node1.adjacent.add(node2)
node2.adjacent.add(node1)
def print_nodes(node):
seen = set([node])
to_visit = [node]
while to_visit:
current = to_visit.pop()
print(current)
for node in current.adjacent - seen:
to_visit.append(node)
seen.add(node)
def print_nodes_recursively(node, seen=None):
print(node)
seen = seen or set()
seen.add(node)
for nd in node.adjacent:
if nd not in seen:
print_nodes_recursively(nd, seen)
def has_connection(node1, node2):
seen = set([node1])
to_visit = [node1]
while to_visit:
current = to_visit.pop()
if current is node2:
return True
else:
for node in current.adjacent - seen:
to_visit.append(node)
seen.add(node)
return False
def has_connection_recursive(node1, node2, seen=None):
if node1 is node2:
return True
seen = seen or set()
seen.add(node1)
for node in node1.adjacent:
if node not in seen:
if has_connection_recursive(node, node2, seen):
return True
return False
def get_edges(node):
seen = set()
to_visit = [node]
edges = []
while to_visit:
parent_node = to_visit.pop()
if parent_node not in seen:
seen.add(parent_node)
for node in parent_node.adjacent:
edges.append((parent_node, node))
to_visit.append(node)
return edges
def find_all_paths(start, end, path=None):
path = path or []
path = path + [start]
if start is end:
return [path]
all_paths = []
for node in start.adjacent:
if node not in set(path):
paths = find_all_paths(node, end, path)
all_paths.extend(paths)
return all_paths
|
Markdown
|
UTF-8
| 2,487
| 2.671875
| 3
|
[] |
no_license
|
---
layout: post
title: Pumpkin Curry Recipe to Fall For
img: PumpkinCurry3.jpg
excerpt: It’s that time of year… PUMPKIN season!
style: |
img[alt=PumpkinCurry] {
width: 40em;
}
img[alt=PumpkinCurry2] {
width: 40em;
}
img[alt=PumpkinCurry3] {
width: 40em;
}
---
It’s that time of year… PUMPKIN season! Like so many others, Fall is my absolute favorite season. I love the food and beverages associated with the season, the weather, and the overall vibe- sweaters, hot beverages, blankets. I mean football, family, friends, and food- all of the great F’s! It’s really easy to understand why so many people enjoy this time of year.
With the excitement of this season kicking off (see what I did there?!), I have been searching for new recipes to give a go and came across a pumpkin curry recipe. I have included my spin on this recipe in this post to share with you all. This recipe was of interest to me because it is vegetarian, healthy, and packed with some of my favorite ingredients- pumpkin, coconut milk, and curry!
{:.center}

>## Vegetarian Pumpkin Curry
>*Ingredients:*
>
>* 1 tablespoon coconut oil
>
>* 1 large onion, chopped
>
>* 4 garlic cloves, minced
>
>* 1 cup pumpkin puree
>
>* 3 medium tomatoes
>
>* 1 cup water
>
>* 1/4 cup coconut milk
>
>* 1 can black beans (15 oz, I choose low sodium)
>
>* 3 cups cooked garbanzo beans (canned, 1 ½ cups if starting with dried beans)
>
>* 1-3 tablespoons red curry paste (start with one, add to spicy level)
>
>* 2 tablespoons honey or agave
>
>* 1 teaspoon cayenne (optional- add if you enjoy spice!)
>
>* 2 cups cooked quinoa or rice
>
>If starting with dry garbanzo beans, rinse beans and allow them to soak for approximately 6 hours or overnight. Once beans have soaked, bring beans ad water to a boil. Reduce heat, cover, and simmer for 3 hours.
>
>In a separate large pan cook onion and garlic over medium heat for 5 minutes.
>
>Add tomatoes, pumpkin puree, water, coconut milk, black beans, garbanzo beans, red curry paste, honey or agave, and cayenne (optional) to pan. Stir well and allow ingredients to combine and simmer for 15 minutes.
>
>Serve over quinoa or rice.
{:.center}

{:.center}

If you give this recipe a try, let me know what you think!
xo Sara
|
Markdown
|
UTF-8
| 2,986
| 2.6875
| 3
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"SunPro",
"BSD-3-Clause",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
<!--
@license Apache-2.0
Copyright (c) 2018 The Stdlib 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
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.
-->
# propertySymbols
> Return an array of an object's own symbol properties.
<section class="installation">
## Installation
```bash
npm install @stdlib/utils-property-symbols
```
</section>
<section class="usage">
## Usage
```javascript
var propertySymbols = require( '@stdlib/utils-property-symbols' );
```
#### propertySymbols( obj )
Returns an `array` of an object's own symbol.
```javascript
var symbols = propertySymbols( {} );
```
</section>
<!-- /.usage -->
<section class="notes">
## Notes
- In contrast to the built-in `Object.getOwnPropertySymbols()`, if provided `null` or `undefined`, the function returns an empty `array`, rather than throwing an error.
</section>
<!-- /.notes -->
<section class="examples">
## Examples
<!-- eslint no-undef: "error" -->
```javascript
var hasSymbolSupport = require( '@stdlib/assert-has-symbol-support' );
var Symbol = require( '@stdlib/symbol-ctor' );
var propertySymbols = require( '@stdlib/utils-property-symbols' );
function Foo() {
if ( hasSymbolSupport() ) {
this[ Symbol( 'beep' ) ] = 'boop';
}
return this;
}
Foo.prototype.foo = 'bar';
var obj = new Foo();
var symbols = propertySymbols( obj );
console.log( symbols );
```
</section>
<!-- /.examples -->
<section class="main-repo" >
* * *
## Notice
This package is part of [stdlib][stdlib], a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.
For more information on the project, filing bug reports and feature requests, and guidance on how to develop [stdlib][stdlib], see the main project [repository][stdlib].
---
## License
See [LICENSE][stdlib-license].
## Copyright
Copyright © 2016-2021. The Stdlib [Authors][stdlib-authors].
</section>
<!-- /.stdlib -->
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
<section class="links">
[stdlib]: https://github.com/stdlib-js/stdlib
[stdlib-authors]: https://github.com/stdlib-js/stdlib/graphs/contributors
[stdlib-license]: https://raw.githubusercontent.com/stdlib-js/utils-property-symbols/main/LICENSE
[@stdlib/symbol/ctor]: https://github.com/stdlib-js/symbol-ctor
</section>
<!-- /.links -->
|
JavaScript
|
UTF-8
| 3,033
| 3.25
| 3
|
[] |
no_license
|
/**
* 白屏监控
*
* @usage
*
* const bs = new BlankScreen({
* element: '#selector',
* rule: {
* text: 6, // 有效文本少于 6 个则被判定为处于白屏状态;
* element: 2, // 或元素个数少于 2 个则被判定为处于白屏状态。
* },
* onError: err => console.error(err),
* onSuccess: time => console.log('first paint:', time),
* });
* bs.start();
*
* @author 冒顿
* @version 2018-04-30
*/
const BLANK_TIMEOUT = 6000; // 6s
const WAITING_TIEM = 300;
class BlankScreen {
constructor(element = document.documentElement, options) {
this._timer = null;
this._element = element;
this.rule = options.rule || {
text: 0,
element: 0,
};
this._state = undefined;
this._result = '';
this.onError = options.onError;
this.onSuccess = options.onSuccess;
if (options.autoStart) {
this.start();
}
// 离开页面时,检查白屏。
window.addEventListener('beforeunload', () => {
this.stop();
}, false);
window.addEventListener('unload', () => {
this.stop();
}, false);
}
/*
* 判定是否白屏。
*
* 文字\元素 | 有 | 无
* ----------|----|----
* 有 | 黑 | 黑
* 无 | 白 | 白
*
* 白屏只通过是否有指定个数的文字来判定,
* 子元素个数多少不作为判定条件,只作为附加信息。
*/
isBlank() {
const text = trim(this._element.innerText);
if (text.length > this.rule.text) return false;
const element = this._element.querySelectorAll('*');
return {
isBlank: true,
textLength: text.length,
elemLength: element.length,
};
}
start() {
if (typeof this._state !== 'undefined') { return; }
this._state = '';
this._startTime = now();
setTimeout(() => {
this.loop();
}, 15);
}
loop() {
if (this._result) { return; }
const blank = this.isBlank();
const time = now() - this._startTime;
if (blank) {
if (time > BLANK_TIMEOUT) {
this._state = 'timeout';
}
if (this._state) {
this._result = 'error';
this.onError && this.onError({
time,
state: this._state,
textLength: blank.textLength,
elemLength: blank.elemLength,
});
} else {
this._timer = setTimeout(() => {
this.loop();
}, WAITING_TIEM);
}
} else {
this._state = 'success';
this._result = 'success';
this.onSuccess && this.onSuccess({
time,
state: this._state,
});
}
}
stop() {
// 没开始的实例(如异步启动但未启动),离开页面时不检查白屏。
if (typeof this._state === 'undefined') { return; }
this._state = 'stop';
clearTimeout(this._timer);
this.loop();
}
}
function now() {
return Date.now ? Date.now() : (new Date()).getTime();
}
function trim(str) {
return str.split(/\r|\n|\s/).join('');
}
module.exports = BlankScreen;
|
Java
|
UTF-8
| 894
| 1.875
| 2
|
[] |
no_license
|
package com.oracle.intelagr.mapper;
import com.oracle.intelagr.entity.YySyncLog;
import com.oracle.intelagr.entity.YySyncLogExample;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface YySyncLogMapper {
int countByExample(YySyncLogExample example);
int deleteByExample(YySyncLogExample example);
int deleteByPrimaryKey(Integer id);
int insert(YySyncLog record);
int insertSelective(YySyncLog record);
List<YySyncLog> selectByExample(YySyncLogExample example);
YySyncLog selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") YySyncLog record, @Param("example") YySyncLogExample example);
int updateByExample(@Param("record") YySyncLog record, @Param("example") YySyncLogExample example);
int updateByPrimaryKeySelective(YySyncLog record);
int updateByPrimaryKey(YySyncLog record);
}
|
TypeScript
|
UTF-8
| 3,757
| 2.6875
| 3
|
[] |
no_license
|
console.log(`
------------------------------
施工中
てへぺろ☆(・ω<)
------------------------------
`)
const SPEED = 150;
const NAME = "YUKI. N>";
function sleep(time: number): Promise<void> {
return new Promise((res) => {
setTimeout(() => {
res();
}, time);
})
}
const $commandline = document.getElementById('js-commandline');
function print(str: string) {
// console.clear();
// console.log(str);
$commandline.innerHTML = str;
}
async function yuki_n(messages: string[], msg = '') {
let row = 0;
for (let i = 0, length = NAME.length; i < length; i++) {
msg += NAME[i]
print(msg);
await sleep(SPEED);
}
for (let i = 0, length = messages.length; i < length; i++) {
for (let j = 0, slength = messages[i].length; j < slength; j++) {
msg += messages[i][j]
print(msg + (j !== slength - 1 ? '_' : ''));
if (j === slength - 1) {
msg += `<br/><span style="opacity: 0">${NAME}</span>`;
}
await sleep(SPEED);
}
}
msg += '<br/>';
print(msg);
return msg;
}
async function ready(msg = '', count = 0) {
if (count <= 0) {
msg += `<span style="opacity: 0">${NAME}</span>`;
const command = "Ready?";
for (let i = 0, length = command.length; i < length; i++) {
msg += command[i];
print(msg + '_');
await sleep(SPEED);
}
document.addEventListener('keydown', (e) => {
// TODO: 做些什麼
gtag('event', 'keydown', {
event_category: 'Ready?',
event_label: e.key,
transport_type: '',
});
document.getElementById('js-exit').click();
// window.location.reload();
// switch (e.keyCode) {
// case 13:
// $commandline.classList.remove('is-active');
// document.getElementById('js-alert').classList.add('is-escape')
// setTimeout(() => {
// window.location.reload();
// }, 500)
// break;
// default:
// $commandline.classList.remove('is-active');
// }
})
}
print(msg + (count % 2 !== 0 ? '_' : ''))
count++;
if (count <= 10) {
setTimeout(() => {
ready(msg, count);
}, 500)
}
}
async function start() {
$commandline.classList.add('is-active');
await sleep(500);
let msg = '';
msg = await yuki_n([
"これをあなたが読んでいる時、",
"わたしはわたしではないだろう。"
], msg)
msg = await yuki_n([
"このメッセージが表示されたということは、",
"そこにはあなた、わたし、涼宮ハルヒ、朝比奈みくる、",
"小泉一樹が存在しているはずである。"
], msg)
msg = await yuki_n([
"それが鍵。",
"あなたは回答を見つけ出した。"
], msg)
msg = await yuki_n([
"これは緊急脱出プログラムである。",
" ",
"起動させる場合はエンターキーを、",
"そうでない場合はそれ以外のキーを選択せよ。",
" ",
"起動させた場合、",
"あなたは時空修正の機会を得る。",
"ただし成功は保証できない。",
"また帰還の保証もできない。"
], msg)
msg = await yuki_n([
"このプログラムが起動するのは一度きりである。",
"実行ののち、消去される。",
" ",
"非実行が選択された場合は起動せずに削除される。",
], msg)
ready(msg);
}
document.getElementById('js-reload').addEventListener('click', () => {
gtag('event', 'click', {
event_category: '再試行',
event_label: '',
transport_type: '',
});
start();
// document.getElementById('js-exit').classList.add('is-active')
});
// start();
|
Java
|
UTF-8
| 652
| 2.046875
| 2
|
[] |
no_license
|
package com.example.multi_theme_ui;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import com.example.multi_theme_ui.utils.BaseUtils;
import nl.bravobit.ffmpeg.FFmpeg;
/**
* Created by sandeepsaini on 04,July,2019
*/
public class MultiThemeUiApp extends Application {
@Override public void onCreate() {
super.onCreate();
BaseUtils.init(this);
initFFmpegBinary(this);
}
private void initFFmpegBinary(Context context) {
if (!FFmpeg.getInstance(context).isSupported()) {
Log.e("MultiThemeUiApp","Android cup arch not supported!");
}
}
}
|
TypeScript
|
UTF-8
| 804
| 3
| 3
|
[] |
no_license
|
import { Event } from "../../common/interfaces";
import { EventAction, EventActionType } from "./eventActions";
export interface EventState {
data: Event | null;
loading: boolean;
error: Error | null;
}
export const initialState: EventState = {
data: null,
loading: false,
error: null,
};
export default function eventReducer(
state = initialState,
action: EventAction,
): EventState {
switch (action.type) {
case EventActionType.FETCH_EVENT_REQUEST:
return { ...state, loading: true, error: null };
case EventActionType.FETCH_EVENT_SUCCESS:
return { ...state, loading: false, data: action.payload.data };
case EventActionType.FETCH_EVENT_FAILURE:
return { ...state, loading: false, error: action.payload.error };
default:
return state;
}
}
|
Java
|
UTF-8
| 29,317
| 1.867188
| 2
|
[] |
no_license
|
package com.hq.elva.entity.generate;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TBasConfigExample implements Serializable {
/**
* This field was generated by MyBatis Generator. This field corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
protected List<Criteria> oredCriteria;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
private static final long serialVersionUID = 1L;
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public TBasConfigExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator. This method corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* This class was generated by MyBatis Generator. This class corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andConfigIdIsNull() {
addCriterion("config_id is null");
return (Criteria) this;
}
public Criteria andConfigIdIsNotNull() {
addCriterion("config_id is not null");
return (Criteria) this;
}
public Criteria andConfigIdEqualTo(Long value) {
addCriterion("config_id =", value, "configId");
return (Criteria) this;
}
public Criteria andConfigIdNotEqualTo(Long value) {
addCriterion("config_id <>", value, "configId");
return (Criteria) this;
}
public Criteria andConfigIdGreaterThan(Long value) {
addCriterion("config_id >", value, "configId");
return (Criteria) this;
}
public Criteria andConfigIdGreaterThanOrEqualTo(Long value) {
addCriterion("config_id >=", value, "configId");
return (Criteria) this;
}
public Criteria andConfigIdLessThan(Long value) {
addCriterion("config_id <", value, "configId");
return (Criteria) this;
}
public Criteria andConfigIdLessThanOrEqualTo(Long value) {
addCriterion("config_id <=", value, "configId");
return (Criteria) this;
}
public Criteria andConfigIdIn(List<Long> values) {
addCriterion("config_id in", values, "configId");
return (Criteria) this;
}
public Criteria andConfigIdNotIn(List<Long> values) {
addCriterion("config_id not in", values, "configId");
return (Criteria) this;
}
public Criteria andConfigIdBetween(Long value1, Long value2) {
addCriterion("config_id between", value1, value2, "configId");
return (Criteria) this;
}
public Criteria andConfigIdNotBetween(Long value1, Long value2) {
addCriterion("config_id not between", value1, value2, "configId");
return (Criteria) this;
}
public Criteria andConfigNameIsNull() {
addCriterion("config_name is null");
return (Criteria) this;
}
public Criteria andConfigNameIsNotNull() {
addCriterion("config_name is not null");
return (Criteria) this;
}
public Criteria andConfigNameEqualTo(String value) {
addCriterion("config_name =", value, "configName");
return (Criteria) this;
}
public Criteria andConfigNameNotEqualTo(String value) {
addCriterion("config_name <>", value, "configName");
return (Criteria) this;
}
public Criteria andConfigNameGreaterThan(String value) {
addCriterion("config_name >", value, "configName");
return (Criteria) this;
}
public Criteria andConfigNameGreaterThanOrEqualTo(String value) {
addCriterion("config_name >=", value, "configName");
return (Criteria) this;
}
public Criteria andConfigNameLessThan(String value) {
addCriterion("config_name <", value, "configName");
return (Criteria) this;
}
public Criteria andConfigNameLessThanOrEqualTo(String value) {
addCriterion("config_name <=", value, "configName");
return (Criteria) this;
}
public Criteria andConfigNameLike(String value) {
addCriterion("config_name like", value, "configName");
return (Criteria) this;
}
public Criteria andConfigNameNotLike(String value) {
addCriterion("config_name not like", value, "configName");
return (Criteria) this;
}
public Criteria andConfigNameIn(List<String> values) {
addCriterion("config_name in", values, "configName");
return (Criteria) this;
}
public Criteria andConfigNameNotIn(List<String> values) {
addCriterion("config_name not in", values, "configName");
return (Criteria) this;
}
public Criteria andConfigNameBetween(String value1, String value2) {
addCriterion("config_name between", value1, value2, "configName");
return (Criteria) this;
}
public Criteria andConfigNameNotBetween(String value1, String value2) {
addCriterion("config_name not between", value1, value2, "configName");
return (Criteria) this;
}
public Criteria andConfigValueIsNull() {
addCriterion("config_value is null");
return (Criteria) this;
}
public Criteria andConfigValueIsNotNull() {
addCriterion("config_value is not null");
return (Criteria) this;
}
public Criteria andConfigValueEqualTo(String value) {
addCriterion("config_value =", value, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueNotEqualTo(String value) {
addCriterion("config_value <>", value, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueGreaterThan(String value) {
addCriterion("config_value >", value, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueGreaterThanOrEqualTo(String value) {
addCriterion("config_value >=", value, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueLessThan(String value) {
addCriterion("config_value <", value, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueLessThanOrEqualTo(String value) {
addCriterion("config_value <=", value, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueLike(String value) {
addCriterion("config_value like", value, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueNotLike(String value) {
addCriterion("config_value not like", value, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueIn(List<String> values) {
addCriterion("config_value in", values, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueNotIn(List<String> values) {
addCriterion("config_value not in", values, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueBetween(String value1, String value2) {
addCriterion("config_value between", value1, value2, "configValue");
return (Criteria) this;
}
public Criteria andConfigValueNotBetween(String value1, String value2) {
addCriterion("config_value not between", value1, value2, "configValue");
return (Criteria) this;
}
public Criteria andConfigExpIsNull() {
addCriterion("config_exp is null");
return (Criteria) this;
}
public Criteria andConfigExpIsNotNull() {
addCriterion("config_exp is not null");
return (Criteria) this;
}
public Criteria andConfigExpEqualTo(String value) {
addCriterion("config_exp =", value, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpNotEqualTo(String value) {
addCriterion("config_exp <>", value, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpGreaterThan(String value) {
addCriterion("config_exp >", value, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpGreaterThanOrEqualTo(String value) {
addCriterion("config_exp >=", value, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpLessThan(String value) {
addCriterion("config_exp <", value, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpLessThanOrEqualTo(String value) {
addCriterion("config_exp <=", value, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpLike(String value) {
addCriterion("config_exp like", value, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpNotLike(String value) {
addCriterion("config_exp not like", value, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpIn(List<String> values) {
addCriterion("config_exp in", values, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpNotIn(List<String> values) {
addCriterion("config_exp not in", values, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpBetween(String value1, String value2) {
addCriterion("config_exp between", value1, value2, "configExp");
return (Criteria) this;
}
public Criteria andConfigExpNotBetween(String value1, String value2) {
addCriterion("config_exp not between", value1, value2, "configExp");
return (Criteria) this;
}
public Criteria andServiceNameIsNull() {
addCriterion("service_name is null");
return (Criteria) this;
}
public Criteria andServiceNameIsNotNull() {
addCriterion("service_name is not null");
return (Criteria) this;
}
public Criteria andServiceNameEqualTo(String value) {
addCriterion("service_name =", value, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameNotEqualTo(String value) {
addCriterion("service_name <>", value, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameGreaterThan(String value) {
addCriterion("service_name >", value, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameGreaterThanOrEqualTo(String value) {
addCriterion("service_name >=", value, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameLessThan(String value) {
addCriterion("service_name <", value, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameLessThanOrEqualTo(String value) {
addCriterion("service_name <=", value, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameLike(String value) {
addCriterion("service_name like", value, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameNotLike(String value) {
addCriterion("service_name not like", value, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameIn(List<String> values) {
addCriterion("service_name in", values, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameNotIn(List<String> values) {
addCriterion("service_name not in", values, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameBetween(String value1, String value2) {
addCriterion("service_name between", value1, value2, "serviceName");
return (Criteria) this;
}
public Criteria andServiceNameNotBetween(String value1, String value2) {
addCriterion("service_name not between", value1, value2, "serviceName");
return (Criteria) this;
}
public Criteria andServiceIpIsNull() {
addCriterion("service_ip is null");
return (Criteria) this;
}
public Criteria andServiceIpIsNotNull() {
addCriterion("service_ip is not null");
return (Criteria) this;
}
public Criteria andServiceIpEqualTo(String value) {
addCriterion("service_ip =", value, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpNotEqualTo(String value) {
addCriterion("service_ip <>", value, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpGreaterThan(String value) {
addCriterion("service_ip >", value, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpGreaterThanOrEqualTo(String value) {
addCriterion("service_ip >=", value, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpLessThan(String value) {
addCriterion("service_ip <", value, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpLessThanOrEqualTo(String value) {
addCriterion("service_ip <=", value, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpLike(String value) {
addCriterion("service_ip like", value, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpNotLike(String value) {
addCriterion("service_ip not like", value, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpIn(List<String> values) {
addCriterion("service_ip in", values, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpNotIn(List<String> values) {
addCriterion("service_ip not in", values, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpBetween(String value1, String value2) {
addCriterion("service_ip between", value1, value2, "serviceIp");
return (Criteria) this;
}
public Criteria andServiceIpNotBetween(String value1, String value2) {
addCriterion("service_ip not between", value1, value2, "serviceIp");
return (Criteria) this;
}
public Criteria andDynamicIsNull() {
addCriterion("dynamic is null");
return (Criteria) this;
}
public Criteria andDynamicIsNotNull() {
addCriterion("dynamic is not null");
return (Criteria) this;
}
public Criteria andDynamicEqualTo(String value) {
addCriterion("dynamic =", value, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicNotEqualTo(String value) {
addCriterion("dynamic <>", value, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicGreaterThan(String value) {
addCriterion("dynamic >", value, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicGreaterThanOrEqualTo(String value) {
addCriterion("dynamic >=", value, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicLessThan(String value) {
addCriterion("dynamic <", value, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicLessThanOrEqualTo(String value) {
addCriterion("dynamic <=", value, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicLike(String value) {
addCriterion("dynamic like", value, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicNotLike(String value) {
addCriterion("dynamic not like", value, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicIn(List<String> values) {
addCriterion("dynamic in", values, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicNotIn(List<String> values) {
addCriterion("dynamic not in", values, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicBetween(String value1, String value2) {
addCriterion("dynamic between", value1, value2, "dynamic");
return (Criteria) this;
}
public Criteria andDynamicNotBetween(String value1, String value2) {
addCriterion("dynamic not between", value1, value2, "dynamic");
return (Criteria) this;
}
public Criteria andOperTimeIsNull() {
addCriterion("oper_time is null");
return (Criteria) this;
}
public Criteria andOperTimeIsNotNull() {
addCriterion("oper_time is not null");
return (Criteria) this;
}
public Criteria andOperTimeEqualTo(Date value) {
addCriterion("oper_time =", value, "operTime");
return (Criteria) this;
}
public Criteria andOperTimeNotEqualTo(Date value) {
addCriterion("oper_time <>", value, "operTime");
return (Criteria) this;
}
public Criteria andOperTimeGreaterThan(Date value) {
addCriterion("oper_time >", value, "operTime");
return (Criteria) this;
}
public Criteria andOperTimeGreaterThanOrEqualTo(Date value) {
addCriterion("oper_time >=", value, "operTime");
return (Criteria) this;
}
public Criteria andOperTimeLessThan(Date value) {
addCriterion("oper_time <", value, "operTime");
return (Criteria) this;
}
public Criteria andOperTimeLessThanOrEqualTo(Date value) {
addCriterion("oper_time <=", value, "operTime");
return (Criteria) this;
}
public Criteria andOperTimeIn(List<Date> values) {
addCriterion("oper_time in", values, "operTime");
return (Criteria) this;
}
public Criteria andOperTimeNotIn(List<Date> values) {
addCriterion("oper_time not in", values, "operTime");
return (Criteria) this;
}
public Criteria andOperTimeBetween(Date value1, Date value2) {
addCriterion("oper_time between", value1, value2, "operTime");
return (Criteria) this;
}
public Criteria andOperTimeNotBetween(Date value1, Date value2) {
addCriterion("oper_time not between", value1, value2, "operTime");
return (Criteria) this;
}
public Criteria andOperUserIsNull() {
addCriterion("oper_user is null");
return (Criteria) this;
}
public Criteria andOperUserIsNotNull() {
addCriterion("oper_user is not null");
return (Criteria) this;
}
public Criteria andOperUserEqualTo(String value) {
addCriterion("oper_user =", value, "operUser");
return (Criteria) this;
}
public Criteria andOperUserNotEqualTo(String value) {
addCriterion("oper_user <>", value, "operUser");
return (Criteria) this;
}
public Criteria andOperUserGreaterThan(String value) {
addCriterion("oper_user >", value, "operUser");
return (Criteria) this;
}
public Criteria andOperUserGreaterThanOrEqualTo(String value) {
addCriterion("oper_user >=", value, "operUser");
return (Criteria) this;
}
public Criteria andOperUserLessThan(String value) {
addCriterion("oper_user <", value, "operUser");
return (Criteria) this;
}
public Criteria andOperUserLessThanOrEqualTo(String value) {
addCriterion("oper_user <=", value, "operUser");
return (Criteria) this;
}
public Criteria andOperUserLike(String value) {
addCriterion("oper_user like", value, "operUser");
return (Criteria) this;
}
public Criteria andOperUserNotLike(String value) {
addCriterion("oper_user not like", value, "operUser");
return (Criteria) this;
}
public Criteria andOperUserIn(List<String> values) {
addCriterion("oper_user in", values, "operUser");
return (Criteria) this;
}
public Criteria andOperUserNotIn(List<String> values) {
addCriterion("oper_user not in", values, "operUser");
return (Criteria) this;
}
public Criteria andOperUserBetween(String value1, String value2) {
addCriterion("oper_user between", value1, value2, "operUser");
return (Criteria) this;
}
public Criteria andOperUserNotBetween(String value1, String value2) {
addCriterion("oper_user not between", value1, value2, "operUser");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Date value) {
addCriterion("update_time =", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Date value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Date value) {
addCriterion("update_time >", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("update_time >=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Date value) {
addCriterion("update_time <", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Date value) {
addCriterion("update_time <=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Date> values) {
addCriterion("update_time in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Date> values) {
addCriterion("update_time not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Date value1, Date value2) {
addCriterion("update_time between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Date value1, Date value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateUserIsNull() {
addCriterion("update_user is null");
return (Criteria) this;
}
public Criteria andUpdateUserIsNotNull() {
addCriterion("update_user is not null");
return (Criteria) this;
}
public Criteria andUpdateUserEqualTo(String value) {
addCriterion("update_user =", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserNotEqualTo(String value) {
addCriterion("update_user <>", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserGreaterThan(String value) {
addCriterion("update_user >", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserGreaterThanOrEqualTo(String value) {
addCriterion("update_user >=", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserLessThan(String value) {
addCriterion("update_user <", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserLessThanOrEqualTo(String value) {
addCriterion("update_user <=", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserLike(String value) {
addCriterion("update_user like", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserNotLike(String value) {
addCriterion("update_user not like", value, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserIn(List<String> values) {
addCriterion("update_user in", values, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserNotIn(List<String> values) {
addCriterion("update_user not in", values, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserBetween(String value1, String value2) {
addCriterion("update_user between", value1, value2, "updateUser");
return (Criteria) this;
}
public Criteria andUpdateUserNotBetween(String value1, String value2) {
addCriterion("update_user not between", value1, value2, "updateUser");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator. This class corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
public static class Criterion implements Serializable {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
/**
* This field was generated by MyBatis Generator. This field corresponds to the database table t_bas_config
* @mbggenerated Mon Nov 07 14:10:41 CST 2016
*/
private static final long serialVersionUID = 1L;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
/**
* This class was generated by MyBatis Generator.
* This class corresponds to the database table t_bas_config
*
* @mbggenerated do_not_delete_during_merge Mon Nov 07 14:09:58 CST 2016
*/
public static class Criteria extends GeneratedCriteria implements Serializable {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table t_bas_config
*
* @mbggenerated Mon Nov 07 14:09:58 CST 2016
*/
private static final long serialVersionUID = 1L;
protected Criteria() {
super();
}
}
}
|
Shell
|
UTF-8
| 1,798
| 3.640625
| 4
|
[
"MIT"
] |
permissive
|
#!/bin/bash
## Config file
source ./config.conf
## Install packages
pacman -S gzip --noconfirm
## Download backup files
echo "Remote server IP ?"
read CONFIG_REMOTE_IP
echo "Remote server SSH username ?"
read CONFIG_REMOTE_USERNAME
mkdir -p /home/backup
scp -r $CONFIG_REMOTE_USERNAME@$CONFIG_REMOTE_IP:/home/backup/* /home/backup/
echo "Download backup files [OK]."
## Restore backup
echo "Restore a backup ? (y/n)"
read restore
if [ "$restore" = "y" ]; then
echo "Version ? (format: AAAAMMDD)"
read CONFIG_BACKUP_VERSION
tar -zxf /home/backup/$CONFIG_BACKUP_VERSION-mailboxes.tar.gz -C /home/
tar -zxf /home/backup/$CONFIG_BACKUP_VERSION-queue.tar.gz -C /home/
gunzip -k /home/backup/$CONFIG_BACKUP_VERSION-vmailme.sql.gz
gunzip -k /home/backup/$CONFIG_BACKUP_VERSION-roundcube.sql.gz
gunzip -k /home/backup/$CONFIG_BACKUP_VERSION-piwik.sql.gz
echo "Unzip backup files [OK]."
## Stop services
for v in dovecot postfix nginx;do systemctl stop $v.service;done
echo "Stop services [OK]."
## Import databases
mysql -p'$CONFIG_MARIADB_ROOT_PASSWORD' vmailme < /home/backup/$CONFIG_BACKUP_VERSION-vmailme.sql
mysql -p'$CONFIG_MARIADB_ROOT_PASSWORD' roundcube < /home/backup/$CONFIG_BACKUP_VERSION-roundcube.sql
mysql -p'$CONFIG_MARIADB_ROOT_PASSWORD' piwik < /home/backup/$CONFIG_BACKUP_VERSION-piwik.sql
rm /home/backup/$CONFIG_BACKUP_VERSION-vmailme.sql
rm /home/backup/$CONFIG_BACKUP_VERSION-roundcube.sql
rm /home/backup/$CONFIG_BACKUP_VERSION-piwik.sql
echo "Import databases [OK]."
## Set permissions
chown -R vmail:vmail /home/mailboxes
postfix set-permissions
echo "Set permissions [OK]."
## Start services
for v in dovecot postfix nginx;do systemctl start $v.service;done
echo "Start services [OK]."
fi
echo "Import [OK]."
|
Java
|
UTF-8
| 665
| 2.171875
| 2
|
[] |
no_license
|
package org.trails.test.functional;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.xpath.HtmlUnitXPath;
public class LocalizationTest extends FunctionalTest
{
public void testLocale() throws Exception
{
HtmlAnchor link = (HtmlAnchor) new HtmlUnitXPath("//a[img/@alt='portuguese']").selectSingleNode(startPage);
startPage = (HtmlPage) link.click();
assertTrue(startPage.asText().contains("Listar"));
HtmlPage listApplesPage = clickLinkOnPage(startPage, "Listar Apples");
assertTrue(listApplesPage.asText().contains("Applar"));
}
}
|
TypeScript
|
UTF-8
| 457
| 2.625
| 3
|
[
"MIT"
] |
permissive
|
import * as jwt from 'jsonwebtoken'
import * as dotenv from 'dotenv'
dotenv.config()
const secret = process.env.SECRET
class Plugin {
/**
*
* @param params Retorna o token decodificado com validade
* @param validade Validade do token, ex: 7d
*/
public async generateToken (params: string | object, validade: string): Promise<string> {
return jwt.sign(params, secret, {
expiresIn: validade
})
}
}
export default new Plugin()
|
Python
|
UTF-8
| 333
| 3.546875
| 4
|
[] |
no_license
|
### first 100 primal digits
def is_prim(a):
l = []
for i in range(2, a):
calc = a / i
if (calc == int(calc)):
l.append(i)
is_prim = (len(l) < 1)
return is_prim
while len(p_elements) < 100:
if(is_prim(i)):
p_elements.append(i)
i = i + 1
print(p_elements)
|
Python
|
UTF-8
| 461
| 3.796875
| 4
|
[
"BSD-3-Clause"
] |
permissive
|
def string(a):
return ''.join(a)
def permutation(s, l, r):
# Base case
if l == r:
print(string(s), end=' ')
else:
# Permutation made
for i in range(l, r):
s[l], s[i] = s[i], s[l]
#recursion called
permutation(s, l+1, r)
#backtrack
s[l], s[i] = s[i], s[l]
def main():
n_case = int(input())
for i in range(n_case):
s = str(input())
a = list(s)
permutation(a, 0, len(s))
print('')
if __name__ == '__main__':
main()
|
C++
|
UTF-8
| 1,490
| 3.453125
| 3
|
[
"MIT"
] |
permissive
|
#include "pint.hpp"
#include <vector>
#include <iostream>
using namespace std;
//retornar o indice (começando em 0) da embalagem mais leve
int solution(const vector<Pint> & input) {
int in = 0;
int size = input.size();
int fi = size - 1;
int size3, cmp;
Pint soma1, soma2;
while (size >= 3) {
size3 = size/3;
soma1 = 0;
soma2 = 0;
for (int i = in; i <= in + size3 - 1; i++) {
soma1 = soma1 + input[i];
}
for (int i = in + size3; i <= in + 2*size3 - 1; i++) {
soma2 = soma2 + input[i];
}
cmp = soma1.compare(soma2);
if (cmp == -1) {
fi = in + size3 - 1;
size = size3;
} else if (cmp == 1) {
fi = in + 2*size3 - 1;
in = in + size3;
size = size3;
} else {
in = in + 2*size3;
size = size - 2*size3;
}
}
if (size == 2 && (input[in].compare(input[fi]) == -1)) {
return in;
}
return fi;
/*
// Dicas:
//soma:
Pint soma = input[0] + input[1];
input[0].print();
cout << " + ";
input[1].print();
cout << " = ";
soma.print();
cout << endl;
//tamanho da entrada:
cout << input.size() << endl;
// comparando: input[99].compare(input[2]) == 0 // iguais
// input[99].compare(input[2]) == -1 // input[99] < input[2]
// input[99].compare(input[2]) == 1 // input[99] > input[2]
return -1;
*/
}
|
Java
|
UTF-8
| 1,704
| 3.140625
| 3
|
[] |
no_license
|
package methodEmbedding.Counting_Sheep.S.LYD1464;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CountingSheep {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt();
for (int i = 1; i <= t; ++i) {
int n = in.nextInt();
StringBuffer digits = new StringBuffer("0123456789");
int multiplier = 1;
int number = n;
int lastNumber = -1;
StringBuffer trace = new StringBuffer();
while(digits.length() > 0) {
number = multiplier * n;
if (lastNumber == number) {
break;
}
String s = Integer.toString(number);
int length = s.length();
for (int j=0; j<length; j++) {
String digit = Character.toString(s.charAt(j));
int index = digits.indexOf(digit);
if (index >= 0) {
digits.deleteCharAt(index);
}
}
//trace.append("[" + multiplier + "*" + n + "=" + number + "]" + digits + "\n");
multiplier++;
lastNumber = number;
}
if (digits.length() > 0) {
System.out.println("Case #" + i + ": INSOMNIA");
} else {
System.out.println("Case #" + i + ": " + number);
//System.out.println(trace.toString());
}
}
in.close();
}
}
|
C++
|
UTF-8
| 2,791
| 2.921875
| 3
|
[
"MIT"
] |
permissive
|
#include <iostream>
#include <vector>
#include <memory>
#include "QuadTree.h"
int main(int argc, char* argv[]) {
QuadTree qTree(0, Rectangle(0, 0, 600, 600));
std::vector<std::shared_ptr<Entity>> entities;
//QUAD 1
entities.push_back(std::shared_ptr<Entity>(new Entity({325, 0, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({325 + 30, 0, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({325, 28, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({325 + 100, 50, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({325 + 100, 100, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({325 + 100, 200, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({325 + 200, 50, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({325 + 200, 100, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({325 + 200, 200, 32, 32})));
//this is not in any quadrant
//for every other entity this shows up in their quadrant
//so you will be able to see this on every other entities collision
entities.push_back(std::shared_ptr<Entity>(new Entity({290, 290, 32, 32})));
//QUAD 2
entities.push_back(std::shared_ptr<Entity>(new Entity({0, 0, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({50, 0, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({0, 100, 32, 32})));
//QUAD 3
entities.push_back(std::shared_ptr<Entity>(new Entity({0, 325, 32, 32})));
//QUAD 4
entities.push_back(std::shared_ptr<Entity>(new Entity({325, 325, 32, 32})));
entities.push_back(std::shared_ptr<Entity>(new Entity({325 + 50, 325 + 50, 32, 32})));
for (auto& i : entities) {
std::cout << *i << "\n";
qTree.insert(i);
}
for (auto& i : entities) {
auto possibleCollisions = qTree.retrievePossibleCollisions(i);
std::cout << "\nThere are " << possibleCollisions.size() << " possible collisions for " << *i << "\n";
for (auto& j : possibleCollisions) {
auto possibleCollider = j.lock();
if (i == possibleCollider) {//if they are the same entity then do not test anything
std::cout << "\t" << *i << " == " << *possibleCollider << " are the same.\n";
continue;
}
if (i->getRect().collided(possibleCollider->getRect())) {
std::cout << "\t" << *i << " collided with " << *possibleCollider << "\n";
} else {
std::cout << "\t" << *possibleCollider << "\n";
}
}
}
std::cout << "\nPre order traversal:\n";
qTree.preOrderTraversal();
entities.clear();
return 0;
}
|
Java
|
UTF-8
| 665
| 1.835938
| 2
|
[] |
no_license
|
package com.dataweb;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Created by user on 29.08.2016.
*/
public class ParticleboardsMenuParametrs extends MenuParametrs {
@JsonProperty("minLaminated")
private Long minLaminated;
@JsonProperty("maxLaminated")
private Long maxLaminated;
public Long getMinLaminated() {
return minLaminated;
}
public Long getMaxLaminated() {
return maxLaminated;
}
public void setMinLaminated(Long minLaminated) {
this.minLaminated = minLaminated;
}
public void setMaxLaminated(Long maxLaminated) {
this.maxLaminated = maxLaminated;
}
}
|
JavaScript
|
UTF-8
| 600
| 3.625
| 4
|
[] |
no_license
|
[] + {}; // "[object Object]"
/*
Explanation:
When JavaScript needs to add "stuff" together it will covert the types to primitives.
That usually means calling the `toString()` function.
In this case:
[].toString() produces an empty string
{}.toString() produces "[object Object]"
Which results in: "" + "[object Object]" -> "[object Object]"
*/
{} + []; // 0
{} + {}; // NaN
[0, -1, -2].sort(); // [-1, -2, 0]
',,,' == new Array(4) // true
["1", "2", "3", "4", "5", "6", "7", "8", "9"].map(parseInt) // [ 1, NaN, NaN, NaN, NaN, NaN, NaN, NaN, NaN ]
2147483648 | 0 // -2147483648
|
PHP
|
UTF-8
| 88
| 2.671875
| 3
|
[] |
no_license
|
<?php
$feetInMile =9033;
function sayHello($name)
{
echo "Hello $name <br>";
}
?>
|
Java
|
UTF-8
| 3,120
| 2.828125
| 3
|
[] |
no_license
|
package com.sitech.prm.subject.cells;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.aspose.cells.ICellsDataTable;
public class AsposeMap implements ICellsDataTable{
//数据集合
@SuppressWarnings("rawtypes")
private List<Map<String,Object>> dataList = null;
//索引
private int index;
//存放dataList当中Map<String, Object>的key
private String[] columns = null;
@SuppressWarnings("rawtypes")
public AsposeMap(Map data) {
if(this.dataList == null) {
this.dataList = new ArrayList<Map<String,Object>>();
}
dataList.add(data);
}
@SuppressWarnings("rawtypes")
public AsposeMap(List<Map<String,Object>> data) {
this.dataList = data;
}
/**
* @Description: 初始化方法
* @author:14K sunyz@si-tech.com.cn
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
@Override
public void beforeFirst() {
index = -1;
columns = this.getColumns();
}
/**
* @Description: WorkbookDesigner自动调用
* 会将this.getColumns()方法所返回的列 按照顺序调用改方法
* @param arg0
* @return
* @author:14K sunyz@si-tech.com.cn
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
@SuppressWarnings("rawtypes")
@Override
public Object get(int columnIndex) {
if(index < 0 || index >= this.getCount()) {
return null;
}
Map record = this.dataList.get(index);
String columnName = this.columns[columnIndex];
return record.get(columnName);
}
/**
* @Description: 根据columnName返回数据
* @param arg0
* @return
* @author:14K sunyz@si-tech.com.cn
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
@Override
@SuppressWarnings("rawtypes")
public Object get(String columnName) {
Map record = this.dataList.get(index);
return record.get(columnName);
}
/**
* @Description: 获得列集合
* @return
* @author:14K sunyz@si-tech.com.cn
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public String[] getColumns() {
if(this.dataList.size() == 0) return new String[] {};
Map temp = this.dataList.get(0);
Set<Entry> entrys = temp.entrySet();
List<String> columns = new ArrayList<String>();
for (Entry e : entrys) {
columns.add((String)e.getKey());
}
String[] s = new String[entrys.size()];
columns.toArray(s);
return s;
}
/**
* @Description: 获取数据总数
* @return
* @author:14K sunyz@si-tech.com.cn
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
@Override
public int getCount() {
return this.dataList.size();
}
/**
* @Description: 判断是否还有数据 并将index下移
* @return
* @author:14K sunyz@si-tech.com.cn
* @update:[日期YYYY-MM-DD] [更改人姓名][变更描述]
*/
@Override
public boolean next() {
return ++index<this.getCount();
}
}
|
JavaScript
|
UTF-8
| 7,319
| 3.203125
| 3
|
[] |
no_license
|
/*
gameId: ...
schema: []
size: 19
capCount: { black: 0, white: 0 },
turn: WGo.B
createdAt: new Date()
*/
Positions = new Mongo.Collection('positions');
// create new Position but don't save it
Positions.new = function(gameId, posAttributes) {
var game = Games.findOne(gameId);
if (!game) throw new Meteor.Error("Game not found!");
var size = game.size;
var schema = [];
for(var i = 0; i < size*size; i++) schema[i] = 0;
var position = {
schema: schema,
size: size,
gameId: game._id,
createdAt: new Date()
};
if (posAttributes) position = _.extend(position, posAttributes);
// so we can use Position methods on this before we save it to Mongo
position = Positions._transform(position);
return position;
}
// create new Position and save it
Positions.create = function(gameId, posAttributes) {
var insert = Positions.new(gameId, posAttributes);
return Positions.insert(insert);
}
Positions.helpers({
/**
* Returns value of given coordinates.
*
* @param {number} x coordinate
* @param {number} y coordinate
* @return {(WGo.BLACK|WGo.WHITE|0)} color
*/
get: function(x,y) {
if(x < 0 || y < 0 || x >= this.size || y >= this.size) return undefined;
return this.schema[x*this.size+y];
},
/**
* Sets value of given coordinates.
*
* @param {number} x coordinate
* @param {number} y coordinate
* @param {(WGo.B|WGo.W|0)} c color
*/
set: function(x,y,c) {
this.schema[x*this.size+y] = c;
return this;
},
/**
* Clears the whole position (every value is set to 0).
*/
clear: function() {
for(var i = 0; i < this.size*this.size; i++) this.schema[i] = 0;
return this;
},
/**
* Clones the whole position.
*
* @return {WGo.Position} copy of position
*/
clone: function() {
var clone = Positions.new(this.gameId);
clone.schema = _.clone(this.schema);
return clone;
},
/**
* Get score values of schema based on Tromp-Taylor
*
* @return "W+3", "B+2"
*/
formattedScore: function() {
var score = this.score();
var modifier = (score < 0) ? "W+" : "B+";
return modifier+Math.abs(score);
},
/**
* Get score values of schema based on Tromp-Taylor
*
* @return integer score (positive value black, negative value white)
*/
score: function() {
var boardScore = this.getScoreSchema().reduce(function(a, b){ return a += b; }, 0);
var komi = -6.5;
return boardScore + komi;
},
/**
* Get score values of schema based on Tromp-Taylor
*
* @return schema with all points correctly scored
*/
getScoreSchema: function() {
var position = this;
var data = {
whiteScore: 0,
blackScore: 0,
contestedCount: 0
}
var schema = this.schema;
// copy array
var scoreSchema = [];
schema.forEach(function(point, index){
if (point === WGo.B) scoreSchema.push(1);
else if (point === WGo.W) scoreSchema.push(-1);
else scoreSchema.push(position.determineColor(index));
});
return scoreSchema;
},
/**
* Determines score of single unoccupied point based on Tromp-Taylor
*
* @return 1 (black), 0, -1 (white)
*/
determineColor: function(index) {
// find values of all directions by traversing
var pointData = [];
pointData.push(this.traverseBlank(index, "up"));
pointData.push(this.traverseBlank(index, "down"));
pointData.push(this.traverseBlank(index, "right"));
pointData.push(this.traverseBlank(index, "left"));
// if it connects with both white and black, or if it connects with neither
// return neutral
if (
(pointData.indexOf(WGo.B) > -1 && pointData.indexOf(WGo.W) > -1) ||
(pointData.indexOf(WGo.B) === -1 && pointData.indexOf(WGo.W) === -1)
) return 0;
// if it connects with only black, this point is scored for black
else if (pointData.indexOf(WGo.B) > -1 && pointData.indexOf(WGo.W) === -1)
return WGo.B;
// if it connects with only white, this point is scored for white
else if (pointData.indexOf(WGo.B) === -1 && pointData.indexOf(WGo.W) > -1)
return WGo.W;
// shoiuld never happen
else return console.log("Something went wrong in determineColor");
},
/**
* Traverses one direction until we hit a stone or the edge (used in scoring)
*
* @return 1 (black encountered), 0 (edge encountered), -1 (white encountered)
*/
traverseBlank: function(pointIndex, direction) {
var result = this.travel(pointIndex, direction);
if (result === 0) { // if blank, keep going
pointIndex += this.getDirectionIncrement(direction);
this.traverseBlank(pointIndex, direction);
}
// if edge, return 0
else if (result === false) return 0;
// if -1 or 1, return that value
else return result;
},
/**
* Traverses single stone to find all connected ones
*
* @return array [pointIndex] connected stones' indices
*/
traverseStones: function(pointIndex, existing) {
if (!existing) var existing = []; // base case
var color = this.schema[pointIndex];
// push this index to the results pile
if (color) {
existing.push(pointIndex);
// 1. check up, down, left, right
var directions = ["up", "down", "left", "right"];
var _this = this;
directions.forEach(function(direction) {
if ( _this.travel(pointIndex, direction) === color ) {
var newIndex = pointIndex + _this.getDirectionIncrement(direction);
if (existing.indexOf(newIndex) === -1)
_.extend(existing, _this.traverseStones(newIndex, existing));
}
});
}
return existing;
},
/**
* Travel one space to a certain direction, returns what it finds
*
* @return 1 (black), 0 (blank), -1 (white), false (edge)
*/
travel: function(pointIndex, direction) {
if (["up", "down", "left", "right"].indexOf(direction) === -1)
var direction = "up";
pointIndex += this.getDirectionIncrement(direction);
// return undefined if this pointIndex is now off the board
var sideLength = Math.sqrt(this.schema.length);
if (
(direction === "up"
&& pointIndex != 0 && (pointIndex % sideLength === (sideLength-1)) )
|| (direction === "down"
&& pointIndex != 0 && pointIndex % sideLength === 0 )
|| (direction === "right"
&& pointIndex > this.schema.length-1)
|| (direction === "left"
&& pointIndex < 0)
) return false;
// for base case when pointIndex = -1
else if (this.schema[pointIndex] === undefined) return false;
// if it's colored stone, return black count
else if (this.schema[pointIndex] === WGo.B) return 1;
else if (this.schema[pointIndex] === WGo.W) return -1;
// if it's neither (another empty space) return 0.
else return 0;
},
/**
* Get increment of certain direction
*
* @return increment based on game's size
*/
getDirectionIncrement: function(direction) {
var sideLength = Math.sqrt(this.schema.length);
var increment;
if (direction === "up") increment = -1;
else if (direction === "down") increment = 1;
else if (direction === "right") increment = sideLength;
else if (direction === "left") increment = -sideLength;
else throw Meteor.Error("Direction is not valid.");
return increment;
}
});
|
C#
|
UTF-8
| 4,873
| 2.53125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
using System.Collections.Generic;
public partial class Display : System.Web.UI.Page
{
public static ArrayList Files = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (elm1 != null && !string.IsNullOrWhiteSpace(elm1.Value))
{
elm1.Value = HttpUtility.HtmlDecode(elm1.Value);
}
}
SqlConnection Cn = new SqlConnection("server=WAZZUP-PC\\SQLEXPRESS; initial catalog=TestDB; integrated security=true");
string com = "SELECT ID, Auteur, [Content], Tag FROM Article_Blog WHERE (ID=5)";
SqlDataAdapter adpt = new SqlDataAdapter(com, Cn);
DataSet myDataSet = new DataSet();
adpt.Fill(myDataSet, "Article_Blog");
DataTable myDataTable = myDataSet.Tables[0];
DataRow tempRow = null;
foreach (DataRow tempRow_Variable in myDataTable.Rows)
{
tempRow = tempRow_Variable;
// ListBox1.Items.Add((tempRow["id"] + " (" + tempRow["auteur"] + ")" + " (" + tempRow["content"] + ")" + " (" + tempRow["Tag"] + ")"));
elm1.Value = tempRow["content"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = Server.HtmlEncode(this.elm1.Value);
//Label1.Text = this.elm1.Value;
//String QueryString = "INSERT INTO Article (Id, auteur, date, categorie) VALUES ('7', 'FCW', '', 'Informatique')";
String QueryString = "INSERT INTO Article_Blog (ID, Auteur, Content, Tag) VALUES ('" + TextBox1.Text + "', '" + TextBox2.Text + "', '" + this.elm1.Value + "','" + TextBox3.Text + "')";
SqlConnection Cn = new SqlConnection("server=WAZZUP-PC\\SQLEXPRESS; initial catalog=TestDB; integrated security=true");
try
{
Cn.Open();
if (Cn != null)
{
Label1.Text = "CONNECTER";
Console.WriteLine("CONNECTER");
}
SqlCommand Cmd = new SqlCommand();
Cmd.CommandText = QueryString;
//Cmd.CommandType = CommandType.Text;
Cmd.Connection = Cn;
Cmd.ExecuteNonQuery();
Cn.Close();
}
catch (Exception Ex)
{
Label1.Text = Ex.ToString();
Cn.Close();
};
}
protected void Button2_Click(object sender, EventArgs e)
{
LabelDebug1.Text = TextBox1.Text;
SqlConnection Cn = null;
SqlDataReader sdr = null;
//this.elm1.Value = "<p>This is a test document. Some <span class='mceNonEditable' style=\"color: #ff0000;\">Portion</span> of this document can't be changed.</p>\r\n<p>The area with red <span class='mceNonEditable' style=\"color: #ff0000;\">background </span>can't be <span class='mceNonEditable' style=\"color: #ff0000;\">removed</span>. You can only <span class='mceNonEditable' style=\"color: #ff0000;\">change </span>the area with black.</p>\r\n<p> </p>";
Cn = new SqlConnection("server=WAZZUP-PC\\SQLEXPRESS; initial catalog=TestDB; integrated security=true");
Cn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM [Article_Blog] WHERE ([id] = @id)", Cn);
//SqlParameter param = new SqlParameter();
//param.ParameterName = "@id";
//param.Value = TextBox1.Text;
//command.Parameters.Add(param);
command.Parameters.Add(new SqlParameter("id", TextBox1.Text));
sdr = command.ExecuteReader();
while (sdr.Read())
{
elm1.Value = sdr["content"].ToString();
Label2.Text = sdr["auteur"].ToString();
}
Cn.Close();
//string com = "SELECT * FROM [Article_Blog] WHERE ([id] = @id)";
//SqlDataAdapter adpt = new SqlDataAdapter(com, Cn);
//DataSet myDataSet = new DataSet();
//adpt.Fill(myDataSet, "Article_Blog");
//DataTable myDataTable = myDataSet.Tables[0];
//DataRow tempRow = null;
//foreach (DataRow tempRow_Variable in myDataTable.Rows)
//{
// tempRow = tempRow_Variable;
// // ListBox1.Items.Add((tempRow["id"] + " (" + tempRow["auteur"] + ")" + " (" + tempRow["content"] + ")" + " (" + tempRow["Tag"] + ")"));
// elm1.Value = tempRow["content"].ToString();
//}
}
public String SystemText
{
get
{
return HttpUtility.HtmlDecode(elm1.Value);
}
set
{
elm1.Value = value;
}
}
}
|
Markdown
|
UTF-8
| 7,116
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
# @dreamnet/deploy
[](https://npmjs.org/package/@dreamnet/deploy)
[](https://npmjs.org/package/@dreamnet/deploy)

Deploy files and folders to different file providers:
- [IPFS](https://docs.ipfs.io/reference/http/api/)
- [Pinata](https://pinata.cloud/)
- [Infura](https://infura.io)
- [IPFS Cluster](https://cluster.ipfs.io/documentation/reference/api/)
- [Minio (S3)](https://docs.min.io/docs/minio-quickstart-guide.html)
- [MEGA](https://mega.co.nz/)
- Git/Gitea
- Github
- codeberg.org
- git.teknik.io
It is also possible to update the [DNSLink](https://docs.ipfs.io/concepts/dnslink/) of a domain if you have uploaded your file to an IPFS provider, supported DNS providers:
- [Cloudflare](https://www.cloudflare.com/)
## Usage
Setup with environment variables:
```ts
import { Release } from '@dreamnet/deploy'
const release = new Release('./build/myapp.exe')
// Upload file to IPFS, Pinata and MEGA.
release.addProvider(['IPFS', 'Pinata', 'MEGA'])
```
Setup without environment variables:
```ts
import { Release, IPFS, Pinata, MEGA } from '@dreamnet/deploy'
const release = new Release('./build/myapp.exe')
// IPFS
const ipfs = new IPFS()
ipfs.setAddress('/ip4/127.0.0.1/tcp/5002')
.setUsername('root')
.setPassword('secret')
// Pinata
const pinata = new Pinata()
pinata.setToken('...')
// MEGA
const mega = new MEGA()
mega.setEmail('test@example.com')
.setPassword('secret')
.setFolder('/projects/releases/')
// Upload file to IPFS, Pinata and MEGA.
release.addProvider([ipfs, pinata, mega])
```
Deploy:
```ts
// Deploy!
const response = await release.deploy()
/*
[
{
provider: "IPFS",
cid: "Qm...",
url: "https://gateway.ipfs.io/ipfs/Qm..."
},
{
provider: "Pinata",
cid: "Qm...",
url: "https://gateway.pinata.cloud/ipfs/Qm..."
},
{
provider: "MEGA",
cid: null,
url: "https://mega.nz/file/cSx..."
}
]
*/
console.log(response)
```
Events:
```ts
import { Provider, UploadResult } from '@dreamnet/deploy'
release.on('upload:begin', (provider: Provider) => {
console.log(`Uploading to ${provider.label}...`)
})
release.on('upload:success', (result: UploadResult, provider: Provider) => {
console.log(`Uploaded to ${provider.label}.`)
console.log(result.url)
})
release.on('upload:fail', (error: Error, provider: Provider) => {
console.error(`Upload to ${provider.label} failed: ${error.message}`)
})
release.on('pin:begin', (provider: Provider) => {
console.log(`Pinning to ${provider.label}...`)
})
release.on('pin:success', (provider: Provider) => {
console.log(`Pinned to ${provider.label}.`)
console.log(cid)
})
release.on('pin:fail', (error: Error, provider: Provider) => {
console.error(`Pin to ${provider.label} failed: ${error.message}`)
})
release.on('unpin:begin', (provider: Provider) => {
console.log(`Unpinning old version from ${provider.label}...`)
})
release.on('unpin:success', (provider: Provider) => {
console.log(`Unpinned from ${provider.label}.`)
console.log(provider.release.previousCID)
})
release.on('unpin:fail', (error: Error, provider: Provider) => {
console.error(`Unpin from ${provider.label} failed: ${error.message}`)
})
release.on('dns:begin', (provider: Provider) => {
console.log(`Updating ${provider.label} DNSLink...`)
})
release.on('dns:fail', (error: Error, provider: Provider) => {
console.error(`${provider.label} DNSLink update has failed: ${error.message}`)
})
release.on('dns:success', (result: DnsRecord, provider: Provider) => {
console.log(`${provider.label} DNSLink updated.`)
console.log(`${result.record} = ${result.content}`)
})
release.on('fail', (error: Error) => {
console.trace(error)
})
```
## Enviroment variables
### IFPS
- `DEPLOY_IPFS_GATEWAY` (default: `https://gateway.ipfs.io`)
- `DEPLOY_IPFS_ADDRESS` (default: `/ip4/127.0.0.1/tcp/5001`)
- `DEPLOY_IPFS_USERNAME`: Username if the API is behind a [basic authentication](https://en.wikipedia.org/wiki/Basic_access_authentication).
- `DEPLOY_IPFS_PASSWORD`: Password if the API is behind a [basic authentication](https://en.wikipedia.org/wiki/Basic_access_authentication).
### Pinata
- `DEPLOY_PINATA_GATEWAY` (default: `https://gateway.pinata.cloud`)
- `DEPLOY_PINATA_TOKEN`: (required) [API JWT](https://pinata.cloud/keys)
### Infura
- `DEPLOY_INFURA_GATEWAY` (default: `https://gateway.ipfs.io`)
- `DEPLOY_INFURA_ADDRESS` (default: `/dns4/ipfs.infura.io/tcp/5001/https`)
### IFPS Cluster
- `DEPLOY_IPFSCLUSTER_GATEWAY` (default: `https://gateway.ipfs.io`)
- `DEPLOY_IPFSCLUSTER_ADDRESS` (default: `/ip4/127.0.0.1/tcp/9094`)
- `DEPLOY_IPFSCLUSTER_USERNAME`: Username if the API is behind a [basic authentication](https://en.wikipedia.org/wiki/Basic_access_authentication).
- `DEPLOY_IPFSCLUSTER_PASSWORD`: Password if the API is behind a [basic authentication](https://en.wikipedia.org/wiki/Basic_access_authentication).
### Minio
- `DEPLOY_MINIO_GATEWAY`: Public url to access the files. (If not provided, a url will be returned valid for 7 days)
- `DEPLOY_MINIO_ADDRESS` (default: `/ip4/127.0.0.1/tcp/9000/http`)
- `DEPLOY_MINIO_SSL` (default by address: `false`)
- `DEPLOY_MINIO_BUCKET` (required)
- `DEPLOY_MINIO_FOLDER`: Parent path where the files will be stored.
- `DEPLOY_MINIO_KEY` (required)
- `DEPLOY_MINIO_SECRET` (required)
### MEGA
- `DEPLOY_MEGA_EMAIL` (required)
- `DEPLOY_MEGA_PASSWORD` (required)
- `DEPLOY_MEGA_FOLDER`: Parent path where the files will be stored.
### Git
> These will be used as defaults for any git-based provider.
- `DEPLOY_GIT_OWNER`: Owner of the repository. (Example: **dreamnettech**)
- `DEPLOY_GIT_REPO`: Repository name. (Example: **monorepo**)
- `DEPLOY_GIT_TAG`: Tag to create the release (if necessary) and upload the files.
- `DEPLOY_GIT_RELEASE_NAME`: (default: `DEPLOY_GIT_TAG`) Name that will be given to the release.
### Github
- `DEPLOY_GITHUB_OWNER` (required)
- `DEPLOY_GITHUB_REPO` (required)
- `DEPLOY_GITHUB_TAG` (required)
- `DEPLOY_GITHUB_RELEASE_NAME`
- `DEPLOY_GITHUB_TOKEN` (required)
### codeberg.org
- `DEPLOY_CODEBERG_OWNER` (required)
- `DEPLOY_CODEBERG_REPO` (required)
- `DEPLOY_CODEBERG_TAG` (required)
- `DEPLOY_CODEBERG_RELEASE_NAME`
- `DEPLOY_CODEBERG_TOKEN` (required)
### git.teknik.io
- `DEPLOY_TEKNIK_OWNER` (required)
- `DEPLOY_TEKNIK_REPO` (required)
- `DEPLOY_TEKNIK_TAG` (required)
- `DEPLOY_TEKNIK_RELEASE_NAME`
- `DEPLOY_TEKNIK_TOKEN` (required)
### Cloudflare
- `DEPLOY_CLOUDFLARE_EMAIL` (required if `DEPLOY_CLOUDFLARE_TOKEN` is empty)
- `DEPLOY_CLOUDFLARE_KEY` (required if `DEPLOY_CLOUDFLARE_TOKEN` is empty)
- `DEPLOY_CLOUDFLARE_TOKEN`
- `DEPLOY_CLOUDFLARE_ZONE` (required)
- `DEPLOY_CLOUDFLARE_RECORD` (required)
## TODO
- Improve programmatic implementation. (Intended to use with enviroment variables)
- Tests
- More providers
- More documentation (DNSLink, Unpin, etc)
## Similar
- [@dreamnet/deploy-cli](https://www.npmjs.com/package/@dreamnet/deploy-cli)
|
Java
|
UTF-8
| 2,350
| 2.453125
| 2
|
[
"MIT"
] |
permissive
|
/**
* This file is part of RawAntTasks - a collection of Ant tasks.
*
* Copyright (c) 2014 Tom Kaczocha
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @category Java
* @package org.crazydev.ant.tasks
* @author Tom Kaczohca <tom@crazydev.org>
* @copyright 2014 Tom Kaczocha
* @license http://crazydev.org/license.txt MIT
* @link http://crazydev.org/
*/
package org.crazydev.ant.tasks;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
/**
* Ant task to reset a property value.
*
* @author Tom Kaczocha
*/
public class PropertySet extends Task
{
private String _name = null;
private String _value = null;
/**
* Resets a property value.
*
* @throws BuildException
*/
@Override
public void execute( ) throws BuildException
{
this.getProject( ).setProperty( this._name, this._value );
}
/**
* Sets the property name.
*
* @param name property name
*/
public void setName( String name )
{
this._name = name;
}
/**
* Sets the property value.
*
* @param value property value
*/
public void setValue( String value )
{
this._value = value;
}
}
|
Java
|
GB18030
| 1,985
| 2.8125
| 3
|
[] |
no_license
|
package cn.itcast.servlet_refactory.servlet;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.servlet_refactory.utils.StringUtils;
public class ActionServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.ȡĵuri
String uri = request.getRequestURI();
//ȡuriȡ÷ʵaction
String actionName = StringUtils.parse(uri);
System.out.println(actionName);
//applicationȡӦclass
Map<String,String> map = (Map<String, String>) request.getServletContext().getAttribute("actions");
String className = map.get(actionName);
System.out.println(className);
try {
//classNameȡö
Class ActionClass = Class.forName(className);
//classNameеexecute
//עҪrequestresponseз䣬ֱgetClass()
Class requestClass = Class.forName("javax.servlet.http.HttpServletRequest");
Class responseClass = Class.forName("javax.servlet.http.HttpServletResponse");
Method method = ActionClass.getMethod("execute",requestClass,responseClass);
//ִз
String result = (String) method.invoke(ActionClass.newInstance(), request,response);
//ת
request.getRequestDispatcher(result).forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Go
|
UTF-8
| 1,381
| 2.796875
| 3
|
[
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
package serviceparamvaluelookups
import (
"fmt"
"strconv"
"github.com/transcom/mymove/pkg/appcontext"
"github.com/transcom/mymove/pkg/models"
)
// DistanceZipSITDestLookup does the lookup of distance for SIT at destination
type DistanceZipSITDestLookup struct {
DestinationAddress models.Address
FinalDestinationAddress models.Address
}
func (r DistanceZipSITDestLookup) lookup(appCtx appcontext.AppContext, keyData *ServiceItemParamKeyData) (string, error) {
planner := keyData.planner
// If the zip3s are identical, we do a zip3 distance calc (which uses RM).
// If they are different, we do a zip5 distance calc (which uses DTOD).
destZip := r.DestinationAddress.PostalCode
if len(destZip) < 5 {
return "", fmt.Errorf("invalid destination postal code of %s", destZip)
}
destZip3 := destZip[:3]
finalDestZip := r.FinalDestinationAddress.PostalCode
if len(finalDestZip) < 5 {
return "", fmt.Errorf("invalid SIT final destination postal code of %s", destZip)
}
finalDestZip3 := finalDestZip[:3]
var distanceMiles int
var distanceErr error
if destZip3 == finalDestZip3 {
distanceMiles, distanceErr = planner.Zip5TransitDistance(destZip, finalDestZip)
} else {
distanceMiles, distanceErr = planner.Zip3TransitDistance(destZip, finalDestZip)
}
if distanceErr != nil {
return "", distanceErr
}
return strconv.Itoa(distanceMiles), nil
}
|
Java
|
UTF-8
| 3,664
| 2.59375
| 3
|
[] |
no_license
|
package com.example.lab7;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class EditActivity extends AppCompatActivity {
EditText fileName;
EditText fielContent;
Button save;
Button load;
Button clear;
Button delete;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
initial();
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = fileName.getText().toString();
String content = fielContent.getText().toString();
if(name.isEmpty())
{
Toast.makeText(EditActivity.this,"File name cannot be empty",Toast.LENGTH_LONG).show();
}
else
{
try {
FileOutputStream outputStream = openFileOutput(name,MODE_PRIVATE);
outputStream.write(content.getBytes());
outputStream.flush();
outputStream.close();
Toast.makeText(EditActivity.this,"Save successfully",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
});
load.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = fileName.getText().toString();
try {
FileInputStream inputStream = openFileInput(name);
byte[] content = new byte[inputStream.available()];
StringBuilder stringBuilder = new StringBuilder("");
int length;
while((length = inputStream.read(content)) > 0)
{
stringBuilder.append(new String(content,0,length));
}
inputStream.close();
fielContent.setText(stringBuilder.toString());
Toast.makeText(EditActivity.this,"Load successfully",Toast.LENGTH_LONG).show();
} catch (java.io.IOException e) {
e.printStackTrace();
Toast.makeText(EditActivity.this,"Failed to load file",Toast.LENGTH_LONG).show();
fielContent.setText("");
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fielContent.setText("");
}
});
delete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = fileName.getText().toString();
deleteFile(name);
Toast.makeText(EditActivity.this,"Delete successfully",Toast.LENGTH_LONG).show();
}
});
}
void initial()
{
fileName = findViewById(R.id.file_name);
fielContent = findViewById(R.id.file_content);
save = findViewById(R.id.save);
load = findViewById(R.id.load);
clear = findViewById(R.id.clear_content);
delete = findViewById(R.id.delete);
}
}
|
Ruby
|
UTF-8
| 993
| 2.984375
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'thor'
require './client/api_client'
# Subcommands to do with the books endpoints.
class Authors < Thor
include API
desc 'list', 'List all authors'
def list
puts api.authors.get.map(&:name).join("\n")
end
desc 'add NAME', 'Add an author'
def add(name)
author = api.authors.post(name: name).body
puts "#{author['name']} has been added"
end
desc 'edit NAME NEW_NAME', 'Edit an existing author'
def edit(name, new_name)
author = find_by_name(name)
return puts "#{name} not found" if author.nil?
new_author = author.put(name: new_name).body
puts "#{new_author['name']} has been updated"
end
desc 'delete NAME', 'Remove an existing author'
def delete(name)
author = find_by_name(name)
return puts "#{name} not found" if author.nil?
author.delete
puts "#{name} has been removed"
end
private
def find_by_name(name)
api.authors.get.select { |a| a.name == name }.first
end
end
|
C++
|
UTF-8
| 1,147
| 2.703125
| 3
|
[] |
no_license
|
//
// Created by hp on 22/07/2020.
//
#ifndef BOMBERMAN_CONTROLADORLADRILLOEXPLOSIVO_H
#define BOMBERMAN_CONTROLADORLADRILLOEXPLOSIVO_H
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Texture.hpp>
#include <SFML/System/Time.hpp>
//<list> nos permite ...
#include <list>
#include "ControladorTiempo.h"
//Esta clase nos permite gestionar la animacion de los ladrillos explosivos
//Posee una referencia a un TimeManager
class ControladorLadrilloExplosivo : public sf::Drawable {
private:
ControladorTiempo const & _controladorTiempo;
struct LadrilloExplosivo{
const unsigned int fila, columna;
const sf::Time horainicio;
};
std::list<LadrilloExplosivo> _ladrillo;
sf::Texture _hojaSprites;
void draw(sf::RenderTarget &target, sf::RenderStates states) const ;
public:
//Manda error si no se pudieron cargar los recursos
ControladorLadrilloExplosivo(ControladorTiempo const & controladorTiempo);
void addLadrillo (unsigned int fila, unsigned int columna);
//Elimina los ladrillos antiguuos
void actualizar();
};
#endif //BOMBERMAN_CONTROLADORLADRILLOEXPLOSIVO_H
|
C++
|
ISO-8859-1
| 2,222
| 2.859375
| 3
|
[] |
no_license
|
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <stdio.h>
using namespace std;
using namespace cv;
Mat img; //Imagem de entrada
Mat_<uchar> gray(194, 259, CV_8UC3); //Imagem em tons de cinza
Mat_<uchar> equalized(194, 259, CV_8UC3); //Imagem equalizada
Mat hist_gray;
Mat hist_equalized;
Mat histograma(Mat& imagem)
{
// Definir as barras do histograma
int bins = 256; //Quantidade de barras
int histSize[] = { bins }; //Tamanho do histograma
// O intervalo do histograma
float lranges[] = { 0, 256 };
const float* ranges[] = { lranges };
Mat hist;
int channels[] = { 0 }; //Numeros de canais, como a imagem de entrada s de um canal, vem 0
int const hist_height = 256;
Mat3b hist_image = Mat3b::zeros(hist_height, bins);
calcHist(&imagem, 1, channels, Mat(), hist, 1, histSize, ranges, true, false); //Funo para criar o histograma
double max_val = 0;
minMaxLoc(hist, 0, &max_val);
// Visualizar cada barra
for (int b = 0; b < bins; b++)
{
float const binVal = hist.at<float>(b);
int const height = cvRound(binVal * hist_height / max_val);
line(hist_image, Point(b, hist_height - height), Point(b, hist_height), Scalar::all(255));
// imagem ponto inicial ponto final
}
return hist_image;
}
int main()
{
//Imagem de entrada
img = imread("C:/Users/User/Desktop/GIT/LapiscoComputerVisionRepo/images/ImagemOriginal.jpg");
//Converter pra cinza
cvtColor(img, gray, COLOR_RGB2GRAY);
int max = gray.at<uchar>(0, 0);
int min = gray.at<uchar>(0, 0);
int x, y;
for (y = 0; y < 194; y++)
{
for (x = 0; x < 259; x++)
{
if (gray.at<uchar>(y, x) < max)
max = gray.at<uchar>(y, x);
if (gray.at<uchar>(y, x) > min)
min = gray.at<uchar>(y, x);
}
}
for (y = 0; y < 194; y++)
{
for (x = 0; x < 259; x++)
{
equalized.at<uchar>(y, x) = (gray.at<uchar>(y, x) - max) * 255 / (min - max);
}
}
imshow("Imagem Cinza", gray);
Mat hist_gray = histograma(gray);
imshow("name1", hist_gray);
imshow("Imagem Equalizada", equalized);
Mat hist_equalized = histograma(equalized);
imshow("name2", hist_equalized);
waitKey(0);
return 0;
}
|
Markdown
|
UTF-8
| 2,015
| 2.609375
| 3
|
[] |
no_license
|
# Currency-Converter-TRY-to-USD-EUR-GBP-CNY
### QT Project - Currency Converter TRY to USD/EUR/GBP/CNY
## Project Details
That's a project I've created as a university homework for the course, CMPE 230 - Systems Programming on Dec 20th, 2017.
Basically, that's a QT project that fetches data from fixer.io and shows converts the given TRY amount to USD/EUR/GBP/CNY.
However, since the fixer.io api has changed and the free plan only supports base as EUR, so I updated the project to convert from EUR to USD/TRY/GBP/CNY instead.
What the project is about can be found via [Project.pdf](https://github.com/corupta/Currency-Converter-EUR-to-USD-TRY-GBP-CNY/blob/master/Project.pdf)
That's a qt project, and I did not used qt designer.
QT4+ is supported. (Lower versions may also support but are not tested.)
## Compile
I've always compiled on terminal/command prompt as I explained below.
To be practical, I created the below script line to compile and run the project automatically.
(I am usung Ubuntu, it is similar to compile in Windows but be careful not to forget to add the line "QT += network" in the bottom of the generated Currency-Converter.pro)
qmake -project && echo "QT += network" >> Currency-Converter.pro && qmake Currency-Converter.pro && make && ./Currency-Converter
Add a '&' in the end to open the program in the background (not connected to terminal)
the line "QT += network" had to be appended on the .pro file, in order to use QNetworkAccessManager (to connect to and fetch data from api.fixer.io)
Program can be rebuild with that command, if interested.
The required files for that purpose are below:
main.cpp
currencyConverter.h and currencyConverter.cpp
currencyButton.h and currencyButton.cpp
rateReader.h and rateReader.cpp
## Run
Just double click on the Currency-Converter to run.
For more details about how to use the project, check out [Report-Documentation.pdf](https://github.com/corupta/Currency-Converter-EUR-to-USD-TRY-GBP-CNY/blob/master/Report-Documentation.pdf)
|
C#
|
UTF-8
| 350
| 2.953125
| 3
|
[] |
no_license
|
public bool ChangeColor {get; set;}
private double _Bid;
public double Bid
{
get { return _Bid; }
set
{
If (_Bid < value)//, change fore color
ChangeColor = True;
_Bid = value;
DisplayCurrentPrice = String.Format("{0} / {1}", value, Ask);
}
}
|
C++
|
UTF-8
| 2,433
| 2.8125
| 3
|
[] |
no_license
|
//
// main.cpp
// 107A-Dorm Water Supply
//
// Created by 양종열 on 2018. 4. 14..
// Copyright © 2018년 양종열. All rights reserved.
//
#include<iostream>
#include<vector>
using namespace std;
vector<vector<int>> vc(1001);
int visited[1001];
int map[1001][1001];
vector<int> startVc, endVc, diameterVc;
int n,p,minDia=1000000;
void dfs(int node, bool flag) {
if(!flag) {
for(int i=0; i<vc[node].size(); i++) {
if(visited[vc[node][i]]) continue;
else {
visited[vc[node][i]] = true;
dfs(vc[node][i], flag);
}
}
} else {
bool isEnd = true;
for(int i=0; i<vc[node].size(); i++) {
if(visited[vc[node][i]]) continue;
else {
isEnd = false;
visited[vc[node][i]] = true;
if(map[node][vc[node][i]] < minDia)
minDia = map[node][vc[node][i]];
dfs(vc[node][i], flag);
}
}
if (isEnd) endVc.push_back(node);
}
}
void clean() {
for(int i=1; i<=n; i++) {
visited[i] = false;
}
}
int main(){
ios::sync_with_stdio(false);
cin>>n>>p;
if(p==0) {
cout<<0<<"\n";
return 0;
}
int house1, house2, diameter;
for(int i=0; i<p; i++) {
cin>>house1>>house2>>diameter;
vc[house1].push_back(house2);
// vc[house2].push_back(house1);
map[house1][house2] = diameter;
map[house2][house1] = diameter;
}
for(int i=1; i<=n; i++) {
dfs(i, false); // search start or end point
}
for(int i=1; i<=n; i++) {
if(visited[i] == false)
startVc.push_back(i);
}
clean();
for(int i=0; i<startVc.size(); i++) {
dfs(startVc[i], true); // find start to end node & min diameter
//cout<<startVc[i]<<" "<<t<<" "<<minDia<<"\n";
diameterVc.push_back(minDia);
minDia=1000000;
}
int count = 0;
for(int i=0; i<startVc.size(); i++) {
if(startVc[i] == endVc[i] || diameterVc[i] == 1000000) continue;
count++;
}
cout<<count<<"\n";
for(int i=0; i<startVc.size(); i++) {
if(startVc[i] == endVc[i] || diameterVc[i] == 1000000) continue;
cout<<startVc[i]<<" "<<endVc[i]<<" "<<diameterVc[i]<<"\n";
}
return 0;
}
|
JavaScript
|
UTF-8
| 2,075
| 2.828125
| 3
|
[
"MIT"
] |
permissive
|
function isElementInViewport (el) {
//special bonus for those using jQuery
if (typeof jQuery === "function" && el instanceof jQuery) {
el = el[0];
}
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
function onVisibilityChange(el, callback) {
var old_visible;
return function () {
var visible = isElementInViewport(el);
if (visible != old_visible) {
old_visible = visible;
if (typeof callback == 'function') {
callback();
}
}
}
}
var animationTime = 3000;
var s0 = Snap('#animated0');
var progress0 = s0.select('#progress0');
var handler0 = onVisibilityChange($('#progress0'), function() {
progress0.attr({strokeDasharray: '0, 251.2'});
Snap.animate(0,135, function( value ) {
progress0.attr({ 'stroke-dasharray':value+',251.2'});
}, animationTime);
});
var s1 = Snap('#animated1');
var progress1 = s1.select('#progress1');
var handler1 = onVisibilityChange($('#progress1'), function() {
progress1.attr({strokeDasharray: '0, 251.2'});
Snap.animate(0,62, function( value ) {
progress1.attr({ 'stroke-dasharray':value+',251.2'});
}, animationTime);
});
var s2 = Snap('#animated2');
var progress2 = s2.select('#progress2');
var handler2 = onVisibilityChange($('#progress2'), function() {
progress2.attr({strokeDasharray: '0, 251.2'});
Snap.animate(0,70, function( value ) {
progress2.attr({ 'stroke-dasharray':value+',251.2'});
}, animationTime);
});
//jQuery
$(window).on('DOMContentLoaded load resize scroll', handler0);
$(window).on('DOMContentLoaded load resize scroll', handler1);
$(window).on('DOMContentLoaded load resize scroll', handler2);
|
Markdown
|
UTF-8
| 1,906
| 2.953125
| 3
|
[] |
no_license
|
- I try to keep an even keel.
- I’m a polyatheist – there are many gods I don’t believe in.
- I’m over it. You strive to win a Super Bowl and you do everything you can to get there. But being in the Hall of Fame, you never play for that honor. It’s incredible.
- I remember Terry being exhausted from his latest Super Bowl win and all the things that go with it.
- One of the great things personally coming to Hawai’i is my friendship of Jim Nicholson.
- Nothing good happens when you jump in the air.
- People ask me who he reminds me of. The way he’s playing, I’d say he doesn’t remind me of anybody. I’ve never seen anybody – running back, quarterback, wide receiver – make the plays that Vince Young made today.
- When you work with a legend as I do, it’s wonderful. There’s so many things I’ve learned working with Keith. He’s so patient, not only with me, but with everyone in our crew and with the audience and with the game. He has a style that is so easy and will never be copied.
- First off there is no question that LaDainian is a first-ballot Hall of Famer. His contributions off the field to the community of San Diego are as important as what he did on the field. What he did on the field was monumental.
- So much of what you do physically happens because you’ve thought about it and mentally prepared for it.
- Now that I’m retired, I want to say that all defensive linemen are sissies.
- I worked the Giants win over the Texans earlier this season. The Giants ran the heck out of the ball. Eli Manning rolled out away from Watt just about every time and changed the release point on his passes. The Cowboys have a road map.
- I always loved going to Hawai’i; it was very, very special.
- First of all, it was such an honor to be chosen. You had to be voted in by players and coaches that time. But having it in Hawai’i was a brilliant idea.
14 quotes
|
Markdown
|
UTF-8
| 932
| 3.375
| 3
|
[] |
no_license
|
## MongoDB相关概念与基本操作
#### 三个概念
- 数据库(database)
- 数据库是一个仓库,在仓库中可以存放集合。
- 集合(collection)
- 集合类似于数组,在集合中可以存放文档。
- 文档(document)
- 文档数据库中的最小单位,我们存储和操作的内容都是文档。
在MongoDB中用户只需要操作`document`即可,数据库与集合则由系统自动生成。
基本指令:
- show dbs 显示所有数据库
- show collections 显示数据库中所有集合
- use [数据库名] 进入到指定数据库中
- db 显示目前所在的数据库名
基本插入文档语句:
db.[集合名,可以随便取,按照规范即可].insert({[json格式的数据]})
基本查询集合中所有数据的语句:
db.[集合名,指定已经存在的集合名].find()
**再次强调:集合不需要我们创建,系统会自动通过语句创建集合。**
|
JavaScript
|
UTF-8
| 1,312
| 2.609375
| 3
|
[] |
no_license
|
function fetch_search_word(){
var keyword = $("#SearchInput").val();
$.ajax({
url:
"http://<?=$_SERVER['HTTP_HOST']?>/wp-content/dbdbdb/dictionary/byKeyword.php",
type: "POST",
data: {
keyword:keyword,
},
success: function(data) {
$("#item_data").html(data);
}
});
}
function fetch_search_chosung(chosung){
var chosung = chosung;
$.ajax({
url:
"http://<?=$_SERVER['HTTP_HOST']?>/wp-content/dbdbdb/dictionary/byChosung.php",
type: "POST",
data: {
chosung:chosung,
},
success: function(data) {
$("#item_data").html(data);
}
});
}
function newWord(){
var north = $("#north").val();
var south = $("#south").val();
var meaning = $("#meaning").val();
var chosung = $("#chosung").val();
$.ajax({
url:
"http://<?=$_SERVER['HTTP_HOST']?>/wp-content/dbdbdb/dictionary/newWord.php",
type: "POST",
data: {
north:north,
south:south,
meaning:meaning,
chosung:chosung,
},
success: function(data) {
console.log(data);
alert('New word added.');
}
});
}
|
Markdown
|
UTF-8
| 1,064
| 3.3125
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
# github-labels
Get repositories' labels for specific github user or organization.
Scripts require github token to run. To generate it, please follow steps
described [here](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/#creating-a-token).
## Usage
Repository contains three scripts:
### `bin/fetch.php <username> <github-token> <output-file>`
Get labels for all repositories (public or available for authenticated token)
and generate file with the following format:
```php
<?php
return [
'repository-name' => [
'label-text' => 'label-color',
'another-label' => 'color',
...
],
...
];
```
### `bin/generate.php <username> <data-file> <output-file>`
Generate html table from file data (generated in script `bin/fetch.php`).
File is generated using template
[`template/layout.phtml`](template/layout.phtml).
### `bin/run.php <username> <github-token>`
The script uses two previous script: `bin/fetch.php` and `bin/generate.php`
and generate output html file in `docs/` directory.
|
Markdown
|
UTF-8
| 4,102
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
---
date: 2020-12-31 18:25:42
layout: post
title: "National Parks Mania"
subtitle: "ft. Death Valley, Sequoia, and Kings Canyon"
description:
image: ../assets/img/travel/feature_img/sand_dunes.jpg
optimized_image: ../assets/img/travel/feature_img/opt_sand_dunes.jpg
category: travel
tags:
- travel
- 1hikeaweek
author: mario
paginate: true
---
Hello! I am excited to update this post for my trip to 3 national parks ([Death Valley](https://www.nps.gov/deva/index.htm), [Sequoia](https://www.nps.gov/seki/index.htm), and [Kings Canyon](https://www.nps.gov/seki/index.htm)).
The first destination is sand dunes at Death Valley national park. As you can see, I am exposed to many canyons from all of the hikes but sand dunes feel so different.
Believe it or not, the sand is so soft that I was walking barefoot and sometimes with a sandal.
We arrived there at sunrise which is a prime time to see the sunrise from beneath the sand dunes.
<img src="../assets/img/travel/death_valley_sequoia_kings/sand_dunes_1.jpg" style="height: 400px;" alt="sand dunes 1"/>
<img src="../assets/img/travel/death_valley_sequoia_kings/sand_dunes_2.jpg" style="height: 400px;" alt="sand dunes 2"/>
From there, we move on to the next viewpoint at Death Valley which is Zabriskie Point. The landscape is so unique and it is composed of sediments from Furnace Creek Lake which dried up 5 million years ago.
<img src="../assets/img/travel/death_valley_sequoia_kings/zabriskie_point.jpg" style="height: 400px;" alt="sand dunes 2"/>
Next up, we visited Badwater Basin and is the lowest point in North America and the US with a depth of 282 ft below sea level.
<img src="../assets/img/travel/death_valley_sequoia_kings/bad_water_basin_sign.jpg" style="height: 400px;" alt="bad water basin sign"/>
<img src="../assets/img/travel/death_valley_sequoia_kings/bad_water_basin_top.jpg" style="height: 400px;" alt="bad water basin top view"/>
The pathway filled with salt. Did I taste the salt? Yes, I did. Does it taste like salt? Absolutely. Is it edible? Who knows - I am still alive :D.
Next up, we are hiking [Mist Falls](https://www.alltrails.com/trail/us/california/mist-falls) at Kings Canyon National Park. The length of the hike is 8.7 miles out and back with 879 ft elevation gain.
At the end of the hike, we were greeted with the cool canyon views and water to play with.
<table><tr>
<td> <img src="../assets/img/travel/death_valley_sequoia_kings/mist_falls_1.jpg" alt="canyon view" style="width: 250px;"/> </td>
<td> <img src="../assets/img/travel/death_valley_sequoia_kings/mist_falls_2.jpg" alt="summit canyon view" style="width: 250px;"/> </td>
<td> <img src="../assets/img/travel/death_valley_sequoia_kings/mist_falls_3.jpg" alt="water" style="width: 250px;"/> </td>
</tr></table>
Finally, onto the last national park (Sequoia). I have been to Kings Canyon and Sequoia national park last year but I got to explore Kings Canyon more this time around.
As usual, the attraction at Sequoia is [Moro Rock](https://www.alltrails.com/trail/us/california/moro-rock-trail) and [the General Sherman tree](https://www.nps.gov/seki/learn/nature/sherman.htm).
<img src="../assets/img/travel/death_valley_sequoia_kings/moro_rock.jpg" style="height: 400px;" alt="moro rock"/>
<img src="../assets/img/travel/death_valley_sequoia_kings/sequioa_trees.jpg" style="height: 400px;" alt="tree"/>
At this point, we are dead tired and on the way home. We stopped by [Three Rivers Yogurt](https://www.yelp.com/biz/three-rivers-yogurt-three-rivers) for frozen yogurt. It wasn't expensive and they give you a lot. I like their decorations at the store.
<table><tr>
<td> <img src="../assets/img/travel/death_valley_sequoia_kings/yogurt_1.jpg" alt="yogurt 1" style="width: 250px;"/> </td>
<td> <img src="../assets/img/travel/death_valley_sequoia_kings/yogurt_2.jpg" alt="yogurt 2" style="width: 250px;"/> </td>
<td> <img src="../assets/img/travel/death_valley_sequoia_kings/yogurt_3.jpg" alt="yogurt 3" style="width: 250px;"/> </td>
</tr></table>
With that, we conclude the adventure. Until next time!
|
Python
|
UTF-8
| 308
| 3.140625
| 3
|
[] |
no_license
|
# CSV must be in of the form [Key,Value]
# E.g.:
#
# img_1.jpg,0
# img_2.jpg,1
# img_3.jpg,0
# img_4.jpg,0
# ...
import csv
def csvToDict(csvIn):
with open(csvIn, mode='r') as infile:
reader = csv.reader(infile)
mydict = dict((rows[0],rows[1]) for rows in reader)
return mydict
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.