language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
|---|---|---|---|---|---|---|---|
PHP
|
UTF-8
| 326
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
<?php
//variavel super global
//$nome = (int)$_GET["a"];
//na url após o endereço vem uma "?" ela separa as áreas
//get e post sempre vem string
//para tornar inteiro damos um "cast"
//var_dump($nome);
$ip = $_SERVER["REMOTE_ADDR"];
echo $ip;
echo "<br/>";echo "<br/>";
$nomme = $_SERVER["SCRIPT_NAME"];
echo $nomme;
|
PHP
|
UTF-8
| 583
| 2.9375
| 3
|
[] |
no_license
|
<?php
namespace App\Classes;
abstract class Controller {
public $model;
public $view;
//Requiring a model by name
public function getModel($model) {
$model = "App\\Models\\".$model;
return new $model;
}
//Requiring a view by name and passing it data if needed
public function getView($view, $data = []) {
$view .= "View";
if (file_exists(__DIR__."/../views/".$view.".php")) {
require_once __DIR__."/../views/".$view.".php";
}
else {
die("View does not exist");
}
}
}
|
Python
|
UTF-8
| 4,150
| 2.578125
| 3
|
[] |
no_license
|
# /usr/bin/python
import logging
import requests
import json
import os
database = None
mangasInfo = {}
chaptersInfo = {}
logger = logging.getLogger("mfetcher")
logger.addHandler(logging.StreamHandler())
# logger.setLevel("DEBUG")
base_mangaeden_url = "https://www.mangaeden.com/api"
base_images_url = "https://cdn.mangaeden.com/mangasimg"
loginUrl = "https://www.mangaeden.com/ajax/login"
# e.g.: https://www.mangaeden.com/ajax/login/?username=X&password=Y
logoutUrl = "https://www.mangaeden.com/ajax/logout/"
myMangaUrl = "https://www.mangaeden.com/api/mymanga"
def updateMangaDb():
r = requests.get(base_mangaeden_url + "/list/0")
global database
database = r.json()
# TODO: rewrite using other functions
def fetch(manga_name, chapter):
manga_id = None
for manga in database["manga"]:
if manga["a"] == manga_name:
manga_id = manga["i"]
break
if manga_id == None:
print "[", manga_name, "] not found"
return 1
r = requests.get(base_mangaeden_url + "/manga/" + manga_id)
manga_data = r.json()
chapters_data = manga_data["chapters"]
try:
chapter
except NameError:
chapter = None
if chapter != None:
chapter_id = None
for chapter_data in chapters_data:
if chapter_data[0] == int(chapter):
chapter_id = chapter_data[3]
break
if chapter_id == None:
print "chapter [",chapter,"] not found"
return 1
r = requests.get(base_mangaeden_url + "/chapter/" + chapter_id)
images_data = r.json()["images"]
directory = manga_name + "__" + chapter
if not os.path.exists(directory):
os.makedirs(directory)
for image_data in images_data:
image_url = image_data[1]
image_number = image_data[0]
r = requests.get(base_images_url + "/" + image_url)
f = open(directory+"/"+str(image_number)+".jpg", "w")
f.write(r.content)
f.close()
else:
print r.text
def getMangaId(mangaName):
logger.info("getting manga_id of ["+mangaName+"] from local database")
manga_id = None
for manga in database["manga"]:
if manga["a"] == mangaName:
manga_id = manga["i"]
logger.debug("found manga_id ["+manga_id+"]")
return manga_id
return None
def getChapterId(mangaId, chapterNumber):
global mangasInfo
if mangaId not in mangasInfo:
logger.debug("updating cache with manga infos")
r = requests.get(base_mangaeden_url + "/manga/" + mangaId)
manga_data = r.json()
mangasInfo[mangaId] = manga_data
manga_data = mangasInfo[mangaId]
chapters_data = manga_data["chapters"]
logger.info("getting chapter ["+str(chapterNumber)+"]")
chapter_id = None
for chapter_data in chapters_data:
chapter_index = chapter_data[0]
logger.debug("checking chapter_index ["+str(chapter_index)+"]")
if chapter_index == int(chapterNumber):
chapter_id = chapter_data[3]
logger.debug("found chapter_id ["+str(chapter_id)+"]")
return chapter_id
return None
def getImageUrl(chapterId, pageNumber):
logger.info("getting page ["+str(pageNumber)+"]")
global chaptersInfo
if chapterId not in chaptersInfo:
logger.debug("updating cache with chapter info")
r = requests.get(base_mangaeden_url + "/chapter/" + chapterId)
chapter_data = r.json()
chaptersInfo[chapterId] = chapter_data
images_data = chaptersInfo[chapterId]["images"]
for image_data in images_data:
image_number = image_data[0]
logger.debug("checking image_number ["+str(image_number)+"]")
if image_number == int(pageNumber):
image_url = image_data[1]
return base_images_url + "/" + image_url
return None
def get_page_url_from_coordinates(manga_name, chapter_number, page_number):
manga_id = getMangaId(manga_name)
chapter_id = getChapterId(manga_id, chapter_number)
return getImageUrl(chapter_id, page_number)
|
C#
|
UTF-8
| 1,707
| 3.21875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Quine_McCluskey
{
public class InSet
{
public Boolean used = false; //合成に使われたか
public int[] pin; //入力情報
public int value = 0;
public List<int> List_value = new List<int>();
public int count = 0;
public int unique = 0;
public InSet(int n)
{
pin = new int[n];
for (int i = 0; i < pin.Length; i++)
{
pin[i] = 0;
}
}
//各入力情報の問い合わせ
public Boolean IsOn(int n)
{
if (pin[n] == 1) return true;
else return false;
}
//入力値の10進数計算
public void CalcValue()
{
value = 0;
count = 0;
for(int i = 0; i < pin.Length; i++)
{
if (pin[i]==1)
{
value += (int)Math.Pow(2, pin.Length - i - 1);
count++;
}
}
if(List_value.Count == 0) List_value.Add(value);
}
public override string ToString()
{
string str = "";
for(int i = 0; i < pin.Length; i++)
{
//ドントケアでなければ表示
if(pin[i] != -1)
{
if (pin[i] == 0) str += " -X";
else str += " X";
str += (i + 1).ToString();
}
}
return str;
}
}
}
|
Go
|
UTF-8
| 1,163
| 2.78125
| 3
|
[] |
no_license
|
package shoppinglisthandler
import (
"fmt"
"net/http"
"github.com/alexandrecodigo/gorestapimysql/internal/app/grocery/repo/shoppinglistrepo"
"github.com/alexandrecodigo/gorestapimysql/internal/app/grocery/types"
"github.com/alexandrecodigo/gorestapimysql/internal/app/grocery/util"
"github.com/gin-gonic/gin"
)
// CreateHandler handler
func CreateHandler(c *gin.Context) {
var shoppingList types.ShoppingList
// App level validation
bindErr := c.BindJSON(&shoppingList)
if bindErr != nil {
c.JSON(http.StatusBadRequest, fmt.Sprint(bindErr))
return
}
// Inserting data
id, insertErr := shoppinglistrepo.Create(shoppingList)
if insertErr != nil {
c.JSON(http.StatusInternalServerError, fmt.Sprintf("Something wrong on our server"))
util.PanicError(insertErr)
} else {
shoppingList.ID = id
c.JSON(http.StatusCreated, shoppingList)
}
}
// ShowHandler show
func ShowHandler(c *gin.Context) {
id := util.GetInt64IdFromReqContext(c)
shoppingList, _ := shoppinglistrepo.FindByID(id)
// Check if resource exist
if shoppingList.ID == 0 {
c.JSON(http.StatusNotFound, "Not found")
} else {
c.JSON(http.StatusOK, shoppingList)
}
}
|
JavaScript
|
UTF-8
| 318
| 2.515625
| 3
|
[] |
no_license
|
function stageStart()
{
global.stagesCount=4;
for(var i=1;i<=global.stagesCount;i++)
{
global.stagesIndexs.push(i);
}
var stageIndex=global.stagesIndexs.splice(parseInt(global.stagesIndexs.length*Math.random()),1);
eval("stage"+stageIndex+"Define();");
global.stagesCount--;
global.currentStage.start();
};
|
JavaScript
|
UTF-8
| 164
| 2.75
| 3
|
[] |
no_license
|
// Adds a LI element to a list when the user
// clicks on the tag DIV#add_item
$('DIV#add_item').click(function () {
$('UL.my_list').append('<li>Item</li>');
});
|
Markdown
|
UTF-8
| 1,212
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
# articles
Command-line article search and tracking
Just a handy, low-maintenance tool to search thru articles by title, authors or year (and content? i forget). You manage the files on your own, and run the script as you want, no need to alert anything about changes you've made to the files.
Some much more thoughtful, explanatory stuff should go here, with screenshots.
In the meantime, check out this blog article from 2013 on it here: http://blog.hyperjeff.net/?p=178 (Note: the name of the scripts have changed since that article.)
## Installation
Type this in at the command line, from the directory containing this project.
(note: change "/usr/local/bin" to wherever you keep such executable scripts. In my case, it's ~/bin)
* mkdir -p ~/.config/articles
* echo "/path/to/your/articles" > ~/.config/articles/article_base
* chmod +x articles unread* openarticle markArticle
* cp articles unread* openarticle markArticle /usr/local/bin/
### Next Steps
Very rough state. Next things to fix:
* An install script / makefile
* Add screenshots in Readme
* Nice full explanation including file and folder naming conventions.
* Better naming of scripts, and perhaps some unifying and refactoring
-Jeff
|
Python
|
UTF-8
| 3,423
| 3.359375
| 3
|
[] |
no_license
|
# -*- coding:utf-8 -*-
# python for data analysis 2.3 babynames data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# names1880 = pd.read_csv('C:/Users/dell/Desktop/pydata/datasets/babynames/yob1880.txt', names=['name', 'sex', 'births'])
years = range(1880, 2011)
pieces = []
columns = ['name', 'sex', 'births']
for year in years:
path = 'C:/Users/dell/Desktop/pydata/datasets/babynames/yob%d.txt' % year
frame = pd.read_csv(path, names=columns)
frame['year'] = year
pieces.append(frame)
names = pd.concat(pieces, ignore_index=True)
# total_births = names.pivot_table('births', index='year',
# columns='sex', aggfunc=sum)
# total_births.plot(title='Total births by year and sex')
def add_prop(group):
# 整数除法回向下取整
births = group.births.astype(float)
group['prop'] = births / births.sum()
return group
names = names.groupby(['year', 'sex']).apply(add_prop)
# 检验分组prop总和是否为1
#print np.allclose(names.groupby(['year', 'sex']).prop.sum(), 1)
def get_top1000(group):
return group.sort_index(by='births', ascending=False)[:1000]
grouped = names.groupby(['year', 'sex'])
top1000 = grouped.apply(get_top1000)
boys = top1000[top1000.sex == 'M']
girls = top1000[top1000.sex == 'F']
total_births = top1000.pivot_table('births', index='year', columns='name',
aggfunc=sum)
subset = total_births[['John', 'Harry', 'Mary', 'Marilyn']]
# subset.plot(subplots=True, figsize=(12, 10), grid=False,
# title='Number of births per year')
table = top1000.pivot_table('prop', index='year',
columns='sex', aggfunc=sum)
# table.plot(title='Sum of table1000.prop by year and sex',
# yticks=np.linspace(0, 1.2, 13), xticks=range(1880, 2020, 10))
# plt.show()
def get_quantile_count(group, q=0.5):
group = group.sort_index(by='prop', ascending=False)
return group.prop.cumsum().searchsorted(q)[0] + 1 # searchsorted返回ndarray类型,取其数值
diversity = top1000.groupby(['year', 'sex']).apply(get_quantile_count)
diversity = diversity.unstack('sex')
# diversity.plot(title='Number of popular names in top 50%')
# 从name列取出最后一个字母
get_last_letter = lambda x: x[-1]
last_letters = names.name.map(get_last_letter)
last_letters.name = 'last_letter'
new_table = names.pivot_table('births', index=last_letters,
columns=['sex', 'year'], aggfunc=sum)
subtable = new_table.reindex(columns=[1910, 1960, 2010], level='year')
letter_prop = subtable / subtable.sum().astype(float)
# fig, axes = plt.subplots(2, 1, figsize=(10, 10))
# letter_prop['M'].plot(kind='bar', rot=0, ax=axes[0], title='Male')
# letter_prop['F'].plot(kind='bar', rot=0, ax=axes[1], title='Female', legend=False) # legend调整图例
# 图像设置(如间隔)在显示界面中可调
# plt.show()
dny_ts = letter_prop.ix[['d', 'n', 'y'], 'M'].T
all_names = top1000.name.unique()
mask = np.array(['lesl' in x.lower() for x in all_names])
lesley_like = all_names[mask]
filtered = top1000[top1000.name.isin(lesley_like)]
# print filtered.groupby('name').births.sum()
last_table = filtered.pivot_table('births', index='year',
columns='sex', aggfunc='sum')
last_table = last_table.div(last_table.sum(1), axis=0)
last_table.plot(style={'M': 'k-', 'F': 'k--'})
plt.show()
|
Java
|
UTF-8
| 18,155
| 1.585938
| 2
|
[] |
no_license
|
package cn.honry.inner.statistics.monthlyDashboard.dao.impl;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.bson.Document;
import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import cn.honry.base.bean.model.MongoLog;
import cn.honry.base.dao.impl.HibernateEntityDao;
import cn.honry.hiasMongo.basic.MongoBasicDao;
import cn.honry.inner.statistics.monthlyDashboard.dao.InnerMonthLyDao;
import cn.honry.inner.statistics.monthlyDashboard.vo.MonthlyDashboardVo;
import cn.honry.inner.statistics.registerInfoGzltj.dao.InnerRegisterInfoGzltjDao;
import cn.honry.inner.statistics.wordLoadDoctorTotal.dao.WordLoadDocDao;
import cn.honry.inner.statistics.wordLoadDoctorTotal.vo.Dashboard;
import cn.honry.inner.system.utli.ZoneManageUtil;
import cn.honry.utils.DateUtils;
import cn.honry.utils.HisParameters;
@Repository("innerMonthLyDao")
@SuppressWarnings("all")
public class InnerMonthLyDaoImpl extends HibernateEntityDao<MonthlyDashboardVo> implements InnerMonthLyDao {
private final String[] inpatientMedi={"T_INPATIENT_ITEMLIST_NOW","T_INPATIENT_ITEMLIST"};//住院主表
private final String[] inpatientFee={"T_INPATIENT_FEEINFO_NOW","T_INPATIENT_FEEINFO"};//住院费用明细
private final String[] inpatientInfo={"T_INPATIENT_INFO_NOW","T_INPATIENT_INFO"};
private final String ZY="ZY";
private final DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
@Autowired
@Qualifier(value="wordLoadDocDao")
private WordLoadDocDao wordLoadDocDao;
public void setWordLoadDocDao(WordLoadDocDao wordLoadDocDao) {
this.wordLoadDocDao = wordLoadDocDao;
}
@Resource(name = "sessionFactory")
// 为父类HibernateDaoSupport注入sessionFactory的值
public void setSuperSessionFactory(SessionFactory sessionFactory) {
super.setSessionFactory(sessionFactory);
}
@Autowired
@Qualifier(value = "innerRegisterInfoGzltjDao")
private InnerRegisterInfoGzltjDao innerRegisterInfoGzltjDao;
@Override
public void init_MYZHYBP_HospExpenses(String menuAlias, String type,String date) {
if(StringUtils.isNotBlank(date)){
Date beginDate=new Date();
List<MonthlyDashboardVo> list=null;
String begin=date+" 00:00:00";
String end=date+" 23:59:59";
List<String> tnL=wordLoadDocDao.returnInTables(begin, end, inpatientFee, "ZY");
if(tnL!=null&&tnL.size()>0){
StringBuffer buffer=new StringBuffer(200);
buffer.append("select sum(f.totCost0) as totCost0 ,f.yearAndMonth as yearAndMonth from( ");
buffer.append("select b.totCost AS totCost0,to_char(b.mon, 'yyyy-mm-dd') AS yearAndMonth from ( ");
for (int i = 0; i < tnL.size(); i++) {
if (i != 0) {
buffer.append(" union all ");
}
buffer.append("select t"+ i +".TOT_COST as totCost,");
buffer.append("t" + i + ".fee_date as mon ");
buffer.append("from " + tnL.get(i) + " t" + i);
buffer.append(" where t" + i+ ".fee_date >=to_date('"+begin+"','yyyy-mm-dd HH24:mi:ss') and t" + i+ ".fee_date <=to_date('"+end+"','yyyy-mm-dd HH24:mi:ss')");
}
buffer.append(" ) b ) f group by f.yearAndMonth");
list = super.getSession().createSQLQuery(buffer.toString())
.addScalar("yearAndMonth").addScalar("totCost0", Hibernate.DOUBLE)
.setResultTransformer(Transformers.aliasToBean(MonthlyDashboardVo.class))
.list();
DBObject query = new BasicDBObject();
query.put("yearAndMonth", date);//移除数据条件
new MongoBasicDao().remove(menuAlias+"_HOSPEXPENSES_DAY", query);//删除原来的数据
if (list!=null && list.size() > 0) {
List<DBObject> userList = new ArrayList<DBObject>();
for (MonthlyDashboardVo vo : list) {
if(vo.getTotCost0()!=null){
BasicDBObject obj = new BasicDBObject();
obj.append("totCost0", vo.getTotCost0());
obj.append("yearAndMonth", vo.getYearAndMonth());
userList.add(obj);
}
}
new MongoBasicDao().insertDataByList(menuAlias+"_HOSPEXPENSES_DAY", userList);
if(!"HIS".equals(type)){
init_MYZHYBP_HospExpenses_MoreDay(menuAlias,"2",date);
init_MYZHYBP_HospExpenses_MoreDay(menuAlias,"3",date);
}
}
wordLoadDocDao.saveMongoLog(beginDate, menuAlias+"_HOSPEXPENSES_DAY", list, date);
}
}
}
public void init_MYZHYBP_HospExpenses_MoreDay(String menuAlias, String type, String date){
Date beginDate=new Date();
BasicDBObject bdObject = new BasicDBObject();
Map<String,Double> map=new HashMap<String,Double>();
String temp;//月数据
Double dou;
String temp1;//key
String begin=null;//开始时间
String end=null;//结束时间
String queryMongo=null;//查询的表
String saveMongo=null;//保存的表
if("2".equals(type)){
//计算最后一个月日期
temp=date.substring(0,7);
begin=temp+"-01";//开始时间
queryMongo=menuAlias+"_HOSPEXPENSES_DAY";
saveMongo=menuAlias+"_HOSPEXPENSES_MONTH";
end=returnEndTime(date).split(" ")[0];
}else{
temp=date.substring(0,4);
begin=temp+"-01";
end=temp+"-12";
queryMongo=menuAlias+"_HOSPEXPENSES_MONTH";
saveMongo=menuAlias+"_HOSPEXPENSES_YEAR";
}
BasicDBList dateList=new BasicDBList();
BasicDBObject data1= new BasicDBObject();//查询开始时间
BasicDBObject data2= new BasicDBObject();//查询结束时间
data1.append("yearAndMonth", new BasicDBObject("$gte",begin));
data2.append("yearAndMonth", new BasicDBObject("$lte",end));
dateList.add(data1);
dateList.add(data2);
bdObject.put("$and", dateList);
DBCursor cursor = new MongoBasicDao().findAlldata(queryMongo, bdObject);
DBObject dbCursor;
while(cursor.hasNext()){
dbCursor = cursor.next();
Double value = (Double) dbCursor.get("totCost0") ;//费用
temp1=temp;
if(map.containsKey(temp1)){//如果key存在 比较name
dou=map.get(temp1);
dou+=value;
map.put(temp1, dou);
}else{//如果key不存在 添加到map1中
map.put(temp1, value);
}
}
DBObject query = new BasicDBObject();
query.put("yearAndMonth", temp);//移除数据条件
new MongoBasicDao().remove(saveMongo, query);//删除原来的数据
List<DBObject> userList = new ArrayList<DBObject>();
for(String key:map.keySet()){
BasicDBObject obj = new BasicDBObject();
obj.append("totCost0",map.get(key));
obj.append("yearAndMonth", key);
userList.add(obj);
}
new MongoBasicDao().insertDataByList(saveMongo, userList);
wordLoadDocDao.saveMongoLog(beginDate, saveMongo, userList, date);
}
@Override
public void init_MYZHYBP_Surgery(String menuAlias, String type, String date) {
if(StringUtils.isNotBlank(date)){
Date beginDate=new Date();
List<Dashboard> list=null;
String temp=date.substring(0,7);
String begin=temp+"-01 00:00:00";
String end=returnEndTime(date);
List<String> tnL=ZoneManageUtil.getInstance().getZoneNameListForDate(HisParameters.HISONLINEDB,"T_OPERATION_APPLY",begin,end);
List<String> inpatiionTnL=wordLoadDocDao.returnInTables(begin, end, inpatientInfo, "ZY");
if(tnL!=null&&tnL.size()>0&&inpatiionTnL!=null&&inpatiionTnL.size()>0){
StringBuffer buffer=new StringBuffer(700);
buffer.append("select TO_Char(sum(b.num)) AS value,b.dat AS name,b.dept AS dept,TO_CHAR(trunc(sum(b.days)/sum(b.num),2)) AS inhost from ( ");
for(int i=0,len=tnL.size();i<len;i++){
buffer.append("select nvl(count(t"+i+".op_id) , 0) as num,to_char(t"+i+".pre_date,'yyyy-mm') as dat,t"+i+".op_doctordept as dept,nvl(i.out_date,sysdate)-nvl(i.in_date,sysdate-2) as days ");
buffer.append("from "+tnL.get(i)+" t"+i+" left join (");
for(int j=0,len1=inpatiionTnL.size();j<len1;j++){
if(j>0){
buffer.append(" union all ");
}
buffer.append("select t"+j+".inpatient_no inpatient_no,t"+j+".in_date in_date,t"+j+".out_date out_date from "+inpatiionTnL.get(j)+" t"+j);
}
buffer.append(" ) i on t"+i+".clinic_code = i.inpatient_no where t"+i+".stop_flg = 0 and t"+i+".del_flg = 0 and t"+i+".status = 4 ");
buffer.append(" and t"+i+".pre_date between to_date('" + begin
+ "','yyyy-mm-dd HH24:mi:ss') and to_date('"
+ end + "','yyyy-mm-dd HH24:mi:ss') ");
buffer.append("group by t"+i+".pre_date,t"+i+".op_doctordept,i.in_date,i.out_date ");
}
buffer.append(" ) b group by b.dat,b.dept ");
list = super
.getSession()
.createSQLQuery(buffer.toString())
.addScalar("value")
.addScalar("name")
.addScalar("dept")
.addScalar("inhost")
.setResultTransformer(Transformers.aliasToBean(Dashboard.class))
.list();
DBObject query = new BasicDBObject();
query.put("name", temp);//移除数据条件
new MongoBasicDao().remove(menuAlias+"_SURGERY_MONTH", query);//删除原来的数据
if (list!=null && list.size() > 0) {
List<DBObject> userList = new ArrayList<DBObject>();
for (Dashboard vo : list) {
if(vo.getValue()!=null&&vo.getInhost()!=null){
BasicDBObject obj = new BasicDBObject();
obj.append("dept", vo.getDept());// 科室
obj.append("value", vo.getValue());// 手术例数统计
obj.append("name", vo.getName());// 时间
obj.append("inHost", vo.getInhost());// 住院时间
userList.add(obj);
}
}
new MongoBasicDao().insertDataByList(menuAlias+"_SURGERY_MONTH", userList);
}
wordLoadDocDao.saveMongoLog(beginDate, menuAlias+"_SURGERY_MONTH", list, date);
}
}
}
@Override
public void init_MYZHYBP_Treatment(String menuAlias, String type,
String date) {
if(StringUtils.isNotBlank(date)){
Date beginDate=new Date();
List<Dashboard> list=null;
String temp=date.substring(0,7);
String begin=temp+"-01 00:00:00";
String end=returnEndTime(date);
List<String> tnL=wordLoadDocDao.returnInTables(begin, end, inpatientInfo, "ZY");
if(tnL!=null&&tnL.size()>0){
StringBuffer buffer=new StringBuffer(770);
buffer.append("select b.stat AS stat,TO_Char(sum(b.con)) AS value,b.dat AS name,b.dept AS dept from ( ");
for(int i=0,len=tnL.size();i<len;i++){
if(i>0){
buffer.append(" union all ");
}
buffer.append("select decode(nvl(t"+i+".diag_outstate,0),0,'治愈',1,'好转',2,'未愈',3,'死亡',4,'其他') as stat,");
buffer.append("count(nvl(t"+i+".diag_outstate,0)) as con,to_char(t"+i+".out_date,'yyyy-mm') as dat,t"+i+".dept_name as dept ");
buffer.append("from "+tnL.get(i)+" t"+i+" where t"+i+".in_state in('O','B') and t"+i+".stop_flg=0 and t"+i+".del_flg=0 ");
buffer.append("and t"+i+".out_date>=to_date('"+begin+"','yyyy-mm-dd HH24:mi:ss') and t"+i+".out_date<to_date('"+end+"','yyyy-mm-dd HH24:mi:ss') ");
buffer.append("group by t"+i+".out_date,t"+i+".diag_outstate,t"+i+".dept_name ");
}
buffer.append(") b group by b.dat,b.con,b.stat,b.dept ");
list = super
.getSession()
.createSQLQuery(buffer.toString())
.addScalar("value")
.addScalar("name")
.addScalar("dept")
.addScalar("stat")
.setResultTransformer(Transformers.aliasToBean(Dashboard.class))
.list();
DBObject query = new BasicDBObject();
query.put("name", temp);//移除数据条件
new MongoBasicDao().remove(menuAlias+"_TREATMENT_MONTH", query);//删除原来的数据
if (list!=null && list.size() > 0) {
List<DBObject> userList = new ArrayList<DBObject>();
for (Dashboard vo : list) {
if(vo.getValue()!=null){
BasicDBObject obj = new BasicDBObject();
obj.append("stat", vo.getStat());// 状态
obj.append("dept", vo.getDept());// 科室
obj.append("value", vo.getValue());// 治疗数量
obj.append("name", vo.getName());// 时间
userList.add(obj);
}
}
new MongoBasicDao().insertDataByList(menuAlias+"_TREATMENT_MONTH", userList);
}
wordLoadDocDao.saveMongoLog(beginDate, menuAlias+"_TREATMENT_MONTH", list, date);
}
}
}
@Override
public void init_MYZHYBP_WardApply(String menuAlias, String type,
String date) {
if(StringUtils.isNotBlank(date)){
Date beginDate=new Date();
List<Dashboard> list=null;
String temp=date.substring(0,7);
String begin=temp+"-01 00:00:00";
String end=returnEndTime(date);
List<String> tnL=wordLoadDocDao.returnInTables(begin, end, inpatientInfo, "ZY");
if(tnL!=null&&tnL.size()>0){
StringBuffer buffer=new StringBuffer(500);
buffer.append("select round(sum(c.con)*100 /(select distinct count(1) from t_business_hospitalbed),2) AS douValue, c.dat AS name,c.dept AS dept,to_CHar(trunc(sum(c.days) / sum(c.con), 2)) as inhost from( ");
buffer.append("select count(b.dat) as con,b.dat as dat,b.dept as dept,b.days as days from( ");
for(int i=0,len=tnL.size();i<len;i++){
if(i>0){
buffer.append(" union all ");
}
buffer.append("select TO_CHAR(t"+i+".in_date,'yyyy-mm') as dat,t"+i+".dept_code as dept, nvl(t"+i+".out_date,sysdate)-t"+i+".in_date as days from "+tnL.get(i)+" t"+i+" where t"+i+".in_date between to_date('"
+ begin
+ "','yyyy-mm-dd HH24:mi:ss') and to_date('"
+ end
+ "','yyyy-mm-dd HH24:mi:ss') ");
}
buffer.append(") b group by b.dat,b.dept,b.days ");
buffer.append(") c group by c.dat ,c.dept ");
list = super
.getSession()
.createSQLQuery(buffer.toString())
.addScalar("douValue",Hibernate.DOUBLE)
.addScalar("name")
.addScalar("dept")
.addScalar("inhost")
.setResultTransformer(Transformers.aliasToBean(Dashboard.class))
.list();
DBObject query = new BasicDBObject();
query.put("name", temp);//移除数据条件
new MongoBasicDao().remove(menuAlias+"_WARDAPPLY_MONTH",query);//删除原来的数据
if (list!=null && list.size() > 0) {
List<DBObject> userList = new ArrayList<DBObject>();
for (Dashboard vo : list) {
if(vo.getDouValue()!=null&&vo.getInhost()!=null){
BasicDBObject bdObject = new BasicDBObject();
bdObject.append("dept", vo.getDept());// 科室
bdObject.append("value", vo.getDouValue().toString());// 病床使用率
bdObject.append("name", vo.getName());// 时间
bdObject.append("inhost", vo.getInhost());// 在院时间
userList.add(bdObject);
}
}
new MongoBasicDao().insertDataByList(menuAlias+"_WARDAPPLY_MONTH", userList);
}
wordLoadDocDao.saveMongoLog(beginDate, menuAlias+"_WARDAPPLY_MONTH", list, date);
}
}
}
@Override
public void init_MYZHYBP_Inpatient(String menuAlias, String type,
String date) {
if(StringUtils.isNotBlank(date)){
Date beginDate=new Date();
List<MonthlyDashboardVo> list=null;
String temp=date.substring(0,7);
String begin=temp+"-01 00:00:00";
String end=returnEndTime(date);
List<String> tnL=wordLoadDocDao.returnInTables(begin, end, inpatientInfo, "ZY");
if(tnL!=null&&tnL.size()>0){
final StringBuffer buffer = new StringBuffer(370);
buffer.append("select TO_Char(Sum(b.totCost)) AS countLeave, b.mon AS yearAndMonth,to_char(floor(sum(b.days)/sum(b.totcost))) as average from ( ");
for(int i=0,len=tnL.size();i<len;i++){
if(i>0){
buffer.append(" union all ");
}
buffer.append("select count(1) as totCost, to_char(t"+i+".in_date, 'yyyy-mm') as mon,trunc(decode(sign(t"+i+".out_date-t"+i+".in_date),-1,t"+i+".in_date + 2,t"+i+".out_date) - t"+i+".in_date,2) as days ");
buffer.append("from "+tnL.get(i)+" t"+i+" ");
buffer.append("where t"+i+".in_state = 'O' and t"+i+".in_date between to_date('"
+ begin
+ "','yyyy-mm-dd HH24:mi:ss') and to_date('"
+ end
+ "','yyyy-mm-dd HH24:mi:ss') group by t"+i+".in_date,t"+i+".out_date ");
}
buffer.append(") b group by b.mon");
list = super
.getSession()
.createSQLQuery(buffer.toString())
.addScalar("countLeave")
.addScalar("yearAndMonth")
.addScalar("average")
.setResultTransformer(
Transformers.aliasToBean(MonthlyDashboardVo.class))
.list();
DBObject query = new BasicDBObject();
query.put("yearAndMonth", temp);//移除数据条件
new MongoBasicDao().remove(menuAlias+"_INPATIENT_MONTH",query);//删除原来的数据
if (list!=null && list.size() > 0) {
List<DBObject> userList = new ArrayList<DBObject>();
for (MonthlyDashboardVo vo : list) {
if(vo.getCountLeave()!=null&&vo.getAverage()!=null){
BasicDBObject bdObject = new BasicDBObject();
bdObject.append("countLeave", vo.getCountLeave());
bdObject.append("yearAndMonth", vo.getYearAndMonth());
bdObject.append("average", vo.getAverage());
userList.add(bdObject);
}
}
new MongoBasicDao().insertDataByList(menuAlias+"_INPATIENT_MONTH", userList);
}
wordLoadDocDao.saveMongoLog(beginDate, menuAlias+"_INPATIENT_MONTH", list, date);
}
}
}
public String returnEndTime(String date){
String end=null;
date=date.substring(0,7)+"-01";
Calendar ca=Calendar.getInstance(Locale.CHINESE);
try {
ca.setTime(df.parse(date));
ca.add(Calendar.MONTH, 1);
ca.add(Calendar.DATE, -1);
end=df.format(ca.getTime())+" 23:59:59";
} catch (ParseException e) {
e.printStackTrace();
}
return end;
}
}
|
C++
|
UTF-8
| 3,239
| 2.578125
| 3
|
[] |
no_license
|
#ifndef _SCHEDULER_H
#define _SCHEDULER_H
#define OK 0
#define FAIL -1
#define SYSTEM_ERROR -2
#define MAIN_THREAD_ID 0
#define STACK_SIZE 4096
#define MAX_THREAD_NUM 100
#define USECS_IN_SEC 1000000
#include <iostream>
#include <list>
#include <memory>
#include <set>
#include <setjmp.h>
#include <signal.h>
#include <utility>
#include <unistd.h>
#include <sys/time.h>
#include <stdexcept>
#include <unordered_map>
#include <assert.h>
#include "thread.h"
#define NOT_SIGALARM SIGVTALRM + 1
#define THREAD_NOT_FOUND "thread library error: thread not found"
#define MOVE_THREAD_FAIL "thread library error: Failed to move thread"
#define SIGEMPTYSET_FAIL "system error: Failed to initiate empty signal mask"
#define SIGADDSET_FAIL "system error: Failed to add signal to mask"
#define SIGMASK_FAIL "system error: failed to create signal mask"
#define UNBLOCK_FAIL "system error: failed to unblock signals"
#define MASK_SET_FAIL "system error: failed to initialize a mask:"
#define MASK_ADD_FAIL "system error: could not add signal to mask:"
#define EMPTY_SET_FAIL "system error: could not set an empty signal mask"
#define SIGACTION_FAIL "system error: could not create sigaction"
#define SIGPENDING_FAIL "system error: could not check pending signals"
#define SIGWAIT_FAIL "system error: could not deal with pending signal"
#define SIGISMEMBER_FAIL "system error: sigismember function fail"
#define SETITIMER_FAIL "system error: failed to set the timer"
using namespace std;
//////////////////////////////////////////////////////////////////////////////////////
// Scheduler class: used by all the library functions to manage the threads //
//////////////////////////////////////////////////////////////////////////////////////
class Scheduler {
public:
//setup the scheduler at library initialization: set the time and create the signal
//masks
int setup(int quantomLength);
//for debug purposes
void getDebugData ();
void setQuantumLength (int quantum_usecs);
shared_ptr<Thread> getThread (int tid);
//creates a new thread
int spawnThread(thread_functor);
//terminates an existing thread
void terminateThread(shared_ptr<Thread>& targetThread);
//suspend a thread
void suspendThread (shared_ptr<Thread>& targetThread);
//resumes a suspended
void resumeThread (shared_ptr <Thread>& targetThread);
void sleepRunning (int quantumNum);
void quantumUpdate(int sig);
//Moves a thread to the appropriate list
void moveThread(shared_ptr<Thread>, state);
//sets the mask for signal blocking
int setMask();
int startTimer();
//blocking and unblocking signals during performing an operation
void blockSignals();
void unblockSignals();
int allocateID();
ThreadsStruct threads;
unordered_map <int,shared_ptr<Thread> > usedThreads;
int quantom_usecs;
long quanta;
private:
sigset_t mask;
struct itimerval tv;
struct sigaction action;
//resets the timer in case the threads were switched before a quantum expired
int resetTimer();
void setRunningThread(shared_ptr<Thread>);
//Cleans empty pointers to moved/deleted threads
void eraseFromState (state originalState, shared_ptr<Thread> threadToErase);
};
extern Scheduler * schd;
//Handler for timer events
void timeHandler(int signum);
#endif
|
Go
|
UTF-8
| 4,162
| 2.875
| 3
|
[] |
no_license
|
package handlers
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"strconv"
"github.com/gorilla/mux"
"landing-place/models"
"landing-place/services"
)
func GetSites(w http.ResponseWriter, r *http.Request) {
rows, err := services.GetSites()
if err != nil {
fmt.Println(err)
}
defer rows.Close()
sites := make([]*models.Site, 0)
for rows.Next() {
site := new(models.Site)
err := rows.Scan(&site.ID, &site.Title, &site.Description, &site.URL, &site.Created, &site.Rating, &site.Views)
if err != nil {
fmt.Println(err)
}
sites = append(sites, site)
}
js, _ := json.MarshalIndent(sites, "", " ")
w.Write(js)
}
func GetOneSite(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
site := new(models.Site)
row := services.GetOneSite(id)
err := row.Scan(&site.ID, &site.Title, &site.Description, &site.URL, &site.Created, &site.Rating, &site.Views)
if err == sql.ErrNoRows {
http.NotFound(w, r)
return
} else if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
/* rows, err := db.Query("SELECT s.title, array_agg(t.title) FILTER (WHERE t.title IS NOT NULL) AS tags FROM sites s LEFT JOIN sitesTags st ON s.id = st.siteid LEFT JOIN tags t ON st.tagid = t.id WHERE s.id = $1 GROUP BY s.title;", id)
if err != nil {
fmt.Println(err)
http.Error(w, "Error", 404)
return
}
fmt.Println(rows) */
/* for rows.Next() {
js, _ := json.MarshalIndent(rows, "", " ")
fmt.Println(js)
} */
js, _ := json.MarshalIndent(site, "", " ")
w.Write(js)
}
func CreateSite(w http.ResponseWriter, r *http.Request) {
site := models.Site{
Title: r.FormValue("title"),
Description: r.FormValue("description"),
URL: r.FormValue("url"),
}
/*
tags := r.FormValue("tags")
categories := r.FormValue("categories") */
err := services.CreateSite(&site)
if err != nil {
http.Error(w, "This site in database", 400)
return
}
/* var validID = regexp.MustCompile(`^[0-9]$`)
for _, value := range tags {
valid := validID.MatchString(string(value))
if valid == true {
tagID := string(value)
rows, err := db.Query("INSERT INTO sitesTags(siteId, tagId) VALUES($1, $2) returning *", site.ID, tagID)
if err != nil {
fmt.Println(err)
return
}
for rows.Next() {
tag := new(tag)
rows.Scan(&tag.Siteid, &tag.TagID)
site.Tags = append(site.Tags, tag)
}
}
}
for _, value := range categories {
valid := validID.MatchString(string(value))
if valid == true {
categoryID := string(value)
rows, err := db.Query("INSERT INTO sitesCategories(siteId, categoryId) VALUES($1, $2) returning *", site.ID, categoryID)
if err != nil {
fmt.Println(err)
return
}
for rows.Next() {
category := new(category)
rows.Scan(&category.Siteid, &category.CategoryID)
site.Categories = append(site.Categories, category)
}
}
}
*/
js, _ := json.MarshalIndent(site, "", " ")
w.Write(js)
}
func UpdateSite(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id, err := strconv.Atoi(vars["id"])
if err != nil {
fmt.Println(err)
}
site := models.Site{
ID: id,
Title: r.FormValue("title"),
Description: r.FormValue("description"),
URL: r.FormValue("url"),
}
rowsAffected, err := services.UpdateSite(&site)
if err != nil || rowsAffected == 0 {
http.Error(w, http.StatusText(500), 500)
return
}
js, _ := json.MarshalIndent(site, "", " ")
w.Write(js)
}
func DeleteSite(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
rowsAffected, err := services.DeleteSite(id)
if err != nil || rowsAffected == 0 {
http.Error(w, http.StatusText(500), 500)
return
}
fmt.Fprintf(w, "Site with id %s deleted successfully\n", id)
}
func LikeSite(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
var rating int
row := services.LikeSite(id)
err := row.Scan(&rating)
if err != nil {
fmt.Println(err)
http.Error(w, "Site not found", 404)
return
}
fmt.Fprintf(w, "Site with id %s has rating %v\n", id, rating)
}
|
JavaScript
|
UTF-8
| 668
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
// //Vars
// postId =
// headline
// body
const editPost = (e) => {
const button = e.target
const postId = e.target.parentElement.parentElement.parentElement.dataset.postid
const headline = document.querySelector(`.id${postId} .text-section h2`).innerText
const body = document.querySelector(`.id${postId} .text-section p`).innerText
const link = document.querySelector(`.id${postId} .image-section`).parentElement.href
location = `/views/edit_post.php?postId=${postId}&headline=${headline}&body=${body}&link=${link}`
}
document.querySelectorAll('.post-edit-button').forEach((button) => {
button.addEventListener('click', editPost)
})
|
PHP
|
UTF-8
| 4,437
| 2.703125
| 3
|
[] |
no_license
|
<?php
// This file initializes Mokoala
require_once '../admin/library/com/mokoala/Mokoala.php';
if ($config->site->enable_tracking == true ) { //Tracking enabled.
$last_run = ( !empty( $config->beacon->lastrun ) ? intval($config->beacon->lastrun) : NULL ); //Get the last runtime.
$time_now = time();
//Time in seconds between each run.
$delay = 604800; //7 Days
if ( $last_run ) { //Beacon has been sent at least once.
if ($time_now - $last_run >= $delay) { //its been more than a day so run our external file
$run = true;
} else { //No need to run.
//Do nothing.
$run = false;
}
} else { //Beacon never sent.
$run = true;
}
} else { //Tracking disbaled.
//Do nothing.
$run = false;
}
if ( !empty($run) && $run === true ) {
// Connect to the database
MK_Database::connect(MK_Database::DBMS_MYSQL, $config->db->host, $config->db->username, $config->db->password, $config->db->name);
$image_module = MK_RecordModuleManager::getFromType('image');
$member_module = MK_RecordModuleManager::getFromType('user');
$server_ip = ( !empty( $_SERVER['SERVER_ADDR'] ) ? $_SERVER['SERVER_ADDR'] : 'Unknown'); //The server IP address.
$site_url = $config->site->url; //The site URL from the config file.
$site_name = ( !empty( $config->site->name ) ? $config->site->name : NULL ); //Get the last runtime.
$site_email = ( !empty( $config->site->email ) ? $config->site->email : NULL ); //The site email address.
$total_members = $member_module->getTotalRecords();
$total_images = $image_module->getTotalRecords(array(array('field' => 'type_gallery', 'value' => 1)));
$total_videos = $image_module->getTotalRecords(array(array('field' => 'type_gallery', 'value' => 2)));
//API Url
$url = "http://engagefb.com/api/gallery/";
//Setup the data array.
$data = array(
'api_key' => "be121740bf988b2225a313fa1f107ca1", //API Key for this application.
'data' => array(
'time_sent' => date('Y-m-d H:i:s', $time_now), //Time stamp.
'site_url' => $site_url, //Site url.
'site_name' => $site_name, //Site name.
'site_email' => $site_email, //Site name.
'ip_address' => $server_ip, //Server IP address.
'members' => $total_members, //Total number of members.
'videos' => $total_videos, //Total number of videos.
'images' => $total_images //Total number of images.
)
);
//Build data string based on array.
$data_string = http_build_query($data);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
//execute post
$result = curl_exec($ch);
$result = json_decode($result); //Decode the JSON response.
if(!empty ($result) ) { //Response is not NULL
if( $result->status == 'ok' ) {
$success = true;
} else { //Error in the response.
$success = false;
}
//close connection
curl_close($ch);
} else { //No resposne from the server.
$success = false;
}
//Update the time last run to now.
$config_data_new = array();
$config_data_new['beacon.lastrun'] = $time_now;
if( is_array( $config_data_new ) ) {
$config = parse_ini_file('../admin/config.ini.php');
write_ini_file(array_merge_replace($config, $config_data_new), '../admin/config.ini.php');
}
}
// Send a BEACON image back to the user's browser
header( 'Content-type: image/gif' );
# The transparent, beacon image
echo chr(71).chr(73).chr(70).chr(56).chr(57).chr(97).
chr(1).chr(0).chr(1).chr(0).chr(128).chr(0).
chr(0).chr(0).chr(0).chr(0).chr(0).chr(0).chr(0).
chr(33).chr(249).chr(4).chr(1).chr(0).chr(0).
chr(0).chr(0).chr(44).chr(0).chr(0).chr(0).chr(0).
chr(1).chr(0).chr(1).chr(0).chr(0).chr(2).chr(2).
chr(68).chr(1).chr(0).chr(59);
?>
|
Java
|
UTF-8
| 1,737
| 2.859375
| 3
|
[] |
no_license
|
package wordsearch;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Matrix {
// Method create
public static char[][] create(File in) throws IOException {
// Read in 20x20-word-search.txt
@SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader(in));
String line = "";
List<String> lines = new ArrayList<>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
// Create 2D array for lines
char[][] chars = new char[lines.size()][];
for (int col = 0; col < lines.size(); col++) {
for (int row = 0; row < lines.get(col).length(); row++) {
chars[col] = lines.get(col).toCharArray();
}
}
return(chars);
}
// Method point
public static void point(List<Integer> matchList2, String word, Map<String, Integer> topTen) {
int point = 2;
for (int start = 0; start < (matchList2.size() - 4); start+=2) {
List<Integer> temp = (matchList2.subList(start, start + 6));
int x1 = temp.get(0);
int x2 = temp.get(2);
int x3 = temp.get(4);
int y1 = temp.get(1);
int y2 = temp.get(3);
int y3 = temp.get(5);
if (x1 == x2 && x2 == x3 || y1 == y2 && y2 == y3 ) {
point += 1;
}
}
if (point > 3) {
topTen.put(word, point);
}
}
}
|
Java
|
UTF-8
| 832
| 1.953125
| 2
|
[] |
no_license
|
package com.android.stanlyfang.chopstick.sample.ui.base;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.android.stanlyfang.chopstick.sample.R;
import dagger.android.AndroidInjection;
public abstract class BaseActivity extends AppCompatActivity {
Toolbar mToolbar;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidInjection.inject(this);
setContentView(getLayoutResId());
mToolbar = findViewById(R.id.toolbar);
mToolbar.setLogo(R.mipmap.ic_launcher);
mToolbar.setTitle("首页");
setSupportActionBar(mToolbar);
}
public abstract int getLayoutResId();
}
|
C++
|
UTF-8
| 2,042
| 2.890625
| 3
|
[] |
no_license
|
#include "Group.h"
Group::Group(int id, string name)
{
this->id = id;
this->name = name;
}
Group::~Group()
{
lstClient.clear();
}
string Group::getName()
{
return name;
}
void Group::setName(string name)
{
this->name = name;
}
int Group::getLstStream(vector<TCPStream*>& lstStream)
{
TCPConnector* connector;
TCPStream* rcvStream;
int size = lstClient.size();
for (int i = 0; i < size; i++)
{
Client* remoteClient = lstClient.at(i);
if (remoteClient->getStatus() == ONLINE)
{
connector = new TCPConnector();
rcvStream = connector->connect(remoteClient->getIPAddr().c_str(), remoteClient->getFilePort());
if (rcvStream != NULL)
{
lstStream.push_back(rcvStream);
}
}
}
return lstStream.size();
}
int Group::getNumOfMem()
{
return lstClient.size();
}
void Group::addMem(Client* client)
{
lstClient.push_back(client);
}
void Group::removeMem(int id)
{
int size = lstClient.size();
int i;
for (i = 0; i < size; i++)
{
if (lstClient.at(i)->getID() == id)
{
lstClient.erase(lstClient.begin() + i);
return;
}
}
}
int Group::checkExistingMem(int clientID)
{
int size = lstClient.size();
for (int i = 0; i < size; i++)
{
if (lstClient.at(i)->getID() == clientID)
return 1;
}
return 0;
}
int Group::checkStatus()
{
int size = lstClient.size();
for (int i = 0; i < size; i++)
{
Client* remoteClient = lstClient.at(i);
if (remoteClient->getStatus() == ONLINE)
{
return 1;
}
}
return 0;
}
void Group::broadcastMessage(Client* client, string msg)
{
int size = lstClient.size();
string sendMsg = getName() + "::" + client->getAlias() + ": " + msg;
for (int i = 0; i < size; i++)
{
Client* remoteClient = lstClient.at(i);
remoteClient->sendMessage(sendMsg);
}
}
|
Python
|
UTF-8
| 587
| 2.71875
| 3
|
[] |
no_license
|
import mysql.connector
class MysqlMarkSixConnector():
def __init__(self):
self.mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="666666",
database="marksix")
def batch_insert_sql(self,sql,val):
mycursor = self.mydb.cursor()
mycursor.executemany(sql, val)
self.mydb.commit()
print(mycursor.rowcount, "was inserted.")
def select_sql(self,sql):
mycursor = self.mydb.cursor()
mycursor.execute(sql)
return mycursor.fetchall()
|
JavaScript
|
UTF-8
| 369
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
/**
* Created by Abbir on 4/19/2017.
*/
//Getting the present screen size
var size = {
width: window.innerWidth || document.body.clientWidth,
height: window.innerHeight || document.body.clientHeight
}
function adjustHeight(){
var container_element = document.getElementById('container_div');
container_element.style.height = size.height+'px';
}
|
JavaScript
|
UTF-8
| 4,373
| 2.59375
| 3
|
[] |
no_license
|
var kolos = [];
var coloring = [];
var pm;
var sA;
var sS;
var sD;
var keythinga = false;
var keythings = false;
var keythingd = false;
var fadeA;
var fadeS;
var fadeD;
var payload;
var mqtt;
var reconnectTimeout = 100;
host = "mqtt.opensensors.io"
port = 443;
topic = "/users/olygamy/test"; // topic to subscribe to
username = "olygamy"; // Your OpenSensors user name
password = "wMoWHbOH"; // Your OpenSensors password
client_id = "4292"; // Your device's client id
function setup() {
createCanvas(800, 600);
for (var i = 0; i < 12; i++) {
kolos[i] = new Kolo(width / 3 + i * 33, height - 300, 20, color(200));
}
coloring[0] = color(17, 186, 177);
coloring[1] = color(16, 177, 75);
coloring[2] = color(196, 216, 46);
coloring[3] = color(241, 233, 18);
coloring[4] = color(254, 188, 18);
coloring[5] = color(248, 151, 29);
coloring[6] = color(228, 110, 170);
coloring[7] = color(238, 57, 115);
coloring[8] = color(237, 31, 36);
coloring[9] = color(174, 31, 35);
coloring[10] = color(85, 15, 14);
coloring[11] = color(0, 0, 0);
coloring[12] = color(200);
sA = 20;
sS = 20;
sD = 20;
fadeA = false;
fadeS = false;
fadeD = false;
}
function MQTTconnect() {
mqtt = new Paho.MQTT.Client(
host, port, "/ws", client_id);
var options = {
timeout: 13,
useSSL: true,
keepAliveInterval: 10,
onSuccess: onConnect,
onFailure: function (message) {
// console.log("Connection failed: " + message.errorMessage + "Retrying");
// console.log(onMessageArrived);
setTimeout(MQTTconnect, reconnectTimeout);
}
};
mqtt.startTrace();
mqtt.onConnectionLost = onConnectionLost;
mqtt.onMessageArrived = onMessageArrived;
options.userName = username;
options.password = password;
mqtt.connect(options);
}
function onConnect() {
// console.log("Connected to " + host + ":" + port);
// Connection succeeded; subscribe to our topic
mqtt.subscribe(topic, {qos: 0});
// mqtt.send(testMessage);
}
function onConnectionLost(response) {
setTimeout(MQTTconnect, reconnectTimeout);
// console.log("connection lost: " + response.errorMessage + ". Reconnecting");
}
function onMessageArrived(message) {
payload = message. payloadString;
// console.log(payload);
// document.getElementById("demo").innerHTML = payload;
// println(payload);
message = messageArrived;
// println(payload);
return payload;
}
// function getData(pm) {
// input = select('#pm25');
// pm = input.value();
// // println(pm);
// return pm;
// }
function dataFlow() {
println(payload);
if (payload > 0 && payload <= 10) {
keythinga = true;
keythings = false;
keythingd = false;
fadeA = true;
fadeS = false;
fadeD = false;
reset();
}
if (payload > 10 && payload <=20) {
keythings = true;
keythinga = true;
keythingd = false;
fadeA = false;
fadeS = true;
fadeD = false;
reset();
}
if (payload > 20 && payload <=30) {
keythingd = true;
keythinga = true;
keythings = true;
fadeA = false;
fadeS = false;
fadeD = true;
reset();
}
}
function fadein() {
if (fadeA == true) {
sA = sA + 1;
if (sA > 40) {
sA = 40;
}
}
if (fadeS == true) {
sS = sS + 1;
if (sS > 40) {
sS = 40;
}
}
if (fadeD == true) {
sD = sD + 1;
if (sD > 40) {
sD = 40;
}
}
}
function reset() {
if (sA = 40) {
sA = 20;
}
if (sS = 40) {
sS = 20;
}
if (sD = 40) {
sD = 20;
}
}
function draw() {
background(255);
for (var i = 0; i < kolos.length; i++) {
kolos[i].display();
}
dataFlow();
if (keythinga == true) {
fadein();
fill(0, 255);
ellipse(50, 50, sA, sA);
for (var i = 0; i < 1; i++) {
kolos[i].update( coloring[i], sA);
}
}
if (keythings == true) {
fadein();
fill(0, 255);
ellipse(150, 50, sS, sS);
for (var i = 1; i < 2; i++) {
kolos[i].update( coloring[i], sS);
}
}
if (keythingd == true) {
fadein();
fill(0, 255);
ellipse(250, 50, sD, sD);
for (var i = 2; i < 3; i++) {
kolos[i].update( coloring[i], sD);
}
}
}
$(document).ready(function() {
MQTTconnect();
});
|
Java
|
UTF-8
| 2,833
| 2.78125
| 3
|
[] |
no_license
|
package com.example.model.entity;
/**
* A model class for orders database table
*/
public class Order implements Entity {
private int id;
private int roomId;
private int userId;
private int daysNumber;
private int peoplesCount;
private double totalSum;
private OrderStatus status = OrderStatus.NEW;
private RoomClass roomClass;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getRoomId() {
return roomId;
}
public void setRoomId(int roomId) {
this.roomId = roomId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getDaysNumber() {
return daysNumber;
}
public void setDaysNumber(int daysNumber) {
this.daysNumber = daysNumber;
}
public double getTotalSum() {
return totalSum;
}
public void setTotalSum(double totalSum) {
this.totalSum = totalSum;
}
public OrderStatus getStatus() {
return status;
}
public void setStatus(OrderStatus status) {
this.status = status;
}
public int getPeoplesCount() {
return peoplesCount;
}
public void setPeoplesCount(int peoplesCount) {
this.peoplesCount = peoplesCount;
}
public RoomClass getRoomClass() {
return roomClass;
}
public void setRoomClass(RoomClass roomClass) {
this.roomClass = roomClass;
}
public Order() {
}
public Order(int id, int room, int user, int daysNumber, int peoplesCount, double totalSum, OrderStatus status, RoomClass roomClass) {
this.id = id;
this.roomId = room;
this.userId = user;
this.daysNumber = daysNumber;
this.peoplesCount = peoplesCount;
this.totalSum = totalSum;
this.status = status;
this.roomClass = roomClass;
}
public Order(int userId, int daysNumber, int peoplesCount, RoomClass roomClass) {
this.userId = userId;
this.daysNumber = daysNumber;
this.peoplesCount = peoplesCount;
this.roomClass = roomClass;
}
public String getStatusRus() {
switch (status) {
case NEW: return "ожидает обработки";
case IN_CONFIRM: return "ожидает подтверждения";
case PENDING_PAYMENT: return "ожидает оплаты";
case PAID: return "оплачен";
case CANCELED: return "отменен";
}
return "неизвестный";
}
public boolean inConfirmation(){
return status == OrderStatus.IN_CONFIRM;
}
public boolean isNew(){
return status == OrderStatus.NEW;
}
}
|
C#
|
UTF-8
| 3,403
| 2.640625
| 3
|
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System;
public class sendData : MonoBehaviour {
public bool dataIsReady = false;
public string server = "localhost";
private bool refined = false;
private LinkedList<lView> views = new LinkedList<lView>();
public string objectPath = "";
public string refinedObjectPath = "";
public bool dataIsRefined
{
get
{
return refined;
}
}
class lView
{
public lView(Matrix4x4 viewTrans, Matrix4x4 projTrans, string path)
{
this.viewTrans = viewTrans;
this.projTrans = projTrans;
this.path = path;
}
public string path;
public Matrix4x4 viewTrans;
public Matrix4x4 projTrans;
}
// Use this for initialization
void Start () {
Console.WriteLine("start");
}
public void addView(Matrix4x4 viewTrans, Matrix4x4 projTrans, string picPath)
{
views.AddLast(new lView(viewTrans, projTrans, picPath));
}
// Update is called once per frame
void Update () {
if (dataIsReady)
{
dataIsReady = false;
//make Thread;
Thread t = new Thread(Run);
t.Start();
}
}
private void Run()
{
try
{
BinaryReader reader;
int port = 11000;
TcpClient client = new TcpClient(server, port);
NetworkStream stream = client.GetStream();
//send data about number of pics
stream.Write(BitConverter.GetBytes(views.Count), 0, 4);
foreach(lView view in views)
{
//send matrices
for(int i = 0; i<16; i++)
stream.Write(BitConverter.GetBytes(view.projTrans[i]), 0, 4);
for (int i = 0; i < 16; i++)
stream.Write(BitConverter.GetBytes(view.viewTrans[i]), 0, 4);
//pic
reader = new BinaryReader(File.Open(view.path, FileMode.Open));
Byte[] picData = reader.ReadBytes(int.MaxValue);
//size
stream.Write(BitConverter.GetBytes(picData.Length), 0, 4);
//pic itself
stream.Write(picData, 0, picData.Length);
}
//save obj
//reader = new BinaryReader(File.Open(objectPath, FileMode.Open));
Byte[] objData = File.ReadAllBytes(objectPath);
//size
stream.Write(BitConverter.GetBytes(objData.Length), 0, 4);
//obj itself
stream.Write(objData, 0, objData.Length);
//wait for incoming data
//read data
byte[] bl = new byte[4];
stream.Read(bl, 0, 4);
bl = new byte[BitConverter.ToInt32(bl,0)];
stream.Read(bl, 0, bl.Length);
//the obj file is now in at the specified path
BinaryWriter writer = new BinaryWriter(File.Open(refinedObjectPath, FileMode.Create));
writer.Write(bl);
writer.Close();
client.Close();
}
catch(Exception e)
{
Console.Out.WriteLine("Error: " + e.ToString());
}
}
}
|
SQL
|
UTF-8
| 571
| 3.484375
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
-- +migrate Up
create table timing_new (
schedule_id text not null,
weekday_id integer default 0,
primary key (schedule_id, weekday_id)
);
insert into timing_new (schedule_id, weekday_id) select schedule_id, weekday_id from timing;
drop table timing;
alter table timing_new rename to timing;
-- +migrate Down
create table timing_old (
schedule_id text primary key,
weekday_id integer default 0
);
insert into timing_old (schedule_id, weekday_id) select schedule_id, weekday_id from timing;
drop table timing;
alter table timing_old rename to timing;
|
JavaScript
|
UTF-8
| 780
| 2.84375
| 3
|
[] |
no_license
|
/* --- Elements --- */
const $progressBar = document.querySelector(".wizard__progress-bar");
const $stage = document.querySelector("[data-stage='4']");
const $finishBuyBtn = document.querySelector(".finish-buyBtn");
let $finishForm = document.querySelector("#finish-form");
let $termsWarning = document.querySelector("#terms-warning");
let $termsCheckBox = document.querySelector("#termsChkBox");
$finishForm.addEventListener("submit", (event) => {
event.preventDefault();
if ($termsCheckBox.checked) {
$finishForm.innerHTML = "Gracias por su compra ♥";
$progressBar.value++;
$stage.classList.add("is-completed");
} else {
$termsWarning.innerHTML = "Please accept the terms and conditions";
$termsWarning.classList.add("input-warning");
}
});
|
Python
|
UTF-8
| 218
| 3.734375
| 4
|
[] |
no_license
|
ls = [x + 1 for x in range(5)]
def enumerator(lst):
for l in lst:
yield lst.index(l) + 1, l
for i in enumerator(ls):
print(i, end=' ')
print()
for i in enumerate(ls):
print(i, end=' ')
print()
|
C#
|
UTF-8
| 1,363
| 2.796875
| 3
|
[] |
no_license
|
using Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders ;
namespace Infraestructure.Persistance.PostgresSQL.EntityConfig
{
public class ActivoConfiguration : IEntityTypeConfiguration<Activo>
{
public void Configure(EntityTypeBuilder<Activo> builder)
{
// Mapeo a la tabla Activos (en plural)
builder.ToTable("Activos");
// set Id como primaryKey
builder.HasKey(a => a.Id);
// set Dominio como Index
builder.HasIndex(a => a.Dominio).IsUnique();
// set NumeroInterno como Index
builder.HasIndex(a => a.NumeroInterno).IsUnique();
// setear como no permitir null y tamaño maximo de 150
builder.Property(a => a.Dominio).IsRequired().HasMaxLength(150);
// setear como no permitir null y tamaño maximo de 300
builder.Property(p => p.Ubicacion).IsRequired().HasMaxLength(300);
builder.HasOne(u => u.TipoModelo).WithMany().HasForeignKey(x => x.TipoModeloId).IsRequired();
builder.HasOne(u => u.TipoActivo).WithMany().HasForeignKey(x => x.TipoActivoId).IsRequired();
}
}
}
|
Java
|
UTF-8
| 685
| 1.960938
| 2
|
[] |
no_license
|
package com.hy.wo.po;
import java.util.Date;
public class FaqRep {
private int id;
private Faq parent;
private String guy;
private String desc;
private Date cdate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGuy() {
return guy;
}
public void setGuy(String guy) {
this.guy = guy;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getCdate() {
return cdate;
}
public void setCdate(Date cdate) {
this.cdate = cdate;
}
public Faq getParent() {
return parent;
}
public void setParent(Faq parent) {
this.parent = parent;
}
}
|
Shell
|
UTF-8
| 608
| 3.5
| 4
|
[] |
no_license
|
#!/bin/bash
#This script checks all mounts and will send an email alert if you reach a certain threshold
#You can add this as a cronjob to monitor all mountpoints
#mackyruiz
#
ADMIN="your@email.com"
df -h | grep -vE '^Filesystem|tmpfs|cdrom' | awk '{print $5 " " $1 }' | while read output;
do
usep=$(echo $output | awk '{ print $1}' | cut -d'%' -f1 )
partition=$(echo $output | awk '{ print $2 }' )
if [ $usep -ge 85 ]; then
echo "Running out of space \"$partition ($usep%)\" as on $(date)" > /tmp/email.txt
mail -s "Alert: $partition Almost out of disk space" $ADMIN < /tmp/email.txt ;
fi
done
|
TypeScript
|
UTF-8
| 1,806
| 2.984375
| 3
|
[] |
no_license
|
import { err } from '../../common';
import CVImage from '../../CVImage';
import { Pixel } from '../../interfaces';
import { Perf } from '../../utils';
export function gaussian(
image: HTMLImageElement,
kernelSize: number,
sigma: number = 0
): HTMLCanvasElement {
const cvImage: CVImage = new CVImage(image);
Perf.timeStart(`GAUSSIAN_FILTERING`);
cvImage.kernelConvolve(action, kernelSize, getWeights(kernelSize, sigma));
Perf.timeEnd(`GAUSSIAN_FILTERING`);
return cvImage.canvas;
}
function action(pixel: Pixel, kernel: Pixel[], kernelSize: number, weights: number[]): Pixel {
const [r, g, b]: number[] = kernel.reduce(
(avgBrightnesses: number[], p: Pixel, cIdx: number): number[] => {
const pixelBrightnesses: number[] = [p.r, p.g, p.b];
return [0, 1, 2].map(
(idx: number): number => avgBrightnesses[idx] + pixelBrightnesses[idx] * weights[cIdx]
);
},
[0, 0, 0]
);
return {
r,
g,
b,
a: pixel.a
} as Pixel;
}
export function getWeights(kernelSize: number, sigma: number): number[] {
if (kernelSize % 2 === 0) {
err('Invalid kernelSize');
}
const s: number = sigma !== 0 ? sigma : getSigma(kernelSize);
const kernel: number[] = [];
const origin: number = Math.floor(kernelSize >> 1);
for (let x = 0; x < kernelSize; x += 1) {
for (let y = 0; y < kernelSize; y += 1) {
kernel[kernelSize * y + x] = getWeight(x, y, origin, s);
}
}
return kernel;
}
function getSigma(kernelSize: number): number {
return 0.3 * ((kernelSize - 1) * 0.5 - 1) + 0.8;
}
function getWeight(x: number, y: number, origin: number, sigma: number): number {
return Math.exp(
-0.5 * (Math.pow((x - origin) / sigma, 2.0) + (Math.pow((y - origin) / sigma, 2.0))))
/ (2 * Math.PI * sigma * sigma
);
}
|
Python
|
UTF-8
| 489
| 3.0625
| 3
|
[] |
no_license
|
import re
def main():
pattern = re.compile(r'\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\w{3}[-\.\s]??\w{4}')
input = open("test.txt", "r")
textToBeChanged = input.read()
results = pattern.findall(textToBeChanged)
for i in results:
print(i.replace("-", "."))
# print(i)
# print(matches)
# for match in matches:
# print(match)
if __name__ == "__main__":
main()
|
Markdown
|
UTF-8
| 26,050
| 3.046875
| 3
|
[] |
no_license
|
## 被疫情逼得gap year的完全菜鸡的春招之路。精烫
### author
JanShaw
### post-time
编辑于 2020-05-29 12:14:55
### content
<div class="post-topic-des nc-post-content">
<h3>
0、写在之前
</h3>
<div>
我知道,我的春招根本不算什么。和我的同学们相比,我只能说是平均水平罢了。但我觉得,我真的经历了很多很多,对我自己来说,我和三个月之前的我相比,我成长了很多很多。从一开始的懵懂无知,自暴自弃,再到后面的急躁,再到最后的淡然,再到后来的坚定。回忆起来,人终究是被社会毒打了一遍才能成长吧。虽然我觉得我还是曾经的少年哈哈哈,但是现在我会比较知道自己该做什么了,该怎么提高自己了。刚刚好要到22岁生日了,写点乱七八糟的东西,就当日记了。
</div>
<h3>
1、个人背景
</h3>
<div>
先简单说一下自己,某985计算机学院物联网工程专业本科,大学期间混了两年日子,大一挂一科,大二挂四科。拿了一个学业预警。大三想想要不然出国吧,均分大概75左右,因为学校可以刷分,所以大三把前面很多数学课重新学了一遍。先打算去日本,后来想想要再考一次试不太行,就转去英国,英国几乎所有学校都拒了。就打算去美国,想着能去一个随便us前50的学校学学计算机就刷刷题毕业找找工作算了。
</div>
<div>
但是疫情来了,本来定下的是2月底的托福,3月初,结果都考不了了。在2月15号左右,确定自己今年大概率来不及考托福之后,决定gap。也就是暂时不去出国了
</div>
<div>
当时的我,c语言只能过华为笔试第一题,Java学校考试60整,而且过了两年没学了,C++也完全没用过。可以说大三一年都在学日语和英语还有学理论课,唯一的一次编程还是去华为的实习笔试。
</div>
<div>
怎么办,如果就这样混着就一定完了,难道要家里蹲吗,至少得做点什么能提高自己竞争力的事情吧。
</div>
<div>
于是决定春招找工作,但一开始我完全是两眼一抹黑。怎么找,找什么样的公司,用什么找。甚至于简历都没有,完全没有工作职位的概念,连前端还是后端都没想好。
</div>
<div>
我如果有一个优点的话,那就是我还算果断。当时想了 一下,也发贴询问了大佬们。
<a href="https://www.nowcoder.com/discuss/366163" target="_blank">
我的个人背景
</a>
这是我当时发的贴子,里面有我的一些背景什么的。
</div>
<div>
我自己告诉自己,我不知道什么是最好的选择,那请选择一个第二好的吧,选一个不坏的吧。
</div>
<div>
于是我选择了Java后端。
</div>
<h3>
2、开始总是分分钟都很煎熬
</h3>
<div>
之前完全没有基础,只好从网课开始看起。选择的是同时看廖雪峰的网站和尚硅谷的300集。同时也开始海投简历。与此同时开始一点点去做剑指offer的题目,从一开始只会做最简单的数组,还是暴力求解,在学到list之后开始用list做。慢慢地一点点去做。犹记得,第一次笔试的是2月最后一天shopee家的Java。题目现在想想很简单,也就是一道二叉树的遍历,一道字符串最大连续子串。当时真的是,一点儿都不会。两点笔试,一点五十五的时候女朋友和我说,她希望把她的中介换给我,让我去和她的中介签约,她觉得她的中介不好。我想了一下,你不喜欢你的中介为什么要我去签约,我难道拿的不是我父母的钱吗。于是我就和她说,你自己去谈退款的事情,我要去笔试了。她说,我不想出国了,我也不想和你在一起了。我看到这句话打出来的时候,颤抖着发了一个,好吧。看着她把头像换掉了,我解除好友关系,开始做笔试题。可那题目它不进眼睛啊,二叉树是什么,字符串是什么,满屏好像都是她以前的笑。我直接交了白卷,我这样不行,我得收拾清楚自己。
</div>
<div>
人生是自己的,没谁一样转。没了女朋友,我至少得努力为自己弄一个不错的未来,如果我不够优秀,下一个也一样会走的。
</div>
<div>
我还记得,那天晚上,我写了十几道剑指offer的题目,好像整个人突然安静了下来,我不需要去每隔一会儿惦记着会不会有人找我了,我可以去一个很一般的公司,我也不用纠结base哪里了。我好像突然什么都没了,又好像什么都可以有了。
</div>
<h3>
3、来了来了,第一次面试的我
</h3>
<div>
3月来了,2月份投递了很多的我,3月4日笔试了第二家公司,是广州的三七互娱。第一次收到HR电话的我超紧张,想和HR商量可不可以晚一些面试,我很清楚,就自己这点儿水平,一面试就一定凉凉了。HR鼓励我说你的笔试成绩还不错,我说那就面吧,约了3月9日的面试,给了我3天的准备时间。这还准备啥啊,我立刻从JavaGuide哥的公众号上下载了Java面试的常问问题。横竖背一下啊。
</div>
<div>
三七互娱的面试我发了贴子。
</div>
<div>
<a href="https://www.nowcoder.com/discuss/381183" target="_blank">
三七互娱面经
</a>
<br/>
</div>
<div>
面试的时候没有什么感觉,后来想想,真的是乱七八糟,连UDP和TCP都说不明白。但我当时也不担心,这才刚刚开始嘛,后面我会慢慢习惯的。
</div>
<h3>
4、华为!我又来了!
</h3>
<div>
<a href="https://www.nowcoder.com/discuss/382355" target="_blank">
华为面经
</a>
<br/>
</div>
<div>
华为这个机会我几乎错失了,因为我参加过华为的实习,在主管面失败了,貌似是因为我当时说了我下半年要出国。捂脸,真是少不经事。然后秋招不知怎么的又给我捞起来,但我没去参加面试。所以 春招的笔试甚至没有邀请我,还是我主动发消息向HR学姐去问,HR学姐才发现我的情况,给我争取了不用笔试。3月14日,我经历了华为的一二三面,也记下了面经,当时还是信心满满的。一二三面一口气通过,第二天还加了一个华为的讨论群,天天在里面聊天。当时华为的面试,我发挥的非常非常好,或者说,运气非常非常好。问的刚刚好是我都会的,手撕了三道代码题,都不是很简单,但都是我前一天刚刚看过的。到三面的时候,我已经慢慢找回了自信。主管问我,你对华为的文化是怎么看的,我说既然华为是狼文化,那么小狼终究要回到狼群中,而不是羊群中。后来我知道,主管对我的印象蛮好。
</div>
<h3>
5、泡池子的日子
</h3>
<div>
经过了性格测试的补测,我正式进入华为的录取排序中状态。华为的
</div>
<div>
字节我拿到了一位师兄的内推,客户端开发,免笔试直通面试。我约在了3月18日,由于沉浸在前一天刚刚通过华为的喜悦中,这几天我都没有好好学习,到了3月18日。进入面试,面试官拿着我的简历扫了一眼。你的简历似乎没有什么客户端的项目经历啊,你确定面试的是客户端开发吗。我一看,这不行,这是要问都不问直接挂的节奏啊。于是我请求先自我介绍一下,他说不用了,我们来撕几道算法题吧。没撕出来,面试结束十分钟后,收到了感谢信,字节的效率还是很可观的,怪我自己不太行呀。浪费了宝贵的机会。第二天,是中国移动成都研究院,居然是早上面试,伤脑筋。用zoom面试,一个一个去面试,每个人的时间不长。到我的时候,问的问题我已经记不太清楚了。但应该都是蛮常规的问题。加上前一天的挫败感还在,我好好的准备了一下,我很快完成了面试。不久是27号,成都研究院给了我二面的机会,同样是早上。
</div>
<h3>
6、什么?群面?还压力面?
</h3>
<div>
成都研究院的Java软件开发的二面。一进zoom,嚯,四个人,一位HR负责主持面试。HR首先请我自我介绍,接着问了我一些关于女朋友,为什么选择成都研究院,为什么选择成都之类的常规问题。接着是几位面试官发问了,其中一位面试官直接问我,我看你发了一篇ei论文,关于机器学习方向的,直接就问了我一个关于贝叶斯的问题。 我直接愣住了,我说面试官,我只是个本科生,发论文是在老师指导之下,我只是会应用一些模型而已,调调参什么的,如果我有那么厉害的话,早就应聘贵公司的算法岗位了。面试官呵呵一笑,看着简历说,可我也不觉得你竞争Java岗位有优势呀,你的项目上也并没有什么关于Java的项目。那么我请问你,你觉得你相比较那些研究生,你觉得你在哪儿有优势能够拿到这个岗位。我想了一下说,我还年轻,我只有21岁,如果我得到这个岗位的话,给我三年的时间,我为公司创造的收益一定远远超过三年之后来的研究生们,我的薪资也比他们对公司比较能接受。而我待的时间更长,会有更强的归属感。这位面试官不说话了,另一位面试官说,你觉得你什么地方最有优势,我说我数学还挺好的。几位面试官互相看了一眼,面试就这样结束了。我内心想,完了,这个应该是没了。不过没事,我还有华为。
</div>
<h3>
7、聊到好真的不一定就能过
</h3>
<div>
<span>
思特奇:
</span>
<br/>
</div>
<div>
这次面试之后,我接下来拿到的是思特奇的面试,思特奇貌似是一家还不错的BTOB公司,也和我们学校有不错的关系,面试我的是一位长得很像主播猴哥(兰林汉)的东北大哥。我俩相谈甚欢,问题也比较常规,比较有印象的就是他问了我一个智力题,如何用500ml和400ml瓶子量出300ml。类似的问题,没答上来。别的都还OK,接下来直接HR面,问了一些关于base和薪资的问题。然后,至今,一个多月了,没联系我。推测是薪资和base踩雷了。
</div>
<div>
4399:
</div>
<div>
然后是4399的一面,直接电话面。问的问题也是比较常规,问计算机网络偏多。我问题全都答上来了,后来还是一直没有消息,发邮件去问,不久收到了感谢信。
</div>
<h3>
8、跌入低谷
</h3>
<div>
3月转瞬即逝,4月来了。按理说到了该发下来华为offer的时候,制裁来了。群里的同学们都表示从他们的渠道那里得知,由于种种原因,offer审批暂停了。也就是说,经历了整个3月的我,参加了超过15+次笔面试的我。颗粒无收。
</div>
<div>
整个4月初,我开始疯狂的降低自己的标准的,外包公司,小公司,我都投去了简历。
</div>
<div>
江苏海隆:
</div>
<div>
这是一家在南京的做对日输出软件外包的公司。负责那边一些银行系统等项目。由于我之前有打算去日本留学,所以日语底子还不错,只面试了一次,问的也非常简单,甚至有问什么是数组什么是栈这种问题。第二天就收到了HR打来的电话。大约是7k左右,在南京,愿意送我去日本出差,拿那边和这边两份工资。我当然答应了下来,他说下周给我正式offer。
</div>
<div>
上海宝信软件:
</div>
<div>
这家公司是宝武集团的专门做一些工业系统的公司,我也是从学校的就业网投递的简历。面试的时候还遇到了熟悉的人。这个公司和东北大学貌似有专门的实习机会。面试的时候是HR和两位老总,自动化部门和信息事业部门。自动化部门的面试官听我说数学还不错,连问了傅里叶变换,泰勒展开等等好几个问题。我磕磕绊绊地回忆着回答,好在另一位老总救场(您真好),说,那些都是应用数学的,人家又不是数学系的。信息事业部的老总问了我很多项目方面的问题,我的物联网项目还是比较贴近他们的,着重问了我一些职业规划的问题,比如你对架构的理解是什么。我结合李苦李前辈的经验,表达了我希望在架构方面深耕的愿望。信息事业部的老总说,你打算如何去实现你的愿望呢。我说那当然得先看公司的意思,公司希望我学什么,我优先学什么。学好架构优化也是为了公司的利益,为公司降低负担。说完HR和信息事业部的老总都笑了,说,我很喜欢你这个态度。面试结束了。
</div>
<div>
大约一周后,下午我去打篮球,听见手机通知,看到来了邮件。下意识的觉得是江苏海隆的offer到了,没想到是上海宝信的。我人生中的第一份offer啊,公司包吃住,在上海税前月薪9k,年薪11-16w。过一会儿,海隆的offer也来了,无奈拒绝。在我最绝望的时候,拿到了人生中第一次offer,还是俩,我突然又有了信心,开始继续努力了起来。
</div>
<h3>
9、渐入佳境
</h3>
<div>
这次之后不久,我收到了成都研究院通知我参加中国移动统一笔试的通知。到此我还是不确定自己通过了那次4对1面试。但反正我已经有保底offer了,不妨继续去闯,反正我毕业论文还早。4月10日,我一个晚上同时参加了建信金融和科大讯飞两家的笔试,一共4道编程题,全部100%AC,提前交卷和朋友吃夜宵去了。想一想一个月之前的我,我想恍若隔世这四个字可以用在这里。转眼4月接近中旬,4月13日我参加了顺丰一面,顺丰的面试官非常nice,在我询问他开发流程的时候,认真而耐心地向我讲解了5分钟。也让我对顺丰的看法非常好。4月14日,浩鲸科技面试和招银网络科技撞在了一起。我连续面了接近两个小时。几乎忘记了什么内容,但我知道,我都通过了。隔了两天是浩鲸科技的二面,国际业务部的主管先生亲自面试我。我很认真地向他陈述了我对于带项目的理解,和我认为的我在业务方面的优势。他直接告诉了我薪资待遇什么的,说第二天HR会再联系我。并且给了我他的微信,告诉我今后如果入职的话有什么问题可以直接去找他。主管先生真是很酷的人,我也一度很想加入浩鲸科技。薪资大约是9k*15,base是南京。第二天是招银的二面,招银的面试官大叔告诉我了什么叫工程师文化,什么叫技术氛围。我对招银的大叔说 :我觉得现在python程序员太多了,去研究汇编和操作系统的反而很少。大叔说,你错了,根本就没有什么python程序员,只有crud的程序员,和工程师。工程师就是,去拧螺丝,大扳手拧大螺丝,小扳手拧小螺丝。语言都只是工具而已,没有好坏之分。他接着和我聊了很多他对技术前景和未来的一些看法,我看到他的办公桌上,背景上,摆满了书。那时我非常向往,我想,就是这儿了吧。大叔直接喊来了HR进行HR面。我顺利通过了,几天之后我推掉了浩鲸科技的offer,在这里向主管先生说一句抱歉,祝浩鲸科技越来越好。接近四月末了,我也慢慢收心开始准备我一点儿都没有开始的毕业论文。
</div>
<h3>
10、结束,也只是开始嘛
</h3>
<div>
虽然论文一点儿也没有开始准备,但我历经金三银四的考验,一点一点把我洗得像一个不那么垃圾的计算机专业的学生了。我用一天配置完了kears的环境,慢慢读论文开始试着调参优化网络了。就在这段时间,有一天我心血来潮去看看华为官网的状态码,这是我三月每天都会做的事情。我出现了offerdate和employid。13级,北研所。也就是审批通过了。成都研究院也向我发来了体检和背景调查的通知,招银网络也进入了资料审核阶段。在这段时间我又参加了多益网络和美菜网的面试,多益网络的面试官看起来非常年轻,但是小孩据他说都上小学了,真是优秀。美菜网的小哥和我面试了整整一个早上,出的题目有一定难度,一道是关于链表的,大概是输出两个链表连续的重合部分,一道是找到树的深度最小序列。大概是这样子,记不清楚了。之后我推掉了科大讯飞的教育BG平台的面试,鸽了我一周,再好也不去了。4月末看了成都研究院的签约会,觉得这个公司非常的年轻,18年刚刚成立,看公司环境也非常不错。5月的一天早上,迷迷糊糊的我被电话叫醒,成都研究院的工作人员和我说,什么面试排名前20名,什么6岗,什么按19年来算最多29w。我晕乎乎的挂了电话,在群里和大家分享。过会儿另一个同学校的同学和我说成研院把她offer记错了,本科生是最高5岗,她被记成了研究生。天真的我觉得自己一定被记错了,于是打电话回去提醒HR,于是我光荣的降了一档。捂脸,我真是纯真的少年啊。那么春招应该就结束啦,感谢成都研究院对我的肯定。接下来,是另一个关于职业规划的故事了,先把毕业论文好好完成。然后认认真真像李苦李前辈说的那样,做一个技术上有深度的人。首先学完那本大一就买了的深入理解计算机系统吧。
</div>
<div>
<br/>
</div>
<div>
这是属于我春招的10个小片段。我相信这段日子对我的改变一定是长期而重要的。
</div>
<div>
先做一个小总结吧
</div>
<div>
<img alt="" src="https://uploadfiles.nowcoder.com/images/20200516/884129919_1589562160334_B342205C29C20C48234CE95CBBE80B46"/>
<br/>
</div>
<div>
<br/>
</div>
<div>
<br/>
</div>
<div>
<img alt="" src="https://uploadfiles.nowcoder.com/images/20200516/884129919_1589562176585_FC9B08B7BE6F940557CE80F162112897"/>
<br/>
</div>
<div>
<br/>
</div>
<div>
<br/>
</div>
<div>
这两张图是我金三银四的见证。
</div>
<div>
已挂:
</div>
<div>
笔试挂:tap4fun,米哈游,中国人寿,美团,拼多多,平安科技,疯狂游戏,快手,360,一加,网易雷火,网龙网络,吉比特,完美世界,映客直播,shopee
</div>
<div>
一面挂:三七互娱,字节跳动,思特奇,4399,建信金融,多益网络,美菜网
</div>
<div>
二面挂:顺丰科技(疑似被刷kpi)
</div>
<div>
三面挂:无
</div>
<div>
<br/>
</div>
<div>
已拒offer:
</div>
<div>
上海宝信,base上海(和技术栈不匹配,薪资偏低)
</div>
<div>
招银网络,base深圳(风评一般,随机分岗位有顾虑)
</div>
<div>
江苏海隆,base南京(薪资偏低,与长远职业规划不匹配)
</div>
<div>
浩鲸科技,base南京(薪资偏低,需要加班)
</div>
<div>
华为, base北京(需要加班,北京生活成本太高,城市不喜欢)
</div>
<div>
<br/>
</div>
<div>
选择offer:
</div>
<div>
中国移动成都研究院,base成都(小sp,城市喜欢,川妹子可爱,兼顾工作与学习)
</div>
<div>
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
</div>
<div>
(5/29 更新)
</div>
<div>
近期整理了一下在我的面试中比较高频的一些知识点,常被问到的一些问题,也就是我之前说面经时候说的常规问题,在这里做一下分享,希望大家一定要知其然并知其所以然,这样才能在面试的时候侃侃而谈,张牙舞爪(不是)。
</div>
<div>
<strong>
Java基础
</strong>
:
</div>
<div>
<ol>
<li>
HashMap的底层架构(一定要从jdk1.8之前与之后分开说,最好再展开谈一谈你对散列链表和红黑树的理解,以及为什么要使用红黑树,红黑树在几次旋转之内可以实现最佳深度)
</li>
<li>
StringBuffer 和StringBuilder的区别以及String的不变性。(这里建议要往里面细说为什么需要保证String的不变性)
</li>
<li>
重载和重写的区别
</li>
<li>
Java对于面向对象的三特性的阐述
</li>
<li>
装箱与拆箱
</li>
<li>
接口与静态类的区别(有好几种,建议多说)
</li>
<li>
静态方法与实例方法的区别
</li>
<li>
==与equals(这个建议与hashcode结合起来说,顺便还可以扩展一下object类中有哪些函数,会显得你比较了解)
</li>
<li>
ArrayList的扩容机制(这个可以深入到函数去讲,不过其实能说到每次扩充多少就已经蛮OK了)
</li>
<li>
ConcurrentHashMap和HashTable的区别(提到分段锁机制和后来的synchronized+CAS最好)
</li>
</ol>
<strong>
Java多线程:
</strong>
</div>
<div>
<ol>
<li>
线程与进程的区别
</li>
<li>
并发与并行的区别
</li>
<li>
线程的生命周期
</li>
<li>
线程死锁以及如何避免
</li>
<li>
volatile关键字
</li>
<li>
sleep和wait方法
</li>
<li>
线程池的使用(这一块比较难,建议大家自己去实现几次,就能很好的理解)
</li>
</ol>
<strong>
Java虚拟机:
</strong>
</div>
<div>
<ol>
<li>
Java的内存区域(结合进程与线程的共享以及jdk1.8之前与之后的变化去讲)
</li>
<li>
垃圾收集的常用算法
</li>
<li>
如何判断对象废弃
</li>
<li>
强引用、弱引用、软引用、虚引用等等
</li>
<li>
hotspot的分代
</li>
<li>
垃圾回收器有哪些
</li>
</ol>
</div>
<div>
<strong>
计算机网络:
</strong>
</div>
<div>
<ol>
<li>
七层与五层架构
</li>
<li>
三次握手与四次挥手
</li>
<li>
TCP、UDP的区别
</li>
<li>
TCP保证可靠传输的方法(展开讲,细讲)
</li>
<li>
post和put的区别
</li>
</ol>
暂时就说这么多吧,数据结构方面的面试问的不会太难,数据库和框架方面的问题太碎。
</div>
<div>
个人的春招应该就这样结束了,如果说让我对学弟学妹们有什么可以传授的经验的话。如果打算找工作的话,请一定提前准备好,做好长期的规划。学习应当是一件以年为单位的事情。善于利用网上的各种资源。比如我举个例子,牛客网就是一个很好的平台。当我对于很多的数据结构的不明白的时候,是没有办法去做题的,也会很影响心态。我想说,有什么是应届生最重要的武器,是很多项目吗,不是,再多项目也没有社招的人一年工作量大。是什么呢,是我们的算法基础,是我们的数据结构基础。这些才是区别最大的地方。很难有人可以静下心来去一点点琢磨那百分之一的优化,去一点点研究算法。框架会变,需求会变,设计模式和算法却不会变。你可能会说,哎呀咩总那我是转专业的,或者我数据结构和算法基础不好,怎么办。你在牛客网呀,牛客网有左神呀,左程云大佬是我非常敬佩的一位大神,10年雕琢,他对代码面试有着深厚的理解。我自己刷完一遍课程之后觉得作为打基础和进阶都非常有效果。如果你刚刚开始刷题,觉得举步维艰,我建议你报名这个课程打打基础。如果你刷完第一遍题目觉得遇到瓶颈,我建议你报名这个课程,查漏补缺。更何况,小咩我还特别为大家申请到了专属优惠。课程链接是:
<a href="https://www.nowcoder.com/courses/cover/live/350?coupon=Ap17HQD" target="_blank">
https://www.nowcoder.com/courses/cover/live/350?coupon=Ap17HQD
</a>
从链接进去报名或者选择使用咩总专属优惠码
<strong>
Ap17HQD
</strong>
,立减140元。也就是原价
<strong>
599
</strong>
的课程只要
<strong>
459
</strong>
,四舍五入等于不要钱呀,还不快给我冲?
</div>
<div>
除了技术上的,还有就是心态上,不要对自己太担心,迷茫归迷茫嘛,不妨碍你去做点什么呀。有项目,有实习的你,再在牛客网上认真刷刷题,面试提前准备一下,一定能够拥有一个良好的职业生涯的开始的。对本校的学弟学妹们,我想说,人家清华的计算机系都是我们帮忙建设的,请不要把自己当成不如清华的同学,人生路很长,比的是谁跑的更远,给我冲。
</div>
<div>
种一棵树最好的十年前,其次是现在。
</div>
<div>
加油吧
</div>
<div>
老规矩,私货时间:
</div>
<div>
这是咩总的个人博客,写的不多,希望各位看官能等我成长成长。
<a href="http://xylogbook.top/" target="_blank">
http://xylogbook.top/
</a>
</div>
<div>
牛客网博客:
<a href="https://blog.csdn.net/qq_35492946" target="_blank">
</a>
<a href="https://blog.nowcoder.net/xiaoyang" target="_blank">
https://blog.nowcoder.net/xiaoyang
</a>
</div>
<div>
私信我也可以加vx哦,一起探讨比如去美国的cs硕士求职之类的,一起加油吧。
</div>
</div>
|
C++
|
UTF-8
| 736
| 3.203125
| 3
|
[] |
no_license
|
#pragma once
#include "Node.h"
#include "Capsule.h"
class AVLTree
{
private:
public:
int nodes;
int getHeight(Node* n) { return (n == nullptr ? -1 : n->height); }
int max(int left, int right){ return (left >= right) ? left : right; }
Node* root;
AVLTree();
~AVLTree() {}
Node* find(Node* root, string* word);
Node* insert(string *word, Node* n);
Node* deleteNode(string* word, Node* n);
Node* singleRightRotate(Node* n);
Node* singleLeftRotate(Node* n);
int getBalance(Node* n) {
if (n == nullptr)
return 0;
return getHeight(n->left) - getHeight(n->right);
}
Node* findMin(Node* n);
Node* findMax(Node* n);
void printPreOrder(Node* root);
void printInOrder(Node* root);
void printPostOrder(Node* root);
};
|
Java
|
UTF-8
| 18,161
| 2.40625
| 2
|
[] |
no_license
|
package gabrielleopoldino.tools;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import java.io.*;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import static javax.net.ssl.SSLEngineResult.HandshakeStatus.*;
public class SSLEngineHelper {
private SSLEngine sslEngine;
private PipedInputStream applicationInputStream;
private PipedOutputStream applicationInputStreamOutputPipe;
private SSLEngineOutputStream applicationOutputStream;
private DataInputStream packetInputStream;
private DataOutputStream packetOutputStream;
private AlternativeIO alternativeIO;
private ByteBuffer inNetData = ByteBuffer.allocate(65535);
private ByteBuffer outNetData = ByteBuffer.allocate(65535);
protected ByteBuffer inAppData = ByteBuffer.allocate(65535);
protected ByteBuffer outAppData = ByteBuffer.allocate(65535);
private HandshakeHandler handshakeHandler;
private Lock handshakeLock = new ReentrantLock();
private Condition hasHandshake = handshakeLock.newCondition();
private ReceiveData receiveData;
private boolean closed = true;
private List<SSLEngineHelperListener> listeners = new LinkedList<>();
public SSLEngineHelper(SSLContext sslContext, InputStream inputStream, OutputStream outputStream, boolean serverMode) {
this(sslContext.createSSLEngine(), inputStream, outputStream);
this.sslEngine.setUseClientMode(!serverMode);
}
public SSLEngineHelper(SSLContext sslContext, AlternativeIO alternativeIO, boolean serverMode)
{
this(sslContext.createSSLEngine(), alternativeIO);
this.sslEngine.setUseClientMode(!serverMode);
}
public SSLEngineHelper(SSLEngine sslEngine, AlternativeIO alternativeIO)
{
this.sslEngine = sslEngine;
this.alternativeIO = alternativeIO;
}
public SSLEngineHelper(SSLEngine sslEngine, InputStream inputStream, OutputStream outputStream) {
this.sslEngine = sslEngine;
packetOutputStream = new DataOutputStream(new BufferedOutputStream(outputStream));
packetInputStream = new DataInputStream(inputStream);
//bufferedInputStream = new BufferedInputStream(packetInputStream);
}
public void connect() throws SSLException {
try {
this.handshakeHandler = new HandshakeHandler();
this.receiveData = new ReceiveData();
this.sslEngine.beginHandshake();
if (!handshakeHandler.isAlive())
handshakeHandler.start();
handshakeLock.lock();
hasHandshake.await();
applicationOutputStream = new SSLEngineOutputStream(this);
//applicationInputStream = new SSLEngineInputStream(this);
applicationInputStreamOutputPipe = new PipedOutputStream();
applicationInputStream = new PipedInputStream(applicationInputStreamOutputPipe);
closed = false;
handshakeLock.unlock();
receiveData.start();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public InputStream getInputStream() throws IOException {
if (applicationInputStream == null)
{
throw new IOException("Handshake not completed");
}
else
return applicationInputStream;
}
public OutputStream getOutputStream() throws IOException {
if (applicationOutputStream == null)
{
throw new IOException("Handshake not completed");
}
else
return applicationOutputStream;
}
public boolean isClosed()
{
return closed;
}
public void addListener(SSLEngineHelperListener listener)
{
if (listener == null) { throw new NullPointerException("listener"); }
synchronized (listeners) {
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
listeners.add(listener);
}
public void removeListener(SSLEngineHelperListener listener)
{
if (listener == null) { throw new NullPointerException("stateListener"); }
synchronized (listeners) {
listeners.remove(listener);
}
}
protected synchronized void sendAppData()
{
SSLEngineResult.HandshakeStatus hs = sslEngine.getHandshakeStatus();
if (hs != FINISHED && hs != NOT_HANDSHAKING)
{
if (!handshakeHandler.isAlive())
handshakeHandler.start();
try {
handshakeLock.lock();
hasHandshake.await();
handshakeLock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
outAppData.flip();
while (outAppData.hasRemaining()) {
SSLEngineResult res = null;
while (res == null || res.getStatus() != SSLEngineResult.Status.OK) {
try {
res = sslEngine.wrap(outAppData, outNetData);
switch (res.getStatus()) {
case OK:
//outNetData.flip();
//System.out.println("Sending Segment: "+segment);
//System.out.println("Sending: "+ Utils.toHex(outNetData.array(),0, outNetData.remaining()));
sendPacketData();
//outputLock.unlock();
outAppData.compact();
outAppData.flip();
break;
case BUFFER_OVERFLOW:
int appSize = sslEngine.getSession().getApplicationBufferSize();
if (appSize > outAppData.capacity()) {
ByteBuffer buffer = ByteBuffer.allocate(appSize);
outAppData.flip();
buffer.put(outAppData);
outAppData = buffer;
}
int netSize = sslEngine.getSession().getPacketBufferSize();
if (netSize > outNetData.capacity()) {
//enlarge the peer network packet buffer
ByteBuffer buffer = ByteBuffer.allocate(netSize);
outNetData.flip();
buffer.put(outNetData);
outNetData = buffer;
}
break;
default:
//outputLock.unlock();
}
} catch (SSLException e) {
e.printStackTrace();
}
}
}
outAppData.clear();
}
/*protected LinkedBlockingQueue<byte[]> appReceivedList = new LinkedBlockingQueue<>();
protected byte[] receiveAppData()
{
try {
return appReceivedList.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}*/
private byte[] inputBuffer = new byte[65535];
private synchronized void receivePacketData()
{
if (alternativeIO != null)
{
inNetData.put(alternativeIO.receive());
}
else
{
try {
//int totalReaded = packetInputStream.read(inNetData.array(), inNetData.limit(), inNetData.capacity());
//byte[] bytesReaded = packetInputStream.readAllBytes();
if (packetInputStream.available() > 0) {
int bytesReaded = packetInputStream.read(inputBuffer);
System.out.println("Received " + bytesReaded + " bytes");
if (bytesReaded > 0) {
inNetData.put(inputBuffer, 0, bytesReaded);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private synchronized void sendPacketData()
{
if (alternativeIO != null)
{
alternativeIO.send(outNetData.array(), outNetData.arrayOffset(), outNetData.limit());
outNetData.clear();
}
else
{
try {
outNetData.flip();
packetOutputStream.write(outNetData.array(), outNetData.arrayOffset(), outNetData.limit());
packetOutputStream.flush();
System.out.println("Sending "+ outNetData.limit()+" bytes");
outNetData.clear();
//outNetData.flip();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class HandshakeHandler extends Thread {
private boolean firstHandshake = true;
@Override
public void run() {
handshakeLock.lock();
SSLEngineResult.HandshakeStatus hs = sslEngine.getHandshakeStatus();
try {
while (hs != FINISHED && hs != NOT_HANDSHAKING) {
System.out.println(hs);
switch (hs) {
case NEED_UNWRAP:
receivePacketData();
inNetData.flip();
case NEED_UNWRAP_AGAIN:
SSLEngineResult res = sslEngine.unwrap(inNetData, inAppData);
inNetData.compact();
switch (res.getStatus()) {
case OK:
System.out.println("consumed "+res.bytesConsumed());
break;
case CLOSED:
//UdpCommon.whenSSLClosed();
break;
case BUFFER_OVERFLOW:
int appSize = sslEngine.getSession().getApplicationBufferSize();
if (appSize > inAppData.capacity()) {
ByteBuffer buffer = ByteBuffer.allocate(appSize);
buffer.put(inAppData);
inAppData = buffer;
}
break;
case BUFFER_UNDERFLOW:
break;
}
break;
case NEED_WRAP:
//outNetData.clear();
res = sslEngine.wrap(outAppData, outNetData);
switch (res.getStatus()) {
case OK:
//outNetData.flip();
sendPacketData();
//outNetData.flip();
break;
case CLOSED:
break;
case BUFFER_OVERFLOW:
int appSize = sslEngine.getSession().getApplicationBufferSize();
if (appSize > outAppData.capacity()) {
ByteBuffer b = ByteBuffer.allocate(appSize);
b.put(outAppData);
outAppData = b;
}
int netSize = sslEngine.getSession().getPacketBufferSize();
if (netSize > outNetData.capacity()) {
ByteBuffer b = ByteBuffer.allocate(netSize);
b.put(outNetData);
outNetData = b;
}
break;
case BUFFER_UNDERFLOW:
//UdpCommon.whenBufferUnderflow(sslEngine, outNetData);
break;
}
break;
case NEED_TASK:
Runnable task;
while ((task = sslEngine.getDelegatedTask()) != null) {
//new Thread(task).start();
task.run();
}
break;
default:
break;
}
hs = sslEngine.getHandshakeStatus();
}
if (firstHandshake)
{
firstHandshake = false;
//inAppData.clear();
//inAppData.limit(0);
//outAppData.clear();
synchronized (listeners)
{
for (SSLEngineHelperListener listener : listeners)
{
listener.onFirstHandshake();
}
}
}
}
catch (SSLException e) {
//TODO add um listener para quando ocorrer erro de conexão DTLS
System.err.println("Connection error");
e.printStackTrace();
} catch (BufferOverflowException e) {
e.printStackTrace();
} finally {
hasHandshake.signalAll();
handshakeLock.unlock();
}
}
}
protected class ReceiveData extends Thread
{
public ReceiveData() {
super("Receiver Data Thread");
}
private DataOutputStream applicationInputPipe;
@Override
public void run() {
applicationInputPipe = new DataOutputStream(new BufferedOutputStream(applicationInputStreamOutputPipe));
while(!isClosed()) {
SSLEngineResult.HandshakeStatus hs = sslEngine.getHandshakeStatus();
if (hs != FINISHED && hs != NOT_HANDSHAKING && !isClosed()) {
if (!handshakeHandler.isAlive())
handshakeHandler.start();
try {
handshakeLock.lock();
hasHandshake.await();
handshakeLock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int bytesProduced = 0;
try {
//inNetData.clear();
receivePacketData();
inNetData.flip();
inAppData.clear();
/*if (!inNetData.hasRemaining())
{
inNetData.flip();
continue;
}*/
SSLEngineResult res = null;
while (res == null || res.getStatus() != SSLEngineResult.Status.OK) {
res = sslEngine.unwrap(inNetData, inAppData);
inNetData.compact();
bytesProduced += res.bytesProduced();
switch (res.getStatus()) {
case BUFFER_OVERFLOW:
int appSize = sslEngine.getSession().getApplicationBufferSize();
if (appSize > inAppData.capacity()) {
ByteBuffer buffer = ByteBuffer.allocate(appSize);
buffer.put(inAppData);
inAppData = buffer;
}
int netSize = sslEngine.getSession().getPacketBufferSize();
if (netSize > inNetData.capacity()) {
ByteBuffer buffer = ByteBuffer.allocate(netSize);
buffer.put(inNetData);
inNetData = buffer;
}
break;
case BUFFER_UNDERFLOW:
//inNetData.compact();
receivePacketData();
inNetData.flip();
break;
case CLOSED:
return;
case OK:
//lenFinalArray += res.bytesProduced();
break;
}
}
if (bytesProduced <= 0)
continue;
System.out.println("Received thread read "+ bytesProduced+ " bytes");
applicationInputPipe.write(inAppData.array(), inAppData.arrayOffset(), bytesProduced);
applicationInputPipe.flush();
//appReceivedList.put(receivedData);
//Segment segment = Segment.parse(inAppData.array(), inAppData.arrayOffset(), bytesProduced);
//System.out.println("Received: "+segment.toString());
//scheduleReceive(segment);
} catch (SSLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
|
SQL
|
UTF-8
| 511
| 2.828125
| 3
|
[] |
no_license
|
CREATE TABLE `customer` (
`id` bigint(16) unsigned NOT NULL AUTO_INCREMENT,
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_by` varchar(32) NOT NULL DEFAULT '',
`updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated_by` varchar(32) NOT NULL DEFAULT '',
`username` varchar(32) NOT NULL DEFAULT '' COMMENT '用户名',
`nickname` varchar(32) NOT NULL DEFAULT '' COMMENT '昵称',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
Python
|
UTF-8
| 2,145
| 2.71875
| 3
|
[] |
no_license
|
import random
import torch
import torch.utils.data as data
import torch.utils.data.dataset as dataset
import numpy as np
import pickle
from sklearn.preprocessing import MinMaxScaler, StandardScaler
class Nav_Dataset(dataset.Dataset):
def __init__(self):
self.full_data = np.genfromtxt('saved/training_data.csv', delimiter=',')
self.norm_scaler = MinMaxScaler()
self.norm_scaler_full = MinMaxScaler()
self.norm_scaler_full.fit(self.full_data)
self.std_scaler = StandardScaler()
self.y = self.full_data[:,-1]
self.X =self. full_data[:,:-1]
self.X_norm = self.norm_scaler.fit_transform(self.X)
self.X_std = self.std_scaler.fit_transform(self.X) # fits and transforms
pickle.dump(self.norm_scaler_full, open("saved/scaler.pkl", "wb")) # save to normalize at inference
def __len__(self):
return self.X[:, 0].size
def __getitem__(self, idx):
if not isinstance(idx, int):
idx = idx.item()
return {'input': self.X_norm[idx],
'label': self.y[idx]}
8
class Data_Loaders():
def __init__(self, batch_size):
self.nav_dataset = Nav_Dataset()
n = len(self.nav_dataset)
split_idx = int(n * .75)
idx = list(range(n))
random.shuffle(idx)
train_idx, test_idx = idx[:split_idx], idx[split_idx:]
train_set = data.Subset(self.nav_dataset, train_idx)
test_set = data.Subset(self.nav_dataset, test_idx)
self.train_loader = data.DataLoader(train_set, batch_size=batch_size, shuffle=True)
self.test_loader = data.DataLoader(test_set, batch_size=batch_size, shuffle=False)
def main():
batch_size = 16
data_loaders = Data_Loaders(batch_size)
# STUDENTS : note this is how the dataloaders will be iterated over, and cannot be deviated from
for idx, sample in enumerate(data_loaders.train_loader):
input, label = sample['input'], sample['label']
for idx, sample in enumerate(data_loaders.test_loader):
input, label = sample['input'], sample['label']
if __name__ == '__main__':
main()
|
C++
|
UTF-8
| 678
| 2.8125
| 3
|
[] |
no_license
|
#ifndef LU_DEBUG_H
#define LU_DEBUG_H
#include <iosfwd>
#include "Matrix.h"
inline
bool operator==(const Matrix &lhs, const Matrix &rhs) {
return lhs.size() == rhs.size()
and std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
inline
std::ostream &operator<<(std::ostream &os, const Matrix &mat) {
std::size_t n = mat.size();
auto it = mat.begin();
os << '{';
for (unsigned i = 0; i < n; ++i) {
if (i) os << ' ';
os << '{';
for (unsigned j = 0; j < n; ++j) {
if (j) os << ' ';
os << *it;
++it;
}
os << '}';
}
os << '}';
return os;
}
#endif //LU_DEBUG_H
|
Java
|
UTF-8
| 229
| 1.898438
| 2
|
[] |
no_license
|
package services.category;
import java.util.List;
import org.springframework.stereotype.Service;
import entities.Category;
@Service
public interface CategoryService {
List<Category> findAll();
Category findById(Long id);
}
|
Python
|
UTF-8
| 365
| 4.03125
| 4
|
[] |
no_license
|
pizza_tooplings = ['onion','tomato']
if 'onion' in pizza_tooplings:
#这里只是一个简单的if语句,因此无论是否通过,都会继续执行下面的代码,而不是跳过后面的测试
print('只使用if的情况')
if 'tomato' in pizza_tooplings:
print('\n满足多个条件')
print('\n因为满足条件,上面的两条print都会输出')
|
C++
|
UTF-8
| 925
| 2.5625
| 3
|
[] |
no_license
|
#include <cstdio>
#include <iostream>
#include <map>
#include <string>
#include <cstdlib>
#include <cstdlib>
using namespace std;
string a, b, list[120];
int T, n, m, cnt;
int main() {
cin >> T;
for (int t = 1; t <= T; ++t) {
cin >> n >> m;
map<string, string> ma;
for (int i = 0; i < m; ++i) {
cin >> a >> b;
ma[a] = b;
}
cnt = 0;
while (cin >> list[cnt]) {
for (int i = 1; i < n; ++i) {
if (!ma.count(list[cnt]))
break;
else
list[cnt] = ma[list[cnt]];
}
cnt++;
if (getchar() != ' ') break;
}
cout << "Case #" << t << ": ";
for (int i = 0; i < cnt - 1; ++i)
cout << list[i] << " ";
cout << list[cnt - 1] << endl;
}
return 0;
}
|
PHP
|
UTF-8
| 4,700
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Modules\MgTimecode\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
class MgTimecodeController extends Controller
{
/**
* Display a listing of the resource.
* @return Response
*/
public function index()
{
$timecodes = \Modules\MgTimecode\Entities\Timecodes::get();
return view('mgtimecode::index', compact('timecodes'));
}
/**
* Show the form for creating a new resource.
* @return Response
*/
public function create()
{
return view('mgtimecode::create');
}
/**
* Store a newly created resource in storage.
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
try{
if( $request->method('post') && $request->ajax() ){
$rules = [
'timecode' => 'required|min:2|max:50'
];
$messages = [
'timecode.required' => trans('mgtimecode::ui.display.error_required', ['attribute' => trans('mgtimecode::ui.attribute.timecode')]),
'timecode.min' => trans('mgtimecode::ui.display.error_min2', ['attribute' => trans('mgtimecode::ui.attribute.timecode')]),
'timecode.max' => trans('mgtimecode::ui.display.error_max50', ['attribute' => trans('mgtimecode::ui.attribute.timecode')])
];
$validator = \Validator::make($request->all(), $rules, $messages);
if ( $validator->fails() ) {
return Response(['msg' => $validator->errors()->all()], 402)->header('Content-Type', 'application/json');
} else {
\Modules\MgTimecode\Entities\Timecodes::create([
'timecode' => ucwords( $request->input('timecode') )
]);
return Response(['msg' => "success", 200])->header('Content-Type', 'application/json');
}
}
} catch(\Exception $e){
return Response(['msgError' => "Ocurrio un error, verificar con el administrador.", 'error' => $e->getMessage()], 400)->header('Content-Type', 'application/json');
}
}
/**
* Show the specified resource.
* @return Response
*/
public function show()
{
return view('mgtimecode::show');
}
/**
* Show the form for editing the specified resource.
* @return Response
*/
public function edit($id)
{
return \Modules\MgTimecode\Entities\Timecodes::find($id);
}
/**
* Update the specified resource in storage.
* @param Request $request
* @return Response
*/
public function update(Request $request)
{
if( $request->method('post') && $request->ajax() ){
$rules = [
'timecode' => 'required|min:2|max:50'
];
$messages = [
'timecode.required' => trans('mgtimecode::ui.display.error_required', ['attribute' => trans('mgtimecode::ui.attribute.timecode')]),
'timecode.min' => trans('mgtimecode::ui.display.error_min2', ['attribute' => trans('mgtimecode::ui.attribute.timecode')]),
'timecode.max' => trans('mgtimecode::ui.display.error_max50', ['attribute' => trans('mgpersonal::ui.attribute.timecode')])
];
$validator = \Validator::make($request->all(), $rules, $messages);
if ( $validator->fails() ) {
return Response(['msg' => $validator->errors()->all()], 402)->header('Content-Type', 'application/json');
} else {
\Modules\MgTimecode\Entities\Timecodes::where('id', $request->input('id'))
->update([
'timecode' => ucwords( $request->input('timecode') )
]);
$request->session()->flash('message', trans('mgtimecode::ui.flash.flash_create_timecode'));
return Response(['msg' => 'success'], 200)->header('Content-Type', 'application/json');
}
}
}
/**
* Remove the specified resource from storage.
* @return Response
*/
public function destroy($id)
{
\Modules\MgTimecode\Entities\Timecodes::destroy($id);
\Request::session()->flash('message', trans('mg::ui.flash.flash_delete_timecode'));
return redirect('mgtimecode');
}
}
|
TypeScript
|
UTF-8
| 357
| 3.671875
| 4
|
[] |
no_license
|
class Base
{
fun()
{
console.log("Inside Fun");
}
constructor(no1,no2)
{
console.log("Addition is : ",no1+no2);
}
}
class Derived extends Base
{
Gun()
{
console.log("Inside Derived Class")
}
}
var obj1=new Base(66,33);
// obj1.fun();
var dobj=new Derived(22,44);
dobj.Gun();
|
Java
|
UTF-8
| 11,179
| 1.601563
| 2
|
[
"Unlicense",
"CC-BY-3.0",
"LicenseRef-scancode-public-domain",
"CC0-1.0"
] |
permissive
|
package crazypants.enderio.machine.painter.blocks;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.enderio.core.common.BlockEnder;
import crazypants.enderio.IModObject;
import crazypants.enderio.ModObject;
import crazypants.enderio.block.BlockDarkSteelTrapDoor;
import crazypants.enderio.machine.MachineRecipeRegistry;
import crazypants.enderio.machine.painter.recipe.BasicPainterTemplate;
import crazypants.enderio.paint.IPaintable;
import crazypants.enderio.paint.PainterUtil2;
import crazypants.enderio.paint.render.PaintHelper;
import crazypants.enderio.paint.render.PaintRegistry;
import crazypants.enderio.render.IBlockStateWrapper;
import crazypants.enderio.render.ICacheKey;
import crazypants.enderio.render.IRenderMapper;
import crazypants.enderio.render.ISmartRenderAwareBlock;
import crazypants.enderio.render.dummy.BlockMachineBase;
import crazypants.enderio.render.pipeline.BlockStateWrapperBase;
import crazypants.enderio.render.property.EnumRenderPart;
import crazypants.enderio.render.property.IOMode.EnumIOMode;
import crazypants.enderio.render.registry.SmartModelAttacher;
import crazypants.enderio.render.util.QuadCollector;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.client.renderer.block.model.IBakedModel;
import net.minecraft.client.renderer.block.model.ModelRotation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockPaintedTrapDoor extends BlockDarkSteelTrapDoor implements ITileEntityProvider, IPaintable.ITexturePaintableBlock, ISmartRenderAwareBlock,
IRenderMapper.IBlockRenderMapper.IRenderLayerAware, IRenderMapper.IItemRenderMapper.IItemModelMapper {
public static BlockPaintedTrapDoor create_wooden() {
BlockPaintedTrapDoor result = new BlockPaintedTrapDoor(ModObject.blockPaintedWoodenTrapdoor, Material.WOOD, false);
result.init();
MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPainter.getUnlocalisedName(), new BasicPainterTemplate<BlockPaintedTrapDoor>(result,
Blocks.TRAPDOOR));
return result;
}
public static BlockPaintedTrapDoor create_iron() {
BlockPaintedTrapDoor result = new BlockPaintedTrapDoor(ModObject.blockPaintedIronTrapdoor, Material.IRON, false);
result.init();
MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPainter.getUnlocalisedName(),
new BasicPainterTemplate<BlockPaintedTrapDoor>(result, Blocks.IRON_TRAPDOOR));
return result;
}
public static BlockPaintedTrapDoor create_dark() {
BlockPaintedTrapDoor result = new BlockPaintedTrapDoor(ModObject.blockPaintedDarkSteelTrapdoor, Material.IRON, true);
result.init();
MachineRecipeRegistry.instance.registerRecipe(ModObject.blockPainter.getUnlocalisedName(),
new BasicPainterTemplate<BlockPaintedTrapDoor>(result, ModObject.blockDarkSteelTrapdoor.getBlock()));
return result;
}
protected BlockPaintedTrapDoor(IModObject modObject, Material materialIn, boolean isBlastResistant) {
super(modObject, materialIn, isBlastResistant);
setCreativeTab(null);
}
@Override
protected void init() {
GameRegistry.register(this);
GameRegistry.register(new BlockItemPaintedBlock(this, modObject.getUnlocalisedName()));
SmartModelAttacher.registerNoProps(this);
PaintRegistry.registerModel("trapdoor_bottom", new ResourceLocation("minecraft", "block/wooden_trapdoor_bottom"), PaintRegistry.PaintMode.ALL_TEXTURES);
PaintRegistry.registerModel("trapdoor_top", new ResourceLocation("minecraft", "block/wooden_trapdoor_top"), PaintRegistry.PaintMode.ALL_TEXTURES);
PaintRegistry.registerModel("trapdoor_open", new ResourceLocation("minecraft", "block/wooden_trapdoor_open"), PaintRegistry.PaintMode.ALL_TEXTURES);
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityPaintedBlock();
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase player, ItemStack stack) {
setPaintSource(state, world, pos, PainterUtil2.getSourceBlock(stack));
if (!world.isRemote) {
world.notifyBlockUpdate(pos, state, state, 3);
}
}
@Override
public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) {
if (willHarvest) {
return true;
}
return super.removedByPlayer(state, world, pos, player, willHarvest);
}
@Override
public void harvestBlock(World worldIn, EntityPlayer player, BlockPos pos, IBlockState state, @Nullable TileEntity te, @Nullable ItemStack stack) {
super.harvestBlock(worldIn, player, pos, state, te, stack);
super.removedByPlayer(state, worldIn, pos, player, true);
}
@Override
public List<ItemStack> getDrops(IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
List<ItemStack> drops = super.getDrops(world, pos, state, fortune);
for (ItemStack drop : drops) {
PainterUtil2.setSourceBlock(drop, getPaintSource(state, world, pos));
}
return drops;
}
@Override
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player) {
final ItemStack pickBlock = super.getPickBlock(state, target, world, pos, player);
PainterUtil2.setSourceBlock(pickBlock, getPaintSource(null, world, pos));
return pickBlock;
}
@Override
public void setPaintSource(IBlockState state, IBlockAccess world, BlockPos pos, @Nullable IBlockState paintSource) {
TileEntity te = world.getTileEntity(pos);
if (te instanceof IPaintable.IPaintableTileEntity) {
((IPaintableTileEntity) te).setPaintSource(paintSource);
}
}
@Override
public void setPaintSource(Block block, ItemStack stack, @Nullable IBlockState paintSource) {
PainterUtil2.setSourceBlock(stack, paintSource);
}
@Override
public IBlockState getPaintSource(IBlockState state, IBlockAccess world, BlockPos pos) {
TileEntity te = BlockEnder.getAnyTileEntitySafe(world, pos);
if (te instanceof IPaintable.IPaintableTileEntity) {
return ((IPaintableTileEntity) te).getPaintSource();
}
return null;
}
@Override
public IBlockState getPaintSource(Block block, ItemStack stack) {
return PainterUtil2.getSourceBlock(stack);
}
@Override
public IBlockState getExtendedState(IBlockState state, IBlockAccess world, BlockPos pos) {
if (state != null && world != null && pos != null) {
IBlockStateWrapper blockStateWrapper = new BlockStateWrapperBase(state, world, pos, this);
blockStateWrapper.addCacheKey(getPaintSource(state, world, pos)).addCacheKey(state.getValue(FACING)).addCacheKey(state.getValue(OPEN))
.addCacheKey(state.getValue(HALF));
blockStateWrapper.bakeModel();
return blockStateWrapper;
} else {
return state;
}
}
@Override
@SideOnly(Side.CLIENT)
public IItemRenderMapper getItemRenderMapper() {
return this;
}
@SideOnly(Side.CLIENT)
private IBakedModel mapRender(IBlockState state, @Nullable IBlockState paint) {
EnumFacing facing = state.getValue(FACING);
Boolean open = state.getValue(OPEN);
DoorHalf half = state.getValue(HALF);
String model;
ModelRotation modelState;
if (open) {
model = "trapdoor_open";
switch (facing) {
case EAST:
modelState = ModelRotation.X0_Y90;
break;
case SOUTH:
modelState = ModelRotation.X0_Y180;
break;
case WEST:
modelState = ModelRotation.X0_Y270;
break;
default:
modelState = null;
}
} else if (half == DoorHalf.TOP) {
model = "trapdoor_top";
modelState = null;
} else {
model = "trapdoor_bottom";
modelState = null;
}
return PaintRegistry.getModel(IBakedModel.class, model, paint, modelState);
}
@Override
@SideOnly(Side.CLIENT)
public @Nonnull ICacheKey getCacheKey(@Nonnull Block block, @Nonnull ItemStack stack, @Nonnull ICacheKey cacheKey) {
return cacheKey.addCacheKey(getPaintSource(block, stack));
}
@Override
@SideOnly(Side.CLIENT)
public List<IBakedModel> mapItemRender(Block block, ItemStack stack) {
IBlockState paintSource = getPaintSource(block, stack);
IBlockState stdOverlay = BlockMachineBase.block.getDefaultState().withProperty(EnumRenderPart.SUB, EnumRenderPart.PAINT_OVERLAY);
IBakedModel model1 = PaintRegistry.getModel(IBakedModel.class, "trapdoor_bottom", paintSource, null);
IBakedModel model2 = PaintRegistry.getModel(IBakedModel.class, "trapdoor_bottom", stdOverlay, PaintRegistry.OVERLAY_TRANSFORMATION3);
List<IBakedModel> list = new ArrayList<IBakedModel>();
list.add(model1);
list.add(model2);
return list;
}
@Override
public boolean canRenderInLayer(BlockRenderLayer layer) {
return true;
}
@Override
@SideOnly(Side.CLIENT)
public void getSubBlocks(Item itemIn, CreativeTabs tab, List<ItemStack> list) {
if (tab != null) {
super.getSubBlocks(itemIn, tab, list);
}
}
@Override
@SideOnly(Side.CLIENT)
public List<IBlockState> mapBlockRender(IBlockStateWrapper state, IBlockAccess world, BlockPos pos, BlockRenderLayer blockLayer,
QuadCollector quadCollector) {
IBlockState paintSource = getPaintSource(state, world, pos);
if (PainterUtil2.canRenderInLayer(paintSource, blockLayer)) {
quadCollector.addFriendlybakedModel(blockLayer, mapRender(state, paintSource), paintSource, MathHelper.getPositionRandom(pos));
}
return null;
}
@Override
@SideOnly(Side.CLIENT)
public EnumMap<EnumFacing, EnumIOMode> mapOverlayLayer(IBlockStateWrapper state, IBlockAccess world, BlockPos pos, boolean isPainted) {
return null;
}
@SideOnly(Side.CLIENT)
@Override
public boolean addHitEffects(IBlockState state, World world, RayTraceResult target, ParticleManager effectRenderer) {
return PaintHelper.addHitEffects(state, world, target, effectRenderer);
}
@SideOnly(Side.CLIENT)
@Override
public boolean addDestroyEffects(World world, BlockPos pos, ParticleManager effectRenderer) {
return PaintHelper.addDestroyEffects(world, pos, effectRenderer);
}
}
|
Markdown
|
UTF-8
| 4,934
| 2.75
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
---
title: "PyGRB: A pure Python gamma-ray burst analysis package."
tags:
- python
- astrophysics
- cosmology
- gamma-ray bursts
- gravitational lensing
authors:
- name: James R. Paynter
orcid: 0000-0002-9672-4008
affiliation: 1
affiliations:
- name: School of Physics, University of Melbourne, Parkville, Victoria, 3010, Australia
index: 1
date: 16 July 2020
bibliography: paper.bib
---
# Introduction
Gamma-ray bursts (GRBs) are short and intense bursts of low energy (keV -- MeV) gamma radiation.
Their cosmological origin and transient nature makes them important probes of the universe and its structure.
Since their discovery astronomers have sought to model the high energy emission.
A popular and enduring model, although phenomenological, is the fast-rise exponential-decay (FRED) pulse [@norris2005; @norris1996],
$$
S(t|A,\Delta,\tau,\xi) = A \exp \left[ - \xi \left( \frac{t - \Delta}{\tau} + \frac{\tau}{t-\Delta} \right) \right].
$$
# Statement of Need
The analysis of large amounts of light-curves requires downloading FITS files from the relevant server.
To do this by hand is a tiring prospect for the 2,704 GRBs observed by the Burst and Transient Source Explorer (BATSE) experiment [@batse].
Having downloaded a FITS file, a scientist would then need to unpack the data from the file, and extract the relevant tables to construct a light-curve.
They may then want to plot the light-curve for publication, requiring them to write more software to appropriately represent the data.
Ultimately, they may want to look at population statistics, or compare different GRB pulses.
There is a gap in the market for software to get researchers off the ground quickly.
This is where `PyGRB` comes in.
# PyGRB
`PyGRB` is a pure Python, open source pulse-fitting package which aims to bring gamma-ray burst light-curve fitting and analysis into the 21st century.
`PyGRB` is able to download the pre-binned BATSE light curves (``bfits`` files), in addition to ``tte_list`` time-tagged photon arrival times.
FITS I/O functionality is provided by `Astropy` [@astropy]. `PyGRB` is built on top of the `Bilby` Bayesian inference library [@bilby], through which `PyGRB` utilises the `Dynesty` [@dynesty] and `Nestle` [@nestle] nested sampling packages [@skilling; @feroz; @multinest].
`PyGRB` makes visually appealing and scientifically instructive light-curves from the four broadband energy channel BATSE data.
The main feature of `PyGRB` is its ability to fit analytic light-curve models to data.
In particular, Bayesian model selection allows the user to determine the most appropriate pulse parameterisation for a particular burst.
Available pulse parameterisations are Gaussian pulses, FRED pulses and FRED variations.
Residual fitting is additionally possible, for which we implement a sine-Gaussian function.

Ultimately, the model selection of `PyGRB` is used to determine if two light-curves are statistically identical, which would be indicative of a gravitational lensing event [@paczynski; @blaes; @mao].
It is quite difficult to compare GRB light-curves occurring at different times due to the variability of the gamma-ray background.
Comparing GRBs observed by different satellites is another matter altogether, owing to the different energy sensitivities, time resolution, and detector geometry.
`PyGRB` creates a unified, abstracted framework allowing for the comparison of gamma-ray bursts based on their fitted pulse parameters, rather than visual or bin-wise statistical comparisons of their light-curves, which is inherently fraught with opportunities for mishap.
In the present release only BATSE functionality is available.
However, due to the modular nature of the code, including additional GRB catalogues is as simple as creating the relevant `fetch`, and `preprocess` modules.
Future releases will allow for the easy comparison of gamma-ray bursts observed by different satellites.
As `PyGRB` is open source, the community is actively encouraged to contribute functionality for the many available GRB catalogues.
`PyGRB` is released under the BSD 3-Clause license.
The source code may be found at https://github.com/JamesPaynter/PyGRB, or alternatively the package may be installed from PyPi via ``pip install PyGRB``.
The online documentation, tutorials and examples are hosted at https://pygrb.readthedocs.io.
# Acknowledgements
I would like to thank Rachel Webster for introducing me to the problem of gravitationally lensed gamma-ray bursts, which spawned this project.
I would like to thank Eric Thrane for introducing me to modern computational statistics, particularly through `Bilby`, on whose shoulders this package stands.
Additionally I would like to thank Julian Carlin, Aman Chokshi for supporting me on my journey from novice programmer to published developer.
# References
|
C
|
UTF-8
| 323
| 2.703125
| 3
|
[] |
no_license
|
#include "../inc/libmx.h"
int mx_strcmp(const char *s1, const char *s2) {
if (s1 == NULL || s2 == NULL)
return 0;
char *tmps1 = (char *) s1;
char *tmps2 = (char *) s2;
while (*tmps1 && *tmps2 && *tmps1 == *tmps2) {
tmps1++;
tmps2++;
}
return *tmps1 - *tmps2;
}
|
Java
|
UTF-8
| 3,742
| 1.921875
| 2
|
[
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"Python-2.0",
"BSD-2-Clause"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.iceberg.mr.hive;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Collection;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.exec.tez.HashableInputSplit;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.iceberg.FileScanTask;
import org.apache.iceberg.mr.mapreduce.IcebergSplit;
import org.apache.iceberg.mr.mapreduce.IcebergSplitContainer;
import org.apache.iceberg.relocated.com.google.common.primitives.Longs;
import org.apache.iceberg.util.SerializationUtil;
// Hive requires file formats to return splits that are instances of `FileSplit`.
public class HiveIcebergSplit extends FileSplit implements IcebergSplitContainer, HashableInputSplit {
private IcebergSplit innerSplit;
// Hive uses the path name of a split to map it back to a partition (`PartitionDesc`) or table description object
// (`TableDesc`) which specifies the relevant input format for reading the files belonging to that partition or table.
// That way, `HiveInputFormat` and `CombineHiveInputFormat` can read files with different file formats in the same
// MapReduce job and merge compatible splits together.
private String tableLocation;
// public no-argument constructor for deserialization
public HiveIcebergSplit() {
}
HiveIcebergSplit(IcebergSplit split, String tableLocation) {
this.innerSplit = split;
this.tableLocation = tableLocation;
}
@Override
public IcebergSplit icebergSplit() {
return innerSplit;
}
@Override
public long getLength() {
return innerSplit.getLength();
}
@Override
public String[] getLocations() {
return innerSplit.getLocations();
}
@Override
public Path getPath() {
return new Path(tableLocation);
}
@Override
public byte[] getBytesForHash() {
Collection<FileScanTask> fileScanTasks = innerSplit.task().files();
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
for (FileScanTask task : fileScanTasks) {
baos.write(task.file().path().toString().getBytes());
baos.write(Longs.toByteArray(task.start()));
}
return baos.toByteArray();
} catch (IOException ioe) {
throw new RuntimeException("Couldn't produce hash input bytes for HiveIcebergSplit: " + this, ioe);
}
}
@Override
public long getStart() {
return 0;
}
@Override
public void write(DataOutput out) throws IOException {
byte[] bytes = SerializationUtil.serializeToBytes(tableLocation);
out.writeInt(bytes.length);
out.write(bytes);
innerSplit.write(out);
}
@Override
public void readFields(DataInput in) throws IOException {
byte[] bytes = new byte[in.readInt()];
in.readFully(bytes);
tableLocation = SerializationUtil.deserializeFromBytes(bytes);
innerSplit = new IcebergSplit();
innerSplit.readFields(in);
}
}
|
C#
|
UTF-8
| 1,882
| 2.953125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FlooringMastery.BLL;
using FlooringMastery.Models;
using FlooringMastery.UI.Workflows;
namespace FlooringMastery.UI
{
public class Menu
{
public void Execute()
{
do
{
Console.Clear();
Console.WriteLine("Welcome to SWC Corp:");
Console.WriteLine("=================================");
Console.WriteLine("1. Display Orders");
Console.WriteLine("2. Add an Order");
Console.WriteLine("3. Edit an Order");
Console.WriteLine("4. Remove an Order");
Console.WriteLine("\n(Q)uit");
Console.Write("\n\nEnter choice: ");
string input = Console.ReadLine();
if (input == "Q")
break;
ProcessChoice(input);
} while (true);
}
private void ProcessChoice(string choice)
{
switch (choice)
{
case "1":
DisplayOrdersWorkflow displaying = new DisplayOrdersWorkflow();
displaying.Execute();
break;
case "2":
AddOrderWorkflow adding = new AddOrderWorkflow();
adding.Execute();
break;
case "3":
EditOrderWorkflow editing = new EditOrderWorkflow();
editing.Execute();
break;
case "4":
RemoveOrderWorkFlow removing = new RemoveOrderWorkFlow();
removing.Execute();
break;
}
}
}
}
|
Markdown
|
UTF-8
| 17,284
| 2.96875
| 3
|
[] |
no_license
|
第 27 章 管理者及其工作
是「白胡子老头儿」,还是「万能天才」──管理者如何开展工作──管理者的工作──信息:管理者的工具──善用时间──管理者的资源:人──对管理者的要求:为人正直──什么样的人才能当管理者──管理者又是教育者──管理者既要有洞察力,又要有道德责任感
为了完成任务,管理者必须善于发挥资源优势──尤其是人力资源方面的长处,以中和其短处。要创造真正的整体,只有采取这个办法。
因此,管理者必须能平衡和协调好三种企业的主要功能:管理企业、管理「管理者」以及管理员工和工作。任何决策或行动如果为了满足某个功能的需求,而削弱其他功能,那么将削弱整个企业的实力。企业的决策和行动必须能兼顾这三个领域的需求。
要创造真正的整体,管理者还必须在采取每个行动时,同时考虑企业的整体绩效,以及需要哪些不同的活动来达成一致的绩效。最佳的比喻仍然是交响乐团的指挥家,交响乐指挥家必须同时聆听整个乐团和第二双簧管奏出的乐音。同样,管理者也必须同时考虑企业整体绩效和所需的市场研究活动,企业整体绩效提升时,也为市场研究创造了更大的空间和挑战,而通过改善市场研究的绩效,企业同时也改善了企业整体绩效。管理者必须随时思考两个问题:企业需要达到什么样的绩效,并因此需要什么样的活动?这些活动如何改善绩效和成果?
管理者的第二项任务是协调每个决策和行动的长远的需求和眼前的需求。无论牺牲长期或短期利益,都会危及整个企业。换句话说,他必须一方面埋头苦干,另一方面却放宽视野、高瞻远瞩,这简直像表演特技一样困难。或者我们换一种比喻方式,管理者既不能说:「船到桥头自然直。」也不能说:「真正重要的是百年大计。」面对远方的桥,他不仅必须预先做好过桥的准备,还必须在抵达桥头之前,先把桥造好。如果管理者不能处理好未来 100 天可能遭遇的问题,公司或许根本看不到百年后的未来,说不定 5 年后公司已经不在了。管理者无论做什么事情,应该一方面是短期的权宜之计,另一方面也符合长期的基本目标和原则。当他无法完全调和长短期的考虑时,至少要设法在中间取得平衡,他必须审慎评估为了保护眼前的利益,将牺牲哪些长期利益,或为了明天的发展,今天需付出多大的代价。无论是哪一种状况,他都必须有所节制,尽可能将必要的牺牲降到最低,同时尽快修补带来的伤害。他穿梭于两种时间范围内,为企业整体绩效和自己部门的绩效负责。
管理者的工作
每位管理者都要做许多非管理性质的工作,可能把大半的工作时间都花在上面。例如销售经理要做统计分析或安抚重要客户;工厂领班得修理机器或填写生产报表;制造经理需要设计新工厂配置图,检验新材料;公司总裁需要处理银行贷款细节或谈判重要合约,或花几个小时主持晚宴,表扬资深员工。这些事情都具备特殊功能,也有其必要性,而且必须把它做好。
但是,这些工作内容却有别于所有管理者共同且独有的工作,而无论管理者负责的功能和活动为何,层级和地位多高,都必须完成这些工作。我们能够把科学管理的系统分析应用在管理者的职务上,就是最好的证明。我们可以把管理者的工作独立出来,将这些工作区分为五项基本作业内容。管理者可以借着改善这几部分的绩效,提升管理绩效。
管理者的工作中包含了五项基本活动,这五项活动共同将所有资源整合成生气蓬勃、不断成长的组织。
首先,管理者设定目标,决定目标应该是什么,也决定应该采取哪些行动,以达到目标。他将目标有效传达给部门员工,并通过这些员工来达成目标。
其次,管理者从事组织的工作。他分析达成目标所需的活动、决策和关系,将工作分门别类,并且分割为可以管理的职务,将这些单位和职务组织成适当的结构,选择对的人来管理这些单位,也管理需要完成的工作。
接下来,管理者还必须激励员工,和员工沟通。他通过管理,通过与下属的关系,通过奖励措施和升迁政策,以及不断地双向沟通,把负责不同职务的人变成一个团队。
第四个管理工作的基本要素是衡量标准。管理者必须为工作建立衡量标准──这是关乎组织绩效和每位成员最重要的因素之一。他必须确立组织中每个人都有适用的衡量标准,并把衡量标准重心放在整个组织的绩效上,同时也放在个人工作绩效上,并协助个人达到绩效。他分析员工表现,也评估及诠释他们的表现。同时,和其他方面的工作一样,他和下属、也和上司沟通这些衡量标准的意义及衡量结果。
最后,管理者必须培养人才。管理者可以通过管理方式,让员工更容易或更难以自我发展。他可能引导下属朝正确的方向发展,也可能误导他们;他可能激发他们的潜能或压抑他们的发展;他可能强化他们正直的品格,或令他们腐败。
无论管理者是否意识到这点,他们在管理的时候都会做这些事情。他可能做得很好,或做得很糟,但是他总是在做这些事情。
这些工作都可以再进一步分类,而这些分类都可以分别出书来深入讨论。换句话说,管理者的工作很复杂,做好每个分类工作都需要不同的资格和品质。
举例来说,设定目标是平衡的问题:在经营成果和实现信念之间求取平衡,在企业目前的需要和未来的需求之间求取平衡;也在想要达到的目标和可用的方法之间求取平衡。因此,设定目标需要有分析和综合能力。
组织也需要分析能力,因为必须以最经济的方式来运用稀少的资源。但是,组织的工作处理的是人的问题,因此必须遵循公正的原则。在培养人才的时候,同样需要具备分析能力,秉持诚实正直的态度。
不过,激励和沟通的技巧比较偏向社交能力,需要的不是分析能力,而是综合的能力,必须把公平正义放在第一位,经济考虑则在其次,诚实正直也比分析能力重要多了。
对绩效评估而言,最重要的是分析能力,但采用的衡量方式必须有助于自我控制,而不是从外部或任由上级滥用衡量方式来控制员工、支配员工。由于企业经常违反这个原则,因此绩效评估往往是管理工作中最弱的一环。只要企业继续滥用绩效评估,把衡量标准当做控制的工具(例如把绩效评估拿来作为公司秘密政策的武器,直接把管理者的稽核和绩效评估结果呈交给上级,而不给管理者一份副本),绩效评估始终都会是管理者工作中最弱的一环。
设定目标、组织、激励和沟通、绩效评估和培养人才,都是正式的管理工作项目。只有靠管理者的经验才能具体实践这些工作内容,并且赋予意义。但是由于这些工作都是正式的管理工作,适用于每一位管理者,以及管理者所从事的每一件事情。因此,每一位管理者都可以通过这些项目来评估自己的能力和绩效,有系统地自我改善及提高管理绩效。
一个人不会因为有能力设定目标,就成为管理者,就好像一个人不会只因为能够有办法在狭小空间中打结,就是外科手术的高手。外科医生改善打结的技巧之后,可以变成更好的外科医生;同理,管理者在所有这五个方面改善他的技巧和绩效的话,那么他就能使自己更加称职。
信息:管理者的工具
管理者有一个特殊工具:信息。管理者不「操纵」人,而是激励、引导、组织他人做好自己的工作。而他做这一切事情的惟一工具是语言、文字或数据。无论管理者的职务属于工程、会计或销售领域,都必须依赖听、说、读、写的能力,来发挥工作效能。他必须懂得如何将自己的想法传达给别人,同时也必须懂得如何掌握别人的需求。
今天的管理者在所有必需的技能中,至少掌握了读、写、说和计算的能力。只要看看大公司里的「政策语言」,就会明白自己是多么无知。这不是仅仅靠学习速读或练习公开演讲就能有所改善的,管理者必须学习了解语言,了解每个字的意义。或许最重要的是,他们必须尊重语言,把语言当做人类最宝贵的天赋与遗产。管理者必须了解修辞学的传统定义乃是:「促使人类的心灵去热爱真实知识的艺术。」管理者如果不能通过书写和口头文字或明确的数据来激励部属,就不可能成为成功的管理者。
善用时间
每个人都有时间的问题,因为时间是最稀有、最昂贵,也最难以掌握的资源。但是,管理者必须运用特殊方法,解决这个普遍的问题。
管理者永远都在为时间不够用的问题寻找神奇的灵丹妙药:上速读课、规定员工呈交上来的报告不能超过一页、机械化地限定面谈时间一律不能超过 15 分钟。这些办法根本没有用,最后只是浪费时间罢了。不过管理者却有可能聪明地分配时间。
懂得善用时间的管理者通过良好的规划,达成绩效。他们愿意先思考,再行动,花很多时间彻底思考应该设定目标的领域,花更多时间有系统地思考如何解决一再出现的老问题。
大多数的管理者都要花很多时间来评估部属的工作绩效与工作品质。然而善用时间的人却不会如此,他们每年对下属做一次系统化的评估。只需要几个小时,许多需要判断的决策──包括部属的薪资、升迁或工作分派等问题──就能获得解答。
善用时间的人也不会花大量时间修改产品的工程设计。他们每年一度──或许花几天的时间,和生产及营销部门一起坐下来讨论必须修改的基本政策、目标和规定,同时也决定修改幅度,并预先指派工程人员负责这项工作。在他们眼中,下面这段话并不值得称许:「多亏了去年的经验,今年我们设法度过了库存危机。」如果公司一再发生同样的危机,他们应该花时间找出问题的根源,防止危机一再发生。这样做或许会耗掉很多时间,但是长远来看,将省下更多时间。
善用时间的管理者花在和上司沟通的时间远多于和下属沟通的时间。他们希望和部属保持良好的沟通,但是似乎不费吹灰之力就能做到。他们不和下属讨论自己的问题,但是却懂得如何让下属主动谈论他们的问题。例如,他们每隔半年阅读「给上司的一封信」,每位下属都在信中设定自己的目标、计划,并说明上司所做的事情中,哪些会提供助力,哪些会形成阻力。他们可能每半年都和每位下属花一整天的时间,仔细沟通「给上司的一封信」中所讨论的内容。结果,他们在其他时候就不需要经常担心和下属沟通的问题。
善用时间的管理者也花很多时间思考上司的问题,以及思考他对上司、对整个企业的成功可以有什么贡献。换句话说,他愿意为上司的工作负起责任──认为这是管理者的分内之事。所以,他似乎不需要花额外的时间理清目标和观点。
管理者的资源:人
管理者手中掌握的资源──人,非常特殊。由于人是特殊的资源,因此管理者运用这个特殊资源时,也需要他具有某些特殊的品质。
因为人(也惟有人)不能「被操纵」。两人之间的关系总是双向的关系,和人与一般资源的关系很不一样。无论是夫妻、父子,或主管和部属,这种相互关系的性质在不断地改变着对方。
培养人才的方向决定了员工(无论把他当成「人」或当成「资源」)究竟是更能发挥生产力,还是最后变得百无一用。我们再三强调,这个原则不但适用于被管理者,也适用于管理者。管理者培养部属时,方向是否正确,能否协助部属成长为更重要、更丰富的人,将直接决定管理者自己能否成长、发展,还是逐渐颓废;内涵越来越丰富,还是每况愈下;不断进步,还是日趋堕落。
管理者能从管理工作中,学到一些技巧,例如主持会议的技巧或面谈的技巧。他可以规划一些有助于人才培育的做法──例如管理者及部属的关系结构、升迁制度、组织的奖励措施等方面。但是当所有该说的都说了,该做的都做了,管理者还需要一种基本的品质,才能做好人才培育的工作,我们无法靠提供人才培育的技能或强调人才培育的重要,创造出这种品质,必须管理者原本就具备诚实正直的品格。
近来,许多人极力强调喜欢人、乐于助人和能够与别人相处融洽的重要性,认为这是管理者的重要条件。但是单靠这些条件绝对不够。每一个成功的组织,都有不喜欢别人、不帮助别人、很难相处的上司。但是尽管这类上司冷酷、不讨人喜欢、要求严苛,但是他培养了许多人才。他也比其他人缘好的上司赢得更多尊敬。他要求下属一丝不苟,也严格要求自己;他建立高标准,期望下属能够始终维护高标准;他只考虑怎么做才正确,绝不因人而异。虽然这些管理者通常才华横溢,但是他在评价下属的时候,绝对不会把聪明才智看得比正直的品格还重要。缺乏这些品格的管理者,无论他是多么讨人喜欢、乐于助人、和蔼可亲,甚至才智过人、能力高强,都是危险人物,「不适合担任管理者」。
或许有人会争辩,无论从事哪个职业──医生、律师、杂货店老板,都需要有正直的品格,但是其中还是有差别。管理者和他所管理的员工生活在一起,决定他们应该做什么工作,指挥和训练他们完成任务,评估他们的工作绩效,并且往往决定了他们的前途。商人和顾客或专业人员与客户之间要求的都是买卖公正。然而管理者的角色却比较像父母或教师,在这类关系中,仅仅公平对待还不够,诚实正直的品格才是关键。
我们现在可以回答这个问题:只有天才,或至少具备特殊才华的人,才能担任管理者吗?管理究竟是艺术,还是直觉?我的答案是:「都不是。」我们可以系统化地分析管理工作,也可以学会管理者必须做的工作(尽管不见得总是有人教)。不过,有一种无法学会的品质,一种管理者无法获取、却必备的条件。它不是人的天才,而是人的品格。
什么样的人才能当管理者
标准定义是,如果一个人要为他人和他人的工作承担责任,那么他就是一位管理者。但是这个定义太过狭隘,管理者的首要职责是向上负责:对企业负责。他和上司及其他管理者的关系,与他和下属的关系同样重要。
另外一个定义──虽然通常都没有明说──是根据重要性来定义员工算不算管理者。但是,在现代企业中,没有任何团队比其他团队更重要。机器操作员、实验室的专业人员或绘图员,都和管理者同样重要。这是为什么企业的每一分子都必须具备管理者的愿景。企业的不同团体之间最大的差别不在于重要性,而在于不同的功能。
关于管理者的定义,最通行的观念是根据阶级和待遇来决定。这种观念不但错误,而且具有破坏力。即使到了今天,我们仍然不时会发现有些所谓基层员工的收入比大多数管理者都还高。举例来说,在汽车公司制作模型的技术员年收入超过 1.5 万美元,但是大家仍然视他们为技术员,让他们参与工会的劳资谈判。除非我们能付专业贡献者足够的薪水,让个人贡献者也有充足的升迁机会,赋予他们专业人员的地位、尊严和价值,否则,我们将无法管理这批日益增长的人员。
总而言之,以阶级和待遇来确定管理者的观念,就好像把现代的企业经理人当成过去做生意的老板一样荒谬。
我们只能以一个人的功能和企业期望他发挥的贡献来定义他是不是管理者。而管理者有别于其他员工的独特功能乃是教育的功能。企业期望他发挥的独特贡献,则是赋予他人达成绩效的能力和愿景。最后,是道德责任和愿景决定了一个人究竟算不算管理者。
|
Markdown
|
UTF-8
| 8,509
| 2.515625
| 3
|
[] |
no_license
|
---
comments: true
date: "2013-12-14T00:00:00Z"
menu: true
tags:
- Notes
title: Supervisor笔记
---
Supervisor是一个C/S系统,用来监控和控制多个服务进程,只限于UNIX-like操作系统。
# 官方文档
http://supervisord.org/
# 安装
setuptools
```bash
pip install supervisor
# or
easy_install supervisor
```
# 初始使用
## 创建配置文件
需要以root身份执行
echo_supervisord_conf > /etc/supervisord.conf
## 调整配置文件
+ 增加web管理界面
取消配置文件中的下列行,并按需配置用户名密码
```ini
[inet_http_server]
port=*:9001
username=your_username ; (default is no username (open server))
password=your_password ; (default is no password (open server))
```
## 添加服务
配置文件详解
```ini
[supervisorctl]
serverurl=unix:///tmp/supervisor.sock ; use a unix:// URL for a unix socket
;serverurl=http://127.0.0.1:9001 ; use an http:// url to specify an inet socket
;username=chris ; should be same as http_username if set
;password=123 ; should be same as http_password if set
;prompt=mysupervisor ; cmd line prompt (default "supervisor")
;history_file=~/.sc_history ; use readline history if available
添加单个进程
; 管理单个进程的配置,可创建多个,下面是所有可能的配置选项
;[program:theprogramname]
;command=/bin/cat ; 启动进程的命令 使用相对路径,可以加参数
;process_name=%(program_name)s ; 进程名称 表达式 (默认 %(program_name)s)
;numprocs=1 ; 进程数目 (def 1)
;directory=/tmp ; 执行命令所在的目录 (def no cwd)
;umask=022 ; 进程默认权限 (default None)
;priority=999 ; 进程启动相对优先权 (default 999)
;autostart=true ; 跟随supervisor启动时启动 (default: true)
;autorestart=unexpected ; 计划启动 (default: unexpected)
;startsecs=1 ; 延时启动 (def. 1)
;startretries=3 ; 最多连续启动失败 (default 3)
;exitcodes=0,2 ; 进程结束代码 (default 0,2)
;stopsignal=QUIT ; signal used to kill process (default TERM)
;stopwaitsecs=10 ; 最长结束等待时间,否则使用 SIGKILL (default 10)
;stopasgroup=false ; 是否想UNIX进程组发送结束信号 (default false)
;killasgroup=false ; SIGKILL UNIX 进程组 (def false)
;user=chrism ; 设置启动此程序的用户
;redirect_stderr=true ; 重定向程序的标准错误到标准输出 (default false)
;stdout_logfile=/a/path ; 标准输出的日志路径, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB ; 日志文件最大值,否则循环写入 (default 50MB)
;stdout_logfile_backups=10 ; 标准输出日志备份数目 (default 10)
;stdout_capture_maxbytes=1MB ; number of bytes in 'capturemode' (default 0)
;stdout_events_enabled=false ; emit events on stdout writes (default false)
;stderr_logfile=/a/path ; 标准错误输出日志路径, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB ; 日志文件最大值,否则循环写入 (default 50MB)
;stderr_logfile_backups=10 ; 标准错误日志备份数目 (default 10)
;stderr_capture_maxbytes=1MB ; number of bytes in 'capturemode' (default 0)
;stderr_events_enabled=false ; emit events on stderr writes (default false)
;environment=A="1",B="2" ; 进程附加环境 (def no adds)
;serverurl=AUTO ; override serverurl computation (childutils)
```
## 添加事件监听器
```ini
; The below sample eventlistener section shows all possible
; eventlistener subsection values, create one or more 'real'
; eventlistener: sections to be able to handle event notifications
; sent by supervisor.
; 下面是事件监听器的可选配置, supervisor能够处理事件通知.
;
; ** 译者注: 和上面相同的解释没有翻译 **
;[eventlistener:theeventlistenername]
;command=/bin/eventlistener ; the program (relative uses PATH, can take args)
;process_name=%(program_name)s ; process_name expr (default %(program_name)s)
;numprocs=1 ; number of processes copies to start (def 1)
;events=EVENT ; event notif. types to subscribe to (req'd)
;buffer_size=10 ; 事件缓冲队列的大小 (default 10)
;directory=/tmp ; directory to cwd to before exec (def no cwd)
;umask=022 ; umask for process (default None)
;priority=-1 ; the relative start priority (default -1)
;autostart=true ; start at supervisord start (default: true)
;autorestart=unexpected ; whether/when to restart (default: unexpected)
;startsecs=1 ; number of secs prog must stay running (def. 1)
;startretries=3 ; max # of serial start failures (default 3)
;exitcodes=0,2 ; 'expected' exit codes for process (default 0,2)
;stopsignal=QUIT ; signal used to kill process (default TERM)
;stopwaitsecs=10 ; max num secs to wait b4 SIGKILL (default 10)
;stopasgroup=false ; send stop signal to the UNIX process group (default false)
;killasgroup=false ; SIGKILL the UNIX process group (def false)
;user=chrism ; setuid to this UNIX account to run the program
;redirect_stderr=true ; redirect proc stderr to stdout (default false)
;stdout_logfile=/a/path ; stdout log path, NONE for none; default AUTO
;stdout_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stdout_logfile_backups=10 ; # of stdout logfile backups (default 10)
;stdout_events_enabled=false ; emit events on stdout writes (default false)
;stderr_logfile=/a/path ; stderr log path, NONE for none; default AUTO
;stderr_logfile_maxbytes=1MB ; max # logfile bytes b4 rotation (default 50MB)
;stderr_logfile_backups ; # of stderr logfile backups (default 10)
;stderr_events_enabled=false ; emit events on stderr writes (default false)
;environment=A="1",B="2" ; process environment additions
;serverurl=AUTO ; override serverurl computation (childutils)
```
## 添加进程组
```ini
; The below sample group section shows all possible group values,
; create one or more 'real' group: sections to create "heterogeneous"
; process groups.
; 下面是进程组的可选配置,可以创建一个或多个进程组。
;[group:thegroupname]
;programs=progname1,progname2 ; 这里的进程名是上文 [program:theprogramname] 定义的theprogramname
;priority=999 ; the relative start priority (default 999)
```
## 命令行工具 supervisorctl
查看所有命令
```bash
$ supervisorctl help
default commands (type help ):
=====================================
add clear fg open quit remove restart start stop update
avail exit maintail pid reload reread shutdown status tail version
命令功能
作者: 飞龙 http://feilong.me/2011/03/monitor-processes-with-supervisord
supervisord,初始启动Supervisord,启动、管理配置中设置的进程。
supervisorctl stop programxxx,停止某一个进程(programxxx),programxxx为[program:chatdemon]里配置的值,这个示例就是chatdemon。
supervisorctl start programxxx,启动某个进程
supervisorctl restart programxxx,重启某个进程
supervisorctl stop groupworker: ,重启所有属于名为groupworker这个分组的进程(start,restart同理)
supervisorctl stop all,停止全部进程,注:start、restart、stop都不会载入最新的配置文件。
supervisorctl reload,载入最新的配置文件,停止原有进程并按新的配置启动、管理所有进程。
supervisorctl update,根据最新的配置文件,启动新配置或有改动的进程,配置没有改动的进程不会受影响而重启。
注意:显示用stop停止掉的进程,用reload或者update都不会自动重启。
```
|
Java
|
UTF-8
| 357
| 1.539063
| 2
|
[] |
no_license
|
package com.tencent.mm.plugin.talkroom.ui;
import android.os.Message;
import com.tencent.mm.sdk.platformtools.af;
class a$1 extends af {
final /* synthetic */ a scu;
a$1(a aVar) {
this.scu = aVar;
}
public final void handleMessage(Message message) {
super.handleMessage(message);
a.a(this.scu).dismiss();
}
}
|
Markdown
|
UTF-8
| 1,807
| 3.859375
| 4
|
[] |
no_license
|
# 表格操作
## 表格隔行换色
*商品分类的信息太多,如果每一行都显示一个颜色的话会让人眼花缭乱,为了提升用户体验,减少用户看错的情况,需要对表格的每行进行隔行换色*
* 通过js来实现
* 确定事件 onload ,页面加载完成后对页表格的颜色作一些修改
* 事件触发函数init()
* 函数操作:
修改表格每一行的背景颜色
```html
<script>
function init(){
//获得表格
var tab = document.getElementById("tab")
//获得表格行
var rows = tab.rows()
//遍历表格的每一行,动态修改每一行的背景颜色
for(var i = 1;i < rows.length;i++){
var row = rows[i];
if(i % 2 == 0){
row.bgColor = "yellow";
}else{
row.bgColor = "red";
}
}
}
</script>
<body onload = "init()">
<table border = "1px" width = "600" id = "tab">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
```
## 表格的全选和全不选
|
PHP
|
UTF-8
| 377
| 2.53125
| 3
|
[] |
no_license
|
<?php
$message = "\n\nИмя: ".$_POST['name']."\r\nТелефон: ".$_POST['phone']."\r\nE-mail: ".$_POST['email'];
// На случай если какая-то строка письма длиннее 70 символов мы используем wordwrap()
$message = wordwrap($message, 70, "\r\n");
// Отправляем
mail('art.sandin@yandex.ru', 'Feedback Form', $message);
?>
|
JavaScript
|
UTF-8
| 256
| 2.53125
| 3
|
[] |
no_license
|
class GameObject
{
constructor(position = {x:0,y:0}, name = "Empty", layer = 5)
{
this.position = position
this.name = name
this.layer = layer
this.active = true
}
start(){}
update(){}
draw(){}
}
|
Java
|
UTF-8
| 1,184
| 2.078125
| 2
|
[] |
no_license
|
package pack;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
public class AuctionServlet extends HttpServlet{
@webServelet"/item/*"
public void doGet(HttpServletRequest request, hrrpservletresponse response,)
{
//this is the controller
System.out.println(request.getRequestURI());
//we need to retrieve the model
//and provide it to the view
try {
response.getWrite().append("<h1>Hello world</h1>");
}
catch {
throw new ServeletException(e);
}
}
}
|
SQL
|
UTF-8
| 395
| 3.296875
| 3
|
[] |
no_license
|
--
-- Non Foreign Key Constraints for Table VED_POD_ROW
--
ALTER TABLE MASTER.VED_POD_ROW ADD (
CHECK ("VED_POD_ID" IS NOT NULL)
DISABLE NOVALIDATE);
ALTER TABLE MASTER.VED_POD_ROW ADD (
CHECK ("NUM_CIST" IS NOT NULL)
DISABLE NOVALIDATE);
ALTER TABLE MASTER.VED_POD_ROW ADD (
CONSTRAINT VED_POD_ROW_PK
PRIMARY KEY
(ID)
USING INDEX MASTER.VED_POD_ROW_PK
ENABLE VALIDATE);
|
Markdown
|
UTF-8
| 523
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
---
templateKey: project
name: Danielle Sheahan
title: (Anti)socialized
category: Short Film
thumbnail: ../thumbnails/danielle_antisocialized.jpg
intro: >-
(Anti)socialized is a short film that uses visual metaphor and storytelling to explore how gendered socialization impacts our sexual interactions. The film examines popular notions of masculinity and femininity, and proposes ways in which we can challenge these norms and transform our interactions with each other.
projectLink: ../video/danielle_sheahan.mp4
type: Video
---
|
Ruby
|
UTF-8
| 2,610
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
module PryStackExplorer
class WhenStartedHook
include Pry::Helpers::BaseHelpers
def caller_bindings(target)
bindings = binding.callers
pre_callers = Thread.current[:pre_callers]
bindings = bindings + pre_callers if pre_callers
bindings = remove_internal_frames(bindings)
mark_vapid_frames(bindings)
bindings
end
def call(target, options, _pry_)
target ||= _pry_.binding_stack.first if _pry_
options = {
:call_stack => true,
:initial_frame => 0
}.merge!(options)
return if !options[:call_stack]
if options[:call_stack].is_a?(Array)
bindings = options[:call_stack]
if !valid_call_stack?(bindings)
raise ArgumentError, ":call_stack must be an array of bindings"
end
else
bindings = caller_bindings(target)
end
PryStackExplorer.create_and_push_frame_manager bindings, _pry_, :initial_frame => options[:initial_frame]
end
private
def mark_vapid_frames(bindings)
stepped_out = false
actual_file, actual_method = nil, nil
bindings.each do |binding|
if stepped_out
if actual_file == binding.eval("__FILE__") and actual_method == binding.eval("__method__")
stepped_out = false
else
binding.local_variable_set :vapid_frame, true
end
elsif binding.frame_type == :block
stepped_out = true
actual_file = binding.eval("__FILE__")
actual_method = binding.eval("__method__")
end
if binding.local_variable_defined? :hide_from_stack
binding.local_variable_set :vapid_frame, true
end
end
end
# remove internal frames related to setting up the session
def remove_internal_frames(bindings)
i = top_internal_frame_index(bindings)
# DEBUG:
#bindings.each_with_index do |b, index|
# puts "#{index}: #{b.eval("self.class")} #{b.eval("__method__")}"
#end
#puts "FOUND top internal frame: #{bindings.size} => #{i}"
bindings.drop i+1
end
def top_internal_frame_index(bindings)
bindings.rindex do |b|
if b.frame_type == :method
self_, method = b.eval("self"), b.eval("__method__")
self_.equal?(Pry) && method == :start ||
self_.class == Binding && method == :pry ||
self_.class == PryMoves::Tracer && method == :tracing_func
end
end
end
def valid_call_stack?(bindings)
bindings.any? && bindings.all? { |v| v.is_a?(Binding) }
end
end
end
|
Java
|
UTF-8
| 10,008
| 1.703125
| 2
|
[] |
no_license
|
package com.google.android.gms.drive.internal;
import android.os.Binder;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.drive.ChangeSequenceNumber;
import com.google.android.gms.drive.realtime.internal.H;
public abstract class n extends Binder
implements m
{
public static m a(IBinder paramIBinder)
{
if (paramIBinder == null)
return null;
IInterface localIInterface = paramIBinder.queryLocalInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
if ((localIInterface != null) && ((localIInterface instanceof m)))
return (m)localIInterface;
return new o(paramIBinder);
}
public boolean onTransact(int paramInt1, Parcel paramParcel1, Parcel paramParcel2, int paramInt2)
{
switch (paramInt1)
{
default:
return super.onTransact(paramInt1, paramParcel1, paramParcel2, paramInt2);
case 1598968902:
paramParcel2.writeString("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
return true;
case 1:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i13 = paramParcel1.readInt();
OnDownloadProgressResponse localOnDownloadProgressResponse = null;
if (i13 != 0)
localOnDownloadProgressResponse = (OnDownloadProgressResponse)OnDownloadProgressResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnDownloadProgressResponse);
paramParcel2.writeNoException();
return true;
case 2:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i12 = paramParcel1.readInt();
OnListEntriesResponse localOnListEntriesResponse = null;
if (i12 != 0)
localOnListEntriesResponse = (OnListEntriesResponse)OnListEntriesResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnListEntriesResponse);
paramParcel2.writeNoException();
return true;
case 3:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i11 = paramParcel1.readInt();
OnDriveIdResponse localOnDriveIdResponse = null;
if (i11 != 0)
localOnDriveIdResponse = (OnDriveIdResponse)OnDriveIdResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnDriveIdResponse);
paramParcel2.writeNoException();
return true;
case 4:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i10 = paramParcel1.readInt();
OnMetadataResponse localOnMetadataResponse = null;
if (i10 != 0)
localOnMetadataResponse = (OnMetadataResponse)OnMetadataResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnMetadataResponse);
paramParcel2.writeNoException();
return true;
case 5:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i9 = paramParcel1.readInt();
OnContentsResponse localOnContentsResponse = null;
if (i9 != 0)
localOnContentsResponse = (OnContentsResponse)OnContentsResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnContentsResponse);
paramParcel2.writeNoException();
return true;
case 6:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i8 = paramParcel1.readInt();
Status localStatus = null;
if (i8 != 0)
localStatus = (Status)Status.CREATOR.createFromParcel(paramParcel1);
a(localStatus);
paramParcel2.writeNoException();
return true;
case 7:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
a();
paramParcel2.writeNoException();
return true;
case 8:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i7 = paramParcel1.readInt();
OnListParentsResponse localOnListParentsResponse = null;
if (i7 != 0)
localOnListParentsResponse = (OnListParentsResponse)OnListParentsResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnListParentsResponse);
paramParcel2.writeNoException();
return true;
case 9:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i6 = paramParcel1.readInt();
OnSyncMoreResponse localOnSyncMoreResponse = null;
if (i6 != 0)
localOnSyncMoreResponse = (OnSyncMoreResponse)OnSyncMoreResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnSyncMoreResponse);
paramParcel2.writeNoException();
return true;
case 11:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i5 = paramParcel1.readInt();
OnLoadRealtimeResponse localOnLoadRealtimeResponse = null;
if (i5 != 0)
localOnLoadRealtimeResponse = (OnLoadRealtimeResponse)OnLoadRealtimeResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnLoadRealtimeResponse, H.a(paramParcel1.readStrongBinder()));
paramParcel2.writeNoException();
return true;
case 12:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i4 = paramParcel1.readInt();
OnResourceIdSetResponse localOnResourceIdSetResponse = null;
if (i4 != 0)
localOnResourceIdSetResponse = (OnResourceIdSetResponse)OnResourceIdSetResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnResourceIdSetResponse);
paramParcel2.writeNoException();
return true;
case 13:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i3 = paramParcel1.readInt();
OnPinnedDownloadPreferencesResponse localOnPinnedDownloadPreferencesResponse = null;
if (i3 != 0)
localOnPinnedDownloadPreferencesResponse = (OnPinnedDownloadPreferencesResponse)OnPinnedDownloadPreferencesResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnPinnedDownloadPreferencesResponse);
paramParcel2.writeNoException();
return true;
case 14:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i2 = paramParcel1.readInt();
OnDeviceUsagePreferenceResponse localOnDeviceUsagePreferenceResponse = null;
if (i2 != 0)
localOnDeviceUsagePreferenceResponse = (OnDeviceUsagePreferenceResponse)OnDeviceUsagePreferenceResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnDeviceUsagePreferenceResponse);
paramParcel2.writeNoException();
return true;
case 15:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
if (paramParcel1.readInt() != 0);
for (boolean bool = true; ; bool = false)
{
a(bool);
paramParcel2.writeNoException();
return true;
}
case 16:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i1 = paramParcel1.readInt();
OnFetchThumbnailResponse localOnFetchThumbnailResponse = null;
if (i1 != 0)
localOnFetchThumbnailResponse = (OnFetchThumbnailResponse)OnFetchThumbnailResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnFetchThumbnailResponse);
paramParcel2.writeNoException();
return true;
case 17:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int n = paramParcel1.readInt();
ChangeSequenceNumber localChangeSequenceNumber = null;
if (n != 0)
localChangeSequenceNumber = (ChangeSequenceNumber)ChangeSequenceNumber.CREATOR.createFromParcel(paramParcel1);
a(localChangeSequenceNumber);
paramParcel2.writeNoException();
return true;
case 18:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int m = paramParcel1.readInt();
OnChangesResponse localOnChangesResponse = null;
if (m != 0)
localOnChangesResponse = (OnChangesResponse)OnChangesResponse.CREATOR.createFromParcel(paramParcel1);
a(localOnChangesResponse);
paramParcel2.writeNoException();
return true;
case 20:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int k = paramParcel1.readInt();
GetPermissionsResponse localGetPermissionsResponse = null;
if (k != 0)
localGetPermissionsResponse = (GetPermissionsResponse)GetPermissionsResponse.CREATOR.createFromParcel(paramParcel1);
a(localGetPermissionsResponse);
paramParcel2.writeNoException();
return true;
case 21:
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int j = paramParcel1.readInt();
StringListResponse localStringListResponse = null;
if (j != 0)
localStringListResponse = (StringListResponse)StringListResponse.CREATOR.createFromParcel(paramParcel1);
a(localStringListResponse);
paramParcel2.writeNoException();
return true;
case 22:
}
paramParcel1.enforceInterface("com.google.android.gms.drive.internal.IDriveServiceCallbacks");
int i = paramParcel1.readInt();
OnStartStreamSession localOnStartStreamSession = null;
if (i != 0)
localOnStartStreamSession = (OnStartStreamSession)OnStartStreamSession.CREATOR.createFromParcel(paramParcel1);
a(localOnStartStreamSession);
paramParcel2.writeNoException();
return true;
}
}
/* Location: C:\Users\KSHITIZ GUPTA\Downloads\apktool-install-windws\dex2jar-0.0.9.15\dex2jar-0.0.9.15\classes_dex2jar.jar
* Qualified Name: com.google.android.gms.drive.internal.n
* JD-Core Version: 0.6.0
*/
|
PHP
|
UTF-8
| 2,647
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace VGirol\JsonApi\Services;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use VGirol\JsonApi\Contracts\ServiceContract;
abstract class AbstractService implements ServiceContract
{
/**
* @var Collection
*/
private $parameters;
/**
* Undocumented function
*
* @return string
*/
abstract protected function getConfigKey(): string;
/**
* Undocumented function
*
* @param Request $request
*
* @return Collection
*/
abstract protected function parseParameters($request);
/**
* Undocumented function
*
* @param Request $request
* @param boolean $force
*
* @return $this
*/
public function parseRequest($request = null, $force = false)
{
$request = $request ?? request();
if (is_null($this->parameters) || $force) {
$this->parameters = $this->parseParameters($request);
}
return $this;
}
/**
* Undocumented function
*
* @param Request $request
*
* @return boolean
*/
public function hasQuery($request = null): bool
{
return $this->parseRequest($request)->parameters->isNotEmpty();
}
/**
* Undocumented function
*
* @return Collection
*/
public function parameters()
{
return $this->parameters;
}
/**
* Undocumented function
*
* @param string|int $key
* @param mixed $default
*
* @return mixed
*/
public function value($key, $default = null)
{
return isset($this->parameters) ? $this->parameters->get($key, $default) : $default;
}
/**
* Undocumented function
*
* @return array
*/
public function getQueryParameter(): array
{
return $this->hasQuery() ? [$this->getConfigKey() => $this->parameters()->toArray()] : [];
}
/**
* Undocumented function
*
* @param string $separator
*
* @return string
*/
public function implode(string $separator = ', '): string
{
return $this->parameters->join($separator);
}
public function allowedByServer(): bool
{
return config("jsonapi.{$this->getConfigKey()}.allowed", true);
}
public function allowedForRoute($request = null): bool
{
$request = $request ?? request();
return $request->routeIs(config("jsonapi.{$this->getConfigKey()}.routes"));
}
public function allowed($request = null): bool
{
return $this->allowedByServer() && $this->allowedForRoute($request);
}
}
|
Python
|
UTF-8
| 2,178
| 3.34375
| 3
|
[] |
no_license
|
from word import *
import logging
class WordStore(set):
def __init__(self, iter = list(), check_sign = True):
"""
iter: itérable de mot à ajouter, potentiellement vide
/!\ on a pas encore de crypto (peut-être pas nécessaire)
"""
# gen une clé RSA ou _hashT ?
set.__init__(self)
self.store = set(iter)
def add(self, word):
#ADD verif plusieurs lettre d'un même auteur
if not [l for l in word.letters if l.period != word.period or not l.check_signature()] and word.check_signature():
set.add(self, word)
def contains(self, item):
for e in self:
if e.signature == item.signature:
return True
return False
def purge(self, period):
WordStore.__init__(self, [x for x in self if x.period >= period])
if __name__ == "__main__":
ws = WordStore([wexemple0])
print([i for i in ws])
class LetterStore(object):
def add_letter(self, letter):
#check_signature into logging.warning
l = letter.letter.decode("utf-8")
if len(l) != 1 or l not in 'azertyuiopqsdfghjklmwxcvbn' or not letter.check_signature():
logging.warning(l + " is not a valid letter")
return
self._hashT[l].append(letter)
def __len__(self):
return sum([len(x) for x in self._hashT.values()])
def __init__(self, iter = None, check_sign = True):
"""
iter: itérable de letter à ajouter, potentiellement vide
/!\ on a pas encore de crypto (peut-être pas nécessaire)
"""
self.check_sign = check_sign
self._hashT = dict()
for i in 'azertyuiopqsdfghjklmwxcvbn':
self._hashT[i] = list()
if iter is not None:
for elem in iter:
self.add_letter(elem)
def getCopy(self):
ret = dict()
for i in 'azertyuiopqsdfghjklmwxcvbn':
ret[i] = self._hashT[i] * 1
return ret
def purge(self, period):
for i in 'azertyuiopqsdfghjklmwxcvbn':
self._hashT[i] = [e for e in self._hashT[i] if e.period >= period]
|
Swift
|
UTF-8
| 851
| 2.8125
| 3
|
[] |
no_license
|
//
// DomainViewModel.swift
// MVVMSample2
//
// Created by taehy.k on 2021/08/02.
//
import UIKit
class DomainViewModel: CellRepresentable {
var domain: Domain
var rowHeight: CGFloat = 60
var status: String {
switch domain.domainStatus {
case .Available:
return "Available"
case .Taken:
return ""
case .Other:
return ""
}
}
init(domain: Domain) {
self.domain = domain
}
func cellInstance(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "DomainTableViewCell", for: indexPath) as? DomainTableViewCell else {
fatalError("no cell.")
}
cell.setup(vm: self)
return cell
}
}
|
Java
|
UTF-8
| 523
| 2.1875
| 2
|
[
"MIT"
] |
permissive
|
package net.login.handler;
import client.MapleClient;
import net.AbstractMaplePacketHandler;
import tools.data.input.SeekableLittleEndianAccessor;
public class CharlistRequestHandler extends AbstractMaplePacketHandler {
@Override
public void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
int server = slea.readByte();
int channel = slea.readByte() + 1;
c.setWorld(server);
c.setChannel(channel);
c.sendCharList(server);
}
}
|
C++
|
UTF-8
| 701
| 2.84375
| 3
|
[] |
no_license
|
#include <cstdio>
#include <iostream>
#include <map>
#include <vector>
int main(void)
{
int n;
while(std::cin >> n)
{
std::map<int, int> homeCnt, AwayCnt;
std::vector<int> homeRec, AwayRec;
for(int i = 0; i < n; ++i)
{
int homeKit, AwayKit;
scanf("%d%d", &homeKit, &AwayKit);
++homeCnt[homeKit];
++AwayCnt[AwayKit];
homeRec.push_back(homeKit);
AwayRec.push_back(AwayKit);
}
for(int i = 0; i < n; ++i)
{
int home = n - 1 + homeCnt[AwayRec[i]];
int away = 2 * (n - 1) - home;
printf("%d %d\n", home, away);
}
}
}
|
JavaScript
|
UTF-8
| 608
| 2.859375
| 3
|
[] |
no_license
|
var $h1 = document.getElementsByTagName('h1')[0]
var url = location.href
var state = {}
// 刷新则重新返回index.html
if (url.indexOf('?') >= 0) {
url = url.split('?')[0]
history.replaceState(null, null, url)
$h1.innerHTML = '首页'
}
$('#content a').click(function () {
var index = $(this).index()
state.index = index
state.query = 'index=' + index
history.pushState(state, null, url + '?index=' + index)
$h1.innerHTML = '页面' + (index + 1)
})
window.addEventListener("popstate", function(e) {
$h1.innerHTML = '页面' + (e.state.index + 1)
console.log(e.state.query)
});
|
Python
|
UTF-8
| 1,953
| 3.828125
| 4
|
[] |
no_license
|
import random
from state import State
class Model:
def __init__(self):
self.state = State()
self.populate()
self.populate()
def populate(self):
value = 2 if random.uniform(0, 1) < 0.9 else 4
row, col = self.state.get_random_empty_cell()
if (row != None) & (col != None):
self.state.fill(row, col, value)
def play(self, dir):
# [0, 1, 2, 3] = [up, down, left, right]
change = False
reversals = self.get_reversals(dir)
traversals = self.get_traversals(reversals)
merges = []
for row in traversals[0]:
for col in traversals[1]:
if self.state.is_filled(row, col):
new_change = self.state.move(row, col, dir, merges)
change = change or new_change
# print((row, col))
return change
def make_move(self, dir):
if self.play(dir):
self.spawn_random()
def spawn_random(self):
row, col = self.state.get_random_empty_cell()
num = 2 if random.random() < 0.9 else 4
self.state.fill(row, col, num)
def get_reversals(self, dir):
# code adapted from gabrielecirulli/2048
# we do reversals because when we search for movements
# we always search from the "last" piece in each direction
# -> A B C D search D, C, B, A
reversals = [
[False, False],
[True, False],
[False, False],
[False, True]
]
return reversals[dir]
def get_traversals(self, reversals):
row = [0, 1, 2, 3]
col = [0, 1, 2, 3]
# hence, for down and right, we need reversals
# on row and col respectively
if (reversals[0]):
row = row[::-1]
if (reversals[1]):
col = col[::-1]
return (row, col)
if __name__ == "__main__":
def print_state(x):
[print(r) for r in x.state.state]
print()
x = Model()
print("Make a move: 0: up | 1: down | 2: left | 3: right")
print_state(x)
while (True):
move = int(input())
x.make_move(move)
print_state(x)
|
SQL
|
UTF-8
| 14,174
| 3.0625
| 3
|
[
"MIT"
] |
permissive
|
-- phpMyAdmin SQL Dump
-- version 4.8.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Mar 27, 2019 at 07:00 AM
-- Server version: 10.1.31-MariaDB
-- PHP Version: 7.2.4
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `db_superblog`
--
-- --------------------------------------------------------
--
-- Table structure for table `categories`
--
CREATE TABLE `categories` (
`id` bigint(20) UNSIGNED NOT NULL,
`cat_name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `categories`
--
INSERT INTO `categories` (`id`, `cat_name`, `created_at`, `updated_at`) VALUES
(1, 'বাংলাদেশ', '2019-03-15 12:34:43', '2019-03-15 12:34:43'),
(2, 'আন্তর্জাতিক', '2019-03-15 12:39:06', '2019-03-15 12:39:06'),
(6, 'অর্থনীতি', '2019-03-15 17:17:02', '2019-03-15 18:24:03'),
(7, 'খেলা', '2019-03-15 17:35:46', '2019-03-15 18:24:29'),
(8, 'Raj', '2019-03-15 18:22:00', '2019-03-15 18:22:00'),
(9, 'sajib Kumer', '2019-03-15 18:22:37', '2019-03-15 18:22:37');
-- --------------------------------------------------------
--
-- Table structure for table `migrations`
--
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `migrations`
--
INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES
(1, '2014_10_12_000000_create_users_table', 1),
(2, '2014_10_12_100000_create_password_resets_table', 1),
(3, '2019_03_01_094011_create_categories_table', 1),
(4, '2019_03_01_094229_create_posts_table', 1);
-- --------------------------------------------------------
--
-- Table structure for table `password_resets`
--
CREATE TABLE `password_resets` (
`email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- Table structure for table `posts`
--
CREATE TABLE `posts` (
`id` bigint(20) UNSIGNED NOT NULL,
`cat_id` int(10) UNSIGNED DEFAULT NULL,
`user_id` int(10) UNSIGNED DEFAULT NULL,
`comment_id` int(10) UNSIGNED DEFAULT NULL,
`title` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`description` text COLLATE utf8mb4_unicode_ci,
`photo` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `posts`
--
INSERT INTO `posts` (`id`, `cat_id`, `user_id`, `comment_id`, `title`, `description`, `photo`, `created_at`, `updated_at`) VALUES
(6, 2, 1, 10, 'Sint iste maxime at eos fuga. bugui Helo', 'Numquam ducimus aut odio cupiditate velit. Dolorem sequi voluptatem maxime laudantium amet delectus facilis. Unde quia et totam voluptas praesentium quae omnis.', '1553235280.jpeg', '2019-03-15 22:03:48', '2019-03-25 00:47:02'),
(7, 7, 1, 10, 'Impedit ea non libero praesentium quis necessitatibus nam.', 'Explicabo et dolores eveniet velit. Voluptatem tenetur vel distinctio doloremque temporibus omnis itaque. Et quas assumenda non occaecati voluptatem iste.', '1553235314.jpeg', '2019-03-15 22:03:48', '2019-03-22 00:15:15'),
(9, 1, 1, 10, 'Quod quis voluptatem repudiandae quisquam ea ea totam.', 'Quam occaecati minima nihil quo quis et. In ut odit eum et iste sit. Ducimus maxime aut itaque vel facere.', '1553235344.jpeg', '2019-03-15 22:03:48', '2019-03-22 00:15:44'),
(10, 1, 1, 8, 'Ut minima sit qui nobis.', 'Est velit in earum et. Alias qui ut maiores voluptas et. Mollitia quam nemo aspernatur ratione. Recusandae consequatur aliquam rerum non quas iure.', '1553235352.jpeg', '2019-03-15 22:03:48', '2019-03-22 00:15:52'),
(13, 1, 1, NULL, 'শ্যাম ভূমিজের গ্রামে পানি নিয়ে স্বস্তি', 'স্ত্রী রমণী ভূমিজ, দুই সন্তান দেবঙ্কর ভূমিজ (৬ বছর) ও দিপা ভূমিজকে (৮ মাস) নিয়ে শ্যাম ভূমিজের সংসার। পৌনে দুই বছরে ধরে মৌলভীবাজারের রাজারঘাটের টিপাইছড়া চা–বাগানের বসবাস করছেন শ্যাম। ছয় মাস আগেও এ জায়গায় ছিল না কোনো পানি সরবরাহের ব্যবস্থা।\nপানি সংগ্রহের উৎস বলতে ছিল টিলার নিচে, প্রায় আধা মাইল দূরে অবস্থিত একটি কল। যেখানে প্রায় সারা বছরই পানির সরবরাহ থাকত। অন্য ব্যবস্থা না থাকায় এই টিলায় বসবাসরত প্রতিটি পরিবারকেই তখন পানি সংগ্রহের জন্য প্রতিদিন আধা মাইল দূরে নিয়মিত যাতায়াত করতে হতো। যাতায়াতের এ পথও ছিল ঝুঁকিপূর্ণ।', '1553235094.jpeg', '2019-03-21 22:48:35', '2019-03-22 00:11:35'),
(14, 2, 1, NULL, 'সামরিক ধাঁচের আগ্নেয়াস্ত্র নিষিদ্ধ করছে নিউজিল্যান্ড', 'নিউজিল্যান্ড সব ধরনের সেমি-অটোমেটিক আগ্নেয়াস্ত্র নিষিদ্ধ করবে। দেশটির প্রধানমন্ত্রী জাসিন্ডা আহডার্ন এ কথা জানিয়েছেন। আজ বৃহস্পতিবার বিবিসি অনলাইনের প্রতিবেদনে এই তথ্য জানানো হয়।\n\nনিউজিল্যান্ডের ক্রাইস্টচার্চের মসজিদ গত শুক্রবারের ভয়াবহ সন্ত্রাসী হামলায় সেমি-অটোমেটিক আগ্নেয়াস্ত্র ব্যবহার করা হয়েছিল।\nক্রাইস্টচার্চের আল নুর মসজিদ ও লিনউড মসজিদে বন্দুকধারীর ওই হামলায় পাঁচ বাংলাদেশিসহ ৫০ জন নিহত হন। আহত হন ৪২ জন। হামলার পর নিউজিল্যান্ডের অস্ত্র আইন সংশোধনের বিষয়টি আলোচনার কেন্দ্র চলে আসে।', '1553230274.jpeg', '2019-03-21 22:51:14', '2019-03-21 22:51:14'),
(15, 6, 1, NULL, 'সামরিক ধাঁচের আগ্নেয়াস্ত্র নিষিদ্ধ করছে নিউজিল্যান্ড', 'নিউজিল্যান্ডের ক্রাইস্টচার্চের মসজিদ গত শুক্রবারের ভয়াবহ সন্ত্রাসী হামলায় সেমি-অটোমেটিক আগ্নেয়াস্ত্র ব্যবহার করা হয়েছিল।', '1553230983.jpeg', '2019-03-21 23:03:03', '2019-03-21 23:03:03'),
(16, 6, 1, NULL, 'ঢাকা–চট্টগ্রাম–চেন্নাই পথে উড়বে ইউএস–বাংলা', 'ঢাকা থেকে চট্টগ্রাম হয়ে সরাসরি ভারতের চেন্নাই পথে উড়বে বেসরকারি এয়ারলাইনস ইউএস-বাংলার উড়োজাহাজ। ৩১ মার্চ থেকে এই সেবা চালু করবে প্রতিষ্ঠানটি। প্রাথমিকভাবে সপ্তাহে তিন দিন এই পথে উড়োজাহাজ চলবে।\n\nরাজধানীর সোনারগাঁও হোটেলে গতকাল বুধবার এক সংবাদ সম্মেলনে ইউএস-বাংলার পক্ষ থেকে নতুন এই পথে উড়োজাহাজ চালুর ঘোষণা দেওয়া হয়। এতে জানানো হয়, ঢাকা-চেন্নাই পথে একমুখী বা ওয়ানওয়ে টিকিটের মূল্য হবে সর্বনিম্ন ১৫ হাজার ৪৩ টাকা। যাওয়া-আসা বা রিটার্ন টিকিটের মূল্য হবে ২৪ হাজার ২২৩ টাকা। অবশ্য এখন রিটার্ন টিকিটে ২ হাজার টাকা ছাড় দেওয়া হচ্ছে। চট্টগ্রাম-চেন্নাই পথে ওয়ানওয়ের ভাড়া সর্বনিম্ন ১৬ হাজার ৪৫ টাকা। রিটার্ন টিকিটের মূল্য ২৬ হাজার ২২৫ টাকা নির্ধারণ করা হয়েছে।', '1553235208.jpeg', '2019-03-21 23:10:48', '2019-03-22 00:13:28');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES
(1, 'SB SAJIB', 'sajib60@gmail.com', NULL, '$2y$10$Vj9rqPKcFqaRV/aZ2oHw5uLJerwE6SvL2SZ8kP9KlSeZOTNQq3F4S', NULL, '2019-03-15 12:33:42', '2019-03-15 12:33:42'),
(2, 'Steve Cummings', 'sboehm@example.net', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'ZNAmqiU2Rg', '2019-03-15 22:03:46', '2019-03-15 22:03:46'),
(3, 'Justina Kub', 'kutch.ford@example.com', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'rgSKFPN3pX', '2019-03-15 22:03:46', '2019-03-15 22:03:46'),
(4, 'Makayla Emmerich', 'brett74@example.com', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'SNa6YoYQSF', '2019-03-15 22:03:46', '2019-03-15 22:03:46'),
(5, 'Blair Labadie', 'windler.russel@example.net', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'wcD0mc0P6D', '2019-03-15 22:03:46', '2019-03-15 22:03:46'),
(6, 'Dr. Kendall Larkin', 'gabbott@example.org', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'V6UsdH70RU', '2019-03-15 22:03:46', '2019-03-15 22:03:46'),
(7, 'Oren Bailey', 'kallie39@example.com', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'a5Wm05KatY', '2019-03-15 22:03:47', '2019-03-15 22:03:47'),
(8, 'Etha Wuckert', 'daisha79@example.org', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Us3dL81o99', '2019-03-15 22:03:47', '2019-03-15 22:03:47'),
(9, 'Mabelle Blick', 'leuschke.yvonne@example.org', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'i8FkbPQMQR', '2019-03-15 22:03:47', '2019-03-15 22:03:47'),
(10, 'Taya Ziemann DDS', 'neil.lakin@example.net', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'yzDdTx2co9', '2019-03-15 22:03:47', '2019-03-15 22:03:47'),
(11, 'Miss Melody Kihn DVM', 'merlin94@example.net', '2019-03-15 22:03:46', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'AtpXvJjbbi', '2019-03-15 22:03:47', '2019-03-15 22:03:47');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `categories`
--
ALTER TABLE `categories`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `migrations`
--
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `password_resets`
--
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
--
-- Indexes for table `posts`
--
ALTER TABLE `posts`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `categories`
--
ALTER TABLE `categories`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `migrations`
--
ALTER TABLE `migrations`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `posts`
--
ALTER TABLE `posts`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
C
|
UTF-8
| 1,119
| 4.09375
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
void printInorder(struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%d ", node->data);
printInorder(node->right);
}
void swapTree(struct node*node)
{
if(node==NULL) return;
struct node*temp=node->left;
node->left=node->right;
node->right=temp;
swapTree(node->left);
swapTree(node->right);
}
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Inorder traversal of binary tree is : ");
printInorder(root);
swapTree(root);
printf("\nAfter swap Inorder traversal of binary tree is : ");
printInorder(root);
printf("\n");
return 0;
}
|
Shell
|
UTF-8
| 2,106
| 3.421875
| 3
|
[] |
no_license
|
#!/bin/bash
#
# script to plot the seazone bathy data
#
gmtset LABEL_FONT_SIZE=18 ANNOT_FONT_SIZE=18 HEADER_FONT_SIZE=18
gmtset PLOT_DATE_FORMAT=dd/mm/yyyy
gmtset D_FORMAT=%g
gmtset OUTPUT_DEGREE_FORMAT=+D PLOT_DEGREE_FORMAT=F
if [ -e ./Bathy/gridded_bathy/bathy.xyz ]; then
echo -n "make a single bathy file... "
awk '{if ($3<1) print $1,$2,$3}' ./Bathy/gridded_bathy/N*.txt \
> ./Bathy/gridded_bathy/bathy.xyz
echo "done."
fi
infile=./Bathy/gridded_bathy/bathy.xyz
outfile=./images/seazone_bathy.ps
name=seazone
area=-R-2.1/2.1/49.9/52.1
proj=-Jm5
mkgrd(){
echo -n "make a surface... "
awk '{if ($3<1) print $1,$2,$3}' $infile | \
xyz2grd $area -G./grids/"$name".grd -I0.002
echo "done."
}
mkgrad(){
echo -n "making the gradient file... "
grdgradient ./grids/"$name".grd -A35 -Nt0.7 -G./grids/"$name"_grad.grd
echo "done."
}
mktiff(){
echo -n "make a geotiff... "
mbgrdtiff -C./."$name".cpt -K./grids/"$name"_grad.grd -I./grids/"$name".grd \
-O${outfile%.ps}.tif
echo "done."
}
plot(){
echo -n "plot an image... "
gmtset D_FORMAT %.2f
psbasemap $proj $area \
-Ba1f0.5/a0.5f0.25WeSn \
-Xc -Yc -K > $outfile
gmtset D_FORMAT %g
makecpt -Cwysiwyg -T-90/10/1 -Z > ."$name".cpt
grdimage $proj $area -I./grids/"$name"_grad.grd \
-C."$name".cpt ./grids/"$name".grd -O -K >> $outfile
pscoast $area $proj -Bg1 -Df -G0/0/0 -O -K \
-N1/255/255/255 -W1/255/255/255 >> $outfile
psscale -D22.3/8/6/0.5 -B20 -C."$name".cpt -O -K >> $outfile
pstext $proj $area -O -N << TEXT >> $outfile
2.26 51.4 18 0 0 1 Depth (m)
TEXT
echo "done."
}
formats() {
echo -n "convert the image to pdf... "
ps2pdf -dPDFSETTINGS=/prepress -sPAPERSIZE=a4 "$outfile" "${outfile%.ps}.pdf"
echo -n "and jpeg... "
gs -sDEVICE=jpeg -r300 -sPAPERSIZE=a4 -dBATCH -dNOPAUSE \
"-sOutputFile=${outfile%.ps}.jpg" \
"$outfile" > /dev/null
echo "done."
}
#mkgrd # convert xyz to grd
#mkgrad # make a gradient file
#mktiff # make a geotiff
plot # plot the bathy grid
formats # convert the output
exit 0
|
Shell
|
UTF-8
| 251
| 2.671875
| 3
|
[] |
no_license
|
#!/usr/bin/bash
REMOTE="fmallet@srv-aoste:/net/servers/www-sop/members/Frederic.Mallet/"
for i in $*
do
src="mallet20${i}.shtml"
echo "src=$src"
tgt="${REMOTE}/publis/20${i}/`date '+%y%m%d'`.shtml"
echo "dst=$tgt"
scp "$src" "$tgt"
done
|
PHP
|
UTF-8
| 577
| 3.609375
| 4
|
[] |
no_license
|
<h2>Ejemplo 3</h2>
<?php
/*crear un programa que imprima por pantalla los primeros
*20 números naturales
*/
$numero =1;
$contador =2;
while($contador <=20){
//$numero = $numero*$contador;
$numero *= $contador;
//desglozará cada multiplicación --++
echo $numero."<br>";
//sirve para incrementar o hacer una
//acción repetitiva
//SIN ESTE, NUESTRO BUBLE SERÍA INFINITO
//NOS CAUSARIA UN ERROR DE APP
$contador++;
}
echo "el resultado de multiplicar
los primeros 20 números naturales es: " .$numero;
?>
|
Java
|
UTF-8
| 933
| 2.46875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.harrikirik.rescheck.dto;
import android.text.TextUtils;
import androidx.annotation.NonNull;
/**
* Category of an InfoItem
* Harri Kirik, harri35@gmail.com
*/
public class InfoCategory extends BaseInfoObject {
private static final long serialVersionUID = -9173790106163356722L;
private String name;
public InfoCategory(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toPrintableString() {
return getName();
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
} else if (o instanceof InfoCategory) {
return TextUtils.equals(getName(), ((InfoCategory) o).getName());
}
return super.equals(o);
}
@NonNull
@Override
public String toString() {
return super.toString() + " with name: " + getName();
}
}
|
Ruby
|
UTF-8
| 1,647
| 2.609375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require 'sinatra'
require 'em-websocket'
EventMachine.run {
@channels = Hash.new{ |h,k| h[k] = { :channel => EM::Channel.new, :players => {} } }
EventMachine::WebSocket.start(:host => "0.0.0.0", :port => 8882) do |socket|
sid = nil
roomname = nil
username = nil
socket.onopen {
roomname = socket.request["path"].split("/")[1]
username = socket.request["path"].split("/")[2]
if roomname and username
sid = @channels[roomname][:channel].subscribe{ |msg| socket.send msg }
@channels[roomname][:players][sid] = username
puts "open: username:#{username}, roomname:#{roomname}, sid:#{sid}"
data = { :type => "welcome", :data => sid, :players => @channels[roomname][:players] }.to_json
socket.send data
else
socket.close_connection
end
}
socket.onclose {
@channels[roomname][:channel].unsubscribe(sid)
@channels[roomname][:players].delete(sid)
puts "close: username:#{username}, roomname:#{roomname}, sid:#{sid}"
data = { :type => "leave", :players => @channels[roomname][:players], :data => sid }.to_json
@channels[roomname][:channel].push data
}
socket.onmessage { |msg|
puts msg
begin
message = JSON.parse( msg )
@channels[roomname][:channel].push msg
rescue Exception => e
puts "not JSON?"
puts e
end
}
end
}
|
Java
|
UTF-8
| 400
| 2.015625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.symtoms.checker.alexa.priaid.diagnosis.model;
public class DiagnosedSpecialisation extends HealthItem {
/// <summary>
/// ID of specialisation
/// </summary>
public Integer SpecialistID;
/// <summary>
/// Accuracy of specialisation
/// </summary>
public float Accuracy;
/// <summary>
/// Ranking of specialisation
/// </summary>
public String Ranking;
}
|
C++
|
UTF-8
| 5,324
| 2.515625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
/*
* A ROS package to control (With an array of joint values)
* the UR10 arm of our campero robotic platform (both simulation and physical robot).
*
* Laurent LEQUIEVRE
* Research Engineer, CNRS (France)
* Institut Pascal UMR6602
* laurent.lequievre@uca.fr
*
* This controller can be commanded by a topic 'command', based on std_msgs/Float64MultiArray message :
* rostopic pub -1 /campero/arm/joint_array_control/command std_msgs/Float64MultiArray "data: [0.0,0.0,0.0,0.0]"
*
* This controller publish also a 'joint_state' topic, based on sensor_msgs::JointState message.
*
*/
#include <joint_array_controller.h>
// For plugin
#include <pluginlib/class_list_macros.h>
namespace campero_ur_ip_controllers
{
JointArrayControl::JointArrayControl(): publish_rate_(0.0), n_joints_(0) {}
JointArrayControl::~JointArrayControl() {}
bool JointArrayControl::init(hardware_interface::PositionJointInterface *robot, ros::NodeHandle &n)
{
ROS_INFO("***** START JointArrayControl::init ************");
// Initialising KDL chain from reading URDF of the robot
if( !(KinematicChainControllerBase<hardware_interface::PositionJointInterface>::init(robot, n)) )
{
ROS_ERROR("Couldn't initilize JointArrayControl controller.");
return false;
}
// get publishing rate (defined in the yaml controller file)
if (!n.getParam("publish_rate", publish_rate_))
{
ROS_ERROR("Parameter 'publish_rate' not set");
return false;
}
ROS_INFO_STREAM("Publish rate = " << publish_rate_);
// Get nb joints of the robot
n_joints_ = joint_handles_.size();
// Init commands buffer with initial 0.0 values
commands_buffer_.writeFromNonRT(std::vector<double>(n_joints_, 0.0));
// init realtime publisher for the joint_state topic
realtime_pub_.reset(new realtime_tools::RealtimePublisher<sensor_msgs::JointState>(n, "joint_states", 4));
// get joints name,position,velocity and allocate message of joint_state
for (unsigned i=0; i<n_joints_; i++){
realtime_pub_->msg_.name.push_back(joint_handles_[i].getName());
realtime_pub_->msg_.position.push_back(joint_handles_[i].getPosition());
realtime_pub_->msg_.velocity.push_back(joint_handles_[i].getVelocity());
realtime_pub_->msg_.effort.push_back(joint_handles_[i].getEffort());
}
// Defining "command" topic, associating to "commandCB" callback function
sub_command_ = nh_.subscribe("command", 1, &JointArrayControl::commandCB, this);
ROS_INFO("***** FINISH JointArrayControl::init ************");
return true;
}
void JointArrayControl::starting(const ros::Time& time)
{
ROS_INFO("***** START JointArrayControl::starting ************");
// initialize last publish time to calculate the rate
last_publish_time_ = time;
// initialize a vector of current joint positions
std::vector<double> current_joints_positions(n_joints_);
// Getting current joint positions
for(int i=0; i < joint_handles_.size(); i++)
{
current_joints_positions[i] = joint_handles_[i].getPosition();
}
// Init commands buffer with the current joint positions at starting
commands_buffer_.writeFromNonRT(current_joints_positions);
ROS_INFO("***** FINISH JointArrayControl::starting ************");
}
void JointArrayControl::stopping(const ros::Time& time)
{
ROS_INFO("***** START JointArrayControl::stopping ************");
ROS_INFO("***** FINISH JointArrayControl::stopping ************");
}
void JointArrayControl::update(const ros::Time& time, const ros::Duration& period)
{
// Read commands buffer to send
std::vector<double> & commands = *commands_buffer_.readFromRT();
// Send joint commands
for(unsigned int i=0; i<n_joints_; i++)
{
joint_handles_[i].setCommand(commands[i]);
}
// limit rate of publishing
if (publish_rate_ > 0.0 && last_publish_time_ + ros::Duration(1.0/publish_rate_) < time)
{
// publish joint state
if (realtime_pub_->trylock())
{
// increment time for publishing
last_publish_time_ = last_publish_time_ + ros::Duration(1.0/publish_rate_);
// populate joint state message:
realtime_pub_->msg_.header.stamp = time;
for (unsigned i=0; i<n_joints_; i++){
realtime_pub_->msg_.position[i] = joint_handles_[i].getPosition();
realtime_pub_->msg_.velocity[i] = joint_handles_[i].getVelocity();
realtime_pub_->msg_.effort[i] = joint_handles_[i].getEffort();
}
realtime_pub_->unlockAndPublish();
}
}
}
void JointArrayControl::commandCB(const std_msgs::Float64MultiArrayConstPtr& msg)
{
ROS_INFO("***** START JointArrayControl::command ************");
if ( msg->data.size()!=n_joints_ )
{
ROS_ERROR_STREAM("Dimension of command (" << msg->data.size() << ") does not match number of joints (" << n_joints_ << ")! Not executing!");
return;
}
commands_buffer_.writeFromNonRT(msg->data);
ROS_INFO("***** FINISH JointArrayControl::command ************");
}
}
PLUGINLIB_EXPORT_CLASS(campero_ur_ip_controllers::JointArrayControl, controller_interface::ControllerBase)
|
PHP
|
UTF-8
| 4,428
| 2.96875
| 3
|
[] |
no_license
|
<?php
//create_cat.php
require 'connect.php';
include 'header.php';
echo '<h2>Create a topic</h2>';
if (!isset($_SESSION['signed_in']) || $_SESSION['signed_in'] == false) {
//the user is not signed in
echo 'Sorry, you have to be <a href="signin.php">signed in</a> to create a topic.';
} else {
//the user is signed in
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
//the form hasn't been posted yet, display it
//retrieve the categories from the database for use in the dropdown
$sql = "SELECT
cat_id,
cat_name,
cat_description
FROM
categories";
$stmt = Database::pdo()->prepare($sql);
$success = $stmt->execute();
if (!$success) {
//the query failed, uh-oh :-(
echo 'Error while selecting from database. Please try again later.';
} else {
if ($stmt->rowCount() === 0) {
//there are no categories, so a topic can't be posted
if ($_SESSION['user_level'] == 1) {
echo 'You have not created categories yet.';
} else {
echo 'Before you can post a topic, you must wait for an admin to create some categories.';
}
} else {
echo '<form method="post" action="">
Subject: <input type="text" name="topic_subject" />
Category:';
echo '<select name="topic_cat">';
foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) {
echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>';
}
echo '</select>';
echo 'Message: <textarea name="post_content" /></textarea>
<input type="submit" value="Create topic" />
</form>';
}
}
} else {
//start the transaction
$success = Database::pdo()->beginTransaction();
if (!$success) {
//Damn! the query failed, quit
echo 'An error occurred while creating your topic. Please try again later.';
} else {
//the form has been posted, so save it
//insert the topic into the topics table first, then we'll save the post into the posts table
$sql = "INSERT INTO topics
(topic_subject, topic_date, topic_cat, topic_by)
VALUES
(:subject, NOW(), :category, :user)";
$stmt = Database::pdo()->prepare($sql);
$success = $stmt->execute([
'subject' => $_POST['topic_subject'],
'category' => $_POST['topic_cat'],
'user' => $_SESSION['user_id']
]);
if (!$success) {
//something went wrong, display the error
echo 'An error occurred while inserting your data. Please try again later.' . $stmt->errorInfo()[2];
Database::pdo()->rollBack();
} else {
//the first query worked, now start the second, posts query
//retrieve the id of the freshly created topic for usage in the posts query
$topicId = Database::pdo()->lastInsertId();
$sql = "INSERT INTO posts
(post_content, post_date, post_topic, post_by)
VALUES
(:content, NOW(), :topic, :user)";
$stmt = Database::pdo()->prepare($sql);
$success = $stmt->execute([
'content' => $_POST['post_content'],
'topic' => $topicId,
'user' => $_SESSION['user_id']
]);
if (!$success) {
//something went wrong, display the error
echo 'An error occurred while inserting your post. Please try again later.' . $stmt->errorInfo()[2];
Database::pdo()->rollBack();
} else {
Database::pdo()->commit();
//after a lot of work, the query succeeded!
echo 'You have successfully created <a href="topic.php?id=' . $topicId . '">your new topic</a>.';
}
}
}
}
}
include 'footer.php';
|
Java
|
UTF-8
| 507
| 2.4375
| 2
|
[] |
no_license
|
package com.example.codelabs.moviestage;
/**
* Created by varshaa on 21-01-2018.
*/
public class Trailer {
String trailerId;
String key;
String name;
public Trailer(String trailerId, String key, String name) {
this.trailerId = trailerId;
this.key = key;
this.name = name;
}
public String getTrailerId() {
return trailerId;
}
public String getKey() {
return key;
}
public String getName() {
return name;
}
}
|
SQL
|
UTF-8
| 714
| 3.09375
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
--exceptional cases whenuseing function as an argument
--argument of string type
select year(time_format('10:17:66', '%H:%i:%s'));
select year(to_char(datetimetz'1111-10-55 12:23:22.111'));
--argument of timestamp type
select year(to_timestamp_tz('19:39:45 BM 12/12/2012 Europe/London'));
--argument of datetime type
select year(to_datetime_tz(123456));
--server side
create table too(str1 int, str2 string);
insert into too values(1234, 'aabbcc');
select year(to_char(to_timestamp_tz(str1))) from too;
select year(to_datetime_tz(str1)) from too;
select year(to_timestamp_tz(str1)) from too;
select year(to_time_tz(str2)) from too;
select year(time_format(str2, '%H:%i:%s')) from too;
drop table too;
|
Java
|
UTF-8
| 5,257
| 3.0625
| 3
|
[] |
no_license
|
package csv;
import java.util.Objects;
public class Person
{
// 11 instances vars
private String firstName;
private String lastName;
private String companyName;
private String address;
private String city;
private String province;
private String postal;
private String phone1;
private String phone2;
private String email;
private String web;
// 2 ctors
public Person()
{
set("","","","","","","","","","","");
}
public Person(String firstName, String lastName, String companyName,
String address, String city, String province, String postal,
String phone1, String phone2, String email, String web)
{
set(firstName, lastName, companyName, address, city, province, postal,
phone1, phone2, email, web);
}
// getters/setters
public void set(String firstName, String lastName, String companyName,
String address, String city, String province, String postal,
String phone1, String phone2, String email, String web)
{
this.firstName = firstName;
this.lastName = lastName;
this.companyName = companyName;
this.address = address;
this.city = city;
this.province = province;
this.postal = postal;
this.phone1 = phone1;
this.phone2 = phone2;
this.email = email;
this.web = web;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getCompanyName()
{
return companyName;
}
public void setCompanyName(String companyName)
{
this.companyName = companyName;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getProvince()
{
return province;
}
public void setProvince(String province)
{
this.province = province;
}
public String getPostal()
{
return postal;
}
public void setPostal(String postal)
{
this.postal = postal;
}
public String getPhone1()
{
return phone1;
}
public void setPhone1(String phone1)
{
this.phone1 = phone1;
}
public String getPhone2()
{
return phone2;
}
public void setPhone2(String phone2)
{
this.phone2 = phone2;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getWeb()
{
return web;
}
public void setWeb(String web)
{
this.web = web;
}
@Override
public String toString()
{
return "Person(" + getFirstName() + ": " + getLastName() + ": " +
getCompanyName() + ": " + getAddress() + ": " +
getCity() + ": " + getProvince() + ": " +
getPostal() + ": " + getPhone1() + ": " +
getPhone2() + ": " + getEmail() + ": " +
getWeb() + ")";
}
@Override
public boolean equals(Object o)
{
if(!(o instanceof Person)) // ignore null or non Person obj
return false;
if(this == o) // ignore itself
return true;
// compare all member fields if they are equals
Person p = (Person)o;
if(this.firstName.equals(p.getFirstName()) &&
this.lastName.equals(p.getLastName()) &&
this.companyName.equals(p.getCompanyName()) &&
this.address.equals(p.getAddress()) &&
this.city.equals(p.getCity()) &&
this.province.equals(p.getProvince()) &&
this.postal.equals(p.getPostal()) &&
this.phone1.equals(p.getPhone1()) &&
this.phone2.equals(p.getPhone2()) &&
this.email.equals(p.getEmail()) &&
this.web.equals(p.getWeb()))
return true;
else
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = 41 * hash + Objects.hashCode(this.firstName);
hash = 41 * hash + Objects.hashCode(this.lastName);
hash = 41 * hash + Objects.hashCode(this.companyName);
hash = 41 * hash + Objects.hashCode(this.address);
hash = 41 * hash + Objects.hashCode(this.city);
hash = 41 * hash + Objects.hashCode(this.province);
hash = 41 * hash + Objects.hashCode(this.postal);
hash = 41 * hash + Objects.hashCode(this.phone1);
hash = 41 * hash + Objects.hashCode(this.phone2);
hash = 41 * hash + Objects.hashCode(this.email);
hash = 41 * hash + Objects.hashCode(this.web);
return hash;
}
}
|
Python
|
UTF-8
| 3,049
| 2.9375
| 3
|
[] |
no_license
|
import os
import json
import importlib
class PluginService:
"""
Klasa koja manipulise nad prosirenjima (pluginovima) u prosirivom okviru.
"""
def __init__(self):
"""
Inicijalizator servisne klase za pluginove.
"""
self._plugins = list()
def get_by_symbolic_name(self, symbolic_name):
"""
Vraca plugin koji ima naziv symbolic_name. Ukoliko se podesi da vise pluginova ima isti symbolic_name, vraca
se samo prvi.
:param symbolic_name: naziv spram kog pretrazujemo sve dostupne pluginove.
:type symbolic_name: str
:returns: Plugin -- pronadjeni plugin.
:raises: IndexError -- ukoliko ne postoji ni jedan plugin koji je zadovoljio filter.
"""
return list(filter(lambda x: x.symbolic_name == symbolic_name, self._plugins))[0]
def set_enabled(self, plugin, value):
"""
Postavlja status aktivnosti plugina na zadatu vrednost.
:param plugin: instanca plugina kojem menjamo status.
:type plugin: Plugin
:param value: nova vrednost statusa
:type value: bool
:returns: bool -- podatak o uspesnosti promene.
"""
if plugin in self._plugins:
plugin.enabled = value
return True
return False
def install(self, plugin):
"""
Dodaje plugin u instalirane. Isti plugin se ne moze dodati dva puta.
:param plugin: instanca plugina kojeg dodajemo.
:type plugin: Plugin
:returns: bool -- podatak o uspesnosti dodavanja.
"""
if plugin not in self._plugins:
self._plugins.append(plugin)
return True
return False
def uninstall(self, plugin):
"""
Brise plugin u instalirane. Isti plugin se ne moze brisati dva puta.
:param plugin: instanca plugina kojeg brisemo.
:type plugin: Plugin
:returns: bool -- podatak o uspesnosti brisanja.
"""
if plugin in self._plugins:
self._plugins.remove(plugin)
return True
return False
@property
def plugins(self):
return self._plugins
def load_plugins(self, plugins_path="plugins"):
"""
Ucitava sve pluginove spram zadate lokacije. Nakon ucitavanja svih modula i pronalaska njihovih specifikacija,
plugin se instalira u sistem.
:param plugins_path: putanja na kojoj se nalaze plugin paketi.
:type plugins_path: str
"""
for d in os.listdir(plugins_path):
dir_path = os.path.join(plugins_path, d)
if os.path.exists(os.path.join(dir_path, "__init__.py")):
with open(os.path.join(dir_path, "spec.json"), "r") as fp:
spec = json.load(fp)
print(os.path.join(dir_path, "plugin"))
modul = importlib.import_module(os.path.join(dir_path, "plugin").replace(os.sep, "."))
obj = modul.Main(spec)
self.install(obj)
|
Java
|
UTF-8
| 2,473
| 2.21875
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.j3a.sherpawebuser.dbEntityClasses;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* @author J3A-AFRIQUE
*/
@Embeddable
public class Etatc10tabbExercicePK implements Serializable {
@Basic(optional = false)
@NotNull
@Column(name = "CODEEXERCICE")
private int codeexercice;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 255)
@Column(name = "CODEETATC10B")
private String codeetatc10b;
public Etatc10tabbExercicePK() {
}
public Etatc10tabbExercicePK(int codeexercice, String codeetatc10b) {
this.codeexercice = codeexercice;
this.codeetatc10b = codeetatc10b;
}
public int getCodeexercice() {
return codeexercice;
}
public void setCodeexercice(int codeexercice) {
this.codeexercice = codeexercice;
}
public String getCodeetatc10b() {
return codeetatc10b;
}
public void setCodeetatc10b(String codeetatc10b) {
this.codeetatc10b = codeetatc10b;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) codeexercice;
hash += (codeetatc10b != null ? codeetatc10b.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Etatc10tabbExercicePK)) {
return false;
}
Etatc10tabbExercicePK other = (Etatc10tabbExercicePK) object;
if (this.codeexercice != other.codeexercice) {
return false;
}
if ((this.codeetatc10b == null && other.codeetatc10b != null) || (this.codeetatc10b != null && !this.codeetatc10b.equals(other.codeetatc10b))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.j3a.sherpawebuser.dbEntityClasses.Etatc10tabbExercicePK[ codeexercice=" + codeexercice + ", codeetatc10b=" + codeetatc10b + " ]";
}
}
|
C
|
UTF-8
| 2,911
| 2.703125
| 3
|
[] |
no_license
|
#ifndef BLOCK_H
#define BLOCK_H
#include <stdint.h>
#include "ST7735.h"
//#include "Images.h"
struct block{
uint32_t x; //x coordinate of bottom left corner
uint32_t y; //y coordinate of bottom right corner
uint32_t greatestY; // the y coordinate of the block that is the lowest on the screen
uint32_t greatestX; // the x coordinate of the block that the furthest to the right on the screen
uint32_t lowestX; // for collision detection
uint32_t pieceID; //numbers 0-7 correspond to a specific piece
uint32_t spawnFlag; //1 = a new piece should be spawned
uint32_t rotationCount; // the number of times the current piece has been rotated from its original position
uint32_t disthigh;
uint32_t distlow;
};
typedef struct block block_t;
struct gridBlock{
uint32_t life; //this block will be drawn
uint32_t color; //this number corresponds to a pieceID
};
typedef struct gridBlock gridBlock_t;
uint32_t CheckGrid_X(void);
uint32_t checkY(void);
//*******delete_Rows********
//constantly runs at the end of the main loop
//if any rows are completely filled, delete them and reposition appropriate blocks
void delete_Rows(void);
void draw_Rows(void);
void FindEmptyRow(uint32_t row);
void SpawnLPiece(void); // This piece is teal
void SpawnZPiece(void); //This piece is red
void SpawnLinePiece(void); //This piece is orange
void SpawnSquarePiece(void); //This piece is yellow
void SpawnTriPiece(void); //This piece is purple
void SpawnJPiece(void);
void SpawnSPiece(void);
void updateLPiece(block_t currentPieceArr[]); // This piece is teal
void updateZPiece(block_t currentPieceArr[]); //This piece is red
void updateLinePiece(block_t currentPieceArr[]); //This piece is orange
void updateSquarePiece(block_t currentPieceArr[]); //This piece is yellow
void updateTriPiece(block_t currentPieceArr[]); //This piece is purple
void updateJPiece(block_t currentPieceArr[]); //This piece pink
void updateSPiece(block_t currentPieceArr[]); //This piece brown
void rotateLPiece(void); // This piece is teal
void rotateZPiece(void); //This piece is red
void rotateLinePiece(void); //This piece is orange
void rotateTriPiece(void); //This piece is purple
void rotateJPiece(void); //This piece pink
void rotateSPiece(void); //This piece brown
void clear(void);
void DrawCurrentPiece(uint32_t ID); //only draws the currentPiece with its updated coordinates
extern uint32_t score;
extern block_t currentPiece[4];
extern block_t futurePiece[4]; //for seeing if the current piece is allowed to move
extern gridBlock_t grid[16][31]; // each item in the array represents a 5x5 block of pixels. If grid[i][j] = 1 -> there is a block there.
extern uint32_t YchangedFlag; // 1 = the Y coordinates of the current piece were incremented by Systick Handler
extern uint32_t previousCurrentPieceX;
#endif
|
JavaScript
|
UTF-8
| 6,579
| 3.09375
| 3
|
[] |
no_license
|
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject)
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (е) {
xmlHttp = false;
}
else
try {
xmlHttp = new XMLHttpRequest();
}
catch (е) {
xmlHttp = false;
}
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
function newgame() {
let csrfToken = document.getElementsByName("Csrf")[0].value;
let difficult = encodeURIComponent(document.getElementById("difficult").value);
let input = document.getElementById("input");
input.maxLength = difficult;
input.value = ""
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
xmlHttp.open("POST", "/private/newgame", true);
xmlHttp.setRequestHeader("X-CSRF-Token", csrfToken);
xmlHttp.onreadystatechange = newgameServerResponse;
xmlHttp.send(JSON.stringify({val: difficult}));
}
else
setTimeout('newgame() ', 1000);
}
function newgameServerResponse() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseText;
try {
var data = JSON.parse(xmlHttp.responseText);
} catch (err) {
console.log(err.message + " in " + xmlHttp.responseText);
return;
}
if (data["val"] === "OK") {
let baseDiv = document.getElementById("rounds");
baseDiv.innerHTML = '';
let div = document.createElement('div');
div.className = "game-round";
div.innerHTML = "<p>Новая игра началась!</p>";
baseDiv.append(div);
baseDiv.scrollTop = baseDiv.scrollHeight;
let btn = document.getElementById("checkBtn");
btn.disabled = false;
btn.className = "nes-btn is-primary";
} else {
alert("Какая-то ошибка: " + data["err"]);
}
}
else
аlеrt("Ошибка доступа к серверу: " + xmlHttp.statusText);
}
}
function check() {
let csrfToken = document.getElementsByName("Csrf")[0].value;
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
input = encodeURIComponent(document.getElementById("input").value);
xmlHttp.open("POST", "/private/check", true);
xmlHttp.setRequestHeader("X-CSRF-Token", csrfToken);
xmlHttp.setRequestHeader('Content-Type', 'application/json');
xmlHttp.onreadystatechange = checkServerResponse;
xmlHttp.send(JSON.stringify({val: input}));
}
else
setTimeout('check() ', 1000);
}
function checkServerResponse() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseText;
try {
var data = JSON.parse(xmlHttp.responseText);
} catch (err) {
console.log(err.message + " in " + xmlHttp.responseText);
return;
}
let baseDiv = document.getElementById("rounds");
let div = document.createElement('div');
div.className = "game-round";
if (data["status"] === "Win") {
div.innerHTML = "<p>Вы отгадали правильно!</p> <p>Конец игры.</p>" + "<p>" + data["val"] + "</p>";
let btn = document.getElementById("checkBtn");
btn.disabled = true;
btn.className = "nes-btn is-primary is-disabled";
} else {
div.innerHTML = "<p>" + data["val"] + "</p>" + "<p>" + data["code"] + "</p>";
}
baseDiv.append(div);
baseDiv.scrollTop = baseDiv.scrollHeight;
}
else
alert("Ошибка доступа к серверу: " + xmlHttp.statusText);
}
}
function loadgame() {
let csrfToken = document.getElementsByName("Csrf")[0].value;
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
xmlHttp.open("POST", "/private/loadgame", true);
xmlHttp.setRequestHeader("X-CSRF-Token", csrfToken);
xmlHttp.onreadystatechange = loadGameServerResponse;
xmlHttp.send(null);
}
else
setTimeout('check() ', 1000);
}
function loadGameServerResponse() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseText;
try {
var data = JSON.parse(xmlHttp.responseText);
} catch (err) {
console.log(err.message + " in " + xmlHttp.responseText);
return;
}
let diff = data[0]["diff"];
document.getElementById("difficult").value = diff;
let baseDiv = document.getElementById("rounds");
let div = document.createElement('div');
div.className = "game-round";
div.innerHTML = "<p>Игра загружена!</p>";
baseDiv.append(div);
baseDiv.scrollTop = baseDiv.scrollHeight;
for (var i = 1; i < data.length; i++) {
let div = document.createElement('div');
div.className = "game-round";
div.innerHTML = "<p>" + data[i]["in"] + "</p>" + "<p>" + data[i]["out"] + "</p>";
baseDiv.append(div);
baseDiv.scrollTop = baseDiv.scrollHeight;
}
let input = document.getElementById("input");
input.maxLength = diff;
let btn = document.getElementById("checkBtn");
btn.disabled = false;
btn.className = "nes-btn is-primary";
}
else
alert("Ошибка доступа к серверу: " + xmlHttp.statusText);
}
}
function sound() {
let sound = document.getElementById("sound");
if (sound.classList.contains("on")) {
sound.pause();
sound.className = "off";
let img = document.getElementById("soundimg");
img.alt = "off";
img.src = "/assets/static/images/sound_off.png";
} else {
sound.play();
sound.className = "on";
let img = document.getElementById("soundimg");
img.alt = "on";
img.src = "/assets/static/images/sound_on.png";
}
}
|
C
|
UTF-8
| 634
| 3.71875
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <string.h>
int main () {
char str[5][50], temp[50];
printf("Enter 5 words: ");
// Getting strings input
for (int i = 0; i < 5; ++i) {
fgets(str[i], sizeof(str[i]), stdin);
}
// storing strings in the lexicographical order
for (int i = 0; i < 5; ++i) {
for (int j = i + 1; j < 5; ++j) {
if (strcmp(str[i], str[j]) > 0) {
strcpy_s(temp, sizeof(str[i]), str[i]);
strcpy_s(str[i], sizeof(str[j]), str[j]);
strcpy_s(str[j], sizeof(temp), temp);
}
}
}
printf("\nIn the lexicographical order: \n");
for (int i = 0; i < 5; ++i) {
fputs(str[i], stdout);
}
return 0;
}
|
Java
|
UTF-8
| 1,980
| 3.765625
| 4
|
[] |
no_license
|
package com.lc.algorithms.lc1189;
import java.util.Arrays;
/**
* @description: 1189. "气球"的最大数量
* 给你一个字符串 text,你需要使用 text 中的字母来拼凑尽可能多的单词 "balloon"(气球)。
* 字符串 text 中的每个字母最多只能被使用一次。请你返回最多可以拼凑出多少个单词 "balloon"。
* 示例 1:
* 输入:text = "nlaebolko"
* 输出:1
* 示例 2:
* 输入:text = "loonbalxballpoon"
* 输出:2
* 示例 3:
* 输入:text = "leetcode"
* 输出:0
* <p>
* 提示:
* 1 <= text.length <= 10^4
* text 全部由小写英文字母组成
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/maximum-number-of-balloons
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
* </p>
* @author: 松针
* @create: 2022-02-28 18:47
**/
public class MaxNumberOfBalloon {
public static void main(String[] args) {
String text = "loonbalxballpoon";
System.out.println(maxNumberOfBalloons(text) == 2);
}
public static int maxNumberOfBalloons(String text) {
// 定义一个数组,用来记录传入的text中包含多少个 balloon 字母,去重后为 b a l o n
int[] array = new int[5];
// 遍历传入的text,获取每个字母出现的次数
for (char s : text.toCharArray()) {
if (s == 'b') {
array[0]++;
}
if (s == 'a') {
array[1]++;
}
if (s == 'l') {
array[2]++;
}
if (s == 'o') {
array[3]++;
}
if (s == 'n') {
array[4]++;
}
}
// 修正,因为balloon中l和o都出现两次,则 array[2]/2 array[3]/2
array[2] /= 2;
array[3] /= 2;
return Arrays.stream(array).min().getAsInt();
}
}
|
PHP
|
UTF-8
| 628
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Rudolf\Modules\Pages\One\Admin;
use Rudolf\Framework\View\AdminView;
class DelView extends AdminView
{
/**
* @var Page
*/
protected $page;
/**
* @var string
*/
protected $path;
/**
* Set data to delete page.
*
* @param array $page
*/
public function delPage(array $page)
{
$this->page = new Page($page);
$this->pageTitle = _('Delete page');
$this->head->setTitle($this->pageTitle);
$this->path = $this->page->delUrl();
$this->templateType = 'del';
$this->template = 'pages-del';
}
}
|
Python
|
UTF-8
| 561
| 2.84375
| 3
|
[] |
no_license
|
'''
执行用时:164 ms, 在所有 Python3 提交中击败了48.65% 的用户
内存消耗:15.1 MB, 在所有 Python3 提交中击败了40.99% 的用户
通过测试用例:57 / 57
'''
class Solution:
def repeatedStringMatch(self, a: str, b: str) -> int:
cnt = len(b) // len(a)
s0 = a * cnt
s1 = a * (cnt + 1)
s2 = a * (cnt + 2)
if b in s0:
return cnt
elif b in s1:
return cnt + 1
elif b in s2:
return cnt + 2
else:
return -1
|
C++
|
UTF-8
| 1,005
| 2.5625
| 3
|
[] |
no_license
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
vector < int > input;
while(scanf("%d",&n)==1)
{
input.push_back(n);
}
int sz = input.size();
int compress_array[sz+5];
memset(compress_array, 0, sizeof compress_array);
int flag=0;
map < int, int > mp;
for(int i = 0; i != sz; i++)
{
int x = input[i];
if(mp.find(x) == mp.end())
{
mp[x] = flag++;
}
x = mp[x];
compress_array [ i ] = x;
}
int count_array[flag+2];
memset(count_array, 0, sizeof count_array);
for( int i = 0; i < sz; i++)
{
int x = compress_array[i];
count_array[x]++;
}
for( int i = 0; i < flag; i++)
{
int b;
for(int j = 0; j != sz; j++)
{
if(compress_array[j] == i)
{
b = j;
break;
}
}
printf("%d %d\n",input[b],count_array[i]);
}
return 0;
}
|
Java
|
UTF-8
| 170
| 1.796875
| 2
|
[] |
no_license
|
package ThinkInJava.c14.c8.NullRobotProxy;
/**
* Created by zhao_yukuan@163.com
* on 2017/4/28
*/
public interface Operation {
String description();
void command();
}
|
Python
|
UTF-8
| 1,343
| 3.1875
| 3
|
[] |
no_license
|
def rotate(key):
n = len(key)
m = len(key[0])
result = [[0]*n for __ in range(m)]
for i in range(n):
for j in range(m):
result[j][n-i-1] = key[i][j]
return result
def check(new_lock):
lock_length = len(new_lock)//3
for i in range(lock_length, lock_length*2):
for j in range(lock_length, lock_length*2):
if new_lock[i][j] != 1:
return False
return True
def solution(key, lock):
n = len(lock)
m = len(key)
# 회전했을 때 범위 벗어나는 경우 제외하기 위해 3배로 재설정
new_lock = [[0]*n*3 for __ in range(n*3)]
# 확대한 자물쇠에다 기존 자물쇠 중앙에 넣기
for i in range(n):
for j in range(n):
new_lock[i+n][j+n] = lock[i][j]
for __ in range(4):
key = rotate(key)
for x in range(n*2):
for y in range(n*2):
for i in range(m):
for j in range(m):
new_lock[x+i][y+j] += key[i][j]
if check(new_lock)==True:
return True
for i in range(m):
for j in range(m):
new_lock[x+i][y+j] -= key[i][j]
return False
# solution([[0, 0, 0], [1, 0, 0], [0, 1, 1]], [[1, 1, 1], [1, 1, 0], [1, 0, 1]])
|
Markdown
|
UTF-8
| 39
| 2.5625
| 3
|
[] |
no_license
|
# tugas-repository-github-reynald_perma
|
Swift
|
UTF-8
| 3,549
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// SignUpViewController.swift
// InstagramDemo
//
// Created by Daniel Ku on 2/24/17.
// Copyright © 2017 djku. All rights reserved.
//
import UIKit
import Parse
class SignUpViewController: UIViewController {
@IBOutlet weak var fullName: UITextField!
@IBOutlet weak var emailAddress: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var confirmPassword: UITextField!
@IBOutlet weak var signUpButton: UIButton!
@IBOutlet weak var username: UITextField!
@IBOutlet weak var profilePhoto: UIImageView!
var photoTakingHelper: PhotoHelper?
let activityView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
override func viewDidLoad() {
super.viewDidLoad()
self.hideKeyboardWhenTappedAround()
signUpButton.layer.cornerRadius = 4
let photoTap = UITapGestureRecognizer()
photoTap.addTarget(self, action: #selector(SignUpViewController.tappedImage))
profilePhoto.addGestureRecognizer(photoTap)
profilePhoto.isUserInteractionEnabled = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tappedImage(){
takePhoto()
}
@IBAction func onSignUp(_ sender: Any) {
activityView.center = self.view.center
activityView.startAnimating()
self.view.addSubview(activityView)
let newUser = PFUser()
if let name = fullName.text{
newUser["name"] = name
}else{
//alert
}
if let username = username.text{
newUser["nickname"] = username
}else{
//alert
}
if let image = profilePhoto.image{
if let imageData = UIImageJPEGRepresentation(image, 0.8) {
newUser["profile_photo"] = PFFile(name: "profile.png", data: imageData)
}
}else{
if let imageData = UIImageJPEGRepresentation(#imageLiteral(resourceName: "profiledefault"), 0.8) {
newUser["profile_photo"] = PFFile(name: "profile.png", data: imageData)
}
profilePhoto.image = #imageLiteral(resourceName: "profiledefault")
}
if let email = emailAddress.text{
newUser.username = email
}else{
//Alert
}
if let password = password.text{
newUser.password = password
}else{
//Alert
}
if confirmPassword.text != password.text{
//alert
}
newUser.signUpInBackground(block: { (success: Bool, error: Error?) in
if error == nil{
//success
let instagramVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "tabBarVC") as! UITabBarController
self.present(instagramVC, animated: false, completion: nil)
self.activityView.stopAnimating()
}else{
print(error!.localizedDescription)
}
})
}
@IBAction func onCancel(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
func takePhoto(){
photoTakingHelper = PhotoHelper(viewController: self, callback: { (image: UIImage?) in
self.profilePhoto.image = image
})
}
}
|
JavaScript
|
UTF-8
| 6,354
| 3
| 3
|
[
"MIT"
] |
permissive
|
const { ipcRenderer } = require('electron')
// Request and parse data
ipcRenderer.send('request-init-data')
ipcRenderer.on('init-data', (event, data) => {
console.log(data);
fillFavoriteGames(data)
fillInstalledGames(data)
})
// Fill the favorite games dropdown
function fillFavoriteGames({favoriteGames, games}) {
const container = document.getElementById('favorite-games-container');
document.getElementById('favorites-amount').innerText = favoriteGames.length;
favoriteGames.forEach((g, index) => {
container.insertAdjacentHTML('beforeend', `
<div class="item game-id-${g.id} ${index === 0 ? 'active' : ''}" onclick="setActive(${g.id})" oncontextmenu="openCustomContextMenu(event, this, ${g.id}, true)">
<div class="cover" style="background-image: url('${g.covers.small}')"></div> ${g.name}
</div>
`)
});
}
function fillInstalledGames({favoriteGames, games}) {
const container = document.getElementById('installed-games-container');
document.getElementById('installed-amount').innerText = games.length;
games.forEach(g => {
container.insertAdjacentHTML('beforeend', `
<div class="item game-id-${g.id}" onclick="setActive(${g.id})" oncontextmenu="openCustomContextMenu(event, this, ${g.id}, ${g.isFavorite})">
<div class="cover" style="background-image: url('${g.covers.small}')"></div> ${g.name}
</div>
`)
});
var firstItem = favoriteGames[0];
if(firstItem) {
setGameDetails(firstItem)
setActive(firstItem)
} else if(games.length > 0) {
setGameDetails(games[0])
setActive(games[0])
} else {
console.log('No games installed')
}
}
function setActive({id}) {
const sideNav = document.getElementById('side-nav');
const items = sideNav.querySelectorAll('.dropdown-container > .item')
items.forEach(i => {
i.classList.remove('active')
if (i.classList.contains(`game-id-${id}`)) i.classList.add('active');
});
}
function setGameDetails(game) {
document.getElementById('play-button').setAttribute('current-id', game.id);
document.getElementById('game-cover').style.backgroundImage = `url('${game.covers.large}')`;
document.getElementById('game-name').innerText = game.name;
document.getElementById('playtime').innerText = msToHHMMSS(game.playTime);
document.getElementById('last-played').innerText = game.lastPlayed == null ? 'Never' : isToday(game.lastPlayed) ? 'Today' : new Date(game.lastPlayed).toLocaleString();
document.getElementById('cover-favorite-icon').style.display = game.isFavorite ? 'block' : 'none';
if (game.summary !== undefined) setSummary(game);
if (game.storyline !== undefined) setStoryline(game);
if (game.friendsPlaying !== undefined) setPlayingFriends(game.friendsPlaying)
if (game.screenshots.length !== 0) setScreenshots(game);
function msToHHMMSS(ms) {
// 1 ms to seconds
var seconds = Math.round(ms / 1000);
// 2- Extract hours:
var hours = parseInt(seconds / 3600); // 3,600 seconds in 1 hour
seconds = seconds % 3600; // seconds remaining after extracting hours
// 3- Extract minutes:
var minutes = parseInt(seconds / 60); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60;
let resString = '';
if (hours !== 0) resString += `${hours} h, `
if (minutes !== 0) resString += `${minutes} min, `
return resString += `${seconds} sec`;
}
function isToday(ms) {
const date = new Date(ms)
const today = new Date()
return date.getDate() == today.getDate() &&
date.getMonth() == today.getMonth() &&
date.getFullYear() == today.getFullYear()
}
}
function setSummary(game) {
document.getElementById('left-content-column').insertAdjacentHTML('beforeend', `
<div class="item">
<p class="title">Game Description</p>
<div class="content">
<p class="title">
${game.name}: Description
</p>
<p>
${game.summary}
</p>
</div>
</div>
`)
}
function setStoryline(game) {
document.getElementById('left-content-column').insertAdjacentHTML('beforeend', `
<div class="item">
<p class="title">Game Storyline</p>
<div class="content">
<p class="title">
${game.name}: Storyline
</p>
<p>
${game.storyline}
</p>
</div>
</div>
`)
}
function setPlayingFriends(friends) {
const parent = document.createElement('div');
parent.className = 'item';
const title = document.createElement('p')
title.className = 'title';
title.innerText = 'Friends Who Play'
parent.appendChild(title)
const list = document.createElement('div');
list.className = 'friends-playing-list';
if (friends.length === 0) {
let heading = document.createElement('p')
heading.className = 'no-friends-playing';
heading.innerText = 'None of your friends have played this game'
parent.appendChild(heading);
document.getElementById('right-content-column').appendChild(parent);
return;
}
friends.forEach(f => {
const imgdiv = document.createElement('div')
imgdiv.style.backgroundImage = `url('${f.avatars.small}')`;
imgdiv.setAttribute('data-tooltip-title', `${f.username}#${f.tag}`)
imgdiv.setAttribute('onmouseover', `showTooltip(this)`)
imgdiv.setAttribute('onmouseleave', `hideTooltips()`)
list.appendChild(imgdiv);
});
parent.appendChild(list);
document.getElementById('right-content-column').appendChild(parent);
}
function setScreenshots(game) {
const parent = document.createElement('div');
parent.className = 'item';
const title = document.createElement('p')
title.className = 'title';
title.innerText = 'Screenshots'
parent.appendChild(title)
game.screenshots.forEach(s => {
const img = document.createElement('img')
img.setAttribute('src', s)
parent.appendChild(img);
});
document.getElementById('right-content-column').appendChild(parent);
}
|
Python
|
UTF-8
| 899
| 4.25
| 4
|
[] |
no_license
|
class Restaurant:
"""a simple to stimulate a restaurant"""
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
"""will define what the restaurant is"""
print(self.restaurant_name + ' is a 5 star restaurant.')
print(self.restaurant_name + ' is open 6 times a day.')
def open_restaurant(self):
"""stimulate that the restaurant is open"""
print(self.restaurant_name + ' is open!')
# create an instance or set of instructions and store into variable restaurant
restaurant = Restaurant('Le de familie', 'french')
print(restaurant.restaurant_name.title() + ' is really good.')
print('They serve ' + restaurant.cuisine_type.title() + '.')
# call the two methods
restaurant.describe_restaurant()
restaurant.open_restaurant()
|
Swift
|
UTF-8
| 713
| 2.671875
| 3
|
[] |
no_license
|
//
// RecipeListRepository.swift
// LetsCook
//
// Created by Luis David Goyes Garces on 5/2/20.
// Copyright © 2020 LuisGoyes. All rights reserved.
//
import RxSwift
final class RecipeListRepository: RecipeListRepositoryType {
let client: ClientType
init(client: ClientType) {
self.client = client
}
func getRecipes() -> Single<[Recipe]> {
let endpoint = Endpoint<[APIRecipe]>(
path: "/recipes",
parameters: nil,
method: HTTPMethod.get,
contentType: APIContentType.json)
return client.request(endpoint).map {
return $0.map {
Recipe(id: $0.id, title: $0.title)
}
}
}
}
|
PHP
|
UTF-8
| 5,302
| 2.78125
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: arthirajeev
* Date: 6/1/2018
* Time: 2:07 PM
*/
require_once RESOURCE_PATH . "/BaseDAO.class.php";
require_once RESOURCE_PATH . "/MenuType.class.php";
require_once RESOURCE_PATH . "/database.php";
class MenuTypeDAO extends BaseDAO
{
private $menuTypeMap = [
'typeId' => 'type_id',
'typeCode' => 'type_code',
'typeDescription' => 'type_description',
'isAvailableOnline' => 'is_available_online'
];
private $entityTableMap = ['MenuType' => 'menu_type'];
private $idMap = []; //'MenuType' => 'typeId'...meant to indicate autoincrement ID field only
private $calculatedFields = ['MenuType' => []];
private $fieldMap;
public function __construct()
{
$this->fieldMap = ['MenuType' => $this->menuTypeMap];
parent::__construct();
}
protected function getEntityTableMap() {
return $this->entityTableMap;
}
protected function getIdMap() {
return $this->idMap;
}
protected function getCalculatedFields() {
return $this->calculatedFields;
}
protected function getFieldMap() {
return $this->fieldMap;
}
private function gatherMenuTypeFields($row,&$menuType) {
$this->gatherEntityFields($row,'MenuType',$menuType);
}
private function getMenuTypesFromSQLRow($rows) {
$idx = 0;
$menuTypes = [];
while($idx <= count($rows) - 1) {
$menuTypeData = [];
$this->gatherMenuTypeFields($rows[$idx],$menuTypeData);
$hours = [];
if (isset($rows[$idx]['hours_description'])) {
while($idx <= count($rows) - 1 && ($menuTypeData['typeId'] === $rows[$idx]['type_id'] )) {
$hours[] = $rows[$idx]['hours_description'];
$idx++;
}
}
else
$idx++;
$menuTypeData['hourDescriptions'] = $hours;
$menuTypes[] = new MenuType($menuTypeData);
}
return $menuTypes;
}
public function getMenuTypeById($dbConnection, $typeId){
$selectMenuTypeSQL =
'SELECT * FROM menu_type mt lEFT OUTER JOIN menu_type_hour mth ON (mt.type_id = mth.menu_type_id)
WHERE
mt.type_id = :typeId';
$statement = $dbConnection->prepare($selectMenuTypeSQL);
$statement->execute(array(':typeId' => $typeId));
$rows = $statement->fetchAll();
$menuTypes = $this->getMenuTypesFromSQLRow($rows);
return $menuTypes[0];
}
public function getMaxMenuTypeId($dbConnection) {
$selectMenuTypeSQL ='SELECT MAX(type_id) max_menu_type_id FROM menu_type';
$statement = $dbConnection->prepare($selectMenuTypeSQL);
$statement->execute();
$rows = $statement->fetchAll();
$maxId = $rows[0]['max_menu_type_id'];
if (empty($maxId))
$maxId = 0;
return $maxId;
}
public function getAllMenuTypes($dbConnection){
$selectMenuTypeSQL ='SELECT * FROM menu_type mt
lEFT OUTER JOIN menu_type_hour mth ON (mt.type_id = mth.menu_type_id)
ORDER BY
type_code';
$statement = $dbConnection->prepare($selectMenuTypeSQL);
$statement->execute();
$rows = $statement->fetchAll();
$menuTypes = $this->getMenuTypesFromSQLRow($rows);
return $menuTypes;
}
public function getHourDescriptionInsertSQL() {
$insertHoursSQL = "INSERT INTO menu_type_hour
(menu_type_id,hours_description)
VALUES
(:menuTypeId,:hoursDescription)";
return $insertHoursSQL;
}
public function getHourDescriptionInsertParameters($menuTypeId,$hours) {
return array(
':menuTypeId' => $menuTypeId,
':hoursDescription' => $hours
);
}
public function createMenuType($dbConnection, $menuType){
$insertMenuTypeSQL = $this->generateInsertSQL('MenuType');
$insertHoursSQL = $this->getHourDescriptionInsertSQL();
$menuTypeStatement = $dbConnection->prepare($insertMenuTypeSQL);
$hoursStatement = $dbConnection->prepare($insertHoursSQL);
$menuTypeStatement->execute($this->getTableInsertParameters('MenuType', $menuType,[]));
$menuTypeId = $menuType->getTypeId();
$hourDescriptions = $menuType->getHourDescriptions();
foreach ($hourDescriptions as $hoursDescription) {
$hoursStatement->execute($this->getHourDescriptionInsertParameters($menuTypeId,$hoursDescription));
}
return $menuTypeId;
}
}
/*
$x = new MenuTypeDAO();
$maxId = $x->getMaxMenuTypeId($db) + 1;
$menuTypeId = $x->createMenuType($db,MenuType::createNewTestMenuType($maxId));
echo 'Created Test MenuType # ' . $menuTypeId . '<br>';
$menuType = $x->getMenuTypeById($db,$menuTypeId);
echo "JSON representation of newly created menuType: <br>" . json_encode($menuType);
echo '<br>';
echo 'JSON representation of list of all menuTypes <br>';
$menuTypes = $x->getAllMenuTypes($db);
echo json_encode($menuTypes);
*/
|
Markdown
|
UTF-8
| 1,095
| 3.3125
| 3
|
[
"MIT"
] |
permissive
|
# Chaser

JavaScript variable chaser
## Installation
```bash
npm install --save chaser
```
## Usage
```javascript
const chaser = require('chaser')
const myAnimatedVar = chaser(12) // 12 is our initial value here
myAnimateVar.target = 20
setInterval(() => {
console.log(myAnimatedVar.value) // You can use .value anywhere and it will be generated accurately by timing function and passed time.
}, 10)
```
## Chaser using React Hooks with `useChaser`
```javascript
import { useChaser } from 'chaser'
function MovingBox() {
const [posX, setPosX] = useChaser(0 /* initialValue */)
return (
<div style={{ transform: `translateX(${posX}px)` }}>
<button onClick={() => setPosX(Math.random() * 100)} />
</div>
)
}
```
## Example
If you're looking for an example, here's a unclean example! but works:
[https://alireza29675.github.io/chaser/](https://alireza29675.github.io/chaser/)
## Contribute
Put issues! Suggest me what you need.
|
Java
|
UTF-8
| 989
| 2.1875
| 2
|
[] |
no_license
|
package com.stm.dao.impl;
import com.stm.dao.FilterDAO;
import com.stm.dao.rowMapper.FilterRowMapper;
import com.stm.domain.Filter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Repository
public class FilterDAOImpl implements FilterDAO {
private NamedParameterJdbcTemplate template;
@Autowired
public void setDataSource(DataSource dataSource) {
this.template = new NamedParameterJdbcTemplate(dataSource);
}
public List<Filter> getAllFilters() {
//TODO cache this data somehow?
return this.template.query("SELECT * FROM FILTERS", new FilterRowMapper());
}
public void addFilter() {
this.template.update("INSERT INTO FILTERS VALUES ()", new HashMap<String, Object>() {});
}
}
|
C#
|
UTF-8
| 1,736
| 2.59375
| 3
|
[] |
no_license
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public static class Pair
{
public static Pair<T> Create<T>(T left,T right)
{
return new Pair<T>() {
Left = left,
Right = right
};
}
public static Pair<T,U> Create<T,U>(T left,U right)
{
return new Pair<T,U>() {
Left = left,
Right = right
};
}
public static KeyValuePair<T,U> KeyValue<T,U>(T key,U value)
{
return new KeyValuePair<T,U>(key,value);
}
}
public static class Triple
{
public static Triple<T> Create<T>(T left,T right)
{
return new Triple<T>() {
Left = left,
Right = right
};
}
public static Triple<T,U,V> Create<T,U,V>(T left,U center,V right)
{
return new Triple<T,U,V>() {
Left = left,
Center = center,
Right = right
};
}
}
[System.Serializable]
public struct Pair<T>
{
public T Left;
public T Right;
public static implicit operator KeyValuePair<T,T>(Pair<T> pair)
{
return new KeyValuePair<T,T>(pair.Left,pair.Right);
}
public static implicit operator Pair<T>(KeyValuePair<T,T> pair)
{
return Pair.Create<T>(pair.Key,pair.Value);
}
}
[System.Serializable]
public struct Pair<T,U>
{
public T Left;
public U Right;
public static implicit operator KeyValuePair<T,U>(Pair<T,U> pair)
{
return new KeyValuePair<T,U>(pair.Left,pair.Right);
}
public static implicit operator Pair<T,U>(KeyValuePair<T,U> pair)
{
return Pair.Create<T,U>(pair.Key,pair.Value);
}
}
[System.Serializable]
public struct Triple<T>
{
public T Left;
public T Center;
public T Right;
}
[System.Serializable]
public struct Triple<T,U,V>
{
public T Left;
public U Center;
public V Right;
}
|
Markdown
|
UTF-8
| 5,786
| 3.1875
| 3
|
[] |
no_license
|
---
title: React一些路由
date: 2018-05-08 23:44:22
tags: [React,编程]
description:
copyright: true
categories: React
top:
---
React路由Prompt、Redirect、match、Switch。

<!--more-->
# 1、Prompt组件
> 除了Router、Route、Link这三个react路由的基础搭配使用,还有一些其他的比较重要的组件,比如我们在页面切换时,需要进行一些提示,我们就能使用Prompt组件。
它有一个必须的属性message,用于给用户提示信息。
基本使用:
```hash
<Prompt message="给用户提示信息"/>
```
有时候,我们希望提示消息,有时候我们不希望提示出现,这就用到它的另外一个属性-when。when有两种情况,当它的值是true时,会提示消息。当它的值为false时,不会提示消息。
基本使用方式:
```hash
<Prompt when={true} message="给用户提示信息"/>
```
***
# 2、Redirect组件
> 在匹配一个路径时,但是可能这个路径,我们更希望它指向一个新的展示界面,而不是它原本的路径匹配界面。
Redirect组件的必须属性是to属性,表示重定向的新地址。 因为重定向了一个新的地址,必须有一个对应的新的地址的Route,来指定重定向的界面。
基本使用:
```hash
<Redirect to='/new-path' />
<Route path='/new-path' component={NewPage}/>
```
```hash
<Route path="/index" render={()=><Redirect to="/other"/>}/>
```
Redirect重定向是路由的重定向,应该写在组件Route中,一般使用render来实现它
基本使用方式:
```hash
import React,{ Component } from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link, Prompt,Redirect } from "react-router-dom";
class Index extends Component{
render(){
return (
<div>this a Index page</div>
)
}
}
class Other extends Component{
render(){
return (
<div>this a Other page</div>
)
}
}
class Main extends Component{
constructor(props){
super(props);
this.state = {
toast: false,
}
}
render(){
return (
<Router>
<div>
<ul>
<li><Link to="/index">这是首页</Link></li>
<li><Link to="/other">这是其他页</Link></li>
</ul>
<Route path="/index" render={()=><Redirect to="/other"/>}/>
<Route path="/other" component={Other}/>
</div>
</Router>
)
}
}
//因为重定向,所以每个路由展示界面都是other界面
render(<Main />,document.getElementById("root"));
```
***
# 3、Switch组件
> 它的特性是我们只渲染所匹配到的第一个路由组件,一般界面渲染的时候,会渲染所有匹配到的路由组件。它的孩子节点只能是Route组件或者Redirect组件。
基本使用方式:
```hash
import { Switch } from "react-router-dom";
<Switch>
<Route path="/" component={Test1} />
<Route path="/Test" component={Test2} />
</Switch>
```
以下实例:
```hash
import React,{ Component } from "react";
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
class Home extends Component{
render(){
return (
<div>Home</div>
)
}
}
class Other extends Component{
render(){
return (
<div>Other</div>
)
}
}
class Switchs extends Component{
render(){
return (
<div>Switchs test</div>
)
}
}
class Main extends Component{
constructor(props){
super(props);
}
render(){
return (
<Router>
<div>
<ul>
<li><Link to="/home">首页</Link></li>
<li><Link to="/other">其他页</Link></li>
</ul>
<Switch>
<Route path="/:id" component={Switchs}/>
<Route path="/home" component={Home}/>
<Route path="/other" component={Other}/>
</Switch>
</div>
</Router>
)
}
}
render(<Main />,document.getElementById("root"));
```
***
# 4、Match对象
> match是一个匹配路径参数的对象,它有一个属性params,里面的内容就是路径参数,除常用的params属性外,它还有url、path、isExact属性。
在组件Match中,通过this.props.match.params.id获取了路径的匹配参数。首页参数home,其他页是other。
Match的获取方式:
在Route component中,组件通过this.props.match获取。
在Route render 和Route children中,通过传递一个参数的方式获取。
```
以下实例:
```hash
import { render } from "react-dom";
import { BrowserRouter as Router, Route, Link, Prompt,Redirect } from "react-router-dom";
class Match extends Component{
render(){
return (
<div>id:{this.props.match.params.id}</div>
)
}
}
class Main extends Component{
constructor(props){
super(props);
}
render(){
return (
<Router>
<div>
<ul>
<li><Link to="/home">首页</Link></li>
<li><Link to="/other">其他页</Link></li>
</ul>
<Route path="/:id" component={Match}/>
</div>
</Router>
)
}
}
//id是路径匹配参数。
render(<Main />,document.getElementById("root"));
```
***
|
Java
|
UTF-8
| 1,792
| 2.28125
| 2
|
[] |
no_license
|
package com.complaint.model;
import java.io.Serializable;
/**
* 问题解决率
* @author peng
*昨天
*/
public class SolvingProbability implements Serializable {
private Integer areaid;//区域id
private String areaname;//区域名称
private Integer special;//归属专业id
private String specialName;//归属专业名称
private long complainl;//投诉量
private long solving;//问题解决量
private long solved;//真正解决量
private double solvingRate;//问题解决率
private double solvedRate;//问题解决率
public double getSolvingRate() {
return solvingRate;
}
public void setSolvingRate(double solvingRate) {
this.solvingRate = solvingRate;
}
public double getSolvedRate() {
return solvedRate;
}
public void setSolvedRate(double solvedRate) {
this.solvedRate = solvedRate;
}
public String getSpecialName() {
return specialName;
}
public void setSpecialName(String specialName) {
this.specialName = specialName;
}
public Integer getAreaid() {
return areaid;
}
public void setAreaid(Integer areaid) {
this.areaid = areaid;
}
public String getAreaname() {
return areaname;
}
public void setAreaname(String areaname) {
this.areaname = areaname;
}
public Integer getSpecial() {
return special;
}
public void setSpecial(Integer special) {
this.special = special;
}
public long getComplainl() {
return complainl;
}
public void setComplainl(long complainl) {
this.complainl = complainl;
}
public long getSolving() {
return solving;
}
public void setSolving(long solving) {
this.solving = solving;
}
public long getSolved() {
return solved;
}
public void setSolved(long solved) {
this.solved = solved;
}
}
|
TypeScript
|
UTF-8
| 2,286
| 2.8125
| 3
|
[
"ISC"
] |
permissive
|
import { Params, ServiceMethods } from '@feathersjs/feathers';
import Factory, { DataGenerator } from './Factory';
export default new class GlobalFactories {
/**
* Defined factories.
*/
public factories: { [s: string]: Factory<any, any> } = {};
/**
* Define a new factory.
*
* @param factoryName
* @param service
* @param generator
* @param defaultParams
*/
public define(
factoryName: string,
service: ServiceMethods<any>,
generator: DataGenerator<any>,
defaultParams?: Params,
) {
this.factories[factoryName] = new Factory(service, generator, defaultParams);
}
/**
* Retrieve a factory name as defined in the define() method.
*
* @param name
*/
public getFactory(name: string) {
const factory = this.factories[name];
if (!factory) {
throw Error(`Could not locate factory '${name}'. Did you define it?`);
}
return factory;
}
/**
* Run factory, creating entry in Feathers service.
*
* @param factoryName
* @param overrides
* @param params
*/
public create(factoryName: string, overrides?: DataGenerator<any>, params?: Params) {
const factory = this.getFactory(factoryName);
return factory.create(overrides, params);
}
/**
* Run a number of factories, creating entries in Feathers service.
*
* @param quantity
* @param factoryName
* @param overrides
* @param params
*/
public createMany(quantity: number, factoryName: string, overrides?: DataGenerator<any>, params?: Params) {
const factory = this.getFactory(factoryName);
return factory.createMany(quantity, overrides, params);
}
/**
* Run factory without creating entry in Feathers service.
* Returns resolved data object.
*
* @param factoryName
* @param overrides
*/
public get(factoryName: string, overrides?: DataGenerator<any>) {
const factory = this.factories[factoryName];
if (!factory) {
throw Error(`Could not locate factory '${factoryName}'. Did you define it?`);
}
return factory.get(overrides);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.