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 |
|---|---|---|---|---|---|---|---|
TypeScript | UTF-8 | 251 | 2.640625 | 3 | [] | no_license | import {AbstractControl} from "@angular/forms";
export const WordsValidator = (word:string, count:number)=>(control:AbstractControl)=>{
return control.value.toLowerCase().includes(word.toLowerCase()) ? null:{noWords: `Too few ${word} included!`}
}
|
Python | UTF-8 | 406 | 3.515625 | 4 | [
"MIT"
] | permissive | class parent:
counter=10
hit=15
def __init__(self):
print("Parent class initialized.")
def SetCounter(self, num):
self.counter= num
class child(parent): # child is the child class of Parent
def __init__(self):
print("Child class being initialized.")
def SetHit(self, num2):
self.hit=num2
c= child()
print(c.counter)
c.SetCounter(20)
print(c.counter)
print(c.hit)
c.SetHit(30)
print(c.hit)
|
Go | UTF-8 | 2,338 | 2.546875 | 3 | [] | no_license | package redis
import (
"errors"
redisv7 "github.com/go-redis/redis/v7"
"github.com/sirupsen/logrus"
"github.com/tmsi-io/go-sardine/logger"
"net/url"
"strconv"
"strings"
"time"
)
func (single *Single) Conn(_url string) error {
single.logger = logger.GetLogger().WithFields(logrus.Fields{
"Config": _url,
})
if pUrl, err := url.Parse(_url); err != nil {
return err
} else {
if args, err := url.ParseQuery(pUrl.RawQuery); err == nil { // 解析url对象
if maxRetry, ok := args[ConfigMaxRetries]; ok {
mR, _ := strconv.Atoi(maxRetry[0])
single.maxRetries = mR
}
if PoolSize, ok := args[ConfigPoolSize]; ok {
pS, _ := strconv.Atoi(PoolSize[0])
single.poolSize = pS
}
}
if len(pUrl.Host) == 3 {
return errors.New(ErrorConfigHost)
} else {
single.addr = pUrl.Host
if db := strings.Split(pUrl.Path, "/"); len(db) < 2 {
return errors.New(ErrorConfigDB)
} else {
single.db, _ = strconv.Atoi(db[1])
}
single.password, _ = pUrl.User.Password()
}
}
if err := single.InitConn(); err != nil {
return err
} else {
single.connOk = true
go single.goKeepAlive() // 发送心跳保活
return nil
}
}
func (single *Single) InitConn() error {
client := redisv7.NewClient(&redisv7.Options{
Addr: single.addr, //
Password: single.password, // no password set
DB: single.db, // use default DB
MaxRetries: single.maxRetries, //
PoolSize: single.poolSize, //
DialTimeout: 10 * time.Second,
PoolTimeout: 1 * time.Second,
IdleTimeout: 20 * time.Second,
})
single.client = client
single.client.AddHook(single)
if _, err := single.client.Ping().Result(); err != nil {
single.logger.Error(err)
return err
} else {
single.logger.Info("Conn To Redis OK.")
return nil
}
}
func (single *Single) StatusOK() bool {
return single.connOk
}
func (single *Single) goKeepAlive() {
for {
if _, err := single.client.Ping().Result(); err != nil {
single.connOk = false
single.logger.Error("Connection Loss, ReBuilding... ")
if err2 := single.InitConn(); err2 != nil {
single.logger.Error("Connection ReBuilding Failed: ", err2)
} else {
single.connOk = true
single.logger.Info("Connection OK, ReBuilding ok ")
}
time.Sleep(3 * time.Second)
}
time.Sleep(time.Second * 10)
}
}
|
Java | UTF-8 | 202 | 2.046875 | 2 | [] | no_license | package com.imc.contructure.simpledemo;
/**
* @author luoly
* @date 2018/12/4 14:50
* @description
*/
public class Product1 implements Product{
public String get() {
return p;
}
}
|
Java | UTF-8 | 5,791 | 1.992188 | 2 | [] | no_license | package com.qingclass.squirrel.cms.controller;
import com.qingclass.squirrel.cms.Service.WxService;
import com.qingclass.squirrel.cms.entity.cms.ConversionPush;
import com.qingclass.squirrel.cms.entity.wechat.WxCustom;
import com.qingclass.squirrel.cms.mapper.cms.ConversionPushMapper;
import com.qingclass.squirrel.cms.mapper.cms.SquirrelWxCustomMapper;
import com.qingclass.squirrel.cms.utils.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping(value = "/wx-conversion-push")
public class WxConversionPushController {
@Autowired
ConversionPushMapper conversionPushMapper;
@Autowired
SquirrelWxCustomMapper squirrelWxCustomMapper;
@Autowired
WxService wxService;
private final String CUSTOM_TYPE = "conversion-push";
@ResponseBody
@RequestMapping(value = "list", method = RequestMethod.POST)
public Map<String,Object> list(){
List<ConversionPush> conversionPushes = conversionPushMapper.selectAll();
return Tools.s(conversionPushes);
}
@ResponseBody
@RequestMapping(value = "info", method = RequestMethod.POST)
public Map<String,Object> info(@RequestParam(value = "id",required = false)Integer id){
ConversionPush conversionPush = conversionPushMapper.selectByPrimaryKey(id);
List<WxCustom> wxCustoms = squirrelWxCustomMapper.selectByPrimaryKey(conversionPush.getCustomId());
conversionPush.setCustomContent(wxCustoms.get(0).getContent());
return Tools.s(conversionPush);
}
@ResponseBody
@RequestMapping(value = "insert", method = RequestMethod.POST)
public Map<String,Object> insert(@RequestParam(value = "levelId",required = false)Integer levelId, @RequestParam(value = "pushTime",required = false)String pushTime,
@RequestParam(value = "scope",required = false)Integer scope,
@RequestParam(value = "customContent",required = false)String customContent,@RequestParam(value = "isOpen",required = false)Integer isOpen){
WxCustom wxCustom = new WxCustom();
wxCustom.setType(CUSTOM_TYPE);
wxCustom.setIsOpen(1);
wxCustom.setContent(customContent);
squirrelWxCustomMapper.insert(wxCustom);
ConversionPush conversionPush = new ConversionPush();
conversionPush.setLevelId(levelId);
conversionPush.setCustomId(wxCustom.getId());
conversionPush.setIsOpen(isOpen);
conversionPush.setScope(scope);
conversionPush.setPushTime(pushTime);
conversionPushMapper.insert(conversionPush);
return Tools.s();
}
@ResponseBody
@RequestMapping(value = "edit", method = RequestMethod.POST)
public Map<String,Object> edit(@RequestParam(value = "id",required = false)Integer id,
@RequestParam(value = "customId",required = false)Integer customId,
@RequestParam(value = "levelId",required = false)Integer levelId,
@RequestParam(value = "scope",required = false)Integer scope,
@RequestParam(value = "pushTime",required = false)String pushTime,
@RequestParam(value = "customContent",required = false)String customContent,
@RequestParam(value = "isOpen",required = false)Integer isOpen){
WxCustom wxCustom = new WxCustom();
wxCustom.setId(customId);
wxCustom.setContent(customContent);
squirrelWxCustomMapper.updateByPrimaryKey(wxCustom);
ConversionPush conversionPush = new ConversionPush();
conversionPush.setId(id);
if(scope == 1){
conversionPush.setLevelId(null);
}else{
conversionPush.setLevelId(levelId);
}
conversionPush.setCustomId(customId);
conversionPush.setIsOpen(isOpen);
conversionPush.setScope(scope);
conversionPush.setPushTime(pushTime);
conversionPushMapper.update(conversionPush);
return Tools.s();
}
@ResponseBody
@RequestMapping(value = "delete", method = RequestMethod.POST)
public Map<String,Object> delete(@RequestParam(value = "id",required = false)Integer id){
conversionPushMapper.delete(id);
return Tools.s();
}
@ResponseBody
@RequestMapping(value = "edit-status", method = RequestMethod.POST)
public Map<String,Object> editStatus(@RequestParam(value = "id",required = false)Integer id,@RequestParam(value = "isOpen",required = false)Integer isOpen){
ConversionPush conversionPush = new ConversionPush();
conversionPush.setId(id);
conversionPush.setIsOpen(isOpen);
conversionPushMapper.updateStatus(conversionPush);
return Tools.s();
}
@ResponseBody
@RequestMapping(value = "/preview-custom", method = RequestMethod.POST)
public Map<String,Object> previewCustom(@RequestParam(value = "openId",required = false)String openId,@RequestParam(value = "content",required = false)String content){
System.out.println(content);
Map<String,Object> text = new HashMap<>();
text.put("content",content);
Map<String,Object> map = new HashMap<>();
map.put("touser",openId);
map.put("msgtype","text");
map.put("text",text);
String loggerInfo = "send custom successful.";
String loggerErr = "send custom failed.";
wxService.sendToWx(map,wxService.SEND_CUSTOM+wxService.getAccessToken(),loggerInfo,loggerErr);
return Tools.s();
}
}
|
SQL | UTF-8 | 2,282 | 3.453125 | 3 | [] | no_license | CREATE TABLE IF NOT EXISTS sequenceTypes (
sequenceId NUMBER PRIMARY KEY,
sequenceTypeName TEXT,
UNIQUE (sequenceTypeName)
);
INSERT OR IGNORE INTO sequenceTypes (sequenceId, sequenceTypeName) VALUES (1, "DURATION");
INSERT OR IGNORE INTO sequenceTypes (sequenceId, sequenceTypeName) VALUES (2, "TIME");
CREATE TABLE IF NOT EXISTS sequences (
uid TEXT PRIMARY KEY,
dateCreated TEXT,
sequenceType NUMBER,
defaultState NUMBER,
FOREIGN KEY(sequenceType) REFERENCES sequenceTypes(sequenceId)
);
CREATE TABLE IF NOT EXISTS gpioPins (
pinNumber NUMBER PRIMARY KEY,
sequenceUid TEXT,
FOREIGN KEY(sequenceUid) REFERENCES sequences(uid)
);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (14, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (15, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (18, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (23, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (24, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (25, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (8, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (7, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (2, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (3, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (4, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (17, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (27, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (22, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (10, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (9, null);
INSERT OR IGNORE INTO gpioPins (pinNumber, sequenceUid) VALUES (11, null);
CREATE TABLE IF NOT EXISTS sequenceItems (
uid TEXT PRIMARY KEY,
dateCreated TEXT,
sequenceUid TEXT,
durationSeconds NUMBER,
ordinal NUMBER,
startTime TEXT,
endTime TEXT,
state TEXT,
UNIQUE (sequenceUid, ordinal),
FOREIGN KEY(sequenceUid) REFERENCES sequences(uid),
FOREIGN KEY(sequenceType) REFERENCES sequenceTypes(sequenceId)
);
|
Python | UTF-8 | 1,824 | 2.6875 | 3 | [] | no_license | import unit_convert_input as uci
import unit_convert_output as uco
import math
def eqn3v():
global v
uci.initial_velocity()
print("\n===============================================================\n")
uci.acceleration()
print("\n===============================================================\n")
uci.distance()
print("\n===============================================================\n")
v = math.sqrt((2 * uci.a * uci.s) + uci.u * uci.u)
uco.eqn3_final_velocity()
def eqn3u():
global u
uci.final_velocity()
print("\n===============================================================\n")
uci.acceleration()
print("\n===============================================================\n")
uci.distance()
print("\n===============================================================\n")
u = math.sqrt((uci.v * uci.v) - (2 * uci.a * uci.s))
uco.eqn3_initial_velocity()
def eqn3a():
global a
uci.initial_velocity()
print("\n===============================================================\n")
uci.final_velocity()
print("\n===============================================================\n")
uci.distance()
print("\n===============================================================\n")
a = ((uci.u * uci.u) - (uci.v * uci.v))/(2 * uci.s)
uco.eqn3_acceleration()
def eqn3s():
global s
uci.initial_velocity()
print("\n===============================================================\n")
uci.final_velocity()
print("\n===============================================================\n")
uci.acceleration()
print("\n===============================================================\n")
s = ((uci.u * uci.u) - (uci.v * uci.v))/(2 * uci.a)
uco.eqn3_distance() |
C++ | UTF-8 | 1,685 | 3.53125 | 4 | [] | no_license | // remove nth node from the end of the linked list
// naive approach: to traverse the entire linked list initialising c = 1 at head and continuing to do so until the last node, then take the last N-n (the nth node to be deleted) and then traverse the list till that node and then put node->next = node->next->next;
/*
The second optimal approach is to create a dummy node and make sure that it points to the head of the linked list. Then we take two pointers slow s and fast f. We take the fast pointer till the nth node and stop. Then we take both s and f and move by one step each time until f->next == NULL. If that's the case, we take s->next = s->next->next and then delete(dummynode)
Edge case if the node is at the head of the list, then the f pointer iterates through to the last node but then s pointer can't go ahead at all. Then we take the head->next = head->next->next; and then return the list.
*/
/*
* Definition of a singly linked list
* struct ListNode {
int val;
ListNode *next;
ListNode(int val) : { this.val = val; }
ListNode(int val, ListNode next): this.val = val; this.next = next; }
};
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode *removeNthNodeFromEnd(ListNode *head, int n) {
ListNode *start = new ListNode();
start->next = head;
ListNode *slow = start;
ListNode *fast = start;
for(int i = 1; i <= n; i++) {
fast = fast->next;
}
while(fast->next != NULL) {
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return start->next;
}
};
|
Java | UTF-8 | 2,778 | 3.03125 | 3 | [] | no_license | package ee.omis.item;
import ee.omis.World;
import ee.omis.WorldObject;
public class Item implements WorldObject {
private final String name;
private final double strength;
private int durability;
private int xCoord;
private int yCoord;
private final char symbol;
private final boolean isVisible;
private int level;
private ItemType itemType;
public Item(String name, double strength, int durability) {
this.name = name;
this.strength = strength;
this.durability = durability;
setRandomCoordinates();
this.symbol = 'I';
this.isVisible = true;
this.level = 0;
this.itemType = ItemType.SILVER;
}
public void setRandomCoordinates() {
this.xCoord = (int) (Math.random() * ( World.getWidth() - 1 ) + 1 );
this.yCoord = (int) (Math.random() * ( World.getHeight() - 1 ) + 1 );
}
public String getName() {
return name;
}
public double getStrength() {
return strength;
}
public int getDurability() {
return durability;
}
public void setDurability(int durability) {
this.durability = durability;
}
public int getxCoord() {
return xCoord;
}
public int getyCoord() {
return yCoord;
}
public char getSymbol() {
return symbol;
}
public boolean isVisible() {
return isVisible;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
if (this.level < 3) {
this.itemType = ItemType.SILVER;
} else if (this.level < 5) {
this.itemType = ItemType.GOLD;
} else if (this.level < 7) {
this.itemType = ItemType.PLATINUM;
} else {
this.itemType = ItemType.TITANIUM;
}
}
public double getStrengthFromItemType(double strength) {
switch (itemType) {
case SILVER:
strength *= 0.75;
break;
case GOLD:
strength *= 1;
break;
case PLATINUM:
strength *= 1.25;
break;
case TITANIUM:
strength *= 1.5;
break;
}
return strength;
}
@Override
public String toString() {
return "Item: " +
"name=" + name +
"strength=" + strength +
", durability=" + durability +
", xCoord=" + xCoord +
", yCoord=" + yCoord +
", symbol=" + symbol +
", isVisible=" + isVisible +
", level=" + level +
", itemType=" + itemType;
}
}
|
Java | UTF-8 | 2,426 | 3.25 | 3 | [] | no_license | package graph;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
class Tuple {
public final Object x;
public final Object y;
public Tuple(Object x, Object y) {
this.x = x;
this.y = y;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append("(" + x + ", " + y + ")");
return s.toString();
}
}
public class DFS {
private Map<Object, Object> parent;
private Map<Object, Integer> start_time;
private Map<Object, Integer> end_time;
private Map<Tuple, String> edges; // edge classification for DFS
private int time = 0;
private List<Object> order;
public DFS() {
parent = new LinkedHashMap<Object, Object>();
start_time = new HashMap<Object, Integer>();
end_time = new HashMap<Object, Integer>();
edges = new HashMap<Tuple, String>();
order = new ArrayList<Object>();
}
public String toString() {
StringBuilder s = new StringBuilder();
String NEWLINE = System.getProperty("line.separator");
s.append("Parent: " + parent + NEWLINE);
s.append("Order: " + order + NEWLINE);
s.append("Edges: " + edges + NEWLINE);
return s.toString();
}
public static DFS dfs(Graph g) {
DFS results = new DFS();
for (Object v: g.itervertices()) {
if(! results.parent.containsKey(v)) {
dfs_visit(g, v, results, null);
}
}
return results;
}
private static void dfs_visit(Graph g, Object v, DFS results, Object parent) {
results.parent.put(v, parent);
results.time++;
results.start_time.put(v, results.time);
if (parent != null) {
Tuple t = new Tuple(parent, v);
results.edges.put(t, "tree");
}
for (Object a: g.adj(v)) {
Tuple t = new Tuple(v, a);
if (! results.parent.containsKey(a)) { // not visited already
dfs_visit(g, a, results, v);
} else if(! results.end_time.containsKey(a)) {
results.edges.put(t, "back");
}
else if(results.start_time.get(v) < results.start_time.get(a)) {
results.edges.put(t, "forward");
}
else {
results.edges.put(t, "cross");
}
}
results.time++;
results.end_time.put(v, results.time);
results.order.add(v);
}
public static List<Object> topological_sort(Graph g) {
DFS d = DFS.dfs(g);
Collections.reverse(d.order);
return d.order;
}
public static void main(String[] args) {
System.out.println(DFS.dfs(Graph.getDfsExampleGraph()));
}
}
|
JavaScript | UTF-8 | 2,612 | 2.953125 | 3 | [] | no_license | import React, {useState, useEffect} from 'react'
import axios from 'axios'
const Details = ({ country }) => {
return (
<div>
<h2>{country.name}</h2>
<p>capital {country.capital}</p>
<p>population {country.population}</p>
<h3>Spoken languages</h3>
<ul>
{
country.languages.map((language) => <li key={language.name}>{language.name}</li>)
}
</ul>
<img src={country.flag} width="150px" alt="flag"/>
<h3>Weather in {country.capital}</h3>
<Weather city={country.capital} />
</div>
)
}
const Weather = ({ city }) => {
const [weatherData, setWeatherData] = useState(false)
useEffect(() => {
axios
.get(`http://api.weatherstack.com/current?access_key=${process.env.REACT_APP_API_KEY}&query=${city}`)
.then(response => {
setWeatherData(response.data)
})
},[city])
if (weatherData) {
return (
<div>
<p> <strong>temperature:</strong> {weatherData.current.temperature} celsius</p>
<img src={weatherData.current.weather_icons[0]} alt='weather icon' />
<p> <strong>wind:</strong> {weatherData.current.wind_speed} mph direction {weatherData.current.wind_dir} </p>
</div>
)
}
return (<p><strong>temperature:</strong></p>)
}
const Filter = ( {newFilter, handleNewFilter} ) =>
<div>
find countries <input value={newFilter} onChange={handleNewFilter} />
</div>
const ShowCountries = ({ countriesToShow }) =>
<div>
{
countriesToShow.map((country) =>
<p key={country.name}> {country.name} </p>
)
}
</div>
const HandleCountries = ({ countriesToShow }) => {
if (countriesToShow.length > 10) {
return (<p>Too many matches, specify another filter</p>)
} else if (countriesToShow.length === 1) {
return (
<Details country={countriesToShow[0]} />
)
}
return (
<>
<ShowCountries countriesToShow={countriesToShow} />
</>
)
}
const App = (props) => {
const [countries, setCountries] = useState([])
const [newFilter, setNewFilter] = useState('')
useEffect(() => {
console.log('effect')
axios
.get('https://restcountries.eu/rest/v2/all')
.then(response => {
console.log('promise fulfilled')
setCountries(response.data)
})
}, [])
console.log('fetched', countries.length, 'countries')
const handleNewFilter = (event) => setNewFilter(event.target.value)
const countriesToShow = newFilter
? countries.filter(country => country.name.match(new RegExp(newFilter, "i")))
: countries
return (
<div>
<Filter newFilter={newFilter} handleNewFilter={handleNewFilter}/>
<HandleCountries countriesToShow={countriesToShow} />
</div>
)
}
export default App
|
Python | UTF-8 | 734 | 2.75 | 3 | [] | no_license | #Problem ID: 3191
#Submit Time: 2013-04-24 10:15:49
#Run Time: 10
#Run Memory: 320
#ZOJ User: calvinxiao
import sys
def getline():
return sys.stdin.readline()
def getint():
return input()
def getints():
return map(int, raw_input().split())
def getlist():
return raw_input().split()
#sys.stdin = open("0.in", "r")
while 1:
n = getint()
if n == -1:
break
now = 3
while n > 29:
n -= 30
now -= 1
if now < 0:
now += 12
if n == 0:
print "Exactly %d o'clock" % now
else:
before = now - 1
if before < 0:
before += 12
print "Between %d o'clock and %d o'clock" % (before, now)
|
Python | UTF-8 | 621 | 3.34375 | 3 | [] | no_license | class Notebook():
# Class attributes here
def __init__(self, entries=[]):
"""
Document constructor method
"""
# journal_entries is public because we can use helper functions to string together a list of all our
# notes, tasks, and priority items, then write it to a file, or display it via our Notebook database, etc
self.journal_entries = entries
def display_notes(self):
"""
Method to output all the current note, task and project contents of the notebook
"""
for entry in self.journal_entries:
entry.print_note() |
Python | UTF-8 | 3,418 | 3.65625 | 4 | [] | no_license | import pandas as pd
import re
def remove_percents(df, col):
column = list(df[col])
new_col = []
for element in column:
if type(element)== float:
new_col.append(element)
continue
new_col.append(float(element.split("%")[0]))
new_series = pd.Series(new_col)
df[col] = new_series
return df
def fill_zero_iron(df):
df['Iron (% DV)'] = df['Iron (% DV)'].fillna(0)
return df
def fix_caffeine(df):
coffee = list(df["Caffeine (mg)"])
add = 0
count = 0
for element in coffee:
if type(element) == float : continue
if element == 'Varies' or element == 'varies': continue
add = int(element)+add
count = count+1
average = add/count
for i in range(len(coffee)):
if type(coffee[i]) == float : coffee[i] = average
if coffee[i] == 'Varies' or coffee[i] == 'varies': coffee[i] = average
coff_series = pd.Series(coffee)
df["Caffeine (mg)"] = coff_series
return df
def standardize_names(df):
col_names = list(df.columns)
for i in range (len(col_names)):
col_names[i] = col_names[i].lower()
col_names[i] = col_names[i].split("(")[0]
df.columns = pd.Series(col_names)
return df
def fix_strings(df, col):
string_list = list(df[col])
new_col = []
for string in string_list:
string = string.lower()
for char in string:
if (re.search("[a-z ]", char)) : continue
string = string.replace(char, "")
new_col.append(string)
df[col] = pd.Series(new_col)
return df
def main():
# first, read in the raw data
df = pd.read_csv('../data/starbucks.csv')
# the columns below represent percent daily value and are stored as strings with a percent sign, e.g. '0%'
# complete the remove_percents function to remove the percent symbol and convert the columns to a numeric type
pct_DV = ['Vitamin A (% DV)', 'Vitamin C (% DV)', 'Calcium (% DV)', 'Iron (% DV)']
for col in pct_DV:
df = remove_percents(df, col)
# the column 'Iron (% DV)' has missing values when the drink has no iron
# complete the fill_zero_iron function to fix this
df = fill_zero_iron(df)
# the column 'Caffeine (mg)' has some missing values and some 'varies' values
# complete the fix_caffeine function to deal with these values
# note: you may choose to fill in the values with the mean/median, or drop those values, etc.
df = fix_caffeine(df)
# the columns below are string columns... starbucks being starbucks there are some fancy characters and symbols in their names
# complete the fix_strings function to convert these strings to lowercase and remove non-alphabet characters
names = ['Beverage_category', 'Beverage']
for col in names:
df = fix_strings(df, col)
# the column names in this data are clear but inconsistent
# complete the standardize_names function to convert all column names to lower case and remove the units (in parentheses)
df = standardize_names(df)
# now that the data is all clean, save your output to the `data` folder as 'starbucks_clean.csv'
# you will use this file in checkpoint 2
df.to_csv(r'../data/starbucks_clean.csv',index = False)
if __name__ == "__main__":
main() |
Java | UTF-8 | 629 | 2.0625 | 2 | [] | no_license | package com.toby.provider;
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@ConfigurationProperties(prefix = "feichao.info")
/** 加载外部配置 注解*/
@Component
@Validated
/** 触发Bean校验 注解*/
@Data
/** 省略 setter 、getter 方法 注解*/
public class ApplicationProperties {
@NotBlank(message = "名字不能为空,请注意检查,参考值为:肥朝。")
private String name;
}
|
TypeScript | UTF-8 | 340 | 2.78125 | 3 | [] | no_license | import { IRandom } from '../interfaces/IRandom';
import { Injectable } from '@nestjs/common';
@Injectable()
export class RandomService implements IRandom {
public integer(start: number, end: number): number {
const random = Math.random();
const randomBetween = (random * end) + start
return Math.floor(randomBetween);
}
}
|
Markdown | UTF-8 | 1,205 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | # Drone
## Get Drones
### HTTP Request
`GET http://tango.avetics.com/api/v1/drones`
> JSON response:
```json
{
"data": [
{
"id": "3",
"type": "drones",
"attributes": {
"name": "Drone 101",
"status": "Ok",
"devise-sn": ""
}
},
{
"id": "5",
"type": "drones",
"attributes": {
"name": "Drone 102",
"status": "Ok",
"devise-sn": "123DEF"
}
}
]
}
```
## Set Drone Devise SN
### HTTP Request
`PUT http://tango.avetics.com/api/v1/drones/:id`
> JSON response:
```json
{
"data": {
"id": "3",
"type": "drones",
"attributes": {
"name": "Drone 101",
"status": "ok",
"devise-sn": "123ABC"
}
}
}
```
### URL Parameters
| Parameter | Description |
| --------- | -------------------------------- |
| ID | The ID of the drone to update |
### PUT Form Parameters
| Parameter | Description |
| --------- | -------------------------------- |
| drone[devise_sn] | The devise sn to set |
<aside class="info">
You can set drone devise sn only if it's empty.
</aside> |
Java | UTF-8 | 2,350 | 4.03125 | 4 | [] | no_license | package _4.dp;
import java.util.Map;
/**
* 72.最小的编辑距离 - hard
* https://leetcode-cn.com/problems/edit-distance/solution/bian-ji-ju-chi-by-leetcode/
* 编辑距离算法被数据科学家广泛应用,是用作机器翻译和语音识别评价标准的基本算法。
* 子问题:D[n][m] 表示输入单词长度为 n 和 m 的编辑距离
* D[i][j] 表示 word1 的前 i 个字母和 word2 的前 j 个字母之间的编辑距离
*我们获得 D[i-1][j],D[i][j-1] 和 D[i-1][j-1] 的值之后就可以计算出 D[i][j]
* 如果两个子串的最后一个字母相同,word1[i] = word2[i] 的情况下:
*
* D[i][j] = D[i - 1][j - 1]
*
* 否则,word1[i] != word2[i] 我们将考虑替换最后一个字符使得他们相同:
*
* D[i][j] = 1 + min(D[i - 1][j], D[i][j - 1], D[i - 1][j - 1])
*
* dp[i-1][j-1] 表示替换操作,dp[i-1][j] 表示删除操作,dp[i][j-1] 表示插入操作
*
*
* dp优化
* 1.dp[][]备忘录 自底向上
* 2.dp table
*/
public class minDistance {
public static int minDistance(String word1, String word2) {
//dp[i][j]表示源串A位置i到目标串B位置j处最低需要操作的次数
int[][] dp = new int[word1.length() + 1][word2.length() + 1];
for(int i = 0; i< word1.length() + 1; i++){
dp[i][0] = i;
}
for(int j = 0; j< word2.length() + 1; j++){
dp[0][j] = j;
}
for(int i = 1; i< word1.length() + 1; i++){
for(int j = 1; j< word2.length() + 1; j++){
if(word1.charAt(i - 1) == word2.charAt(j - 1)){ //相等时,向前移动,不花费距离
dp[i][j] = dp[i - 1][j - 1];
}else{
dp[i][j] = (Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1])) + 1;//不相等时,插入,删除,替换的最小距离
// 插入 dp[i][j-1] 直接在 s1[i] 插入一个和 s2[j] 一样的字符,那么 s2[j] 就被匹配了,前移 j,继续跟 i 对比
// 删除 dp[i-1][j] 直接把 s[i] 这个字符删掉,前移 i,继续跟 j 对比
// 替换 直接把 s1[i] 替换成 s2[j],这样它俩就匹配了,同时前移 i,j 继续对比
}
}
}
return dp[word1.length()][word2.length()];
}
}
|
Markdown | UTF-8 | 2,957 | 2.671875 | 3 | [
"LicenseRef-scancode-generic-cla",
"CC-BY-4.0"
] | permissive | ---
layout: developer
title: Using Dweet with Android
---
<div class="page-header">
<h1> Using Dweet with Android</h1>
</div>
<p>Open settings in Open XC android app</p>

<br>
<br>
<br>
<p>Click “Recording”</p>

<br>
<br>
<br>
<p>
Enable checkbox to “Send Data to Dweet.io”
Make a note of Thing-name
</p>

<br>
<br>
<br>
<p>
Open <a href="http://dweet.io/follow"> https://dweet.io/follow </a>
Enter thing-name from previous step to read dweets from the device
Above steps should display data on website to ensure the device is able to send dweets to dweets.io and proceed with freeboard dashboards
</p>



<br>
<br>
<br>
<p>Users can click on freeboard text to navigate to <a href="http://freeboard.io/"> http://freeboard.io/ </a> and sign up / login on the page</p>

<br>
<br>
<br>
<p>After finishing registration on freeboard.io, users can create custom dashboards:</p>

<br>
<br>
<br>
<p>
Enter any preferred name for the custom dashboard
<br>
You will navigate to the new dashboard
</p>

<br>
<br>
<br>
<p>
Click on ADD (below DATASOURCES) to select the source for the data
<br>
Select TYPE as Dweet.io
<br>
NAME “anything of your choice”
<br>
THING NAME : "enter thing name which is assigned in the first step"
<br>
KEY: "optional"
</p>

<br>
<br>
<br>
<p>After setting up DATASOURCE, users can click on ADD PANE to create an empty area on webpage as shown:</p>

<p>After setting up DATASOURCE for the current dashboard, users can proceed with a different widget view by clicking “ADD PANE”.</p>
<br>
<br>
<br>
<p>
Click on + icon to configure details about displaying data
<br>
Select TYPE: Gauge
<br>
TITLE : Vehicle Speed
<br>
VALUE: datasources["v2"]["vehicle_speed"]
<br>
UNITS: miles/hr
<br>
MINIMUM: 0
<br>
MAXIMUM: 0
</p>
<p>While configuring engine speed and accelerator pedal position, use DATASOURCE hyperlink available next the textbox which will auto populate text for selecting DATASOURCE and autocomplete all the available parameters.</P>

<br>
<br>
<br>
<p>Graph displayed below: </p>
 |
Python | UTF-8 | 3,706 | 3.109375 | 3 | [
"MIT"
] | permissive |
# coding: utf-8
# In[25]:
import nltk
import csv
import pickle
from nltk.classify.scikitlearn import SklearnClassifier
from sklearn.naive_bayes import MultinomialNB,BernoulliNB
from sklearn.linear_model import LogisticRegression,SGDClassifier
from sklearn.svm import SVC, LinearSVC, NuSVC
# In[26]:
f=open('/home/aman/Desktop/QLearn Aman_Malali/train_questions.txt','rU') #Reads in the training questions text file
with open('/home/aman/train_labels.csv','rb') as k:
reader=csv.reader(k)
train_labels=list(reader) #Reads in the training labels file
train_labels.remove(train_labels[0]) #removes 'id' and 'label' from the label file
# In[27]:
train_data=f.read()
# In[28]:
train_sent=train_data.splitlines()
train_sent.remove(train_sent[0]) #split the training set into its corresponding
#print len(train_sent) #sentences
# In[29]:
final_set=[]
all_words1=[]
token=nltk.RegexpTokenizer(r'\w+') #the word tokenizer that does not read in punctuation
all_words=token.tokenize(train_data) #All words in the file are tokenized
for j in all_words:
if j.isdigit() is False: #Read in only non numerical words present in the entire train set
all_words1.append(j)
e=0
for i in train_sent: # Creates a list of list of lists with words of each question and the
words=[] # corresponding label [0-6]
set1=[]
set2=[]
words=nltk.word_tokenize(i)
set1.append(words[2:])
set1.append(train_labels[e][1])
final_set.append(set1)
e=e+1
# In[30]:
all_words2=nltk.FreqDist(all_words1) #The frequency distribution of all of the words present in the train file
word_features=list(all_words2.keys())
#print len(word_features)
# In[31]:
def find_features(sent): # Finding the features of each question and storing it as a dictionary
words2=set(sent)
features={}
for w in word_features:
features[w]=(w in words2)
return features
# In[32]:
featuresets=[(find_features(rev),category) for (rev, category) in final_set]
# Finds all the features of all the questions present in the training set and puts it in the form of a list
# In[36]:
training_set=featuresets[:3000]
#testing_set=featuresets[2900:]
#Split of 80:20 for training and testing set
# In[37]:
LinearSVC_classifier = SklearnClassifier(LinearSVC())
LinearSVC_classifier.train(training_set)
#print nltk.classify.accuracy(LinearSVC_classifier, testing_set)
# In[35]:
x=open('/home/aman/test_questions.txt','rU') #Opening the testing data and follow the same procedure as for training
test_data=x.read() #data
test_set=test_data.splitlines()
test_set.remove(test_set[0])
# In[19]:
final_test=[] #Putting all the words in the same form as that for training data
for i in test_set:
words=[]
set1=[]
words=nltk.word_tokenize(i)
set1.append(words[2:])
final_test.append(set1)
# In[20]:
answer=[['Id','Prediction']]
# In[22]:
id1=3001 #Predicting for all the testing data and writing it in a list
for r in final_test:
prediction=LinearSVC_classifier.classify(find_features(r[0]))
tempset=[id1,prediction]
id1=id1+1
answer.append(tempset)
# In[23]:
with open("Submission.csv",'wb') as y: #Converting the list of prediction to a .csv file
writer=csv.writer(y)
writer.writerows(answer)
# In[ ]:
|
Java | UTF-8 | 2,954 | 2.015625 | 2 | [] | no_license | package org.castor.jaxb.reflection.processor.field;
import java.lang.annotation.Annotation;
import javax.xml.bind.annotation.XmlElementWrapper;
import org.apache.commons.lang3.StringUtils;
import org.castor.core.annotationprocessing.AnnotationProcessor;
import org.castor.core.nature.BaseNature;
import org.castor.jaxb.reflection.info.JaxbFieldNature;
import org.castor.jaxb.reflection.processor.BaseFieldProcessor;
import org.springframework.stereotype.Component;
/**
* Annotation processor for XMLElement.
*
* @author Joachim Grueneis, jgrueneis_at_gmail_dot_com
* @version $Id$
*/
@Component("xmlElementWrapperFieldProcessor")
public class XmlElementWrapperProcessor extends BaseFieldProcessor {
/** XmlElementWrapper.name default is ##default. */
public static final String ELEMENT_WRAPPER_NAME_DEFAULT = "##default";
/** XmlElementWrapper.namespace default is ##default. */
public static final String ELEMENT_WRAPPER_NAMESPACE_DEFAULT = "##default";
/**
* {@inheritDoc}
*
* @see org.codehaus.castor.annoproc.AnnotationProcessor#
* processAnnotation(org.castor.xml.introspection.BaseNature,
* java.lang.annotation.Annotation)
*/
public final <I extends BaseNature, A extends Annotation> boolean processAnnotation(
final I info, final A annotation) {
if ((annotation instanceof XmlElementWrapper)
&& (info instanceof JaxbFieldNature)) {
XmlElementWrapper xmlElementWrapper = (XmlElementWrapper) annotation;
JaxbFieldNature fieldInfo = (JaxbFieldNature) info;
this.annotationVisitMessage(xmlElementWrapper);
fieldInfo.setXmlElementWrapper(true);
if (!ELEMENT_WRAPPER_NAME_DEFAULT.equals(xmlElementWrapper
.name())) {
fieldInfo.setElementWrapperName(xmlElementWrapper.name());
} else {
//TODO[WG]: nit sure this is the right place
// default naming handling
String xmlElementName = fieldInfo.getElementName();
if (StringUtils.isNotEmpty(xmlElementName)) {
fieldInfo.setElementWrapperName(xmlElementName);
}
}
fieldInfo.setElementWrapperNillable(xmlElementWrapper
.nillable());
fieldInfo.setElementWrapperRequired(xmlElementWrapper
.required());
if (!ELEMENT_WRAPPER_NAMESPACE_DEFAULT.equals(xmlElementWrapper
.namespace())) {
fieldInfo.setElementWrapperNamespace(xmlElementWrapper
.namespace());
}
return true;
}
return false;
}
/**
* {@inheritDoc}
*
* @see AnnotationProcessor#forAnnotationClass()
*/
public Class<? extends Annotation> forAnnotationClass() {
return XmlElementWrapper.class;
}
} |
Python | UTF-8 | 2,267 | 2.65625 | 3 | [
"MIT"
] | permissive | '''
matplotlib datasets
'''
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits import mplot3d
class DatasetPlotter(object):
def __init__(self, ax):
self.ax = self._gca(ax) # axes object
@staticmethod
def _gca(ax):
if ax is None:
ax = plt.gca()
else:
assert isinstance(ax, plt.Axes), 'ax must be None or a matplotlib axes object'
return ax
def _ensure3d(self):
if not isinstance(self.ax, mplot3d.Axes3D):
bbox = self.ax.get_position()
plt.delaxes(self.ax)
self.ax = plt.axes(bbox, projection='3d')
def plot(self, *args, **kwdargs):
return self.ax.plot(*args, **kwdargs)
def plot_bivariate1d(self, y, **kwdargs):
h0 = self.ax.plot( y[0,:,0] )[0]
h1 = self.ax.plot( y[0,:,1] )[0]
c0 = h0.get_color()
c1 = h1.get_color()
hh0 = self.ax.plot( y[1:,:,0].T , color=c0 )
hh1 = self.ax.plot( y[1:,:,1].T , color=c1 )
def plot_trivariate1d(self, y, **kwdargs):
h0 = self.ax.plot( y[0,:,0] )[0]
h1 = self.ax.plot( y[0,:,1] )[0]
h2 = self.ax.plot( y[0,:,2] )[0]
c0 = h0.get_color()
c1 = h1.get_color()
c2 = h2.get_color()
hh0 = self.ax.plot( y[1:,:,0].T , color=c0 )
hh1 = self.ax.plot( y[1:,:,1].T , color=c1 )
hh2 = self.ax.plot( y[1:,:,2].T , color=c2 )
def scatter(self, *args, **kwdargs):
return self.ax.scatter(*args, **kwdargs)
#
# x = 0 if (x is None) else x
# ax,J = self.ax, self.d.J
# h = self.ax.scatter(x*np.ones(J), self.y, **kwdargs)
# if plot_sample_mean:
# fc = h.get_facecolor()[0][:3]
# ec = h.get_edgecolor()[0][:3]
# h1 = self.ax.plot( x, self.mean, 'o', ms=15, mfc=fc, mec=ec, alpha=0.5)[0]
# return h,h1
# else:
# return h
def scatter3d(self, *args, **kwdargs):
self._ensure3d()
return self.ax.scatter(*args, **kwdargs)
# def scatter_u0d(ds, ax=None, x=None, plot_sample_mean=True, **kwdargs):
# plotter = DatasetPlotter(ax)
# x = 0 if (x is None) else x
# h = self.ax.scatter(x*np.ones(ds.J), ds.y, **kwdargs)
# if plot_sample_mean:
# fc = h.get_facecolor()[0][:3]
# ec = h.get_edgecolor()[0][:3]
# h1 = self.ax.plot( x, self.mean, 'o', ms=15, mfc=fc, mec=ec, alpha=0.5)[0]
# return h,h1
# else:
# return h
#
#
# return plotter.scatter_u0d()
|
Python | UTF-8 | 2,773 | 2.765625 | 3 | [] | no_license | from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from .models import Page
import urllib.parse
import urllib.request
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
import sys
titulares = ""
class myContentHandler(ContentHandler):
def __init__ (self):
self.inItem = False
self.inContent = False
self.theContent = ""
self.title = ""
self.link = ""
def startElement (self, name, attrs):
if name == 'item':
self.inItem = True
elif self.inItem:
if name == 'title':
self.inContent = True
elif name == 'link':
self.inContent = True
def endElement (self, name):
global titulares
if name == 'item':
self.inItem = False
elif self.inItem:
if name == 'title':
line = "Title: " + self.theContent + "."
self.title = self.theContent
# To avoid Unicode trouble
#print line.encode('utf-8')
self.inContent = False
self.theContent = ""
elif name == 'link':
self.link = self.theContent
#print " Link: " + self.theContent + "."
self.inContent = False
self.theContent = ""
titulares = titulares + "<a href='" + self.link + "'>" + self.title + "</a><br>"
def characters (self, chars):
if self.inContent:
self.theContent = self.theContent + chars
def mostrar(request):
global titulares
#Pido el XML de Barrapunto
xmlFile = urllib.request.urlopen('http://barrapunto.com/index.rss')
#Inicializo el parse de barrapunt
theParser = make_parser()
theHandler = myContentHandler()
theParser.setContentHandler(theHandler)
theParser.parse(xmlFile)
salida = "<ul>"
for listado in Page.objects.all():
salida += "<li>" + str(listado.nombre)
salida += "</ul>"
return HttpResponse("<h1>Contenido de la base de datos:</h1>" + salida + "<br><h2>Titulares de Barrapunto</h2>" + titulares)
@csrf_exempt
def insertar(request, texto):
if request.method == "GET":
try:
p = Page.objects.get(nombre = texto)
return HttpResponse(p.contenido)
except Page.DoesNotExist:
return HttpResponse("No existe una página para ese recurso.")
else:
p = Page(nombre = texto, pagina = request.body.decode('utf-8'))
p.save()
return HttpResponse("Página con el nombre: '" + str(p.nombre) + "' y el contenido: " + str(p.contenido) + " ha sido creada.")
|
Markdown | UTF-8 | 6,385 | 2.578125 | 3 | [] | no_license | # Notes Part 6
## Episode 58: The Will to Power
The Flock take a bow in the wake of their arena victory, and head to the meeting room where the new treatise of Reece will be signed. They are greeted by Ephialtes (EFF-ee-all-tees), former magnate of the black faction, who coyly gave them a tip for their victory and implied an interest in future ventures.
After exchanging some brief niceties with The Oracle and Dracuil, the Flock head back to Calicyon to take better stock of their affairs and await a meeting with Draciul. Tywin finds that Alexios has been busy while he has been away, and has begun construction of a mansion on the island as well as begun preparations for some vineyards. A few varieties of grapes have been secured:
- Sunburst Grapes
- Mooflake Grapes
- Green Goddess Grapes
As Tywin and Carlo begin to pore over the pile of magic swords they had received from the arena bout, Pewt announces that he had wagered a siginficant portion of the crew's assets on the result of the fight, and as a result the Flock are owed 12 new ships as well as having been paid out 80,000 gold pieces that Pewt had had carried in a heavy chest. After some debate (and some scolding Pewt for so flippantly gambling with other peoples' money), the Flock resolve to use the gold as an investment in a new Wizards' Tower in their lands in the eclipse kingdoms.
Draciul finally appears, laden with the news of the world. It seems that one of the Yankos is dead, and most of the OGW's navy is busily attending the impending war over the remains of her empire. Meanwhile, the Flock had been named official Warlords in service to the OGW.... for about two days before it is officially revoked. New bounties are also up, which put the total bounty for the crew to nearly 1,000,000 gold and officially named them enemies of the state (what else is new). Draciul then relates a tale of his past, being orphaned, a longtime rivalry with Sadhbh, and setting out to become the greatest swordsman in the world. His tale leaves him empty, however, with nothing left to achieve. The Flock tell Draciul of their quest, leaving him with much to think on.
Nail appears with a message from Kurthnaga: Kurthnaga needs the flock to head to Wano and secure allies before the coming conflict. After some discussion, the flock have a plan of action:
- Check in on Shepherd's Rest
- Visit Alabasta to recruit wizards for the tower
- Get the tower started in Spearval
- Head south and begin Kurthnaga's mission
## Episode 59: Archipelago Economics
The flock depart Calicyon for Shepherd's Rest, where they are greeted by their staff and good news of the progress being made on the now-bustling port. The marketplace has reached profitability, and the flock make a few useful purchases:
- Tywin arranges for a construction materials representative from the Beedles to be sent out to Portlandia
- Carlo buys Teleportation Circle from a Blue Beedle
- Tywin buys several preservative canisters, and puts an investment in the Istan-based Gnome Physics company, with a promise of future distribution support.
In Alabasta, Tywin and Carlo meet with Kazadrel Locthwain about the plans to establish a wizard's tower in Spearval. Kazadrel agrees to send a contingent of retirees and eager graduates with some specialization to get started on the research operations there.
They head to Istan (which is swarming with marines) next to inquire about their recent ship acquisitions, and Leetus Iceberg gives them a tour:
6 Small ships (8 cannons total)
3 Light Ships (8 cannons per side)
2 Frigates (15 cannons per side)
1 Brass Kraken (armored plating, 24 cannons per side with additional 6 frontal cannons. )
On the way to the eclipse kingdoms the Flock have a distant and luckily peaceful encounter with ships that seem to be the fleet of one of the Admirals. Upon arriving, they find Portlandia has a large encampment of marines that are disrupting the restoration operations. Tywin conducts several meetings with the vice admiral, merchants' council, the Queens, and the Beedle merchant in order to get things moving again.
Their business in various kingdoms concluded for now, the flock turn their eyes southward...
## Episode 60: A Bridge Ten Yards Over Troubled Water
The flock begin heading for Minashotia to meet with the heir of Owari. Along the way, Alithyra does some fishing and dredges up Jebediah, a 10 foot magical fish who seems intent on swindling the party. After the flock best him in a battle of riddles, Jebediah tries to shirk his end of the bargain by claiming he owns no posessions. While the flock is wrestling with getting Jebediah to meet his agreement, Madara appears, and demands that Jebediah turn over two items instead of just one. Madara mentions he has become the God-King of the Sea, and then jumps off the ship to be about his business.
Further along, the Flock encounter a dense fog. clearing out the fog reveals a lonely stone tower, with the puzzling feature of a dock positioned 30ft above the surface of the water. Inside are thousands of inert warforged, and Dimitri, a warforged acquanted with Simon, preserved from the void century. He speaks of a purge that was to come, one which these warforged were prepared to help assist with. The Flock leave Simon and a freshly retrieved Gepetto to oversee the handling of these wayward automatons, and soldier on toward Minashotia.
After finishing up in the tower, the Flock continue sailing until they encounter two ships in pitched combat. They descend upon the ships by warp gate and demand a ceasefire. As the fighting dissipates, Tywin and Carlo begin locating the leadership of the two factions for questioning.
- Duke of Dogs
- Princess Dalia of House Lassie, Daughter of the Duke of Dogs
- Captain Eisenhower Kerberus
- Countess of Cats
- Prince Cornelius of House O'Malley, Cub of the Countess of Cats
- Captain Bigel Yeager
As it turns out, the catfolk were fleeing the Dukedom of Dogs, having been sent to provide escort for the engaged Daughter of the Duke of Dogs. The Daughter left without any word to her father, however, and Captain Eisenhower's ship was sent to recover her. As neither side agree on much of anything, the flock opt to keep care of the Daughter until both factions can meet on the island of Nidavellir.
Having temporarily resolved the conflict, the Flock continue on, and find themselves within view of Minashotia...
[<--Vast-Oceans Home](README.md)
|
C# | UTF-8 | 9,984 | 2.765625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebREST.Models;
using MySql.Data.MySqlClient;
using System.Security.Cryptography;
using System.Text;
namespace WebREST.Services
{
public class ContactRepository
{
private const string CacheKey = "ContactStore";
string cs = @"server=localhost;userid=root;password=root;database=cempaka";
private List<Contact> ConnectDB()
{
List<Contact> users = new List<Contact>();
var con = new MySqlConnection(cs);
con.Open();
var stm = "SELECT * FROM users";
var cmd = new MySqlCommand(stm, con);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Contact user = new Contact();
user.Id = Convert.ToInt32(rdr["id"].ToString());
user.Email = rdr["emailAddress"].ToString();
user.Name = rdr["userName"].ToString();
user.Password = rdr["password"].ToString();
user.CreatedDate = rdr["createdDate"].ToString();
user.UpdateDate = rdr["updateDate"].ToString();
users.Add(user);
}
con.Close();
return users;
}
private byte[] GetHash(string inputString)
{
HashAlgorithm algorithm = SHA1.Create();
return algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString));
}
public string GetHashString(string inputString)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in GetHash(inputString))
sb.Append(b.ToString("X2"));
return sb.ToString();
}
private List<Contact> InsertDB(Contact userContact)
{
int id = 0;
List<Contact> users = new List<Contact>();
var con = new MySqlConnection(cs);
con.Open();
var stm = "SELECT MAX(id) as id from users";
var cmd = new MySqlCommand(stm, con);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
id = Convert.ToInt32(rdr["id"].ToString());
}
id++;
con.Close();
con.Open();
string pswd = GetHashString(userContact.Password);
stm = "INSERT INTO users(id,emailAddress,username,password,createdDate,updateDate) VALUES("+id+",'"+userContact.Email+"','"+ userContact.Name+ "','"+ pswd + "',"+DateTime.Today.ToString("yyyyMMddHHmmss")+", "+DateTime.Today.ToString("yyyyMMddHHmmss") + ")";
cmd = new MySqlCommand(stm, con);
cmd.ExecuteNonQuery();
con.Close();
con.Open();
stm = "SELECT * FROM users";
cmd = new MySqlCommand(stm, con);
MySqlDataReader rdr2 = cmd.ExecuteReader();
while (rdr2.Read())
{
Contact user = new Contact();
user.Id = Convert.ToInt32(rdr2["id"].ToString());
user.Email = rdr2["emailAddress"].ToString();
user.Name = rdr2["userName"].ToString();
user.Password = rdr2["password"].ToString();
user.CreatedDate = rdr2["createdDate"].ToString();
user.UpdateDate = rdr2["updateDate"].ToString();
users.Add(user);
}
con.Close();
return users;
}
private bool CheckPswdDB(string email,string password)
{
List<Contact> users = new List<Contact>();
var con = new MySqlConnection(cs);
con.Open();
string pswd = GetHashString(password);
var stm = "SELECT * FROM users where emailAddress = '"+email+"' and password ='"+pswd+"'";
var cmd = new MySqlCommand(stm, con);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return true;
}
con.Close();
return false;
}
private List<Contact> UpdateDB(Contact userContact)
{
List<Contact> users = new List<Contact>();
var con = new MySqlConnection(cs);
con.Open();
string pswd = GetHashString(userContact.Password);
var stm = "UPDATE users set password ='" + pswd + "',updateDate = " + DateTime.Today.ToString("yyyyMMddHHmmss") + " where id=" + userContact.Id;
var cmd = new MySqlCommand(stm, con);
cmd.ExecuteNonQuery();
con.Close();
con.Open();
stm = "SELECT * FROM users";
cmd = new MySqlCommand(stm, con);
MySqlDataReader rdr2 = cmd.ExecuteReader();
while (rdr2.Read())
{
Contact user = new Contact();
user.Id = Convert.ToInt32(rdr2["id"].ToString());
user.Email = rdr2["emailAddress"].ToString();
user.Name = rdr2["userName"].ToString();
user.Password = rdr2["password"].ToString();
user.CreatedDate = rdr2["createdDate"].ToString();
user.UpdateDate = rdr2["updateDate"].ToString();
users.Add(user);
}
con.Close();
return users;
}
private List<Contact> DeleteDB(string email)
{
List<Contact> users = new List<Contact>();
var con = new MySqlConnection(cs);
con.Open();
var stm = "DELETE from users where emailAddress = '"+email+"'";
var cmd = new MySqlCommand(stm, con);
cmd.ExecuteNonQuery();
con.Close();
con.Open();
stm = "SELECT * FROM users";
cmd = new MySqlCommand(stm, con);
MySqlDataReader rdr2 = cmd.ExecuteReader();
while (rdr2.Read())
{
Contact user = new Contact();
user.Id = Convert.ToInt32(rdr2["id"].ToString());
user.Email = rdr2["emailAddress"].ToString();
user.Name = rdr2["userName"].ToString();
user.Password = rdr2["password"].ToString();
user.CreatedDate = rdr2["createdDate"].ToString();
user.UpdateDate = rdr2["updateDate"].ToString();
users.Add(user);
}
con.Close();
return users;
}
public ContactRepository()
{
var ctx = HttpContext.Current;
if (ctx != null)
{
if (ctx.Cache[CacheKey] == null)
{
var contacts = new Contact[]
{
new Contact
{
Id = 1, Name = "Glenn"
},
new Contact
{
Id = 2, Name = "Dan"
}
};
//ctx.Cache[CacheKey] = contacts;
ctx.Cache[CacheKey] = ConnectDB();
}
}
}
public List<Contact> GetAllContacts()
{
var ctx = HttpContext.Current;
if (ctx != null)
{
//return (Contact[])ctx.Cache[CacheKey];
return ConnectDB();
}
return null;
//return new Contact[]
// {
// new Contact
// {
// Id = 0,
// Name = "Placeholder"
// }
// };
}
public bool LoginCheck(string email,string password)
{
return CheckPswdDB(email,password);
}
public bool DeleteContacts(string email)
{
var ctx = HttpContext.Current;
if (ctx != null)
{
try
{
//var currentData = ((List<Contact>)ctx.Cache[CacheKey]).ToList();
var currentData = ConnectDB();
foreach (Contact item in currentData)
{
if (item.Email.Equals(email))
{
ctx.Cache[CacheKey] = DeleteDB(email);
return true;
}
}
ctx.Cache[CacheKey] = currentData.ToArray();
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
return false;
}
public bool SaveContact(Contact contact)
{
var ctx = HttpContext.Current;
if (ctx != null)
{
try
{
//need to check records if exist edit!!
var currentData = ((List<Contact>)ctx.Cache[CacheKey]).ToList();
foreach (Contact user in currentData)
{
if (user.Email.Equals(contact.Email))
{
ctx.Cache[CacheKey] = UpdateDB(contact);
return true;
}
}
//currentData.Add(contact);
ctx.Cache[CacheKey] = InsertDB(contact);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
return false;
}
}
} |
C++ | GB18030 | 1,532 | 3.234375 | 3 | [] | no_license | //*************************************************************************
//
// 9㷨ܽо
//
// 2017-06-06
//
//*************************************************************************
#pragma once
#include <string>
#include <iostream>
#include <time.h>
using namespace std;
//9ԭƪ
class AutoSort
{
public:
static int main(int argc, char** argv);
public:
AutoSort() {};
~AutoSort() {};
public:
//ֱӲ
void InsertSort(int data[], int n);
//ֲ
void BiInsertSort(int data[], int n);
//ϣ
void ShellSort(int data[], int n);
//ð
void BubbleSort(int data[], int n);
//[LΪȡһȽֵindex]
void QuickSort(int data[], int n, int L = 0);
//ѡ
void SelectSort(int data[], int n);
//
void HeapSort(int data[], int n);
//鲢
void MergeSort(int data[], int n);
//
void RadixSort(int data[], int n);
//
void CountSort(void);
private:
//ӡ
void print(int data[], int n);
//ʱ
void TakeTime(void);
public:
template <typename T>
void Swap(T& A, T& B)
{
T temp(A);
A = B;
B = temp;
}
template <typename T>
void PSwap(T* A, T* B)
{
T tmp = *A;
*A = *B;
*B = tmp;
}
};
|
Markdown | UTF-8 | 9,618 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | # Istio in a Kubernetes Engine Cluster
## Table of Contents
<!--ts-->
- [Istio in a Kubernetes Engine Cluster](#istio-in-a-kubernetes-engine-cluster)
* [Table of Contents](#table-of-contents)
* [Introduction](#introduction)
* [Architecture](#architecture)
+ [Istio Overview](#istio-overview)
- [Istio Control Plane](#istio-control-plane)
- [Istio Data Plane](#istio-data-plane)
+ [BookInfo Sample Application](#bookinfo-sample-application)
+ [Putting it All Together](#putting-it-all-together)
* [Initialize GCP](#initialize-gcp)
* [Deployment steps](#deployment-steps)
* [Validation](#validation)
+ [View Prometheus UI](#view-prometheus-ui)
+ [View Grafana UI](#view-grafana-ui)
+ [View Jaeger UI](#view-jaeger-ui)
* [Tear Down](#tear-down)
* [Relevant Material](#relevant-material)
<!--te-->
## Introduction
[Istio](http://istio.io/) is part of a new category of products known as "service mesh" software
designed to manage the complexity of service resilience in a microservice
infrastructure. It defines itself as a service management framework built to
keep business logic separate from the logic to keep your services up and
running. In other words, it provides a layer on top of the network that will
automatically route traffic to the appropriate services, handle [circuit
breaker](https://en.wikipedia.org/wiki/Circuit_breaker_design_pattern) logic,
enforce access and load balancing policies, and generate telemetry data to
gain insight into the network and allow for quick diagnosis of issues.
For more information on Istio, please refer to the [Istio
documentation](https://istio.io/docs/). Some familiarity with Istio is assumed.
This repository contains demonstration code to create an Istio service mesh in
a single GKE cluster and use [Prometheus](https://prometheus.io/),
[Jaeger](https://www.jaegertracing.io/), and [Grafana](https://grafana.com/) to
collect metrics and tracing data and then visualize that data.
## Architecture
### Istio Overview
Istio has two main pieces that create the service mesh: the control plane and
the data plane.
#### Istio Control Plane
The control plane is made up of the following set of components that act
together to serve as the hub for the infrastructure's service management:
* _[Mixer](https://istio.io/docs/concepts/what-is-istio/#mixer)_: a platform-independent component responsible for enforcing access control and usage policies across the service mesh and collecting telemetry data from the [Envoy](https://istio.io/docs/concepts/what-is-istio/#envoy) proxy and other services
* _[Pilot](https://istio.io/docs/concepts/what-is-istio/#pilot)_: provides service discovery for the Envoy sidecars, traffic management capabilities for intelligent routing, (A/B tests, canary deployments, etc.), and resiliency (timeouts, retries, circuit breakers, etc.)
* _[Citadel](https://istio.io/docs/concepts/what-is-istio/#citadel)_: provides strong service-to-service and end-user authentication using mutual TLS, with built-in identity and credential management.
#### Istio Data Plane
The data plane comprises all the individual service proxies that are
distributed throughout the infrastructure. Istio uses
[Envoy](https://www.envoyproxy.io/) with some Istio-specific extensions as its
service proxy. It mediates all inbound and outbound traffic for all services in
the service mesh. Istio leverages Envoy’s many built-in features such as
dynamic service discovery, load balancing, TLS termination, HTTP/2 & gRPC
proxying, circuit breakers, health checks, staged roll-outs with
percentage-based traffic splits, fault injection, and rich metrics.
### BookInfo Sample Application
The sample [BookInfo](https://istio.io/docs/guides/bookinfo.html)
application displays information about a book, similar to a single catalog entry
of an online book store. Displayed on the page is a description of the book,
book details (ISBN, number of pages, and so on), and a few book reviews.
The BookInfo application is broken into four separate microservices and calls on
various language environments for its implementation:
- **productpage** - The productpage microservice calls the details and reviews
microservices to populate the page.
- **details** - The details microservice contains book information.
- **reviews** - The reviews microservice contains book reviews. It also calls the
ratings microservice.
- **ratings** - The ratings microservice contains book ranking information that
accompanies a book review.
There are 3 versions of the reviews microservice:
- **Version v1** doesn’t call the ratings service.
- **Version v2** calls the ratings service, and displays each rating as 1 to 5
black stars.
- **Version v3** calls the ratings service, and displays each rating as 1 to 5
red stars.

To learn more about Istio, please refer to the
[project's documentation](https://istio.io/docs/).
### Putting it All Together
The pods and services that make up the Istio control plane are the first components of the architecture that will be installed into Kubernetes Engine. An Istio service proxy is installed along with each microservice during the installation of the BookInfo application, as are our telemetry add-ons. At this point, in addition to the application microservices there are two tiers that make up the Istio architecture: the Control Plane and the Data Plane.
In the diagram, note:
* All input and output from any BookInfo microservice goes through the service proxy.
* Each service proxy communicates with each other and the Control Plane to implement the features of the service mesh, circuit breaking, discovery, etc.
* The Mixer component of the Control Plane is the conduit for the telemetry add-ons to get metrics from the service mesh.
* The Istio ingress component provides external access to the mesh.
* The environment is setup in the Kubernetes Engine default network.

## Initialize GCP
```console
gcloud init
```
## Deployment steps
_NOTE: The following instructions are applicable for deployments performed both with and without Cloud Shell._
Copy the `properties` file to `properties.env` and set the following variables in the `properties.env` file:
* `YOUR_PROJECT` - the name of the project you want to use
* `YOUR_REGION` - the region in which to locate all the infrastructure
* `YOUR_ZONE` - the zone in which to locate all the infrastructure
```console
make create
```
The script should deploy all of the necessary infrastructure and install Istio. The script will end with a line like this, though the IP address will likely be different:
```
Update istio service proxy environment file
104.196.243.210/productpage
```
You can open this URL in your browser and see the simple web application provided by the demo.
## Validation
1. On the command line, run the following command:
```console
echo "http://$(kubectl get -n istio-system service istio-ingressgateway -o jsonpath='{.status.loadBalancer.ingress[0].ip}'):$(kubectl get -n istio-system service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="http")].port}')/productpage"
```
1. Visit the generated URL in your browser to see the BookInfo application.
### View Prometheus UI
1. To forward the Prometheus UI port locally so you can use the browser to access it, run the following command on the command line:
```console
kubectl -n istio-system port-forward $(kubectl -n istio-system get pod -l app=prometheus -o jsonpath='{.items[0].metadata.name}') 9090:9090
```
1. Visit the following URL in your web browser: http://localhost:9090/graph
Press `CTRL-C` to quit forwarding the port.
For more information on how to use Prometheus with Istio, please refer to the
[Istio documentation](https://istio.io/docs/tasks/telemetry/querying-metrics/)
### View Grafana UI
1. To forward the Grafana UI port locally so you can use the browser to access it, run the following command:
```console
kubectl -n istio-system port-forward $(kubectl -n istio-system get pod -l app=grafana -o jsonpath='{.items[0].metadata.name}') 3000:3000
```
1. Visit the following url in your web browser:
http://localhost:3000/dashboard/db/istio-dashboard
Press `CTRL-C` to quit forwarding the port.
For more information on how to use Grafana with Istio, please refer to the
[Istio documentation](https://istio.io/docs/tasks/telemetry/using-istio-dashboard/)
### View Jaeger UI
1. To forward the Jaeger UI port locally so you can use the browser to access it, run the following command:
```console
kubectl port-forward -n istio-system $(kubectl get pod -n istio-system -l app=jaeger -o jsonpath='{.items[0].metadata.name}') 16686:16686
```
1. Visit the following url in your web browser: http://localhost:16686
Press `CTRL-C` to quit forwarding the port.
For more information on how to generate sample traces, please refer to the [Istio
documentation](https://istio.io/docs/tasks/telemetry/distributed-tracing/).
## Tear Down
To tear down the resources created by this demonstration, run:
```console
make teardown
```
## Relevant Material
This demo was created with help from the following links:
* https://cloud.google.com/kubernetes-engine/docs/tutorials/istio-on-gke
* https://cloud.google.com/compute/docs/tutorials/istio-on-compute-engine
* https://istio.io/docs/guides/bookinfo.html
* https://istio.io/docs/tasks/telemetry/querying-metrics/
* https://istio.io/docs/tasks/telemetry/using-istio-dashboard/
* https://istio.io/docs/tasks/telemetry/distributed-tracing/
**This is not an officially supported Google product**
|
Java | UTF-8 | 21,776 | 2.15625 | 2 | [] | no_license | package no.hioa.crawler.parser;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import no.hioa.crawler.model.Link;
import no.hioa.crawler.util.LinkUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.log4j.PropertyConfigurator;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExtractTextContent
{
private static final Logger logger = LoggerFactory.getLogger(ExtractTextContent.class);
private List<String> stopWords = null;
public static void main(String[] args) throws Exception
{
PropertyConfigurator.configure("log4j.properties");
ExtractTextContent extractor = new ExtractTextContent();
// extractor.extractFolders(new File("E:/Data/blogs2/crawl/"), new
// File("E:/Data/blogs2/text/"));
// extractor.extractFolderContent(new
// File("E:/Data/blogs2/crawl/honestthinkingorgno/"), new
// File("E:/Data/blogs2/text/honestthinkingorgno/"));
// System.out.println(extractor.extractDate(new
// File("E:/Data/blogs2/crawl/4freedomsningcom/1428482190019.html")));
// System.out.println(extractor.extractLinks(new
// Link("frie-ytringer.com"), new
// File("E:/Data/blogs2/crawl/frieytringercom/1428526543682.html")));
// extractor.extractFolderLinks(new Link("sian.no"), new File("E:/Data/blogs2/crawl/sianno/"), new File("E:/Data/blogs2/links/"));
//extractor.extractLinksFolders();
//extractor.filterLinksFolder(new File("E:/Data/blogs2/links - hebdo or charlie"), new File("E:/Data/blogs2/alllinks-hebdo_or_charlie.csv"));
extractor.filterLinksFolder(new File("E:/Data/blogs2/links - hebdo"), new File("E:/Data/blogs2/alllinks-hebdo.csv"));
}
public ExtractTextContent()
{
stopWords = getStopWords();
}
public void filterLinksFolder(File folderPath, File outputFile) throws Exception
{
StringBuffer buffer = new StringBuffer();
long links = 0;
long unknown = 0;
long notFound = 0;
long invalid = 0;
for (File file : folderPath.listFiles())
{
List<LinkDate> dates = new LinkedList<>();
List<String> lines = FileUtils.readLines(file, "UTF-8");
for (String line : lines)
{
try
{
String domain = file.getName().replace("-links.txt", "");
String date = StringUtils.substringBefore(line, ":");
String foundDate = StringUtils.substringAfter(line, ":");
foundDate = StringUtils.substringBefore(foundDate, ":");
String url = StringUtils.substringAfter(line, ":");
url = StringUtils.substringAfter(url, ":");
url = LinkUtil.normalizeDomain(url);
buffer.append(domain).append(";");
buffer.append(date).append(";");
buffer.append(foundDate).append(";");
buffer.append(url).append("\n");
if (date.equalsIgnoreCase("2000-01-01"))
unknown++;
if (foundDate.equalsIgnoreCase("false") && !date.equalsIgnoreCase("2000-01-01"))
notFound++;
links++;
}
catch (Exception ex)
{
invalid++;
}
}
}
FileUtils.writeStringToFile(outputFile, buffer.toString());
logger.info("Links found: {}", links);
logger.info("Unknown dates: {}", unknown);
logger.info("Not found dates: {}", notFound);
logger.info("Invalid: {}", invalid);
}
public void extractLinksFolders()
{
this.extractFolderLinks(new Link("4freedoms.com"), new File("E:/Data/blogs2/crawl/4freedomsningcom/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("britainfirst.org"), new File("E:/Data/blogs2/crawl/britainfirstorg/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("demokratene.no"), new File("E:/Data/blogs2/crawl/demokrateneno/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("document.no"), new File("E:/Data/blogs2/crawl/documentno/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("frie-ytringer.com"), new File("E:/Data/blogs2/crawl/frieytringercom/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("frihetspartiet.net"), new File("E:/Data/blogs2/crawl/frihetspartietnet/"),
new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("honestthinking.org"), new File("E:/Data/blogs2/crawl/honestthinkingorgno/"), new File(
"E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("idag.no"), new File("E:/Data/blogs2/crawl/idagno/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("kristentsamlingsparti.no"), new File("E:/Data/blogs2/crawl/kristentsamlingspartino/"), new File(
"E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("lionheartuk.blogspot.no"), new File("E:/Data/blogs2/crawl/lionheartukblogspotno/"), new File(
"E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("marchforengland.weebly.com"), new File("E:/Data/blogs2/crawl/marchforenglandweeblycom/"), new File(
"E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("norgesavisen.no"), new File("E:/Data/blogs2/crawl/norgesavisenno/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("norwegiandefenceleague.com"), new File("E:/Data/blogs2/crawl/norwegiandefenceleaguecom/"), new File(
"E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("rights.no"), new File("E:/Data/blogs2/crawl/rightsno/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("ronnyalte.net"), new File("E:/Data/blogs2/crawl/ronnyaltenet/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("sian.no"), new File("E:/Data/blogs2/crawl/sianno/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("sisteskanse.net"), new File("E:/Data/blogs2/crawl/sisteskansenet/"), new File("E:/Data/blogs2/links/"));
this.extractFolderLinks(new Link("theenglishdefenceleagueextra.blogspot.no"), new File(
"E:/Data/blogs2/crawl/theenglishdefenceleagueextrablogspotno/"), new File("E:/Data/blogs2/links/"));
}
public void extractFolders(File folderPath, File outputPath)
{
for (File folder : folderPath.listFiles())
{
if (folder.isDirectory())
{
logger.info("Extracting text from folder {}", folder.getName());
try
{
File outputFolder = new File(outputPath + "/" + folder.getName());
FileUtils.forceMkdir(outputFolder);
extractFolderContent(folder, outputFolder);
}
catch (IOException ex)
{
logger.error("Could not save content for folder", ex);
}
}
}
}
public boolean extractFolderLinks(Link domain, File folder, File outputFolder)
{
List<LinkDate> dates = new LinkedList<>();
for (File file : folder.listFiles())
{
if (file.isFile())
{
dates.addAll(extractLinks(domain, file));
}
}
try
{
int found = 0;
int notfound = 0;
String buffer = "";
for (LinkDate date : dates)
{
buffer += date.date + ":" + date.foundDate + ":" + date.url + "\n";
if (date.foundDate)
found++;
else
notfound++;
}
buffer = StringUtils.substringBeforeLast(buffer, ",");
FileUtils.writeStringToFile(new File(outputFolder + "/" + domain.getLink() + "-links.txt"), buffer.toString());
logger.info("Found dates: {}", found);
logger.info("Did not find dates: {}", notfound);
}
catch (Exception ex)
{
logger.error("Unknown error", ex);
}
return true;
}
public boolean extractFolderContent(File folder, File outputFolder)
{
HashMap<String, LocalDate> dates = new HashMap<>();
for (File file : folder.listFiles())
{
if (file.isFile())
{
String content = extractTextContent(file);
if (content != null && !StringUtils.isEmpty(content))
{
saveResult(new File(outputFolder + "/" + file.getName() + ".txt"), content);
dates.put(file.getName(), extractDate(file));
}
}
}
try
{
String buffer = "";
for (String key : dates.keySet())
{
if (dates.get(key) == null)
buffer += key + ":unknown,";
else
buffer += key + ":" + dates.get(key) + ",";
}
buffer = StringUtils.substringBeforeLast(buffer, ",");
FileUtils.writeStringToFile(new File(outputFolder + "/dates.txt"), buffer.toString());
}
catch (Exception ex)
{
logger.error("Unknown error", ex);
}
return true;
}
public List<LinkDate> extractLinks(Link domain, File htmlFile)
{
try
{
List<LinkDate> links = new LinkedList<>();
List<String> unknown = new LinkedList<>();
String html = FileUtils.readFileToString(htmlFile, "UTF-8");
if (StringUtils.containsIgnoreCase(html, "hebdo") || StringUtils.containsIgnoreCase(html, "charlie"))
{
Document doc = Jsoup.parse(html);
Elements elements = doc.select("p");
Iterator<Element> it = elements.listIterator();
while (it.hasNext())
{
Element element = it.next();
Elements el = element.select("a[href]");
for (Element e : el)
{
String url = e.attr("href");
if (!shouldUseLink(domain, url))
continue;
// find tag in source (can be multiple)
// extract 500 chars before and after, regex for dates
int index = StringUtils.indexOf(html, e.html());
if (index != -1)
{
int start = index - 1000;
if (start < 0)
start = 0;
int end = index + 4000;
if (end >= html.length())
end = html.length() - 1;
String source = StringUtils.substring(html, start, end);
source = StringUtils.replace(source, url, "");
if (url.contains("http://www.vg.no/nyheter/innenriks/lyst-til"))
{
// logger.info(source);
}
LocalDate date = getDate(source, url);
if (date != null)
{
// logger.info("Found date ({}) for {}", date, url);
links.add(new LinkDate(url, date, true));
}
else
{
// logger.info("Could not find date ({}) for {} in {}",
// date, url, htmlFile);
unknown.add(url);
}
}
}
el = element.select("iframe[src]");
for (Element e : el)
{
String url = e.attr("src");
if (!shouldUseLink(domain, url))
continue;
// find tag in source (can be multiple)
// extract 500 chars before and after, regex for dates
int index = StringUtils.indexOf(html, e.toString());
if (index != -1)
{
int start = index - 1000;
if (start < 0)
start = 0;
String source = StringUtils.substring(html, start, index);
source = StringUtils.replace(source, url, "");
if (url.contains("nzRliBASdCc"))
{
// logger.info(source);
}
LocalDate date = getDate(source, url);
if (date != null)
{
// logger.info("Found date ({}) for {}", date, url);
links.add(new LinkDate(url, date, true));
}
else
{
// logger.info("Could not find date ({}) for {} in {}",
// date, url, htmlFile);
unknown.add(url);
}
}
}
}
if (!unknown.isEmpty() && !links.isEmpty())
{
LocalDate firstDate = links.get(0).date;
for (String url : unknown)
links.add(new LinkDate(url, firstDate, false));
}
else if (!unknown.isEmpty() && links.isEmpty())
{
LocalDate fileDate = extractDate(htmlFile);
if (fileDate != null)
{
for (String url : unknown)
links.add(new LinkDate(url, fileDate, false));
}
else
{
for (String url : unknown)
links.add(new LinkDate(url, LocalDate.parse("2000-01-01", DateTimeFormat.forPattern("yyyy-MM-dd")), false));
}
}
}
return links;
}
catch (Exception ex)
{
ex.printStackTrace();
return null;
}
}
private LocalDate getDate(String input, String url)
{
try
{
input = input.replaceAll("\n", " ");
input = input.replaceAll("\"", "");
LocalDate date = findDate(input);
if (date != null)
return date;
date = findDateFromUrl(url);
return date;
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
private LocalDate findDate(String input)
{
try
{
String regex = ".*(january|february|march|april|may|june|july|august|september|october|november|december)(\\s)(\\d+?)(,\\s)(20\\d\\d).*";
Pattern p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(input);
if (m.matches())
{
String year = m.group(5);
String month = getMonthFromText(m.group(1));
String day = m.group(3);
String date = year + "-" + month + "-" + day;
return LocalDate.parse(date, DateTimeFormat.forPattern("yyyy-MM-dd"));
}
regex = ".*(\\s)(\\d+?)(\\s)(january|february|march|april|may|june|july|august|september|october|november|december)(\\s)(20\\d\\d).*";
p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
m = p.matcher(input);
if (m.matches())
{
String year = m.group(6);
String month = getMonthFromText(m.group(4));
String day = m.group(2);
String date = year + "-" + month + "-" + day;
return LocalDate.parse(date, DateTimeFormat.forPattern("yyyy-MM-dd"));
}
regex = ".*(\\d\\d)(/)(\\d\\d)(/)(20\\d\\d).*";
p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
m = p.matcher(input);
if (m.matches())
{
String year = m.group(5);
String month = m.group(3);
String day = m.group(1);
String date = year + "-" + month + "-" + day;
return LocalDate.parse(date, DateTimeFormat.forPattern("yyyy-MM-dd"));
}
return null;
}
catch (Exception ex)
{
return null;
}
}
private LocalDate findDateFromUrl(String url)
{
try
{
String regex = ".*(/)(20\\d\\d)(/)(\\d\\d)(/)(\\d\\d)(/).*";
Pattern p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(url);
if (m.matches())
{
String year = m.group(2);
String month = getMonthFromText(m.group(4));
String day = m.group(6);
String date = year + "-" + month + "-" + day;
return LocalDate.parse(date, DateTimeFormat.forPattern("yyyy-MM-dd"));
}
regex = ".*(/)(20\\d\\d)(/)(\\d\\d)(/).*";
p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
m = p.matcher(url);
if (m.matches())
{
String year = m.group(2);
String month = getMonthFromText(m.group(4));
String day = "01";
String date = year + "-" + month + "-" + day;
return LocalDate.parse(date, DateTimeFormat.forPattern("yyyy-MM-dd"));
}
regex = ".*(/)(20\\d\\d)(/)(\\d\\d)(/).*";
p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
m = p.matcher(url);
if (m.matches())
{
String year = m.group(2);
String month = getMonthFromText(m.group(4));
String day = "01";
String date = year + "-" + month + "-" + day;
return LocalDate.parse(date, DateTimeFormat.forPattern("yyyy-MM-dd"));
}
regex = ".*(/)(20\\d\\d)(/)(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)(/)(\\d\\d)(/).*";
p = Pattern.compile(regex, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
m = p.matcher(url);
if (m.matches())
{
String year = m.group(2);
String month = getMonthFromText(m.group(4));
String day = m.group(6);
String date = year + "-" + month + "-" + day;
return LocalDate.parse(date, DateTimeFormat.forPattern("yyyy-MM-dd"));
}
return null;
}
catch (Exception ex)
{
return null;
}
}
public boolean shouldUseLink(Link domain, String url)
{
try
{
if (StringUtils.isEmpty(url))
return false;
if (!url.startsWith("http"))
return false;
if (url.contains(domain.getLink()))
return false;
url = url.replace("https://", "http://");
if (domain.getLink().equalsIgnoreCase(LinkUtil.normalizeDomain(url)) || "/".equalsIgnoreCase(LinkUtil.normalizeDomain(url)))
{
logger.debug("Ignoring link since internal: " + url);
return false;
}
for (String ignore : getIgnoreLinks())
{
if (url.contains(ignore))
return false;
}
return true;
}
catch (Exception ex)
{
return false;
}
}
private String getMonthFromText(String input)
{
switch (input.toLowerCase())
{
case "january":
return "01";
case "february":
return "02";
case "march":
return "03";
case "april":
return "04";
case "may":
return "05";
case "june":
return "06";
case "july":
return "07";
case "august":
return "08";
case "september":
return "09";
case "october":
return "10";
case "november":
return "11";
case "december":
return "12";
}
return "01";
}
@SuppressWarnings("unchecked")
public LocalDate extractDate(File htmlFile)
{
try
{
List<String> lines = FileUtils.readLines(htmlFile);
String urlLine = lines.get(0);
if (!StringUtils.contains(urlLine, "URL:"))
{
logger.error("Could not find URL in file: {}", htmlFile);
return null;
}
else
{
String url = StringUtils.substringAfter(urlLine, "URL: ");
String year = getYear(url);
String month = getMonth(url);
if (year != null && month != null)
{
String date = year + "-" + month;
return LocalDate.parse(date, DateTimeFormat.forPattern("yyyy-MM"));
}
else if (year != null)
return LocalDate.parse(year, DateTimeFormat.forPattern("yyyy"));
else
{
for (String line : lines)
{
if (StringUtils.contains(line, "article:published_time"))
{
String date = StringUtils.substringAfter(line, "content");
date = StringUtils.substringBetween(date, "\"", "\"");
return LocalDate.parse(year, DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"));
}
}
}
}
return null;
}
catch (Exception ex)
{
return null;
}
}
public String extractTextContent(File htmlFile)
{
try
{
String html = FileUtils.readFileToString(htmlFile, "UTF-8");
Document doc = Jsoup.parse(html);
Elements elements = doc.select("p");
StringBuffer buffer = new StringBuffer();
Iterator<Element> it = elements.listIterator();
while (it.hasNext())
{
Element element = it.next();
String content = element.text();
StringTokenizer words = new StringTokenizer(content);
if (words.countTokens() < 5)
{
// ignore
}
else if (words.countTokens() > 5 && words.countTokens() < 15)
{
boolean found = false;
while (words.hasMoreTokens())
{
if (stopWords.contains(words.nextToken()))
// if
// (StandardAnalyzer.STOP_WORDS_SET.contains(words.nextToken()))
{
found = true;
break;
}
}
if (found)
buffer.append("\n" + content);
}
else
{
buffer.append("\n" + content);
}
}
return buffer.toString();
}
catch (Exception ex)
{
logger.error("Unknown error", ex);
return null;
}
}
private List<String> getStopWords()
{
return getFileContent(new File("src/main/resources/no/hioa/crawler/parser/stop-words-english.txt"));
}
private void saveResult(File file, String buffer)
{
try (PrintWriter writer = new PrintWriter(file, "ISO-8859-1"))
{
writer.write(buffer.toString());
}
catch (IOException ex)
{
logger.error("Could not save content to file " + file, ex);
}
}
private List<String> getFileContent(File file)
{
List<String> words = new LinkedList<>();
try (Scanner scanner = new Scanner(new FileInputStream(file), "ISO-8859-1"))
{
while (scanner.hasNextLine())
{
String input = scanner.nextLine().toLowerCase();
words.add(input);
}
}
catch (Exception ex)
{
logger.error("Could not read content for file " + file.getAbsolutePath(), ex);
}
return words;
}
private String getMonth(String input)
{
try
{
Pattern p = Pattern.compile(".*([/\\\\]\\d\\d[/\\\\]).*");
Matcher m = p.matcher(input.replaceAll(" ,", ","));
if (m.matches())
return StringUtils.substringBetween(m.group(1), "/", "/");
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
}
private String getYear(String input)
{
try
{
Pattern p = Pattern.compile(".*([/\\\\]20\\d\\d[/\\\\]).*");
Matcher m = p.matcher(input);
if (m.matches())
return StringUtils.substringBetween(m.group(1), "/", "/");
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
}
private List<String> getIgnoreLinks()
{
List<String> ignore = new LinkedList<>();
ignore.add("facebook");
ignore.add("ning");
ignore.add("twitter");
ignore.add("dropbox");
ignore.add("mailto");
ignore.add("google.com");
ignore.add("linkedin.com");
ignore.add("paypal");
ignore.add("presscustomizr");
ignore.add("ideaboxthemes");
ignore.add("youtube.com/DocumentNo");
ignore.add("presse.no/Etisk-regelverk/");
return ignore;
}
public class LinkDate
{
public String url;
public LocalDate date;
public boolean foundDate;
public LinkDate(String url, LocalDate date, boolean foundDate)
{
super();
this.url = url;
this.date = date;
this.foundDate = foundDate;
}
@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
}
|
Shell | UTF-8 | 306 | 3.09375 | 3 | [] | no_license | #!/bin/bash
# Increase swap space from 4GB to 13GB
# Usage: `_set_swap 13G`
swap_file=/mnt/swapfile
swap_file_size="${1}"
sudo swapoff $swap_file
sudo rm -f $swap_file
sudo fallocate -l $swap_file_size $swap_file
sudo chmod 600 $swap_file
sudo mkswap $swap_file
sudo swapon $swap_file
sudo swapon --show
|
PHP | UTF-8 | 1,702 | 2.984375 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace site\models;
use common\models\User;
use yii\base\Model;
use Yii;
/**
* change password form
*/
class ChangePasswordForm extends Model
{
public $old_password;
public $new_password;
private $user;
/**
* Creates a form model
*
* @param object $user
* @param array $config name-value pairs that will be used to initialize the object properties
*/
public function __construct(\common\interfaces\UserInterface $user, $config = [])
{
$this->user = $user;
parent::__construct($config);
}
/**
* @inheritdoc
*/
public function rules()
{
return [
['old_password', 'string', 'min' => 6],
['new_password', 'string', 'min' => 8],
[['old_password', 'new_password'], 'required'],
['old_password', 'validatePassword'],
];
}
public function attributeLabels()
{
return [
'old_password' => 'Current Password',
'new_password' => 'New Password',
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*/
public function validatePassword()
{
if (!$this->hasErrors()) {
if (!$this->user->validatePassword($this->old_password)) {
$this->addError('old_password', 'Incorrect email or password.');
}
}
}
/**
* changes user's password.
*
* @return Boolean whether or not the save was successful
*/
public function changePassword()
{
$this->user->setPassword($this->new_password);
return $this->user->save();
}
}
|
C# | UTF-8 | 11,410 | 2.609375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Script.Serialization;
using FluentValidation;
using Model;
using Service.Utilities;
using System.Linq.Expressions;
using System.Reflection;
using AutoMapper.Internal;
using FluentValidation.Results;
namespace Service.Base
{
public class CRUDService : BaseService, ICRUDService {
private static ValidationService _validationService;
public CRUDService(IPrimaryContext context)
: base(context) {
_validationService = new ValidationService(context);
}
/// <summary>
/// Creates a row in the database for the entity T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The entity to attach</param>
public int Create<T>(T data) where T : class, IEntity {
var parameter = Expression.Parameter(typeof(T));
var props = typeof(T).GetProperties();
foreach (System.Reflection.PropertyInfo prop in props
.Where(x => x.CustomAttributes
.Any(z => z.AttributeType.Name
.Equals("ForeignKeyAttribute"))))
{
prop.SetValue(data, null);
}
ThrowIfNull(data);
ValidateAndThrow(data, _validationService.GetValidator<T>(data));
Context.Set<T>().Add(data);
// ReSharper disable once PossibleNullReferenceException
Context.SaveChanges();
return data.Id;
}
/// <summary>
/// Gets all of an entity.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>Returns an IEnumerable of the entity.</returns>
public IQueryable<T> Get<T>() where T : class, IEntity {
return Context.Set<T>().AsQueryable();
}
/// <summary>
/// Gets all of an entity.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="includes">The entities to attach</param>
/// <returns>Returns an IEnumerable of the entity.</returns>
public IQueryable<T> Get<T>(string[] includes) where T : class, IEntity
{
var query = Context.Set<T>().AsQueryable();
if (includes.Length > 0) {
query = includes.Aggregate(query, (current, t) => current.Include(t));
}
return query;
}
/// <summary>
/// Gets an entity by Id.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="id"></param>
/// <returns>Returns the entity, or null if not found.</returns>
public new T GetById<T>(int id) where T : class, IEntity {
return Context.Set<T>().SingleOrDefault(c => c.Id == id);
}
public T GetById<T>(int id, string[] includes) where T : class, IEntity {
var query = Context.Set<T>().AsQueryable();
if (includes.Length > 0) {
for (int i = 0; i < includes.Length; i++) {
query = query.Include(includes[i]);
}
}
return query.SingleOrDefault(c => c.Id == id);
}
/// <summary>
/// Updates a generic model T with the generic Class given.
/// Maps the field names of the JSON object to the field names on
/// the model T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The entity to attach</param>
public void Update<T>(T data) where T : class, IEntity, new() {
ThrowIfNull(data);
ValidateAndThrow(data, _validationService.GetValidator<T>(data));
Context.Set<T>().Attach(data);
Context.SetEntityState(data, EntityState.Modified);
Context.SaveChanges();
}
/// <summary>
/// Updates a generic model T with the generic JSON data given.
/// Maps the field names of the JSON object to the field names on
/// the model T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The generic JSON object</param>
public void Update<T>(string data) where T : class, IEntity, new() {
ThrowIfNull(data);
var dict = (IDictionary<string, object>)new JavaScriptSerializer().DeserializeObject(data.ToString());
var obj = new T() {
Id = Convert.ToInt32(dict["Id"])
};
Context.Set<T>().Attach(obj);
ContextHelper.Map(dict, obj, Context);
Context.SaveChanges();
}
/// <summary>
/// Updates a generic list T.
/// This overwrites the Lists, if you only want to update specific fields add a mapping action as a second parameter.
/// ONLY USE FOR SMALL LISTS, Bigger Lists should use a BulkExtension Package.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="itemList">List of the Generic Object</param>
/// <param name="mapping">This contains the mapping of the object for example: (e,u) => e.name = u.name</param>
public void Update<T>(IEnumerable<T> itemList) where T : class, IEntity {
ThrowIfNull(itemList);
var existing = Context.Set<T>();
Context.Set<T>().AddRange(itemList);
Context.SaveChanges();
}
/// <summary>
/// Updates a generic list T.
/// Maps the properties to update using the mapping function.
/// ONLY USE FOR SMALL LISTS, Bigger Lists should use a BulkExtension Package.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="itemList">List of the Generic Object</param>
/// <param name="mapping">This contains the mapping of the object for example: (e,u) => e.name = u.name</param>
public void Update<T>(IEnumerable<T> itemList, Action<T, T> mapping) where T : class, IEntity {
var enumerable = itemList as T[] ?? itemList.ToArray();
ThrowIfNull(enumerable);
foreach (var item in itemList) {
ValidateAndThrow(item, _validationService.GetValidator<T>(item));
}
;
var existing = Context.Set<T>();
Context.Merge<T>()
.SetExisting(existing)
.SetUpdates(enumerable)
.MergeBy((e, u) => e.Id == u.Id)
.MapUpdatesBy(mapping)
.Merge();
Context.SaveChanges();
}
/// <summary>
/// Updates a generic model T with the generic JSON data given.
/// Maps the field names of the JSON object to the field names on
/// the model T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The generic JSON object</param>
/// <returns>The rowversion of the updated object</returns>
public byte[] UpdateVersionable<T>(string data) where T : class, IEntity, IVersionable, new() {
ThrowIfNull(data);
var dict = (IDictionary<string, object>)new JavaScriptSerializer().DeserializeObject(data.ToString());
var obj = new T() {
Id = Convert.ToInt32(dict["Id"]),
Version = Convert.FromBase64String(dict["Version"].ToString())
};
Context.Set<T>().Attach(obj);
ContextHelper.Map(dict, obj, Context);
Context.SaveChanges();
return obj.Version;
}
/// <summary>
/// Updates a generic model T with the generic JSON data given.
/// Maps the field names of the JSON object to the field names on
/// the model T.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The generic JSON object</param>
/// <returns>The rowversion of the updated object</returns>
public byte[] UpdateVersionable<T>(T data) where T : class, IEntity, IVersionable, new() {
ThrowIfNull(data);
ValidateAndThrow(data, _validationService.GetValidator<T>(data));
Context.Set<T>().Attach(data);
Context.SetEntityState(data, EntityState.Modified);
Context.SaveChanges();
return data.Version;
}
public T Reload<T>(int id) where T : class, IEntity, new() {
return Context.Set<T>().AsNoTracking().SingleOrDefault(c => c.Id == id);
}
/// <summary>
/// Needs to know what the parent Entity is as well as the FK Entity.
/// Then it determines if it should throw a validation exception that the item is in use.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TS"></typeparam>
/// <param name="itemList"></param>
/// <param name="foreignKeyColumnName"></param>
/// <param name="entityErrorMsg"></param>
/// <returns></returns>
public bool CheckEntityInUse<T, TS>(IEnumerable<T> itemList, string foreignKeyColumnName, string entityErrorMsg) where T : class, IEntity where TS : class, IEntity {
var existing = Context.Set<T>().ToArray();
var toRemove = existing.Where(e => itemList.All(u => e.Id != u.Id)).ToArray();
if (toRemove.Length == 0) return false;
var ids = toRemove.Select(tr => tr.Id).ToList();
var filterField = foreignKeyColumnName;
var eParam = Expression.Parameter(typeof(TS), "e");
CheckNullable(ids, filterField, eParam, out List<int?> nullableList);
var method = nullableList != null ? nullableList.GetType().GetMethod("Contains") : ids.GetType().GetMethod("Contains");
if (method != null)
{
var call = nullableList != null
? Expression.Call(Expression.Constant(nullableList), method, Expression.Property(eParam, filterField))
: Expression.Call(Expression.Constant(ids), method, Expression.Property(eParam, filterField));
var predicate = Expression.Lambda<Func<TS, bool>>(call, eParam);
if (Context.Set<TS>().Where(predicate).ToList().Count <= 0) return false;
} else {
throw new NullReferenceException("method is null");
}
var error = new ValidationFailure("Id", entityErrorMsg);
throw new ValidationException(new[] { error });
}
private static void CheckNullable(IEnumerable<int> ids, string filterField, Expression eParam, out List<int?> nullableList)
{
var member = (PropertyInfo)Expression.Property(eParam, filterField).Member;
nullableList = member.PropertyType.IsNullableType() ? ids.Select(i => (int?)i).ToList() : null;
}
public void Delete<T>(int id) where T : class, IEntity, new() {
T obj = new T { Id = id };
Context.Set<T>().Attach(obj);
Context.Set<T>().Remove(obj);
Context.SaveChanges();
}
public void Delete<T>(T data) where T : class, IEntity, new() {
Context.Set<T>().Attach(data);
Context.Set<T>().Remove(data);
Context.SaveChanges();
}
}
}
|
Java | UTF-8 | 1,764 | 2.546875 | 3 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package AnalyzersAndFilters.Window;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.IndexWriter;
/**
*
* @author grey
*/
public class TenWordsCalculator {
final static int windowSize = 10;
public static String text;
public List<String> getTens() throws IOException {
// final String text = SimilarityReader1.text;
BufferedReader in;
StringBuilder sb;
int tokenNumber = WindowFilter.x;
sb = new StringBuilder();
sb.append(text);
String[] tokenterm = sb.toString().replaceAll("[\\W&&[^\\s]]", "").split("\\W+");
List<String> tarray = new ArrayList<String>();
int i = tokenNumber;
if(tokenterm!=null){
String term = tokenterm[i];
//int m = 0;
for (int j = windowSize / 2; j > 0; j--) {
if (i - j < 0) {
tarray.add(" ");
} else {
tarray.add(tokenterm[i - j]);
//write(tokenterm[i-j]);
// m++;
}
}
// m++;
for (int j = 1; j <= windowSize / 2; j++) {
if (i + j > tokenterm.length - 1) {
tarray.add(" ");
} else {
tarray.add(tokenterm[i + j]);
// m++;
}
}}
return tarray;
}
}
|
JavaScript | UTF-8 | 2,490 | 2.515625 | 3 | [] | no_license | import { Paper, makeStyles, ButtonBase, Chip } from "@material-ui/core";
import React, { useEffect, useState } from "react";
import CategoriesContainer from "./CategoriesContainer";
import Filter from "./Filter";
const useStyles = makeStyles((theme) => ({
container: {
position: "relative",
width: "300px",
overflowY: "scroll",
bottom: "0",
},
listWrapper: {
position: "absolute",
},
list: {
listStyle: "none",
marginLeft: "-40px",
},
paper: {
width: 250,
margin: `${theme.spacing(1)}px auto`,
padding: theme.spacing(2),
backgroundColor: "#f5f5f5",
},
button: {
display: "block",
},
}));
const AllTasks = (props) => {
const classes = useStyles();
const [filters, setFilters] = useState([]);
const [tasks, setTasks] = useState([]);
useEffect(() => {
if (filters.length > 0) {
// Check tasks that contains categories
const tasks = props.tasks.filter((task) => {
return filters.some((filter) => {
return task.categories.some(
(category) => filter.name === category.name
);
});
});
setTasks(tasks);
} else {
setTasks(props.tasks);
}
}, [filters, props.tasks]);
return (
<div className={classes.container}>
<h1>All tasks</h1>
<Filter setFilters={setFilters} />
<div className={classes.listWrapper}>
<ul className={classes.list}>
{tasks.length > 0 ? (
tasks.map((task, index) => (
<li key={index.toString()}>
<ButtonBase
key={task._id.toString()}
href={`/${task._id}`}
className={classes.button}
>
<Paper className={classes.paper}>
<h2>{task.title}</h2>
{task.categories.length > 0 && (
<CategoriesContainer>
{task.categories.map((category) => (
<Chip
key={category.id}
label={category.name}
color="primary"
/>
))}
</CategoriesContainer>
)}
</Paper>
</ButtonBase>
</li>
))
) : (
<p>No tasks</p>
)}
</ul>
</div>
</div>
);
};
export default AllTasks;
|
JavaScript | UTF-8 | 1,901 | 2.53125 | 3 | [] | no_license | var express = require('express');
var router = express.Router();
let mongoose = require('mongoose');
//let signupControl = require('../controller/signupcontrol');
//let loginControl = require('../controller/logincontrol');
let movieSearch = require('../controller/moviecontrol');
/*route for signup*/
//router.get('/signup', signupControl.addNewUser);
/*route for logging in*/
//router.get('/login', loginControl.login);
//router.get('/logout', loginControl.logout);
/*routes for movies add,delete,search,view*/
/*router.get('/movie/search', movieSearch.search);
router.get('/movie/add', movieSearch.favourite);
router.get('/movie/view', movieSearch.viewfavourite);
router.get('/movie/delete', movieSearch.delfavourite);*/
module.exports = router;
var isAuthenticated = function (req, res, next) {
// if user is authenticated in the session, call the next() to call the next request handler
// Passport adds this method to request object. A middleware is allowed to add properties to
// request and response objects
if (req.isAuthenticated())
return next();
// if the user is not authenticated then redirect him to the login page
res.redirect('/');
}
module.exports = function(passport){
router.get('/movie/search', movieSearch.search);
router.get('/movie/add', movieSearch.favourite);
router.get('/movie/view', movieSearch.viewfavourite);
router.get('/movie/delete', movieSearch.delfavourite);
/* Handle Login POST */
router.post('/login', passport.authenticate('login', {
successRedirect: '/movie.html',
failureRedirect: '/',
failureFlash : true
}));
/* Handle Registration POST */
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/movie.html',
failureRedirect: '/',
failureFlash : true
}));
/* Handle Logout */
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
} |
C++ | UHC | 8,656 | 2.84375 | 3 | [
"MIT"
] | permissive | #ifndef NEURALNETWORK_H_INCLUDED
#define NEURALNETWORK_H_INCLUDED
#include <wiz/global.h> /// for toString
#include <wiz/newArrays.h>
namespace wiz
{
// namespace NN
// 0 or 1
template <typename INTEGER, typename NUMBER>
INTEGER up(const NUMBER nx) /// move to main.cpp?
{
int ix = nx + 0.5;/// + 0.5;
//if( nx > 0.1 ) { ix = 1; }
//else { ix = 0; }
return ix;
}
/// namespace NeuralNetwork?
/// Neural Net
// IH : input_layer->hidden_layer
// HO : hidden_layer -> output_layer
// output is list of ( 0 or 1 ).
/// first goal is make one class
template < typename INTEGER, typename NUMBER, class RAND, class G >
class NeuralNet
{
private:
SecondArray<NUMBER> weightIH; /// input_layer -> hidden_layer
SecondArray<NUMBER> weightHO; /// hidden_layer -> output_layer
public:
NUMBER GAMMA; /// ToDo make - set, get
NUMBER H; /// remove??
INTEGER INPUT_NODE_NUM;
INTEGER HIDDEN_NODE_NUM;
INTEGER OUTPUT_NODE_NUM;
NUMBER GetGAMMA()const { return GAMMA; }
NUMBER GetH()const { return H; }
SecondArray<NUMBER> GetWeightIH()const { return weightIH; }
SecondArray<NUMBER> GetWeightHO()const { return weightHO; }
void SetWeightIH( const INTEGER row, const INTEGER col, const NUMBER weight )
{
weightIH[row][col] = weight;
}
void SetWeightHO( const INTEGER row, const INTEGER col, const NUMBER weight )
{
weightHO[row][col] = weight;
}
private:
void InitWeight(Array<NUMBER>& arr)
{
const int size = arr.size();
for (int i = 0; i < size; i++) {
arr[i] = RAND()();
}
}
void InitWeight(SecondArray<NUMBER>& arr)
{
const int rowSize = arr.getRowN();
for (int i = 0; i < rowSize; i++) {
InitWeight(arr[i]);
}
}
NUMBER Sum(const Array<NUMBER>& arr) const
{
NUMBER sum = 0;
const int size = arr.size();
for (int i = 0; i < size; i++)
{
sum = sum + arr[i];
}
return sum;
}
NUMBER Sum(const SecondArray<NUMBER>& arr) const
{
NUMBER sum = 0;
const int rowSize = arr.getRowN();
for (int i = 0; i < rowSize; i++)
{
sum = sum + Sum(arr[i]);
}
return sum;
}
/// chk...
Array<INTEGER> Convert( const INTEGER ival )const /// assume ival >= 0
{
Array<INTEGER> iarr;
string str = wiz::toStr(ival, 2);
iarr = Array<INTEGER>(str.size(), 0);
for (int i = 0; i < str.size(); i++)
{
iarr[i] = str[i] - '0';
}
return iarr;
}
NUMBER a(const Array<NUMBER>& weight, const Array<NUMBER>& input,
const int num)const /// int INTEGER??
{
NUMBER sum = 0;
for ( int i = 0; i < num; i++) {
sum = sum + weight[i] * input[i];
}
return sum;
}
/// weight -> input weight!
NUMBER o(const Array<NUMBER>& weight,
const Array<NUMBER>& input, const int num) const
// output
{
return G()(a(weight, input, num));
}
NUMBER delta_wij(const NUMBER delta_j, const NUMBER x_ij) const {
return GAMMA * delta_j * x_ij;
}
public:
explicit NeuralNet( const INTEGER input_node_num, const INTEGER hidden_node_num, const INTEGER output_node_num,
const NUMBER gamma = 0.005, const NUMBER h = 0.01 )
: INPUT_NODE_NUM( input_node_num ), HIDDEN_NODE_NUM( hidden_node_num ), OUTPUT_NODE_NUM( output_node_num ),
GAMMA( gamma ), H( h )
{
/// init()?
weightIH = SecondArray<NUMBER>(HIDDEN_NODE_NUM, INPUT_NODE_NUM, 0);
weightHO = SecondArray<NUMBER>(OUTPUT_NODE_NUM, HIDDEN_NODE_NUM, 0);
InitWeight( weightIH );
InitWeight( weightHO );
}
/// void reset()?
void GetOutput( const Array<NUMBER>& input, Array<NUMBER>& output) const
{
//const int HIDDEN_NODE_NUM = weightIH.getRowN();
//const int INPUT_NODE_NUM = input.size();
//const int OUTPUT_NODE_NUM = output.size();
Array<NUMBER> hidden(HIDDEN_NODE_NUM, 0);
// void GetOutput( weightIH, weightHo, input, out output )
// 1. input node -> hidden node
for (int i = 0; i < HIDDEN_NODE_NUM; i++) {
hidden[i] = o(weightIH[i], input, INPUT_NODE_NUM);
}
// 2. hidden node -> output node
for (int i = 0; i < OUTPUT_NODE_NUM; i++) {
output[i] = o(weightHO[i], hidden, HIDDEN_NODE_NUM);
}
}
void Train(
const Array<NUMBER>& input, /// const Array<NUMBER>& output,
const Array<NUMBER>& truthValue // INTEGER?
)
{
/// chk, ũ ...
//const int HIDDEN_NODE_NUM = weightIH.getRowN();
//const int OUTPUT_NODE_NUM = output.size();
//const int INPUT_NODE_NUM = input.size();
Array<NUMBER> hidden(HIDDEN_NODE_NUM, 0);
Array<NUMBER> output(OUTPUT_NODE_NUM, 0 );
Array<NUMBER> deltaH(HIDDEN_NODE_NUM, 0);
Array<NUMBER> deltaK(weightHO.getRowN(), 0); // OUTPUT_NODE_NUM
// Compute output
// void GetOutput( weightIH, weightHo, input, out output )
// 1. input node -> hidden node
for (int i = 0; i < HIDDEN_NODE_NUM; i++) {
hidden[i] = o(weightIH[i], input, INPUT_NODE_NUM);
}
// 2. hidden node -> output node
for (int i = 0; i < OUTPUT_NODE_NUM; i++) {
output[i] = o(weightHO[i], hidden, HIDDEN_NODE_NUM);
}
// Calcul delta value
// 1. delta k
for (int i = 0; i < OUTPUT_NODE_NUM; i++) {
deltaK[i] = output[i] * (1 - output[i]) * (truthValue[i] - output[i]);
}
// 2. delta h
{ // ij̽ ȭ?
Array<NUMBER> sum(HIDDEN_NODE_NUM, 0);
for (int k = 0; k < OUTPUT_NODE_NUM; k++) {
for (int h = 0; h < HIDDEN_NODE_NUM; h++) { //
sum[h] = sum[h] + weightHO[k][h] * deltaK[k];
}
}
for (int h = 0; h < HIDDEN_NODE_NUM; h++) {
deltaH[h] = hidden[h] * (1 - hidden[h]) * sum[h];
}
/*
//
for( int h=0; h < HIDDEN_NODE_NUM; h++ ) {
NUMBER sum = 0;
for( int k=0; k < OUTPUT_NODE_NUM; k++ ) {
sum = sum + weightHO[k][h] * deltaK[k];
}
deltaH[h] = hidden[h] * ( 1 - hidden[h] ) * sum;
} */
}
// Update each network weight w(i,j)
// gammar? = 0.005, 0.05
// 1. update input node -> hidden node
for (int i = 0; i < HIDDEN_NODE_NUM; i++) {
for (int j = 0; j < INPUT_NODE_NUM; j++) {
weightIH[i][j] = weightIH[i][j] + delta_wij(deltaH[i], input[j]);
}
}
// 2. hidden node -> output node
for (int i = 0; i < OUTPUT_NODE_NUM; i++) { // ̸ ݴӿ !
for (int j = 0; j < HIDDEN_NODE_NUM; j++) {
weightHO[i][j] = weightHO[i][j] + delta_wij(deltaK[i], hidden[j]);
}
}
}
/// To Do - sumOfWeight = Sum( weightIH ) + Sum( weightHO );
double SumOfWeight()const
{
return Sum( weightIH ) + Sum( weightHO );
}
};
}
#endif // NEURALNETWORK_H_INCLUDED
|
Python | UTF-8 | 2,793 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | """
"""
import pytest
from bitvector import BitVector
@pytest.mark.fast
def test_bitvector_shift_negative(BV_1: BitVector):
with pytest.raises(ValueError):
BV_1 << -1
with pytest.raises(ValueError):
BV_1 >> -1
@pytest.mark.fast
def test_bitvector_shift_boundries(BV_1: BitVector, BV_HI: BitVector):
result = BV_1 << 128
assert result == 0
result = BV_HI >> 128
assert result == 0
@pytest.mark.parametrize("position", list(range(0, 128)))
def test_bitvector_shift_left_scalar(position: int, BV_1: BitVector):
expected = 1 << position
result = BV_1 << position
assert result == expected
assert isinstance(result, BitVector) and result is not BV_1
@pytest.mark.parametrize("position", list(range(0, 128)))
def test_bitvector_shift_left_bitvector(position: int, BV_1: BitVector):
expected = 1 << position
with pytest.raises(TypeError):
# not sure how to get BitVectors to be valid on the RHS of <<
result = 1 << BitVector(position)
assert result == expected
result = BV_1 << BitVector(position)
assert result == expected
@pytest.mark.parametrize("position", list(range(0, 128)))
def test_bitvector_shift_left_inplace_scalar(position: int, BV_1: BitVector):
expected = 1 << position
BV_1 <<= position
assert BV_1 == expected
@pytest.mark.parametrize("position", list(range(0, 128)))
def test_bitvector_shift_left_inplace_bitvector(position: int, BV_1: BitVector):
expected = 1 << position
BV_1 <<= BitVector(position)
assert BV_1 == expected
@pytest.mark.parametrize("position", list(range(0, 128)))
def test_bitvector_shift_right_scalar(position: int, BV_HI: BitVector):
expected = (1 << 127) >> position
result = BV_HI >> position
assert result == expected
assert isinstance(result, BitVector) and result is not BV_HI
@pytest.mark.parametrize("position", list(range(0, 128)))
def test_bitvector_shift_right_bitvector(position: int, BV_HI: BitVector):
expected = (1 << 127) >> position
with pytest.raises(TypeError):
# not sure how to get BitVectors to be valid on the RHS of >>
result = 1 >> BitVector(position)
assert result == expected
result = BV_HI >> BitVector(position)
assert result == expected
@pytest.mark.parametrize("position", list(range(0, 128)))
def test_bitvector_shift_right_inplace_scalar(position: int, BV_HI: BitVector):
expected = (1 << 127) >> position
BV_HI >>= position
assert BV_HI == expected
@pytest.mark.parametrize("position", list(range(0, 128)))
def test_bitvector_shift_right_inplace_bitvector(position: int, BV_HI: BitVector):
expected = (1 << 127) >> position
BV_HI >>= BitVector(position)
assert BV_HI == expected
|
Markdown | UTF-8 | 1,187 | 3.5 | 4 | [] | no_license | 不难得出结论:f(n) = f(n-1) + f(n-2) + ***+1
第一思路是递归外面套一个for循环,但是累加值依赖于返回值:
1、如果使用内部类,count作为参数每次返回结果都是1
```
def helper(num,count)
if num == 1: return 1
***
count += helper(num,count)
等价于
a = helper(num,count)
count +=a
***
这样每次传进去的count值始终为0,最后返回的count其实只是计算了递归次数
***
```
```
# -*- coding:utf-8 -*-
class Solution:
def jumpFloorII(self, number):
# write code here
count = 0
def helper(num):
nonlocal count
if num == 1: return 1
i = 1
while(num - i > 0):
count += helper(num-i)
i += 1
return count+1
return helper(number)
```
对该无穷级数进行化简,除num=1或num=2返回num,其他返回2*f(n-1)
```
# -*- coding:utf-8 -*-
class Solution:
def jumpFloorII(self, number):
# write code here
if number <3 :
return number
else:
return 2*self.jumpFloorII(number-1)
```
|
C# | UTF-8 | 3,140 | 2.546875 | 3 | [] | no_license | using MobileSchoolAPI.Models;
using MobileSchoolAPI.ParamModel;
using MobileSchoolAPI.ResultModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MobileSchoolAPI.BusinessLayer
{
public class GetExamScheduleBL
{
public object GetExamSchedule(ParamExamSchedule OBJ)
{
try
{
SchoolMainContext db = new ConcreateContext().GetContext(OBJ.USERID, OBJ.PASSWORD);
if (db == null)
{
return new Results() { IsSuccess = false, Message = "Invalid User" };
}
var AcadamicYear = db.View_GETACADEMICYEAR.FirstOrDefault();
if (AcadamicYear == null)
{
return new Results
{
IsSuccess = false,
Message = "Not Found Academic Year"
};
}
var result = db.VW_EXAMSCHEDULE.Where(r=>r.STANDARDID.Contains(""+OBJ.STANDARDID+"") && r.TESTTYPEID==OBJ.TESTID && r.ACADEMICYEAR==AcadamicYear.ACADEMICYEAR ).ToList();
if(result.Count==0)
{
return new InvalidUser() { IsSuccess = false, Result = "Record Not Found" };
}
List<examclass> Details = new List<examclass>();
for (int i = 0; i < result.Count; i++)
{
string[] std = result[i].STANDARDID.Split(',');
int count = 0;
for (int j = 0; j < std.Length; j++)
{
if (std[j] == OBJ.STANDARDID)
{
count = j;
}
}
string[] sub = result[i].SUBJECTID.Split(',');
int subid = int.Parse(sub[count]);
var subname = db.VIEWSUBJECTNAMEs.Where(r => r.SUBJECTID == subid).SingleOrDefault();
int testid =int.Parse(result[i].TESTTYPEID.ToString());
var testname = db.VW_UNITMASTER.Where(r => r.UNITID == testid).SingleOrDefault();
Details.Add(new examclass
{
Subject = subname.SUBJECTNAME,
Test= testname.TESTNAME,
ExamDate=result[i].EXAMDATE,
ExamTime=result[i].EXAMTIME
});
}
return new InvalidUser() { IsSuccess = true, Result = Details.ToArray() };
}
catch(Exception ex)
{
return new Results
{
IsSuccess = false,
Message = ex.Message
};
}
}
public class examclass
{
public string Subject { get; set; }
public string Test { get; set; }
public string ExamDate { get; set; }
public string ExamTime { get; set; }
}
}
} |
C | UTF-8 | 1,176 | 3.109375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <os2.h>
/*
declare the assembler function as 16 bit
*/
VOID _THUNK_FUNCTION (TEST) (ULONG);
/*
build an interface between the calling programm and the thunk function
*/
USHORT fill_array(ULONG i)
{
return((USHORT)
(_THUNK_PROLOG(4);
_THUNK_FAR16(i);
_THUNK_CALL(TEST)));
}
int main( void )
{
ULONG i=0;
USHORT j=1;
SHORT *t;
FILE *ergfile;
/*
allocate the memory, where the assembler routine will write to
*/
printf("\nallocating 1,048,577 short integers...");
t = (SHORT*)calloc(1048577,sizeof(SHORT));
printf("done.\n\n");
/*
convert the flat pointer to 16bit format..
*/
i = _emx_32to16(t);
/*
...and call the routine
*/
printf("calling IOPL routine to fill array...");
j = fill_array(i);
printf("done.\n\n");
/*
write some data points to a file, so we can see that it works
*/
printf("writing every 64th datapoint to file...");
ergfile = fopen("test.dat","w");
for(i=0;i<1048577;i++)
if( !(i%64)) fprintf(ergfile,"array[%6d]=%6d\n",i,t[i]);
close(ergfile);
printf("done.\n");
/*
free the allocated memory
*/
free(t);
}
|
PHP | UTF-8 | 2,246 | 2.65625 | 3 | [
"ISC"
] | permissive | <?php
/**
* Class WPXRPINFO_Ledger
* Contains code by Jesper Wallin (WooCommerce XRP Plugin https://github.com/empatogen/woocommerce-xrp)
*/
class WPXRPINFO_Ledger
{
private $node = false;
private $headers = [];
/**
* Ledger constructor.
* @param $node
* @param $proxy
*/
function __construct($node, $proxy=null)
{
if (empty($node)) {
$node = 'https://s2.ripple.com:51234';
}
if ($proxy === 'yes') {
$this->node = 'https://cors-anywhere.herokuapp.com/' . $node;
$this->headers = ['origin' => get_site_url()];
} else {
$this->node = $node;
}
}
/**
* Send an account_tx request to the specify rippled node.
* @param $account
* @param $limit
* @return bool|object
*/
function account_tx($account, $limit = 10)
{
$payload = json_encode([
'method' => 'account_tx',
'params' => [[
'account' => $account,
'ledger_index_min' => -1,
'ledger_index_max' => -1,
'limit' => $limit,
]]
]);
$res = wp_remote_post($this->node, [
'body' => $payload,
'headers' => $this->headers
]);
if (is_wp_error($res) || $res['response']['code'] !== 200) {
return false;
}
if (($data = json_decode($res['body'])) === null) {
return false;
}
return $data->result->transactions;
}
/**
* Send an account_info request to the specify rippled node.
* @param $account
* @return bool
*/
function account_info($account)
{
$payload = json_encode([
'method' => 'account_info',
'params' => [[
'account' => $account
]]
]);
$res = wp_remote_post($this->node, [
'body' => $payload,
'headers' => $this->headers
]);
if (is_wp_error($res) || $res['response']['code'] !== 200) {
return false;
}
if (($data = json_decode($res['body'])) === null) {
return false;
}
return $data->result;
}
}
|
Ruby | UTF-8 | 131 | 3.375 | 3 | [] | no_license | puts "計算をはじめます"
puts "2つの値を入力してください"
a = gets.to_i
b = gets.to_i
puts "a * b = #{a * b}" |
Markdown | UTF-8 | 671 | 2.734375 | 3 | [
"MIT"
] | permissive | ###LPF
A 24db per octave resonant filter.
Example:
```javascript
d = XOX( 'x*o*x*o-' )
l = LPF()
l.cutoff = Add( .4, Sine(.2, .3)._ )
l.resonance = 4
d.fx.add( d )
```
#### Properties
* _cutoff_ : Default range: { 0, 1 }. Float. The cutoff frequency for the filter measured from 0 to 1 where 1 is nyquist. In practice, values above .75 or so seem unstable.
* _resonance_ : Default range: { 0, 5.5 }. The amount of emphasis placed on the frequencies surrounding the cutoff. This can cause the filter to blow up at values above 5.5, but can also introduce pleasing distortion at high values in certain situations. Be careful!
#### Methods
None worth mentioning.
|
Markdown | UTF-8 | 1,514 | 2.796875 | 3 | [
"MIT"
] | permissive | ---
title: "Las cosas pequeñas importan"
date: 2020-05-17
author: arthur
tags: [principio]
description: Uno de los principios fundamentales en el desarrollo de software que aparecen incluso en la vida misma
---
Si alguna vez escuchaste las frases: "Dios está en los detalles" o "La honestidad en las cosas pequeñas no es una cosa pequeña", entonces te has topado con este principio.
Uno de esos que es aplicable en todas partes e incluso en el desarrollo de software.
## En el software
En el desarrollo de software es un principio que aparecen muy frecuente en muchas prácticas y métodos de desarrollo de software. Es la premisa de la refactorizacion: pequeños cambios en el código hacen un gran impacto, es la premisa de la Integracion Continua (CI): integrar muy frecuentemente pequeños cambios disminuye el riesgo de una integración, y de igual manera de Continous Delivery (CD), Agile, entre muchas otras...
...pero ¿porque es importante?
## La razón de ser
Alguna vez no te haz molestado por tener una cañeria 🚰 que no cierra bien? o el no poder cerrar bien una puerta, tener que hacerle "trucos" para cerrarla bien? o dormir en una cama que no es comoda? ...son cosas pequeñas que nos pasan a cada día, pero si suceden a menudo, frecuentemente, pueden llegar a romper la armonia [1].
Es decir, las cosas pequeñas pueden tener un impacto menor, pero la acumulación y frecuencia de cosas pequeñas puede dar un efecto a gran escala.
## Referencias:
1. Clean Code, Robert C. Martin, pp. xix
|
Java | UTF-8 | 5,016 | 2.546875 | 3 | [] | no_license | package com.sample.demo.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* @author sskim
*/
@Slf4j
@Controller
public class UploadController {
//todo 서버업로드 경로 설정
public static final String UPLOAD_FOLDER = "/Users/sskim/Documents/ckeditor/";
/**
* cKeditor 이미지 서버에 전송
*/
@RequestMapping({"/image/upload", "image/drag"})
public void imageUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile upload) throws Exception {
// 랜덤 문자 생성
UUID uid = UUID.randomUUID();
OutputStream out = null;
PrintWriter printWriter = null;
//인코딩
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
try {
//파일 이름 가져오기
String fileName = upload.getOriginalFilename();
byte[] bytes = upload.getBytes();
//이미지 경로 생성
String uploadFolder = UPLOAD_FOLDER;
String uploadFolderPath = getFolder();
//make folder
File uploadPath = new File(uploadFolder, uploadFolderPath);
log.info("uploadPath = " + uploadPath);
if (!uploadPath.exists()) {
uploadPath.mkdirs();
}
String ckUploadFileName = uid + "_" + fileName;
out = new FileOutputStream(new File(uploadPath, ckUploadFileName));
out.write(bytes);
out.flush(); // outputStram에 저장된 데이터를 전송하고 초기화
String callback = request.getParameter("CKEditorFuncNum");
printWriter = response.getWriter();
String fileUrl = "/image/ckUploadResult?uid=" + uid + "&fileName=" + fileName + "®Date=" + getFolder(); // 작성화면
// 업로드시 메시지 출력
printWriter.println("{\"filename\" : \"" + fileName + "\", \"uploaded\" : 1, \"url\":\"" + fileUrl + "\"}");
printWriter.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (printWriter != null) {
printWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return;
}
/**
* cKeditor 서버로 전송된 이미지 뿌려주기
*/
@RequestMapping(value = "/image/ckUploadResult")
public void ckSubmit(@RequestParam(value = "uid") String uid,
@RequestParam(value = "fileName") String fileName,
@RequestParam(value = "regDate") String regDate,
HttpServletResponse response) throws IOException {
//서버에 저장된 이미지 경로
String uploadFolder = UPLOAD_FOLDER;
String ckUploadFileName = uid + "_" + fileName;
File imgFile = new File(uploadFolder + regDate, ckUploadFileName);
log.info("imgFile = " + imgFile);
//사진 이미지 찾지 못하는 경우 예외처리로 빈 이미지 파일을 설정한다.
if (imgFile.isFile()) {
byte[] buf = new byte[1024];
int readByte = 0;
int length = 0;
byte[] imgBuf = null;
FileInputStream fileInputStream = null;
ByteArrayOutputStream outputStream = null;
ServletOutputStream out = null;
try {
fileInputStream = new FileInputStream(imgFile);
outputStream = new ByteArrayOutputStream();
out = response.getOutputStream();
while ((readByte = fileInputStream.read(buf)) != -1) {
outputStream.write(buf, 0, readByte);
}
imgBuf = outputStream.toByteArray();
length = imgBuf.length;
out.write(imgBuf, 0, length);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
outputStream.close();
fileInputStream.close();
out.close();
}
}
}
/**
* 폴더 생성 메서드
*
* @return
*/
private String getFolder() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String str = sdf.format(date);
return str.replace("-", File.separator);
}
}
|
PHP | UTF-8 | 2,293 | 3.5 | 4 | [
"MIT"
] | permissive | <?php
namespace Brick\Html;
/**
* Represents an HTML tag.
*/
abstract class Tag
{
/**
* The tag name.
*
* @var string
*/
protected $name;
/**
* The tag attributes as an associative array.
*
* @var array
*/
protected $attributes;
/**
* Class constructor.
*
* @param string $name
* @param array $attributes
*/
public function __construct($name, array $attributes = [])
{
$this->name = $name;
$this->attributes = $attributes;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return array
*/
public function getAttributes()
{
return $this->attributes;
}
/**
* @param string $name
*
* @return boolean
*/
public function hasAttribute($name)
{
return isset($this->attributes[$name]);
}
/**
* @param string $name
*
* @return string|null
*/
public function getAttribute($name)
{
return isset($this->attributes[$name]) ? $this->attributes[$name] : null;
}
/**
* @param string $name
* @param string $value
*
* @return static
*/
public function setAttribute($name, $value)
{
$this->attributes[$name] = $value;
return $this;
}
/**
* @param array $attributes
*
* @return static
*/
public function setAttributes(array $attributes)
{
$this->attributes = $attributes + $this->attributes;
return $this;
}
/**
* @param string $name
*
* @return static
*/
public function removeAttribute($name)
{
unset($this->attributes[$name]);
return $this;
}
/**
* @return string
*/
protected function renderAttributes()
{
$result = '';
foreach ($this->attributes as $name => $value) {
$result .= sprintf(' %s="%s"', $name, htmlspecialchars($value));
}
return $result;
}
/**
* @return string
*/
abstract public function render();
/**
* @return string
*/
public function __toString()
{
return $this->render();
}
}
|
Java | UTF-8 | 977 | 3.375 | 3 | [
"MIT"
] | permissive | package interview.tree;
public class TreeCreator {
public TreeNode createSampleTree() {
TreeNode root = new TreeNode('A');
root.setLeft(new TreeNode('B'));
root.getLeft().setLeft(new TreeNode('D'));
root.getLeft().setRight(new TreeNode('E'));
root.getLeft().getRight().setLeft(new TreeNode('G'));
root.setRight(new TreeNode('C'));
root.getRight().setRight(new TreeNode('F'));
return root;
}
public TreeNode createTree(String preOrder, String inOrder) {
if (preOrder.isEmpty()) {
return null;
}
char rootValue = preOrder.charAt(0);
int rootIndex = inOrder.indexOf(rootValue);
TreeNode root = new TreeNode(rootValue);
root.setLeft(
createTree(
preOrder.substring(1, 1 + rootIndex),
inOrder.substring(0, rootIndex)));
root.setRight(
createTree(
preOrder.substring(1 + rootIndex),
inOrder.substring(1 + rootIndex)));
return root;
}
}
|
C++ | UTF-8 | 1,608 | 2.53125 | 3 | [] | no_license | #include "quadrangle.h"
Quadrangle::Quadrangle(QVector3D p1, QVector3D p2, QVector3D p3, QVector3D p4):
point1(p1), point2(p2), point3(p3), point4(p4), t1(p1, p2, p3), t2(p3, p4, p1)
{
box.x_max = max({point1.x(), point2.x(), point3.x(), point4.x()});
box.x_min = min({point1.x(), point2.x(), point3.x(), point4.x()});
box.y_max = max({point1.y(), point2.y(), point3.y(), point4.y()});
box.y_min = min({point1.y(), point2.y(), point3.y(), point4.y()});
box.z_max = max({point1.z(), point2.z(), point3.z(), point4.z()});
box.z_min = min({point1.z(), point2.z(), point3.z(), point4.z()});
}
vector<QVector3D> Quadrangle::getPoints(){
return {point1, point2, point3, point4};
}
bool Quadrangle::isShadowing(QVector3D from, QVector3D to){
return t1.isShadowing(from, to) || t2.isShadowing(from, to);
}
intersection_data Quadrangle::intersect(beam &beam, bool &isIntersected){
bool ii1;
intersection_data out = t1.intersect(beam, ii1);
if (ii1){
isIntersected = ii1;
out.diff_refl = diff_refl;
out.mirror_refl = mirror_refl;
out.blinn_power = blinn_power;
return out;
} else {
out = t2.intersect(beam, isIntersected);
out.diff_refl = diff_refl;
out.mirror_refl = mirror_refl;
out.blinn_power = blinn_power;
return out;
}
}
vector<pair<QVector3D, QVector3D>> Quadrangle::getSegments(){
return {
{point1, point2},
{point2, point3},
{point3, point4},
{point4, point1}
};
}
gabarite_box Quadrangle::getGabariteBox(){
return box;
}
|
C# | UTF-8 | 1,483 | 3.359375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using System.Linq;
using Algorithms.Code;
namespace Algorithms.Tests.Code
{
public class RecursionTests
{
[Theory]
[InlineData(5, 0)]
[InlineData(2, -2)]
[InlineData(0, 0)]
[InlineData(-2, 0)]
public void Countdown(int from, int to)
{
var recursionService = new Recursion();
var resultActual = recursionService.Countdown(from, to);
if(from <= to)
{
Assert.Equal(from.ToString(), resultActual);
}
else
{
var list = new List<int>();
for(var i = from; i >= to; i--)
list.Add(i);
Assert.Equal(string.Join(' ', list), resultActual);
}
}
[Theory]
[InlineData(-3)]
[InlineData(1)]
[InlineData(5)]
public void GetFactorial(int x)
{
var recursion = new Recursion();
var resultActual = recursion.GetFactorial(x);
if (x <= 1)
Assert.Equal(1, resultActual);
else
{
var resultExpected = 1;
while (x > 1)
{
resultExpected *= x;
x--;
}
Assert.Equal(resultExpected, resultActual);
}
}
}
}
|
Rust | UTF-8 | 13,117 | 2.65625 | 3 | [] | no_license | use std::net::{TcpStream, UdpSocket, ToSocketAddrs};
use std::fs::File;
use std::io::Read;
use std::io::Write;
use byteorder::{NetworkEndian, LittleEndian, ByteOrder};
use std::str;
extern crate get_if_addrs;
extern crate resolve;
extern crate byteorder;
extern crate bytes;
extern crate minilzo;
#[derive(Copy, Clone,Debug)]
pub enum MsgType
{
End = 67,
GetCS = 71,
CompileFile = 73,
FileChunk = 74,
Login = 80,
Stats = 81,
EnvTransfer = 88,
VerifyEnv = 93,
}
pub struct Msg
{
msgtype: MsgType,
data: Vec<u8>,
}
impl Msg
{
pub fn new(msgtype: MsgType) -> Msg
{
Msg{
msgtype: msgtype,
data: Vec::new()
}
}
pub fn append_u32(&mut self, val: u32)
{
let mut buf = [0 ; 4 ];
NetworkEndian::write_u32(&mut buf, val);
self.data.extend_from_slice(&buf);
}
pub fn append_str(&mut self, s: &str)
{
self.append_u32((s.len() + 1) as u32);
self.data.extend_from_slice(s.as_bytes());
self.data.push(0);
}
pub fn append_envs(&mut self, envs: Vec<(&str, &str)>)
{
self.append_u32(envs.len() as u32);
for env in envs {
self.append_str(env.0);
self.append_str(env.1);
}
}
pub fn len(&self) -> usize
{
self.data.len() + 4
}
}
pub struct MsgChannel
{
pub stream :TcpStream,
pub protocol :u32,
}
impl MsgChannel
{
pub fn new<A: ToSocketAddrs>(addr: A) -> MsgChannel
{
let mut sock = TcpStream::connect(addr).expect("connect");
let protobuf = [35, 0, 0, 0];
sock.write(&protobuf).expect("write proto");
// Get the maximum protocol version we have in common with the scheduler or daemon.
let proto = read_u32le(&mut sock);
println!("proto version {}", proto);
let protobuf = [proto as u8, 0, 0, 0];
sock.write(&protobuf).expect("write proto");
let proto = read_u32le(&mut sock);
println!("proto version {}", proto);
MsgChannel{
stream: sock,
protocol: proto
}
}
}
pub fn send_msg<W: Write>(mut sock: W, msg: &Msg)
{
assert!(msg.len() < 1000000);
let len = [0, (msg.len() >> 16) as u8, (msg.len() >> 8) as u8, msg.len() as u8]; // fix me
sock.write(&len).expect("writing length");;
let typebuf = [0, 0, (msg.msgtype as u16 >> 8) as u8, msg.msgtype as u8];
sock.write(&typebuf).expect("write type");
let write_len = sock.write(msg.data.as_slice()).expect("write");
println!("sent packet type {:?} length {}", msg.msgtype, write_len);
}
fn send_file(sock: &TcpStream, path: &str)
{
let mut f = File::open(path).expect("open");
let mut buf: Vec<u8> = Vec::new();
let _ = f.read_to_end(&mut buf).expect("read file");
for chunk in buf.chunks(100000) {
let mut fcmsg = Msg::new(MsgType::FileChunk);
fcmsg.append_u32(chunk.len() as u32);
let mut compressed = minilzo::compress(chunk).expect("compression");
fcmsg.append_u32(compressed.len() as u32);
fcmsg.data.append(&mut compressed);
send_msg(sock, &fcmsg);
}
}
fn read_u32le(mut sock: &TcpStream) -> u32
{
let mut buf = [0; 4];
let ret = sock.read(&mut buf).expect("read 4");
assert!(ret == 4);
let val: u32 = buf[0] as u32 | (buf[1] as u32) << 8 | (buf[2] as u32) << 16 | (buf[3] as u32) << 24;
val
}
fn read_u32be(mut sock: &TcpStream) -> u32
{
let mut buf = [0; 4];
let ret = sock.read(&mut buf).expect("read 4");
assert!(ret == 4);
let val: u32 = buf[3] as u32 | (buf[2] as u32) << 8 | (buf[1] as u32) << 16 | (buf[0] as u32) << 24;
val
}
fn read_string(buf: &mut bytes::BytesMut) -> String
{
let len = NetworkEndian::read_u32(&buf.split_to(4)) as usize;
assert!(len > 0);
let str_data = buf.split_to(len);
// get rid of '\0'
buf.truncate(len - 1);
String::from(str::from_utf8(&str_data).expect("valid string"))
}
pub fn send_compile_file_msg(stream: &mut MsgChannel, job_id :u32)
{
let mut msg = Msg::new(MsgType::CompileFile);
msg.append_u32(0); // language of source
msg.append_u32(job_id);
msg.append_u32(0); // remote flags
msg.append_u32(0); // rest flags
msg.append_str("foo.tar.gz"); // environment
msg.append_str("x86_64"); // target platform
msg.append_str("gcc"); // compiler name
if stream.protocol >= 34 {
msg.append_str("bar.c"); // input file
msg.append_str("/tmp/"); // cwd
}
if stream.protocol >= 35 {
msg.append_str("bar.o"); // output file name
msg.append_u32(0); // dwo enabled
}
send_msg(&mut stream.stream, &msg);
}
pub fn get_cs(con: &mut MsgChannel, file: &str, lang: SourceLanguage)
{
let mut get_cs_msg = Msg::new(MsgType::GetCS);
// a set of (host platform, tool chain file) pairs for each platform we have a toolchain for.
// Currently we just hardcode this.
let envs = vec!(("x86_64", "foo.tar.gz"));
get_cs_msg.append_envs(envs);
// information about the file we'll compile to show to things monitoring jobs.
get_cs_msg.append_str(file);
get_cs_msg.append_u32(lang as u32);
// the number of jobs we'd like to run, this is only used by icecream when compiling a file
// multiple times which we don't do yet.
get_cs_msg.append_u32(1);
// the type of platform we would prefer the compile server be.
get_cs_msg.append_str("x86_64");
// argument flags, aparently only used in calculating speed of compile servers so unimplemented
// for now.
get_cs_msg.append_u32(0);
// client id is really a daemon id that requested a compile server allocation from the scheduler.
get_cs_msg.append_u32(53);
// preferred host is to use a particular daemon, we don't support that yet.
get_cs_msg.append_str("");
if con.protocol >= 31 {
get_cs_msg.append_u32(0);
if con.protocol >= 34 {
get_cs_msg.append_u32(0);
}
}
send_msg(&mut con.stream, &get_cs_msg);
}
pub fn run_job(host: &str, port: u32, host_platform: &str, job_id: u32, got_env: bool)
{
let mut cssock = MsgChannel::new((host, port as u16));
if !got_env {
let mut env_transfer_msg = Msg::new(MsgType::EnvTransfer);
env_transfer_msg.append_str("foo.tar.gz");
env_transfer_msg.append_str(host_platform);
send_msg(&mut cssock.stream, &env_transfer_msg);
send_file(&mut cssock.stream, "/tmp/foo.tar.gz");
send_msg(&mut cssock.stream, &Msg::new(MsgType::End));
let mut verify_msg = Msg::new(MsgType::VerifyEnv);
verify_msg.append_str("foo.tar.gz");
verify_msg.append_str("x86_64");
send_msg(&mut cssock.stream, &verify_msg);
display_msg(&mut cssock);
}
send_compile_file_msg(&mut cssock, job_id);
send_file(&mut cssock.stream, "/tmp/bar.c");
send_msg(&mut cssock.stream, &Msg::new(MsgType::End));
loop {
display_msg(&mut cssock);
}
}
pub fn display_msg(sock: &mut MsgChannel)
{
let msglen = read_u32be(&mut sock.stream);
assert!(msglen >= 4);
let mut buf = bytes::BytesMut::with_capacity(msglen as usize);
unsafe { buf.set_len(msglen as usize); }
sock.stream.read_exact(&mut buf).expect("should get a full message");
assert!(msglen as usize == buf.len());
let msgtype = NetworkEndian::read_u32(&buf.split_to(4));
println!("msg length {} type {}", msglen, msgtype);
match msgtype {
92 => {
let max_scheduler_pong = NetworkEndian::read_u32(&buf.split_to(4));
let max_scheduler_ping = NetworkEndian::read_u32(&buf.split_to(4));
let _bench_source = read_string(&mut buf);
println!("max scheduler pong {} max scheduler ping {}", max_scheduler_pong, max_scheduler_ping);
}
72 => {
//let ret = sock.read(buf.as_mut_slice()).expect("read buf");
//println!("data {:?}", buf);
let job_id = NetworkEndian::read_u32(&buf.split_to(4));
let port = NetworkEndian::read_u32(&buf.split_to(4));
let host = read_string(&mut buf);
let host_platform = read_string(&mut buf);
let got_env = NetworkEndian::read_u32(&buf.split_to(4));
let client_id = NetworkEndian::read_u32(&buf.split_to(4));
let matched_job_id = NetworkEndian::read_u32(&buf.split_to(4));
println!("job {} assigned to {}:{} platform {} got_env {} for client {} matched {}", job_id, host, port, host_platform, got_env, client_id, matched_job_id);
run_job(&host, port, &host_platform, job_id, got_env != 0);
}
94 => {
let val = NetworkEndian::read_u32(&buf.split_to(4));
println!("verification of env is {}", val);
}
75 => {
let stderr = read_string(&mut buf);
let stdout = read_string(&mut buf);
let status = NetworkEndian::read_u32(&buf.split_to(4));
let oom = NetworkEndian::read_u32(&buf.split_to(4));
println!("compile finished status {} stdout {} stderr {} oom {}", status, stdout, stderr, oom);
}
90 => {
let str = read_string(&mut buf);
println!("status text: {}", str);
}
67 => {
println!("end msg");
}
i => { println!("unmatched type {}", i) }
}
}
fn main()
{
let mut sched_sock = get_scheduler(&start_udp_discovery(), "icecc-test").unwrap();
let host_name :String = resolve::hostname::get_hostname().expect("hostname");
println!("{}", host_name);
let mut login_msg = Msg::new(MsgType::Login);
login_msg.append_u32(0); // not supporting remote connections so port 0 is fine.
login_msg.append_u32(8); // not supporting remote connections so this doesn't really matter.
login_msg.append_u32(0); // no envs.
login_msg.append_str("cat");
login_msg.append_str("x86_64");
login_msg.append_u32(0); // chroot_possible is false.
login_msg.append_u32(1); // noremote.
send_msg(&mut sched_sock.stream, &login_msg);
let mut stats_msg = Msg::new(MsgType::Stats);
stats_msg.append_u32(0);
stats_msg.append_u32(0);
stats_msg.append_u32(0);
stats_msg.append_u32(0);
send_msg(&mut sched_sock.stream, &stats_msg);
display_msg(&mut sched_sock);
let mut get_cs_msg = Msg::new(MsgType::GetCS);
let envs = vec!(("x86_64", "foo.tar.gz"));
get_cs_msg.append_envs(envs);
get_cs_msg.append_str("/tmp/test-icecc.c");
get_cs_msg.append_u32(0);
get_cs_msg.append_u32(1);
get_cs_msg.append_str("x86_64");
get_cs_msg.append_u32(0);
get_cs_msg.append_u32(53);
get_cs_msg.append_str("");
get_cs_msg.append_u32(0);
send_msg(&mut sched_sock.stream, &get_cs_msg);
loop {
display_msg(&mut sched_sock);
}
}
const MAX_PROTOCOL_VERSION : u8 = 35;
pub fn start_udp_discovery() -> UdpSocket
{
let ifaces = get_if_addrs::get_if_addrs().expect("qux");
let sock = UdpSocket::bind("0.0.0.0:0").expect("error");
sock.set_broadcast(true).expect("broadcast");
for iface in &ifaces {
if iface.is_loopback() {
continue;
}
match iface.addr {
get_if_addrs::IfAddr::V4(ref addr) => {
match addr.broadcast {
Some(ip) => {
let buf = [ MAX_PROTOCOL_VERSION ];
sock.send_to(&buf, (ip, 8765)).expect("foobar");
}
_ => ()
}
}
_ => ()
};
}
println!("sent packet");
sock
}
pub fn get_scheduler(sock: & UdpSocket, network: & str) -> Option<MsgChannel>
{
let mut sched: Option<std::net::SocketAddr>;
loop {
let mut ans = [0; 30];
let (_, s) = sock.recv_from(&mut ans).expect("read");
let mut net : String = String::new();
let version_ack = ans[0];
let mut offset = 1;
let mut sched_version = 0;
let mut sched_start = 0;
if MAX_PROTOCOL_VERSION + 2 == version_ack {
// !!! this depends on the endianness of the scheduler, assume its little endian for
// now.
sched_version = LittleEndian::read_u32(&ans[1..5]);
sched_start = LittleEndian::read_u64(&ans[5..13]);
offset += 12;
}
for x in &ans[offset..] {
if *x != 0 {
net.push(*x as char);
}
}
println!("raw: {:?}", &ans);
println!("{} {} {} {}", net, net.len(), sched_version, sched_start);
sched = Some(s);
if net == network {
break;
}
}
let sched_sock = MsgChannel::new(sched.unwrap());
sched_sock.stream.set_nodelay(true).expect("nodelay");
// sched_sock.set_nonblocking(true).expect("nonblocking");
println!("{:#?}", sched_sock.stream);
Some(sched_sock)
}
pub enum SourceLanguage
{
C = 0,
CPlusPlus = 1,
OBJC = 2,
Custom = 3,
}
|
C# | UTF-8 | 555 | 2.59375 | 3 | [] | no_license | using HomeAutomation.Models.Abstract;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HomeAutomation.Extensions
{
public static class ModelBuilderExtensions
{
public static void SeedData<T>(this ModelBuilder modelBuilder, IEnumerable<T> dataSeedCollection) where T : Entity
{
foreach (var seed in dataSeedCollection)
{
modelBuilder.Entity<T>().HasData(seed);
}
}
}
}
|
Java | UTF-8 | 874 | 3.375 | 3 | [] | no_license | import java.util.Scanner;
public class codeup_1097 {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int[][] arr = new int[19][19];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
arr[i][j] = scanner.nextInt();
}
}
int n = scanner.nextInt();
for (int i = 0; i < n; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
for (int j = 0; j < 19; j++) {
if (arr[x - 1][j] == 0) {
arr[x - 1][j] = 1;
} else {
arr[x - 1][j] = 0;
}
}
for (int j = 0; j < 19; j++) {
if (arr[j][y - 1] == 0) {
arr[j][y - 1] = 1;
} else {
arr[j][y - 1] = 0;
}
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
|
JavaScript | UTF-8 | 6,899 | 3.3125 | 3 | [] | no_license | /**
* AdaptoidBoard
* @constructor
*/
function AdaptoidBoard(scene, game, radiusOfTile, heightOfTile) {
this.scene = scene;
this.game = game;
this.radiusOfTile = radiusOfTile;
this.heightOfTile = heightOfTile;
this.widthBoard = 7 * this.radiusOfTile * 2;
this.tiles = [];
this.initTiles();
};
AdaptoidBoard.prototype.constructor = AdaptoidBoard;
AdaptoidBoard.prototype.initTiles = function() {
for (var r = 1; r <= 7; r++) {
this.tiles[r] = [];
for (var c = 1; c <= this.getNumColumnsInRow(r); c++) {
this.tiles[r][c] = new Tile(this.scene, this, r, c,
this.radiusOfTile, this.heightOfTile, [], [], []);
}
}
};
AdaptoidBoard.prototype.playerCanMoveAndCapture = function(colorPlayer) {
for (var r = 1; r <= 7; r++) {
for (var c = 1; c <= this.getNumColumnsInRow(r); c++) {
if (!this.tiles[r][c].isEmpty() &&
this.tiles[r][c].getColorOfHisPiece() === colorPlayer &&
this.tiles[r][c].getNumLegs() > 0) {
return true;
}
}
}
return false;
};
AdaptoidBoard.prototype.takeAllPieces = function() {
for (var r = 1; r <= 7; r++) {
for (var c = 1; c <= this.getNumColumnsInRow(r); c++) {
this.tiles[r][c].adaptoidBody = [];
this.tiles[r][c].adaptoidLegs = [];
this.tiles[r][c].adaptoidPincers = [];
}
}
};
AdaptoidBoard.prototype.setBodyInTile = function(body, row, collumn, color) {
var tile = this.tiles[row][collumn];
tile.setBody([body]);
body.game = this.game;
body.color = color;
};
AdaptoidBoard.prototype.setLegsInTile = function(legs, row, collumn, color) {
var tile = this.tiles[row][collumn];
tile.setLegs(legs);
for (var i = 0; i < legs.length; i++) {
legs[i].game = this.game;
legs[i].color = color;
}
};
AdaptoidBoard.prototype.setPincersInTile = function(pincers, row, collumn, color) {
var tile = this.tiles[row][collumn];
tile.setPincers(pincers);
for (var i = 0; i < pincers.length; i++) {
pincers[i].game = this.game;
pincers[i].color = color;
}
};
AdaptoidBoard.prototype.getHotspots = function() {
var hotspots = [];
for (var r = 1; r <= 7; r++) {
for (var c = 1; c <= this.getNumColumnsInRow(r); c++) {
hotspots.push(this.tiles[r][c].hotspot);
}
}
return hotspots;
};
AdaptoidBoard.prototype.display = function() {
this.scene.pushMatrix();
this.scene.translate(-this.widthBoard/2, 0, -this.widthBoard/2);
for (var r = 1; r <= 7; r++) {
for (var c = 1; c <= this.getNumColumnsInRow(r); c++) {
this.displayTile(this.tiles[r][c], r, c);
}
}
this.scene.popMatrix();
};
AdaptoidBoard.prototype.numPiecesOfAColorInBoard = function(color) {
var res = 0;
for (var r = 1; r <= 7; r++) {
for (var c = 1; c <= this.getNumColumnsInRow(r); c++) {
if (this.tiles[r][c].isEmpty() === false
&& this.tiles[r][c].getColorOfHisPiece() === color)
res++;
}
}
return res;
};
AdaptoidBoard.prototype.displayTile = function(tile, r, c) {
this.scene.pushMatrix();
var xz = this.getCoords_XZ(r, c);
this.scene.translate(xz[0], 0, xz[1]);
tile.display();
this.scene.popMatrix();
};
AdaptoidBoard.prototype.getCoords_XZ = function(r, c) {
return [this.getLeftSpaceOfRow(r) + (c - 1) * 2 * this.radiusOfTile,
this.radiusOfTile + (r - 1) * this.radiusOfTile * 2];
};
AdaptoidBoard.prototype.getRealCoords_XZ = function(r, c) {
return [this.getLeftSpaceOfRow(r) + (c - 1) * 2 * this.radiusOfTile - this.widthBoard/2,
this.radiusOfTile + (r - 1) * this.radiusOfTile * 2 - this.widthBoard/2];
};
AdaptoidBoard.prototype.getNumColumnsInRow = function(row) {
var numColumns;
switch(row) {
case 1:
case 7:
numColumns = 4;
break;
case 2:
case 6:
numColumns = 5;
break;
case 3:
case 5:
numColumns = 6;
break;
case 4:
numColumns = 7;
break;
default:
console.error("invalid row!!!");
break;
}
return numColumns;
};
AdaptoidBoard.prototype.getLeftSpaceOfRow = function(row) {
var leftSpace;
switch(row) {
case 1:
case 7:
leftSpace = 4 * this.radiusOfTile;
break;
case 2:
case 6:
leftSpace = 3 * this.radiusOfTile;
break;
case 3:
case 5:
leftSpace = 2 * this.radiusOfTile;
break;
case 4:
leftSpace = this.radiusOfTile;
break;
default:
console.error("invalid row!!!");
break;
}
return leftSpace;
};
AdaptoidBoard.prototype.getBoardInStringFormat = function() {
var boardString = "[";
for (var r = 1; r <= 7; r++) {
var rowString = "[";
for (var c = 1; c <= this.getNumColumnsInRow(r); c++) {
var pieceString;
if (this.tiles[r][c].isEmpty()) {
pieceString = "empty";
}
else {
pieceString = "[";
var color = this.tiles[r][c].getColorOfHisPiece();
color = (color === "white") ? "w" : "b";
pieceString += color + "," + this.tiles[r][c].getNumLegs().toString()
+ "," + this.tiles[r][c].getNumPincers().toString()
+ "]";
}
pieceString = (c < this.getNumColumnsInRow(r)) ? pieceString + "," : pieceString;
rowString += pieceString;
}
rowString += "]";
rowString = (r < 7) ? rowString + "," : rowString;
boardString += rowString;
}
boardString += "]";
return boardString;
};
AdaptoidBoard.prototype.getBoardInArrayFormat = function() {
var board = [];
for (var r = 1; r <= 7; r++) {
var row = [];
for (var c = 1; c <= this.getNumColumnsInRow(r); c++) {
if (this.tiles[r][c].isEmpty()) {
row.push(0);
}
else {
var color = this.tiles[r][c].getColorOfHisPiece();
color = (color === "white") ? 0 : 1;
row.push([color, this.tiles[r][c].getNumLegs(), this.tiles[r][c].getNumPincers()]);
}
}
board.push(row);
}
return board;
};
|
Python | UTF-8 | 3,090 | 2.78125 | 3 | [] | no_license | # Import dependencies
import pandas as pd
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, inspect, func
from flask import Flask, jsonify
import datetime as dt
import numpy as np
# Create engine
engine = create_engine("sqlite:///hawaii.sqlite")
# Reflect databases into ORM classes
Base = automap_base()
Base.prepare(engine, reflect=True)
#Base.classes.keys()
# Save a reference to tables
Station = Base.classes.hawaii_station
Measurement = Base.classes.hawaii_measurement
# Create session link
session = Session(engine)
# Flask setup
app = Flask(__name__)
# Flask routes
@app.route("/")
def welcome():
"""List all available api routes."""
return (
f"Avalable Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"- JSON representation of dictionary<br/>"
f"/api/v1.0/stations<br/>"
f"- JSON list of weather stations<br/>"
f"/api/v1.0/tobs<br/>"
f"- JSON list of tobs from previous year<br/>"
f"/api/v1.0/<start><br/>"
f"- JSON list of min, avg, and max temperature for a given start date<br/>"
f"/api/v1.0/<start>/<end><br/>"
f"- JSON list of min, avg, and max temperature for a given start/end range<br/>"
)
@app.route("/api/v1.0/precipitation")
def precipitation():
"""JSON representation of dictionary """
results = session.query(Measurement.date, Measurement.prcp).all()
# Convert query into dictionary
prcp_data = []
for date, prcp in results:
prcp_dict = {}
prcp_dict["date"] = date
prcp_dict["prcp"] = prcp
prcp_data.append(prcp_dict)
return jsonify(prcp_data)
@app.route("/api/v1.0/stations")
def stations():
"""JSON list of weather stations """
# Query all stations
results = session.query(Station.station).all()
stations_list = list(np.ravel(results))
return jsonify(stations_list)
@app.route("/api/v1.0/tobs")
def tobs():
"""JSON list of tobs from previous year """
# Query for all temperature observations from previous year
results = session.query(Measurement.date, Measurement.tobs).\
group_by(Measurement.date).\
filter(Measurement.date <= '2017-08-23').\
filter(Measurement.date >= '2016-08-23').all()
tobs_list = list(np.ravel(results))
return jsonify(tobs_list)
@app.route("/api/v1.0/<start>")
@app.route("/api/v1.0/<start>/<end>")
def start_end(start=None, end=None):
"""JSON list of min, avg, max for specific dates"""
sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]
if not end:
results= session.query(*sel).filter(Measurement.date >= start).all()
temps = list(np.ravel(results))
return jsonify(temps)
results = session.query(*sel).filter(Measurement.date >= start).filter(Measurement.date <= end).all()
temps2 = list(np.ravel(results))
return jsonify(temps2)
if __name__ == '__main__':
app.run() |
PHP | UTF-8 | 310 | 2.796875 | 3 | [] | no_license | <?php
namespace App\Classes;
abstract class AbstractCommand
{
protected $firstPart;
protected $secondPart;
protected $firstBlock;
protected $secondBlock;
protected $fistPartValues = ['move','pile'];
protected $secondPartValues = ['over','onto'];
protected $exitCommand = 'quit';
}
|
Markdown | UTF-8 | 8,246 | 2.9375 | 3 | [] | no_license | 一、CSS概述
CSS是Cascading Style Sheets的简称,中文称为层叠样式表,对html标签的渲染和布局
CSS 规则由两个主要的部分构成:选择器,以及一条或多条声明。

二、CSS的四种引入方式
1.行内式
行内式是在标记的style属性中设定CSS样式这种方式没有体现出CSS的优势,不推荐使用。

2.内嵌式
嵌入式是将CSS样式集中写在网页的<head></head>标签对的<style></style>标签中。

3.链接式
建一个index.css的文件存放样式,在主页面中把index.css引入。

4.导入式
将一个独立的.css文件引入HTML文件中,导入式使用CSS规则引入外部CSS文件,<style>
标记也是写在<head>标记中。使用格式 @import "index.css"

注意:
导入式会在整个网页装载完后再装载CSS文件,因此这就导致了一个问题,如果网页比较大则会儿出现先显示无样式的页面,闪烁一下之后,再出现网页的样式。这是导入式固有的一个缺陷。使用链接式时与导入式不同的是它会以网页文件主体装载前装载CSS文件,因此显示出来的网页从一开始就是带样式的效果的,它不会像导入式那样先显示无样式的网页,然后再显示有样式的网页,这是链接式的优点。所以还是推荐用链接式。。。。。。。。。。。
三、注意嵌套规则
1. 块级元素可以包含内联元素或某些块级元素,但内联元素不能包含块级元素,它只能包含其它内联元素。
2. 有几个特殊的块级元素只能包含内联元素,不能包含块级元素。如h1,h2,h3,h4,h5,h6,p,dt
3. li内可以包含div
4. 块级元素与块级元素并列、内联元素与内联元素并列。
五、CSS选择器
1.基础选择器

“选择器”指明了{}中的“样式”的作用对象,也就是"样式"作用与网页中的哪些元素
1.通用元素选择器 *: 所有的标签都变色
2.标签选择器:匹配所有使用p标签的样式 p{color:red}
3.id选择器:匹配指定的标签 #p2{color:red}
4.class类选择器:谁指定class谁的变色,可选多个 .c1{color:red} 或者 div.c1{color:red}
# #注意
可以对块级标签设置长宽
不可以对内联标签设长宽(它只会根据他的文字大小来变)
2.组合选择器
1.后代选择器 (不分层级,只让p标签变色) .c2 p{color:red}
2.子代选择器(只在儿子层找) .c2>p{color:red}
3.多元素选择器:同时匹配所有指定的元素 .div,p{color:red} 或者
.c2 .c3,.c2~.c3{
color: red;
background-color: green;
font-size: 15px;
}
```
不常用
3.毗邻选择器(紧挨着,找相邻的,只找下面的,不找上面的).c2+p{color:red}
4.兄弟选择器:同一级别的,离得很近的.c2~p{color:red}
5.多元素选择器: .c2 .c3,.c2~ .c3{ color:red }
```
3.属性选择器
1. E[att] 匹配所有具有att属性的E元素,不考虑它的值。(注意:E在此处可以省略。 ) 比如“[cheacked]”。以下同。) p[title] { color:#f00; }
2.E[att=val] 匹配所有att属性等于“val”的E元素 div[class=”error”] { color:#f00; }
3.E[att~=val] 匹配所有att属性具有多个空格分隔的值、其中一个值等于“val”的E元素 td[class~=”name”] { color:#f00; }
4.E[attr^=val] 匹配属性值以指定值开头的每个元素 div[class^="test"]{background:#ffff00;}
5.E[attr$=val] 匹配属性值以指定值结尾的每个元素 div[class$="test"]{background:#ffff00;}
6.E[attr\*=val] 匹配属性值中包含指定值的每个元素 div[class*="test"]{background:#ffff00;}
4.伪类
anchor伪类:专用于控制链接的显示效果
```
a:link(没有接触过的链接),用于定义了链接的常规状态。
a:hover(鼠标放在链接上的状态),用于产生视觉效果。
a:visited(访问过的链接),用于阅读文章,能清楚的判断已经访问过的链接。
a:active(在链接上按下鼠标时的状态),用于表现鼠标按下时的链接状态。
伪类选择器 : 伪类指的是标签的不同状态:
a ==> 点过状态 没有点过的状态 鼠标悬浮状态 激活状态
a:link {color: #FF0000} /* 未访问的链接 */
a:visited {color: #00FF00} /* 已访问的链接 */
a:hover {color: #FF00FF} /* 鼠标移动到链接上 */
a:active {color: #0000FF} /* 选定的链接 */ 格式: 标签:伪类名称{ css代码; }
```
**before after**伪类
```
:before p:before 在每个<p>元素之前插入内容
:after p:after 在每个<p>元素之后插入内容
例:p:before{content:"hello";color:red;display: block;}
```
5.CSS优先级和继承
css的继承
继承是CSS的一个主要特征,它是依赖于祖先-后代的关系的。继承是一种机制,它允许样式不仅可以应用于某个特定的元素,还可以应用于它的后代。例如一个BODY定义了的颜色值也会应用到段落的文本中。
```
body{color:red;} <p>helloyuan</p>
```
### 这段文字都继承了由body {color:red;}样式定义的颜色。然而CSS继承性的权重是非常低的,是比普通元素的权重还要低的0。
```
p{color:green}
```
发现只需要给加个颜色值就能覆盖掉它继承的样式颜色。由此可见:任何显示申明的规则都可以覆盖其继承样式。
此外,继承是CSS重要的一部分,我们甚至不用去考虑它为什么能够这样,但CSS继承也是有限制的。有一些属性不能被继承,如:border, margin, padding, background等。
```
div{
border:1px solid #222
}
<div>hello <p>wzy</p> </div>
```
### c*ss的优先级*
所谓CSS优先级,即是指CSS样式在浏览器中被解析的先后顺序。
样式表中的特殊性描述了不同规则的相对权重,它的基本规则是:
1 内联样式表的权值最高 style=""------------1000;
2 统计选择符中的ID属性个数。 #id --------------100
3 统计选择符中的CLASS属性个数。 .class -------------10
4 统计选择符中的HTML标签名个数。 p ---------------1
按这些规则将数字符串逐位相加,就得到最终的权重,然后在比较取舍时按照从左到右的顺序逐位比较。
```
1、文内的样式优先级为1,0,0,0,所以始终高于外部定义。
2、有!important声明的规则高于一切。
3、如果!important声明冲突,则比较优先权。
4、如果优先权一样,则按照在源码中出现的顺序决定,后来者居上。
5、由继承而得到的样式没有specificity的计算,它低于一切其它规则(比如全局选择符*定义的规则)。
```
|
C++ | UTF-8 | 418 | 2.609375 | 3 | [] | no_license | #pragma once
#include "Edge.h"
namespace DataStructures
{
class EdgeList
{
public:
EdgeList(Vertex* root);
~EdgeList();
bool MatchesKey(int key);
Vertex* GetRoot();
void AddEdge(Edge* newEdge);
std::list<Edge*> GetEdges();
private:
bool ValidateEdge(int newEdgeVal);
private:
std::pair<Vertex*, std::list<Edge*>> m_edges;
};
} |
Markdown | UTF-8 | 1,890 | 2.625 | 3 | [
"MIT"
] | permissive | # BSplineImgInterp
Image Interpolation mex file for matlab allowing 2nd to 9th order BSplines.
This is a simple wrapper use the excellent image interpolation code provided by P. Thevenaz on http://bigwww.epfl.ch/thevenaz/interpolation/interpolation.html. The file BSplineImgInterp.c can be compiled using the matlab mex function to create the matlab function BSplineImgInterp.
The original author provides three versions of the code, one for MAC, Unix and PC. I've only tested the MAC version. BSplineImgInterp.c includes the code from the lib directory. This way, different versions can easily be interchanged by renaming lib_MAC, lib_UNIX or lib_PC to lib.
## Matlab usage:
```matlab
% g = ImgInterpBSpline(f,pos,SplineDegree,MirrorFlag,Tol)
% Inputs:
% f : input image (single)
% pos : [N x 2] list of interpolation coordinates (double)
% SplineDegree* : default=3, one of [2,3,4,5,6,7,8,9] (double)
% MirrorFlag* : default=true, extrapolate outside of the image by mirroring
% Tol* : default=1e-9, tolerance used when computing the coefficients
% Outputs:
% g : interpolated values of f on pos (single)
% c* : BSpline coefficient image (single)
% * in/outputs marked with an asterisk are optional
```
## Copyright:
This code is using the MIT licence. The original code provided by P. Thevenaz is provided with this repo with the permision of the author, provided that the following message remains with this code:
This C program is based on the following paper:
P. Thevenaz, T. Blu, M. Unser, "Interpolation Revisited,"
IEEE Transactions on Medical Imaging,
vol. 19, no. 7, pp. 739-758, July 2000.
EPFL makes no warranties of any kind on this software and shall in no event
be liable for damages of any kind in connection with the use and
exploitation of this technology.
|
Python | UTF-8 | 2,584 | 2.890625 | 3 | [] | no_license | '''
Injury Data from http://nhlinjuryviz.blogspot.ca/p/index-page.html
'''
import pandas as pd
import re
# TODO: Get victim's team
inj = pd.read_csv('NHL_Injuries.csv')
# TODO: Change this CSV to the new stats one
dops = pd.read_csv('Scrubbed_CSV.csv', encoding='latin1')
def reformat_season_year(row):
'''
Uses regex to parse the starting year of the season
'''
year = re.compile(r'''
([2][0]\d{2})
''', re.VERBOSE)
return int(re.search(year, row).group(1))
inj['start_year'] = inj['Season'].apply(reformat_season_year)
# Eliminate the injuries that are not caused by things players get
# suspended for.
elim_injs = ['Pneumonia', 'Thyroid', 'Migraine', 'Blood clots',
'Sinus', 'Stomach', 'Bronchitis', 'Vertigo', 'Heart',
'Dizziness', 'Appendectomy', 'Fatigue', 'Illness', 'Flu']
inj = inj[-inj['Injury Type'].isin(elim_injs)]
victim_names = dops['victim'].unique()
#victim_names = victim_names[victim_names != 'No Player Victim']
vic_set = set(dops['vic_last_name'])
inj_set = set(inj['Player'])
intersect = inj_set.intersection(vic_set)
#intersect = set(['Zucker'])
# See how many injuries and suspension year match up
inj_connect = pd.DataFrame(columns=['victim', 'date', 'games_missed',
'inj_type', 'susp_act'])
# TODO: Multiple injuries in a year should appear as separate lines
# TODO: Maybe get victim's team first
# USE df[(df['x'] == 'a') & (df['y'] == 'b')]!!!
for player in intersect:
dops_df = dops[dops['vic_last_name'] == player]
inj_df = inj[inj['Player'] == player]
new_year_months = [1,2,3,4,5,6,7]
for index, row in dops_df.iterrows():
off_year = row['off_year']
if row['off_month'] in new_year_months:
off_year -= 1
if off_year in inj_df['start_year'].values:
inj_year = inj_df[inj_df['start_year'] == off_year]
#print(inj_year)
victim = row['vic_last_name']
date = row['off_date']
print(date)
g_miss = inj_year['Games Missed']
print(g_miss)
inj_type = inj_year['Injury Type']
susp_act = row['offense_cat']
inj_connect.loc[len(inj_susp_connect)] = [victim, date,
g_miss, inj_type, susp_act]
break
print(len(inj_susp_connect))
|
Markdown | UTF-8 | 1,026 | 2.78125 | 3 | [] | no_license | Joshua Renewed the Covenant 15-13
===================================
**When Joshua was an old man**, he called all the people of **Israel**
together. Then Joshua reminded the people of their obligation to
**obey** the **covenant** that **God** had made with the **Israelites**
at **Sinai**. The people **promised** to **remain faithful to God**
and **follow his laws**.
*A Bible story from: Joshua 1-24*
Translation Notes:
------------------
- **When Joshua was an old man** – It may be clearer to say, “Many
years later, when Joshua was an old man.” Joshua was over 100
years old at this time.
- **remain faithful to God** - In other words, they would be loyal to
God. They would worship and serve only God; they would not worship
or serve any other gods.
- **follow his laws** - This means that the people would obey the laws
that God had given them already as part of the covenant.
- *A Bible story from* - These references may be slightly different in
some Bible translations.
|
Java | UTF-8 | 1,471 | 2.296875 | 2 | [] | no_license | package nl.Programit.urenregistratieModel1;
import java.util.Date;
public abstract class Persoon {
private String voorNaam;
private String achterNaam;
private String straatNaam;
private String postCode;
private String woonPlaats;
private int huisNummer;
private Date geboorteDatum;
private String rekeningNummer;
public String getVoorNaam() {
return voorNaam;
}
public void setVoorNaam(String voorNaam) {
this.voorNaam = voorNaam;
}
public String getAchterNaam() {
return achterNaam;
}
public void setAchterNaam(String achterNaam) {
this.achterNaam = achterNaam;
}
public String getStraatNaam() {
return straatNaam;
}
public void setStraatNaam(String straatNaam) {
this.straatNaam = straatNaam;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getWoonPlaats() {
return woonPlaats;
}
public void setWoonPlaats(String woonPlaats) {
this.woonPlaats = woonPlaats;
}
public int getHuisNummer() {
return huisNummer;
}
public void setHuisNummer(int huisNummer) {
this.huisNummer = huisNummer;
}
public Date getGeboorteDatum() {
return geboorteDatum;
}
public void setGeboorteDatum(Date geboorteDatum) {
this.geboorteDatum = geboorteDatum;
}
public String getRekeningNummer() {
return rekeningNummer;
}
public void setRekeningNummer(String rekeningNummer) {
this.rekeningNummer = rekeningNummer;
}
} |
Java | UTF-8 | 682 | 3.296875 | 3 | [] | no_license | package com.question.eg029;
public class ReverseLinkedListUsingIterativeApproachTester {
public static void main(String args[]) {
LinkedList list = new LinkedList();
Node head = new Node(1);
list.insertAtEnd(head);
list.insertAtEnd(new Node(2));
list.insertAtEnd(new Node(3));
list.insertAtEnd(new Node(4));
list.insertAtEnd(new Node(5));
// list.insertAtStart(25);
// list.insertAt(0, 55);
// list.deleteAt(2);
// list.deleteAt(3);
System.out.println("Before Reverse : ");
list.printLinkedList();
System.out.println("After Reverse : ");
Node reverseHead = list.reverseLinkedListUsingIterativeApproach(head);
list.printLinkedList(reverseHead);
}
} |
Java | UTF-8 | 343 | 2.671875 | 3 | [] | no_license | package com.javaguru.lesson4;
import java.util.Random;
public class NumberUtils {
public static int getRandomNumber(){
Random random = new Random();
return random.nextInt(101);
}
public static int getRandomNumber(int bound) {
Random random = new Random();
return random.nextInt(bound);
}
}
|
C++ | UTF-8 | 2,740 | 2.75 | 3 | [] | no_license | /******************************************************************************/
#ifndef _UTILITY_H_
#define _UTILITY_H_
/******************************************************************************/
/******************************************************************************/
namespace MG {
public ref class Utility
{
public:
static bool isIntegral(System::String ^ str);
static WCHAR * convertStringToBSTR(System::String ^ str);
static int convertStringToInt(System::String ^ str);
static double convertStringToDouble(System::String ^ str);
static DWORD convertStringToDWORD(System::String ^ str);
static ULONGLONG convertStringToULONGLONG(System::String ^ str);
static System::String ^ convertConstAnsiToString(const char * c);
static System::String ^ convertConstBSTRToString(const wchar_t * c);
static System::String ^ convertAnsiToString(char * c);
static System::String ^ convertBSTRToString(wchar_t * c);
static System::String ^ convertIntToString(int src);
static System::String ^ convertULongToString(DWORD src);
static System::String ^ convertULONGLONGToString(ULONGLONG src);
static System::String ^ convertTimeToString(time_t src);
static time_t convertDateToTime_t(System::DateTime dt,int hour,int minute);
static System::DateTime convertTime_tToDateTime(time_t time);
static System::DateTime convertTimeToDateTime(WORD hour, WORD minute, WORD second);
static System::String ^ getNowTime();
static void copyStringToAnsi(char * dest, int destSize, System::String ^ src);
static CHAR * getPCharCopyFromString(System::String ^ str);
static void freePCharCopyFromString(CHAR *cr);
static void showErrorMessage(System::String ^ str);
static void showWarningMessage(System::String ^ str);
static void showHintMessage(System::String ^ str);
};
struct StringToChar
{
public:
StringToChar(System::String ^ str)
{
str_char = Utility::getPCharCopyFromString(str);
}
~StringToChar()
{
Utility::freePCharCopyFromString(str_char);
}
char* str_char;
};
class GlobleParameter
{
public:
SINGLETON_INSTANCE(GlobleParameter)
GlobleParameter();
char utility_ansi_string[2000];
wchar_t utility_bstr_string[2000];
};
}
/******************************************************************************/
#endif //_UTILITY_H_
|
Java | UTF-8 | 5,586 | 2.15625 | 2 | [] | no_license | package com.example.demo.controller;
import com.example.demo.configuration.Messages;
import com.project.core.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@Controller
@SessionAttributes("user")
public class LoginController {
private String uri = "http://localhost:9999/project/v1/login/";
@Autowired
private RestTemplate restTemplate;
@Autowired
private Messages messages;
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView showLoginPage(Locale locale, ModelAndView modelAndView, String email, String password) {
modelAndView.addObject("email", email);
modelAndView.addObject("password", password);
modelAndView.setViewName("login");
return modelAndView;
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView showWelcomePage(Authentication authentication, Locale locale, ModelAndView modelAndView, @Valid @RequestParam String email, @Valid @RequestParam String password, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
modelAndView.addObject("wrongCredentials", messages.get("login.wrongCredentials", locale));
return modelAndView;
} else {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
String URL = uri + "validateUser/" + email + "/" + password;
boolean passedValidation = false;
try {
passedValidation = restTemplate.getForObject(URL, boolean.class, params);
} catch (Exception e) {
e.printStackTrace();
}
if (!passedValidation) {
modelAndView.addObject("errorMessage", messages.get("login.errorMessage", locale));
return modelAndView;
} else {
boolean isLogged = true;
ModelAndView modelAndViewWelcomePage = new ModelAndView();
modelAndViewWelcomePage.addObject("isLogged", isLogged);
modelAndViewWelcomePage.addObject("welcomeMessage", messages.get("login.welcomeMessage", locale));
modelAndViewWelcomePage.setViewName("home");
return modelAndViewWelcomePage;
}
}
}
@RequestMapping(value = "/loginhome", method = RequestMethod.GET)
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
// Map<String, String> params = new HashMap<>();
// params.put("email", auth.getName());
// String email = auth.getName();
// User user = restTemplate.getForObject(uri + "getUserByEmail/" + auth.getName(), User.class, params);
getUserByEmail("dupa");
String url = "http://localhost:9999/project/v1/user/getUserByEmail/{email}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(auth.getName(), headers);
ResponseEntity<User> user = restTemplate.exchange(url, HttpMethod.GET, entity, User.class, auth.getName());
//modelAndView.addObject("userName", "Welcome " + user.getName() + " " + user.getLastName() + " (" + user.getEmail() + ")");
//modelAndView.addObject("adminMessage","Content Available Only for Users with Admin Role");
modelAndView.setViewName("home");
return modelAndView;
}
@RequestMapping(value = "/logowanie", method = RequestMethod.GET)
public ModelAndView logowanie() {
ModelAndView modelAndView = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String url = "http://localhost:9999/project/v1/getUserByEmail/{email}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(auth.getName(), headers);
ResponseEntity<User> user = restTemplate.exchange(url, HttpMethod.GET, entity, User.class, auth.getName());
modelAndView.addObject("userName", "Welcome " + user.getBody().getFirstName() +
" " + user.getBody().getLastName() + " (" + user.getBody().getEmail() + ")");
modelAndView.addObject("adminMessage", "Content Available Only for Users with Admin Role");
modelAndView.setViewName("home");
return modelAndView;
}
public User getUserByEmail(String email) {
String url = "http://localhost:9999/project/v1/getUserByEmail/{email}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(email, headers);
ResponseEntity<User> user = restTemplate.exchange(url, HttpMethod.GET, entity, User.class, email);
return user.getBody();
}
}
|
Python | UTF-8 | 1,058 | 3.125 | 3 | [] | no_license | class employee:
def __init__(self):
self.eno=int(input("enetr the number"))
self.ename=input("enter the name")
self.dsg=input("enetr the designation")
self.bsal=float(input("enetr the basic sal"))
def calemploy(self):
self.da=self.bsal*0.2
self.ta=self.bsal*0.1
self.cca=self.bsal*0.02
self.ma=self.bsal*0.05
self.hra=self.bsal*0.15
self.lic=self.bsal*0.02
self.gif=self.bsal*0.02
self.netsal=(self.da+self.ta+self.cca+self.ma+self.hra+self.bsal)-(self.lic+self.gif)
def disp(self):
print("-"*30)
print("employee details")
print("employ number=%d"%self.eno)
print("employ name=%s"%self.ename)
print("employ designation=%s"%self.dsg)
print("employ basic salr=%f"%self.bsal)
print("employ da=%f"%self.da)
print("employ ta=%f"%self.ta)
print("employ cca=%f"%self.cca)
print("employ ma=%f"%self.ma)
print("employ hra=%f"%self.hra)
print("employ lic=%f"%self.lic)
print("employ gpf=%f"%self.gif)
print("employ netsal=%f"%self.netsal)
eo=employee()
eo.calemploy()
eo.disp()
|
Java | UTF-8 | 12,503 | 2.703125 | 3 | [] | no_license | package com.zookeeper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
public class TestZooKeeperDistributeLock {
// 是否为可重入锁
private boolean reentrant = false;
public boolean isReentrant() {
return reentrant;
}
private ZooKeeper zk = null;
public ZooKeeper getZk() {
return zk;
}
public TestZooKeeperDistributeLock(boolean reentrant) {
this.reentrant = reentrant;
// 初始化环境:连接Zookeeper并创建根目录
init();
}
private void init() {
try {
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("开始连接ZooKeeper...");
// 创建与ZooKeeper服务器的连接zk
String address = "192.168.171.131:2181";
int sessionTimeout = 3000;
zk = new ZooKeeper(address, sessionTimeout, new Watcher() {
// 监控所有被触发的事件
public void process(WatchedEvent event) {
if (event.getType() == null || "".equals(event.getType())) {
return;
}
System.out.println("已经触发了" + event.getType() + "事件!");
}
});
System.out.println("ZooKeeper连接创建成功!");
Thread.currentThread().sleep(1000l);
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("...");
// 创建根目录节点
// 路径为/tmp_root_path
// 节点内容为字符串"我是根目录/tmp_root_path"
// 创建模式为CreateMode.PERSISTENT
System.out.println("开始创建根目录节点/tmp_root_path...");
zk.create("/tmp_root_path", "我是根目录/tmp_root_path".getBytes(),
Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
System.out.println("根目录节点/tmp_root_path创建成功!");
Thread.currentThread().sleep(1000l);
System.out.println("...");
System.out.println("...");
System.out.println("...");
System.out.println("...");
} catch (Exception e) {
zk = null;
}
}
public void destroy() {
// 删除根目录节点
try {
System.out.println("开始删除根目录节点/tmp_root_path...");
zk.delete("/tmp_root_path", -1);
System.out.println("根目录节点/tmp_root_path删除成功!");
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (KeeperException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// 关闭连接
if (zk != null) {
try {
zk.close();
System.out.println("释放ZooKeeper连接成功!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
final TestZooKeeperDistributeLock testZooKeeperDistributeLock = new TestZooKeeperDistributeLock(
true);
final Random radom = new Random();
try {
Thread.currentThread().sleep(1000l);
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
ArrayList<Thread> threadList = new ArrayList<Thread>();
for (int i = 0; i < 4; i++) {
Thread thread = new Thread() {
@Override
public void run() {
boolean locked = false;
while (true) {
try {
// 创建需要获取锁的目录节点,创建成功则说明能够获取到锁,创建不成功,则说明锁已被其他线程(哪怕是不同进程的)获取
// 路径为/tmp_root_path/lock
// 节点内容为当前线程名
// 创建模式为CreateMode.PERSISTENT
System.out.println("线程"
+ Thread.currentThread().getName()
+ "尝试获取锁...");
testZooKeeperDistributeLock.getZk()
.create("/tmp_root_path/lock",
Thread.currentThread().getName()
.getBytes(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
System.out.println("线程"
+ Thread.currentThread().getName()
+ "成功获取到锁!");
locked = true;
System.out.println("线程"
+ Thread.currentThread().getName()
+ "开始处理业务逻辑...");
Thread.currentThread().sleep(
3000 + radom.nextInt(3000));
System.out.println("线程"
+ Thread.currentThread().getName()
+ "业务逻辑处理完毕!");
} catch (Exception e) {
if (testZooKeeperDistributeLock.isReentrant()) {
try {
String lockThread = new String(
testZooKeeperDistributeLock
.getZk()
.getData(
"/tmp_root_path/lock",
false, null));
if (lockThread != null) {
// 当前线程与获取到的锁线程名一致,重入锁
if (lockThread.equals(Thread
.currentThread().getName())) {
System.out.println("线程"
+ Thread.currentThread()
.getName()
+ "成功重入锁!");
locked = true;
System.out.println("线程"
+ Thread.currentThread()
.getName()
+ "开始处理业务逻辑...");
Thread.currentThread().sleep(
3000 + radom.nextInt(3000));
System.out.println("线程"
+ Thread.currentThread()
.getName()
+ "业务逻辑处理完毕!");
} else {
System.out.println("线程"
+ Thread.currentThread()
.getName()
+ "尝试获取锁失败,锁被线程"
+ lockThread + "占用!");
}
}
} catch (KeeperException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} else {
System.out.println("线程"
+ Thread.currentThread().getName()
+ "尝试获取锁失败!");
}
try {
Thread.currentThread().sleep(
3000 + radom.nextInt(3000));
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} finally {
try {
if (locked) {
System.out.println("线程"
+ Thread.currentThread().getName()
+ "开始释放锁...");
testZooKeeperDistributeLock.getZk().delete(
"/tmp_root_path/lock", -1);
System.out.println("线程"
+ Thread.currentThread().getName()
+ "成功释放锁!");
Thread.currentThread().sleep(
3000 + radom.nextInt(3000));
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (KeeperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
locked = false;
}
}
}
}
};
threadList.add(thread);
thread.start();
}
try {
Thread.currentThread().sleep(1000 * 20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i = 0; i < threadList.size(); i++){
Thread thread = threadList.get(i);
thread.stop();
}
// 释放资源
testZooKeeperDistributeLock.destroy();
}
} |
Python | UTF-8 | 450 | 2.953125 | 3 | [] | no_license | import os
def f(x):
"User function calling an external script"
# write variables to file
f = open('energy_calc/variables.in', 'w')
for i in range(len(x[0])):
f.write('%15.7f\n'%(x[0][i]))
f.close()
# call bash script for AMBER simulation
os.system('energy_calc/run_4D.sh')
# read energy from file and return it
f = open('energy_calc/energy.out')
E = float(f.readline())
f.close()
return E
|
C# | UTF-8 | 3,156 | 2.515625 | 3 | [
"Apache-2.0"
] | permissive | using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Text;
using DTcms.DBUtility;
using DTcms.Common;
using System.Linq;
namespace DTcms.DAL
{
/// <summary>
/// 数据访问类:OAuth应用
/// </summary>
public partial class oauth_app : DapperRepository<Model.oauth_app>
{
private string databaseprefix; //数据库表名前缀
public oauth_app(string _databaseprefix)
{
databaseprefix = _databaseprefix;
}
#region 基本方法================================
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(int id)
{
//删除站点OAtuh应用
StringBuilder strSql1 = new StringBuilder();
strSql1.Append("delete from " + databaseprefix + "site_oauth");
strSql1.Append(" where oauth_id=@0");
WriteDataBase.Execute(strSql1.ToString(), id);
//删除主表
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from " + databaseprefix + "oauth_app ");
strSql.Append(" where id=@0");
int rows = WriteDataBase.Execute(strSql.ToString(), id);
return rows > 0;
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public Model.oauth_app GetModel(string api_path)
{
StringBuilder strSql = new StringBuilder();
StringBuilder str1 = new StringBuilder();
Model.oauth_app model = new Model.oauth_app();
//利用反射获得属性的所有公共属性
PropertyInfo[] pros = model.GetType().GetProperties();
foreach (PropertyInfo p in pros)
{
str1.Append(p.Name + ",");//拼接字段
}
strSql.Append("select top 1 " + str1.ToString().Trim(','));
strSql.Append(" from " + databaseprefix + "oauth_app");
strSql.Append(" where api_path=@0");
return ReadDataBase.Query<Model.oauth_app>(strSql.ToString(), api_path).FirstOrDefault();
}
#endregion
#region 扩展方法================================
/// <summary>
/// 获取站点未添加数据
/// </summary>
public DataSet GetList(int site_id, int oauth_id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * FROM " + databaseprefix + "oauth_app");
strSql.Append(" where is_lock=0 and id not in(");
strSql.Append("select oauth_id from " + databaseprefix + "site_oauth where site_id=" + site_id);
if (oauth_id > 0)
{
strSql.Append(" and oauth_id<>" + oauth_id);
}
strSql.Append(")");
strSql.Append(" order by sort_id asc,id desc");
return WriteDataBase.QueryFillDataSet(strSql.ToString());
}
#endregion
}
} |
C | UTF-8 | 670 | 3.28125 | 3 | [] | no_license | /*................................A programe by Mr.Arijit Ghosh.............................................*/
/*...............................To display the fibonanci series............................................*/
#include<stdio.h>
int main()
{
int first,second,temp,end;
printf("\t\t\t\tFibonanci Series\n");
printf("\t\t\t\t_________________\n");
printf("Enter that Number upto you want to see the Fibonanci series\n "); /*Taking the user input*/
scanf("%d",&end);
first=0;
second=1;
while(second<=end)
{
temp=second;
second=first+second;
first=temp;
printf("%d\n",second);
}
return 0;
}
|
Shell | UTF-8 | 131 | 2.734375 | 3 | [] | no_license | #!/bin/bash
function warn() {
echo -en "$col_yellow[warning] $col_white"
echo "$@"
echo -en "$col_reset"
}
warn "$@"
|
Java | UTF-8 | 416 | 1.757813 | 2 | [] | no_license | /**
* Copyright (c) 2000-2006, Serhiy Yevtushenko
* All rights reserved.
* Please read license.txt for licensing issues.
**/
package conexp.core.compareutils;
import conexp.core.Lattice;
public class LatticeComparator extends ConceptCollectionComparator {
public LatticeComparator(Lattice one, Lattice two) {
super(new LatticeElementCompareInfoFactory(),
one,
two);
}
}
|
C# | UTF-8 | 3,908 | 2.53125 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DrawOnTexture : MonoBehaviour
{
RenderTexture rt;
public Texture2D brush;
public int brushSize;
Texture2D currentPaintMap;
public Renderer worms;
Material mat;
[HideInInspector]
public int deltaPixelDrawn;
int lastRemaining;
//Do this in while cleaning to save performance instead
public int Remaining
{
get
{
int pixelRemaining = 0;
Color[] pixels = currentPaintMap.GetPixels();
for (int i = 0; i < pixels.Length; i++)
{
if (pixels[i].r > 0.1f) // or ==1 if using cleaning
pixelRemaining++;
}
return pixelRemaining;
}
}
public static DrawOnTexture Instance;
private void Awake()
{
Instance = this;
}
// Start is called before the first frame update
void Start()
{
mat = worms.material;
Texture2D paintMap = (Texture2D)mat.GetTexture("_PaintMap");
rt = new RenderTexture(paintMap.width, paintMap.height, 32);
//Make it writable so the clean image compute shader can write on it
rt.enableRandomWrite = true;
Graphics.Blit(paintMap, rt);
this.currentPaintMap = paintMap;
UpdateMap();
lastRemaining = Remaining;
#if UNITY_EDITOR
Debug.Log("Pixels to clear :" + lastRemaining);
#endif
}
public void UpdateMap()
{
mat.SetTexture("_PaintMap", currentPaintMap);
}
public void Draw(Vector2 currentPos, Vector2 lastPos, out int pixelCleared)
{
currentPaintMap = new Texture2D(rt.width, rt.height);
//Find the draw position on the paint map
Vector2 currentDrawPos = new Vector2(currentPos.x * rt.width - brushSize * 0.5f, (1 - currentPos.y) * rt.height - brushSize * 0.5f);
Vector2 lastDrawPos = new Vector2(lastPos.x * rt.width - brushSize * 0.5f, (1 - lastPos.y) * rt.height - brushSize * 0.5f);
//Get the positions to draw on
List<Vector2> drawPositions = GetIntermediatePositions(currentDrawPos, lastDrawPos);
RenderTexture.active = rt;
GL.PushMatrix();
GL.LoadPixelMatrix(0, rt.width, rt.height, 0);
//Draw on every positions
for (int i = 0; i < drawPositions.Count; i++)
{
Graphics.DrawTexture(new Rect(drawPositions[i].x, drawPositions[i].y, brushSize, brushSize), brush);// draw the brush on PaintMap
}
currentPaintMap.ReadPixels(new Rect(0, 0, rt.width, rt.height), 0, 0);
currentPaintMap.Apply(false);
GL.PopMatrix();
RenderTexture.active = null;
//Update stats
int pixelRemaining = Remaining;
deltaPixelDrawn = lastRemaining- pixelRemaining;
lastRemaining = pixelRemaining;
pixelCleared = deltaPixelDrawn;
UpdateMap();
//Clean the image using a compute shader
CleanImage.CleanCompute(ref rt);
}
public List<Vector2> GetIntermediatePositions(Vector2 currentPos, Vector2 lastPos)
{
//Create a list holding all the positions to draw on
List<Vector2> positions = new List<Vector2>();
//Get the max distance before we add an intermediate postion
float maxDistance = (float)brushSize / 2;
//Find the number of pos to add in between
int intermediatePosCount = Mathf.FloorToInt(Vector2.Distance(lastPos, currentPos) / maxDistance);
for (int i = 1; i <= intermediatePosCount; i++)
{
//Add all the in between positions
positions.Add(Vector2.Lerp(lastPos, currentPos, (float)i / (intermediatePosCount+1)));
}
//Always Add the current position
positions.Add(currentPos);
return positions;
}
}
|
JavaScript | UTF-8 | 364 | 4.28125 | 4 | [] | no_license | /*
Instructions:
A function called 'callAFunction' is defined below.
Please call the function three different times
Each call should have these return values.
First call: 12
Second call: 0
Third call: NaN
BE SURE TO PRINT THE VALUE OF YOUR FUNCTION CALLS
*/
function callAFunction(num1, num2) {
return num1 * num2;
}
// Code below this line
|
C# | UTF-8 | 1,718 | 2.515625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Entidad;
namespace Persistencia
{
public class datCliente
{
#region singleton
private static readonly datCliente _instancia = new datCliente();
public static datCliente Instancia
{
get { return datCliente._instancia; }
}
#endregion singleton
#region BuscarDni
public Cliente BusClienteDni(String dni)
{
SqlCommand cmd = null;
Cliente cli = null;
try
{
SqlConnection cn = Conexion.Instancia.conectar();
cmd = new SqlCommand("bus_cliente_dni", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@prmintDni", dni);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
cli = new Cliente();
cli.idCli = Convert.ToInt32(dr["idCli"]);
cli.nombres = dr["nombres"].ToString();
cli.apellidos = dr["apellidos"].ToString();
cli.dni = dr["dni"].ToString();
cli.direccion = dr["direccion"].ToString();
cli.fechaRegistro = Convert.ToDateTime(dr["fechaRegistro"]);
}
}
catch (Exception ex)
{
throw ex;
}
finally { cmd.Connection.Close(); }
return cli;
}
#endregion BuscarDni
}
}
|
Java | UTF-8 | 977 | 3.25 | 3 | [] | no_license | package hw4;
import java.awt.Color;
import api.Block;
import api.Cell;
import api.Position;
/**
* Subclass for the T-shaped Shape
*
* @author Gendid
*
*/
public class TShape extends AbstractShape
{
/**
* Creates a T-shaped shape
*
* @param position
* Origin position of the shape
* @param magic
* Determines if the shape is magic
*/
public TShape(Position position, boolean magic) {
super(position, magic, false);
Position position1 = new Position(position.row() - 1, position.col());
Position position2 = new Position(position1.row() + 1, position1.col() - 1);
Position position3 = new Position(position2.row(), position2.col() + 2);
super.setCell(new Cell(new Block(Color.MAGENTA, magic), position1),
new Cell(new Block(Color.MAGENTA, false), position2),
new Cell(new Block(Color.MAGENTA, false), position),
new Cell(new Block(Color.MAGENTA, false), position3));
}
}
|
C# | UTF-8 | 2,316 | 2.546875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Logging;
namespace DataControl.Impl
{
public class ExceptionHandler
{
public static bool WriteLog(Exception ex, Dictionary<string, string> dic)
{
StringBuilder strBuilder = new StringBuilder();
LogEntry logEntry = new LogEntry();
logEntry.Title = System.Web.HttpContext.Current.Request.Url.AbsoluteUri.ToString();
logEntry.AppDomainName = AppDomain.CurrentDomain.BaseDirectory.ToString();
logEntry.MachineName = System.Web.HttpContext.Current.Server.MachineName.ToString();
logEntry.Message = ex.Message.ToString();
logEntry.TimeStamp = DateTime.Now;
if (dic != null)
{
foreach (KeyValuePair<string, string> entry in dic)
{
logEntry.ExtendedProperties.Add(entry.Key.ToString(), entry.Value.ToString());
}
}
if (System.Web.HttpContext.Current.Session["Comp_Code"] != null)
{
logEntry.ExtendedProperties.Add("Session Company Code :", System.Web.HttpContext.Current.Session["Comp_Code"].ToString());
logEntry.ExtendedProperties.Add("Session User Name :", System.Web.HttpContext.Current.Session["User_Name"].ToString());
logEntry.ExtendedProperties.Add("Session Region Name :", System.Web.HttpContext.Current.Session["Region_Name"].ToString());
logEntry.ExtendedProperties.Add("Session User Code :", System.Web.HttpContext.Current.Session["User_Code"].ToString());
logEntry.ExtendedProperties.Add("Session Region Code :", System.Web.HttpContext.Current.Session["Region_Code"].ToString());
logEntry.ExtendedProperties.Add("Session User Type Code :", System.Web.HttpContext.Current.Session["User_Type_Code"].ToString());
}
else
{
logEntry.ExtendedProperties.Add("Session : ", "-- No session values available --");
}
logEntry.ExtendedProperties.Add("Exception StackTrace :", ex.StackTrace.ToString());
Logger.Write(logEntry);
return true;
}
}
}
|
Java | UTF-8 | 1,170 | 3.0625 | 3 | [
"MIT"
] | permissive | package tictactoe.core;
import tictactoe.core.players.PlayerSymbol;
import java.util.Optional;
import java.util.function.Function;
public class Tile {
private Optional<PlayerSymbol> playerSymbol;
private int index;
Tile(int index) {
this.index = index;
this.playerSymbol = Optional.empty();
}
Tile(int index, PlayerSymbol playerSymbol) {
this.index = index;
this.playerSymbol = Optional.of(playerSymbol);
}
boolean isTakenBy(PlayerSymbol p) {
return playerSymbol.map(s -> s == p).orElse(false);
}
public boolean isEmpty() {
return !playerSymbol.isPresent();
}
public int getIndex() {
return index;
}
public String toString() {
return toStringWithDefault().apply(Integer.toString(index));
}
public String toString(String emptyTile) {
return toStringWithDefault().apply(emptyTile);
}
private Function<String, String> toStringWithDefault() {
return defaultTileString ->
playerSymbol
.map(PlayerSymbol::toString)
.orElse(defaultTileString);
}
}
|
PHP | UTF-8 | 1,957 | 2.546875 | 3 | [] | no_license | <?php
session_start();
require_once('conexion.php');
require_once('saneo.php');
$p=$_POST;
$clase=new pv();
$r=$clase->pvi($p);
/**
*
*/
class pv
{
private $con;
private $s;
function __construct()
{
$this->con=new Database();
}
public function pvi($p)
{
header("Content-type: text/plain;charset=utf-8");
$sa=new saneo($p);
$res=$sa->s();
$query = $this->con->prepare('INSERT INTO pv (`id_cr`, `email`, `nombre`, `telefono`, `lugar_s`, `lugar_l`, `fecha`, `hora`, `cupos`, `precio`, `marca`, `modelo`) values (:id_cr,:email,:nombre,:telefono,:lugar_s,:lugar_ll,:fecha,:hora,:cupos,:precio,:marca,:modelo)');
$dato="si";
$query->bindParam(':email',$_SESSION['email']);
$query->bindParam(':nombre',$_SESSION['nombre']);
$query->bindParam(':telefono',$_SESSION['telefono']);
$query->bindParam(':lugar_s',$res[0]);
$query->bindParam(':lugar_ll',$res[1]);
$query->bindParam(':fecha',$res[2]);
$query->bindParam(':hora',$res[3]);
$query->bindParam(':cupos',$res[4]);
$query->bindParam(':precio',$res[5]);
$query->bindParam(':marca',$res[6]);
$query->bindParam(':modelo',$res[7]);
$query->bindParam(':id_cr',$_SESSION['id']);
$query->execute();
if (!$query) {
echo 12;
}else{
$e=$query->rowCount();
if ($e==1) {
echo '<table>
<tr>
<td>'.$_SESSION['nombre'].'</td>
<td>'.$res[0].'</td>
<td>'.$res[1].'</td>
<td>'.$res[2].'</td>
<td>'.$res[3].'</td>
<td>'.$res[4].'</td>
<td>'.$res[5].'</td>
<td>'.$res[6].'</td>
<td>'.$res[7].'</td>
</tr>
</table>';
// <td>'.$dato.'</td>
}else {
echo 0;
}
}
}
}
?>
|
C++ | UTF-8 | 398 | 3.4375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int number, i;
bool flag;
flag = true;
cout<<"Enter a number\n";
cin>>number;
for(i=2; i<number/2;i++){
if(number%i==0){
flag = false;
break;
}
}
if(flag==true){
cout<<number<<"\nPrime NUmber";
}
else{
cout<<number<<"\nNot a prime number";
}
}
|
Go | UTF-8 | 451 | 3.34375 | 3 | [
"BSD-3-Clause",
"CC-BY-4.0",
"LicenseRef-scancode-google-patent-license-golang"
] | permissive | // Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"unsafe"
)
var intGlo int
func main() {
r := bar(&intGlo)
fmt.Printf("r value is %d", r)
}
func bar(a *int) int {
p := (*int)(unsafe.Add(unsafe.Pointer(a), 1*unsafe.Sizeof(int(1))))
if *p == 10 { // BOOM
fmt.Println("its value is 10")
}
return *p
}
|
Java | UTF-8 | 3,200 | 3.796875 | 4 | [] | no_license | //************************************************************************
// Stars.java Author: Benjamin Prud'homme
// Draws a triangle or diamond of a size specified by the user on the
// screen with asterisks.
//************************************************************************
import java.util.Scanner;
public class Stars {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int shapeChoice,
rows;
System.out.print("Choose shape to print:\n"
+ "1: Bottom-left aligned triangle\n"
+ "2: Top-left aligned triangle\n"
+ "3: Bottom-right aligned triangle\n"
+ "4: Top-right aligned triangle\n"
+ "5: Diamond\n"
+ "Shape: ");
shapeChoice = in.nextInt();
System.out.print("Size (rows): ");
rows = in.nextInt();
switch(shapeChoice){
case 1:
bottomLeftTriangle(rows);
break;
case 2:
topLeftTriangle(rows);
break;
case 3:
bottomRightTriangle(rows);
break;
case 4:
topRightTriangle(rows);
break;
case 5:
diamond(rows);
break;
default:
}
}
public static void bottomLeftTriangle(int rows){
int size = rows;
int asterisks = 1;
for(int i=0; i<size; i++){
for(int j=0; j<asterisks; j++){
System.out.print("*");
}
asterisks++;
System.out.println();
}
}
public static void topLeftTriangle(int rows){
int size = rows;
int asterisks = size;
for(int i=0; i<size; i++){
for(int j=0; j<asterisks; j++){
System.out.print("*");
}
asterisks--;
System.out.println();
}
}
public static void bottomRightTriangle(int rows){
int size = rows;
int asterisks = 1;
for(int i=0; i<size; i++){
for(int j=0; j<(size-asterisks); j++){
System.out.print(" ");
}
for(int k=0; k<asterisks; k++){
System.out.print("*");
}
asterisks++;
System.out.println();
}
}
public static void topRightTriangle(int rows){
int size = rows;
int asterisks = size;
for(int i=0; i<size; i++){
for(int j=0; j<(size-asterisks); j++){
System.out.print(" ");
}
for(int k=0; k<asterisks; k++){
System.out.print("*");
}
asterisks--;
System.out.println();
}
}
public static void diamond(int rows){
int size = rows;
int upperRows;
int lowerRows;
int asterisks = 1;
int width;
int spaces;
width = (size%2 == 0) ? size-1 : size;
spaces = width/2;
upperRows = (size%2 == 0) ? size/2 : (size/2)+1;
lowerRows = size-upperRows;
System.out.println("size = " + size);
System.out.println("width = " + width);
System.out.println("spaces = " + spaces);
for(int i=0; i<upperRows; i++){
for(int j=0; j<spaces; j++){
System.out.print(" ");
}
for(int j=0; j<asterisks; j++){
System.out.print("*");
}
spaces--;
asterisks+=2; // Increment row
System.out.println();
}
spaces = 0;
asterisks = width;
if(size%2 == 1){
spaces++;
asterisks-=2; // If there are an odd number of rows, decrement the next row
}
for(int i=0; i<lowerRows; i++){
for(int j=0; j<spaces; j++){
System.out.print(" ");
}
for(int j=0; j<asterisks; j++){
System.out.print("*");
}
spaces++;
asterisks-=2; // Decrement row
System.out.println();
}
}
} |
JavaScript | UTF-8 | 1,516 | 2.6875 | 3 | [] | no_license | /*global exports, setInterval, clearInterval, document, PVector, getRandomNumber */
(function (exports) {
'use strict';
var ParticleSystem = (function () {
function ParticleSystem(opts) {
var opts = this.getOptions() || {};
this.burst = opts.burst || 1;
}
ParticleSystem.prototype.getOptions = function () {
return exports.particleSystemOptions;
}
ParticleSystem.prototype.idCount = 0;
ParticleSystem.prototype.launchParticle = function (particle) {
particle.applyForce(PVector.create(getRandomNumber(-2, 2, true), getRandomNumber(-2, 0, true)));
exports.world.elements.push(particle);
this.idCount += 1;
};
ParticleSystem.prototype.createParticles = function (ps) {
return function () {
var i, max;
if (ps.burst > 0) {
for (i = 0, max = ps.burst; i < max; i += 1) {
ps.launchParticle(new exports.Particle(ps.idCount));
}
} else {
if (exports.world.clock % ps.burst === 0) {
ps.launchParticle(new exports.Particle(ps.idCount));
}
}
};
};
ParticleSystem.prototype.start = function () {
var funcRef = this.createParticles(this);
this.interval = setInterval(funcRef, 16); // using funcRef/closure to maintain reference to "this" instance of ParticleSystem
};
ParticleSystem.prototype.stop = function () {
clearInterval(this.interval);
this.interval = null;
};
return ParticleSystem;
}());
exports.ParticleSystem = ParticleSystem;
}(exports)); |
Java | UTF-8 | 1,042 | 2.953125 | 3 | [] | no_license | package com.benjaminran.intonationcore;
import be.tarsos.dsp.util.PitchConverter;
public class Pitch implements Comparable<Pitch> {
private double absoluteCents;
private double frequency;
private double time;
public Pitch(double absoluteCents, double frequency, double time) {
this.absoluteCents = absoluteCents;
this.frequency = frequency;
this.time = time;
}
public static Pitch fromFrequency(double frequency, double time) {
return new Pitch(PitchConverter.hertzToAbsoluteCent(frequency), frequency, time);
}
public int getNoteNumber() {
return (int) Math.floor(absoluteCents/100);
}
public double getFrequency() {
return frequency;
}
public double getAbsoluteCents() {
return absoluteCents;
}
@Override
public int compareTo(Pitch another) {
return Double.compare(frequency,another.frequency);
}
@Override
public String toString() {
return String.format("%fc", absoluteCents);
}
}
|
Markdown | UTF-8 | 7,885 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | # Getting Started
## ダウンロードとインストール
NLP4L/nlp4lの配布用ZIPファイルをダウンロードして、解凍しましょう。
* ダウンロードサイト:https://github.com/NLP4L/nlp4l/releases
```shell
mkdir -p /opt/nlp4l
cd /opt/nlp4l
wget https://github.com/NLP4L/nlp4l/releases/download/rel-x.x.x/nlp4l-x.x.x.zip
unzip nlp4l-x.x.x.zip
cd nlp4l-x.x.x
```
## NLP4LのGUIツール
### GUIツールサーバの起動
NLP4L/nlp4lのGUIツールサーバを起動します。
* 起動には、Java 1.8以上がインストールされている必要があります。
```shell
bin/nlp4l
```
### GUIツールを使う
ブラウザから [http://localhost:9000/](http://localhost:9000/) にアクセスしてみて下さい。
ブラウザの画面に、TOP画面が表示されます。
Getting Startedでは、NLP4L-DICTプロジェクトのサンプルを利用しますので、 NLP4L-DICTを選択(クリック)します。

NLP4L-DICTを選択すると、以下のようなWelcomeメッセージが画面表示されます。

## サンプルを試してみる(固有表現抽出)
それでは、固有表現抽出の付属サンプルを動かしてみましょう。
### 固有表現抽出サンプルの概要
NLP4Lの提供する固有表現抽出ソリューションは、自然言語で書かれたテキストから固有表現(人名、場所、組織、金額、日付、時間など)を切り出す機能を提供します。
固有表現の抽出には、[Apache OpenNLP (http://opennlp.apache.org/)](http://opennlp.apache.org/)で提供されているName Finderの学習済みモデルを使用することにより、実現されています。
このサンプルでは、文書ID(docID)とテキスト(body)をCSVデータとして入力し、テキスト(body)から、人名(Person)と場所(Location)を抽出する処理を行うサンプルとなっています。

### OpenNLPモデルファイルのダウンロード
NLP4Lの固有表現抽出では、[Apache OpenNLP (http://opennlp.apache.org/)](http://opennlp.apache.org/)で提供されている学習済みモデルを使用します。これらの学習済みモデルはSourceforgeのサイトよりダウンロードできます。
* OpenNLPの学習済みモデルのダウンロードサイト:http://opennlp.sourceforge.net/models-1.5/
NLP4Lの固有表現抽出では、SentenceとTokenの切り出しに、それぞれの学習済みモデルを使用します。サンプルデータのテキスト文書は英語で記述されていますので、Languageはenのモデルをダウンロードしておきます。
* Sentence Detector (en):http://opennlp.sourceforge.net/models-1.5/en-sent.bin
* Tokenizer (en):http://opennlp.sourceforge.net/models-1.5/en-token.bin
さらに、サンプルでは、人名(Person)と場所(Location)を抽出しますので、それぞれの学習済みモデルもダウンロードしておきます。
* Name Finder Person (en): http://opennlp.sourceforge.net/models-1.5/en-ner-person.bin
* Name Finder Location (en): http://opennlp.sourceforge.net/models-1.5/en-ner-location.bin
ダウンロードしたファイルは、/opt/nlp4l/example-ner/models ディレクトリに配置しておくと、サンプルのコンフィグレーション(後述)を修正することなく使用できるので便利です。
```
mkdir -p /opt/nlp4l/example-ner/models
cd /opt/nlp4l/example-ner/models
wget http://opennlp.sourceforge.net/models-1.5/en-sent.bin
wget http://opennlp.sourceforge.net/models-1.5/en-token.bin
wget http://opennlp.sourceforge.net/models-1.5/en-ner-person.bin
wget http://opennlp.sourceforge.net/models-1.5/en-ner-location.bin
```
これでモデルの準備は整いました。それでは、実際にGUI Toolを用いて、固有表現抽出を動かしてみましょう。
### 新規Jobの登録
1 . [New Job](http://localhost:9000/dashboard/job/new) リンクをクリックしてください。Jobの登録画面が表示されます。

2 .Configファイルをアップロードします。
サンプルとして提供されている examples/example-opennlp-ner.confを指定して、Uploadボタンをクリックしてください。
このConfigファイルには、先の概要の図で説明した通り、CSVデータを読み込み(サンプルの英文データはConfigファイル内に埋め込まれています)、学習済みモデルを使用して固有表現を抽出し、テーブル形式のデータ(Dictionaryと呼ばれます)として保存する処理が定義されています。保存した結果は、後述の画面で参照していきます。
```
{
dictionary : [
{
class : org.nlp4l.framework.builtin.GenericDictionaryAttributeFactory
settings : {
name: "OpenNLPNerDict"
attributes : [
{ name: "docId" },
{ name: "body_person" },
{ name: "body_location" },
{ name: "body" }
]
}
}
]
processors : [
{
class : org.nlp4l.sample.SampleCsvDataProcessorFactory
settings : {
fields: [
"docId",
"body"
],
data: [
"DOC-001, The Washington Nationals have released right-handed pitcher Mitch Lively."
"DOC-002, Chris Heston who no hit the New York Mets on June 9th."
"DOC-003, Mark Warburton wants to make veteran midfielder John Eustace the next captain of Rangers."
]
}
}
{
class : org.nlp4l.framework.processors.WrapProcessor
recordProcessors : [
{
class : org.nlp4l.framework.builtin.ner.OpenNLPNerRecordProcessorFactory
settings : {
sentModel: "/opt/nlp4l/example-ner/models/en-sent.bin"
tokenModel: "/opt/nlp4l/example-ner/models/en-token.bin"
nerModels: [
"/opt/nlp4l/example-ner/models/en-ner-person.bin",
"/opt/nlp4l/example-ner/models/en-ner-location.bin"
]
nerTypes: [
"person",
"location"
]
srcFields: [
"body"
]
idField: "docId"
passThruFields: [
"body"
]
separator: ","
}
}
]
}
{
class : org.nlp4l.framework.builtin.ReplayProcessorFactory
settings : {
}
}
]
}
```
3 . Job Name テキストボックスに、ジョブの名前を入力し、Saveボタンをクリックしてください。
これで新規Jobの登録が完了です。

### Jobの実行
Jobの登録が完了すると、Runボタンが表示されます。Runボタンをクリックして、Jobを実行してみましょう。
実行したJobは、[Job Status](http://localhost:9000/dashboard/job/status)画面で見ることができます。

Jobの実行中は、StatusがRunningと表示されます。
Jobの実行が終了すると、StatusがDoneと表示され、結果を見ることが出来ます。

### Jobの結果
Jobの実行結果は、(1) Job Status画面のから該当JobのJobIDをクリックする、または、(2) Job Info画面左側に表示されているJobID(#1)をクリックすることで、該当Jobの結果画面に遷移します。
下図の結果画面に示すとおり、固有表現(ここでは人名と場所)が抽出されていることがわかります。

|
Java | UTF-8 | 1,082 | 2.875 | 3 | [] | no_license | package PizzaFactory;
import IngredientFactory.NYPizzaIngredientFactory;
import IngredientFactory.PizzaIngredientFactory;
import Pizza.Pizza;
import Pizza.ChicagoStyleCheesePizza;
import Pizza.NYStyleVeggiePizza;
import Pizza.NYStyleClamPizza;
import Pizza.NYStylePepperoniPizza;
/**
* @author sqw123az@sina.com
* @date 2019/7/26 0026 11:20
*/
public class NYPizzaStore extends PizzaStore {
Pizza createPizza(String item) {
Pizza pizza = null;
PizzaIngredientFactory ingredientFactory = new NYPizzaIngredientFactory();
switch (item) {
case "cheese":
pizza = new ChicagoStyleCheesePizza(ingredientFactory);
pizza.setName("New York Style Cheese Pizza");
case "veggie":
return new ChicagoStyleCheesePizza(ingredientFactory);
case "clam":
return new ChicagoStyleCheesePizza(ingredientFactory);
case "pepperoni":
return new ChicagoStyleCheesePizza(ingredientFactory);
default:
return null;
}
}
}
|
C | UTF-8 | 1,816 | 2.78125 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* commands1.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bchan <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/08/01 12:58:22 by bchan #+# #+# */
/* Updated: 2018/08/01 12:58:28 by bchan ### ########.fr */
/* */
/* ************************************************************************** */
#include "checker.h"
void swap_a(t_check *check)
{
t_list *tmp;
if (check->a_size > 1)
{
tmp = check->a;
check->a = check->a->next;
tmp->next = check->a->next;
check->a->next = tmp;
}
}
void swap_b(t_check *check)
{
t_list *tmp;
if (check->b_size > 1)
{
tmp = check->b;
check->b = check->b->next;
tmp->next = check->b->next;
check->b->next = tmp;
}
}
void push_a(t_check *check)
{
t_list *tmp;
if (check->b_size > 0)
{
tmp = check->b->next;
ft_lstadd(&(check->a), check->b);
check->b = tmp;
check->a_size++;
check->b_size--;
}
}
void push_b(t_check *check)
{
t_list *tmp;
if (check->a_size > 0)
{
tmp = check->a->next;
ft_lstadd(&(check->b), check->a);
check->a = tmp;
check->a_size--;
check->b_size++;
}
}
void rotate_a(t_check *check)
{
t_list *tmp;
if (check->a_size > 1)
{
tmp = check->a;
check->a = check->a->next;
ft_lstadd_end(&(check->a), tmp);
}
}
|
Go | UTF-8 | 548 | 3.015625 | 3 | [] | no_license | package utils
import xerrors "github.com/pkg/errors"
// 工具包内所有panic 转 error 向上抛
// 默认运行时异常处理,panic 转 error
func deferError(msg string) {
if r := recover(); r != nil {
switch x := r.(type) {
case string:
errMsg = xerrors.New(x)
case error:
if xerrors.Cause(x) == x { //根因
errMsg = xerrors.Wrap(x, msg)
} else { //非根因用with message
errMsg = xerrors.WithMessage(x, msg)
}
default:
errMsg = xerrors.New("unbekannt panic")
}
panic(errMsg)
}
}
var errMsg error
|
JavaScript | UTF-8 | 662 | 2.578125 | 3 | [] | no_license | const Discord = require('discord.js');
const actions = require('../json/actions.json');
exports.run = async (bot, message, args) => {
try {
//for(i = 0; i < actions.winkP.length; i++) {
const embed = new Discord.RichEmbed()
.setColor('#FBCFCF')
//.setImage(actions.winkP[args[0]]);
.setImage(actions.disgustP[Math.round(Math.random() * (actions.disgustP.length - 1))]);
return message.channel.send(embed);
//}
} catch (err) {
console.error(err);
return message.channel.send('Ocorreu um erro! Contate o administrador (Zanotto)!');
}
};
exports.help = {
name: 'disgust',
description: 'Isso é repugnante!',
};
|
C | UTF-8 | 561 | 3.1875 | 3 | [] | no_license | #include <stdio.h>
#include "ponto.h"
#include "circulo.h"
int main()
{
Ponto* p1 = pto_cria(8.0,15.0); // aloca dinamic.
Ponto* p2 = pto_cria(8.0, 16.0);
Circulo* circ = circ_cria(p2, 4.9);
printf ("Area do Circulo: %.2f\n", circ_area(circ));
if(circ_interior(circ,p1) == 1 )
{
printf ("P1 está dentro do Circulo\n") ;
}
else
{
printf ("P1 não está dentro do Circulo\n") ;
}
// chamar função para liberar memoria de circulo.
pto_libera (p1);
circ_libera (circ);
return 0;
} |
Java | UTF-8 | 571 | 1.570313 | 2 | [] | no_license | package com.lee.springbootdemo.service.impl;
import com.lee.springbootdemo.entity.PcCpmReview;
import com.lee.springbootdemo.mapper.PcCpmReviewMapper;
import com.lee.springbootdemo.service.PcCpmReviewService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* v2党员民主评议情况表 服务实现类
* </p>
*
* @author admin
* @since 2019-09-20
*/
@Service
public class PcCpmReviewServiceImpl extends ServiceImpl<PcCpmReviewMapper, PcCpmReview> implements PcCpmReviewService {
}
|
Java | UTF-8 | 597 | 1.84375 | 2 | [] | no_license | package com.quanliren.quan_one.activity.group;
import android.os.Bundle;
import com.quanliren.quan_one.activity.R;
import com.quanliren.quan_one.activity.base.BaseActivity;
import com.quanliren.quan_one.fragment.ChosePositionFragment;
public class ChoseLocationActivity extends BaseActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chose_position_actvitiy);
setTitleTxt("选择城市");
getSupportFragmentManager().beginTransaction().replace(R.id.content, new ChosePositionFragment()).commit();
}
}
|
Java | ISO-8859-1 | 10,156 | 2.703125 | 3 | [] | no_license | package application;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
public class ActiviteServeur extends Thread {
Socket clientSocket;
boolean isConnected;
private enum Connexion {
NEW, NOTNEW;
}
private enum Action{
LIST_TASK, NEW_TASK, SUPPRESS_TASK, DISCONNECT;
}
/**
* Constuctor of ActiviteServeur with 2 params
*
* @param n
* : String : Name of the Thread
* @param s
* : Socket
*/
public ActiviteServeur(String n, Socket s) {
super(n);
clientSocket = s;
}
/**
* Send the user list to the client
*
* @param listUser
* : List<Personne>
* @param out
* : OutputStream
*/
public void SendUserList(List<Personne> listUser, OutputStream out) {
try {
ObjectOutputStream userObj = new ObjectOutputStream(out);
userObj.writeObject(listUser);
userObj.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SendUser(Personne me, OutputStream out){
try {
ObjectOutputStream userObj = new ObjectOutputStream(out);
userObj.writeObject(me);
userObj.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SendListTaskToDo(Personne p, OutputStream out){
try {
ParserTache parser = new ParserTache();
List <Tache> list = parser.getListTacheAffecteById(p.getIdPersonne());
ObjectOutputStream userObj = new ObjectOutputStream(out);
userObj.writeObject(list);
userObj.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void SendListTaskGiven(Personne p, OutputStream out){
try {
ParserTache parser = new ParserTache();
List <Tache> list = parser.getListTacheCreateurById(p.getIdPersonne());
ObjectOutputStream userObj = new ObjectOutputStream(out);
userObj.writeObject(list);
userObj.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @param in
* : InputStream
* @return
*/
public Personne ReceiveNewUser(InputStream in) {
Personne user = null;
ObjectInputStream userObj;
try {
userObj = new ObjectInputStream(in);
user = (Personne) userObj.readObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return user;
}
/**
* Run method no parameters needed :)
*/
public void run() {
Connexion connexion;
Action action;
List<Tache> tacheCreate = new ArrayList<Tache>();
List<Tache> tacheAff = new ArrayList<Tache>();
Personne me = null;
boolean goOn = false;
System.out.println("Nouveau client");
try {
System.out.println("Client " + clientSocket.getLocalAddress() + " accept");
// La connexion est tablie
OutputStream output = clientSocket.getOutputStream();
InputStream input = clientSocket.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
PrintStream out = new PrintStream(output);
ObjectOutputStream objOut = new ObjectOutputStream(output);
//objOut.flush();
ObjectInputStream objIn = new ObjectInputStream(input);
// Initialisation du parser XML pour le document user.xml
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser sax = factory.newSAXParser();
ParserUser handlerSAX = new ParserUser();
sax.parse("src/user.xml", handlerSAX);
//Initialisation du parser pour le document tache.xml
SAXParserFactory factoryTask = SAXParserFactory.newInstance();
factoryTask.setNamespaceAware(true);
SAXParser saxTask = factoryTask.newSAXParser();
ParserTache taskXML = new ParserTache(handlerSAX);
saxTask.parse("src/tache.xml", taskXML);
// Initialisation du parser DOM pour crire dans les documents xml
WriterXMLUserDOM domUser = new WriterXMLUserDOM();
WriterXMLTaskDOM domTask = new WriterXMLTaskDOM();
//Connexion
while (!goOn) {
// Attente des instructions de connection
System.out.println("Attente demande connexion");
while (!in.readLine().equals("CONNEXION"))
System.out.println("Attente du client " + clientSocket.getLocalAddress());
System.out.println("renvoi connexion");
connexion = Connexion.valueOf(in.readLine());
String nom = in.readLine();
String pass = in.readLine();
// Options en fonction du type de connexion
switch (connexion) {
// Cration d'un nouveau compte
case NEW:
// Vrification si le nom existe dj dans le document XML des users
if (handlerSAX.nameExist(nom))
out.println("CONNEXION\nNOTOK");
else {
me = new Personne(handlerSAX.getListUser().get(handlerSAX.getListUser().size()-1).getIdPersonne()+1, nom, pass);
domUser.writeUser(me);
out.println("CONNEXION\nOK");
isConnected = true;
goOn = true;
}
break;
// Connexion avec un compte dj existant
case NOTNEW:
// Vrification que le nom correspond au mot de passe envoy
if (handlerSAX.correspondanceNamePassword(nom, pass)) {
me = handlerSAX.getPersonneByName(nom);
System.out.println(me);
out.println("CONNEXION\nOK");
isConnected = true;
goOn = true;
} else
out.println("CONNEXION\nNOTOK");
break;
default:
System.out.println("Erreur du message de connexion");
break;
}
}
goOn = false;
while(!in.readLine().equals("OK"))
System.out.println("Attente client");
// Rcupration de tous les users dans le
List<Personne> listUser = handlerSAX.getListUser();
// Send the user list
SendUserList(listUser, output);
System.out.println("envoi 1 fait : " + listUser.size());
while(!in.readLine().equals("ME"))
System.out.println("Attente client");
//Thread.sleep(1000);
System.out.println("ME reu");
//Envoi de la personne connecte
SendUser(me, output);
System.out.println("envoi 2 fait");
while(!in.readLine().equals("OK"))
System.out.println("Attente client");
System.out.println(me);
//Envoi de la liste de tache faire par la personne connecte
if(taskXML.getListTacheCreateurById(me.getIdPersonne()) == null)
out.println("LISTEAFAIRE\nNULL");
else{
out.println("LISTEAFAIRE\nENVOI");
while(!in.readLine().equals("OK"))
System.out.println("attente du client");
SendListTaskToDo(me, output);
}
while(!in.readLine().equals("OK"))
System.out.println("Attente client");
//Envoi de la liste de tache cres par la personne connecte
if(taskXML.getListTacheCreateurById(me.getIdPersonne()) == null)
out.println("LISTECREEE\nNULL");
else{
out.println("LISTECREEE\nENVOI");
while(!in.readLine().equals("OK"))
System.out.println("attente du client");
SendListTaskGiven(me, output);
}
while(!in.readLine().equals("OK"))
System.out.println("Attente client");
// Une fois la personne connecte
while(isConnected){
System.out.println("isConnected " + isConnected);
while(!in.readLine().equals("ACTION")){
System.out.println("Attente client");
}
action = Action.valueOf(in.readLine());
switch(action){
//Dconnexion du client
case DISCONNECT:
isConnected = false;
out.println("ACTION\nOK");
break;
//Cration d'une nouvelle tache
case NEW_TASK:
/*Tache newTask = (Tache) objIn.readObject();
newTask.setIdTache(taskXML.getListTache().get(taskXML.getListTache().size()).getIdTache() + 1);
domTask.writeTask(newTask);*/
break;
// Envoie d'une liste de tache en fonction de l'utilisateur
case LIST_TASK:
System.out.println("list ache");
int idPers = Integer.parseInt(in.readLine());
System.out.println("Envoie liste des taches" + idPers);
//Envoie de la liste createur
objOut.writeObject(taskXML.getListTacheCreateurById(idPers));
System.out.println("Envoi OK 1 ");
objOut.flush();
System.out.println("Attente ///");
//Attente de la bonne rception du client
while(!in.readLine().equals("OK"))
System.out.println("Attente du client");
System.out.println("Attente OK");
//Attente de la liste affecte
System.out.println("Envpi 2 ");
objOut.writeObject(taskXML.getListTacheAffecteById(idPers));
System.out.println("envoi 2 ok");
objOut.flush();
break;
//Suppression d'une tache
case SUPPRESS_TASK:
domTask.removeTask(in.readLine());
out.println("ACTION\nOK");
default:
System.out.println("Action non prise en compte");
break;
}
}
// Creation d'un tache
/*
* Tache t1 = new Tache("Faire les courses", 1, new
* Personne("Roger", 12), new Personne("Marcel", 30),
* "Liste : \n\t-pain\n\t-lait\n\t-lardon");
*
* // Envoi de l'objet tache ObjectOutputStream obj = new
* ObjectOutputStream(output); obj.writeObject(t1); obj.flush();
*/
} catch (IOException | ParserConfigurationException | SAXException /*| ClassNotFoundException*/ e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
C# | UTF-8 | 1,520 | 2.71875 | 3 | [] | no_license | using System;
using System.Text.RegularExpressions;
using RadioReport.Common.Consts;
namespace RadioReport.Common.Helpers
{
public static class RridHelper
{
private const string _uniPrefix = "uni";
public static bool CompareRridPageNumber(string rrid, byte pageNumber)
{
var pageNumberFromRrid = GetPageNumberFromRrid(rrid);
return pageNumberFromRrid.HasValue && pageNumberFromRrid.Value == pageNumber;
}
public static byte? GetPageNumberFromRrid(string rrid)
{
// Assuming the first two digits are always page number
const string regex = @"\D*(\d{2}).*";
var matches = Regex.Match(rrid, regex);
if (matches.Success)
{
var rridNumberString = matches.Groups[1].Value;
return byte.TryParse(rridNumberString, out byte result) ? result : default(byte?);
}
return null;
}
public static bool CheckRridValidityForPage(string rrid, string moduleName, byte pageNumber)
{
if (rrid == null) throw new ArgumentNullException(nameof(rrid));
return rrid.StartsWith(_uniPrefix, StringComparison.InvariantCulture) ||
ReportTypeNames.PrefixesDictionary.TryGetValue(moduleName, out var modulePrefix) &&
rrid.StartsWith(modulePrefix, StringComparison.InvariantCulture) &&
CompareRridPageNumber(rrid, pageNumber);
}
}
}
|
C++ | UTF-8 | 822 | 2.71875 | 3 | [] | no_license | #include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <poll.h>
#include "../Include/Pipe.hpp"
#include "../Include/String_Utils.hpp"
#include "../Include/File_Utils.hpp"
using namespace String;
using namespace File;
Wrappers::Pipe::Pipe(const char *path, const size_t buffer_size)
: buffer_(buffer_size),
path_{AllocateAndCopyString(path)},
fd_{-1} {}
Wrappers::Pipe::~Pipe() {
if (fd_ != -1) Close();
}
bool Wrappers::Pipe::Open(Mode mode) {
if (!FileExists(path_)) {
mkfifo(path_, 0777);
}
fd_ = open(path_, mode);
return fd_ != -1;
}
bool Wrappers::Pipe::Close() {
if (unlink(path_) == -1) return false;
fd_ = -1;
return true;
}
void Wrappers::Pipe::SetTimeout(int seconds) {
timeout_ = seconds * 1000U;
} |
Python | UTF-8 | 343 | 3.171875 | 3 | [] | no_license | from matplotlib import pyplot as plt
from matplotlib import style
style.use("ggplot")
x= [5,8,12]
y= [12,16,6]
x1= [6,9,11]
y1= [6,15,17]
plt.plot(x,y,'g',label="line 1", linewidth=5)
plt.plot(x1,y1,'c',label="line 2", linewidth=5)
plt.title("Info")
plt.ylabel("Y-axis")
plt.xlabel("X-axis")
plt.legend()
plt.grid(True,color='K')
plt.show() |
Python | UTF-8 | 3,643 | 2.984375 | 3 | [] | no_license | import tensorflow as tf
from tensorflow.keras.layers import Dense, Conv1D, Embedding, GlobalMaxPooling1D
from tensorflow.keras import Model
from tensorflow import keras as kr
import sys
import numpy as np
"""
用于文本分类的app,加载模型输入预测值,输出预测结果。右键直接运行查看
"""
# 要使用模型 先还原模型
checkpoint_path = r"./ckpt/cnn_model/cnn_model.ckpt"
embedding_dim = 64 # 词向量维度
seq_length = 600 # 序列长度
num_classes = 5 # 类别数
num_filters = 256 # 卷积核数目
kernel_size = 5 # 卷积核尺寸
vocab_size = 5000 # 词汇表达小
hidden_dim = 128 # 全连接层神经元
dropout_keep_prob = 0.5 # dropout保留比例
learning_rate = 1e-3 # 学习率
batch_size = 64 # 每批训练大小
num_epochs = 10 # 总迭代轮次
print_per_batch = 100 # 每多少轮输出一次结果
save_per_batch = 10 # 每多少轮存入tensorboard
train_dir = r'./datasets/train.txt'
val_dir = r'./datasets/val.txt'
vocab_dir = r'./datasets/c_vocab.txt'
# 模型类,卷积、全局最大池化、全连接1、全连接2
class CnnModel(Model):
def __init__(self):
super(CnnModel, self).__init__()
self.embeddings = Embedding(vocab_size, embedding_dim)
self.c1 = Conv1D(num_filters, kernel_size)
self.p1 = GlobalMaxPooling1D() # GlobalAveragePooling1D()
self.d1 = Dense(hidden_dim, activation='relu')
self.d2 = Dense(num_classes, activation='softmax')
def call(self, x):
x = self.embeddings(x)
x = self.c1(x)
x = self.p1(x)
x = self.d1(x)
y = self.d2(x)
return y
# 模型创建
model = CnnModel()
# 模型加载
model.load_weights(checkpoint_path)
# 和训练脚本一样的数据预处理
if sys.version_info[0] > 2:
is_py3 = True
else:
# reload(sys)
sys.setdefaultencoding("utf-8")
is_py3 = False
def open_file(filename, mode='r'):
"""
常用文件操作,可在python2和python3间切换.
mode: 'r' or 'w' for read or write
"""
if is_py3:
return open(filename, mode, encoding='utf-8', errors='ignore')
else:
return open(filename, mode)
def native_content(content):
if not is_py3:
return content.decode('utf-8')
else:
return content
# 数据预处理 - 词汇表映射
def read_vocab(vocab_dir):
"""读取词汇表"""
# words = open_file(vocab_dir).read().strip().split('\n')
with open_file(vocab_dir) as fp:
# 如果是py2 则每个值都转化为unicode
words = [native_content(_.strip()) for _ in fp.readlines()]
word_to_id = dict(zip(words, range(len(words))))
return words, word_to_id
def process_file_my(contents, word_to_id, max_length=600):
"""将文件转换为id表示"""
data_id, label_id = [], []
for i in range(len(contents)):
data_id.append([word_to_id[x] for x in contents[i] if x in word_to_id])
# 使用keras提供的pad_sequences来将文本pad为固定长度
x_pad = kr.preprocessing.sequence.pad_sequences(data_id, max_length)
return x_pad
words, word_to_id = read_vocab(vocab_dir)
# 待预测的文本,传入列表
# 1 2
content_text = [";【 新葡京】女神节9000万红包回馈 ,8-12号晚6-10点免费抢红包V信:zgh91575 官网:5197ff.com",
"看免费真人AV、www.amh1588.com复制到浏览器打开哟"] # np.array([[4,0.01,1,1],[2,0.19,0,5],[3,0.17,1,0]]) #1,2
img_arr = process_file_my(content_text, word_to_id)
x_predict = img_arr
result = model.predict(x_predict)
result = tf.argmax(result,1)
print('\n')
tf.print(result)
|
Markdown | UTF-8 | 2,060 | 3.03125 | 3 | [] | no_license | # laravel-push-notification
Based off of https://github.com/davibennun/laravel-push-notification with support for Laravel 5 and 5.1.
Installation
----
Update your `composer.json` file to include this package as a dependency
```json
"byrontudhope/pushnotificationlaravel": "dev-master"
```
Register the PushNotification service provider by adding it to the providers array in the `config/app.php` file.
```php
'providers' => array(
'ByronTudhope\LaravelPushNotification\PushNotificationServiceProvider'
)
```
Alias the PushNotification facade by adding it to the aliases array in the `config/app.php` file.
```php
'aliases' => array(
'PushNotification' => 'ByronTudhope\LaravelPushNotification\PushNotification',
)
```
# Configuration
Copy the config file into your project by running
```
php artisan vendor:publish
```
This will generate a config file like this
```php
array(
'iOS' => [
'environment' => env('IOS_PUSH_ENV', 'development'),
'certificate' => env('IOS_PUSH_CERT', __DIR__ . '/ios-push-notification-certificates/development/'),
'passPhrase' => env('IOS_PUSH_PASSWORD', '291923Job'),
'service' => 'apns'
],
'android' => [
'environment' => env('ANDROID_PUSH_ENV', 'development'),
'apiKey' => env('ANDROID_PUSH_API_KEY', 'yourAPIKey'),
'service' => 'gcm'
]
);
```
Where all first level keys corresponds to an service configuration, each service has its own properties, android for instance have `apiKey` and IOS uses `certificate` and `passPhrase`. You can set as many services configurations as you want, one for each app. A directory with the name 'ios-push-notification-certificates' will be added to the config folder for you to store both development and production certificates.
##### Dont forget to set `service` key to identify iOS `'service'=>'apns'` and Android `'service'=>'gcm'`
# Usage
```php
PushNotification::app('iOS')
->to($deviceToken)
->send('Hello World, i`m a push message');
``` |
Java | UTF-8 | 1,311 | 2.21875 | 2 | [] | no_license | package org.tensorflow.demo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import org.tensorflow.demo.R;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button start = (Button)findViewById(R.id.start);
Button koniec = (Button)findViewById(R.id.exit);
Button wspolrzedne = (Button)findViewById(R.id.start2);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, DetectorActivity.class));
}
});
koniec.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
System.exit(0);
}
});
wspolrzedne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, LocationActivity.class));
}
});
}
}
|
C++ | UTF-8 | 521 | 3.046875 | 3 | [] | no_license | bool searchMatrix(vector<vector<int>>& matrix, int target) {
int row_num = matrix.size();
int col_num = matrix[0].size();
int begin = 0, end = row_num * col_num - 1;
while(begin <= end){
int mid = (begin + end) / 2;
int mid_value = matrix[mid/col_num][mid%col_num];
if( mid_value == target){
return true;
}else if(mid_value < target){
//Should move a bit further, otherwise dead loop.
begin = mid+1;
}else{
end = mid-1;
}
}
return false;
}
|
Markdown | UTF-8 | 5,131 | 3.265625 | 3 | [] | no_license | title: Haskell-2
date: 2015-09-25 19:32:14
category: Haskell
tags: [Haskell]
---
# Case Expressions and Pattern Matching
`As-patterns`
语法糖
``` haskell
f s@(x:xs) = x:s -- where s means (x:xs)
```
`Wild-cards 通配符`
`head (x: _) = x`, actually we don't care where _ is, but in fact, we all know _ must a list, for `:` operator has list as its second argument.
`tail (_: x) = x`
<!-- more -->
## Pattern-Matching Semantics
匹配时严格按照由左到右,由上而下的顺序进行
匹配一般有三种结果 *fail, succedd, diverge*,比如`[1, 2]`和`[2, bot]`进行匹配,则是匹配失败,而`[2, 1]`和`[bot, 2]`进行匹配,则是diverge
`Guard`
``` haskell
sign x | x > 0 = 1
| x == 0 = 0
| x < 0 = -1
```
其中对于x的条件选择称为`Guard`
Guard的顺序不同可能会引起逻辑顺序不同
``` haskell
f x | x > 0 = 1
| x > -1 = 2
| x <= -1 = 3
f2 x | x > -1 = 2
| x > 0 = 1
| x <= -1 = 3
-- f 1 结果为 1
-- f2 1 结果为 2
```
困难一点的,对于$\perp$
``` haskell
bot = bot
take 0 _ = []
take _ [] = []
take n (x: xs) = x : take (n-1) xs
take2 _ [] = []
take2 0 _ = []
take2 n (x: xs) = x: take2 (n-1) xs
-- take 0 bot = [], bot 匹配上 _, 不需要求值
-- take2 0 bot = $\prep$ 0先匹配上_, bot匹配上[]则发生diverge
-- take bot [] = $\prep$ bot 匹配上0, 发生diverge
-- take2 bot [] = [], bot匹配上_, [] 匹配上[]
```
## Case Expressions
``` haskell
take2 m ys = case (m, ys) of
(0, _) -> []
(_, []) -> []
(n, x:xs) -> x: take2 (n-1) xs
```
`if e1 then e2 else e3`也可以看做`case e1 of True -> e2 False -> e3`
## Lazy Patterns 看上去有点吊
Lazy Patterns are *irrefutable*: matching a value *v* against *~pat* always succeeds, regardless of *pat*.简单点说就是你参数进来的时候我不看你正不正确,但是如果在等号右边被用到了,那么此时才会去进行match操作,成功或者$\perp$。
举个例子
``` haskell
reqs = client init_client resps
resps = server reqs
client init_client (resp: resps) = init_client: client (next resp) resps
server (req: reqs) = process req: server reqs
init_client = 1
next resp = resp * 2
process req = req + 10
```
这个程序的意思是,client先发出初始request, `init_client`,然后server接受request, process它返回response, 接着client使用next对resp进行处理,并发出下一条request,如此循环
从逻辑上看,对于`resps`,在`client init_client (resp: resps)`的时候,`server (req: reqs)`并没有知晓,所以`resp:resps`究竟能否不为空也并不知晓,因此这样的程序存在过早匹配,就是说我们可以将`resp:resps`先缓一缓在进行匹配
当然传统的改进是这样
``` haskell
reqs = client init_client resps
resps = server reqs
client init_client resps = init_client: client (next (head resps)) (tail resps)
server (req: reqs) = process req: server reqs
init_client = 1
next resp = resp * 2
process req = req + 10
```
这样改进,程序肯定能够运行,并且语意上也能懂,就是讲resps只要是个list就肯定能匹配上,至于运行会不会出错,那不关我的事了
lazy pattern的改进是这样的
``` haskell
reqs = client init_client resps
resps = server reqs
client init_client ~(resp: resps) = init_client: client (next resp) resps
server (req: reqs) = process req: server reqs
init_client = 1
next resp = resp * 2
process req = req + 10
```
先对`resp: resps`的非空list的匹配先缓一缓,日后如果匹配上就好,匹配不上就直接为$\perp$值
这个有点绕,需要好好理解一下。
另一个例子是Fibonacci数列。
``` haskell
fib@(1: tfib) = 1: 1: [a+b | (a, b) <- zip fib tfib]
```
$fib$ is $[1, 1, 2, 3, 5, 8, 13, \ldots]$
$tfib$ is $[1, 2, 3, 5, 8, 13, \ldots]$
$[a+b | (a, b) <- zip fib tfib]$ is $[2, 3, 5, 8, 13, \ldots]$
$1: 1: [a+b|(a, b) <- zip fib tfib]$ is $[1, 1, 2, 3, 5, 8, 13, \ldots]$ 正好就是$fib$
正确性可以得到验证,但是至于它是怎么计算出来的,转换成什么样的汇编就不清楚了
从另一个角度来看,这种写法的好处是结尾少一个tail函数。这样的写法叫做**pattern binding**.另外,按照原先的看法是在fib还不知道是什么样子的情况下,莫名地匹配上$1: tfib$的格式,理论上是不会有输出的,但事实上**pattern binding**会自动在fib前面加上`~`。
## Lexical Scoping and Nested Forms
``` haskell
-- let 用法
f x = let y = x * x
in y
```
``` haskell
-- where 用法
f x y | y > z = 1
| y == z = 2
| y < z = 3
where z = x * x
```
函数在`where`绑定中定义的名字只对本函数可见。`where`绑定不会在多个模式中共享。`where`绑定可以使用模式匹配。
``` haskell
initials :: String -> String -> String
initials firstname lastname = [f] ++ "." ++ [l] ++ "."
where (f:_) = firstname
(l:_) = lastname
```
## 有$的函数调用
$的优先级最低并且是右结合的,所以可以减少括号的写作
`sum (map sqrt[1..130])` => `sum $ map sqrt [1..130]` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.